Detailed changes
@@ -1,73 +0,0 @@
-Apache License
-Version 2.0, January 2004
-http://www.apache.org/licenses/
-
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-1. Definitions.
-
-"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
-
-"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
-
-"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
-
-"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
-
-"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
-
-"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
-
-"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
-
-"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
-
-"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
-
-"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
-
-2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
-
-3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
-
-4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
-
- (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
-
- You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
-
-5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
-
-6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
-
-8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS
-
-APPENDIX: How to apply the Apache License to your work.
-
-To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
-
-Copyright [yyyy] [name of copyright owner]
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
@@ -9,22 +9,3 @@ SPDX-License-Identifier = "LicenseRef-MutuaL-1.2"
path = "README.md"
SPDX-FileCopyrightText = "Amolith <amolith@secluded.site>"
SPDX-License-Identifier = "CC0-1.0"
-
-[[annotations]]
-path = [
- "skills/charm-*/**",
- "vendor/forge/**",
-]
-SPDX-FileCopyrightText = "2026 alxx"
-SPDX-License-Identifier = "MIT"
-
-[[annotations]]
-path = [
- "skills/impeccable/**",
- "vendor/impeccable/**",
-]
-SPDX-FileCopyrightText = [
- "2025-2026 Paul Bakaus",
- "2025 Anthropic, PBC",
-]
-SPDX-License-Identifier = "Apache-2.0"
@@ -1,82 +0,0 @@
-#!/usr/bin/env fish
-#
-# Update git-subtree-vendored repositories listed in vendor/sources.
-#
-# vendor/sources format (tab-separated):
-# name url branch
-#
-# Lines starting with # are ignored.
-#
-# Usage:
-# scripts/vendor-update.fish # update all vendored repos
-# scripts/vendor-update.fish forge # update only vendor/forge
-
-set repo_root (git -C (status dirname) rev-parse --show-toplevel)
-
-if test $status -ne 0
- echo "error: not inside a git repository" >&2
- exit 1
-end
-
-cd $repo_root
-
-set sources_file vendor/sources
-
-if not test -f $sources_file
- echo "error: $sources_file not found" >&2
- exit 1
-end
-
-set filter $argv
-set failed 0
-set found 0
-
-while read -l line
- # Skip comments and blank lines
- string match -qr '^\s*#' -- $line; and continue
- string match -qr '^\s*$' -- $line; and continue
-
- set parts (string split \t -- $line)
- if test (count $parts) -ne 3
- echo "skip: malformed line: $line" >&2
- set failed (math $failed + 1)
- continue
- end
-
- set name $parts[1]
- set url $parts[2]
- set branch $parts[3]
-
- # If specific targets were given, skip non-matching entries
- if test (count $filter) -gt 0
- contains $name $filter; or continue
- end
-
- set found (math $found + 1)
-
- if not test -d vendor/$name
- echo "skip: vendor/$name does not exist (run 'git subtree add' first)" >&2
- set failed (math $failed + 1)
- continue
- end
-
- echo ":: updating vendor/$name from $url ($branch)"
- git subtree pull --prefix=vendor/$name $url $branch --squash
- if test $status -ne 0
- echo "error: failed to update vendor/$name" >&2
- set failed (math $failed + 1)
- else
- echo ":: vendor/$name updated"
- end
- echo
-end <$sources_file
-
-if test $found -eq 0
- echo "No matching vendored repos found." >&2
- exit 1
-end
-
-if test $failed -gt 0
- echo "$failed vendor update(s) failed" >&2
- exit 1
-end
@@ -1 +0,0 @@
-../vendor/impeccable/skill
@@ -1,163 +0,0 @@
----
-name: impeccable
-description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
----
-
-Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
-
-## Setup
-
-Before any design work or file edits:
-
-1. Load context (PRODUCT.md / DESIGN.md) via the loader script.
-2. Identify the register and load the matching register reference (brand.md or product.md).
-3. **If the user invoked a sub-command (e.g. `craft`, `shape`, `audit`), load its reference file too.** This is non-negotiable: `craft` without `craft.md` loaded means you'll skip the shape-and-confirm step the user expects.
-
-Skipping these produces generic output that ignores the project.
-
-### 1. Context gathering
-
-Two files, case-insensitive. The loader looks at the project root by default and falls back to `.agents/context/` and `docs/` if the root is clean. Override with `IMPECCABLE_CONTEXT_DIR=path/to/dir` (absolute or relative to cwd).
-
-- **PRODUCT.md**: required. Users, brand, tone, anti-references, strategic principles.
-- **DESIGN.md**: optional, strongly recommended. Colors, typography, elevation, components.
-
-Load both in one call:
-
-```bash
-node .agents/skills/impeccable/scripts/load-context.mjs
-```
-
-Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`. The output's `contextDir` field tells you where the files were resolved from.
-
-If the output is already in this session's conversation history, don't re-run. Exceptions requiring a fresh load: you just ran `$impeccable teach` or `$impeccable document` (they rewrite the files), or the user manually edited one.
-
-`$impeccable live` already warms context via `live.mjs`. If you've run `live.mjs`, don't also run `load-context.mjs` this session.
-
-If PRODUCT.md is missing, empty, or placeholder (`[TODO]` markers, <200 chars): run `$impeccable teach`, then resume the user's original task with the fresh context. If the original task was `$impeccable craft`, resume into `$impeccable shape` before any implementation work.
-
-If DESIGN.md is missing: nudge once per session (*"Run `$impeccable document` for more on-brand output"*), then proceed.
-
-### 2. Register
-
-Every design task is **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboard, tool: design SERVES the product).
-
-Identify before designing. Priority: (1) cue in the task itself ("landing page" vs "dashboard"); (2) the surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. First match wins.
-
-If PRODUCT.md lacks the `register` field (legacy), infer it once from its "Users" and "Product Purpose" sections, then cache the inferred value for the session. Suggest the user run `$impeccable teach` to add the field explicitly.
-
-Load the matching reference: [reference/brand.md](reference/brand.md) or [reference/product.md](reference/product.md). The shared design laws below apply to both.
-
-## Shared design laws
-
-Apply to every design, both registers. Match implementation complexity to the aesthetic vision: maximalism needs elaborate code, minimalism needs precision. Interpret creatively. Vary across projects; never converge on the same choices. GPT is capable of extraordinary work. Don't hold back.
-
-### Color
-
-- Use OKLCH. Reduce chroma as lightness approaches 0 or 100; high chroma at extremes looks garish.
-- Never use `#000` or `#fff`. Tint every neutral toward the brand hue (chroma 0.005–0.01 is enough).
-- Pick a **color strategy** before picking colors. Four steps on the commitment axis:
- - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism.
- - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages.
- - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz.
- - **Drenched**: the surface IS the color. Brand heroes, campaign pages.
-- The "one accent ≤10%" rule is Restrained only. Committed / Full palette / Drenched exceed it on purpose. Don't collapse every design to Restrained by reflex.
-
-### Theme
-
-Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe."
-
-Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does.
-
-"Observability dashboard" does not force an answer. "SRE glancing at incident severity on a 27-inch monitor at 2am in a dim room" does. Run the sentence, not the category.
-
-### Typography
-
-- Cap body line length at 65–75ch.
-- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales.
-
-### Layout
-
-- Vary spacing for rhythm. Same padding everywhere is monotony.
-- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
-- Don't wrap everything in a container. Most things don't need one.
-
-### Motion
-
-- Don't animate CSS layout properties.
-- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
-
-### Absolute bans
-
-Match-and-refuse. If you're about to write any of these, rewrite the element with different structure.
-
-- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing.
-- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size.
-- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing.
-- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché.
-- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly.
-- **Modal as first thought.** Modals are usually laziness. Exhaust inline / progressive alternatives first.
-
-### Copy
-
-- Every word earns its place. No restated headings, no intros that repeat the title.
-- **No em dashes.** Use commas, colons, semicolons, periods, or parentheses. Also not `--`.
-
-### The AI slop test
-
-If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference.
-
-**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses.
-
-- **First-order:** if someone could guess the theme + palette from the category alone ("observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black"), it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
-- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families.
-
-## Commands
-
-| Command | Category | Description | Reference |
-|---|---|---|---|
-| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) |
-| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) |
-| `teach` | Build | Set up PRODUCT.md and DESIGN.md context | [reference/teach.md](reference/teach.md) |
-| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) |
-| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) |
-| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) |
-| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) |
-| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) |
-| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) |
-| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) |
-| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) |
-| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) |
-| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) |
-| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) |
-| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) |
-| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) |
-| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) |
-| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) |
-| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) |
-| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) |
-| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) |
-| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
-| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
-
-### Routing rules
-
-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
-3. **First word doesn't match**: general design invocation. Apply the setup steps, shared design laws, and the loaded register reference, using the full argument as context.
-
-Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `$impeccable`.
-
-If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `teach` as a blocker, finish teach, refresh context, then resume the original command and target.
-
-## Pin / Unpin
-
-**Pin** creates a standalone shortcut so `$<command>` invokes `$impeccable <command>` directly. **Unpin** removes it. The script writes to every harness directory present in the project.
-
-```bash
-node .agents/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
-```
-
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
@@ -1,4 +0,0 @@
-interface:
- display_name: Impeccable
- short_description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify,...
- default_prompt: Use Impeccable to redesign, critique, audit, or polish this frontend.
@@ -1,190 +0,0 @@
-> **Additional context needed**: target platforms/devices and usage contexts.
-
-Adapt an existing design to a different context: another screen size, device, platform, or use case. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context.
-
-
----
-
-## Assess Adaptation Challenge
-
-Understand what needs adaptation and why:
-
-1. **Identify the source context**:
- - What was it designed for originally? (Desktop web? Mobile app?)
- - What assumptions were made? (Large screen? Mouse input? Fast connection?)
- - What works well in current context?
-
-2. **Understand target context**:
- - **Device**: Mobile, tablet, desktop, TV, watch, print?
- - **Input method**: Touch, mouse, keyboard, voice, gamepad?
- - **Screen constraints**: Size, resolution, orientation?
- - **Connection**: Fast wifi, slow 3G, offline?
- - **Usage context**: On-the-go vs desk, quick glance vs focused reading?
- - **User expectations**: What do users expect on this platform?
-
-3. **Identify adaptation challenges**:
- - What won't fit? (Content, navigation, features)
- - What won't work? (Hover states on touch, tiny touch targets)
- - What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop)
-
-**CRITICAL**: Adaptation is rethinking the experience for the new context, not scaling pixels.
-
-## Plan Adaptation Strategy
-
-Create context-appropriate strategy:
-
-### Mobile Adaptation (Desktop → Mobile)
-
-**Layout Strategy**:
-- Single column instead of multi-column
-- Vertical stacking instead of side-by-side
-- Full-width components instead of fixed widths
-- Bottom navigation instead of top/side navigation
-
-**Interaction Strategy**:
-- Touch targets 44x44px minimum (not hover-dependent)
-- Swipe gestures where appropriate (lists, carousels)
-- Bottom sheets instead of dropdowns
-- Thumbs-first design (controls within thumb reach)
-- Larger tap areas with more spacing
-
-**Content Strategy**:
-- Progressive disclosure (don't show everything at once)
-- Prioritize primary content (secondary content in tabs/accordions)
-- Shorter text (more concise)
-- Larger text (16px minimum)
-
-**Navigation Strategy**:
-- Hamburger menu or bottom navigation
-- Reduce navigation complexity
-- Sticky headers for context
-- Back button in navigation flow
-
-### Tablet Adaptation (Hybrid Approach)
-
-**Layout Strategy**:
-- Two-column layouts (not single or three-column)
-- Side panels for secondary content
-- Master-detail views (list + detail)
-- Adaptive based on orientation (portrait vs landscape)
-
-**Interaction Strategy**:
-- Support both touch and pointer
-- Touch targets 44x44px but allow denser layouts than phone
-- Side navigation drawers
-- Multi-column forms where appropriate
-
-### Desktop Adaptation (Mobile → Desktop)
-
-**Layout Strategy**:
-- Multi-column layouts (use horizontal space)
-- Side navigation always visible
-- Multiple information panels simultaneously
-- Fixed widths with max-width constraints (don't stretch to 4K)
-
-**Interaction Strategy**:
-- Hover states for additional information
-- Keyboard shortcuts
-- Right-click context menus
-- Drag and drop where helpful
-- Multi-select with Shift/Cmd
-
-**Content Strategy**:
-- Show more information upfront (less progressive disclosure)
-- Data tables with many columns
-- Richer visualizations
-- More detailed descriptions
-
-### Print Adaptation (Screen → Print)
-
-**Layout Strategy**:
-- Page breaks at logical points
-- Remove navigation, footer, interactive elements
-- Black and white (or limited color)
-- Proper margins for binding
-
-**Content Strategy**:
-- Expand shortened content (show full URLs, hidden sections)
-- Add page numbers, headers, footers
-- Include metadata (print date, page title)
-- Convert charts to print-friendly versions
-
-### Email Adaptation (Web → Email)
-
-**Layout Strategy**:
-- Narrow width (600px max)
-- Single column only
-- Inline CSS (no external stylesheets)
-- Table-based layouts (for email client compatibility)
-
-**Interaction Strategy**:
-- Large, obvious CTAs (buttons not text links)
-- No hover states (not reliable)
-- Deep links to web app for complex interactions
-
-## Implement Adaptations
-
-Apply changes systematically:
-
-### Responsive Breakpoints
-
-Choose appropriate breakpoints:
-- Mobile: 320px-767px
-- Tablet: 768px-1023px
-- Desktop: 1024px+
-- Or content-driven breakpoints (where design breaks)
-
-### Layout Adaptation Techniques
-
-- **CSS Grid/Flexbox**: Reflow layouts automatically
-- **Container Queries**: Adapt based on container, not viewport
-- **`clamp()`**: Fluid sizing between min and max
-- **Media queries**: Different styles for different contexts
-- **Display properties**: Show/hide elements per context
-
-### Touch Adaptation
-
-- Increase touch target sizes (44x44px minimum)
-- Add more spacing between interactive elements
-- Remove hover-dependent interactions
-- Add touch feedback (ripples, highlights)
-- Consider thumb zones (easier to reach bottom than top)
-
-### Content Adaptation
-
-- Use `display: none` sparingly (still downloads)
-- Progressive enhancement (core content first, enhancements on larger screens)
-- Lazy loading for off-screen content
-- Responsive images (`srcset`, `picture` element)
-
-### Navigation Adaptation
-
-- Transform complex nav to hamburger/drawer on mobile
-- Bottom nav bar for mobile apps
-- Persistent side navigation on desktop
-- Breadcrumbs on smaller screens for context
-
-**IMPORTANT**: Test on real devices. Device emulation in DevTools is helpful but not perfect.
-
-**NEVER**:
-- Hide core functionality on mobile (if it matters, make it work)
-- Assume desktop = powerful device (consider accessibility, older machines)
-- Use different information architecture across contexts (confusing)
-- Break user expectations for platform (mobile users expect mobile patterns)
-- Forget landscape orientation on mobile/tablet
-- Use generic breakpoints blindly (use content-driven breakpoints)
-- Ignore touch on desktop (many desktop devices have touch)
-
-## Verify Adaptations
-
-Test thoroughly across contexts:
-
-- **Real devices**: Test on actual phones, tablets, desktops
-- **Different orientations**: Portrait and landscape
-- **Different browsers**: Safari, Chrome, Firefox, Edge
-- **Different OS**: iOS, Android, Windows, macOS
-- **Different input methods**: Touch, mouse, keyboard
-- **Edge cases**: Very small screens (320px), very large screens (4K)
-- **Slow connections**: Test on throttled network
-
-When the adaptation feels native to each context, hand off to `$impeccable polish` for the final pass.
@@ -1,175 +0,0 @@
-> **Additional context needed**: performance constraints.
-
-Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it.
-
----
-
-## Register
-
-Brand: orchestrated page-load sequences, staggered reveals, scroll-driven animation. Motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions.
-
-Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it.
-
----
-
-## Assess Animation Opportunities
-
-Analyze where motion would improve the experience:
-
-1. **Identify static areas**:
- - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.)
- - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes)
- - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious
- - **Lack of delight**: Functional but joyless interactions
- - **Missed guidance**: Opportunities to direct attention or explain behavior
-
-2. **Understand the context**:
- - What's the personality? (Playful vs serious, energetic vs calm)
- - What's the performance budget? (Mobile-first? Complex page?)
- - Who's the audience? (Motion-sensitive users? Power users who want speed?)
- - What matters most? (One hero animation vs many micro-interactions?)
-
-If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer.
-
-**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them.
-
-## Plan Animation Strategy
-
-Create a purposeful animation plan:
-
-- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?)
-- **Feedback layer**: Which interactions need acknowledgment?
-- **Transition layer**: Which state changes need smoothing?
-- **Delight layer**: Where can we surprise and delight?
-
-**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments.
-
-## Implement Animations
-
-Add motion systematically across these categories:
-
-### Entrance Animations
-- **Page load choreography**: Stagger element reveals (100-150ms delays), fade + slide combinations
-- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects)
-- **Content reveals**: Scroll-triggered animations using intersection observer
-- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management
-
-### Micro-interactions
-- **Button feedback**:
- - Hover: Subtle scale (1.02-1.05), color shift, shadow increase
- - Click: Quick scale down then up (0.95 → 1), ripple effect
- - Loading: Spinner or pulse state
-- **Form interactions**:
- - Input focus: Border color transition, slight scale or glow
- - Validation: Shake on error, check mark on success, smooth color transitions
-- **Toggle switches**: Smooth slide + color transition (200-300ms)
-- **Checkboxes/radio**: Check mark animation, ripple effect
-- **Like/favorite**: Scale + rotation, particle effects, color transition
-
-### State Transitions
-- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms)
-- **Expand/collapse**: Height transition with overflow handling, icon rotation
-- **Loading states**: Skeleton screen fades, spinner animations, progress bars
-- **Success/error**: Color transitions, icon animations, gentle scale pulse
-- **Enable/disable**: Opacity transitions, cursor changes
-
-### Navigation & Flow
-- **Page transitions**: Crossfade between routes, shared element transitions
-- **Tab switching**: Slide indicator, content fade/slide
-- **Carousel/slider**: Smooth transforms, snap points, momentum
-- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators
-
-### Feedback & Guidance
-- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights
-- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning
-- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation
-- **Focus flow**: Highlight path through form or workflow
-
-### Delight Moments
-- **Empty states**: Subtle floating animations on illustrations
-- **Completed actions**: Confetti, check mark flourish, success celebrations
-- **Easter eggs**: Hidden interactions for discovery
-- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches
-
-## Technical Implementation
-
-Use appropriate techniques for each animation:
-
-### Timing & Easing
-
-**Durations by purpose:**
-- **100-150ms**: Instant feedback (button press, toggle)
-- **200-300ms**: State changes (hover, menu open)
-- **300-500ms**: Layout changes (accordion, modal)
-- **500-800ms**: Entrance animations (page load)
-
-**Easing curves (use these, not CSS defaults):**
-```css
-/* Recommended: natural deceleration */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */
-
-/* AVOID: feel dated and tacky */
-/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */
-/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */
-```
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-### CSS Animations
-```css
-/* Prefer for simple, declarative animations */
-- transitions for state changes
-- @keyframes for complex sequences
-- transform and opacity for reliable movement
-- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth
-```
-
-### JavaScript Animation
-```javascript
-/* Use for complex, interactive animations */
-- Web Animations API for programmatic control
-- Framer Motion for React
-- GSAP for complex sequences
-```
-
-### Performance
-- **Motion materials**: Use transform/opacity for reliable movement, but use blur, filters, masks, shadows, and color shifts when they materially improve the effect
-- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- **will-change**: Add sparingly for known expensive animations
-- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate
-- **Monitor FPS**: Ensure 60fps on target devices
-
-### Accessibility
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**NEVER**:
-- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself
-- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work
-- Use durations over 500ms for feedback (it feels laggy)
-- Animate without purpose (every animation needs a reason)
-- Ignore `prefers-reduced-motion` (this is an accessibility violation)
-- Animate everything (animation fatigue makes interfaces feel exhausting)
-- Block interaction during animations unless intentional
-
-## Verify Quality
-
-Test animations thoroughly:
-
-- **Smooth at 60fps**: No jank on target devices
-- **Feels natural**: Easing curves feel organic, not robotic
-- **Appropriate timing**: Not too fast (jarring) or too slow (laggy)
-- **Reduced motion works**: Animations disabled or simplified appropriately
-- **Doesn't block**: Users can interact during/after animations
-- **Adds value**: Makes interface clearer or more delightful
-
-When the motion clarifies state instead of decorating it, hand off to `$impeccable polish` for the final pass.
@@ -1,133 +0,0 @@
-Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues; document them for other commands to address.
-
-This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation.
-
-## Diagnostic Scan
-
-Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below.
-
-### 1. Accessibility (A11y)
-
-**Check for**:
-- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA)
-- **Missing ARIA**: Interactive elements without proper roles, labels, or states
-- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps
-- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons
-- **Alt text**: Missing or poor image descriptions
-- **Form issues**: Inputs without labels, poor error messaging, missing required indicators
-
-**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA)
-
-### 2. Performance
-
-**Check for**:
-- **Layout thrashing**: Reading/writing layout properties in loops
-- **Expensive animations**: Casual layout-property animation, unbounded blur/filter/shadow effects, or effects that visibly drop frames
-- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change
-- **Bundle size**: Unnecessary imports, unused dependencies
-- **Render performance**: Unnecessary re-renders, missing memoization
-
-**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized)
-
-### 3. Theming
-
-**Check for**:
-- **Hard-coded colors**: Colors not using design tokens
-- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme
-- **Inconsistent tokens**: Using wrong tokens, mixing token types
-- **Theme switching issues**: Values that don't update on theme change
-
-**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly)
-
-### 4. Responsive Design
-
-**Check for**:
-- **Fixed widths**: Hard-coded widths that break on mobile
-- **Touch targets**: Interactive elements < 44x44px
-- **Horizontal scroll**: Content overflow on narrow viewports
-- **Text scaling**: Layouts that break when text size increases
-- **Missing breakpoints**: No mobile/tablet variants
-
-**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets)
-
-### 5. Anti-Patterns (CRITICAL)
-
-Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy).
-
-**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design)
-
-## Generate Report
-
-### Audit Health Score
-
-| # | Dimension | Score | Key Finding |
-|---|-----------|-------|-------------|
-| 1 | Accessibility | ? | [most critical a11y issue or "--"] |
-| 2 | Performance | ? | |
-| 3 | Responsive Design | ? | |
-| 4 | Theming | ? | |
-| 5 | Anti-Patterns | ? | |
-| **Total** | | **??/20** | **[Rating band]** |
-
-**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues)
-
-### Anti-Patterns Verdict
-**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest.
-
-### Executive Summary
-- Audit Health Score: **??/20** ([rating band])
-- Total issues found (count by severity: P0/P1/P2/P3)
-- Top 3-5 critical issues
-- Recommended next steps
-
-### Detailed Findings by Severity
-
-Tag every issue with **P0-P3 severity**:
-- **P0 Blocking**: Prevents task completion. Fix immediately
-- **P1 Major**: Significant difficulty or WCAG AA violation. Fix before release
-- **P2 Minor**: Annoyance, workaround exists. Fix in next pass
-- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits
-
-For each issue, document:
-- **[P?] Issue name**
-- **Location**: Component, file, line
-- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern
-- **Impact**: How it affects users
-- **WCAG/Standard**: Which standard it violates (if applicable)
-- **Recommendation**: How to fix it
-- **Suggested command**: Which command to use (prefer: $impeccable adapt, $impeccable animate, $impeccable audit, $impeccable bolder, $impeccable clarify, $impeccable colorize, $impeccable critique, $impeccable delight, $impeccable distill, $impeccable document, $impeccable harden, $impeccable layout, $impeccable onboard, $impeccable optimize, $impeccable overdrive, $impeccable polish, $impeccable quieter, $impeccable shape, $impeccable typeset)
-
-### Patterns & Systemic Issues
-
-Identify recurring problems that indicate systemic gaps rather than one-off mistakes:
-- "Hard-coded colors appear in 15+ components, should use design tokens"
-- "Touch targets consistently too small (<44px) throughout mobile experience"
-
-### Positive Findings
-
-Note what's working well: good practices to maintain and replicate.
-
-## Recommended Actions
-
-List recommended commands in priority order (P0 first, then P1, then P2):
-
-1. **[P?] `$command-name`**: Brief description (specific context from audit findings)
-2. **[P?] `$command-name`**: Brief description (specific context)
-
-**Rules**: Only recommend commands from: $impeccable adapt, $impeccable animate, $impeccable audit, $impeccable bolder, $impeccable clarify, $impeccable colorize, $impeccable critique, $impeccable delight, $impeccable distill, $impeccable document, $impeccable harden, $impeccable layout, $impeccable onboard, $impeccable optimize, $impeccable overdrive, $impeccable polish, $impeccable quieter, $impeccable shape, $impeccable typeset. Map findings to the most appropriate command. End with `$impeccable polish` as the final step if any fixes were recommended.
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `$impeccable audit` after fixes to see your score improve.
-
-**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters.
-
-**NEVER**:
-- Report issues without explaining impact (why does this matter?)
-- Provide generic recommendations (be specific and actionable)
-- Skip positive findings (celebrate what works)
-- Forget to prioritize (everything can't be P0)
-- Report false positives without verification
-
@@ -1,113 +0,0 @@
-When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact and personality through stronger hierarchy, committed scale, and decisive type.
-
----
-
-## Register
-
-Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
-
-Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too safe or boring:
-
-1. **Identify weakness sources**:
- - **Generic choices**: System fonts, basic colors, standard layouts
- - **Timid scale**: Everything is medium-sized with no drama
- - **Low contrast**: Everything has similar visual weight
- - **Static**: No motion, no energy, no life
- - **Predictable**: Standard patterns with no surprises
- - **Flat hierarchy**: Nothing stands out or commands attention
-
-2. **Understand the context**:
- - What's the brand personality? (How far can we push?)
- - What's the purpose? (Marketing can be bolder than financial dashboards)
- - Who's the audience? (What will resonate?)
- - What are the constraints? (Brand guidelines, accessibility, performance)
-
-If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer.
-
-**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
-
-**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
-
-## Plan Amplification
-
-Create a strategy to increase impact while maintaining coherence:
-
-- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
-- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
-- **Risk budget**: How experimental can we be? Push boundaries within constraints.
-- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
-
-**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration.
-
-## Amplify the Design
-
-Systematically increase impact across these dimensions:
-
-### Typography Amplification
-- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and [typography.md](typography.md) for inspiration)
-- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
-- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
-- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
-
-### Color Intensification
-- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
-- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop
-- **Dominant color strategy**: Let one bold color own 60% of the design
-- **Sharp accents**: High-contrast accent colors that pop
-- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
-- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
-
-### Spatial Drama
-- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
-- **Break the grid**: Let hero elements escape containers and cross boundaries
-- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
-- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
-- **Overlap**: Layer elements intentionally for depth
-
-### Visual Effects
-- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
-- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
-- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop)
-- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
-- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
-
-### Motion & Animation
-- **Entrance choreography**: Staggered, dramatic page load animations with 50-100ms delays
-- **Scroll effects**: Parallax, reveal animations, scroll-triggered sequences
-- **Micro-interactions**: Satisfying hover effects, click feedback, state changes
-- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect)
-
-### Composition Boldness
-- **Hero moments**: Create clear focal points with dramatic treatment
-- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
-- **Full-bleed elements**: Use full viewport width/height for impact
-- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
-
-**NEVER**:
-- Add effects randomly without purpose (chaos ≠ bold)
-- Sacrifice readability for aesthetics (body text must be readable)
-- Make everything bold (then nothing is bold; you need contrast)
-- Ignore accessibility (bold design must still meet WCAG standards)
-- Overwhelm with motion (animation fatigue is real)
-- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
-
-## Verify Quality
-
-Ensure amplification maintains usability and coherence:
-
-- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over.
-- **Still functional**: Can users accomplish tasks without distraction?
-- **Coherent**: Does everything feel intentional and unified?
-- **Memorable**: Will users remember this experience?
-- **Performant**: Do all these effects run smoothly?
-- **Accessible**: Does it still meet accessibility standards?
-
-**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects."
-
-When the result feels right, hand off to `$impeccable polish` for the final pass.
@@ -1,118 +0,0 @@
-# Brand register
-
-When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made.
-
-The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look.
-
-## The brand slop test
-
-If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?"
-
-Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home.
-
-**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register.
-
-Then the inverse test: in one sentence, describe what you're about to build the way a competitor would describe theirs. If that sentence fits the modal landing page in the category, restart.
-
-## Typography
-
-### Font selection procedure
-
-Every project. Never skip.
-
-1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words.
-2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture.
-3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy."
-4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over.
-
-### Reflex-reject list
-
-Training-data defaults. Ban list. Look further:
-
-Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif
-
-### Reflex-reject aesthetic lanes
-
-Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further.
-
-- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery.
-
-(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.)
-
-The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md).
-
-### Pairing and voice
-
-Distinctive + refined is the goal. The specific shape depends on the brand:
-
-- **Editorial / long-form / luxury**: display serif + sans body (a magazine shape).
-- **Tech / dev tools / fintech**: one committed sans, usually; custom-tight tracking, strong weight contrast inside a single family.
-- **Consumer / food / travel**: warmer pairings, often a humanist sans plus a script or display serif.
-- **Creative studios / agencies**: rule-breaking welcome. Mono-only, or display-only, or custom-drawn type as voice.
-
-Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair.
-
-Vary across projects. If the last brief was a serif-display landing page, this one isn't.
-
-### Scale
-
-Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted.
-
-Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room.
-
-## Color
-
-Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register.
-
-- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige.
-- Palette IS voice. A calm brand and a restless brand should not share palette mechanics.
-- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit.
-- Don't converge across projects. If the last brand surface was restrained-on-cream, this one is not.
-- When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette.
-
-## Layout
-
-- Asymmetric compositions are one option. Break the grid intentionally for emphasis.
-- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings.
-- Alternative: a strict, visible grid as the voice (brutalist / Swiss / tech-spec aesthetics). Either asymmetric or rigorously-gridded can be "designed"; the failure mode is splitting the difference into a generic centered stack.
-- Don't default to centering everything. Left-aligned with asymmetric layouts feels more designed; a strict grid reads as confident structure. A centered-stack hero with icon-title-subtitle cards reads as template.
-- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness.
-
-## Imagery
-
-Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo.
-
-**When the brief implies imagery (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product), you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy.
-
-- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `<div>` placeholders.
-- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel".
-- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one.
-- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish".
-
-"Imagery" here is broader than stock photography: product screenshots, custom data visualizations, generated SVG, and canvas/WebGL scenes are all imagery. Text-only pages where typography alone carries the entire visual weight are the failure mode.
-
-## Motion
-
-- One well-orchestrated page-load with staggered reveals beats scattered micro-interactions, when the brand invites it. Tech-minimal brands often skip entrance motion entirely; the restraint is the voice.
-- For collapsing/expanding sections, transition `grid-template-rows` rather than `height`.
-
-## Brand bans (on top of the shared absolute bans)
-
-- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume.
-- Large rounded-corner icons above every heading. Screams template.
-- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.)
-- All-caps body copy. Reserve caps for short labels and headings.
-- Timid palettes and average layouts. Safe = invisible.
-- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs.
-- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic.
-- Repeated tiny uppercase tracked labels above every section heading. A single strong kicker can be voice; repeating it as section grammar is AI scaffolding unless it's a deliberate, named brand system.
-
-## Brand permissions
-
-Brand can afford things product can't. Take them.
-
-- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography.
-- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing.
-- Typographic risk. Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines, a single oversize word as a hero.
-- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics.
-- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment.
@@ -1,174 +0,0 @@
-> **Additional context needed**: audience technical level and users' mental state in context.
-
-Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task.
-
-
----
-
-## Assess Current Copy
-
-Identify what makes the text unclear or ineffective:
-
-1. **Find clarity problems**:
- - **Jargon**: Technical terms users won't understand
- - **Ambiguity**: Multiple interpretations possible
- - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file"
- - **Length**: Too wordy or too terse
- - **Assumptions**: Assuming user knowledge they don't have
- - **Missing context**: Users don't know what to do or why
- - **Tone mismatch**: Too formal, too casual, or inappropriate for situation
-
-2. **Understand the context**:
- - Who's the audience? (Technical? General? First-time users?)
- - What's the user's mental state? (Stressed during error? Confident during success?)
- - What's the action? (What do we want users to do?)
- - What's the constraint? (Character limits? Space limitations?)
-
-**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets.
-
-## Plan Copy Improvements
-
-Create a strategy for clearer communication:
-
-- **Primary message**: What's the ONE thing users need to know?
-- **Action needed**: What should users do next (if anything)?
-- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?)
-- **Constraints**: Length limits, brand voice, localization considerations
-
-**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words.
-
-## Improve Copy Systematically
-
-Refine text across these common areas:
-
-### Error Messages
-**Bad**: "Error 403: Forbidden"
-**Good**: "You don't have permission to view this page. Contact your admin for access."
-
-**Bad**: "Invalid input"
-**Good**: "Email addresses need an @ symbol. Try: name@example.com"
-
-**Principles**:
-- Explain what went wrong in plain language
-- Suggest how to fix it
-- Don't blame the user
-- Include examples when helpful
-- Link to help/support if applicable
-
-### Form Labels & Instructions
-**Bad**: "DOB (MM/DD/YYYY)"
-**Good**: "Date of birth" (with placeholder showing format)
-
-**Bad**: "Enter value here"
-**Good**: "Your email address" or "Company name"
-
-**Principles**:
-- Use clear, specific labels (not generic placeholders)
-- Show format expectations with examples
-- Explain why you're asking (when not obvious)
-- Put instructions before the field, not after
-- Keep required field indicators clear
-
-### Button & CTA Text
-**Bad**: "Click here" | "Submit" | "OK"
-**Good**: "Create account" | "Save changes" | "Got it, thanks"
-
-**Principles**:
-- Describe the action specifically
-- Use active voice (verb + noun)
-- Match user's mental model
-- Be specific ("Save" is better than "OK")
-
-### Help Text & Tooltips
-**Bad**: "This is the username field"
-**Good**: "Choose a username. You can change this later in Settings."
-
-**Principles**:
-- Add value (don't just repeat the label)
-- Answer the implicit question ("What is this?" or "Why do you need this?")
-- Keep it brief but complete
-- Link to detailed docs if needed
-
-### Empty States
-**Bad**: "No items"
-**Good**: "No projects yet. Create your first project to get started."
-
-**Principles**:
-- Explain why it's empty (if not obvious)
-- Show next action clearly
-- Make it welcoming, not dead-end
-
-### Success Messages
-**Bad**: "Success"
-**Good**: "Settings saved! Your changes will take effect immediately."
-
-**Principles**:
-- Confirm what happened
-- Explain what happens next (if relevant)
-- Be brief but complete
-- Match the user's emotional moment (celebrate big wins)
-
-### Loading States
-**Bad**: "Loading..." (for 30+ seconds)
-**Good**: "Analyzing your data... this usually takes 30-60 seconds"
-
-**Principles**:
-- Set expectations (how long?)
-- Explain what's happening (when it's not obvious)
-- Show progress when possible
-- Offer escape hatch if appropriate ("Cancel")
-
-### Confirmation Dialogs
-**Bad**: "Are you sure?"
-**Good**: "Delete 'Project Alpha'? This can't be undone."
-
-**Principles**:
-- State the specific action
-- Explain consequences (especially for destructive actions)
-- Use clear button labels ("Delete project" not "Yes")
-- Don't overuse confirmations (only for risky actions)
-
-### Navigation & Wayfinding
-**Bad**: Generic labels like "Items" | "Things" | "Stuff"
-**Good**: Specific labels like "Your projects" | "Team members" | "Settings"
-
-**Principles**:
-- Be specific and descriptive
-- Use language users understand (not internal jargon)
-- Make hierarchy clear
-- Consider information scent (breadcrumbs, current location)
-
-## Apply Clarity Principles
-
-Every piece of copy should follow these rules:
-
-1. **Be specific**: "Enter email" not "Enter value"
-2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity)
-3. **Be active**: "Save changes" not "Changes will be saved"
-4. **Be human**: "Oops, something went wrong" not "System error encountered"
-5. **Tell users what to do**, not just what happened
-6. **Be consistent**: Use same terms throughout (don't vary for variety)
-
-**NEVER**:
-- Use jargon without explanation
-- Blame users ("You made an error" → "This field is required")
-- Be vague ("Something went wrong" without explanation)
-- Use passive voice unnecessarily
-- Write overly long explanations (be concise)
-- Use humor for errors (be empathetic instead)
-- Assume technical knowledge
-- Vary terminology (pick one term and stick with it)
-- Repeat information (headers restating intros, redundant explanations)
-- Use placeholders as the only labels (they disappear when users type)
-
-## Verify Improvements
-
-Test that copy improvements work:
-
-- **Comprehension**: Can users understand without context?
-- **Actionability**: Do users know what to do next?
-- **Brevity**: Is it as short as possible while remaining clear?
-- **Consistency**: Does it match terminology elsewhere?
-- **Tone**: Is it appropriate for the situation?
-
-When the copy reads cleanly, hand off to `$impeccable polish` for the final pass.
@@ -1,105 +0,0 @@
-# Codex: Visual Direction & Asset Production
-
-This file is loaded by `$impeccable craft` when the harness has native image generation (currently Codex via `image_gen`). Other harnesses skip it. It covers the two craft steps that depend on real image generation: landing the visual direction, and producing the raster assets the implementation will compose.
-
-Read this *before* generating any images. The order matters, and the per-step user pauses are what keep generated imagery from drifting away from the brief.
-
-### Four stop points before code
-
-Steps A through D each end with the user. Do not advance past any of them on your own read of the situation.
-
-1. **STOP after Step A questions.** Wait for answers.
-2. **STOP after Step B palette generation.** Wait for "confirm palette."
-3. **STOP after Step C mocks.** Wait for direction approval or delegation.
-4. **Only after Step D approves a direction** do you return to craft.md Step 4 and write code.
-
-Prior shape approval does **not** satisfy any of these. Shape's "confirm or override" advances you into Step A; it is not a substitute for it.
-
-## Step A: Explore Directions with the User
-
-Before generating anything, run a brief direction conversation grounded in the shape brief.
-
-**Step A is required even when shape just produced a confirmed brief.** The shape questions and Step A questions cover different ground: shape pins purpose, content, scope; Step A pins palette, atmosphere, and named visual references for the comps you're about to generate. The only time you can skip Step A is when the user has already answered these exact palette/atmosphere/reference questions in the same session.
-
-Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions:
-
-- "Brief says 'editorial restraint, Klim-adjacent.' Are we closer to a quiet specimen page or a magazine-spread feel with hero imagery?"
-- "Palette strategy from shape was 'Committed.' Want it warm-grounded (deep oxblood + cream) or cool-grounded (slate + paper white)?"
-
-**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded.
-
-## Step B: Generate the Brand Palette First
-
-Generate **one** palette artifact before any mocks. This is a small, focused image: typography pairing on the chosen background, primary + accent color swatches, one signature ornament or motif. Single image, single pass.
-
-Why palette first: mocks generated against a vague color sense produce noise that drowns out the structural decisions. A confirmed palette is the first concrete contract for everything downstream.
-
-Show the palette to the user. Ask one question: "This is the palette I'm locking in for the mocks. Confirm, or call out what to shift?"
-
-**STOP and wait for confirmation.** Do not generate mocks against an unconfirmed palette. "Probably good enough" is the wrong call here; the palette is the contract for everything downstream.
-
-## Step C: Generate 1-3 Visual Mocks Against the Palette
-
-Once the palette is confirmed, generate **1 to 3** high-fidelity north-star comps. Each mock must use the confirmed palette and typography. Mocks differ in *structural* direction (hierarchy, topology, density, composition), not in color or motif.
-
-- Brand work: push visual identity, composition, mood, and signature motifs.
-- Product work: push hierarchy, topology, density, tone, grounded in realistic product structure.
-- Landing pages and long-form brand surfaces: show enough of the second fold to establish the system beyond the hero.
-
-Use the `image_gen` tool directly (or via the imagegen skill when available). Don't ask the user to install anything.
-
-## Step D: Approval Loop
-
-Show the comps. Ask what carries forward. Iterate until **one direction is approved** or the user explicitly delegates.
-
-**STOP and wait for the approval or the delegation.** Do not begin Step E or return to craft.md Step 4 until a single direction is named. If the user delegates, pick the strongest direction and explain it from the brief, not personal taste.
-
-Before moving to assets, summarize what to carry into code and what *not* to literalize from the mock. This is the handoff between visual exploration and semantic implementation.
-
-## Step E: Mock Fidelity Inventory
-
-Inventory the approved mock's major visible ingredients. For each, decide implementation: semantic HTML/CSS/SVG, generated raster, sourced raster, icon library, canvas/WebGL, or accepted omission.
-
-Common ingredients to inventory:
-
-- Hero silhouette and dominant composition
-- Signature motifs (planets, devices, portraits, charts, route lines, insets, badges, etc.)
-- Nav and primary CTA treatment
-- Section sequence, especially the second fold
-- Image-native content the concept depends on
-- Typography, density, color/material treatment, motion cues
-
-Treat the mock as a north star, not a screenshot to trace. Don't rasterize core UI text. But if the live result lacks the mock's major ingredients, the implementation is wrong.
-
-If a photographic, architectural, product, or place-led mock becomes generic CSS scenery, decorative diagrams, bullets, or copy, stop and fix it. That's a broken implementation, not a harmless interpretation.
-
-Don't substitute a different hero composition or visual driver post-approval without user sign-off.
-
-## Step F: Asset Slicing via the Asset Producer
-
-Raster ingredients identified in Step E need clean production assets. Use the bundled `impeccable_asset_producer` subagent rather than producing inline.
-
-Spawn it as a scoped subagent. If you do not have explicit permission to use agents, stop and ask:
-
-```text
-Asset production will work better as a scoped subagent job. Should I spawn the Impeccable asset producer subagent for this step?
-```
-
-Pass to the agent:
-
-- Approved mock path or screenshot reference
-- Crop paths or a contact sheet with crop ids
-- Output directory
-- Required dimensions, format, transparency needs
-- Avoid list
-- Notes on what should remain semantic HTML/CSS/SVG instead of raster
-
-Attach image generation capability to the spawned agent when the harness supports it. Do **not** load image-generation reference material into the parent thread.
-
-Inline asset production is allowed only if the user declines subagents, the harness cannot spawn the authorized agent, or the user explicitly asks for single-thread mode.
-
-Prefer HTML/CSS/SVG/canvas when they can credibly reproduce an ingredient; reach for real, generated, or stock imagery when the mock or subject matter calls for actual visual content.
-
-## After This File
-
-Once Steps A through F are complete, return to `craft.md` Step 5 (Build to Production Quality). The implementation builds against the confirmed palette, approved mock, and the assets the producer wrote.
@@ -1,106 +0,0 @@
-# Cognitive Load Assessment
-
-Cognitive load is the total mental effort required to use an interface. Overloaded users make mistakes, get frustrated, and leave. This reference helps identify and fix cognitive overload.
-
----
-
-## Three Types of Cognitive Load
-
-### Intrinsic Load: The Task Itself
-Complexity inherent to what the user is trying to do. You can't eliminate this, but you can structure it.
-
-**Manage it by**:
-- Breaking complex tasks into discrete steps
-- Providing scaffolding (templates, defaults, examples)
-- Progressive disclosure: show what's needed now, hide the rest
-- Grouping related decisions together
-
-### Extraneous Load: Bad Design
-Mental effort caused by poor design choices. **Eliminate this ruthlessly.** It's pure waste.
-
-**Common sources**:
-- Confusing navigation that requires mental mapping
-- Unclear labels that force users to guess meaning
-- Visual clutter competing for attention
-- Inconsistent patterns that prevent learning
-- Unnecessary steps between user intent and result
-
-### Germane Load: Learning Effort
-Mental effort spent building understanding. This is *good* cognitive load; it leads to mastery.
-
-**Support it by**:
-- Progressive disclosure that reveals complexity gradually
-- Consistent patterns that reward learning
-- Feedback that confirms correct understanding
-- Onboarding that teaches through action, not walls of text
-
----
-
-## Cognitive Load Checklist
-
-Evaluate the interface against these 8 items:
-
-- [ ] **Single focus**: Can the user complete their primary task without distraction from competing elements?
-- [ ] **Chunking**: Is information presented in digestible groups (≤4 items per group)?
-- [ ] **Grouping**: Are related items visually grouped together (proximity, borders, shared background)?
-- [ ] **Visual hierarchy**: Is it immediately clear what's most important on the screen?
-- [ ] **One thing at a time**: Can the user focus on a single decision before moving to the next?
-- [ ] **Minimal choices**: Are decisions simplified (≤4 visible options at any decision point)?
-- [ ] **Working memory**: Does the user need to remember information from a previous screen to act on the current one?
-- [ ] **Progressive disclosure**: Is complexity revealed only when the user needs it?
-
-**Scoring**: Count the failed items. 0–1 failures = low cognitive load (good). 2–3 = moderate (address soon). 4+ = high cognitive load (critical fix needed).
-
----
-
-## The Working Memory Rule
-
-**Humans can hold ≤4 items in working memory at once** (Miller's Law revised by Cowan, 2001).
-
-At any decision point, count the number of distinct options, actions, or pieces of information a user must simultaneously consider:
-- **≤4 items**: Within working memory limits, manageable
-- **5–7 items**: Pushing the boundary; consider grouping or progressive disclosure
-- **8+ items**: Overloaded; users will skip, misclick, or abandon
-
-**Practical applications**:
-- Navigation menus: ≤5 top-level items (group the rest under clear categories)
-- Form sections: ≤4 fields visible per group before a visual break
-- Action buttons: 1 primary, 1–2 secondary, group the rest in a menu
-- Dashboard widgets: ≤4 key metrics visible without scrolling
-- Pricing tiers: ≤3 options (more causes analysis paralysis)
-
----
-
-## Common Cognitive Load Violations
-
-### 1. The Wall of Options
-**Problem**: Presenting 10+ choices at once with no hierarchy.
-**Fix**: Group into categories, highlight recommended, use progressive disclosure.
-
-### 2. The Memory Bridge
-**Problem**: User must remember info from step 1 to complete step 3.
-**Fix**: Keep relevant context visible, or repeat it where it's needed.
-
-### 3. The Hidden Navigation
-**Problem**: User must build a mental map of where things are.
-**Fix**: Always show current location (breadcrumbs, active states, progress indicators).
-
-### 4. The Jargon Barrier
-**Problem**: Technical or domain language forces translation effort.
-**Fix**: Use plain language. If domain terms are unavoidable, define them inline.
-
-### 5. The Visual Noise Floor
-**Problem**: Every element has the same visual weight; nothing stands out.
-**Fix**: Establish clear hierarchy: one primary element, 2–3 secondary, everything else muted.
-
-### 6. The Inconsistent Pattern
-**Problem**: Similar actions work differently in different places.
-**Fix**: Standardize interaction patterns. Same type of action = same type of UI.
-
-### 7. The Multi-Task Demand
-**Problem**: Interface requires processing multiple simultaneous inputs (reading + deciding + navigating).
-**Fix**: Sequence the steps. Let the user do one thing at a time.
-
-### 8. The Context Switch
-**Problem**: User must jump between screens/tabs/modals to gather info for a single decision.
-**Fix**: Co-locate the information needed for each decision. Reduce back-and-forth.
@@ -1,105 +0,0 @@
-# Color & Contrast
-
-## Color Spaces: Use OKLCH
-
-**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark.
-
-The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish.
-
-The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand.
-
-## Building Functional Palettes
-
-### Tinted Neutrals
-
-**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces.
-
-The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette.
-
-**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects.
-
-### Palette Structure
-
-A complete system needs:
-
-| Role | Purpose | Example |
-|------|---------|---------|
-| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades |
-| **Neutral** | Text, backgrounds, borders | 9-11 shade scale |
-| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each |
-| **Surface** | Cards, modals, overlays | 2-3 elevation levels |
-
-**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise.
-
-### The 60-30-10 Rule (Applied Correctly)
-
-This rule is about **visual weight**, not pixel count:
-
-- **60%**: Neutral backgrounds, white space, base surfaces
-- **30%**: Secondary colors: text, borders, inactive states
-- **10%**: Accent: CTAs, highlights, focus states
-
-The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power.
-
-## Contrast & Accessibility
-
-### WCAG Requirements
-
-| Content Type | AA Minimum | AAA Target |
-|--------------|------------|------------|
-| Body text | 4.5:1 | 7:1 |
-| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 |
-| UI components, icons | 3:1 | 4.5:1 |
-| Non-essential decorations | None | None |
-
-**The gotcha**: Placeholder text still needs 4.5:1. That light gray placeholder you see everywhere? Usually fails WCAG.
-
-### Dangerous Color Combinations
-
-These commonly fail contrast or cause readability issues:
-
-- Light gray text on white (the #1 accessibility fail)
-- **Gray text on any colored background**: gray looks washed out and dead on color. Use a darker shade of the background color, or transparency
-- Red text on green background (or vice versa): 8% of men can't distinguish these
-- Blue text on red background (vibrates visually)
-- Yellow text on white (almost always fails)
-- Thin light text on images (unpredictable contrast)
-
-### Never Use Pure Gray or Pure Black
-
-Pure gray (`oklch(50% 0 0)`) and pure black (`#000`) don't exist in nature; real shadows and surfaces always have a color cast. Even a chroma of 0.005-0.01 is enough to feel natural without being obviously tinted. (See tinted neutrals example above.)
-
-### Testing
-
-Don't trust your eyes. Use tools:
-
-- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/)
-- Browser DevTools → Rendering → Emulate vision deficiencies
-- [Polypane](https://polypane.app/) for real-time testing
-
-## Theming: Light & Dark Mode
-
-### Dark Mode Is Not Inverted Light Mode
-
-You can't just swap colors. Dark mode requires different design decisions:
-
-| Light Mode | Dark Mode |
-|------------|-----------|
-| Shadows for depth | Lighter surfaces for depth (no shadows) |
-| Dark text on light | Light text on dark (reduce font weight) |
-| Vibrant accents | Desaturate accents slightly |
-| White backgrounds | Never pure black; use dark gray (oklch 12-18%) |
-
-In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light.
-
-### Token Hierarchy
-
-Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same.
-
-## Alpha Is A Design Smell
-
-Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed.
-
----
-
-**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Using pure black (#000) for large areas. Skipping color blindness testing (8% of men affected).
@@ -1,154 +0,0 @@
-> **Additional context needed**: existing brand colors.
-
-Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit.
-
----
-
-## Register
-
-Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it.
-
-Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen.
-
----
-
-## Assess Color Opportunity
-
-Analyze the current state and identify opportunities:
-
-1. **Understand current state**:
- - **Color absence**: Pure grayscale? Limited neutrals? One timid accent?
- - **Missed opportunities**: Where could color add meaning, hierarchy, or delight?
- - **Context**: What's appropriate for this domain and audience?
- - **Brand**: Are there existing brand colors we should use?
-
-2. **Identify where color adds value**:
- - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue)
- - **Hierarchy**: Drawing attention to important elements
- - **Categorization**: Different sections, types, or states
- - **Emotional tone**: Warmth, energy, trust, creativity
- - **Wayfinding**: Helping users navigate and understand structure
- - **Delight**: Moments of visual interest and personality
-
-If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer.
-
-**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose.
-
-## Plan Color Strategy
-
-Create a purposeful color introduction plan:
-
-- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals)
-- **Dominant color**: Which color owns 60% of colored elements?
-- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%)
-- **Application strategy**: Where does each color appear and why?
-
-**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more.
-
-## Introduce Color Strategically
-
-Add color systematically across these dimensions:
-
-### Semantic Color
-- **State indicators**:
- - Success: Green tones (emerald, forest, mint)
- - Error: Red/pink tones (rose, crimson, coral)
- - Warning: Orange/amber tones
- - Info: Blue tones (sky, ocean, indigo)
- - Neutral: Gray/slate for inactive states
-
-- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.)
-- **Progress indicators**: Colored bars, rings, or charts showing completion or health
-
-### Accent Color Application
-- **Primary actions**: Color the most important buttons/CTAs
-- **Links**: Add color to clickable text (maintain accessibility)
-- **Icons**: Colorize key icons for recognition and personality
-- **Headers/titles**: Add color to section headers or key labels
-- **Hover states**: Introduce color on interaction
-
-### Background & Surfaces
-- **Tinted backgrounds**: Replace pure gray (`#f5f5f5`) with warm neutrals (`oklch(97% 0.01 60)`) or cool tints (`oklch(97% 0.01 250)`)
-- **Colored sections**: Use subtle background colors to separate areas
-- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue)
-- **Cards & surfaces**: Tint cards or surfaces slightly for warmth
-
-**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
-
-### Data Visualization
-- **Charts & graphs**: Use color to encode categories or values
-- **Heatmaps**: Color intensity shows density or importance
-- **Comparison**: Color coding for different datasets or timeframes
-
-### Borders & Accents
-- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`)
-- **Underlines**: Color underlines for emphasis or active states
-- **Dividers**: Subtle colored dividers instead of gray lines
-- **Focus rings**: Colored focus indicators matching brand
-- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe
-
-**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe.
-
-### Typography Color
-- **Colored headings**: Use brand colors for section headings (maintain contrast)
-- **Highlight text**: Color for emphasis or categories
-- **Labels & tags**: Small colored labels for metadata or categories
-
-### Decorative Elements
-- **Illustrations**: Add colored illustrations or icons
-- **Shapes**: Geometric shapes in brand colors as background elements
-- **Gradients**: Colorful gradient overlays or mesh backgrounds
-- **Blobs/organic shapes**: Soft colored shapes for visual interest
-
-## Balance & Refinement
-
-Ensure color addition improves rather than overwhelms:
-
-### Maintain Hierarchy
-- **Dominant color** (60%): Primary brand color or most used accent
-- **Secondary color** (30%): Supporting color for variety
-- **Accent color** (10%): High contrast for key moments
-- **Neutrals** (remaining): Gray/black/white for structure
-
-### Accessibility
-- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components)
-- **Don't rely on color alone**: Use icons, labels, or patterns alongside color
-- **Test for color blindness**: Verify red/green combinations work for all users
-
-### Cohesion
-- **Consistent palette**: Use colors from defined palette, not arbitrary choices
-- **Systematic application**: Same color meanings throughout (green always = success)
-- **Temperature consistency**: Warm palette stays warm, cool stays cool
-
-**NEVER**:
-- Use every color in the rainbow (choose 2-4 colors beyond neutrals)
-- Apply color randomly without semantic meaning
-- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead
-- Use pure gray for neutrals. Add subtle color tint (warm or cool) for depth
-- Use pure black (`#000`) or pure white (`#fff`) for large areas
-- Violate WCAG contrast requirements
-- Use color as the only indicator (accessibility issue)
-- Make everything colorful (defeats the purpose)
-- Default to purple-blue gradients (AI slop aesthetic)
-
-## Verify Color Addition
-
-Test that colorization improves the experience:
-
-- **Better hierarchy**: Does color guide attention appropriately?
-- **Clearer meaning**: Does color help users understand states/categories?
-- **More engaging**: Does the interface feel warmer and more inviting?
-- **Still accessible**: Do all color combinations meet WCAG standards?
-- **Not overwhelming**: Is color balanced and purposeful?
-
-When the palette earns its place, hand off to `$impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage.
-
-```json
-{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"}
-```
-
-Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract.
@@ -1,123 +0,0 @@
-# Craft Flow
-
-Build a feature with impeccable UX and UI quality: shape the design, land the visual direction, build real production code, inspect and improve in-browser until it meets a high-end studio bar.
-
-Before writing code, you need: PRODUCT.md loaded, register identified and the matching reference loaded, and a confirmed design direction for this task (either from `shape` or supplied by the user). PRODUCT.md is project context, not a task-specific brief.
-
-Treat any approved visual direction (generated mock or stated reference) as a concrete contract for composition, hierarchy, density, atmosphere, signature motifs, and distinctive visual moves. Don't let mocks replace structure, copy, accessibility, or state design. But if the live result lacks the approved direction's major ingredients, the implementation is wrong.
-
-### Gates: do not compress
-
-Craft has **multiple user gates**, not one. When the harness has native image generation (Codex via `image_gen`), the gate sequence before code is:
-
-1. **Shape brief confirmed** (Step 1)
-2. **Direction questions answered** (codex.md Step A)
-3. **Palette confirmed** (codex.md Step B)
-4. **One mock direction approved or delegated** (codex.md Step D)
-
-You must stop at every gate. **Shape confirmation alone is NOT a green light to start coding.** It is the green light to begin codex.md Step A. Compressing gates 2 through 4 because the shape brief felt complete is the dominant failure mode of this flow.
-
-When the harness lacks native image generation, gates 2-4 collapse into the brief itself, and shape confirmation does advance straight to code.
-
-## Step 0: Project Foundation
-
-Before shape, before code: figure out what kind of project you're working in.
-
-Look at the working directory. Run `ls`. Check for:
-
-- An existing framework: `astro.config.mjs/ts`, `next.config.js/ts`, `nuxt.config.ts`, `svelte.config.js`, `vite.config.js/ts`, `package.json` with framework deps, `Cargo.toml` + Leptos/Yew, `Gemfile` + Rails. **If found, use it.** Do not start a parallel build, do not introduce a second framework, do not write to `dist/` or `build/` directly. Whatever pipeline the project has, respect it.
-- An existing component library or design system: `src/components/`, `app/components/`, a `tokens.css` / `theme.ts`, an `astro.config` `integrations`. Read what's there before adding to it.
-- An existing icon set: `lucide-react`, `@phosphor-icons/react`, `@iconify/*`, hand-rolled SVG sprites in `assets/icons/`. **Use what's already in the project**; don't introduce a second set.
-
-If the directory is empty (greenfield), don't pick a framework silently. Ask the user via the AskUserQuestion tool, with sensible defaults framed by the brief:
-
-```text
-What should this be built on?
- - Astro (default for content-led brand sites, landing pages, marketing surfaces)
- - SvelteKit / Next.js / Nuxt (when the brief implies an app surface or significant interactivity)
- - Single index.html (one-shot demo, prototype, or a deliberately framework-free experiment)
-```
-
-Default: Astro for brand briefs, the project's existing framework for product briefs. Ask once; don't re-ask mid-task.
-
-## Step 1: Shape the Design
-
-Run $impeccable shape, passing along whatever feature description the user provided. Shape is **required** for craft; it is what produces a confirmed direction.
-
-Present the shape output and stop. Wait for the user to confirm, override, or course-correct before writing code.
-
-If the user already supplied a confirmed brief or ran shape separately, use it and skip this step.
-
-When the original prompt + PRODUCT.md already answer scope, content, and visual direction with no real ambiguity, the shape output can be **compact** (3-5 bullets stating what you're building and the visual lane, ending with one or two specific questions or "confirm or override"). The full 10-section structured brief is reserved for genuinely ambiguous, multi-screen, or stakeholder-heavy tasks. Don't pad a clear brief into a long one to look thorough; equally, don't skip the pause to look efficient.
-
-If the harness has native image generation (Codex), a compact shape's "confirm or override" advances to **Step 3 and the codex.md flow**, not to Step 4. Phrase the closing line accordingly: "Confirm or override; once we lock direction, I'll run a couple of palette and reference questions before generating any mocks." This stops the model from reading shape confirmation as code-green.
-
-## Step 2: Load References
-
-Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult:
-
-- [spatial-design.md](spatial-design.md) for layout and spacing
-- [typography.md](typography.md) for type hierarchy
-
-Then add references based on the brief's needs:
-- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md)
-- Animation or transitions? Consult [motion-design.md](motion-design.md)
-- Color-heavy or themed? Consult [color-and-contrast.md](color-and-contrast.md)
-- Responsive requirements? Consult [responsive-design.md](responsive-design.md)
-- Heavy on copy, labels, or errors? Consult [ux-writing.md](ux-writing.md)
-
-## Step 3: Visual Direction & Assets (Harness-Gated)
-
-If the harness has **native image generation** (currently Codex via `image_gen`), this step is mandatory. **Stop and load [codex.md](codex.md)**. It covers palette generation, mock exploration, the approval loop, mock-fidelity inventory, and asset slicing via the `impeccable_asset_producer` subagent. Follow Steps A-F in that file, then return here for Step 4.
-
-If the harness lacks native image generation, **state in one line that the visual-direction-by-generation step is being skipped because the harness lacks native image generation, then proceed**. The one-line announcement is required; it forces a conscious decision instead of letting the step quietly evaporate. The brief is your only visual reference. Implement directly from it, treating any named anchor references and the brief's "Design Direction" as the contract.
-
-Whether you generated mocks or not: don't replace required imagery with generic cards, bullets, emoji, fake metrics, decorative CSS panels, or filler copy. Image-led briefs (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product) need real or sourced imagery in the build, not CSS scenery.
-
-## Step 4: Build to Production Quality
-
-**Precondition.** If Step 3 routed you to codex.md (native image generation available), Steps A through D in that file must be complete before any code: questions answered, palette confirmed, mocks generated, one direction approved or delegated. **Do not mention implementation, file paths, or patch plans until that's done.** A confirmed shape brief is not enough; the model that compressed those gates is the model that already failed this flow.
-
-Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration.
-
-### Production bar
-
-- **Real content.** No placeholder copy, placeholder images, dead links, fake controls, or unused scaffold at presentation time.
-- **Preserve the approved mock's major ingredients.** Missing hero objects, world/product imagery, section structure, CTA/nav treatment, or distinctive motifs are blocking defects unless the user accepted the change.
-- **Semantic first.** Real headings, landmarks, labels, form associations, button/link semantics, accessible names, state announcements where needed.
-- **Deliberate spacing and alignment.** No default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment.
-- **Intentional typography.** Chosen loading strategy, clear hierarchy, readable measure, stable line breaks, no overflow at any width.
-- **Realistic state coverage.** Default, hover, focus-visible, active, disabled, loading, error, success, empty, overflow, long/short text, first-run.
-- **Finished interaction quality.** Keyboard paths, touch targets, feedback timing, scroll behavior, state transitions, no hover-only functionality.
-- **Coherent icon set.** Use the project's established set; otherwise pick one library or use accessible text. Don't mix.
-- **Respect the build pipeline.** Edit source files and run the project's build (`npm run build` or equivalent). Don't write to `build/` / `dist/` / `.next/` with `cat`, heredoc, or Bash redirects; that skips asset hashing, image optimization, code splitting, and CSS extraction, and produces output the dev server won't serve.
-- **Verify image URLs before referencing them.** Use image-search MCP or web-fetch when available; guessed photo IDs ship as broken-image placeholders. Without verification, prefer fewer images you're confident about.
-- **Optimized imagery and media.** Correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset`/`picture` for raster, no project-referenced asset left outside the workspace.
-- **Premium motion.** Use atmospheric blur, filter, mask, shadow, reveal when they improve the experience. Avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion.
-- **Maintainable.** Reusable local patterns, clear component boundaries, project conventions. No rasterized UI text or one-off hacks when a local pattern exists.
-- **Technically clean.** Production build passes, no console errors, no avoidable layout shift, no needless dependencies, no broken asset paths.
-- **Ask when uncertain.** If a discovery materially changes the brief or approved direction, stop and ask. Don't guess.
-
-## Step 5: Iterate Visually
-
-Look at what you built like a designer would. Your eyes are whatever the harness gives you: a connected browser, a screenshotting tool, Playwright, or asking the user. Use them for responsive testing (mobile, tablet, desktop minimum) and general visual validation.
-
-If your tool returns a file path, read the PNG back into the conversation. A screenshot you didn't read doesn't count.
-
-For long-form brand surfaces, inspect major sections individually. Thumbnails hide spacing, clipping, and cascade defects.
-
-After the first pass, write an honest critique against the brief, the approved mock's major ingredients (hero silhouette, motifs, imagery, nav/CTA, density), and impeccable's DON'Ts. Patch material defects and re-inspect. **Don't invent defects to demonstrate iteration.** A confident "first pass clean, shipping" beats a fake fix.
-
-Actively check: responsive behavior (composes, not shrinks), every state (empty / error / loading / edge), craft details (spacing, alignment, hierarchy, contrast, motion timing, focus), performance basics. The exit bar: defensible in a high-end studio review.
-
-Detector or QA output is defect evidence only; never proof the work is finished.
-
-## Step 6: Present
-
-Present the result to the user:
-- Show the feature in its primary state
-- Summarize the browser/viewports checked and the most important fixes made after inspection
-- Walk through the key states (empty, error, responsive)
-- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients.
-- Note any remaining limitations or follow-up risks honestly
-- Ask: "What's working? What isn't?"
@@ -1,259 +0,0 @@
-### Purpose
-
-Resolve one stable target, run two independent assessments, synthesize a design critique, persist a snapshot, and ask the user what to improve next. The chat response is the primary deliverable; the snapshot is an archive/backlog for future commands.
-
-### Hard Invariants
-
-- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
-- Assessment A must finish before detector findings enter the parent synthesis context. Detector output is deterministic, but it still anchors judgment.
-- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize.
-- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
-- Viewable targets require browser inspection when available.
-- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
-- Do not claim a user-visible overlay exists unless script injection succeeded and the detector ran in the page.
-
-### Setup
-
-1. **Resolve the target** to a concrete file path or URL. Prefer a source path over a dev-server URL when both identify the same surface; ports drift, paths do not.
- - "the homepage" -> `site/pages/index.astro` or `index.html`
- - "the settings modal" -> the primary component file
- - "this page" -> the current URL or source file
-2. **Compute the slug**:
- ```bash
- node .agents/skills/impeccable/scripts/critique-storage.mjs slug "<resolved-path-or-url>"
- ```
- Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique.
-3. **Read `.impeccable/critique/ignore.md`** if it exists. Drop matching findings silently; it is the only prior-run input critique consumes.
-
-### Assessment Orchestration
-
-Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis.
-
-Codex sub-agent gate:
-- If `spawn_agent` is exposed and the user explicitly allowed sub-agents, delegation, or parallel agent work, spawn A and B immediately.
-- If `spawn_agent` is exposed but the user did not explicitly allow sub-agents, ask exactly once: "Impeccable critique is designed to run two independent sub-agents for an unanchored assessment. May I use sub-agents for this critique?" Then stop until the user answers.
-- If allowed, spawn A and B. If declined, run sequentially and report `Assessment independence: degraded (sub-agents declined by user)`.
-- If `spawn_agent` is not exposed, do not ask; run sequentially and report `Assessment independence: degraded (spawn_agent unavailable in this session)`.
-- If spawning fails after permission, run sequentially and report `Assessment independence: degraded (sub-agent spawn failed: <exact error>)`.
-Prefer `fork_context: false` with self-contained prompts containing cwd, target, live URL, references, product context, and output contract. If using `fork_context: true`, omit `agent_type`, `model`, and `reasoning_effort`.
-
-If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
-
-### Assessment A: Design Review
-
-Read relevant source files and visually inspect the live page when browser automation is available. Think like a design director.
-
-Evaluate:
-- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill.
-- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases.
-- **Cognitive load**: consult [cognitive-load](cognitive-load.md); report checklist failures and decision points with >4 visible options.
-- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments.
-- **Nielsen heuristics**: consult [heuristics-scoring](heuristics-scoring.md); score all 10 heuristics 0-4.
-
-Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions.
-
-### Assessment B: Detector + Browser Evidence
-
-Run the bundled detector and browser visualization evidence. Assessment B is mandatory and must remain isolated from Assessment A until both are complete.
-
-CLI scan:
-```bash
-node .agents/skills/impeccable/scripts/detect.mjs --json [--fast] [target]
-```
-
-- Pass markup files/directories as `[target]`; do not pass CSS-only files.
-- For URLs, skip CLI scan and use browser visualization.
-- For 200+ scannable files, use `--fast`; for 500+, narrow scope or ask.
-- Exit code 0 = clean; 2 = findings.
-- If the detector entrypoint is missing or fails to load, report deterministic scan unavailable and continue with browser/manual review.
-
-Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
-
-1. Create a fresh tab and navigate.
-2. Preflight mutable injection by setting `document.title` and appending a `<script>` tag. Read-only evaluate APIs do not count.
-3. If mutation is unavailable, skip live server, browser presentation, and injection; report fallback signal.
-4. If mutation is available, start `node .agents/skills/impeccable/scripts/live-server.mjs --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then stop the live server.
-5. For multi-view targets, inject on 3-5 representative pages.
-
-Codex Browser note: Use the Browser skill. Do not spend a Browser attempt on `file://`. Only call `visibility.set(true)` after mutable script injection is confirmed for the `[Human]` overlay path; verify with `get()`. Use `tab.dev.logs({ filter: "impeccable" })` for console results. Its Playwright `evaluate(...)` surface is read-only; do not rely on it for mutation.
-
-Return: CLI findings JSON/counts, browser console findings if applicable, false positives, and skipped/failed browser steps with concrete reasons.
-
-After Assessment B returns usable CLI findings, reuse them. Do not rerun `detect.mjs` in the parent unless Assessment B failed, was truncated, or omitted count, rule names, or file locations.
-
-Codex failure accounting: final Run Notes must include target slug, ignore list, assessment independence, CLI detector, browser visibility, overlay injection, live-server cleanup, temp-file cleanup, and any fallback signal used. Do not run repo status checks, late API spelunking, or unrelated verification after the report is assembled.
-
-### Generate Combined Critique Report
-
-Synthesize both assessments into a single report. Do NOT simply concatenate. Weave the findings together, noting where the LLM review and detector agree, where the detector caught issues the LLM missed, and where detector findings are false positives.
-
-The chat response is the primary user-facing deliverable. Present the full structured critique below in chat; do not replace it with a summary and a link. The persisted snapshot is only an archive/backlog for later commands.
-
-Codex final-answer note: `$impeccable critique` produces a report artifact, so the final chat response should intentionally exceed the usual concise close-out style. Do not title the final response "Critique Summary" unless the user explicitly asked for a summary.
-
-Structure your feedback as a design director would:
-
-#### Design Health Score
-> *Consult [heuristics-scoring](heuristics-scoring.md)*
-
-Present the Nielsen's 10 heuristics scores as a table:
-
-| # | Heuristic | Score | Key Issue |
-|---|-----------|-------|-----------|
-| 1 | Visibility of System Status | ? | [specific finding or "n/a" if solid] |
-| 2 | Match System / Real World | ? | |
-| 3 | User Control and Freedom | ? | |
-| 4 | Consistency and Standards | ? | |
-| 5 | Error Prevention | ? | |
-| 6 | Recognition Rather Than Recall | ? | |
-| 7 | Flexibility and Efficiency | ? | |
-| 8 | Aesthetic and Minimalist Design | ? | |
-| 9 | Error Recovery | ? | |
-| 10 | Help and Documentation | ? | |
-| **Total** | | **??/40** | **[Rating band]** |
-
-Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32.
-
-#### Anti-Patterns Verdict
-
-**Start here.** Does this look AI-generated?
-
-**LLM assessment**: Your own evaluation of AI slop tells. Cover overall aesthetic feel, layout sameness, generic composition, missed opportunities for personality.
-
-**Deterministic scan**: Summarize what the automated detector found, with counts and file locations. Note any additional issues the detector caught that you missed, and flag any false positives.
-
-**Visual overlays** (if injection succeeded): Tell the user that overlays are now visible in the **[Human]** tab in their browser, highlighting the detected issues. Summarize what the console output reported. If browser visualization was attempted but injection failed, say that no reliable user-visible overlay is available and report the fallback signal instead.
-
-#### Overall Impression
-A brief gut reaction: what works, what doesn't, and the single biggest opportunity.
-
-#### What's Working
-Highlight 2-3 things done well. Be specific about why they work.
-
-#### Priority Issues
-The 3-5 most impactful design problems, ordered by importance.
-
-For each issue, tag with **P0-P3 severity** (consult [heuristics-scoring](heuristics-scoring.md) for severity definitions):
-- **[P?] What**: Name the problem clearly
-- **Why it matters**: How this hurts users or undermines goals
-- **Fix**: What to do about it (be concrete)
-- **Suggested command**: Which command could address this (from: $impeccable adapt, $impeccable animate, $impeccable audit, $impeccable bolder, $impeccable clarify, $impeccable colorize, $impeccable critique, $impeccable delight, $impeccable distill, $impeccable document, $impeccable harden, $impeccable layout, $impeccable onboard, $impeccable optimize, $impeccable overdrive, $impeccable polish, $impeccable quieter, $impeccable shape, $impeccable typeset)
-
-#### Persona Red Flags
-> *Consult [personas](personas.md)*
-
-Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `AGENTS.md` contains a `## Design Context` section from `impeccable teach`, also generate 1-2 project-specific personas from the audience/brand info.
-
-For each selected persona, walk through the primary user action and list specific red flags found:
-
-**Alex (Power User)**: No keyboard shortcuts detected. Form requires 8 clicks for primary action. Forced modal onboarding. High abandonment risk.
-
-**Jordan (First-Timer)**: Icon-only nav in sidebar. Technical jargon in error messages ("404 Not Found"). No visible help. Will abandon at step 2.
-
-Be specific. Name the exact elements and interactions that fail each persona. Don't write generic persona descriptions; write what broke for them.
-
-#### Minor Observations
-Quick notes on smaller issues worth addressing.
-
-#### Questions to Consider
-Provocative questions that might unlock better solutions:
-- "What if the primary action were more prominent?"
-- "Does this need to feel this complex?"
-- "What would a confident version of this look like?"
-
-#### Run Notes
-Keep this compact. Include status for target slug, ignore list, assessment independence, CLI detector, browser visibility, overlay injection, live server cleanup, and temp-file cleanup. For failed or skipped steps, give the concrete observed reason and the fallback signal used. In the final chat response, also include snapshot write and trend read status after persistence has run.
-
-Codex Run Notes are final-chat only. Do not include this section in the persisted snapshot body, because persistence, trend read, and temp cleanup happen after the snapshot write and would otherwise archive stale status such as "pending after persistence."
-
-**Remember**:
-- Be direct. Vague feedback wastes everyone's time.
-- Be specific. "The submit button," not "some elements."
-- Say what's wrong AND why it matters to users.
-- Give concrete suggestions. Cut "consider exploring..." entirely.
-- Prioritize ruthlessly. If everything is important, nothing is.
-- Don't soften criticism. Developers need honest feedback to ship great design.
-
-### Persist the Snapshot
-
-Once the report above is finalized, write it to `.impeccable/critique/` so the user can refer back, and so `$impeccable polish` can pick up the priority issues without a copy-paste.
-
-Skip this step if the Setup slug was null (vague or root-level target).
-
-1. **Write the body to a temp file** so you can pipe it to the helper. Use the full critique report (heuristic table, anti-patterns verdict, priority issues, persona red flags, minor observations, and questions), but stop before the "Ask the User" / "Recommended Actions" sections that come later.
-
- Codex: exclude Run Notes from the temp body file; Run Notes are final-chat only because persistence, trend read, and temp cleanup happen after the snapshot write.
-
-2. **Pass the structured metadata** through `IMPECCABLE_CRITIQUE_META` (JSON), then run the write command:
- ```bash
- IMPECCABLE_CRITIQUE_META='{"target":"<user phrasing>","total_score":<n>,"p0_count":<n>,"p1_count":<n>}' \
- node .agents/skills/impeccable/scripts/critique-storage.mjs write <slug> <body-file>
- ```
- The helper prints the absolute path it wrote.
-
-3. **Delete the temp body file** after the write attempt completes, whether the write succeeded or failed. If deletion fails, mention `temp-file cleanup failed: <reason>` briefly in the final output, but do not block the critique.
-
-4. **Read the trend** for context:
- ```bash
- node .agents/skills/impeccable/scripts/critique-storage.mjs trend <slug> 5
- ```
- This returns a JSON array of the last 5 frontmatter entries (including the one you just wrote).
-
-5. **Append a single line to the user-visible output**, after the report and before the questions:
-
- > **Trend for `<slug>` (last 5 runs): 24 → 28 → 32 → 29 → 32**
- > Wrote `.impeccable/critique/<filename>`.
-
- If this is the first run for the slug, the trend is just one score; say so: "First run for this target, no trend yet."
-
-This is fire-and-forget. Do not show the user the helper's JSON output; only the human-readable trend line and the written path. Failures here should not block the rest of the flow; print the error and move on.
-
-### Ask the User
-
-**After presenting findings**, use targeted questions based on what was actually found. STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. These answers will shape the action plan.
-
-Ask questions along these lines (adapt to the specific findings; do NOT ask generic questions):
-
-1. **Priority direction**: Based on the issues found, ask which category matters most to the user right now. For example: "I found problems with visual hierarchy, color usage, and information overload. Which area should we tackle first?" Offer the top 2-3 issue categories as options.
-
-2. **Design intent**: If the critique found a tonal mismatch, ask whether it was intentional. For example: "The interface feels clinical and corporate. Is that the intended tone, or should it feel warmer/bolder/more playful?" Offer 2-3 tonal directions as options based on what would fix the issues found.
-
-3. **Scope**: Ask how much the user wants to take on. For example: "I found N issues. Want to address everything, or focus on the top 3?" Offer scope options like "Top 3 only", "All issues", "Critical issues only".
-
-4. **Constraints** (optional; only ask if relevant): If the findings touch many areas, ask if anything is off-limits. For example: "Should any sections stay as-is?" This prevents the plan from touching things the user considers done.
-
-**Rules for questions**:
-- Every question must reference specific findings from the report. Never ask generic "who is your audience?" questions.
-- Keep it to 2-4 questions maximum. Respect the user's time.
-- Offer concrete options, not open-ended prompts.
-- If findings are straightforward (e.g., only 1-2 clear issues), skip questions and go directly to Recommended Actions.
-
-Codex final-question gate: The user-visible response must either include the targeted questions or explicitly say `Questions skipped: <reason>` because the findings were straightforward. Each question must include 2-3 concrete answer options tied to the actual critique findings. Do not end with only open-ended questions.
-
-### Recommended Actions
-
-**After receiving the user's answers**, present a prioritized action summary reflecting the user's priorities and scope from Ask the User.
-
-#### Action Summary
-
-List recommended commands in priority order, based on the user's answers:
-
-1. **`$command-name`**: Brief description of what to fix (specific context from critique findings)
-2. **`$command-name`**: Brief description (specific context)
-...
-
-**Rules for recommendations**:
-- Only recommend commands from: $impeccable adapt, $impeccable animate, $impeccable audit, $impeccable bolder, $impeccable clarify, $impeccable colorize, $impeccable critique, $impeccable delight, $impeccable distill, $impeccable document, $impeccable harden, $impeccable layout, $impeccable onboard, $impeccable optimize, $impeccable overdrive, $impeccable polish, $impeccable quieter, $impeccable shape, $impeccable typeset
-- Order by the user's stated priorities first, then by impact
-- Each item's description should carry enough context that the command knows what to focus on
-- Map each Priority Issue to the appropriate command
-- Skip commands that would address zero issues
-- If the user chose a limited scope, only include items within that scope
-- If the user marked areas as off-limits, exclude commands that would touch those areas
-- End with `$impeccable polish` as the final step if any fixes were recommended
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `$impeccable critique` after fixes to see your score improve.
@@ -1,302 +0,0 @@
-> **Additional context needed**: what's appropriate for the domain (playful vs professional vs quirky vs elegant).
-
-Find the moments where personality and unexpected polish would turn a functional interface into one users remember and tell other people about. Add only where the moment earns it; delight everywhere reads as noise.
-
----
-
-## Register
-
-Brand: delight can be distributed across copy voice, section transitions, discovery rewards, seasonal touches, personality across the whole surface.
-
-Product: delight at specific moments, not pages. Completion, first-time actions, error recovery, milestone crossings. Reliability and consistency carry the rest of the experience; delight pushed everywhere reads as noise.
-
----
-
-## Assess Delight Opportunities
-
-Identify where delight would enhance (not distract from) the experience:
-
-1. **Find natural delight moments**:
- - **Success states**: Completed actions (save, send, publish)
- - **Empty states**: First-time experiences, onboarding
- - **Loading states**: Waiting periods that could be entertaining
- - **Achievements**: Milestones, streaks, completions
- - **Interactions**: Hover states, clicks, drags
- - **Errors**: Softening frustrating moments
- - **Easter eggs**: Hidden discoveries for curious users
-
-2. **Understand the context**:
- - What's the brand personality? (Playful? Professional? Quirky? Elegant?)
- - Who's the audience? (Tech-savvy? Creative? Corporate?)
- - What's the emotional context? (Accomplishment? Exploration? Frustration?)
- - What's appropriate? (Banking app ≠ gaming app)
-
-3. **Define delight strategy**:
- - **Subtle sophistication**: Refined micro-interactions (luxury brands)
- - **Playful personality**: Whimsical illustrations and copy (consumer apps)
- - **Helpful surprises**: Anticipating needs before users ask (productivity tools)
- - **Sensory richness**: Satisfying sounds, smooth animations (creative tools)
-
-If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer.
-
-**CRITICAL**: Delight should enhance usability, never obscure it. If users notice the delight more than accomplishing their goal, you've gone too far.
-
-## Delight Principles
-
-Follow these guidelines:
-
-### Delight Amplifies, Never Blocks
-- Delight moments should be quick (< 1 second)
-- Never delay core functionality for delight
-- Make delight skippable or subtle
-- Respect user's time and task focus
-
-### Surprise and Discovery
-- Hide delightful details for users to discover
-- Reward exploration and curiosity
-- Don't announce every delight moment
-- Let users share discoveries with others
-
-### Appropriate to Context
-- Match delight to emotional moment (celebrate success, empathize with errors)
-- Respect the user's state (don't be playful during critical errors)
-- Match brand personality and audience expectations
-- Cultural sensitivity (what's delightful varies by culture)
-
-### Compound Over Time
-- Delight should remain fresh with repeated use
-- Vary responses (not same animation every time)
-- Reveal deeper layers with continued use
-- Build anticipation through patterns
-
-## Delight Techniques
-
-Add personality and joy through these methods:
-
-### Micro-interactions & Animation
-
-**Button delight**:
-```css
-/* Satisfying button press */
-.button {
- transition: transform 0.1s, box-shadow 0.1s;
-}
-.button:active {
- transform: translateY(2px);
- box-shadow: 0 2px 4px rgba(0,0,0,0.2);
-}
-
-/* Ripple effect on click */
-/* Smooth lift on hover */
-.button:hover {
- transform: translateY(-2px);
- transition: transform 0.2s cubic-bezier(0.25, 1, 0.5, 1); /* ease-out-quart */
-}
-```
-
-**Loading delight**:
-- Playful loading animations (not just spinners)
-- Personality in loading messages (write product-specific ones, not generic AI filler)
-- Progress indication with encouraging messages
-- Skeleton screens with subtle animations
-
-**Success animations**:
-- Checkmark draw animation
-- Confetti burst for major achievements
-- Gentle scale + fade for confirmation
-- Satisfying sound effects (subtle)
-
-**Hover surprises**:
-- Icons that animate on hover
-- Color shifts or glow effects
-- Tooltip reveals with personality
-- Cursor changes (custom cursors for branded experiences)
-
-### Personality in Copy
-
-**Playful error messages**:
-```
-"Error 404"
-"This page is playing hide and seek. (And winning)"
-
-"Connection failed"
-"Looks like the internet took a coffee break. Want to retry?"
-```
-
-**Encouraging empty states**:
-```
-"No projects"
-"Your canvas awaits. Create something amazing."
-
-"No messages"
-"Inbox zero! You're crushing it today."
-```
-
-**Playful labels & tooltips**:
-```
-"Delete"
-"Send to void" (for playful brand)
-
-"Help"
-"Rescue me" (tooltip)
-```
-
-**IMPORTANT**: Match copy personality to brand. Banks shouldn't be wacky, but they can be warm.
-
-### Illustrations & Visual Personality
-
-**Custom illustrations**:
-- Empty state illustrations (not stock icons)
-- Error state illustrations (friendly monsters, quirky characters)
-- Loading state illustrations (animated characters)
-- Success state illustrations (celebrations)
-
-**Icon personality**:
-- Custom icon set matching brand personality
-- Animated icons (subtle motion on hover/click)
-- Illustrative icons (more detailed than generic)
-- Consistent style across all icons
-
-**Background effects**:
-- Subtle particle effects
-- Gradient mesh backgrounds
-- Geometric patterns
-- Parallax depth
-- Time-of-day themes (morning vs night)
-
-### Satisfying Interactions
-
-**Drag and drop delight**:
-- Lift effect on drag (shadow, scale)
-- Snap animation when dropped
-- Satisfying placement sound
-- Undo toast ("Dropped in wrong place? [Undo]")
-
-**Toggle switches**:
-- Smooth slide with spring physics
-- Color transition
-- Haptic feedback on mobile
-- Optional sound effect
-
-**Progress & achievements**:
-- Streak counters with celebratory milestones
-- Progress bars that "celebrate" at 100%
-- Badge unlocks with animation
-- Playful stats ("You're on fire! 5 days in a row")
-
-**Form interactions**:
-- Input fields that animate on focus
-- Checkboxes with a satisfying scale pulse when checked
-- Success state that celebrates valid input
-- Auto-grow textareas
-
-### Sound Design
-
-**Subtle audio cues** (when appropriate):
-- Notification sounds (distinctive but not annoying)
-- Success sounds (satisfying "ding")
-- Error sounds (empathetic, not harsh)
-- Typing sounds for chat/messaging
-- Ambient background audio (very subtle)
-
-**IMPORTANT**:
-- Respect system sound settings
-- Provide mute option
-- Keep volumes quiet (subtle cues, not alarms)
-- Don't play on every interaction (sound fatigue is real)
-
-### Easter Eggs & Hidden Delights
-
-**Discovery rewards**:
-- Konami code unlocks special theme
-- Hidden keyboard shortcuts (Cmd+K for special features)
-- Hover reveals on logos or illustrations
-- Alt text jokes on images (for screen reader users too!)
-- Console messages for developers ("Like what you see? We're hiring!")
-
-**Seasonal touches**:
-- Holiday themes (subtle, tasteful)
-- Seasonal color shifts
-- Weather-based variations
-- Time-based changes (dark at night, light during day)
-
-**Contextual personality**:
-- Different messages based on time of day
-- Responses to specific user actions
-- Randomized variations (not same every time)
-- Progressive reveals with continued use
-
-### Loading & Waiting States
-
-**Make waiting engaging**:
-- Interesting loading messages that rotate
-- Progress bars with personality
-- Mini-games during long loads
-- Fun facts or tips while waiting
-- Countdown with encouraging messages
-
-```
-Loading messages: write ones specific to your product, not generic AI filler:
-- "Crunching your latest numbers..."
-- "Syncing with your team's changes..."
-- "Preparing your dashboard..."
-- "Checking for updates since yesterday..."
-```
-
-**WARNING**: Avoid cliched loading messages like "Herding pixels", "Teaching robots to dance", "Consulting the magic 8-ball", "Counting backwards from infinity". These are AI-slop copy, instantly recognizable as machine-generated. Write messages that are specific to what your product actually does.
-
-### Celebration Moments
-
-**Success celebrations**:
-- Confetti for major milestones
-- Animated checkmarks for completions
-- Progress bar celebrations at 100%
-- "Achievement unlocked" style notifications
-- Personalized messages ("You published your 10th article!")
-
-**Milestone recognition**:
-- First-time actions get special treatment
-- Streak tracking and celebration
-- Progress toward goals
-- Anniversary celebrations
-
-## Implementation Patterns
-
-**Animation libraries**:
-- Framer Motion (React)
-- GSAP (universal)
-- Lottie (After Effects animations)
-- Canvas confetti (party effects)
-
-**Sound libraries**:
-- Howler.js (audio management)
-- Use-sound (React hook)
-
-**Physics libraries**:
-- React Spring (spring physics)
-- Popmotion (animation primitives)
-
-**IMPORTANT**: File size matters. Compress images, optimize animations, lazy load delight features.
-
-**NEVER**:
-- Delay core functionality for delight
-- Force users through delightful moments (make skippable)
-- Use delight to hide poor UX
-- Overdo it (less is more)
-- Ignore accessibility (animate responsibly, provide alternatives)
-- Make every interaction delightful (special moments should be special)
-- Sacrifice performance for delight
-- Be inappropriate for context (read the room)
-
-## Verify Delight Quality
-
-Test that delight actually delights:
-
-- **User reactions**: Do users smile? Share screenshots?
-- **Doesn't annoy**: Still pleasant after 100th time?
-- **Doesn't block**: Can users opt out or skip?
-- **Performant**: No jank, no slowdown
-- **Appropriate**: Matches brand and context
-- **Accessible**: Works with reduced motion, screen readers
-
-When the moments feel earned, hand off to `$impeccable polish` for the final pass.
@@ -1,111 +0,0 @@
-Strip a design to its essence. Remove anything that doesn't earn its place: redundant elements, repeated information, decorative noise, cosmetic complexity.
-
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel complex or cluttered:
-
-1. **Identify complexity sources**:
- - **Too many elements**: Competing buttons, redundant information, visual clutter
- - **Excessive variation**: Too many colors, fonts, sizes, styles without purpose
- - **Information overload**: Everything visible at once, no progressive disclosure
- - **Visual noise**: Unnecessary borders, shadows, backgrounds, decorations
- - **Confusing hierarchy**: Unclear what matters most
- - **Feature creep**: Too many options, actions, or paths forward
-
-2. **Find the essence**:
- - What's the primary user goal? (There should be ONE)
- - What's actually necessary vs nice-to-have?
- - What can be removed, hidden, or combined?
- - What's the 20% that delivers 80% of value?
-
-If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer.
-
-**CRITICAL**: Simplicity is not about removing features. It's about removing obstacles between users and their goals. Every element should justify its existence.
-
-## Plan Simplification
-
-Create a ruthless editing strategy:
-
-- **Core purpose**: What's the ONE thing this should accomplish?
-- **Essential elements**: What's truly necessary to achieve that purpose?
-- **Progressive disclosure**: What can be hidden until needed?
-- **Consolidation opportunities**: What can be combined or integrated?
-
-**IMPORTANT**: Simplification is hard. It requires saying no to good ideas to make room for great execution. Be ruthless.
-
-## Simplify the Design
-
-Systematically remove complexity across these dimensions:
-
-### Information Architecture
-- **Reduce scope**: Remove secondary actions, optional features, redundant information
-- **Progressive disclosure**: Hide complexity behind clear entry points (accordions, modals, step-through flows)
-- **Combine related actions**: Merge similar buttons, consolidate forms, group related content
-- **Clear hierarchy**: ONE primary action, few secondary actions, everything else tertiary or hidden
-- **Remove redundancy**: If it's said elsewhere, don't repeat it here
-
-### Visual Simplification
-- **Reduce color palette**: Use 1-2 colors plus neutrals, not 5-7 colors
-- **Limit typography**: One font family, 3-4 sizes maximum, 2-3 weights
-- **Remove decorations**: Eliminate borders, shadows, backgrounds that don't serve hierarchy or function
-- **Flatten structure**: Reduce nesting, remove unnecessary containers; never nest cards inside cards
-- **Remove unnecessary cards**: Cards aren't needed for basic layout; use spacing and alignment instead
-- **Consistent spacing**: Use one spacing scale, remove arbitrary gaps
-
-### Layout Simplification
-- **Linear flow**: Replace complex grids with simple vertical flow where possible
-- **Remove sidebars**: Move secondary content inline or hide it
-- **Full-width**: Use available space generously instead of complex multi-column layouts
-- **Consistent alignment**: Pick left or center, stick with it
-- **Generous white space**: Let content breathe, don't pack everything tight
-
-### Interaction Simplification
-- **Reduce choices**: Fewer buttons, fewer options, clearer path forward (paradox of choice is real)
-- **Smart defaults**: Make common choices automatic, only ask when necessary
-- **Inline actions**: Replace modal flows with inline editing where possible
-- **Remove steps**: Can signup be one step instead of three? Can checkout be simplified?
-- **Clear CTAs**: ONE obvious next step, not five competing actions
-
-### Content Simplification
-- **Shorter copy**: Cut every sentence in half, then do it again
-- **Active voice**: "Save changes" not "Changes will be saved"
-- **Remove jargon**: Plain language always wins
-- **Scannable structure**: Short paragraphs, bullet points, clear headings
-- **Essential information only**: Remove marketing fluff, legalese, hedging
-- **Remove redundant copy**: No headers restating intros, no repeated explanations, say it once
-
-### Code Simplification
-- **Remove unused code**: Dead CSS, unused components, orphaned files
-- **Flatten component trees**: Reduce nesting depth
-- **Consolidate styles**: Merge similar styles, use utilities consistently
-- **Reduce variants**: Does that component need 12 variations, or can 3 cover 90% of cases?
-
-**NEVER**:
-- Remove necessary functionality (simplicity ≠ feature-less)
-- Sacrifice accessibility for simplicity (clear labels and ARIA still required)
-- Make things so simple they're unclear (mystery ≠ minimalism)
-- Remove information users need to make decisions
-- Eliminate hierarchy completely (some things should stand out)
-- Oversimplify complex domains (match complexity to actual task complexity)
-
-## Verify Simplification
-
-Ensure simplification improves usability:
-
-- **Faster task completion**: Can users accomplish goals more quickly?
-- **Reduced cognitive load**: Is it easier to understand what to do?
-- **Still complete**: Are all necessary features still accessible?
-- **Clearer hierarchy**: Is it obvious what matters most?
-- **Better performance**: Does simpler design load faster?
-
-## Document Removed Complexity
-
-If you removed features or options:
-- Document why they were removed
-- Consider if they need alternative access points
-- Note any user feedback to monitor
-
-When the cuts feel right, hand off to `$impeccable polish` for the final pass. As Antoine de Saint-Exupéry put it: "Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away."
@@ -1,427 +0,0 @@
-Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
-
-DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
-
-## The frontmatter: token schema
-
-The YAML frontmatter is the machine-readable layer. It's what Stitch's linter validates and what the live panel renders tiles from. Keep it tight; every entry should correspond to a token the project actually uses.
-
-```yaml
----
-name: <project title>
-description: <one-line tagline>
-colors:
- primary: "#b8422e"
- neutral-bg: "#faf7f2"
- # ...one entry per extracted color; key = descriptive slug
-typography:
- display:
- fontFamily: "Cormorant Garamond, Georgia, serif"
- fontSize: "clamp(2.5rem, 7vw, 4.5rem)"
- fontWeight: 300
- lineHeight: 1
- letterSpacing: "normal"
- body:
- # ...
-rounded:
- sm: "4px"
- md: "8px"
-spacing:
- sm: "8px"
- md: "16px"
-components:
- button-primary:
- backgroundColor: "{colors.primary}"
- textColor: "{colors.neutral-bg}"
- rounded: "{rounded.sm}"
- padding: "16px 48px"
- button-primary-hover:
- backgroundColor: "{colors.primary-deep}"
----
-```
-
-Rules that matter:
-
-- **Token refs** use `{path.to.token}` (e.g. `{colors.primary}`, `{rounded.md}`). Components may reference primitives; primitives may not reference each other.
-- **Stitch validates colors as hex sRGB only** (`#RGB` / `#RGBA` / `#RRGGBB` / `#RRGGBBAA`); OKLCH/HSL/P3 trigger a linter warning, not a hard error. YAML accepts the string either way and our own parser is format-agnostic. Choose based on project posture: (a) if the project has an "OKLCH-only" doctrine or uses Display-P3 values that don't round-trip through sRGB, put OKLCH directly in the frontmatter and accept the Stitch linter warning; (b) if the project wants strict Stitch compliance or plans to use their Tailwind/DTCG export pipeline, put hex in the frontmatter and keep OKLCH in prose as the canonical reference. Never split the source of truth without explicit reason.
-- **Component sub-tokens** are limited to 8 props: `backgroundColor`, `textColor`, `typography`, `rounded`, `padding`, `size`, `height`, `width`. Shadows, motion, focus rings, backdrop-filter: none of those fit. Carry them in the sidecar (Step 4b).
-- **Scale keys are open-ended.** Use whatever names the project already uses (`warm-ash-cream`, `surface-container-low`). Don't rename to Material defaults.
-- **Variants are naming convention, not schema.** `button-primary` / `button-primary-hover` / `button-primary-active` as sibling keys.
-
-## The markdown body: six sections (exact order)
-
-1. `## Overview`
-2. `## Colors`
-3. `## Typography`
-4. `## Elevation`
-5. `## Components`
-6. `## Do's and Don'ts`
-
-Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] Palette` (Stitch's own outputs do this), but the literal word in each header (Overview, Colors, Typography, Elevation, Components, Do's and Don'ts) must be present. Do NOT add extra top-level sections (Layout Principles, Responsive Behavior, Motion, Agent Prompt Guide). Fold that content into the six spec sections where it naturally belongs.
-
-## When to run
-
-- The user just ran `$impeccable teach` and needs the visual side documented.
-- The skill noticed no `DESIGN.md` exists and nudged the user to create one.
-- An existing `DESIGN.md` is stale (the design has drifted).
-- Before a large redesign, to capture the current state as a reference.
-
-If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user the existing file and STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. whether to refresh, overwrite, or merge.
-
-## Two paths
-
-- **Scan mode** (default): the project has design tokens, components, or rendered output. Extract, then confirm descriptive language. Use when there's code to analyze.
-- **Seed mode**: the project is pre-implementation (fresh teach, nothing built yet). Interview for five high-level answers, write a minimal DESIGN.md marked `<!-- SEED -->`. Re-run in scan mode once there's code.
-
-Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode; don't silently switch. `$impeccable document --seed` forces seed mode regardless of code presence.
-
-## Scan mode (approach C: auto-extract, then confirm descriptive language)
-
-### Step 1: Find the design assets
-
-Search the codebase in priority order:
-
-1. **CSS custom properties**: grep for `--color-`, `--font-`, `--spacing-`, `--radius-`, `--shadow-`, `--ease-`, `--duration-` declarations in CSS files (usually `src/styles/`, `public/css/`, `app/globals.css`, etc.). Record name, value, and the file it's defined in.
-2. **Tailwind config**: if `tailwind.config.{js,ts,mjs}` exists, read the `theme.extend` block for colors, fontFamily, spacing, borderRadius, boxShadow.
-3. **CSS-in-JS theme files**: styled-components, emotion, vanilla-extract, stitches; look for `theme.ts`, `tokens.ts`, or equivalent.
-4. **Design token files**: `tokens.json`, `design-tokens.json`, Style Dictionary output, W3C token community group format.
-5. **Component library**: scan the main button, card, input, navigation, dialog components. Note their variant APIs and default styles.
-6. **Global stylesheet**: the root CSS file usually has the base typography and color assignments.
-7. **Visible rendered output**: if browser automation tools are available, load the live site and sample computed styles from key elements (body, h1, a, button, .card). This catches values that tokens miss.
-
-### Step 2: Auto-extract what can be auto-extracted
-
-Build a structured draft from the discovered tokens. For each token class:
-
-- **Colors**: Group into Primary / Secondary / Tertiary / Neutral (the Material-derived roles Stitch uses). If the project only has one accent, express it as Primary + Neutral; omit Secondary and Tertiary rather than inventing them.
-- **Typography**: Map observed sizes and weights to the Material hierarchy (display / headline / title / body / label). Note font-family stacks and the scale ratio.
-- **Elevation**: Catalogue the shadow vocabulary. If the project is flat and uses tonal layering instead, that's a valid answer; state it explicitly.
-- **Components**: For each common component (button, card, input, chip, list item, tooltip, nav), extract shape (radius), color assignment, hover/focus treatment, internal padding.
-- **Spacing + layout**: Fold into Overview or relevant Components. The spec does NOT have a Layout section.
-
-### Step 2b: Stage the frontmatter
-
-From the auto-extracted tokens, draft the YAML frontmatter now (you'll write it at the top of DESIGN.md in Step 4). This is the machine-readable layer: what the live panel and Stitch's linter consume.
-
-- **Colors**: one entry per extracted color. Key = descriptive slug (`warm-ash-cream`, `editorial-magenta`, not `blue-800`). Value = whichever format the project treats as canonical (OKLCH or hex; see the frontmatter rules above). Don't split the source of truth: one format in the frontmatter, don't redefine the same token in prose with a different value.
-- **Typography**: one entry per role (`display`, `headline`, `title`, `body`, `label`). Typography is an object; include only the props that are real for the project (`fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `fontFeature`, `fontVariation`).
-- **Rounded / Spacing**: whatever scale steps the project actually uses, keyed by whatever scale name the project uses (`sm` / `md` / `lg`, or `surface-sm`, or numeric steps).
-- **Components**: one entry per variant (`button-primary`, `button-primary-hover`, `button-ghost`). Reference primitives via `{colors.X}`, `{rounded.Y}`. If a variant needs a property Stitch's 8-prop set doesn't cover (shadow, focus ring, backdrop-filter), carry the full snippet in the sidecar instead.
-
-Skip anything the project doesn't have. Empty scale keys or fabricated tokens pollute the spec.
-
-### Step 3: Ask the user for qualitative language
-
-The following require creative input that cannot be auto-extracted. Group them into one `AskUserQuestion` interaction:
-
-- **Creative North Star**: a single named metaphor for the whole system ("The Editorial Sanctuary", "The Golden State Curator", "The Lab Notebook"). Offer 2-3 options that honor PRODUCT.md's brand personality.
-- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, anti-references (what the system should not feel like).
-- **Color character** (for auto-extracted colors): descriptive names ("Deep Muted Teal-Navy", not "blue-800"). Suggest 2-3 options per key color based on hue/saturation.
-- **Elevation philosophy**: flat/layered/lifted. If shadows exist, is their role ambient or structural?
-- **Component philosophy**: the feel of buttons, cards, inputs in one phrase ("tactile and confident" vs. "refined and restrained").
-
-Quote a line from PRODUCT.md when possible so the user sees their own strategic language carry forward.
-
-### Step 4: Write DESIGN.md
-
-The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the structure below. Headers must match character-for-character. Optional evocative subtitles (e.g. `## 2. Colors: The Coastal Palette`) are allowed.
-
-```markdown
----
-name: [Project Title]
-description: [one-line tagline]
-colors:
- # ... staged frontmatter from Step 2b
----
-
-# Design System: [Project Title]
-
-## 1. Overview
-
-**Creative North Star: "[Named metaphor in quotes]"**
-
-[2-3 paragraph holistic description: personality, density, aesthetic philosophy. Start from the North Star and work outward. State what this system explicitly rejects (pulled from PRODUCT.md's anti-references). End with a short **Key Characteristics:** bullet list.]
-
-## 2. Colors
-
-[Describe the palette character in one sentence.]
-
-### Primary
-- **[Descriptive Name]** (#HEX / oklch(...)): [Where and why this color is used. Be specific about context, not just role.]
-
-### Secondary (optional; omit if the project has only one accent)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Tertiary (optional)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Neutral
-- **[Descriptive Name]** (#HEX): [Text / background / border / divider role.]
-- [...]
-
-### Named Rules (optional, powerful)
-**The [Rule Name] Rule.** [Short, forceful prohibition or doctrine, e.g. "The One Voice Rule. The primary accent is used on ≤10% of any given screen. Its rarity is the point."]
-
-## 3. Typography
-
-**Display Font:** [Family] (with [fallback])
-**Body Font:** [Family] (with [fallback])
-**Label/Mono Font:** [Family, if distinct]
-
-**Character:** [1-2 sentence personality description of the pairing.]
-
-### Hierarchy
-- **Display** ([weight], [size/clamp], [line-height]): [Purpose; where it appears.]
-- **Headline** ([weight], [size], [line-height]): [Purpose.]
-- **Title** ([weight], [size], [line-height]): [Purpose.]
-- **Body** ([weight], [size], [line-height]): [Purpose. Include max line length like 65–75ch if relevant.]
-- **Label** ([weight], [size], [letter-spacing], [case if uppercase]): [Purpose.]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [Short doctrine about type use.]
-
-## 4. Elevation
-
-[One paragraph: does this system use shadows, tonal layering, or a hybrid? If "no shadows", say so explicitly and describe how depth is conveyed instead.]
-
-### Shadow Vocabulary (if applicable)
-- **[Role name]** (`box-shadow: [exact value]`): [When to use it.]
-- [...]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [e.g. "The Flat-By-Default Rule. Surfaces are flat at rest. Shadows appear only as a response to state (hover, elevation, focus)."]
-
-## 5. Components
-
-For each component, lead with a short character line, then specify shape, color assignment, states, and any distinctive behavior.
-
-### Buttons
-- **Shape:** [radius described, exact value in parens]
-- **Primary:** [color assignment + padding, in semantic + exact terms]
-- **Hover / Focus:** [transitions, treatments]
-- **Secondary / Ghost / Tertiary (if applicable):** [brief description]
-
-### Chips (if used)
-- **Style:** [background, text color, border treatment]
-- **State:** [selected / unselected, filter / action variants]
-
-### Cards / Containers
-- **Corner Style:** [radius]
-- **Background:** [colors used]
-- **Shadow Strategy:** [reference Elevation section]
-- **Border:** [if any]
-- **Internal Padding:** [scale]
-
-### Inputs / Fields
-- **Style:** [stroke, background, radius]
-- **Focus:** [treatment, e.g. glow, border shift, etc.]
-- **Error / Disabled:** [if applicable]
-
-### Navigation
-- **Style, typography, default/hover/active states, mobile treatment.**
-
-### [Signature Component] (optional; if the project has a distinctive custom component worth documenting)
-[Description.]
-
-## 6. Do's and Don'ts
-
-Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: include exact colors, pixel values, and named anti-patterns the user mentioned in PRODUCT.md. **Every anti-reference in PRODUCT.md should show up here as a "Don't" with the same language**, so the visual spec carries the strategic line through. Quote PRODUCT.md directly where possible: if PRODUCT.md says *"avoid dark mode with purple gradients, neon accents, glassmorphism"*, the Don'ts here should repeat that by name.
-
-### Do:
-- **Do** [specific prescription with exact values / named rule].
-- **Do** [...]
-
-### Don't:
-- **Don't** [specific prohibition, e.g. "use border-left greater than 1px as a colored stripe"].
-- **Don't** [...]
-- **Don't** [...]
-```
-
-### Step 4b: Write .impeccable/design.json sidecar (extensions only)
-
-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.
-
-Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.
-
-#### Schema
-
-```json
-{
- "schemaVersion": 2,
- "generatedAt": "ISO-8601 string",
- "title": "Design System: [Project Title]",
- "extensions": {
- "colorMeta": {
- "primary": { "role": "primary", "displayName": "Editorial Magenta", "canonical": "oklch(60% 0.25 350)", "tonalRamp": ["...", "...", "..."] },
- "warm-ash-cream": { "role": "neutral", "displayName": "Warm Ash Cream", "canonical": "oklch(96% 0.005 350)", "tonalRamp": ["...", "...", "..."] }
- },
- "typographyMeta": {
- "display": { "displayName": "Display", "purpose": "Hero headlines only." }
- },
- "shadows": [
- { "name": "ambient-low", "value": "0 4px 24px rgba(0,0,0,0.12)", "purpose": "Diffuse hover glow under accent elements." }
- ],
- "motion": [
- { "name": "ease-standard", "value": "cubic-bezier(0.4, 0, 0.2, 1)", "purpose": "Default easing for state transitions." }
- ],
- "breakpoints": [
- { "name": "sm", "value": "640px" }
- ]
- },
- "components": [
- {
- "name": "Primary Button",
- "kind": "button | input | nav | chip | card | custom",
- "refersTo": "button-primary",
- "description": "One-line what and when.",
- "html": "<button class=\"ds-btn-primary\">GET STARTED</button>",
- "css": ".ds-btn-primary { background: #191c1d; color: #fff; padding: 16px 48px; letter-spacing: 0.05em; text-transform: uppercase; font-weight: 500; border: none; border-radius: 0; transition: background 0.2s, transform 0.2s; } .ds-btn-primary:hover { background: oklch(60% 0.25 350); transform: translateY(-2px); }"
- }
- ],
- "narrative": {
- "northStar": "The Editorial Sanctuary",
- "overview": "2-3 paragraphs of the philosophy, pulled from DESIGN.md Overview section.",
- "keyCharacteristics": ["...", "..."],
- "rules": [{ "name": "The One Voice Rule", "body": "...", "section": "colors|typography|elevation" }],
- "dos": ["Do use ..."],
- "donts": ["Don't use ..."]
- }
-}
-```
-
-**What changed from schemaVersion 1.** The old sidecar carried token primitive arrays (`tokens.colors[]`, `tokens.typography[]`, etc.). Those values now live in the frontmatter. The sidecar only carries metadata that can't live in the frontmatter (tonal ramps, canonical OKLCH when the hex is an approximation, display names, role hints), keyed by the frontmatter token name (`colorMeta.<token-name>`, `typographyMeta.<token-name>`). Components still carry full HTML/CSS because Stitch's 8-prop set can't hold them.
-
-#### Component translation rules
-
-The `html` and `css` fields must be **self-contained, drop-in snippets** that render correctly when injected into a shadow DOM. The panel applies them directly: no post-processing, no framework runtime.
-
-1. **Tailwind expansion.** If the source uses Tailwind (className="bg-primary text-white rounded-lg px-6 py-3"), expand every utility to literal CSS properties in the `css` string. Do **not** reference Tailwind classes; do **not** assume a Tailwind CSS bundle is loaded. Each component is self-contained.
-2. **Token resolution.** If the project exposes tokens as CSS custom properties on `:root` (e.g. `--color-primary`, `--radius-md`), reference them via `var(--color-primary)`; they inherit through the shadow DOM and stay live-bound. If tokens live only in JS theme objects (styled-components, CSS-in-JS), resolve to literal values at generation time.
-3. **Icons.** Inline as SVG. Do not reference Lucide/Heroicons packages, icon fonts, or `<img src="...">`. A typical icon is 16-24px; copy the SVG path data directly.
-4. **States.** Include `:hover`, `:focus-visible`, and (if meaningful) `:active` rules inline. A static default-only snapshot makes the panel feel dead. Hover + focus rules in the CSS make it feel alive.
-5. **Reset bloat.** Extract only the component's *distinctive* CSS (background, color, padding, border-radius, typography, transition). Skip universal resets (`box-sizing: border-box`, `line-height: inherit`, `-webkit-font-smoothing`). The panel already has a neutral canvas; don't re-ship resets.
-6. **Scoped class names.** Prefix every class with `ds-` (e.g. `ds-btn-primary`, `ds-input-search`) so component CSS doesn't collide with other components' CSS in the same shadow DOM.
-
-#### What to include
-
-Aim for a tight set of **5-10 components** that best represent the visual system:
-
-- **Canonical primitives (always include if the project has them):** button (each variant as a separate component entry), input/text field, navigation, chip/tag, card.
-- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.
-- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.
-
-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.
-
-#### Tonal ramps
-
-For each color token, generate an 8-step `tonalRamp` array: dark to light, same hue and chroma, stepped lightness from ~15% to ~95%. The panel renders this as a strip under the swatch. If the project already defines a tonal scale (Material `surface-container-low` family, Tailwind-style `blue-50..blue-900`), use those values. Otherwise synthesize in OKLCH.
-
-#### Narrative mapping
-
-Pull directly from the DESIGN.md you just wrote:
-
-- `narrative.northStar` → the `**Creative North Star: "..."**` line from Overview
-- `narrative.overview` → the philosophy paragraphs from Overview
-- `narrative.keyCharacteristics` → the bulleted `**Key Characteristics:**` list
-- `narrative.rules` → every `**The [Name] Rule.** [body]` across all sections, tagged with `section`
-- `narrative.dos` / `narrative.donts` → the bullet lists from Do's and Don'ts verbatim
-
-Do not reword. The panel shows these as secondary collapsible context; the same voice that's in the Markdown carries through.
-
-### Step 5: Confirm, refine, and refresh session cache
-
-1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).
-2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.
-3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"
-4. **Refresh the session cache.** Run `node .agents/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.
-
-## Seed mode
-
-For projects with no visual system to extract yet. Produces a minimal scaffold, not a full spec.
-
-### Step 1: Confirm seed mode
-
-Before interviewing: "There's no existing visual system to scan. I'll ask five quick questions to seed a starter DESIGN.md. You can re-run `$impeccable document` once there's code, to capture the real tokens and components. OK?"
-
-If the user prefers to skip, stop. No file.
-
-### Step 2: Five questions
-
-Group into one `AskUserQuestion` interaction. Options must be concrete.
-
-1. **Color strategy.** Pick one:
- - Restrained: tinted neutrals + one accent ≤10%
- - Committed: one saturated color carries 30–60% of the surface
- - Full palette: 3–4 named color roles, each deliberate
- - Drenched: the surface IS the color
-
- Then: one hue family or anchor reference ("deep teal", "mustard", "Klim #ff4500 orange").
-
-2. **Typography direction.** Pick one (specific fonts come later):
- - Serif display + sans body
- - Single sans (warm / technical / geometric / humanist; pick a feel)
- - Display + mono
- - Mono-forward
- - Editorial script + sans
-
-3. **Motion energy.** Pick one:
- - Restrained: state changes only
- - Responsive: feedback + transitions, no choreography
- - Choreographed: orchestrated entrances, scroll-driven sequences
-
-4. **Three named references.** Brands, products, printed objects. Not adjectives.
-
-5. **One anti-reference.** What it should NOT feel like. Also named.
-
-### Step 3: Write seed DESIGN.md
-
-Use the six-section spec from Scan mode. Populate what the interview answers; leave the rest as honest placeholders. The seed is a scaffold, not a fabricated spec.
-
-Lead the file with:
-
-```markdown
-<!-- SEED: re-run $impeccable document once there's code to capture the actual tokens and components. -->
-```
-
-Per-section guidance in seed mode:
-
-- **Overview**: Creative North Star and philosophy phrased from the answers (color strategy + motion energy + references). Reference the user's anti-reference directly.
-- **Colors**: Color strategy as a Named Rule (e.g. *"The Drenched Rule. The surface IS the color."*). Hue family or anchor reference. No hex values; mark as `[to be resolved during implementation]`.
-- **Typography**: the direction the user picked (e.g. "Serif display + sans body"). No font names yet: `[font pairing to be chosen at implementation]`.
-- **Elevation**: inferred from motion energy. Restrained/Responsive → flat by default; Choreographed → layered. One sentence.
-- **Components**: omit entirely; no components exist yet.
-- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.
-
-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.
-
-### Step 4: Confirm and refresh session cache
-
-1. Show the seed DESIGN.md. Call out that it is a seed (the marker is the literal commitment).
-2. Tell the user: "Re-run `$impeccable document` once you have some code. That pass will extract real tokens and generate the sidecar."
-3. Run `node .agents/skills/impeccable/scripts/load-context.mjs` once so the seed lands in conversation for the rest of the session.
-
-## Style guidelines
-
-- **Frontmatter first, prose second.** Tokens go in the YAML frontmatter; prose contextualizes them. Don't redefine a token value in two places; the frontmatter is normative.
-- **Cite PRODUCT.md anti-references by name** in the Do's and Don'ts section. If PRODUCT.md lists "SaaS landing-page clichés" or "generic AI tool marketing" as anti-references, the DESIGN.md Don'ts should repeat those phrases verbatim so the visual spec enforces the strategic line.
-- **Match the spec, don't invent new sections.** The six section names are fixed. If you have Layout/Motion/Responsive content to document, fold it into Overview (philosophy-level rules) or Components (per-component behavior).
-- **Descriptive > technical**: "Gently curved edges (8px radius)" > "rounded-lg". Include the technical value in parens, lead with the description.
-- **Functional > decorative**: for each token, explain WHERE and WHY it's used, not just WHAT it is.
-- **Exact values in parens**: hex codes, px/rem values, font weights; always the number in parens alongside the description.
-- **Use Named Rules**: `**The [Name] Rule.** [short doctrine]`. These are memorable, citable, and much stickier for AI consumers than bullet lists. Stitch's own outputs use them heavily ("The No-Line Rule", "The Ghost Border Fallback"). Aim for 1-3 per section.
-- **Be forceful**. The voice of a design director. "Prohibited", "forbidden", "never", "always", not "consider", "might", "prefer". Match PRODUCT.md's tone.
-- **Concrete anti-pattern tests**. Stitch writes things like *"If it looks like a 2014 app, the shadow is too dark and the blur is too small."* A one-sentence audit test beats a paragraph of principle.
-- **Reference PRODUCT.md**. The anti-references section of PRODUCT.md should directly inform the Do's and Don'ts section here. Quote or paraphrase.
-- **Group colors by role**, not by hex-order or hue-order. Primary / Secondary / Tertiary / Neutral is the spec ordering.
-
-## Pitfalls
-
-- Don't paste raw CSS class names. Translate to descriptive language.
-- Don't extract every token. Stop at what's actually reused; one-offs pollute the system.
-- Don't invent components that don't exist. If the project only has buttons and cards, only document those.
-- Don't overwrite an existing DESIGN.md without asking.
-- Don't duplicate content from PRODUCT.md. DESIGN.md is strictly visual.
-- Don't add a "Layout Principles" or "Motion" or "Responsive Behavior" top-level section. The spec has six, not nine. Fold that content where it belongs.
-- Don't rename sections even slightly. "Colors" not "Color Palette & Roles". "Typography" not "Typography Rules". Tooling parsing depends on exact headers.
-- Don't duplicate token values between frontmatter and prose. If a color is in `colors.primary` as hex, the prose can name it and describe its role but should not reassert a different hex. The frontmatter is normative.
-- Don't invent frontmatter token groups outside Stitch's schema (no `motion:`, `breakpoints:`, `shadows:` at the top level). Stitch's Zod schema only accepts `colors`, `typography`, `rounded`, `spacing`, `components`. Anything else belongs in the sidecar's `extensions`.
@@ -1,69 +0,0 @@
-# Extract Flow
-
-Identify reusable patterns, components, and design tokens, then extract and consolidate them into the design system for systematic reuse.
-
-## Step 1: Discover the Design System
-
-Find the design system, component library, or shared UI directory. Understand its structure: component organization, naming conventions, design token structure, import/export conventions.
-
-**CRITICAL**: If no design system exists, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. before creating one. Understand the preferred location and structure first.
-
-## Step 2: Identify Patterns
-
-Look for extraction opportunities in the target area:
-
-- **Repeated components**: Similar UI patterns used 3+ times (buttons, cards, inputs)
-- **Hard-coded values**: Colors, spacing, typography, shadows that should be tokens
-- **Inconsistent variations**: Multiple implementations of the same concept
-- **Composition patterns**: Layout or interaction patterns that repeat (form rows, toolbar groups, empty states)
-- **Type styles**: Repeated font-size + weight + line-height combinations
-- **Animation patterns**: Repeated easing, duration, or keyframe combinations
-
-Assess value: only extract things used 3+ times with the same intent. Premature abstraction is worse than duplication.
-
-## Step 3: Plan Extraction
-
-Create a systematic plan:
-
-- **Components to extract**: Which UI elements become reusable components?
-- **Tokens to create**: Which hard-coded values become design tokens?
-- **Variants to support**: What variations does each component need?
-- **Naming conventions**: Component names, token names, prop names that match existing patterns
-- **Migration path**: How to refactor existing uses to consume the new shared versions
-
-**IMPORTANT**: Design systems grow incrementally. Extract what is clearly reusable now, not everything that might someday be reusable.
-
-## Step 4: Extract & Enrich
-
-Build improved, reusable versions:
-
-- **Components**: Clear props API with sensible defaults, proper variants for different use cases, accessibility built in (ARIA, keyboard navigation, focus management), documentation and usage examples
-- **Design tokens**: Clear naming (primitive vs semantic), proper hierarchy and organization, documentation of when to use each token
-- **Patterns**: When to use this pattern, code examples, variations and combinations
-
-## Step 5: Migrate
-
-Replace existing uses with the new shared versions:
-
-- **Find all instances**: Search for the patterns you extracted
-- **Replace systematically**: Update each use to consume the shared version
-- **Test thoroughly**: Ensure visual and functional parity
-- **Delete dead code**: Remove the old implementations
-
-## Step 6: Document
-
-Update design system documentation:
-
-- Add new components to the component library
-- Document token usage and values
-- Add examples and guidelines
-- Update any Storybook or component catalog
-
-**NEVER**:
-- Extract one-off, context-specific implementations without generalization
-- Create components so generic they are useless
-- Extract without considering existing design system conventions
-- Skip proper TypeScript types or prop documentation
-- Create tokens for every single value (tokens should have semantic meaning)
-- Extract things that differ in intent (two buttons that look similar but serve different purposes should stay separate)
-
@@ -1,347 +0,0 @@
-Designs that only work with perfect data aren't production-ready. Harden the interface against the inputs, errors, languages, and network conditions that real users will throw at it.
-
-## Assess Hardening Needs
-
-Identify weaknesses and edge cases:
-
-1. **Test with extreme inputs**:
- - Very long text (names, descriptions, titles)
- - Very short text (empty, single character)
- - Special characters (emoji, RTL text, accents)
- - Large numbers (millions, billions)
- - Many items (1000+ list items, 50+ options)
- - No data (empty states)
-
-2. **Test error scenarios**:
- - Network failures (offline, slow, timeout)
- - API errors (400, 401, 403, 404, 500)
- - Validation errors
- - Permission errors
- - Rate limiting
- - Concurrent operations
-
-3. **Test internationalization**:
- - Long translations (German is often 30% longer than English)
- - RTL languages (Arabic, Hebrew)
- - Character sets (Chinese, Japanese, Korean, emoji)
- - Date/time formats
- - Number formats (1,000 vs 1.000)
- - Currency symbols
-
-**CRITICAL**: Designs that only work with perfect data aren't production-ready. Harden against reality.
-
-## Hardening Dimensions
-
-Systematically improve resilience:
-
-### Text Overflow & Wrapping
-
-**Long text handling**:
-```css
-/* Single line with ellipsis */
-.truncate {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* Multi-line with clamp */
-.line-clamp {
- display: -webkit-box;
- -webkit-line-clamp: 3;
- -webkit-box-orient: vertical;
- overflow: hidden;
-}
-
-/* Allow wrapping */
-.wrap {
- word-wrap: break-word;
- overflow-wrap: break-word;
- hyphens: auto;
-}
-```
-
-**Flex/Grid overflow**:
-```css
-/* Prevent flex items from overflowing */
-.flex-item {
- min-width: 0; /* Allow shrinking below content size */
- overflow: hidden;
-}
-
-/* Prevent grid items from overflowing */
-.grid-item {
- min-width: 0;
- min-height: 0;
-}
-```
-
-**Responsive text sizing**:
-- Use `clamp()` for fluid typography
-- Set minimum readable sizes (14px on mobile)
-- Test text scaling (zoom to 200%)
-- Ensure containers expand with text
-
-### Internationalization (i18n)
-
-**Text expansion**:
-- Add 30-40% space budget for translations
-- Use flexbox/grid that adapts to content
-- Test with longest language (usually German)
-- Avoid fixed widths on text containers
-
-```jsx
-// ❌ Bad: Assumes short English text
-<button className="w-24">Submit</button>
-
-// ✅ Good: Adapts to content
-<button className="px-4 py-2">Submit</button>
-```
-
-**RTL (Right-to-Left) support**:
-```css
-/* Use logical properties */
-margin-inline-start: 1rem; /* Not margin-left */
-padding-inline: 1rem; /* Not padding-left/right */
-border-inline-end: 1px solid; /* Not border-right */
-
-/* Or use dir attribute */
-[dir="rtl"] .arrow { transform: scaleX(-1); }
-```
-
-**Character set support**:
-- Use UTF-8 encoding everywhere
-- Test with Chinese/Japanese/Korean (CJK) characters
-- Test with emoji (they can be 2-4 bytes)
-- Handle different scripts (Latin, Cyrillic, Arabic, etc.)
-
-**Date/Time formatting**:
-```javascript
-// ✅ Use Intl API for proper formatting
-new Intl.DateTimeFormat('en-US').format(date); // 1/15/2024
-new Intl.DateTimeFormat('de-DE').format(date); // 15.1.2024
-
-new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: 'USD'
-}).format(1234.56); // $1,234.56
-```
-
-**Pluralization**:
-```javascript
-// ❌ Bad: Assumes English pluralization
-`${count} item${count !== 1 ? 's' : ''}`
-
-// ✅ Good: Use proper i18n library
-t('items', { count }) // Handles complex plural rules
-```
-
-### Error Handling
-
-**Network errors**:
-- Show clear error messages
-- Provide retry button
-- Explain what happened
-- Offer offline mode (if applicable)
-- Handle timeout scenarios
-
-```jsx
-// Error states with recovery
-{error && (
- <ErrorMessage>
- <p>Failed to load data. {error.message}</p>
- <button onClick={retry}>Try again</button>
- </ErrorMessage>
-)}
-```
-
-**Form validation errors**:
-- Inline errors near fields
-- Clear, specific messages
-- Suggest corrections
-- Don't block submission unnecessarily
-- Preserve user input on error
-
-**API errors**:
-- Handle each status code appropriately
- - 400: Show validation errors
- - 401: Redirect to login
- - 403: Show permission error
- - 404: Show not found state
- - 429: Show rate limit message
- - 500: Show generic error, offer support
-
-**Graceful degradation**:
-- Core functionality works without JavaScript
-- Images have alt text
-- Progressive enhancement
-- Fallbacks for unsupported features
-
-### Edge Cases & Boundary Conditions
-
-**Empty states**:
-- No items in list
-- No search results
-- No notifications
-- No data to display
-- Provide clear next action
-
-**Loading states**:
-- Initial load
-- Pagination load
-- Refresh
-- Show what's loading ("Loading your projects...")
-- Time estimates for long operations
-
-**Large datasets**:
-- Pagination or virtual scrolling
-- Search/filter capabilities
-- Performance optimization
-- Don't load all 10,000 items at once
-
-**Concurrent operations**:
-- Prevent double-submission (disable button while loading)
-- Handle race conditions
-- Optimistic updates with rollback
-- Conflict resolution
-
-**Permission states**:
-- No permission to view
-- No permission to edit
-- Read-only mode
-- Clear explanation of why
-
-**Browser compatibility**:
-- Polyfills for modern features
-- Fallbacks for unsupported CSS
-- Feature detection (not browser detection)
-- Test in target browsers
-
-### Input Validation & Sanitization
-
-**Client-side validation**:
-- Required fields
-- Format validation (email, phone, URL)
-- Length limits
-- Pattern matching
-- Custom validation rules
-
-**Server-side validation** (always):
-- Never trust client-side only
-- Validate and sanitize all inputs
-- Protect against injection attacks
-- Rate limiting
-
-**Constraint handling**:
-```html
-<!-- Set clear constraints -->
-<input
- type="text"
- maxlength="100"
- pattern="[A-Za-z0-9]+"
- required
- aria-describedby="username-hint"
-/>
-<small id="username-hint">
- Letters and numbers only, up to 100 characters
-</small>
-```
-
-### Accessibility Resilience
-
-**Keyboard navigation**:
-- All functionality accessible via keyboard
-- Logical tab order
-- Focus management in modals
-- Skip links for long content
-
-**Screen reader support**:
-- Proper ARIA labels
-- Announce dynamic changes (live regions)
-- Descriptive alt text
-- Semantic HTML
-
-**Motion sensitivity**:
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**High contrast mode**:
-- Test in Windows high contrast mode
-- Don't rely only on color
-- Provide alternative visual cues
-
-### Performance Resilience
-
-**Slow connections**:
-- Progressive image loading
-- Skeleton screens
-- Optimistic UI updates
-- Offline support (service workers)
-
-**Memory leaks**:
-- Clean up event listeners
-- Cancel subscriptions
-- Clear timers/intervals
-- Abort pending requests on unmount
-
-**Throttling & Debouncing**:
-```javascript
-// Debounce search input
-const debouncedSearch = debounce(handleSearch, 300);
-
-// Throttle scroll handler
-const throttledScroll = throttle(handleScroll, 100);
-```
-
-## Testing Strategies
-
-**Manual testing**:
-- Test with extreme data (very long, very short, empty)
-- Test in different languages
-- Test offline
-- Test slow connection (throttle to 3G)
-- Test with screen reader
-- Test keyboard-only navigation
-- Test on old browsers
-
-**Automated testing**:
-- Unit tests for edge cases
-- Integration tests for error scenarios
-- E2E tests for critical paths
-- Visual regression tests
-- Accessibility tests (axe, WAVE)
-
-**IMPORTANT**: Hardening is about expecting the unexpected. Real users will do things you never imagined.
-
-**NEVER**:
-- Assume perfect input (validate everything)
-- Ignore internationalization (design for global)
-- Leave error messages generic ("Error occurred")
-- Forget offline scenarios
-- Trust client-side validation alone
-- Use fixed widths for text
-- Assume English-length text
-- Block entire interface when one component errors
-
-## Verify Hardening
-
-Test thoroughly with edge cases:
-
-- **Long text**: Try names with 100+ characters
-- **Emoji**: Use emoji in all text fields
-- **RTL**: Test with Arabic or Hebrew
-- **CJK**: Test with Chinese/Japanese/Korean
-- **Network issues**: Disable internet, throttle connection
-- **Large datasets**: Test with 1000+ items
-- **Concurrent actions**: Click submit 10 times rapidly
-- **Errors**: Force API errors, test all error states
-- **Empty**: Remove all data, test empty states
-
-When edge cases are covered, hand off to `$impeccable polish` for the final pass.
@@ -1,234 +0,0 @@
-# Heuristics Scoring Guide
-
-Score each of Nielsen's 10 Usability Heuristics on a 0–4 scale. Be honest: a 4 means genuinely excellent, not "good enough."
-
-## Nielsen's 10 Heuristics
-
-### 1. Visibility of System Status
-
-Keep users informed about what's happening through timely, appropriate feedback.
-
-**Check for**:
-- Loading indicators during async operations
-- Confirmation of user actions (save, submit, delete)
-- Progress indicators for multi-step processes
-- Current location in navigation (breadcrumbs, active states)
-- Form validation feedback (inline, not just on submit)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No feedback; user is guessing what happened |
-| 1 | Rare feedback; most actions produce no visible response |
-| 2 | Partial; some states communicated, major gaps remain |
-| 3 | Good; most operations give clear feedback, minor gaps |
-| 4 | Excellent; every action confirms, progress is always visible |
-
-### 2. Match Between System and Real World
-
-Speak the user's language. Follow real-world conventions. Information appears in natural, logical order.
-
-**Check for**:
-- Familiar terminology (no unexplained jargon)
-- Logical information order matching user expectations
-- Recognizable icons and metaphors
-- Domain-appropriate language for the target audience
-- Natural reading flow (left-to-right, top-to-bottom priority)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Pure tech jargon, alien to users |
-| 1 | Mostly confusing; requires domain expertise to navigate |
-| 2 | Mixed; some plain language, some jargon leaks through |
-| 3 | Mostly natural; occasional term needs context |
-| 4 | Speaks the user's language fluently throughout |
-
-### 3. User Control and Freedom
-
-Users need a clear "emergency exit" from unwanted states without extended dialogue.
-
-**Check for**:
-- Undo/redo functionality
-- Cancel buttons on forms and modals
-- Clear navigation back to safety (home, previous)
-- Easy way to clear filters, search, selections
-- Escape from long or multi-step processes
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Users get trapped; no way out without refreshing |
-| 1 | Difficult exits; must find obscure paths to escape |
-| 2 | Some exits; main flows have escape, edge cases don't |
-| 3 | Good control; users can exit and undo most actions |
-| 4 | Full control; undo, cancel, back, and escape everywhere |
-
-### 4. Consistency and Standards
-
-Users shouldn't wonder whether different words, situations, or actions mean the same thing.
-
-**Check for**:
-- Consistent terminology throughout the interface
-- Same actions produce same results everywhere
-- Platform conventions followed (standard UI patterns)
-- Visual consistency (colors, typography, spacing, components)
-- Consistent interaction patterns (same gesture = same behavior)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Inconsistent everywhere; feels like different products stitched together |
-| 1 | Many inconsistencies; similar things look/behave differently |
-| 2 | Partially consistent; main flows match, details diverge |
-| 3 | Mostly consistent; occasional deviation, nothing confusing |
-| 4 | Fully consistent; cohesive system, predictable behavior |
-
-### 5. Error Prevention
-
-Better than good error messages is a design that prevents problems in the first place.
-
-**Check for**:
-- Confirmation before destructive actions (delete, overwrite)
-- Constraints preventing invalid input (date pickers, dropdowns)
-- Smart defaults that reduce errors
-- Clear labels that prevent misunderstanding
-- Autosave and draft recovery
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Errors easy to make; no guardrails anywhere |
-| 1 | Few safeguards; some inputs validated, most aren't |
-| 2 | Partial prevention; common errors caught, edge cases slip |
-| 3 | Good prevention; most error paths blocked proactively |
-| 4 | Excellent; errors nearly impossible through smart constraints |
-
-### 6. Recognition Rather Than Recall
-
-Minimize memory load. Make objects, actions, and options visible or easily retrievable.
-
-**Check for**:
-- Visible options (not buried in hidden menus)
-- Contextual help when needed (tooltips, inline hints)
-- Recent items and history
-- Autocomplete and suggestions
-- Labels on icons (not icon-only navigation)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Heavy memorization; users must remember paths and commands |
-| 1 | Mostly recall; many hidden features, few visible cues |
-| 2 | Some aids; main actions visible, secondary features hidden |
-| 3 | Good recognition; most things discoverable, few memory demands |
-| 4 | Everything discoverable; users never need to memorize |
-
-### 7. Flexibility and Efficiency of Use
-
-Accelerators, invisible to novices, speed up expert interaction.
-
-**Check for**:
-- Keyboard shortcuts for common actions
-- Customizable interface elements
-- Recent items and favorites
-- Bulk/batch actions
-- Power user features that don't complicate the basics
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | One rigid path; no shortcuts or alternatives |
-| 1 | Limited flexibility; few alternatives to the main path |
-| 2 | Some shortcuts; basic keyboard support, limited bulk actions |
-| 3 | Good accelerators; keyboard nav, some customization |
-| 4 | Highly flexible; multiple paths, power features, customizable |
-
-### 8. Aesthetic and Minimalist Design
-
-Interfaces should not contain irrelevant or rarely needed information. Every element should serve a purpose.
-
-**Check for**:
-- Only necessary information visible at each step
-- Clear visual hierarchy directing attention
-- Purposeful use of color and emphasis
-- No decorative clutter competing for attention
-- Focused, uncluttered layouts
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Overwhelming; everything competes for attention equally |
-| 1 | Cluttered; too much noise, hard to find what matters |
-| 2 | Some clutter; main content clear, periphery noisy |
-| 3 | Mostly clean; focused design, minor visual noise |
-| 4 | Perfectly minimal; every element earns its pixel |
-
-### 9. Help Users Recognize, Diagnose, and Recover from Errors
-
-Error messages should use plain language, precisely indicate the problem, and constructively suggest a solution.
-
-**Check for**:
-- Plain language error messages (no error codes for users)
-- Specific problem identification ("Email is missing @" not "Invalid input")
-- Actionable recovery suggestions
-- Errors displayed near the source of the problem
-- Non-blocking error handling (don't wipe the form)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Cryptic errors; codes, jargon, or no message at all |
-| 1 | Vague errors; "Something went wrong" with no guidance |
-| 2 | Clear but unhelpful; names the problem but not the fix |
-| 3 | Clear with suggestions; identifies problem and offers next steps |
-| 4 | Perfect recovery; pinpoints issue, suggests fix, preserves user work |
-
-### 10. Help and Documentation
-
-Even if the system is usable without docs, help should be easy to find, task-focused, and concise.
-
-**Check for**:
-- Searchable help or documentation
-- Contextual help (tooltips, inline hints, guided tours)
-- Task-focused organization (not feature-organized)
-- Concise, scannable content
-- Easy access without leaving current context
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No help available anywhere |
-| 1 | Help exists but hard to find or irrelevant |
-| 2 | Basic help; FAQ or docs exist, not contextual |
-| 3 | Good documentation; searchable, mostly task-focused |
-| 4 | Excellent contextual help; right info at the right moment |
-
----
-
-## Score Summary
-
-**Total possible**: 40 points (10 heuristics × 4 max)
-
-| Score Range | Rating | What It Means |
-|-------------|--------|---------------|
-| 36–40 | Excellent | Minor polish only; ship it |
-| 28–35 | Good | Address weak areas, solid foundation |
-| 20–27 | Acceptable | Significant improvements needed before users are happy |
-| 12–19 | Poor | Major UX overhaul required; core experience broken |
-| 0–11 | Critical | Redesign needed; unusable in current state |
-
----
-
-## Issue Severity (P0–P3)
-
-Tag each individual issue found during scoring with a priority level:
-
-| Priority | Name | Description | Action |
-|----------|------|-------------|--------|
-| **P0** | Blocking | Prevents task completion entirely | Fix immediately; this is a showstopper |
-| **P1** | Major | Causes significant difficulty or confusion | Fix before release |
-| **P2** | Minor | Annoyance, but workaround exists | Fix in next pass |
-| **P3** | Polish | Nice-to-fix, no real user impact | Fix if time permits |
-
-**Tip**: If you're unsure between two levels, ask: "Would a user contact support about this?" If yes, it's at least P1.
@@ -1,195 +0,0 @@
-# Interaction Design
-
-## The Eight Interactive States
-
-Every interactive element needs these states designed:
-
-| State | When | Visual Treatment |
-|-------|------|------------------|
-| **Default** | At rest | Base styling |
-| **Hover** | Pointer over (not touch) | Subtle lift, color shift |
-| **Focus** | Keyboard/programmatic focus | Visible ring (see below) |
-| **Active** | Being pressed | Pressed in, darker |
-| **Disabled** | Not interactive | Reduced opacity, no pointer |
-| **Loading** | Processing | Spinner, skeleton |
-| **Error** | Invalid state | Red border, icon, message |
-| **Success** | Completed | Green check, confirmation |
-
-**The common miss**: Designing hover without focus, or vice versa. They're different. Keyboard users never see hover states.
-
-## Focus Rings: Do Them Right
-
-**Never `outline: none` without replacement.** It's an accessibility violation. Instead, use `:focus-visible` to show focus only for keyboard users:
-
-```css
-/* Hide focus ring for mouse/touch */
-button:focus {
- outline: none;
-}
-
-/* Show focus ring for keyboard */
-button:focus-visible {
- outline: 2px solid var(--color-accent);
- outline-offset: 2px;
-}
-```
-
-**Focus ring design**:
-- High contrast (3:1 minimum against adjacent colors)
-- 2-3px thick
-- Offset from element (not inside it)
-- Consistent across all interactive elements
-
-## Form Design: The Non-Obvious
-
-**Placeholders aren't labels.** They disappear on input. Always use visible `<label>` elements. **Validate on blur**, not on every keystroke (exception: password strength). Place errors **below** fields with `aria-describedby` connecting them.
-
-## Loading States
-
-**Optimistic updates**: Show success immediately, rollback on failure. Use for low-stakes actions (likes, follows), not payments or destructive actions. **Skeleton screens > spinners**: they preview content shape and feel faster than generic spinners.
-
-## Modals: The Inert Approach
-
-Focus trapping in modals used to require complex JavaScript. Now use the `inert` attribute:
-
-```html
-<!-- When modal is open -->
-<main inert>
- <!-- Content behind modal can't be focused or clicked -->
-</main>
-<dialog open>
- <h2>Modal Title</h2>
- <!-- Focus stays inside modal -->
-</dialog>
-```
-
-Or use the native `<dialog>` element:
-
-```javascript
-const dialog = document.querySelector('dialog');
-dialog.showModal(); // Opens with focus trap, closes on Escape
-```
-
-## The Popover API
-
-For tooltips, dropdowns, and non-modal overlays, use native popovers:
-
-```html
-<button popovertarget="menu">Open menu</button>
-<div id="menu" popover>
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-**Benefits**: Light-dismiss (click outside closes), proper stacking, no z-index wars, accessible by default.
-
-## Dropdown & Overlay Positioning
-
-Dropdowns rendered with `position: absolute` inside a container that has `overflow: hidden` or `overflow: auto` will be clipped. This is the single most common dropdown bug in generated code.
-
-### CSS Anchor Positioning
-
-The modern solution uses the CSS Anchor Positioning API to tether an overlay to its trigger without JavaScript:
-
-```css
-.trigger {
- anchor-name: --menu-trigger;
-}
-
-.dropdown {
- position: fixed;
- position-anchor: --menu-trigger;
- position-area: block-end span-inline-end;
- margin-top: 4px;
-}
-
-/* Flip above if no room below */
-@position-try --flip-above {
- position-area: block-start span-inline-end;
- margin-bottom: 4px;
-}
-```
-
-Because the dropdown uses `position: fixed`, it escapes any `overflow` clipping on ancestor elements. The `@position-try` block handles viewport edges automatically. **Browser support**: Chrome 125+, Edge 125+. Not yet in Firefox or Safari - use a fallback for those browsers.
-
-### Popover + Anchor Combo
-
-Combining the Popover API with anchor positioning gives you stacking, light-dismiss, accessibility, and correct positioning in one pattern:
-
-```html
-<button popovertarget="menu" class="trigger">Open</button>
-<div id="menu" popover class="dropdown">
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-The `popover` attribute places the element in the **top layer**, which sits above all other content regardless of z-index or overflow. No portal needed.
-
-### Portal / Teleport Pattern
-
-In component frameworks, render the dropdown at the document root and position it with JavaScript:
-
-- **React**: `createPortal(dropdown, document.body)`
-- **Vue**: `<Teleport to="body">`
-- **Svelte**: Use a portal library or mount to `document.body`
-
-Calculate position from the trigger's `getBoundingClientRect()`, then apply `position: fixed` with `top` and `left` values. Recalculate on scroll and resize.
-
-### Fixed Positioning Fallback
-
-For browsers without anchor positioning support, `position: fixed` with manual coordinates avoids overflow clipping:
-
-```css
-.dropdown {
- position: fixed;
- /* top/left set via JS from trigger's getBoundingClientRect() */
-}
-```
-
-Check viewport boundaries before rendering. If the dropdown would overflow the bottom edge, flip it above the trigger. If it would overflow the right edge, align it to the trigger's right side instead.
-
-### Anti-Patterns
-
-- **`position: absolute` inside `overflow: hidden`** - The dropdown will be clipped. Use `position: fixed` or the top layer instead.
-- **Arbitrary z-index values** like `z-index: 9999` - Use a semantic z-index scale: `dropdown (100) -> sticky (200) -> modal-backdrop (300) -> modal (400) -> toast (500) -> tooltip (600)`.
-- **Rendering dropdown markup inline** without an escape hatch from the parent's stacking context. Either use `popover` (top layer), a portal, or `position: fixed`.
-
-## Destructive Actions: Undo > Confirm
-
-**Undo is better than confirmation dialogs.** Users click through confirmations mindlessly. Remove from UI immediately, show undo toast, actually delete after toast expires. Use confirmation only for truly irreversible actions (account deletion), high-cost actions, or batch operations.
-
-## Keyboard Navigation Patterns
-
-### Roving Tabindex
-
-For component groups (tabs, menu items, radio groups), one item is tabbable; arrow keys move within:
-
-```html
-<div role="tablist">
- <button role="tab" tabindex="0">Tab 1</button>
- <button role="tab" tabindex="-1">Tab 2</button>
- <button role="tab" tabindex="-1">Tab 3</button>
-</div>
-```
-
-Arrow keys move `tabindex="0"` between items. Tab moves to the next component entirely.
-
-### Skip Links
-
-Provide skip links (`<a href="#main-content">Skip to main content</a>`) for keyboard users to jump past navigation. Hide off-screen, show on focus.
-
-## Gesture Discoverability
-
-Swipe-to-delete and similar gestures are invisible. Hint at their existence:
-
-- **Partially reveal**: Show delete button peeking from edge
-- **Onboarding**: Coach marks on first use
-- **Alternative**: Always provide a visible fallback (menu with "Delete")
-
-Don't rely on gestures as the only way to perform actions.
-
----
-
-**Avoid**: Removing focus indicators without alternatives. Using placeholder text as labels. Touch targets <44x44px. Generic error messages. Custom controls without ARIA/keyboard support.
@@ -1,141 +0,0 @@
-Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids, the centered-stack default) and fix the structure, not the surface.
-
----
-
-## Register
-
-Brand: asymmetric compositions, fluid spacing with `clamp()`, intentional grid-breaking for emphasis. Rhythm through contrast: tight groupings paired with generous separations.
-
-Product: predictable grids, consistent densities, familiar navigation patterns. Responsive behavior is structural (collapse sidebar, responsive table), not fluid typography. Consistency IS an affordance.
-
----
-
-## Assess Current Layout
-
-Analyze what's weak about the current spatial design:
-
-1. **Spacing**:
- - Is spacing consistent or arbitrary? (Random padding/margin values)
- - Is all spacing the same? (Equal padding everywhere = no rhythm)
- - Are related elements grouped tightly, with generous space between groups?
-
-2. **Visual hierarchy**:
- - Apply the squint test: blur your (metaphorical) eyes. Can you still identify the most important element, second most important, and clear groupings?
- - Is hierarchy achieved effectively? (Space and weight alone can be enough; is the current approach working?)
- - Does whitespace guide the eye to what matters?
-
-3. **Grid & structure**:
- - Is there a clear underlying structure, or does the layout feel random?
- - Are identical card grids used everywhere? (Icon + heading + text, repeated endlessly)
- - Is everything centered? (Left-aligned with asymmetric layouts feels more designed, but not a hard and fast rule)
-
-4. **Rhythm & variety**:
- - Does the layout have visual rhythm? (Alternating tight/generous spacing)
- - Is every section structured the same way? (Monotonous repetition)
- - Are there intentional moments of surprise or emphasis?
-
-5. **Density**:
- - Is the layout too cramped? (Not enough breathing room)
- - Is the layout too sparse? (Excessive whitespace without purpose)
- - Does density match the content type? (Data-dense UIs need tighter spacing; marketing pages need more air)
-
-**CRITICAL**: Layout problems are often the root cause of interfaces feeling "off" even when colors and fonts are fine. Space is a design material; use it with intention.
-
-## Plan Layout Improvements
-
-Consult the [spatial design reference](spatial-design.md) for detailed guidance on grids, rhythm, and container queries.
-
-Create a systematic plan:
-
-- **Spacing system**: Use a consistent scale (a framework's built-in scale like Tailwind's, rem-based tokens, or a custom system). The specific values matter less than consistency.
-- **Hierarchy strategy**: How will space communicate importance?
-- **Layout approach**: What structure fits the content? Flex for 1D, Grid for 2D, named areas for complex page layouts.
-- **Rhythm**: Where should spacing be tight vs generous?
-
-## Improve Layout Systematically
-
-### Establish a Spacing System
-
-- Use a consistent spacing scale (framework scales like Tailwind, rem-based tokens, or a custom scale all work). What matters is that values come from a defined set, not arbitrary numbers.
-- Name tokens semantically if using custom properties: `--space-xs` through `--space-xl`, not `--spacing-8`
-- Use `gap` for sibling spacing instead of margins; eliminates margin collapse hacks
-- Apply `clamp()` for fluid spacing that breathes on larger screens
-
-### Create Visual Rhythm
-
-- **Tight grouping** for related elements (8-12px between siblings)
-- **Generous separation** between distinct sections (48-96px)
-- **Varied spacing** within sections (not every row needs the same gap)
-- **Asymmetric compositions**: break the predictable centered-content pattern when it makes sense
-
-### Choose the Right Layout Tool
-
-- **Use Flexbox for 1D layouts**: Rows of items, nav bars, button groups, card contents, most component internals. Flex is simpler and more appropriate for the majority of layout tasks.
-- **Use Grid for 2D layouts**: Page-level structure, dashboards, data-dense interfaces, anything where rows AND columns need coordinated control.
-- **Don't default to Grid** when Flexbox with `flex-wrap` would be simpler and more flexible.
-- Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints.
-- Use named grid areas (`grid-template-areas`) for complex page layouts; redefine at breakpoints.
-
-### Break Card Grid Monotony
-
-- Don't default to card grids for everything; spacing and alignment create visual grouping naturally
-- Use cards only when content is truly distinct and actionable. Never nest cards inside cards
-- Vary card sizes, span columns, or mix cards with non-card content to break repetition
-
-### Strengthen Visual Hierarchy
-
-- Use the fewest dimensions needed for clear hierarchy. Space alone can be enough; generous whitespace around an element draws the eye. Some of the most polished designs achieve rhythm with just space and weight. Add color or size contrast only when simpler means aren't sufficient.
-- Be aware of reading flow: in LTR languages, the eye naturally scans top-left to bottom-right, but primary action placement depends on context (e.g., bottom-right in dialogs, top in navigation).
-- Create clear content groupings through proximity and separation.
-
-### Manage Depth & Elevation
-
-- Create a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip)
-- Build a consistent shadow scale (sm → md → lg → xl); shadows should be subtle
-- Use elevation to reinforce hierarchy, not as decoration
-
-### Optical Adjustments
-
-- If an icon looks visually off-center despite being geometrically centered, nudge it. But only if you're confident it actually looks wrong. Don't adjust speculatively.
-
-**NEVER**:
-- Use arbitrary spacing values outside your scale
-- Make all spacing equal (variety creates hierarchy)
-- Wrap everything in cards (not everything needs a container)
-- Nest cards inside cards (use spacing and dividers for hierarchy within)
-- Use identical card grids everywhere (icon + heading + text, repeated)
-- Center everything (left-aligned with asymmetry feels more designed)
-- Default to the hero metric layout (big number, small label, stats, gradient) as a template. If showing real user data, a prominent metric can work, but it should display actual data, not decorative numbers.
-- Default to CSS Grid when Flexbox would be simpler; use the simplest tool for the job
-- Use arbitrary z-index values (999, 9999); build a semantic scale
-
-## Verify Layout Improvements
-
-- **Squint test**: Can you identify primary, secondary, and groupings with blurred vision?
-- **Rhythm**: Does the page have a satisfying beat of tight and generous spacing?
-- **Hierarchy**: Is the most important content obvious within 2 seconds?
-- **Breathing room**: Does the layout feel comfortable, not cramped or wasteful?
-- **Consistency**: Is the spacing system applied uniformly?
-- **Responsiveness**: Does the layout adapt gracefully across screen sizes?
-
-When the rhythm and hierarchy land, hand off to `$impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `density` param. Drive all spacing tokens in the variant's scoped CSS through `calc(var(--p-density, 1) * <base>)`: paddings, gaps, column widths. Users slide from airy to packed and see layout re-breathe with no regeneration.
-
-```json
-{"id":"density","kind":"range","min":0.6,"max":1.4,"step":0.05,"default":1,"label":"Density"}
-```
-
-For variants whose topology genuinely changes (stacked vs. side-by-side, grid vs. bento), use a `steps` param whose scoped CSS branches via `:scope[data-p-structure="X"]`. One structure param + one density param is a powerful combo; resist adding a third.
-
-```json
-{"id":"structure","kind":"steps","default":"grid","label":"Structure","options":[
- {"value":"stacked","label":"Stacked"},
- {"value":"grid","label":"Grid"},
- {"value":"bento","label":"Bento"}
-]}
-```
-
-See `reference/live.md` for the full params contract.
@@ -1,622 +0,0 @@
-Interactive live variant mode: select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via the dev server's HMR.
-
-## Prerequisites
-
-A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR a static HTML file open in the browser.
-
-## The contract (read once)
-
-Execute in order. No step skipped, no step reordered.
-
-1. `live.mjs`: boot.
-2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.
-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.
-5. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
-6. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
-7. On `exit`: run the cleanup at the bottom.
-
-Harness policy:
-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.
-- **Cursor**: run the poll in the **foreground** (blocking shell; not a background terminal, not a subagent). Cursor background terminals and subagents do not reliably resume the chat with poll stdout.
-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.
-- **Other harnesses**: foreground unless you know stdout reliably returns to this session.
-
-Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.
-
-## Start
-
-```bash
-node .agents/skills/impeccable/scripts/live.mjs
-```
-
-Output JSON: `{ ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath, migrated }`. `pageFiles` is the list of HTML entries the live script was injected into. Keep PRODUCT.md and DESIGN.md in mind for variant generation; **DESIGN.md wins on visual decisions; PRODUCT.md wins on strategic/voice decisions.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt. If `migrated: true`, the loader auto-renamed legacy `.impeccable.md` to `PRODUCT.md`; mention this once and suggest `$impeccable document` for the matching DESIGN.md.
-
-`serverPort` and `serverToken` belong to the small **Impeccable live helper** HTTP server (serves `/live.js`, SSE, and `/poll`). That port is **not** your dev server and is usually not the URL you open to view the app. The browser page is whatever origin serves one of the `pageFiles` entries (Vite / Next / Bun / tunnel / LAN hostname).
-
-If output is `{ ok: false, error: "config_missing" | "config_invalid", path }`, this project hasn't been configured for live mode (or its config is stale). See **First-time setup** at the bottom.
-
-## Poll loop
-
-```
-LOOP:
- node .agents/skills/impeccable/scripts/live-poll.mjs # default long timeout; no --timeout=
- Read JSON; dispatch on "type"
-
- "generate" → Handle Generate; reply done; LOOP
- "accept" → Handle Accept; complete carbonize cleanup if required; LOOP
- "discard" → Handle Discard; LOOP
- "prefetch" → Handle Prefetch; LOOP
- "timeout" → LOOP
- "exit" → break → Cleanup
-```
-
-## Recovery commands
-
-The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.
-
-Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:
-
-```bash
-node .agents/skills/impeccable/scripts/live-status.mjs
-node .agents/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID
-node .agents/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID
-```
-
-- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.
-- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.
-- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.
-
-Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.
-
-## Handle `generate`
-
-Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.
-
-Speed matters; the user is watching a spinner. Minimize tool calls by using the `wrap` helper and writing all variants in a single edit.
-
-### 1. Read the screenshot (if present)
-
-`event.screenshotPath` is **only sent when the user placed at least one comment or stroke before Go.** When present, it's an absolute path to a PNG of the element as rendered with the annotations baked in. **Read it before planning**: annotations encode user intent not recoverable from `element.outerHTML` alone.
-
-When `screenshotPath` is absent, don't ask for one and don't go looking for the current rendering. The omission is deliberate: without annotations, a screenshot would anchor the model on the existing design and fight the three-distinct-directions brief. Work from `element.outerHTML`, the computed styles in `event.element`, and the freeform prompt if present.
-
-`event.comments` and `event.strokes` carry structured metadata alongside the visual. Treat the screenshot as primary; use the structured data for specifics worth quoting (e.g. the exact text of a comment).
-
-Reading annotations precisely:
-
-- **Comment position carries meaning.** Its `{x, y}` is element-local CSS px (same coord space as `element.boundingRect`). Find the child under that point and apply the comment text LOCALLY to that sub-element. A comment near the title is about the title, not a global description.
-- **Comments and strokes are independent annotations** unless clearly paired by overlap or tight proximity. Don't let the visual weight of a prominent stroke override the precise location of a textually-specific comment elsewhere.
-- **Strokes are gestures; read them by shape.** Closed loop = "this thing" (emphasis / focus); arrow = direction (move / point to); cross or slash = delete; free scribble = emphasis or delete depending on context. A loop around region X means "pay attention to X," not "only change pixels inside X."
-- **When a stroke's intent is ambiguous** (circle or arrow? emphasis or move?), state your reading in one sentence of rationale rather than silently guessing. If the uncertainty materially changes the brief, ask one short clarifying question before generating.
-
-### 2. Wrap the element
-
-```bash
-node .agents/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"
-```
-
-Flag mapping. Keep them separate, don't collapse into `--query`:
-
-- `--element-id` ← `event.element.id`
-- `--classes` ← `event.element.classes` joined with commas
-- `--tag` ← `event.element.tagName`
-- `--text` ← first ~80 chars of `event.element.textContent` (trim, single-line). **Pass this every call.** When the picked element shares classes + tag with sibling components (a list of `<Card>`s, repeating sections), this is what disambiguates which branch in source to wrap. Without it, wrap silently lands on the first match and may rewrite the wrong element.
-
-The helper searches ID first, then classes, then tag + class combo. If `event.pageUrl` implies the file (e.g. `/` is usually `index.html`), pass `--file PATH` to skip the search. `--query` is a fallback for raw text search only; do not use it for normal element lookups.
-
-If `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.
-
-Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.
-
-`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:
-
-- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.
-- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.
-
-Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.
-
-**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:
-
-- `{ error: "file_is_generated", file, hint }`: user-supplied `--file` points at a generated file.
-- `{ error: "element_not_in_source", generatedMatch, hint }`: element exists only in a generated file (the next build would wipe any edits).
-- `{ error: "element_not_found", hint }`: element isn't in any project file; likely runtime-injected (JS component, dynamic render from data).
-
-All three carry `fallback: "agent-driven"`. Follow **Handle fallback** below.
-
-### 3. Load the action's reference
-
-If `event.action` is `impeccable` (the default freeform action), use SKILL.md's shared laws plus the loaded register reference (`brand.md` or `product.md`). Do not load a sub-command reference. **Freeform is not a pass to skip parameters:** you still follow the composition budget and the freeform bias in **§7 Parameters** below. Sub-command files list MUST-have signature knobs; freeform has no such file, so sizing knobs from surface weight and primary axes is entirely on you.
-
-Any other `event.action` (`bolder`, `quieter`, `distill`, `polish`, `typeset`, `colorize`, `layout`, `adapt`, `animate`, `delight`, `overdrive`): Read `reference/<action>.md` before planning. Each sub-command encodes a specific discipline; skipping its reference produces generic output. Those files may require specific params; layer them on top of the §7 budget, not instead of it.
-
-### 4. Plan three variants: identity first, then mode, then axes
-
-The wrong frame for live mode is "show three different design directions." Live runs on an existing surface; the brand has already been chosen. The job is variation **within identity**, not selection between identities. Failure mode: three editorial-typographic variants on a brief that wasn't editorial. Bigger failure mode: three off-brand variants the user can't accept because they don't look like their product.
-
-Four phases. Do them in order.
-
-#### Phase A: Extract the identity (non-skippable)
-
-The existing surface has an identity already. Read it before planning anything. Sources, in priority order:
-
-1. **DESIGN.md** if loaded: read the visual system fields (palette, type pairing, motion, components). This is the authoritative answer.
-2. **CSS custom properties** in the page's stylesheets (`:root { --color-...; --font-...; ... }`): these are de-facto tokens.
-3. **Computed styles** on the picked element and its parent: colors, fonts, spacing scales, corner radii.
-4. **Sibling components on the page**: what visual rhetoric do existing components use? (Asymmetric or centered? Dense or airy? Bold or quiet?)
-
-Write down what you see in **one sentence**. The sentence describes the surface that's actually on screen; it is not aspirational, not opinionated, not edited toward what the brand "should" be. Capture, in roughly this order:
-
-- The dominant surface color and accent color, by hex or token name (use the actual values, not categories like "warm" or "neutral").
-- The type pairing: the actual font names loaded, primary first.
-- The layout topology: how the dominant elements are arranged (stacked / side-by-side / grid / asymmetric / overlay).
-- The surface treatment: corners, borders, shadows, density of decoration.
-- The voice tone you read off the copy itself, not off the aesthetic feel.
-
-Be specific. "Modern" is not a color, "elegant" is not a type pairing, "clean" is not a layout. If you can't extract a real value for an axis, skip it rather than fabricate. The point is to record what is, not to describe what you wish it were.
-
-Do not include adjectives that name an aesthetic family ("editorial-leaning", "terminal-flavored", "brutalist"); those are conclusions, not data. They belong to Phase C lane selection in departure mode, not to identity description. Letting them sneak into Phase A is how the identity-lock collapses into a self-fulfilling prophecy.
-
-This sentence is the **identity lock**. Every variant must be readable as the same brand if rendered side by side. Skipping this phase is the primary cause of off-brand variants. Absence of DESIGN.md is never an excuse; extract from CSS and computed styles instead.
-
-#### Phase B: Pick mode (default vs departure)
-
-**Default mode**: the existing identity is preserved. Variants vary expression axes within it. *This is the right mode for ~90% of live sessions.* The user picked an element on a real product they're shipping; they expect variants of *their* hero, not three different brands' heroes.
-
-**Departure mode**: the existing identity is rejected. Variants propose alternatives consistent with PRODUCT.md voice. Trigger only when at least one is true:
-
-- PRODUCT.md anti-references explicitly call out the current surface ("the current `index.html` is itself an example"; "diffuse away from this"; "the page on screen is the failure"). Generic anti-references that describe what to avoid in general do **not** trigger departure mode; only ones that point at *this* surface specifically.
-- The user's freeform prompt explicitly asks for departure ("rebuild this from scratch", "what if it weren't editorial at all", "show me something completely different").
-
-If you're unsure, you're in default mode. The cost of being wrong about default is "three on-brand variants with similar feel": recoverable, the user picks none. The cost of being wrong about departure is "three off-brand variants": unrecoverable, the user is annoyed.
-
-#### Phase C: Plan three variants
-
-**Default mode.** Each variant commits to a different **primary axis** of difference, while preserving the identity sentence. The six axes:
-
-1. **Hierarchy**: which element commands the eye?
-2. **Layout topology**: stacked / side-by-side / grid / asymmetric / overlay
-3. **Typographic system**: pairing logic, scale ratio, case/weight strategy *within the available faces*
-4. **Color strategy**: which existing palette role carries the surface (Restrained / Committed / Full palette / Drenched). Use the brand's existing palette tokens, not new colors.
-5. **Density**: minimal / comfortable / dense
-6. **Structural decomposition**: merge, split, progressive disclosure
-
-Three variants → three DIFFERENT axes. The trio reads as *the same brand at three angles*. Do not introduce new fonts, new palette hues, or new aesthetic-family signals; those belong to departure mode.
-
-**While planning each variant, also name its 2–3 parameter knobs** (per the §7 budget table). Parameters are part of the design, not a decoration added afterward. If the variant explores density, expose a density knob. If it explores color commitment, expose a color-amount range. Deciding "what's tunable" during planning produces better knobs than retrofitting them onto finished HTML.
-
-**Departure mode.** Each variant anchors to a different **aesthetic direction**, derived from the brand's stated voice and register in PRODUCT.md. Do NOT pick from a fixed catalog of lane categories. The right three directions for this brand are not the same as the right three for another brand, and picking from a list is itself the training-data reflex (the model selects "Swiss-grid, Terminal, Industrial-signage" every time because those are the furthest-from-editorial items in any enumerated list).
-
-Instead, work from the brand:
-
-1. Read PRODUCT.md's Brand Personality words. What physical, spatial, or material experiences would embody those words if design were not involved? (A personality described as "specific, earned, unmistakable" evokes a hand-stamped letter, a numbered print, a watchmaker's loupe. A personality described as "restless, loud, unfiltered" evokes a concert poster, a spray-painted wall, a megaphone.)
-2. From those physical experiences, derive three visual directions that are genuinely different from each other AND from the current surface you're departing.
-3. Avoid the **reflex-reject lanes** in [brand.md](brand.md). Don't trade one monoculture for another. If you find yourself reaching for "Swiss-grid" or "Terminal" or "Industrial-signage" by reflex, you are pattern-matching a catalog in your training data, not reading the brand. Start over from the personality words.
-4. Each direction must be expressible in one concrete sentence that names a real-world referent ("a museum exhibition label system for a contemporary art gallery" not "clean and minimal"). If your sentence contains only adjectives, it's not concrete enough.
-5. **While planning each direction, also name its 2–3 parameter knobs** (per the §7 budget table). The same principle as default mode: decide "what's tunable" during planning, not after writing the HTML. A departure-mode hero with 0 parameters is not "bold creative vision," it's a missed opportunity for the user to fine-tune the direction they pick.
-
-#### Phase D: Squint test
-
-**Default mode squint.** Read each variant's identity sentence and compare to the locked identity from Phase A. If any variant has drifted to a different palette, type voice, or visual rhetoric, it has crossed into departure mode by accident; rework. Then check that each variant commits to a different primary axis. Three "tighter density" variants is failure.
-
-**Departure mode squint.** Two passes, family before sentence:
-
-1. **Family pass.** Label each variant with one design-family word of your own choosing (any concrete noun: *exhibition, storefront, cockpit, recipe-card, playbill, field-manual*). If any two variants share a label, or if the label could apply to the other variants equally well, rework. Do not use a fixed vocabulary list for the labels. *This pass is non-negotiable in departure mode and catches the monoculture failure that the sentence pass misses.*
-2. **Sentence pass.** Write three one-sentence descriptions side by side. If two of them rhyme ("both feature big type" / "both are stacks of sections" / "both center the CTA"), rework the offender.
-
-**When the primary axis is color or theme, forbid the trio from sharing theme + dominant hue.** Two dark-plus-one-dark is not distinct. Aim for three color worlds, not three shades of the same.
-
-**For action-specific invocations**, each variant must vary along the dimension the action names:
-
-- `bolder`: amplify a different dimension per variant (scale / saturation / structural change). Not three "slightly bigger" variants.
-- `quieter`: pull back a different dimension (color / ornament / spacing).
-- `distill`: remove a different class of excess (visual noise / redundant content / nested structure).
-- `polish`: target a different refinement axis (rhythm / hierarchy / micro-details like corner radii, focus states, optical kerning).
-- `typeset`: different type pairing AND different scale ratio each. Not three riffs on one pairing.
-- `colorize`: different hue family each (not shades of one hue). Vary chroma and contrast strategy.
-- `layout`: different structural arrangement (stacked / side-by-side / grid / asymmetric). Not spacing tweaks.
-- `adapt`: different target context per variant (mobile-first / tablet / desktop / print or low-data). Don't make three mobile layouts.
-- `animate`: different motion vocabulary (cascade stagger / clip wipe / scale-and-focus / morph / parallax). Not three staggered fades.
-- `delight`: different flavor of personality (unexpected micro-interaction / typographic surprise / illustrated accent / sonic-or-haptic moment / easter-egg interaction).
-- `overdrive`: different convention broken (scale / structure / motion / input model / state transitions). Skip `overdrive.md`'s "propose and ask" step; live mode is non-interactive.
-
-### 5. Apply the freeform prompt (if present)
-
-`event.freeformPrompt` is the user's ceiling on direction (all variants must honor it), but still explore meaningfully different *interpretations*. The interpretations stay within whichever mode you picked in Phase B.
-
-In **default mode**, the prompt narrows the axes you choose, not the identity. *"Make it feel more confident"* → variant 1 amplifies hierarchy (one element commands the eye), variant 2 commits the existing accent color (Committed strategy on the brand's hue), variant 3 tightens density and removes decorative slack. Three different axes, same brand.
-
-In **departure mode**, the prompt narrows the lanes you draw from, not the families. *"Make it feel like a newspaper front page"* would itself be a departure-mode prompt; honor it but pick three meaningfully different newspaper-adjacent lanes (broadsheet vs. tabloid vs. trade journal), and run the family pass to confirm they don't collapse into one.
-
-When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.
-
-### 6. Write all variants in a single edit
-
-Complete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).
-
-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).
-
-Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:
-
-```html
-<!-- Variants: insert below this line -->
-<style data-impeccable-css="SESSION_ID">
- /* rules matching cssAuthoring.rulePattern */
-</style>
-<div data-impeccable-variant="1">
- <!-- variant 1: full element replacement (single top-level element) -->
-</div>
-<div data-impeccable-variant="2" style="display: none">
- <!-- variant 2: full element replacement -->
-</div>
-<div data-impeccable-variant="3" style="display: none">
- <!-- variant 3: full element replacement -->
-</div>
-```
-
-**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.
-
-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.
-
-One edit, all variants; the browser's MutationObserver picks everything up in one pass.
-
-For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.
-
-**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:
-
-```tsx
-<style data-impeccable-css="SESSION_ID">{`
- @scope ([data-impeccable-variant="1"]) { ... }
- @scope ([data-impeccable-variant="2"]) { ... }
-`}</style>
-<div data-impeccable-variant="1">
- {/* variant 1 */}
-</div>
-<div data-impeccable-variant="2" style={{ display: 'none' }}>
- {/* variant 2 */}
-</div>
-```
-
-The wrap script already gives you a single-rooted JSX wrapper: a `<div data-impeccable-variants="…">` outer element with the marker comments tucked inside. Drop the variants block above into the "Variants: insert below this line" comment and the source stays valid TSX.
-
-### 7. Parameters (composition-sized, 0–4 per variant)
-
-Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement. The browser docks a small panel to the right of the outline with one control per parameter. The user drags/clicks and sees instant feedback: there is zero regeneration cost because the knob toggles a CSS variable or data attribute that the variant's scoped CSS is already authored against.
-
-**What “optional” does not mean.** Parameters are not nice-to-have decoration on large work. The word meant “omit controls that are redundant or cosmetic,” not “default to zero because three variants were enough work.”
-
-**When to add.** As soon as the variant’s scoped CSS has a meaningful continuous or stepped axis: density, color amount, type scale, motion intensity, column weight, and so on. If you can imagine the user muttering “a bit tighter” or “a touch more accent” **without** wanting a full regeneration, wire that axis. **Not** micro-margins or one-off nudges; those are not parameters.
-
-**Freeform (`action` is `impeccable`) bias.** You did not load a sub-command reference, so you must **choose** signature axes yourself. Match the budget table: for a hero or large composition, that means **2–3 axes per variant**, not 1. Prefer knobs that sit on the dimensions where your three variants actually differ (if density varies, expose it as a `steps` knob; if color commitment varies, expose it as a `range`). A hero that ships with **0** params is almost always a mistake, not a judgment call. A hero with exactly **1** param is underweight unless the design is genuinely a fixed-point comparison. Start from the budget table, not from zero.
-
-**Budget scales with the element's visual weight, not token budget.** Knobs need real estate to read as tunable; three sliders on a single control are noise.
-
-- **Leaf / tiny**: a single button, icon, input, bare heading, solitary paragraph: **0 params.**
-- **Small composition**: labeled input, simple card, short callout (≤ ~5 visual children): **0–1** params when one dominant axis is obvious; otherwise **0.**
-- **Medium composition**: section component, nav cluster, dense card, short feature block (6–15 visual children): **target 2**; **1** is acceptable if the block is simple; **0** only when variants are truly fixed points.
-- **Large composition**: hero section, full page region, spread layout, strong internal structure (16+ visual children or multiple sub-sections): **target 2–3**; **up to 4** when several independent axes (e.g. structure `steps` + `density` + one accent) are all authored in scoped CSS.
-
-**When in doubt, ask whether a dial exists before defaulting to zero.** The user can always request more variants, but the point of live mode is instant tuning without another Go. Crowding the panel is bad; **under-shipping** knobs on a dense composition is the more common failure for freeform. Count by **visual** children, not DOM depth; a shallow-but-wide hero is still large.
-
-**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.
-
-**How to declare.** Put a JSON manifest on the variant wrapper:
-
-```html
-<div data-impeccable-variant="1" data-impeccable-params='[
- {"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"},
- {"id":"density","kind":"steps","default":"snug","label":"Density","options":[
- {"value":"airy","label":"Airy"},
- {"value":"snug","label":"Snug"},
- {"value":"packed","label":"Packed"}
- ]},
- {"id":"serif","kind":"toggle","default":false,"label":"Serif display"}
-]'>
- ...variant content...
-</div>
-```
-
-**Three kinds:**
-
-- `range`: smooth slider. Drives a CSS custom property `--p-<id>` on the variant wrapper. Author CSS with `var(--p-color-amount, 0.5)`. Fields: `min`, `max`, `step`, `default` (number), `label`.
-- `steps`: segmented radio. Drives a data attribute `data-p-<id>` on the variant wrapper. Author CSS with `:scope[data-p-density="airy"] .grid { ... }`. Fields: `options` (array of `{value, label}`), `default` (string), `label`.
-- `toggle`: on/off switch. Drives BOTH a CSS var (`--p-<id>: 0|1`) and a data attribute (present when on, absent when off). Use whichever is more convenient. Fields: `default` (boolean), `label`.
-
-**Signature params per action.** For named sub-commands, read that action’s `reference/<action>.md` for one or two **MUST** params (e.g. `layout` → `density`). Those are non-negotiable when the design can express them. **Freeform has no file-level MUST**; the **Freeform (`impeccable`) bias** in this section is the stand-in. If the user’s action is both stylized and sub-command (e.g. `colorize`), the sub-command’s MUST list takes precedence for its axes; still respect the **Hard cap** and add no redundant duplicate knobs.
-
-**Reset on variant switch.** User dials density on v1, flips to v2, v2 starts at v2's declared defaults. Known limitation; preservation across variants may land later.
-
-**On accept**, the browser sends the user's current values in the accept event. `live-accept.mjs` writes them as a sibling comment:
-
-```html
-<!-- impeccable-param-values SESSION_ID: {"color-amount":0.7,"density":"packed"} -->
-```
-
-The carbonize cleanup step (see below) reads that comment and bakes the chosen values into the final CSS. For `steps`/`toggle` attribute selectors: keep only the branch matching the chosen value, drop the others, collapse `:scope[data-p-density="packed"] .grid` to a semantic class rule. For `range` vars: either substitute the literal or keep the var with the chosen value as its new default.
-
-### 8. Signal done
-
-```bash
-node .agents/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
-```
-
-`RELATIVE_PATH` is relative to project root (`public/index.html`, `src/App.tsx`, etc.); the browser fetches source directly if the dev server lacks HMR.
-
-Then run `live-poll.mjs` again immediately.
-
-### Aborting an in-flight session
-
-If wrap or generation fails after the browser has flipped to GENERATING (e.g. wrap landed on the wrong source branch and you've already reverted it, or generation hit an unrecoverable error), tell the **browser** so its bar resets to PICKING:
-
-```bash
-node .agents/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID error "Short reason"
-```
-
-Don't run `live-accept --discard` for this; that's a pure file mutator, the browser doesn't see it, and the bar gets stuck on the GENERATING dots forever (the user has to refresh). `--discard` is only correct when the **browser** initiated the discard (user clicked ✕ during CYCLING) and the agent is just running source-side cleanup the browser already triggered.
-
-## Handle fallback
-
-When wrap returns `fallback: "agent-driven"`, the deterministic flow doesn't apply. Pick up here.
-
-The goal is the same: give the user three variants to choose from AND persist the accepted one in a place the next build won't wipe. The difference is that you have to pick the right source file yourself.
-
-### Step 1: Identify where the element actually lives
-
-Use the error payload:
-
-- `element_not_in_source` with `generatedMatch: "public/docs/foo.html"`: the served HTML is generated. Find the generator (grep for writers of that path, e.g. `scripts/build-sub-pages.js`, an Astro/Next template) and locate the template or partial that emits this element.
-- `element_not_found`: the element is runtime-injected. Look for the component that renders it (React/Vue/Svelte), the JS that assembles it, or the data source that feeds it.
-- `file_is_generated` with `file: "..."`: user pointed at a generated file explicitly. Same resolution as `element_not_in_source`.
-
-Read the candidate source until you're confident where a change to the element would belong. If the change is purely visual, that source might be a shared stylesheet, not the template.
-
-### Step 2: Show three variants in the DOM for preview
-
-The browser bar is waiting for variants. Even without a wrapper in source, you still need to show something:
-
-1. Manually write the wrapper scaffold into the **served** file (the one the browser actually loaded). Use the same structure `live-wrap.mjs` produces; `<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents">…</div><!-- end -->`.
-2. Insert your three variant divs inside it, same shape as the deterministic path.
-3. Signal done with `--reply EVENT_ID done --file <served file>`. The browser's no-HMR fallback will fetch and inject.
-
-This served-file edit is **temporary**: next regen wipes it, and that's fine. The real work happens on accept.
-
-### Step 3: On accept, write to true source
-
-When the accept event arrives (`_acceptResult.handled` will usually be `false` here because accept also refuses to persist into generated files; see Handle accept for the carbonize branch), extract the accepted variant's content and write it into the source you identified in Step 1:
-
-- Structural change → edit the template / component source.
-- Visual-only change → add or update rules in the appropriate stylesheet; remove the inline `<style>` scope.
-- Dynamic from data → update the data source or the render logic.
-
-Then remove the temporary wrapper from the served file if it's still there.
-
-### Step 4: On discard, clean up the served file
-
-Remove the wrapper you inserted in Step 2. Nothing else to do.
-
-## Handle `accept`
-
-Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.
-
-- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.
-- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.
-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.
-- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.
-- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.
-
-### Required after accept (carbonize)
-
-When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.
-
-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.
-
-1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.
-2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).
-3. **Bake in parameter values while rewriting selectors.** For `@scope ([data-impeccable-variant="N"])` wrappers: retarget to real, semantic classes on the accepted HTML (`.why-visual--v2 .v2-label { … }`). For `:scope[data-p-<id>="VALUE"]` selectors: keep only the branch matching the chosen value from the param-values comment; drop the others (they're dead after accept). For `var(--p-<id>, DEFAULT)` in the CSS: either substitute the literal value, or if the param is still useful as a knob going forward, leave the var and update its initial declaration to the chosen value.
-4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; those are live-mode plumbing, not source.
-5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.
-
-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.
-
-A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.
-
-## Handle `discard`
-
-Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.
-
-## Handle `prefetch`
-
-Event: `{pageUrl}`. The browser fires this the first time the user selects an element on a given route, as a latency shortcut; it signals the user is likely about to Go on a page you haven't read yet.
-
-Resolve `pageUrl` to the underlying file:
-
-- Root `/` → the `pageFile` returned by `live.mjs` (usually `public/index.html` or equivalent).
-- Sub-routes (e.g. `/docs`, `/docs/live`) → the generated or source file for that route. Use your knowledge of the project layout (multi-page static sites often resolve `/foo` → `public/foo/index.html`; SPAs may map all routes to a single entry).
-
-Read the file into context, then poll again. No `--reply`: this is speculative pre-work; Go will come later. If you can't confidently resolve the route to a file, skip and poll again.
-
-Dedupe is the browser's job (one prefetch per unique pathname per session); trust it. If the same file shows up twice from different routes mapping to the same file, the second Read is cached anyway.
-
-## Exit
-
-The user can stop live mode by:
-- Saying "stop live mode" / "exit live" in chat
-- Closing the browser tab (SSE drops, poll returns `exit` after 8s)
-- The browser's exit button
-
-When the poll returns `exit`, proceed to cleanup. If the poll is still running as a background task, kill it first.
-
-## Cleanup
-
-```bash
-node .agents/skills/impeccable/scripts/live-server.mjs stop
-```
-
-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.
-
-Then:
-- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).
-- Remove any leftover carbonize blocks (search for `impeccable-carbonize-start` markers).
-
-## First-time setup (config missing or invalid)
-
-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.
-
-Schema:
-
-```json
-{
- "files": ["<path-or-glob>", "<path-or-glob>", ...],
- "exclude": ["<optional-glob>", ...],
- "insertBefore": "</body>",
- "commentSyntax": "html",
- "cspChecked": true
-}
-```
-
-`files` is the inject target; **the HTML files the browser actually loads**, not necessarily source. Each entry is either a literal path (`"public/index.html"`) or a glob pattern (`"public/**/*.html"`). Tracked or generated doesn't matter here; wrap has its own generated-file guard and routes accepts through the fallback flow.
-
-`exclude` (optional) is a list of glob patterns matching files to skip, even if a `files` glob would have included them. Use for email templates, demo fixtures, or any HTML that isn't a live page.
-
-`cspChecked` tracks whether the CSP detection step below has already run. Absent on first setup; set to `true` after CSP is checked (whether patched, declined, or not needed).
-
-**Hard-excluded paths (cannot be overridden).** `**/node_modules/**` and `**/.git/**` are never matched regardless of what the user writes. These are vendor/metadata directories and injecting into them would silently instrument third-party code.
-
-**Glob syntax.** `**` matches any number of path segments (including zero), `*` matches any characters except `/`, `?` matches a single character except `/`. Paths are always relative to the project root with forward slashes.
-
-| Framework | `files` | `insertBefore` | `commentSyntax` |
-|-----------|---------|----------------|-----------------|
-| SPA with single shell (Vite / React / Plain HTML) | `["index.html"]` | `</body>` | `html` |
-| Next.js (App Router) | `["app/layout.tsx"]` | `</body>` | `jsx` |
-| Next.js (Pages) | `["pages/_document.tsx"]` | `</body>` | `jsx` |
-| Nuxt | `["app.vue"]` | `</body>` | `html` |
-| Svelte / SvelteKit | `["src/app.html"]` | `</body>` | `html` |
-| Astro | `[" <root layout .astro>"]` | `</body>` | `html` |
-| Multi-page (separate HTML per route) | `["public/**/*.html"]`: a glob covering the served directory | `</body>` | `html` |
-
-Pick an anchor that exists in every file (`</body>` almost always works). Use `insertAfter` if the anchor should match **after** a specific line.
-
-For multi-page sites, **prefer a glob over a literal file list**. New pages added later are picked up automatically on the next `live-inject.mjs` run; no config maintenance needed.
-
-For multi-page sites whose pages are *rebuilt* by a generator (Astro, static-site generators, custom scripts like `build-sub-pages.js`), the inject survives only until the next regeneration. Re-run `live.mjs` after each build. Accept is unaffected; it writes to true source via the fallback flow.
-
-### Drift-heal warning
-
-On every `live.mjs` boot, after inject, the project is scanned for HTML files under common page-source roots (`public/`, `src/`, `app/`, `pages/`). If any exist that aren't covered by the resolved `files` list, the output includes a `configDrift` field:
-
-```json
-{
- "ok": true,
- "serverPort": 8400,
- "pageFiles": [ "..." ],
- "configDrift": {
- "orphans": ["public/new-section/index.html", "public/docs/new-command.html"],
- "orphanCount": 2,
- "hint": "2 HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like \"public/**/*.html\"."
- }
-}
-```
-
-When `configDrift` is present, surface it to the user once per session before entering the poll loop:
-
-> Noticed N HTML file(s) in the project that aren't in `config.files`:
->
-> - `public/new-section/index.html`
-> - `public/docs/new-command.html`
->
-> Add them, or switch `files` to a glob like `["public/**/*.html"]` and let it track new pages automatically?
-
-Don't auto-update the config; let the user decide. `configDrift` is `null` when there's no drift.
-
-### CSP detection (first-time only)
-
-If `config.cspChecked === true`, skip this entire section. You already asked this user once; the answer sticks.
-
-Otherwise, run the detection helper:
-
-```bash
-node .agents/skills/impeccable/scripts/detect-csp.mjs
-```
-
-Output: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.
-
-- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.
-- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:
- - Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)
- - SvelteKit `kit.csp.directives`
- - Nuxt `nuxt-security` module's `contentSecurityPolicy`
-- **`append-string`**: CSP written as a literal value string. Auto-patchable. See *append-string* below. Covers:
- - Inline `next.config.*` `headers()` with a CSP literal
- - Nuxt `routeRules` / `nitro.routeRules` headers
-- **`middleware`** or **`meta-tag`**: rarer. Detected but not auto-patched in v1. Show the user the detected files and ask them to add `http://localhost:8400` to `script-src` and `connect-src` manually, then mark `cspChecked: true` and proceed.
-
-#### Consent prompt template
-
-Use this phrasing so the experience is consistent across agents:
-
-> **CSP patch needed.** I detected a Content Security Policy in your project that blocks `http://localhost:8400`: the live picker won't load without an allowance. Here's the change I'd make:
->
-> ```diff
-> [file: <patchTarget>]
-> [exact diff, 2–5 lines]
-> ```
->
-> It's guarded by `NODE_ENV === "development"` so the extra entry only appears in dev and never reaches production. You can remove it any time by reverting this file. Apply? [y/n]
-
-On "no": skip the patch, mention live won't work until the user adds the allowance manually, still write `cspChecked: true` (the question's been asked).
-
-On "yes": apply the Shape-specific patch below, then write `cspChecked: true`.
-
-#### append-arrays
-
-CSP expressed as structured directive arrays. Patch mechanism: declare a dev-only array, spread it into the script-src and connect-src arrays.
-
-**Declare near the top of the file that holds the CSP arrays:**
-
-```ts
-// Dev-only allowance so impeccable live mode can load. Guarded by NODE_ENV.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? ["http://localhost:8400"] : [];
-```
-
-**Append `...__impeccableLiveDev` to the script-src and connect-src directive arrays.** Per-framework specifics:
-
-- **Next.js + monorepo helper**: edit the *app's* `next.config.*` (not the shared helper), appending to `additionalScriptSrc` and `additionalConnectSrc` passed into `createBaseNextConfig` (or equivalent). Keeps the shared package clean.
-- **SvelteKit**: edit `svelte.config.js`, appending to `kit.csp.directives['script-src']` and `kit.csp.directives['connect-src']`.
-- **Nuxt + nuxt-security**: edit `nuxt.config.*`, appending to `security.headers.contentSecurityPolicy['script-src']` and `['connect-src']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-turborepo/expected-after-patch.ts` (Next.js)
-- `tests/framework-fixtures/sveltekit-csp/expected-after-patch.js` (SvelteKit)
-
-Idempotency: if `__impeccableLiveDev` already exists in the file, the patch is already applied; skip asking and just mark `cspChecked: true`.
-
-#### append-string
-
-CSP built as a literal value string. Two-point patch: declare a dev-only string near the top, interpolate it into the CSP at the `script-src` and `connect-src` directives.
-
-```ts
-// Dev-only allowance so impeccable live mode can load.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? " http://localhost:8400" : "";
-```
-
-Then in the CSP value string:
-- `script-src 'self' 'unsafe-inline'` → `` `script-src 'self' 'unsafe-inline'${__impeccableLiveDev}` ``
-- `connect-src 'self'` → `` `connect-src 'self'${__impeccableLiveDev}` ``
-
-(Leading space on the dev string so it concatenates cleanly into the existing value. Convert the literal CSP directives into template strings as part of the edit if they aren't already.)
-
-Per-framework specifics:
-- **Next.js inline `headers()`**: edit `next.config.*`, splicing the variable into the CSP value.
-- **Nuxt `routeRules`**: edit `nuxt.config.*`, splicing into the CSP in `routeRules['/**'].headers['Content-Security-Policy']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-inline-csp/expected-after-patch.js` (Next.js)
-- `tests/framework-fixtures/nuxt-csp/expected-after-patch.ts` (Nuxt)
-
-### Troubleshooting
-
-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.
-
-Then re-run `live.mjs`.
@@ -1,109 +0,0 @@
-# Motion Design
-
-## Duration: The 100/300/500 Rule
-
-Timing matters more than easing. These durations feel right for most UI:
-
-| Duration | Use Case | Examples |
-|----------|----------|----------|
-| **100-150ms** | Instant feedback | Button press, toggle, color change |
-| **200-300ms** | State changes | Menu open, tooltip, hover states |
-| **300-500ms** | Layout changes | Accordion, modal, drawer |
-| **500-800ms** | Entrance animations | Page load, hero reveals |
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-## Easing: Pick the Right Curve
-
-**Don't use `ease`.** It's a compromise that's rarely optimal. Instead:
-
-| Curve | Use For | CSS |
-|-------|---------|-----|
-| **ease-out** | Elements entering | `cubic-bezier(0.16, 1, 0.3, 1)` |
-| **ease-in** | Elements leaving | `cubic-bezier(0.7, 0, 0.84, 0)` |
-| **ease-in-out** | State toggles (there → back) | `cubic-bezier(0.65, 0, 0.35, 1)` |
-
-**For micro-interactions, use exponential curves.** They feel natural because they mimic real physics (friction, deceleration):
-
-```css
-/* Quart out - smooth, refined (recommended default) */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1);
-
-/* Quint out - slightly more dramatic */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1);
-
-/* Expo out - snappy, confident */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1);
-```
-
-**Avoid bounce and elastic curves.** They were trendy in 2015 but now feel tacky and amateurish. Real objects don't bounce when they stop; they decelerate smoothly. Overshoot effects draw attention to the animation itself rather than the content.
-
-## Premium Motion Materials
-
-Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties: blur reveals, backdrop-filter panels, saturation or brightness shifts, shadow bloom, SVG filters, masks, clip paths, gradient-position movement, and variable font or shader-driven effects.
-
-Use the right material for the effect:
-
-- **Transform / opacity**: movement, press feedback, simple reveals, list choreography.
-- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances, atmospheric transitions.
-- **Clip path / masks**: wipes, reveals, editorial cropping, product-like transitions.
-- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state.
-- **Grid-template rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly.
-
-The hard rule is not "transform and opacity only." The hard rule is: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify in-browser that the result is smooth on the target viewports. If blur/filter makes the interaction feel significantly more premium and remains smooth, use it.
-
-## Staggered Animations
-
-Use CSS custom properties for cleaner stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"` on each item. **Cap total stagger time**: 10 items at 50ms = 500ms total. For many items, reduce per-item delay or cap staggered count.
-
-## Reduced Motion
-
-This is not optional. Vestibular disorders affect ~35% of adults over 40.
-
-```css
-/* Define animations normally */
-.card {
- animation: slide-up 500ms ease-out;
-}
-
-/* Provide alternative for reduced motion */
-@media (prefers-reduced-motion: reduce) {
- .card {
- animation: fade-in 200ms ease-out; /* Crossfade instead of motion */
- }
-}
-
-/* Or disable entirely */
-@media (prefers-reduced-motion: reduce) {
- *, *::before, *::after {
- animation-duration: 0.01ms !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**What to preserve**: Functional animations like progress bars, loading spinners (slowed down), and focus indicators should still work, just without spatial movement.
-
-## Perceived Performance
-
-**Nobody cares how fast your site is, just how fast it feels.** Perception can be as effective as actual performance.
-
-**The 80ms threshold**: Our brains buffer sensory input for ~80ms to synchronize perception. Anything under 80ms feels instant and simultaneous. This is your target for micro-interactions.
-
-**Active vs passive time**: Passive waiting (staring at a spinner) feels longer than active engagement. Strategies to shift the balance:
-
-- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening.
-- **Early completion**: Show content progressively, don't wait for everything. Video buffering, progressive images, streaming HTML.
-- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Instagram likes work offline; the UI updates instantly, syncs later. Use for low-stakes actions; avoid for payments or destructive operations.
-
-**Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances, but ease-in toward a task's end compresses perceived time.
-
-**Caution**: Too-fast responses can decrease perceived value. Users may distrust instant results for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
-
-## Performance
-
-Don't use `will-change` preemptively, only when animation is imminent (`:hover`, `.animating`). For scroll-triggered animations, use Intersection Observer instead of scroll events; unobserve after animating once. Create motion tokens for consistency (durations, easings, common transitions).
-
----
-
-**Avoid**: Animating everything (animation fatigue is real). Using >500ms for UI feedback. Ignoring `prefers-reduced-motion`. Using animation to hide slow loading.
@@ -1,234 +0,0 @@
-> **Additional context needed**: the "aha moment" you want users to reach, and users' experience level.
-
-Get users to first value as fast as possible. Onboarding's job is not to teach the product. Its job is to get people to the moment that proves the product is worth their time.
-
-## Assess Onboarding Needs
-
-Understand what users need to learn and why:
-
-1. **Identify the challenge**:
- - What are users trying to accomplish?
- - What's confusing or unclear about current experience?
- - Where do users get stuck or drop off?
- - What's the "aha moment" we want users to reach?
-
-2. **Understand the users**:
- - What's their experience level? (Beginners, power users, mixed?)
- - What's their motivation? (Excited and exploring? Required by work?)
- - What's their time commitment? (5 minutes? 30 minutes?)
- - What alternatives do they know? (Coming from competitor? New to category?)
-
-3. **Define success**:
- - What's the minimum users need to learn to be successful?
- - What's the key action we want them to take? (First project? First invite?)
- - How do we know onboarding worked? (Completion rate? Time to value?)
-
-**CRITICAL**: Onboarding should get users to value as quickly as possible, not teach everything possible.
-
-## Onboarding Principles
-
-Follow these core principles:
-
-### Show, Don't Tell
-- Demonstrate with working examples, not just descriptions
-- Provide real functionality in onboarding, not separate tutorial mode
-- Use progressive disclosure, teach one thing at a time
-
-### Make It Optional (When Possible)
-- Let experienced users skip onboarding
-- Don't block access to product
-- Provide "Skip" or "I'll explore on my own" options
-
-### Time to Value
-- Get users to their "aha moment" ASAP
-- Front-load most important concepts
-- Teach 20% that delivers 80% of value
-- Save advanced features for contextual discovery
-
-### Context Over Ceremony
-- Teach features when users need them, not upfront
-- Empty states are onboarding opportunities
-- Tooltips and hints at point of use
-
-### Respect User Intelligence
-- Don't patronize or over-explain
-- Be concise and clear
-- Assume users can figure out standard patterns
-
-## Design Onboarding Experiences
-
-Create appropriate onboarding for the context:
-
-### Initial Product Onboarding
-
-**Welcome Screen**:
-- Clear value proposition (what is this product?)
-- What users will learn/accomplish
-- Time estimate (honest about commitment)
-- Option to skip (for experienced users)
-
-**Account Setup**:
-- Minimal required information (collect more later)
-- Explain why you're asking for each piece of information
-- Smart defaults where possible
-- Social login when appropriate
-
-**Core Concept Introduction**:
-- Introduce 1-3 core concepts (not everything)
-- Use simple language and examples
-- Interactive when possible (do, don't just read)
-- Progress indication (step 1 of 3)
-
-**First Success**:
-- Guide users to accomplish something real
-- Pre-populated examples or templates
-- Celebrate completion (but don't overdo it)
-- Clear next steps
-
-### Feature Discovery & Adoption
-
-**Empty States**:
-Instead of blank space, show:
-- What will appear here (description + screenshot/illustration)
-- Why it's valuable
-- Clear CTA to create first item
-- Example or template option
-
-Example:
-```
-No projects yet
-Projects help you organize your work and collaborate with your team.
-[Create your first project] or [Start from template]
-```
-
-**Contextual Tooltips**:
-- Appear at relevant moment (first time user sees feature)
-- Point directly at relevant UI element
-- Brief explanation + benefit
-- Dismissable (with "Don't show again" option)
-- Optional "Learn more" link
-
-**Feature Announcements**:
-- Highlight new features when they're released
-- Show what's new and why it matters
-- Let users try immediately
-- Dismissable
-
-**Progressive Onboarding**:
-- Teach features when users encounter them
-- Badges or indicators on new/unused features
-- Unlock complexity gradually (don't show all options immediately)
-
-### Guided Tours & Walkthroughs
-
-**When to use**:
-- Complex interfaces with many features
-- Significant changes to existing product
-- Industry-specific tools needing domain knowledge
-
-**How to design**:
-- Spotlight specific UI elements (dim rest of page)
-- Keep steps short (3-7 steps max per tour)
-- Allow users to click through tour freely
-- Include "Skip tour" option
-- Make replayable (help menu)
-
-**Best practices**:
-- Interactive over passive (let users click real buttons)
-- Focus on workflow, not features ("Create a project" not "This is the project button")
-- Provide sample data so actions work
-
-### Interactive Tutorials
-
-**When to use**:
-- Users need hands-on practice
-- Concepts are complex or unfamiliar
-- High stakes (better to practice in safe environment)
-
-**How to design**:
-- Sandbox environment with sample data
-- Clear objectives ("Create a chart showing sales by region")
-- Step-by-step guidance
-- Validation (confirm they did it right)
-- Graduation moment (you're ready!)
-
-### Documentation & Help
-
-**In-product help**:
-- Contextual help links throughout interface
-- Keyboard shortcut reference
-- Search-able help center
-- Video tutorials for complex workflows
-
-**Help patterns**:
-- `?` icon near complex features
-- "Learn more" links in tooltips
-- Keyboard shortcut hints (`⌘K` shown on search box)
-
-## Empty State Design
-
-Every empty state needs:
-
-### What Will Be Here
-"Your recent projects will appear here"
-
-### Why It Matters
-"Projects help you organize your work and collaborate with your team"
-
-### How to Get Started
-[Create project] or [Import from template]
-
-### Visual Interest
-Illustration or icon (not just text on blank page)
-
-### Contextual Help
-"Need help getting started? [Watch 2-min tutorial]"
-
-**Empty state types**:
-- **First use**: Never used this feature (emphasize value, provide template)
-- **User cleared**: Intentionally deleted everything (light touch, easy to recreate)
-- **No results**: Search or filter returned nothing (suggest different query, clear filters)
-- **No permissions**: Can't access (explain why, how to get access)
-- **Error state**: Failed to load (explain what happened, retry option)
-
-## Implementation Patterns
-
-### Technical approaches:
-
-**Tooltip libraries**: Tippy.js, Popper.js
-**Tour libraries**: Intro.js, Shepherd.js, React Joyride
-**Modal patterns**: Focus trap, backdrop, ESC to close
-**Progress tracking**: LocalStorage for "seen" states
-**Analytics**: Track completion, drop-off points
-
-**Storage patterns**:
-```javascript
-// Track which onboarding steps user has seen
-localStorage.setItem('onboarding-completed', 'true');
-localStorage.setItem('feature-tooltip-seen-reports', 'true');
-```
-
-**IMPORTANT**: Don't show same onboarding twice (annoying). Track completion and respect dismissals.
-
-**NEVER**:
-- Force users through long onboarding before they can use product
-- Patronize users with obvious explanations
-- Show same tooltip repeatedly (respect dismissals)
-- Block all UI during tour (let users explore)
-- Create separate tutorial mode disconnected from real product
-- Overwhelm with information upfront (progressive disclosure!)
-- Hide "Skip" or make it hard to find
-- Forget about returning users (don't show initial onboarding again)
-
-## Verify Onboarding Quality
-
-Test with real users:
-
-- **Time to completion**: Can users complete onboarding quickly?
-- **Comprehension**: Do users understand after completing?
-- **Action**: Do users take desired next step?
-- **Skip rate**: Are too many users skipping? (Maybe it's too long or not valuable)
-- **Completion rate**: Are users completing? (If low, simplify)
-- **Time to value**: How long until users get first value?
-
-When users hit the aha moment fast and don't drop off, hand off to `$impeccable polish` for the final pass.
@@ -1,258 +0,0 @@
-Performance is a feature. Identify the actual bottleneck for THIS interface, fix it, then measure. Don't optimize what isn't slow.
-
-## Assess Performance Issues
-
-Understand current performance and identify problems:
-
-1. **Measure current state**:
- - **Core Web Vitals**: LCP, FID/INP, CLS scores
- - **Load time**: Time to interactive, first contentful paint
- - **Bundle size**: JavaScript, CSS, image sizes
- - **Runtime performance**: Frame rate, memory usage, CPU usage
- - **Network**: Request count, payload sizes, waterfall
-
-2. **Identify bottlenecks**:
- - What's slow? (Initial load? Interactions? Animations?)
- - What's causing it? (Large images? Expensive JavaScript? Layout thrashing?)
- - How bad is it? (Perceivable? Annoying? Blocking?)
- - Who's affected? (All users? Mobile only? Slow connections?)
-
-**CRITICAL**: Measure before and after. Premature optimization wastes time. Optimize what actually matters.
-
-## Optimization Strategy
-
-Create systematic improvement plan:
-
-### Loading Performance
-
-**Optimize Images**:
-- Use modern formats (WebP, AVIF)
-- Proper sizing (don't load 3000px image for 300px display)
-- Lazy loading for below-fold images
-- Responsive images (`srcset`, `picture` element)
-- Compress images (80-85% quality is usually imperceptible)
-- Use CDN for faster delivery
-
-```html
-<img
- src="hero.webp"
- srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
- sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
- loading="lazy"
- alt="Hero image"
-/>
-```
-
-**Reduce JavaScript Bundle**:
-- Code splitting (route-based, component-based)
-- Tree shaking (remove unused code)
-- Remove unused dependencies
-- Lazy load non-critical code
-- Use dynamic imports for large components
-
-```javascript
-// Lazy load heavy component
-const HeavyChart = lazy(() => import('./HeavyChart'));
-```
-
-**Optimize CSS**:
-- Remove unused CSS
-- Critical CSS inline, rest async
-- Minimize CSS files
-- Use CSS containment for independent regions
-
-**Optimize Fonts**:
-- Use `font-display: swap` or `optional`
-- Subset fonts (only characters you need)
-- Preload critical fonts
-- Use system fonts when appropriate
-- Limit font weights loaded
-
-```css
-@font-face {
- font-family: 'CustomFont';
- src: url('/fonts/custom.woff2') format('woff2');
- font-display: swap; /* Show fallback immediately */
- unicode-range: U+0020-007F; /* Basic Latin only */
-}
-```
-
-**Optimize Loading Strategy**:
-- Critical resources first (async/defer non-critical)
-- Preload critical assets
-- Prefetch likely next pages
-- Service worker for offline/caching
-- HTTP/2 or HTTP/3 for multiplexing
-
-### Rendering Performance
-
-**Avoid Layout Thrashing**:
-```javascript
-// ❌ Bad: Alternating reads and writes (causes reflows)
-elements.forEach(el => {
- const height = el.offsetHeight; // Read (forces layout)
- el.style.height = height * 2; // Write
-});
-
-// ✅ Good: Batch reads, then batch writes
-const heights = elements.map(el => el.offsetHeight); // All reads
-elements.forEach((el, i) => {
- el.style.height = heights[i] * 2; // All writes
-});
-```
-
-**Optimize Rendering**:
-- Use CSS `contain` property for independent regions
-- Minimize DOM depth (flatter is faster)
-- Reduce DOM size (fewer elements)
-- Use `content-visibility: auto` for long lists
-- Virtual scrolling for very long lists (react-window, react-virtualized)
-
-**Reduce Paint & Composite**:
-- Use `transform` and `opacity` for reliable movement, but allow blur, filters, masks, clip paths, shadows, and color shifts when they create meaningful polish
-- Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- Use `will-change` sparingly for known expensive operations
-- Bound expensive paint areas for blur/filter/shadow effects (smaller and isolated is faster)
-
-### Animation Performance
-
-**GPU Acceleration**:
-```css
-/* ✅ GPU-accelerated (fast) */
-.animated {
- transform: translateX(100px);
- opacity: 0.5;
-}
-
-/* ❌ CPU-bound (slow) */
-.animated {
- left: 100px;
- width: 300px;
-}
-```
-
-**Smooth 60fps**:
-- Target 16ms per frame (60fps)
-- Use `requestAnimationFrame` for JS animations
-- Debounce/throttle scroll handlers
-- Use CSS animations when possible
-- Avoid long-running JavaScript during animations
-
-**Intersection Observer**:
-```javascript
-// Efficiently detect when elements enter viewport
-const observer = new IntersectionObserver((entries) => {
- entries.forEach(entry => {
- if (entry.isIntersecting) {
- // Element is visible, lazy load or animate
- }
- });
-});
-```
-
-### React/Framework Optimization
-
-**React-specific**:
-- Use `memo()` for expensive components
-- `useMemo()` and `useCallback()` for expensive computations
-- Virtualize long lists
-- Code split routes
-- Avoid inline function creation in render
-- Use React DevTools Profiler
-
-**Framework-agnostic**:
-- Minimize re-renders
-- Debounce expensive operations
-- Memoize computed values
-- Lazy load routes and components
-
-### Network Optimization
-
-**Reduce Requests**:
-- Combine small files
-- Use SVG sprites for icons
-- Inline small critical assets
-- Remove unused third-party scripts
-
-**Optimize APIs**:
-- Use pagination (don't load everything)
-- GraphQL to request only needed fields
-- Response compression (gzip, brotli)
-- HTTP caching headers
-- CDN for static assets
-
-**Optimize for Slow Connections**:
-- Adaptive loading based on connection (navigator.connection)
-- Optimistic UI updates
-- Request prioritization
-- Progressive enhancement
-
-## Core Web Vitals Optimization
-
-### Largest Contentful Paint (LCP < 2.5s)
-- Optimize hero images
-- Inline critical CSS
-- Preload key resources
-- Use CDN
-- Server-side rendering
-
-### First Input Delay (FID < 100ms) / INP (< 200ms)
-- Break up long tasks
-- Defer non-critical JavaScript
-- Use web workers for heavy computation
-- Reduce JavaScript execution time
-
-### Cumulative Layout Shift (CLS < 0.1)
-- Set dimensions on images and videos
-- Don't inject content above existing content
-- Use `aspect-ratio` CSS property
-- Reserve space for ads/embeds
-- Avoid animations that cause layout shifts
-
-```css
-/* Reserve space for image */
-.image-container {
- aspect-ratio: 16 / 9;
-}
-```
-
-## Performance Monitoring
-
-**Tools to use**:
-- Chrome DevTools (Lighthouse, Performance panel)
-- WebPageTest
-- Core Web Vitals (Chrome UX Report)
-- Bundle analyzers (webpack-bundle-analyzer)
-- Performance monitoring (Sentry, DataDog, New Relic)
-
-**Key metrics**:
-- LCP, FID/INP, CLS (Core Web Vitals)
-- Time to Interactive (TTI)
-- First Contentful Paint (FCP)
-- Total Blocking Time (TBT)
-- Bundle size
-- Request count
-
-**IMPORTANT**: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.
-
-**NEVER**:
-- Optimize without measuring (premature optimization)
-- Sacrifice accessibility for performance
-- Break functionality while optimizing
-- Use `will-change` everywhere (creates new layers, uses memory)
-- Lazy load above-fold content
-- Optimize micro-optimizations while ignoring major issues (optimize the biggest bottleneck first)
-- Forget about mobile performance (often slower devices, slower connections)
-
-## Verify Improvements
-
-Test that optimizations worked:
-
-- **Before/after metrics**: Compare Lighthouse scores
-- **Real user monitoring**: Track improvements for real users
-- **Different devices**: Test on low-end Android, not just flagship iPhone
-- **Slow connections**: Throttle to 3G, test experience
-- **No regressions**: Ensure functionality still works
-- **User perception**: Does it *feel* faster?
-
-When the user-facing numbers move, hand off to `$impeccable polish` for the final pass.
@@ -1,130 +0,0 @@
-Start your response with:
-
-```
-──────────── ⚡ OVERDRIVE ─────────────
-》》》 Entering overdrive mode...
-```
-
-Push an interface past conventional limits. This isn't just about visual effects. It's about using the full power of the browser to make any part of an interface feel extraordinary: a table that handles a million rows, a dialog that morphs from its trigger, a form that validates in real-time with streaming feedback, a page transition that feels cinematic.
-
-**EXTRA IMPORTANT FOR THIS COMMAND**: Context determines what "extraordinary" means. A particle system on a creative portfolio is impressive. The same particle system on a settings page is embarrassing. But a settings page with instant optimistic saves and animated state transitions? That's extraordinary too. Understand the project's personality and goals before deciding what's appropriate.
-
-### Propose Before Building
-
-This command has the highest potential to misfire. Do NOT jump straight into implementation. You MUST:
-
-1. **Think through 2-3 different directions**: consider different techniques, levels of ambition, and aesthetic approaches. For each direction, briefly describe what the result would look and feel like.
-2. **STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer.** to present these directions and get the user's pick before writing any code. Explain trade-offs (browser support, performance cost, complexity).
-3. Only proceed with the direction the user confirms.
-
-Skipping this step risks building something embarrassing that needs to be thrown away.
-
-### Iterate with Browser Automation
-
-Technically ambitious effects almost never work on the first try. You MUST actively use browser automation tools to preview your work, visually verify the result, and iterate. Do not assume the effect looks right, check it. Expect multiple rounds of refinement. The gap between "technically works" and "looks extraordinary" is closed through visual iteration, not code alone.
-
----
-
-## Assess What "Extraordinary" Means Here
-
-The right kind of technical ambition depends entirely on what you're working with. Before choosing a technique, ask: **what would make a user of THIS specific interface say "wow, that's nice"?**
-
-### For visual/marketing surfaces
-Pages, hero sections, landing pages, portfolios: the "wow" is often sensory: a scroll-driven reveal, a shader background, a cinematic page transition, generative art that responds to the cursor.
-
-### For functional UI
-Tables, forms, dialogs, navigation: the "wow" is in how it FEELS: a dialog that morphs from the button that triggered it via View Transitions, a data table that renders 100k rows at 60fps via virtual scrolling, a form with streaming validation that feels instant, drag-and-drop with spring physics.
-
-### For performance-critical UI
-The "wow" is invisible but felt: a search that filters 50k items without a flicker, a complex form that never blocks the main thread, an image editor that processes in near-real-time. The interface just never hesitates.
-
-### For data-heavy interfaces
-Charts and dashboards: the "wow" is in fluidity: GPU-accelerated rendering via Canvas/WebGL for massive datasets, animated transitions between data states, force-directed graph layouts that settle naturally.
-
-**The common thread**: something about the implementation goes beyond what users expect from a web interface. The technique serves the experience, not the other way around.
-
-## The Toolkit
-
-Organized by what you're trying to achieve, not by technology name.
-
-### Make transitions feel cinematic
-- **View Transitions API** (same-document: all browsers; cross-document: no Firefox): shared element morphing between states. A list item expanding into a detail page. A button morphing into a dialog. This is the closest thing to native FLIP animations.
-- **`@starting-style`** (all browsers): animate elements from `display: none` to visible with CSS only, including entry keyframes
-- **Spring physics**: natural motion with mass, tension, and damping instead of cubic-bezier. Libraries: motion (formerly Framer Motion), GSAP, or roll your own spring solver.
-
-### Tie animation to scroll position
-- **Scroll-driven animations** (`animation-timeline: scroll()`): CSS-only, no JS. Parallax, progress bars, reveal sequences all driven by scroll position. (Chrome/Edge/Safari; Firefox: flag only; always provide a static fallback)
-
-### Render beyond CSS
-- **WebGL** (all browsers): shader effects, post-processing, particle systems. Libraries: Three.js, OGL (lightweight), regl. Use for effects CSS can't express.
-- **WebGPU** (Chrome/Edge; Safari partial; Firefox: flag only): next-gen GPU compute. More powerful than WebGL but limited browser support. Always fall back to WebGL2.
-- **Canvas 2D / OffscreenCanvas**: custom rendering, pixel manipulation, or moving heavy rendering off the main thread entirely via Web Workers + OffscreenCanvas.
-- **SVG filter chains**: displacement maps, turbulence, morphology for organic distortion effects. CSS-animatable.
-
-### Make data feel alive
-- **Virtual scrolling**: render only visible rows for tables/lists with tens of thousands of items. No library required for simple cases; TanStack Virtual for complex ones.
-- **GPU-accelerated charts**: Canvas or WebGL-rendered data visualization for datasets too large for SVG/DOM. Libraries: deck.gl, regl-based custom renderers.
-- **Animated data transitions**: morph between chart states rather than replacing. D3's `transition()` or View Transitions for DOM-based charts.
-
-### Animate complex properties
-- **`@property`** (all browsers): register custom CSS properties with types, enabling animation of gradients, colors, and complex values that CSS can't normally interpolate.
-- **Web Animations API** (all browsers): JavaScript-driven animations with the performance of CSS. Composable, cancellable, reversible. The foundation for complex choreography.
-
-### Push performance boundaries
-- **Web Workers**: move computation off the main thread. Heavy data processing, image manipulation, search indexing: anything that would cause jank.
-- **OffscreenCanvas**: render in a Worker thread. The main thread stays free while complex visuals render in the background.
-- **WASM**: near-native performance for computation-heavy features. Image processing, physics simulations, codecs.
-
-### Interact with the device
-- **Web Audio API**: spatial audio, audio-reactive visualizations, sonic feedback. Requires user gesture to start.
-- **Device APIs**: orientation, ambient light, geolocation. Use sparingly and always with user permission.
-
-**NOTE**: This command is about enhancing how an interface FEELS, not changing what a product DOES. Adding real-time collaboration, offline support, or new backend capabilities are product decisions, not UI enhancements. Focus on making existing features feel extraordinary.
-
-## Implement with Discipline
-
-### Progressive enhancement is non-negotiable
-
-Every technique must degrade gracefully. The experience without the enhancement must still be good.
-
-```css
-@supports (animation-timeline: scroll()) {
- .hero { animation-timeline: scroll(); }
-}
-```
-
-```javascript
-if ('gpu' in navigator) { /* WebGPU */ }
-else if (canvas.getContext('webgl2')) { /* WebGL2 fallback */ }
-/* CSS-only fallback must still look good */
-```
-
-### Performance rules
-
-- Target 60fps. If dropping below 50, simplify.
-- Respect `prefers-reduced-motion`, always. Provide a beautiful static alternative.
-- Lazy-initialize heavy resources (WebGL contexts, WASM modules) only when near viewport.
-- Pause off-screen rendering. Kill what you can't see.
-- Test on real mid-range devices, not just your development machine.
-
-### Polish is the difference
-
-The gap between "cool" and "extraordinary" is in the last 20% of refinement: the easing curve on a spring animation, the timing offset in a staggered reveal, the subtle secondary motion that makes a transition feel physical. Don't ship the first version that works; ship the version that feels inevitable.
-
-**NEVER**:
-- Ignore `prefers-reduced-motion`. This is an accessibility requirement, not a suggestion
-- Ship effects that cause jank on mid-range devices
-- Use bleeding-edge APIs without a functional fallback
-- Add sound without explicit user opt-in
-- Use technical ambition to mask weak design fundamentals; fix those first with other commands
-- Layer multiple competing extraordinary moments. Focus creates impact, excess creates noise
-
-## Verify the Result
-
-- **The wow test**: Show it to someone who hasn't seen it. Do they react?
-- **The removal test**: Take it away. Does the experience feel diminished, or does nobody notice?
-- **The device test**: Run it on a phone, a tablet, a Chromebook. Still smooth?
-- **The accessibility test**: Enable reduced motion. Still beautiful?
-- **The context test**: Does this make sense for THIS brand and audience?
-
-"Technically extraordinary" isn't about using the newest API. It's about making an interface do something users didn't think a website could do.
@@ -1,179 +0,0 @@
-# Persona-Based Design Testing
-
-Test the interface through the eyes of 5 distinct user archetypes. Each persona exposes different failure modes that a single "design director" perspective would miss.
-
-**How to use**: Select 2–3 personas most relevant to the interface being critiqued. Walk through the primary user action as each persona. Report specific red flags, not generic concerns.
-
----
-
-## 1. Impatient Power User: "Alex"
-
-
-**Profile**: Expert with similar products. Expects efficiency, hates hand-holding. Will find shortcuts or leave.
-
-**Behaviors**:
-- Skips all onboarding and instructions
-- Looks for keyboard shortcuts immediately
-- Tries to bulk-select, batch-edit, and automate
-- Gets frustrated by required steps that feel unnecessary
-- Abandons if anything feels slow or patronizing
-
-**Test Questions**:
-- Can Alex complete the core task in under 60 seconds?
-- Are there keyboard shortcuts for common actions?
-- Can onboarding be skipped entirely?
-- Do modals have keyboard dismiss (Esc)?
-- Is there a "power user" path (shortcuts, bulk actions)?
-
-**Red Flags** (report these specifically):
-- Forced tutorials or unskippable onboarding
-- No keyboard navigation for primary actions
-- Slow animations that can't be skipped
-- One-item-at-a-time workflows where batch would be natural
-- Redundant confirmation steps for low-risk actions
-
----
-
-## 2. Confused First-Timer: "Jordan"
-
-**Profile**: Never used this type of product. Needs guidance at every step. Will abandon rather than figure it out.
-
-**Behaviors**:
-- Reads all instructions carefully
-- Hesitates before clicking anything unfamiliar
-- Looks for help or support constantly
-- Misunderstands jargon and abbreviations
-- Takes the most literal interpretation of any label
-
-**Test Questions**:
-- Is the first action obviously clear within 5 seconds?
-- Are all icons labeled with text?
-- Is there contextual help at decision points?
-- Does terminology assume prior knowledge?
-- Is there a clear "back" or "undo" at every step?
-
-**Red Flags** (report these specifically):
-- Icon-only navigation with no labels
-- Technical jargon without explanation
-- No visible help option or guidance
-- Ambiguous next steps after completing an action
-- No confirmation that an action succeeded
-
----
-
-## 3. Accessibility-Dependent User: "Sam"
-
-**Profile**: Uses screen reader (VoiceOver/NVDA), keyboard-only navigation. May have low vision, motor impairment, or cognitive differences.
-
-**Behaviors**:
-- Tabs through the interface linearly
-- Relies on ARIA labels and heading structure
-- Cannot see hover states or visual-only indicators
-- Needs adequate color contrast (4.5:1 minimum)
-- May use browser zoom up to 200%
-
-**Test Questions**:
-- Can the entire primary flow be completed keyboard-only?
-- Are all interactive elements focusable with visible focus indicators?
-- Do images have meaningful alt text?
-- Is color contrast WCAG AA compliant (4.5:1 for text)?
-- Does the screen reader announce state changes (loading, success, errors)?
-
-**Red Flags** (report these specifically):
-- Click-only interactions with no keyboard alternative
-- Missing or invisible focus indicators
-- Meaning conveyed by color alone (red = error, green = success)
-- Unlabeled form fields or buttons
-- Time-limited actions without extension option
-- Custom components that break screen reader flow
-
----
-
-## 4. Deliberate Stress Tester: "Riley"
-
-**Profile**: Methodical user who pushes interfaces beyond the happy path. Tests edge cases, tries unexpected inputs, and probes for gaps in the experience.
-
-**Behaviors**:
-- Tests edge cases intentionally (empty states, long strings, special characters)
-- Submits forms with unexpected data (emoji, RTL text, very long values)
-- Tries to break workflows by navigating backwards, refreshing mid-flow, or opening in multiple tabs
-- Looks for inconsistencies between what the UI promises and what actually happens
-- Documents problems methodically
-
-**Test Questions**:
-- What happens at the edges (0 items, 1000 items, very long text)?
-- Do error states recover gracefully or leave the UI in a broken state?
-- What happens on refresh mid-workflow? Is state preserved?
-- Are there features that appear to work but produce broken results?
-- How does the UI handle unexpected input (emoji, special chars, paste from Excel)?
-
-**Red Flags** (report these specifically):
-- Features that appear to work but silently fail or produce wrong results
-- Error handling that exposes technical details or leaves UI in a broken state
-- Empty states that show nothing useful ("No results" with no guidance)
-- Workflows that lose user data on refresh or navigation
-- Inconsistent behavior between similar interactions in different parts of the UI
-
----
-
-## 5. Distracted Mobile User: "Casey"
-
-**Profile**: Using phone one-handed on the go. Frequently interrupted. Possibly on a slow connection.
-
-**Behaviors**:
-- Uses thumb only; prefers bottom-of-screen actions
-- Gets interrupted mid-flow and returns later
-- Switches between apps frequently
-- Has limited attention span and low patience
-- Types as little as possible, prefers taps and selections
-
-**Test Questions**:
-- Are primary actions in the thumb zone (bottom half of screen)?
-- Is state preserved if the user leaves and returns?
-- Does it work on slow connections (3G)?
-- Can forms use autocomplete and smart defaults?
-- Are touch targets at least 44×44pt?
-
-**Red Flags** (report these specifically):
-- Important actions positioned at the top of the screen (unreachable by thumb)
-- No state persistence; progress lost on tab switch or interruption
-- Large text inputs required where selection would work
-- Heavy assets loading on every page (no lazy loading)
-- Tiny tap targets or targets too close together
-
----
-
-## Selecting Personas
-
-Choose personas based on the interface type:
-
-| Interface Type | Primary Personas | Why |
-|---------------|-----------------|-----|
-| Landing page / marketing | Jordan, Riley, Casey | First impressions, trust, mobile |
-| Dashboard / admin | Alex, Sam | Power users, accessibility |
-| E-commerce / checkout | Casey, Riley, Jordan | Mobile, edge cases, clarity |
-| Onboarding flow | Jordan, Casey | Confusion, interruption |
-| Data-heavy / analytics | Alex, Sam | Efficiency, keyboard nav |
-| Form-heavy / wizard | Jordan, Sam, Casey | Clarity, accessibility, mobile |
-
----
-
-## Project-Specific Personas
-
-If `AGENTS.md` contains a `## Design Context` section (generated by `impeccable teach`), derive 1–2 additional personas from the audience and brand information:
-
-1. Read the target audience description
-2. Identify the primary user archetype not covered by the 5 predefined personas
-3. Create a persona following this template:
-
-```
-### [Role]: "[Name]"
-
-**Profile**: [2-3 key characteristics derived from Design Context]
-
-**Behaviors**: [3-4 specific behaviors based on the described audience]
-
-**Red Flags**: [3-4 things that would alienate this specific user type]
-```
-
-Only generate project-specific personas when real Design Context data is available. Don't invent audience details; use the 5 predefined personas when no context exists.
@@ -1,242 +0,0 @@
-> **Additional context needed**: quality bar (MVP vs flagship).
-
-Perform a meticulous final pass to catch all the small details that separate good work from great work. The difference between shipped and polished.
-
-Detector and automated QA output are defect evidence only. A clean script result is never proof that the design is strong; gather browser evidence and inspect the real interaction path.
-
-## Design System Discovery
-
-Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
-
-1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
-2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
-3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category: patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
-
-If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask. Never guess at design system principles.**
-
-## Pre-Polish Assessment
-
-Understand the current state and goals before touching anything:
-
-1. **Review completeness**:
- - Is it functionally complete?
- - Are there known issues to preserve (mark with TODOs)?
- - What's the quality bar? (MVP vs flagship feature?)
- - When does it ship? (How much time for polish?)
-
-2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish; a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
-
-3. **Identify polish areas**:
- - Visual inconsistencies
- - Spacing and alignment issues
- - Interaction state gaps
- - Copy inconsistencies
- - Edge cases and error states
- - Loading and transition smoothness
- - Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
-
-4. **Pull in any prior critique** (optional signal): If `$impeccable critique` has been run on the same target, its priority issues are a useful prior for what to address first. Resolve the target to a file path or URL, then:
- ```bash
- slug=$(node .agents/skills/impeccable/scripts/critique-storage.mjs slug "<resolved>")
- node .agents/skills/impeccable/scripts/critique-storage.mjs latest "$slug"
- ```
- Exit 0 with body = found; fold the P0/P1 items into your polish list and mention the snapshot path so the user sees what you read. Exit 2 = no snapshot, continue without it. The critique is one input among many. Do your own pass either way.
-
-5. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent; never perfect one corner while leaving another rough.
-
-**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
-
-## Polish Systematically
-
-Work through these dimensions methodically:
-
-### Visual Alignment & Spacing
-
-- **Pixel-perfect alignment**: Everything lines up to grid
-- **Consistent spacing**: All gaps use spacing scale (no random 13px gaps)
-- **Optical alignment**: Adjust for visual weight (icons may need offset for optical centering)
-- **Responsive consistency**: Spacing and alignment work at all breakpoints
-- **Grid adherence**: Elements snap to baseline grid
-
-**Check**:
-- Enable grid overlay and verify alignment
-- Check spacing with browser inspector
-- Test at multiple viewport sizes
-- Look for elements that "feel" off
-
-### Information Architecture & Flow
-
-Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
-
-- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
-- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere: modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
-- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
-- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
-- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
-
-### Typography Refinement
-
-- **Hierarchy consistency**: Same elements use same sizes/weights throughout
-- **Line length**: 45-75 characters for body text
-- **Line height**: Appropriate for font size and context
-- **Widows & orphans**: No single words on last line
-- **Hyphenation**: Appropriate for language and column width
-- **Kerning**: Adjust letter spacing where needed (especially headlines)
-- **Font loading**: No FOUT/FOIT flashes
-
-### Color & Contrast
-
-- **Contrast ratios**: All text meets WCAG standards
-- **Consistent token usage**: No hard-coded colors, all use design tokens
-- **Theme consistency**: Works in all theme variants
-- **Color meaning**: Same colors mean same things throughout
-- **Accessible focus**: Focus indicators visible with sufficient contrast
-- **Tinted neutrals**: No pure gray or pure black; add subtle color tint (0.01 chroma)
-- **Gray on color**: Never put gray text on colored backgrounds; use a shade of that color or transparency
-
-### Interaction States
-
-Every interactive element needs all states:
-
-- **Default**: Resting state
-- **Hover**: Subtle feedback (color, scale, shadow)
-- **Focus**: Keyboard focus indicator (never remove without replacement)
-- **Active**: Click/tap feedback
-- **Disabled**: Clearly non-interactive
-- **Loading**: Async action feedback
-- **Error**: Validation or error state
-- **Success**: Successful completion
-
-**Missing states create confusion and broken experiences**.
-
-### Micro-interactions & Transitions
-
-- **Smooth transitions**: All state changes animated appropriately (150-300ms)
-- **Consistent easing**: Use ease-out-quart/quint/expo for natural deceleration. Never bounce or elastic; they feel dated.
-- **No jank**: Smooth animations; use atmospheric blur/filter/mask/shadow effects when they add polish, but bound expensive paint areas and avoid casual layout-property animation
-- **Appropriate motion**: Motion serves purpose, not decoration
-- **Reduced motion**: Respects `prefers-reduced-motion`
-
-### Content & Copy
-
-- **Consistent terminology**: Same things called same names throughout
-- **Consistent capitalization**: Title Case vs Sentence case applied consistently
-- **Grammar & spelling**: No typos
-- **Appropriate length**: Not too wordy, not too terse
-- **Punctuation consistency**: Periods on sentences, not on labels (unless all labels have them)
-
-### Icons & Images
-
-- **Consistent style**: All icons from same family or matching style
-- **Appropriate sizing**: Icons sized consistently for context
-- **Proper alignment**: Icons align with adjacent text optically
-- **Alt text**: All images have descriptive alt text
-- **Loading states**: Images don't cause layout shift, proper aspect ratios
-- **Retina support**: 2x assets for high-DPI screens
-
-### Forms & Inputs
-
-- **Label consistency**: All inputs properly labeled
-- **Required indicators**: Clear and consistent
-- **Error messages**: Helpful and consistent
-- **Tab order**: Logical keyboard navigation
-- **Auto-focus**: Appropriate (don't overuse)
-- **Validation timing**: Consistent (on blur vs on submit)
-
-### Edge Cases & Error States
-
-- **Loading states**: All async actions have loading feedback
-- **Empty states**: Helpful empty states, not just blank space
-- **Error states**: Clear error messages with recovery paths
-- **Success states**: Confirmation of successful actions
-- **Long content**: Handles very long names, descriptions, etc.
-- **No content**: Handles missing data gracefully
-- **Offline**: Appropriate offline handling (if applicable)
-
-### Responsiveness
-
-- **All breakpoints**: Test mobile, tablet, desktop
-- **Touch targets**: 44x44px minimum on touch devices
-- **Readable text**: No text smaller than 14px on mobile
-- **No horizontal scroll**: Content fits viewport
-- **Appropriate reflow**: Content adapts logically
-
-### Performance
-
-- **Fast initial load**: Optimize critical path
-- **No layout shift**: Elements don't jump after load (CLS)
-- **Smooth interactions**: No lag or jank
-- **Optimized images**: Appropriate formats and sizes
-- **Lazy loading**: Off-screen content loads lazily
-
-### Code Quality
-
-- **Remove console logs**: No debug logging in production
-- **Remove commented code**: Clean up dead code
-- **Remove unused imports**: Clean up unused dependencies
-- **Consistent naming**: Variables and functions follow conventions
-- **Type safety**: No TypeScript `any` or ignored errors
-- **Accessibility**: Proper ARIA labels and semantic HTML
-
-## Polish Checklist
-
-Go through systematically:
-
-- [ ] Aligned to the design system (drift named and resolved by root cause)
-- [ ] Information architecture and flow shape match neighboring features
-- [ ] Visual alignment perfect at all breakpoints
-- [ ] Spacing uses design tokens consistently
-- [ ] Typography hierarchy consistent
-- [ ] All interactive states implemented
-- [ ] All transitions smooth (60fps)
-- [ ] Copy is consistent and polished
-- [ ] Icons are consistent and properly sized
-- [ ] All forms properly labeled and validated
-- [ ] Error states are helpful
-- [ ] Loading states are clear
-- [ ] Empty states are welcoming
-- [ ] Touch targets are 44x44px minimum
-- [ ] Contrast ratios meet WCAG AA
-- [ ] Keyboard navigation works
-- [ ] Focus indicators visible
-- [ ] No console errors or warnings
-- [ ] No layout shift on load
-- [ ] Works in all supported browsers
-- [ ] Respects reduced motion preference
-- [ ] Code is clean (no TODOs, console.logs, commented code)
-
-**IMPORTANT**: Polish is about details. Zoom in. Squint at it. Use it yourself. The little things add up.
-
-Sweat the details. Zoom in until the alignment is right and the spacing reads as deliberate. Then ship.
-
-**NEVER**:
-- Polish before it's functionally complete
-- Polish without aligning to the design system; that's decoration on drift
-- Guess at design system principles instead of asking when something is ambiguous
-- Spend hours on polish if it ships in 30 minutes (triage)
-- Introduce bugs while polishing (test thoroughly)
-- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
-- Perfect one thing while leaving others rough (consistent quality level)
-- Create new one-off components when design system equivalents exist
-- Hard-code values that should use design tokens
-- Introduce new patterns or flows that diverge from established ones
-
-## Final Verification
-
-Before marking as done:
-
-- **Use it yourself**: Actually interact with the feature.
-- **Test on real devices**: Not just browser DevTools.
-- **Ask someone else to review**: Fresh eyes catch things.
-- **Compare to design**: Match intended design.
-- **Check all states**: Don't just test happy path.
-- **Treat automation carefully**: Run detector or QA commands when they are available and relevant, fix their defects, but never cite a clean result as proof that the work is polished.
-
-## Clean Up
-
-After polishing, ensure code quality:
-
-- **Replace custom implementations**: If the design system provides a component you reimplemented, switch to the shared version.
-- **Remove orphaned code**: Delete unused styles, components, or files made obsolete by polish.
-- **Consolidate tokens**: If you introduced new values, check whether they should be tokens.
-- **Verify DRYness**: Look for duplication introduced during polishing and consolidate.
@@ -1,62 +0,0 @@
-# Product register
-
-When design SERVES the product: app UIs, admin dashboards, settings panels, data tables, tools, authenticated surfaces, anything where the user is in a task.
-
-## The product slop test
-
-Not "would someone say AI made this." Familiarity is often a feature here. The test is: would a user fluent in the category's best tools (Linear, Figma, Notion, Raycast, Stripe come to mind) sit down and trust this interface, or pause at every subtly-off component?
-
-Product UI's failure mode isn't flatness, it's strangeness without purpose: over-decorated buttons, mismatched form controls, gratuitous motion, display fonts where labels should be, invented affordances for standard tasks. The bar is earned familiarity. The tool should disappear into the task.
-
-## Typography
-
-- **System fonts are legitimate.** `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` gives you native feel on every platform. Inter is the common cross-platform default for a reason.
-- **One family is often right.** Product UIs don't need display/body pairing. A well-tuned sans carries headings, buttons, labels, body, data.
-- **Fixed rem scale, not fluid.** Clamp-sized headings don't serve product UI. Users view at consistent DPI, and a fluid h1 that shrinks in a sidebar looks worse, not better.
-- **Tighter scale ratio.** 1.125–1.2 between steps is typical. More type elements here than on brand surfaces; exaggerated contrast creates noise.
-- **Line length still applies for prose** (65–75ch). Data and compact UI can run denser; tables at 120ch+ are fine.
-
-## Color
-
-Product defaults to Restrained. A single surface can earn Committed (a dashboard where one category color carries a report, an onboarding flow with a drenched welcome screen), but Restrained is the floor.
-
-- State-rich semantic vocabulary: hover, focus, active, disabled, selected, loading, error, warning, success, info. Standardize these.
-- Accent color used for primary actions, current selection, and state indicators only, not decoration.
-- A second neutral layer for sidebars, toolbars, and panels (slightly cooler or warmer than the content surface).
-
-## Layout
-
-- Predictable grids. Consistency IS an affordance; users navigate faster when the structure is expected.
-- Familiar patterns are features. Standard navigation (top bar, side nav), breadcrumbs, tabs, and form layouts have established user expectations. Don't reinvent for flavor.
-- Responsive behavior is structural (collapse sidebar, responsive table, breakpoint-driven columns), not fluid typography.
-
-## Components
-
-Every interactive component has: default, hover, focus, active, disabled, loading, error. Don't ship with half of these.
-
-- Skeleton states for loading, not spinners in the middle of content.
-- Empty states that teach the interface, not "nothing here."
-- Consistent affordances across the surface. Same button shape. Same form-control vocabulary. Same icon style.
-
-## Motion
-
-- 150–250 ms on most transitions. Users are in flow; don't make them wait for choreography.
-- Motion conveys state, not decoration. State change, feedback, loading, reveal: nothing else.
-- No orchestrated page-load sequences. Product loads into a task; users don't want to watch it load.
-
-## Product bans (on top of the shared absolute bans)
-
-- Decorative motion that doesn't convey state.
-- Inconsistent component vocabulary across screens. If the "save" button looks different in two places, one is wrong.
-- Display fonts in UI labels, buttons, data.
-- Reinventing standard affordances for flavor (custom scrollbars, weird form controls, non-standard modals).
-- Heavy color or full-saturation accents on inactive states.
-
-## Product permissions
-
-Product can afford things brand surfaces can't.
-
-- System fonts and familiar sans defaults (Inter, SF Pro, system-ui stacks).
-- Standard navigation patterns: top bar + side nav, breadcrumbs, tabs, command palettes.
-- Density. Tables with many rows, panels with many labels, dense information when users need it.
-- Consistency over surprise. The same visual vocabulary screen to screen is a virtue; delight is saved for moments, not pages.
@@ -1,99 +0,0 @@
-Quiet design is harder than bold design. Subtlety needs precision. Reduce visual intensity in designs that are too loud, aggressive, or overstimulating without losing personality or making the result generic.
-
----
-
-## Register
-
-Brand: "quieter" means more restrained palette, more whitespace, more typographic air. Drama is reduced, not eliminated; the POV stays intact.
-
-Product: "quieter" means reducing visual noise. Fewer background accents, flatter cards, less color, less motion. The tool should disappear more completely into the task.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too intense:
-
-1. **Identify intensity sources**:
- - **Color saturation**: Overly bright or saturated colors
- - **Contrast extremes**: Too much high-contrast juxtaposition
- - **Visual weight**: Too many bold, heavy elements competing
- - **Animation excess**: Too much motion or overly dramatic effects
- - **Complexity**: Too many visual elements, patterns, or decorations
- - **Scale**: Everything is large and loud with no hierarchy
-
-2. **Understand the context**:
- - What's the purpose? (Marketing vs tool vs reading experience)
- - Who's the audience? (Some contexts need energy)
- - What's working? (Don't throw away good ideas)
- - What's the core message? (Preserve what matters)
-
-If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer.
-
-**CRITICAL**: "Quieter" doesn't mean boring or generic. It means refined and easier on the eyes. Think luxury, not laziness.
-
-## Plan Refinement
-
-Create a strategy to reduce intensity while maintaining impact:
-
-- **Color approach**: Desaturate or shift to more restrained tones?
-- **Hierarchy approach**: Which elements should stay bold (very few), which should recede?
-- **Simplification approach**: What can be removed entirely?
-- **Sophistication approach**: How can we signal quality through restraint?
-
-**IMPORTANT**: Subtlety requires precision. Quiet without intent collapses to generic.
-
-## Refine the Design
-
-Systematically reduce intensity across these dimensions:
-
-### Color Refinement
-- **Reduce saturation**: Shift from fully saturated to 70-85% saturation
-- **Soften palette**: Replace bright colors with muted tones
-- **Reduce color variety**: Use fewer colors more thoughtfully
-- **Neutral dominance**: Let neutrals do more work, use color as accent (10% rule)
-- **Gentler contrasts**: High contrast only where it matters most
-- **Tinted grays**: Use warm or cool tinted grays instead of pure gray. Adds depth without loudness
-- **Never gray on color**: If you have gray text on a colored background, use a darker shade of that color or transparency instead
-
-### Visual Weight Reduction
-- **Typography**: Reduce font weights (900 → 600, 700 → 500), decrease sizes where appropriate
-- **Hierarchy through subtlety**: Use weight, size, and space instead of color and boldness
-- **White space**: Increase breathing room, reduce density
-- **Borders & lines**: Reduce thickness, decrease opacity, or remove entirely
-
-### Simplification
-- **Remove decorative elements**: Gradients, shadows, patterns, textures that don't serve purpose
-- **Simplify shapes**: Reduce border radius extremes, simplify custom shapes
-- **Reduce layering**: Flatten visual hierarchy where possible
-- **Clean up effects**: Reduce or remove blur effects, glows, multiple shadows
-
-### Motion Reduction
-- **Reduce animation intensity**: Shorter distances (10-20px instead of 40px), gentler easing
-- **Remove decorative animations**: Keep functional motion, remove flourishes
-- **Subtle micro-interactions**: Replace dramatic effects with gentle feedback
-- **Refined easing**: Use ease-out-quart for smooth, understated motion. Never bounce or elastic
-- **Remove animations entirely** if they're not serving a clear purpose
-
-### Composition Refinement
-- **Reduce scale jumps**: Smaller contrast between sizes creates calmer feeling
-- **Align to grid**: Bring rogue elements back into systematic alignment
-- **Even out spacing**: Replace extreme spacing variations with consistent rhythm
-
-**NEVER**:
-- Make everything the same size/weight (hierarchy still matters)
-- Remove all color (quiet ≠ grayscale)
-- Eliminate all personality (maintain character through refinement)
-- Sacrifice usability for aesthetics (functional elements still need clear affordances)
-- Make everything small and light (some anchors needed)
-
-## Verify Quality
-
-Ensure refinement maintains quality:
-
-- **Still functional**: Can users still accomplish tasks easily?
-- **Still distinctive**: Does it have character, or is it generic now?
-- **Better reading**: Is text easier to read for extended periods?
-- **Restrained, not absent**: Does the POV survive the cuts?
-
-When the result feels right, hand off to `$impeccable polish` for the final pass.
@@ -1,114 +0,0 @@
-# Responsive Design
-
-## Mobile-First: Write It Right
-
-Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
-
-## Breakpoints: Content-Driven
-
-Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
-
-## Detect Input Method, Not Just Screen Size
-
-**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
-
-```css
-/* Fine pointer (mouse, trackpad) */
-@media (pointer: fine) {
- .button { padding: 8px 16px; }
-}
-
-/* Coarse pointer (touch, stylus) */
-@media (pointer: coarse) {
- .button { padding: 12px 20px; } /* Larger touch target */
-}
-
-/* Device supports hover */
-@media (hover: hover) {
- .card:hover { transform: translateY(-2px); }
-}
-
-/* Device doesn't support hover (touch) */
-@media (hover: none) {
- .card { /* No hover state - use active instead */ }
-}
-```
-
-**Critical**: Don't rely on hover for functionality. Touch users can't hover.
-
-## Safe Areas: Handle the Notch
-
-Modern phones have notches, rounded corners, and home indicators. Use `env()`:
-
-```css
-body {
- padding-top: env(safe-area-inset-top);
- padding-bottom: env(safe-area-inset-bottom);
- padding-left: env(safe-area-inset-left);
- padding-right: env(safe-area-inset-right);
-}
-
-/* With fallback */
-.footer {
- padding-bottom: max(1rem, env(safe-area-inset-bottom));
-}
-```
-
-**Enable viewport-fit** in your meta tag:
-```html
-<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
-```
-
-## Responsive Images: Get It Right
-
-### srcset with Width Descriptors
-
-```html
-<img
- src="hero-800.jpg"
- srcset="
- hero-400.jpg 400w,
- hero-800.jpg 800w,
- hero-1200.jpg 1200w
- "
- sizes="(max-width: 768px) 100vw, 50vw"
- alt="Hero image"
->
-```
-
-**How it works**:
-- `srcset` lists available images with their actual widths (`w` descriptors)
-- `sizes` tells the browser how wide the image will display
-- Browser picks the best file based on viewport width AND device pixel ratio
-
-### Picture Element for Art Direction
-
-When you need different crops/compositions (not just resolutions):
-
-```html
-<picture>
- <source media="(min-width: 768px)" srcset="wide.jpg">
- <source media="(max-width: 767px)" srcset="tall.jpg">
- <img src="fallback.jpg" alt="...">
-</picture>
-```
-
-## Layout Adaptation Patterns
-
-**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
-
-## Testing: Don't Trust DevTools Alone
-
-DevTools device emulation is useful for layout but misses:
-
-- Actual touch interactions
-- Real CPU/memory constraints
-- Network latency patterns
-- Font rendering differences
-- Browser chrome/keyboard appearances
-
-**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
-
----
-
-**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
@@ -1,165 +0,0 @@
-Shape the UX and UI for a feature before any code is written. This command produces a **design brief**: a structured artifact that guides implementation through discovery, not guesswork.
-
-**Scope**: Design planning only. This command does NOT write code. It produces the thinking that makes code good.
-
-**Output**: A design brief that can be handed off to $impeccable craft, or directly to $impeccable for freeform implementation. When visual direction probes are used, the images are supporting artifacts, not the primary output.
-
-## Philosophy
-
-Most AI-generated UIs fail not because of bad code, but because of skipped thinking. They jump to "here's a card grid" without asking "what is the user trying to accomplish?" This command inverts that: understand deeply first, so implementation is precise.
-
-## Phase 1: Discovery Interview
-
-**Do NOT write any code or make any design decisions during this phase.** Your only job is to understand the feature deeply enough to make excellent design decisions later.
-
-This is a required interaction, not optional guidance. Ask these questions in conversation, adapting based on answers. Don't dump them all at once; have a natural dialogue. STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer.
-
-### Interview cadence
-
-Discovery includes at least one user-answer round unless PRODUCT.md, DESIGN.md, or an already-confirmed brief directly answers the needed inputs. With a sparse prompt, do **not** synthesize a complete brief for confirmation on the first response.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Treat PRODUCT.md and DESIGN.md as anchors; they reduce repeated questions but do **not** replace shape for craft. Shape is task-specific.
-- One round is the default. Add a second only if the first answers leave material gaps. Don't run a second round just to feel thorough.
-- Round 1 should clarify purpose, audience/context, content/scope, and (for brand) visual direction.
-- Round 2, when needed, fills in whatever's still genuinely missing.
-
-**Assert-then-confirm, not menu-with-escape.** When PRODUCT.md and the user's prompt make one option obvious, name it and ask the user to confirm or override. Don't enumerate "Restrained / Committed / Or something else?" as a real choice; "This reads as Restrained, confirm?" beats a four-option menu when the answer is already clear.
-
-### Purpose & Context
-- What is this feature for? What problem does it solve?
-- Who specifically will use it? (Not "users"; be specific: role, context, frequency)
-- What does success look like? How will you know this feature is working?
-- What's the user's state of mind when they reach this feature? (Rushed? Exploring? Anxious? Focused?)
-
-### Content & Data
-- What content or data does this feature display or collect?
-- What are the realistic ranges? (Minimum, typical, maximum, e.g., 0 items, 5 items, 500 items)
-- What are the edge cases? (Empty state, error state, first-time use, power user)
-- Is any content dynamic? What changes and how often?
-- What visual assets are real content here? Note required images, product shots, illustrations, maps, textures, diagrams, generated objects, or existing project assets.
-
-### Design Direction
-
-Force a visual decision on three fronts. Skip anything PRODUCT.md or DESIGN.md already answers; ask only what's missing.
-
-- **Color strategy for this surface.** Pick one: Restrained / Committed / Full palette / Drenched. Can override the project default if the surface earns it (e.g. a drenched hero inside an otherwise Restrained product).
-- **Theme via scene sentence.** Write one sentence of physical context for this surface: who uses it, where, under what ambient light, in what mood. The sentence forces dark vs light. If it doesn't, add detail until it does.
-- **Two or three named anchor references.** Specific products, brands, objects. Not adjectives like "modern" or "clean."
-
-### Scope
-
-Always ask. Sketch quality and shipped quality are different outputs; don't guess between them.
-
-- **Fidelity.** Sketch / mid-fi / high-fi / production-ready?
-- **Breadth.** One screen / a flow / a whole surface?
-- **Interactivity.** Static visual / interactive prototype / shipped-quality component?
-- **Time intent.** Quick exploration, or polish until it ships?
-
-Scope answers are task-scoped. Don't write them to PRODUCT.md or DESIGN.md; carry them through the design brief only.
-
-### Constraints
-- Are there technical constraints? (Framework, performance budget, browser support)
-- Are there content constraints? (Localization, dynamic text length, user-generated content)
-- Mobile/responsive requirements?
-- Accessibility requirements beyond WCAG AA?
-
-### Anti-Goals
-- What should this NOT be? What would be a wrong direction?
-- What's the biggest risk of getting this wrong?
-
-## Phase 1.5: Visual Direction Probe (Capability-Gated)
-
-After the discovery interview, generate a small set of visual direction probes **before** writing the final brief when all of these are true:
-
-- The work is **net-new** or directionally ambiguous enough that visual exploration will clarify the brief.
-- The requested fidelity is **mid-fi, high-fi, or production-ready**. Skip for sketch-only planning.
-- The current harness gives you native image generation (Codex's `image_gen`, an equivalent MCP tool, or similar). Don't ask the user to install APIs or tooling.
-
-When those conditions are met, this step is mandatory. If image generation isn't natively available, do not ask the user to install APIs or tooling. State in one line that the image step is skipped because the harness lacks native image generation, then proceed. The one-line announcement is required, not optional; it forces a conscious decision instead of letting the step quietly evaporate.
-
-Use probes to explore visual lanes, not to replace the brief.
-
-Do not skip probes because the final UI will be semantic, editable, code-native, responsive, or accessible. Those are implementation requirements, not reasons to avoid visual exploration.
-
-### What to generate
-
-Generate **2 to 4** distinct direction probes based on the discovery answers, especially:
-
-- Color strategy
-- Theme scene sentence
-- Named anchor references
-- Scope and fidelity
-
-The probes should differ in primary visual direction (hierarchy, topology, density, typographic voice, or color strategy), not just palette tweaks.
-
-### How to use the probes
-
-- Treat them as **direction tests**, not final designs.
-- Use them to pressure-test whether the brief is pointing at the right lane.
-- Ask the user which direction feels closest, what feels off, and what should carry forward.
-- If the probes reveal a mismatch, revise the brief inputs before finalizing the brief.
-
-### Important limits
-
-- Do **not** skip discovery because image generation is available.
-- Do **not** treat generated imagery as final UX specification, final copy, or final accessibility behavior.
-- Do **not** use this step for minor refinements of existing work. It's for shaping a new surface or clarifying a big directional choice.
-
-If image generation isn't natively available, announce the skip in one line and proceed to the design brief.
-
-## Phase 2: Design Brief
-
-After the interview and any required probes, present a brief and **end your response**. The user must confirm before any implementation runs. Do not present a brief and then continue to code in the same response, even if the brief feels obvious to you. The user's confirmation is the gate.
-
-**Choose the brief shape based on how clear the answers are:**
-
-- **Compact form (3-5 bullets)** when discovery was crisp and the original prompt + PRODUCT.md already pinned scope, content, and direction. State what you're building, the visual lane, and end with one or two specific questions or a clear "confirm or override?" prompt. This is the default for typical craft requests with a clear prompt.
-- **Full structured form (sections below)** when the task is genuinely ambiguous, multi-screen, or when the user asked for shape as a standalone step. Use this when the discipline of structure earns its weight.
-
-Don't pad a clear brief into a long one to look thorough. A 70-line brief restating answers the user just gave is noise, not rigor. Equally, don't skip the confirmation pause to look efficient: the pause is the point.
-
-Present the brief, then **stop and wait for explicit confirmation**. You are not the judge of whether the user already approved. Even when the brief feels obviously right, ask once and wait. The pause is what separates shape from premature implementation.
-
-### Brief Structure
-
-**1. Feature Summary** (2-3 sentences)
-What this is, who it's for, what it needs to accomplish.
-
-**2. Primary User Action**
-The single most important thing a user should do or understand here.
-
-**3. Design Direction**
-Color strategy (Restrained / Committed / Full palette / Drenched) + the theme scene sentence + 2–3 named anchor references. Reference PRODUCT.md and DESIGN.md where they already answer, and note any per-surface overrides.
-
-If you ran the Visual Direction Probe step, name which probe direction won and what changed in the brief because of it.
-
-**4. Scope**
-Fidelity, breadth, interactivity, and time intent from the Scope section of the interview. Task-scoped; these don't persist beyond the brief.
-
-**5. Layout Strategy**
-High-level spatial approach: what gets emphasis, what's secondary, how information flows. Describe the visual hierarchy and rhythm, not specific CSS.
-
-**6. Key States**
-List every state the feature needs: default, empty, loading, error, success, edge cases. For each, note what the user needs to see and feel.
-
-**7. Interaction Model**
-How users interact with this feature. What happens on click, hover, scroll? What feedback do they get? What's the flow from entry to completion?
-
-**8. Content Requirements**
-What copy, labels, empty state messages, error messages, and microcopy are needed. Note any dynamic content and its realistic ranges. For image-led surfaces, also list the required image/media roles and their likely source (project asset, generated raster, semantic SVG/CSS, canvas/WebGL, icon library, or accepted omission).
-
-**9. Recommended References**
-Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., spatial-design.md for complex layouts, motion-design.md for animated features, interaction-design.md for form-heavy features).
-
-**10. Open Questions**
-Anything genuinely unresolved. Don't list "open questions" you've already recommended a default for; assert the default and move on. If you'd write `Recommend: X` next to a question, just decide X.
-
----
-
-STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. Ask for explicit confirmation of the brief before finishing.
-
-If the user disagrees with any part, revisit the relevant discovery questions. A shape run is incomplete until the user confirms direction.
-
-Once confirmed, the brief is complete. The user can now hand it to $impeccable, or use it to guide any other implementation approach. (If the user wants the full discovery-then-build flow in one step, they should use $impeccable craft instead, which runs this command internally.)
@@ -1,100 +0,0 @@
-# Spatial Design
-
-## Spacing Systems
-
-### Use 4pt Base, Not 8pt
-
-8pt systems are too coarse; you'll frequently need 12px (between 8 and 16). Use 4pt for granularity: 4, 8, 12, 16, 24, 32, 48, 64, 96px.
-
-### Name Tokens Semantically
-
-Name by relationship (`--space-sm`, `--space-lg`), not value (`--spacing-8`). Use `gap` instead of margins for sibling spacing; it eliminates margin collapse and cleanup hacks.
-
-## Grid Systems
-
-### The Self-Adjusting Grid
-
-Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Columns are at least 280px, as many as fit per row, leftovers stretch. For complex layouts, use named grid areas (`grid-template-areas`) and redefine them at breakpoints.
-
-## Visual Hierarchy
-
-### The Squint Test
-
-Blur your eyes (or screenshot and blur). Can you still identify:
-- The most important element?
-- The second most important?
-- Clear groupings?
-
-If everything looks the same weight blurred, you have a hierarchy problem.
-
-### Hierarchy Through Multiple Dimensions
-
-Don't rely on size alone. Combine:
-
-| Tool | Strong Hierarchy | Weak Hierarchy |
-|------|------------------|----------------|
-| **Size** | 3:1 ratio or more | <2:1 ratio |
-| **Weight** | Bold vs Regular | Medium vs Regular |
-| **Color** | High contrast | Similar tones |
-| **Position** | Top/left (primary) | Bottom/right |
-| **Space** | Surrounded by white space | Crowded |
-
-**The best hierarchy uses 2-3 dimensions at once**: A heading that's larger, bolder, AND has more space above it.
-
-### Cards Are Not Required
-
-Cards are overused. Spacing and alignment create visual grouping naturally. Use cards only when content is truly distinct and actionable, items need visual comparison in a grid, or content needs clear interaction boundaries. **Never nest cards inside cards.** Use spacing, typography, and subtle dividers for hierarchy within a card.
-
-## Container Queries
-
-Viewport queries are for page layouts. **Container queries are for components**:
-
-```css
-.card-container {
- container-type: inline-size;
-}
-
-.card {
- display: grid;
- gap: var(--space-md);
-}
-
-/* Card layout changes based on its container, not viewport */
-@container (min-width: 400px) {
- .card {
- grid-template-columns: 120px 1fr;
- }
-}
-```
-
-**Why this matters**: A card in a narrow sidebar stays compact, while the same card in a main content area expands automatically, without viewport hacks.
-
-## Optical Adjustments
-
-Text at `margin-left: 0` looks indented due to letterform whitespace; use negative margin (`-0.05em`) to optically align. Geometrically centered icons often look off-center; play icons need to shift right, arrows shift toward their direction.
-
-### Touch Targets vs Visual Size
-
-Buttons can look small but need large touch targets (44px minimum). Use padding or pseudo-elements:
-
-```css
-.icon-button {
- width: 24px; /* Visual size */
- height: 24px;
- position: relative;
-}
-
-.icon-button::before {
- content: '';
- position: absolute;
- inset: -10px; /* Expand tap target to 44px */
-}
-```
-
-## Depth & Elevation
-
-Create semantic z-index scales (dropdown → sticky → modal-backdrop → modal → toast → tooltip) instead of arbitrary numbers. For shadows, create a consistent elevation scale (sm → md → lg → xl). **Key insight**: Shadows should be subtle. If you can clearly see it, it's probably too strong.
-
----
-
-**Avoid**: Arbitrary spacing values outside your scale. Making all spacing equal (variety creates hierarchy). Creating hierarchy through size alone - combine size, weight, color, and space.
@@ -1,156 +0,0 @@
-# Teach Flow
-
-Gathers design context for a project and writes two complementary files at the project root:
-
-- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
-- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
-
-Every other impeccable command reads these files before doing any work.
-
-## Step 1: Load current state
-
-Run the shared loader first so you know what already exists:
-
-```bash
-node .agents/skills/impeccable/scripts/load-context.mjs
-```
-
-The output tells you whether PRODUCT.md and/or DESIGN.md already exist. If `migrated: true`, legacy `.impeccable.md` was auto-renamed to `PRODUCT.md`. Mention this once to the user.
-
-Decision tree:
-- **Neither file exists (empty project or no context yet)**: do Steps 2-4 (write PRODUCT.md), then decide on DESIGN.md based on whether there's code to analyze.
-- **PRODUCT.md exists, DESIGN.md missing**: skip to Step 5 and offer to run `$impeccable document` for DESIGN.md.
-- **PRODUCT.md exists but has no `## Register` section (legacy)**: add it. Infer a hypothesis from the codebase (see Step 2), confirm with the user, write the field.
-- **Both exist**: STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. Ask which file to refresh. Skip the one the user doesn't want changed.
-- **Just DESIGN.md exists (unusual)**: do Steps 2-4 to produce PRODUCT.md.
-
-Never silently overwrite an existing file. Always confirm first.
-
-If teach was invoked as a setup blocker by another command, such as `$impeccable craft landing page`, pause that command here. Complete teach, re-run the loader, then resume the original command with the freshly loaded context. For craft, resume into shape next; teach creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
-
-## Step 2: Explore the codebase
-
-Before asking questions, thoroughly scan the project to discover what you can:
-
-- **README and docs**: Project purpose, target audience, any stated goals
-- **Package.json / config files**: Tech stack, dependencies, existing design libraries
-- **Existing components**: Current design patterns, spacing, typography in use
-- **Brand assets**: Logos, favicons, color values already defined
-- **Design tokens / CSS variables**: Existing color palettes, font stacks, spacing scales
-- **Any style guides or brand documentation**
-
-Also form a **register hypothesis** from what you find:
-
-- Brand signals: `/`, `/about`, `/pricing`, `/blog/*`, `/docs/*`, hero sections, big typography, scroll-driven sections, landing-page-shaped content.
-- Product signals: `/app/*`, `/dashboard`, `/settings`, `/(auth)`, forms, data tables, side/top nav, app-shell components.
-
-Register is a hypothesis at this point, not a decision; Step 3 confirms it.
-
-Note what you've learned and what remains unclear. This exploration feeds both PRODUCT.md and DESIGN.md.
-
-## Step 3: Ask strategic questions (for PRODUCT.md)
-
-STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. Ask only about what you couldn't infer from the codebase.
-
-### Interview mode, not confirmation mode
-
-If the repo is empty or the user's brief is sparse, run a short interview before proposing PRODUCT.md. Do **not** turn a one-sentence request into a complete inferred PRODUCT.md and ask for blanket confirmation.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Use inferred answers as hypotheses or options, not as finished facts.
-- Complete at least one real user-answer round before drafting PRODUCT.md, unless every required answer is directly discoverable from repo docs.
-- Round 1 should establish register, users/purpose, and desired outcome.
-- Round 2 should establish brand personality or references, anti-references, and accessibility needs.
-
-### Minimum viable interview
-
-Ask enough to complete PRODUCT.md. At minimum, cover register confirmation, users and purpose, brand personality, anti-references, and accessibility needs unless each answer is directly discoverable from repo context. After at least one interview round, you may propose inferred answers, but the user must confirm them before you write PRODUCT.md. Never synthesize PRODUCT.md from the original task prompt alone.
-
-### Register (ask first; it shapes everything below)
-
-Every design task is either **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboards, tools: design SERVES the product).
-
-If Step 2 produced a clear hypothesis, lead with it: *"From the codebase, this looks like a [brand / product] surface. Does that match your intent, or should we treat it differently?"*
-
-If the signal is genuinely split (e.g. a product with a big marketing landing), STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. Ask which register describes the **primary** surface. The register can be overridden per task later, but PRODUCT.md carries one default.
-
-### Users & Purpose
-- Who uses this? What's their context when using it?
-- What job are they trying to get done?
-- For brand: what emotions should the interface evoke? (confidence, delight, calm, urgency)
-- For product: what workflow are they in? What's the primary task on any given screen?
-
-### Brand & Personality
-- How would you describe the brand personality in 3 words?
-- Reference sites or apps that capture the right feel? What specifically about them?
- - For brand, push for real-world references in the right lane (tech-minimal, editorial-magazine, consumer-warm, brutalist-grid, etc.), not generic "modern" adjectives.
- - For product, push for category best-tool references (Linear, Figma, Notion, Raycast, Stripe).
-- What should this explicitly NOT look like? Any anti-references?
-
-### Accessibility & Inclusion
-- Specific accessibility requirements? (WCAG level, known user needs)
-- Considerations for reduced motion, color blindness, or other accommodations?
-
-Skip questions where the answer is already clear. **Do NOT ask about colors, fonts, radii, or visual styling here.** Those belong in DESIGN.md, not PRODUCT.md.
-
-## Step 4: Write PRODUCT.md
-
-Write PRODUCT.md only after the user has confirmed the strategic answers from Step 3. If an inferred answer is uncertain or unconfirmed, ask before writing.
-
-Synthesize into a strategic document:
-
-```markdown
-# Product
-
-## Register
-
-product
-
-## Users
-[Who they are, their context, the job to be done]
-
-## Product Purpose
-[What this product does, why it exists, what success looks like]
-
-## Brand Personality
-[Voice, tone, 3-word personality, emotional goals]
-
-## Anti-references
-[What this should NOT look like. Specific bad-example sites or patterns to avoid.]
-
-## Design Principles
-[3-5 strategic principles derived from the conversation. Principles like "practice what you preach", "show, don't tell", "expert confidence". NOT visual rules like "use OKLCH" or "magenta accent".]
-
-## Accessibility & Inclusion
-[WCAG level, known user needs, considerations]
-```
-
-Register is either `brand` or `product` as a bare value. No prose, no commentary.
-
-Write to `PROJECT_ROOT/PRODUCT.md`. If `.impeccable.md` existed, the loader already renamed it; merge into that content rather than starting from scratch.
-
-## Step 5: Decide on DESIGN.md
-
-Offer `$impeccable document` either way. Two paths:
-
-- **Code exists** (CSS tokens, components, a running site): "I can generate a DESIGN.md that captures your visual system (colors, typography, components) so variants stay on-brand. Want to do that now?"
-- **Pre-implementation** (empty project): "I can seed a starter DESIGN.md from five quick questions about color strategy, type direction, motion energy, and references. You can re-run once there's code, to capture the real tokens. Want to do that now?"
-
-If the user agrees, delegate to `$impeccable document` (it auto-detects scan vs seed). Load its reference and follow that flow.
-
-If the user prefers to skip, mention they can run `$impeccable document` any time later.
-
-## Step 6: Confirm and wrap up
-
-Summarize:
-- Register captured (brand / product)
-- What was written (PRODUCT.md, DESIGN.md, or both)
-- The 3-5 strategic principles from PRODUCT.md that will guide future work
-- If DESIGN.md is pending, remind the user how to generate it later
-
-**Critical: re-run the loader to refresh session context.** After writing PRODUCT.md, run `node .agents/skills/impeccable/scripts/load-context.mjs` one final time and let its full JSON output land in conversation. This ensures subsequent commands in this session use the freshly-written PRODUCT.md, not a stale earlier version.
-
-If teach was invoked as a blocker by another impeccable command (e.g. the user ran `$impeccable polish` with no PRODUCT.md), resume that original task now with the fresh context.
-
-Optionally STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. Ask whether they'd like a brief summary of PRODUCT.md appended to AGENTS.md for easier agent reference. If yes, append a short **Design Context** pointer section there.
@@ -1,124 +0,0 @@
-Typography carries most of the information on the page. Replace generic defaults (Inter, Roboto, system fallback at flat scale) with type that reflects the brand and scales with intentional contrast.
-
----
-
-## Register
-
-Brand: run the font selection procedure in [brand.md](brand.md). Pairing follows the brand's lane (display serif + sans body for editorial/luxury, one committed sans for tech, etc.). Fluid `clamp()` scale, ≥1.25 ratio between steps.
-
-Product: system fonts and familiar sans stacks are legitimate here. One well-tuned family typically carries the whole UI. Fixed `rem` scale, 1.125–1.2 ratio between more closely-spaced steps.
-
----
-
-## Assess Current Typography
-
-Analyze what's weak or generic about the current type:
-
-1. **Font choices**:
- - Are we using invisible defaults? (Inter, Roboto, Arial, Open Sans, system defaults)
- - Does the font match the brand personality? (A playful brand shouldn't use a corporate typeface)
- - Are there too many font families? (More than 2-3 is almost always a mess)
-
-2. **Hierarchy**:
- - Can you tell headings from body from captions at a glance?
- - Are font sizes too close together? (14px, 15px, 16px = muddy hierarchy)
- - Are weight contrasts strong enough? (Medium vs Regular is barely visible)
-
-3. **Sizing & scale**:
- - Is there a consistent type scale, or are sizes arbitrary?
- - Does body text meet minimum readability? (16px+)
- - Is the sizing strategy appropriate for the context? (Fixed `rem` scales for app UIs; fluid `clamp()` for marketing/content page headings)
-
-4. **Readability**:
- - Are line lengths comfortable? (45-75 characters ideal)
- - Is line-height appropriate for the font and context?
- - Is there enough contrast between text and background?
-
-5. **Consistency**:
- - Are the same elements styled the same way throughout?
- - Are font weights used consistently? (Not bold in one section, semibold in another for the same role)
- - Is letter-spacing intentional or default everywhere?
-
-**CRITICAL**: The goal isn't to make text "fancier." It's to make it clearer, more readable, and more intentional. Good typography is invisible; bad typography is distracting.
-
-## Plan Typography Improvements
-
-Consult the [typography reference](typography.md) for detailed guidance on scales, pairing, and loading strategies.
-
-Create a systematic plan:
-
-- **Font selection**: Do fonts need replacing? What fits the brand/context?
-- **Type scale**: Establish a modular scale (e.g., 1.25 ratio) with clear hierarchy
-- **Weight strategy**: Which weights serve which roles? (Regular for body, Semibold for labels, Bold for headings, or whatever fits)
-- **Spacing**: Line-heights, letter-spacing, and margins between typographic elements
-
-## Improve Typography Systematically
-
-### Font Selection
-
-If fonts need replacing:
-- Choose fonts that reflect the brand personality
-- Pair with genuine contrast (serif + sans, geometric + humanist), or use a single family in multiple weights
-- Ensure web font loading doesn't cause layout shift (`font-display: swap`, metric-matched fallbacks)
-
-### Establish Hierarchy
-
-Build a clear type scale:
-- **5 sizes cover most needs**: caption, secondary, body, subheading, heading
-- **Use a consistent ratio** between levels (1.25, 1.333, or 1.5)
-- **Combine dimensions**: Size + weight + color + space for strong hierarchy. Don't rely on size alone
-- **App UIs**: Use a fixed `rem`-based type scale, optionally adjusted at 1-2 breakpoints. Fluid sizing undermines the spatial predictability that dense, container-based layouts need
-- **Marketing / content pages**: Use fluid sizing via `clamp(min, preferred, max)` for headings and display text. Keep body text fixed
-
-### Fix Readability
-
-- Set `max-width` on text containers using `ch` units (`max-width: 65ch`)
-- Adjust line-height per context: tighter for headings (1.1-1.2), looser for body (1.5-1.7)
-- Increase line-height slightly for light-on-dark text
-- Ensure body text is at least 16px / 1rem
-
-### Refine Details
-
-- Use `tabular-nums` for data tables and numbers that should align
-- Apply proper `letter-spacing`: slightly open for small caps and uppercase, default or tight for large display text
-- Use semantic token names (`--text-body`, `--text-heading`), not value names (`--font-16`)
-- Set `font-kerning: normal` and consider OpenType features where appropriate
-
-### Weight Consistency
-
-- Define clear roles for each weight and stick to them
-- Don't use more than 3-4 weights (Regular, Medium, Semibold, Bold is plenty)
-- Load only the weights you actually use (each weight adds to page load)
-
-**NEVER**:
-- Use more than 2-3 font families
-- Pick sizes arbitrarily; commit to a scale
-- Set body text below 16px
-- Use decorative/display fonts for body text
-- Disable browser zoom (`user-scalable=no`)
-- Use `px` for font sizes; use `rem` to respect user settings
-- Default to Inter/Roboto/Open Sans when personality matters
-- Pair fonts that are similar but not identical (two geometric sans-serifs)
-
-## Verify Typography Improvements
-
-- **Hierarchy**: Can you identify heading vs body vs caption instantly?
-- **Readability**: Is body text comfortable to read in long passages?
-- **Consistency**: Are same-role elements styled identically throughout?
-- **Personality**: Does the typography reflect the brand?
-- **Performance**: Are web fonts loading efficiently without layout shift?
-- **Accessibility**: Does text meet WCAG contrast ratios? Is it zoomable to 200%?
-
-When the type carries the hierarchy on its own, hand off to `$impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `scale` param controlling the hierarchy ratio. Express all font sizes in the variant's scoped CSS through `calc(var(--p-scale, 1) * <base>)` or, better, scale the type ramp via `clamp(min, calc(var(--p-scale, 1) * Npx), max)`. Users slide from subdued to commanding.
-
-```json
-{"id":"scale","kind":"range","min":0.85,"max":1.3,"step":0.05,"default":1,"label":"Scale"}
-```
-
-Where the variant riffs on a specific pairing, expose the pairing choice as a `steps` param (e.g. "serif display + sans body" vs. "mono display + sans body" vs. "all-sans"). Each branch routes through `:scope[data-p-pairing="X"]` selectors in scoped CSS.
-
-See `reference/live.md` for the full params contract.
@@ -1,159 +0,0 @@
-# Typography
-
-## Classic Typography Principles
-
-### Vertical Rhythm
-
-Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
-
-### Modular Scale & Hierarchy
-
-The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
-
-**Use fewer sizes with more contrast.** A 5-size system covers most needs:
-
-| Role | Typical Ratio | Use Case |
-|------|---------------|----------|
-| xs | 0.75rem | Captions, legal |
-| sm | 0.875rem | Secondary UI, metadata |
-| base | 1rem | Body text |
-| lg | 1.25-1.5rem | Subheadings, lead text |
-| xl+ | 2-4rem | Headlines, hero text |
-
-Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
-
-### Readability & Measure
-
-Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
-
-**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
-
-**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
-
-## Font Selection & Pairing
-
-The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
-
-### Anti-reflexes worth defending against
-
-- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
-- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
-- A children's product does NOT need a rounded display font. Kids' books use real type.
-- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
-
-**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
-
-### Pairing Principles
-
-**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
-
-When pairing, contrast on multiple axes:
-- Serif + Sans (structure contrast)
-- Geometric + Humanist (personality contrast)
-- Condensed display + Wide body (proportion contrast)
-
-**Never pair fonts that are similar but not identical** (e.g., two geometric sans-serifs). They create visual tension without clear hierarchy.
-
-### Web Font Loading
-
-The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
-
-```css
-/* 1. Use font-display: swap for visibility */
-@font-face {
- font-family: 'CustomFont';
- src: url('font.woff2') format('woff2');
- font-display: swap;
-}
-
-/* 2. Match fallback metrics to minimize shift */
-@font-face {
- font-family: 'CustomFont-Fallback';
- src: local('Arial');
- size-adjust: 105%; /* Scale to match x-height */
- ascent-override: 90%; /* Match ascender height */
- descent-override: 20%; /* Match descender depth */
- line-gap-override: 10%; /* Match line spacing */
-}
-
-body {
- font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
-}
-```
-
-Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
-
-**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
-
-**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
-
-**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
-
-## Modern Web Typography
-
-### Fluid Type
-
-Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
-
-**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
-
-**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
-
-**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
-
-**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
-
-### OpenType Features
-
-Most developers don't know these exist. Use them for polish:
-
-```css
-/* Tabular numbers for data alignment */
-.data-table { font-variant-numeric: tabular-nums; }
-
-/* Proper fractions */
-.recipe-amount { font-variant-numeric: diagonal-fractions; }
-
-/* Small caps for abbreviations */
-abbr { font-variant-caps: all-small-caps; }
-
-/* Disable ligatures in code */
-code { font-variant-ligatures: none; }
-
-/* Enable kerning (usually on by default, but be explicit) */
-body { font-kerning: normal; }
-```
-
-Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
-
-### Rendering polish
-
-```css
-/* Even out heading line lengths (browser picks better break points) */
-h1, h2, h3 { text-wrap: balance; }
-
-/* Reduce orphans and ragged endings in long prose */
-article p { text-wrap: pretty; }
-
-/* Variable fonts: pick the right optical-size master automatically */
-body { font-optical-sizing: auto; }
-```
-
-**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
-
-## Typography System Architecture
-
-Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
-
-## Accessibility Considerations
-
-Beyond contrast ratios (which are well-documented), consider:
-
-- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
-- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
-- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
-- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
-
----
-
-**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
@@ -1,107 +0,0 @@
-# UX Writing
-
-## The Button Label Problem
-
-**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
-
-| Bad | Good | Why |
-|-----|------|-----|
-| OK | Save changes | Says what will happen |
-| Submit | Create account | Outcome-focused |
-| Yes | Delete message | Confirms the action |
-| Cancel | Keep editing | Clarifies what "cancel" means |
-| Click here | Download PDF | Describes the destination |
-
-**For destructive actions**, name the destruction:
-- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
-- "Delete 5 items" not "Delete selected" (show the count)
-
-## Error Messages: The Formula
-
-Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
-
-### Error Message Templates
-
-| Situation | Template |
-|-----------|----------|
-| **Format error** | "[Field] needs to be [format]. Example: [example]" |
-| **Missing required** | "Please enter [what's missing]" |
-| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
-| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
-| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
-
-### Don't Blame the User
-
-Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
-
-## Empty States Are Opportunities
-
-Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
-
-## Voice vs Tone
-
-**Voice** is your brand's personality, consistent everywhere.
-**Tone** adapts to the moment.
-
-| Moment | Tone Shift |
-|--------|------------|
-| Success | Celebratory, brief: "Done! Your changes are live." |
-| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
-| Loading | Reassuring: "Saving your work..." |
-| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
-
-**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
-
-## Writing for Accessibility
-
-**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
-
-## Writing for Translation
-
-### Plan for Expansion
-
-German text is ~30% longer than English. Allocate space:
-
-| Language | Expansion |
-|----------|-----------|
-| German | +30% |
-| French | +20% |
-| Finnish | +30-40% |
-| Chinese | -30% (fewer chars, but same width) |
-
-### Translation-Friendly Patterns
-
-Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
-
-## Consistency: The Terminology Problem
-
-Pick one term and stick with it:
-
-| Inconsistent | Consistent |
-|--------------|------------|
-| Delete / Remove / Trash | Delete |
-| Settings / Preferences / Options | Settings |
-| Sign in / Log in / Enter | Sign in |
-| Create / Add / New | Create |
-
-Build a terminology glossary and enforce it. Variety creates confusion.
-
-## Avoid Redundant Copy
-
-If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
-
-## Loading States
-
-Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
-
-## Confirmation Dialogs: Use Sparingly
-
-Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
-
-## Form Instructions
-
-Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
-
----
-
-**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
@@ -1,284 +0,0 @@
-#!/usr/bin/env node
-/**
- * Cleans up deprecated Impeccable skill files, symlinks, and
- * skills-lock.json entries left over from previous versions.
- *
- * Safe to run repeatedly -- it is a no-op when nothing needs cleaning.
- *
- * Usage (from the project root):
- * node {{scripts_path}}/cleanup-deprecated.mjs
- *
- * What it does:
- * 1. Finds every harness-specific skills directory (.claude/skills,
- * .cursor/skills, .agents/skills, etc.).
- * 2. For each deprecated skill name (with and without i- prefix),
- * checks if the directory exists and its SKILL.md mentions
- * "impeccable" (to avoid deleting unrelated user skills).
- * 3. Deletes confirmed matches (files, directories, or symlinks).
- * 4. Removes the corresponding entries from skills-lock.json.
- */
-
-import { existsSync, readFileSync, writeFileSync, rmSync, readdirSync, statSync, lstatSync, unlinkSync } from 'node:fs';
-import { join, resolve } from 'node:path';
-
-// Skills that were renamed, merged, or folded in v2.0, v2.1, and v3.0.
-const DEPRECATED_NAMES = [
- // v2.0 renames
- 'frontend-design', // renamed to impeccable
- 'teach-impeccable', // folded into /impeccable teach
- // v2.1 merges
- 'arrange', // renamed to layout
- 'normalize', // merged into polish
- 'onboard', // merged into harden
- 'extract', // merged into /impeccable extract
- // v3.0 consolidation: all standalone skills -> /impeccable sub-commands
- 'adapt',
- 'animate',
- 'audit',
- 'bolder',
- 'clarify',
- 'colorize',
- 'critique',
- 'delight',
- 'distill',
- 'harden',
- 'layout',
- 'optimize',
- 'overdrive',
- 'polish',
- 'quieter',
- 'shape',
- 'typeset',
-];
-
-// All known harness directories that may contain a skills/ subfolder.
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Per-skill fingerprints for SKILL.md bodies that never mentioned
-// "impeccable" in their v2.x source. Used as a last-resort match
-// when no skills-lock.json exists and the word heuristic fails.
-// The strings are lifted verbatim from the v2.x frontmatter
-// descriptions, so collisions with hand-written user skills are
-// vanishingly unlikely.
-const SKILL_FINGERPRINTS = {
- harden: 'Make interfaces production-ready: error handling, empty states',
- optimize: 'Diagnoses and fixes UI performance across loading speed',
-};
-
-/**
- * Walk up from startDir until we find a directory that looks like a
- * project root (has package.json, .git, or skills-lock.json).
- */
-export function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- const { root } = { root: '/' };
- while (dir !== root) {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Load skills-lock.json from the project root, or null if missing/unreadable.
- */
-export function loadLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return null;
- try {
- return JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return null;
- }
-}
-
-/**
- * Check whether a skill directory belongs to Impeccable. Three layered
- * signals, in order of reliability:
- * 1. Lock source equals "pbakaus/impeccable" (authoritative).
- * 2. SKILL.md body contains the word "impeccable".
- * 3. SKILL.md body contains a per-skill fingerprint (for harden and
- * optimize, whose v2.x SKILL.md never mentioned the pack name).
- */
-export function isImpeccableSkill(skillDir, { skillName, lock } = {}) {
- // 1. Authoritative: the lock file claims this skill is ours.
- if (skillName && lock?.skills?.[skillName]?.source === 'pbakaus/impeccable') {
- return true;
- }
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) return false;
- let content;
- try {
- content = readFileSync(skillMd, 'utf-8');
- } catch {
- return false;
- }
- // 2. Word-level content heuristic.
- if (/impeccable/i.test(content)) return true;
- // 3. Per-skill fingerprint for old skills that never mentioned the pack.
- // Strip the i- prefix so both `harden` and `i-harden` resolve to the
- // same fingerprint entry.
- const unprefixed = skillName?.startsWith('i-') ? skillName.slice(2) : skillName;
- const fingerprint = unprefixed && SKILL_FINGERPRINTS[unprefixed];
- if (fingerprint && content.includes(fingerprint)) return true;
- return false;
-}
-
-/**
- * Build the full list of names to check: each deprecated name, plus
- * its i-prefixed variant.
- */
-export function buildTargetNames() {
- const names = [];
- for (const name of DEPRECATED_NAMES) {
- names.push(name);
- names.push(`i-${name}`);
- }
- return names;
-}
-
-/**
- * Find every skills directory across all harness dirs in the project.
- * Returns absolute paths that exist on disk.
- */
-export function findSkillsDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const candidate = join(projectRoot, harness, 'skills');
- if (existsSync(candidate)) {
- dirs.push(candidate);
- }
- }
- return dirs;
-}
-
-/**
- * Remove deprecated skill directories/symlinks from all harness dirs.
- * Reads skills-lock.json so the authoritative "source" field can
- * drive deletion even when SKILL.md never mentions impeccable.
- * Returns an array of paths that were deleted.
- */
-export function removeDeprecatedSkills(projectRoot, lock) {
- if (lock === undefined) lock = loadLock(projectRoot);
- const targets = buildTargetNames();
- const skillsDirs = findSkillsDirs(projectRoot);
- const deleted = [];
-
- for (const skillsDir of skillsDirs) {
- for (const name of targets) {
- const skillPath = join(skillsDir, name);
-
- // Use lstat to detect symlinks (existsSync follows symlinks and
- // returns false for dangling ones).
- let stat;
- try {
- stat = lstatSync(skillPath);
- } catch {
- continue; // does not exist at all
- }
-
- if (stat.isSymbolicLink()) {
- // Symlink: check the target if it's alive, otherwise treat
- // dangling symlinks to deprecated names as safe to remove.
- const targetAlive = existsSync(skillPath);
- const isMatch = targetAlive
- ? isImpeccableSkill(skillPath, { skillName: name, lock })
- : true;
- if (isMatch) {
- unlinkSync(skillPath);
- deleted.push(skillPath);
- }
- continue;
- }
-
- // Regular directory -- verify it belongs to impeccable
- if (isImpeccableSkill(skillPath, { skillName: name, lock })) {
- rmSync(skillPath, { recursive: true, force: true });
- deleted.push(skillPath);
- }
- }
- }
-
- return deleted;
-}
-
-/**
- * Remove deprecated entries from skills-lock.json.
- * Only removes entries whose source is "pbakaus/impeccable".
- * Returns the list of removed skill names.
- */
-export function cleanSkillsLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return [];
-
- let lock;
- try {
- lock = JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return [];
- }
-
- if (!lock.skills || typeof lock.skills !== 'object') return [];
-
- const targets = buildTargetNames();
- const removed = [];
-
- for (const name of targets) {
- const entry = lock.skills[name];
- if (!entry) continue;
- // Only remove if it belongs to impeccable
- if (entry.source === 'pbakaus/impeccable') {
- delete lock.skills[name];
- removed.push(name);
- }
- }
-
- if (removed.length > 0) {
- writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\n', 'utf-8');
- }
-
- return removed;
-}
-
-/**
- * Run the full cleanup. Returns a summary object.
- *
- * Order matters: read the lock and delete directories first, then
- * strip lock entries. Otherwise the authoritative signal is gone by
- * the time directory deletion runs.
- */
-export function cleanup(projectRoot) {
- const root = projectRoot || findProjectRoot();
- const lock = loadLock(root);
- const deletedPaths = removeDeprecatedSkills(root, lock);
- const removedLockEntries = cleanSkillsLock(root);
- return { deletedPaths, removedLockEntries, projectRoot: root };
-}
-
-// CLI entry point
-if (process.argv[1] && resolve(process.argv[1]) === resolve(new URL(import.meta.url).pathname)) {
- const result = cleanup();
- if (result.deletedPaths.length === 0 && result.removedLockEntries.length === 0) {
- console.log('No deprecated Impeccable skills found. Nothing to clean up.');
- } else {
- if (result.deletedPaths.length > 0) {
- console.log(`Removed ${result.deletedPaths.length} deprecated skill(s):`);
- for (const p of result.deletedPaths) console.log(` - ${p}`);
- }
- if (result.removedLockEntries.length > 0) {
- console.log(`Cleaned ${result.removedLockEntries.length} entry/entries from skills-lock.json:`);
- for (const name of result.removedLockEntries) console.log(` - ${name}`);
- }
- }
-}
@@ -1,94 +0,0 @@
-{
- "craft": {
- "description": "Full confirmed-brief-then-build flow. Runs multi-round shape discovery first, resolves visual probe and north-star mock gates when available, then builds and visually iterates. Use when building a new feature end-to-end.",
- "argumentHint": "[feature description]"
- },
- "teach": {
- "description": "Gathers design context for a project. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles) and, when code exists to analyze, DESIGN.md (visual: colors, typography, components). Every other command reads these files before doing work. Use once per project.",
- "argumentHint": ""
- },
- "document": {
- "description": "Generate a DESIGN.md file that captures the current visual design system. Auto-extracts colors, typography, spacing, radii, and component patterns from the codebase, then asks the user to confirm descriptive language for atmosphere and color character. Follows the Google Stitch DESIGN.md format so the file is tool-compatible. Use when you need a visual design spec an AI agent can follow to stay on-brand.",
- "argumentHint": ""
- },
- "extract": {
- "description": "Pull reusable patterns, components, and design tokens into the design system. Identifies repeated patterns and consolidates them. Use when you have drift across the codebase and want to bring things back to a consistent system.",
- "argumentHint": "[target]"
- },
- "live": {
- "description": "Interactive live variant mode. Select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via HMR. Requires a running dev server. Use when you want to visually experiment with design alternatives in real time.",
- "argumentHint": ""
- },
- "adapt": {
- "description": "Adapt designs to work across different screen sizes, devices, contexts, or platforms. Implements breakpoints, fluid layouts, and touch targets. Use when the user mentions responsive design, mobile layouts, breakpoints, viewport adaptation, or cross-device compatibility.",
- "argumentHint": "[target] [context (mobile, tablet, print...)]"
- },
- "animate": {
- "description": "Review a feature and enhance it with purposeful animations, micro-interactions, and motion effects that improve usability and delight. Use when the user mentions adding animation, transitions, micro-interactions, motion design, hover effects, or making the UI feel more alive.",
- "argumentHint": "[target]"
- },
- "audit": {
- "description": "Run technical quality checks across accessibility, performance, theming, responsive design, and anti-patterns. Generates a scored report with P0-P3 severity ratings and actionable plan. Use when the user wants an accessibility check, performance audit, or technical quality review.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "bolder": {
- "description": "Amplify safe or boring designs to make them more visually interesting and stimulating. Increases impact while maintaining usability. Use when the user says the design looks bland, generic, too safe, lacks personality, or wants more visual impact and character.",
- "argumentHint": "[target]"
- },
- "clarify": {
- "description": "Improve unclear UX copy, error messages, microcopy, labels, and instructions to make interfaces easier to understand. Use when the user mentions confusing text, unclear labels, bad error messages, hard-to-follow instructions, or wanting better UX writing.",
- "argumentHint": "[target]"
- },
- "colorize": {
- "description": "Add strategic color to features that are too monochromatic or lack visual interest, making interfaces more engaging and expressive. Use when the user mentions the design looking gray, dull, lacking warmth, needing more color, or wanting a more vibrant or expressive palette.",
- "argumentHint": "[target]"
- },
- "critique": {
- "description": "Evaluate design from a UX perspective, assessing visual hierarchy, information architecture, emotional resonance, cognitive load, and overall quality with quantitative scoring, persona-based testing, automated anti-pattern detection, and actionable feedback. Use when the user asks to review, critique, evaluate, or give feedback on a design or component.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "delight": {
- "description": "Add moments of joy, personality, and unexpected touches that make interfaces memorable and enjoyable to use. Elevates functional to delightful. Use when the user asks to add polish, personality, animations, micro-interactions, delight, or make an interface feel fun or memorable.",
- "argumentHint": "[target]"
- },
- "distill": {
- "description": "Strip designs to their essence by removing unnecessary complexity. Great design is simple, powerful, and clean. Use when the user asks to simplify, declutter, reduce noise, remove elements, or make a UI cleaner and more focused.",
- "argumentHint": "[target]"
- },
- "harden": {
- "description": "Make interfaces production-ready: error handling, i18n, text overflow, edge case management, and resilience under real-world data. Use when the user asks to harden, make production-ready, handle edge cases, add error states, or fix overflow and i18n issues.",
- "argumentHint": "[target]"
- },
- "onboard": {
- "description": "Design onboarding flows, first-run experiences, and empty states that guide new users to value. Covers welcome screens, account setup, progressive disclosure, contextual tooltips, feature announcements, and activation moments. Use when the user mentions onboarding, first-time users, empty states, activation, getting started, new user flows, or the aha moment.",
- "argumentHint": "[target]"
- },
- "layout": {
- "description": "Improve layout, spacing, and visual rhythm. Fixes monotonous grids, inconsistent spacing, and weak visual hierarchy. Use when the user mentions layout feeling off, spacing issues, visual hierarchy, crowded UI, alignment problems, or wanting better composition.",
- "argumentHint": "[target]"
- },
- "optimize": {
- "description": "Diagnoses and fixes UI performance across loading speed, rendering, animations, images, and bundle size. Use when the user mentions slow, laggy, janky, performance, bundle size, load time, or wants a faster, smoother experience.",
- "argumentHint": "[target]"
- },
- "overdrive": {
- "description": "Pushes interfaces past conventional limits with technically ambitious implementations — shaders, spring physics, scroll-driven reveals, 60fps animations. Use when the user wants to wow, impress, go all-out, or make something that feels extraordinary.",
- "argumentHint": "[target]"
- },
- "polish": {
- "description": "Performs a final quality pass fixing alignment, spacing, consistency, and micro-detail issues before shipping. Use when the user mentions polish, finishing touches, pre-launch review, something looks off, or wants to go from good to great.",
- "argumentHint": "[target]"
- },
- "quieter": {
- "description": "Tones down visually aggressive or overstimulating designs, reducing intensity while preserving quality. Use when the user mentions too bold, too loud, overwhelming, aggressive, garish, or wants a calmer, more refined aesthetic.",
- "argumentHint": "[target]"
- },
- "shape": {
- "description": "Plan UX and UI before code. Runs a required multi-round discovery interview, uses visual probes when available, and produces a user-confirmed design brief for implementation.",
- "argumentHint": "[feature to shape]"
- },
- "typeset": {
- "description": "Improves typography by fixing font choices, hierarchy, sizing, weight, and readability so text feels intentional. Use when the user mentions fonts, type, readability, text hierarchy, sizing looks off, or wants more polished, intentional typography.",
- "argumentHint": "[target]"
- }
-}
@@ -1,242 +0,0 @@
-#!/usr/bin/env node
-/**
- * Critique persistence helper.
- *
- * Each run of /impeccable critique writes a per-target snapshot to
- * .impeccable/critique/<timestamp>__<slug>.md
- * with a small YAML frontmatter carrying the score + P0/P1 counts.
- *
- * /impeccable polish reads the latest matching snapshot at start as its
- * fix backlog. No other skill auto-reads critique output.
- *
- * The slug is derived mechanically from the *resolved* primary artifact
- * (file path or URL), never from the user's natural-language phrasing.
- * Slug stability across runs is what lets the trend display work.
- *
- * CLI entry points (called from skill instructions):
- * node critique-storage.mjs slug <resolved-target>
- * node critique-storage.mjs write <slug> <snapshot-body-file>
- * node critique-storage.mjs latest <slug>
- * node critique-storage.mjs trend <slug> [limit]
- *
- * Note: there is intentionally no `ignore` subcommand. ignore.md is a plain
- * markdown file; the model reads it directly with its file-read tool. This
- * helper only exists for operations the model can't trivially do inline
- * (normalizing paths, generating filenames, globbing + parsing frontmatter).
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath, pathToFileURL } from 'node:url';
-import { getCritiqueDir } from './impeccable-paths.mjs';
-
-const SLUG_MAX = 50;
-
-/**
- * Mechanically derive a slug from a resolved target. Returns null if the
- * input doesn't look like a stable identifier (empty, project root, etc).
- *
- * Accepts file paths and URLs. The model resolves "the homepage" to a
- * concrete artifact before calling this — we never slug a natural-language
- * phrase.
- */
-export function slugFromTarget(resolved, { cwd = process.cwd() } = {}) {
- if (!resolved || typeof resolved !== 'string') return null;
- const trimmed = resolved.trim();
- if (!trimmed) return null;
-
- // URL
- if (/^https?:\/\//i.test(trimmed)) {
- let url;
- try { url = new URL(trimmed); } catch { return null; }
- const hostPath = `${url.hostname}${url.pathname}`;
- return kebab(hostPath);
- }
-
- // File path. Make it project-relative so two devs critiquing the same
- // checkout get the same slug regardless of where their repo is cloned.
- const abs = path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- let rel = path.relative(cwd, abs);
- // If the target is outside cwd, fall back to the basename so we still
- // produce a stable slug (vs the absolute path, which would include
- // home dirs / usernames).
- if (rel.startsWith('..') || path.isAbsolute(rel)) {
- rel = path.basename(abs);
- }
- if (!rel || rel === '.' || rel === '') return null;
- return kebab(rel);
-}
-
-function kebab(s) {
- const slug = s
- .toLowerCase()
- .replace(/[/\\.]+/g, '-')
- .replace(/[^a-z0-9-]+/g, '-')
- .replace(/-+/g, '-')
- .replace(/^-|-$/g, '');
- if (!slug) return null;
- // Cap from the tail — the tail (filename) is more identifying than the
- // top-level directory.
- return slug.length <= SLUG_MAX ? slug : slug.slice(slug.length - SLUG_MAX).replace(/^-/, '');
-}
-
-/**
- * Filename-safe UTC ISO timestamp: hyphens for separators, trailing Z.
- * Plain colons aren't allowed on Windows filesystems.
- */
-export function nowFilenameStamp(date = new Date()) {
- const iso = date.toISOString(); // 2026-05-12T18:30:00.123Z
- return iso.replace(/[:.]/g, '-').replace(/-\d+Z$/, 'Z');
-}
-
-/**
- * Write a snapshot for `slug`. `meta` carries the small structured frontmatter
- * keys read back by readTrend(). `body` is the human-readable critique
- * report (everything below the frontmatter).
- *
- * Returns the absolute path written.
- */
-export function writeSnapshot({ slug, meta, body, cwd = process.cwd(), now = new Date() }) {
- if (!slug) throw new Error('writeSnapshot requires a slug');
- const dir = getCritiqueDir(cwd);
- fs.mkdirSync(dir, { recursive: true });
- const timestamp = nowFilenameStamp(now);
- const filePath = path.join(dir, `${timestamp}__${slug}.md`);
- // Spread `meta` first so internally computed `timestamp` and `slug`
- // always win. Otherwise a caller-supplied meta blob (parsed from the
- // IMPECCABLE_CRITIQUE_META env var) could clobber them, leaving the
- // filename in disagreement with its frontmatter and corrupting trends.
- const front = serializeFrontmatter({ ...meta, timestamp, slug });
- fs.writeFileSync(filePath, `${front}\n${body.trim()}\n`, 'utf-8');
- return filePath;
-}
-
-function serializeFrontmatter(obj) {
- const lines = ['---'];
- for (const [key, value] of Object.entries(obj)) {
- if (value === undefined || value === null) continue;
- const str = typeof value === 'string' ? value : String(value);
- // Quote strings that contain : or # to keep parsing simple.
- const needsQuotes = typeof value === 'string' && /[:#]/.test(str);
- lines.push(`${key}: ${needsQuotes ? JSON.stringify(str) : str}`);
- }
- lines.push('---');
- return lines.join('\n');
-}
-
-function parseFrontmatter(text) {
- const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
- if (!match) return {};
- const out = {};
- for (const line of match[1].split(/\r?\n/)) {
- const colon = line.indexOf(':');
- if (colon < 0) continue;
- const key = line.slice(0, colon).trim();
- let value = line.slice(colon + 1).trim();
- if (/^".*"$/.test(value)) {
- try { value = JSON.parse(value); } catch { /* leave as-is */ }
- } else if (/^-?\d+$/.test(value)) {
- value = Number(value);
- }
- out[key] = value;
- }
- return out;
-}
-
-/**
- * Return all snapshot files for `slug`, sorted oldest → newest.
- */
-function listSnapshotsForSlug(slug, cwd) {
- const dir = getCritiqueDir(cwd);
- if (!fs.existsSync(dir)) return [];
- const suffix = `__${slug}.md`;
- return fs.readdirSync(dir)
- .filter((f) => f.endsWith(suffix))
- .sort()
- .map((f) => path.join(dir, f));
-}
-
-/**
- * Return the most recent snapshot for `slug`, or null. Polish reads this
- * to find its fix backlog when the slug matches.
- */
-export function readLatestSnapshot(slug, { cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- if (!all.length) return null;
- const latest = all[all.length - 1];
- const body = fs.readFileSync(latest, 'utf-8');
- return { path: latest, body, meta: parseFrontmatter(body) };
-}
-
-/**
- * Return the last `limit` snapshots' frontmatter, oldest → newest.
- * Critique appends a one-line trend to its output using this.
- */
-export function readTrend(slug, { limit = 5, cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- const slice = all.slice(-limit);
- return slice.map((file) => parseFrontmatter(fs.readFileSync(file, 'utf-8')));
-}
-
-// ---- CLI ---------------------------------------------------------------
-
-function main(argv) {
- const [cmd, ...args] = argv;
- switch (cmd) {
- case 'slug': {
- const slug = slugFromTarget(args[0]);
- if (!slug) { process.stderr.write('no stable slug for input\n'); process.exit(1); }
- process.stdout.write(`${slug}\n`);
- return;
- }
- case 'write': {
- const [slug, bodyFile] = args;
- if (!slug || !bodyFile) { process.stderr.write('usage: write <slug> <body-file>\n'); process.exit(1); }
- const raw = fs.readFileSync(bodyFile, 'utf-8');
- // The body file may be a full report. The caller passes the meta as
- // a JSON object on stdin if it wants structured frontmatter; otherwise
- // we write with minimal metadata.
- let meta = {};
- const metaArg = process.env.IMPECCABLE_CRITIQUE_META;
- if (metaArg) {
- try { meta = JSON.parse(metaArg); } catch { /* ignore */ }
- }
- const out = writeSnapshot({ slug, meta, body: raw });
- process.stdout.write(`${out}\n`);
- return;
- }
- case 'latest': {
- const latest = readLatestSnapshot(args[0]);
- if (!latest) { process.exit(2); }
- process.stdout.write(latest.body);
- return;
- }
- case 'trend': {
- const rows = readTrend(args[0], { limit: args[1] ? Number(args[1]) : 5 });
- process.stdout.write(JSON.stringify(rows, null, 2) + '\n');
- return;
- }
- default:
- process.stderr.write('usage: critique-storage.mjs <slug|write|latest|trend> [args]\n');
- process.exit(1);
- }
-}
-
-function isMainModule() {
- if (!process.argv[1]) return false;
- try {
- return fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1]);
- } catch {
- // pathToFileURL normalizes Windows paths; keep it as a fallback for any
- // environment where realpath is unavailable.
- return import.meta.url === pathToFileURL(process.argv[1]).href;
- }
-}
-
-// Why the realpath check: generated skills are often reached through symlinked
-// harness directories (for example a demo repo's `.agents` -> source `.agents`).
-// Node resolves import.meta.url to the real file, while process.argv[1] keeps
-// the symlink path. Comparing canonical paths prevents a silent exit-0 no-op.
-if (isMainModule()) {
- main(process.argv.slice(2));
-}
@@ -1,820 +0,0 @@
-// Parse a DESIGN.md (Stitch-spec format) into a structured JSON model that
-// the live-mode design-system panel can render. Deterministic, dependency-free.
-//
-// Two-layer: YAML frontmatter (machine-readable tokens) + markdown body
-// (prose with six canonical H2 sections). When frontmatter is present, it's
-// exposed on `model.frontmatter` alongside the prose-scraped sections;
-// consumers can prefer frontmatter values and fall back to prose.
-
-const CANONICAL_SECTIONS = [
- 'Overview',
- 'Colors',
- 'Typography',
- 'Elevation',
- 'Components',
- "Do's and Don'ts",
-];
-
-// ---------- Frontmatter (Stitch YAML subset) ----------
-
-function parseFrontmatter(md) {
- const lines = md.split(/\r?\n/);
- if (lines[0]?.trim() !== '---') return { frontmatter: null, body: md };
-
- let end = -1;
- for (let i = 1; i < lines.length; i++) {
- if (lines[i].trim() === '---') { end = i; break; }
- }
- if (end === -1) return { frontmatter: null, body: md };
-
- const yaml = lines.slice(1, end).join('\n');
- const body = lines.slice(end + 1).join('\n');
- try {
- return { frontmatter: parseYamlSubset(yaml), body };
- } catch {
- return { frontmatter: null, body: md };
- }
-}
-
-// Minimal YAML reader for the Stitch frontmatter subset: scalar maps with
-// one level of nested objects (typography roles, components). Indent-based,
-// 2-space convention. No arrays, no anchors, no multi-line scalars — Stitch's
-// schema doesn't need them and accepting them would require a real YAML
-// dependency we don't want to vendor.
-function parseYamlSubset(yaml) {
- const lines = yaml.split(/\r?\n/);
- const root = {};
- const stack = [{ indent: -1, obj: root }];
-
- for (const raw of lines) {
- // Skip blanks and line-only comments. Don't strip inline comments:
- // unquoted hex values start with `#` and can't be safely distinguished
- // from a comment after whitespace.
- if (!raw.trim() || /^\s*#/.test(raw)) continue;
-
- const indent = raw.match(/^\s*/)[0].length;
- const content = raw.slice(indent);
-
- const colonIdx = findTopLevelColon(content);
- if (colonIdx === -1) continue;
-
- while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
- stack.pop();
- }
-
- const key = content.slice(0, colonIdx).trim();
- const rest = content.slice(colonIdx + 1).trim();
- const parent = stack[stack.length - 1].obj;
-
- if (rest === '') {
- const obj = {};
- parent[key] = obj;
- stack.push({ indent, obj });
- } else {
- parent[key] = parseScalar(rest);
- }
- }
-
- return root;
-}
-
-function findTopLevelColon(s) {
- let inQuote = null;
- for (let i = 0; i < s.length; i++) {
- const ch = s[i];
- if (inQuote) {
- if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
- } else if (ch === '"' || ch === "'") {
- inQuote = ch;
- } else if (ch === ':') {
- return i;
- }
- }
- return -1;
-}
-
-function parseScalar(raw) {
- const s = raw.trim();
- if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
- return s.slice(1, -1);
- }
- if (s === 'true') return true;
- if (s === 'false') return false;
- if (s === 'null' || s === '~') return null;
- if (/^-?\d+$/.test(s)) return Number(s);
- if (/^-?\d*\.\d+$/.test(s)) return Number(s);
- return s;
-}
-
-const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
-const OKLCH_RE = /oklch\([^)]+\)/gi;
-const RGBA_RE = /rgba?\([^)]+\)/gi;
-const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
-const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
-
-// ---------- Section splitting ----------
-
-function splitSections(md) {
- const lines = md.split(/\r?\n/);
- let title = null;
- const sections = {};
- let current = null;
-
- for (const raw of lines) {
- const line = raw.trimEnd();
-
- if (!title && line.startsWith('# ') && !line.startsWith('## ')) {
- title = line.replace(/^#\s+/, '').trim();
- continue;
- }
-
- const h2 = line.match(/^##\s+(?:\d+\.\s*)?([^:\n]+?)(?::\s*(.+))?$/);
- if (h2) {
- const rawName = normalizeApostrophes(h2[1].trim());
- const subtitle = h2[2] ? h2[2].trim() : null;
- const canonical = matchCanonicalSection(rawName);
- if (canonical) {
- current = { name: canonical, subtitle, lines: [] };
- sections[canonical] = current;
- continue;
- }
- // non-canonical H2 — ignore but stop feeding into current
- current = null;
- continue;
- }
-
- if (current) current.lines.push(raw);
- }
-
- return { title, sections };
-}
-
-function normalizeApostrophes(s) {
- return s.replace(/[\u2018\u2019]/g, "'");
-}
-
-function matchCanonicalSection(name) {
- const normalized = normalizeApostrophes(name).toLowerCase();
- // Exact match first
- for (const c of CANONICAL_SECTIONS) {
- if (normalizeApostrophes(c).toLowerCase() === normalized) return c;
- }
- // Keyword-contained match: "Overview & Creative North Star" -> "Overview",
- // "Elevation & Depth" -> "Elevation", etc.
- for (const c of CANONICAL_SECTIONS) {
- const key = normalizeApostrophes(c).toLowerCase();
- const pattern = new RegExp(`\\b${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
- if (pattern.test(normalized)) return c;
- }
- return null;
-}
-
-// ---------- Subsection splitting (inside a canonical section) ----------
-
-function splitSubsections(lines) {
- const subs = [];
- let current = { name: null, lines: [] };
- subs.push(current);
-
- for (const raw of lines) {
- const h3 = raw.match(/^###\s+(.+?)\s*$/);
- if (h3) {
- current = { name: h3[1].trim(), lines: [] };
- subs.push(current);
- continue;
- }
- current.lines.push(raw);
- }
-
- return subs;
-}
-
-// ---------- Generic helpers ----------
-
-function collectParagraphs(lines) {
- const paragraphs = [];
- let buf = [];
- const flush = () => {
- if (buf.length) {
- paragraphs.push(buf.join(' ').trim());
- buf = [];
- }
- };
- for (const raw of lines) {
- const trimmed = raw.trim();
- if (trimmed === '') { flush(); continue; }
- // Horizontal rules (---, ***) and headings/bullets end a paragraph.
- if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { flush(); continue; }
- if (raw.startsWith('#') || raw.match(/^[-*]\s/)) { flush(); continue; }
- buf.push(trimmed);
- }
- flush();
- return paragraphs.filter(Boolean);
-}
-
-function collectBullets(lines) {
- const bullets = [];
- let current = null;
- for (const raw of lines) {
- const m = raw.match(/^\s*[-*]\s+(.+)$/);
- if (m) {
- if (current) bullets.push(current);
- current = m[1];
- continue;
- }
- // continuation of a bullet (indented line)
- if (current && raw.match(/^\s{2,}\S/)) {
- current += ' ' + raw.trim();
- continue;
- }
- // blank line ends a bullet
- if (raw.trim() === '' && current) {
- bullets.push(current);
- current = null;
- }
- }
- if (current) bullets.push(current);
- return bullets;
-}
-
-function stripBold(s) {
- return s.replace(/\*\*(.+?)\*\*/g, '$1');
-}
-
-function extractNamedRules(lines) {
- const rules = [];
- const seen = new Set();
-
- // Style A (Impeccable): "**The X Rule.** body body body" — can span lines.
- const joined = lines.join('\n');
- const inlineStart = /\*\*(The [^*]+?Rule)\.\*\*/g;
- const inlineMatches = [];
- let m;
- while ((m = inlineStart.exec(joined)) !== null) {
- inlineMatches.push({ name: m[1], start: m.index, end: inlineStart.lastIndex });
- }
- for (let i = 0; i < inlineMatches.length; i++) {
- const mm = inlineMatches[i];
- const bodyEnd = i + 1 < inlineMatches.length ? inlineMatches[i + 1].start : joined.length;
- const body = joined
- .slice(mm.end, bodyEnd)
- .replace(/\n##[^\n]*$/s, '')
- .replace(/\n###[^\n]*$/s, '')
- .trim();
- const name = stripBold(mm.name).trim();
- seen.add(name.toLowerCase());
- rules.push({ name, body: stripBold(body) });
- }
-
- // Style B (Stitch): `### The "X" Rule` or `### The X Fallback`, body is the
- // bullets/paragraphs until the next heading. Accept Rule / Fallback / Principle.
- for (let i = 0; i < lines.length; i++) {
- const h3 = lines[i].match(/^###\s+(.+?)\s*$/);
- if (!h3) continue;
- const headerName = stripBold(h3[1]).replace(/["“”]/g, '').trim();
- if (!/^The\b.*\b(Rule|Fallback|Principle)\b/i.test(headerName)) continue;
- if (seen.has(headerName.toLowerCase())) continue;
-
- const bodyLines = [];
- for (let j = i + 1; j < lines.length; j++) {
- if (/^##\s|^###\s/.test(lines[j])) break;
- bodyLines.push(lines[j]);
- }
- const body = stripBold(bodyLines.join('\n').replace(/\n+/g, ' ')).trim();
- if (body) {
- seen.add(headerName.toLowerCase());
- rules.push({ name: headerName, body });
- }
- }
-
- // Style C (Stitch bullet form): "* **The Layering Principle:** body"
- // Colon/period lives inside the bold, so match "**...**" then inspect.
- for (const b of collectBullets(lines)) {
- const mm = b.match(/^\*\*([^*]+?)\*\*\s*(.+)$/);
- if (!mm) continue;
- const nameRaw = mm[1].replace(/[.:]\s*$/, '').replace(/["“”]/g, '').trim();
- if (!/^The\b.+\b(Rule|Fallback|Principle)$/i.test(nameRaw)) continue;
- if (seen.has(nameRaw.toLowerCase())) continue;
- seen.add(nameRaw.toLowerCase());
- rules.push({ name: nameRaw, body: stripBold(mm[2]).trim() });
- }
-
- return rules;
-}
-
-// ---------- Per-section extractors ----------
-
-function extractOverview(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
- const northStar = text.match(/\*\*Creative North Star:\s*"([^"]+)"\*\*/);
- const keyChars = [];
- const keyCharMatch = text.match(/\*\*Key Characteristics:\*\*\s*\n([\s\S]+?)(?:\n##|\n###|$)/);
- if (keyCharMatch) {
- for (const line of keyCharMatch[1].split('\n')) {
- const m = line.match(/^\s*[-*]\s+(.+)$/);
- if (m) keyChars.push(stripBold(m[1].trim()));
- }
- }
-
- // Philosophy paragraphs: everything that isn't a rule header or key-char block
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) =>
- !p.startsWith('**Creative North Star') &&
- !p.startsWith('**Key Characteristics')
- );
-
- return {
- subtitle: section.subtitle,
- creativeNorthStar: northStar ? northStar[1] : null,
- philosophy: paragraphs,
- keyCharacteristics: keyChars,
- };
-}
-
-function extractColors(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ');
- const groups = [];
- const ROLE_KEYWORDS = /^(primary|secondary|tertiary|neutral|accent)\b/i;
-
- for (const sub of subs.slice(1)) {
- if (!sub.name || /Named Rules?/i.test(sub.name) || /^The\s/i.test(sub.name)) continue;
-
- const bullets = collectBullets(sub.lines);
- const parsed = bullets.map((b) => parseColorBullet(b)).filter(Boolean);
- if (parsed.length === 0) continue;
-
- // If every bullet starts with a role keyword (Primary/Secondary/...), promote
- // each bullet to its own group. Otherwise keep the subsection as the group.
- const allRoleBullets =
- parsed.length > 0 && parsed.every((p) => p.name && ROLE_KEYWORDS.test(p.name));
-
- if (allRoleBullets) {
- for (const p of parsed) {
- groups.push({ role: p.name, colors: [p] });
- }
- } else {
- groups.push({ role: sub.name, colors: parsed });
- }
- }
-
- // If the Colors section has no subsections at all (unlikely), fall back to
- // scanning the whole section as a flat bullet list.
- if (groups.length === 0) {
- const flat = collectBullets(section.lines)
- .map((b) => parseColorBullet(b))
- .filter(Boolean);
- if (flat.length) {
- for (const p of flat) {
- if (p.name && ROLE_KEYWORDS.test(p.name)) {
- groups.push({ role: p.name, colors: [p] });
- } else {
- const fallback = groups.find((g) => g.role === 'Palette');
- if (fallback) fallback.colors.push(p);
- else groups.push({ role: 'Palette', colors: [p] });
- }
- }
- }
- }
-
- return {
- subtitle: section.subtitle,
- description: description || null,
- groups,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function parseColorBullet(bullet) {
- const text = bullet.trim();
-
- // Case 1 (Impeccable): **Name** (value-with-maybe-nested-parens): description
- const bold = text.match(/^\*\*(.+?)\*\*\s*(.*)$/);
- if (bold && bold[2].startsWith('(')) {
- const value = extractParenGroup(bold[2]);
- if (value !== null) {
- const after = bold[2].slice(value.length + 2).trimStart();
- if (after.startsWith(':')) {
- return buildColor(bold[1], value, after.slice(1).trim());
- }
- }
- }
-
- // Case 2 (Stitch): **Name (values):** description — value embedded in bold.
- const stitch = text.match(/^\*\*([^*]+?)\s*\(([^)]+)\):\*\*\s*(.*)$/);
- if (stitch) {
- return buildColor(stitch[1].trim(), stitch[2], stitch[3]);
- }
-
- // Case 3: bullet without bold, just hex/oklch inside.
- const values = collectColorValues(text);
- if (values.length) {
- return buildColor(null, values.join(' to '), text);
- }
- return null;
-}
-
-function extractParenGroup(s) {
- if (s[0] !== '(') return null;
- let depth = 0;
- for (let i = 0; i < s.length; i++) {
- if (s[i] === '(') depth++;
- else if (s[i] === ')') {
- depth--;
- if (depth === 0) return s.slice(1, i);
- }
- }
- return null;
-}
-
-function buildColor(name, rawValue, description) {
- const values = collectColorValues(rawValue);
- const primary = values[0] ?? rawValue.trim();
- return {
- name: name ? stripBold(name).trim() : null,
- value: primary,
- valueRange: values.length > 1 ? values : null,
- format: detectFormat(primary),
- description: stripBold(description || '').trim() || null,
- };
-}
-
-function collectColorValues(s) {
- const out = [];
- s.replace(HEX_RE, (v) => {
- out.push(v);
- return v;
- });
- s.replace(OKLCH_RE, (v) => {
- out.push(v);
- return v;
- });
- return out;
-}
-
-function detectFormat(v) {
- if (!v) return 'unknown';
- if (v.startsWith('#')) return 'hex';
- if (/^oklch/i.test(v)) return 'oklch';
- if (/^rgb/i.test(v)) return 'rgb';
- return 'unknown';
-}
-
-function scanInlineColors(lines) {
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '');
- const color = parseColorBullet(trimmed);
- if (color) out.push(color);
- }
- return out;
-}
-
-function parseStitchInlineGroups(lines) {
- // Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
- // Each bullet IS its own role. Group them under the spoken role name.
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
- const m = trimmed.match(
- /^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
- );
- if (m) {
- const role = m[1];
- const color = buildColor(role, m[2], m[3]);
- out.push({ role, colors: [color] });
- }
- }
- return out;
-}
-
-function extractTypography(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
-
- const fonts = {};
- // Pattern A: **Display Font:** Family (with fallback)
- const fontLineRe = /\*\*([\w\s/]+?)Font:\*\*\s*([^\n(]+?)(?:\s*\(with\s+([^)]+)\))?\s*$/gm;
- let fm;
- while ((fm = fontLineRe.exec(text)) !== null) {
- const rawRole = fm[1].trim().toLowerCase().replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || 'display';
- fonts[role] = {
- family: fm[2].trim(),
- fallback: fm[3] ? fm[3].trim() : null,
- };
- }
-
- // Pattern B (Stitch): * **Display & Headlines (Noto Serif):** description
- if (Object.keys(fonts).length === 0) {
- const stitchRe = /\*\*([\w\s&/]+?)\s*\(([^)]+)\):\*\*\s*(.+)/g;
- let sm;
- while ((sm = stitchRe.exec(text)) !== null) {
- const rawRole = sm[1]
- .trim()
- .toLowerCase()
- .replace(/\s*&\s*/g, '-')
- .replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || rawRole;
- fonts[role] = { family: sm[2].trim(), fallback: null, purpose: sm[3].trim() };
- }
- }
-
- // Character paragraph — either a **Character:** label, or fall back to the
- // first free paragraph under the section header (Stitch style).
- const characterMatch = text.match(/\*\*Character:\*\*\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\n|\n###|\n##|$)/);
- let character = characterMatch ? characterMatch[1].replace(/\n/g, ' ').trim() : null;
- if (!character) {
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) => !/^\*\*[\w\s/&]+Font/i.test(p) && !/^\*\*[\w\s/&]+\([^)]+\)/.test(p)
- );
- if (paragraphs.length) character = paragraphs[0];
- }
-
- // Hierarchy bullets under ### Hierarchy
- const subs = splitSubsections(section.lines);
- let hierarchy = [];
- const hierSub = subs.find((s) => s.name && /hierarch/i.test(s.name));
- if (hierSub) {
- const bullets = collectBullets(hierSub.lines);
- hierarchy = bullets.map(parseTypeBullet).filter(Boolean);
- }
-
- return {
- subtitle: section.subtitle,
- fonts,
- character,
- hierarchy,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function normalizeFontRole(raw) {
- // Canonical roles the panel cares about: display, body, label, mono.
- // Stitch often writes compound roles like "display-&-headlines" or "ui-&-body"
- // — collapse them to the first canonical role present.
- const tokens = raw.split(/[-/&\s]+/).filter(Boolean);
- const priority = ['display', 'headline', 'body', 'ui', 'label', 'mono'];
- const canonical = { headline: 'display', ui: 'body' };
- for (const p of priority) {
- if (tokens.includes(p)) return canonical[p] || p;
- }
- return null;
-}
-
-function parseTypeBullet(bullet) {
- // - **Display** (family, weight 300, italic, clamp(...), line-height 1): purpose
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(([^)]+)\):\s*(.*)$/);
- if (!m) return null;
- const name = m[1].trim();
- const specs = m[2].split(',').map((s) => s.trim());
- return {
- name,
- specs,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractElevation(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ') || null;
-
- const shadows = [];
- const seen = new Set();
- const dedupe = (entry) => {
- const key = (entry.name || '') + '::' + entry.value;
- if (seen.has(key)) return;
- seen.add(key);
- shadows.push(entry);
- };
-
- for (const b of collectBullets(section.lines)) {
- const parsed = parseShadowBullet(b);
- if (parsed) dedupe(parsed);
- }
-
- // Fallback: extract shadows written inline in prose. Stitch style is
- // "...use an extra-diffused shadow: `box-shadow: 0 12px 40px rgba(...)`."
- for (const p of collectParagraphs(section.lines)) {
- for (const inline of extractInlineShadows(p)) dedupe(inline);
- }
- for (const b of collectBullets(section.lines)) {
- for (const inline of extractInlineShadows(b)) dedupe(inline);
- }
-
- return {
- subtitle: section.subtitle,
- description,
- shadows,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function extractInlineShadows(text) {
- // Find `box-shadow: ...` anywhere in prose and capture the value. Work on the
- // raw string so it handles both backtick-fenced and unfenced variants.
- const out = [];
- const re = /box-shadow\s*:\s*([^`;\n]+)/gi;
- let m;
- while ((m = re.exec(text)) !== null) {
- const value = m[1].replace(/[`.)]+$/, '').trim();
- if (!value) continue;
- // Name heuristic: the noun immediately before the shadow phrase.
- // e.g. "an extra-diffused shadow: ..." -> "extra-diffused shadow"
- const before = text.slice(0, m.index);
- const nameMatch = before.match(/\b([A-Za-z][A-Za-z\- ]{2,40})\s+shadow\b[^A-Za-z0-9]*$/i);
- let name = null;
- if (nameMatch) {
- const stripped = nameMatch[1]
- .replace(/^(?:use|using|apply|applying|is|are|looks? like)\s+/i, '')
- .replace(/^(?:a|an|the)\s+/i, '')
- .trim();
- if (stripped) {
- name =
- stripped.charAt(0).toUpperCase() + stripped.slice(1) + ' shadow';
- }
- }
- out.push({
- name,
- value,
- purpose: null,
- });
- }
- return out;
-}
-
-function parseShadowBullet(bullet) {
- // - **Name** (`box-shadow: value`): purpose
- // - **Name** (`value`): purpose
- // Only accept if the paren content looks like a shadow value (contains px,
- // rem, rgba, or box-shadow). This filters out `**Rule Name:**` bullets.
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(`?([^`]+?)`?\):\s*(.*)$/);
- if (!m) return null;
- const rawValue = m[2].replace(/^box-shadow:\s*/i, '').trim();
- const looksLikeShadow =
- /box-shadow|rgba?\(|\bpx\b|\brem\b|^-?\d+\s/i.test(rawValue) &&
- /\d/.test(rawValue);
- if (!looksLikeShadow) return null;
- const name = stripBold(m[1]).trim();
- return {
- name,
- value: rawValue,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractComponents(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const components = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
-
- const bullets = collectBullets(sub.lines);
- const paragraphs = collectParagraphs(sub.lines);
-
- const variants = [];
- const properties = {};
-
- for (const b of bullets) {
- // - **Key:** value
- const m = b.match(/^\*\*(.+?):?\*\*:?\s*(.+)$/);
- if (m) {
- const key = stripBold(m[1]).trim();
- const value = stripBold(m[2]).trim();
- // Heuristic: "Primary", "Secondary", "Hover", "Focus" etc are variants;
- // "Shape", "Background", "Padding" are properties.
- if (/^(primary|secondary|tertiary|ghost|hover|focus|active|disabled|default|error|selected|unselected|state)$/i.test(key.split(/[\s/]/)[0])) {
- variants.push({ name: key, description: value });
- } else {
- properties[key.toLowerCase()] = value;
- }
- }
- }
-
- components.push({
- name: sub.name,
- description: paragraphs.join(' ') || null,
- properties,
- variants,
- });
- }
-
- return {
- subtitle: section.subtitle,
- components,
- };
-}
-
-function extractDosDonts(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const dos = [];
- const donts = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
- const subName = normalizeApostrophes(sub.name);
- const bullets = collectBullets(sub.lines).map((b) => stripBold(b).trim());
- if (/^do'?t?:?$/i.test(subName) || /^do:?$/i.test(subName)) {
- dos.push(...bullets);
- } else if (/^don'?t:?$/i.test(subName)) {
- donts.push(...bullets);
- }
- }
-
- // Classify by bullet prefix as a backup (catches loose bullets outside H3 wrappers)
- for (const b of collectBullets(section.lines)) {
- const stripped = normalizeApostrophes(stripBold(b).trim());
- if (/^don'?t\b/i.test(stripped)) {
- if (!donts.some((d) => normalizeApostrophes(d) === stripped)) donts.push(stripped);
- } else if (/^do\b/i.test(stripped)) {
- if (!dos.some((d) => normalizeApostrophes(d) === stripped)) dos.push(stripped);
- }
- }
-
- return { dos, donts };
-}
-
-// ---------- Coverage assessment ----------
-
-function assessCoverage(model) {
- const report = {};
-
- report.overview = model.overview
- ? {
- northStar: Boolean(model.overview.creativeNorthStar),
- philosophy: model.overview.philosophy.length > 0,
- keyCharacteristics: model.overview.keyCharacteristics.length,
- }
- : 'missing';
-
- report.colors = model.colors
- ? {
- groups: model.colors.groups.length,
- totalColors: model.colors.groups.reduce((n, g) => n + g.colors.length, 0),
- rules: model.colors.rules.length,
- }
- : 'missing';
-
- report.typography = model.typography
- ? {
- fonts: Object.keys(model.typography.fonts).length,
- hierarchyEntries: model.typography.hierarchy.length,
- character: Boolean(model.typography.character),
- rules: model.typography.rules.length,
- }
- : 'missing';
-
- report.elevation = model.elevation
- ? {
- shadows: model.elevation.shadows.length,
- rules: model.elevation.rules.length,
- description: Boolean(model.elevation.description),
- }
- : 'missing';
-
- report.components = model.components
- ? {
- count: model.components.components.length,
- variantTotal: model.components.components.reduce((n, c) => n + c.variants.length, 0),
- }
- : 'missing';
-
- report.dosDonts = model.dosDonts
- ? {
- dos: model.dosDonts.dos.length,
- donts: model.dosDonts.donts.length,
- }
- : 'missing';
-
- return report;
-}
-
-// ---------- Main ----------
-
-export function parseDesignMd(md) {
- const { frontmatter, body } = parseFrontmatter(md);
- const { title, sections } = splitSections(body);
- return {
- schemaVersion: 2,
- title,
- frontmatter,
- overview: extractOverview(sections['Overview']),
- colors: extractColors(sections['Colors']),
- typography: extractTypography(sections['Typography']),
- elevation: extractElevation(sections['Elevation']),
- components: extractComponents(sections['Components']),
- dosDonts: extractDosDonts(sections["Do's and Don'ts"]),
- };
-}
-
-export { assessCoverage };
@@ -1,198 +0,0 @@
-/**
- * Scan a project tree for Content-Security-Policy signals and classify the
- * shape so the agent knows which patch template to propose.
- *
- * Used at first-time `live.mjs` setup. Mechanical (grep-based) — no network,
- * no dev server, no JS evaluation. The classification drives a user-facing
- * consent prompt; the agent does the actual patch writing.
- *
- * Shapes are named by patch mechanism, not framework origin:
- * - "append-arrays": CSP defined as structured directive arrays. Patch
- * appends a dev-only localhost entry. Covers:
- * - Monorepo helpers with additional*Src options
- * (e.g. createBaseNextConfig for Next)
- * - SvelteKit kit.csp.directives
- * - nuxt-security module's contentSecurityPolicy
- * - "append-string": CSP built as a literal value string. Patch splices
- * a dev-only token into script-src and connect-src.
- * Covers:
- * - Inline Next.js headers() with CSP string
- * - Nuxt routeRules / nitro.routeRules CSP headers
- * - "middleware": CSP set dynamically in middleware.{ts,js}.
- * Detected but not auto-patched in v1.
- * - "meta-tag": <meta http-equiv="Content-Security-Policy"> in
- * layout files. Detected but not auto-patched in v1.
- * - null: no CSP signals found; no patch needed.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const SKIP_DIRS = new Set([
- 'node_modules',
- '.git',
- '.next',
- '.turbo',
- '.svelte-kit',
- '.nuxt',
- '.astro',
- 'dist',
- 'build',
- 'out',
- '.vercel',
-]);
-
-const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.tsx', '.jsx']);
-const LAYOUT_EXTS = new Set(['.tsx', '.jsx', '.astro', '.vue', '.svelte', '.html']);
-const MAX_DEPTH = 6;
-const MAX_READ_BYTES = 64 * 1024;
-
-// append-arrays signals: CSP expressed as structured directive arrays
-const MONOREPO_HELPER_SIGNALS = [
- /\bbuildCSPConfig\b/,
- /\bbuildSecurityHeaders\b/,
- /\badditionalScriptSrc\b/,
- /\badditionalConnectSrc\b/,
- /\bcreateBaseNextConfig\b/,
-];
-const SVELTEKIT_CSP_SIGNALS = [
- /\bkit\s*:/,
- /\bcsp\s*:/,
- /\bdirectives\s*:/,
-];
-const NUXT_SECURITY_SIGNALS = [
- /['"]nuxt-security['"]/,
- /\bcontentSecurityPolicy\b/,
-];
-
-// append-string signals: CSP written as a literal value string
-const INLINE_HEADER_SIGNALS = [
- /["']Content-Security-Policy["']/i,
- /\bscript-src\b/,
- /\bconnect-src\b/,
-];
-const NUXT_ROUTE_RULES_SIGNALS = [
- /\brouteRules\b/,
- /Content-Security-Policy/i,
- /\bscript-src\b/,
-];
-
-const MIDDLEWARE_HINT = /headers\.set\(\s*["']Content-Security-Policy["']/i;
-const META_TAG_HINT = /http-equiv\s*=\s*["']Content-Security-Policy["']/i;
-
-/**
- * @param {string} cwd Project root.
- * @returns {{ shape: string|null, signals: string[] }}
- */
-export function detectCsp(cwd = process.cwd()) {
- const hits = { appendArrays: [], appendString: [], middleware: [], metaTag: [] };
-
- walk(cwd, cwd, 0, (absPath, relPath, body) => {
- const ext = path.extname(absPath);
- const base = path.basename(absPath).toLowerCase();
- const isConfig = (name) =>
- new RegExp('(^|/)' + name + '\\.config\\.').test(relPath);
-
- // === append-arrays candidates ===
-
- // Monorepo CSP helper: packages/*/src/.../(config|security)/*
- if (SCAN_EXTS.has(ext) &&
- /packages\/[^/]+\/src\/.*(config|next-config|security)/.test(relPath) &&
- MONOREPO_HELPER_SIGNALS.some((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // SvelteKit kit.csp.directives
- if (SCAN_EXTS.has(ext) && isConfig('svelte') &&
- SVELTEKIT_CSP_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // Nuxt nuxt-security module
- if (SCAN_EXTS.has(ext) && isConfig('nuxt') &&
- NUXT_SECURITY_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // === append-string candidates ===
-
- // Inline headers in Next/Nuxt/SvelteKit/Astro/Vite config
- if (SCAN_EXTS.has(ext) &&
- /(^|\/)(next|nuxt|vite|astro|svelte)\.config\./.test(relPath) &&
- INLINE_HEADER_SIGNALS.every((re) => re.test(body))) {
- // Nuxt routeRules is a sub-shape of append-string; we already covered
- // nuxt-security above via return, so any remaining Nuxt CSP match here
- // is a route-rules / inline-headers case. Either way, same patch
- // mechanism.
- hits.appendString.push(relPath);
- return;
- }
-
- // === detect-only shapes ===
-
- if ((base === 'middleware.ts' || base === 'middleware.js' || base === 'middleware.mjs') &&
- MIDDLEWARE_HINT.test(body)) {
- hits.middleware.push(relPath);
- }
-
- if (LAYOUT_EXTS.has(ext) && META_TAG_HINT.test(body)) {
- hits.metaTag.push(relPath);
- }
- });
-
- // Priority: append-arrays > append-string > middleware > meta-tag.
- // Structured patches are safer than string splices; runtime and HTML
- // injection patches are less reliable and v1 doesn't auto-apply them.
- if (hits.appendArrays.length > 0) {
- return { shape: 'append-arrays', signals: hits.appendArrays };
- }
- if (hits.appendString.length > 0) {
- return { shape: 'append-string', signals: hits.appendString };
- }
- if (hits.middleware.length > 0) {
- return { shape: 'middleware', signals: hits.middleware };
- }
- if (hits.metaTag.length > 0) {
- return { shape: 'meta-tag', signals: hits.metaTag };
- }
- return { shape: null, signals: [] };
-}
-
-function walk(root, dir, depth, visit) {
- if (depth > MAX_DEPTH) return;
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
-
- for (const entry of entries) {
- const abs = path.join(dir, entry.name);
- if (entry.isDirectory()) {
- if (SKIP_DIRS.has(entry.name)) continue;
- walk(root, abs, depth + 1, visit);
- continue;
- }
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name);
- if (!SCAN_EXTS.has(ext) && !LAYOUT_EXTS.has(ext)) continue;
- let body;
- try {
- const fd = fs.openSync(abs, 'r');
- try {
- const buf = Buffer.alloc(MAX_READ_BYTES);
- const n = fs.readSync(fd, buf, 0, MAX_READ_BYTES, 0);
- body = buf.slice(0, n).toString('utf-8');
- } finally { fs.closeSync(fd); }
- } catch { continue; }
- visit(abs, path.relative(root, abs), body);
- }
-}
-
-// CLI mode
-const _running = process.argv[1];
-if (_running?.endsWith('detect-csp.mjs') || _running?.endsWith('detect-csp.mjs/')) {
- const result = detectCsp(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
@@ -1,21 +0,0 @@
-#!/usr/bin/env node
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { pathToFileURL, fileURLToPath } from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const candidates = [
- path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
-];
-const detectorPath = candidates.find(p => fs.existsSync(p));
-
-if (!detectorPath) {
- process.stderr.write('Error: bundled detector not found.\n');
- process.exit(1);
-}
-
-const { detectCli } = await import(pathToFileURL(detectorPath));
-
-await detectCli();
@@ -1,1688 +0,0 @@
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
@@ -1,232 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
-import { detectHtml } from '../engines/static-html/detect-html.mjs';
-import { detectText } from '../engines/regex/detect-text.mjs';
-import {
- HTML_EXTENSIONS,
- buildImportGraph,
- detectFrameworkConfig,
- isPortListening,
- walkDir,
-} from '../node/file-system.mjs';
-
-// ---------------------------------------------------------------------------
-// Output formatting
-// ---------------------------------------------------------------------------
-
-function formatFindings(findings, jsonMode) {
- if (jsonMode) return JSON.stringify(findings, null, 2);
-
- const grouped = {};
- for (const f of findings) {
- if (!grouped[f.file]) grouped[f.file] = [];
- grouped[f.file].push(f);
- }
- const out = [];
- for (const [file, items] of Object.entries(grouped)) {
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
- out.push(`\n${file}${importNote}`);
- for (const item of items) {
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
- out.push(` → ${item.description}`);
- }
- }
- out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
- return out.join('\n');
-}
-
-// ---------------------------------------------------------------------------
-// Stdin handling
-// ---------------------------------------------------------------------------
-
-async function handleStdin() {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- const input = Buffer.concat(chunks).toString('utf-8');
- try {
- const parsed = JSON.parse(input);
- const fp = parsed?.tool_input?.file_path;
- if (fp && fs.existsSync(fp)) {
- return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
- ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
- }
- } catch { /* not JSON */ }
- return detectText(input, '<stdin>');
-}
-
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-async function confirm(question) {
- const rl = (await import('node:readline')).default.createInterface({
- input: process.stdin, output: process.stderr,
- });
- return new Promise((resolve) => {
- rl.question(`${question} [Y/n] `, (answer) => {
- rl.close();
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
- });
- });
-}
-
-function printUsage() {
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
-
-Scan files or URLs for UI anti-patterns and design quality issues.
-
-Options:
- --fast Regex-only mode (skip static HTML/CSS analysis, faster but misses linked stylesheets)
- --json Output results as JSON
- --help Show this help message
-
-Detection modes:
- HTML files Static HTML/CSS analysis (default, catches linked CSS)
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
- URLs Puppeteer full browser rendering (auto-detected)
- --fast Forces regex for all files
-
-Examples:
- impeccable detect src/
- impeccable detect index.html
- impeccable detect https://example.com
- impeccable detect --fast --json .`);
-}
-
-async function detectCli() {
- let args = process.argv.slice(2).map(arg => {
- if (arg === '-json') return '--json';
- if (arg === '-fast') return '--fast';
- return arg;
- });
- if (args[0] === 'detect') args = args.slice(1);
- const jsonMode = args.includes('--json');
- const helpMode = args.includes('--help');
- const fastMode = args.includes('--fast');
- const targets = args.filter(a => !a.startsWith('--'));
-
- if (helpMode) { printUsage(); process.exit(0); }
-
- let allFindings = [];
-
- if (!process.stdin.isTTY && targets.length === 0) {
- allFindings = await handleStdin();
- } else {
- const paths = targets.length > 0 ? targets : [process.cwd()];
- const urlTargetCount = paths.filter(target => /^https?:\/\//i.test(target)).length;
- const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
-
- try {
- for (const target of paths) {
- if (/^https?:\/\//i.test(target)) {
- try {
- const scanner = browserDetector
- ? (url) => browserDetector.detectUrl(url)
- : (url) => detectUrl(url);
- allFindings.push(...await scanner(target));
- } catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
- continue;
- }
-
- const resolved = path.resolve(target);
- let stat;
- try { stat = fs.statSync(resolved); }
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
-
- if (stat.isDirectory()) {
- // Check for framework dev server config (skip in JSON mode to avoid polluting output)
- if (!jsonMode) {
- const fwConfig = detectFrameworkConfig(resolved);
- if (fwConfig) {
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
- if (probe.listening && probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
- `For more accurate results, scan the running site:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- } else if (probe.listening && !probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
- );
- } else {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Start the dev server and scan via URL for best results:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- }
- }
- }
-
- const files = walkDir(resolved);
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
-
- // Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
- if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
- process.stderr.write(
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
- `Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
- `Use --fast to skip static HTML/CSS analysis, or target a specific subdirectory.\n`
- );
- const ok = await confirm('Continue?');
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
- }
-
- // Build import graph for multi-file awareness
- const graph = buildImportGraph(files);
- // Build reverse map: file -> set of files that import it
- const importedByMap = new Map();
- for (const [importer, imports] of graph) {
- for (const imported of imports) {
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
- importedByMap.get(imported).add(importer);
- }
- }
-
- for (const file of files) {
- const ext = path.extname(file).toLowerCase();
- let fileFindings;
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- fileFindings = await detectHtml(file);
- } else {
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
- }
- // Annotate findings with import context
- const importers = importedByMap.get(file);
- if (importers && importers.size > 0) {
- const importerNames = [...importers].map(f => path.basename(f));
- for (const f of fileFindings) {
- f.importedBy = importerNames;
- }
- }
- allFindings.push(...fileFindings);
- }
- } else if (stat.isFile()) {
- const ext = path.extname(resolved).toLowerCase();
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- allFindings.push(...await detectHtml(resolved));
- } else {
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
- }
- }
- }
- } finally {
- if (browserDetector) await browserDetector.close();
- }
- }
-
- if (allFindings.length > 0) {
- if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
- else process.stderr.write(formatFindings(allFindings, false) + '\n');
- process.exit(2);
- }
- if (jsonMode) process.stdout.write('[]\n');
- process.exit(0);
-}
-
-export { formatFindings, handleStdin, confirm, printUsage, detectCli };
@@ -1,4030 +0,0 @@
-/**
- * Anti-Pattern Browser Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * GENERATED -- do not edit. Source: cli/engine/browser/injected/index.mjs
- * Rebuild: node scripts/build-browser-detector.js
- *
- * Usage: <script src="detect-antipatterns-browser.js"></script>
- * Re-scan: window.impeccableScan()
- */
-(function () {
-if (typeof window === 'undefined') return;
-// --- cli/engine/shared/constants.mjs ---
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-// --- cli/engine/registry/antipatterns.mjs ---
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-// --- cli/engine/shared/color.mjs ---
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-// --- cli/engine/rules/checks.mjs ---
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-// --- cli/engine/browser/injected/index.mjs ---
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
-
-})();
@@ -1,43 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Anti-Pattern Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * Public API facade. Runtime engines live under cli/engine/engines/.
- */
-
-import { detectCli } from './cli/main.mjs';
-
-export { ANTIPATTERNS, RULE_ENGINE_SUPPORT, getAntipattern, getRulesForCategory, getRuleEngineSupport } from './registry/antipatterns.mjs';
-export { SAFE_TAGS, BORDER_SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS, KNOWN_SERIF_FONTS } from './shared/constants.mjs';
-export { isNeutralColor, parseRgb, relativeLuminance, contrastRatio, parseGradientColors, hasChroma, getHue, colorToHex } from './shared/color.mjs';
-export { isFullPage } from './shared/page.mjs';
-export {
- checkElementBorders,
- checkElementMotion,
- checkElementGlow,
- checkPageTypography,
- checkPageLayout,
- checkHtmlPatterns,
-} from './rules/checks.mjs';
-export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
-export { detectHtml } from './engines/static-html/detect-html.mjs';
-export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
-export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
-export {
- walkDir,
- SCANNABLE_EXTENSIONS,
- SKIP_DIRS,
- buildImportGraph,
- resolveImport,
- detectFrameworkConfig,
- isPortListening,
- FRAMEWORK_CONFIGS,
-} from './node/file-system.mjs';
-export { formatFindings, detectCli } from './cli/main.mjs';
-
-const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
-if (isMainModule) detectCli();
@@ -1,251 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { finding } from '../../findings.mjs';
-import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
-
-async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
- if (options?.visualContrast === false) return [];
- const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : 12;
- const scrollOffscreen = options?.visualContrastScrollOffscreen !== false;
- const existingLowContrastSelectors = new Set(
- serializedGroups
- .filter(group => group.findings?.some(f => f.type === 'low-contrast'))
- .map(group => group.selector)
- .filter(Boolean)
- );
-
- let browserAnalyses = [];
- const findings = [];
- if (options?.visualContrastBrowser !== false) {
- const browserFindings = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'browser-fallback',
- target,
- }, async () => {
- browserAnalyses = await page.evaluate(async ({ maxCandidates, scrollOffscreen }) => {
- if (typeof window.impeccableAnalyzeVisualContrast !== 'function') return [];
- return window.impeccableAnalyzeVisualContrast({ maxCandidates, scrollOffscreen });
- }, { maxCandidates, scrollOffscreen });
- return browserAnalyses
- .filter(result => result.finding && !existingLowContrastSelectors.has(result.selector))
- .map(result => result.finding);
- });
- findings.push(...browserFindings);
- }
-
- let candidates = browserAnalyses.length > 0 ? browserAnalyses : [];
- if (candidates.length === 0) {
- candidates = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'collect-candidates',
- target,
- }, () => page.evaluate(({ maxCandidates }) => {
- if (typeof window.impeccableCollectVisualContrastCandidates !== 'function') return [];
- return window.impeccableCollectVisualContrastCandidates({ maxCandidates });
- }, { maxCandidates }));
- }
-
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const browserResolvedSelectors = new Set(
- browserAnalyses
- .filter(result => result.status === 'fail' || result.status === 'pass')
- .map(result => result.selector)
- .filter(Boolean)
- );
- const filtered = candidates.filter(candidate =>
- !existingLowContrastSelectors.has(candidate.selector) &&
- !browserResolvedSelectors.has(candidate.selector)
- );
- if (options?.visualContrastPixel === false) return findings;
- for (const candidate of filtered) {
- const result = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'pixel-diff',
- target,
- }, async () => {
- const finding = await captureVisualContrastCandidate(page, candidate, viewport);
- return finding ? [finding] : [];
- });
- findings.push(...result);
- }
- return findings;
-}
-
-// ---------------------------------------------------------------------------
-// Puppeteer detection (for URLs)
-// ---------------------------------------------------------------------------
-
-async function detectUrl(url, options = {}) {
- const profile = options?.profile;
- const waitUntil = options?.waitUntil || 'networkidle0';
- const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const externalBrowser = options?.browser || null;
- let puppeteer;
- if (!externalBrowser) {
- try {
- puppeteer = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'import-puppeteer',
- target: url,
- }, () => import('puppeteer'));
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- }
-
- // Read the browser detection script — reuse it instead of reimplementing
- const browserScriptPath = path.resolve(
- path.dirname(fileURLToPath(import.meta.url)),
- '..',
- '..',
- 'detect-antipatterns-browser.js'
- );
- let browserScript;
- try {
- browserScript = profileStep(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'read-browser-script',
- target: url,
- }, () => fs.readFileSync(browserScriptPath, 'utf-8'));
- } catch {
- throw new Error(`Browser script not found at ${browserScriptPath}`);
- }
-
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
- // running in CI; local users keep the default hardened launch.
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
- const browser = externalBrowser || await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'launch-browser',
- target: url,
- }, () => puppeteer.default.launch({ headless: true, args: launchArgs }));
- const page = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'new-page',
- target: url,
- }, () => browser.newPage());
- let results = [];
- try {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'set-viewport',
- target: url,
- }, () => page.setViewport(viewport));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: `goto:${waitUntil}`,
- target: url,
- }, () => page.goto(url, { waitUntil, timeout: 30000 }));
- if (settleMs > 0) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'settle',
- target: url,
- }, () => new Promise(resolve => setTimeout(resolve, settleMs)));
- }
-
- // Inject the browser detection script and collect results
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'configure-pure-detect',
- target: url,
- }, () => page.evaluate(() => {
- window.__IMPECCABLE_CONFIG__ = {
- ...(window.__IMPECCABLE_CONFIG__ || {}),
- autoScan: false,
- };
- }));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'inject-browser-script',
- target: url,
- }, () => page.evaluate(browserScript));
- let serializedGroups = [];
- results = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'browser-scan',
- target: url,
- }, async () => {
- serializedGroups = await page.evaluate(() => {
- if (!window.impeccableDetect) return [];
- return window.impeccableDetect({ decorate: false, serialize: true });
- });
- return serializedGroups.flatMap(({ findings }) =>
- findings.map(f => ({ id: f.type, snippet: f.detail }))
- );
- });
- const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
- results.push(...visualFindings);
- } finally {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-page',
- target: url,
- }, () => page.close().catch(() => {}));
- if (!externalBrowser) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-browser',
- target: url,
- }, () => browser.close());
- }
- }
- return results.map(f => finding(f.id, url, f.snippet));
-}
-
-async function createBrowserDetector(options = {}) {
- let puppeteer;
- try {
- puppeteer = await import('puppeteer');
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- const launchArgs = options.launchArgs || (process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : []);
- const browser = options.browser || await puppeteer.default.launch({
- headless: options.headless ?? true,
- args: launchArgs,
- });
- const ownsBrowser = !options.browser;
- const defaults = {
- waitUntil: options.waitUntil || 'load',
- settleMs: Number.isFinite(options.settleMs) ? options.settleMs : 100,
- viewport: options.viewport || { width: 1280, height: 800 },
- };
- return {
- browser,
- async detectUrl(url, scanOptions = {}) {
- return detectUrl(url, {
- ...defaults,
- ...scanOptions,
- browser,
- });
- },
- async close() {
- if (ownsBrowser) await browser.close().catch(() => {});
- },
- };
-}
-
-export { runVisualContrastFallback, detectUrl, createBrowserDetector };
@@ -1,420 +0,0 @@
-import { GENERIC_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep } from '../../profile/profiler.mjs';
-
-// ---------------------------------------------------------------------------
-// Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
-// ---------------------------------------------------------------------------
-
-const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
-const hasBorderRadius = (line) => /border-radius/i.test(line);
-const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
-
-function isNeutralBorderColor(str) {
- const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
- if (!m) return false;
- const c = m[1].toLowerCase();
- if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
- const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
- if (hex) {
- const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
- if (shex) {
- const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- return false;
-}
-
-const REGEX_MATCHERS = [
- // --- Side-tab ---
- { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
- test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
- test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
- fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
- { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
- test: (m) => +m[1] >= 3,
- fmt: (m) => m[0] },
- // --- Border accent on rounded ---
- { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
- test: (m, line) => hasRounded(line) && +m[1] >= 1,
- fmt: (m) => m[0] },
- { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
- fmt: (m) => m[0] },
- // --- Overused font ---
- { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
- test: () => true,
- fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
- // --- Pure black background ---
- { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Gradient text ---
- { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
- test: (m, line) => /gradient/i.test(line),
- fmt: () => 'background-clip: text + gradient' },
- // --- Gradient text (Tailwind) ---
- { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
- test: (m, line) => /\bbg-gradient-to-/i.test(line),
- fmt: () => 'bg-clip-text + bg-gradient' },
- // --- Tailwind pure black background ---
- { id: 'pure-black-white', regex: /\bbg-black\b/g,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Tailwind gray on colored bg ---
- { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
- test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
- fmt: (m, line) => { const bg = line.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/); return `${m[0]} on ${bg?.[0] || '?'}`; } },
- // --- Tailwind AI palette ---
- { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
- fmt: (m) => `${m[0]} on heading` },
- { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
- fmt: (m) => `${m[0]} gradient` },
- // --- Bounce/elastic easing ---
- { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
- test: () => true,
- fmt: () => 'animate-bounce (Tailwind)' },
- { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
- test: (m) => {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
- },
- fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
- // --- Layout property transition ---
- { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition: ${found ? found.join(', ') : m[1].trim()}`;
- } },
- { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
- } },
-];
-
-const REGEX_ANALYZERS = [
- // Single font
- (content, filePath) => {
- const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
- const fonts = new Set();
- let m;
- while ((m = fontFamilyRe.exec(content)) !== null) {
- for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
- }
- }
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- while ((m = gfRe.exec(content)) !== null) {
- for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
- }
- if (fonts.size !== 1 || content.split('\n').length < 20) return [];
- const name = [...fonts][0];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
- return [finding('single-font', filePath, `only font used is ${name}`, line)];
- },
- // Flat type hierarchy
- (content, filePath) => {
- const sizes = new Set();
- const REM = 16;
- let m;
- const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
- while ((m = sizeRe.exec(content)) !== null) {
- const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
- if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
- }
- const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
- while ((m = clampRe.exec(content)) !== null) {
- sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
- sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
- }
- const TW = { 'text-xs': 12, 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24, 'text-3xl': 30, 'text-4xl': 36, 'text-5xl': 48, 'text-6xl': 60, 'text-7xl': 72, 'text-8xl': 96, 'text-9xl': 128 };
- for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
- if (sizes.size < 3) return [];
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio >= 2.0) return [];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (/font-size/i.test(lines[i]) || /\btext-(?:xs|sm|base|lg|xl|\d)/i.test(lines[i])) { line = i + 1; break; } }
- return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
- },
- // Monotonous spacing (regex)
- (content, filePath) => {
- const vals = [];
- let m;
- const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
- const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
- const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
- const rounded = vals.map(v => Math.round(v / 4) * 4);
- if (rounded.length < 10) return [];
- const counts = {};
- for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const pct = maxCount / rounded.length;
- const unique = [...new Set(rounded)].filter(v => v > 0);
- if (pct <= 0.6 || unique.length > 3) return [];
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
- },
- // Everything centered (regex)
- (content, filePath) => {
- const lines = content.split('\n');
- let centered = 0, total = 0;
- for (const line of lines) {
- if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
- total++;
- if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
- }
- }
- if (total < 5 || centered / total <= 0.7) return [];
- return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
- },
- // Dark glow (page-level: dark bg + colored box-shadow with blur)
- (content, filePath) => {
- // Check if page has a dark background
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
- if (!hasDarkBg) return [];
-
- // Check for colored box-shadow with blur > 4px
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let m;
- while ((m = shadowRe.exec(content)) !== null) {
- const val = m[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
- // Check blur: look for pattern like "0 0 20px" (third number > 4)
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- const lines = content.substring(0, m.index).split('\n');
- return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
- }
- }
- return [];
- },
-];
-
-// ---------------------------------------------------------------------------
-// Style block extraction (Vue/Svelte <style> blocks)
-// ---------------------------------------------------------------------------
-
-function extractStyleBlocks(content, ext) {
- ext = ext.toLowerCase();
- if (ext !== '.vue' && ext !== '.svelte') return [];
- const blocks = [];
- const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length + 1;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-// ---------------------------------------------------------------------------
-// CSS-in-JS extraction (styled-components, emotion)
-// ---------------------------------------------------------------------------
-
-const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
-
-function extractCSSinJS(content, ext) {
- ext = ext.toLowerCase();
- if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
- const blocks = [];
- const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null, options = {}) {
- const { profile, phase = 'regex-matchers' } = options || {};
- const findings = [];
- if (!profile) {
- for (const matcher of REGEX_MATCHERS) {
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- }
- return findings;
- }
-
- for (const matcher of REGEX_MATCHERS) {
- const matcherFindings = profileFindings(profile, {
- engine: 'regex',
- phase,
- ruleId: matcher.id,
- target: filePath,
- }, () => {
- const matches = [];
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- matches.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- return matches;
- });
- findings.push(...matcherFindings);
- }
- return findings;
-}
-
-function detectText(content, filePath, options = {}) {
- const profile = options?.profile;
- const findings = [];
- const lines = content.split('\n');
- const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
-
- // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
- // Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
- findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
- profile,
- phase: 'source',
- }));
-
- // Extract and scan <style> blocks from Vue/Svelte SFCs
- const styleBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'style-blocks',
- target: filePath,
- }, () => extractStyleBlocks(content, ext))
- : extractStyleBlocks(content, ext);
- for (const block of styleBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'style-block',
- }));
- }
-
- // Extract and scan CSS-in-JS template literals
- const cssJsBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'css-in-js',
- target: filePath,
- }, () => extractCSSinJS(content, ext))
- : extractCSSinJS(content, ext);
- for (const block of cssJsBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'css-in-js',
- }));
- }
-
- // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
- const deduped = [];
- for (const f of findings) {
- const isDupe = deduped.some(d =>
- d.antipattern === f.antipattern &&
- d.snippet === f.snippet &&
- Math.abs(d.line - f.line) <= 2
- );
- if (!isDupe) deduped.push(f);
- }
-
- // Page-level analyzers only run on full pages
- if (isFullPage(content)) {
- const analyzerIds = [
- 'single-font',
- 'flat-type-hierarchy',
- 'monotonous-spacing',
- 'everything-centered',
- 'dark-glow',
- ];
- for (let i = 0; i < REGEX_ANALYZERS.length; i++) {
- const analyzer = REGEX_ANALYZERS[i];
- deduped.push(...profileFindings(profile, {
- engine: 'regex',
- phase: 'page-analyzer',
- ruleId: analyzerIds[i] || `analyzer-${i + 1}`,
- target: filePath,
- }, () => analyzer(content, filePath)));
- }
- }
-
- return deduped;
-}
-
-export {
- REGEX_MATCHERS,
- REGEX_ANALYZERS,
- extractStyleBlocks,
- extractCSSinJS,
- runRegexMatchers,
- detectText,
-};
@@ -1,954 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { profileStep, recordProfileEvent } from '../../profile/profiler.mjs';
-import { parseAnyColor, resolveLengthPx, resolveVarRefs } from '../../rules/checks.mjs';
-
-// ---------------------------------------------------------------------------
-// jsdom CSS-variable border override map
-// ---------------------------------------------------------------------------
-//
-// jsdom's CSSOM silently drops any border shorthand that contains a var()
-// reference — the computed style for the element then shows empty width,
-// empty style, and a default black color. That's enough to hide the most
-// common real-world side-tab pattern in AI-generated pages:
-//
-// :root { --brand: #87a8ff; }
-// .card { border-left: 5px solid var(--brand); border-radius: 4px; }
-//
-// Real browsers (and therefore the browser detector path) resolve var()
-// natively, so this only affects the Node jsdom path.
-//
-// This pre-pass walks the stylesheets, finds any rule whose per-side or
-// all-sides border property contains var(), resolves the var() against
-// :root-level custom properties (read from the documentElement's computed
-// style, which jsdom DOES handle correctly), and attaches the resolved
-// width+color to every element that matches the rule's selector. The
-// Node-side `checkElementBorders` adapter consumes that map as a fallback
-// whenever jsdom's computed style came back empty.
-//
-// Limitations (intentional, to keep the pass simple):
-// * Only :root-level custom properties are resolved. Scoped overrides on
-// descendants are not tracked — uncommon in practice and would require
-// a per-element cascade walk.
-// * @media / @supports wrapped rules are ignored (jsdom often mishandles
-// these anyway).
-// * The fallback only fills sides that jsdom left empty, so any rule
-// whose border parses normally still wins via the computed style.
-
-const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
-
-// isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
-// CSS variables typically hold hex or named colors, so normalize those to
-// rgb() before handing the value off to the shared check. Anything we don't
-// recognise is passed through unchanged — isNeutralColor then treats it as
-// non-neutral, which is the safer default (matches the oklch-era bugfix).
-const NAMED_COLORS = {
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
-};
-
-function normalizeColorForCheck(value) {
- if (!value) return value;
- const v = value.trim();
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
- if (hex6) {
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
- if (hex3) {
- const [r, g, b] = [
- parseInt(hex3[1] + hex3[1], 16),
- parseInt(hex3[2] + hex3[2], 16),
- parseInt(hex3[3] + hex3[3], 16),
- ];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const named = NAMED_COLORS[v.toLowerCase()];
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
- return v;
-}
-
-function buildBorderOverrideMap(document, window) {
- const map = new Map();
- const rootStyle = window.getComputedStyle(document.documentElement);
-
- function resolveVar(value, depth = 0) {
- if (!value || depth > 10 || !value.includes('var(')) return value;
- return value.replace(
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
- (_, name, fallback) => {
- const v = rootStyle.getPropertyValue(name).trim();
- if (v) return resolveVar(v, depth + 1);
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
- return '';
- }
- );
- }
-
- function parseShorthand(text) {
- const m = text.trim().match(BORDER_SHORTHAND_RE);
- if (!m) return null;
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
- }
-
- // Read from the per-property accessors on rule.style. jsdom preserves
- // each border-* shorthand it parsed, even when the overall cssText has
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
- // `border-left: ...` loses the first declaration but keeps the second).
- const SIDE_PROPS = [
- ['borderLeft', 'Left'],
- ['borderRight', 'Right'],
- ['borderTop', 'Top'],
- ['borderBottom', 'Bottom'],
- ['borderInlineStart', 'Left'],
- ['borderInlineEnd', 'Right'],
- ];
-
- for (const sheet of document.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || []; } catch { continue; }
- for (const rule of rules) {
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
-
- const perSide = {};
-
- for (const [prop, side] of SIDE_PROPS) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const parsed = parseShorthand(resolveVar(val));
- if (parsed && parsed.color) perSide[side] = parsed;
- }
-
- // Uniform `border: <w> <style> var(...)` applies to every side the
- // per-side map didn't already claim.
- const borderAll = rule.style.border;
- if (borderAll && borderAll.includes('var(')) {
- const parsed = parseShorthand(resolveVar(borderAll));
- if (parsed && parsed.color) {
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
- if (!perSide[s]) perSide[s] = parsed;
- }
- }
- }
-
- // Longhand `border-*-color: var(...)` with width/style in separate
- // declarations. Rare in AI-generated pages, but cheap to cover.
- for (const [prop, side] of [
- ['borderLeftColor', 'Left'],
- ['borderRightColor', 'Right'],
- ['borderTopColor', 'Top'],
- ['borderBottomColor', 'Bottom'],
- ]) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const resolved = resolveVar(val).trim();
- if (!resolved) continue;
- // Width may or may not come from this rule — that's fine; the
- // adapter only substitutes the color when jsdom left it as a
- // literal var() string.
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
- }
-
- if (Object.keys(perSide).length === 0) continue;
-
- let matched;
- try { matched = document.querySelectorAll(rule.selectorText); }
- catch { continue; }
-
- for (const el of matched) {
- const existing = map.get(el);
- if (existing) {
- // Later rules overwrite earlier ones — approximates source-order
- // cascade for equal-specificity rules and is good enough for the
- // uncontested var()-dropped sides we're trying to recover.
- Object.assign(existing, perSide);
- } else {
- map.set(el, { ...perSide });
- }
- }
- }
- }
-
- return map;
-}
-
-// Strip `@layer NAME { … }` wrappers from a CSS / HTML source, leaving
-// the inner rules as flat CSS. jsdom doesn't implement CSS @layer, so
-// any rule inside a layer block becomes invisible to getComputedStyle.
-// Tailwind v4 makes this ubiquitous: every utility class lives in
-// `@layer utilities`, and Preflight lives in `@layer base`. Without
-// unwrapping, every Tailwind-styled element returns empty computed
-// styles. We walk the source character-by-character, balancing braces
-// so we correctly handle nested style rules inside the layer block.
-function unwrapCssAtLayer(source) {
- if (!source || !source.includes('@layer')) return source;
- // Find `@layer <name>? {` openers. The match starts at the @, and
- // we then balance braces from the opening { onward.
- const re = /@layer\b[^{;]*\{/g;
- let out = '';
- let lastIdx = 0;
- let m;
- while ((m = re.exec(source)) !== null) {
- const openStart = m.index;
- const openEnd = m.index + m[0].length; // position right after `{`
- let depth = 1;
- let i = openEnd;
- while (i < source.length && depth > 0) {
- const c = source.charCodeAt(i);
- if (c === 0x7b /* { */) depth++;
- else if (c === 0x7d /* } */) depth--;
- i++;
- }
- if (depth !== 0) {
- // Unbalanced — bail and return source unchanged.
- return source;
- }
- // Emit everything before the @layer, then the inner contents
- // (between the opening { and the matched closing }), then advance.
- out += source.slice(lastIdx, openStart);
- out += source.slice(openEnd, i - 1); // i-1 = position of the closing }
- lastIdx = i;
- re.lastIndex = i;
- }
- out += source.slice(lastIdx);
- return out;
-}
-
-// ---------------------------------------------------------------------------
-// Static HTML/CSS detection (default for local HTML files)
-// ---------------------------------------------------------------------------
-
-const STATIC_INHERITED_PROPS = new Set([
- 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight',
- 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'hyphens',
- 'webkitHyphens',
-]);
-
-const STATIC_DEFAULT_STYLE = {
- color: 'rgb(0, 0, 0)',
- backgroundColor: 'rgba(0, 0, 0, 0)',
- backgroundImage: 'none',
- borderTopWidth: '0px',
- borderRightWidth: '0px',
- borderBottomWidth: '0px',
- borderLeftWidth: '0px',
- borderTopColor: 'rgb(0, 0, 0)',
- borderRightColor: 'rgb(0, 0, 0)',
- borderBottomColor: 'rgb(0, 0, 0)',
- borderLeftColor: 'rgb(0, 0, 0)',
- borderRadius: '0px',
- boxShadow: 'none',
- fontFamily: '',
- fontSize: '16px',
- fontStyle: 'normal',
- fontWeight: '400',
- lineHeight: 'normal',
- letterSpacing: 'normal',
- textTransform: 'none',
- textAlign: 'start',
- hyphens: 'manual',
- webkitHyphens: 'manual',
- transitionProperty: '',
- transitionTimingFunction: '',
- animationName: '',
- animationTimingFunction: '',
- webkitBackgroundClip: '',
- backgroundClip: '',
- width: '',
- height: '',
- paddingTop: '0px',
- paddingRight: '0px',
- paddingBottom: '0px',
- paddingLeft: '0px',
- position: 'static',
- display: '',
-};
-
-const STATIC_PROP_MAP = {
- 'background-color': 'backgroundColor',
- 'background-image': 'backgroundImage',
- 'background-clip': 'backgroundClip',
- '-webkit-background-clip': 'webkitBackgroundClip',
- 'border-radius': 'borderRadius',
- 'border-top-width': 'borderTopWidth',
- 'border-right-width': 'borderRightWidth',
- 'border-bottom-width': 'borderBottomWidth',
- 'border-left-width': 'borderLeftWidth',
- 'border-top-color': 'borderTopColor',
- 'border-right-color': 'borderRightColor',
- 'border-bottom-color': 'borderBottomColor',
- 'border-left-color': 'borderLeftColor',
- 'box-shadow': 'boxShadow',
- 'font-family': 'fontFamily',
- 'font-size': 'fontSize',
- 'font-style': 'fontStyle',
- 'font-weight': 'fontWeight',
- 'line-height': 'lineHeight',
- 'letter-spacing': 'letterSpacing',
- 'text-transform': 'textTransform',
- 'text-align': 'textAlign',
- 'hyphens': 'hyphens',
- '-webkit-hyphens': 'webkitHyphens',
- 'transition-property': 'transitionProperty',
- 'transition-timing-function': 'transitionTimingFunction',
- 'animation-name': 'animationName',
- 'animation-timing-function': 'animationTimingFunction',
- 'width': 'width',
- 'height': 'height',
- 'padding-top': 'paddingTop',
- 'padding-right': 'paddingRight',
- 'padding-bottom': 'paddingBottom',
- 'padding-left': 'paddingLeft',
- 'position': 'position',
- 'display': 'display',
-};
-
-const STATIC_NAMED_COLORS = {
- black: { r: 0, g: 0, b: 0, a: 1 },
- white: { r: 255, g: 255, b: 255, a: 1 },
- transparent: { r: 0, g: 0, b: 0, a: 0 },
- gray: { r: 128, g: 128, b: 128, a: 1 },
- grey: { r: 128, g: 128, b: 128, a: 1 },
- silver: { r: 192, g: 192, b: 192, a: 1 },
- red: { r: 255, g: 0, b: 0, a: 1 },
- green: { r: 0, g: 128, b: 0, a: 1 },
- blue: { r: 0, g: 0, b: 255, a: 1 },
-};
-
-function splitCssList(value) {
- const parts = [];
- let depth = 0, quote = '', start = 0;
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; continue; }
- if (ch === '(' || ch === '[') depth++;
- else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);
- else if (ch === ',' && depth === 0) {
- parts.push(value.slice(start, i).trim());
- start = i + 1;
- }
- }
- const tail = value.slice(start).trim();
- if (tail) parts.push(tail);
- return parts;
-}
-
-function splitCssTokens(value) {
- const tokens = [];
- let depth = 0, quote = '', current = '';
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- current += ch;
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
- if (ch === '(') { depth++; current += ch; continue; }
- if (ch === ')') { depth = Math.max(0, depth - 1); current += ch; continue; }
- if (/\s/.test(ch) && depth === 0) {
- if (current) { tokens.push(current); current = ''; }
- continue;
- }
- current += ch;
- }
- if (current) tokens.push(current);
- return tokens;
-}
-
-function cssPropToCamel(prop) {
- if (!prop) return prop;
- const mapped = STATIC_PROP_MAP[prop];
- if (mapped) return mapped;
- return prop.replace(/-([a-z])/g, (_m, ch) => ch.toUpperCase());
-}
-
-function staticColorToCss(c) {
- if (!c) return '';
- if (c.a != null && c.a < 1) return `rgba(${c.r}, ${c.g}, ${c.b}, ${Number(c.a.toFixed(3))})`;
- return `rgb(${c.r}, ${c.g}, ${c.b})`;
-}
-
-function parseStaticColor(value) {
- const parsed = parseAnyColor(value);
- if (parsed) return parsed;
- const named = STATIC_NAMED_COLORS[String(value || '').trim().toLowerCase()];
- return named ? { ...named } : null;
-}
-
-function extractStaticColor(value) {
- if (!value) return '';
- const raw = String(value).trim();
- if (/^var\(/i.test(raw)) return raw;
- const colorLike = raw.match(/(?:rgba?\([^)]+\)|oklch\([^)]+\)|oklab\([^)]+\)|lch\([^)]+\)|lab\([^)]+\)|hsla?\([^)]+\)|hwb\([^)]+\)|#[0-9a-f]{3,8}\b|\b(?:black|white|gray|grey|silver|red|green|blue|transparent)\b)/i);
- if (!colorLike) return '';
- return colorLike[0];
-}
-
-function normalizeStaticCssValue(prop, value, customProps, parentStyle, currentStyle = null) {
- let resolved = resolveVarRefs(String(value || '').trim(), customProps);
- if (resolved === 'inherit') return parentStyle?.[prop] || STATIC_DEFAULT_STYLE[prop] || '';
- const isModernBorderColor = /^border[A-Z][a-z]+Color$/.test(prop) && /^(?:oklch|oklab|lch|lab|hsl|hwb)\(/i.test(resolved);
- if (!isModernBorderColor && (/color$/i.test(prop) || prop === 'color' || prop === 'backgroundColor')) {
- const parsed = parseStaticColor(resolved);
- if (parsed) resolved = staticColorToCss(parsed);
- }
- if (prop === 'fontSize') {
- const base = parseFloat(parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'letterSpacing') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'lineHeight' && resolved !== 'normal') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- return resolved;
-}
-
-function expandStaticBoxValues(tokens) {
- if (tokens.length === 0) return ['0px', '0px', '0px', '0px'];
- if (tokens.length === 1) return [tokens[0], tokens[0], tokens[0], tokens[0]];
- if (tokens.length === 2) return [tokens[0], tokens[1], tokens[0], tokens[1]];
- if (tokens.length === 3) return [tokens[0], tokens[1], tokens[2], tokens[1]];
- return [tokens[0], tokens[1], tokens[2], tokens[3]];
-}
-
-function parseStaticBorder(value) {
- const tokens = splitCssTokens(value);
- let width = '', color = '';
- for (const token of tokens) {
- if (!width && /^-?[\d.]+(?:px|rem|em|%)$/.test(token)) width = token;
- if (!color) color = extractStaticColor(token);
- }
- return { width, color };
-}
-
-function parseStaticFont(value) {
- const out = [];
- const slashParts = value.match(/(?:^|\s)([\d.]+(?:px|rem|em|%))(?:\/([^\s]+))?/);
- if (/\bitalic\b/i.test(value)) out.push(['fontStyle', 'italic']);
- const weight = value.match(/\b([1-9]00|bold|normal|lighter|bolder)\b/i);
- if (weight) out.push(['fontWeight', weight[1]]);
- if (slashParts) {
- out.push(['fontSize', slashParts[1]]);
- if (slashParts[2]) out.push(['lineHeight', slashParts[2]]);
- const familyStart = value.indexOf(slashParts[0]) + slashParts[0].length;
- const family = value.slice(familyStart).trim();
- if (family) out.push(['fontFamily', family]);
- }
- return out;
-}
-
-function parseStaticTransition(value) {
- const props = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const prop = tokens.find(token => /^[a-z-]+$/i.test(token) && !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none)$/.test(token) && !/s$/.test(token));
- if (prop) props.push(prop);
- }
- return {
- property: props.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function parseStaticAnimation(value) {
- const names = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const name = tokens.find(token =>
- /^[a-z_-][\w-]*$/i.test(token) &&
- !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none|running|paused)$/.test(token)
- );
- if (name) names.push(name);
- }
- return {
- name: names.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function expandStaticDeclaration(prop, value) {
- const p = prop.toLowerCase();
- const v = String(value || '').trim();
- if (!v) return [];
- if (p.startsWith('--')) return [[p, v]];
- if (p === 'background') {
- const out = [];
- const hasImage = /gradient|url\(/i.test(v);
- if (hasImage) out.push(['backgroundImage', v]);
- const beforeImage = hasImage ? v.split(/(?:repeating-)?(?:linear|radial|conic)-gradient\(|url\(/i)[0] : v;
- const color = extractStaticColor(hasImage ? beforeImage : v);
- if (color) out.push(['backgroundColor', color]);
- return out;
- }
- if (p === 'border') {
- const parsed = parseStaticBorder(v);
- const out = [];
- for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
- if (parsed.width) out.push([`border${side}Width`, parsed.width]);
- if (parsed.color) out.push([`border${side}Color`, parsed.color]);
- }
- return out;
- }
- const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
- if (sideMatch) {
- const parsed = parseStaticBorder(v);
- const side = sideMatch[1][0].toUpperCase() + sideMatch[1].slice(1);
- return [
- ...(parsed.width ? [[`border${side}Width`, parsed.width]] : []),
- ...(parsed.color ? [[`border${side}Color`, parsed.color]] : []),
- ];
- }
- if (p === 'border-width') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopWidth', vals[0]],
- ['borderRightWidth', vals[1]],
- ['borderBottomWidth', vals[2]],
- ['borderLeftWidth', vals[3]],
- ];
- }
- if (p === 'border-color') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopColor', vals[0]],
- ['borderRightColor', vals[1]],
- ['borderBottomColor', vals[2]],
- ['borderLeftColor', vals[3]],
- ];
- }
- if (p === 'padding') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['paddingTop', vals[0]],
- ['paddingRight', vals[1]],
- ['paddingBottom', vals[2]],
- ['paddingLeft', vals[3]],
- ];
- }
- if (p === 'font') return parseStaticFont(v);
- if (p === 'transition') {
- const parsed = parseStaticTransition(v);
- return [
- ...(parsed.property ? [['transitionProperty', parsed.property]] : []),
- ...(parsed.timing ? [['transitionTimingFunction', parsed.timing]] : []),
- ];
- }
- if (p === 'animation') {
- const parsed = parseStaticAnimation(v);
- return [
- ...(parsed.name ? [['animationName', parsed.name]] : []),
- ...(parsed.timing ? [['animationTimingFunction', parsed.timing]] : []),
- ];
- }
- const mapped = cssPropToCamel(p);
- if (STATIC_DEFAULT_STYLE[mapped] != null || STATIC_INHERITED_PROPS.has(mapped)) {
- return [[mapped, v]];
- }
- return [];
-}
-
-function compareStaticPriority(a, b) {
- if (!a) return true;
- if (!!b.important !== !!a.important) return !!b.important;
- if (!!b.inline !== !!a.inline) return !!b.inline;
- for (let i = 0; i < 3; i++) {
- if ((b.specificity[i] || 0) !== (a.specificity[i] || 0)) {
- return (b.specificity[i] || 0) > (a.specificity[i] || 0);
- }
- }
- return b.order >= a.order;
-}
-
-function staticSpecificity(selector) {
- const noWhere = selector.replace(/:where\([^)]*\)/g, '');
- const ids = (noWhere.match(/#[\w-]+/g) || []).length;
- const classes = (noWhere.match(/\.[\w-]+|\[[^\]]+\]|:(?!:)[\w-]+(?:\([^)]*\))?/g) || []).length;
- const stripped = noWhere
- .replace(/#[\w-]+/g, ' ')
- .replace(/\.[\w-]+|\[[^\]]+\]|:{1,2}[\w-]+(?:\([^)]*\))?/g, ' ')
- .replace(/[*>+~(),]/g, ' ');
- const types = (stripped.match(/\b[a-zA-Z][\w-]*\b/g) || []).length;
- return [ids, classes, types];
-}
-
-function applyStaticDeclaration(specified, node, prop, value, meta) {
- let map = specified.get(node);
- if (!map) { map = new Map(); specified.set(node, map); }
- for (const [expandedProp, expandedValue] of expandStaticDeclaration(prop, value)) {
- const existing = map.get(expandedProp);
- const next = { ...meta, prop: expandedProp, value: expandedValue };
- if (compareStaticPriority(existing, next)) map.set(expandedProp, next);
- }
-}
-
-function parseStaticStyleAttribute(styleText, orderBase = 0) {
- const decls = [];
- for (const part of String(styleText || '').split(';')) {
- const idx = part.indexOf(':');
- if (idx <= 0) continue;
- const prop = part.slice(0, idx).trim();
- let value = part.slice(idx + 1).trim();
- const important = /!important\s*$/i.test(value);
- value = value.replace(/\s*!important\s*$/i, '').trim();
- decls.push({ prop, value, important, order: orderBase + decls.length });
- }
- return decls;
-}
-
-function collectStaticCssRules(cssText, csstree) {
- const rules = [];
- let ast;
- try {
- ast = csstree.parse(cssText, { positions: false, parseValue: true, parseCustomProperty: false });
- } catch {
- return rules;
- }
- let order = 0;
- const walkList = (list, atRuleStack = []) => {
- list?.forEach?.(node => {
- if (node.type === 'Rule' && node.block) {
- if (atRuleStack.some(name => /keyframes$/i.test(name))) return;
- const selectorText = csstree.generate(node.prelude).trim();
- const declarations = [];
- node.block.children?.forEach?.(child => {
- if (child.type !== 'Declaration') return;
- declarations.push({
- prop: child.property,
- value: csstree.generate(child.value).trim(),
- important: !!child.important,
- });
- });
- for (const selector of splitCssList(selectorText)) {
- if (selector) rules.push({ selector, declarations, specificity: staticSpecificity(selector), order: order++ });
- }
- return;
- }
- if (node.type === 'Atrule' && node.block) {
- const name = String(node.name || '').toLowerCase();
- if (name === 'media' || name === 'supports' || name === 'layer') {
- walkList(node.block.children, [...atRuleStack, name]);
- }
- }
- });
- };
- walkList(ast.children);
- return rules;
-}
-
-class StaticElement {
- constructor(node, doc) {
- this.node = node;
- this._doc = doc;
- this.nodeType = 1;
- this.tagName = String(node.name || '').toUpperCase();
- this.nodeName = this.tagName;
- }
- get parentElement() {
- let cur = this.node.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- return cur ? this._doc.wrap(cur) : null;
- }
- get previousElementSibling() {
- let cur = this.node.prev;
- while (cur && cur.type !== 'tag') cur = cur.prev;
- return cur ? this._doc.wrap(cur) : null;
- }
- get children() {
- return (this.node.children || []).filter(child => child.type === 'tag').map(child => this._doc.wrap(child));
- }
- get childNodes() {
- return (this.node.children || []).map(child => {
- if (child.type === 'text') return { nodeType: 3, textContent: child.data || '' };
- if (child.type === 'tag') return this._doc.wrap(child);
- return { nodeType: 8, textContent: child.data || '' };
- });
- }
- get textContent() {
- return this._doc.domutils.textContent(this.node);
- }
- get className() {
- return this.getAttribute('class') || '';
- }
- get id() {
- return this.getAttribute('id') || '';
- }
- getAttribute(name) {
- return this.node.attribs?.[name] ?? null;
- }
- querySelector(selector) {
- try {
- const found = this._doc.selectOne(selector, this.node.children || []);
- return found ? this._doc.wrap(found) : null;
- } catch {
- return null;
- }
- }
- querySelectorAll(selector) {
- try {
- return this._doc.selectAll(selector, this.node.children || []).map(node => this._doc.wrap(node));
- } catch {
- return [];
- }
- }
- closest(selector) {
- let cur = this.node;
- while (cur && cur.type === 'tag') {
- try {
- if (this._doc.is(cur, selector)) return this._doc.wrap(cur);
- } catch {
- return null;
- }
- cur = cur.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- }
- return null;
- }
- contains(other) {
- let cur = other?.node || null;
- while (cur) {
- if (cur === this.node) return true;
- cur = cur.parent;
- }
- return false;
- }
-}
-
-class StaticDocument {
- constructor(root, modules) {
- this.root = root;
- this.selectAll = modules.selectAll;
- this.selectOne = modules.selectOne;
- this.is = modules.is;
- this.domutils = modules.domutils;
- this._wrappers = new WeakMap();
- this._styleMap = new WeakMap();
- }
- wrap(node) {
- let wrapped = this._wrappers.get(node);
- if (!wrapped) {
- wrapped = new StaticElement(node, this);
- this._wrappers.set(node, wrapped);
- }
- return wrapped;
- }
- querySelectorAll(selector) {
- try {
- return this.selectAll(selector, this.root.children || []).map(node => this.wrap(node));
- } catch {
- return [];
- }
- }
- querySelector(selector) {
- try {
- const found = this.selectOne(selector, this.root.children || []);
- return found ? this.wrap(found) : null;
- } catch {
- return null;
- }
- }
- get documentElement() {
- return this.querySelector('html');
- }
- get body() {
- return this.querySelector('body');
- }
- setStyle(node, style) {
- this._styleMap.set(node, style);
- }
- getStyle(el) {
- return this._styleMap.get(el.node) || makeStaticStyle();
- }
-}
-
-function makeStaticStyle(values = {}) {
- const style = { ...STATIC_DEFAULT_STYLE, ...values };
- style.getPropertyValue = (prop) => {
- const key = cssPropToCamel(prop);
- return style[key] || style[prop] || '';
- };
- return style;
-}
-
-function buildStaticWindow(staticDoc) {
- return {
- document: staticDoc,
- getComputedStyle: (el) => staticDoc.getStyle(el),
- };
-}
-
-function collectStaticCssText(root, fileDir, profile, filePath, modules) {
- const styleTexts = [];
- for (const styleEl of modules.selectAll('style', root.children || [])) {
- styleTexts.push(modules.domutils.textContent(styleEl));
- }
- const links = modules.selectAll('link', root.children || []);
- for (const link of links) {
- const rel = link.attribs?.rel || '';
- const href = link.attribs?.href || '';
- if (!/\bstylesheet\b/i.test(rel) || !href || /^(https?:)?\/\//i.test(href)) continue;
- const cssPath = path.resolve(fileDir, href);
- try {
- const css = profileStep(profile, {
- engine: 'static-html',
- phase: 'preprocess',
- ruleId: 'inline-linked-stylesheet',
- target: filePath,
- detail: href,
- }, () => fs.readFileSync(cssPath, 'utf-8'));
- styleTexts.push(css);
- } catch { /* skip unreadable */ }
- }
- return styleTexts.join('\n');
-}
-
-function buildStaticStyleMap(root, staticDoc, cssText, modules, profile, filePath) {
- const specified = new Map();
- const allNodes = modules.selectAll('*', root.children || []);
- const rules = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-css',
- ruleId: 'css-rules',
- target: filePath,
- }, () => collectStaticCssRules(cssText, modules.csstree));
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'css-selectors',
- target: filePath,
- }, () => {
- for (const rule of rules) {
- let matched;
- try {
- matched = modules.selectAll(rule.selector, root.children || []);
- } catch {
- recordProfileEvent(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'unsupported-selector',
- target: filePath,
- ms: 0,
- findings: 0,
- detail: rule.selector,
- });
- continue;
- }
- for (const node of matched) {
- for (const decl of rule.declarations) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: rule.specificity,
- order: rule.order,
- inline: false,
- });
- }
- }
- }
-
- let inlineOrder = rules.length + 1;
- for (const node of allNodes) {
- const styleText = node.attribs?.style;
- if (!styleText) continue;
- for (const decl of parseStaticStyleAttribute(styleText, inlineOrder)) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: [1, 0, 0],
- order: decl.order,
- inline: true,
- });
- }
- inlineOrder += 1000;
- }
- });
-
- const computeNode = (node, parentStyle = null, parentCustom = new Map()) => {
- const specifiedMap = specified.get(node) || new Map();
- const customProps = new Map(parentCustom);
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) customProps.set(prop, resolveVarRefs(decl.value, customProps));
- }
- const values = {};
- for (const prop of Object.keys(STATIC_DEFAULT_STYLE)) {
- if (STATIC_INHERITED_PROPS.has(prop) && parentStyle?.[prop] != null) values[prop] = parentStyle[prop];
- else values[prop] = STATIC_DEFAULT_STYLE[prop];
- }
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) continue;
- values[prop] = normalizeStaticCssValue(prop, decl.value, customProps, parentStyle, values);
- }
- const style = makeStaticStyle(values);
- staticDoc.setStyle(node, style);
- for (const child of node.children || []) {
- if (child.type === 'tag') computeNode(child, style, customProps);
- }
- };
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'cascade',
- ruleId: 'compute-styles',
- target: filePath,
- }, () => {
- for (const child of root.children || []) {
- if (child.type === 'tag') computeNode(child);
- }
- });
-}
-
-export {
- BORDER_SHORTHAND_RE,
- NAMED_COLORS,
- normalizeColorForCheck,
- buildBorderOverrideMap,
- unwrapCssAtLayer,
- STATIC_INHERITED_PROPS,
- STATIC_DEFAULT_STYLE,
- STATIC_PROP_MAP,
- STATIC_NAMED_COLORS,
- splitCssList,
- splitCssTokens,
- cssPropToCamel,
- staticColorToCss,
- parseStaticColor,
- extractStaticColor,
- normalizeStaticCssValue,
- expandStaticBoxValues,
- parseStaticBorder,
- parseStaticFont,
- parseStaticTransition,
- parseStaticAnimation,
- expandStaticDeclaration,
- compareStaticPriority,
- staticSpecificity,
- applyStaticDeclaration,
- parseStaticStyleAttribute,
- collectStaticCssRules,
- StaticElement,
- StaticDocument,
- makeStaticStyle,
- buildStaticWindow,
- collectStaticCssText,
- buildStaticStyleMap,
-};
@@ -1,174 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import {
- checkElementBorders,
- checkElementColors,
- checkElementGlow,
- checkElementHeroEyebrow,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementMotion,
- checkElementQuality,
- checkHtmlPatterns,
- checkPageLayout,
- checkPageQualityFromDoc,
- checkRepeatedSectionKickersFromDoc,
- resolveBackground,
- resolveBorderRadiusPx,
-} from '../../rules/checks.mjs';
-import { detectText } from '../regex/detect-text.mjs';
-import {
- StaticDocument,
- buildStaticStyleMap,
- buildStaticWindow,
- collectStaticCssText,
-} from './css-cascade.mjs';
-
-function checkStaticPageTypography(document, window) {
- const findings = [];
- const fonts = new Set();
- const overusedFound = new Set();
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span, div')) {
- const hasText = el.childNodes.some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const ff = window.getComputedStyle(el).fontFamily || '';
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
- if (fonts.size === 1 && document.querySelectorAll('*').length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div')) {
- const fontSize = parseFloat(window.getComputedStyle(el).fontSize);
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
- return findings;
-}
-
-const STATIC_ELEMENT_RULES = [
- { id: 'border-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementBorders(tag, style, null, resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window)) },
- { id: 'color-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementColors(el, style, tag, window, customPropMap, false) },
- { id: 'dark-glow', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window, customPropMap)) },
- { id: 'motion-rules', selector: '*', run: (el, tag, style) => checkElementMotion(tag, style) },
- { id: 'icon-tile-stack', selector: 'h1,h2,h3,h4,h5,h6', run: (el, tag, _style, window) => checkElementIconTile(el, tag, window) },
- { id: 'italic-serif-display', selector: 'h1,h2', run: (el, tag, style) => checkElementItalicSerif(el, style, tag) },
- { id: 'hero-eyebrow-chip', selector: 'h1', run: (el, tag, style, window, customPropMap) => checkElementHeroEyebrow(el, style, tag, window, customPropMap) },
- { id: 'quality-rules', selector: '*', run: (el, tag, style, window) => checkElementQuality(el, style, tag, window) },
-];
-
-async function detectHtml(filePath, options = {}) {
- const profile = options?.profile;
- const html = profileStep(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'read-html',
- target: filePath,
- }, () => fs.readFileSync(filePath, 'utf-8'));
-
- let modules;
- try {
- modules = await profileStepAsync(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'import-static-parser',
- target: filePath,
- }, async () => {
- const [htmlparser2, cssSelect, csstree, domutils] = await Promise.all([
- import('htmlparser2'),
- import('css-select'),
- import('css-tree'),
- import('domutils'),
- ]);
- return {
- parseDocument: htmlparser2.parseDocument,
- selectAll: cssSelect.selectAll,
- selectOne: cssSelect.selectOne,
- is: cssSelect.is,
- csstree,
- domutils,
- };
- });
- } catch {
- return detectText(html, filePath, options);
- }
-
- const resolvedPath = path.resolve(filePath);
- const fileDir = path.dirname(resolvedPath);
- const root = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-html',
- ruleId: 'parse-document',
- target: filePath,
- }, () => modules.parseDocument(html, { lowerCaseAttributeNames: false, lowerCaseTags: true }));
-
- const cssText = collectStaticCssText(root, fileDir, profile, filePath, modules);
- const document = new StaticDocument(root, modules);
- buildStaticStyleMap(root, document, cssText, modules, profile, filePath);
- const window = buildStaticWindow(document);
-
- const customPropMap = null;
-
- const findings = [];
- const runElementCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'element', ruleId, target: filePath }, callback)
- : callback();
-
- const visitedByRule = new Map();
- for (const rule of STATIC_ELEMENT_RULES) {
- const elements = document.querySelectorAll(rule.selector);
- visitedByRule.set(rule.id, elements.length);
- for (const el of elements) {
- const tag = el.tagName.toLowerCase();
- const style = window.getComputedStyle(el);
- for (const f of runElementCheck(rule.id, () => rule.run(el, tag, style, window, customPropMap))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
- }
-
- if (isFullPage(html)) {
- const runPageCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
- : callback();
- for (const f of runPageCheck('typography-rules', () => checkStaticPageTypography(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('repeated-section-kickers', () => checkRepeatedSectionKickersFromDoc(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('layout-rules', () => checkPageLayout(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('skipped-heading', () => checkPageQualityFromDoc(document))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('html-patterns', () => checkHtmlPatterns(html).filter(item =>
- item.id !== 'bounce-easing' && item.id !== 'layout-transition'
- ))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
-
- return findings;
-}
-
-export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -1,189 +0,0 @@
-function sanitizeScreenshotClip(clip, viewport) {
- if (!clip) return null;
- const x = Math.max(0, Math.floor(clip.x || 0));
- const y = Math.max(0, Math.floor(clip.y || 0));
- const width = Math.min(
- Math.max(1, Math.ceil(clip.width || 0)),
- Math.max(1, viewport?.width || 1600),
- );
- const height = Math.min(
- Math.max(1, Math.ceil(clip.height || 0)),
- 320,
- );
- if (width < 1 || height < 1) return null;
- return { x, y, width, height };
-}
-
-async function compareScreenshotContrast(page, beforeBase64, afterBase64, candidate) {
- return page.evaluate(async ({ beforeBase64, afterBase64, candidate }) => {
- const loadImage = (base64) => new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = () => reject(new Error('Could not decode contrast screenshot'));
- img.src = `data:image/png;base64,${base64}`;
- });
- const [before, after] = await Promise.all([loadImage(beforeBase64), loadImage(afterBase64)]);
- const width = Math.min(before.width, after.width);
- const height = Math.min(before.height, after.height);
- if (width < 1 || height < 1) return null;
-
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return null;
-
- ctx.drawImage(before, 0, 0, width, height);
- const beforePixels = ctx.getImageData(0, 0, width, height).data;
- ctx.clearRect(0, 0, width, height);
- ctx.drawImage(after, 0, 0, width, height);
- const afterPixels = ctx.getImageData(0, 0, width, height).data;
-
- const luminance = ({ r, g, b }) => {
- const convert = c => {
- const v = c / 255;
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
- };
- return 0.2126 * convert(r) + 0.7152 * convert(g) + 0.0722 * convert(b);
- };
- const ratio = (a, b) => {
- const l1 = luminance(a);
- const l2 = luminance(b);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
- };
-
- const cssTextColor = candidate.textColor && !candidate.preferRenderedForeground
- ? {
- r: candidate.textColor.r,
- g: candidate.textColor.g,
- b: candidate.textColor.b,
- }
- : null;
- const ratios = [];
- let glyphPixels = 0;
- let strongestDelta = 0;
- for (let i = 0; i < beforePixels.length; i += 4) {
- const delta = Math.abs(beforePixels[i] - afterPixels[i])
- + Math.abs(beforePixels[i + 1] - afterPixels[i + 1])
- + Math.abs(beforePixels[i + 2] - afterPixels[i + 2])
- + Math.abs(beforePixels[i + 3] - afterPixels[i + 3]);
- strongestDelta = Math.max(strongestDelta, delta);
- if (delta < 10) continue;
- glyphPixels++;
- const fg = cssTextColor || {
- r: beforePixels[i],
- g: beforePixels[i + 1],
- b: beforePixels[i + 2],
- };
- const bg = {
- r: afterPixels[i],
- g: afterPixels[i + 1],
- b: afterPixels[i + 2],
- };
- ratios.push(ratio(fg, bg));
- }
-
- if (ratios.length < 8) {
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: null,
- p10Ratio: null,
- medianRatio: null,
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: ratios[0],
- p10Ratio: pick(10),
- medianRatio: pick(50),
- };
- }, { beforeBase64, afterBase64, candidate });
-}
-
-async function captureVisualContrastCandidate(page, candidate, viewport) {
- const clip = sanitizeScreenshotClip(candidate.clip, viewport);
- if (!clip) return null;
-
- const beforeBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- const token = `impeccable-contrast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- const applied = await page.evaluate(({ selector, token, backgroundClipText }) => {
- let el;
- try {
- el = document.querySelector(selector);
- } catch {
- return false;
- }
- if (!el) return false;
- let style = document.getElementById('impeccable-visual-contrast-hide-style');
- if (!style) {
- style = document.createElement('style');
- style.id = 'impeccable-visual-contrast-hide-style';
- style.textContent = [
- '[data-impeccable-visual-contrast-target] {',
- ' color: transparent !important;',
- ' -webkit-text-fill-color: transparent !important;',
- ' text-shadow: none !important;',
- '}',
- '[data-impeccable-visual-contrast-target][data-impeccable-bgclip-text="true"] {',
- ' background-image: none !important;',
- '}',
- ].join('\n');
- document.head.appendChild(style);
- }
- el.setAttribute('data-impeccable-visual-contrast-target', token);
- if (backgroundClipText) el.setAttribute('data-impeccable-bgclip-text', 'true');
- return true;
- }, {
- selector: candidate.selector,
- token,
- backgroundClipText: candidate.backgroundClipText,
- });
- if (!applied) return null;
-
- let afterBase64;
- try {
- afterBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- } finally {
- await page.evaluate(({ selector }) => {
- try {
- const el = document.querySelector(selector);
- if (el) {
- el.removeAttribute('data-impeccable-visual-contrast-target');
- el.removeAttribute('data-impeccable-bgclip-text');
- }
- } catch {
- // Ignore invalid or stale selectors during cleanup.
- }
- }, { selector: candidate.selector }).catch(() => {});
- }
-
- const metrics = await compareScreenshotContrast(page, beforeBase64, afterBase64, candidate);
- if (!metrics || !Number.isFinite(metrics.p10Ratio) || metrics.glyphPixels < 8) return null;
- const measuredRatio = metrics.p10Ratio;
- if (measuredRatio >= candidate.threshold) return null;
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const reasonLabel = (candidate.reasons || []).slice(0, 3).join(', ') || 'visual background';
- return {
- id: 'low-contrast',
- snippet: `pixel contrast ${measuredRatio.toFixed(1)}:1 median ${metrics.medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) on ${reasonLabel}${textLabel}`,
- };
-}
-
-export {
- sanitizeScreenshotClip,
- compareScreenshotContrast,
- captureVisualContrastCandidate,
-};
@@ -1,12 +0,0 @@
-import { getAntipattern } from './registry/antipatterns.mjs';
-
-function getAP(id) {
- return getAntipattern(id);
-}
-
-function finding(id, filePath, snippet, line = 0) {
- const ap = getAP(id);
- return { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', file: filePath, line, snippet };
-}
-
-export { getAP, finding };
@@ -1,198 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-// ---------------------------------------------------------------------------
-// File walker
-// ---------------------------------------------------------------------------
-
-const SKIP_DIRS = new Set([
- 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
- '.svelte-kit', '__pycache__', '.turbo', '.vercel',
-]);
-
-const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
- '.jsx', '.tsx', '.js', '.ts',
- '.vue', '.svelte', '.astro',
-]);
-
-const HTML_EXTENSIONS = new Set(['.html', '.htm']);
-
-function walkDir(dir) {
- const files = [];
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
- for (const entry of entries) {
- if (SKIP_DIRS.has(entry.name)) continue;
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) files.push(...walkDir(full));
- else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
- }
- return files;
-}
-
-
-// ---------------------------------------------------------------------------
-// Import graph (multi-file awareness)
-// ---------------------------------------------------------------------------
-
-function resolveImport(specifier, fromDir, fileSet) {
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
- const base = path.resolve(fromDir, specifier);
- if (fileSet.has(base)) return base;
- for (const ext of SCANNABLE_EXTENSIONS) {
- const withExt = base + ext;
- if (fileSet.has(withExt)) return withExt;
- }
- // index file convention
- for (const ext of SCANNABLE_EXTENSIONS) {
- const indexFile = path.join(base, 'index' + ext);
- if (fileSet.has(indexFile)) return indexFile;
- }
- return null;
-}
-
-function buildImportGraph(files) {
- const fileSet = new Set(files);
- const graph = new Map();
-
- for (const file of files) {
- const content = fs.readFileSync(file, 'utf-8');
- const dir = path.dirname(file);
- const imports = new Set();
-
- // ES imports: import ... from '...' and import '...'
- const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
- let m;
- while ((m = esRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // CSS @import
- const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
- while ((m = cssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // SCSS @use / @forward
- const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
- while ((m = scssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- graph.set(file, imports);
- }
- return graph;
-}
-
-// ---------------------------------------------------------------------------
-// Framework dev server detection
-// ---------------------------------------------------------------------------
-
-const FRAMEWORK_CONFIGS = [
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /next/i } },
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-sveltekit-page', value: null } },
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /@vite\/client/ } },
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /astro/i } },
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
- portRe: /"port"\s*:\s*(\d+)/,
- fingerprint: { body: /ng-version/i } },
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
-];
-
-function detectFrameworkConfig(dir) {
- let entries;
- try { entries = fs.readdirSync(dir); } catch { return null; }
- const entrySet = new Set(entries);
-
- for (const cfg of FRAMEWORK_CONFIGS) {
- const match = cfg.files.find(f => entrySet.has(f));
- if (!match) continue;
-
- const configPath = path.join(dir, match);
- let port = cfg.defaultPort;
- try {
- const content = fs.readFileSync(configPath, 'utf-8');
- const portMatch = content.match(cfg.portRe);
- if (portMatch) port = parseInt(portMatch[1], 10);
- } catch { /* use default */ }
-
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
- }
- return null;
-}
-
-/**
- * Check if a port is listening and optionally verify it matches the expected framework.
- * Returns { listening: true, matched: true/false } or { listening: false }.
- */
-async function isPortListening(port, fingerprint = null) {
- if (!fingerprint) {
- // Simple TCP probe fallback
- const net = await import('node:net');
- return new Promise((resolve) => {
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
- sock.setTimeout(500);
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
- sock.on('error', () => resolve({ listening: false }));
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
- });
- }
-
- // HTTP probe with fingerprint matching
- try {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 2000);
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
- clearTimeout(timeout);
-
- // Check header fingerprint
- if (fingerprint.header) {
- const val = res.headers.get(fingerprint.header);
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
- return { listening: true, matched: true };
- }
- }
-
- // Check body fingerprint
- if (fingerprint.body) {
- const body = await res.text();
- if (fingerprint.body.test(body)) {
- return { listening: true, matched: true };
- }
- }
-
- // Port is listening but doesn't match the expected framework
- return { listening: true, matched: false };
- } catch {
- return { listening: false };
- }
-}
-
-export {
- SKIP_DIRS,
- SCANNABLE_EXTENSIONS,
- HTML_EXTENSIONS,
- walkDir,
- resolveImport,
- buildImportGraph,
- FRAMEWORK_CONFIGS,
- detectFrameworkConfig,
- isPortListening,
-};
@@ -1,166 +0,0 @@
-function profileNow() {
- return typeof performance !== 'undefined' && performance.now
- ? performance.now()
- : Date.now();
-}
-
-function createDetectorProfile() {
- return { events: [] };
-}
-
-function recordProfileEvent(profile, event) {
- if (!profile) return;
- const normalized = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- ms: Number.isFinite(event.ms) ? event.ms : 0,
- findings: Number.isFinite(event.findings) ? event.findings : 0,
- };
- if (event.detail) normalized.detail = event.detail;
- if (Array.isArray(event.findingIds) && event.findingIds.length) {
- normalized.findingIds = event.findingIds;
- }
- if (typeof profile === 'function') {
- profile(normalized);
- } else if (typeof profile.record === 'function') {
- profile.record(normalized);
- } else if (Array.isArray(profile.events)) {
- profile.events.push(normalized);
- } else if (Array.isArray(profile)) {
- profile.push(normalized);
- }
-}
-
-function extractFindingIds(findings) {
- if (!Array.isArray(findings) || findings.length === 0) return [];
- return [...new Set(findings.map(f => f?.id || f?.type || f?.antipattern).filter(Boolean))];
-}
-
-function profileFindings(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-function profileStep(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-async function profileFindingsAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = await callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-async function profileStepAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return await callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-function percentile(sortedValues, pct) {
- if (!sortedValues.length) return 0;
- const idx = Math.min(
- sortedValues.length - 1,
- Math.max(0, Math.ceil((pct / 100) * sortedValues.length) - 1),
- );
- return sortedValues[idx];
-}
-
-function summarizeDetectorProfile(profile) {
- const events = Array.isArray(profile)
- ? profile
- : (Array.isArray(profile?.events) ? profile.events : []);
- const groups = new Map();
- for (const event of events) {
- const key = [
- event.engine || 'unknown',
- event.phase || 'unknown',
- event.ruleId || 'unknown',
- event.target || '',
- ].join('\u0000');
- let group = groups.get(key);
- if (!group) {
- group = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- calls: 0,
- totalMs: 0,
- findings: 0,
- samples: [],
- };
- groups.set(key, group);
- }
- const ms = Number.isFinite(event.ms) ? event.ms : 0;
- group.calls += 1;
- group.totalMs += ms;
- group.findings += Number.isFinite(event.findings) ? event.findings : 0;
- group.samples.push(ms);
- }
- return [...groups.values()]
- .map(group => {
- const samples = group.samples.sort((a, b) => a - b);
- return {
- engine: group.engine,
- phase: group.phase,
- ruleId: group.ruleId,
- target: group.target,
- calls: group.calls,
- totalMs: Number(group.totalMs.toFixed(3)),
- avgMs: Number((group.totalMs / group.calls).toFixed(3)),
- p50: Number(percentile(samples, 50).toFixed(3)),
- p95: Number(percentile(samples, 95).toFixed(3)),
- findings: group.findings,
- };
- })
- .sort((a, b) => b.totalMs - a.totalMs);
-}
-
-export {
- profileNow,
- createDetectorProfile,
- recordProfileEvent,
- extractFindingIds,
- profileFindings,
- profileStep,
- profileFindingsAsync,
- profileStepAsync,
- percentile,
- summarizeDetectorProfile,
-};
@@ -1,278 +0,0 @@
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-const RULE_ENGINE_SUPPORT = {
- regex: new Set(['source', 'page-analyzer']),
- 'static-html': new Set(['element', 'page']),
- browser: new Set(['element', 'page', 'layout']),
- visual: new Set(['visual-contrast']),
-};
-
-function getAntipattern(id) {
- return ANTIPATTERNS.find(rule => rule.id === id);
-}
-
-function getRulesForCategory(category) {
- return ANTIPATTERNS.filter(rule => rule.category === category);
-}
-
-function getRuleEngineSupport(engine) {
- return RULE_ENGINE_SUPPORT[engine] || new Set();
-}
-
-export {
- ANTIPATTERNS,
- RULE_ENGINE_SUPPORT,
- getAntipattern,
- getRulesForCategory,
- getRuleEngineSupport,
-};
@@ -1,1948 +0,0 @@
-import {
- BORDER_SAFE_TAGS,
- GENERIC_FONTS,
- KNOWN_SERIF_FONTS,
- OVERUSED_FONTS,
- SAFE_TAGS,
- WCAG_LARGE_BOLD_TEXT_PX,
- WCAG_LARGE_TEXT_PX,
- isBrandFontOnOwnDomain,
-} from '../shared/constants.mjs';
-import {
- colorToHex,
- contrastRatio,
- getHue,
- hasChroma,
- isNeutralColor,
- parseGradientColors,
- parseRgb,
- relativeLuminance,
-} from '../shared/color.mjs';
-
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-export {
- checkBorders,
- isEmojiOnlyText,
- checkColors,
- isCardLikeFromProps,
- checkIconTile,
- resolveSerif,
- checkItalicSerif,
- isAccentColor,
- checkHeroEyebrow,
- checkRepeatedSectionKickers,
- checkMotion,
- checkGlow,
- checkHtmlPatterns,
- readOwnBackgroundColor,
- resolveBackground,
- resolveGradientStops,
- parseRadiusToPx,
- resolveBorderRadiusPx,
- checkElementBordersDOM,
- checkElementColorsDOM,
- checkElementIconTileDOM,
- checkElementItalicSerifDOM,
- checkElementHeroEyebrowDOM,
- buildCustomPropMap,
- resolveVarRefs,
- oklchToRgb,
- parseAnyColor,
- parseColorResolved,
- cleanInlineText,
- isRepeatedKickerCandidate,
- collectRepeatedSectionKickerCandidates,
- checkRepeatedSectionKickersDOM,
- checkElementMotionDOM,
- checkElementGlowDOM,
- checkElementAIPaletteDOM,
- resolveFontSizePx,
- resolveLengthPx,
- checkQuality,
- checkElementQualityDOM,
- checkPageQualityFromDoc,
- checkPageQualityDOM,
- checkElementQuality,
- checkElementBorders,
- checkElementColors,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementHeroEyebrow,
- checkRepeatedSectionKickersFromDoc,
- checkElementMotion,
- checkElementGlow,
- checkTypography,
- isCardLikeDOM,
- checkLayout,
- checkPageTypography,
- isCardLike,
- checkPageLayout,
-};
@@ -1,124 +0,0 @@
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-export {
- isNeutralColor,
- parseRgb,
- relativeLuminance,
- contrastRatio,
- parseGradientColors,
- hasChroma,
- getHue,
- colorToHex,
-};
@@ -1,101 +0,0 @@
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-export {
- SAFE_TAGS,
- BORDER_SAFE_TAGS,
- OVERUSED_FONTS,
- GOOGLE_DOMAINS,
- VERCEL_DOMAINS,
- GITHUB_DOMAINS,
- BRAND_FONT_DOMAINS,
- isBrandFontOnOwnDomain,
- GENERIC_FONTS,
- WCAG_LARGE_TEXT_PX,
- WCAG_LARGE_BOLD_TEXT_PX,
- KNOWN_SERIF_FONTS,
-};
@@ -1,7 +0,0 @@
-/** Check if content looks like a full page (not a component/partial) */
-function isFullPage(content) {
- const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
- return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
-}
-
-export { isFullPage };
@@ -1,110 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-export const IMPECCABLE_DIR = '.impeccable';
-export const LIVE_DIR = 'live';
-export const CRITIQUE_DIR = 'critique';
-
-export function getImpeccableDir(cwd = process.cwd()) {
- return path.join(cwd, IMPECCABLE_DIR);
-}
-
-export function getDesignSidecarPath(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), 'design.json');
-}
-
-export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {
- const candidates = [
- getDesignSidecarPath(cwd),
- path.join(cwd, 'DESIGN.json'),
- ];
- const contextLegacy = path.join(contextDir, 'DESIGN.json');
- if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
- return candidates;
-}
-
-export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
- return firstExisting(getDesignSidecarCandidates(cwd, contextDir));
-}
-
-export function getLiveDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), LIVE_DIR);
-}
-
-export function getLiveConfigPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'config.json');
-}
-
-export function getLegacyLiveConfigPath(scriptsDir) {
- return path.join(scriptsDir, 'config.json');
-}
-
-export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {
- if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
- const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
- return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
- }
- const primary = getLiveConfigPath(cwd);
- if (fs.existsSync(primary)) return primary;
- if (scriptsDir) {
- const legacy = getLegacyLiveConfigPath(scriptsDir);
- if (fs.existsSync(legacy)) return legacy;
- }
- return primary;
-}
-
-export function getLiveServerPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'server.json');
-}
-
-export function getLegacyLiveServerPath(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live.json');
-}
-
-export function readLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try {
- return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };
- } catch {
- /* try next */
- }
- }
- return null;
-}
-
-export function writeLiveServerInfo(cwd = process.cwd(), info) {
- const filePath = getLiveServerPath(cwd);
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- fs.writeFileSync(filePath, JSON.stringify(info));
- return filePath;
-}
-
-export function removeLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try { fs.unlinkSync(filePath); } catch {}
- }
-}
-
-export function getLiveSessionsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'sessions');
-}
-
-export function getLegacyLiveSessionsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'sessions');
-}
-
-export function getLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'annotations');
-}
-
-export function getCritiqueDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), CRITIQUE_DIR);
-}
-
-export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'annotations');
-}
-
-function firstExisting(paths) {
- return paths.find((filePath) => fs.existsSync(filePath)) || null;
-}
@@ -1,69 +0,0 @@
-/**
- * Decide whether a given file is "generated" (regenerated by a build step,
- * unsafe to write variants into) or "source" (safe to edit, changes persist).
- *
- * Why this matters: when the user picks an element on a page whose underlying
- * file is regenerated by a build step (e.g. `scripts/build-sub-pages.js`
- * rewriting `public/docs/*.html`), writing variants or accepted changes into
- * that file is silent data loss — the next build wipes them.
- *
- * Signals, in order of reliability:
- * 1. Git check-ignore: gitignored files are assumed generated.
- * 2. File-header markers ("GENERATED", "DO NOT EDIT", "AUTO-GENERATED")
- * within the first ~300 characters — catches non-git projects.
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-
-const HEADER_SCAN_BYTES = 300;
-const HEADER_MARKERS = [
- /@generated\b/i,
- /\bGENERATED\s+FILE\b/,
- /\bAUTO-?GENERATED\b/i,
- /\bDO\s+NOT\s+EDIT\b/i,
-];
-
-/**
- * @param {string} filePath - absolute or cwd-relative path
- * @param {object} [options]
- * @param {string} [options.cwd] - project root (defaults to process.cwd())
- */
-export function isGeneratedFile(filePath, options = {}) {
- const cwd = options.cwd || process.cwd();
- const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
-
- if (isGitIgnored(absPath, cwd)) return true;
- if (hasGeneratedHeader(absPath)) return true;
- return false;
-}
-
-function isGitIgnored(absPath, cwd) {
- try {
- execSync(`git check-ignore --quiet ${JSON.stringify(absPath)}`, {
- cwd,
- stdio: 'ignore',
- });
- return true; // exit 0 = ignored
- } catch (err) {
- // Exit code 1 = not ignored. Exit code 128 = not a git repo or other error.
- // In both cases, treat as "not known to be ignored."
- return false;
- }
-}
-
-function hasGeneratedHeader(absPath) {
- let fd;
- try {
- fd = fs.openSync(absPath, 'r');
- const buf = Buffer.alloc(HEADER_SCAN_BYTES);
- const bytesRead = fs.readSync(fd, buf, 0, HEADER_SCAN_BYTES, 0);
- const head = buf.slice(0, bytesRead).toString('utf-8');
- return HEADER_MARKERS.some((re) => re.test(head));
- } catch {
- return false;
- } finally {
- if (fd !== undefined) { try { fs.closeSync(fd); } catch {} }
- }
-}
@@ -1,595 +0,0 @@
-/**
- * CLI helper: deterministic accept/discard of variant sessions.
- *
- * Usage:
- * node live-accept.mjs --id SESSION_ID --discard
- * node live-accept.mjs --id SESSION_ID --variant N
- *
- * For discard: removes the entire variant wrapper and restores the original.
- * For accept: replaces the wrapper with the chosen variant's content. If the
- * session had a colocated <style> block, it's preserved with carbonize markers
- * for a background agent to integrate into the project's CSS.
- *
- * Output: JSON to stdout.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-export async function acceptCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-accept.mjs [options]
-
-Deterministic accept/discard for live variant sessions.
-
-Modes:
- --discard Remove variants, restore original
- --variant N Accept variant N, discard the rest
-
-Required:
- --id SESSION_ID Session ID of the variant wrapper
-
-Output (JSON):
- { handled, file, carbonize }`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const variantNum = argVal(args, '--variant');
- const paramValuesRaw = argVal(args, '--param-values');
- const isDiscard = args.includes('--discard');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }
-
- let paramValues = null;
- if (paramValuesRaw) {
- try { paramValues = JSON.parse(paramValuesRaw); }
- catch { paramValues = null; } // malformed blob: skip the comment rather than failing the accept
- }
-
- // Find the file containing this session's markers
- const found = findSessionFile(id, process.cwd());
- if (!found) {
- console.log(JSON.stringify({ handled: false, error: 'Session markers not found for id: ' + id }));
- process.exit(0);
- }
-
- const { file: targetFile, content, lines } = found;
- const relFile = path.relative(process.cwd(), targetFile);
-
- // Bail if the session lives in a generated file. The agent manually wrote
- // the wrapper there for preview, and is responsible for writing the
- // accepted variant to true source (or cleaning up on discard). See
- // "Handle fallback" in live.md.
- if (isGeneratedFile(targetFile, { cwd: process.cwd() })) {
- console.log(JSON.stringify({
- handled: false,
- mode: 'fallback',
- file: relFile,
- hint: 'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.',
- }));
- process.exit(0);
- }
-
- if (isDiscard) {
- const result = handleDiscard(id, lines, targetFile);
- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));
- } else {
- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);
- // Single-line attention-grabber when cleanup is required. The full
- // five-step checklist lives in reference/live.md (loaded once per
- // session); repeating it per-event would waste tokens.
- if (result.carbonize) {
- result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + relFile + '. See reference/live.md "Required after accept".';
- }
- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));
- }
-}
-
-// ---------------------------------------------------------------------------
-// Discard
-// ---------------------------------------------------------------------------
-
-function handleDiscard(id, lines, targetFile) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const original = extractOriginal(lines, block);
- const isJsx = detectCommentSyntax(targetFile).open === '{/*';
- const replaceRange = expandReplaceRange(block, lines, isJsx);
-
- // Restore at the line we're actually replacing FROM, not the marker line.
- // For JSX wrappers the marker comments live INSIDE the outer `<div>`, so
- // `block.start` sits 2 spaces deeper than the original element. Using that
- // as the deindent base would push the restored content 2 spaces too far
- // right on every JSX/TSX session. `replaceRange.start` is the outer wrapper
- // line, which is at the original element's indent for both HTML and JSX.
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
- const restored = deindentContent(original, indent);
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...restored,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
- return {};
-}
-
-// ---------------------------------------------------------------------------
-// Accept
-// ---------------------------------------------------------------------------
-
-function handleAccept(id, variantNum, lines, targetFile, paramValues) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const commentSyntax = detectCommentSyntax(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- // Anchor indent on the line we're replacing FROM (the outer wrapper),
- // not on `block.start` — for JSX that's the marker comment 2 spaces
- // deeper than the original element. See handleDiscard for the full
- // rationale.
- const replaceRange = expandReplaceRange(block, lines, isJsx);
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
-
- // Extract the chosen variant's inner content
- const variantContent = extractVariant(lines, block, variantNum);
- if (!variantContent) return { handled: false, error: 'Variant ' + variantNum + ' not found' };
-
- // Extract CSS block if present
- const cssContent = extractCss(lines, block, id);
-
- // Check if carbonizing is needed:
- // - CSS block exists, OR
- // - variant HTML contains helper classes/attributes that need cleanup
- const variantText = variantContent.join('\n');
- const hasHelperAttrs = variantText.includes('data-impeccable-variant');
- const needsCarbonize = !!(cssContent || hasHelperAttrs);
-
- // Build the replacement
- const restored = deindentContent(variantContent, indent);
- const replacement = [];
-
- if (cssContent) {
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
- // JSX targets need the CSS body wrapped in a template literal so that the
- // `{` and `}` in CSS rules don't get parsed as JSX expressions.
- replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
- // Re-indent CSS content to match
- for (const cssLine of cssContent) {
- replacement.push(indent + cssLine.trimStart());
- }
- replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
- if (paramValues && Object.keys(paramValues).length > 0) {
- // Preserve the user's knob positions for the carbonize-cleanup agent
- // to bake into the final CSS when it collapses scoped rules.
- replacement.push(indent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close);
- }
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close);
- }
-
- // Keep the `@scope ([data-impeccable-variant="N"])` selectors in the
- // carbonize CSS block working visually by re-wrapping the accepted content
- // in a data-impeccable-variant="N" div with `display: contents` (so layout
- // isn't affected). The carbonize agent strips this attribute + wrapper when
- // it moves the CSS to a proper stylesheet.
- //
- // Style attribute syntax has to follow the host file's flavor — JSX files
- // need the object form, otherwise React 19 throws "Failed to set indexed
- // property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
- if (cssContent) {
- const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
- replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
- replacement.push(...restored);
- replacement.push(indent + '</div>');
- } else {
- replacement.push(...restored);
- }
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...replacement,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- return { carbonize: needsCarbonize };
-}
-
-// ---------------------------------------------------------------------------
-// Parsing helpers
-// ---------------------------------------------------------------------------
-
-/**
- * Find the start/end marker lines for a session.
- * Returns { start, end } (0-indexed line numbers) or null.
- */
-function findMarkerBlock(id, lines) {
- let start = -1;
- let end = -1;
- const startPattern = 'impeccable-variants-start ' + id;
- const endPattern = 'impeccable-variants-end ' + id;
-
- for (let i = 0; i < lines.length; i++) {
- if (start === -1 && lines[i].includes(startPattern)) start = i;
- if (lines[i].includes(endPattern)) { end = i; break; }
- }
-
- return (start !== -1 && end !== -1) ? { start, end } : null;
-}
-
-/**
- * Compute the line range to REPLACE (vs. just the marker range to extract
- * from). For JSX/TSX wrappers, live-wrap places the marker comments INSIDE
- * the `<div data-impeccable-variants="ID">` outer wrapper so the picked
- * element's JSX slot keeps a single child — a Fragment `<></>` would have
- * solved the multi-sibling case but failed inside `asChild` / cloneElement
- * parents with "Invalid prop supplied to React.Fragment".
- *
- * That means the marker block is enclosed by the wrapper `<div>` opener
- * (with `data-impeccable-variants="ID"`) and its matching `</div>`. We
- * walk back to the opener and forward to the closer so accept/discard
- * remove the entire scaffold, not just the inner markers.
- *
- * Marker lines themselves stay where they were so extractOriginal /
- * extractVariant / extractCss continue to walk the same range.
- */
-function expandReplaceRange(block, lines, isJsx) {
- if (!isJsx) return { start: block.start, end: block.end };
-
- let { start, end } = block;
-
- // Walk back for the wrapper `<div data-impeccable-variants="..."` opener.
- // The attr may sit on a continuation line of a multi-line opening tag, so
- // also walk to the line that actually contains `<div`.
- for (let i = start - 1; i >= Math.max(0, start - 12); i--) {
- if (/data-impeccable-variants=/.test(lines[i])) {
- let opener = i;
- while (opener > 0 && !/<div\b/.test(lines[opener])) opener--;
- start = opener;
- break;
- }
- }
-
- // Walk forward to the matching `</div>` by div-depth tracking from the
- // wrapper opener. Operate on JOINED text instead of per-line: a
- // multi-line self-closing JSX `<div\n className="spacer"\n/>` would
- // fool per-line regex tracking (the `<div` line matches openRe but the
- // `/>` line never matches selfCloseRe since it needs `<div` on the same
- // line). That left depth permanently over-counted and the wrapper's
- // outer `</div>` orphaned after accept/discard. Single regex with
- // `[^>]*?` (which spans newlines in JS) handles either form correctly.
- const joined = lines.slice(start).join('\n');
- // Match either `<div … />` (self-close, group 1 is `/`), `<div … >`
- // (open, group 1 is empty), or `</div>`.
- const tagRe = /<div\b[^>]*?(\/?)>|<\/div\s*>/g;
- let depth = 0;
- let m;
- while ((m = tagRe.exec(joined)) !== null) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && m[1] === '/';
- if (isClose) depth--;
- else if (!isSelfClose) depth++;
- if (depth <= 0) {
- // m.index is offset within `joined`; convert back to a file line.
- const linesBefore = joined.slice(0, m.index + m[0].length).split('\n').length - 1;
- const candidateEnd = start + linesBefore;
- if (candidateEnd >= end) {
- end = candidateEnd;
- break;
- }
- }
- }
-
- return { start, end };
-}
-
-/**
- * Join wrapper lines into a single string with `<style>` elements removed so
- * marker matching and div-depth tracking aren't confused by:
- * - CSS `@scope ([data-impeccable-variant="N"])` strings that look like the
- * HTML marker we're searching for
- * - JSX self-closing `<style ... />` (no separate `</style>` to close on)
- * - Same-line `<style>…</style>` blocks
- * - Multi-line `<style>\n…\n</style>` blocks
- */
-function stripStyleAndJoin(lines, block) {
- const out = [];
- let inStyle = false;
- for (let i = block.start; i <= block.end; i++) {
- let line = lines[i];
-
- if (!inStyle) {
- // Strip any complete <style> elements on this line (self-closed or
- // same-line-closed), including their body content.
- line = line
- .replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/g, '')
- .replace(/<style\b[^>]*\/\s*>/g, '');
-
- // If a <style> opener remains (multi-line body starts here), strip from
- // the opener to end-of-line and flip into skip mode.
- const openerIdx = line.search(/<style\b/);
- if (openerIdx !== -1) {
- line = line.slice(0, openerIdx);
- inStyle = true;
- }
- out.push(line);
- } else {
- // In multi-line style body; drop everything until we see </style>.
- const closeIdx = line.search(/<\/style\s*>/);
- if (closeIdx !== -1) {
- inStyle = false;
- out.push(line.slice(closeIdx).replace(/<\/style\s*>/, ''));
- }
- // else: skip line entirely
- }
- }
- return out.join('\n');
-}
-
-/**
- * Find the inner content of `<TAG ...attrMatch...>…</TAG>` inside `text`,
- * handling nested same-tag elements via depth counting. `attrMatch` is a
- * regex source fragment that must appear inside the opener tag.
- * Returns the inner string (may be empty), or null if not found.
- */
-function extractInnerByAttr(text, attrMatch) {
- const openerRe = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*' + attrMatch + '[^>]*>');
- const openMatch = text.match(openerRe);
- if (!openMatch) return null;
-
- const tagName = openMatch[1];
- const innerStart = openMatch.index + openMatch[0].length;
-
- // Match any opener or closer of this tag name after innerStart.
- // (Does not match self-closing <TAG … />, which doesn't contribute to depth.)
- const tagRe = new RegExp('<(?:/)?' + tagName + '\\b[^>]*>', 'g');
- tagRe.lastIndex = innerStart;
-
- let depth = 1;
- let m;
- while ((m = tagRe.exec(text))) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && /\/\s*>$/.test(m[0]);
- if (isClose) {
- depth--;
- if (depth === 0) return text.slice(innerStart, m.index);
- } else if (!isSelfClose) {
- depth++;
- }
- }
- return null;
-}
-
-/**
- * Extract the original element content from within the variant wrapper.
- * Returns an array of lines.
- */
-function extractOriginal(lines, block) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="original"');
- if (inner === null) return [];
- return inner.split('\n');
-}
-
-/**
- * Extract a specific variant's inner content (stripping the wrapper div).
- * Returns an array of lines, or null if not found.
- */
-function extractVariant(lines, block, variantNum) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + variantNum + '"');
- if (inner === null) return null;
- const result = inner.split('\n');
- // Collapse a lone empty leading/trailing line (common after string splice).
- while (result.length > 1 && result[0].trim() === '') result.shift();
- while (result.length > 1 && result[result.length - 1].trim() === '') result.pop();
- return result.length > 0 ? result : null;
-}
-
-/**
- * Extract the colocated <style> block content (between the style tags).
- * Returns an array of CSS lines, or null if no style block found.
- *
- * Handles three shapes of `<style data-impeccable-css="ID" ...>`:
- * 1. Self-closing: `<style ... />` — no body; return null (nothing to carbonize).
- * 2. Same-line open+close: `<style>...</style>` — return the inner content.
- * 3. Multi-line: `<style>` on one line, `</style>` on a later line — return
- * the lines between them.
- */
-function extractCss(lines, block, id) {
- const styleAttr = 'data-impeccable-css="' + id + '"';
- let inStyle = false;
- const content = [];
-
- for (let i = block.start; i <= block.end; i++) {
- const line = lines[i];
-
- if (!inStyle && line.includes(styleAttr)) {
- // Self-closing: nothing to carbonize.
- if (/<style\b[^>]*\/\s*>/.test(line)) return null;
- // Same-line open + close: extract inner text.
- const sameLine = line.match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/);
- if (sameLine) {
- const inner = stripJsxTemplateWrap(sameLine[1]);
- return inner.length > 0 ? inner.split('\n') : null;
- }
- inStyle = true;
- continue; // skip the <style> opening tag
- }
-
- if (inStyle) {
- // Detect </style> anywhere on the line — JSX template-literal closes
- // (`}</style>`) put the close mid-line, and we don't want to absorb the
- // template-literal punctuation as CSS content.
- const closeIdx = line.indexOf('</style>');
- if (closeIdx !== -1) break;
- content.push(line);
- }
- }
-
- if (content.length === 0) return null;
- return stripJsxTemplateLines(content);
-}
-
-/**
- * Strip a JSX template-literal wrap (`{` … `}`) from CSS extracted out of a
- * `<style>` element in a JSX/TSX file. The agent may write the wrap with
- * `{` and `}` directly attached to the `<style>` tags, on their own lines,
- * or attached to the first/last CSS lines — all three are JSX-legal.
- *
- * Stripping is required because handleAccept re-wraps the CSS itself when
- * carbonizing. Without this, two consecutive accepts (or a previously-
- * accepted variants block being carbonized) would produce nested
- * `{` `{` … `}` `}`, which oxc rejects with "Expected `}` but found `@`".
- */
-function stripJsxTemplateLines(content) {
- const out = content.slice();
-
- // Drop any leading blank lines so we don't miss a `{` line buried below
- // them; same for trailing.
- while (out.length > 0 && out[0].trim() === '') out.shift();
- while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
- if (out.length === 0) return null;
-
- // Leading `{`: own line, or attached to the first CSS line.
- const firstTrim = out[0].trimStart();
- if (firstTrim === '{`') {
- out.shift();
- } else if (firstTrim.startsWith('{`')) {
- const idx = out[0].indexOf('{`');
- out[0] = out[0].slice(0, idx) + out[0].slice(idx + 2);
- if (out[0].trim() === '') out.shift();
- }
- if (out.length === 0) return null;
-
- // Trailing `` ` `` `}`: own line, or attached to the last CSS line.
- const lastIdx = out.length - 1;
- const lastTrim = out[lastIdx].trimEnd();
- if (lastTrim === '`}') {
- out.pop();
- } else if (lastTrim.endsWith('`}')) {
- const text = out[lastIdx];
- const idx = text.lastIndexOf('`}');
- out[lastIdx] = text.slice(0, idx) + text.slice(idx + 2);
- if (out[lastIdx].trim() === '') out.pop();
- }
-
- return out.length > 0 ? out : null;
-}
-
-function stripJsxTemplateWrap(text) {
- const lines = text.split('\n');
- const stripped = stripJsxTemplateLines(lines);
- return stripped ? stripped.join('\n') : '';
-}
-
-/**
- * De-indent content that was indented by live-wrap.mjs.
- * The wrap script adds `indent + ' '` (4 extra spaces) to each line.
- * We restore to just `indent` level.
- */
-function deindentContent(contentLines, baseIndent) {
- // Find the minimum indentation in the content to determine how much was added
- let minIndent = Infinity;
- for (const line of contentLines) {
- if (line.trim() === '') continue;
- const leadingSpaces = line.match(/^(\s*)/)[1].length;
- minIndent = Math.min(minIndent, leadingSpaces);
- }
- if (minIndent === Infinity) minIndent = 0;
-
- // Strip the extra indentation and re-add base indent
- return contentLines.map(line => {
- if (line.trim() === '') return '';
- return baseIndent + line.slice(minIndent);
- });
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- return { open: '<!--', close: '-->' };
-}
-
-// ---------------------------------------------------------------------------
-// File search (find the file containing session markers)
-// ---------------------------------------------------------------------------
-
-function findSessionFile(id, cwd) {
- const marker = 'impeccable-variants-start ' + id;
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, marker, seen, 0);
- if (result) {
- const content = fs.readFileSync(result, 'utf-8');
- return { file: result, content, lines: content.split('\n') };
- }
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth) {
- if (depth > 5) return null;
- let realDir;
- try { realDir = fs.realpathSync(dir); } catch { return null; }
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- if (!EXTENSIONS.includes(path.extname(entry.name).toLowerCase())) continue;
- const filePath = path.join(dir, entry.name);
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip */ }
- }
-
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
- if (result) return result;
- }
-
- return null;
-}
-
-// ---------------------------------------------------------------------------
-// Utilities
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-accept.mjs') || _running?.endsWith('live-accept.mjs/')) {
- acceptCli();
-}
-
-export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax };
@@ -1,123 +0,0 @@
-/**
- * Browser-side durable session helpers for Impeccable live mode.
- *
- * Kept separate from live-browser.js so recovery state can be tested without
- * booting the full overlay UI. Served before live-browser.js and attached to
- * window.__IMPECCABLE_LIVE_SESSION__.
- */
-(function (root) {
- 'use strict';
-
- function createLiveBrowserSessionState({ prefix, storage, idFactory }) {
- if (!prefix) throw new Error('prefix required');
- const store = storage || root.localStorage;
- const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };
- const sessionKey = prefix + '-session';
- const handledKey = sessionKey + '-handled';
- const scrollKey = sessionKey + '-scroll';
- let checkpointRevision = 0;
- const owner = makeId();
-
- function safeRead(key) {
- try { return store.getItem(key); } catch { return null; }
- }
-
- function safeWrite(key, value) {
- try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }
- }
-
- function safeRemove(key) {
- try { store.removeItem(key); } catch { /* unavailable storage */ }
- }
-
- function loadSession() {
- try {
- const raw = safeRead(sessionKey);
- if (!raw) return null;
- const parsed = JSON.parse(raw);
- if (Number.isInteger(parsed.checkpointRevision)) {
- checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);
- }
- return parsed;
- } catch { return null; }
- }
-
- function saveSession(session) {
- if (!session || !session.id) return;
- const payload = {
- ...session,
- checkpointRevision,
- };
- safeWrite(sessionKey, JSON.stringify(payload));
- }
-
- function clearSession() {
- safeRemove(sessionKey);
- }
-
- function nextCheckpointRevision() {
- checkpointRevision += 1;
- const existing = loadSession();
- if (existing?.id) saveSession(existing);
- return checkpointRevision;
- }
-
- function seedCheckpointRevision(value) {
- if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);
- return checkpointRevision;
- }
-
- function currentCheckpointRevision() {
- return checkpointRevision;
- }
-
- function markHandled(id) {
- if (!id) return;
- safeWrite(handledKey, id);
- }
-
- function isHandled(id) {
- return !!id && safeRead(handledKey) === id;
- }
-
- function clearHandled() {
- safeRemove(handledKey);
- }
-
- function writeScrollY(y) {
- safeWrite(scrollKey, String(y));
- }
-
- function readScrollY() {
- const raw = safeRead(scrollKey);
- if (raw == null) return null;
- const n = parseFloat(raw);
- return isFinite(n) ? n : null;
- }
-
- function clearScrollY() {
- safeRemove(scrollKey);
- }
-
- return {
- owner,
- sessionKey,
- handledKey,
- scrollKey,
- saveSession,
- loadSession,
- clearSession,
- nextCheckpointRevision,
- seedCheckpointRevision,
- currentCheckpointRevision,
- markHandled,
- isHandled,
- clearHandled,
- writeScrollY,
- readScrollY,
- clearScrollY,
- };
- }
-
- root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };
-})(typeof window !== 'undefined' ? window : globalThis);
@@ -1,4860 +0,0 @@
-/**
- * Impeccable Live Variant Mode — Browser Script
- *
- * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
- * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
- * before this code.
- *
- * UI: a single floating bar that morphs between three states —
- * configure (pick action + go), generating (progressive dots), and cycling
- * (prev/next + accept/discard). Feels like Spotlight, not a modal.
- */
-(function () {
- 'use strict';
- if (typeof window === 'undefined') return;
-
- // Guard against double-init. Bun's HTML loader may process the <script> tag
- // and create a bundled copy alongside the external load, or HMR may re-execute.
- // Check BEFORE reading token/port to catch all cases.
- if (window.__IMPECCABLE_LIVE_INIT__) return;
- window.__IMPECCABLE_LIVE_INIT__ = true;
-
- const TOKEN = window.__IMPECCABLE_TOKEN__;
- const PORT = window.__IMPECCABLE_PORT__;
- if (!TOKEN || !PORT) {
- window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
- return;
- }
-
- // ---------------------------------------------------------------------------
- // Design tokens
- // ---------------------------------------------------------------------------
-
- // Brand magenta is pinned to the site token (--color-accent in main.css)
- // so Accept / knobs / cycle-dots match the site's accent, not a washed
- // theme-adjusted one.
- const C = {
- brand: 'oklch(60% 0.25 350)',
- brandHov: 'oklch(52% 0.25 350)',
- brandSoft: 'oklch(60% 0.25 350 / 0.15)',
- ink: 'oklch(15% 0.01 350)',
- ash: 'oklch(55% 0 0)',
- paper: 'oklch(98% 0.005 350 / 0.92)',
- paperSolid:'oklch(98% 0.005 350)',
- mist: 'oklch(90% 0.01 350 / 0.6)',
- white: 'oklch(99% 0 0)',
- };
- const FONT = 'system-ui, -apple-system, sans-serif';
- const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
- // z-index: detect overlays use 99999, so our UI must be above them
- const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };
- const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
- const PREFIX = 'impeccable-live';
- const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
- prefix: PREFIX,
- storage: localStorage,
- idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),
- });
- if (!sessionState) {
- console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');
- window.__IMPECCABLE_LIVE_INIT__ = false;
- return;
- }
- const HIGHLIGHT_TRANSITION =
- 'top 140ms ' + EASE +
- ', left 140ms ' + EASE +
- ', width 140ms ' + EASE +
- ', height 140ms ' + EASE +
- ', opacity 150ms ease';
- const TOOLTIP_TRANSITION =
- 'top 140ms ' + EASE + ', left 140ms ' + EASE + ', opacity 150ms ease';
-
- const SKIP_TAGS = new Set([
- 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
- ]);
-
- // SVG icons stack above each chip label. All strokes use currentColor so the
- // icon recolors to C.brand when its chip is selected. 20x20 render, 24-viewBox,
- // 1.5 stroke — visually consistent with the Foundation grid on the homepage.
- const ICON_ATTRS = 'width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block"';
- const ICONS = {
- impeccable: `<svg ${ICON_ATTRS}><path d="M4 20l4-1L18 9l-3-3L5 16z"/><path d="M14 7l3 3"/></svg>`,
- bolder: `<svg ${ICON_ATTRS}><rect x="6" y="12" width="4" height="7" rx="0.5"/><rect x="14" y="5" width="4" height="14" rx="0.5"/></svg>`,
- quieter: `<svg ${ICON_ATTRS}><rect x="6" y="5" width="4" height="14" rx="0.5"/><rect x="14" y="12" width="4" height="7" rx="0.5"/></svg>`,
- distill: `<svg ${ICON_ATTRS}><path d="M4 5h16l-6 8v7l-4-2v-5z"/></svg>`,
- polish: `<svg ${ICON_ATTRS}><path d="M15 3l1 3 3 1-3 1-1 3-1-3-3-1 3-1z"/><path d="M7 13l0.6 1.8 1.8 0.6-1.8 0.6-0.6 1.8-0.6-1.8-1.8-0.6 1.8-0.6z"/></svg>`,
- typeset: `<svg ${ICON_ATTRS}><path d="M5 6h14" stroke-width="2.6"/><path d="M5 12h9" stroke-width="1.9"/><path d="M5 18h5" stroke-width="1.3"/></svg>`,
- colorize: `<svg ${ICON_ATTRS}><circle cx="9" cy="10" r="5"/><circle cx="15" cy="10" r="5"/><circle cx="12" cy="15" r="5"/></svg>`,
- layout: `<svg ${ICON_ATTRS}><rect x="3" y="4" width="8" height="16" rx="0.5"/><rect x="13" y="4" width="8" height="7" rx="0.5"/><rect x="13" y="13" width="8" height="7" rx="0.5"/></svg>`,
- adapt: `<svg ${ICON_ATTRS}><rect x="2.5" y="5" width="12" height="11" rx="1"/><line x1="2.5" y1="19" x2="14.5" y2="19"/><rect x="16.5" y="8" width="5" height="11" rx="1"/></svg>`,
- animate: `<svg ${ICON_ATTRS}><path d="M3 18c4-4 6-10 10-10"/><path d="M13 8c3 0 5 5 8 10"/><circle cx="13" cy="8" r="1.6" fill="currentColor" stroke="none"/></svg>`,
- delight: `<svg ${ICON_ATTRS}><path d="M12 3l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>`,
- overdrive: `<svg ${ICON_ATTRS}><path d="M13 3L5 13h5l-1 8 9-12h-6z"/></svg>`,
- };
-
- const ACTIONS = [
- { value: 'impeccable', label: 'Freeform' },
- { value: 'bolder', label: 'Bolder' },
- { value: 'quieter', label: 'Quieter' },
- { value: 'distill', label: 'Distill' },
- { value: 'polish', label: 'Polish' },
- { value: 'typeset', label: 'Typeset' },
- { value: 'colorize', label: 'Colorize' },
- { value: 'layout', label: 'Layout' },
- { value: 'adapt', label: 'Adapt' },
- { value: 'animate', label: 'Animate' },
- { value: 'delight', label: 'Delight' },
- { value: 'overdrive', label: 'Overdrive' },
- ];
-
- // ---------------------------------------------------------------------------
- // State
- // ---------------------------------------------------------------------------
-
- let state = 'IDLE';
- let hoveredElement = null;
- let selectedElement = null;
- let currentSessionId = null;
- let expectedVariants = 0;
- let arrivedVariants = 0;
- let visibleVariant = 0;
- let variantObserver = null;
- let hasProjectContext = false;
- let selectedAction = 'impeccable';
- let selectedCount = 3;
- const browserOwner = sessionState.owner;
- let checkpointTimer = null;
-
- // Scroll lock — holds window.scrollY at a fixed value while the session is
- // active, so HMR DOM patches and variant swaps can't drift the page. See
- // startScrollLock / stopScrollLock below.
- let scrollLockObserver = null;
- let scrollLockTargetY = null;
- let scrollLockRaf = null;
- let scrollLockAbort = null;
-
- // Dedicated key for scroll position — SEPARATE from LS_KEY so that
- // saveSession's state updates don't clobber a carefully-captured scrollY.
- // (Previously: saveSession wrote scrollY alongside state, so every call
- // during resume overwrote the pre-reload value with whatever the browser
- // had landed on, typically 0.)
- function writeScrollY(y) { sessionState.writeScrollY(y); }
- function readScrollY() { return sessionState.readScrollY(); }
- function clearScrollY() { sessionState.clearScrollY(); }
-
- // Pre-empt the browser: apply manual scroll restoration and jump to the
- // saved scrollY at script-parse time. Retries on fonts.ready and load
- // are essential: scrollTo(y) clamps to the current document.scrollHeight,
- // which is often hundreds of pixels short of the final value until
- // async-loaded fonts swap in and reflow.
- try {
- history.scrollRestoration = 'manual';
- const savedY = readScrollY();
- if (savedY != null) {
- const apply = () => {
- if (Math.abs(window.scrollY - savedY) > 0.5) {
- console.log('[impeccable.scroll] early restore', { from: window.scrollY, to: savedY });
- window.scrollTo(0, savedY);
- }
- };
- apply();
- if (document.fonts?.ready) document.fonts.ready.then(apply).catch(() => {});
- window.addEventListener('load', apply, { once: true });
- }
- } catch {}
-
- // UI refs
- let highlightEl = null;
- let tooltipEl = null;
- let barEl = null;
- let pickerEl = null;
- let toastEl = null;
- let scrollRaf = null;
-
- // ---------------------------------------------------------------------------
- // Helpers
- // ---------------------------------------------------------------------------
-
- function own(el) {
- return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
- }
-
- function pickable(el) {
- if (!el || el.nodeType !== 1) return false;
- if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
- if (own(el)) return false;
- const r = el.getBoundingClientRect();
- return r.width >= 20 && r.height >= 20;
- }
-
- function desc(el) {
- if (!el) return '';
- let s = el.tagName.toLowerCase();
- if (el.id) s += '#' + el.id;
- else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
- return s;
- }
-
- function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
-
- // Modal-aware chrome: keep our floating UI clickable inside Radix /
- // Headless UI / vaul portals.
- //
- // Two host-page behaviors break us when the picked element lives inside a
- // modal dialog:
- //
- // 1. Modal scroll-lock disables outside pointer events. Radix's
- // `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
- // while a modal is open and only restores `auto` on the layer. Our
- // chrome inherits `none` from <body> and becomes unclickable.
- // 2. The dialog's outside-interaction handler (Radix's
- // `usePointerDownOutside`) listens at document level and dismisses
- // the dialog whenever a `pointerdown` lands outside the layer node.
- // Our chrome is a sibling of <body>, so Radix classifies our clicks
- // as outside and tears the dialog down mid-task.
- //
- // We can't reliably re-parent our chrome into the dialog subtree (z-index
- // stacking, scroll containers, theming all become host-page concerns), so
- // we defang both behaviors at our root:
- //
- // - `pointer-events: auto !important` overrides the inherited `none`.
- // - Stop `pointerdown` / `mousedown` propagation so the document-level
- // dismiss listener never fires for our clicks.
- // - Stop `focusin` propagation so any focus shifts inside our chrome
- // don't read as "focus moved outside the dialog" to focus traps.
- //
- // Click events still bubble normally — only the early pointer/focus
- // signals that drive outside-interaction detection are silenced.
- function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
- if (!rootEl) return;
- if (setPointerEvents) {
- rootEl.style.setProperty('pointer-events', 'auto', 'important');
- }
- const stop = (e) => e.stopPropagation();
- rootEl.addEventListener('pointerdown', stop);
- rootEl.addEventListener('mousedown', stop);
- rootEl.addEventListener('focusin', stop);
- }
-
- // ---------------------------------------------------------------------------
- // Highlight overlay
- // ---------------------------------------------------------------------------
-
- function initHighlight() {
- highlightEl = document.createElement('div');
- highlightEl.id = PREFIX + '-highlight';
- Object.assign(highlightEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- border: '2px solid ' + C.brand, borderRadius: '3px',
- pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
- transition: HIGHLIGHT_TRANSITION,
- display: 'none', opacity: '0',
- });
- document.body.appendChild(highlightEl);
-
- tooltipEl = document.createElement('div');
- tooltipEl.id = PREFIX + '-tooltip';
- Object.assign(tooltipEl.style, {
- position: 'fixed',
- background: C.ink, color: C.white,
- fontFamily: MONO, fontSize: '10px', fontWeight: '500',
- padding: '2px 6px', borderRadius: '3px',
- zIndex: Z.highlight + 1, pointerEvents: 'none',
- whiteSpace: 'nowrap', display: 'none',
- letterSpacing: '0.02em',
- transition: TOOLTIP_TRANSITION,
- });
- document.body.appendChild(tooltipEl);
- }
-
- function showHighlight(el) {
- if (!el || !highlightEl) return;
- const r = el.getBoundingClientRect();
- const top = (r.top - 2) + 'px', left = (r.left - 2) + 'px';
- const width = (r.width + 4) + 'px', height = (r.height + 4) + 'px';
- const tipTop = r.top - 20;
- const tipY = (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px';
- const tipX = Math.max(4, r.left) + 'px';
- tooltipEl.textContent = desc(el);
-
- const hiWasHidden = highlightEl.style.display === 'none' || highlightEl.style.opacity === '0';
- if (hiWasHidden) {
- // Snap to first target without animating from (0,0), then fade in.
- highlightEl.style.transition = 'none';
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block' });
- tooltipEl.style.transition = 'none';
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block' });
- void highlightEl.offsetWidth;
- highlightEl.style.transition = HIGHLIGHT_TRANSITION;
- highlightEl.style.opacity = '1';
- tooltipEl.style.transition = TOOLTIP_TRANSITION;
- tooltipEl.style.opacity = '1';
- } else {
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block', opacity: '1' });
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block', opacity: '1' });
- }
- }
-
- function hideHighlight() {
- if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
- if (tooltipEl) { tooltipEl.style.opacity = '0'; tooltipEl.style.display = 'none'; }
- }
-
- // ---------------------------------------------------------------------------
- // Annotation overlay (comment pins + magenta strokes)
- //
- // Active while state === 'CONFIGURING'. The overlay is a fixed-positioned
- // sibling of <body> mirroring selectedElement's bounding rect. Click (no
- // drag) drops a comment pin; drag paints a magenta SVG stroke. All coords
- // are stored in element-local CSS px so they survive scroll / resize and
- // correlate directly with the captured PNG.
- // ---------------------------------------------------------------------------
-
- const DRAG_THRESHOLD = 5; // px — below this, treat pointerup as a click
- const PIN_DBL_CLICK_MS = 300; // two clicks on the same pin within this delete it
- let annotOverlayEl = null;
- let annotSvgEl = null;
- let annotPinsEl = null;
- let annotClearChipEl = null;
- let annotState = { comments: [], strokes: [] };
- let annotActive = false;
- // `annotPointer` is either:
- // { kind: 'new', x0, y0, moved, strokeEl, strokePoints } creating a stroke/pin
- // { kind: 'pin', idx, startPointer, startPin, moved } dragging an existing pin
- let annotPointer = null;
- let annotEditing = null; // { idx, input, wrapEl }
- let annotLastPinClick = { idx: -1, time: 0 }; // for click-click-to-delete
-
- function initAnnotOverlay() {
- annotOverlayEl = document.createElement('div');
- annotOverlayEl.id = PREFIX + '-annot';
- Object.assign(annotOverlayEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- pointerEvents: 'auto', zIndex: Z.highlight + 2,
- display: 'none', overflow: 'visible',
- cursor: 'crosshair', touchAction: 'none',
- });
-
- annotSvgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- annotSvgEl.id = PREFIX + '-annot-svg';
- Object.assign(annotSvgEl.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%',
- // The SVG itself doesn't absorb clicks; individual hit-paths opt-in via
- // pointer-events=stroke so gaps still fall through to the overlay.
- pointerEvents: 'none', overflow: 'visible',
- });
- annotOverlayEl.appendChild(annotSvgEl);
-
- annotPinsEl = document.createElement('div');
- annotPinsEl.id = PREFIX + '-annot-pins';
- Object.assign(annotPinsEl.style, {
- position: 'absolute', inset: '0',
- pointerEvents: 'none',
- });
- annotOverlayEl.appendChild(annotPinsEl);
-
- annotClearChipEl = document.createElement('div');
- annotClearChipEl.id = PREFIX + '-annot-clear';
- annotClearChipEl.dataset.annotClear = 'true';
- annotClearChipEl.textContent = 'Clear';
- Object.assign(annotClearChipEl.style, {
- position: 'absolute', top: '8px', right: '8px',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '10px', fontWeight: '500',
- letterSpacing: '0.08em', textTransform: 'uppercase',
- padding: '5px 12px', borderRadius: '999px',
- cursor: 'pointer', pointerEvents: 'auto',
- display: 'none', userSelect: 'none',
- boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
- });
- annotOverlayEl.appendChild(annotClearChipEl);
-
- annotOverlayEl.addEventListener('pointerdown', onAnnotDown);
- annotOverlayEl.addEventListener('pointermove', onAnnotMove);
- annotOverlayEl.addEventListener('pointerup', onAnnotUp);
- annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
- document.body.appendChild(annotOverlayEl);
- // Modal-host friendliness: pointer-events is already 'auto' on this
- // overlay; we only need to silence the host's outside-interaction
- // listeners. Don't override pointer-events here (the overlay toggles
- // visibility via display:none, which is fine).
- defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
- }
-
- function updateClearChip() {
- if (!annotClearChipEl) return;
- const hasAny = annotState.comments.length > 0 || annotState.strokes.length > 0;
- annotClearChipEl.style.display = hasAny ? 'block' : 'none';
- }
-
- function showAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- annotActive = true;
- positionAnnotOverlay(el);
- annotOverlayEl.style.display = 'block';
- }
-
- function hideAnnotOverlay() {
- annotActive = false;
- if (annotOverlayEl) annotOverlayEl.style.display = 'none';
- // Drop any in-progress edit without touching annotState — clearAnnotations
- // (if the caller is exiting configure mode) handles state reset.
- annotEditing = null;
- }
-
- function positionAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- const r = el.getBoundingClientRect();
- Object.assign(annotOverlayEl.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- annotSvgEl.setAttribute('viewBox', '0 0 ' + r.width + ' ' + r.height);
- }
-
- function clearAnnotations() {
- annotState.comments = [];
- annotState.strokes = [];
- if (annotSvgEl) while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- if (annotPinsEl) annotPinsEl.innerHTML = '';
- annotPointer = null;
- annotEditing = null;
- annotLastPinClick = { idx: -1, time: 0 };
- updateClearChip();
- }
-
- // Rebuild the SVG layer. Each stroke gets a wider invisible hit path
- // beneath the visible magenta path so clicks register on thin lines.
- function redrawStrokes() {
- while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- annotState.strokes.forEach((s, idx) => {
- const d = pointsToPath(s.points);
- const hit = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- hit.setAttribute('d', d);
- hit.setAttribute('stroke', 'transparent');
- hit.setAttribute('stroke-width', '16');
- hit.setAttribute('stroke-linecap', 'round');
- hit.setAttribute('stroke-linejoin', 'round');
- hit.setAttribute('fill', 'none');
- hit.setAttribute('pointer-events', 'stroke');
- hit.style.cursor = 'pointer';
- hit.dataset.annotStroke = String(idx);
- annotSvgEl.appendChild(hit);
- const visible = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- visible.setAttribute('d', d);
- visible.setAttribute('stroke', C.brand);
- visible.setAttribute('stroke-width', '3');
- visible.setAttribute('stroke-linecap', 'round');
- visible.setAttribute('stroke-linejoin', 'round');
- visible.setAttribute('fill', 'none');
- visible.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(visible);
- });
- updateClearChip();
- }
-
- function localCoords(e) {
- const rect = annotOverlayEl.getBoundingClientRect();
- return { x: e.clientX - rect.left, y: e.clientY - rect.top };
- }
-
- function onAnnotDown(e) {
- if (!annotActive) return;
-
- // 1) Clear chip → wipe all annotations
- if (e.target.closest?.('[data-annot-clear]')) {
- if (annotEditing) annotEditing = null;
- clearAnnotations();
- renderAllPins();
- redrawStrokes();
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 2) Stroke hit path → delete that stroke
- const strokeHit = e.target.closest?.('[data-annot-stroke]');
- if (strokeHit) {
- const idx = parseInt(strokeHit.dataset.annotStroke, 10);
- if (Number.isInteger(idx)) {
- annotState.strokes.splice(idx, 1);
- redrawStrokes();
- }
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 3) Pin → drag, edit, or delete-on-double-click
- const pinWrap = e.target.closest?.('[data-annot-pin]');
- if (pinWrap) {
- const idx = parseInt(pinWrap.dataset.annotPin, 10);
- if (!Number.isInteger(idx)) return;
- // Double-click (two pointerdowns on the same pin within window) → delete.
- const now = Date.now();
- if (annotLastPinClick.idx === idx && now - annotLastPinClick.time < PIN_DBL_CLICK_MS) {
- if (annotEditing && annotEditing.idx === idx) annotEditing = null;
- annotState.comments.splice(idx, 1);
- annotLastPinClick = { idx: -1, time: 0 };
- renderAllPins();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- annotLastPinClick = { idx, time: now };
- // If editing a different pin, commit that edit before starting here.
- if (annotEditing && annotEditing.idx !== idx) finalizeEditingPin();
- // If already editing THIS pin and the user clicked the dot, let the
- // input keep focus (don't start a drag — the click wasn't meant as one).
- if (annotEditing && annotEditing.idx === idx) return;
- const p = localCoords(e);
- const pin = annotState.comments[idx];
- annotPointer = {
- kind: 'pin', idx,
- startPointer: p,
- startPin: { x: pin.x, y: pin.y },
- moved: false,
- };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 4) Empty area → commit any open edit, then start new annotation
- if (annotEditing) {
- finalizeEditingPin();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- const p = localCoords(e);
- annotPointer = { kind: 'new', x0: p.x, y0: p.y, moved: false, strokeEl: null, strokePoints: null };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- }
-
- function onAnnotMove(e) {
- if (!annotActive || !annotPointer) return;
- const p = localCoords(e);
-
- if (annotPointer.kind === 'pin') {
- const dx = p.x - annotPointer.startPointer.x;
- const dy = p.y - annotPointer.startPointer.y;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- }
- const pin = annotState.comments[annotPointer.idx];
- if (!pin) { annotPointer = null; return; }
- pin.x = annotPointer.startPin.x + dx;
- pin.y = annotPointer.startPin.y + dy;
- renderAllPins();
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const dx = p.x - annotPointer.x0, dy = p.y - annotPointer.y0;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- const strokeEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- strokeEl.setAttribute('stroke', C.brand);
- strokeEl.setAttribute('stroke-width', '3');
- strokeEl.setAttribute('stroke-linecap', 'round');
- strokeEl.setAttribute('stroke-linejoin', 'round');
- strokeEl.setAttribute('fill', 'none');
- strokeEl.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(strokeEl);
- annotPointer.strokeEl = strokeEl;
- annotPointer.strokePoints = [[annotPointer.x0, annotPointer.y0]];
- }
- annotPointer.strokePoints.push([p.x, p.y]);
- annotPointer.strokeEl.setAttribute('d', pointsToPath(annotPointer.strokePoints));
- e.stopPropagation();
- }
-
- function onAnnotUp(e) {
- if (!annotActive || !annotPointer) return;
-
- if (annotPointer.kind === 'pin') {
- const wasDrag = annotPointer.moved;
- const idx = annotPointer.idx;
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- if (wasDrag) {
- // A drag is an intentional reposition; a follow-up click shouldn't be
- // interpreted as a double-click-to-delete.
- annotLastPinClick = { idx: -1, time: 0 };
- } else {
- beginEditPin(idx);
- }
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const wasDrag = annotPointer.moved;
- if (wasDrag) {
- annotState.strokes.push({ points: annotPointer.strokePoints });
- // Swap the temporary preview SVG path for the full render with hit paths.
- redrawStrokes();
- } else {
- const idx = annotState.comments.length;
- annotState.comments.push({ x: annotPointer.x0, y: annotPointer.y0, text: '' });
- renderAllPins();
- beginEditPin(idx);
- }
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- e.stopPropagation();
- }
-
- function pointsToPath(points) {
- if (!points || points.length === 0) return '';
- let d = 'M' + points[0][0].toFixed(1) + ' ' + points[0][1].toFixed(1);
- for (let i = 1; i < points.length; i++) {
- d += ' L' + points[i][0].toFixed(1) + ' ' + points[i][1].toFixed(1);
- }
- return d;
- }
-
- function renderAllPins() {
- annotPinsEl.innerHTML = '';
- annotState.comments.forEach((c, idx) => {
- annotPinsEl.appendChild(buildPinElement(c, idx));
- });
- updateClearChip();
- }
-
- function buildPinElement(comment, idx) {
- const interactive = idx >= 0;
- const wrap = document.createElement('div');
- if (interactive) wrap.dataset.annotPin = String(idx);
- Object.assign(wrap.style, {
- position: 'absolute',
- left: (comment.x - 7) + 'px', top: (comment.y - 7) + 'px',
- pointerEvents: interactive ? 'auto' : 'none',
- display: 'flex', alignItems: 'flex-start', gap: '6px',
- cursor: interactive ? 'grab' : 'default',
- touchAction: 'none',
- });
- const dot = document.createElement('div');
- Object.assign(dot.style, {
- width: '14px', height: '14px', borderRadius: '50%',
- background: C.brand, border: '2px solid ' + C.white,
- boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
- flexShrink: '0',
- });
- wrap.appendChild(dot);
-
- if (comment.text) {
- const bubble = document.createElement('div');
- bubble.textContent = comment.text;
- Object.assign(bubble.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- marginTop: '-2px', maxWidth: '220px',
- pointerEvents: 'none', whiteSpace: 'pre-wrap',
- wordBreak: 'break-word',
- });
- wrap.appendChild(bubble);
- }
- return wrap;
- }
-
- function beginEditPin(idx) {
- const wrapEl = annotPinsEl.querySelector('[data-annot-pin="' + idx + '"]');
- if (!wrapEl) return;
- // Strip any existing bubble (but keep the dot)
- wrapEl.querySelectorAll('div:not(:first-child)').forEach(n => n.remove());
- const input = document.createElement('input');
- input.type = 'text';
- input.placeholder = 'Note…';
- Object.assign(input.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- border: '1px solid ' + C.brand,
- outline: 'none', marginTop: '-2px',
- width: '220px', pointerEvents: 'auto',
- });
- const originalText = annotState.comments[idx].text || '';
- input.value = originalText;
- wrapEl.appendChild(input);
- annotEditing = { idx, input, wrapEl, originalText };
- input.addEventListener('keydown', onAnnotInputKey, true);
- input.addEventListener('blur', () => {
- // Fires on both focus-loss and programmatic blur; commit unless we
- // already handled it.
- if (annotEditing && annotEditing.input === input) finalizeEditingPin();
- });
- // Stop clicks/pointerdowns inside the input from bubbling to the overlay
- ['pointerdown', 'click'].forEach(ev => {
- input.addEventListener(ev, e => e.stopPropagation());
- });
- setTimeout(() => input.focus(), 0);
- }
-
- function onAnnotInputKey(e) {
- if (e.key === 'Enter') {
- e.preventDefault(); e.stopPropagation();
- finalizeEditingPin();
- } else if (e.key === 'Escape') {
- e.preventDefault(); e.stopPropagation();
- cancelEditingPin();
- } else {
- // Keep arrows / backspace from hitting global handlers
- e.stopPropagation();
- }
- }
-
- function finalizeEditingPin() {
- if (!annotEditing) return;
- const { idx, input } = annotEditing;
- const text = input.value.trim();
- annotEditing = null;
- if (text) annotState.comments[idx].text = text;
- else annotState.comments.splice(idx, 1);
- renderAllPins();
- }
-
- function cancelEditingPin() {
- if (!annotEditing) return;
- const { idx, originalText } = annotEditing;
- annotEditing = null;
- // If the pin had text before this edit, revert to it. If it was a
- // just-created empty pin, Escape removes it.
- if (originalText) {
- annotState.comments[idx].text = originalText;
- } else {
- annotState.comments.splice(idx, 1);
- }
- renderAllPins();
- }
-
- // Build a detached annotation subtree suitable for injection into the clone
- // modern-screenshot creates. Coordinates are element-local so this slots
- // straight into an element that's been made position:relative. Takes an
- // explicit snapshot so it works after annotState has been cleared.
- function buildAnnotationsForCapture(rect, snapshot) {
- const comments = snapshot ? snapshot.comments : annotState.comments;
- const strokes = snapshot ? snapshot.strokes : annotState.strokes;
- if (comments.length === 0 && strokes.length === 0) return null;
- const wrap = document.createElement('div');
- Object.assign(wrap.style, {
- position: 'absolute', top: '0', left: '0',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none', overflow: 'visible',
- });
- if (strokes.length > 0) {
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- svg.setAttribute('viewBox', '0 0 ' + rect.width + ' ' + rect.height);
- Object.assign(svg.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%', overflow: 'visible',
- });
- for (const s of strokes) {
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- path.setAttribute('stroke', C.brand);
- path.setAttribute('stroke-width', '3');
- path.setAttribute('stroke-linecap', 'round');
- path.setAttribute('stroke-linejoin', 'round');
- path.setAttribute('fill', 'none');
- path.setAttribute('d', pointsToPath(s.points));
- svg.appendChild(path);
- }
- wrap.appendChild(svg);
- }
- for (const c of comments) {
- // idx=-1 means non-interactive; pointerEvents stay off in the clone
- wrap.appendChild(buildPinElement(c, -1));
- }
- return wrap;
- }
-
- // ---------------------------------------------------------------------------
- // Element context extraction
- // ---------------------------------------------------------------------------
-
- function extractContext(el) {
- const cs = getComputedStyle(el);
- const r = el.getBoundingClientRect();
- const props = {};
- for (const sheet of document.styleSheets) {
- try {
- for (const rule of sheet.cssRules) {
- if (rule.style) for (let i = 0; i < rule.style.length; i++) {
- const p = rule.style[i];
- if (p.startsWith('--') && !props[p]) {
- const v = cs.getPropertyValue(p).trim();
- if (v) props[p] = v;
- }
- }
- }
- } catch { /* cross-origin */ }
- }
- return {
- tagName: el.tagName.toLowerCase(), id: el.id || null,
- classes: [...el.classList],
- textContent: (el.textContent || '').slice(0, 500),
- outerHTML: el.outerHTML.slice(0, 10000),
- computedStyles: {
- 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
- 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
- 'color': cs.color, 'background': cs.background,
- 'background-color': cs.backgroundColor,
- 'padding': cs.padding, 'margin': cs.margin,
- 'display': cs.display, 'position': cs.position,
- 'gap': cs.gap, 'border-radius': cs.borderRadius,
- 'box-shadow': cs.boxShadow,
- },
- cssCustomProperties: props,
- parentContext: el.parentElement
- ? '<' + el.parentElement.tagName.toLowerCase()
- + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
- + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
- + '>'
- : null,
- boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
- };
- }
-
- // ---------------------------------------------------------------------------
- // The Bar — one floating element, three modes
- // ---------------------------------------------------------------------------
-
- // Contextual-bar palette. Cached at init so every build*Row reads a
- // consistent set of colors; detectPageTheme runs once rather than on every
- // phase transition.
- let BP = null;
-
- // Bar shadow variants. The default projects down + subtle around. When
- // the Tune popover opens below the bar, a downward shadow lands on the
- // dark popover and reads as a bright ghost line. We swap to UP-only while
- // tune is open below so the popover's top edge is clean.
- const BAR_SHADOW_DEFAULT = '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_UP = '0 -4px 20px oklch(0% 0 0 / 0.08), 0 -1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_DOWN = BAR_SHADOW_DEFAULT;
-
- function initBar() {
- BP = barPaletteForTheme(detectPageTheme());
- barEl = document.createElement('div');
- barEl.id = PREFIX + '-bar';
- Object.assign(barEl.style, {
- position: 'fixed', zIndex: Z.bar,
- display: 'none', opacity: '0',
- transform: 'translateY(6px)',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- background: BP.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + BP.hairline,
- borderRadius: '10px',
- boxShadow: BAR_SHADOW_DEFAULT,
- transition: 'box-shadow 0.2s ease, opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- fontFamily: FONT, fontSize: '13px', color: BP.text,
- padding: '6px',
- maxWidth: '520px', minWidth: '320px',
- });
- document.body.appendChild(barEl);
- defangOutsideHandlers(barEl);
- }
-
- function positionBar() {
- if (!barEl || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- const barH = barEl.offsetHeight || 44;
- const barW = barEl.offsetWidth || 380;
- const GLOBAL_BAR_RESERVE = 64; // global bar height + bottom margin + breathing room
- const GAP = 8;
-
- // Prefer below the element; fall back to above; if neither fits (element
- // taller than viewport), pin to a stable viewport anchor so the bar
- // doesn't teleport between top and bottom as the user scrolls.
- let top;
- const belowTop = r.bottom + GAP;
- const aboveTop = r.top - barH - GAP;
- if (belowTop + barH + GAP <= window.innerHeight - GLOBAL_BAR_RESERVE) {
- top = belowTop;
- } else if (aboveTop >= GAP) {
- top = aboveTop;
- } else {
- top = window.innerHeight - barH - GLOBAL_BAR_RESERVE;
- }
-
- let left = r.left + (r.width - barW) / 2;
- if (left < GAP) left = GAP;
- if (left + barW > window.innerWidth - GAP) left = window.innerWidth - barW - GAP;
- Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
- }
-
- function showBar(mode) {
- barEl.innerHTML = '';
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- barEl.style.display = 'block';
- positionBar();
- requestAnimationFrame(() => {
- barEl.style.opacity = '1';
- barEl.style.transform = 'translateY(0)';
- });
- }
-
- function hideBar() {
- if (!barEl) return;
- barEl.style.opacity = '0';
- barEl.style.transform = 'translateY(6px)';
- setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
- hideActionPicker();
- closeTunePopover();
- }
-
- function updateBarContent(mode) {
- if (!barEl || barEl.style.display === 'none') return;
- barEl.innerHTML = '';
- // Reset bar styling to the theme-aware palette
- barEl.style.background = BP.surface;
- barEl.style.border = '1px solid ' + BP.hairline;
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- else if (mode === 'saving') barEl.appendChild(buildSavingRow());
- else if (mode === 'confirmed') {
- barEl.appendChild(buildConfirmedRow());
- barEl.style.background = 'oklch(95% 0.05 145)';
- barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
- }
- }
-
- // --- Configure row ---
-
- function buildConfigureRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
-
- // Action pill
- const pill = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '4px',
- padding: '5px 10px', borderRadius: '6px',
- background: BP.mark, color: BP.markText,
- fontFamily: FONT, fontSize: '12px', fontWeight: '500',
- border: 'none', cursor: 'pointer',
- transition: 'background 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap', flexShrink: '0',
- });
- pill.textContent = actionLabel() + ' \u25BE';
- pill.addEventListener('mouseenter', () => pill.style.background = BP.accent);
- pill.addEventListener('mouseleave', () => pill.style.background = BP.mark);
- pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
- pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
- pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
- row.appendChild(pill);
-
- // Freeform input. Focus state shows an accent-colored border only —
- // an earlier version tinted the background with `BP.accentSoft`, which
- // composited against the dark bar surface to a murky purple where the
- // browser's default placeholder gray was unreadable. Placeholder color
- // is set explicitly via a one-shot stylesheet keyed off this input's id
- // so it picks up the bar's `textDim` token in both themes.
- const input = document.createElement('input');
- input.id = PREFIX + '-input';
- input.type = 'text';
- input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
- Object.assign(input.style, {
- flex: '1', minWidth: '0',
- padding: '5px 8px', borderRadius: '6px',
- border: '1px solid transparent', background: 'transparent',
- fontFamily: FONT, fontSize: '12px', color: BP.text,
- outline: 'none',
- transition: 'border-color 0.15s ease',
- });
- if (!document.getElementById(PREFIX + '-input-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-input-style';
- s.textContent =
- '#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
- document.head.appendChild(s);
- }
- input.addEventListener('focus', () => {
- input.style.borderColor = BP.accent;
- });
- input.addEventListener('blur', () => {
- input.style.borderColor = 'transparent';
- });
- input.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
- if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; return; }
- // Let arrow keys pass through to the element picker when the input is empty
- if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && !input.value) return;
- e.stopPropagation();
- });
- row.appendChild(input);
-
- // Variant count toggle
- const count = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: MONO, fontSize: '11px', fontWeight: '600',
- color: BP.textDim, cursor: 'pointer',
- transition: 'color 0.12s ease, border-color 0.12s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- count.textContent = '\u00D7' + selectedCount;
- count.title = 'Variants: click to change';
- count.addEventListener('mouseenter', () => { count.style.color = BP.text; count.style.borderColor = BP.text; });
- count.addEventListener('mouseleave', () => { count.style.color = BP.textDim; count.style.borderColor = BP.hairline; });
- count.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
- count.textContent = '\u00D7' + selectedCount;
- });
- row.appendChild(count);
-
- // Go button
- const go = el('button', {
- padding: '5px 12px', borderRadius: '6px',
- border: 'none', background: BP.accent, color: BP.mark,
- fontFamily: FONT, fontSize: '12px', fontWeight: '600',
- cursor: 'pointer',
- transition: 'filter 0.12s ease, transform 0.1s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- go.textContent = 'Go \u2192';
- go.addEventListener('mouseenter', () => go.style.filter = 'brightness(1.1)');
- go.addEventListener('mouseleave', () => go.style.filter = 'none');
- go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
- go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
- go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
- row.appendChild(go);
-
- // Auto-focus input after a beat
- setTimeout(() => input.focus(), 60);
- return row;
- }
-
- // --- Generating row ---
-
- function buildGeneratingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 4px',
- });
-
- // Action label
- const label = el('span', {
- fontWeight: '600', fontSize: '12px', color: BP.text,
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- label.textContent = actionLabel();
- row.appendChild(label);
-
- // Dots
- row.appendChild(buildDots(false));
-
- // Status
- const status = el('span', {
- fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',
- marginLeft: 'auto',
- });
- // Variants currently arrive atomically in a single file edit, so a
- // per-variant counter would lie. Say what's true.
- status.textContent = arrivedVariants < expectedVariants
- ? 'Generating ' + expectedVariants + ' variants...'
- : 'Done';
- row.appendChild(status);
-
- return row;
- }
-
- // --- Cycling row ---
-
- const TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';
-
- function buildCyclingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '6px',
- padding: '1px 2px',
- });
-
- // Prev
- const prev = navBtn('\u2190');
- prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
- if (visibleVariant <= 1) prev.style.opacity = '0.3';
- row.appendChild(prev);
-
- // Dots (clickable)
- row.appendChild(buildDots(true));
-
- // Counter
- const counter = el('span', {
- fontFamily: MONO, fontSize: '11px', fontWeight: '500',
- color: BP.textDim, minWidth: '24px', textAlign: 'center',
- });
- counter.textContent = visibleVariant + '/' + arrivedVariants;
- row.appendChild(counter);
-
- // Next
- const next = navBtn('\u2192');
- next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
- if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
- row.appendChild(next);
-
- // Tune chip — only when the visible variant exposes params
- const visParams = parseVariantParams(getVisibleVariantEl());
- const hasParams = visParams.length > 0;
- if (hasParams) {
- const tune = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '6px',
- padding: '4px 10px', borderRadius: '5px',
- border: '1px solid transparent',
- background: tuneOpen ? BP.accentSoft : 'transparent',
- color: tuneOpen ? BP.accent : BP.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'color 0.12s ease, background 0.12s ease',
- whiteSpace: 'nowrap',
- });
- tune.innerHTML = TUNE_ICON_SVG;
- const tuneLabel = document.createElement('span');
- tuneLabel.textContent = 'Tune';
- tune.appendChild(tuneLabel);
- const tuneBadge = document.createElement('span');
- Object.assign(tuneBadge.style, {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- minWidth: '16px', height: '16px', padding: '0 4px',
- borderRadius: '999px',
- background: tuneOpen ? C.brand : BP.hairline,
- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',
- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',
- lineHeight: '1',
- boxSizing: 'border-box',
- });
- tuneBadge.textContent = String(visParams.length);
- tune.appendChild(tuneBadge);
- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';
- tune.addEventListener('mouseenter', () => {
- if (!tuneOpen) tune.style.background = BP.accentSoft;
- });
- tune.addEventListener('mouseleave', () => {
- if (!tuneOpen) tune.style.background = 'transparent';
- });
- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });
- tune.dataset.iceqTune = '1';
- row.appendChild(tune);
- }
-
- // Spacer
- row.appendChild(el('div', { flex: '1' }));
-
- // Accept — primary action, uses the site's saturated brand magenta
- // with paper-white text, not the theme-muted BP.accent.
- const accept = el('button', {
- padding: '5px 14px', borderRadius: '5px',
- border: 'none', background: C.brand, color: 'oklch(98% 0 0)',
- fontFamily: FONT, fontSize: '11px', fontWeight: '600',
- cursor: 'pointer', transition: 'filter 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap',
- });
- accept.textContent = '\u2713 Accept';
- accept.addEventListener('mouseenter', () => accept.style.filter = 'brightness(1.08)');
- accept.addEventListener('mouseleave', () => accept.style.filter = 'none');
- accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');
- accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');
- accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
- row.appendChild(accept);
-
- // Discard
- const discard = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: FONT, fontSize: '11px', color: BP.textDim,
- cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
- });
- discard.textContent = '\u2715';
- discard.title = 'Discard all variants';
- discard.addEventListener('mouseenter', () => { discard.style.color = BP.text; discard.style.borderColor = BP.text; });
- discard.addEventListener('mouseleave', () => { discard.style.color = BP.textDim; discard.style.borderColor = BP.hairline; });
- discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
- row.appendChild(discard);
-
- return row;
- }
-
- // --- Shared UI builders ---
-
- // --- Saving row (waiting for agent to process accept/discard) ---
-
- function buildSavingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const spinner = el('div', {
- width: '14px', height: '14px', borderRadius: '50%',
- border: '2px solid ' + BP.hairline,
- borderTopColor: BP.accent,
- animation: 'impeccable-spin 0.6s linear infinite',
- flexShrink: '0',
- });
- row.appendChild(spinner);
- const label = el('span', {
- fontSize: '12px', color: BP.textDim, fontWeight: '500',
- });
- label.textContent = 'Applying variant...';
- row.appendChild(label);
-
- // Inject the keyframes if not already present
- if (!document.getElementById(PREFIX + '-keyframes')) {
- const style = document.createElement('style');
- style.id = PREFIX + '-keyframes';
- style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
- document.head.appendChild(style);
- }
- return row;
- }
-
- // --- Confirmed row (green success, auto-dismisses) ---
-
- function buildConfirmedRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const check = el('span', {
- fontSize: '15px', lineHeight: '1', flexShrink: '0',
- color: 'oklch(45% 0.15 145)',
- });
- check.textContent = '\u2713';
- row.appendChild(check);
- const label = el('span', {
- fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
- });
- label.textContent = 'Variant applied';
- row.appendChild(label);
- return row;
- }
-
- // --- Shared UI builders ---
-
- function buildDots(clickable) {
- const container = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
- for (let i = 1; i <= expectedVariants; i++) {
- const arrived = i <= arrivedVariants;
- const active = i === visibleVariant;
- // active: solid site-brand magenta dot. arrived+inactive: muted neutral.
- // pending (not yet arrived): faint outline ring. No borders on arrived
- // dots — the previous "accent ring + ash fill" combo read as noisy
- // magenta chips, especially when all variants had arrived and every
- // dot wore an accent ring.
- const dotBg = active ? C.brand
- : arrived ? BP.textDim
- : 'transparent';
- const dotBorder = arrived ? 'none' : '1.5px solid ' + BP.hairline;
- const dot = el('div', {
- width: active ? '8px' : '6px',
- height: active ? '8px' : '6px',
- borderRadius: '50%',
- background: dotBg,
- border: dotBorder,
- boxSizing: 'border-box',
- transition: 'all 0.2s ' + EASE,
- cursor: (clickable && arrived) ? 'pointer' : 'default',
- transform: arrived ? 'scale(1)' : 'scale(0.85)',
- opacity: arrived ? (active ? '1' : '0.6') : '0.4',
- });
- if (clickable && arrived) {
- const idx = i;
- dot.addEventListener('click', (e) => {
- e.stopPropagation();
- visibleVariant = idx;
- showVariantInDOM(currentSessionId, idx);
- updateSelectedElement();
- updateBarContent('cycling');
- });
- }
- container.appendChild(dot);
- }
- return container;
- }
-
- function navBtn(text) {
- const b = el('button', {
- width: '26px', height: '26px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- color: BP.text, fontFamily: FONT, fontSize: '13px',
- cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
- transition: 'border-color 0.12s ease, background 0.12s ease',
- padding: '0', lineHeight: '1',
- });
- b.textContent = text;
- b.addEventListener('mouseenter', () => { b.style.borderColor = BP.text; });
- b.addEventListener('mouseleave', () => { b.style.borderColor = BP.hairline; });
- return b;
- }
-
- function actionLabel() {
- const a = ACTIONS.find(a => a.value === selectedAction);
- return a ? a.label : 'Freeform';
- }
-
- function el(tag, styles) {
- const e = document.createElement(tag);
- if (styles) Object.assign(e.style, styles);
- return e;
- }
-
- // ---------------------------------------------------------------------------
- // Action picker popover
- // ---------------------------------------------------------------------------
-
- function initActionPicker() {
- const P = barPaletteForTheme(detectPageTheme());
- pickerEl = document.createElement('div');
- pickerEl.id = PREFIX + '-picker';
- Object.assign(pickerEl.style, {
- position: 'fixed', zIndex: Z.picker,
- display: 'none', opacity: '0',
- transform: 'scale(0.96) translateY(4px)',
- transformOrigin: 'bottom left',
- transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
- background: P.surface,
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
- padding: '6px',
- fontFamily: FONT,
- backdropFilter: 'blur(10px)',
- WebkitBackdropFilter: 'blur(10px)',
- });
-
- // Build the chip grid
- const grid = el('div', {
- display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
- });
-
- ACTIONS.forEach(action => {
- const chip = el('button', {
- display: 'flex', flexDirection: 'column', alignItems: 'center',
- gap: '4px',
- padding: '8px 6px', borderRadius: '6px',
- border: 'none',
- background: action.value === selectedAction ? P.accentSoft : 'transparent',
- color: action.value === selectedAction ? P.accent : P.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.1s ease, color 0.1s ease',
- textAlign: 'center', whiteSpace: 'nowrap',
- });
- const iconWrap = el('span', {
- display: 'flex', alignItems: 'center', justifyContent: 'center',
- height: '20px', opacity: '0.9',
- });
- iconWrap.innerHTML = ICONS[action.value] || '';
- const labelEl = el('span', { lineHeight: '1' });
- labelEl.textContent = action.label;
- chip.appendChild(iconWrap);
- chip.appendChild(labelEl);
- chip.dataset.action = action.value;
- chip.addEventListener('mouseenter', () => {
- if (action.value !== selectedAction) chip.style.background = P.accentSoft;
- });
- chip.addEventListener('mouseleave', () => {
- chip.style.background = action.value === selectedAction ? P.accentSoft : 'transparent';
- });
- chip.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedAction = action.value;
- hideActionPicker();
- updateBarContent('configure');
- });
- grid.appendChild(chip);
- });
-
- pickerEl.appendChild(grid);
- document.body.appendChild(pickerEl);
- defangOutsideHandlers(pickerEl);
-
- // Cache the palette on the picker so toggleActionPicker's state refresh
- // uses the same theme-aware colors when it repaints chips.
- pickerEl.__iceq_palette = P;
- }
-
- function toggleActionPicker() {
- if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
- // Rebuild chips to reflect current selection
- const P = pickerEl.__iceq_palette || barPaletteForTheme(detectPageTheme());
- pickerEl.querySelectorAll('button').forEach(chip => {
- const isActive = chip.dataset.action === selectedAction;
- chip.style.background = isActive ? P.accentSoft : 'transparent';
- chip.style.color = isActive ? P.accent : P.text;
- });
- // Position above the bar
- const barRect = barEl.getBoundingClientRect();
- const pickerH = 170; // approximate; grows with icon + label rows
- let top = barRect.top - pickerH - 6;
- if (top < 8) top = barRect.bottom + 6;
- Object.assign(pickerEl.style, {
- top: top + 'px', left: barRect.left + 'px',
- display: 'block',
- });
- requestAnimationFrame(() => {
- pickerEl.style.opacity = '1';
- pickerEl.style.transform = 'scale(1) translateY(0)';
- });
- }
-
- function hideActionPicker() {
- if (!pickerEl) return;
- pickerEl.style.opacity = '0';
- pickerEl.style.transform = 'scale(0.96) translateY(4px)';
- setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
- }
-
- // ---------------------------------------------------------------------------
- // Params panel (per-variant coarse controls)
- //
- // Variants may declare a parameter manifest via a JSON attribute on the
- // variant wrapper:
- //
- // <div data-impeccable-variant="1"
- // data-impeccable-params='[{"id":"density","kind":"steps",...}]'>
- //
- // The panel docks to the right edge of the outline during CYCLING and
- // exposes 2-5 coarse knobs. Values apply to the variant wrapper so scoped
- // CSS can respond instantly without regeneration:
- //
- // range / numeric toggle → CSS var (`--p-<id>`) used via var(--p-foo, N)
- // steps / boolean toggle → data-p-<id> attribute used via :scope[data-p-foo="..."]
- //
- // On variant switch, values reset to that variant's declared defaults.
- // On accept, current values are sent in the event payload so the agent
- // can bake them into the source-file write.
- // ---------------------------------------------------------------------------
-
- let paramsPanelEl = null; // outer wrapper (overflow:hidden, clips the slide)
- let paramsPanelInner = null; // translating content (carries bg, padding, knobs)
- let paramsPanelBody = null; // grid holding the knob cells
- let paramsCurrentValues = {}; // {paramId: value} — mirror of the visible variant's live values
- let tuneOpen = false; // whether the Tune popover is open right now
-
- // Theme-aware Tune popover. Appears as a drawer that slides out from the
- // contextual bar's bar-facing edge (below if the bar sits below the
- // element, above otherwise). Same width as the bar. Auto-wraps to extra
- // rows when the knobs exceed one row. The bar's border-radius on the
- // popover side goes flat while open so the two shapes read as one.
- let paramsPanelPalette = null;
-
- function initParamsPanel() {
- paramsPanelPalette = barPaletteForTheme(detectPageTheme());
- const P = paramsPanelPalette;
-
- // Single element, always in the DOM. The slide animation is a CSS mask
- // with mask-size growing from 0% to 100% along the bar-facing axis — no
- // display toggle, no opacity toggle, no transform trickery. The mask
- // hides everything initially; as it grows, content is revealed from
- // the bar edge outward.
- paramsPanelEl = document.createElement('div');
- paramsPanelEl.id = PREFIX + '-params-panel';
- Object.assign(paramsPanelEl.style, {
- position: 'fixed', zIndex: String(Z.bar - 1),
- background: P.surfaceDeep,
- color: P.text,
- fontFamily: FONT,
- padding: '14px 18px',
- boxSizing: 'border-box',
- borderRadius: '0 0 10px 10px',
- pointerEvents: 'none',
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
-
- // clip-path is the same conceptual reveal as mask but with rock-solid
- // transition support across engines. Closed state clips from the far
- // edge; open = inset(0) shows everything.
- clipPath: 'inset(0 0 100% 0)',
- transition: 'clip-path 0.44s ' + EASE,
-
- // Park off-screen until positionParamsPanel places it. These are NOT
- // in the transition list, so they snap instantly — no fly-in from the
- // top-left when first shown.
- top: '-9999px', left: '-9999px', width: '0',
- });
-
- paramsPanelBody = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
- gap: '12px 16px',
- });
-
- paramsPanelEl.appendChild(paramsPanelBody);
- document.body.appendChild(paramsPanelEl);
- // Don't override pointer-events: the panel toggles between 'none' (closed,
- // click-through) and 'auto' (open) on its own. Just silence the host's
- // outside-interaction listeners while the panel is open.
- defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
- paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
- }
-
- function getVisibleVariantEl() {
- if (!currentSessionId) return null;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return null;
- return wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"]');
- }
-
- function parseVariantParams(variantEl) {
- if (!variantEl) return [];
- const raw = variantEl.getAttribute('data-impeccable-params');
- if (!raw) return [];
- try {
- const parsed = JSON.parse(raw);
- return Array.isArray(parsed) ? parsed : [];
- } catch (err) {
- console.warn('[impeccable] Invalid data-impeccable-params JSON:', err.message);
- return [];
- }
- }
-
- function applyParamValue(variantEl, param, value) {
- if (!variantEl) return;
- const attr = 'data-p-' + param.id;
- if (param.kind === 'range') {
- variantEl.style.setProperty('--p-' + param.id, String(value));
- } else if (param.kind === 'toggle') {
- const on = !!value;
- variantEl.style.setProperty('--p-' + param.id, on ? '1' : '0');
- if (on) variantEl.setAttribute(attr, 'on');
- else variantEl.removeAttribute(attr);
- } else if (param.kind === 'steps') {
- variantEl.setAttribute(attr, String(value));
- }
- }
-
- function applyParamDefaults(variantEl, params) {
- paramsCurrentValues = {};
- for (const p of params) {
- paramsCurrentValues[p.id] = p.default;
- applyParamValue(variantEl, p, p.default);
- }
- }
-
- function formatRangeValue(input) {
- const max = parseFloat(input.max), min = parseFloat(input.min);
- const v = parseFloat(input.value);
- if (!isFinite(v)) return input.value;
- return (max - min) <= 2 ? v.toFixed(2) : String(Math.round(v));
- }
-
- function buildParamsPanel(variantEl, params) {
- const P = paramsPanelPalette || barPaletteForTheme(detectPageTheme());
- paramsPanelBody.innerHTML = '';
- for (const p of params) {
- const row = el('div', { display: 'flex', flexDirection: 'column', gap: '6px' });
- const labelRow = el('div', {
- display: 'flex', justifyContent: 'space-between',
- alignItems: 'baseline', gap: '8px',
- });
- const lbl = el('span', {
- fontSize: '10.5px', fontWeight: '600', color: P.text,
- letterSpacing: '0.03em',
- });
- lbl.textContent = p.label || p.id;
- labelRow.appendChild(lbl);
- const readout = el('span', {
- fontSize: '10.5px', color: P.textDim,
- fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
- });
- labelRow.appendChild(readout);
- row.appendChild(labelRow);
-
- if (p.kind === 'range') {
- const input = document.createElement('input');
- input.type = 'range';
- input.min = String(p.min != null ? p.min : 0);
- input.max = String(p.max != null ? p.max : 1);
- input.step = String(p.step != null ? p.step : 0.05);
- input.value = String(p.default);
- Object.assign(input.style, {
- width: '100%', accentColor: C.brand, cursor: 'pointer',
- });
- readout.textContent = formatRangeValue(input);
- input.addEventListener('input', (e) => {
- e.stopPropagation();
- const v = parseFloat(input.value);
- paramsCurrentValues[p.id] = v;
- readout.textContent = formatRangeValue(input);
- applyParamValue(variantEl, p, v);
- queueCheckpoint('param_changed');
- });
- row.appendChild(input);
- } else if (p.kind === 'toggle') {
- const initial = !!p.default;
- readout.textContent = initial ? 'On' : 'Off';
- const track = el('button', {
- position: 'relative', width: '36px', height: '20px',
- borderRadius: '10px', border: 'none', padding: '0',
- cursor: 'pointer',
- background: initial ? C.brand : P.hairline,
- transition: 'background 0.15s ease',
- alignSelf: 'flex-start',
- });
- const knob = el('span', {
- position: 'absolute', top: '2px',
- left: initial ? '18px' : '2px',
- width: '16px', height: '16px', borderRadius: '50%',
- background: 'oklch(98% 0 0)',
- transition: 'left 0.18s ' + EASE,
- boxShadow: '0 1px 2px oklch(0% 0 0 / 0.2)',
- });
- track.appendChild(knob);
- track.addEventListener('click', (e) => {
- e.stopPropagation();
- const next = !paramsCurrentValues[p.id];
- paramsCurrentValues[p.id] = next;
- track.style.background = next ? C.brand : P.hairline;
- knob.style.left = next ? '18px' : '2px';
- readout.textContent = next ? 'On' : 'Off';
- applyParamValue(variantEl, p, next);
- queueCheckpoint('param_changed');
- });
- row.appendChild(track);
- } else if (p.kind === 'steps') {
- const opts = (p.options || []).map(o =>
- typeof o === 'string' ? { value: o, label: o } : o
- );
- const activeOpt = opts.find(o => o.value === p.default) || opts[0];
- readout.textContent = activeOpt ? activeOpt.label : String(p.default);
- const segRow = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(' + opts.length + ', 1fr)',
- gap: '1px', padding: '2px',
- background: P.hairline, borderRadius: '5px',
- });
- const segBtns = [];
- opts.forEach(o => {
- const active = o.value === p.default;
- const b = el('button', {
- padding: '5px 4px', border: 'none', borderRadius: '3px',
- background: active ? C.brand : 'transparent',
- color: active ? 'oklch(98% 0 0)' : P.text,
- fontFamily: FONT, fontSize: '10.5px', fontWeight: '500',
- cursor: 'pointer', whiteSpace: 'nowrap',
- transition: 'background 0.1s ease, color 0.1s ease',
- });
- b.textContent = o.label;
- b.addEventListener('click', (e) => {
- e.stopPropagation();
- paramsCurrentValues[p.id] = o.value;
- readout.textContent = o.label;
- segBtns.forEach(({ btn, val }) => {
- const on = val === o.value;
- btn.style.background = on ? C.brand : 'transparent';
- btn.style.color = on ? 'oklch(98% 0 0)' : P.text;
- });
- applyParamValue(variantEl, p, o.value);
- queueCheckpoint('param_changed');
- });
- segRow.appendChild(b);
- segBtns.push({ btn: b, val: o.value });
- });
- row.appendChild(segRow);
- }
-
- paramsPanelBody.appendChild(row);
- }
- }
-
- // Decide which way the popover opens: away from the picked element. If the
- // bar landed below the element, popover slides DOWN from the bar's bottom.
- // If the bar landed above, popover slides UP from the bar's top.
- function popoverDirection() {
- if (!barEl || !selectedElement) return 'below';
- const br = barEl.getBoundingClientRect();
- const er = selectedElement.getBoundingClientRect();
- return br.top >= er.bottom - 4 ? 'below' : 'above';
- }
-
- // The popover overlaps the bar by OVERLAP px on the bar-facing side. With
- // popover z-index below bar, that overlap sits behind bar (invisible) and
- // reinforces the "tucked behind" feel. Padding compensates so the real
- // content starts flush with bar's outer edge.
- const TUNE_OVERLAP = 6;
-
- // Closed clip-path depends on direction: for 'below' clip from the far
- // (bottom) edge so the reveal grows downward from the bar; for 'above'
- // clip from the top edge so the reveal grows upward from the bar.
- function closedClipPath(direction) {
- return direction === 'below' ? 'inset(0 0 100% 0)' : 'inset(100% 0 0 0)';
- }
-
- function setClipPath(value, withTransition) {
- const saved = paramsPanelEl.style.transition;
- if (!withTransition) paramsPanelEl.style.transition = 'none';
- paramsPanelEl.style.clipPath = value;
- if (!withTransition) {
- void paramsPanelEl.offsetHeight;
- paramsPanelEl.style.transition = saved;
- }
- }
-
- function positionParamsPanel() {
- if (!paramsPanelEl || !barEl || barEl.style.display === 'none') return;
- const br = barEl.getBoundingClientRect();
- const direction = popoverDirection();
- const prevDirection = paramsPanelEl.dataset.tuneDirection;
-
- // top/left/width are NOT in the transition list, so they snap instantly.
- paramsPanelEl.style.left = br.left + 'px';
- paramsPanelEl.style.width = br.width + 'px';
-
- if (direction === 'below') {
- paramsPanelEl.style.top = (br.bottom - TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '0 0 10px 10px';
- paramsPanelEl.style.paddingTop = (14 + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.paddingBottom = '14px';
- } else {
- const ih = paramsPanelEl.offsetHeight || 80;
- paramsPanelEl.style.top = (br.top - ih + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '10px 10px 0 0';
- paramsPanelEl.style.paddingTop = '14px';
- paramsPanelEl.style.paddingBottom = (14 + TUNE_OVERLAP) + 'px';
- }
- paramsPanelEl.dataset.tuneDirection = direction;
-
- // If currently closed and direction flipped (or first-time setup),
- // snap the clip-path to the new direction's closed pose without
- // transitioning (so the clip doesn't slide across the element).
- if (!tuneOpen && (!prevDirection || prevDirection !== direction)) {
- setClipPath(closedClipPath(direction), false);
- }
- }
-
- function showParamsPanel() {
- if (!paramsPanelEl) return;
- positionParamsPanel();
- paramsPanelEl.style.pointerEvents = 'auto';
- // rAF so the positioning paint commits before the transition fires.
- requestAnimationFrame(() => {
- setClipPath('inset(0 0 0 0)', true);
- });
- }
-
- function hideParamsPanel() {
- if (!paramsPanelEl) return;
- paramsPanelEl.style.pointerEvents = 'none';
- const direction = paramsPanelEl.dataset.tuneDirection || 'below';
- setClipPath(closedClipPath(direction), true);
- }
-
- // Build/rebuild the panel's contents for the current variant AND apply
- // its defaults to the variant wrapper (so scoped CSS responds even before
- // the user opens the popover). Visibility is governed by tuneOpen.
- function refreshParamsPanel() {
- if (state !== 'CYCLING') {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- if (tuneOpen) {
- // If already visible (variant cycled while open), refresh in place
- // instead of re-running the clip-path animation.
- const alreadyVisible = paramsPanelEl.style.display === 'block'
- && paramsPanelEl.style.opacity === '1';
- if (alreadyVisible) positionParamsPanel();
- else showParamsPanel();
- } else {
- hideParamsPanel();
- }
- }
-
- function toggleTunePopover() {
- if (tuneOpen) { closeTunePopover(); return; }
- openTunePopover();
- }
-
- function openTunePopover() {
- if (state !== 'CYCLING') return;
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) return;
- // Build fresh to ensure the current variant's controls are shown.
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- tuneOpen = true;
- showParamsPanel();
- // Kill the bar's shadow on the popover-facing side so the dark popover
- // doesn't pick up a bright glow line.
- if (barEl) {
- const direction = paramsPanelEl?.dataset.tuneDirection || 'below';
- barEl.style.boxShadow = direction === 'below' ? BAR_SHADOW_UP : BAR_SHADOW_DOWN;
- }
- // Re-render the bar so the Tune chip picks up the active styling.
- updateBarContent('cycling');
- }
-
- function closeTunePopover() {
- tuneOpen = false;
- hideParamsPanel();
- if (barEl) barEl.style.boxShadow = BAR_SHADOW_DEFAULT;
- if (barEl && barEl.style.display !== 'none' && state === 'CYCLING') {
- updateBarContent('cycling');
- }
- }
-
- // ---------------------------------------------------------------------------
- // Variant cycling in DOM
- // ---------------------------------------------------------------------------
-
- function showVariantInDOM(sessionId, num) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
- for (const child of wrapper.children) {
- const v = child.dataset ? child.dataset.impeccableVariant : null;
- if (!v) continue;
- child.style.display = (v === String(num)) ? '' : 'none';
- }
- // Unconditional refresh — covers first-reveal (no-op if state isn't
- // CYCLING yet, the subsequent CYCLING transition triggers its own
- // refresh) and every cycle step.
- refreshParamsPanel();
- }
-
- /**
- * No-HMR fallback: fetch the raw source file from the live server,
- * parse it, extract the variant wrapper, and inject it into the live DOM.
- * This works even when the dev server caches HTML (Bun, static servers).
- */
- function injectVariantsFromSource(filePath, sessionId) {
- const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
- fetch(url)
- .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
- .then(html => {
- // Parse the raw source HTML
- const parser = new DOMParser();
- const doc = parser.parseFromString(html, 'text/html');
- const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!srcWrapper) {
- console.error('[impeccable] Variant wrapper not found in source file.');
- return;
- }
-
- // Find the original element in the live DOM.
- // The original is inside the wrapper in the source. We find the
- // corresponding element in the live DOM by matching the first child's
- // tag + classes from the original snapshot.
- const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
- if (!origContent) return;
-
- const tag = origContent.tagName.toLowerCase();
- const cls = origContent.className;
- let liveEl = null;
- if (origContent.id) {
- liveEl = document.getElementById(origContent.id);
- } else if (cls) {
- // Find by tag + exact class match
- const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
- for (const c of candidates) {
- if (c.className === cls && !own(c)) { liveEl = c; break; }
- }
- }
-
- if (!liveEl) {
- console.error('[impeccable] Could not find original element in live DOM.');
- return;
- }
-
- const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;
-
- // Replace the live element with the full wrapper from source
- const wrapper = srcWrapper.cloneNode(true);
- liveEl.parentElement.replaceChild(wrapper, liveEl);
-
- // Update state: count variants, preserving the user's current variant
- // when a late HMR/source reinjection lands after they have cycled.
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants
- ? previousVisibleVariant
- : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);
- showVariantInDOM(sessionId, visibleVariant);
-
- // Update selectedElement to the visible variant's content
- selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;
-
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- saveSession();
- console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
- })
- .catch(err => {
- console.error('[impeccable] Failed to fetch source:', err);
- showToast('Could not load variants. Try refreshing the page.', 5000);
- });
- }
-
- function cycleVariant(dir) {
- const next = visibleVariant + dir;
- if (next < 1 || next > arrivedVariants) return;
- visibleVariant = next;
- showVariantInDOM(currentSessionId, next); // calls refreshParamsPanel itself
- updateSelectedElement();
- updateBarContent('cycling');
- saveSession();
- queueCheckpoint('variant_changed');
- }
-
- function updateSelectedElement() {
- if (!currentSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return;
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- function readVisibleVariantFromDOM(sessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return 0;
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- for (const variant of variants) {
- if (variant.style.display === 'none') continue;
- const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);
- if (idx > 0) return idx;
- }
- return 0;
- }
-
- // Resolve the element that represents the variant's visible content.
- // Contract: each variant div should contain exactly one top-level element
- // (the full replacement). In practice a model may ship loose siblings or
- // lead with <style>/<script>. Be defensive: skip non-visual elements, and
- // if the variant has multiple element children, use the variant div itself
- // (it wraps all of them and gets correct bounds).
- function pickVariantContent(wrapper, index) {
- if (!wrapper) return null;
- const variantDiv = wrapper.querySelector('[data-impeccable-variant="' + index + '"]');
- if (!variantDiv) return null;
- const NON_VISUAL = new Set(['STYLE', 'SCRIPT', 'LINK', 'META', 'TEMPLATE']);
- const visual = [];
- for (const child of variantDiv.children) {
- if (!NON_VISUAL.has(child.tagName)) visual.push(child);
- }
- if (visual.length === 1) return visual[0];
- return variantDiv;
- }
-
- // Hold window.scrollY at a fixed value across DOM mutations inside the
- // session's wrapper (HMR patches, variant inserts, cycle swaps).
- function startScrollLock(sessionId, initialTargetY) {
- stopScrollLock();
- scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)
- ? initialTargetY
- : window.scrollY;
- console.log('[impeccable.scroll] startScrollLock', { sessionId, scrollY: window.scrollY, targetY: scrollLockTargetY, initialOverride: initialTargetY });
-
- try { history.scrollRestoration = 'manual'; } catch {}
-
- const prevHtmlAnchor = document.documentElement.style.overflowAnchor;
- const prevBodyAnchor = document.body.style.overflowAnchor;
- document.documentElement.style.overflowAnchor = 'none';
- document.body.style.overflowAnchor = 'none';
-
- const correct = (why) => {
- scrollLockRaf = null;
- if (scrollLockTargetY == null) return;
- const before = window.scrollY;
- const delta = before - scrollLockTargetY;
- if (Math.abs(delta) < 0.5) {
- console.log('[impeccable.scroll] correct noop', { why, scrollY: before, targetY: scrollLockTargetY });
- return;
- }
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] corrected', { why, from: before, to: scrollLockTargetY, delta, nowAt: window.scrollY });
- };
- const schedule = (why) => {
- if (scrollLockRaf != null) return;
- scrollLockRaf = requestAnimationFrame(() => correct(why));
- };
-
- scrollLockObserver = new MutationObserver((mutations) => {
- for (const m of mutations) {
- if (m.target?.closest?.('[data-impeccable-variants="' + sessionId + '"]')) {
- const childAdds = Array.from(m.addedNodes).map(n => n.nodeType === 1 ? (n.tagName + (n.dataset?.impeccableVariant ? ('[variant=' + n.dataset.impeccableVariant + ']') : '')) : n.nodeType).join(',');
- console.log('[impeccable.scroll] mutation inside wrapper', { type: m.type, target: m.target?.tagName, adds: childAdds, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('mutation-in-wrapper');
- return;
- }
- for (const n of m.addedNodes) {
- if (n.nodeType === 1 && (n.matches?.('[data-impeccable-variants="' + sessionId + '"]') || n.querySelector?.('[data-impeccable-variants="' + sessionId + '"]'))) {
- console.log('[impeccable.scroll] wrapper node added', { tag: n.tagName, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('wrapper-added');
- return;
- }
- }
- }
- });
- scrollLockObserver.observe(document.body, { childList: true, subtree: true });
-
- scrollLockAbort = new AbortController();
- scrollLockAbort.signal.addEventListener('abort', () => {
- document.documentElement.style.overflowAnchor = prevHtmlAnchor;
- document.body.style.overflowAnchor = prevBodyAnchor;
- }, { once: true });
- const sig = { signal: scrollLockAbort.signal };
- // Track whether the most recent scroll came from a user gesture. We
- // gate user-scroll re-anchoring on this flag so programmatic smooth
- // scrolls (browser reload-restore, scrollIntoView from other scripts)
- // don't accidentally update our target.
- let userGestureAt = 0;
- const USER_GESTURE_WINDOW_MS = 250;
-
- const reanchor = (why) => {
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- const prevTarget = scrollLockTargetY;
- scrollLockTargetY = window.scrollY;
- writeScrollY(scrollLockTargetY);
- console.log('[impeccable.scroll] reanchor', { why, prevTarget, newTarget: scrollLockTargetY });
- };
- const markGesture = (why) => {
- userGestureAt = performance.now();
- reanchor(why);
- };
- window.addEventListener('wheel', () => markGesture('wheel'), { passive: true, ...sig });
- window.addEventListener('touchstart', () => markGesture('touchstart'), { passive: true, ...sig });
- window.addEventListener('touchmove', () => markGesture('touchmove'), { passive: true, ...sig });
- window.addEventListener('keydown', (e) => {
- if (['PageDown', 'PageUp', ' ', 'End', 'Home', 'ArrowDown', 'ArrowUp'].includes(e.key)) markGesture('key:' + e.key);
- }, sig);
-
- // Correct on EVERY scroll event: whether it's the browser's
- // post-reload animated restore or some other script calling
- // scrollIntoView, we want to snap back immediately. Only skip if a
- // user gesture fired in the last 250ms.
- let lastLoggedScrollY = window.scrollY;
- window.addEventListener('scroll', () => {
- const now = window.scrollY;
- if (Math.abs(now - lastLoggedScrollY) > 5) {
- console.log('[impeccable.scroll] scroll event', { from: lastLoggedScrollY, to: now, targetY: scrollLockTargetY });
- lastLoggedScrollY = now;
- }
- if (scrollLockTargetY == null) return;
- if (performance.now() - userGestureAt < USER_GESTURE_WINDOW_MS) return;
- if (Math.abs(now - scrollLockTargetY) < 0.5) return;
- console.log('[impeccable.scroll] scroll-event snap', { from: now, to: scrollLockTargetY });
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- }, { passive: true, ...sig });
-
- // Apply target synchronously, not via rAF — racing the browser's
- // restore or a smooth-scroll animation means we want to win now.
- if (Math.abs(window.scrollY - scrollLockTargetY) > 0.5) {
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] startScrollLock initial apply', { to: scrollLockTargetY });
- }
- }
-
- function stopScrollLock() {
- if (scrollLockObserver) { scrollLockObserver.disconnect(); scrollLockObserver = null; }
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }
- scrollLockTargetY = null;
- // NOTE: do NOT clear the persistent scroll key here. startScrollLock
- // calls us as a reset, and clearing the key would nuke the Go-time
- // scrollY that the next resume needs to read.
- }
-
- // ---------------------------------------------------------------------------
- // MutationObserver for progressive variant reveal
- // ---------------------------------------------------------------------------
-
- function startVariantObserver(sessionId) {
- let updating = false; // re-entrancy guard
-
- const obs = new MutationObserver((mutations) => {
- if (updating) return;
-
- // Only react to mutations that add nodes with data-impeccable-variant,
- // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
- let dominated = false;
- for (const m of mutations) {
- if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
- for (const n of m.addedNodes) {
- if (n.nodeType !== 1) continue;
- // Direct hit: the added node itself is the wrapper or a variant.
- if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
- dominated = true; break;
- }
- // Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
- // a whole subtree where the wrapper is a descendant of the added
- // node. Without this check, the observer ignores those mutations
- // and the session stays in GENERATING forever.
- if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
- dominated = true; break;
- }
- }
- if (dominated) break;
- }
- if (!dominated) return;
-
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
-
- // Re-anchor selectedElement if it was detached by live-wrap's HMR swap.
- // Without this, the shader / highlight / bar track a zero-rect phantom
- // and the overlay appears frozen.
- if (selectedElement && !document.body.contains(selectedElement)) {
- selectedElement = pickVariantContent(wrapper, 'original') || wrapper;
- }
-
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- const count = variants.length;
-
- // Nothing new
- if (count <= arrivedVariants) return;
-
- updating = true;
- arrivedVariants = count;
- if (visibleVariant === 0 && arrivedVariants > 0) {
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;
- showVariantInDOM(sessionId, visibleVariant);
- // showVariantInDOM hid the original (display:none); if we were still
- // anchored to the original's content, its boundingRect is now zero
- // and the bar snaps to (0,0). Re-point at the visible variant instead.
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- if (expected > 0) expectedVariants = expected;
-
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- } else if (state === 'GENERATING') {
- updateBarContent('generating');
- }
- saveSession();
- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');
- updating = false;
- });
-
- obs.observe(document.body, { childList: true, subtree: true });
- return obs;
- }
-
- // ---------------------------------------------------------------------------
- // Bar scroll tracking
- // ---------------------------------------------------------------------------
-
- function startScrollTracking() {
- function tick() {
- if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
- positionBar();
- showHighlight(selectedElement);
- if (tuneOpen) positionParamsPanel();
- }
- if (annotActive) positionAnnotOverlay(selectedElement);
- // Shader overlay (via debug P toggle or generation) is repositioned
- // by its own branch below; debug no longer has a separate overlay.
- if (shaderState) positionShaderOverlay();
- scrollRaf = requestAnimationFrame(tick);
- }
- scrollRaf = requestAnimationFrame(tick);
- }
-
- function stopScrollTracking() {
- if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
- }
-
- // ---------------------------------------------------------------------------
- // SSE (server→browser) + fetch POST (browser→server)
- // Zero-dependency replacement for WebSocket.
- // ---------------------------------------------------------------------------
-
- let evtSource = null;
- let sseRetries = 0;
- const SSE_MAX_RETRIES = 20; // generous: heartbeats keep the connection alive, so retries mean real trouble
-
- function connectSSE() {
- evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
-
- evtSource.onopen = () => {
- sseRetries = 0; // reset on successful (re)connect
- };
-
- evtSource.onmessage = (e) => {
- sseRetries = 0; // reset on any successful message
- let msg; try { msg = JSON.parse(e.data); } catch { return; }
- switch (msg.type) {
- case 'connected':
- hasProjectContext = !!msg.hasProjectContext;
- if (!hasProjectContext) showToast('No PRODUCT.md found. Variants will be brand-agnostic. Run /impeccable teach to generate one.', 7000);
- console.log('[impeccable] Live mode connected.');
- if (state === 'IDLE') state = 'PICKING';
- break;
- case 'done':
- // Variants already arrived via HMR → normal transition.
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- if (state === 'GENERATING') {
- state = 'CYCLING';
- updateBarContent('cycling');
- refreshParamsPanel();
- }
- break;
- }
- // Variants are in source but not in the DOM yet. Common when the
- // picked element lived inside conditional render (closed modal,
- // hidden tab, a route the user navigated away from). The variant
- // MutationObserver stays armed and auto-transitions to CYCLING
- // the moment the wrapper actually mounts. Nudge the user toward
- // that path with a toast — better than the prior force-reload
- // which reset framework state and left the session stuck.
- setTimeout(() => {
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
- if (state !== 'GENERATING') return;
- showToast(
- "Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
- 15000,
- );
- }, 2000);
- break;
- case 'error':
- console.error('[impeccable] Error:', msg.message);
- showToast('Error: ' + msg.message, 5000);
- hideBar();
- state = 'PICKING';
- break;
- }
- };
-
- evtSource.onerror = () => {
- sseRetries++;
- if (sseRetries <= SSE_MAX_RETRIES) {
- console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
- return; // EventSource auto-reconnects
- }
- // Server is gone. Clean up gracefully.
- console.log('[impeccable] Live server unreachable. Cleaning up UI.');
- evtSource.close();
- evtSource = null;
- handleServerLost();
- };
- }
-
- /** Server died or became unreachable. Reset UI to a clean state. */
- function handleServerLost() {
- const recoveryState = currentSessionId ? state : 'IDLE';
- if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
- showToast('Live server disconnected. Session ended.', 5000);
- }
- hideBar();
- hideHighlight();
- hideShaderOverlay();
- hideAnnotOverlay();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- // Preserve local session state on server loss. The durable journal is the
- // source of truth, but localStorage plus the variant wrapper lets the UI
- // resume after a helper restart or page reload instead of treating a
- // transient disconnect as an explicit discard.
- selectedElement = null;
- selectedAction = 'impeccable';
- state = recoveryState;
- if (currentSessionId) saveSession();
- }
-
- function sendEvent(msg, opts) {
- msg.token = TOKEN;
- function handleFailure(err) {
- console.error('[impeccable] Failed to send event:', err);
- if (opts && opts.throwOnError) throw err;
- return null;
- }
- return fetch('http://localhost:' + PORT + '/events', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(msg),
- }).then(res => {
- if (res.ok) return res;
- return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));
- }).catch(handleFailure);
- }
-
- function checkpointPayload(reason) {
- return {
- type: 'checkpoint',
- id: currentSessionId,
- revision: sessionState.nextCheckpointRevision(),
- owner: browserOwner,
- phase: String(state || '').toLowerCase(),
- reason,
- pageUrl: location.pathname,
- expectedVariants,
- arrivedVariants,
- visibleVariant,
- paramValues: { ...paramsCurrentValues },
- };
- }
-
- function sendCheckpoint(reason) {
- if (!currentSessionId) return Promise.resolve(null);
- return sendEvent(checkpointPayload(reason)).catch(() => null);
- }
-
- function queueCheckpoint(reason) {
- if (!currentSessionId) return;
- if (checkpointTimer) clearTimeout(checkpointTimer);
- checkpointTimer = setTimeout(() => {
- checkpointTimer = null;
- sendCheckpoint(reason);
- }, 120);
- }
-
- // ---------------------------------------------------------------------------
- // Event handlers
- // ---------------------------------------------------------------------------
-
- function handleMouseMove(e) {
- if (state !== 'PICKING' || !pickActive) return;
- const target = document.elementFromPoint(e.clientX, e.clientY);
- if (!target || !pickable(target) || target === hoveredElement) return;
- hoveredElement = target;
- showHighlight(target);
- }
-
- function handleClick(e) {
- // Close action picker on any outside click
- if (pickerEl?.style.display !== 'none' && !own(e.target)) {
- hideActionPicker();
- }
- // Close Tune popover on outside click (anything outside panel + bar)
- if (tuneOpen && paramsPanelEl && !paramsPanelEl.contains(e.target) && barEl && !barEl.contains(e.target)) {
- closeTunePopover();
- }
- // In CONFIGURING: click outside the bar and selected element returns to PICKING
- if (state === 'CONFIGURING' && !own(e.target) && selectedElement && !selectedElement.contains(e.target)) {
- hideBar();
- stopScrollTracking();
- hideAnnotOverlay();
- clearAnnotations();
- state = 'PICKING';
- hoveredElement = null;
- hideHighlight();
- return;
- }
- if (state !== 'PICKING' || !pickActive) return;
- if (own(e.target)) return;
- if (!hoveredElement || !pickable(hoveredElement)) return;
- e.preventDefault();
- e.stopPropagation();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- maybePrefetchPage();
- maybeWarnConditionalAncestor(selectedElement);
- }
-
- /**
- * Surface a brief, non-blocking heads-up when the picked element lives
- * inside a container whose visibility is gated by ephemeral state — modals,
- * collapsible panels, popovers, off-screen tab panels. If HMR remounts the
- * parent during generation (Vite Fast Refresh, SvelteKit page reload), the
- * variants land in source but stay invisible until the user re-opens the
- * container. Telling the user upfront is much friendlier than the silent
- * timeout-then-toast that they'd otherwise hit.
- *
- * Heuristic, intentionally narrow — only fires for unambiguous cases so
- * we don't cry wolf on every nested element.
- */
- function maybeWarnConditionalAncestor(el) {
- let node = el?.parentElement;
- let depth = 0;
- while (node && depth < 12) {
- // 1. Active dialog / modal
- if (node.getAttribute && node.getAttribute('role') === 'dialog'
- && node.getAttribute('aria-modal') === 'true') {
- showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 2. Common Radix / shadcn / headless-ui open-state attribute
- if (node.dataset && node.dataset.state === 'open') {
- showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 3. Tab panel — only meaningful when the page also shows ANOTHER
- // tab as selected. A single tabpanel with no tablist is just a static
- // section in disguise and isn't conditional.
- if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
- const list = document.querySelector('[role="tablist"]');
- if (list) {
- const tabs = list.querySelectorAll('[role="tab"]');
- if (tabs.length > 1) {
- showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
- return;
- }
- }
- }
- // 4. Collapsible: aria-expanded sibling. Look for the trigger button.
- if (node.id) {
- const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
- if (trigger) {
- showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
- return;
- }
- }
- node = node.parentElement;
- depth++;
- }
- }
-
- // Fire a lightweight prefetch event the first time the user selects an
- // element on a given route. The agent uses this to Read the underlying file
- // into context before Go is hit, shaving the read off the critical path.
- // Dedupe per session by pathname — clicking around on the same page doesn't
- // re-fire.
- //
- // DISABLED: quick-Go workflows pay an extra harness round trip because
- // prefetch + generate arrive as two events instead of one. Re-enable with
- // a browser-side debounce (~800–1000ms, cancelled on Go) if we want to
- // resurrect this. Server validator and skill dispatch remain in place so
- // flipping this flag is the only change needed.
- const PREFETCH_ENABLED = false;
- const prefetchedPaths = new Set();
- function maybePrefetchPage() {
- if (!PREFETCH_ENABLED) return;
- const path = location.pathname;
- if (prefetchedPaths.has(path)) return;
- prefetchedPaths.add(path);
- sendEvent({ type: 'prefetch', pageUrl: path });
- }
-
- function handleKeyDown(e) {
- // When the annotation input is focused, let it handle its own keys.
- if (annotEditing && annotEditing.input && e.target === annotEditing.input) return;
- if (e.key === 'Escape') {
- e.preventDefault();
- if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
- if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); hideAnnotOverlay(); clearAnnotations(); state = 'PICKING'; return; }
- if (state === 'CYCLING') { handleDiscard(); return; }
- if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
- if (state === 'PICKING') {
- // Use togglePick so the "Pick" button in the global bar also flips
- // off, otherwise the bar stays lit while nothing else is active.
- if (pickActive) togglePick();
- else { hideHighlight(); state = 'IDLE'; }
- return;
- }
- }
-
- // Arrow/Enter nav works in PICKING (hover) and CONFIGURING (selected, input empty)
- var navEl = (state === 'PICKING') ? hoveredElement : (state === 'CONFIGURING') ? selectedElement : null;
- if (navEl && (e.key === 'ArrowUp' || e.key === 'ArrowDown' || (e.key === 'Enter' && state === 'PICKING'))) {
- let next = null;
- if (e.key === 'ArrowDown' && !e.shiftKey) {
- next = navEl.nextElementSibling;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'ArrowUp' && !e.shiftKey) {
- next = navEl.previousElementSibling;
- while (next && !pickable(next)) next = next.previousElementSibling;
- } else if (e.key === 'ArrowUp' && e.shiftKey) {
- next = navEl.parentElement;
- if (next && !pickable(next)) next = null;
- } else if (e.key === 'ArrowDown' && e.shiftKey) {
- next = navEl.firstElementChild;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'Enter') {
- e.preventDefault();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- return;
- }
- if (next) {
- e.preventDefault();
- if (state === 'PICKING') {
- hoveredElement = next;
- } else {
- // CONFIGURING: re-select the new element and refresh the bar
- selectedElement = next;
- clearAnnotations();
- showAnnotOverlay(next);
- showBar('configure');
- startScrollTracking();
- }
- showHighlight(next);
- next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
- }
- return;
- }
-
- if (state === 'CYCLING') {
- if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
- if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
- if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
- }
- }
-
- function handleGo() {
- if (!selectedElement || state !== 'CONFIGURING') return;
- const input = document.getElementById(PREFIX + '-input');
- const prompt = input ? input.value.trim() : '';
-
- // Commit any pending pin edit BEFORE we snapshot annotations.
- if (annotEditing) finalizeEditingPin();
-
- currentSessionId = id8();
- expectedVariants = selectedCount;
- arrivedVariants = 0;
- visibleVariant = 0;
-
- // Flip to GENERATING immediately so the bar morphs without waiting on
- // capture + upload. The event is emitted from captureAndEmit() once the
- // screenshot is uploaded (or capture fails — we still emit, just without
- // screenshotPath).
- const elForCapture = selectedElement;
- const captureRect = elForCapture.getBoundingClientRect();
- const snapshot = {
- comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),
- strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),
- };
- const basePayload = {
- type: 'generate', id: currentSessionId,
- action: selectedAction,
- freeformPrompt: prompt || undefined,
- count: selectedCount,
- pageUrl: location.pathname,
- element: extractContext(elForCapture),
- };
- if (snapshot.comments.length > 0) basePayload.comments = snapshot.comments;
- if (snapshot.strokes.length > 0) basePayload.strokes = snapshot.strokes;
-
- // Hide the interactive overlay so it doesn't linger during generation.
- hideAnnotOverlay();
- clearAnnotations();
-
- state = 'GENERATING';
- showBar('generating');
- saveSession();
- sendCheckpoint('generate_started');
- writeScrollY(window.scrollY);
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
- console.log('[impeccable.scroll] Go pressed', { scrollY: window.scrollY, sessionId: currentSessionId });
- startScrollLock(currentSessionId);
-
- captureAndEmit(elForCapture, basePayload, snapshot, captureRect);
- }
-
- // ---------------------------------------------------------------------------
- // Screenshot capture + upload
- // ---------------------------------------------------------------------------
-
- let msLoadPromise = null;
- function loadModernScreenshot() {
- if (window.modernScreenshot) return Promise.resolve(window.modernScreenshot);
- if (msLoadPromise) return msLoadPromise;
- msLoadPromise = new Promise((resolve, reject) => {
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/modern-screenshot.js';
- s.onload = () => resolve(window.modernScreenshot);
- s.onerror = () => { msLoadPromise = null; reject(new Error('modern-screenshot failed to load')); };
- document.head.appendChild(s);
- });
- return msLoadPromise;
- }
-
- // Collect @font-face rules from every stylesheet on the page. Cross-origin
- // sheets (Google Fonts, Typekit, etc.) throw SecurityError on .cssRules
- // access, so modern-screenshot can't embed them on its own — the resulting
- // SVG falls back to system fonts and text re-wraps + renders with different
- // weight. We fetch the raw CSS text (CORS-permitted for these providers),
- // extract @font-face blocks, inline the referenced font files as base64
- // data URIs (SVGs rasterized via canvas can't fetch external resources,
- // so URLs inside the SVG silently fail without this), and pass the result
- // to modern-screenshot as font.cssText.
- const FONT_EXT_RE = /\.(woff2?|ttf|otf|eot)(\?.*)?$/i;
- const FONT_MIME = {
- woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', eot: 'application/vnd.ms-fontobject',
- };
- function bufferToBase64(buf) {
- const bytes = new Uint8Array(buf);
- let binary = '';
- const CHUNK = 0x8000;
- for (let i = 0; i < bytes.length; i += CHUNK) {
- binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
- }
- return btoa(binary);
- }
- async function inlineFontUrls(cssText) {
- const urlRe = /url\((['"]?)(https?:\/\/[^'")\s]+)\1\)/g;
- const urls = new Set();
- let m;
- while ((m = urlRe.exec(cssText))) {
- if (FONT_EXT_RE.test(m[2])) urls.add(m[2]);
- }
- const map = new Map();
- await Promise.all([...urls].map(async (url) => {
- try {
- const res = await fetch(url);
- if (!res.ok) return;
- const buf = await res.arrayBuffer();
- const ext = url.toLowerCase().match(FONT_EXT_RE)?.[1] || 'woff2';
- const mime = FONT_MIME[ext] || 'application/octet-stream';
- map.set(url, 'data:' + mime + ';base64,' + bufferToBase64(buf));
- } catch { /* skip; fall through to URL */ }
- }));
- return cssText.replace(urlRe, (orig, q, url) => {
- const data = map.get(url);
- return data ? 'url(' + q + data + q + ')' : orig;
- });
- }
- async function collectFontCssText() {
- const chunks = [];
- const fontFaceRe = /@font-face\s*\{[^}]*\}/g;
- for (const sheet of document.styleSheets) {
- try {
- const rules = sheet.cssRules;
- for (const rule of rules) {
- if (rule.constructor.name === 'CSSFontFaceRule' || rule.cssText?.startsWith('@font-face')) {
- chunks.push(rule.cssText);
- }
- }
- } catch {
- if (!sheet.href) continue;
- try {
- const res = await fetch(sheet.href);
- if (!res.ok) continue;
- const text = await res.text();
- let m2;
- while ((m2 = fontFaceRe.exec(text))) chunks.push(m2[0]);
- } catch { /* ignore; capture is best-effort */ }
- }
- }
- if (chunks.length === 0) return '';
- return inlineFontUrls(chunks.join('\n'));
- }
-
- // True if `s` is a computed color string that renders as nothing
- // (explicit `transparent`, or `rgba(...)` with alpha 0).
- function isTransparentColor(s) {
- if (!s) return true;
- if (s === 'transparent') return true;
- const m = /rgba?\(([^)]+)\)/.exec(s);
- if (!m) return false;
- const parts = m[1].split(',').map((p) => p.trim());
- if (parts.length === 4) return parseFloat(parts[3]) === 0;
- return false;
- }
-
- // modern-screenshot force-sets `background-color: X !important` on the
- // cloned root whenever `backgroundColor` is passed, clobbering the
- // element's own background. So we only pass it when the element is
- // genuinely transparent (no own color, no own image) — in that case
- // we resolve up the DOM to the nearest opaque ancestor so the capture
- // sits on the page's real background instead of rendering black.
- function resolveCanvasBackground(el) {
- const own = getComputedStyle(el);
- if (!isTransparentColor(own.backgroundColor)) return null;
- if (own.backgroundImage && own.backgroundImage !== 'none') return null;
- let node = el.parentElement;
- while (node) {
- const cs = getComputedStyle(node);
- if (!isTransparentColor(cs.backgroundColor)) return cs.backgroundColor;
- node = node.parentElement;
- }
- // The walk already passed through <body> and <html>; if they had been
- // opaque we would have returned. Falling through with the previous
- // `getComputedStyle(body).backgroundColor || …` chain is a trap: that
- // call returns the literal string `"rgba(0, 0, 0, 0)"` for a page that
- // never set its own bg, which is truthy and short-circuits the chain to
- // transparent-black — modern-screenshot then renders the capture on a
- // black canvas and the shader overlay flashes solid black during load.
- // The browser canvas defaults to white, so we do too.
- return '#ffffff';
- }
-
- // Capture the element (with current annotations baked in) and return a PNG
- // Blob. Shared between the Go flow (uploads it to the server) and the
- // debug toggle (displays it as an overlay for side-by-side comparison).
- async function captureElementToBlob(el, snapshot, rect) {
- try { if (document.fonts?.ready) await document.fonts.ready; } catch {}
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- let annotNode = null;
- let savedPosition = null;
- if (hasAnnotations) {
- const pos = getComputedStyle(el).position;
- if (pos === 'static') {
- savedPosition = el.style.position;
- el.style.position = 'relative';
- }
- annotNode = buildAnnotationsForCapture(rect, snapshot);
- el.appendChild(annotNode);
- }
- try {
- const ms = await loadModernScreenshot();
- const fontCssText = await collectFontCssText();
- const backgroundColor = resolveCanvasBackground(el);
- return await ms.domToBlob(el, {
- scale: Math.min(window.devicePixelRatio || 1, 2),
- font: fontCssText ? { cssText: fontCssText } : undefined,
- ...(backgroundColor ? { backgroundColor } : {}),
- });
- } finally {
- if (annotNode) annotNode.remove();
- if (savedPosition !== null) el.style.position = savedPosition;
- }
- }
-
- async function captureAndEmit(el, basePayload, snapshot, rect) {
- let screenshotPath;
- let blob;
- try {
- blob = await captureElementToBlob(el, snapshot, rect);
- } catch (err) {
- console.warn('[impeccable] capture failed, proceeding without screenshot:', err);
- }
- // Light up the shader overlay the moment capture is ready — no reason to
- // wait for the upload to complete before the user sees something alive.
- if (blob && state === 'GENERATING') {
- showShaderOverlay(el, blob, rect);
- }
- // Only upload + forward the screenshot when annotations (comments/strokes)
- // are present. Without annotations the image is pure visual anchoring —
- // it biases the model toward the current rendering and works against the
- // three-distinct-directions brief.
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- if (blob && hasAnnotations) {
- try {
- const uploadRes = await fetch(
- 'http://localhost:' + PORT + '/annotation?token=' + encodeURIComponent(TOKEN) +
- '&eventId=' + encodeURIComponent(basePayload.id),
- { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: blob },
- );
- if (uploadRes.ok) {
- const { path: p } = await uploadRes.json();
- screenshotPath = p;
- } else {
- console.warn('[impeccable] annotation upload failed:', uploadRes.status);
- }
- } catch (err) {
- console.warn('[impeccable] annotation upload failed:', err);
- }
- }
- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);
- }
-
- // ---------------------------------------------------------------------------
- // Shader overlay — renders the captured screenshot as a WebGL texture and
- // runs an editorial "ink-wash" fragment shader over it during generation.
- // A single rolling band sweeps top-to-bottom, desaturating + tinting magenta
- // and leaving a soft trail. Makes the wait feel like a letterpress scan
- // instead of a dead spinner.
- // ---------------------------------------------------------------------------
-
- const SHADER_VS = `attribute vec2 a_position;
-attribute vec2 a_uv;
-varying vec2 v_uv;
-void main() {
- v_uv = a_uv;
- gl_Position = vec4(a_position, 0.0, 1.0);
-}`;
-
- const SHADER_FS = `precision highp float;
-uniform sampler2D u_texture;
-uniform float u_time;
-uniform vec2 u_resolution;
-uniform vec3 u_accent;
-varying vec2 v_uv;
-
-// Asymmetric roller band. Product of two one-sided smoothsteps — peaks at
-// d=0 with a short sharp leading ramp and a longer soft trailing tail. Clean
-// outside the [-leadW, trailW] range (no rogue "trail=1 everywhere below"
-// failure that reversed-edge smoothstep would give).
-float bandAt(float d, float leadW, float trailW) {
- float above = smoothstep(-leadW, 0.0, d);
- float below = 1.0 - smoothstep(0.0, trailW, d);
- return above * below;
-}
-
-void main() {
- vec2 uv = v_uv;
- // Roller sweeps top-to-bottom with small overshoot so each cycle enters
- // and exits the element cleanly.
- float phase = fract(u_time / 3.4);
- float y = phase * 1.25 - 0.12;
- float band = bandAt(uv.y - y, 0.05, 0.32);
-
- // Halftone cell grid (fixed ~10 px pitch).
- float cellPx = 10.0;
- vec2 gridUv = uv * u_resolution / cellPx;
- vec2 cellId = floor(gridUv);
- vec2 cellUv = fract(gridUv) - 0.5;
- vec2 sampleCenter = (cellId + 0.5) * cellPx / u_resolution;
- vec3 cellImg = texture2D(u_texture, sampleCenter).rgb;
- float luma = dot(cellImg, vec3(0.299, 0.587, 0.114));
- // Darker cells → bigger magenta dots (classic risograph halftone curve).
- float radius = sqrt(clamp(1.0 - luma, 0.0, 1.0)) * 0.56;
- float dotMask = smoothstep(radius + 0.06, radius, length(cellUv));
- vec3 paper = vec3(0.975, 0.965, 0.955);
- vec3 dotLayer = mix(paper, u_accent, dotMask);
-
- // Blend the halftone layer in where the roller is passing; leave the
- // element pristine elsewhere.
- vec3 base = texture2D(u_texture, uv).rgb;
- gl_FragColor = vec4(mix(base, dotLayer, band), 1.0);
-}`;
-
- // Editorial Magenta converted to approximate sRGB 0-1 (matches oklch(60% 0.25 350))
- const SHADER_ACCENT = [0.82, 0.16, 0.47];
- let shaderState = null; // { canvas, gl, program, texture, rafId, startTime }
-
- function compileShader(gl, type, source) {
- const sh = gl.createShader(type);
- gl.shaderSource(sh, source);
- gl.compileShader(sh);
- if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
- const info = gl.getShaderInfoLog(sh);
- gl.deleteShader(sh);
- throw new Error('shader compile failed: ' + info);
- }
- return sh;
- }
-
- function positionShaderOverlay() {
- if (!shaderState || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- Object.assign(shaderState.canvas.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- }
-
- function hideShaderOverlay() {
- if (!shaderState) return;
- if (shaderState.rafId) cancelAnimationFrame(shaderState.rafId);
- if (shaderState.canvas) shaderState.canvas.remove();
- const lose = shaderState.gl?.getExtension?.('WEBGL_lose_context');
- try { lose?.loseContext(); } catch {}
- shaderState = null;
- }
-
- async function showShaderOverlay(el, blob, rect) {
- hideShaderOverlay();
- if (!blob || !el) return;
- const canvas = document.createElement('canvas');
- canvas.id = PREFIX + '-shader';
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
- canvas.width = Math.max(1, Math.floor(rect.width * dpr));
- canvas.height = Math.max(1, Math.floor(rect.height * dpr));
- Object.assign(canvas.style, {
- position: 'fixed',
- top: rect.top + 'px', left: rect.left + 'px',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none',
- zIndex: Z.bar - 1,
- });
- document.body.appendChild(canvas);
-
- const gl = canvas.getContext('webgl', { premultipliedAlpha: false, preserveDrawingBuffer: false })
- || canvas.getContext('experimental-webgl');
- if (!gl) {
- // WebGL unavailable — fall back to a plain <img> overlay so the user
- // still sees something meaningful during generation.
- canvas.remove();
- const img = document.createElement('img');
- img.src = URL.createObjectURL(blob);
- img.id = PREFIX + '-shader';
- // Copy positioning via cssText. Object.assign across CSSStyleDeclaration
- // throws in modern Chromium because the source's indexed properties
- // (style[0], [1], ...) are read-only and the engine forbids writing
- // them on the destination.
- img.style.cssText = canvas.style.cssText;
- img.style.outline = '2px dashed ' + C.brand;
- img.style.outlineOffset = '-2px';
- document.body.appendChild(img);
- shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
- return;
- }
-
- let program, texture;
- try {
- const vs = compileShader(gl, gl.VERTEX_SHADER, SHADER_VS);
- const fs = compileShader(gl, gl.FRAGMENT_SHADER, SHADER_FS);
- program = gl.createProgram();
- gl.attachShader(program, vs);
- gl.attachShader(program, fs);
- gl.linkProgram(program);
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- throw new Error('program link failed: ' + gl.getProgramInfoLog(program));
- }
- // Full-screen quad
- const buf = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
- -1, -1, 0, 1,
- 1, -1, 1, 1,
- -1, 1, 0, 0,
- -1, 1, 0, 0,
- 1, -1, 1, 1,
- 1, 1, 1, 0,
- ]), gl.STATIC_DRAW);
- const posLoc = gl.getAttribLocation(program, 'a_position');
- const uvLoc = gl.getAttribLocation(program, 'a_uv');
- gl.enableVertexAttribArray(posLoc);
- gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 16, 0);
- gl.enableVertexAttribArray(uvLoc);
- gl.vertexAttribPointer(uvLoc, 2, gl.FLOAT, false, 16, 8);
- } catch (err) {
- console.warn('[impeccable] shader setup failed:', err);
- canvas.remove();
- return;
- }
-
- // Upload the screenshot as a texture
- let bitmap;
- try {
- bitmap = await createImageBitmap(blob);
- } catch {
- // Safari fallback: go via a regular Image
- const imgUrl = URL.createObjectURL(blob);
- const img = new Image();
- img.src = imgUrl;
- await new Promise((r, rej) => { img.onload = r; img.onerror = rej; });
- bitmap = img;
- URL.revokeObjectURL(imgUrl);
- }
- texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
- if (bitmap.close) bitmap.close();
-
- const uTime = gl.getUniformLocation(program, 'u_time');
- const uRes = gl.getUniformLocation(program, 'u_resolution');
- const uAccent = gl.getUniformLocation(program, 'u_accent');
- const uTex = gl.getUniformLocation(program, 'u_texture');
- const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-
- shaderState = { canvas, gl, program, texture, rafId: 0, startTime: performance.now(), reduced };
- function frame() {
- if (!shaderState) return;
- const elapsed = (performance.now() - shaderState.startTime) / 1000;
- const t = shaderState.reduced ? 0.0 : elapsed;
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.useProgram(program);
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.uniform1i(uTex, 0);
- gl.uniform1f(uTime, t);
- gl.uniform2f(uRes, canvas.width, canvas.height);
- gl.uniform3f(uAccent, SHADER_ACCENT[0], SHADER_ACCENT[1], SHADER_ACCENT[2]);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- shaderState.rafId = requestAnimationFrame(frame);
- }
- frame();
- }
-
- function handleAccept() {
- if (!currentSessionId || arrivedVariants === 0) return;
- const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);
- if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;
- const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };
- if (Object.keys(paramsCurrentValues).length > 0) {
- acceptPayload.paramValues = { ...paramsCurrentValues };
- }
- // The accepted variant is already the only visible child of the wrapper
- // (all other variants are display:none). HMR from the source rewrite will
- // replace the wrapper imminently. Don't eagerly replaceChild here — React
- // reconciliation races with our mutation and throws NotFoundError in Next
- // 16 / Turbopack. Schedule a fallback that runs the manual swap only if
- // HMR hasn't cleaned up by then (keeps static-server flows working).
- const acceptedSessionId = currentSessionId;
- const acceptedVariant = visibleVariant;
-
- state = 'SAVING';
- updateBarContent('saving');
-
- sendEvent(acceptPayload, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- confirmAcceptAfterReceipt();
- })
- .catch(() => {
- state = 'CYCLING';
- updateBarContent('cycling');
- showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);
- });
-
- function confirmAcceptAfterReceipt() {
- state = 'CONFIRMED';
- updateBarContent('confirmed');
- scheduleAcceptCleanup();
- }
-
- function scheduleAcceptCleanup() {
- setTimeout(function() {
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }, 1800);
-
- // Static-server / no-HMR fallback: if the wrapper is still around 2s after
- // the cleanup above, swap it out manually. By now React has either moved
- // on or the app isn't React at all. Preserve the `data-impeccable-variant="N"`
- // div (with display:contents) so @scope rules anchored to the variant
- // attribute keep matching until reload replaces it with the carbonize block.
- setTimeout(function() {
- const wrapper = document.querySelector('[data-impeccable-variants="' + acceptedSessionId + '"]');
- if (!wrapper) return;
- const accepted = wrapper.querySelector('[data-impeccable-variant="' + acceptedVariant + '"]');
- if (accepted && accepted.firstElementChild) {
- const parent = wrapper.parentElement;
- if (!parent) return;
- accepted.style.display = 'contents';
- parent.replaceChild(accepted, wrapper);
- }
- }, 2000);
- }
- }
-
- function handleDiscard() {
- if (!currentSessionId) return;
- sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- cleanup();
- })
- .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));
- }
-
- // ---------------------------------------------------------------------------
- // Session persistence via live-browser-session.js
- // ---------------------------------------------------------------------------
- // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
-
- function saveSession() {
- if (!currentSessionId) return;
- // NOTE: scrollY is stored under a separate key (writeScrollY). Storing
- // it here would overwrite the Go-time value every time state changes.
- sessionState.saveSession({
- id: currentSessionId,
- state,
- action: selectedAction,
- count: selectedCount,
- expected: expectedVariants,
- arrived: arrivedVariants,
- visible: visibleVariant,
- });
- }
-
- function loadSession() {
- return sessionState.loadSession();
- }
-
- function clearSession() {
- sessionState.clearSession();
- }
-
- /** Mark session as handled (accepted/discarded). The agent will clean up
- * the source, but until it does the wrapper is still in the HTML. This
- * prevents resumeSession from picking it up again after reload. */
- function markSessionHandled() {
- if (!currentSessionId) return;
- sessionState.markHandled(currentSessionId);
- }
-
- function isSessionHandled(id) {
- return sessionState.isHandled(id);
- }
-
- function clearHandled() {
- sessionState.clearHandled();
- }
-
- function cleanup() {
- // Hide the wrapper immediately so variants disappear. DON'T structurally
- // mutate the DOM yet — HMR from the agent's source rewrite is on its way,
- // and a manual replaceChild under React causes NotFoundError when the
- // reconciler later tries to remove a wrapper we already removed.
- // Schedule a 2s fallback that does the manual swap only if HMR hasn't
- // replaced the wrapper by then (keeps static-server / no-HMR flows alive).
- const cleanupSessionId = currentSessionId;
- if (cleanupSessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (wrapper) wrapper.style.display = 'none';
- }
- setTimeout(function() {
- if (!cleanupSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (!wrapper) return;
- const orig = wrapper.querySelector('[data-impeccable-variant="original"]');
- if (orig) {
- const content = orig.firstElementChild;
- if (content) {
- wrapper.parentElement.replaceChild(content, wrapper);
- return;
- }
- }
- wrapper.remove();
- }, 2000);
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }
-
- // ---------------------------------------------------------------------------
- // Toast
- // ---------------------------------------------------------------------------
-
- function showToast(message, duration) {
- if (toastEl) toastEl.remove();
- // Stack the toast above the global bar (which sits at bottom:14px) so
- // the two never overlap. Read the bar's actual rect — its height varies
- // with hover-expanded labels — and fall back to a sensible default
- // when the bar isn't mounted yet.
- const barRect = globalBarEl?.getBoundingClientRect();
- const barTopFromBottom = barRect && barRect.height > 0
- ? Math.max(16, window.innerHeight - barRect.top + 12)
- : 16;
- toastEl = el('div', {
- position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
- transform: 'translateX(-50%) translateY(8px)',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px',
- padding: '8px 16px', borderRadius: '8px',
- zIndex: Z.toast, opacity: '0',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
- pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
- });
- toastEl.id = PREFIX + '-toast';
- toastEl.textContent = message;
- document.body.appendChild(toastEl);
- requestAnimationFrame(() => {
- toastEl.style.opacity = '1';
- toastEl.style.transform = 'translateX(-50%) translateY(0)';
- });
- setTimeout(() => {
- if (toastEl) {
- toastEl.style.opacity = '0';
- toastEl.style.transform = 'translateX(-50%) translateY(8px)';
- setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
- }
- }, duration);
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- // Resume an active variant session after HMR/page reload.
- // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
- // variants before HMR fired. Pick up where we left off.
- function resumeSession() {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) { clearSession(); clearHandled(); return false; }
-
- const sessionId = wrapper.dataset.impeccableVariants;
-
- // Don't resume if this session was already accepted/discarded
- if (isSessionHandled(sessionId)) return false;
-
- currentSessionId = sessionId;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
-
- // Restore state from localStorage if available
- const saved = loadSession();
- if (saved && saved.id === sessionId) {
- visibleVariant = (saved.visible > 0 && saved.visible <= arrivedVariants) ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
- if (saved.action) selectedAction = saved.action;
- if (saved.count) selectedCount = saved.count;
- } else {
- visibleVariant = arrivedVariants > 0 ? 1 : 0;
- }
-
- // Find the visible variant's content element for highlight positioning.
- // Try the visible variant first, fall back to the original's content.
- const visEl = visibleVariant > 0 ? pickVariantContent(wrapper, visibleVariant) : null;
- const origEl = pickVariantContent(wrapper, 'original');
- selectedElement = visEl || origEl || wrapper.parentElement;
-
- // Set display state BEFORE starting observer (avoid triggering it)
- if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
-
- state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
- showBar(state === 'CYCLING' ? 'cycling' : 'generating');
- startScrollTracking();
- // Build the params panel for the restored visible variant. Previously
- // this was missed on page-reload resume: showVariantInDOM above fires
- // refreshParamsPanel, but state was still IDLE at that moment so it
- // hid. Now that state is CYCLING, re-fire.
- if (state === 'CYCLING') refreshParamsPanel();
- saveSession();
- queueCheckpoint('browser_resumed');
-
- // Start observing for more variants AFTER initial setup
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
-
- // Hold the target at its saved viewport top through any subsequent
- // HMR patches, variant inserts, or cycle swaps.
- startScrollLock(currentSessionId, readScrollY());
-
- // If we reloaded mid-generation (Bun's HTML HMR destroys the shader
- // canvas), re-capture the original's content and restart the shader so
- // the wait doesn't go dead.
- if (state === 'GENERATING' && origEl) {
- (async () => {
- try {
- const rect = origEl.getBoundingClientRect();
- if (rect.width === 0 || rect.height === 0) return;
- const blob = await captureElementToBlob(origEl, null, rect);
- if (blob && state === 'GENERATING') {
- showShaderOverlay(origEl, blob, rect);
- }
- } catch (err) {
- console.warn('[impeccable] shader resume failed:', err);
- }
- })();
- }
- return true;
- }
-
- // ---------------------------------------------------------------------------
- // Global bar (always visible at bottom)
- // ---------------------------------------------------------------------------
-
- let globalBarEl = null;
- let detectActive = false;
- let pickActive = true;
- let detectCount = 0;
- let detectScriptLoaded = false;
-
- // Theme-aware color palette for the global bar. We detect the page's
- // ambient background and invert — dark bar on light pages, light bar on
- // dark pages. This keeps the bar from fighting with the host design.
- function detectPageTheme() {
- try {
- // Dev override: set localStorage 'impeccable-dev-theme' to 'light' or
- // 'dark' to preview the opposite palette without actually changing the
- // page bg. Used for screenshots and theme QA.
- const override = localStorage.getItem('impeccable-dev-theme');
- if (override === 'light' || override === 'dark') return override;
-
- // Walk body → html, taking the first opaque background. The browser's
- // default body / html background is `rgba(0, 0, 0, 0)`, which a naive
- // regex would read as black and mislabel a perfectly white page as
- // dark. Honoring alpha avoids that — and falling through to <html>
- // catches the common pattern of a bg only on <html> (or only on body).
- function readOpaque(el) {
- if (!el) return null;
- const bg = getComputedStyle(el).backgroundColor;
- const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
- if (!m) return null;
- const alpha = m[4] == null ? 1 : parseFloat(m[4]);
- if (alpha < 0.5) return null; // transparent / nearly transparent → skip
- return [+m[1], +m[2], +m[3]];
- }
-
- const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
- // Both transparent → fall back to the browser's effective canvas color.
- // White is the universal default; only one in a thousand sites swaps it
- // via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
- // us catch that case.
- if (!rgb) {
- return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
- }
- const [r, g, b] = rgb;
- // Perceptual luminance (Rec. 709)
- const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
- return L > 0.55 ? 'light' : 'dark';
- } catch { return 'light'; }
- }
-
- function barPaletteForTheme(theme) {
- if (theme === 'dark') {
- // Light bar on dark page
- return {
- surface: 'oklch(98% 0 0 / 0.92)',
- surfaceDeep: 'oklch(92% 0.005 60 / 0.96)', // slightly deeper, faint warm
- hairline: 'oklch(70% 0 0 / 0.35)',
- text: 'oklch(15% 0 0)',
- textDim: 'oklch(45% 0 0)',
- accent: 'oklch(60% 0.25 350)',
- accentSoft: 'oklch(60% 0.25 350 / 0.18)',
- mark: 'oklch(98% 0 0)', // logo mark fill
- markText: 'oklch(15% 0 0)', // logo "/" color
- exitHover: 'oklch(85% 0 0 / 0.5)',
- };
- }
- // Dark bar on light page. Bar is a warm charcoal, logo slab is much
- // deeper so the rounded-right shape reads as a clear sculpted mark.
- return {
- surface: 'oklch(26% 0 0 / 0.94)',
- surfaceDeep: 'oklch(18% 0 0 / 0.96)', // darker sand for Tune popover
- hairline: 'oklch(42% 0 0 / 0.5)',
- text: 'oklch(96% 0 0)',
- textDim: 'oklch(72% 0 0)',
- accent: 'oklch(72% 0.22 350)',
- accentSoft: 'oklch(72% 0.22 350 / 0.22)',
- mark: 'oklch(8% 0 0)',
- markText: 'oklch(96% 0 0)',
- exitHover: 'oklch(36% 0 0 / 0.6)',
- };
- }
-
- // Impeccable logo mark — matches the site-header SVG (rounded square + "/").
- function brandMarkSvg(fill, ink, size = 18) {
- return `<svg width="${size}" height="${size}" viewBox="0 0 32 32" aria-hidden="true">
- <rect width="32" height="32" rx="7" fill="${fill}"/>
- <text x="16" y="24" font-family="system-ui, -apple-system, sans-serif" font-size="22" font-weight="500" fill="${ink}" text-anchor="middle">/</text>
- </svg>`;
- }
-
- function initGlobalBar() {
- const theme = detectPageTheme();
- const P = barPaletteForTheme(theme);
-
- // Custom focus-visible for bar buttons. Browser default is a heavy
- // blue ring that looks jarring on the dark capsule. Replace with a
- // soft accent-tinted inner ring that respects the bar's palette.
- if (!document.getElementById(PREFIX + '-bar-focus-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-bar-focus-style';
- s.textContent =
- '#' + PREFIX + '-global-bar button:focus { outline: none; }' +
- '#' + PREFIX + '-global-bar button:focus-visible {' +
- ' outline: none;' +
- ' box-shadow: 0 0 0 2px ' + P.accentSoft + ', 0 0 0 3px ' + P.accent + ';' +
- '}';
- document.head.appendChild(s);
- }
-
- globalBarEl = el('div', {
- position: 'fixed', bottom: '14px', left: '50%',
- transform: 'translateX(-50%) translateY(20px)',
- zIndex: Z.bar + 5,
- display: 'flex', alignItems: 'stretch',
- gap: '2px',
- background: P.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 4px 20px oklch(0% 0 0 / 0.12), 0 1px 3px oklch(0% 0 0 / 0.08)',
- fontFamily: FONT, fontSize: '12px', lineHeight: '1',
- opacity: '0',
- overflow: 'hidden', // clip the full-bleed brand mark to the bar radius
- transition: 'opacity 0.3s ' + EASE + ', transform 0.3s ' + EASE,
- });
- globalBarEl.id = PREFIX + '-global-bar';
- globalBarEl.dataset.theme = theme;
-
- // Brand mark — fills bar height on the left. Left side inherits the bar's
- // rounded corner via overflow:hidden; right side is a clean hard edge since
- // the near-black/charcoal contrast does the shape-defining work.
- const brand = el('span', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- alignSelf: 'stretch',
- padding: '0 12px 0 14px',
- background: P.mark,
- color: P.markText,
- fontFamily: 'system-ui, -apple-system, sans-serif',
- fontWeight: '500',
- fontSize: '18px', lineHeight: '1',
- });
- brand.textContent = '/';
- brand.title = 'Impeccable';
- globalBarEl.appendChild(brand);
-
- // Inner wrapper: holds the toggles with normal bar padding.
- const inner = el('div', {
- display: 'flex', alignItems: 'center',
- padding: '4px 5px', gap: '2px',
- });
- inner.id = PREFIX + '-global-bar-inner';
- globalBarEl.appendChild(inner);
-
- // --- button factory: icon-only at rest, label slides in on hover/active ---
- function makeIconBtn({ id, svg, label, ariaLabel, labelFont, onClick }) {
- const b = el('button', {
- position: 'relative',
- display: 'inline-flex', alignItems: 'center',
- padding: '6px 8px', borderRadius: '7px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '11.5px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.15s ease, color 0.15s ease',
- whiteSpace: 'nowrap', overflow: 'hidden',
- });
- b.id = id;
- b.title = ariaLabel || label || '';
- b.setAttribute('aria-label', ariaLabel || label || '');
- b.innerHTML = svg + (label
- ? `<span class="icon-btn-label" style="display:inline-block;max-width:0;opacity:0;margin-left:0;overflow:hidden;font-family:${labelFont || FONT};transition:max-width 0.25s ${EASE}, opacity 0.2s ease, margin-left 0.25s ${EASE};">${label}</span>`
- : '');
- const labelEl = b.querySelector('.icon-btn-label');
- const expand = () => {
- if (!labelEl) return;
- labelEl.style.maxWidth = '120px'; labelEl.style.opacity = '1'; labelEl.style.marginLeft = '6px';
- };
- const collapse = () => {
- if (!labelEl || b.dataset.active === 'true') return;
- labelEl.style.maxWidth = '0'; labelEl.style.opacity = '0'; labelEl.style.marginLeft = '0';
- };
- // Per-button hover only changes color (no layout). The label expand/
- // collapse is driven by the bar-level mouseenter/mouseleave so moving
- // the mouse between adjacent buttons doesn't trigger per-button width
- // thrashing — the whole bar grows once and shrinks once.
- b.addEventListener('mouseenter', () => { if (b.dataset.active !== 'true') b.style.color = P.text; });
- b.addEventListener('mouseleave', () => { if (b.dataset.active !== 'true') b.style.color = P.textDim; });
- b.addEventListener('click', onClick);
- b._expandLabel = expand;
- b._collapseLabel = collapse;
- return b;
- }
-
- // Pick toggle — starts active (primary intent when entering live mode).
- const pickBtn = makeIconBtn({
- id: PREFIX + '-pick-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',
- label: 'Pick',
- ariaLabel: 'Pick element',
- onClick: () => togglePick(),
- });
- pickBtn.style.background = P.accentSoft;
- pickBtn.style.color = P.accent;
- pickBtn.dataset.active = 'true';
- pickBtn._expandLabel();
- inner.appendChild(pickBtn);
-
- // Detect toggle
- const detectBtn = makeIconBtn({
- id: PREFIX + '-detect-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',
- label: 'Detect',
- ariaLabel: 'Detect anti-patterns',
- onClick: () => toggleDetect(),
- });
- const detectBadge = el('span', {
- fontSize: '10px', fontWeight: '600',
- padding: '0px 5px', borderRadius: '7px', lineHeight: '16px',
- background: P.accent, color: P.surface.includes('18%') ? 'oklch(18% 0 0)' : 'oklch(98% 0 0)',
- display: 'none', fontFamily: MONO, marginLeft: '4px',
- });
- detectBadge.id = PREFIX + '-detect-badge';
- detectBtn.appendChild(detectBadge);
- inner.appendChild(detectBtn);
-
- // DESIGN.md panel toggle — quartet of color squares as the mark.
- const designBtn = makeIconBtn({
- id: PREFIX + '-design-toggle',
- svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px ${P.hairline};flex-shrink:0">
- <span style="background:oklch(60% 0.25 350)"></span>
- <span style="background:oklch(60% 0.15 45)"></span>
- <span style="background:oklch(55% 0.12 250)"></span>
- <span style="background:oklch(30% 0 0)"></span>
- </span>`,
- label: 'DESIGN.md',
- ariaLabel: 'Toggle DESIGN.md panel',
- labelFont: MONO,
- onClick: () => toggleDesignPanel(),
- });
- inner.appendChild(designBtn);
-
- // Thin divider before the exit button
- const divider = el('span', {
- width: '1px', height: '18px',
- background: P.hairline,
- margin: '0 4px 0 2px',
- });
- inner.appendChild(divider);
-
- // Exit × on the right — intentionally subtle (textDim at rest, text on
- // hover) so it sits behind the active toggles in visual hierarchy.
- //
- // Explicit padding + box-sizing here is load-bearing: a host page like
- // `button { padding: 0.5rem 1rem; }` (very common in resets) would
- // otherwise inflate this 24x24 button into 56x40 and push the SVG out
- // of the visible bar — the X stays invisible even though the styles in
- // DevTools look fine. Every other chrome button sets padding inline;
- // this one needed it too.
- const exitBtn = el('button', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- padding: '0', boxSizing: 'border-box',
- width: '24px', height: '24px', borderRadius: '6px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
- cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
- });
- exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
- exitBtn.title = 'Exit live mode';
- exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
- exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
- exitBtn.addEventListener('click', () => { sendEvent({ type: 'exit' }); teardown(); });
- inner.appendChild(exitBtn);
-
- // Bar-level hover: expand every toggle's label at once; collapse on leave.
- // Buttons with dataset.active="true" ignore collapse (their label stays).
- const toggles = [pickBtn, detectBtn, designBtn];
- globalBarEl.addEventListener('mouseenter', () => {
- toggles.forEach((t) => t._expandLabel && t._expandLabel());
- });
- globalBarEl.addEventListener('mouseleave', () => {
- toggles.forEach((t) => t._collapseLabel && t._collapseLabel());
- });
-
- document.body.appendChild(globalBarEl);
- defangOutsideHandlers(globalBarEl);
-
- requestAnimationFrame(() => {
- globalBarEl.style.opacity = '1';
- globalBarEl.style.transform = 'translateX(-50%) translateY(0)';
- });
-
- // Listen for detection results AND ready signal
- window.addEventListener('message', onDetectMessage);
- }
-
- function updateGlobalBarState() {
- const detectToggle = document.getElementById(PREFIX + '-detect-toggle');
- const detectBadge = document.getElementById(PREFIX + '-detect-badge');
- const pickToggle = document.getElementById(PREFIX + '-pick-toggle');
- const designToggle = document.getElementById(PREFIX + '-design-toggle');
- const theme = globalBarEl?.dataset.theme || 'light';
- const P = barPaletteForTheme(theme);
-
- // Sync one toggle's active state, colors, and slide-label visibility.
- function sync(btn, active) {
- if (!btn) return;
- btn.style.background = active ? P.accentSoft : 'transparent';
- btn.style.color = active ? P.accent : P.textDim;
- btn.dataset.active = active ? 'true' : 'false';
- if (active && btn._expandLabel) btn._expandLabel();
- else if (!active && btn._collapseLabel) btn._collapseLabel();
- }
- sync(pickToggle, pickActive);
- sync(detectToggle, detectActive);
- sync(designToggle, designState.open);
-
- // If the bar is currently under the cursor, keep all labels expanded —
- // otherwise clicking a toggle that deactivates (e.g. closing DESIGN.md)
- // would collapse its label while the user's mouse is still on the bar.
- if (globalBarEl && globalBarEl.matches(':hover')) {
- [pickToggle, detectToggle, designToggle].forEach((t) => t?._expandLabel?.());
- }
-
- if (detectBadge) {
- detectBadge.style.display = (detectActive && detectCount > 0) ? 'inline' : 'none';
- detectBadge.textContent = detectCount;
- }
-
- // When pick is active, make detect overlays click-through so the picker works
- document.querySelectorAll('.impeccable-overlay').forEach(o => {
- o.style.pointerEvents = pickActive ? 'none' : '';
- });
- }
-
- let detectReady = false; // true once detect script posts 'impeccable-ready'
- let detectPendingScan = false; // scan requested before script was ready
-
- function toggleDetect() {
- detectActive = !detectActive;
- updateGlobalBarState();
-
- if (detectActive) {
- if (!detectScriptLoaded) {
- detectPendingScan = true;
- loadDetectScript();
- } else if (detectReady) {
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- } else {
- detectPendingScan = true;
- }
- } else {
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- detectCount = 0;
- updateGlobalBarState();
- }
- }
-
- function togglePick() {
- pickActive = !pickActive;
- updateGlobalBarState();
-
- if (!pickActive) {
- // Disabling pick clears any in-flight selection and UI: highlight,
- // contextual bar, selectedElement. Otherwise a stale selection sits
- // on screen with no obvious way to dismiss.
- hideHighlight();
- hideBar();
- hideActionPicker();
- selectedElement = null;
- if (state === 'PICKING' || state === 'CONFIGURING') state = 'IDLE';
- } else {
- if (state === 'IDLE') state = 'PICKING';
- }
- }
-
- function loadDetectScript() {
- if (detectScriptLoaded) return;
- detectScriptLoaded = true;
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/detect.js';
- s.dataset.impeccableExtension = 'true';
- document.head.appendChild(s);
- }
-
- function onDetectMessage(e) {
- if (!e.data || typeof e.data.source !== 'string') return;
- // Detection script is loaded and ready
- if (e.data.source === 'impeccable-ready') {
- detectReady = true;
- if (detectPendingScan && detectActive) {
- detectPendingScan = false;
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- }
- }
- // Scan results arrived
- if (e.data.source === 'impeccable-results') {
- detectCount = e.data.count || 0;
- updateGlobalBarState();
- }
- }
-
- /** Full teardown: remove all UI, disconnect SSE, clean up. */
- function teardown() {
- cleanup();
- hideBar();
- if (globalBarEl) {
- globalBarEl.style.transform = 'translateY(100%)';
- setTimeout(() => { if (globalBarEl) globalBarEl.remove(); globalBarEl = null; }, 300);
- }
- if (highlightEl) { highlightEl.remove(); highlightEl = null; }
- if (tooltipEl) { tooltipEl.remove(); tooltipEl = null; }
- if (barEl) { barEl.remove(); barEl = null; }
- if (pickerEl) { pickerEl.remove(); pickerEl = null; }
- if (paramsPanelEl) { paramsPanelEl.remove(); paramsPanelEl = null; paramsPanelInner = null; paramsPanelBody = null; }
- if (evtSource) { evtSource.close(); evtSource = null; }
- document.removeEventListener('mousemove', handleMouseMove, true);
- document.removeEventListener('click', handleClick, true);
- document.removeEventListener('keydown', handleKeyDown, true);
- window.removeEventListener('message', onDetectMessage);
- // Remove detection overlays
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- state = 'IDLE';
- window.__IMPECCABLE_LIVE_INIT__ = false;
- console.log('[impeccable] Live mode exited.');
- }
-
- // ---------------------------------------------------------------------------
- // Design System Panel — visualizes the project's .impeccable/design.json sidecar
- // ---------------------------------------------------------------------------
-
- const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';
- const DESIGN_PANEL_WIDTH = 440;
-
- let designHost = null;
- let designShadow = null;
- let designState = {
- open: false,
- tab: 'visual', // 'visual' | 'raw'
- parsed: null, // parseDesignMd output (frontmatter + body sections)
- sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)
- hasMd: false,
- hasSidecar: false,
- present: null, // true/false once fetch resolves
- raw: null, // raw DESIGN.md for the raw tab
- mdNewerThanJson: false, // stale-hint flag
- loading: false,
- error: null,
- collapsed: { // narrative-section accordion state
- rules: true, dosdonts: true, overview: true,
- },
- };
-
- function loadDesignPrefs() {
- // `open` is intentionally NOT persisted — the panel always starts closed
- // so live mode doesn't auto-slide a big panel over the page on startup.
- try {
- const raw = localStorage.getItem(DESIGN_PREFS_KEY);
- if (!raw) return;
- const prefs = JSON.parse(raw);
- if (prefs.tab === 'visual' || prefs.tab === 'raw') designState.tab = prefs.tab;
- if (prefs.collapsed && typeof prefs.collapsed === 'object') {
- Object.assign(designState.collapsed, prefs.collapsed);
- }
- } catch { /* ignore */ }
- }
-
- function saveDesignPrefs() {
- try {
- localStorage.setItem(DESIGN_PREFS_KEY, JSON.stringify({
- tab: designState.tab,
- collapsed: designState.collapsed,
- }));
- } catch { /* ignore */ }
- }
-
- function initDesignPanel() {
- designHost = document.createElement('div');
- designHost.id = PREFIX + '-design-host';
- Object.assign(designHost.style, {
- position: 'fixed', top: '0', left: '0',
- width: '0', height: '0',
- zIndex: String(Z.bar + 10),
- pointerEvents: 'none',
- });
- designShadow = designHost.attachShadow({ mode: 'open' });
-
- const style = document.createElement('style');
- // Theme-match the bar: dark chrome on light pages, light chrome on dark pages.
- const theme = detectPageTheme();
- style.textContent = designPanelCss(barPaletteForTheme(theme));
- designShadow.appendChild(style);
-
- const root = document.createElement('div');
- root.className = 'root';
- designShadow.appendChild(root);
-
- document.body.appendChild(designHost);
- // The host is pointer-events: none; the panel inside the shadow DOM
- // manages its own auto/none. Events bubble through the shadow boundary,
- // so attaching here silences host-page outside-interaction handlers
- // without touching the host's click-through behavior.
- defangOutsideHandlers(designHost, { setPointerEvents: false });
-
- loadDesignPrefs();
- renderDesignChrome();
- if (designState.open) {
- fetchDesignSystem();
- }
- }
-
- // Neutral panel palette — deliberately NOT Impeccable-branded. The panel is
- // a viewer of the project's design system, not an Impeccable surface.
- const DP = {
- canvas: 'oklch(94% 0 0)', // panel background
- tile: 'oklch(98.5% 0 0)', // card-on-canvas
- tileAlt: 'oklch(96% 0 0)', // subtler tile for inner surfaces
- ink: 'oklch(15% 0 0)',
- ink2: 'oklch(35% 0 0)',
- meta: 'oklch(55% 0 0)',
- hairline: 'oklch(88% 0 0)',
- hairlineSoft: 'oklch(92% 0 0)',
- amber: 'oklch(70% 0.13 65)', // stale-hint accent
- amberBg: 'oklch(95% 0.05 80)',
- };
-
- function designPanelCss(BP) {
- // BP = bar palette (theme-aware, matches the global bar).
- // DP = internal content palette (neutral, so tiles render colors true).
- return `
- :host, .root { all: initial; }
- .root {
- font-family: ${FONT};
- color: ${DP.ink};
- pointer-events: none;
- }
- .root * { box-sizing: border-box; }
- button { font: inherit; color: inherit; }
-
- /* --- Panel shell: chrome matches the bar; body canvas stays neutral --- */
- .panel {
- position: fixed; top: 12px; bottom: 72px; right: 12px;
- width: ${DESIGN_PANEL_WIDTH}px; max-width: calc(100vw - 24px);
- background: ${BP.surface};
- border: 1px solid ${BP.hairline};
- border-radius: 14px;
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- box-shadow: 0 20px 60px oklch(0% 0 0 / 0.18), 0 4px 12px oklch(0% 0 0 / 0.08);
- display: flex; flex-direction: column;
- transform: translateX(calc(100% + 24px));
- opacity: 0;
- transition: transform 0.35s ${EASE}, opacity 0.25s ${EASE};
- pointer-events: none;
- overflow: hidden;
- }
- .panel[data-open="true"] { transform: translateX(0); opacity: 1; pointer-events: auto; }
-
- .panel-header {
- display: flex; align-items: center; gap: 10px;
- padding: 10px 10px 10px 14px;
- background: transparent;
- border-bottom: 1px solid ${BP.hairline};
- }
- .panel-title {
- flex: 1; min-width: 0;
- font-family: ${MONO};
- font-size: 11.5px; font-weight: 600;
- letter-spacing: 0.02em;
- color: ${BP.text};
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
- }
- .panel-close {
- border: none; background: transparent; color: ${BP.textDim};
- width: 26px; height: 26px; border-radius: 7px;
- display: inline-flex; align-items: center; justify-content: center;
- cursor: pointer; transition: background 0.15s ease, color 0.15s ease;
- }
- .panel-close:hover { background: ${BP.hairline}; color: ${BP.text}; }
-
- .tabs {
- display: inline-flex; padding: 2px;
- background: ${BP.hairline};
- border-radius: 7px;
- gap: 2px;
- }
- .tab {
- border: none; background: transparent;
- padding: 4px 10px; border-radius: 5px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 600; letter-spacing: 0.08em;
- text-transform: uppercase;
- color: ${BP.textDim}; cursor: pointer;
- transition: background 0.15s ease, color 0.15s ease;
- }
- .tab[data-active="true"] { background: ${BP.surface}; color: ${BP.text}; }
-
- .panel-body {
- flex: 1; overflow-y: auto;
- padding: 12px 12px 20px;
- background: ${DP.canvas};
- scrollbar-width: thin;
- scrollbar-color: ${DP.hairline} transparent;
- }
- .panel-body::-webkit-scrollbar { width: 8px; }
- .panel-body::-webkit-scrollbar-thumb { background: ${DP.hairline}; border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
-
- /* --- States --- */
- .empty, .loading, .error {
- margin: 16px 4px;
- padding: 28px 20px; text-align: center;
- background: ${DP.tile}; border-radius: 14px;
- color: ${DP.ink2}; font-size: 13px; line-height: 1.55;
- }
- .empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
- .empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
- .error { color: oklch(45% 0.15 25); }
-
- /* --- Stale hint --- */
- .stale {
- display: flex; align-items: center; gap: 8px;
- margin: 8px 4px 12px;
- padding: 8px 12px;
- background: ${DP.amberBg};
- border-radius: 10px;
- font-size: 11.5px; color: ${DP.ink2};
- }
- .stale-dot { width: 8px; height: 8px; border-radius: 50%; background: ${DP.amber}; flex-shrink: 0; }
- .stale-text { flex: 1; min-width: 0; }
- .stale-text strong { color: ${DP.ink}; font-weight: 600; }
-
- /* --- Parsed-md fallback banner --- */
- .parsed-md-cta {
- margin: 8px 4px 14px;
- padding: 14px 16px;
- background: ${DP.tile};
- border: 1px dashed ${DP.hairline};
- border-radius: 12px;
- font-size: 12px; color: ${DP.ink2}; line-height: 1.55;
- }
- .parsed-md-cta strong { color: ${DP.ink}; display: block; margin-bottom: 4px; font-size: 13px; font-weight: 600; }
- .parsed-md-cta code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; font-size: 11.5px; color: ${DP.ink}; }
-
- /* --- Tile primitives --- */
- .tile {
- position: relative;
- background: ${DP.tile};
- border-radius: 16px;
- padding: 16px;
- margin: 0 4px 10px;
- }
- .tile-row { margin: 0 4px 10px; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
- .tile-row .tile { margin: 0; }
- .tile-meta {
- display: flex; align-items: baseline; justify-content: space-between;
- gap: 10px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase;
- color: ${DP.meta};
- }
- .tile-meta .name { color: ${DP.ink}; font-weight: 600; letter-spacing: 0.05em; text-transform: none; font-family: ${FONT}; font-size: 12.5px; }
-
- /* --- Color tile --- */
- .c-tile { cursor: pointer; transition: transform 0.2s ${EASE}; }
- .c-tile:hover { transform: translateY(-1px); }
- .c-hero {
- height: 72px; border-radius: 10px; margin-top: 10px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.05);
- }
- .c-ramp {
- display: flex; gap: 0; height: 14px; border-radius: 4px; overflow: hidden;
- margin-top: 8px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.04);
- }
- .c-ramp > span { flex: 1; }
- .c-desc { margin-top: 8px; font-size: 11.5px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Type tile --- */
- .t-tile { }
- .t-specimen {
- margin: 4px 0 6px;
- color: ${DP.ink};
- line-height: 0.9;
- }
- .t-family { margin-top: 4px; font-size: 12px; font-weight: 600; color: ${DP.ink}; }
- .t-purpose { margin-top: 4px; font-size: 11px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Shadow tile --- */
- .s-tile { }
- .s-surface {
- height: 60px; margin: 8px 2px 10px;
- background: ${DP.tile};
- border-radius: 10px;
- }
- .s-value { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; word-break: break-all; line-height: 1.4; }
- .s-purpose { margin-top: 4px; font-size: 11px; color: ${DP.ink2}; line-height: 1.45; }
-
- /* --- Radii strip --- */
- .r-strip { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
- .r-item { display: flex; flex-direction: column; align-items: center; gap: 4px; flex: 1; min-width: 60px; }
- .r-sample { width: 44px; height: 44px; background: ${DP.canvas}; box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.08); }
- .r-label { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; text-transform: uppercase; }
- .r-val { font-family: ${MONO}; font-size: 10px; color: ${DP.ink}; }
-
- /* --- Component tile (hosts live primitives) --- */
- .cmp-tile { }
- .cmp-stage {
- margin: 12px -4px 0;
- padding: 18px 16px 10px;
- border-top: 1px solid ${DP.hairlineSoft};
- display: flex; flex-direction: column; align-items: center; justify-content: center;
- gap: 14px;
- min-height: 68px;
- }
- .cmp-stage + .cmp-stage { border-top: 1px dashed ${DP.hairlineSoft}; }
- .cmp-sublabel { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.06em; }
- .cmp-kind { font-family: ${MONO}; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; }
-
- /* --- Collapsible --- */
- .coll {
- margin: 0 4px 8px;
- background: ${DP.tile};
- border-radius: 12px;
- overflow: hidden;
- }
- .coll-head {
- display: flex; align-items: center; gap: 10px;
- width: 100%;
- padding: 12px 14px;
- background: transparent; border: none;
- cursor: pointer; text-align: left;
- font-family: ${FONT}; font-size: 12.5px; font-weight: 600; color: ${DP.ink};
- transition: background 0.12s ease;
- }
- .coll-head:hover { background: ${DP.tileAlt}; }
- .coll-chev {
- width: 12px; height: 12px; flex-shrink: 0;
- color: ${DP.meta};
- transition: transform 0.2s ${EASE};
- }
- .coll[data-open="true"] .coll-chev { transform: rotate(90deg); }
- .coll-count { margin-left: auto; font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; }
- .coll-body { padding: 0 14px 14px; display: none; }
- .coll[data-open="true"] .coll-body { display: block; }
-
- .rule-card {
- padding: 10px 0;
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .rule-card:first-child { border-top: none; padding-top: 2px; }
- .rule-card .name { font-size: 11.5px; font-weight: 700; color: ${DP.ink}; margin-bottom: 3px; }
- .rule-card .name .section { font-family: ${MONO}; font-size: 9px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; margin-left: 8px; }
- .rule-card .body { font-size: 11.5px; color: ${DP.ink2}; line-height: 1.5; }
-
- .coll .dos { display: grid; gap: 0; margin-top: 2px; }
- .coll .do, .coll .dont {
- position: relative;
- padding: 8px 0 8px 22px;
- font-size: 11.5px; line-height: 1.5; color: ${DP.ink2};
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .coll .do:first-child, .coll .dont:first-child,
- .coll .do:first-of-type { border-top: none; }
- .coll .do + .dont { border-top: 1px solid ${DP.hairlineSoft}; }
- .coll .do::before, .coll .dont::before {
- content: ''; position: absolute; left: 4px; top: 13px;
- width: 8px; height: 8px; border-radius: 50%;
- }
- .coll .do::before { background: oklch(62% 0.16 145); }
- .coll .dont::before { background: oklch(58% 0.22 25); }
-
- .coll .overview-body {
- font-size: 12px; line-height: 1.55; color: ${DP.ink2};
- }
- .coll .overview-body .north-star {
- display: block; font-family: ${FONT}; font-style: italic;
- font-size: 15px; line-height: 1.3; color: ${DP.ink};
- margin-bottom: 8px;
- }
- .coll .overview-body p { margin: 0 0 8px; }
- .coll .overview-body ul { margin: 6px 0 0; padding-left: 16px; font-size: 11.5px; }
- .coll .overview-body li { margin-bottom: 3px; }
-
- /* --- raw tab markdown (unchanged layout, neutralized palette) --- */
- .md { padding: 4px 10px 20px; font-size: 13px; line-height: 1.6; color: ${DP.ink}; }
- .md h1, .md h2, .md h3, .md h4 { margin: 20px 0 8px; color: ${DP.ink}; font-weight: 600; }
- .md h1 { font-size: 18px; }
- .md h2 { font-size: 15px; padding-bottom: 4px; border-bottom: 1px solid ${DP.hairlineSoft}; }
- .md h3 { font-size: 13px; }
- .md h4 { font-size: 12px; color: ${DP.meta}; }
- .md p { margin: 0 0 10px; }
- .md ul, .md ol { margin: 0 0 10px; padding-left: 20px; }
- .md li { margin-bottom: 4px; }
- .md code { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; }
- .md pre { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 10px 12px; border-radius: 8px; overflow-x: auto; margin: 0 0 10px; }
- .md pre code { background: none; padding: 0; }
- .md strong { font-weight: 700; }
- .md em { font-style: italic; }
- .md a { color: ${DP.ink}; text-decoration: underline; }
- .md hr { border: none; border-top: 1px solid ${DP.hairlineSoft}; margin: 16px 0; }
- `;
- }
-
- function renderDesignChrome() {
- const root = designShadow.querySelector('.root');
- root.innerHTML = '';
-
- // (Panel toggle lives in the global bar — no floating FAB.)
- // Panel
- const panel = document.createElement('aside');
- panel.className = 'panel';
- panel.setAttribute('data-open', designState.open ? 'true' : 'false');
- panel.appendChild(buildDesignHeader());
- const body = document.createElement('div');
- body.className = 'panel-body';
- body.id = 'panel-body';
- panel.appendChild(body);
- root.appendChild(panel);
-
- renderDesignBody();
- }
-
- function buildDesignHeader() {
- const header = document.createElement('div');
- header.className = 'panel-header';
-
- const title = document.createElement('div');
- title.className = 'panel-title';
- title.textContent = 'DESIGN.md';
- header.appendChild(title);
-
- const tabs = document.createElement('div');
- tabs.className = 'tabs';
- for (const t of [['visual', 'Visual'], ['raw', 'Raw']]) {
- const btn = document.createElement('button');
- btn.className = 'tab';
- btn.textContent = t[1];
- btn.setAttribute('data-active', designState.tab === t[0] ? 'true' : 'false');
- btn.addEventListener('click', () => {
- if (designState.tab === t[0]) return;
- designState.tab = t[0];
- saveDesignPrefs();
- renderDesignChrome();
- if (t[0] === 'raw' && designState.raw === null && !designState.loading) {
- fetchDesignSystem(); // raw is part of the same fetch pair
- }
- });
- tabs.appendChild(btn);
- }
- header.appendChild(tabs);
-
- const close = document.createElement('button');
- close.className = 'panel-close';
- close.innerHTML = '✕';
- close.setAttribute('aria-label', 'Close panel');
- close.addEventListener('click', toggleDesignPanel);
- header.appendChild(close);
-
- return header;
- }
-
- function toggleDesignPanel() {
- designState.open = !designState.open;
- renderDesignChrome();
- updateGlobalBarState();
- if (designState.open && designState.present === null && !designState.loading) {
- fetchDesignSystem();
- }
- }
-
- async function fetchDesignSystem() {
- designState.loading = true;
- designState.error = null;
- renderDesignBody();
- try {
- const [jsonRes, rawRes] = await Promise.all([
- fetch(`http://localhost:${PORT}/design-system.json?token=${TOKEN}`, { cache: 'no-store' }),
- fetch(`http://localhost:${PORT}/design-system/raw?token=${TOKEN}`, { cache: 'no-store' }),
- ]);
- const jsonData = await jsonRes.json();
- designState.present = jsonData.present === true;
- designState.parsed = jsonData.parsed || null;
- designState.sidecar = jsonData.sidecar || null;
- designState.hasMd = !!jsonData.hasMd;
- designState.hasSidecar = !!jsonData.hasSidecar;
- designState.mdNewerThanJson = !!jsonData.mdNewerThanJson;
- designState.raw = designState.present && rawRes.ok ? await rawRes.text() : null;
- designState.error = jsonData.parseError || jsonData.sidecarError || null;
- } catch (err) {
- designState.error = err?.message || 'Failed to load design system.';
- } finally {
- designState.loading = false;
- renderDesignChrome(); // refresh title from data
- }
- }
-
- function renderDesignBody() {
- const body = designShadow.querySelector('#panel-body');
- if (!body) return;
- body.innerHTML = '';
-
- if (designState.loading) {
- body.appendChild(msgDiv('loading', 'Loading design system…'));
- return;
- }
- if (designState.error) {
- body.appendChild(msgDiv('error', designState.error));
- return;
- }
- if (designState.present === false) {
- const empty = document.createElement('div');
- empty.className = 'empty';
- empty.innerHTML = `<strong>No DESIGN.md yet</strong>Create one by running <code>/impeccable document</code> in your terminal, then re-open this panel.`;
- body.appendChild(empty);
- return;
- }
-
- if (designState.tab === 'raw') {
- renderRawTab(body, designState.raw || '');
- return;
- }
-
- // Visual tab — single unified render path.
- if (designState.mdNewerThanJson) body.appendChild(renderStaleHint());
- if (designState.hasMd && !designState.hasSidecar) {
- body.appendChild(renderParsedMdCta());
- }
- renderDesignVisual(body, designState.parsed, designState.sidecar);
- }
-
- function msgDiv(cls, text) {
- const d = document.createElement('div');
- d.className = cls;
- d.textContent = text;
- return d;
- }
-
- function renderStaleHint() {
- const box = document.createElement('div');
- box.className = 'stale';
- box.innerHTML = `
- <span class="stale-dot"></span>
- <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>
- `;
- return box;
- }
-
- function renderParsedMdCta() {
- const box = document.createElement('div');
- box.className = 'parsed-md-cta';
- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;
- return box;
- }
-
- // --- Unified render: merge parsed DESIGN.md frontmatter with sidecar v2 ---
-
- function renderDesignVisual(body, parsed, sidecar) {
- const frontmatter = parsed?.frontmatter || {};
- const extensions = sidecar?.extensions || {};
- const proseColors = parsed?.colors || null;
-
- const colors = buildColorModels(frontmatter.colors, extensions.colorMeta, proseColors);
- if (colors.length) renderColorTiles(body, colors);
-
- const types = buildTypographyModels(frontmatter.typography, extensions.typographyMeta);
- if (types.length) renderTypeTiles(body, types);
-
- const radii = buildRadiiModels(frontmatter.rounded);
- if (radii.length) renderRadiiTile(body, radii);
-
- if (extensions.shadows?.length) renderShadowTiles(body, extensions.shadows);
-
- const components = sidecar?.components || [];
- if (components.length) renderComponentTiles(body, components);
-
- // Narrative: sidecar wins if present (richer, agent-curated). Otherwise
- // synthesize from prose sections.
- const narrative = sidecar?.narrative || synthesizeNarrative(parsed);
- if (narrative.rules?.length) body.appendChild(renderRulesCollapsible(narrative.rules));
- if ((narrative.dos?.length || narrative.donts?.length)) body.appendChild(renderDosDontsCollapsible(narrative));
- if (narrative.overview || narrative.northStar || narrative.keyCharacteristics?.length) {
- body.appendChild(renderOverviewCollapsible(narrative));
- }
-
- if (body.childElementCount === 0) {
- body.appendChild(msgDiv('empty', 'No design system data available.'));
- }
- }
-
- // Frontmatter primitives + sidecar colorMeta → tile-ready color models.
- // A matching prose bullet (when the slug sits in the bullet text) supplies
- // description as a last-resort fallback.
- function buildColorModels(fmColors, colorMeta, proseColors) {
- if (!fmColors) return [];
- const meta = colorMeta || {};
- return Object.entries(fmColors).map(([key, value]) => {
- const m = meta[key] || {};
- return {
- role: m.role || humanizeKey(key),
- name: m.displayName || humanizeKey(key),
- value: value,
- canonical: m.canonical || null,
- description: m.description || findProseDescription(proseColors, key, m.displayName),
- tonalRamp: m.tonalRamp || null,
- };
- });
- }
-
- function buildTypographyModels(fmTypography, typographyMeta) {
- if (!fmTypography) return [];
- const meta = typographyMeta || {};
- return Object.entries(fmTypography).map(([key, spec]) => {
- const m = meta[key] || {};
- const { family, fallback } = splitFontFamily(spec?.fontFamily);
- return {
- role: key,
- name: m.displayName || humanizeKey(key),
- family,
- fallback,
- weight: spec?.fontWeight ?? 400,
- // fontStyle isn't in Stitch's frontmatter schema; the sidecar carries
- // it when a role is rendered in italic (e.g. display italic).
- style: m.style || 'normal',
- sampleSize: spec?.fontSize || '1rem',
- lineHeight: spec?.lineHeight != null ? String(spec.lineHeight) : '',
- letterSpacing: spec?.letterSpacing,
- purpose: m.purpose,
- };
- });
- }
-
- function buildRadiiModels(fmRounded) {
- if (!fmRounded) return [];
- return Object.entries(fmRounded).map(([name, value]) => ({ name, value }));
- }
-
- function splitFontFamily(stack) {
- if (!stack || typeof stack !== 'string') return { family: '', fallback: '' };
- const parts = stack.split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, ''));
- return { family: parts[0] || '', fallback: parts.slice(1).join(', ') };
- }
-
- function humanizeKey(k) {
- return String(k || '').replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
- }
-
- function findProseDescription(proseColors, key, displayName) {
- if (!proseColors || !proseColors.groups) return null;
- const needles = [key, displayName].filter(Boolean).map((s) => s.toLowerCase());
- for (const g of proseColors.groups) {
- for (const c of g.colors || []) {
- const hay = String(c.name || '').toLowerCase();
- if (hay && needles.some((n) => hay.includes(n) || n.includes(hay))) {
- return c.description || null;
- }
- }
- }
- return null;
- }
-
- function synthesizeNarrative(parsed) {
- if (!parsed) return {};
- const md = parsed;
- return {
- northStar: md.overview?.creativeNorthStar,
- overview: (md.overview?.philosophy || []).join(' '),
- keyCharacteristics: md.overview?.keyCharacteristics || [],
- rules: [
- ...(md.colors?.rules || []).map((r) => ({ ...r, section: 'colors' })),
- ...(md.typography?.rules || []).map((r) => ({ ...r, section: 'typography' })),
- ...(md.elevation?.rules || []).map((r) => ({ ...r, section: 'elevation' })),
- ],
- dos: md.dosDonts?.dos || [],
- donts: md.dosDonts?.donts || [],
- };
- }
-
- function renderColorTiles(body, colors) {
- for (const c of colors) {
- const tile = document.createElement('div');
- tile.className = 'tile c-tile';
- tile.title = 'Click to copy';
- tile.addEventListener('click', () => copyToClipboard(c.value));
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(c.name || c.role || 'Color')}</span><span>${escapeHtml(c.value || '')}</span>`;
- tile.appendChild(meta);
-
- const hero = document.createElement('div');
- hero.className = 'c-hero';
- hero.style.background = c.value;
- tile.appendChild(hero);
-
- const ramp = synthesizeRamp(c);
- if (ramp.length) {
- const r = document.createElement('div');
- r.className = 'c-ramp';
- r.innerHTML = ramp.map((v) => `<span style="background:${cssSafe(v)}"></span>`).join('');
- tile.appendChild(r);
- }
-
- if (c.description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = c.description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function synthesizeRamp(c) {
- if (c.tonalRamp?.length) return c.tonalRamp;
- // If base value is OKLCH, synthesize an 8-step ramp across lightness.
- const m = typeof c.value === 'string' && c.value.match(/^oklch\(\s*([\d.]+)%\s+([\d.]+)\s+([\d.]+)\s*(?:\/\s*([\d.]+))?\s*\)$/i);
- if (!m) return [];
- const [, , chroma, hue] = m;
- const steps = [20, 32, 44, 56, 68, 80, 90, 96];
- return steps.map((l) => `oklch(${l}% ${chroma} ${hue})`);
- }
-
- function renderTypeTiles(body, types) {
- for (const t of types) {
- const tile = document.createElement('div');
- tile.className = 'tile t-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span>${escapeHtml(t.role || '')}</span><span>${escapeHtml(t.weight || '')} ${escapeHtml(t.style === 'italic' ? 'italic' : '')}</span>`;
- tile.appendChild(meta);
-
- const specimen = document.createElement('div');
- specimen.className = 't-specimen';
- specimen.textContent = 'Aa';
- specimen.style.fontFamily = fontStack(t);
- specimen.style.fontWeight = String(t.weight || 400);
- specimen.style.fontStyle = t.style || 'normal';
- specimen.style.fontSize = '56px'; // Fixed specimen size — compare faces, not scales.
- specimen.style.letterSpacing = 'normal';
- specimen.style.textTransform = 'none';
- tile.appendChild(specimen);
-
- // The system's actual sample size for this role, shown as small mono meta below.
- if (t.sampleSize) {
- const scale = document.createElement('div');
- scale.style.cssText = 'font-family:' + MONO + '; font-size: 10px; color:' + DP.meta + '; margin-top: 2px;';
- scale.textContent = t.sampleSize;
- tile.appendChild(scale);
- }
-
- const family = document.createElement('div');
- family.className = 't-family';
- family.textContent = t.family || t.name || '';
- tile.appendChild(family);
-
- if (t.purpose) {
- const p = document.createElement('div');
- p.className = 't-purpose';
- p.textContent = t.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function fontStack(t) {
- const fam = t.family || '';
- const fb = t.fallback || '';
- if (fam && /[,\s]/.test(fam) && !fam.includes("'") && !fam.includes('"')) {
- return `"${fam}", ${fb}`;
- }
- return fam && fb ? `"${fam}", ${fb}` : (fam || fb);
- }
-
- function renderRadiiTile(body, radii) {
- const tile = document.createElement('div');
- tile.className = 'tile';
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">Corner Radii</span><span>${radii.length}</span>`;
- tile.appendChild(meta);
-
- const strip = document.createElement('div');
- strip.className = 'r-strip';
- for (const r of radii) {
- const item = document.createElement('div');
- item.className = 'r-item';
- const s = document.createElement('div');
- s.className = 'r-sample';
- s.style.borderRadius = r.value || '0';
- item.appendChild(s);
- const lbl = document.createElement('div');
- lbl.className = 'r-label';
- lbl.textContent = r.name || '';
- item.appendChild(lbl);
- const val = document.createElement('div');
- val.className = 'r-val';
- val.textContent = r.value || '';
- item.appendChild(val);
- strip.appendChild(item);
- }
- tile.appendChild(strip);
- body.appendChild(tile);
- }
-
- function renderShadowTiles(body, shadows) {
- for (const sh of shadows) {
- const tile = document.createElement('div');
- tile.className = 'tile s-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(sh.name || 'Shadow')}</span><span>Elevation</span>`;
- tile.appendChild(meta);
-
- const surface = document.createElement('div');
- surface.className = 's-surface';
- surface.style.boxShadow = sh.value || 'none';
- tile.appendChild(surface);
-
- const val = document.createElement('div');
- val.className = 's-value';
- val.textContent = sh.value || '';
- tile.appendChild(val);
-
- if (sh.purpose) {
- const p = document.createElement('div');
- p.className = 's-purpose';
- p.textContent = sh.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function renderComponentTiles(body, components) {
- // Group consecutive components that share a kind into one tile. This avoids
- // a pile of one-component tiles (e.g., three button variants = three tiles)
- // and reads more like a proper category.
- const groups = groupByKind(components);
-
- for (const group of groups) {
- const tile = document.createElement('div');
- tile.className = 'tile cmp-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- const groupTitle = group.length === 1
- ? (group[0].name || group[0].kind || 'Component')
- : titleForKind(group[0].kind, group.length);
- meta.innerHTML = `<span class="name">${escapeHtml(groupTitle)}</span><span class="cmp-kind">${escapeHtml(group[0].kind || '')}</span>`;
- tile.appendChild(meta);
-
- for (const c of group) {
- const stage = document.createElement('div');
- stage.className = 'cmp-stage';
-
- // Render the component in its own shadow root so its CSS can't bleed.
- const host = document.createElement('div');
- const sub = host.attachShadow({ mode: 'open' });
- const style = document.createElement('style');
- style.textContent = c.css || '';
- sub.appendChild(style);
- const container = document.createElement('div');
- container.innerHTML = c.html || '';
- sub.appendChild(container);
- stage.appendChild(host);
-
- // Show component name as a sublabel only when the tile groups >1 item,
- // or when the component's display name differs from its kind.
- const showSublabel = group.length > 1;
- if (showSublabel) {
- const lbl = document.createElement('div');
- lbl.className = 'cmp-sublabel';
- lbl.textContent = c.name || '';
- stage.appendChild(lbl);
- }
- tile.appendChild(stage);
- }
-
- // Single shared description if all items carry the same one; otherwise
- // skip — per-item descriptions clutter a grouped tile.
- if (group.length === 1 && group[0].description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = group[0].description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function groupByKind(components) {
- const groups = [];
- for (const c of components) {
- const last = groups[groups.length - 1];
- if (last && last[0].kind && c.kind === last[0].kind) {
- last.push(c);
- } else {
- groups.push([c]);
- }
- }
- return groups;
- }
-
- function titleForKind(kind, count) {
- const labels = {
- button: 'Buttons',
- input: 'Inputs',
- nav: 'Navigation',
- chip: 'Chips',
- card: 'Cards',
- custom: 'Components',
- };
- return labels[kind] || (kind ? kind.charAt(0).toUpperCase() + kind.slice(1) + 's' : 'Components');
- }
-
- // --- Collapsibles ---------------------------------------------------------
-
- function buildCollapsible(key, label, count) {
- const wrap = document.createElement('div');
- wrap.className = 'coll';
- wrap.setAttribute('data-open', designState.collapsed[key] ? 'false' : 'true');
-
- const head = document.createElement('button');
- head.className = 'coll-head';
- head.innerHTML = `
- <svg class="coll-chev" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 2.5L8 6 4 9.5"/></svg>
- <span>${escapeHtml(label)}</span>
- ${count != null ? `<span class="coll-count">${escapeHtml(String(count))}</span>` : ''}
- `;
- head.addEventListener('click', () => {
- designState.collapsed[key] = !designState.collapsed[key];
- saveDesignPrefs();
- renderDesignBody();
- });
- wrap.appendChild(head);
-
- const body = document.createElement('div');
- body.className = 'coll-body';
- wrap.appendChild(body);
- return { wrap, body };
- }
-
- function renderRulesCollapsible(rules) {
- const { wrap, body } = buildCollapsible('rules', 'Named Rules', rules.length);
- for (const r of rules) {
- const card = document.createElement('div');
- card.className = 'rule-card';
- const name = document.createElement('div');
- name.className = 'name';
- name.innerHTML = `${escapeHtml(r.name)}${r.section ? `<span class="section">${escapeHtml(r.section)}</span>` : ''}`;
- card.appendChild(name);
- const b = document.createElement('div');
- b.className = 'body';
- b.textContent = r.body || '';
- card.appendChild(b);
- body.appendChild(card);
- }
- return wrap;
- }
-
- function renderDosDontsCollapsible(n) {
- const total = (n.dos?.length || 0) + (n.donts?.length || 0);
- const { wrap, body } = buildCollapsible('dosdonts', "Do's and Don'ts", total);
- const grid = document.createElement('div');
- grid.className = 'dos';
- for (const d of n.dos || []) {
- const el = document.createElement('div');
- el.className = 'do';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- for (const d of n.donts || []) {
- const el = document.createElement('div');
- el.className = 'dont';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- body.appendChild(grid);
- return wrap;
- }
-
- function renderOverviewCollapsible(n) {
- const { wrap, body } = buildCollapsible('overview', 'Overview', null);
- const ov = document.createElement('div');
- ov.className = 'overview-body';
- if (n.northStar) {
- const star = document.createElement('span');
- star.className = 'north-star';
- star.textContent = '“' + n.northStar + '”';
- ov.appendChild(star);
- }
- if (n.overview) {
- const p = document.createElement('p');
- p.innerHTML = inlineMd(n.overview);
- ov.appendChild(p);
- }
- if (n.keyCharacteristics?.length) {
- const ul = document.createElement('ul');
- ul.innerHTML = n.keyCharacteristics.map((k) => `<li>${inlineMd(k)}</li>`).join('');
- ov.appendChild(ul);
- }
- body.appendChild(ov);
- return wrap;
- }
-
- function cssSafe(v) {
- // Strip anything outside valid CSS value chars to prevent injection via
- // .impeccable/design.json values rendered into inline style strings.
- return String(v).replace(/[<>"'`\n]/g, '');
- }
-
- // --- Raw tab: minimal markdown renderer (subset) --------------------------
-
- function renderRawTab(body, md) {
- const wrap = document.createElement('div');
- wrap.className = 'md';
- wrap.innerHTML = renderMarkdown(md);
- body.appendChild(wrap);
- }
-
- function renderMarkdown(md) {
- const lines = md.split(/\r?\n/);
- const out = [];
- let i = 0;
- let inCode = false;
- let codeBuf = [];
- let paraBuf = [];
- let listBuf = []; // array of { indent, html }
- let listType = null; // 'ul' | 'ol'
-
- const flushPara = () => {
- if (paraBuf.length) {
- out.push(`<p>${inlineMd(paraBuf.join(' '))}</p>`);
- paraBuf = [];
- }
- };
- const flushList = () => {
- if (listBuf.length) {
- out.push(buildListHtml(listBuf, listType));
- listBuf = [];
- listType = null;
- }
- };
- const flushAll = () => { flushPara(); flushList(); };
-
- for (; i < lines.length; i++) {
- const line = lines[i];
-
- // Code fence
- const fence = line.match(/^```(\w*)\s*$/);
- if (fence) {
- if (!inCode) { flushAll(); inCode = true; codeBuf = []; }
- else {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- inCode = false;
- }
- continue;
- }
- if (inCode) { codeBuf.push(line); continue; }
-
- if (line.trim() === '') { flushAll(); continue; }
-
- const hr = line.match(/^\s*(?:---+|\*\*\*+)\s*$/);
- if (hr) { flushAll(); out.push('<hr />'); continue; }
-
- const heading = line.match(/^(#{1,4})\s+(.+)$/);
- if (heading) {
- flushAll();
- const lvl = heading[1].length;
- out.push(`<h${lvl}>${inlineMd(heading[2])}</h${lvl}>`);
- continue;
- }
-
- const bullet = line.match(/^(\s*)([-*])\s+(.+)$/);
- const ordered = line.match(/^(\s*)(\d+)\.\s+(.+)$/);
- if (bullet || ordered) {
- flushPara();
- const m = bullet || ordered;
- const indent = Math.floor(m[1].length / 2);
- const t = bullet ? 'ul' : 'ol';
- if (listType && listType !== t) flushList();
- listType = t;
- listBuf.push({ indent, html: inlineMd(m[3]) });
- continue;
- }
-
- paraBuf.push(line);
- }
- flushAll();
- if (inCode && codeBuf.length) {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- }
- return out.join('\n');
- }
-
- function buildListHtml(items, type) {
- // Nest by indent (one level deep is plenty for DESIGN.md).
- let html = `<${type}>`;
- let lastIndent = 0;
- for (const it of items) {
- if (it.indent > lastIndent) html += `<${type}>`;
- else if (it.indent < lastIndent) html += `</${type}>`.repeat(lastIndent - it.indent);
- html += `<li>${it.html}</li>`;
- lastIndent = it.indent;
- }
- html += `</${type}>`.repeat(lastIndent + 1);
- return html;
- }
-
- function inlineMd(text) {
- // Order matters: escape first, then re-inject tags.
- let s = escapeHtml(text);
- // Code spans
- s = s.replace(/`([^`]+)`/g, (_, code) => `<code>${code}</code>`);
- // Links [text](url)
- s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, t, u) => `<a href="${u}" target="_blank" rel="noopener noreferrer">${t}</a>`);
- // Bold
- s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
- // Italic (only single *…*, skip if inside bold already handled)
- s = s.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em>$2</em>');
- return s;
- }
-
- function highlightBold(text) {
- return inlineMd(text);
- }
-
- function escapeHtml(s) {
- return String(s)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
-
- function copyToClipboard(text) {
- if (!text) return;
- try {
- navigator.clipboard.writeText(text);
- showToast('Copied: ' + text);
- } catch { /* ignore */ }
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- function init() {
- try { history.scrollRestoration = 'manual'; } catch {}
- initHighlight();
- initAnnotOverlay();
- initBar();
- initActionPicker();
- initParamsPanel();
- initGlobalBar();
- initDesignPanel();
- document.addEventListener('mousemove', handleMouseMove, true);
- document.addEventListener('click', handleClick, true);
- document.addEventListener('keydown', handleKeyDown, true);
- connectSSE();
-
- // Check for an active session to resume (variant wrapper already in DOM after HMR)
- if (!resumeSession()) {
- console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
- // SvelteKit (and any framework that hydrates after HTML parse) may add
- // the variant wrapper AFTER init runs. Watch for it and retry resume
- // once it appears. Disconnect on first hit.
- const scout = new MutationObserver(() => {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) return;
- scout.disconnect();
- if (resumeSession()) {
- console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
- }
- });
- scout.observe(document.body, { childList: true, subtree: true });
- } else {
- console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
- }
- }
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
- } else {
- init();
- }
-})();
@@ -1,75 +0,0 @@
-#!/usr/bin/env node
-/**
- * Canonical durable completion acknowledgement for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function parseArgs(argv) {
- const out = { status: 'complete' };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';
- else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }
- else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function completeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help || !args.id) {
- console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);
- process.exit(args.help ? 0 : 1);
- }
-
- const serverInfo = readServerInfo();
- const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;
- if (serverResult?.ok) {
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const snapshot = store.getSnapshot(args.id, { includeCompleted: true });
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const event = args.status === 'discarded'
- ? { type: 'discarded', id: args.id }
- : args.status === 'agent_error'
- ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }
- : { type: 'complete', id: args.id };
- const snapshot = store.appendEvent(event);
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));
-}
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function completeThroughServer(info, args) {
- const type = args.status === 'discarded'
- ? 'discarded'
- : args.status === 'agent_error'
- ? 'error'
- : 'complete';
- try {
- const res = await fetch(`http://localhost:${info.port}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),
- });
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {
- completeCli();
-}
@@ -1,18 +0,0 @@
-export function completionTypeForAcceptResult(eventType, acceptResult) {
- if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';
- if (acceptResult?.handled === true) return 'complete';
- if (acceptResult?.mode === 'error') return 'error';
- return 'agent_done';
-}
-
-export function completionAckForAcceptResult(eventId, completionType, acceptResult) {
- const ack = { ok: true, type: completionType };
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) {
- ack.final = false;
- ack.requiresComplete = true;
- ack.nextCommand = `live-complete.mjs --id ${eventId}`;
- ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';
- }
- return ack;
-}
@@ -1,446 +0,0 @@
-/**
- * CLI helper: insert/remove the live variant mode script tag in the project's
- * main HTML entry point.
- *
- * On first live run, the agent generates `.impeccable/live/config.json`
- * with the project's insertion target (framework-specific). On
- * every subsequent run, this script handles insert/remove deterministically
- * with zero LLM involvement.
- *
- * Usage:
- * node live-inject.mjs --port PORT # Insert the live script tag
- * node live-inject.mjs --remove # Remove the live script tag
- * node live-inject.mjs --check # Check whether live config exists
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { resolveLiveConfigPath } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });
-const MARKER_OPEN_TEXT = 'impeccable-live-start';
-const MARKER_CLOSE_TEXT = 'impeccable-live-end';
-
-/**
- * Hard-excluded directory patterns. These are NEVER user-facing pages and
- * matching them would silently inject tracking scripts into third-party
- * code. The user cannot turn these off via config — they are the floor.
- */
-const HARD_EXCLUDES = [
- '**/node_modules/**',
- '**/.git/**',
-];
-
-export async function injectCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-inject.mjs [options]
-
-Insert or remove the live mode script tag in the project's HTML entry point.
-Reads configuration from .impeccable/live/config.json.
-
-Modes:
- --port PORT Insert script tag pointing at http://localhost:PORT/live.js
- --remove Remove the script tag (if present)
- --check Print whether .impeccable/live/config.json exists and its content
-
-Output (JSON):
- { ok, file, inserted|removed, config? }`);
- process.exit(0);
- }
-
- if (args.includes('--check')) {
- if (!fs.existsSync(CONFIG_PATH)) {
- console.log(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(0);
- }
- let cfg;
- try {
- cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- try {
- validateConfig(cfg);
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- console.log(JSON.stringify({ ok: true, config: cfg, path: CONFIG_PATH }));
- return;
- }
-
- // Load config
- if (!fs.existsSync(CONFIG_PATH)) {
- console.error(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(1);
- }
- const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- validateConfig(config);
-
- const resolvedFiles = resolveFiles(process.cwd(), config);
-
- if (args.includes('--remove')) {
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const detagged = removeTag(content, config.commentSyntax);
- const updated = revertCspMeta(detagged);
- if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- removed: detagged !== content,
- cspReverted: updated !== detagged,
- };
- });
- console.log(JSON.stringify({ ok: true, results }));
- return;
- }
-
- // Insert mode — need --port
- const portIdx = args.indexOf('--port');
- const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : NaN;
- if (!Number.isFinite(port)) {
- console.error(JSON.stringify({ ok: false, error: 'missing_port' }));
- process.exit(1);
- }
-
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
- const withTag = insertTag(withoutOld, config, port);
- if (withTag === withoutOld) {
- return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
- }
- const updated = patchCspMeta(withTag, port);
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- inserted: true,
- cspPatched: updated !== withTag,
- };
- });
- const anyInserted = results.some((r) => r.inserted);
- console.log(JSON.stringify({ ok: anyInserted, port, results }));
- if (!anyInserted) process.exit(1);
-}
-
-/**
- * Expand config.files (which may contain glob patterns) into a literal list
- * of existing file paths relative to rootDir. Literal entries pass through;
- * glob patterns are expanded via fs.globSync. HARD_EXCLUDES and config.exclude
- * are applied as filters. Duplicates are removed. Order is preserved by
- * first appearance.
- */
-export function resolveFiles(rootDir, config) {
- const patterns = config.files;
- const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
- const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
- const excludeRegexes = allExcludes.map(globToRegex);
-
- const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
- const isGlob = (s) => /[*?[]/.test(s);
-
- const seen = new Set();
- const out = [];
- for (const pat of patterns) {
- if (!isGlob(pat)) {
- // Literal path — include even if it doesn't exist yet; the caller
- // reports file_not_found per-entry. Exclude list doesn't apply to
- // explicit literal entries (user named it on purpose).
- if (!seen.has(pat)) {
- seen.add(pat);
- out.push(pat);
- }
- continue;
- }
- let matches;
- try {
- matches = fs.globSync(pat, { cwd: rootDir, withFileTypes: true });
- } catch {
- continue;
- }
- for (const ent of matches) {
- if (!ent.isFile || !ent.isFile()) continue;
- const abs = path.join(ent.parentPath || ent.path || rootDir, ent.name);
- const rel = path.relative(rootDir, abs).split(path.sep).join('/');
- if (isExcluded(rel)) continue;
- if (seen.has(rel)) continue;
- seen.add(rel);
- out.push(rel);
- }
- }
- return out;
-}
-
-/**
- * Convert a glob pattern to a RegExp. Supports:
- * ** → any number of path segments (including zero)
- * * → any chars except `/`
- * ? → any single char except `/`
- * Paths are normalized to forward slashes before matching.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- // ** — any number of segments, including zero. Handle the common
- // **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
- if (pattern[i + 2] === '/') {
- re += '(?:.*/)?';
- i += 3;
- } else {
- re += '.*';
- i += 2;
- }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Core operations
-// ---------------------------------------------------------------------------
-
-function validateConfig(cfg) {
- if (!cfg || typeof cfg !== 'object') throw new Error('config.json must be an object');
- if (!Array.isArray(cfg.files) || cfg.files.length === 0) {
- throw new Error('config.files (non-empty string array) required');
- }
- if (!cfg.files.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.files must contain only non-empty strings');
- }
- if (cfg.exclude !== undefined) {
- if (!Array.isArray(cfg.exclude)) {
- throw new Error('config.exclude, if present, must be a string array');
- }
- if (!cfg.exclude.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.exclude must contain only non-empty strings');
- }
- }
- if (typeof cfg.insertBefore !== 'string' && typeof cfg.insertAfter !== 'string') {
- throw new Error('config.insertBefore or config.insertAfter (string) required');
- }
- if (cfg.commentSyntax !== 'html' && cfg.commentSyntax !== 'jsx') {
- throw new Error("config.commentSyntax must be 'html' or 'jsx'");
- }
- if (cfg.cspChecked !== undefined && typeof cfg.cspChecked !== 'boolean') {
- throw new Error("config.cspChecked, if present, must be a boolean");
- }
-}
-
-function commentOpen(syntax) { return syntax === 'jsx' ? '{/*' : '<!--'; }
-function commentClose(syntax) { return syntax === 'jsx' ? '*/}' : '-->'; }
-
-function buildTagBlock(syntax, port) {
- const open = commentOpen(syntax);
- const close = commentClose(syntax);
- return (
- open + ' ' + MARKER_OPEN_TEXT + ' ' + close + '\n' +
- '<script src="http://localhost:' + port + '/live.js"></script>\n' +
- open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n'
- );
-}
-
-function insertTag(content, config, port) {
- const block = buildTagBlock(config.commentSyntax, port);
- // insertBefore: match the LAST occurrence. Anchors like `</body>` naturally
- // belong at the end, and the same literal can appear earlier in code blocks
- // within rendered documentation pages.
- if (config.insertBefore) {
- const idx = content.lastIndexOf(config.insertBefore);
- if (idx === -1) return content;
- return content.slice(0, idx) + block + content.slice(idx);
- }
- // insertAfter: match the FIRST occurrence — typical anchors like `<head>` or
- // `<body>` open near the top of the document.
- const idx = content.indexOf(config.insertAfter);
- if (idx === -1) return content;
- const after = idx + config.insertAfter.length;
- // Preserve a single trailing newline if the anchor didn't end with one
- const prefix = content[after] === '\n' ? content.slice(0, after + 1) : content.slice(0, after) + '\n';
- return prefix + block + content.slice(prefix.length);
-}
-
-/**
- * Remove the live script block. Matches either HTML or JSX comment markers
- * regardless of config (so stale tags from a wrong config can still be cleaned).
- *
- * Indent-preserving: captures any whitespace immediately preceding the opener
- * marker and re-emits it in place of the removed block. `insertTag` inserted
- * the block *after* the original line's indent and *before* the anchor (e.g.
- * `</body>`), which moved the indent onto the opener line and left the anchor
- * unindented. Replacing the whole block (plus its trailing newline) with just
- * the captured indent hands the indent back to the anchor that follows.
- */
-function removeTag(content, _syntax) {
- const patterns = [
- /([ \t]*)<!--\s*impeccable-live-start\s*-->[\s\S]*?<!--\s*impeccable-live-end\s*-->[ \t]*\n/,
- /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}[ \t]*\n/,
- ];
- for (const pat of patterns) {
- const next = content.replace(pat, '$1');
- if (next !== content) return next;
- }
- return content;
-}
-
-// ---------------------------------------------------------------------------
-// Content-Security-Policy meta-tag patcher
-//
-// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
-// the cross-origin load of /live.js (and the SSE/POST connection back to
-// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
-//
-// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
-// and stash the original `content` value in a `data-impeccable-csp-original`
-// attribute (base64) so revert is exact.
-//
-// On remove: detect the marker attribute, decode it, restore the original
-// content value verbatim, drop the marker.
-//
-// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
-// shared helpers) is NOT patched here — those need framework-specific config
-// edits and are handled via the existing detect-csp.mjs reference output.
-// Only the in-source meta-tag form gets the auto-patch.
-// ---------------------------------------------------------------------------
-
-const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
-
-function findCspMetaTags(content) {
- const out = [];
- const tagRe = /<meta\s+([^>]*?)\/?>/gis;
- let m;
- while ((m = tagRe.exec(content)) !== null) {
- const attrs = m[1];
- if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
- out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
- }
- return out;
-}
-
-function getAttr(attrs, name) {
- const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
- const m = attrs.match(re);
- return m ? { quote: m[1], value: m[2], full: m[0] } : null;
-}
-
-function appendOriginToDirective(csp, directive, origin) {
- const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
- const m = csp.match(re);
- if (m) {
- const tokens = m[4].trim().split(/\s+/);
- if (tokens.includes(origin)) return csp;
- return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
- }
- // Directive missing — add it. Use 'self' + origin so we don't inadvertently
- // narrow the policy compared to the default-src fallback (most users with
- // an explicit CSP have 'self' there).
- return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
-}
-
-export function patchCspMeta(content, port) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
- const origin = `http://localhost:${port}`;
-
- // Walk last-to-first so prior splices don't invalidate later indices.
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const attrs = tag.attrs;
- if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
- const contentAttr = getAttr(attrs, 'content');
- if (!contentAttr) continue;
-
- const original = contentAttr.value;
- let patched = original;
- patched = appendOriginToDirective(patched, 'script-src', origin);
- patched = appendOriginToDirective(patched, 'connect-src', origin);
- // The shader overlay during 'generating' creates a screenshot via
- // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
- // those. Add `blob:` so the overlay doesn't throw a CSP violation.
- patched = appendOriginToDirective(patched, 'img-src', 'blob:');
- if (patched === original) continue;
-
- const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
- const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
- // The tagRe captures any whitespace between the last attribute and the
- // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
- // a replace would land it BEFORE that trailing space, leaving a double
- // space inside attrs and clobbering the space before `/>`. Split off
- // the trailing whitespace, splice the marker into the attribute body,
- // and re-append the original trailing whitespace so a self-closing
- // `<meta … />` round-trips byte-for-byte.
- const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
- const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
- const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
- const newTag = tag.full.replace(attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-export function revertCspMeta(content) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
-
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
- if (!origAttr) continue;
- const contentAttr = getAttr(tag.attrs, 'content');
- if (!contentAttr) continue;
-
- let originalValue;
- try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
- catch { continue; }
-
- const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
- let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
- // Drop the marker attribute and any single space immediately preceding it.
- newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
- const newTag = tag.full.replace(tag.attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
- injectCli();
-}
-
-export { insertTag, removeTag, validateConfig, buildTagBlock };
-// patchCspMeta + revertCspMeta are exported above where they're defined.
@@ -1,200 +0,0 @@
-/**
- * CLI client for the live variant mode poll/reply protocol.
- *
- * Usage:
- * npx impeccable poll # Block until browser event, print JSON
- * npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
- * npx impeccable poll --reply <id> done # Reply "done" to event <id>
- * npx impeccable poll --reply <id> error "msg" # Reply with error
- */
-
-import { execFileSync } from 'node:child_process';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-// Node's built-in fetch (undici under the hood) enforces a 300s headers
-// timeout that can't be lowered per-request. We cap each request below
-// that ceiling and loop in `pollOnce` to synthesize a long poll without
-// depending on the standalone undici package.
-const PER_REQUEST_TIMEOUT_MS = 270_000;
-
-function readServerInfo() {
- const record = readLiveServerInfo(process.cwd());
- if (!record) {
- console.error('No running live server found. Start one with: npx impeccable live');
- process.exit(1);
- }
- return record.info;
-}
-
-export function buildPollReplyPayload(token, { id, type, message, file, data }) {
- return { token, id, type, message, file, data };
-}
-
-async function postReply(base, token, reply) {
- const res = await fetch(`${base}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(buildPollReplyPayload(token, reply)),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error || res.statusText);
- }
-}
-
-export async function pollCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable poll [options]
-
-Wait for a browser event from the live variant server, or reply to one.
-
-Modes:
- poll Block until a browser event arrives, print JSON
- poll --reply <id> done Reply "done" to event <id>
- poll --reply <id> error "msg" Reply with an error message
-
-Options:
- --timeout=MS Long-poll timeout in ms (default: 600000). Use the default unless the user asked to pause live; never use a short timeout to end the chat turn
- --help Show this help message`);
- process.exit(0);
- }
-
- const info = readServerInfo();
- const base = `http://localhost:${info.port}`;
-
- // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
- const replyIdx = args.indexOf('--reply');
- if (replyIdx !== -1) {
- const id = args[replyIdx + 1];
- const status = args[replyIdx + 2] || 'done';
- const fileIdx = args.indexOf('--file');
- const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
- // Message is any remaining positional arg that isn't a flag
- const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
-
- if (!id) {
- console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
- process.exit(1);
- }
-
- try {
- await postReply(base, info.token, { id, type: status, message, file: filePath });
-
- // Success — silent exit (agent doesn't need output for replies)
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Reply failed:', err.message);
- }
- process.exit(1);
- }
- return;
- }
-
- // Poll mode: block until browser event. Default 10 min. Node's built-in
- // fetch enforces a 300s headers timeout, so we loop in slices under that
- // ceiling and keep re-polling until we get a real event or the user's
- // total timeout runs out.
- const timeoutArg = args.find(a => a.startsWith('--timeout='));
- const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600000;
-
- const deadline = Date.now() + totalTimeout;
- let event;
- try {
- while (true) {
- const remaining = deadline - Date.now();
- if (remaining <= 0) {
- event = { type: 'timeout' };
- break;
- }
- const slice = Math.min(remaining, PER_REQUEST_TIMEOUT_MS);
- const res = await fetch(`${base}/poll?token=${info.token}&timeout=${slice}`);
-
- if (res.status === 401) {
- console.error('Authentication failed. The server token may have changed.');
- console.error('Try restarting: npx impeccable live stop && npx impeccable live');
- process.exit(1);
- }
-
- if (!res.ok) {
- console.error(`Poll failed: ${res.status} ${res.statusText}`);
- process.exit(1);
- }
-
- const next = await res.json();
- // Server-side timeout means no browser event arrived in this slice.
- // Loop and re-poll until we get a real event or we hit the user's
- // total deadline.
- if (next?.type === 'timeout' && Date.now() < deadline) continue;
- event = next;
- break;
- }
-
- // Auto-handle accept/discard via deterministic script
- if (event.type === 'accept' || event.type === 'discard') {
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const acceptScript = path.join(__dirname, 'live-accept.mjs');
- const scriptArgs = event.type === 'discard'
- ? ['--id', event.id, '--discard']
- : ['--id', event.id, '--variant', event.variantId];
- if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
- scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
- }
- try {
- const out = execFileSync(
- 'node',
- [acceptScript, ...scriptArgs],
- { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 }
- );
- event._acceptResult = JSON.parse(out.trim());
- } catch (err) {
- event._acceptResult = { handled: false, mode: 'error', error: err.message };
- }
-
- const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
- try {
- await postReply(base, info.token, {
- id: event.id,
- type: completionType,
- message: event._acceptResult?.error,
- file: event._acceptResult?.file,
- data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
- });
- } catch (err) {
- event._completionAck = { ok: false, error: err.message };
- }
- if (!event._completionAck) {
- event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
- }
- }
-
- // Second signal path: stderr banner in case the agent parses stdout
- // JSON but skips nested fields. One line is enough — the full checklist
- // is in reference/live.md.
- if (event._acceptResult?.carbonize === true) {
- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
- }
-
- // Print the event as JSON — the agent reads this from stdout
- console.log(JSON.stringify(event));
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Poll failed:', err.message);
- }
- process.exit(1);
- }
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
- pollCli();
-}
@@ -1,48 +0,0 @@
-#!/usr/bin/env node
-/**
- * Recover the next agent action from the durable live-session journal.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-
-function parseArgs(argv) {
- const out = { id: null };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function resumeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help) {
- console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });
- const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;
- if (!snapshot) {
- console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));
- return;
- }
-
- const pending = snapshot.pendingEvent || null;
- const nextAction = pending
- ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`
- : snapshot.phase === 'carbonize_required'
- ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`
- : snapshot.phase === 'accept_requested'
- ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`
- : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;
-
- console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {
- resumeCli();
-}
@@ -1,838 +0,0 @@
-#!/usr/bin/env node
-/**
- * Live variant mode server (self-contained, zero dependencies).
- *
- * Serves the browser script (/live.js), the detection overlay (/detect.js),
- * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
- * browser→server events. Agent communicates via HTTP long-poll (/poll).
- *
- * Usage:
- * node <scripts_path>/live-server.mjs # start
- * node <scripts_path>/live-server.mjs stop # stop + remove injected live.js tag
- * node <scripts_path>/live-server.mjs stop --keep-inject # stop only
- * node <scripts_path>/live-server.mjs --help
- */
-
-import http from 'node:http';
-import { randomUUID } from 'node:crypto';
-import { spawn, execFileSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import net from 'node:net';
-import { fileURLToPath } from 'node:url';
-import { parseDesignMd } from './design-parser.mjs';
-import { resolveContextDir } from './load-context.mjs';
-import { createLiveSessionStore } from './live-session-store.mjs';
-import {
- getDesignSidecarPath,
- getLiveAnnotationsDir,
- readLiveServerInfo,
- removeLiveServerInfo,
- resolveDesignSidecarPath,
- writeLiveServerInfo,
-} from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated
-// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
-// DESIGN.json fallback for existing projects.
-const CONTEXT_DIR = resolveContextDir(process.cwd());
-const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anyway
-const SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s
-
-// ---------------------------------------------------------------------------
-// Port detection
-// ---------------------------------------------------------------------------
-
-async function findOpenPort(start = 8400) {
- return new Promise((resolve) => {
- const srv = net.createServer();
- srv.listen(start, '127.0.0.1', () => {
- const port = srv.address().port;
- srv.close(() => resolve(port));
- });
- srv.on('error', () => resolve(findOpenPort(start + 1)));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Session state
-// ---------------------------------------------------------------------------
-
-const state = {
- token: null,
- port: null,
- sseClients: new Set(), // SSE response objects (server→browser push)
- pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
- pendingPolls: [], // agent poll callbacks waiting for browser events
- exitTimer: null,
- sessionDir: null, // per-session tmp dir for annotation screenshots
- sessionStore: null,
- leaseTimer: null,
-};
-
-// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;
-// cap at 10 MB to guard against runaway writes from a misbehaving client.
-const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
-
-function enqueueEvent(event) {
- if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;
- state.pendingEvents.push({ event, leaseUntil: 0 });
- flushPendingPolls();
-}
-
-function restorePendingEventsFromStore() {
- if (!state.sessionStore) return;
- for (const snapshot of state.sessionStore.listActiveSessions()) {
- if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);
- }
-}
-
-function findAvailablePendingEvent(now = Date.now()) {
- return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);
-}
-
-function leaseEvent(entry, leaseMs) {
- if (!entry.event?.id) {
- const idx = state.pendingEvents.indexOf(entry);
- if (idx !== -1) state.pendingEvents.splice(idx, 1);
- return entry.event;
- }
- entry.leaseUntil = Date.now() + leaseMs;
- return entry.event;
-}
-
-function acknowledgePendingEvent(id) {
- if (!id) return false;
- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);
- if (idx === -1) return false;
- state.pendingEvents.splice(idx, 1);
- scheduleLeaseFlush();
- return true;
-}
-
-function scheduleLeaseFlush() {
- if (state.leaseTimer) {
- clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- }
- if (state.pendingPolls.length === 0) return;
- const now = Date.now();
- const nextLeaseUntil = state.pendingEvents
- .map((entry) => entry.leaseUntil || 0)
- .filter((leaseUntil) => leaseUntil > now)
- .sort((a, b) => a - b)[0];
- if (!nextLeaseUntil) return;
- state.leaseTimer = setTimeout(() => {
- state.leaseTimer = null;
- flushPendingPolls();
- }, Math.max(0, nextLeaseUntil - now));
-}
-
-function flushPendingPolls() {
- while (state.pendingPolls.length > 0) {
- const entry = findAvailablePendingEvent();
- if (!entry) {
- scheduleLeaseFlush();
- return;
- }
- const poll = state.pendingPolls.shift();
- poll.resolve(leaseEvent(entry, poll.leaseMs));
- }
- scheduleLeaseFlush();
-}
-
-/** Push a message to all connected SSE clients. */
-function broadcast(msg) {
- const data = 'data: ' + JSON.stringify(msg) + '\n\n';
- for (const res of state.sseClients) {
- try { res.write(data); } catch { /* client gone */ }
- }
-}
-
-// ---------------------------------------------------------------------------
-// Load scripts
-// ---------------------------------------------------------------------------
-
-function loadBrowserScripts() {
- // Detection script: prefer the skill-bundled detector, then fall back to
- // source/npm package locations for local development and older installs.
- // This one IS cached — detect.js rarely changes during a session.
- const detectPaths = [
- path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(process.cwd(), 'node_modules', 'impeccable', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- ];
- let detectScript = '';
- for (const p of detectPaths) {
- try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
- }
-
- // live-browser.js: DO NOT cache. Return the path so the /live.js handler
- // can re-read on every request. Editing the browser script during iteration
- // should land on the next tab reload, not require a server restart.
- const sessionPath = path.join(__dirname, 'live-browser-session.js');
- const livePath = path.join(__dirname, 'live-browser.js');
- for (const p of [sessionPath, livePath]) {
- if (!fs.existsSync(p)) {
- process.stderr.write('Error: live browser script not found at ' + p + '\n');
- process.exit(1);
- }
- }
-
- return { detectScript, sessionPath, livePath };
-}
-
-function hasProjectContext() {
- // PRODUCT.md carries brand voice / anti-references — that's what determines
- // whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
- // concern, surfaced by the design panel's own empty state. Legacy
- // .impeccable.md is auto-migrated to PRODUCT.md by load-context.mjs.
- try {
- fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
- return true;
- } catch { return false; }
-}
-
-function statOrNull(filePath) {
- try { return fs.statSync(filePath); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// Validation (inline — no external import needed for self-contained script)
-// ---------------------------------------------------------------------------
-
-const VISUAL_ACTIONS = [
- 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
- 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
-];
-
-// Browser generates ids via crypto.randomUUID().slice(0, 8) (8 hex chars)
-// and variantIds via String(small integer). Restrict to those shapes so
-// any value that reaches a downstream child_process or DOM selector is
-// inert by construction.
-const ID_PATTERN = /^[0-9a-f]{8}$/;
-const VARIANT_ID_PATTERN = /^[0-9]{1,3}$/;
-
-function isValidId(v) { return typeof v === 'string' && ID_PATTERN.test(v); }
-function isValidVariantId(v) { return typeof v === 'string' && VARIANT_ID_PATTERN.test(v); }
-
-function validateEvent(msg) {
- if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
- switch (msg.type) {
- case 'generate':
- if (!isValidId(msg.id)) return 'generate: missing or malformed id';
- if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
- if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
- if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
- // Optional annotation fields (all-or-nothing: if any present, all must be well-formed).
- if (msg.screenshotPath !== undefined && typeof msg.screenshotPath !== 'string') return 'generate: screenshotPath must be string';
- if (msg.comments !== undefined && !Array.isArray(msg.comments)) return 'generate: comments must be array';
- if (msg.strokes !== undefined && !Array.isArray(msg.strokes)) return 'generate: strokes must be array';
- return null;
- case 'accept':
- if (!isValidId(msg.id)) return 'accept: missing or malformed id';
- if (!isValidVariantId(msg.variantId)) return 'accept: missing or malformed variantId';
- if (msg.paramValues !== undefined) {
- if (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues)) {
- return 'accept: paramValues must be an object';
- }
- }
- return null;
- case 'discard':
- return isValidId(msg.id) ? null : 'discard: missing or malformed id';
- case 'checkpoint':
- if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';
- if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';
- if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {
- return 'checkpoint: paramValues must be an object';
- }
- return null;
- case 'exit':
- return null;
- case 'prefetch':
- if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return 'prefetch: missing pageUrl';
- return null;
- default:
- return 'Unknown event type: ' + msg.type;
- }
-}
-
-// ---------------------------------------------------------------------------
-// HTTP request handler
-// ---------------------------------------------------------------------------
-
-function createRequestHandler({ detectScript, sessionPath, livePath }) {
- return (req, res) => {
- const url = new URL(req.url, `http://localhost:${state.port}`);
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
- if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
-
- const p = url.pathname;
-
- // --- Scripts ---
- if (p === '/live.js') {
- // Re-read from disk each request so edits to live-browser.js land on
- // the next tab reload. No-store headers prevent browser caching across
- // sessions — during iteration, a cached old script silently breaks
- // every subsequent session.
- let sessionScript;
- let liveScript;
- try {
- sessionScript = fs.readFileSync(sessionPath, 'utf-8');
- liveScript = fs.readFileSync(livePath, 'utf-8');
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'text/plain' });
- res.end('Error reading live browser scripts: ' + err.message);
- return;
- }
- const body =
- `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
- `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
- sessionScript + '\n' +
- liveScript;
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
- 'Pragma': 'no-cache',
- });
- res.end(body);
- return;
- }
- if (p === '/detect.js' || p === '/') {
- if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
- res.writeHead(200, { 'Content-Type': 'application/javascript' });
- res.end(detectScript);
- return;
- }
-
- // --- Vendored modern-screenshot (UMD build) ---
- // Lazy-loaded by live.js when the user clicks Go; exposes
- // window.modernScreenshot.domToBlob(...) for capture.
- if (p === '/modern-screenshot.js') {
- const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
- try {
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'public, max-age=31536000, immutable',
- });
- res.end(fs.readFileSync(vendorPath));
- } catch {
- res.writeHead(404); res.end('Vendor script not found');
- }
- return;
- }
-
- // --- Annotation upload (browser → server, raw PNG body) ---
- // Client generates the eventId, POSTs the PNG, then POSTs the generate
- // event with screenshotPath already set. Keeps bytes out of the SSE/poll
- // bridge and preserves the "one shot from the user's POV" UX.
- if (p === '/annotation' && req.method === 'POST') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const eventId = url.searchParams.get('eventId');
- if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid eventId' }));
- return;
- }
- if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
- res.writeHead(415, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
- return;
- }
- if (!state.sessionDir) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Session dir unavailable' }));
- return;
- }
- const chunks = [];
- let total = 0;
- let aborted = false;
- req.on('data', (c) => {
- if (aborted) return;
- total += c.length;
- if (total > MAX_ANNOTATION_BYTES) {
- aborted = true;
- res.writeHead(413, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Payload too large' }));
- req.destroy();
- return;
- }
- chunks.push(c);
- });
- req.on('end', () => {
- if (aborted) return;
- const absPath = path.join(state.sessionDir, eventId + '.png');
- try {
- fs.writeFileSync(absPath, Buffer.concat(chunks));
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Write failed: ' + err.message }));
- return;
- }
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true, path: absPath }));
- });
- req.on('error', () => {
- if (!aborted) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Upload failed' }));
- }
- });
- return;
- }
-
- // --- Health ---
- if (p === '/status') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
- const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok',
- port: state.port,
- connectedClients: state.sseClients.size,
- pendingEvents: state.pendingEvents.map((entry) => ({
- id: entry.event?.id,
- type: entry.event?.type,
- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),
- leaseUntil: entry.leaseUntil || null,
- })),
- activeSessions: sessions,
- }));
- return;
- }
-
- if (p === '/health') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok', port: state.port, mode: 'variant',
- hasProjectContext: hasProjectContext(),
- connectedClients: state.sseClients.size,
- }));
- return;
- }
-
- // --- Design system (unified v2 response) + raw ---
- // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json
- // sidecar when present. Panel merges them:
- // { present, parsed, sidecar, hasMd, hasSidecar,
- // mdNewerThanJson, parseError?, sidecarError? }
- // - parsed: output of parseDesignMd (frontmatter
- // + six canonical sections) when DESIGN.md exists.
- // - sidecar: .impeccable/design.json contents when present.
- // Expected shape: schemaVersion 2, carrying
- // extensions + components + narrative.
- // /design-system/raw returns DESIGN.md markdown verbatim
- if (p === '/design-system.json' || p === '/design-system/raw') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
-
- const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
- const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
- const mdStat = statOrNull(mdPath);
- const jsonStat = statOrNull(jsonPath);
-
- if (p === '/design-system/raw') {
- if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
- res.end(fs.readFileSync(mdPath, 'utf-8'));
- return;
- }
-
- if (!mdStat && !jsonStat) {
- res.writeHead(404, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ present: false }));
- return;
- }
-
- const response = {
- present: true,
- hasMd: !!mdStat,
- hasSidecar: !!jsonStat,
- mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
- };
-
- if (mdStat) {
- try {
- response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
- } catch (err) {
- response.parseError = err.message;
- }
- }
-
- if (jsonStat) {
- try {
- response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
- } catch (err) {
- response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;
- }
- }
-
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(response));
- return;
- }
-
- // --- Source file (no-HMR fallback) ---
- if (p === '/source') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const filePath = url.searchParams.get('path');
- if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
- const absPath = path.resolve(process.cwd(), filePath);
- if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
- let content;
- try { content = fs.readFileSync(absPath, 'utf-8'); }
- catch { res.writeHead(404); res.end('File not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
- res.end(content);
- return;
- }
-
- // --- SSE: server→browser push (replaces WebSocket) ---
- if (p === '/events' && req.method === 'GET') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- 'Connection': 'keep-alive',
- });
- res.write('data: ' + JSON.stringify({
- type: 'connected',
- hasProjectContext: hasProjectContext(),
- }) + '\n\n');
-
- state.sseClients.add(res);
- clearTimeout(state.exitTimer);
-
- // Keepalive: SSE comment every 30s prevents silent connection drops.
- const heartbeat = setInterval(() => {
- try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
- }, SSE_HEARTBEAT_INTERVAL);
-
- req.on('close', () => {
- clearInterval(heartbeat);
- state.sseClients.delete(res);
- if (state.sseClients.size === 0) {
- clearTimeout(state.exitTimer);
- state.exitTimer = setTimeout(() => {
- if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
- }, 8000);
- }
- });
- return;
- }
-
- // --- Browser→server events (replaces WebSocket messages) ---
- if (p === '/events' && req.method === 'POST') {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const error = validateEvent(msg);
- if (error) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error }));
- return;
- }
- if (state.sessionStore && msg.id) {
- try {
- state.sessionStore.appendEvent(msg);
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
- return;
- }
- }
- if (msg.type !== 'checkpoint') enqueueEvent(msg);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
- return;
- }
-
- // --- Stop ---
- if (p === '/stop') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.end('stopping');
- shutdown();
- return;
- }
-
- // --- Agent poll ---
- if (p === '/poll' && req.method === 'GET') {
- handlePollGet(req, res, url);
- return;
- }
- if (p === '/poll' && req.method === 'POST') {
- handlePollPost(req, res);
- return;
- }
-
- res.writeHead(404); res.end('Not found');
- };
-}
-
-// ---------------------------------------------------------------------------
-// Agent poll endpoints (unchanged from WS version)
-// ---------------------------------------------------------------------------
-
-function handlePollGet(req, res, url) {
- const token = url.searchParams.get('token');
- if (token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
- const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
- const available = findAvailablePendingEvent();
- if (available) {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(leaseEvent(available, leaseMs)));
- return;
- }
- const poll = { resolve, leaseMs };
- const timer = setTimeout(() => {
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ type: 'timeout' }));
- }, timeout);
- function resolve(event) {
- clearTimeout(timer);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(event));
- }
- state.pendingPolls.push(poll);
- scheduleLeaseFlush();
- req.on('close', () => {
- clearTimeout(timer);
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- });
-}
-
-function handlePollPost(req, res) {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- acknowledgePendingEvent(msg.id);
- if (state.sessionStore && msg.id) {
- try {
- const eventType = msg.type === 'discard' || msg.type === 'discarded'
- ? 'discarded'
- : msg.type === 'complete'
- ? 'complete'
- : msg.type === 'error'
- ? 'agent_error'
- : 'agent_done';
- state.sessionStore.appendEvent({
- type: eventType,
- id: msg.id,
- file: msg.file,
- message: msg.message,
- carbonize: msg.data?.carbonize === true,
- });
- } catch { /* keep reply path best-effort; browser still needs SSE */ }
- }
- flushPendingPolls();
- // Forward the reply to the browser via SSE
- broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Lifecycle
-// ---------------------------------------------------------------------------
-
-let httpServer = null;
-
-function shutdown() {
- removeLiveServerInfo(process.cwd());
- if (state.leaseTimer) clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- if (state.sessionDir) {
- try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}
- }
- for (const res of state.sseClients) { try { res.end(); } catch {} }
- state.sseClients.clear();
- for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });
- state.pendingPolls.length = 0;
- if (httpServer) httpServer.close();
- process.exit(0);
-}
-
-// ---------------------------------------------------------------------------
-// Main
-// ---------------------------------------------------------------------------
-
-const args = process.argv.slice(2);
-
-if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-server.mjs [options]
-
-Start the live variant mode server (zero dependencies).
-
-Commands:
- (default) Start the server (foreground)
- stop Stop the server and remove the injected live.js script tag
- stop --keep-inject Stop the server only (leave the script tag in the HTML entry)
-
-Options:
- --background Start detached, print connection JSON to stdout, then exit
- --port=PORT Use a specific port (default: auto-detect starting at 8400)
- --keep-inject Only with stop: skip live-inject.mjs --remove
- --help Show this help
-
-Endpoints:
- /live.js Browser script (element picker + variant cycling)
- /detect.js Detection overlay (backwards compatible)
- /modern-screenshot.js Vendored modern-screenshot UMD build (lazy-loaded by live.js)
- /annotation POST raw image/png to stage a variant screenshot
- /events SSE stream (server→browser) + POST (browser→server)
- /poll Long-poll for agent CLI
- /source Raw source file reader (no-HMR fallback)
- /status Durable recovery status (token-protected)
- /health Health check`);
- process.exit(0);
-}
-
-if (args.includes('stop')) {
- const keepInject = args.includes('--keep-inject');
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);
- if (res.ok) console.log(`Stopped live server on port ${info.port}.`);
- } catch {
- console.log('No running live server found.');
- }
- if (!keepInject) {
- const injectPath = path.join(__dirname, 'live-inject.mjs');
- try {
- const out = execFileSync(process.execPath, [injectPath, '--remove'], {
- encoding: 'utf-8',
- cwd: process.cwd(),
- });
- const line = out.trim().split('\n').filter(Boolean).pop();
- if (line) {
- try {
- const j = JSON.parse(line);
- if (j.removed === true) {
- console.log(`Removed live script tag from ${j.file}.`);
- }
- } catch {
- /* ignore non-JSON lines */
- }
- }
- } catch (err) {
- const detail = err.stderr?.toString?.().trim?.()
- || err.stdout?.toString?.().trim?.()
- || err.message
- || String(err);
- console.warn(`Note: could not remove live script tag (${detail.split('\n')[0]})`);
- }
- }
- process.exit(0);
-}
-
-// --background: spawn a detached child server, wait for it to be ready,
-// print the connection JSON, then exit. This keeps the startup command
-// simple (no shell backgrounding or chained commands).
-if (args.includes('--background')) {
- const childArgs = args.filter(a => a !== '--background');
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), ...childArgs], {
- detached: true,
- stdio: 'ignore',
- cwd: process.cwd(),
- });
- child.unref();
-
- // Poll for the PID file (the child writes it once the HTTP server is listening).
- const deadline = Date.now() + 10_000;
- while (Date.now() < deadline) {
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- if (info.pid !== process.pid) {
- // Output JSON so the agent can read port + token from stdout.
- console.log(JSON.stringify(info));
- process.exit(0);
- }
- } catch { /* not ready yet */ }
- await new Promise(r => setTimeout(r, 200));
- }
- console.error('Timed out waiting for live server to start.');
- process.exit(1);
-}
-
-// Check for existing session
-const existingRecord = readLiveServerInfo(process.cwd());
-if (existingRecord?.info) {
- const existing = existingRecord.info;
- try {
- process.kill(existing.pid, 0);
- console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
- console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');
- process.exit(1);
- } catch {
- try { fs.unlinkSync(existingRecord.path); } catch {}
- }
-}
-
-state.token = randomUUID();
-state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });
-restorePendingEventsFromStore();
-const portArg = args.find(a => a.startsWith('--port='));
-state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
-// Annotation screenshots live in the project root so the agent's Read tool
-// doesn't trip a per-file permission prompt. Sessioned by token so concurrent
-// projects (or quick restarts) don't collide.
-const annotRoot = getLiveAnnotationsDir(process.cwd());
-fs.mkdirSync(annotRoot, { recursive: true });
-state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));
-
-const { detectScript, sessionPath, livePath } = loadBrowserScripts();
-httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));
-
-httpServer.listen(state.port, '127.0.0.1', () => {
- writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });
- const url = `http://localhost:${state.port}`;
- console.log(`\nImpeccable live server running on ${url}`);
- console.log(`Token: ${state.token}\n`);
- console.log(`Inject: <script src="${url}/live.js"><\/script>`);
- console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
-});
-
-process.on('SIGINT', shutdown);
-process.on('SIGTERM', shutdown);
@@ -1,254 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';
-
-const COMPLETED_PHASES = new Set(['completed', 'discarded']);
-
-export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {
- const rootDir = getLiveSessionsDir(cwd);
- const legacyRootDir = getLegacyLiveSessionsDir(cwd);
- fs.mkdirSync(rootDir, { recursive: true });
- const snapshotCache = new Map();
-
- function loadCachedOrRebuild(id) {
- const cached = snapshotCache.get(id);
- if (cached) return cached;
- const journalPath = getReadableJournalPath(id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- return rebuilt;
- }
-
- function getReadableJournalPath(id) {
- const primary = getJournalPath(rootDir, id);
- if (fs.existsSync(primary)) return primary;
- const legacy = getJournalPath(legacyRootDir, id);
- if (fs.existsSync(legacy)) return legacy;
- return primary;
- }
-
- return {
- rootDir,
- legacyRootDir,
- appendEvent(event) {
- const normalized = normalizeEvent(event, sessionId);
- const journalPath = getJournalPath(rootDir, normalized.id);
- const snapshotPath = getSnapshotPath(rootDir, normalized.id);
- const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);
- if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {
- fs.copyFileSync(legacyJournalPath, journalPath);
- }
- const prior = loadCachedOrRebuild(normalized.id);
- const seq = prior.nextSeq;
- const entry = {
- seq,
- id: normalized.id,
- type: normalized.type,
- ts: new Date().toISOString(),
- event: normalized,
- };
- fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');
- const next = applyEvent(prior.snapshot, entry, prior.diagnostics);
- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });
- writeSnapshot(snapshotPath, next);
- return next;
- },
- getSnapshot(id = sessionId, opts = {}) {
- if (!id) throw new Error('session id required');
- const journalPath = getReadableJournalPath(id);
- const snapshotPath = getSnapshotPath(rootDir, id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- writeSnapshot(snapshotPath, rebuilt.snapshot);
- if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;
- return rebuilt.snapshot;
- },
- listActiveSessions() {
- const ids = new Set();
- for (const dir of [legacyRootDir, rootDir]) {
- if (!fs.existsSync(dir)) continue;
- for (const name of fs.readdirSync(dir)) {
- if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));
- }
- }
- return [...ids]
- .sort()
- .map((id) => this.getSnapshot(id))
- .filter(Boolean);
- },
- };
-}
-
-function normalizeEvent(event, fallbackId) {
- if (!event || typeof event !== 'object') throw new Error('event object required');
- const id = event.id || fallbackId;
- if (!id || typeof id !== 'string') throw new Error('event id required');
- if (!event.type || typeof event.type !== 'string') throw new Error('event type required');
- return { ...event, id };
-}
-
-function getJournalPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.jsonl');
-}
-
-function getSnapshotPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.snapshot.json');
-}
-
-function safeSessionId(id) {
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);
- return id;
-}
-
-function baseSnapshot(id) {
- return {
- id,
- phase: 'new',
- pageUrl: null,
- sourceFile: null,
- expectedVariants: 0,
- arrivedVariants: 0,
- visibleVariant: null,
- paramValues: {},
- pendingEventSeq: null,
- pendingEvent: null,
- deliveryLease: null,
- checkpointRevision: 0,
- activeOwner: null,
- sourceMarkers: {},
- fallbackMode: null,
- annotationArtifacts: [],
- diagnostics: [],
- updatedAt: null,
- };
-}
-
-function rebuildSnapshotFromJournal(journalPath, id) {
- let snapshot = baseSnapshot(id);
- const diagnostics = [];
- let nextSeq = 1;
- if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };
-
- const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- if (!line.trim()) continue;
- try {
- const entry = JSON.parse(line);
- if (!entry || typeof entry !== 'object') throw new Error('entry is not object');
- if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);
- snapshot = applyEvent(snapshot, entry);
- } catch (err) {
- diagnostics.push({
- error: 'journal_parse_failed',
- line: i + 1,
- message: err.message,
- });
- }
- }
- snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];
- return { snapshot, diagnostics, nextSeq };
-}
-
-function applyEvent(snapshot, entry, inheritedDiagnostics = []) {
- const event = entry.event || entry;
- const next = {
- ...snapshot,
- paramValues: { ...(snapshot.paramValues || {}) },
- sourceMarkers: { ...(snapshot.sourceMarkers || {}) },
- annotationArtifacts: [...(snapshot.annotationArtifacts || [])],
- diagnostics: [...(snapshot.diagnostics || [])],
- updatedAt: entry.ts || new Date().toISOString(),
- };
-
- if (inheritedDiagnostics.length && next.diagnostics.length === 0) {
- next.diagnostics = [...inheritedDiagnostics];
- }
-
- switch (event.type) {
- case 'generate':
- next.phase = 'generate_requested';
- next.pageUrl = event.pageUrl ?? next.pageUrl;
- next.expectedVariants = event.count ?? next.expectedVariants;
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });
- break;
- case 'variants_ready':
- case 'agent_done':
- next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';
- next.sourceFile = event.file ?? next.sourceFile;
- next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- if (event.carbonize === true) {
- next.diagnostics.push({
- error: 'carbonize_cleanup_required',
- file: event.file || null,
- message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',
- });
- }
- break;
- case 'checkpoint':
- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {
- next.phase = event.phase ?? next.phase;
- next.checkpointRevision = event.revision ?? next.checkpointRevision;
- next.activeOwner = event.owner ?? next.activeOwner;
- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;
- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- } else {
- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });
- }
- break;
- case 'accept':
- case 'accept_intent':
- next.phase = 'accept_requested';
- next.visibleVariant = Number(event.variantId ?? next.visibleVariant);
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discard':
- next.phase = 'discard_requested';
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discarded':
- next.phase = 'discarded';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'complete':
- next.phase = 'completed';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'agent_error':
- next.phase = 'agent_error';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });
- break;
- default:
- next.diagnostics.push({ error: 'unknown_event_type', type: event.type });
- break;
- }
- return next;
-}
-
-function toPendingEvent(event) {
- const pending = { ...event };
- delete pending.token;
- return pending;
-}
-
-function upsertArtifact(artifacts, artifact) {
- if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {
- artifacts.push(artifact);
- }
-}
-
-function writeSnapshot(snapshotPath, snapshot) {
- fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');
-}
@@ -1,47 +0,0 @@
-#!/usr/bin/env node
-/**
- * Print durable recovery status for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function fetchServerStatus(info) {
- if (!info) return null;
- try {
- const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-export async function statusCli() {
- const info = readServerInfo();
- const server = await fetchServerStatus(info);
- const store = createLiveSessionStore({ cwd: process.cwd() });
- const activeSessions = store.listActiveSessions();
- const payload = {
- liveServer: server ? {
- status: server.status,
- port: server.port,
- connectedClients: server.connectedClients,
- pendingEvents: server.pendingEvents,
- } : null,
- activeSessions: server?.activeSessions || activeSessions,
- recoveryHint: server
- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'
- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',
- };
- console.log(JSON.stringify(payload, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {
- statusCli();
-}
@@ -1,632 +0,0 @@
-/**
- * CLI helper: find an element in source and wrap it in a variant container.
- *
- * Usage:
- * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
- *
- * Searches project files for the element matching the query (class name, ID, or
- * text snippet), wraps it with the variant scaffolding, and prints the file path
- * + line range where the agent should insert variant HTML.
- *
- * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-export async function wrapCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable wrap [options]
-
-Find an element in source and wrap it in a variant container.
-
-Required:
- --id ID Session ID for the variant wrapper
- --count N Number of expected variants (1-8)
-
-Element identification (at least one required):
- --element-id ID HTML id attribute of the element
- --classes A,B,C Comma-separated CSS class names
- --tag TAG Tag name (div, section, etc.)
- --query TEXT Fallback: raw text to search for
-
-Optional:
- --file PATH Source file to search in (skips auto-detection)
- --text TEXT Picked element's textContent. Used to disambiguate when
- classes/tag match multiple sibling elements (e.g. a list
- of <Card>s with the same className). Pass the first ~80
- chars of event.element.textContent.
- --help Show this help message
-
-Output (JSON):
- { file, startLine, endLine, insertLine, commentSyntax }
-
-The agent should insert variant HTML at insertLine.`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const count = parseInt(argVal(args, '--count') || '3');
- const elementId = argVal(args, '--element-id');
- const classes = argVal(args, '--classes');
- const tag = argVal(args, '--tag');
- const query = argVal(args, '--query');
- const filePath = argVal(args, '--file');
- const text = argVal(args, '--text');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!elementId && !classes && !query) {
- console.error('Need at least one of: --element-id, --classes, --query');
- process.exit(1);
- }
-
- // Build search queries in priority order (most specific first)
- const queries = buildSearchQueries(elementId, classes, tag, query);
-
- const genOpts = { cwd: process.cwd() };
-
- // Find the source file. Generated files are excluded from auto-search so we
- // don't silently write variants into a file the next build will wipe.
- let targetFile = filePath;
- let matchedQuery = null;
- if (!targetFile) {
- for (const q of queries) {
- targetFile = findFileWithQuery(q, process.cwd(), genOpts);
- if (targetFile) { matchedQuery = q; break; }
- }
- if (!targetFile) {
- // Nothing in source. Did the element show up in a generated file? That
- // tells the agent "fall back to the agent-driven flow" vs "element just
- // doesn't exist in this project."
- let generatedHit = null;
- for (const q of queries) {
- generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
- if (generatedHit) break;
- }
- if (generatedHit) {
- console.error(JSON.stringify({
- error: 'element_not_in_source',
- fallback: 'agent-driven',
- generatedMatch: path.relative(process.cwd(), generatedHit),
- hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
- }));
- } else {
- console.error(JSON.stringify({
- error: 'element_not_found',
- fallback: 'agent-driven',
- hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
- }));
- }
- process.exit(1);
- }
- } else {
- if (isGeneratedFile(targetFile, genOpts)) {
- console.error(JSON.stringify({
- error: 'file_is_generated',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
- hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- matchedQuery = queries[0];
- }
-
- const content = fs.readFileSync(targetFile, 'utf-8');
- const lines = content.split('\n');
-
- // Find the element, trying each query in priority order. When `--text` is
- // supplied, collect every candidate the queries surface and disambiguate
- // by the picked element's textContent. Without `--text`, fall back to the
- // legacy first-match behavior so unmodified callers keep working.
- let match = null;
- if (text) {
- const candidates = [];
- for (const q of queries) {
- const all = findAllElements(lines, q, tag);
- for (const c of all) {
- if (!candidates.some((x) => x.startLine === c.startLine)) {
- candidates.push(c);
- }
- }
- // Once a more-specific query (ID, full className combo) yielded a unique
- // result, stop — falling through to the loose tag+single-class query
- // would readmit the siblings we just disambiguated past.
- if (candidates.length === 1) break;
- }
- if (candidates.length === 0) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- if (candidates.length === 1) {
- match = candidates[0];
- } else {
- const filtered = filterByText(candidates, lines, text);
- if (filtered.length === 1) {
- match = filtered[0];
- } else if (filtered.length === 0) {
- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the
- // browser-side textContent doesn't appear literally in source. Fall
- // back to first-match rather than refusing — this is the same
- // behavior unmodified callers see, just preserved.
- match = candidates[0];
- } else {
- // Multiple candidates ALSO match the text. Truly ambiguous — refuse
- // rather than pick wrong, and hand the agent the candidate locations
- // so it can disambiguate by reading the file.
- console.error(JSON.stringify({
- error: 'element_ambiguous',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), targetFile),
- candidates: filtered.map((c) => ({
- startLine: c.startLine + 1,
- endLine: c.endLine + 1,
- })),
- hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- }
- } else {
- for (const q of queries) {
- match = findElement(lines, q, tag);
- if (match) break;
- }
- if (!match) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- }
-
- const { startLine, endLine } = match;
- const commentSyntax = detectCommentSyntax(targetFile);
- const styleMode = detectStyleMode(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- const indent = lines[startLine].match(/^(\s*)/)[1];
-
- // Extract the original element. Reindent under the wrapper while preserving
- // the relative depth between lines — `l.trimStart()` would strip ALL leading
- // whitespace and collapse e.g. `<aside>`/` <h1>`/`</aside>` (6/8/6 spaces)
- // to a single uniform indent, so on accept/discard the round-trip restores
- // the inner element at its parent's depth instead of nested inside it.
- // Strip only the COMMON minimum leading whitespace across the picked lines;
- // `deindentContent` on the accept side already mirrors this convention.
- const originalLines = lines.slice(startLine, endLine + 1);
- const originalBaseIndent = minLeadingSpaces(originalLines);
- const reindentOriginal = (extra) => originalLines
- .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
- .join('\n');
- const originalIndented = reindentOriginal(' ');
-
- // Wrapper attributes differ by syntax. HTML allows plain string attrs;
- // JSX requires object-literal style and parses string attrs as HTML (which
- // either type-errors or renders a literal CSS string).
- const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
-
- // JSX/TSX guard: the picked element occupies a single JSX child slot
- // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
- // any other expression position). Replacing it with `comment + <div> +
- // comment` yields three adjacent siblings — invalid JSX. We can't use a
- // Fragment `<></>` either: parents that clone children (Radix `asChild`,
- // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
- // they try to pass an `id` through.
- //
- // Solution: keep the wrapper `<div>` as the single JSX-slot child and
- // tuck both marker comments INSIDE it. accept/discard then expands its
- // replacement range to include the wrapper's `<div>` open / close lines
- // so the entire scaffold gets removed cleanly.
- const wrapperLines = isJsx ? [
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- reindentOriginal(' '),
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- indent + '</div>',
- ] : [
- indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- originalIndented,
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + '</div>',
- indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- ];
-
- // Replace the original element with the wrapper
- const newLines = [
- ...lines.slice(0, startLine),
- ...wrapperLines,
- ...lines.slice(endLine + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- // Calculate insert line (the "insert below this line" comment).
- // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
- // the insert marker (HTML: start-comment + outer-div + Original-comment +
- // original-div + content + close-original-div; JSX: outer-div +
- // start-comment + Original-comment + original-div + content +
- // close-original-div). Multi-line originals push the marker by their
- // extra line count.
- const insertLine = startLine + 6 + (originalLines.length - 1);
-
- console.log(JSON.stringify({
- file: path.relative(process.cwd(), targetFile),
- startLine: startLine + 1, // 1-indexed for the agent
- // wrapperLines is an array but one element (the original-content slot)
- // is a `\n`-joined multi-line string, so the actual file-row count is
- // wrapperLines.length + (originalLines.length - 1). Without the offset,
- // endLine pointed inside the wrapper for any picked element that
- // spanned more than one source line.
- endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexed
- insertLine: insertLine + 1, // 1-indexed: where variants go
- commentSyntax: commentSyntax,
- styleMode: styleMode.mode,
- styleTag: styleMode.styleTag,
- cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
- cssAuthoring: buildCssAuthoring(styleMode, count),
- originalLineCount: originalLines.length,
- }));
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-/**
- * Build search query strings in priority order (most specific first).
- * ID is most reliable, then specific class combos, then single classes, then raw query.
- */
-function buildSearchQueries(elementId, classes, tag, query) {
- const queries = [];
-
- // 1. ID is the most specific
- if (elementId) {
- queries.push('id="' + elementId + '"');
- }
-
- // 2. Full class attribute match (for elements with distinctive multi-class combos).
- // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
- // convention the file uses will match.
- if (classes) {
- const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
- if (classList.length > 1) {
- const joined = classList.join(' ');
- const sorted = [...classList].sort((a, b) => b.length - a.length);
- queries.push('class="' + joined + '"');
- queries.push('className="' + joined + '"');
- queries.push(sorted[0]); // most distinctive single class, fallback
- } else if (classList.length === 1) {
- queries.push(classList[0]);
- }
- }
-
- // 3. Tag + class combo (e.g., <section class="hero">).
- // Same dual-emit for JSX compatibility.
- if (tag && classes) {
- const firstClass = classes.split(',')[0].trim();
- queries.push('<' + tag + ' class="' + firstClass);
- queries.push('<' + tag + ' className="' + firstClass);
- }
-
- // 4. Raw fallback query
- if (query) {
- queries.push(query);
- }
-
- return queries;
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- // HTML, Vue, Svelte, Astro all use HTML comments
- return { open: '<!--', close: '-->' };
-}
-
-function detectStyleMode(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.astro') {
- return {
- mode: 'astro-global-prefixed',
- styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',
- };
- }
- return {
- mode: 'scoped',
- styleTag: '<style data-impeccable-css="SESSION_ID">',
- };
-}
-
-function buildCssSelectorPrefixExamples(styleMode, count) {
- if (styleMode !== 'astro-global-prefixed') return [];
- return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);
-}
-
-function buildCssAuthoring(styleMode, count) {
- const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
- if (styleMode.mode === 'astro-global-prefixed') {
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'global-prefixed',
- rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',
- selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),
- requirements: [
- 'Use the styleTag exactly; the is:inline attribute is required for this file.',
- 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',
- 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
- ],
- forbidden: [
- 'Do not use @scope for this styleMode.',
- ],
- };
- }
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'scope-rule',
- rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',
- selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),
- requirements: [
- 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',
- 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
- 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
- ],
- forbidden: [
- 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',
- 'Do not add is:inline to the style tag for this styleMode.',
- ],
- };
-}
-
-/**
- * Search project files for the query string (class name, ID, etc.)
- * Returns the first matching file path, or null.
- */
-function findFileWithQuery(query, cwd, genOpts = {}) {
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, query, seen, 0, genOpts);
- if (result) return result;
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth, genOpts) {
- if (depth > 5) return null; // don't go too deep
- const realDir = fs.realpathSync(dir);
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- // Check files first
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name).toLowerCase();
- if (!EXTENSIONS.includes(ext)) continue;
-
- const filePath = path.join(dir, entry.name);
- if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip unreadable files */ }
- }
-
- // Then recurse into directories. Always skip node_modules and .git (never
- // project content). dist/build/out are left to the isGeneratedFile guard so
- // the includeGenerated second-pass can still find the element there and
- // report `generatedMatch`.
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
- if (result) return result;
- }
-
- return null;
-}
-
-/**
- * Regex that matches a tag opener on a line. Allows the tag name to be
- * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
- * openers (e.g. `<section\n className="..."\n>`) are recognised.
- */
-const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
-
-/**
- * Find the element's start and end line in the file.
- *
- * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
- * `id="..."`), or a raw text snippet. Because a query can appear on a
- * continuation line of a multi-line tag (e.g. the `className="..."` row of a
- * `<section\n className="..."\n>` JSX tag), we walk backward from the match
- * line to find the actual tag opener. When `tag` is provided, opener candidates
- * must match that tag name.
- */
-/**
- * Return the smallest leading-whitespace count across a set of lines,
- * ignoring blank lines (whose indent isn't load-bearing). Used to compute
- * the common base indent of a multi-line picked element so reindenting
- * under the wrapper preserves the relative depth between lines.
- */
-function minLeadingSpaces(lines) {
- let min = Infinity;
- for (const l of lines) {
- if (l.trim() === '') continue;
- const m = l.match(/^(\s*)/);
- if (m && m[1].length < min) min = m[1].length;
- }
- return min === Infinity ? 0 : min;
-}
-
-function findElement(lines, query, tag = null) {
- // Iterate all matches — the first substring hit isn't always the right one.
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
-
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- // Skip lines already inside a variant wrapper
- if (lines[i].includes('data-impeccable-variant')) continue;
-
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
-
- const endLine = findClosingLine(lines, openerLine);
- return { startLine: openerLine, endLine };
- }
-
- return null;
-}
-
-/**
- * Like findElement, but returns every match. Used for ambiguity detection
- * when the agent passes --text: when the same className appears on multiple
- * sibling elements (a list of cards, repeated section variants, etc.),
- * first-match silently lands on the wrong branch. Returning all matches lets
- * the caller narrow by textContent or fail with a structured ambiguity error.
- */
-function findAllElements(lines, query, tag = null) {
- const out = [];
- const seen = new Set();
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- if (lines[i].includes('data-impeccable-variant')) continue;
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
- if (seen.has(openerLine)) continue; // multiple matches inside the same element
- seen.add(openerLine);
- const endLine = findClosingLine(lines, openerLine);
- out.push({ startLine: openerLine, endLine });
- }
- return out;
-}
-
-/**
- * Narrow a candidate set to those whose source body matches a meaningful
- * prefix of the picked element's textContent. The compare strips tags and
- * JSX expressions, then checks two whitespace normalizations side-by-side:
- *
- * - single-space ("hero two second card body")
- * - no-whitespace ("herotwosecondcardbody")
- *
- * Both are needed because `el.textContent` concatenates sibling text without
- * inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
- * `"Hero TwoSecond…"`), while the source has whitespace between tags. If
- * EITHER normalization matches, the candidate keeps. A snippet shorter than
- * 8 chars after stripping is too weak to disambiguate — the caller falls
- * back to first-match.
- */
-function filterByText(candidates, lines, text) {
- const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
- // Too short to disambiguate. Return [] so the caller's `filtered.length
- // === 0` branch fires (fall back to first-match) — the previous
- // `candidates.slice()` return forced `filtered.length > 1` and surfaced
- // a spurious `element_ambiguous` error on every short-text picker event
- // with multiple candidates.
- if (trimmed.length < 8) return [];
- const targetSpaced = trimmed;
- const targetCompact = trimmed.replace(/\s+/g, '');
-
- return candidates.filter((c) => {
- const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
- const inner = body
- .replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
- .replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
- .toLowerCase();
- const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
- const sourceCompact = inner.replace(/\s+/g, '');
- return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
- });
-}
-
-/**
- * Resolve a match line to the real tag opener. If the match line itself opens
- * a tag, return it. Otherwise walk up to 10 lines backward looking for the
- * first tag opener. If `tag` is specified, the opener must match that tag
- * name; an opener with a different tag name aborts the backward walk for this
- * match (we don't jump across element boundaries).
- *
- * Returns the line index of the opener, or -1 if none can be resolved.
- */
-function findOpenerLine(lines, matchLine, tag) {
- const self = lines[matchLine].match(OPENER_RE);
- if (self) {
- if (!tag || self[1] === tag) return matchLine;
- return -1;
- }
- const MAX_BACKWALK = 10;
- for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
- const opener = lines[i].match(OPENER_RE);
- if (!opener) continue;
- if (!tag || opener[1] === tag) return i;
- // Different tag name than requested — abort; we're inside a non-target opener.
- return -1;
- }
- return -1;
-}
-
-/**
- * Starting from a line with an opening tag, find the line with the matching
- * closing tag by counting tag nesting depth.
- */
-function findClosingLine(lines, start) {
- const openMatch = lines[start].match(OPENER_RE);
- if (!openMatch) return start; // caller passed a non-opener; nothing to span
-
- const tagName = openMatch[1];
- let depth = 0;
- const openRe = new RegExp('<' + tagName + '(?=[\\s/>]|$)', 'g');
- const selfCloseRe = new RegExp('<' + tagName + '[^>]*/>', 'g');
- const closeRe = new RegExp('</' + tagName + '\\s*>', 'g');
-
- for (let i = start; i < lines.length; i++) {
- const line = lines[i];
- const opens = (line.match(openRe) || []).length;
- const selfCloses = (line.match(selfCloseRe) || []).length;
- const closes = (line.match(closeRe) || []).length;
-
- depth += opens - selfCloses - closes;
-
- if (depth <= 0) return i;
- }
-
- // If we can't find the close, return a reasonable guess
- return Math.min(start + 50, lines.length - 1);
-}
-
-// Auto-execute when run directly (node live-wrap.mjs ...)
-const _running = process.argv[1];
-if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {
- wrapCli();
-}
-
-// Test exports (used by tests/live-wrap.test.mjs)
-export { buildSearchQueries, findElement, findClosingLine, detectCommentSyntax };
@@ -1,247 +0,0 @@
-/**
- * CLI entry point: prepare everything needed to enter the live variant poll loop.
- *
- * Does (all in one command):
- * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)
- * 2. Start the live server in the background (or reuse a running one)
- * 3. Inject the browser script tag into the project's entry file
- * 4. Read PRODUCT.md / DESIGN.md for project context
- * 5. Print a single JSON blob with everything the agent needs
- *
- * After this, the agent's only remaining steps are:
- * - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll
- * - Enter the poll loop: `node live-poll.mjs`
- *
- * Usage:
- * node live.mjs # Prepare everything, print JSON, exit
- * node live.mjs --help
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { loadContext } from './load-context.mjs';
-import { resolveFiles } from './live-inject.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-async function liveCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live.mjs
-
-Prepare everything for live variant mode in a single command:
- - Checks .impeccable/live/config.json (required, created once per project)
- - Starts (or reuses) the live server in the background
- - Injects the browser script tag
- - Reads PRODUCT.md / DESIGN.md for project context
-
-On success, prints a JSON blob with:
- { ok, serverPort, serverToken, pageFile, hasContext, context }
-
-On config_missing, prints:
- { ok: false, error: "config_missing", configPath, hint }
-
-The agent should then:
- 1. If config_missing, create the config and re-run this script
- 2. Optionally open the project's dev/preview URL in the browser (see reference/live.md—not serverPort)
- 3. Enter the poll loop: node live-poll.mjs`);
- process.exit(0);
- }
-
- // 1. Check config (fail fast if missing — no point starting anything else)
- const checkOut = runScript('live-inject.mjs', ['--check']);
- const checkResult = safeParse(checkOut);
- if (!checkResult || !checkResult.ok) {
- console.log(JSON.stringify(checkResult || { ok: false, error: 'check_failed', raw: checkOut }));
- process.exit(0);
- }
-
- // 2. Start server (or reuse existing)
- const serverInfo = ensureServerRunning();
- if (!serverInfo) {
- console.log(JSON.stringify({ ok: false, error: 'server_start_failed' }));
- process.exit(1);
- }
-
- // 3. Inject the script tag at the current port
- const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)]);
- const injectResult = safeParse(injectOut);
- if (!injectResult || !injectResult.ok) {
- console.log(JSON.stringify({
- ok: false,
- error: 'inject_failed',
- detail: injectResult || injectOut,
- serverPort: serverInfo.port,
- }));
- process.exit(1);
- }
-
- // 4. Load PRODUCT.md + DESIGN.md context (auto-migrates legacy .impeccable.md)
- const ctx = loadContext(process.cwd());
-
- // 5. Compute drift-heal: compare resolved inject targets against the
- // project's HTML files. Orphans are HTML files not covered by config.
- // Warning only — the agent decides whether to act.
- const resolvedFiles = resolveFiles(process.cwd(), checkResult.config);
- const drift = scanForDrift(process.cwd(), resolvedFiles, checkResult.config);
-
- // 6. Emit everything the agent needs
- console.log(JSON.stringify({
- ok: true,
- serverPort: serverInfo.port,
- serverToken: serverInfo.token,
- pageFiles: resolvedFiles,
- configDrift: drift,
- hasProduct: ctx.hasProduct,
- product: ctx.product,
- productPath: ctx.productPath,
- hasDesign: ctx.hasDesign,
- design: ctx.design,
- designPath: ctx.designPath,
- migrated: ctx.migrated,
- }, null, 2));
-}
-
-/**
- * Drift-heal scan. Walks the project for HTML files under common
- * page-source directories (public/, src/, app/, pages/) and reports any
- * that aren't covered by the resolved inject targets. This is purely
- * advisory — the agent can ignore it, or suggest the user add the
- * orphans to config.files.
- *
- * Skipped if config.files already contains at least one glob pattern
- * covering everything in practice (signaled by the orphan count being 0).
- */
-function scanForDrift(rootDir, resolvedFiles, config) {
- const SCAN_ROOTS = ['public', 'src', 'app', 'pages'];
- const IGNORE_DIRS = new Set([
- 'node_modules', '.git', '.next', '.nuxt', '.svelte-kit', '.astro',
- '.turbo', '.vercel', '.cache', 'coverage', 'dist', 'build',
- ]);
-
- const resolvedSet = new Set(resolvedFiles.map((f) => f.split(path.sep).join('/')));
-
- // Files matching the user's `exclude` globs are intentional omissions,
- // not drift. Compile them to regexes so the orphan list stays signal.
- const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
- .map((p) => globToRegex(p));
- const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
-
- const orphans = [];
-
- const walk = (dir, relBase) => {
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
- for (const e of entries) {
- const rel = relBase ? `${relBase}/${e.name}` : e.name;
- if (e.isDirectory()) {
- if (IGNORE_DIRS.has(e.name) || e.name.startsWith('.')) continue;
- walk(path.join(dir, e.name), rel);
- } else if (e.isFile() && e.name.endsWith('.html')) {
- if (resolvedSet.has(rel)) continue;
- if (isUserExcluded(rel)) continue;
- orphans.push(rel);
- }
- }
- };
-
- for (const root of SCAN_ROOTS) {
- const abs = path.join(rootDir, root);
- if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
- walk(abs, root);
- }
- }
-
- if (orphans.length === 0) return null;
- const capped = orphans.slice(0, 20);
- return {
- orphans: capped,
- orphanCount: orphans.length,
- hint: `${orphans.length} HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like "public/**/*.html".`,
- };
-}
-
-/**
- * Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
- * to avoid a circular import (live-inject.mjs already imports nothing
- * from live.mjs). The two must stay in sync.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
- else { re += '.*'; i += 2; }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function runScript(name, args) {
- const scriptPath = path.join(__dirname, name);
- const cmd = `node "${scriptPath}" ${args.map(a => `"${a}"`).join(' ')}`;
- try {
- return execSync(cmd, { encoding: 'utf-8', cwd: process.cwd(), timeout: 15_000 });
- } catch (err) {
- // execSync throws on non-zero exit; return stdout if any
- return err.stdout || err.message || '';
- }
-}
-
-function safeParse(out) {
- try { return JSON.parse(String(out).trim()); } catch { return null; }
-}
-
-/**
- * Return { pid, port, token } for the running live server, starting one if needed.
- */
-function ensureServerRunning() {
- // Try to reuse an existing server
- try {
- const existing = readLiveServerInfo(process.cwd())?.info;
- if (existing && existing.pid) {
- try {
- process.kill(existing.pid, 0); // throws if dead
- return existing;
- } catch { /* stale PID file — the server script will clean it up */ }
- }
- } catch { /* no PID file */ }
-
- // Start a new server
- const out = runScript('live-server.mjs', ['--background']);
- return safeParse(out);
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live.mjs') || _running?.endsWith('live.mjs/')) {
- liveCli();
-}
@@ -1,141 +0,0 @@
-/**
- * Shared context loader for every impeccable command that needs to know
- * "who is this for" and "what does this look like".
- *
- * Input: project root (process.cwd()).
- *
- * Output (JSON to stdout):
- * {
- * hasProduct: boolean, // PRODUCT.md found (or auto-migrated)
- * product: string | null, // PRODUCT.md contents
- * productPath: string | null, // relative path
- * hasDesign: boolean, // DESIGN.md found
- * design: string | null, // DESIGN.md contents
- * designPath: string | null,
- * migrated: boolean, // true if we auto-renamed .impeccable.md -> PRODUCT.md
- * contextDir: string, // absolute path of the directory the files were found in
- * }
- *
- * Filename matching is case-insensitive for PRODUCT.md and DESIGN.md. The
- * Google DESIGN.md convention is uppercase at repo root; Kiro-style and
- * lowercase variants are also matched so users don't get punished for case.
- *
- * Lookup directory resolution (first match wins):
- * 1. process.env.IMPECCABLE_CONTEXT_DIR (absolute or relative to cwd)
- * 2. cwd, if PRODUCT.md / DESIGN.md / .impeccable.md is there (back-compat)
- * 3. Auto-fallback subdirectories of cwd: .agents/context/, then docs/
- * 4. cwd as a default "no context found" location
- *
- * Legacy `.impeccable.md` -> PRODUCT.md migration only fires at cwd root;
- * fallback directories are read-only as far as auto-rename is concerned.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
-const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
-const LEGACY_NAMES = ['.impeccable.md'];
-const FALLBACK_DIRS = ['.agents/context', 'docs'];
-
-/**
- * Resolve the directory that holds PRODUCT.md / DESIGN.md for
- * this project. Exported so other scripts (e.g. live-server.mjs) can read the
- * design files from the same location the loader uses.
- */
-export function resolveContextDir(cwd = process.cwd()) {
- // 1. Explicit override
- const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
- if (envDir && envDir.trim()) {
- const trimmed = envDir.trim();
- return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- }
-
- // 2. cwd wins if any canonical or legacy file is there. We check legacy too
- // so the auto-migration path in loadContext stays predictable.
- if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES, ...LEGACY_NAMES])) {
- return cwd;
- }
-
- // 3. Auto-fallback subdirs. Match if PRODUCT.md or DESIGN.md is present;
- // legacy `.impeccable.md` does not pull the lookup into a fallback dir.
- for (const rel of FALLBACK_DIRS) {
- const candidate = path.resolve(cwd, rel);
- if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
- return candidate;
- }
- }
-
- // 4. Nothing found — keep the historical "default to cwd" behaviour so the
- // caller's `hasProduct === false` branch still fires the same way.
- return cwd;
-}
-
-export function loadContext(cwd = process.cwd()) {
- let migrated = false;
- const contextDir = resolveContextDir(cwd);
-
- // 1. Look for PRODUCT.md (case-insensitive) in the resolved dir
- let productPath = firstExisting(contextDir, PRODUCT_NAMES);
-
- // 2. Legacy: if no PRODUCT.md but .impeccable.md exists at cwd root, rename
- // it in place. We only migrate at the root — fallback dirs are read-only
- // so we don't surprise users by mutating files under docs/ or .agents/.
- if (!productPath && contextDir === cwd) {
- const legacyPath = firstExisting(cwd, LEGACY_NAMES);
- if (legacyPath) {
- const newPath = path.join(cwd, 'PRODUCT.md');
- try {
- fs.renameSync(legacyPath, newPath);
- productPath = newPath;
- migrated = true;
- } catch {
- // Rename failed (permissions, etc.) — fall back to reading legacy in place
- productPath = legacyPath;
- }
- }
- }
-
- // 3. DESIGN.md (case-insensitive)
- const designPath = firstExisting(contextDir, DESIGN_NAMES);
-
- const product = productPath ? safeRead(productPath) : null;
- const design = designPath ? safeRead(designPath) : null;
-
- return {
- hasProduct: !!product,
- product,
- productPath: productPath ? path.relative(cwd, productPath) : null,
- hasDesign: !!design,
- design,
- designPath: designPath ? path.relative(cwd, designPath) : null,
- migrated,
- contextDir,
- };
-}
-
-function firstExisting(dir, names) {
- for (const name of names) {
- const abs = path.join(dir, name);
- if (fs.existsSync(abs)) return abs;
- }
- return null;
-}
-
-function safeRead(p) {
- try { return fs.readFileSync(p, 'utf-8'); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// CLI mode — print the context as JSON
-// ---------------------------------------------------------------------------
-
-function cli() {
- const result = loadContext(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('load-context.mjs') || _running?.endsWith('load-context.mjs/')) {
- cli();
-}
@@ -1,14 +0,0 @@
@@ -1,214 +0,0 @@
-#!/usr/bin/env node
-/**
- * Pin/unpin sub-commands as standalone skill shortcuts.
- *
- * Usage:
- * node <scripts_path>/pin.mjs pin <command>
- * node <scripts_path>/pin.mjs unpin <command>
- *
- * `pin audit` creates a lightweight /audit skill that redirects to /impeccable audit.
- * `unpin audit` removes that shortcut.
- *
- * The script discovers harness directories (.claude/skills, .cursor/skills, etc.)
- * in the project root and creates/removes the pin in all of them.
- */
-
-import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
-import { join, resolve, dirname } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-// All known harness directories
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Valid sub-command names
-const VALID_COMMANDS = [
- 'craft', 'teach', 'extract', 'document', 'shape',
- 'critique', 'audit',
- 'polish', 'bolder', 'quieter', 'distill', 'harden', 'onboard', 'live',
- 'animate', 'colorize', 'typeset', 'layout', 'delight', 'overdrive',
- 'clarify', 'adapt', 'optimize',
-];
-
-// Marker to identify pinned skills (so unpin doesn't delete user skills)
-const PIN_MARKER = '<!-- impeccable-pinned-skill -->';
-
-/**
- * Walk up from startDir to find a project root.
- */
-function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- while (dir !== '/') {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Find harness skill directories that have an impeccable skill installed.
- */
-function findHarnessDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const skillsDir = join(projectRoot, harness, 'skills');
- // Only pin in harness dirs that already have impeccable installed
- const impeccableDir = join(skillsDir, 'impeccable');
- if (existsSync(impeccableDir) || existsSync(join(skillsDir, 'i-impeccable'))) {
- dirs.push(skillsDir);
- }
- }
- return dirs;
-}
-
-/**
- * Load command metadata (descriptions for pinned skills).
- */
-function loadCommandMetadata() {
- const metadataPath = join(__dirname, 'command-metadata.json');
- if (existsSync(metadataPath)) {
- return JSON.parse(readFileSync(metadataPath, 'utf-8'));
- }
- return {};
-}
-
-/**
- * Generate a pinned skill's SKILL.md content.
- */
-function generatePinnedSkill(command, metadata) {
- const desc = metadata[command]?.description || `Shortcut for /impeccable ${command}.`;
- const hint = metadata[command]?.argumentHint || '[target]';
-
- return `---
-name: ${command}
-description: "${desc}"
-argument-hint: "${hint}"
-user-invocable: true
----
-
-${PIN_MARKER}
-
-This is a pinned shortcut for \`{{command_prefix}}impeccable ${command}\`.
-
-Invoke {{command_prefix}}impeccable ${command}, passing along any arguments provided here, and follow its instructions.
-`;
-}
-
-/**
- * Pin a command: create shortcut skill in all harness dirs.
- */
-function pin(command, projectRoot) {
- const metadata = loadCommandMetadata();
- const harnessDirs = findHarnessDirs(projectRoot);
-
- if (harnessDirs.length === 0) {
- console.log('No harness directories with impeccable installed found.');
- return false;
- }
-
- const content = generatePinnedSkill(command, metadata);
- let created = 0;
-
- for (const skillsDir of harnessDirs) {
- // Check if skill already exists (and isn't a pin)
- const skillDir = join(skillsDir, command);
- if (existsSync(skillDir)) {
- const existingMd = join(skillDir, 'SKILL.md');
- if (existsSync(existingMd)) {
- const existing = readFileSync(existingMd, 'utf-8');
- if (!existing.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (non-pinned skill already exists)`);
- continue;
- }
- }
- }
-
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(join(skillDir, 'SKILL.md'), content, 'utf-8');
- console.log(` + ${skillDir}`);
- created++;
- }
-
- if (created > 0) {
- console.log(`\nPinned '${command}' as a standalone shortcut in ${created} location(s).`);
- console.log(`You can now use /${command} directly.`);
- }
-
- return created > 0;
-}
-
-/**
- * Unpin a command: remove shortcut skill from all harness dirs.
- */
-function unpin(command, projectRoot) {
- const harnessDirs = findHarnessDirs(projectRoot);
- let removed = 0;
-
- for (const skillsDir of harnessDirs) {
- const skillDir = join(skillsDir, command);
- if (!existsSync(skillDir)) continue;
-
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) continue;
-
- // Safety: only remove if it's a pinned skill
- const content = readFileSync(skillMd, 'utf-8');
- if (!content.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (not a pinned skill)`);
- continue;
- }
-
- rmSync(skillDir, { recursive: true, force: true });
- console.log(` - ${skillDir}`);
- removed++;
- }
-
- if (removed > 0) {
- console.log(`\nUnpinned '${command}' from ${removed} location(s).`);
- console.log(`Use /impeccable ${command} to access it.`);
- } else {
- console.log(`No pinned '${command}' shortcut found.`);
- }
-
- return removed > 0;
-}
-
-// --- CLI ---
-const [,, action, command] = process.argv;
-
-if (!action || !command) {
- console.log('Usage: node pin.mjs <pin|unpin> <command>');
- console.log(`\nAvailable commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-if (action !== 'pin' && action !== 'unpin') {
- console.error(`Unknown action: ${action}. Use 'pin' or 'unpin'.`);
- process.exit(1);
-}
-
-if (!VALID_COMMANDS.includes(command)) {
- console.error(`Unknown command: ${command}`);
- console.error(`Available commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-const root = findProjectRoot();
-
-if (action === 'pin') {
- pin(command, root);
-} else {
- unpin(command, root);
-}
@@ -1,26 +0,0 @@
-{
- "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
- "name": "impeccable",
- "metadata": {
- "description": "Design fluency for AI harnesses. 1 skill, 23 commands, and curated anti-patterns for impeccable frontend design."
- },
- "owner": {
- "name": "Paul Bakaus",
- "email": "paul@paulbakaus.com"
- },
- "plugins": [
- {
- "name": "impeccable",
- "description": "Design fluency for frontend development. 1 skill with 23 commands (/impeccable polish, /impeccable audit, /impeccable critique, etc.) and curated anti-pattern detection.",
- "version": "3.1.1",
- "author": {
- "name": "Paul Bakaus",
- "email": "paul@paulbakaus.com"
- },
- "source": "./plugin",
- "category": "design",
- "homepage": "https://impeccable.style",
- "tags": ["design", "frontend", "ui", "ux", "skills", "commands"]
- }
- ]
-}
@@ -1,12 +0,0 @@
-{
- "name": "impeccable",
- "description": "Design fluency for frontend development. 1 skill with 23 commands (/impeccable polish, /impeccable audit, /impeccable critique, etc.) and curated anti-pattern detection.",
- "version": "3.1.1",
- "author": {
- "name": "Paul Bakaus",
- "email": "paul@paulbakaus.com"
- },
- "homepage": "https://impeccable.style",
- "repository": "https://github.com/pbakaus/impeccable",
- "skills": "./.claude/skills/"
-}
@@ -1,169 +0,0 @@
----
-name: impeccable
-description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
-version: 3.1.1
-user-invocable: true
-argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · teach|document|extract|live] [target]"
-license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
-allowed-tools:
- - Bash(npx impeccable *)
----
-
-Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
-
-## Setup
-
-Before any design work or file edits:
-
-1. Load context (PRODUCT.md / DESIGN.md) via the loader script.
-2. Identify the register and load the matching register reference (brand.md or product.md).
-3. **If the user invoked a sub-command (e.g. `craft`, `shape`, `audit`), load its reference file too.** This is non-negotiable: `craft` without `craft.md` loaded means you'll skip the shape-and-confirm step the user expects.
-
-Skipping these produces generic output that ignores the project.
-
-### 1. Context gathering
-
-Two files, case-insensitive. The loader looks at the project root by default and falls back to `.agents/context/` and `docs/` if the root is clean. Override with `IMPECCABLE_CONTEXT_DIR=path/to/dir` (absolute or relative to cwd).
-
-- **PRODUCT.md**: required. Users, brand, tone, anti-references, strategic principles.
-- **DESIGN.md**: optional, strongly recommended. Colors, typography, elevation, components.
-
-Load both in one call:
-
-```bash
-node .claude/skills/impeccable/scripts/load-context.mjs
-```
-
-Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`. The output's `contextDir` field tells you where the files were resolved from.
-
-If the output is already in this session's conversation history, don't re-run. Exceptions requiring a fresh load: you just ran `/impeccable teach` or `/impeccable document` (they rewrite the files), or the user manually edited one.
-
-`/impeccable live` already warms context via `live.mjs`. If you've run `live.mjs`, don't also run `load-context.mjs` this session.
-
-If PRODUCT.md is missing, empty, or placeholder (`[TODO]` markers, <200 chars): run `/impeccable teach`, then resume the user's original task with the fresh context. If the original task was `/impeccable craft`, resume into `/impeccable shape` before any implementation work.
-
-If DESIGN.md is missing: nudge once per session (*"Run `/impeccable document` for more on-brand output"*), then proceed.
-
-### 2. Register
-
-Every design task is **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboard, tool: design SERVES the product).
-
-Identify before designing. Priority: (1) cue in the task itself ("landing page" vs "dashboard"); (2) the surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. First match wins.
-
-If PRODUCT.md lacks the `register` field (legacy), infer it once from its "Users" and "Product Purpose" sections, then cache the inferred value for the session. Suggest the user run `/impeccable teach` to add the field explicitly.
-
-Load the matching reference: [reference/brand.md](reference/brand.md) or [reference/product.md](reference/product.md). The shared design laws below apply to both.
-
-## Shared design laws
-
-Apply to every design, both registers. Match implementation complexity to the aesthetic vision: maximalism needs elaborate code, minimalism needs precision. Interpret creatively. Vary across projects; never converge on the same choices. Claude is capable of extraordinary work. Don't hold back.
-
-### Color
-
-- Use OKLCH. Reduce chroma as lightness approaches 0 or 100; high chroma at extremes looks garish.
-- Never use `#000` or `#fff`. Tint every neutral toward the brand hue (chroma 0.005–0.01 is enough).
-- Pick a **color strategy** before picking colors. Four steps on the commitment axis:
- - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism.
- - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages.
- - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz.
- - **Drenched**: the surface IS the color. Brand heroes, campaign pages.
-- The "one accent ≤10%" rule is Restrained only. Committed / Full palette / Drenched exceed it on purpose. Don't collapse every design to Restrained by reflex.
-
-### Theme
-
-Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe."
-
-Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does.
-
-"Observability dashboard" does not force an answer. "SRE glancing at incident severity on a 27-inch monitor at 2am in a dim room" does. Run the sentence, not the category.
-
-### Typography
-
-- Cap body line length at 65–75ch.
-- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales.
-
-### Layout
-
-- Vary spacing for rhythm. Same padding everywhere is monotony.
-- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
-- Don't wrap everything in a container. Most things don't need one.
-
-### Motion
-
-- Don't animate CSS layout properties.
-- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
-
-### Absolute bans
-
-Match-and-refuse. If you're about to write any of these, rewrite the element with different structure.
-
-- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing.
-- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size.
-- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing.
-- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché.
-- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly.
-- **Modal as first thought.** Modals are usually laziness. Exhaust inline / progressive alternatives first.
-
-### Copy
-
-- Every word earns its place. No restated headings, no intros that repeat the title.
-- **No em dashes.** Use commas, colons, semicolons, periods, or parentheses. Also not `--`.
-
-### The AI slop test
-
-If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference.
-
-**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses.
-
-- **First-order:** if someone could guess the theme + palette from the category alone ("observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black"), it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
-- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families.
-
-## Commands
-
-| Command | Category | Description | Reference |
-|---|---|---|---|
-| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) |
-| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) |
-| `teach` | Build | Set up PRODUCT.md and DESIGN.md context | [reference/teach.md](reference/teach.md) |
-| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) |
-| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) |
-| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) |
-| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) |
-| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) |
-| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) |
-| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) |
-| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) |
-| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) |
-| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) |
-| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) |
-| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) |
-| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) |
-| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) |
-| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) |
-| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) |
-| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) |
-| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) |
-| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
-| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
-
-### Routing rules
-
-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
-3. **First word doesn't match**: general design invocation. Apply the setup steps, shared design laws, and the loaded register reference, using the full argument as context.
-
-Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `/impeccable`.
-
-If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `teach` as a blocker, finish teach, refresh context, then resume the original command and target.
-
-## Pin / Unpin
-
-**Pin** creates a standalone shortcut so `/<command>` invokes `/impeccable <command>` directly. **Unpin** removes it. The script writes to every harness directory present in the project.
-
-```bash
-node .claude/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
-```
-
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
@@ -1,190 +0,0 @@
-> **Additional context needed**: target platforms/devices and usage contexts.
-
-Adapt an existing design to a different context: another screen size, device, platform, or use case. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context.
-
-
----
-
-## Assess Adaptation Challenge
-
-Understand what needs adaptation and why:
-
-1. **Identify the source context**:
- - What was it designed for originally? (Desktop web? Mobile app?)
- - What assumptions were made? (Large screen? Mouse input? Fast connection?)
- - What works well in current context?
-
-2. **Understand target context**:
- - **Device**: Mobile, tablet, desktop, TV, watch, print?
- - **Input method**: Touch, mouse, keyboard, voice, gamepad?
- - **Screen constraints**: Size, resolution, orientation?
- - **Connection**: Fast wifi, slow 3G, offline?
- - **Usage context**: On-the-go vs desk, quick glance vs focused reading?
- - **User expectations**: What do users expect on this platform?
-
-3. **Identify adaptation challenges**:
- - What won't fit? (Content, navigation, features)
- - What won't work? (Hover states on touch, tiny touch targets)
- - What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop)
-
-**CRITICAL**: Adaptation is rethinking the experience for the new context, not scaling pixels.
-
-## Plan Adaptation Strategy
-
-Create context-appropriate strategy:
-
-### Mobile Adaptation (Desktop → Mobile)
-
-**Layout Strategy**:
-- Single column instead of multi-column
-- Vertical stacking instead of side-by-side
-- Full-width components instead of fixed widths
-- Bottom navigation instead of top/side navigation
-
-**Interaction Strategy**:
-- Touch targets 44x44px minimum (not hover-dependent)
-- Swipe gestures where appropriate (lists, carousels)
-- Bottom sheets instead of dropdowns
-- Thumbs-first design (controls within thumb reach)
-- Larger tap areas with more spacing
-
-**Content Strategy**:
-- Progressive disclosure (don't show everything at once)
-- Prioritize primary content (secondary content in tabs/accordions)
-- Shorter text (more concise)
-- Larger text (16px minimum)
-
-**Navigation Strategy**:
-- Hamburger menu or bottom navigation
-- Reduce navigation complexity
-- Sticky headers for context
-- Back button in navigation flow
-
-### Tablet Adaptation (Hybrid Approach)
-
-**Layout Strategy**:
-- Two-column layouts (not single or three-column)
-- Side panels for secondary content
-- Master-detail views (list + detail)
-- Adaptive based on orientation (portrait vs landscape)
-
-**Interaction Strategy**:
-- Support both touch and pointer
-- Touch targets 44x44px but allow denser layouts than phone
-- Side navigation drawers
-- Multi-column forms where appropriate
-
-### Desktop Adaptation (Mobile → Desktop)
-
-**Layout Strategy**:
-- Multi-column layouts (use horizontal space)
-- Side navigation always visible
-- Multiple information panels simultaneously
-- Fixed widths with max-width constraints (don't stretch to 4K)
-
-**Interaction Strategy**:
-- Hover states for additional information
-- Keyboard shortcuts
-- Right-click context menus
-- Drag and drop where helpful
-- Multi-select with Shift/Cmd
-
-**Content Strategy**:
-- Show more information upfront (less progressive disclosure)
-- Data tables with many columns
-- Richer visualizations
-- More detailed descriptions
-
-### Print Adaptation (Screen → Print)
-
-**Layout Strategy**:
-- Page breaks at logical points
-- Remove navigation, footer, interactive elements
-- Black and white (or limited color)
-- Proper margins for binding
-
-**Content Strategy**:
-- Expand shortened content (show full URLs, hidden sections)
-- Add page numbers, headers, footers
-- Include metadata (print date, page title)
-- Convert charts to print-friendly versions
-
-### Email Adaptation (Web → Email)
-
-**Layout Strategy**:
-- Narrow width (600px max)
-- Single column only
-- Inline CSS (no external stylesheets)
-- Table-based layouts (for email client compatibility)
-
-**Interaction Strategy**:
-- Large, obvious CTAs (buttons not text links)
-- No hover states (not reliable)
-- Deep links to web app for complex interactions
-
-## Implement Adaptations
-
-Apply changes systematically:
-
-### Responsive Breakpoints
-
-Choose appropriate breakpoints:
-- Mobile: 320px-767px
-- Tablet: 768px-1023px
-- Desktop: 1024px+
-- Or content-driven breakpoints (where design breaks)
-
-### Layout Adaptation Techniques
-
-- **CSS Grid/Flexbox**: Reflow layouts automatically
-- **Container Queries**: Adapt based on container, not viewport
-- **`clamp()`**: Fluid sizing between min and max
-- **Media queries**: Different styles for different contexts
-- **Display properties**: Show/hide elements per context
-
-### Touch Adaptation
-
-- Increase touch target sizes (44x44px minimum)
-- Add more spacing between interactive elements
-- Remove hover-dependent interactions
-- Add touch feedback (ripples, highlights)
-- Consider thumb zones (easier to reach bottom than top)
-
-### Content Adaptation
-
-- Use `display: none` sparingly (still downloads)
-- Progressive enhancement (core content first, enhancements on larger screens)
-- Lazy loading for off-screen content
-- Responsive images (`srcset`, `picture` element)
-
-### Navigation Adaptation
-
-- Transform complex nav to hamburger/drawer on mobile
-- Bottom nav bar for mobile apps
-- Persistent side navigation on desktop
-- Breadcrumbs on smaller screens for context
-
-**IMPORTANT**: Test on real devices. Device emulation in DevTools is helpful but not perfect.
-
-**NEVER**:
-- Hide core functionality on mobile (if it matters, make it work)
-- Assume desktop = powerful device (consider accessibility, older machines)
-- Use different information architecture across contexts (confusing)
-- Break user expectations for platform (mobile users expect mobile patterns)
-- Forget landscape orientation on mobile/tablet
-- Use generic breakpoints blindly (use content-driven breakpoints)
-- Ignore touch on desktop (many desktop devices have touch)
-
-## Verify Adaptations
-
-Test thoroughly across contexts:
-
-- **Real devices**: Test on actual phones, tablets, desktops
-- **Different orientations**: Portrait and landscape
-- **Different browsers**: Safari, Chrome, Firefox, Edge
-- **Different OS**: iOS, Android, Windows, macOS
-- **Different input methods**: Touch, mouse, keyboard
-- **Edge cases**: Very small screens (320px), very large screens (4K)
-- **Slow connections**: Test on throttled network
-
-When the adaptation feels native to each context, hand off to `/impeccable polish` for the final pass.
@@ -1,175 +0,0 @@
-> **Additional context needed**: performance constraints.
-
-Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it.
-
----
-
-## Register
-
-Brand: orchestrated page-load sequences, staggered reveals, scroll-driven animation. Motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions.
-
-Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it.
-
----
-
-## Assess Animation Opportunities
-
-Analyze where motion would improve the experience:
-
-1. **Identify static areas**:
- - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.)
- - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes)
- - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious
- - **Lack of delight**: Functional but joyless interactions
- - **Missed guidance**: Opportunities to direct attention or explain behavior
-
-2. **Understand the context**:
- - What's the personality? (Playful vs serious, energetic vs calm)
- - What's the performance budget? (Mobile-first? Complex page?)
- - Who's the audience? (Motion-sensitive users? Power users who want speed?)
- - What matters most? (One hero animation vs many micro-interactions?)
-
-If any of these are unclear from the codebase, STOP and call the AskUserQuestion tool to clarify.
-
-**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them.
-
-## Plan Animation Strategy
-
-Create a purposeful animation plan:
-
-- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?)
-- **Feedback layer**: Which interactions need acknowledgment?
-- **Transition layer**: Which state changes need smoothing?
-- **Delight layer**: Where can we surprise and delight?
-
-**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments.
-
-## Implement Animations
-
-Add motion systematically across these categories:
-
-### Entrance Animations
-- **Page load choreography**: Stagger element reveals (100-150ms delays), fade + slide combinations
-- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects)
-- **Content reveals**: Scroll-triggered animations using intersection observer
-- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management
-
-### Micro-interactions
-- **Button feedback**:
- - Hover: Subtle scale (1.02-1.05), color shift, shadow increase
- - Click: Quick scale down then up (0.95 → 1), ripple effect
- - Loading: Spinner or pulse state
-- **Form interactions**:
- - Input focus: Border color transition, slight scale or glow
- - Validation: Shake on error, check mark on success, smooth color transitions
-- **Toggle switches**: Smooth slide + color transition (200-300ms)
-- **Checkboxes/radio**: Check mark animation, ripple effect
-- **Like/favorite**: Scale + rotation, particle effects, color transition
-
-### State Transitions
-- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms)
-- **Expand/collapse**: Height transition with overflow handling, icon rotation
-- **Loading states**: Skeleton screen fades, spinner animations, progress bars
-- **Success/error**: Color transitions, icon animations, gentle scale pulse
-- **Enable/disable**: Opacity transitions, cursor changes
-
-### Navigation & Flow
-- **Page transitions**: Crossfade between routes, shared element transitions
-- **Tab switching**: Slide indicator, content fade/slide
-- **Carousel/slider**: Smooth transforms, snap points, momentum
-- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators
-
-### Feedback & Guidance
-- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights
-- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning
-- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation
-- **Focus flow**: Highlight path through form or workflow
-
-### Delight Moments
-- **Empty states**: Subtle floating animations on illustrations
-- **Completed actions**: Confetti, check mark flourish, success celebrations
-- **Easter eggs**: Hidden interactions for discovery
-- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches
-
-## Technical Implementation
-
-Use appropriate techniques for each animation:
-
-### Timing & Easing
-
-**Durations by purpose:**
-- **100-150ms**: Instant feedback (button press, toggle)
-- **200-300ms**: State changes (hover, menu open)
-- **300-500ms**: Layout changes (accordion, modal)
-- **500-800ms**: Entrance animations (page load)
-
-**Easing curves (use these, not CSS defaults):**
-```css
-/* Recommended: natural deceleration */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */
-
-/* AVOID: feel dated and tacky */
-/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */
-/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */
-```
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-### CSS Animations
-```css
-/* Prefer for simple, declarative animations */
-- transitions for state changes
-- @keyframes for complex sequences
-- transform and opacity for reliable movement
-- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth
-```
-
-### JavaScript Animation
-```javascript
-/* Use for complex, interactive animations */
-- Web Animations API for programmatic control
-- Framer Motion for React
-- GSAP for complex sequences
-```
-
-### Performance
-- **Motion materials**: Use transform/opacity for reliable movement, but use blur, filters, masks, shadows, and color shifts when they materially improve the effect
-- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- **will-change**: Add sparingly for known expensive animations
-- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate
-- **Monitor FPS**: Ensure 60fps on target devices
-
-### Accessibility
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**NEVER**:
-- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself
-- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work
-- Use durations over 500ms for feedback (it feels laggy)
-- Animate without purpose (every animation needs a reason)
-- Ignore `prefers-reduced-motion` (this is an accessibility violation)
-- Animate everything (animation fatigue makes interfaces feel exhausting)
-- Block interaction during animations unless intentional
-
-## Verify Quality
-
-Test animations thoroughly:
-
-- **Smooth at 60fps**: No jank on target devices
-- **Feels natural**: Easing curves feel organic, not robotic
-- **Appropriate timing**: Not too fast (jarring) or too slow (laggy)
-- **Reduced motion works**: Animations disabled or simplified appropriately
-- **Doesn't block**: Users can interact during/after animations
-- **Adds value**: Makes interface clearer or more delightful
-
-When the motion clarifies state instead of decorating it, hand off to `/impeccable polish` for the final pass.
@@ -1,133 +0,0 @@
-Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues; document them for other commands to address.
-
-This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation.
-
-## Diagnostic Scan
-
-Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below.
-
-### 1. Accessibility (A11y)
-
-**Check for**:
-- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA)
-- **Missing ARIA**: Interactive elements without proper roles, labels, or states
-- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps
-- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons
-- **Alt text**: Missing or poor image descriptions
-- **Form issues**: Inputs without labels, poor error messaging, missing required indicators
-
-**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA)
-
-### 2. Performance
-
-**Check for**:
-- **Layout thrashing**: Reading/writing layout properties in loops
-- **Expensive animations**: Casual layout-property animation, unbounded blur/filter/shadow effects, or effects that visibly drop frames
-- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change
-- **Bundle size**: Unnecessary imports, unused dependencies
-- **Render performance**: Unnecessary re-renders, missing memoization
-
-**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized)
-
-### 3. Theming
-
-**Check for**:
-- **Hard-coded colors**: Colors not using design tokens
-- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme
-- **Inconsistent tokens**: Using wrong tokens, mixing token types
-- **Theme switching issues**: Values that don't update on theme change
-
-**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly)
-
-### 4. Responsive Design
-
-**Check for**:
-- **Fixed widths**: Hard-coded widths that break on mobile
-- **Touch targets**: Interactive elements < 44x44px
-- **Horizontal scroll**: Content overflow on narrow viewports
-- **Text scaling**: Layouts that break when text size increases
-- **Missing breakpoints**: No mobile/tablet variants
-
-**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets)
-
-### 5. Anti-Patterns (CRITICAL)
-
-Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy).
-
-**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design)
-
-## Generate Report
-
-### Audit Health Score
-
-| # | Dimension | Score | Key Finding |
-|---|-----------|-------|-------------|
-| 1 | Accessibility | ? | [most critical a11y issue or "--"] |
-| 2 | Performance | ? | |
-| 3 | Responsive Design | ? | |
-| 4 | Theming | ? | |
-| 5 | Anti-Patterns | ? | |
-| **Total** | | **??/20** | **[Rating band]** |
-
-**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues)
-
-### Anti-Patterns Verdict
-**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest.
-
-### Executive Summary
-- Audit Health Score: **??/20** ([rating band])
-- Total issues found (count by severity: P0/P1/P2/P3)
-- Top 3-5 critical issues
-- Recommended next steps
-
-### Detailed Findings by Severity
-
-Tag every issue with **P0-P3 severity**:
-- **P0 Blocking**: Prevents task completion. Fix immediately
-- **P1 Major**: Significant difficulty or WCAG AA violation. Fix before release
-- **P2 Minor**: Annoyance, workaround exists. Fix in next pass
-- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits
-
-For each issue, document:
-- **[P?] Issue name**
-- **Location**: Component, file, line
-- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern
-- **Impact**: How it affects users
-- **WCAG/Standard**: Which standard it violates (if applicable)
-- **Recommendation**: How to fix it
-- **Suggested command**: Which command to use (prefer: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-### Patterns & Systemic Issues
-
-Identify recurring problems that indicate systemic gaps rather than one-off mistakes:
-- "Hard-coded colors appear in 15+ components, should use design tokens"
-- "Touch targets consistently too small (<44px) throughout mobile experience"
-
-### Positive Findings
-
-Note what's working well: good practices to maintain and replicate.
-
-## Recommended Actions
-
-List recommended commands in priority order (P0 first, then P1, then P2):
-
-1. **[P?] `/command-name`**: Brief description (specific context from audit findings)
-2. **[P?] `/command-name`**: Brief description (specific context)
-
-**Rules**: Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset. Map findings to the most appropriate command. End with `/impeccable polish` as the final step if any fixes were recommended.
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable audit` after fixes to see your score improve.
-
-**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters.
-
-**NEVER**:
-- Report issues without explaining impact (why does this matter?)
-- Provide generic recommendations (be specific and actionable)
-- Skip positive findings (celebrate what works)
-- Forget to prioritize (everything can't be P0)
-- Report false positives without verification
-
@@ -1,113 +0,0 @@
-When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact and personality through stronger hierarchy, committed scale, and decisive type.
-
----
-
-## Register
-
-Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
-
-Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too safe or boring:
-
-1. **Identify weakness sources**:
- - **Generic choices**: System fonts, basic colors, standard layouts
- - **Timid scale**: Everything is medium-sized with no drama
- - **Low contrast**: Everything has similar visual weight
- - **Static**: No motion, no energy, no life
- - **Predictable**: Standard patterns with no surprises
- - **Flat hierarchy**: Nothing stands out or commands attention
-
-2. **Understand the context**:
- - What's the brand personality? (How far can we push?)
- - What's the purpose? (Marketing can be bolder than financial dashboards)
- - Who's the audience? (What will resonate?)
- - What are the constraints? (Brand guidelines, accessibility, performance)
-
-If any of these are unclear from the codebase, STOP and call the AskUserQuestion tool to clarify.
-
-**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
-
-**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
-
-## Plan Amplification
-
-Create a strategy to increase impact while maintaining coherence:
-
-- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
-- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
-- **Risk budget**: How experimental can we be? Push boundaries within constraints.
-- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
-
-**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration.
-
-## Amplify the Design
-
-Systematically increase impact across these dimensions:
-
-### Typography Amplification
-- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and [typography.md](typography.md) for inspiration)
-- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
-- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
-- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
-
-### Color Intensification
-- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
-- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop
-- **Dominant color strategy**: Let one bold color own 60% of the design
-- **Sharp accents**: High-contrast accent colors that pop
-- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
-- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
-
-### Spatial Drama
-- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
-- **Break the grid**: Let hero elements escape containers and cross boundaries
-- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
-- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
-- **Overlap**: Layer elements intentionally for depth
-
-### Visual Effects
-- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
-- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
-- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop)
-- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
-- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
-
-### Motion & Animation
-- **Entrance choreography**: Staggered, dramatic page load animations with 50-100ms delays
-- **Scroll effects**: Parallax, reveal animations, scroll-triggered sequences
-- **Micro-interactions**: Satisfying hover effects, click feedback, state changes
-- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect)
-
-### Composition Boldness
-- **Hero moments**: Create clear focal points with dramatic treatment
-- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
-- **Full-bleed elements**: Use full viewport width/height for impact
-- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
-
-**NEVER**:
-- Add effects randomly without purpose (chaos ≠ bold)
-- Sacrifice readability for aesthetics (body text must be readable)
-- Make everything bold (then nothing is bold; you need contrast)
-- Ignore accessibility (bold design must still meet WCAG standards)
-- Overwhelm with motion (animation fatigue is real)
-- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
-
-## Verify Quality
-
-Ensure amplification maintains usability and coherence:
-
-- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over.
-- **Still functional**: Can users accomplish tasks without distraction?
-- **Coherent**: Does everything feel intentional and unified?
-- **Memorable**: Will users remember this experience?
-- **Performant**: Do all these effects run smoothly?
-- **Accessible**: Does it still meet accessibility standards?
-
-**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects."
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,118 +0,0 @@
-# Brand register
-
-When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made.
-
-The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look.
-
-## The brand slop test
-
-If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?"
-
-Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home.
-
-**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register.
-
-Then the inverse test: in one sentence, describe what you're about to build the way a competitor would describe theirs. If that sentence fits the modal landing page in the category, restart.
-
-## Typography
-
-### Font selection procedure
-
-Every project. Never skip.
-
-1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words.
-2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture.
-3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy."
-4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over.
-
-### Reflex-reject list
-
-Training-data defaults. Ban list. Look further:
-
-Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif
-
-### Reflex-reject aesthetic lanes
-
-Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further.
-
-- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery.
-
-(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.)
-
-The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md).
-
-### Pairing and voice
-
-Distinctive + refined is the goal. The specific shape depends on the brand:
-
-- **Editorial / long-form / luxury**: display serif + sans body (a magazine shape).
-- **Tech / dev tools / fintech**: one committed sans, usually; custom-tight tracking, strong weight contrast inside a single family.
-- **Consumer / food / travel**: warmer pairings, often a humanist sans plus a script or display serif.
-- **Creative studios / agencies**: rule-breaking welcome. Mono-only, or display-only, or custom-drawn type as voice.
-
-Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair.
-
-Vary across projects. If the last brief was a serif-display landing page, this one isn't.
-
-### Scale
-
-Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted.
-
-Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room.
-
-## Color
-
-Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register.
-
-- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige.
-- Palette IS voice. A calm brand and a restless brand should not share palette mechanics.
-- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit.
-- Don't converge across projects. If the last brand surface was restrained-on-cream, this one is not.
-- When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette.
-
-## Layout
-
-- Asymmetric compositions are one option. Break the grid intentionally for emphasis.
-- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings.
-- Alternative: a strict, visible grid as the voice (brutalist / Swiss / tech-spec aesthetics). Either asymmetric or rigorously-gridded can be "designed"; the failure mode is splitting the difference into a generic centered stack.
-- Don't default to centering everything. Left-aligned with asymmetric layouts feels more designed; a strict grid reads as confident structure. A centered-stack hero with icon-title-subtitle cards reads as template.
-- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness.
-
-## Imagery
-
-Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo.
-
-**When the brief implies imagery (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product), you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy.
-
-- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `<div>` placeholders.
-- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel".
-- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one.
-- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish".
-
-"Imagery" here is broader than stock photography: product screenshots, custom data visualizations, generated SVG, and canvas/WebGL scenes are all imagery. Text-only pages where typography alone carries the entire visual weight are the failure mode.
-
-## Motion
-
-- One well-orchestrated page-load with staggered reveals beats scattered micro-interactions, when the brand invites it. Tech-minimal brands often skip entrance motion entirely; the restraint is the voice.
-- For collapsing/expanding sections, transition `grid-template-rows` rather than `height`.
-
-## Brand bans (on top of the shared absolute bans)
-
-- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume.
-- Large rounded-corner icons above every heading. Screams template.
-- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.)
-- All-caps body copy. Reserve caps for short labels and headings.
-- Timid palettes and average layouts. Safe = invisible.
-- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs.
-- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic.
-- Repeated tiny uppercase tracked labels above every section heading. A single strong kicker can be voice; repeating it as section grammar is AI scaffolding unless it's a deliberate, named brand system.
-
-## Brand permissions
-
-Brand can afford things product can't. Take them.
-
-- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography.
-- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing.
-- Typographic risk. Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines, a single oversize word as a hero.
-- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics.
-- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment.
@@ -1,174 +0,0 @@
-> **Additional context needed**: audience technical level and users' mental state in context.
-
-Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task.
-
-
----
-
-## Assess Current Copy
-
-Identify what makes the text unclear or ineffective:
-
-1. **Find clarity problems**:
- - **Jargon**: Technical terms users won't understand
- - **Ambiguity**: Multiple interpretations possible
- - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file"
- - **Length**: Too wordy or too terse
- - **Assumptions**: Assuming user knowledge they don't have
- - **Missing context**: Users don't know what to do or why
- - **Tone mismatch**: Too formal, too casual, or inappropriate for situation
-
-2. **Understand the context**:
- - Who's the audience? (Technical? General? First-time users?)
- - What's the user's mental state? (Stressed during error? Confident during success?)
- - What's the action? (What do we want users to do?)
- - What's the constraint? (Character limits? Space limitations?)
-
-**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets.
-
-## Plan Copy Improvements
-
-Create a strategy for clearer communication:
-
-- **Primary message**: What's the ONE thing users need to know?
-- **Action needed**: What should users do next (if anything)?
-- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?)
-- **Constraints**: Length limits, brand voice, localization considerations
-
-**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words.
-
-## Improve Copy Systematically
-
-Refine text across these common areas:
-
-### Error Messages
-**Bad**: "Error 403: Forbidden"
-**Good**: "You don't have permission to view this page. Contact your admin for access."
-
-**Bad**: "Invalid input"
-**Good**: "Email addresses need an @ symbol. Try: name@example.com"
-
-**Principles**:
-- Explain what went wrong in plain language
-- Suggest how to fix it
-- Don't blame the user
-- Include examples when helpful
-- Link to help/support if applicable
-
-### Form Labels & Instructions
-**Bad**: "DOB (MM/DD/YYYY)"
-**Good**: "Date of birth" (with placeholder showing format)
-
-**Bad**: "Enter value here"
-**Good**: "Your email address" or "Company name"
-
-**Principles**:
-- Use clear, specific labels (not generic placeholders)
-- Show format expectations with examples
-- Explain why you're asking (when not obvious)
-- Put instructions before the field, not after
-- Keep required field indicators clear
-
-### Button & CTA Text
-**Bad**: "Click here" | "Submit" | "OK"
-**Good**: "Create account" | "Save changes" | "Got it, thanks"
-
-**Principles**:
-- Describe the action specifically
-- Use active voice (verb + noun)
-- Match user's mental model
-- Be specific ("Save" is better than "OK")
-
-### Help Text & Tooltips
-**Bad**: "This is the username field"
-**Good**: "Choose a username. You can change this later in Settings."
-
-**Principles**:
-- Add value (don't just repeat the label)
-- Answer the implicit question ("What is this?" or "Why do you need this?")
-- Keep it brief but complete
-- Link to detailed docs if needed
-
-### Empty States
-**Bad**: "No items"
-**Good**: "No projects yet. Create your first project to get started."
-
-**Principles**:
-- Explain why it's empty (if not obvious)
-- Show next action clearly
-- Make it welcoming, not dead-end
-
-### Success Messages
-**Bad**: "Success"
-**Good**: "Settings saved! Your changes will take effect immediately."
-
-**Principles**:
-- Confirm what happened
-- Explain what happens next (if relevant)
-- Be brief but complete
-- Match the user's emotional moment (celebrate big wins)
-
-### Loading States
-**Bad**: "Loading..." (for 30+ seconds)
-**Good**: "Analyzing your data... this usually takes 30-60 seconds"
-
-**Principles**:
-- Set expectations (how long?)
-- Explain what's happening (when it's not obvious)
-- Show progress when possible
-- Offer escape hatch if appropriate ("Cancel")
-
-### Confirmation Dialogs
-**Bad**: "Are you sure?"
-**Good**: "Delete 'Project Alpha'? This can't be undone."
-
-**Principles**:
-- State the specific action
-- Explain consequences (especially for destructive actions)
-- Use clear button labels ("Delete project" not "Yes")
-- Don't overuse confirmations (only for risky actions)
-
-### Navigation & Wayfinding
-**Bad**: Generic labels like "Items" | "Things" | "Stuff"
-**Good**: Specific labels like "Your projects" | "Team members" | "Settings"
-
-**Principles**:
-- Be specific and descriptive
-- Use language users understand (not internal jargon)
-- Make hierarchy clear
-- Consider information scent (breadcrumbs, current location)
-
-## Apply Clarity Principles
-
-Every piece of copy should follow these rules:
-
-1. **Be specific**: "Enter email" not "Enter value"
-2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity)
-3. **Be active**: "Save changes" not "Changes will be saved"
-4. **Be human**: "Oops, something went wrong" not "System error encountered"
-5. **Tell users what to do**, not just what happened
-6. **Be consistent**: Use same terms throughout (don't vary for variety)
-
-**NEVER**:
-- Use jargon without explanation
-- Blame users ("You made an error" → "This field is required")
-- Be vague ("Something went wrong" without explanation)
-- Use passive voice unnecessarily
-- Write overly long explanations (be concise)
-- Use humor for errors (be empathetic instead)
-- Assume technical knowledge
-- Vary terminology (pick one term and stick with it)
-- Repeat information (headers restating intros, redundant explanations)
-- Use placeholders as the only labels (they disappear when users type)
-
-## Verify Improvements
-
-Test that copy improvements work:
-
-- **Comprehension**: Can users understand without context?
-- **Actionability**: Do users know what to do next?
-- **Brevity**: Is it as short as possible while remaining clear?
-- **Consistency**: Does it match terminology elsewhere?
-- **Tone**: Is it appropriate for the situation?
-
-When the copy reads cleanly, hand off to `/impeccable polish` for the final pass.
@@ -1,105 +0,0 @@
-# Codex: Visual Direction & Asset Production
-
-This file is loaded by `/impeccable craft` when the harness has native image generation (currently Codex via `image_gen`). Other harnesses skip it. It covers the two craft steps that depend on real image generation: landing the visual direction, and producing the raster assets the implementation will compose.
-
-Read this *before* generating any images. The order matters, and the per-step user pauses are what keep generated imagery from drifting away from the brief.
-
-### Four stop points before code
-
-Steps A through D each end with the user. Do not advance past any of them on your own read of the situation.
-
-1. **STOP after Step A questions.** Wait for answers.
-2. **STOP after Step B palette generation.** Wait for "confirm palette."
-3. **STOP after Step C mocks.** Wait for direction approval or delegation.
-4. **Only after Step D approves a direction** do you return to craft.md Step 4 and write code.
-
-Prior shape approval does **not** satisfy any of these. Shape's "confirm or override" advances you into Step A; it is not a substitute for it.
-
-## Step A: Explore Directions with the User
-
-Before generating anything, run a brief direction conversation grounded in the shape brief.
-
-**Step A is required even when shape just produced a confirmed brief.** The shape questions and Step A questions cover different ground: shape pins purpose, content, scope; Step A pins palette, atmosphere, and named visual references for the comps you're about to generate. The only time you can skip Step A is when the user has already answered these exact palette/atmosphere/reference questions in the same session.
-
-Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions:
-
-- "Brief says 'editorial restraint, Klim-adjacent.' Are we closer to a quiet specimen page or a magazine-spread feel with hero imagery?"
-- "Palette strategy from shape was 'Committed.' Want it warm-grounded (deep oxblood + cream) or cool-grounded (slate + paper white)?"
-
-**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded.
-
-## Step B: Generate the Brand Palette First
-
-Generate **one** palette artifact before any mocks. This is a small, focused image: typography pairing on the chosen background, primary + accent color swatches, one signature ornament or motif. Single image, single pass.
-
-Why palette first: mocks generated against a vague color sense produce noise that drowns out the structural decisions. A confirmed palette is the first concrete contract for everything downstream.
-
-Show the palette to the user. Ask one question: "This is the palette I'm locking in for the mocks. Confirm, or call out what to shift?"
-
-**STOP and wait for confirmation.** Do not generate mocks against an unconfirmed palette. "Probably good enough" is the wrong call here; the palette is the contract for everything downstream.
-
-## Step C: Generate 1-3 Visual Mocks Against the Palette
-
-Once the palette is confirmed, generate **1 to 3** high-fidelity north-star comps. Each mock must use the confirmed palette and typography. Mocks differ in *structural* direction (hierarchy, topology, density, composition), not in color or motif.
-
-- Brand work: push visual identity, composition, mood, and signature motifs.
-- Product work: push hierarchy, topology, density, tone, grounded in realistic product structure.
-- Landing pages and long-form brand surfaces: show enough of the second fold to establish the system beyond the hero.
-
-Use the `image_gen` tool directly (or via the imagegen skill when available). Don't ask the user to install anything.
-
-## Step D: Approval Loop
-
-Show the comps. Ask what carries forward. Iterate until **one direction is approved** or the user explicitly delegates.
-
-**STOP and wait for the approval or the delegation.** Do not begin Step E or return to craft.md Step 4 until a single direction is named. If the user delegates, pick the strongest direction and explain it from the brief, not personal taste.
-
-Before moving to assets, summarize what to carry into code and what *not* to literalize from the mock. This is the handoff between visual exploration and semantic implementation.
-
-## Step E: Mock Fidelity Inventory
-
-Inventory the approved mock's major visible ingredients. For each, decide implementation: semantic HTML/CSS/SVG, generated raster, sourced raster, icon library, canvas/WebGL, or accepted omission.
-
-Common ingredients to inventory:
-
-- Hero silhouette and dominant composition
-- Signature motifs (planets, devices, portraits, charts, route lines, insets, badges, etc.)
-- Nav and primary CTA treatment
-- Section sequence, especially the second fold
-- Image-native content the concept depends on
-- Typography, density, color/material treatment, motion cues
-
-Treat the mock as a north star, not a screenshot to trace. Don't rasterize core UI text. But if the live result lacks the mock's major ingredients, the implementation is wrong.
-
-If a photographic, architectural, product, or place-led mock becomes generic CSS scenery, decorative diagrams, bullets, or copy, stop and fix it. That's a broken implementation, not a harmless interpretation.
-
-Don't substitute a different hero composition or visual driver post-approval without user sign-off.
-
-## Step F: Asset Slicing via the Asset Producer
-
-Raster ingredients identified in Step E need clean production assets. Use the bundled `impeccable_asset_producer` subagent rather than producing inline.
-
-Spawn it as a scoped subagent. If you do not have explicit permission to use agents, stop and ask:
-
-```text
-Asset production will work better as a scoped subagent job. Should I spawn the Impeccable asset producer subagent for this step?
-```
-
-Pass to the agent:
-
-- Approved mock path or screenshot reference
-- Crop paths or a contact sheet with crop ids
-- Output directory
-- Required dimensions, format, transparency needs
-- Avoid list
-- Notes on what should remain semantic HTML/CSS/SVG instead of raster
-
-Attach image generation capability to the spawned agent when the harness supports it. Do **not** load image-generation reference material into the parent thread.
-
-Inline asset production is allowed only if the user declines subagents, the harness cannot spawn the authorized agent, or the user explicitly asks for single-thread mode.
-
-Prefer HTML/CSS/SVG/canvas when they can credibly reproduce an ingredient; reach for real, generated, or stock imagery when the mock or subject matter calls for actual visual content.
-
-## After This File
-
-Once Steps A through F are complete, return to `craft.md` Step 5 (Build to Production Quality). The implementation builds against the confirmed palette, approved mock, and the assets the producer wrote.
@@ -1,106 +0,0 @@
-# Cognitive Load Assessment
-
-Cognitive load is the total mental effort required to use an interface. Overloaded users make mistakes, get frustrated, and leave. This reference helps identify and fix cognitive overload.
-
----
-
-## Three Types of Cognitive Load
-
-### Intrinsic Load: The Task Itself
-Complexity inherent to what the user is trying to do. You can't eliminate this, but you can structure it.
-
-**Manage it by**:
-- Breaking complex tasks into discrete steps
-- Providing scaffolding (templates, defaults, examples)
-- Progressive disclosure: show what's needed now, hide the rest
-- Grouping related decisions together
-
-### Extraneous Load: Bad Design
-Mental effort caused by poor design choices. **Eliminate this ruthlessly.** It's pure waste.
-
-**Common sources**:
-- Confusing navigation that requires mental mapping
-- Unclear labels that force users to guess meaning
-- Visual clutter competing for attention
-- Inconsistent patterns that prevent learning
-- Unnecessary steps between user intent and result
-
-### Germane Load: Learning Effort
-Mental effort spent building understanding. This is *good* cognitive load; it leads to mastery.
-
-**Support it by**:
-- Progressive disclosure that reveals complexity gradually
-- Consistent patterns that reward learning
-- Feedback that confirms correct understanding
-- Onboarding that teaches through action, not walls of text
-
----
-
-## Cognitive Load Checklist
-
-Evaluate the interface against these 8 items:
-
-- [ ] **Single focus**: Can the user complete their primary task without distraction from competing elements?
-- [ ] **Chunking**: Is information presented in digestible groups (≤4 items per group)?
-- [ ] **Grouping**: Are related items visually grouped together (proximity, borders, shared background)?
-- [ ] **Visual hierarchy**: Is it immediately clear what's most important on the screen?
-- [ ] **One thing at a time**: Can the user focus on a single decision before moving to the next?
-- [ ] **Minimal choices**: Are decisions simplified (≤4 visible options at any decision point)?
-- [ ] **Working memory**: Does the user need to remember information from a previous screen to act on the current one?
-- [ ] **Progressive disclosure**: Is complexity revealed only when the user needs it?
-
-**Scoring**: Count the failed items. 0–1 failures = low cognitive load (good). 2–3 = moderate (address soon). 4+ = high cognitive load (critical fix needed).
-
----
-
-## The Working Memory Rule
-
-**Humans can hold ≤4 items in working memory at once** (Miller's Law revised by Cowan, 2001).
-
-At any decision point, count the number of distinct options, actions, or pieces of information a user must simultaneously consider:
-- **≤4 items**: Within working memory limits, manageable
-- **5–7 items**: Pushing the boundary; consider grouping or progressive disclosure
-- **8+ items**: Overloaded; users will skip, misclick, or abandon
-
-**Practical applications**:
-- Navigation menus: ≤5 top-level items (group the rest under clear categories)
-- Form sections: ≤4 fields visible per group before a visual break
-- Action buttons: 1 primary, 1–2 secondary, group the rest in a menu
-- Dashboard widgets: ≤4 key metrics visible without scrolling
-- Pricing tiers: ≤3 options (more causes analysis paralysis)
-
----
-
-## Common Cognitive Load Violations
-
-### 1. The Wall of Options
-**Problem**: Presenting 10+ choices at once with no hierarchy.
-**Fix**: Group into categories, highlight recommended, use progressive disclosure.
-
-### 2. The Memory Bridge
-**Problem**: User must remember info from step 1 to complete step 3.
-**Fix**: Keep relevant context visible, or repeat it where it's needed.
-
-### 3. The Hidden Navigation
-**Problem**: User must build a mental map of where things are.
-**Fix**: Always show current location (breadcrumbs, active states, progress indicators).
-
-### 4. The Jargon Barrier
-**Problem**: Technical or domain language forces translation effort.
-**Fix**: Use plain language. If domain terms are unavoidable, define them inline.
-
-### 5. The Visual Noise Floor
-**Problem**: Every element has the same visual weight; nothing stands out.
-**Fix**: Establish clear hierarchy: one primary element, 2–3 secondary, everything else muted.
-
-### 6. The Inconsistent Pattern
-**Problem**: Similar actions work differently in different places.
-**Fix**: Standardize interaction patterns. Same type of action = same type of UI.
-
-### 7. The Multi-Task Demand
-**Problem**: Interface requires processing multiple simultaneous inputs (reading + deciding + navigating).
-**Fix**: Sequence the steps. Let the user do one thing at a time.
-
-### 8. The Context Switch
-**Problem**: User must jump between screens/tabs/modals to gather info for a single decision.
-**Fix**: Co-locate the information needed for each decision. Reduce back-and-forth.
@@ -1,105 +0,0 @@
-# Color & Contrast
-
-## Color Spaces: Use OKLCH
-
-**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark.
-
-The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish.
-
-The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand.
-
-## Building Functional Palettes
-
-### Tinted Neutrals
-
-**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces.
-
-The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette.
-
-**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects.
-
-### Palette Structure
-
-A complete system needs:
-
-| Role | Purpose | Example |
-|------|---------|---------|
-| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades |
-| **Neutral** | Text, backgrounds, borders | 9-11 shade scale |
-| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each |
-| **Surface** | Cards, modals, overlays | 2-3 elevation levels |
-
-**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise.
-
-### The 60-30-10 Rule (Applied Correctly)
-
-This rule is about **visual weight**, not pixel count:
-
-- **60%**: Neutral backgrounds, white space, base surfaces
-- **30%**: Secondary colors: text, borders, inactive states
-- **10%**: Accent: CTAs, highlights, focus states
-
-The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power.
-
-## Contrast & Accessibility
-
-### WCAG Requirements
-
-| Content Type | AA Minimum | AAA Target |
-|--------------|------------|------------|
-| Body text | 4.5:1 | 7:1 |
-| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 |
-| UI components, icons | 3:1 | 4.5:1 |
-| Non-essential decorations | None | None |
-
-**The gotcha**: Placeholder text still needs 4.5:1. That light gray placeholder you see everywhere? Usually fails WCAG.
-
-### Dangerous Color Combinations
-
-These commonly fail contrast or cause readability issues:
-
-- Light gray text on white (the #1 accessibility fail)
-- **Gray text on any colored background**: gray looks washed out and dead on color. Use a darker shade of the background color, or transparency
-- Red text on green background (or vice versa): 8% of men can't distinguish these
-- Blue text on red background (vibrates visually)
-- Yellow text on white (almost always fails)
-- Thin light text on images (unpredictable contrast)
-
-### Never Use Pure Gray or Pure Black
-
-Pure gray (`oklch(50% 0 0)`) and pure black (`#000`) don't exist in nature; real shadows and surfaces always have a color cast. Even a chroma of 0.005-0.01 is enough to feel natural without being obviously tinted. (See tinted neutrals example above.)
-
-### Testing
-
-Don't trust your eyes. Use tools:
-
-- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/)
-- Browser DevTools → Rendering → Emulate vision deficiencies
-- [Polypane](https://polypane.app/) for real-time testing
-
-## Theming: Light & Dark Mode
-
-### Dark Mode Is Not Inverted Light Mode
-
-You can't just swap colors. Dark mode requires different design decisions:
-
-| Light Mode | Dark Mode |
-|------------|-----------|
-| Shadows for depth | Lighter surfaces for depth (no shadows) |
-| Dark text on light | Light text on dark (reduce font weight) |
-| Vibrant accents | Desaturate accents slightly |
-| White backgrounds | Never pure black; use dark gray (oklch 12-18%) |
-
-In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light.
-
-### Token Hierarchy
-
-Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same.
-
-## Alpha Is A Design Smell
-
-Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed.
-
----
-
-**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Using pure black (#000) for large areas. Skipping color blindness testing (8% of men affected).
@@ -1,154 +0,0 @@
-> **Additional context needed**: existing brand colors.
-
-Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit.
-
----
-
-## Register
-
-Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it.
-
-Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen.
-
----
-
-## Assess Color Opportunity
-
-Analyze the current state and identify opportunities:
-
-1. **Understand current state**:
- - **Color absence**: Pure grayscale? Limited neutrals? One timid accent?
- - **Missed opportunities**: Where could color add meaning, hierarchy, or delight?
- - **Context**: What's appropriate for this domain and audience?
- - **Brand**: Are there existing brand colors we should use?
-
-2. **Identify where color adds value**:
- - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue)
- - **Hierarchy**: Drawing attention to important elements
- - **Categorization**: Different sections, types, or states
- - **Emotional tone**: Warmth, energy, trust, creativity
- - **Wayfinding**: Helping users navigate and understand structure
- - **Delight**: Moments of visual interest and personality
-
-If any of these are unclear from the codebase, STOP and call the AskUserQuestion tool to clarify.
-
-**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose.
-
-## Plan Color Strategy
-
-Create a purposeful color introduction plan:
-
-- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals)
-- **Dominant color**: Which color owns 60% of colored elements?
-- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%)
-- **Application strategy**: Where does each color appear and why?
-
-**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more.
-
-## Introduce Color Strategically
-
-Add color systematically across these dimensions:
-
-### Semantic Color
-- **State indicators**:
- - Success: Green tones (emerald, forest, mint)
- - Error: Red/pink tones (rose, crimson, coral)
- - Warning: Orange/amber tones
- - Info: Blue tones (sky, ocean, indigo)
- - Neutral: Gray/slate for inactive states
-
-- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.)
-- **Progress indicators**: Colored bars, rings, or charts showing completion or health
-
-### Accent Color Application
-- **Primary actions**: Color the most important buttons/CTAs
-- **Links**: Add color to clickable text (maintain accessibility)
-- **Icons**: Colorize key icons for recognition and personality
-- **Headers/titles**: Add color to section headers or key labels
-- **Hover states**: Introduce color on interaction
-
-### Background & Surfaces
-- **Tinted backgrounds**: Replace pure gray (`#f5f5f5`) with warm neutrals (`oklch(97% 0.01 60)`) or cool tints (`oklch(97% 0.01 250)`)
-- **Colored sections**: Use subtle background colors to separate areas
-- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue)
-- **Cards & surfaces**: Tint cards or surfaces slightly for warmth
-
-**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
-
-### Data Visualization
-- **Charts & graphs**: Use color to encode categories or values
-- **Heatmaps**: Color intensity shows density or importance
-- **Comparison**: Color coding for different datasets or timeframes
-
-### Borders & Accents
-- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`)
-- **Underlines**: Color underlines for emphasis or active states
-- **Dividers**: Subtle colored dividers instead of gray lines
-- **Focus rings**: Colored focus indicators matching brand
-- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe
-
-**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe.
-
-### Typography Color
-- **Colored headings**: Use brand colors for section headings (maintain contrast)
-- **Highlight text**: Color for emphasis or categories
-- **Labels & tags**: Small colored labels for metadata or categories
-
-### Decorative Elements
-- **Illustrations**: Add colored illustrations or icons
-- **Shapes**: Geometric shapes in brand colors as background elements
-- **Gradients**: Colorful gradient overlays or mesh backgrounds
-- **Blobs/organic shapes**: Soft colored shapes for visual interest
-
-## Balance & Refinement
-
-Ensure color addition improves rather than overwhelms:
-
-### Maintain Hierarchy
-- **Dominant color** (60%): Primary brand color or most used accent
-- **Secondary color** (30%): Supporting color for variety
-- **Accent color** (10%): High contrast for key moments
-- **Neutrals** (remaining): Gray/black/white for structure
-
-### Accessibility
-- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components)
-- **Don't rely on color alone**: Use icons, labels, or patterns alongside color
-- **Test for color blindness**: Verify red/green combinations work for all users
-
-### Cohesion
-- **Consistent palette**: Use colors from defined palette, not arbitrary choices
-- **Systematic application**: Same color meanings throughout (green always = success)
-- **Temperature consistency**: Warm palette stays warm, cool stays cool
-
-**NEVER**:
-- Use every color in the rainbow (choose 2-4 colors beyond neutrals)
-- Apply color randomly without semantic meaning
-- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead
-- Use pure gray for neutrals. Add subtle color tint (warm or cool) for depth
-- Use pure black (`#000`) or pure white (`#fff`) for large areas
-- Violate WCAG contrast requirements
-- Use color as the only indicator (accessibility issue)
-- Make everything colorful (defeats the purpose)
-- Default to purple-blue gradients (AI slop aesthetic)
-
-## Verify Color Addition
-
-Test that colorization improves the experience:
-
-- **Better hierarchy**: Does color guide attention appropriately?
-- **Clearer meaning**: Does color help users understand states/categories?
-- **More engaging**: Does the interface feel warmer and more inviting?
-- **Still accessible**: Do all color combinations meet WCAG standards?
-- **Not overwhelming**: Is color balanced and purposeful?
-
-When the palette earns its place, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage.
-
-```json
-{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"}
-```
-
-Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract.
@@ -1,123 +0,0 @@
-# Craft Flow
-
-Build a feature with impeccable UX and UI quality: shape the design, land the visual direction, build real production code, inspect and improve in-browser until it meets a high-end studio bar.
-
-Before writing code, you need: PRODUCT.md loaded, register identified and the matching reference loaded, and a confirmed design direction for this task (either from `shape` or supplied by the user). PRODUCT.md is project context, not a task-specific brief.
-
-Treat any approved visual direction (generated mock or stated reference) as a concrete contract for composition, hierarchy, density, atmosphere, signature motifs, and distinctive visual moves. Don't let mocks replace structure, copy, accessibility, or state design. But if the live result lacks the approved direction's major ingredients, the implementation is wrong.
-
-### Gates: do not compress
-
-Craft has **multiple user gates**, not one. When the harness has native image generation (Codex via `image_gen`), the gate sequence before code is:
-
-1. **Shape brief confirmed** (Step 1)
-2. **Direction questions answered** (codex.md Step A)
-3. **Palette confirmed** (codex.md Step B)
-4. **One mock direction approved or delegated** (codex.md Step D)
-
-You must stop at every gate. **Shape confirmation alone is NOT a green light to start coding.** It is the green light to begin codex.md Step A. Compressing gates 2 through 4 because the shape brief felt complete is the dominant failure mode of this flow.
-
-When the harness lacks native image generation, gates 2-4 collapse into the brief itself, and shape confirmation does advance straight to code.
-
-## Step 0: Project Foundation
-
-Before shape, before code: figure out what kind of project you're working in.
-
-Look at the working directory. Run `ls`. Check for:
-
-- An existing framework: `astro.config.mjs/ts`, `next.config.js/ts`, `nuxt.config.ts`, `svelte.config.js`, `vite.config.js/ts`, `package.json` with framework deps, `Cargo.toml` + Leptos/Yew, `Gemfile` + Rails. **If found, use it.** Do not start a parallel build, do not introduce a second framework, do not write to `dist/` or `build/` directly. Whatever pipeline the project has, respect it.
-- An existing component library or design system: `src/components/`, `app/components/`, a `tokens.css` / `theme.ts`, an `astro.config` `integrations`. Read what's there before adding to it.
-- An existing icon set: `lucide-react`, `@phosphor-icons/react`, `@iconify/*`, hand-rolled SVG sprites in `assets/icons/`. **Use what's already in the project**; don't introduce a second set.
-
-If the directory is empty (greenfield), don't pick a framework silently. Ask the user via the AskUserQuestion tool, with sensible defaults framed by the brief:
-
-```text
-What should this be built on?
- - Astro (default for content-led brand sites, landing pages, marketing surfaces)
- - SvelteKit / Next.js / Nuxt (when the brief implies an app surface or significant interactivity)
- - Single index.html (one-shot demo, prototype, or a deliberately framework-free experiment)
-```
-
-Default: Astro for brand briefs, the project's existing framework for product briefs. Ask once; don't re-ask mid-task.
-
-## Step 1: Shape the Design
-
-Run /impeccable shape, passing along whatever feature description the user provided. Shape is **required** for craft; it is what produces a confirmed direction.
-
-Present the shape output and stop. Wait for the user to confirm, override, or course-correct before writing code.
-
-If the user already supplied a confirmed brief or ran shape separately, use it and skip this step.
-
-When the original prompt + PRODUCT.md already answer scope, content, and visual direction with no real ambiguity, the shape output can be **compact** (3-5 bullets stating what you're building and the visual lane, ending with one or two specific questions or "confirm or override"). The full 10-section structured brief is reserved for genuinely ambiguous, multi-screen, or stakeholder-heavy tasks. Don't pad a clear brief into a long one to look thorough; equally, don't skip the pause to look efficient.
-
-If the harness has native image generation (Codex), a compact shape's "confirm or override" advances to **Step 3 and the codex.md flow**, not to Step 4. Phrase the closing line accordingly: "Confirm or override; once we lock direction, I'll run a couple of palette and reference questions before generating any mocks." This stops the model from reading shape confirmation as code-green.
-
-## Step 2: Load References
-
-Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult:
-
-- [spatial-design.md](spatial-design.md) for layout and spacing
-- [typography.md](typography.md) for type hierarchy
-
-Then add references based on the brief's needs:
-- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md)
-- Animation or transitions? Consult [motion-design.md](motion-design.md)
-- Color-heavy or themed? Consult [color-and-contrast.md](color-and-contrast.md)
-- Responsive requirements? Consult [responsive-design.md](responsive-design.md)
-- Heavy on copy, labels, or errors? Consult [ux-writing.md](ux-writing.md)
-
-## Step 3: Visual Direction & Assets (Harness-Gated)
-
-If the harness has **native image generation** (currently Codex via `image_gen`), this step is mandatory. **Stop and load [codex.md](codex.md)**. It covers palette generation, mock exploration, the approval loop, mock-fidelity inventory, and asset slicing via the `impeccable_asset_producer` subagent. Follow Steps A-F in that file, then return here for Step 4.
-
-If the harness lacks native image generation, **state in one line that the visual-direction-by-generation step is being skipped because the harness lacks native image generation, then proceed**. The one-line announcement is required; it forces a conscious decision instead of letting the step quietly evaporate. The brief is your only visual reference. Implement directly from it, treating any named anchor references and the brief's "Design Direction" as the contract.
-
-Whether you generated mocks or not: don't replace required imagery with generic cards, bullets, emoji, fake metrics, decorative CSS panels, or filler copy. Image-led briefs (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product) need real or sourced imagery in the build, not CSS scenery.
-
-## Step 4: Build to Production Quality
-
-**Precondition.** If Step 3 routed you to codex.md (native image generation available), Steps A through D in that file must be complete before any code: questions answered, palette confirmed, mocks generated, one direction approved or delegated. **Do not mention implementation, file paths, or patch plans until that's done.** A confirmed shape brief is not enough; the model that compressed those gates is the model that already failed this flow.
-
-Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration.
-
-### Production bar
-
-- **Real content.** No placeholder copy, placeholder images, dead links, fake controls, or unused scaffold at presentation time.
-- **Preserve the approved mock's major ingredients.** Missing hero objects, world/product imagery, section structure, CTA/nav treatment, or distinctive motifs are blocking defects unless the user accepted the change.
-- **Semantic first.** Real headings, landmarks, labels, form associations, button/link semantics, accessible names, state announcements where needed.
-- **Deliberate spacing and alignment.** No default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment.
-- **Intentional typography.** Chosen loading strategy, clear hierarchy, readable measure, stable line breaks, no overflow at any width.
-- **Realistic state coverage.** Default, hover, focus-visible, active, disabled, loading, error, success, empty, overflow, long/short text, first-run.
-- **Finished interaction quality.** Keyboard paths, touch targets, feedback timing, scroll behavior, state transitions, no hover-only functionality.
-- **Coherent icon set.** Use the project's established set; otherwise pick one library or use accessible text. Don't mix.
-- **Respect the build pipeline.** Edit source files and run the project's build (`npm run build` or equivalent). Don't write to `build/` / `dist/` / `.next/` with `cat`, heredoc, or Bash redirects; that skips asset hashing, image optimization, code splitting, and CSS extraction, and produces output the dev server won't serve.
-- **Verify image URLs before referencing them.** Use image-search MCP or web-fetch when available; guessed photo IDs ship as broken-image placeholders. Without verification, prefer fewer images you're confident about.
-- **Optimized imagery and media.** Correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset`/`picture` for raster, no project-referenced asset left outside the workspace.
-- **Premium motion.** Use atmospheric blur, filter, mask, shadow, reveal when they improve the experience. Avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion.
-- **Maintainable.** Reusable local patterns, clear component boundaries, project conventions. No rasterized UI text or one-off hacks when a local pattern exists.
-- **Technically clean.** Production build passes, no console errors, no avoidable layout shift, no needless dependencies, no broken asset paths.
-- **Ask when uncertain.** If a discovery materially changes the brief or approved direction, stop and ask. Don't guess.
-
-## Step 5: Iterate Visually
-
-Look at what you built like a designer would. Your eyes are whatever the harness gives you: a connected browser, a screenshotting tool, Playwright, or asking the user. Use them for responsive testing (mobile, tablet, desktop minimum) and general visual validation.
-
-If your tool returns a file path, read the PNG back into the conversation. A screenshot you didn't read doesn't count.
-
-For long-form brand surfaces, inspect major sections individually. Thumbnails hide spacing, clipping, and cascade defects.
-
-After the first pass, write an honest critique against the brief, the approved mock's major ingredients (hero silhouette, motifs, imagery, nav/CTA, density), and impeccable's DON'Ts. Patch material defects and re-inspect. **Don't invent defects to demonstrate iteration.** A confident "first pass clean, shipping" beats a fake fix.
-
-Actively check: responsive behavior (composes, not shrinks), every state (empty / error / loading / edge), craft details (spacing, alignment, hierarchy, contrast, motion timing, focus), performance basics. The exit bar: defensible in a high-end studio review.
-
-Detector or QA output is defect evidence only; never proof the work is finished.
-
-## Step 6: Present
-
-Present the result to the user:
-- Show the feature in its primary state
-- Summarize the browser/viewports checked and the most important fixes made after inspection
-- Walk through the key states (empty, error, responsive)
-- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients.
-- Note any remaining limitations or follow-up risks honestly
-- Ask: "What's working? What isn't?"
@@ -1,236 +0,0 @@
-### Purpose
-
-Resolve one stable target, run two independent assessments, synthesize a design critique, persist a snapshot, and ask the user what to improve next. The chat response is the primary deliverable; the snapshot is an archive/backlog for future commands.
-
-### Hard Invariants
-
-- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
-- Assessment A must finish before detector findings enter the parent synthesis context. Detector output is deterministic, but it still anchors judgment.
-- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize.
-- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
-- Viewable targets require browser inspection when available.
-- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
-- Do not claim a user-visible overlay exists unless script injection succeeded and the detector ran in the page.
-
-### Setup
-
-1. **Resolve the target** to a concrete file path or URL. Prefer a source path over a dev-server URL when both identify the same surface; ports drift, paths do not.
- - "the homepage" -> `site/pages/index.astro` or `index.html`
- - "the settings modal" -> the primary component file
- - "this page" -> the current URL or source file
-2. **Compute the slug**:
- ```bash
- node .claude/skills/impeccable/scripts/critique-storage.mjs slug "<resolved-path-or-url>"
- ```
- Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique.
-3. **Read `.impeccable/critique/ignore.md`** if it exists. Drop matching findings silently; it is the only prior-run input critique consumes.
-
-### Assessment Orchestration
-
-Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis.
-
-If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
-
-### Assessment A: Design Review
-
-Read relevant source files and visually inspect the live page when browser automation is available. Think like a design director.
-
-Evaluate:
-- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill.
-- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases.
-- **Cognitive load**: consult [cognitive-load](cognitive-load.md); report checklist failures and decision points with >4 visible options.
-- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments.
-- **Nielsen heuristics**: consult [heuristics-scoring](heuristics-scoring.md); score all 10 heuristics 0-4.
-
-Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions.
-
-### Assessment B: Detector + Browser Evidence
-
-Run the bundled detector and browser visualization evidence. Assessment B is mandatory and must remain isolated from Assessment A until both are complete.
-
-CLI scan:
-```bash
-node .claude/skills/impeccable/scripts/detect.mjs --json [--fast] [target]
-```
-
-- Pass markup files/directories as `[target]`; do not pass CSS-only files.
-- For URLs, skip CLI scan and use browser visualization.
-- For 200+ scannable files, use `--fast`; for 500+, narrow scope or ask.
-- Exit code 0 = clean; 2 = findings.
-- If the detector entrypoint is missing or fails to load, report deterministic scan unavailable and continue with browser/manual review.
-
-Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
-
-1. Create a fresh tab and navigate.
-2. Preflight mutable injection by setting `document.title` and appending a `<script>` tag. Read-only evaluate APIs do not count.
-3. If mutation is unavailable, skip live server, browser presentation, and injection; report fallback signal.
-4. If mutation is available, start `node .claude/skills/impeccable/scripts/live-server.mjs --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then stop the live server.
-5. For multi-view targets, inject on 3-5 representative pages.
-
-Return: CLI findings JSON/counts, browser console findings if applicable, false positives, and skipped/failed browser steps with concrete reasons.
-
-After Assessment B returns usable CLI findings, reuse them. Do not rerun `detect.mjs` in the parent unless Assessment B failed, was truncated, or omitted count, rule names, or file locations.
-
-### Generate Combined Critique Report
-
-Synthesize both assessments into a single report. Do NOT simply concatenate. Weave the findings together, noting where the LLM review and detector agree, where the detector caught issues the LLM missed, and where detector findings are false positives.
-
-The chat response is the primary user-facing deliverable. Present the full structured critique below in chat; do not replace it with a summary and a link. The persisted snapshot is only an archive/backlog for later commands.
-
-Structure your feedback as a design director would:
-
-#### Design Health Score
-> *Consult [heuristics-scoring](heuristics-scoring.md)*
-
-Present the Nielsen's 10 heuristics scores as a table:
-
-| # | Heuristic | Score | Key Issue |
-|---|-----------|-------|-----------|
-| 1 | Visibility of System Status | ? | [specific finding or "n/a" if solid] |
-| 2 | Match System / Real World | ? | |
-| 3 | User Control and Freedom | ? | |
-| 4 | Consistency and Standards | ? | |
-| 5 | Error Prevention | ? | |
-| 6 | Recognition Rather Than Recall | ? | |
-| 7 | Flexibility and Efficiency | ? | |
-| 8 | Aesthetic and Minimalist Design | ? | |
-| 9 | Error Recovery | ? | |
-| 10 | Help and Documentation | ? | |
-| **Total** | | **??/40** | **[Rating band]** |
-
-Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32.
-
-#### Anti-Patterns Verdict
-
-**Start here.** Does this look AI-generated?
-
-**LLM assessment**: Your own evaluation of AI slop tells. Cover overall aesthetic feel, layout sameness, generic composition, missed opportunities for personality.
-
-**Deterministic scan**: Summarize what the automated detector found, with counts and file locations. Note any additional issues the detector caught that you missed, and flag any false positives.
-
-**Visual overlays** (if injection succeeded): Tell the user that overlays are now visible in the **[Human]** tab in their browser, highlighting the detected issues. Summarize what the console output reported. If browser visualization was attempted but injection failed, say that no reliable user-visible overlay is available and report the fallback signal instead.
-
-#### Overall Impression
-A brief gut reaction: what works, what doesn't, and the single biggest opportunity.
-
-#### What's Working
-Highlight 2-3 things done well. Be specific about why they work.
-
-#### Priority Issues
-The 3-5 most impactful design problems, ordered by importance.
-
-For each issue, tag with **P0-P3 severity** (consult [heuristics-scoring](heuristics-scoring.md) for severity definitions):
-- **[P?] What**: Name the problem clearly
-- **Why it matters**: How this hurts users or undermines goals
-- **Fix**: What to do about it (be concrete)
-- **Suggested command**: Which command could address this (from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-#### Persona Red Flags
-> *Consult [personas](personas.md)*
-
-Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `CLAUDE.md` contains a `## Design Context` section from `impeccable teach`, also generate 1-2 project-specific personas from the audience/brand info.
-
-For each selected persona, walk through the primary user action and list specific red flags found:
-
-**Alex (Power User)**: No keyboard shortcuts detected. Form requires 8 clicks for primary action. Forced modal onboarding. High abandonment risk.
-
-**Jordan (First-Timer)**: Icon-only nav in sidebar. Technical jargon in error messages ("404 Not Found"). No visible help. Will abandon at step 2.
-
-Be specific. Name the exact elements and interactions that fail each persona. Don't write generic persona descriptions; write what broke for them.
-
-#### Minor Observations
-Quick notes on smaller issues worth addressing.
-
-#### Questions to Consider
-Provocative questions that might unlock better solutions:
-- "What if the primary action were more prominent?"
-- "Does this need to feel this complex?"
-- "What would a confident version of this look like?"
-
-**Remember**:
-- Be direct. Vague feedback wastes everyone's time.
-- Be specific. "The submit button," not "some elements."
-- Say what's wrong AND why it matters to users.
-- Give concrete suggestions. Cut "consider exploring..." entirely.
-- Prioritize ruthlessly. If everything is important, nothing is.
-- Don't soften criticism. Developers need honest feedback to ship great design.
-
-### Persist the Snapshot
-
-Once the report above is finalized, write it to `.impeccable/critique/` so the user can refer back, and so `/impeccable polish` can pick up the priority issues without a copy-paste.
-
-Skip this step if the Setup slug was null (vague or root-level target).
-
-1. **Write the body to a temp file** so you can pipe it to the helper. Use the full critique report (heuristic table, anti-patterns verdict, priority issues, persona red flags, minor observations, and questions), but stop before the "Ask the User" / "Recommended Actions" sections that come later.
-
-2. **Pass the structured metadata** through `IMPECCABLE_CRITIQUE_META` (JSON), then run the write command:
- ```bash
- IMPECCABLE_CRITIQUE_META='{"target":"<user phrasing>","total_score":<n>,"p0_count":<n>,"p1_count":<n>}' \
- node .claude/skills/impeccable/scripts/critique-storage.mjs write <slug> <body-file>
- ```
- The helper prints the absolute path it wrote.
-
-3. **Delete the temp body file** after the write attempt completes, whether the write succeeded or failed. If deletion fails, mention `temp-file cleanup failed: <reason>` briefly in the final output, but do not block the critique.
-
-4. **Read the trend** for context:
- ```bash
- node .claude/skills/impeccable/scripts/critique-storage.mjs trend <slug> 5
- ```
- This returns a JSON array of the last 5 frontmatter entries (including the one you just wrote).
-
-5. **Append a single line to the user-visible output**, after the report and before the questions:
-
- > **Trend for `<slug>` (last 5 runs): 24 → 28 → 32 → 29 → 32**
- > Wrote `.impeccable/critique/<filename>`.
-
- If this is the first run for the slug, the trend is just one score; say so: "First run for this target, no trend yet."
-
-This is fire-and-forget. Do not show the user the helper's JSON output; only the human-readable trend line and the written path. Failures here should not block the rest of the flow; print the error and move on.
-
-### Ask the User
-
-**After presenting findings**, use targeted questions based on what was actually found. STOP and call the AskUserQuestion tool to clarify. These answers will shape the action plan.
-
-Ask questions along these lines (adapt to the specific findings; do NOT ask generic questions):
-
-1. **Priority direction**: Based on the issues found, ask which category matters most to the user right now. For example: "I found problems with visual hierarchy, color usage, and information overload. Which area should we tackle first?" Offer the top 2-3 issue categories as options.
-
-2. **Design intent**: If the critique found a tonal mismatch, ask whether it was intentional. For example: "The interface feels clinical and corporate. Is that the intended tone, or should it feel warmer/bolder/more playful?" Offer 2-3 tonal directions as options based on what would fix the issues found.
-
-3. **Scope**: Ask how much the user wants to take on. For example: "I found N issues. Want to address everything, or focus on the top 3?" Offer scope options like "Top 3 only", "All issues", "Critical issues only".
-
-4. **Constraints** (optional; only ask if relevant): If the findings touch many areas, ask if anything is off-limits. For example: "Should any sections stay as-is?" This prevents the plan from touching things the user considers done.
-
-**Rules for questions**:
-- Every question must reference specific findings from the report. Never ask generic "who is your audience?" questions.
-- Keep it to 2-4 questions maximum. Respect the user's time.
-- Offer concrete options, not open-ended prompts.
-- If findings are straightforward (e.g., only 1-2 clear issues), skip questions and go directly to Recommended Actions.
-
-### Recommended Actions
-
-**After receiving the user's answers**, present a prioritized action summary reflecting the user's priorities and scope from Ask the User.
-
-#### Action Summary
-
-List recommended commands in priority order, based on the user's answers:
-
-1. **`/command-name`**: Brief description of what to fix (specific context from critique findings)
-2. **`/command-name`**: Brief description (specific context)
-...
-
-**Rules for recommendations**:
-- Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset
-- Order by the user's stated priorities first, then by impact
-- Each item's description should carry enough context that the command knows what to focus on
-- Map each Priority Issue to the appropriate command
-- Skip commands that would address zero issues
-- If the user chose a limited scope, only include items within that scope
-- If the user marked areas as off-limits, exclude commands that would touch those areas
-- End with `/impeccable polish` as the final step if any fixes were recommended
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable critique` after fixes to see your score improve.
@@ -1,302 +0,0 @@
-> **Additional context needed**: what's appropriate for the domain (playful vs professional vs quirky vs elegant).
-
-Find the moments where personality and unexpected polish would turn a functional interface into one users remember and tell other people about. Add only where the moment earns it; delight everywhere reads as noise.
-
----
-
-## Register
-
-Brand: delight can be distributed across copy voice, section transitions, discovery rewards, seasonal touches, personality across the whole surface.
-
-Product: delight at specific moments, not pages. Completion, first-time actions, error recovery, milestone crossings. Reliability and consistency carry the rest of the experience; delight pushed everywhere reads as noise.
-
----
-
-## Assess Delight Opportunities
-
-Identify where delight would enhance (not distract from) the experience:
-
-1. **Find natural delight moments**:
- - **Success states**: Completed actions (save, send, publish)
- - **Empty states**: First-time experiences, onboarding
- - **Loading states**: Waiting periods that could be entertaining
- - **Achievements**: Milestones, streaks, completions
- - **Interactions**: Hover states, clicks, drags
- - **Errors**: Softening frustrating moments
- - **Easter eggs**: Hidden discoveries for curious users
-
-2. **Understand the context**:
- - What's the brand personality? (Playful? Professional? Quirky? Elegant?)
- - Who's the audience? (Tech-savvy? Creative? Corporate?)
- - What's the emotional context? (Accomplishment? Exploration? Frustration?)
- - What's appropriate? (Banking app ≠ gaming app)
-
-3. **Define delight strategy**:
- - **Subtle sophistication**: Refined micro-interactions (luxury brands)
- - **Playful personality**: Whimsical illustrations and copy (consumer apps)
- - **Helpful surprises**: Anticipating needs before users ask (productivity tools)
- - **Sensory richness**: Satisfying sounds, smooth animations (creative tools)
-
-If any of these are unclear from the codebase, STOP and call the AskUserQuestion tool to clarify.
-
-**CRITICAL**: Delight should enhance usability, never obscure it. If users notice the delight more than accomplishing their goal, you've gone too far.
-
-## Delight Principles
-
-Follow these guidelines:
-
-### Delight Amplifies, Never Blocks
-- Delight moments should be quick (< 1 second)
-- Never delay core functionality for delight
-- Make delight skippable or subtle
-- Respect user's time and task focus
-
-### Surprise and Discovery
-- Hide delightful details for users to discover
-- Reward exploration and curiosity
-- Don't announce every delight moment
-- Let users share discoveries with others
-
-### Appropriate to Context
-- Match delight to emotional moment (celebrate success, empathize with errors)
-- Respect the user's state (don't be playful during critical errors)
-- Match brand personality and audience expectations
-- Cultural sensitivity (what's delightful varies by culture)
-
-### Compound Over Time
-- Delight should remain fresh with repeated use
-- Vary responses (not same animation every time)
-- Reveal deeper layers with continued use
-- Build anticipation through patterns
-
-## Delight Techniques
-
-Add personality and joy through these methods:
-
-### Micro-interactions & Animation
-
-**Button delight**:
-```css
-/* Satisfying button press */
-.button {
- transition: transform 0.1s, box-shadow 0.1s;
-}
-.button:active {
- transform: translateY(2px);
- box-shadow: 0 2px 4px rgba(0,0,0,0.2);
-}
-
-/* Ripple effect on click */
-/* Smooth lift on hover */
-.button:hover {
- transform: translateY(-2px);
- transition: transform 0.2s cubic-bezier(0.25, 1, 0.5, 1); /* ease-out-quart */
-}
-```
-
-**Loading delight**:
-- Playful loading animations (not just spinners)
-- Personality in loading messages (write product-specific ones, not generic AI filler)
-- Progress indication with encouraging messages
-- Skeleton screens with subtle animations
-
-**Success animations**:
-- Checkmark draw animation
-- Confetti burst for major achievements
-- Gentle scale + fade for confirmation
-- Satisfying sound effects (subtle)
-
-**Hover surprises**:
-- Icons that animate on hover
-- Color shifts or glow effects
-- Tooltip reveals with personality
-- Cursor changes (custom cursors for branded experiences)
-
-### Personality in Copy
-
-**Playful error messages**:
-```
-"Error 404"
-"This page is playing hide and seek. (And winning)"
-
-"Connection failed"
-"Looks like the internet took a coffee break. Want to retry?"
-```
-
-**Encouraging empty states**:
-```
-"No projects"
-"Your canvas awaits. Create something amazing."
-
-"No messages"
-"Inbox zero! You're crushing it today."
-```
-
-**Playful labels & tooltips**:
-```
-"Delete"
-"Send to void" (for playful brand)
-
-"Help"
-"Rescue me" (tooltip)
-```
-
-**IMPORTANT**: Match copy personality to brand. Banks shouldn't be wacky, but they can be warm.
-
-### Illustrations & Visual Personality
-
-**Custom illustrations**:
-- Empty state illustrations (not stock icons)
-- Error state illustrations (friendly monsters, quirky characters)
-- Loading state illustrations (animated characters)
-- Success state illustrations (celebrations)
-
-**Icon personality**:
-- Custom icon set matching brand personality
-- Animated icons (subtle motion on hover/click)
-- Illustrative icons (more detailed than generic)
-- Consistent style across all icons
-
-**Background effects**:
-- Subtle particle effects
-- Gradient mesh backgrounds
-- Geometric patterns
-- Parallax depth
-- Time-of-day themes (morning vs night)
-
-### Satisfying Interactions
-
-**Drag and drop delight**:
-- Lift effect on drag (shadow, scale)
-- Snap animation when dropped
-- Satisfying placement sound
-- Undo toast ("Dropped in wrong place? [Undo]")
-
-**Toggle switches**:
-- Smooth slide with spring physics
-- Color transition
-- Haptic feedback on mobile
-- Optional sound effect
-
-**Progress & achievements**:
-- Streak counters with celebratory milestones
-- Progress bars that "celebrate" at 100%
-- Badge unlocks with animation
-- Playful stats ("You're on fire! 5 days in a row")
-
-**Form interactions**:
-- Input fields that animate on focus
-- Checkboxes with a satisfying scale pulse when checked
-- Success state that celebrates valid input
-- Auto-grow textareas
-
-### Sound Design
-
-**Subtle audio cues** (when appropriate):
-- Notification sounds (distinctive but not annoying)
-- Success sounds (satisfying "ding")
-- Error sounds (empathetic, not harsh)
-- Typing sounds for chat/messaging
-- Ambient background audio (very subtle)
-
-**IMPORTANT**:
-- Respect system sound settings
-- Provide mute option
-- Keep volumes quiet (subtle cues, not alarms)
-- Don't play on every interaction (sound fatigue is real)
-
-### Easter Eggs & Hidden Delights
-
-**Discovery rewards**:
-- Konami code unlocks special theme
-- Hidden keyboard shortcuts (Cmd+K for special features)
-- Hover reveals on logos or illustrations
-- Alt text jokes on images (for screen reader users too!)
-- Console messages for developers ("Like what you see? We're hiring!")
-
-**Seasonal touches**:
-- Holiday themes (subtle, tasteful)
-- Seasonal color shifts
-- Weather-based variations
-- Time-based changes (dark at night, light during day)
-
-**Contextual personality**:
-- Different messages based on time of day
-- Responses to specific user actions
-- Randomized variations (not same every time)
-- Progressive reveals with continued use
-
-### Loading & Waiting States
-
-**Make waiting engaging**:
-- Interesting loading messages that rotate
-- Progress bars with personality
-- Mini-games during long loads
-- Fun facts or tips while waiting
-- Countdown with encouraging messages
-
-```
-Loading messages: write ones specific to your product, not generic AI filler:
-- "Crunching your latest numbers..."
-- "Syncing with your team's changes..."
-- "Preparing your dashboard..."
-- "Checking for updates since yesterday..."
-```
-
-**WARNING**: Avoid cliched loading messages like "Herding pixels", "Teaching robots to dance", "Consulting the magic 8-ball", "Counting backwards from infinity". These are AI-slop copy, instantly recognizable as machine-generated. Write messages that are specific to what your product actually does.
-
-### Celebration Moments
-
-**Success celebrations**:
-- Confetti for major milestones
-- Animated checkmarks for completions
-- Progress bar celebrations at 100%
-- "Achievement unlocked" style notifications
-- Personalized messages ("You published your 10th article!")
-
-**Milestone recognition**:
-- First-time actions get special treatment
-- Streak tracking and celebration
-- Progress toward goals
-- Anniversary celebrations
-
-## Implementation Patterns
-
-**Animation libraries**:
-- Framer Motion (React)
-- GSAP (universal)
-- Lottie (After Effects animations)
-- Canvas confetti (party effects)
-
-**Sound libraries**:
-- Howler.js (audio management)
-- Use-sound (React hook)
-
-**Physics libraries**:
-- React Spring (spring physics)
-- Popmotion (animation primitives)
-
-**IMPORTANT**: File size matters. Compress images, optimize animations, lazy load delight features.
-
-**NEVER**:
-- Delay core functionality for delight
-- Force users through delightful moments (make skippable)
-- Use delight to hide poor UX
-- Overdo it (less is more)
-- Ignore accessibility (animate responsibly, provide alternatives)
-- Make every interaction delightful (special moments should be special)
-- Sacrifice performance for delight
-- Be inappropriate for context (read the room)
-
-## Verify Delight Quality
-
-Test that delight actually delights:
-
-- **User reactions**: Do users smile? Share screenshots?
-- **Doesn't annoy**: Still pleasant after 100th time?
-- **Doesn't block**: Can users opt out or skip?
-- **Performant**: No jank, no slowdown
-- **Appropriate**: Matches brand and context
-- **Accessible**: Works with reduced motion, screen readers
-
-When the moments feel earned, hand off to `/impeccable polish` for the final pass.
@@ -1,111 +0,0 @@
-Strip a design to its essence. Remove anything that doesn't earn its place: redundant elements, repeated information, decorative noise, cosmetic complexity.
-
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel complex or cluttered:
-
-1. **Identify complexity sources**:
- - **Too many elements**: Competing buttons, redundant information, visual clutter
- - **Excessive variation**: Too many colors, fonts, sizes, styles without purpose
- - **Information overload**: Everything visible at once, no progressive disclosure
- - **Visual noise**: Unnecessary borders, shadows, backgrounds, decorations
- - **Confusing hierarchy**: Unclear what matters most
- - **Feature creep**: Too many options, actions, or paths forward
-
-2. **Find the essence**:
- - What's the primary user goal? (There should be ONE)
- - What's actually necessary vs nice-to-have?
- - What can be removed, hidden, or combined?
- - What's the 20% that delivers 80% of value?
-
-If any of these are unclear from the codebase, STOP and call the AskUserQuestion tool to clarify.
-
-**CRITICAL**: Simplicity is not about removing features. It's about removing obstacles between users and their goals. Every element should justify its existence.
-
-## Plan Simplification
-
-Create a ruthless editing strategy:
-
-- **Core purpose**: What's the ONE thing this should accomplish?
-- **Essential elements**: What's truly necessary to achieve that purpose?
-- **Progressive disclosure**: What can be hidden until needed?
-- **Consolidation opportunities**: What can be combined or integrated?
-
-**IMPORTANT**: Simplification is hard. It requires saying no to good ideas to make room for great execution. Be ruthless.
-
-## Simplify the Design
-
-Systematically remove complexity across these dimensions:
-
-### Information Architecture
-- **Reduce scope**: Remove secondary actions, optional features, redundant information
-- **Progressive disclosure**: Hide complexity behind clear entry points (accordions, modals, step-through flows)
-- **Combine related actions**: Merge similar buttons, consolidate forms, group related content
-- **Clear hierarchy**: ONE primary action, few secondary actions, everything else tertiary or hidden
-- **Remove redundancy**: If it's said elsewhere, don't repeat it here
-
-### Visual Simplification
-- **Reduce color palette**: Use 1-2 colors plus neutrals, not 5-7 colors
-- **Limit typography**: One font family, 3-4 sizes maximum, 2-3 weights
-- **Remove decorations**: Eliminate borders, shadows, backgrounds that don't serve hierarchy or function
-- **Flatten structure**: Reduce nesting, remove unnecessary containers; never nest cards inside cards
-- **Remove unnecessary cards**: Cards aren't needed for basic layout; use spacing and alignment instead
-- **Consistent spacing**: Use one spacing scale, remove arbitrary gaps
-
-### Layout Simplification
-- **Linear flow**: Replace complex grids with simple vertical flow where possible
-- **Remove sidebars**: Move secondary content inline or hide it
-- **Full-width**: Use available space generously instead of complex multi-column layouts
-- **Consistent alignment**: Pick left or center, stick with it
-- **Generous white space**: Let content breathe, don't pack everything tight
-
-### Interaction Simplification
-- **Reduce choices**: Fewer buttons, fewer options, clearer path forward (paradox of choice is real)
-- **Smart defaults**: Make common choices automatic, only ask when necessary
-- **Inline actions**: Replace modal flows with inline editing where possible
-- **Remove steps**: Can signup be one step instead of three? Can checkout be simplified?
-- **Clear CTAs**: ONE obvious next step, not five competing actions
-
-### Content Simplification
-- **Shorter copy**: Cut every sentence in half, then do it again
-- **Active voice**: "Save changes" not "Changes will be saved"
-- **Remove jargon**: Plain language always wins
-- **Scannable structure**: Short paragraphs, bullet points, clear headings
-- **Essential information only**: Remove marketing fluff, legalese, hedging
-- **Remove redundant copy**: No headers restating intros, no repeated explanations, say it once
-
-### Code Simplification
-- **Remove unused code**: Dead CSS, unused components, orphaned files
-- **Flatten component trees**: Reduce nesting depth
-- **Consolidate styles**: Merge similar styles, use utilities consistently
-- **Reduce variants**: Does that component need 12 variations, or can 3 cover 90% of cases?
-
-**NEVER**:
-- Remove necessary functionality (simplicity ≠ feature-less)
-- Sacrifice accessibility for simplicity (clear labels and ARIA still required)
-- Make things so simple they're unclear (mystery ≠ minimalism)
-- Remove information users need to make decisions
-- Eliminate hierarchy completely (some things should stand out)
-- Oversimplify complex domains (match complexity to actual task complexity)
-
-## Verify Simplification
-
-Ensure simplification improves usability:
-
-- **Faster task completion**: Can users accomplish goals more quickly?
-- **Reduced cognitive load**: Is it easier to understand what to do?
-- **Still complete**: Are all necessary features still accessible?
-- **Clearer hierarchy**: Is it obvious what matters most?
-- **Better performance**: Does simpler design load faster?
-
-## Document Removed Complexity
-
-If you removed features or options:
-- Document why they were removed
-- Consider if they need alternative access points
-- Note any user feedback to monitor
-
-When the cuts feel right, hand off to `/impeccable polish` for the final pass. As Antoine de Saint-Exupéry put it: "Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away."
@@ -1,427 +0,0 @@
-Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
-
-DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
-
-## The frontmatter: token schema
-
-The YAML frontmatter is the machine-readable layer. It's what Stitch's linter validates and what the live panel renders tiles from. Keep it tight; every entry should correspond to a token the project actually uses.
-
-```yaml
----
-name: <project title>
-description: <one-line tagline>
-colors:
- primary: "#b8422e"
- neutral-bg: "#faf7f2"
- # ...one entry per extracted color; key = descriptive slug
-typography:
- display:
- fontFamily: "Cormorant Garamond, Georgia, serif"
- fontSize: "clamp(2.5rem, 7vw, 4.5rem)"
- fontWeight: 300
- lineHeight: 1
- letterSpacing: "normal"
- body:
- # ...
-rounded:
- sm: "4px"
- md: "8px"
-spacing:
- sm: "8px"
- md: "16px"
-components:
- button-primary:
- backgroundColor: "{colors.primary}"
- textColor: "{colors.neutral-bg}"
- rounded: "{rounded.sm}"
- padding: "16px 48px"
- button-primary-hover:
- backgroundColor: "{colors.primary-deep}"
----
-```
-
-Rules that matter:
-
-- **Token refs** use `{path.to.token}` (e.g. `{colors.primary}`, `{rounded.md}`). Components may reference primitives; primitives may not reference each other.
-- **Stitch validates colors as hex sRGB only** (`#RGB` / `#RGBA` / `#RRGGBB` / `#RRGGBBAA`); OKLCH/HSL/P3 trigger a linter warning, not a hard error. YAML accepts the string either way and our own parser is format-agnostic. Choose based on project posture: (a) if the project has an "OKLCH-only" doctrine or uses Display-P3 values that don't round-trip through sRGB, put OKLCH directly in the frontmatter and accept the Stitch linter warning; (b) if the project wants strict Stitch compliance or plans to use their Tailwind/DTCG export pipeline, put hex in the frontmatter and keep OKLCH in prose as the canonical reference. Never split the source of truth without explicit reason.
-- **Component sub-tokens** are limited to 8 props: `backgroundColor`, `textColor`, `typography`, `rounded`, `padding`, `size`, `height`, `width`. Shadows, motion, focus rings, backdrop-filter: none of those fit. Carry them in the sidecar (Step 4b).
-- **Scale keys are open-ended.** Use whatever names the project already uses (`warm-ash-cream`, `surface-container-low`). Don't rename to Material defaults.
-- **Variants are naming convention, not schema.** `button-primary` / `button-primary-hover` / `button-primary-active` as sibling keys.
-
-## The markdown body: six sections (exact order)
-
-1. `## Overview`
-2. `## Colors`
-3. `## Typography`
-4. `## Elevation`
-5. `## Components`
-6. `## Do's and Don'ts`
-
-Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] Palette` (Stitch's own outputs do this), but the literal word in each header (Overview, Colors, Typography, Elevation, Components, Do's and Don'ts) must be present. Do NOT add extra top-level sections (Layout Principles, Responsive Behavior, Motion, Agent Prompt Guide). Fold that content into the six spec sections where it naturally belongs.
-
-## When to run
-
-- The user just ran `/impeccable teach` and needs the visual side documented.
-- The skill noticed no `DESIGN.md` exists and nudged the user to create one.
-- An existing `DESIGN.md` is stale (the design has drifted).
-- Before a large redesign, to capture the current state as a reference.
-
-If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user the existing file and STOP and call the AskUserQuestion tool to clarify. whether to refresh, overwrite, or merge.
-
-## Two paths
-
-- **Scan mode** (default): the project has design tokens, components, or rendered output. Extract, then confirm descriptive language. Use when there's code to analyze.
-- **Seed mode**: the project is pre-implementation (fresh teach, nothing built yet). Interview for five high-level answers, write a minimal DESIGN.md marked `<!-- SEED -->`. Re-run in scan mode once there's code.
-
-Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode; don't silently switch. `/impeccable document --seed` forces seed mode regardless of code presence.
-
-## Scan mode (approach C: auto-extract, then confirm descriptive language)
-
-### Step 1: Find the design assets
-
-Search the codebase in priority order:
-
-1. **CSS custom properties**: grep for `--color-`, `--font-`, `--spacing-`, `--radius-`, `--shadow-`, `--ease-`, `--duration-` declarations in CSS files (usually `src/styles/`, `public/css/`, `app/globals.css`, etc.). Record name, value, and the file it's defined in.
-2. **Tailwind config**: if `tailwind.config.{js,ts,mjs}` exists, read the `theme.extend` block for colors, fontFamily, spacing, borderRadius, boxShadow.
-3. **CSS-in-JS theme files**: styled-components, emotion, vanilla-extract, stitches; look for `theme.ts`, `tokens.ts`, or equivalent.
-4. **Design token files**: `tokens.json`, `design-tokens.json`, Style Dictionary output, W3C token community group format.
-5. **Component library**: scan the main button, card, input, navigation, dialog components. Note their variant APIs and default styles.
-6. **Global stylesheet**: the root CSS file usually has the base typography and color assignments.
-7. **Visible rendered output**: if browser automation tools are available, load the live site and sample computed styles from key elements (body, h1, a, button, .card). This catches values that tokens miss.
-
-### Step 2: Auto-extract what can be auto-extracted
-
-Build a structured draft from the discovered tokens. For each token class:
-
-- **Colors**: Group into Primary / Secondary / Tertiary / Neutral (the Material-derived roles Stitch uses). If the project only has one accent, express it as Primary + Neutral; omit Secondary and Tertiary rather than inventing them.
-- **Typography**: Map observed sizes and weights to the Material hierarchy (display / headline / title / body / label). Note font-family stacks and the scale ratio.
-- **Elevation**: Catalogue the shadow vocabulary. If the project is flat and uses tonal layering instead, that's a valid answer; state it explicitly.
-- **Components**: For each common component (button, card, input, chip, list item, tooltip, nav), extract shape (radius), color assignment, hover/focus treatment, internal padding.
-- **Spacing + layout**: Fold into Overview or relevant Components. The spec does NOT have a Layout section.
-
-### Step 2b: Stage the frontmatter
-
-From the auto-extracted tokens, draft the YAML frontmatter now (you'll write it at the top of DESIGN.md in Step 4). This is the machine-readable layer: what the live panel and Stitch's linter consume.
-
-- **Colors**: one entry per extracted color. Key = descriptive slug (`warm-ash-cream`, `editorial-magenta`, not `blue-800`). Value = whichever format the project treats as canonical (OKLCH or hex; see the frontmatter rules above). Don't split the source of truth: one format in the frontmatter, don't redefine the same token in prose with a different value.
-- **Typography**: one entry per role (`display`, `headline`, `title`, `body`, `label`). Typography is an object; include only the props that are real for the project (`fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `fontFeature`, `fontVariation`).
-- **Rounded / Spacing**: whatever scale steps the project actually uses, keyed by whatever scale name the project uses (`sm` / `md` / `lg`, or `surface-sm`, or numeric steps).
-- **Components**: one entry per variant (`button-primary`, `button-primary-hover`, `button-ghost`). Reference primitives via `{colors.X}`, `{rounded.Y}`. If a variant needs a property Stitch's 8-prop set doesn't cover (shadow, focus ring, backdrop-filter), carry the full snippet in the sidecar instead.
-
-Skip anything the project doesn't have. Empty scale keys or fabricated tokens pollute the spec.
-
-### Step 3: Ask the user for qualitative language
-
-The following require creative input that cannot be auto-extracted. Group them into one `AskUserQuestion` interaction:
-
-- **Creative North Star**: a single named metaphor for the whole system ("The Editorial Sanctuary", "The Golden State Curator", "The Lab Notebook"). Offer 2-3 options that honor PRODUCT.md's brand personality.
-- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, anti-references (what the system should not feel like).
-- **Color character** (for auto-extracted colors): descriptive names ("Deep Muted Teal-Navy", not "blue-800"). Suggest 2-3 options per key color based on hue/saturation.
-- **Elevation philosophy**: flat/layered/lifted. If shadows exist, is their role ambient or structural?
-- **Component philosophy**: the feel of buttons, cards, inputs in one phrase ("tactile and confident" vs. "refined and restrained").
-
-Quote a line from PRODUCT.md when possible so the user sees their own strategic language carry forward.
-
-### Step 4: Write DESIGN.md
-
-The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the structure below. Headers must match character-for-character. Optional evocative subtitles (e.g. `## 2. Colors: The Coastal Palette`) are allowed.
-
-```markdown
----
-name: [Project Title]
-description: [one-line tagline]
-colors:
- # ... staged frontmatter from Step 2b
----
-
-# Design System: [Project Title]
-
-## 1. Overview
-
-**Creative North Star: "[Named metaphor in quotes]"**
-
-[2-3 paragraph holistic description: personality, density, aesthetic philosophy. Start from the North Star and work outward. State what this system explicitly rejects (pulled from PRODUCT.md's anti-references). End with a short **Key Characteristics:** bullet list.]
-
-## 2. Colors
-
-[Describe the palette character in one sentence.]
-
-### Primary
-- **[Descriptive Name]** (#HEX / oklch(...)): [Where and why this color is used. Be specific about context, not just role.]
-
-### Secondary (optional; omit if the project has only one accent)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Tertiary (optional)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Neutral
-- **[Descriptive Name]** (#HEX): [Text / background / border / divider role.]
-- [...]
-
-### Named Rules (optional, powerful)
-**The [Rule Name] Rule.** [Short, forceful prohibition or doctrine, e.g. "The One Voice Rule. The primary accent is used on ≤10% of any given screen. Its rarity is the point."]
-
-## 3. Typography
-
-**Display Font:** [Family] (with [fallback])
-**Body Font:** [Family] (with [fallback])
-**Label/Mono Font:** [Family, if distinct]
-
-**Character:** [1-2 sentence personality description of the pairing.]
-
-### Hierarchy
-- **Display** ([weight], [size/clamp], [line-height]): [Purpose; where it appears.]
-- **Headline** ([weight], [size], [line-height]): [Purpose.]
-- **Title** ([weight], [size], [line-height]): [Purpose.]
-- **Body** ([weight], [size], [line-height]): [Purpose. Include max line length like 65–75ch if relevant.]
-- **Label** ([weight], [size], [letter-spacing], [case if uppercase]): [Purpose.]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [Short doctrine about type use.]
-
-## 4. Elevation
-
-[One paragraph: does this system use shadows, tonal layering, or a hybrid? If "no shadows", say so explicitly and describe how depth is conveyed instead.]
-
-### Shadow Vocabulary (if applicable)
-- **[Role name]** (`box-shadow: [exact value]`): [When to use it.]
-- [...]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [e.g. "The Flat-By-Default Rule. Surfaces are flat at rest. Shadows appear only as a response to state (hover, elevation, focus)."]
-
-## 5. Components
-
-For each component, lead with a short character line, then specify shape, color assignment, states, and any distinctive behavior.
-
-### Buttons
-- **Shape:** [radius described, exact value in parens]
-- **Primary:** [color assignment + padding, in semantic + exact terms]
-- **Hover / Focus:** [transitions, treatments]
-- **Secondary / Ghost / Tertiary (if applicable):** [brief description]
-
-### Chips (if used)
-- **Style:** [background, text color, border treatment]
-- **State:** [selected / unselected, filter / action variants]
-
-### Cards / Containers
-- **Corner Style:** [radius]
-- **Background:** [colors used]
-- **Shadow Strategy:** [reference Elevation section]
-- **Border:** [if any]
-- **Internal Padding:** [scale]
-
-### Inputs / Fields
-- **Style:** [stroke, background, radius]
-- **Focus:** [treatment, e.g. glow, border shift, etc.]
-- **Error / Disabled:** [if applicable]
-
-### Navigation
-- **Style, typography, default/hover/active states, mobile treatment.**
-
-### [Signature Component] (optional; if the project has a distinctive custom component worth documenting)
-[Description.]
-
-## 6. Do's and Don'ts
-
-Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: include exact colors, pixel values, and named anti-patterns the user mentioned in PRODUCT.md. **Every anti-reference in PRODUCT.md should show up here as a "Don't" with the same language**, so the visual spec carries the strategic line through. Quote PRODUCT.md directly where possible: if PRODUCT.md says *"avoid dark mode with purple gradients, neon accents, glassmorphism"*, the Don'ts here should repeat that by name.
-
-### Do:
-- **Do** [specific prescription with exact values / named rule].
-- **Do** [...]
-
-### Don't:
-- **Don't** [specific prohibition, e.g. "use border-left greater than 1px as a colored stripe"].
-- **Don't** [...]
-- **Don't** [...]
-```
-
-### Step 4b: Write .impeccable/design.json sidecar (extensions only)
-
-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.
-
-Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.
-
-#### Schema
-
-```json
-{
- "schemaVersion": 2,
- "generatedAt": "ISO-8601 string",
- "title": "Design System: [Project Title]",
- "extensions": {
- "colorMeta": {
- "primary": { "role": "primary", "displayName": "Editorial Magenta", "canonical": "oklch(60% 0.25 350)", "tonalRamp": ["...", "...", "..."] },
- "warm-ash-cream": { "role": "neutral", "displayName": "Warm Ash Cream", "canonical": "oklch(96% 0.005 350)", "tonalRamp": ["...", "...", "..."] }
- },
- "typographyMeta": {
- "display": { "displayName": "Display", "purpose": "Hero headlines only." }
- },
- "shadows": [
- { "name": "ambient-low", "value": "0 4px 24px rgba(0,0,0,0.12)", "purpose": "Diffuse hover glow under accent elements." }
- ],
- "motion": [
- { "name": "ease-standard", "value": "cubic-bezier(0.4, 0, 0.2, 1)", "purpose": "Default easing for state transitions." }
- ],
- "breakpoints": [
- { "name": "sm", "value": "640px" }
- ]
- },
- "components": [
- {
- "name": "Primary Button",
- "kind": "button | input | nav | chip | card | custom",
- "refersTo": "button-primary",
- "description": "One-line what and when.",
- "html": "<button class=\"ds-btn-primary\">GET STARTED</button>",
- "css": ".ds-btn-primary { background: #191c1d; color: #fff; padding: 16px 48px; letter-spacing: 0.05em; text-transform: uppercase; font-weight: 500; border: none; border-radius: 0; transition: background 0.2s, transform 0.2s; } .ds-btn-primary:hover { background: oklch(60% 0.25 350); transform: translateY(-2px); }"
- }
- ],
- "narrative": {
- "northStar": "The Editorial Sanctuary",
- "overview": "2-3 paragraphs of the philosophy, pulled from DESIGN.md Overview section.",
- "keyCharacteristics": ["...", "..."],
- "rules": [{ "name": "The One Voice Rule", "body": "...", "section": "colors|typography|elevation" }],
- "dos": ["Do use ..."],
- "donts": ["Don't use ..."]
- }
-}
-```
-
-**What changed from schemaVersion 1.** The old sidecar carried token primitive arrays (`tokens.colors[]`, `tokens.typography[]`, etc.). Those values now live in the frontmatter. The sidecar only carries metadata that can't live in the frontmatter (tonal ramps, canonical OKLCH when the hex is an approximation, display names, role hints), keyed by the frontmatter token name (`colorMeta.<token-name>`, `typographyMeta.<token-name>`). Components still carry full HTML/CSS because Stitch's 8-prop set can't hold them.
-
-#### Component translation rules
-
-The `html` and `css` fields must be **self-contained, drop-in snippets** that render correctly when injected into a shadow DOM. The panel applies them directly: no post-processing, no framework runtime.
-
-1. **Tailwind expansion.** If the source uses Tailwind (className="bg-primary text-white rounded-lg px-6 py-3"), expand every utility to literal CSS properties in the `css` string. Do **not** reference Tailwind classes; do **not** assume a Tailwind CSS bundle is loaded. Each component is self-contained.
-2. **Token resolution.** If the project exposes tokens as CSS custom properties on `:root` (e.g. `--color-primary`, `--radius-md`), reference them via `var(--color-primary)`; they inherit through the shadow DOM and stay live-bound. If tokens live only in JS theme objects (styled-components, CSS-in-JS), resolve to literal values at generation time.
-3. **Icons.** Inline as SVG. Do not reference Lucide/Heroicons packages, icon fonts, or `<img src="...">`. A typical icon is 16-24px; copy the SVG path data directly.
-4. **States.** Include `:hover`, `:focus-visible`, and (if meaningful) `:active` rules inline. A static default-only snapshot makes the panel feel dead. Hover + focus rules in the CSS make it feel alive.
-5. **Reset bloat.** Extract only the component's *distinctive* CSS (background, color, padding, border-radius, typography, transition). Skip universal resets (`box-sizing: border-box`, `line-height: inherit`, `-webkit-font-smoothing`). The panel already has a neutral canvas; don't re-ship resets.
-6. **Scoped class names.** Prefix every class with `ds-` (e.g. `ds-btn-primary`, `ds-input-search`) so component CSS doesn't collide with other components' CSS in the same shadow DOM.
-
-#### What to include
-
-Aim for a tight set of **5-10 components** that best represent the visual system:
-
-- **Canonical primitives (always include if the project has them):** button (each variant as a separate component entry), input/text field, navigation, chip/tag, card.
-- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.
-- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.
-
-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.
-
-#### Tonal ramps
-
-For each color token, generate an 8-step `tonalRamp` array: dark to light, same hue and chroma, stepped lightness from ~15% to ~95%. The panel renders this as a strip under the swatch. If the project already defines a tonal scale (Material `surface-container-low` family, Tailwind-style `blue-50..blue-900`), use those values. Otherwise synthesize in OKLCH.
-
-#### Narrative mapping
-
-Pull directly from the DESIGN.md you just wrote:
-
-- `narrative.northStar` → the `**Creative North Star: "..."**` line from Overview
-- `narrative.overview` → the philosophy paragraphs from Overview
-- `narrative.keyCharacteristics` → the bulleted `**Key Characteristics:**` list
-- `narrative.rules` → every `**The [Name] Rule.** [body]` across all sections, tagged with `section`
-- `narrative.dos` / `narrative.donts` → the bullet lists from Do's and Don'ts verbatim
-
-Do not reword. The panel shows these as secondary collapsible context; the same voice that's in the Markdown carries through.
-
-### Step 5: Confirm, refine, and refresh session cache
-
-1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).
-2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.
-3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"
-4. **Refresh the session cache.** Run `node .claude/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.
-
-## Seed mode
-
-For projects with no visual system to extract yet. Produces a minimal scaffold, not a full spec.
-
-### Step 1: Confirm seed mode
-
-Before interviewing: "There's no existing visual system to scan. I'll ask five quick questions to seed a starter DESIGN.md. You can re-run `/impeccable document` once there's code, to capture the real tokens and components. OK?"
-
-If the user prefers to skip, stop. No file.
-
-### Step 2: Five questions
-
-Group into one `AskUserQuestion` interaction. Options must be concrete.
-
-1. **Color strategy.** Pick one:
- - Restrained: tinted neutrals + one accent ≤10%
- - Committed: one saturated color carries 30–60% of the surface
- - Full palette: 3–4 named color roles, each deliberate
- - Drenched: the surface IS the color
-
- Then: one hue family or anchor reference ("deep teal", "mustard", "Klim #ff4500 orange").
-
-2. **Typography direction.** Pick one (specific fonts come later):
- - Serif display + sans body
- - Single sans (warm / technical / geometric / humanist; pick a feel)
- - Display + mono
- - Mono-forward
- - Editorial script + sans
-
-3. **Motion energy.** Pick one:
- - Restrained: state changes only
- - Responsive: feedback + transitions, no choreography
- - Choreographed: orchestrated entrances, scroll-driven sequences
-
-4. **Three named references.** Brands, products, printed objects. Not adjectives.
-
-5. **One anti-reference.** What it should NOT feel like. Also named.
-
-### Step 3: Write seed DESIGN.md
-
-Use the six-section spec from Scan mode. Populate what the interview answers; leave the rest as honest placeholders. The seed is a scaffold, not a fabricated spec.
-
-Lead the file with:
-
-```markdown
-<!-- SEED: re-run /impeccable document once there's code to capture the actual tokens and components. -->
-```
-
-Per-section guidance in seed mode:
-
-- **Overview**: Creative North Star and philosophy phrased from the answers (color strategy + motion energy + references). Reference the user's anti-reference directly.
-- **Colors**: Color strategy as a Named Rule (e.g. *"The Drenched Rule. The surface IS the color."*). Hue family or anchor reference. No hex values; mark as `[to be resolved during implementation]`.
-- **Typography**: the direction the user picked (e.g. "Serif display + sans body"). No font names yet: `[font pairing to be chosen at implementation]`.
-- **Elevation**: inferred from motion energy. Restrained/Responsive → flat by default; Choreographed → layered. One sentence.
-- **Components**: omit entirely; no components exist yet.
-- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.
-
-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.
-
-### Step 4: Confirm and refresh session cache
-
-1. Show the seed DESIGN.md. Call out that it is a seed (the marker is the literal commitment).
-2. Tell the user: "Re-run `/impeccable document` once you have some code. That pass will extract real tokens and generate the sidecar."
-3. Run `node .claude/skills/impeccable/scripts/load-context.mjs` once so the seed lands in conversation for the rest of the session.
-
-## Style guidelines
-
-- **Frontmatter first, prose second.** Tokens go in the YAML frontmatter; prose contextualizes them. Don't redefine a token value in two places; the frontmatter is normative.
-- **Cite PRODUCT.md anti-references by name** in the Do's and Don'ts section. If PRODUCT.md lists "SaaS landing-page clichés" or "generic AI tool marketing" as anti-references, the DESIGN.md Don'ts should repeat those phrases verbatim so the visual spec enforces the strategic line.
-- **Match the spec, don't invent new sections.** The six section names are fixed. If you have Layout/Motion/Responsive content to document, fold it into Overview (philosophy-level rules) or Components (per-component behavior).
-- **Descriptive > technical**: "Gently curved edges (8px radius)" > "rounded-lg". Include the technical value in parens, lead with the description.
-- **Functional > decorative**: for each token, explain WHERE and WHY it's used, not just WHAT it is.
-- **Exact values in parens**: hex codes, px/rem values, font weights; always the number in parens alongside the description.
-- **Use Named Rules**: `**The [Name] Rule.** [short doctrine]`. These are memorable, citable, and much stickier for AI consumers than bullet lists. Stitch's own outputs use them heavily ("The No-Line Rule", "The Ghost Border Fallback"). Aim for 1-3 per section.
-- **Be forceful**. The voice of a design director. "Prohibited", "forbidden", "never", "always", not "consider", "might", "prefer". Match PRODUCT.md's tone.
-- **Concrete anti-pattern tests**. Stitch writes things like *"If it looks like a 2014 app, the shadow is too dark and the blur is too small."* A one-sentence audit test beats a paragraph of principle.
-- **Reference PRODUCT.md**. The anti-references section of PRODUCT.md should directly inform the Do's and Don'ts section here. Quote or paraphrase.
-- **Group colors by role**, not by hex-order or hue-order. Primary / Secondary / Tertiary / Neutral is the spec ordering.
-
-## Pitfalls
-
-- Don't paste raw CSS class names. Translate to descriptive language.
-- Don't extract every token. Stop at what's actually reused; one-offs pollute the system.
-- Don't invent components that don't exist. If the project only has buttons and cards, only document those.
-- Don't overwrite an existing DESIGN.md without asking.
-- Don't duplicate content from PRODUCT.md. DESIGN.md is strictly visual.
-- Don't add a "Layout Principles" or "Motion" or "Responsive Behavior" top-level section. The spec has six, not nine. Fold that content where it belongs.
-- Don't rename sections even slightly. "Colors" not "Color Palette & Roles". "Typography" not "Typography Rules". Tooling parsing depends on exact headers.
-- Don't duplicate token values between frontmatter and prose. If a color is in `colors.primary` as hex, the prose can name it and describe its role but should not reassert a different hex. The frontmatter is normative.
-- Don't invent frontmatter token groups outside Stitch's schema (no `motion:`, `breakpoints:`, `shadows:` at the top level). Stitch's Zod schema only accepts `colors`, `typography`, `rounded`, `spacing`, `components`. Anything else belongs in the sidecar's `extensions`.
@@ -1,69 +0,0 @@
-# Extract Flow
-
-Identify reusable patterns, components, and design tokens, then extract and consolidate them into the design system for systematic reuse.
-
-## Step 1: Discover the Design System
-
-Find the design system, component library, or shared UI directory. Understand its structure: component organization, naming conventions, design token structure, import/export conventions.
-
-**CRITICAL**: If no design system exists, STOP and call the AskUserQuestion tool to clarify. before creating one. Understand the preferred location and structure first.
-
-## Step 2: Identify Patterns
-
-Look for extraction opportunities in the target area:
-
-- **Repeated components**: Similar UI patterns used 3+ times (buttons, cards, inputs)
-- **Hard-coded values**: Colors, spacing, typography, shadows that should be tokens
-- **Inconsistent variations**: Multiple implementations of the same concept
-- **Composition patterns**: Layout or interaction patterns that repeat (form rows, toolbar groups, empty states)
-- **Type styles**: Repeated font-size + weight + line-height combinations
-- **Animation patterns**: Repeated easing, duration, or keyframe combinations
-
-Assess value: only extract things used 3+ times with the same intent. Premature abstraction is worse than duplication.
-
-## Step 3: Plan Extraction
-
-Create a systematic plan:
-
-- **Components to extract**: Which UI elements become reusable components?
-- **Tokens to create**: Which hard-coded values become design tokens?
-- **Variants to support**: What variations does each component need?
-- **Naming conventions**: Component names, token names, prop names that match existing patterns
-- **Migration path**: How to refactor existing uses to consume the new shared versions
-
-**IMPORTANT**: Design systems grow incrementally. Extract what is clearly reusable now, not everything that might someday be reusable.
-
-## Step 4: Extract & Enrich
-
-Build improved, reusable versions:
-
-- **Components**: Clear props API with sensible defaults, proper variants for different use cases, accessibility built in (ARIA, keyboard navigation, focus management), documentation and usage examples
-- **Design tokens**: Clear naming (primitive vs semantic), proper hierarchy and organization, documentation of when to use each token
-- **Patterns**: When to use this pattern, code examples, variations and combinations
-
-## Step 5: Migrate
-
-Replace existing uses with the new shared versions:
-
-- **Find all instances**: Search for the patterns you extracted
-- **Replace systematically**: Update each use to consume the shared version
-- **Test thoroughly**: Ensure visual and functional parity
-- **Delete dead code**: Remove the old implementations
-
-## Step 6: Document
-
-Update design system documentation:
-
-- Add new components to the component library
-- Document token usage and values
-- Add examples and guidelines
-- Update any Storybook or component catalog
-
-**NEVER**:
-- Extract one-off, context-specific implementations without generalization
-- Create components so generic they are useless
-- Extract without considering existing design system conventions
-- Skip proper TypeScript types or prop documentation
-- Create tokens for every single value (tokens should have semantic meaning)
-- Extract things that differ in intent (two buttons that look similar but serve different purposes should stay separate)
-
@@ -1,347 +0,0 @@
-Designs that only work with perfect data aren't production-ready. Harden the interface against the inputs, errors, languages, and network conditions that real users will throw at it.
-
-## Assess Hardening Needs
-
-Identify weaknesses and edge cases:
-
-1. **Test with extreme inputs**:
- - Very long text (names, descriptions, titles)
- - Very short text (empty, single character)
- - Special characters (emoji, RTL text, accents)
- - Large numbers (millions, billions)
- - Many items (1000+ list items, 50+ options)
- - No data (empty states)
-
-2. **Test error scenarios**:
- - Network failures (offline, slow, timeout)
- - API errors (400, 401, 403, 404, 500)
- - Validation errors
- - Permission errors
- - Rate limiting
- - Concurrent operations
-
-3. **Test internationalization**:
- - Long translations (German is often 30% longer than English)
- - RTL languages (Arabic, Hebrew)
- - Character sets (Chinese, Japanese, Korean, emoji)
- - Date/time formats
- - Number formats (1,000 vs 1.000)
- - Currency symbols
-
-**CRITICAL**: Designs that only work with perfect data aren't production-ready. Harden against reality.
-
-## Hardening Dimensions
-
-Systematically improve resilience:
-
-### Text Overflow & Wrapping
-
-**Long text handling**:
-```css
-/* Single line with ellipsis */
-.truncate {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* Multi-line with clamp */
-.line-clamp {
- display: -webkit-box;
- -webkit-line-clamp: 3;
- -webkit-box-orient: vertical;
- overflow: hidden;
-}
-
-/* Allow wrapping */
-.wrap {
- word-wrap: break-word;
- overflow-wrap: break-word;
- hyphens: auto;
-}
-```
-
-**Flex/Grid overflow**:
-```css
-/* Prevent flex items from overflowing */
-.flex-item {
- min-width: 0; /* Allow shrinking below content size */
- overflow: hidden;
-}
-
-/* Prevent grid items from overflowing */
-.grid-item {
- min-width: 0;
- min-height: 0;
-}
-```
-
-**Responsive text sizing**:
-- Use `clamp()` for fluid typography
-- Set minimum readable sizes (14px on mobile)
-- Test text scaling (zoom to 200%)
-- Ensure containers expand with text
-
-### Internationalization (i18n)
-
-**Text expansion**:
-- Add 30-40% space budget for translations
-- Use flexbox/grid that adapts to content
-- Test with longest language (usually German)
-- Avoid fixed widths on text containers
-
-```jsx
-// ❌ Bad: Assumes short English text
-<button className="w-24">Submit</button>
-
-// ✅ Good: Adapts to content
-<button className="px-4 py-2">Submit</button>
-```
-
-**RTL (Right-to-Left) support**:
-```css
-/* Use logical properties */
-margin-inline-start: 1rem; /* Not margin-left */
-padding-inline: 1rem; /* Not padding-left/right */
-border-inline-end: 1px solid; /* Not border-right */
-
-/* Or use dir attribute */
-[dir="rtl"] .arrow { transform: scaleX(-1); }
-```
-
-**Character set support**:
-- Use UTF-8 encoding everywhere
-- Test with Chinese/Japanese/Korean (CJK) characters
-- Test with emoji (they can be 2-4 bytes)
-- Handle different scripts (Latin, Cyrillic, Arabic, etc.)
-
-**Date/Time formatting**:
-```javascript
-// ✅ Use Intl API for proper formatting
-new Intl.DateTimeFormat('en-US').format(date); // 1/15/2024
-new Intl.DateTimeFormat('de-DE').format(date); // 15.1.2024
-
-new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: 'USD'
-}).format(1234.56); // $1,234.56
-```
-
-**Pluralization**:
-```javascript
-// ❌ Bad: Assumes English pluralization
-`${count} item${count !== 1 ? 's' : ''}`
-
-// ✅ Good: Use proper i18n library
-t('items', { count }) // Handles complex plural rules
-```
-
-### Error Handling
-
-**Network errors**:
-- Show clear error messages
-- Provide retry button
-- Explain what happened
-- Offer offline mode (if applicable)
-- Handle timeout scenarios
-
-```jsx
-// Error states with recovery
-{error && (
- <ErrorMessage>
- <p>Failed to load data. {error.message}</p>
- <button onClick={retry}>Try again</button>
- </ErrorMessage>
-)}
-```
-
-**Form validation errors**:
-- Inline errors near fields
-- Clear, specific messages
-- Suggest corrections
-- Don't block submission unnecessarily
-- Preserve user input on error
-
-**API errors**:
-- Handle each status code appropriately
- - 400: Show validation errors
- - 401: Redirect to login
- - 403: Show permission error
- - 404: Show not found state
- - 429: Show rate limit message
- - 500: Show generic error, offer support
-
-**Graceful degradation**:
-- Core functionality works without JavaScript
-- Images have alt text
-- Progressive enhancement
-- Fallbacks for unsupported features
-
-### Edge Cases & Boundary Conditions
-
-**Empty states**:
-- No items in list
-- No search results
-- No notifications
-- No data to display
-- Provide clear next action
-
-**Loading states**:
-- Initial load
-- Pagination load
-- Refresh
-- Show what's loading ("Loading your projects...")
-- Time estimates for long operations
-
-**Large datasets**:
-- Pagination or virtual scrolling
-- Search/filter capabilities
-- Performance optimization
-- Don't load all 10,000 items at once
-
-**Concurrent operations**:
-- Prevent double-submission (disable button while loading)
-- Handle race conditions
-- Optimistic updates with rollback
-- Conflict resolution
-
-**Permission states**:
-- No permission to view
-- No permission to edit
-- Read-only mode
-- Clear explanation of why
-
-**Browser compatibility**:
-- Polyfills for modern features
-- Fallbacks for unsupported CSS
-- Feature detection (not browser detection)
-- Test in target browsers
-
-### Input Validation & Sanitization
-
-**Client-side validation**:
-- Required fields
-- Format validation (email, phone, URL)
-- Length limits
-- Pattern matching
-- Custom validation rules
-
-**Server-side validation** (always):
-- Never trust client-side only
-- Validate and sanitize all inputs
-- Protect against injection attacks
-- Rate limiting
-
-**Constraint handling**:
-```html
-<!-- Set clear constraints -->
-<input
- type="text"
- maxlength="100"
- pattern="[A-Za-z0-9]+"
- required
- aria-describedby="username-hint"
-/>
-<small id="username-hint">
- Letters and numbers only, up to 100 characters
-</small>
-```
-
-### Accessibility Resilience
-
-**Keyboard navigation**:
-- All functionality accessible via keyboard
-- Logical tab order
-- Focus management in modals
-- Skip links for long content
-
-**Screen reader support**:
-- Proper ARIA labels
-- Announce dynamic changes (live regions)
-- Descriptive alt text
-- Semantic HTML
-
-**Motion sensitivity**:
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**High contrast mode**:
-- Test in Windows high contrast mode
-- Don't rely only on color
-- Provide alternative visual cues
-
-### Performance Resilience
-
-**Slow connections**:
-- Progressive image loading
-- Skeleton screens
-- Optimistic UI updates
-- Offline support (service workers)
-
-**Memory leaks**:
-- Clean up event listeners
-- Cancel subscriptions
-- Clear timers/intervals
-- Abort pending requests on unmount
-
-**Throttling & Debouncing**:
-```javascript
-// Debounce search input
-const debouncedSearch = debounce(handleSearch, 300);
-
-// Throttle scroll handler
-const throttledScroll = throttle(handleScroll, 100);
-```
-
-## Testing Strategies
-
-**Manual testing**:
-- Test with extreme data (very long, very short, empty)
-- Test in different languages
-- Test offline
-- Test slow connection (throttle to 3G)
-- Test with screen reader
-- Test keyboard-only navigation
-- Test on old browsers
-
-**Automated testing**:
-- Unit tests for edge cases
-- Integration tests for error scenarios
-- E2E tests for critical paths
-- Visual regression tests
-- Accessibility tests (axe, WAVE)
-
-**IMPORTANT**: Hardening is about expecting the unexpected. Real users will do things you never imagined.
-
-**NEVER**:
-- Assume perfect input (validate everything)
-- Ignore internationalization (design for global)
-- Leave error messages generic ("Error occurred")
-- Forget offline scenarios
-- Trust client-side validation alone
-- Use fixed widths for text
-- Assume English-length text
-- Block entire interface when one component errors
-
-## Verify Hardening
-
-Test thoroughly with edge cases:
-
-- **Long text**: Try names with 100+ characters
-- **Emoji**: Use emoji in all text fields
-- **RTL**: Test with Arabic or Hebrew
-- **CJK**: Test with Chinese/Japanese/Korean
-- **Network issues**: Disable internet, throttle connection
-- **Large datasets**: Test with 1000+ items
-- **Concurrent actions**: Click submit 10 times rapidly
-- **Errors**: Force API errors, test all error states
-- **Empty**: Remove all data, test empty states
-
-When edge cases are covered, hand off to `/impeccable polish` for the final pass.
@@ -1,234 +0,0 @@
-# Heuristics Scoring Guide
-
-Score each of Nielsen's 10 Usability Heuristics on a 0–4 scale. Be honest: a 4 means genuinely excellent, not "good enough."
-
-## Nielsen's 10 Heuristics
-
-### 1. Visibility of System Status
-
-Keep users informed about what's happening through timely, appropriate feedback.
-
-**Check for**:
-- Loading indicators during async operations
-- Confirmation of user actions (save, submit, delete)
-- Progress indicators for multi-step processes
-- Current location in navigation (breadcrumbs, active states)
-- Form validation feedback (inline, not just on submit)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No feedback; user is guessing what happened |
-| 1 | Rare feedback; most actions produce no visible response |
-| 2 | Partial; some states communicated, major gaps remain |
-| 3 | Good; most operations give clear feedback, minor gaps |
-| 4 | Excellent; every action confirms, progress is always visible |
-
-### 2. Match Between System and Real World
-
-Speak the user's language. Follow real-world conventions. Information appears in natural, logical order.
-
-**Check for**:
-- Familiar terminology (no unexplained jargon)
-- Logical information order matching user expectations
-- Recognizable icons and metaphors
-- Domain-appropriate language for the target audience
-- Natural reading flow (left-to-right, top-to-bottom priority)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Pure tech jargon, alien to users |
-| 1 | Mostly confusing; requires domain expertise to navigate |
-| 2 | Mixed; some plain language, some jargon leaks through |
-| 3 | Mostly natural; occasional term needs context |
-| 4 | Speaks the user's language fluently throughout |
-
-### 3. User Control and Freedom
-
-Users need a clear "emergency exit" from unwanted states without extended dialogue.
-
-**Check for**:
-- Undo/redo functionality
-- Cancel buttons on forms and modals
-- Clear navigation back to safety (home, previous)
-- Easy way to clear filters, search, selections
-- Escape from long or multi-step processes
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Users get trapped; no way out without refreshing |
-| 1 | Difficult exits; must find obscure paths to escape |
-| 2 | Some exits; main flows have escape, edge cases don't |
-| 3 | Good control; users can exit and undo most actions |
-| 4 | Full control; undo, cancel, back, and escape everywhere |
-
-### 4. Consistency and Standards
-
-Users shouldn't wonder whether different words, situations, or actions mean the same thing.
-
-**Check for**:
-- Consistent terminology throughout the interface
-- Same actions produce same results everywhere
-- Platform conventions followed (standard UI patterns)
-- Visual consistency (colors, typography, spacing, components)
-- Consistent interaction patterns (same gesture = same behavior)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Inconsistent everywhere; feels like different products stitched together |
-| 1 | Many inconsistencies; similar things look/behave differently |
-| 2 | Partially consistent; main flows match, details diverge |
-| 3 | Mostly consistent; occasional deviation, nothing confusing |
-| 4 | Fully consistent; cohesive system, predictable behavior |
-
-### 5. Error Prevention
-
-Better than good error messages is a design that prevents problems in the first place.
-
-**Check for**:
-- Confirmation before destructive actions (delete, overwrite)
-- Constraints preventing invalid input (date pickers, dropdowns)
-- Smart defaults that reduce errors
-- Clear labels that prevent misunderstanding
-- Autosave and draft recovery
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Errors easy to make; no guardrails anywhere |
-| 1 | Few safeguards; some inputs validated, most aren't |
-| 2 | Partial prevention; common errors caught, edge cases slip |
-| 3 | Good prevention; most error paths blocked proactively |
-| 4 | Excellent; errors nearly impossible through smart constraints |
-
-### 6. Recognition Rather Than Recall
-
-Minimize memory load. Make objects, actions, and options visible or easily retrievable.
-
-**Check for**:
-- Visible options (not buried in hidden menus)
-- Contextual help when needed (tooltips, inline hints)
-- Recent items and history
-- Autocomplete and suggestions
-- Labels on icons (not icon-only navigation)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Heavy memorization; users must remember paths and commands |
-| 1 | Mostly recall; many hidden features, few visible cues |
-| 2 | Some aids; main actions visible, secondary features hidden |
-| 3 | Good recognition; most things discoverable, few memory demands |
-| 4 | Everything discoverable; users never need to memorize |
-
-### 7. Flexibility and Efficiency of Use
-
-Accelerators, invisible to novices, speed up expert interaction.
-
-**Check for**:
-- Keyboard shortcuts for common actions
-- Customizable interface elements
-- Recent items and favorites
-- Bulk/batch actions
-- Power user features that don't complicate the basics
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | One rigid path; no shortcuts or alternatives |
-| 1 | Limited flexibility; few alternatives to the main path |
-| 2 | Some shortcuts; basic keyboard support, limited bulk actions |
-| 3 | Good accelerators; keyboard nav, some customization |
-| 4 | Highly flexible; multiple paths, power features, customizable |
-
-### 8. Aesthetic and Minimalist Design
-
-Interfaces should not contain irrelevant or rarely needed information. Every element should serve a purpose.
-
-**Check for**:
-- Only necessary information visible at each step
-- Clear visual hierarchy directing attention
-- Purposeful use of color and emphasis
-- No decorative clutter competing for attention
-- Focused, uncluttered layouts
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Overwhelming; everything competes for attention equally |
-| 1 | Cluttered; too much noise, hard to find what matters |
-| 2 | Some clutter; main content clear, periphery noisy |
-| 3 | Mostly clean; focused design, minor visual noise |
-| 4 | Perfectly minimal; every element earns its pixel |
-
-### 9. Help Users Recognize, Diagnose, and Recover from Errors
-
-Error messages should use plain language, precisely indicate the problem, and constructively suggest a solution.
-
-**Check for**:
-- Plain language error messages (no error codes for users)
-- Specific problem identification ("Email is missing @" not "Invalid input")
-- Actionable recovery suggestions
-- Errors displayed near the source of the problem
-- Non-blocking error handling (don't wipe the form)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Cryptic errors; codes, jargon, or no message at all |
-| 1 | Vague errors; "Something went wrong" with no guidance |
-| 2 | Clear but unhelpful; names the problem but not the fix |
-| 3 | Clear with suggestions; identifies problem and offers next steps |
-| 4 | Perfect recovery; pinpoints issue, suggests fix, preserves user work |
-
-### 10. Help and Documentation
-
-Even if the system is usable without docs, help should be easy to find, task-focused, and concise.
-
-**Check for**:
-- Searchable help or documentation
-- Contextual help (tooltips, inline hints, guided tours)
-- Task-focused organization (not feature-organized)
-- Concise, scannable content
-- Easy access without leaving current context
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No help available anywhere |
-| 1 | Help exists but hard to find or irrelevant |
-| 2 | Basic help; FAQ or docs exist, not contextual |
-| 3 | Good documentation; searchable, mostly task-focused |
-| 4 | Excellent contextual help; right info at the right moment |
-
----
-
-## Score Summary
-
-**Total possible**: 40 points (10 heuristics × 4 max)
-
-| Score Range | Rating | What It Means |
-|-------------|--------|---------------|
-| 36–40 | Excellent | Minor polish only; ship it |
-| 28–35 | Good | Address weak areas, solid foundation |
-| 20–27 | Acceptable | Significant improvements needed before users are happy |
-| 12–19 | Poor | Major UX overhaul required; core experience broken |
-| 0–11 | Critical | Redesign needed; unusable in current state |
-
----
-
-## Issue Severity (P0–P3)
-
-Tag each individual issue found during scoring with a priority level:
-
-| Priority | Name | Description | Action |
-|----------|------|-------------|--------|
-| **P0** | Blocking | Prevents task completion entirely | Fix immediately; this is a showstopper |
-| **P1** | Major | Causes significant difficulty or confusion | Fix before release |
-| **P2** | Minor | Annoyance, but workaround exists | Fix in next pass |
-| **P3** | Polish | Nice-to-fix, no real user impact | Fix if time permits |
-
-**Tip**: If you're unsure between two levels, ask: "Would a user contact support about this?" If yes, it's at least P1.
@@ -1,195 +0,0 @@
-# Interaction Design
-
-## The Eight Interactive States
-
-Every interactive element needs these states designed:
-
-| State | When | Visual Treatment |
-|-------|------|------------------|
-| **Default** | At rest | Base styling |
-| **Hover** | Pointer over (not touch) | Subtle lift, color shift |
-| **Focus** | Keyboard/programmatic focus | Visible ring (see below) |
-| **Active** | Being pressed | Pressed in, darker |
-| **Disabled** | Not interactive | Reduced opacity, no pointer |
-| **Loading** | Processing | Spinner, skeleton |
-| **Error** | Invalid state | Red border, icon, message |
-| **Success** | Completed | Green check, confirmation |
-
-**The common miss**: Designing hover without focus, or vice versa. They're different. Keyboard users never see hover states.
-
-## Focus Rings: Do Them Right
-
-**Never `outline: none` without replacement.** It's an accessibility violation. Instead, use `:focus-visible` to show focus only for keyboard users:
-
-```css
-/* Hide focus ring for mouse/touch */
-button:focus {
- outline: none;
-}
-
-/* Show focus ring for keyboard */
-button:focus-visible {
- outline: 2px solid var(--color-accent);
- outline-offset: 2px;
-}
-```
-
-**Focus ring design**:
-- High contrast (3:1 minimum against adjacent colors)
-- 2-3px thick
-- Offset from element (not inside it)
-- Consistent across all interactive elements
-
-## Form Design: The Non-Obvious
-
-**Placeholders aren't labels.** They disappear on input. Always use visible `<label>` elements. **Validate on blur**, not on every keystroke (exception: password strength). Place errors **below** fields with `aria-describedby` connecting them.
-
-## Loading States
-
-**Optimistic updates**: Show success immediately, rollback on failure. Use for low-stakes actions (likes, follows), not payments or destructive actions. **Skeleton screens > spinners**: they preview content shape and feel faster than generic spinners.
-
-## Modals: The Inert Approach
-
-Focus trapping in modals used to require complex JavaScript. Now use the `inert` attribute:
-
-```html
-<!-- When modal is open -->
-<main inert>
- <!-- Content behind modal can't be focused or clicked -->
-</main>
-<dialog open>
- <h2>Modal Title</h2>
- <!-- Focus stays inside modal -->
-</dialog>
-```
-
-Or use the native `<dialog>` element:
-
-```javascript
-const dialog = document.querySelector('dialog');
-dialog.showModal(); // Opens with focus trap, closes on Escape
-```
-
-## The Popover API
-
-For tooltips, dropdowns, and non-modal overlays, use native popovers:
-
-```html
-<button popovertarget="menu">Open menu</button>
-<div id="menu" popover>
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-**Benefits**: Light-dismiss (click outside closes), proper stacking, no z-index wars, accessible by default.
-
-## Dropdown & Overlay Positioning
-
-Dropdowns rendered with `position: absolute` inside a container that has `overflow: hidden` or `overflow: auto` will be clipped. This is the single most common dropdown bug in generated code.
-
-### CSS Anchor Positioning
-
-The modern solution uses the CSS Anchor Positioning API to tether an overlay to its trigger without JavaScript:
-
-```css
-.trigger {
- anchor-name: --menu-trigger;
-}
-
-.dropdown {
- position: fixed;
- position-anchor: --menu-trigger;
- position-area: block-end span-inline-end;
- margin-top: 4px;
-}
-
-/* Flip above if no room below */
-@position-try --flip-above {
- position-area: block-start span-inline-end;
- margin-bottom: 4px;
-}
-```
-
-Because the dropdown uses `position: fixed`, it escapes any `overflow` clipping on ancestor elements. The `@position-try` block handles viewport edges automatically. **Browser support**: Chrome 125+, Edge 125+. Not yet in Firefox or Safari - use a fallback for those browsers.
-
-### Popover + Anchor Combo
-
-Combining the Popover API with anchor positioning gives you stacking, light-dismiss, accessibility, and correct positioning in one pattern:
-
-```html
-<button popovertarget="menu" class="trigger">Open</button>
-<div id="menu" popover class="dropdown">
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-The `popover` attribute places the element in the **top layer**, which sits above all other content regardless of z-index or overflow. No portal needed.
-
-### Portal / Teleport Pattern
-
-In component frameworks, render the dropdown at the document root and position it with JavaScript:
-
-- **React**: `createPortal(dropdown, document.body)`
-- **Vue**: `<Teleport to="body">`
-- **Svelte**: Use a portal library or mount to `document.body`
-
-Calculate position from the trigger's `getBoundingClientRect()`, then apply `position: fixed` with `top` and `left` values. Recalculate on scroll and resize.
-
-### Fixed Positioning Fallback
-
-For browsers without anchor positioning support, `position: fixed` with manual coordinates avoids overflow clipping:
-
-```css
-.dropdown {
- position: fixed;
- /* top/left set via JS from trigger's getBoundingClientRect() */
-}
-```
-
-Check viewport boundaries before rendering. If the dropdown would overflow the bottom edge, flip it above the trigger. If it would overflow the right edge, align it to the trigger's right side instead.
-
-### Anti-Patterns
-
-- **`position: absolute` inside `overflow: hidden`** - The dropdown will be clipped. Use `position: fixed` or the top layer instead.
-- **Arbitrary z-index values** like `z-index: 9999` - Use a semantic z-index scale: `dropdown (100) -> sticky (200) -> modal-backdrop (300) -> modal (400) -> toast (500) -> tooltip (600)`.
-- **Rendering dropdown markup inline** without an escape hatch from the parent's stacking context. Either use `popover` (top layer), a portal, or `position: fixed`.
-
-## Destructive Actions: Undo > Confirm
-
-**Undo is better than confirmation dialogs.** Users click through confirmations mindlessly. Remove from UI immediately, show undo toast, actually delete after toast expires. Use confirmation only for truly irreversible actions (account deletion), high-cost actions, or batch operations.
-
-## Keyboard Navigation Patterns
-
-### Roving Tabindex
-
-For component groups (tabs, menu items, radio groups), one item is tabbable; arrow keys move within:
-
-```html
-<div role="tablist">
- <button role="tab" tabindex="0">Tab 1</button>
- <button role="tab" tabindex="-1">Tab 2</button>
- <button role="tab" tabindex="-1">Tab 3</button>
-</div>
-```
-
-Arrow keys move `tabindex="0"` between items. Tab moves to the next component entirely.
-
-### Skip Links
-
-Provide skip links (`<a href="#main-content">Skip to main content</a>`) for keyboard users to jump past navigation. Hide off-screen, show on focus.
-
-## Gesture Discoverability
-
-Swipe-to-delete and similar gestures are invisible. Hint at their existence:
-
-- **Partially reveal**: Show delete button peeking from edge
-- **Onboarding**: Coach marks on first use
-- **Alternative**: Always provide a visible fallback (menu with "Delete")
-
-Don't rely on gestures as the only way to perform actions.
-
----
-
-**Avoid**: Removing focus indicators without alternatives. Using placeholder text as labels. Touch targets <44x44px. Generic error messages. Custom controls without ARIA/keyboard support.
@@ -1,141 +0,0 @@
-Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids, the centered-stack default) and fix the structure, not the surface.
-
----
-
-## Register
-
-Brand: asymmetric compositions, fluid spacing with `clamp()`, intentional grid-breaking for emphasis. Rhythm through contrast: tight groupings paired with generous separations.
-
-Product: predictable grids, consistent densities, familiar navigation patterns. Responsive behavior is structural (collapse sidebar, responsive table), not fluid typography. Consistency IS an affordance.
-
----
-
-## Assess Current Layout
-
-Analyze what's weak about the current spatial design:
-
-1. **Spacing**:
- - Is spacing consistent or arbitrary? (Random padding/margin values)
- - Is all spacing the same? (Equal padding everywhere = no rhythm)
- - Are related elements grouped tightly, with generous space between groups?
-
-2. **Visual hierarchy**:
- - Apply the squint test: blur your (metaphorical) eyes. Can you still identify the most important element, second most important, and clear groupings?
- - Is hierarchy achieved effectively? (Space and weight alone can be enough; is the current approach working?)
- - Does whitespace guide the eye to what matters?
-
-3. **Grid & structure**:
- - Is there a clear underlying structure, or does the layout feel random?
- - Are identical card grids used everywhere? (Icon + heading + text, repeated endlessly)
- - Is everything centered? (Left-aligned with asymmetric layouts feels more designed, but not a hard and fast rule)
-
-4. **Rhythm & variety**:
- - Does the layout have visual rhythm? (Alternating tight/generous spacing)
- - Is every section structured the same way? (Monotonous repetition)
- - Are there intentional moments of surprise or emphasis?
-
-5. **Density**:
- - Is the layout too cramped? (Not enough breathing room)
- - Is the layout too sparse? (Excessive whitespace without purpose)
- - Does density match the content type? (Data-dense UIs need tighter spacing; marketing pages need more air)
-
-**CRITICAL**: Layout problems are often the root cause of interfaces feeling "off" even when colors and fonts are fine. Space is a design material; use it with intention.
-
-## Plan Layout Improvements
-
-Consult the [spatial design reference](spatial-design.md) for detailed guidance on grids, rhythm, and container queries.
-
-Create a systematic plan:
-
-- **Spacing system**: Use a consistent scale (a framework's built-in scale like Tailwind's, rem-based tokens, or a custom system). The specific values matter less than consistency.
-- **Hierarchy strategy**: How will space communicate importance?
-- **Layout approach**: What structure fits the content? Flex for 1D, Grid for 2D, named areas for complex page layouts.
-- **Rhythm**: Where should spacing be tight vs generous?
-
-## Improve Layout Systematically
-
-### Establish a Spacing System
-
-- Use a consistent spacing scale (framework scales like Tailwind, rem-based tokens, or a custom scale all work). What matters is that values come from a defined set, not arbitrary numbers.
-- Name tokens semantically if using custom properties: `--space-xs` through `--space-xl`, not `--spacing-8`
-- Use `gap` for sibling spacing instead of margins; eliminates margin collapse hacks
-- Apply `clamp()` for fluid spacing that breathes on larger screens
-
-### Create Visual Rhythm
-
-- **Tight grouping** for related elements (8-12px between siblings)
-- **Generous separation** between distinct sections (48-96px)
-- **Varied spacing** within sections (not every row needs the same gap)
-- **Asymmetric compositions**: break the predictable centered-content pattern when it makes sense
-
-### Choose the Right Layout Tool
-
-- **Use Flexbox for 1D layouts**: Rows of items, nav bars, button groups, card contents, most component internals. Flex is simpler and more appropriate for the majority of layout tasks.
-- **Use Grid for 2D layouts**: Page-level structure, dashboards, data-dense interfaces, anything where rows AND columns need coordinated control.
-- **Don't default to Grid** when Flexbox with `flex-wrap` would be simpler and more flexible.
-- Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints.
-- Use named grid areas (`grid-template-areas`) for complex page layouts; redefine at breakpoints.
-
-### Break Card Grid Monotony
-
-- Don't default to card grids for everything; spacing and alignment create visual grouping naturally
-- Use cards only when content is truly distinct and actionable. Never nest cards inside cards
-- Vary card sizes, span columns, or mix cards with non-card content to break repetition
-
-### Strengthen Visual Hierarchy
-
-- Use the fewest dimensions needed for clear hierarchy. Space alone can be enough; generous whitespace around an element draws the eye. Some of the most polished designs achieve rhythm with just space and weight. Add color or size contrast only when simpler means aren't sufficient.
-- Be aware of reading flow: in LTR languages, the eye naturally scans top-left to bottom-right, but primary action placement depends on context (e.g., bottom-right in dialogs, top in navigation).
-- Create clear content groupings through proximity and separation.
-
-### Manage Depth & Elevation
-
-- Create a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip)
-- Build a consistent shadow scale (sm → md → lg → xl); shadows should be subtle
-- Use elevation to reinforce hierarchy, not as decoration
-
-### Optical Adjustments
-
-- If an icon looks visually off-center despite being geometrically centered, nudge it. But only if you're confident it actually looks wrong. Don't adjust speculatively.
-
-**NEVER**:
-- Use arbitrary spacing values outside your scale
-- Make all spacing equal (variety creates hierarchy)
-- Wrap everything in cards (not everything needs a container)
-- Nest cards inside cards (use spacing and dividers for hierarchy within)
-- Use identical card grids everywhere (icon + heading + text, repeated)
-- Center everything (left-aligned with asymmetry feels more designed)
-- Default to the hero metric layout (big number, small label, stats, gradient) as a template. If showing real user data, a prominent metric can work, but it should display actual data, not decorative numbers.
-- Default to CSS Grid when Flexbox would be simpler; use the simplest tool for the job
-- Use arbitrary z-index values (999, 9999); build a semantic scale
-
-## Verify Layout Improvements
-
-- **Squint test**: Can you identify primary, secondary, and groupings with blurred vision?
-- **Rhythm**: Does the page have a satisfying beat of tight and generous spacing?
-- **Hierarchy**: Is the most important content obvious within 2 seconds?
-- **Breathing room**: Does the layout feel comfortable, not cramped or wasteful?
-- **Consistency**: Is the spacing system applied uniformly?
-- **Responsiveness**: Does the layout adapt gracefully across screen sizes?
-
-When the rhythm and hierarchy land, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `density` param. Drive all spacing tokens in the variant's scoped CSS through `calc(var(--p-density, 1) * <base>)`: paddings, gaps, column widths. Users slide from airy to packed and see layout re-breathe with no regeneration.
-
-```json
-{"id":"density","kind":"range","min":0.6,"max":1.4,"step":0.05,"default":1,"label":"Density"}
-```
-
-For variants whose topology genuinely changes (stacked vs. side-by-side, grid vs. bento), use a `steps` param whose scoped CSS branches via `:scope[data-p-structure="X"]`. One structure param + one density param is a powerful combo; resist adding a third.
-
-```json
-{"id":"structure","kind":"steps","default":"grid","label":"Structure","options":[
- {"value":"stacked","label":"Stacked"},
- {"value":"grid","label":"Grid"},
- {"value":"bento","label":"Bento"}
-]}
-```
-
-See `reference/live.md` for the full params contract.
@@ -1,622 +0,0 @@
-Interactive live variant mode: select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via the dev server's HMR.
-
-## Prerequisites
-
-A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR a static HTML file open in the browser.
-
-## The contract (read once)
-
-Execute in order. No step skipped, no step reordered.
-
-1. `live.mjs`: boot.
-2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.
-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.
-5. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
-6. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
-7. On `exit`: run the cleanup at the bottom.
-
-Harness policy:
-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.
-- **Cursor**: run the poll in the **foreground** (blocking shell; not a background terminal, not a subagent). Cursor background terminals and subagents do not reliably resume the chat with poll stdout.
-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.
-- **Other harnesses**: foreground unless you know stdout reliably returns to this session.
-
-Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.
-
-## Start
-
-```bash
-node .claude/skills/impeccable/scripts/live.mjs
-```
-
-Output JSON: `{ ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath, migrated }`. `pageFiles` is the list of HTML entries the live script was injected into. Keep PRODUCT.md and DESIGN.md in mind for variant generation; **DESIGN.md wins on visual decisions; PRODUCT.md wins on strategic/voice decisions.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt. If `migrated: true`, the loader auto-renamed legacy `.impeccable.md` to `PRODUCT.md`; mention this once and suggest `/impeccable document` for the matching DESIGN.md.
-
-`serverPort` and `serverToken` belong to the small **Impeccable live helper** HTTP server (serves `/live.js`, SSE, and `/poll`). That port is **not** your dev server and is usually not the URL you open to view the app. The browser page is whatever origin serves one of the `pageFiles` entries (Vite / Next / Bun / tunnel / LAN hostname).
-
-If output is `{ ok: false, error: "config_missing" | "config_invalid", path }`, this project hasn't been configured for live mode (or its config is stale). See **First-time setup** at the bottom.
-
-## Poll loop
-
-```
-LOOP:
- node .claude/skills/impeccable/scripts/live-poll.mjs # default long timeout; no --timeout=
- Read JSON; dispatch on "type"
-
- "generate" → Handle Generate; reply done; LOOP
- "accept" → Handle Accept; complete carbonize cleanup if required; LOOP
- "discard" → Handle Discard; LOOP
- "prefetch" → Handle Prefetch; LOOP
- "timeout" → LOOP
- "exit" → break → Cleanup
-```
-
-## Recovery commands
-
-The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.
-
-Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:
-
-```bash
-node .claude/skills/impeccable/scripts/live-status.mjs
-node .claude/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID
-node .claude/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID
-```
-
-- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.
-- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.
-- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.
-
-Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.
-
-## Handle `generate`
-
-Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.
-
-Speed matters; the user is watching a spinner. Minimize tool calls by using the `wrap` helper and writing all variants in a single edit.
-
-### 1. Read the screenshot (if present)
-
-`event.screenshotPath` is **only sent when the user placed at least one comment or stroke before Go.** When present, it's an absolute path to a PNG of the element as rendered with the annotations baked in. **Read it before planning**: annotations encode user intent not recoverable from `element.outerHTML` alone.
-
-When `screenshotPath` is absent, don't ask for one and don't go looking for the current rendering. The omission is deliberate: without annotations, a screenshot would anchor the model on the existing design and fight the three-distinct-directions brief. Work from `element.outerHTML`, the computed styles in `event.element`, and the freeform prompt if present.
-
-`event.comments` and `event.strokes` carry structured metadata alongside the visual. Treat the screenshot as primary; use the structured data for specifics worth quoting (e.g. the exact text of a comment).
-
-Reading annotations precisely:
-
-- **Comment position carries meaning.** Its `{x, y}` is element-local CSS px (same coord space as `element.boundingRect`). Find the child under that point and apply the comment text LOCALLY to that sub-element. A comment near the title is about the title, not a global description.
-- **Comments and strokes are independent annotations** unless clearly paired by overlap or tight proximity. Don't let the visual weight of a prominent stroke override the precise location of a textually-specific comment elsewhere.
-- **Strokes are gestures; read them by shape.** Closed loop = "this thing" (emphasis / focus); arrow = direction (move / point to); cross or slash = delete; free scribble = emphasis or delete depending on context. A loop around region X means "pay attention to X," not "only change pixels inside X."
-- **When a stroke's intent is ambiguous** (circle or arrow? emphasis or move?), state your reading in one sentence of rationale rather than silently guessing. If the uncertainty materially changes the brief, ask one short clarifying question before generating.
-
-### 2. Wrap the element
-
-```bash
-node .claude/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"
-```
-
-Flag mapping. Keep them separate, don't collapse into `--query`:
-
-- `--element-id` ← `event.element.id`
-- `--classes` ← `event.element.classes` joined with commas
-- `--tag` ← `event.element.tagName`
-- `--text` ← first ~80 chars of `event.element.textContent` (trim, single-line). **Pass this every call.** When the picked element shares classes + tag with sibling components (a list of `<Card>`s, repeating sections), this is what disambiguates which branch in source to wrap. Without it, wrap silently lands on the first match and may rewrite the wrong element.
-
-The helper searches ID first, then classes, then tag + class combo. If `event.pageUrl` implies the file (e.g. `/` is usually `index.html`), pass `--file PATH` to skip the search. `--query` is a fallback for raw text search only; do not use it for normal element lookups.
-
-If `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.
-
-Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.
-
-`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:
-
-- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.
-- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.
-
-Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.
-
-**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:
-
-- `{ error: "file_is_generated", file, hint }`: user-supplied `--file` points at a generated file.
-- `{ error: "element_not_in_source", generatedMatch, hint }`: element exists only in a generated file (the next build would wipe any edits).
-- `{ error: "element_not_found", hint }`: element isn't in any project file; likely runtime-injected (JS component, dynamic render from data).
-
-All three carry `fallback: "agent-driven"`. Follow **Handle fallback** below.
-
-### 3. Load the action's reference
-
-If `event.action` is `impeccable` (the default freeform action), use SKILL.md's shared laws plus the loaded register reference (`brand.md` or `product.md`). Do not load a sub-command reference. **Freeform is not a pass to skip parameters:** you still follow the composition budget and the freeform bias in **§7 Parameters** below. Sub-command files list MUST-have signature knobs; freeform has no such file, so sizing knobs from surface weight and primary axes is entirely on you.
-
-Any other `event.action` (`bolder`, `quieter`, `distill`, `polish`, `typeset`, `colorize`, `layout`, `adapt`, `animate`, `delight`, `overdrive`): Read `reference/<action>.md` before planning. Each sub-command encodes a specific discipline; skipping its reference produces generic output. Those files may require specific params; layer them on top of the §7 budget, not instead of it.
-
-### 4. Plan three variants: identity first, then mode, then axes
-
-The wrong frame for live mode is "show three different design directions." Live runs on an existing surface; the brand has already been chosen. The job is variation **within identity**, not selection between identities. Failure mode: three editorial-typographic variants on a brief that wasn't editorial. Bigger failure mode: three off-brand variants the user can't accept because they don't look like their product.
-
-Four phases. Do them in order.
-
-#### Phase A: Extract the identity (non-skippable)
-
-The existing surface has an identity already. Read it before planning anything. Sources, in priority order:
-
-1. **DESIGN.md** if loaded: read the visual system fields (palette, type pairing, motion, components). This is the authoritative answer.
-2. **CSS custom properties** in the page's stylesheets (`:root { --color-...; --font-...; ... }`): these are de-facto tokens.
-3. **Computed styles** on the picked element and its parent: colors, fonts, spacing scales, corner radii.
-4. **Sibling components on the page**: what visual rhetoric do existing components use? (Asymmetric or centered? Dense or airy? Bold or quiet?)
-
-Write down what you see in **one sentence**. The sentence describes the surface that's actually on screen; it is not aspirational, not opinionated, not edited toward what the brand "should" be. Capture, in roughly this order:
-
-- The dominant surface color and accent color, by hex or token name (use the actual values, not categories like "warm" or "neutral").
-- The type pairing: the actual font names loaded, primary first.
-- The layout topology: how the dominant elements are arranged (stacked / side-by-side / grid / asymmetric / overlay).
-- The surface treatment: corners, borders, shadows, density of decoration.
-- The voice tone you read off the copy itself, not off the aesthetic feel.
-
-Be specific. "Modern" is not a color, "elegant" is not a type pairing, "clean" is not a layout. If you can't extract a real value for an axis, skip it rather than fabricate. The point is to record what is, not to describe what you wish it were.
-
-Do not include adjectives that name an aesthetic family ("editorial-leaning", "terminal-flavored", "brutalist"); those are conclusions, not data. They belong to Phase C lane selection in departure mode, not to identity description. Letting them sneak into Phase A is how the identity-lock collapses into a self-fulfilling prophecy.
-
-This sentence is the **identity lock**. Every variant must be readable as the same brand if rendered side by side. Skipping this phase is the primary cause of off-brand variants. Absence of DESIGN.md is never an excuse; extract from CSS and computed styles instead.
-
-#### Phase B: Pick mode (default vs departure)
-
-**Default mode**: the existing identity is preserved. Variants vary expression axes within it. *This is the right mode for ~90% of live sessions.* The user picked an element on a real product they're shipping; they expect variants of *their* hero, not three different brands' heroes.
-
-**Departure mode**: the existing identity is rejected. Variants propose alternatives consistent with PRODUCT.md voice. Trigger only when at least one is true:
-
-- PRODUCT.md anti-references explicitly call out the current surface ("the current `index.html` is itself an example"; "diffuse away from this"; "the page on screen is the failure"). Generic anti-references that describe what to avoid in general do **not** trigger departure mode; only ones that point at *this* surface specifically.
-- The user's freeform prompt explicitly asks for departure ("rebuild this from scratch", "what if it weren't editorial at all", "show me something completely different").
-
-If you're unsure, you're in default mode. The cost of being wrong about default is "three on-brand variants with similar feel": recoverable, the user picks none. The cost of being wrong about departure is "three off-brand variants": unrecoverable, the user is annoyed.
-
-#### Phase C: Plan three variants
-
-**Default mode.** Each variant commits to a different **primary axis** of difference, while preserving the identity sentence. The six axes:
-
-1. **Hierarchy**: which element commands the eye?
-2. **Layout topology**: stacked / side-by-side / grid / asymmetric / overlay
-3. **Typographic system**: pairing logic, scale ratio, case/weight strategy *within the available faces*
-4. **Color strategy**: which existing palette role carries the surface (Restrained / Committed / Full palette / Drenched). Use the brand's existing palette tokens, not new colors.
-5. **Density**: minimal / comfortable / dense
-6. **Structural decomposition**: merge, split, progressive disclosure
-
-Three variants → three DIFFERENT axes. The trio reads as *the same brand at three angles*. Do not introduce new fonts, new palette hues, or new aesthetic-family signals; those belong to departure mode.
-
-**While planning each variant, also name its 2–3 parameter knobs** (per the §7 budget table). Parameters are part of the design, not a decoration added afterward. If the variant explores density, expose a density knob. If it explores color commitment, expose a color-amount range. Deciding "what's tunable" during planning produces better knobs than retrofitting them onto finished HTML.
-
-**Departure mode.** Each variant anchors to a different **aesthetic direction**, derived from the brand's stated voice and register in PRODUCT.md. Do NOT pick from a fixed catalog of lane categories. The right three directions for this brand are not the same as the right three for another brand, and picking from a list is itself the training-data reflex (the model selects "Swiss-grid, Terminal, Industrial-signage" every time because those are the furthest-from-editorial items in any enumerated list).
-
-Instead, work from the brand:
-
-1. Read PRODUCT.md's Brand Personality words. What physical, spatial, or material experiences would embody those words if design were not involved? (A personality described as "specific, earned, unmistakable" evokes a hand-stamped letter, a numbered print, a watchmaker's loupe. A personality described as "restless, loud, unfiltered" evokes a concert poster, a spray-painted wall, a megaphone.)
-2. From those physical experiences, derive three visual directions that are genuinely different from each other AND from the current surface you're departing.
-3. Avoid the **reflex-reject lanes** in [brand.md](brand.md). Don't trade one monoculture for another. If you find yourself reaching for "Swiss-grid" or "Terminal" or "Industrial-signage" by reflex, you are pattern-matching a catalog in your training data, not reading the brand. Start over from the personality words.
-4. Each direction must be expressible in one concrete sentence that names a real-world referent ("a museum exhibition label system for a contemporary art gallery" not "clean and minimal"). If your sentence contains only adjectives, it's not concrete enough.
-5. **While planning each direction, also name its 2–3 parameter knobs** (per the §7 budget table). The same principle as default mode: decide "what's tunable" during planning, not after writing the HTML. A departure-mode hero with 0 parameters is not "bold creative vision," it's a missed opportunity for the user to fine-tune the direction they pick.
-
-#### Phase D: Squint test
-
-**Default mode squint.** Read each variant's identity sentence and compare to the locked identity from Phase A. If any variant has drifted to a different palette, type voice, or visual rhetoric, it has crossed into departure mode by accident; rework. Then check that each variant commits to a different primary axis. Three "tighter density" variants is failure.
-
-**Departure mode squint.** Two passes, family before sentence:
-
-1. **Family pass.** Label each variant with one design-family word of your own choosing (any concrete noun: *exhibition, storefront, cockpit, recipe-card, playbill, field-manual*). If any two variants share a label, or if the label could apply to the other variants equally well, rework. Do not use a fixed vocabulary list for the labels. *This pass is non-negotiable in departure mode and catches the monoculture failure that the sentence pass misses.*
-2. **Sentence pass.** Write three one-sentence descriptions side by side. If two of them rhyme ("both feature big type" / "both are stacks of sections" / "both center the CTA"), rework the offender.
-
-**When the primary axis is color or theme, forbid the trio from sharing theme + dominant hue.** Two dark-plus-one-dark is not distinct. Aim for three color worlds, not three shades of the same.
-
-**For action-specific invocations**, each variant must vary along the dimension the action names:
-
-- `bolder`: amplify a different dimension per variant (scale / saturation / structural change). Not three "slightly bigger" variants.
-- `quieter`: pull back a different dimension (color / ornament / spacing).
-- `distill`: remove a different class of excess (visual noise / redundant content / nested structure).
-- `polish`: target a different refinement axis (rhythm / hierarchy / micro-details like corner radii, focus states, optical kerning).
-- `typeset`: different type pairing AND different scale ratio each. Not three riffs on one pairing.
-- `colorize`: different hue family each (not shades of one hue). Vary chroma and contrast strategy.
-- `layout`: different structural arrangement (stacked / side-by-side / grid / asymmetric). Not spacing tweaks.
-- `adapt`: different target context per variant (mobile-first / tablet / desktop / print or low-data). Don't make three mobile layouts.
-- `animate`: different motion vocabulary (cascade stagger / clip wipe / scale-and-focus / morph / parallax). Not three staggered fades.
-- `delight`: different flavor of personality (unexpected micro-interaction / typographic surprise / illustrated accent / sonic-or-haptic moment / easter-egg interaction).
-- `overdrive`: different convention broken (scale / structure / motion / input model / state transitions). Skip `overdrive.md`'s "propose and ask" step; live mode is non-interactive.
-
-### 5. Apply the freeform prompt (if present)
-
-`event.freeformPrompt` is the user's ceiling on direction (all variants must honor it), but still explore meaningfully different *interpretations*. The interpretations stay within whichever mode you picked in Phase B.
-
-In **default mode**, the prompt narrows the axes you choose, not the identity. *"Make it feel more confident"* → variant 1 amplifies hierarchy (one element commands the eye), variant 2 commits the existing accent color (Committed strategy on the brand's hue), variant 3 tightens density and removes decorative slack. Three different axes, same brand.
-
-In **departure mode**, the prompt narrows the lanes you draw from, not the families. *"Make it feel like a newspaper front page"* would itself be a departure-mode prompt; honor it but pick three meaningfully different newspaper-adjacent lanes (broadsheet vs. tabloid vs. trade journal), and run the family pass to confirm they don't collapse into one.
-
-When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.
-
-### 6. Write all variants in a single edit
-
-Complete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).
-
-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).
-
-Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:
-
-```html
-<!-- Variants: insert below this line -->
-<style data-impeccable-css="SESSION_ID">
- /* rules matching cssAuthoring.rulePattern */
-</style>
-<div data-impeccable-variant="1">
- <!-- variant 1: full element replacement (single top-level element) -->
-</div>
-<div data-impeccable-variant="2" style="display: none">
- <!-- variant 2: full element replacement -->
-</div>
-<div data-impeccable-variant="3" style="display: none">
- <!-- variant 3: full element replacement -->
-</div>
-```
-
-**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.
-
-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.
-
-One edit, all variants; the browser's MutationObserver picks everything up in one pass.
-
-For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.
-
-**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:
-
-```tsx
-<style data-impeccable-css="SESSION_ID">{`
- @scope ([data-impeccable-variant="1"]) { ... }
- @scope ([data-impeccable-variant="2"]) { ... }
-`}</style>
-<div data-impeccable-variant="1">
- {/* variant 1 */}
-</div>
-<div data-impeccable-variant="2" style={{ display: 'none' }}>
- {/* variant 2 */}
-</div>
-```
-
-The wrap script already gives you a single-rooted JSX wrapper: a `<div data-impeccable-variants="…">` outer element with the marker comments tucked inside. Drop the variants block above into the "Variants: insert below this line" comment and the source stays valid TSX.
-
-### 7. Parameters (composition-sized, 0–4 per variant)
-
-Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement. The browser docks a small panel to the right of the outline with one control per parameter. The user drags/clicks and sees instant feedback: there is zero regeneration cost because the knob toggles a CSS variable or data attribute that the variant's scoped CSS is already authored against.
-
-**What “optional” does not mean.** Parameters are not nice-to-have decoration on large work. The word meant “omit controls that are redundant or cosmetic,” not “default to zero because three variants were enough work.”
-
-**When to add.** As soon as the variant’s scoped CSS has a meaningful continuous or stepped axis: density, color amount, type scale, motion intensity, column weight, and so on. If you can imagine the user muttering “a bit tighter” or “a touch more accent” **without** wanting a full regeneration, wire that axis. **Not** micro-margins or one-off nudges; those are not parameters.
-
-**Freeform (`action` is `impeccable`) bias.** You did not load a sub-command reference, so you must **choose** signature axes yourself. Match the budget table: for a hero or large composition, that means **2–3 axes per variant**, not 1. Prefer knobs that sit on the dimensions where your three variants actually differ (if density varies, expose it as a `steps` knob; if color commitment varies, expose it as a `range`). A hero that ships with **0** params is almost always a mistake, not a judgment call. A hero with exactly **1** param is underweight unless the design is genuinely a fixed-point comparison. Start from the budget table, not from zero.
-
-**Budget scales with the element's visual weight, not token budget.** Knobs need real estate to read as tunable; three sliders on a single control are noise.
-
-- **Leaf / tiny**: a single button, icon, input, bare heading, solitary paragraph: **0 params.**
-- **Small composition**: labeled input, simple card, short callout (≤ ~5 visual children): **0–1** params when one dominant axis is obvious; otherwise **0.**
-- **Medium composition**: section component, nav cluster, dense card, short feature block (6–15 visual children): **target 2**; **1** is acceptable if the block is simple; **0** only when variants are truly fixed points.
-- **Large composition**: hero section, full page region, spread layout, strong internal structure (16+ visual children or multiple sub-sections): **target 2–3**; **up to 4** when several independent axes (e.g. structure `steps` + `density` + one accent) are all authored in scoped CSS.
-
-**When in doubt, ask whether a dial exists before defaulting to zero.** The user can always request more variants, but the point of live mode is instant tuning without another Go. Crowding the panel is bad; **under-shipping** knobs on a dense composition is the more common failure for freeform. Count by **visual** children, not DOM depth; a shallow-but-wide hero is still large.
-
-**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.
-
-**How to declare.** Put a JSON manifest on the variant wrapper:
-
-```html
-<div data-impeccable-variant="1" data-impeccable-params='[
- {"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"},
- {"id":"density","kind":"steps","default":"snug","label":"Density","options":[
- {"value":"airy","label":"Airy"},
- {"value":"snug","label":"Snug"},
- {"value":"packed","label":"Packed"}
- ]},
- {"id":"serif","kind":"toggle","default":false,"label":"Serif display"}
-]'>
- ...variant content...
-</div>
-```
-
-**Three kinds:**
-
-- `range`: smooth slider. Drives a CSS custom property `--p-<id>` on the variant wrapper. Author CSS with `var(--p-color-amount, 0.5)`. Fields: `min`, `max`, `step`, `default` (number), `label`.
-- `steps`: segmented radio. Drives a data attribute `data-p-<id>` on the variant wrapper. Author CSS with `:scope[data-p-density="airy"] .grid { ... }`. Fields: `options` (array of `{value, label}`), `default` (string), `label`.
-- `toggle`: on/off switch. Drives BOTH a CSS var (`--p-<id>: 0|1`) and a data attribute (present when on, absent when off). Use whichever is more convenient. Fields: `default` (boolean), `label`.
-
-**Signature params per action.** For named sub-commands, read that action’s `reference/<action>.md` for one or two **MUST** params (e.g. `layout` → `density`). Those are non-negotiable when the design can express them. **Freeform has no file-level MUST**; the **Freeform (`impeccable`) bias** in this section is the stand-in. If the user’s action is both stylized and sub-command (e.g. `colorize`), the sub-command’s MUST list takes precedence for its axes; still respect the **Hard cap** and add no redundant duplicate knobs.
-
-**Reset on variant switch.** User dials density on v1, flips to v2, v2 starts at v2's declared defaults. Known limitation; preservation across variants may land later.
-
-**On accept**, the browser sends the user's current values in the accept event. `live-accept.mjs` writes them as a sibling comment:
-
-```html
-<!-- impeccable-param-values SESSION_ID: {"color-amount":0.7,"density":"packed"} -->
-```
-
-The carbonize cleanup step (see below) reads that comment and bakes the chosen values into the final CSS. For `steps`/`toggle` attribute selectors: keep only the branch matching the chosen value, drop the others, collapse `:scope[data-p-density="packed"] .grid` to a semantic class rule. For `range` vars: either substitute the literal or keep the var with the chosen value as its new default.
-
-### 8. Signal done
-
-```bash
-node .claude/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
-```
-
-`RELATIVE_PATH` is relative to project root (`public/index.html`, `src/App.tsx`, etc.); the browser fetches source directly if the dev server lacks HMR.
-
-Then run `live-poll.mjs` again immediately.
-
-### Aborting an in-flight session
-
-If wrap or generation fails after the browser has flipped to GENERATING (e.g. wrap landed on the wrong source branch and you've already reverted it, or generation hit an unrecoverable error), tell the **browser** so its bar resets to PICKING:
-
-```bash
-node .claude/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID error "Short reason"
-```
-
-Don't run `live-accept --discard` for this; that's a pure file mutator, the browser doesn't see it, and the bar gets stuck on the GENERATING dots forever (the user has to refresh). `--discard` is only correct when the **browser** initiated the discard (user clicked ✕ during CYCLING) and the agent is just running source-side cleanup the browser already triggered.
-
-## Handle fallback
-
-When wrap returns `fallback: "agent-driven"`, the deterministic flow doesn't apply. Pick up here.
-
-The goal is the same: give the user three variants to choose from AND persist the accepted one in a place the next build won't wipe. The difference is that you have to pick the right source file yourself.
-
-### Step 1: Identify where the element actually lives
-
-Use the error payload:
-
-- `element_not_in_source` with `generatedMatch: "public/docs/foo.html"`: the served HTML is generated. Find the generator (grep for writers of that path, e.g. `scripts/build-sub-pages.js`, an Astro/Next template) and locate the template or partial that emits this element.
-- `element_not_found`: the element is runtime-injected. Look for the component that renders it (React/Vue/Svelte), the JS that assembles it, or the data source that feeds it.
-- `file_is_generated` with `file: "..."`: user pointed at a generated file explicitly. Same resolution as `element_not_in_source`.
-
-Read the candidate source until you're confident where a change to the element would belong. If the change is purely visual, that source might be a shared stylesheet, not the template.
-
-### Step 2: Show three variants in the DOM for preview
-
-The browser bar is waiting for variants. Even without a wrapper in source, you still need to show something:
-
-1. Manually write the wrapper scaffold into the **served** file (the one the browser actually loaded). Use the same structure `live-wrap.mjs` produces; `<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents">…</div><!-- end -->`.
-2. Insert your three variant divs inside it, same shape as the deterministic path.
-3. Signal done with `--reply EVENT_ID done --file <served file>`. The browser's no-HMR fallback will fetch and inject.
-
-This served-file edit is **temporary**: next regen wipes it, and that's fine. The real work happens on accept.
-
-### Step 3: On accept, write to true source
-
-When the accept event arrives (`_acceptResult.handled` will usually be `false` here because accept also refuses to persist into generated files; see Handle accept for the carbonize branch), extract the accepted variant's content and write it into the source you identified in Step 1:
-
-- Structural change → edit the template / component source.
-- Visual-only change → add or update rules in the appropriate stylesheet; remove the inline `<style>` scope.
-- Dynamic from data → update the data source or the render logic.
-
-Then remove the temporary wrapper from the served file if it's still there.
-
-### Step 4: On discard, clean up the served file
-
-Remove the wrapper you inserted in Step 2. Nothing else to do.
-
-## Handle `accept`
-
-Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.
-
-- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.
-- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.
-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.
-- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.
-- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.
-
-### Required after accept (carbonize)
-
-When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.
-
-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.
-
-1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.
-2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).
-3. **Bake in parameter values while rewriting selectors.** For `@scope ([data-impeccable-variant="N"])` wrappers: retarget to real, semantic classes on the accepted HTML (`.why-visual--v2 .v2-label { … }`). For `:scope[data-p-<id>="VALUE"]` selectors: keep only the branch matching the chosen value from the param-values comment; drop the others (they're dead after accept). For `var(--p-<id>, DEFAULT)` in the CSS: either substitute the literal value, or if the param is still useful as a knob going forward, leave the var and update its initial declaration to the chosen value.
-4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; those are live-mode plumbing, not source.
-5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.
-
-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.
-
-A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.
-
-## Handle `discard`
-
-Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.
-
-## Handle `prefetch`
-
-Event: `{pageUrl}`. The browser fires this the first time the user selects an element on a given route, as a latency shortcut; it signals the user is likely about to Go on a page you haven't read yet.
-
-Resolve `pageUrl` to the underlying file:
-
-- Root `/` → the `pageFile` returned by `live.mjs` (usually `public/index.html` or equivalent).
-- Sub-routes (e.g. `/docs`, `/docs/live`) → the generated or source file for that route. Use your knowledge of the project layout (multi-page static sites often resolve `/foo` → `public/foo/index.html`; SPAs may map all routes to a single entry).
-
-Read the file into context, then poll again. No `--reply`: this is speculative pre-work; Go will come later. If you can't confidently resolve the route to a file, skip and poll again.
-
-Dedupe is the browser's job (one prefetch per unique pathname per session); trust it. If the same file shows up twice from different routes mapping to the same file, the second Read is cached anyway.
-
-## Exit
-
-The user can stop live mode by:
-- Saying "stop live mode" / "exit live" in chat
-- Closing the browser tab (SSE drops, poll returns `exit` after 8s)
-- The browser's exit button
-
-When the poll returns `exit`, proceed to cleanup. If the poll is still running as a background task, kill it first.
-
-## Cleanup
-
-```bash
-node .claude/skills/impeccable/scripts/live-server.mjs stop
-```
-
-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.
-
-Then:
-- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).
-- Remove any leftover carbonize blocks (search for `impeccable-carbonize-start` markers).
-
-## First-time setup (config missing or invalid)
-
-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.
-
-Schema:
-
-```json
-{
- "files": ["<path-or-glob>", "<path-or-glob>", ...],
- "exclude": ["<optional-glob>", ...],
- "insertBefore": "</body>",
- "commentSyntax": "html",
- "cspChecked": true
-}
-```
-
-`files` is the inject target; **the HTML files the browser actually loads**, not necessarily source. Each entry is either a literal path (`"public/index.html"`) or a glob pattern (`"public/**/*.html"`). Tracked or generated doesn't matter here; wrap has its own generated-file guard and routes accepts through the fallback flow.
-
-`exclude` (optional) is a list of glob patterns matching files to skip, even if a `files` glob would have included them. Use for email templates, demo fixtures, or any HTML that isn't a live page.
-
-`cspChecked` tracks whether the CSP detection step below has already run. Absent on first setup; set to `true` after CSP is checked (whether patched, declined, or not needed).
-
-**Hard-excluded paths (cannot be overridden).** `**/node_modules/**` and `**/.git/**` are never matched regardless of what the user writes. These are vendor/metadata directories and injecting into them would silently instrument third-party code.
-
-**Glob syntax.** `**` matches any number of path segments (including zero), `*` matches any characters except `/`, `?` matches a single character except `/`. Paths are always relative to the project root with forward slashes.
-
-| Framework | `files` | `insertBefore` | `commentSyntax` |
-|-----------|---------|----------------|-----------------|
-| SPA with single shell (Vite / React / Plain HTML) | `["index.html"]` | `</body>` | `html` |
-| Next.js (App Router) | `["app/layout.tsx"]` | `</body>` | `jsx` |
-| Next.js (Pages) | `["pages/_document.tsx"]` | `</body>` | `jsx` |
-| Nuxt | `["app.vue"]` | `</body>` | `html` |
-| Svelte / SvelteKit | `["src/app.html"]` | `</body>` | `html` |
-| Astro | `[" <root layout .astro>"]` | `</body>` | `html` |
-| Multi-page (separate HTML per route) | `["public/**/*.html"]`: a glob covering the served directory | `</body>` | `html` |
-
-Pick an anchor that exists in every file (`</body>` almost always works). Use `insertAfter` if the anchor should match **after** a specific line.
-
-For multi-page sites, **prefer a glob over a literal file list**. New pages added later are picked up automatically on the next `live-inject.mjs` run; no config maintenance needed.
-
-For multi-page sites whose pages are *rebuilt* by a generator (Astro, static-site generators, custom scripts like `build-sub-pages.js`), the inject survives only until the next regeneration. Re-run `live.mjs` after each build. Accept is unaffected; it writes to true source via the fallback flow.
-
-### Drift-heal warning
-
-On every `live.mjs` boot, after inject, the project is scanned for HTML files under common page-source roots (`public/`, `src/`, `app/`, `pages/`). If any exist that aren't covered by the resolved `files` list, the output includes a `configDrift` field:
-
-```json
-{
- "ok": true,
- "serverPort": 8400,
- "pageFiles": [ "..." ],
- "configDrift": {
- "orphans": ["public/new-section/index.html", "public/docs/new-command.html"],
- "orphanCount": 2,
- "hint": "2 HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like \"public/**/*.html\"."
- }
-}
-```
-
-When `configDrift` is present, surface it to the user once per session before entering the poll loop:
-
-> Noticed N HTML file(s) in the project that aren't in `config.files`:
->
-> - `public/new-section/index.html`
-> - `public/docs/new-command.html`
->
-> Add them, or switch `files` to a glob like `["public/**/*.html"]` and let it track new pages automatically?
-
-Don't auto-update the config; let the user decide. `configDrift` is `null` when there's no drift.
-
-### CSP detection (first-time only)
-
-If `config.cspChecked === true`, skip this entire section. You already asked this user once; the answer sticks.
-
-Otherwise, run the detection helper:
-
-```bash
-node .claude/skills/impeccable/scripts/detect-csp.mjs
-```
-
-Output: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.
-
-- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.
-- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:
- - Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)
- - SvelteKit `kit.csp.directives`
- - Nuxt `nuxt-security` module's `contentSecurityPolicy`
-- **`append-string`**: CSP written as a literal value string. Auto-patchable. See *append-string* below. Covers:
- - Inline `next.config.*` `headers()` with a CSP literal
- - Nuxt `routeRules` / `nitro.routeRules` headers
-- **`middleware`** or **`meta-tag`**: rarer. Detected but not auto-patched in v1. Show the user the detected files and ask them to add `http://localhost:8400` to `script-src` and `connect-src` manually, then mark `cspChecked: true` and proceed.
-
-#### Consent prompt template
-
-Use this phrasing so the experience is consistent across agents:
-
-> **CSP patch needed.** I detected a Content Security Policy in your project that blocks `http://localhost:8400`: the live picker won't load without an allowance. Here's the change I'd make:
->
-> ```diff
-> [file: <patchTarget>]
-> [exact diff, 2–5 lines]
-> ```
->
-> It's guarded by `NODE_ENV === "development"` so the extra entry only appears in dev and never reaches production. You can remove it any time by reverting this file. Apply? [y/n]
-
-On "no": skip the patch, mention live won't work until the user adds the allowance manually, still write `cspChecked: true` (the question's been asked).
-
-On "yes": apply the Shape-specific patch below, then write `cspChecked: true`.
-
-#### append-arrays
-
-CSP expressed as structured directive arrays. Patch mechanism: declare a dev-only array, spread it into the script-src and connect-src arrays.
-
-**Declare near the top of the file that holds the CSP arrays:**
-
-```ts
-// Dev-only allowance so impeccable live mode can load. Guarded by NODE_ENV.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? ["http://localhost:8400"] : [];
-```
-
-**Append `...__impeccableLiveDev` to the script-src and connect-src directive arrays.** Per-framework specifics:
-
-- **Next.js + monorepo helper**: edit the *app's* `next.config.*` (not the shared helper), appending to `additionalScriptSrc` and `additionalConnectSrc` passed into `createBaseNextConfig` (or equivalent). Keeps the shared package clean.
-- **SvelteKit**: edit `svelte.config.js`, appending to `kit.csp.directives['script-src']` and `kit.csp.directives['connect-src']`.
-- **Nuxt + nuxt-security**: edit `nuxt.config.*`, appending to `security.headers.contentSecurityPolicy['script-src']` and `['connect-src']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-turborepo/expected-after-patch.ts` (Next.js)
-- `tests/framework-fixtures/sveltekit-csp/expected-after-patch.js` (SvelteKit)
-
-Idempotency: if `__impeccableLiveDev` already exists in the file, the patch is already applied; skip asking and just mark `cspChecked: true`.
-
-#### append-string
-
-CSP built as a literal value string. Two-point patch: declare a dev-only string near the top, interpolate it into the CSP at the `script-src` and `connect-src` directives.
-
-```ts
-// Dev-only allowance so impeccable live mode can load.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? " http://localhost:8400" : "";
-```
-
-Then in the CSP value string:
-- `script-src 'self' 'unsafe-inline'` → `` `script-src 'self' 'unsafe-inline'${__impeccableLiveDev}` ``
-- `connect-src 'self'` → `` `connect-src 'self'${__impeccableLiveDev}` ``
-
-(Leading space on the dev string so it concatenates cleanly into the existing value. Convert the literal CSP directives into template strings as part of the edit if they aren't already.)
-
-Per-framework specifics:
-- **Next.js inline `headers()`**: edit `next.config.*`, splicing the variable into the CSP value.
-- **Nuxt `routeRules`**: edit `nuxt.config.*`, splicing into the CSP in `routeRules['/**'].headers['Content-Security-Policy']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-inline-csp/expected-after-patch.js` (Next.js)
-- `tests/framework-fixtures/nuxt-csp/expected-after-patch.ts` (Nuxt)
-
-### Troubleshooting
-
-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.
-
-Then re-run `live.mjs`.
@@ -1,109 +0,0 @@
-# Motion Design
-
-## Duration: The 100/300/500 Rule
-
-Timing matters more than easing. These durations feel right for most UI:
-
-| Duration | Use Case | Examples |
-|----------|----------|----------|
-| **100-150ms** | Instant feedback | Button press, toggle, color change |
-| **200-300ms** | State changes | Menu open, tooltip, hover states |
-| **300-500ms** | Layout changes | Accordion, modal, drawer |
-| **500-800ms** | Entrance animations | Page load, hero reveals |
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-## Easing: Pick the Right Curve
-
-**Don't use `ease`.** It's a compromise that's rarely optimal. Instead:
-
-| Curve | Use For | CSS |
-|-------|---------|-----|
-| **ease-out** | Elements entering | `cubic-bezier(0.16, 1, 0.3, 1)` |
-| **ease-in** | Elements leaving | `cubic-bezier(0.7, 0, 0.84, 0)` |
-| **ease-in-out** | State toggles (there → back) | `cubic-bezier(0.65, 0, 0.35, 1)` |
-
-**For micro-interactions, use exponential curves.** They feel natural because they mimic real physics (friction, deceleration):
-
-```css
-/* Quart out - smooth, refined (recommended default) */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1);
-
-/* Quint out - slightly more dramatic */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1);
-
-/* Expo out - snappy, confident */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1);
-```
-
-**Avoid bounce and elastic curves.** They were trendy in 2015 but now feel tacky and amateurish. Real objects don't bounce when they stop; they decelerate smoothly. Overshoot effects draw attention to the animation itself rather than the content.
-
-## Premium Motion Materials
-
-Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties: blur reveals, backdrop-filter panels, saturation or brightness shifts, shadow bloom, SVG filters, masks, clip paths, gradient-position movement, and variable font or shader-driven effects.
-
-Use the right material for the effect:
-
-- **Transform / opacity**: movement, press feedback, simple reveals, list choreography.
-- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances, atmospheric transitions.
-- **Clip path / masks**: wipes, reveals, editorial cropping, product-like transitions.
-- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state.
-- **Grid-template rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly.
-
-The hard rule is not "transform and opacity only." The hard rule is: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify in-browser that the result is smooth on the target viewports. If blur/filter makes the interaction feel significantly more premium and remains smooth, use it.
-
-## Staggered Animations
-
-Use CSS custom properties for cleaner stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"` on each item. **Cap total stagger time**: 10 items at 50ms = 500ms total. For many items, reduce per-item delay or cap staggered count.
-
-## Reduced Motion
-
-This is not optional. Vestibular disorders affect ~35% of adults over 40.
-
-```css
-/* Define animations normally */
-.card {
- animation: slide-up 500ms ease-out;
-}
-
-/* Provide alternative for reduced motion */
-@media (prefers-reduced-motion: reduce) {
- .card {
- animation: fade-in 200ms ease-out; /* Crossfade instead of motion */
- }
-}
-
-/* Or disable entirely */
-@media (prefers-reduced-motion: reduce) {
- *, *::before, *::after {
- animation-duration: 0.01ms !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**What to preserve**: Functional animations like progress bars, loading spinners (slowed down), and focus indicators should still work, just without spatial movement.
-
-## Perceived Performance
-
-**Nobody cares how fast your site is, just how fast it feels.** Perception can be as effective as actual performance.
-
-**The 80ms threshold**: Our brains buffer sensory input for ~80ms to synchronize perception. Anything under 80ms feels instant and simultaneous. This is your target for micro-interactions.
-
-**Active vs passive time**: Passive waiting (staring at a spinner) feels longer than active engagement. Strategies to shift the balance:
-
-- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening.
-- **Early completion**: Show content progressively, don't wait for everything. Video buffering, progressive images, streaming HTML.
-- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Instagram likes work offline; the UI updates instantly, syncs later. Use for low-stakes actions; avoid for payments or destructive operations.
-
-**Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances, but ease-in toward a task's end compresses perceived time.
-
-**Caution**: Too-fast responses can decrease perceived value. Users may distrust instant results for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
-
-## Performance
-
-Don't use `will-change` preemptively, only when animation is imminent (`:hover`, `.animating`). For scroll-triggered animations, use Intersection Observer instead of scroll events; unobserve after animating once. Create motion tokens for consistency (durations, easings, common transitions).
-
----
-
-**Avoid**: Animating everything (animation fatigue is real). Using >500ms for UI feedback. Ignoring `prefers-reduced-motion`. Using animation to hide slow loading.
@@ -1,234 +0,0 @@
-> **Additional context needed**: the "aha moment" you want users to reach, and users' experience level.
-
-Get users to first value as fast as possible. Onboarding's job is not to teach the product. Its job is to get people to the moment that proves the product is worth their time.
-
-## Assess Onboarding Needs
-
-Understand what users need to learn and why:
-
-1. **Identify the challenge**:
- - What are users trying to accomplish?
- - What's confusing or unclear about current experience?
- - Where do users get stuck or drop off?
- - What's the "aha moment" we want users to reach?
-
-2. **Understand the users**:
- - What's their experience level? (Beginners, power users, mixed?)
- - What's their motivation? (Excited and exploring? Required by work?)
- - What's their time commitment? (5 minutes? 30 minutes?)
- - What alternatives do they know? (Coming from competitor? New to category?)
-
-3. **Define success**:
- - What's the minimum users need to learn to be successful?
- - What's the key action we want them to take? (First project? First invite?)
- - How do we know onboarding worked? (Completion rate? Time to value?)
-
-**CRITICAL**: Onboarding should get users to value as quickly as possible, not teach everything possible.
-
-## Onboarding Principles
-
-Follow these core principles:
-
-### Show, Don't Tell
-- Demonstrate with working examples, not just descriptions
-- Provide real functionality in onboarding, not separate tutorial mode
-- Use progressive disclosure, teach one thing at a time
-
-### Make It Optional (When Possible)
-- Let experienced users skip onboarding
-- Don't block access to product
-- Provide "Skip" or "I'll explore on my own" options
-
-### Time to Value
-- Get users to their "aha moment" ASAP
-- Front-load most important concepts
-- Teach 20% that delivers 80% of value
-- Save advanced features for contextual discovery
-
-### Context Over Ceremony
-- Teach features when users need them, not upfront
-- Empty states are onboarding opportunities
-- Tooltips and hints at point of use
-
-### Respect User Intelligence
-- Don't patronize or over-explain
-- Be concise and clear
-- Assume users can figure out standard patterns
-
-## Design Onboarding Experiences
-
-Create appropriate onboarding for the context:
-
-### Initial Product Onboarding
-
-**Welcome Screen**:
-- Clear value proposition (what is this product?)
-- What users will learn/accomplish
-- Time estimate (honest about commitment)
-- Option to skip (for experienced users)
-
-**Account Setup**:
-- Minimal required information (collect more later)
-- Explain why you're asking for each piece of information
-- Smart defaults where possible
-- Social login when appropriate
-
-**Core Concept Introduction**:
-- Introduce 1-3 core concepts (not everything)
-- Use simple language and examples
-- Interactive when possible (do, don't just read)
-- Progress indication (step 1 of 3)
-
-**First Success**:
-- Guide users to accomplish something real
-- Pre-populated examples or templates
-- Celebrate completion (but don't overdo it)
-- Clear next steps
-
-### Feature Discovery & Adoption
-
-**Empty States**:
-Instead of blank space, show:
-- What will appear here (description + screenshot/illustration)
-- Why it's valuable
-- Clear CTA to create first item
-- Example or template option
-
-Example:
-```
-No projects yet
-Projects help you organize your work and collaborate with your team.
-[Create your first project] or [Start from template]
-```
-
-**Contextual Tooltips**:
-- Appear at relevant moment (first time user sees feature)
-- Point directly at relevant UI element
-- Brief explanation + benefit
-- Dismissable (with "Don't show again" option)
-- Optional "Learn more" link
-
-**Feature Announcements**:
-- Highlight new features when they're released
-- Show what's new and why it matters
-- Let users try immediately
-- Dismissable
-
-**Progressive Onboarding**:
-- Teach features when users encounter them
-- Badges or indicators on new/unused features
-- Unlock complexity gradually (don't show all options immediately)
-
-### Guided Tours & Walkthroughs
-
-**When to use**:
-- Complex interfaces with many features
-- Significant changes to existing product
-- Industry-specific tools needing domain knowledge
-
-**How to design**:
-- Spotlight specific UI elements (dim rest of page)
-- Keep steps short (3-7 steps max per tour)
-- Allow users to click through tour freely
-- Include "Skip tour" option
-- Make replayable (help menu)
-
-**Best practices**:
-- Interactive over passive (let users click real buttons)
-- Focus on workflow, not features ("Create a project" not "This is the project button")
-- Provide sample data so actions work
-
-### Interactive Tutorials
-
-**When to use**:
-- Users need hands-on practice
-- Concepts are complex or unfamiliar
-- High stakes (better to practice in safe environment)
-
-**How to design**:
-- Sandbox environment with sample data
-- Clear objectives ("Create a chart showing sales by region")
-- Step-by-step guidance
-- Validation (confirm they did it right)
-- Graduation moment (you're ready!)
-
-### Documentation & Help
-
-**In-product help**:
-- Contextual help links throughout interface
-- Keyboard shortcut reference
-- Search-able help center
-- Video tutorials for complex workflows
-
-**Help patterns**:
-- `?` icon near complex features
-- "Learn more" links in tooltips
-- Keyboard shortcut hints (`⌘K` shown on search box)
-
-## Empty State Design
-
-Every empty state needs:
-
-### What Will Be Here
-"Your recent projects will appear here"
-
-### Why It Matters
-"Projects help you organize your work and collaborate with your team"
-
-### How to Get Started
-[Create project] or [Import from template]
-
-### Visual Interest
-Illustration or icon (not just text on blank page)
-
-### Contextual Help
-"Need help getting started? [Watch 2-min tutorial]"
-
-**Empty state types**:
-- **First use**: Never used this feature (emphasize value, provide template)
-- **User cleared**: Intentionally deleted everything (light touch, easy to recreate)
-- **No results**: Search or filter returned nothing (suggest different query, clear filters)
-- **No permissions**: Can't access (explain why, how to get access)
-- **Error state**: Failed to load (explain what happened, retry option)
-
-## Implementation Patterns
-
-### Technical approaches:
-
-**Tooltip libraries**: Tippy.js, Popper.js
-**Tour libraries**: Intro.js, Shepherd.js, React Joyride
-**Modal patterns**: Focus trap, backdrop, ESC to close
-**Progress tracking**: LocalStorage for "seen" states
-**Analytics**: Track completion, drop-off points
-
-**Storage patterns**:
-```javascript
-// Track which onboarding steps user has seen
-localStorage.setItem('onboarding-completed', 'true');
-localStorage.setItem('feature-tooltip-seen-reports', 'true');
-```
-
-**IMPORTANT**: Don't show same onboarding twice (annoying). Track completion and respect dismissals.
-
-**NEVER**:
-- Force users through long onboarding before they can use product
-- Patronize users with obvious explanations
-- Show same tooltip repeatedly (respect dismissals)
-- Block all UI during tour (let users explore)
-- Create separate tutorial mode disconnected from real product
-- Overwhelm with information upfront (progressive disclosure!)
-- Hide "Skip" or make it hard to find
-- Forget about returning users (don't show initial onboarding again)
-
-## Verify Onboarding Quality
-
-Test with real users:
-
-- **Time to completion**: Can users complete onboarding quickly?
-- **Comprehension**: Do users understand after completing?
-- **Action**: Do users take desired next step?
-- **Skip rate**: Are too many users skipping? (Maybe it's too long or not valuable)
-- **Completion rate**: Are users completing? (If low, simplify)
-- **Time to value**: How long until users get first value?
-
-When users hit the aha moment fast and don't drop off, hand off to `/impeccable polish` for the final pass.
@@ -1,258 +0,0 @@
-Performance is a feature. Identify the actual bottleneck for THIS interface, fix it, then measure. Don't optimize what isn't slow.
-
-## Assess Performance Issues
-
-Understand current performance and identify problems:
-
-1. **Measure current state**:
- - **Core Web Vitals**: LCP, FID/INP, CLS scores
- - **Load time**: Time to interactive, first contentful paint
- - **Bundle size**: JavaScript, CSS, image sizes
- - **Runtime performance**: Frame rate, memory usage, CPU usage
- - **Network**: Request count, payload sizes, waterfall
-
-2. **Identify bottlenecks**:
- - What's slow? (Initial load? Interactions? Animations?)
- - What's causing it? (Large images? Expensive JavaScript? Layout thrashing?)
- - How bad is it? (Perceivable? Annoying? Blocking?)
- - Who's affected? (All users? Mobile only? Slow connections?)
-
-**CRITICAL**: Measure before and after. Premature optimization wastes time. Optimize what actually matters.
-
-## Optimization Strategy
-
-Create systematic improvement plan:
-
-### Loading Performance
-
-**Optimize Images**:
-- Use modern formats (WebP, AVIF)
-- Proper sizing (don't load 3000px image for 300px display)
-- Lazy loading for below-fold images
-- Responsive images (`srcset`, `picture` element)
-- Compress images (80-85% quality is usually imperceptible)
-- Use CDN for faster delivery
-
-```html
-<img
- src="hero.webp"
- srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
- sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
- loading="lazy"
- alt="Hero image"
-/>
-```
-
-**Reduce JavaScript Bundle**:
-- Code splitting (route-based, component-based)
-- Tree shaking (remove unused code)
-- Remove unused dependencies
-- Lazy load non-critical code
-- Use dynamic imports for large components
-
-```javascript
-// Lazy load heavy component
-const HeavyChart = lazy(() => import('./HeavyChart'));
-```
-
-**Optimize CSS**:
-- Remove unused CSS
-- Critical CSS inline, rest async
-- Minimize CSS files
-- Use CSS containment for independent regions
-
-**Optimize Fonts**:
-- Use `font-display: swap` or `optional`
-- Subset fonts (only characters you need)
-- Preload critical fonts
-- Use system fonts when appropriate
-- Limit font weights loaded
-
-```css
-@font-face {
- font-family: 'CustomFont';
- src: url('/fonts/custom.woff2') format('woff2');
- font-display: swap; /* Show fallback immediately */
- unicode-range: U+0020-007F; /* Basic Latin only */
-}
-```
-
-**Optimize Loading Strategy**:
-- Critical resources first (async/defer non-critical)
-- Preload critical assets
-- Prefetch likely next pages
-- Service worker for offline/caching
-- HTTP/2 or HTTP/3 for multiplexing
-
-### Rendering Performance
-
-**Avoid Layout Thrashing**:
-```javascript
-// ❌ Bad: Alternating reads and writes (causes reflows)
-elements.forEach(el => {
- const height = el.offsetHeight; // Read (forces layout)
- el.style.height = height * 2; // Write
-});
-
-// ✅ Good: Batch reads, then batch writes
-const heights = elements.map(el => el.offsetHeight); // All reads
-elements.forEach((el, i) => {
- el.style.height = heights[i] * 2; // All writes
-});
-```
-
-**Optimize Rendering**:
-- Use CSS `contain` property for independent regions
-- Minimize DOM depth (flatter is faster)
-- Reduce DOM size (fewer elements)
-- Use `content-visibility: auto` for long lists
-- Virtual scrolling for very long lists (react-window, react-virtualized)
-
-**Reduce Paint & Composite**:
-- Use `transform` and `opacity` for reliable movement, but allow blur, filters, masks, clip paths, shadows, and color shifts when they create meaningful polish
-- Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- Use `will-change` sparingly for known expensive operations
-- Bound expensive paint areas for blur/filter/shadow effects (smaller and isolated is faster)
-
-### Animation Performance
-
-**GPU Acceleration**:
-```css
-/* ✅ GPU-accelerated (fast) */
-.animated {
- transform: translateX(100px);
- opacity: 0.5;
-}
-
-/* ❌ CPU-bound (slow) */
-.animated {
- left: 100px;
- width: 300px;
-}
-```
-
-**Smooth 60fps**:
-- Target 16ms per frame (60fps)
-- Use `requestAnimationFrame` for JS animations
-- Debounce/throttle scroll handlers
-- Use CSS animations when possible
-- Avoid long-running JavaScript during animations
-
-**Intersection Observer**:
-```javascript
-// Efficiently detect when elements enter viewport
-const observer = new IntersectionObserver((entries) => {
- entries.forEach(entry => {
- if (entry.isIntersecting) {
- // Element is visible, lazy load or animate
- }
- });
-});
-```
-
-### React/Framework Optimization
-
-**React-specific**:
-- Use `memo()` for expensive components
-- `useMemo()` and `useCallback()` for expensive computations
-- Virtualize long lists
-- Code split routes
-- Avoid inline function creation in render
-- Use React DevTools Profiler
-
-**Framework-agnostic**:
-- Minimize re-renders
-- Debounce expensive operations
-- Memoize computed values
-- Lazy load routes and components
-
-### Network Optimization
-
-**Reduce Requests**:
-- Combine small files
-- Use SVG sprites for icons
-- Inline small critical assets
-- Remove unused third-party scripts
-
-**Optimize APIs**:
-- Use pagination (don't load everything)
-- GraphQL to request only needed fields
-- Response compression (gzip, brotli)
-- HTTP caching headers
-- CDN for static assets
-
-**Optimize for Slow Connections**:
-- Adaptive loading based on connection (navigator.connection)
-- Optimistic UI updates
-- Request prioritization
-- Progressive enhancement
-
-## Core Web Vitals Optimization
-
-### Largest Contentful Paint (LCP < 2.5s)
-- Optimize hero images
-- Inline critical CSS
-- Preload key resources
-- Use CDN
-- Server-side rendering
-
-### First Input Delay (FID < 100ms) / INP (< 200ms)
-- Break up long tasks
-- Defer non-critical JavaScript
-- Use web workers for heavy computation
-- Reduce JavaScript execution time
-
-### Cumulative Layout Shift (CLS < 0.1)
-- Set dimensions on images and videos
-- Don't inject content above existing content
-- Use `aspect-ratio` CSS property
-- Reserve space for ads/embeds
-- Avoid animations that cause layout shifts
-
-```css
-/* Reserve space for image */
-.image-container {
- aspect-ratio: 16 / 9;
-}
-```
-
-## Performance Monitoring
-
-**Tools to use**:
-- Chrome DevTools (Lighthouse, Performance panel)
-- WebPageTest
-- Core Web Vitals (Chrome UX Report)
-- Bundle analyzers (webpack-bundle-analyzer)
-- Performance monitoring (Sentry, DataDog, New Relic)
-
-**Key metrics**:
-- LCP, FID/INP, CLS (Core Web Vitals)
-- Time to Interactive (TTI)
-- First Contentful Paint (FCP)
-- Total Blocking Time (TBT)
-- Bundle size
-- Request count
-
-**IMPORTANT**: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.
-
-**NEVER**:
-- Optimize without measuring (premature optimization)
-- Sacrifice accessibility for performance
-- Break functionality while optimizing
-- Use `will-change` everywhere (creates new layers, uses memory)
-- Lazy load above-fold content
-- Optimize micro-optimizations while ignoring major issues (optimize the biggest bottleneck first)
-- Forget about mobile performance (often slower devices, slower connections)
-
-## Verify Improvements
-
-Test that optimizations worked:
-
-- **Before/after metrics**: Compare Lighthouse scores
-- **Real user monitoring**: Track improvements for real users
-- **Different devices**: Test on low-end Android, not just flagship iPhone
-- **Slow connections**: Throttle to 3G, test experience
-- **No regressions**: Ensure functionality still works
-- **User perception**: Does it *feel* faster?
-
-When the user-facing numbers move, hand off to `/impeccable polish` for the final pass.
@@ -1,130 +0,0 @@
-Start your response with:
-
-```
-──────────── ⚡ OVERDRIVE ─────────────
-》》》 Entering overdrive mode...
-```
-
-Push an interface past conventional limits. This isn't just about visual effects. It's about using the full power of the browser to make any part of an interface feel extraordinary: a table that handles a million rows, a dialog that morphs from its trigger, a form that validates in real-time with streaming feedback, a page transition that feels cinematic.
-
-**EXTRA IMPORTANT FOR THIS COMMAND**: Context determines what "extraordinary" means. A particle system on a creative portfolio is impressive. The same particle system on a settings page is embarrassing. But a settings page with instant optimistic saves and animated state transitions? That's extraordinary too. Understand the project's personality and goals before deciding what's appropriate.
-
-### Propose Before Building
-
-This command has the highest potential to misfire. Do NOT jump straight into implementation. You MUST:
-
-1. **Think through 2-3 different directions**: consider different techniques, levels of ambition, and aesthetic approaches. For each direction, briefly describe what the result would look and feel like.
-2. **STOP and call the AskUserQuestion tool to clarify.** to present these directions and get the user's pick before writing any code. Explain trade-offs (browser support, performance cost, complexity).
-3. Only proceed with the direction the user confirms.
-
-Skipping this step risks building something embarrassing that needs to be thrown away.
-
-### Iterate with Browser Automation
-
-Technically ambitious effects almost never work on the first try. You MUST actively use browser automation tools to preview your work, visually verify the result, and iterate. Do not assume the effect looks right, check it. Expect multiple rounds of refinement. The gap between "technically works" and "looks extraordinary" is closed through visual iteration, not code alone.
-
----
-
-## Assess What "Extraordinary" Means Here
-
-The right kind of technical ambition depends entirely on what you're working with. Before choosing a technique, ask: **what would make a user of THIS specific interface say "wow, that's nice"?**
-
-### For visual/marketing surfaces
-Pages, hero sections, landing pages, portfolios: the "wow" is often sensory: a scroll-driven reveal, a shader background, a cinematic page transition, generative art that responds to the cursor.
-
-### For functional UI
-Tables, forms, dialogs, navigation: the "wow" is in how it FEELS: a dialog that morphs from the button that triggered it via View Transitions, a data table that renders 100k rows at 60fps via virtual scrolling, a form with streaming validation that feels instant, drag-and-drop with spring physics.
-
-### For performance-critical UI
-The "wow" is invisible but felt: a search that filters 50k items without a flicker, a complex form that never blocks the main thread, an image editor that processes in near-real-time. The interface just never hesitates.
-
-### For data-heavy interfaces
-Charts and dashboards: the "wow" is in fluidity: GPU-accelerated rendering via Canvas/WebGL for massive datasets, animated transitions between data states, force-directed graph layouts that settle naturally.
-
-**The common thread**: something about the implementation goes beyond what users expect from a web interface. The technique serves the experience, not the other way around.
-
-## The Toolkit
-
-Organized by what you're trying to achieve, not by technology name.
-
-### Make transitions feel cinematic
-- **View Transitions API** (same-document: all browsers; cross-document: no Firefox): shared element morphing between states. A list item expanding into a detail page. A button morphing into a dialog. This is the closest thing to native FLIP animations.
-- **`@starting-style`** (all browsers): animate elements from `display: none` to visible with CSS only, including entry keyframes
-- **Spring physics**: natural motion with mass, tension, and damping instead of cubic-bezier. Libraries: motion (formerly Framer Motion), GSAP, or roll your own spring solver.
-
-### Tie animation to scroll position
-- **Scroll-driven animations** (`animation-timeline: scroll()`): CSS-only, no JS. Parallax, progress bars, reveal sequences all driven by scroll position. (Chrome/Edge/Safari; Firefox: flag only; always provide a static fallback)
-
-### Render beyond CSS
-- **WebGL** (all browsers): shader effects, post-processing, particle systems. Libraries: Three.js, OGL (lightweight), regl. Use for effects CSS can't express.
-- **WebGPU** (Chrome/Edge; Safari partial; Firefox: flag only): next-gen GPU compute. More powerful than WebGL but limited browser support. Always fall back to WebGL2.
-- **Canvas 2D / OffscreenCanvas**: custom rendering, pixel manipulation, or moving heavy rendering off the main thread entirely via Web Workers + OffscreenCanvas.
-- **SVG filter chains**: displacement maps, turbulence, morphology for organic distortion effects. CSS-animatable.
-
-### Make data feel alive
-- **Virtual scrolling**: render only visible rows for tables/lists with tens of thousands of items. No library required for simple cases; TanStack Virtual for complex ones.
-- **GPU-accelerated charts**: Canvas or WebGL-rendered data visualization for datasets too large for SVG/DOM. Libraries: deck.gl, regl-based custom renderers.
-- **Animated data transitions**: morph between chart states rather than replacing. D3's `transition()` or View Transitions for DOM-based charts.
-
-### Animate complex properties
-- **`@property`** (all browsers): register custom CSS properties with types, enabling animation of gradients, colors, and complex values that CSS can't normally interpolate.
-- **Web Animations API** (all browsers): JavaScript-driven animations with the performance of CSS. Composable, cancellable, reversible. The foundation for complex choreography.
-
-### Push performance boundaries
-- **Web Workers**: move computation off the main thread. Heavy data processing, image manipulation, search indexing: anything that would cause jank.
-- **OffscreenCanvas**: render in a Worker thread. The main thread stays free while complex visuals render in the background.
-- **WASM**: near-native performance for computation-heavy features. Image processing, physics simulations, codecs.
-
-### Interact with the device
-- **Web Audio API**: spatial audio, audio-reactive visualizations, sonic feedback. Requires user gesture to start.
-- **Device APIs**: orientation, ambient light, geolocation. Use sparingly and always with user permission.
-
-**NOTE**: This command is about enhancing how an interface FEELS, not changing what a product DOES. Adding real-time collaboration, offline support, or new backend capabilities are product decisions, not UI enhancements. Focus on making existing features feel extraordinary.
-
-## Implement with Discipline
-
-### Progressive enhancement is non-negotiable
-
-Every technique must degrade gracefully. The experience without the enhancement must still be good.
-
-```css
-@supports (animation-timeline: scroll()) {
- .hero { animation-timeline: scroll(); }
-}
-```
-
-```javascript
-if ('gpu' in navigator) { /* WebGPU */ }
-else if (canvas.getContext('webgl2')) { /* WebGL2 fallback */ }
-/* CSS-only fallback must still look good */
-```
-
-### Performance rules
-
-- Target 60fps. If dropping below 50, simplify.
-- Respect `prefers-reduced-motion`, always. Provide a beautiful static alternative.
-- Lazy-initialize heavy resources (WebGL contexts, WASM modules) only when near viewport.
-- Pause off-screen rendering. Kill what you can't see.
-- Test on real mid-range devices, not just your development machine.
-
-### Polish is the difference
-
-The gap between "cool" and "extraordinary" is in the last 20% of refinement: the easing curve on a spring animation, the timing offset in a staggered reveal, the subtle secondary motion that makes a transition feel physical. Don't ship the first version that works; ship the version that feels inevitable.
-
-**NEVER**:
-- Ignore `prefers-reduced-motion`. This is an accessibility requirement, not a suggestion
-- Ship effects that cause jank on mid-range devices
-- Use bleeding-edge APIs without a functional fallback
-- Add sound without explicit user opt-in
-- Use technical ambition to mask weak design fundamentals; fix those first with other commands
-- Layer multiple competing extraordinary moments. Focus creates impact, excess creates noise
-
-## Verify the Result
-
-- **The wow test**: Show it to someone who hasn't seen it. Do they react?
-- **The removal test**: Take it away. Does the experience feel diminished, or does nobody notice?
-- **The device test**: Run it on a phone, a tablet, a Chromebook. Still smooth?
-- **The accessibility test**: Enable reduced motion. Still beautiful?
-- **The context test**: Does this make sense for THIS brand and audience?
-
-"Technically extraordinary" isn't about using the newest API. It's about making an interface do something users didn't think a website could do.
@@ -1,179 +0,0 @@
-# Persona-Based Design Testing
-
-Test the interface through the eyes of 5 distinct user archetypes. Each persona exposes different failure modes that a single "design director" perspective would miss.
-
-**How to use**: Select 2–3 personas most relevant to the interface being critiqued. Walk through the primary user action as each persona. Report specific red flags, not generic concerns.
-
----
-
-## 1. Impatient Power User: "Alex"
-
-
-**Profile**: Expert with similar products. Expects efficiency, hates hand-holding. Will find shortcuts or leave.
-
-**Behaviors**:
-- Skips all onboarding and instructions
-- Looks for keyboard shortcuts immediately
-- Tries to bulk-select, batch-edit, and automate
-- Gets frustrated by required steps that feel unnecessary
-- Abandons if anything feels slow or patronizing
-
-**Test Questions**:
-- Can Alex complete the core task in under 60 seconds?
-- Are there keyboard shortcuts for common actions?
-- Can onboarding be skipped entirely?
-- Do modals have keyboard dismiss (Esc)?
-- Is there a "power user" path (shortcuts, bulk actions)?
-
-**Red Flags** (report these specifically):
-- Forced tutorials or unskippable onboarding
-- No keyboard navigation for primary actions
-- Slow animations that can't be skipped
-- One-item-at-a-time workflows where batch would be natural
-- Redundant confirmation steps for low-risk actions
-
----
-
-## 2. Confused First-Timer: "Jordan"
-
-**Profile**: Never used this type of product. Needs guidance at every step. Will abandon rather than figure it out.
-
-**Behaviors**:
-- Reads all instructions carefully
-- Hesitates before clicking anything unfamiliar
-- Looks for help or support constantly
-- Misunderstands jargon and abbreviations
-- Takes the most literal interpretation of any label
-
-**Test Questions**:
-- Is the first action obviously clear within 5 seconds?
-- Are all icons labeled with text?
-- Is there contextual help at decision points?
-- Does terminology assume prior knowledge?
-- Is there a clear "back" or "undo" at every step?
-
-**Red Flags** (report these specifically):
-- Icon-only navigation with no labels
-- Technical jargon without explanation
-- No visible help option or guidance
-- Ambiguous next steps after completing an action
-- No confirmation that an action succeeded
-
----
-
-## 3. Accessibility-Dependent User: "Sam"
-
-**Profile**: Uses screen reader (VoiceOver/NVDA), keyboard-only navigation. May have low vision, motor impairment, or cognitive differences.
-
-**Behaviors**:
-- Tabs through the interface linearly
-- Relies on ARIA labels and heading structure
-- Cannot see hover states or visual-only indicators
-- Needs adequate color contrast (4.5:1 minimum)
-- May use browser zoom up to 200%
-
-**Test Questions**:
-- Can the entire primary flow be completed keyboard-only?
-- Are all interactive elements focusable with visible focus indicators?
-- Do images have meaningful alt text?
-- Is color contrast WCAG AA compliant (4.5:1 for text)?
-- Does the screen reader announce state changes (loading, success, errors)?
-
-**Red Flags** (report these specifically):
-- Click-only interactions with no keyboard alternative
-- Missing or invisible focus indicators
-- Meaning conveyed by color alone (red = error, green = success)
-- Unlabeled form fields or buttons
-- Time-limited actions without extension option
-- Custom components that break screen reader flow
-
----
-
-## 4. Deliberate Stress Tester: "Riley"
-
-**Profile**: Methodical user who pushes interfaces beyond the happy path. Tests edge cases, tries unexpected inputs, and probes for gaps in the experience.
-
-**Behaviors**:
-- Tests edge cases intentionally (empty states, long strings, special characters)
-- Submits forms with unexpected data (emoji, RTL text, very long values)
-- Tries to break workflows by navigating backwards, refreshing mid-flow, or opening in multiple tabs
-- Looks for inconsistencies between what the UI promises and what actually happens
-- Documents problems methodically
-
-**Test Questions**:
-- What happens at the edges (0 items, 1000 items, very long text)?
-- Do error states recover gracefully or leave the UI in a broken state?
-- What happens on refresh mid-workflow? Is state preserved?
-- Are there features that appear to work but produce broken results?
-- How does the UI handle unexpected input (emoji, special chars, paste from Excel)?
-
-**Red Flags** (report these specifically):
-- Features that appear to work but silently fail or produce wrong results
-- Error handling that exposes technical details or leaves UI in a broken state
-- Empty states that show nothing useful ("No results" with no guidance)
-- Workflows that lose user data on refresh or navigation
-- Inconsistent behavior between similar interactions in different parts of the UI
-
----
-
-## 5. Distracted Mobile User: "Casey"
-
-**Profile**: Using phone one-handed on the go. Frequently interrupted. Possibly on a slow connection.
-
-**Behaviors**:
-- Uses thumb only; prefers bottom-of-screen actions
-- Gets interrupted mid-flow and returns later
-- Switches between apps frequently
-- Has limited attention span and low patience
-- Types as little as possible, prefers taps and selections
-
-**Test Questions**:
-- Are primary actions in the thumb zone (bottom half of screen)?
-- Is state preserved if the user leaves and returns?
-- Does it work on slow connections (3G)?
-- Can forms use autocomplete and smart defaults?
-- Are touch targets at least 44×44pt?
-
-**Red Flags** (report these specifically):
-- Important actions positioned at the top of the screen (unreachable by thumb)
-- No state persistence; progress lost on tab switch or interruption
-- Large text inputs required where selection would work
-- Heavy assets loading on every page (no lazy loading)
-- Tiny tap targets or targets too close together
-
----
-
-## Selecting Personas
-
-Choose personas based on the interface type:
-
-| Interface Type | Primary Personas | Why |
-|---------------|-----------------|-----|
-| Landing page / marketing | Jordan, Riley, Casey | First impressions, trust, mobile |
-| Dashboard / admin | Alex, Sam | Power users, accessibility |
-| E-commerce / checkout | Casey, Riley, Jordan | Mobile, edge cases, clarity |
-| Onboarding flow | Jordan, Casey | Confusion, interruption |
-| Data-heavy / analytics | Alex, Sam | Efficiency, keyboard nav |
-| Form-heavy / wizard | Jordan, Sam, Casey | Clarity, accessibility, mobile |
-
----
-
-## Project-Specific Personas
-
-If `CLAUDE.md` contains a `## Design Context` section (generated by `impeccable teach`), derive 1–2 additional personas from the audience and brand information:
-
-1. Read the target audience description
-2. Identify the primary user archetype not covered by the 5 predefined personas
-3. Create a persona following this template:
-
-```
-### [Role]: "[Name]"
-
-**Profile**: [2-3 key characteristics derived from Design Context]
-
-**Behaviors**: [3-4 specific behaviors based on the described audience]
-
-**Red Flags**: [3-4 things that would alienate this specific user type]
-```
-
-Only generate project-specific personas when real Design Context data is available. Don't invent audience details; use the 5 predefined personas when no context exists.
@@ -1,242 +0,0 @@
-> **Additional context needed**: quality bar (MVP vs flagship).
-
-Perform a meticulous final pass to catch all the small details that separate good work from great work. The difference between shipped and polished.
-
-Detector and automated QA output are defect evidence only. A clean script result is never proof that the design is strong; gather browser evidence and inspect the real interaction path.
-
-## Design System Discovery
-
-Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
-
-1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
-2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
-3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category: patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
-
-If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask. Never guess at design system principles.**
-
-## Pre-Polish Assessment
-
-Understand the current state and goals before touching anything:
-
-1. **Review completeness**:
- - Is it functionally complete?
- - Are there known issues to preserve (mark with TODOs)?
- - What's the quality bar? (MVP vs flagship feature?)
- - When does it ship? (How much time for polish?)
-
-2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish; a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
-
-3. **Identify polish areas**:
- - Visual inconsistencies
- - Spacing and alignment issues
- - Interaction state gaps
- - Copy inconsistencies
- - Edge cases and error states
- - Loading and transition smoothness
- - Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
-
-4. **Pull in any prior critique** (optional signal): If `/impeccable critique` has been run on the same target, its priority issues are a useful prior for what to address first. Resolve the target to a file path or URL, then:
- ```bash
- slug=$(node .claude/skills/impeccable/scripts/critique-storage.mjs slug "<resolved>")
- node .claude/skills/impeccable/scripts/critique-storage.mjs latest "$slug"
- ```
- Exit 0 with body = found; fold the P0/P1 items into your polish list and mention the snapshot path so the user sees what you read. Exit 2 = no snapshot, continue without it. The critique is one input among many. Do your own pass either way.
-
-5. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent; never perfect one corner while leaving another rough.
-
-**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
-
-## Polish Systematically
-
-Work through these dimensions methodically:
-
-### Visual Alignment & Spacing
-
-- **Pixel-perfect alignment**: Everything lines up to grid
-- **Consistent spacing**: All gaps use spacing scale (no random 13px gaps)
-- **Optical alignment**: Adjust for visual weight (icons may need offset for optical centering)
-- **Responsive consistency**: Spacing and alignment work at all breakpoints
-- **Grid adherence**: Elements snap to baseline grid
-
-**Check**:
-- Enable grid overlay and verify alignment
-- Check spacing with browser inspector
-- Test at multiple viewport sizes
-- Look for elements that "feel" off
-
-### Information Architecture & Flow
-
-Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
-
-- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
-- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere: modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
-- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
-- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
-- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
-
-### Typography Refinement
-
-- **Hierarchy consistency**: Same elements use same sizes/weights throughout
-- **Line length**: 45-75 characters for body text
-- **Line height**: Appropriate for font size and context
-- **Widows & orphans**: No single words on last line
-- **Hyphenation**: Appropriate for language and column width
-- **Kerning**: Adjust letter spacing where needed (especially headlines)
-- **Font loading**: No FOUT/FOIT flashes
-
-### Color & Contrast
-
-- **Contrast ratios**: All text meets WCAG standards
-- **Consistent token usage**: No hard-coded colors, all use design tokens
-- **Theme consistency**: Works in all theme variants
-- **Color meaning**: Same colors mean same things throughout
-- **Accessible focus**: Focus indicators visible with sufficient contrast
-- **Tinted neutrals**: No pure gray or pure black; add subtle color tint (0.01 chroma)
-- **Gray on color**: Never put gray text on colored backgrounds; use a shade of that color or transparency
-
-### Interaction States
-
-Every interactive element needs all states:
-
-- **Default**: Resting state
-- **Hover**: Subtle feedback (color, scale, shadow)
-- **Focus**: Keyboard focus indicator (never remove without replacement)
-- **Active**: Click/tap feedback
-- **Disabled**: Clearly non-interactive
-- **Loading**: Async action feedback
-- **Error**: Validation or error state
-- **Success**: Successful completion
-
-**Missing states create confusion and broken experiences**.
-
-### Micro-interactions & Transitions
-
-- **Smooth transitions**: All state changes animated appropriately (150-300ms)
-- **Consistent easing**: Use ease-out-quart/quint/expo for natural deceleration. Never bounce or elastic; they feel dated.
-- **No jank**: Smooth animations; use atmospheric blur/filter/mask/shadow effects when they add polish, but bound expensive paint areas and avoid casual layout-property animation
-- **Appropriate motion**: Motion serves purpose, not decoration
-- **Reduced motion**: Respects `prefers-reduced-motion`
-
-### Content & Copy
-
-- **Consistent terminology**: Same things called same names throughout
-- **Consistent capitalization**: Title Case vs Sentence case applied consistently
-- **Grammar & spelling**: No typos
-- **Appropriate length**: Not too wordy, not too terse
-- **Punctuation consistency**: Periods on sentences, not on labels (unless all labels have them)
-
-### Icons & Images
-
-- **Consistent style**: All icons from same family or matching style
-- **Appropriate sizing**: Icons sized consistently for context
-- **Proper alignment**: Icons align with adjacent text optically
-- **Alt text**: All images have descriptive alt text
-- **Loading states**: Images don't cause layout shift, proper aspect ratios
-- **Retina support**: 2x assets for high-DPI screens
-
-### Forms & Inputs
-
-- **Label consistency**: All inputs properly labeled
-- **Required indicators**: Clear and consistent
-- **Error messages**: Helpful and consistent
-- **Tab order**: Logical keyboard navigation
-- **Auto-focus**: Appropriate (don't overuse)
-- **Validation timing**: Consistent (on blur vs on submit)
-
-### Edge Cases & Error States
-
-- **Loading states**: All async actions have loading feedback
-- **Empty states**: Helpful empty states, not just blank space
-- **Error states**: Clear error messages with recovery paths
-- **Success states**: Confirmation of successful actions
-- **Long content**: Handles very long names, descriptions, etc.
-- **No content**: Handles missing data gracefully
-- **Offline**: Appropriate offline handling (if applicable)
-
-### Responsiveness
-
-- **All breakpoints**: Test mobile, tablet, desktop
-- **Touch targets**: 44x44px minimum on touch devices
-- **Readable text**: No text smaller than 14px on mobile
-- **No horizontal scroll**: Content fits viewport
-- **Appropriate reflow**: Content adapts logically
-
-### Performance
-
-- **Fast initial load**: Optimize critical path
-- **No layout shift**: Elements don't jump after load (CLS)
-- **Smooth interactions**: No lag or jank
-- **Optimized images**: Appropriate formats and sizes
-- **Lazy loading**: Off-screen content loads lazily
-
-### Code Quality
-
-- **Remove console logs**: No debug logging in production
-- **Remove commented code**: Clean up dead code
-- **Remove unused imports**: Clean up unused dependencies
-- **Consistent naming**: Variables and functions follow conventions
-- **Type safety**: No TypeScript `any` or ignored errors
-- **Accessibility**: Proper ARIA labels and semantic HTML
-
-## Polish Checklist
-
-Go through systematically:
-
-- [ ] Aligned to the design system (drift named and resolved by root cause)
-- [ ] Information architecture and flow shape match neighboring features
-- [ ] Visual alignment perfect at all breakpoints
-- [ ] Spacing uses design tokens consistently
-- [ ] Typography hierarchy consistent
-- [ ] All interactive states implemented
-- [ ] All transitions smooth (60fps)
-- [ ] Copy is consistent and polished
-- [ ] Icons are consistent and properly sized
-- [ ] All forms properly labeled and validated
-- [ ] Error states are helpful
-- [ ] Loading states are clear
-- [ ] Empty states are welcoming
-- [ ] Touch targets are 44x44px minimum
-- [ ] Contrast ratios meet WCAG AA
-- [ ] Keyboard navigation works
-- [ ] Focus indicators visible
-- [ ] No console errors or warnings
-- [ ] No layout shift on load
-- [ ] Works in all supported browsers
-- [ ] Respects reduced motion preference
-- [ ] Code is clean (no TODOs, console.logs, commented code)
-
-**IMPORTANT**: Polish is about details. Zoom in. Squint at it. Use it yourself. The little things add up.
-
-Sweat the details. Zoom in until the alignment is right and the spacing reads as deliberate. Then ship.
-
-**NEVER**:
-- Polish before it's functionally complete
-- Polish without aligning to the design system; that's decoration on drift
-- Guess at design system principles instead of asking when something is ambiguous
-- Spend hours on polish if it ships in 30 minutes (triage)
-- Introduce bugs while polishing (test thoroughly)
-- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
-- Perfect one thing while leaving others rough (consistent quality level)
-- Create new one-off components when design system equivalents exist
-- Hard-code values that should use design tokens
-- Introduce new patterns or flows that diverge from established ones
-
-## Final Verification
-
-Before marking as done:
-
-- **Use it yourself**: Actually interact with the feature.
-- **Test on real devices**: Not just browser DevTools.
-- **Ask someone else to review**: Fresh eyes catch things.
-- **Compare to design**: Match intended design.
-- **Check all states**: Don't just test happy path.
-- **Treat automation carefully**: Run detector or QA commands when they are available and relevant, fix their defects, but never cite a clean result as proof that the work is polished.
-
-## Clean Up
-
-After polishing, ensure code quality:
-
-- **Replace custom implementations**: If the design system provides a component you reimplemented, switch to the shared version.
-- **Remove orphaned code**: Delete unused styles, components, or files made obsolete by polish.
-- **Consolidate tokens**: If you introduced new values, check whether they should be tokens.
-- **Verify DRYness**: Look for duplication introduced during polishing and consolidate.
@@ -1,62 +0,0 @@
-# Product register
-
-When design SERVES the product: app UIs, admin dashboards, settings panels, data tables, tools, authenticated surfaces, anything where the user is in a task.
-
-## The product slop test
-
-Not "would someone say AI made this." Familiarity is often a feature here. The test is: would a user fluent in the category's best tools (Linear, Figma, Notion, Raycast, Stripe come to mind) sit down and trust this interface, or pause at every subtly-off component?
-
-Product UI's failure mode isn't flatness, it's strangeness without purpose: over-decorated buttons, mismatched form controls, gratuitous motion, display fonts where labels should be, invented affordances for standard tasks. The bar is earned familiarity. The tool should disappear into the task.
-
-## Typography
-
-- **System fonts are legitimate.** `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` gives you native feel on every platform. Inter is the common cross-platform default for a reason.
-- **One family is often right.** Product UIs don't need display/body pairing. A well-tuned sans carries headings, buttons, labels, body, data.
-- **Fixed rem scale, not fluid.** Clamp-sized headings don't serve product UI. Users view at consistent DPI, and a fluid h1 that shrinks in a sidebar looks worse, not better.
-- **Tighter scale ratio.** 1.125–1.2 between steps is typical. More type elements here than on brand surfaces; exaggerated contrast creates noise.
-- **Line length still applies for prose** (65–75ch). Data and compact UI can run denser; tables at 120ch+ are fine.
-
-## Color
-
-Product defaults to Restrained. A single surface can earn Committed (a dashboard where one category color carries a report, an onboarding flow with a drenched welcome screen), but Restrained is the floor.
-
-- State-rich semantic vocabulary: hover, focus, active, disabled, selected, loading, error, warning, success, info. Standardize these.
-- Accent color used for primary actions, current selection, and state indicators only, not decoration.
-- A second neutral layer for sidebars, toolbars, and panels (slightly cooler or warmer than the content surface).
-
-## Layout
-
-- Predictable grids. Consistency IS an affordance; users navigate faster when the structure is expected.
-- Familiar patterns are features. Standard navigation (top bar, side nav), breadcrumbs, tabs, and form layouts have established user expectations. Don't reinvent for flavor.
-- Responsive behavior is structural (collapse sidebar, responsive table, breakpoint-driven columns), not fluid typography.
-
-## Components
-
-Every interactive component has: default, hover, focus, active, disabled, loading, error. Don't ship with half of these.
-
-- Skeleton states for loading, not spinners in the middle of content.
-- Empty states that teach the interface, not "nothing here."
-- Consistent affordances across the surface. Same button shape. Same form-control vocabulary. Same icon style.
-
-## Motion
-
-- 150–250 ms on most transitions. Users are in flow; don't make them wait for choreography.
-- Motion conveys state, not decoration. State change, feedback, loading, reveal: nothing else.
-- No orchestrated page-load sequences. Product loads into a task; users don't want to watch it load.
-
-## Product bans (on top of the shared absolute bans)
-
-- Decorative motion that doesn't convey state.
-- Inconsistent component vocabulary across screens. If the "save" button looks different in two places, one is wrong.
-- Display fonts in UI labels, buttons, data.
-- Reinventing standard affordances for flavor (custom scrollbars, weird form controls, non-standard modals).
-- Heavy color or full-saturation accents on inactive states.
-
-## Product permissions
-
-Product can afford things brand surfaces can't.
-
-- System fonts and familiar sans defaults (Inter, SF Pro, system-ui stacks).
-- Standard navigation patterns: top bar + side nav, breadcrumbs, tabs, command palettes.
-- Density. Tables with many rows, panels with many labels, dense information when users need it.
-- Consistency over surprise. The same visual vocabulary screen to screen is a virtue; delight is saved for moments, not pages.
@@ -1,99 +0,0 @@
-Quiet design is harder than bold design. Subtlety needs precision. Reduce visual intensity in designs that are too loud, aggressive, or overstimulating without losing personality or making the result generic.
-
----
-
-## Register
-
-Brand: "quieter" means more restrained palette, more whitespace, more typographic air. Drama is reduced, not eliminated; the POV stays intact.
-
-Product: "quieter" means reducing visual noise. Fewer background accents, flatter cards, less color, less motion. The tool should disappear more completely into the task.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too intense:
-
-1. **Identify intensity sources**:
- - **Color saturation**: Overly bright or saturated colors
- - **Contrast extremes**: Too much high-contrast juxtaposition
- - **Visual weight**: Too many bold, heavy elements competing
- - **Animation excess**: Too much motion or overly dramatic effects
- - **Complexity**: Too many visual elements, patterns, or decorations
- - **Scale**: Everything is large and loud with no hierarchy
-
-2. **Understand the context**:
- - What's the purpose? (Marketing vs tool vs reading experience)
- - Who's the audience? (Some contexts need energy)
- - What's working? (Don't throw away good ideas)
- - What's the core message? (Preserve what matters)
-
-If any of these are unclear from the codebase, STOP and call the AskUserQuestion tool to clarify.
-
-**CRITICAL**: "Quieter" doesn't mean boring or generic. It means refined and easier on the eyes. Think luxury, not laziness.
-
-## Plan Refinement
-
-Create a strategy to reduce intensity while maintaining impact:
-
-- **Color approach**: Desaturate or shift to more restrained tones?
-- **Hierarchy approach**: Which elements should stay bold (very few), which should recede?
-- **Simplification approach**: What can be removed entirely?
-- **Sophistication approach**: How can we signal quality through restraint?
-
-**IMPORTANT**: Subtlety requires precision. Quiet without intent collapses to generic.
-
-## Refine the Design
-
-Systematically reduce intensity across these dimensions:
-
-### Color Refinement
-- **Reduce saturation**: Shift from fully saturated to 70-85% saturation
-- **Soften palette**: Replace bright colors with muted tones
-- **Reduce color variety**: Use fewer colors more thoughtfully
-- **Neutral dominance**: Let neutrals do more work, use color as accent (10% rule)
-- **Gentler contrasts**: High contrast only where it matters most
-- **Tinted grays**: Use warm or cool tinted grays instead of pure gray. Adds depth without loudness
-- **Never gray on color**: If you have gray text on a colored background, use a darker shade of that color or transparency instead
-
-### Visual Weight Reduction
-- **Typography**: Reduce font weights (900 → 600, 700 → 500), decrease sizes where appropriate
-- **Hierarchy through subtlety**: Use weight, size, and space instead of color and boldness
-- **White space**: Increase breathing room, reduce density
-- **Borders & lines**: Reduce thickness, decrease opacity, or remove entirely
-
-### Simplification
-- **Remove decorative elements**: Gradients, shadows, patterns, textures that don't serve purpose
-- **Simplify shapes**: Reduce border radius extremes, simplify custom shapes
-- **Reduce layering**: Flatten visual hierarchy where possible
-- **Clean up effects**: Reduce or remove blur effects, glows, multiple shadows
-
-### Motion Reduction
-- **Reduce animation intensity**: Shorter distances (10-20px instead of 40px), gentler easing
-- **Remove decorative animations**: Keep functional motion, remove flourishes
-- **Subtle micro-interactions**: Replace dramatic effects with gentle feedback
-- **Refined easing**: Use ease-out-quart for smooth, understated motion. Never bounce or elastic
-- **Remove animations entirely** if they're not serving a clear purpose
-
-### Composition Refinement
-- **Reduce scale jumps**: Smaller contrast between sizes creates calmer feeling
-- **Align to grid**: Bring rogue elements back into systematic alignment
-- **Even out spacing**: Replace extreme spacing variations with consistent rhythm
-
-**NEVER**:
-- Make everything the same size/weight (hierarchy still matters)
-- Remove all color (quiet ≠ grayscale)
-- Eliminate all personality (maintain character through refinement)
-- Sacrifice usability for aesthetics (functional elements still need clear affordances)
-- Make everything small and light (some anchors needed)
-
-## Verify Quality
-
-Ensure refinement maintains quality:
-
-- **Still functional**: Can users still accomplish tasks easily?
-- **Still distinctive**: Does it have character, or is it generic now?
-- **Better reading**: Is text easier to read for extended periods?
-- **Restrained, not absent**: Does the POV survive the cuts?
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,114 +0,0 @@
-# Responsive Design
-
-## Mobile-First: Write It Right
-
-Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
-
-## Breakpoints: Content-Driven
-
-Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
-
-## Detect Input Method, Not Just Screen Size
-
-**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
-
-```css
-/* Fine pointer (mouse, trackpad) */
-@media (pointer: fine) {
- .button { padding: 8px 16px; }
-}
-
-/* Coarse pointer (touch, stylus) */
-@media (pointer: coarse) {
- .button { padding: 12px 20px; } /* Larger touch target */
-}
-
-/* Device supports hover */
-@media (hover: hover) {
- .card:hover { transform: translateY(-2px); }
-}
-
-/* Device doesn't support hover (touch) */
-@media (hover: none) {
- .card { /* No hover state - use active instead */ }
-}
-```
-
-**Critical**: Don't rely on hover for functionality. Touch users can't hover.
-
-## Safe Areas: Handle the Notch
-
-Modern phones have notches, rounded corners, and home indicators. Use `env()`:
-
-```css
-body {
- padding-top: env(safe-area-inset-top);
- padding-bottom: env(safe-area-inset-bottom);
- padding-left: env(safe-area-inset-left);
- padding-right: env(safe-area-inset-right);
-}
-
-/* With fallback */
-.footer {
- padding-bottom: max(1rem, env(safe-area-inset-bottom));
-}
-```
-
-**Enable viewport-fit** in your meta tag:
-```html
-<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
-```
-
-## Responsive Images: Get It Right
-
-### srcset with Width Descriptors
-
-```html
-<img
- src="hero-800.jpg"
- srcset="
- hero-400.jpg 400w,
- hero-800.jpg 800w,
- hero-1200.jpg 1200w
- "
- sizes="(max-width: 768px) 100vw, 50vw"
- alt="Hero image"
->
-```
-
-**How it works**:
-- `srcset` lists available images with their actual widths (`w` descriptors)
-- `sizes` tells the browser how wide the image will display
-- Browser picks the best file based on viewport width AND device pixel ratio
-
-### Picture Element for Art Direction
-
-When you need different crops/compositions (not just resolutions):
-
-```html
-<picture>
- <source media="(min-width: 768px)" srcset="wide.jpg">
- <source media="(max-width: 767px)" srcset="tall.jpg">
- <img src="fallback.jpg" alt="...">
-</picture>
-```
-
-## Layout Adaptation Patterns
-
-**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
-
-## Testing: Don't Trust DevTools Alone
-
-DevTools device emulation is useful for layout but misses:
-
-- Actual touch interactions
-- Real CPU/memory constraints
-- Network latency patterns
-- Font rendering differences
-- Browser chrome/keyboard appearances
-
-**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
-
----
-
-**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
@@ -1,165 +0,0 @@
-Shape the UX and UI for a feature before any code is written. This command produces a **design brief**: a structured artifact that guides implementation through discovery, not guesswork.
-
-**Scope**: Design planning only. This command does NOT write code. It produces the thinking that makes code good.
-
-**Output**: A design brief that can be handed off to /impeccable craft, or directly to /impeccable for freeform implementation. When visual direction probes are used, the images are supporting artifacts, not the primary output.
-
-## Philosophy
-
-Most AI-generated UIs fail not because of bad code, but because of skipped thinking. They jump to "here's a card grid" without asking "what is the user trying to accomplish?" This command inverts that: understand deeply first, so implementation is precise.
-
-## Phase 1: Discovery Interview
-
-**Do NOT write any code or make any design decisions during this phase.** Your only job is to understand the feature deeply enough to make excellent design decisions later.
-
-This is a required interaction, not optional guidance. Ask these questions in conversation, adapting based on answers. Don't dump them all at once; have a natural dialogue. STOP and call the AskUserQuestion tool to clarify.
-
-### Interview cadence
-
-Discovery includes at least one user-answer round unless PRODUCT.md, DESIGN.md, or an already-confirmed brief directly answers the needed inputs. With a sparse prompt, do **not** synthesize a complete brief for confirmation on the first response.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Treat PRODUCT.md and DESIGN.md as anchors; they reduce repeated questions but do **not** replace shape for craft. Shape is task-specific.
-- One round is the default. Add a second only if the first answers leave material gaps. Don't run a second round just to feel thorough.
-- Round 1 should clarify purpose, audience/context, content/scope, and (for brand) visual direction.
-- Round 2, when needed, fills in whatever's still genuinely missing.
-
-**Assert-then-confirm, not menu-with-escape.** When PRODUCT.md and the user's prompt make one option obvious, name it and ask the user to confirm or override. Don't enumerate "Restrained / Committed / Or something else?" as a real choice; "This reads as Restrained, confirm?" beats a four-option menu when the answer is already clear.
-
-### Purpose & Context
-- What is this feature for? What problem does it solve?
-- Who specifically will use it? (Not "users"; be specific: role, context, frequency)
-- What does success look like? How will you know this feature is working?
-- What's the user's state of mind when they reach this feature? (Rushed? Exploring? Anxious? Focused?)
-
-### Content & Data
-- What content or data does this feature display or collect?
-- What are the realistic ranges? (Minimum, typical, maximum, e.g., 0 items, 5 items, 500 items)
-- What are the edge cases? (Empty state, error state, first-time use, power user)
-- Is any content dynamic? What changes and how often?
-- What visual assets are real content here? Note required images, product shots, illustrations, maps, textures, diagrams, generated objects, or existing project assets.
-
-### Design Direction
-
-Force a visual decision on three fronts. Skip anything PRODUCT.md or DESIGN.md already answers; ask only what's missing.
-
-- **Color strategy for this surface.** Pick one: Restrained / Committed / Full palette / Drenched. Can override the project default if the surface earns it (e.g. a drenched hero inside an otherwise Restrained product).
-- **Theme via scene sentence.** Write one sentence of physical context for this surface: who uses it, where, under what ambient light, in what mood. The sentence forces dark vs light. If it doesn't, add detail until it does.
-- **Two or three named anchor references.** Specific products, brands, objects. Not adjectives like "modern" or "clean."
-
-### Scope
-
-Always ask. Sketch quality and shipped quality are different outputs; don't guess between them.
-
-- **Fidelity.** Sketch / mid-fi / high-fi / production-ready?
-- **Breadth.** One screen / a flow / a whole surface?
-- **Interactivity.** Static visual / interactive prototype / shipped-quality component?
-- **Time intent.** Quick exploration, or polish until it ships?
-
-Scope answers are task-scoped. Don't write them to PRODUCT.md or DESIGN.md; carry them through the design brief only.
-
-### Constraints
-- Are there technical constraints? (Framework, performance budget, browser support)
-- Are there content constraints? (Localization, dynamic text length, user-generated content)
-- Mobile/responsive requirements?
-- Accessibility requirements beyond WCAG AA?
-
-### Anti-Goals
-- What should this NOT be? What would be a wrong direction?
-- What's the biggest risk of getting this wrong?
-
-## Phase 1.5: Visual Direction Probe (Capability-Gated)
-
-After the discovery interview, generate a small set of visual direction probes **before** writing the final brief when all of these are true:
-
-- The work is **net-new** or directionally ambiguous enough that visual exploration will clarify the brief.
-- The requested fidelity is **mid-fi, high-fi, or production-ready**. Skip for sketch-only planning.
-- The current harness gives you native image generation (Codex's `image_gen`, an equivalent MCP tool, or similar). Don't ask the user to install APIs or tooling.
-
-When those conditions are met, this step is mandatory. If image generation isn't natively available, do not ask the user to install APIs or tooling. State in one line that the image step is skipped because the harness lacks native image generation, then proceed. The one-line announcement is required, not optional; it forces a conscious decision instead of letting the step quietly evaporate.
-
-Use probes to explore visual lanes, not to replace the brief.
-
-Do not skip probes because the final UI will be semantic, editable, code-native, responsive, or accessible. Those are implementation requirements, not reasons to avoid visual exploration.
-
-### What to generate
-
-Generate **2 to 4** distinct direction probes based on the discovery answers, especially:
-
-- Color strategy
-- Theme scene sentence
-- Named anchor references
-- Scope and fidelity
-
-The probes should differ in primary visual direction (hierarchy, topology, density, typographic voice, or color strategy), not just palette tweaks.
-
-### How to use the probes
-
-- Treat them as **direction tests**, not final designs.
-- Use them to pressure-test whether the brief is pointing at the right lane.
-- Ask the user which direction feels closest, what feels off, and what should carry forward.
-- If the probes reveal a mismatch, revise the brief inputs before finalizing the brief.
-
-### Important limits
-
-- Do **not** skip discovery because image generation is available.
-- Do **not** treat generated imagery as final UX specification, final copy, or final accessibility behavior.
-- Do **not** use this step for minor refinements of existing work. It's for shaping a new surface or clarifying a big directional choice.
-
-If image generation isn't natively available, announce the skip in one line and proceed to the design brief.
-
-## Phase 2: Design Brief
-
-After the interview and any required probes, present a brief and **end your response**. The user must confirm before any implementation runs. Do not present a brief and then continue to code in the same response, even if the brief feels obvious to you. The user's confirmation is the gate.
-
-**Choose the brief shape based on how clear the answers are:**
-
-- **Compact form (3-5 bullets)** when discovery was crisp and the original prompt + PRODUCT.md already pinned scope, content, and direction. State what you're building, the visual lane, and end with one or two specific questions or a clear "confirm or override?" prompt. This is the default for typical craft requests with a clear prompt.
-- **Full structured form (sections below)** when the task is genuinely ambiguous, multi-screen, or when the user asked for shape as a standalone step. Use this when the discipline of structure earns its weight.
-
-Don't pad a clear brief into a long one to look thorough. A 70-line brief restating answers the user just gave is noise, not rigor. Equally, don't skip the confirmation pause to look efficient: the pause is the point.
-
-Present the brief, then **stop and wait for explicit confirmation**. You are not the judge of whether the user already approved. Even when the brief feels obviously right, ask once and wait. The pause is what separates shape from premature implementation.
-
-### Brief Structure
-
-**1. Feature Summary** (2-3 sentences)
-What this is, who it's for, what it needs to accomplish.
-
-**2. Primary User Action**
-The single most important thing a user should do or understand here.
-
-**3. Design Direction**
-Color strategy (Restrained / Committed / Full palette / Drenched) + the theme scene sentence + 2–3 named anchor references. Reference PRODUCT.md and DESIGN.md where they already answer, and note any per-surface overrides.
-
-If you ran the Visual Direction Probe step, name which probe direction won and what changed in the brief because of it.
-
-**4. Scope**
-Fidelity, breadth, interactivity, and time intent from the Scope section of the interview. Task-scoped; these don't persist beyond the brief.
-
-**5. Layout Strategy**
-High-level spatial approach: what gets emphasis, what's secondary, how information flows. Describe the visual hierarchy and rhythm, not specific CSS.
-
-**6. Key States**
-List every state the feature needs: default, empty, loading, error, success, edge cases. For each, note what the user needs to see and feel.
-
-**7. Interaction Model**
-How users interact with this feature. What happens on click, hover, scroll? What feedback do they get? What's the flow from entry to completion?
-
-**8. Content Requirements**
-What copy, labels, empty state messages, error messages, and microcopy are needed. Note any dynamic content and its realistic ranges. For image-led surfaces, also list the required image/media roles and their likely source (project asset, generated raster, semantic SVG/CSS, canvas/WebGL, icon library, or accepted omission).
-
-**9. Recommended References**
-Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., spatial-design.md for complex layouts, motion-design.md for animated features, interaction-design.md for form-heavy features).
-
-**10. Open Questions**
-Anything genuinely unresolved. Don't list "open questions" you've already recommended a default for; assert the default and move on. If you'd write `Recommend: X` next to a question, just decide X.
-
----
-
-STOP and call the AskUserQuestion tool to clarify. Ask for explicit confirmation of the brief before finishing.
-
-If the user disagrees with any part, revisit the relevant discovery questions. A shape run is incomplete until the user confirms direction.
-
-Once confirmed, the brief is complete. The user can now hand it to /impeccable, or use it to guide any other implementation approach. (If the user wants the full discovery-then-build flow in one step, they should use /impeccable craft instead, which runs this command internally.)
@@ -1,100 +0,0 @@
-# Spatial Design
-
-## Spacing Systems
-
-### Use 4pt Base, Not 8pt
-
-8pt systems are too coarse; you'll frequently need 12px (between 8 and 16). Use 4pt for granularity: 4, 8, 12, 16, 24, 32, 48, 64, 96px.
-
-### Name Tokens Semantically
-
-Name by relationship (`--space-sm`, `--space-lg`), not value (`--spacing-8`). Use `gap` instead of margins for sibling spacing; it eliminates margin collapse and cleanup hacks.
-
-## Grid Systems
-
-### The Self-Adjusting Grid
-
-Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Columns are at least 280px, as many as fit per row, leftovers stretch. For complex layouts, use named grid areas (`grid-template-areas`) and redefine them at breakpoints.
-
-## Visual Hierarchy
-
-### The Squint Test
-
-Blur your eyes (or screenshot and blur). Can you still identify:
-- The most important element?
-- The second most important?
-- Clear groupings?
-
-If everything looks the same weight blurred, you have a hierarchy problem.
-
-### Hierarchy Through Multiple Dimensions
-
-Don't rely on size alone. Combine:
-
-| Tool | Strong Hierarchy | Weak Hierarchy |
-|------|------------------|----------------|
-| **Size** | 3:1 ratio or more | <2:1 ratio |
-| **Weight** | Bold vs Regular | Medium vs Regular |
-| **Color** | High contrast | Similar tones |
-| **Position** | Top/left (primary) | Bottom/right |
-| **Space** | Surrounded by white space | Crowded |
-
-**The best hierarchy uses 2-3 dimensions at once**: A heading that's larger, bolder, AND has more space above it.
-
-### Cards Are Not Required
-
-Cards are overused. Spacing and alignment create visual grouping naturally. Use cards only when content is truly distinct and actionable, items need visual comparison in a grid, or content needs clear interaction boundaries. **Never nest cards inside cards.** Use spacing, typography, and subtle dividers for hierarchy within a card.
-
-## Container Queries
-
-Viewport queries are for page layouts. **Container queries are for components**:
-
-```css
-.card-container {
- container-type: inline-size;
-}
-
-.card {
- display: grid;
- gap: var(--space-md);
-}
-
-/* Card layout changes based on its container, not viewport */
-@container (min-width: 400px) {
- .card {
- grid-template-columns: 120px 1fr;
- }
-}
-```
-
-**Why this matters**: A card in a narrow sidebar stays compact, while the same card in a main content area expands automatically, without viewport hacks.
-
-## Optical Adjustments
-
-Text at `margin-left: 0` looks indented due to letterform whitespace; use negative margin (`-0.05em`) to optically align. Geometrically centered icons often look off-center; play icons need to shift right, arrows shift toward their direction.
-
-### Touch Targets vs Visual Size
-
-Buttons can look small but need large touch targets (44px minimum). Use padding or pseudo-elements:
-
-```css
-.icon-button {
- width: 24px; /* Visual size */
- height: 24px;
- position: relative;
-}
-
-.icon-button::before {
- content: '';
- position: absolute;
- inset: -10px; /* Expand tap target to 44px */
-}
-```
-
-## Depth & Elevation
-
-Create semantic z-index scales (dropdown → sticky → modal-backdrop → modal → toast → tooltip) instead of arbitrary numbers. For shadows, create a consistent elevation scale (sm → md → lg → xl). **Key insight**: Shadows should be subtle. If you can clearly see it, it's probably too strong.
-
----
-
-**Avoid**: Arbitrary spacing values outside your scale. Making all spacing equal (variety creates hierarchy). Creating hierarchy through size alone - combine size, weight, color, and space.
@@ -1,156 +0,0 @@
-# Teach Flow
-
-Gathers design context for a project and writes two complementary files at the project root:
-
-- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
-- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
-
-Every other impeccable command reads these files before doing any work.
-
-## Step 1: Load current state
-
-Run the shared loader first so you know what already exists:
-
-```bash
-node .claude/skills/impeccable/scripts/load-context.mjs
-```
-
-The output tells you whether PRODUCT.md and/or DESIGN.md already exist. If `migrated: true`, legacy `.impeccable.md` was auto-renamed to `PRODUCT.md`. Mention this once to the user.
-
-Decision tree:
-- **Neither file exists (empty project or no context yet)**: do Steps 2-4 (write PRODUCT.md), then decide on DESIGN.md based on whether there's code to analyze.
-- **PRODUCT.md exists, DESIGN.md missing**: skip to Step 5 and offer to run `/impeccable document` for DESIGN.md.
-- **PRODUCT.md exists but has no `## Register` section (legacy)**: add it. Infer a hypothesis from the codebase (see Step 2), confirm with the user, write the field.
-- **Both exist**: STOP and call the AskUserQuestion tool to clarify. Ask which file to refresh. Skip the one the user doesn't want changed.
-- **Just DESIGN.md exists (unusual)**: do Steps 2-4 to produce PRODUCT.md.
-
-Never silently overwrite an existing file. Always confirm first.
-
-If teach was invoked as a setup blocker by another command, such as `/impeccable craft landing page`, pause that command here. Complete teach, re-run the loader, then resume the original command with the freshly loaded context. For craft, resume into shape next; teach creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
-
-## Step 2: Explore the codebase
-
-Before asking questions, thoroughly scan the project to discover what you can:
-
-- **README and docs**: Project purpose, target audience, any stated goals
-- **Package.json / config files**: Tech stack, dependencies, existing design libraries
-- **Existing components**: Current design patterns, spacing, typography in use
-- **Brand assets**: Logos, favicons, color values already defined
-- **Design tokens / CSS variables**: Existing color palettes, font stacks, spacing scales
-- **Any style guides or brand documentation**
-
-Also form a **register hypothesis** from what you find:
-
-- Brand signals: `/`, `/about`, `/pricing`, `/blog/*`, `/docs/*`, hero sections, big typography, scroll-driven sections, landing-page-shaped content.
-- Product signals: `/app/*`, `/dashboard`, `/settings`, `/(auth)`, forms, data tables, side/top nav, app-shell components.
-
-Register is a hypothesis at this point, not a decision; Step 3 confirms it.
-
-Note what you've learned and what remains unclear. This exploration feeds both PRODUCT.md and DESIGN.md.
-
-## Step 3: Ask strategic questions (for PRODUCT.md)
-
-STOP and call the AskUserQuestion tool to clarify. Ask only about what you couldn't infer from the codebase.
-
-### Interview mode, not confirmation mode
-
-If the repo is empty or the user's brief is sparse, run a short interview before proposing PRODUCT.md. Do **not** turn a one-sentence request into a complete inferred PRODUCT.md and ask for blanket confirmation.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Use inferred answers as hypotheses or options, not as finished facts.
-- Complete at least one real user-answer round before drafting PRODUCT.md, unless every required answer is directly discoverable from repo docs.
-- Round 1 should establish register, users/purpose, and desired outcome.
-- Round 2 should establish brand personality or references, anti-references, and accessibility needs.
-
-### Minimum viable interview
-
-Ask enough to complete PRODUCT.md. At minimum, cover register confirmation, users and purpose, brand personality, anti-references, and accessibility needs unless each answer is directly discoverable from repo context. After at least one interview round, you may propose inferred answers, but the user must confirm them before you write PRODUCT.md. Never synthesize PRODUCT.md from the original task prompt alone.
-
-### Register (ask first; it shapes everything below)
-
-Every design task is either **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboards, tools: design SERVES the product).
-
-If Step 2 produced a clear hypothesis, lead with it: *"From the codebase, this looks like a [brand / product] surface. Does that match your intent, or should we treat it differently?"*
-
-If the signal is genuinely split (e.g. a product with a big marketing landing), STOP and call the AskUserQuestion tool to clarify. Ask which register describes the **primary** surface. The register can be overridden per task later, but PRODUCT.md carries one default.
-
-### Users & Purpose
-- Who uses this? What's their context when using it?
-- What job are they trying to get done?
-- For brand: what emotions should the interface evoke? (confidence, delight, calm, urgency)
-- For product: what workflow are they in? What's the primary task on any given screen?
-
-### Brand & Personality
-- How would you describe the brand personality in 3 words?
-- Reference sites or apps that capture the right feel? What specifically about them?
- - For brand, push for real-world references in the right lane (tech-minimal, editorial-magazine, consumer-warm, brutalist-grid, etc.), not generic "modern" adjectives.
- - For product, push for category best-tool references (Linear, Figma, Notion, Raycast, Stripe).
-- What should this explicitly NOT look like? Any anti-references?
-
-### Accessibility & Inclusion
-- Specific accessibility requirements? (WCAG level, known user needs)
-- Considerations for reduced motion, color blindness, or other accommodations?
-
-Skip questions where the answer is already clear. **Do NOT ask about colors, fonts, radii, or visual styling here.** Those belong in DESIGN.md, not PRODUCT.md.
-
-## Step 4: Write PRODUCT.md
-
-Write PRODUCT.md only after the user has confirmed the strategic answers from Step 3. If an inferred answer is uncertain or unconfirmed, ask before writing.
-
-Synthesize into a strategic document:
-
-```markdown
-# Product
-
-## Register
-
-product
-
-## Users
-[Who they are, their context, the job to be done]
-
-## Product Purpose
-[What this product does, why it exists, what success looks like]
-
-## Brand Personality
-[Voice, tone, 3-word personality, emotional goals]
-
-## Anti-references
-[What this should NOT look like. Specific bad-example sites or patterns to avoid.]
-
-## Design Principles
-[3-5 strategic principles derived from the conversation. Principles like "practice what you preach", "show, don't tell", "expert confidence". NOT visual rules like "use OKLCH" or "magenta accent".]
-
-## Accessibility & Inclusion
-[WCAG level, known user needs, considerations]
-```
-
-Register is either `brand` or `product` as a bare value. No prose, no commentary.
-
-Write to `PROJECT_ROOT/PRODUCT.md`. If `.impeccable.md` existed, the loader already renamed it; merge into that content rather than starting from scratch.
-
-## Step 5: Decide on DESIGN.md
-
-Offer `/impeccable document` either way. Two paths:
-
-- **Code exists** (CSS tokens, components, a running site): "I can generate a DESIGN.md that captures your visual system (colors, typography, components) so variants stay on-brand. Want to do that now?"
-- **Pre-implementation** (empty project): "I can seed a starter DESIGN.md from five quick questions about color strategy, type direction, motion energy, and references. You can re-run once there's code, to capture the real tokens. Want to do that now?"
-
-If the user agrees, delegate to `/impeccable document` (it auto-detects scan vs seed). Load its reference and follow that flow.
-
-If the user prefers to skip, mention they can run `/impeccable document` any time later.
-
-## Step 6: Confirm and wrap up
-
-Summarize:
-- Register captured (brand / product)
-- What was written (PRODUCT.md, DESIGN.md, or both)
-- The 3-5 strategic principles from PRODUCT.md that will guide future work
-- If DESIGN.md is pending, remind the user how to generate it later
-
-**Critical: re-run the loader to refresh session context.** After writing PRODUCT.md, run `node .claude/skills/impeccable/scripts/load-context.mjs` one final time and let its full JSON output land in conversation. This ensures subsequent commands in this session use the freshly-written PRODUCT.md, not a stale earlier version.
-
-If teach was invoked as a blocker by another impeccable command (e.g. the user ran `/impeccable polish` with no PRODUCT.md), resume that original task now with the fresh context.
-
-Optionally STOP and call the AskUserQuestion tool to clarify. Ask whether they'd like a brief summary of PRODUCT.md appended to CLAUDE.md for easier agent reference. If yes, append a short **Design Context** pointer section there.
@@ -1,124 +0,0 @@
-Typography carries most of the information on the page. Replace generic defaults (Inter, Roboto, system fallback at flat scale) with type that reflects the brand and scales with intentional contrast.
-
----
-
-## Register
-
-Brand: run the font selection procedure in [brand.md](brand.md). Pairing follows the brand's lane (display serif + sans body for editorial/luxury, one committed sans for tech, etc.). Fluid `clamp()` scale, ≥1.25 ratio between steps.
-
-Product: system fonts and familiar sans stacks are legitimate here. One well-tuned family typically carries the whole UI. Fixed `rem` scale, 1.125–1.2 ratio between more closely-spaced steps.
-
----
-
-## Assess Current Typography
-
-Analyze what's weak or generic about the current type:
-
-1. **Font choices**:
- - Are we using invisible defaults? (Inter, Roboto, Arial, Open Sans, system defaults)
- - Does the font match the brand personality? (A playful brand shouldn't use a corporate typeface)
- - Are there too many font families? (More than 2-3 is almost always a mess)
-
-2. **Hierarchy**:
- - Can you tell headings from body from captions at a glance?
- - Are font sizes too close together? (14px, 15px, 16px = muddy hierarchy)
- - Are weight contrasts strong enough? (Medium vs Regular is barely visible)
-
-3. **Sizing & scale**:
- - Is there a consistent type scale, or are sizes arbitrary?
- - Does body text meet minimum readability? (16px+)
- - Is the sizing strategy appropriate for the context? (Fixed `rem` scales for app UIs; fluid `clamp()` for marketing/content page headings)
-
-4. **Readability**:
- - Are line lengths comfortable? (45-75 characters ideal)
- - Is line-height appropriate for the font and context?
- - Is there enough contrast between text and background?
-
-5. **Consistency**:
- - Are the same elements styled the same way throughout?
- - Are font weights used consistently? (Not bold in one section, semibold in another for the same role)
- - Is letter-spacing intentional or default everywhere?
-
-**CRITICAL**: The goal isn't to make text "fancier." It's to make it clearer, more readable, and more intentional. Good typography is invisible; bad typography is distracting.
-
-## Plan Typography Improvements
-
-Consult the [typography reference](typography.md) for detailed guidance on scales, pairing, and loading strategies.
-
-Create a systematic plan:
-
-- **Font selection**: Do fonts need replacing? What fits the brand/context?
-- **Type scale**: Establish a modular scale (e.g., 1.25 ratio) with clear hierarchy
-- **Weight strategy**: Which weights serve which roles? (Regular for body, Semibold for labels, Bold for headings, or whatever fits)
-- **Spacing**: Line-heights, letter-spacing, and margins between typographic elements
-
-## Improve Typography Systematically
-
-### Font Selection
-
-If fonts need replacing:
-- Choose fonts that reflect the brand personality
-- Pair with genuine contrast (serif + sans, geometric + humanist), or use a single family in multiple weights
-- Ensure web font loading doesn't cause layout shift (`font-display: swap`, metric-matched fallbacks)
-
-### Establish Hierarchy
-
-Build a clear type scale:
-- **5 sizes cover most needs**: caption, secondary, body, subheading, heading
-- **Use a consistent ratio** between levels (1.25, 1.333, or 1.5)
-- **Combine dimensions**: Size + weight + color + space for strong hierarchy. Don't rely on size alone
-- **App UIs**: Use a fixed `rem`-based type scale, optionally adjusted at 1-2 breakpoints. Fluid sizing undermines the spatial predictability that dense, container-based layouts need
-- **Marketing / content pages**: Use fluid sizing via `clamp(min, preferred, max)` for headings and display text. Keep body text fixed
-
-### Fix Readability
-
-- Set `max-width` on text containers using `ch` units (`max-width: 65ch`)
-- Adjust line-height per context: tighter for headings (1.1-1.2), looser for body (1.5-1.7)
-- Increase line-height slightly for light-on-dark text
-- Ensure body text is at least 16px / 1rem
-
-### Refine Details
-
-- Use `tabular-nums` for data tables and numbers that should align
-- Apply proper `letter-spacing`: slightly open for small caps and uppercase, default or tight for large display text
-- Use semantic token names (`--text-body`, `--text-heading`), not value names (`--font-16`)
-- Set `font-kerning: normal` and consider OpenType features where appropriate
-
-### Weight Consistency
-
-- Define clear roles for each weight and stick to them
-- Don't use more than 3-4 weights (Regular, Medium, Semibold, Bold is plenty)
-- Load only the weights you actually use (each weight adds to page load)
-
-**NEVER**:
-- Use more than 2-3 font families
-- Pick sizes arbitrarily; commit to a scale
-- Set body text below 16px
-- Use decorative/display fonts for body text
-- Disable browser zoom (`user-scalable=no`)
-- Use `px` for font sizes; use `rem` to respect user settings
-- Default to Inter/Roboto/Open Sans when personality matters
-- Pair fonts that are similar but not identical (two geometric sans-serifs)
-
-## Verify Typography Improvements
-
-- **Hierarchy**: Can you identify heading vs body vs caption instantly?
-- **Readability**: Is body text comfortable to read in long passages?
-- **Consistency**: Are same-role elements styled identically throughout?
-- **Personality**: Does the typography reflect the brand?
-- **Performance**: Are web fonts loading efficiently without layout shift?
-- **Accessibility**: Does text meet WCAG contrast ratios? Is it zoomable to 200%?
-
-When the type carries the hierarchy on its own, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `scale` param controlling the hierarchy ratio. Express all font sizes in the variant's scoped CSS through `calc(var(--p-scale, 1) * <base>)` or, better, scale the type ramp via `clamp(min, calc(var(--p-scale, 1) * Npx), max)`. Users slide from subdued to commanding.
-
-```json
-{"id":"scale","kind":"range","min":0.85,"max":1.3,"step":0.05,"default":1,"label":"Scale"}
-```
-
-Where the variant riffs on a specific pairing, expose the pairing choice as a `steps` param (e.g. "serif display + sans body" vs. "mono display + sans body" vs. "all-sans"). Each branch routes through `:scope[data-p-pairing="X"]` selectors in scoped CSS.
-
-See `reference/live.md` for the full params contract.
@@ -1,159 +0,0 @@
-# Typography
-
-## Classic Typography Principles
-
-### Vertical Rhythm
-
-Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
-
-### Modular Scale & Hierarchy
-
-The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
-
-**Use fewer sizes with more contrast.** A 5-size system covers most needs:
-
-| Role | Typical Ratio | Use Case |
-|------|---------------|----------|
-| xs | 0.75rem | Captions, legal |
-| sm | 0.875rem | Secondary UI, metadata |
-| base | 1rem | Body text |
-| lg | 1.25-1.5rem | Subheadings, lead text |
-| xl+ | 2-4rem | Headlines, hero text |
-
-Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
-
-### Readability & Measure
-
-Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
-
-**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
-
-**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
-
-## Font Selection & Pairing
-
-The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
-
-### Anti-reflexes worth defending against
-
-- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
-- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
-- A children's product does NOT need a rounded display font. Kids' books use real type.
-- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
-
-**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
-
-### Pairing Principles
-
-**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
-
-When pairing, contrast on multiple axes:
-- Serif + Sans (structure contrast)
-- Geometric + Humanist (personality contrast)
-- Condensed display + Wide body (proportion contrast)
-
-**Never pair fonts that are similar but not identical** (e.g., two geometric sans-serifs). They create visual tension without clear hierarchy.
-
-### Web Font Loading
-
-The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
-
-```css
-/* 1. Use font-display: swap for visibility */
-@font-face {
- font-family: 'CustomFont';
- src: url('font.woff2') format('woff2');
- font-display: swap;
-}
-
-/* 2. Match fallback metrics to minimize shift */
-@font-face {
- font-family: 'CustomFont-Fallback';
- src: local('Arial');
- size-adjust: 105%; /* Scale to match x-height */
- ascent-override: 90%; /* Match ascender height */
- descent-override: 20%; /* Match descender depth */
- line-gap-override: 10%; /* Match line spacing */
-}
-
-body {
- font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
-}
-```
-
-Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
-
-**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
-
-**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
-
-**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
-
-## Modern Web Typography
-
-### Fluid Type
-
-Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
-
-**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
-
-**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
-
-**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
-
-**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
-
-### OpenType Features
-
-Most developers don't know these exist. Use them for polish:
-
-```css
-/* Tabular numbers for data alignment */
-.data-table { font-variant-numeric: tabular-nums; }
-
-/* Proper fractions */
-.recipe-amount { font-variant-numeric: diagonal-fractions; }
-
-/* Small caps for abbreviations */
-abbr { font-variant-caps: all-small-caps; }
-
-/* Disable ligatures in code */
-code { font-variant-ligatures: none; }
-
-/* Enable kerning (usually on by default, but be explicit) */
-body { font-kerning: normal; }
-```
-
-Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
-
-### Rendering polish
-
-```css
-/* Even out heading line lengths (browser picks better break points) */
-h1, h2, h3 { text-wrap: balance; }
-
-/* Reduce orphans and ragged endings in long prose */
-article p { text-wrap: pretty; }
-
-/* Variable fonts: pick the right optical-size master automatically */
-body { font-optical-sizing: auto; }
-```
-
-**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
-
-## Typography System Architecture
-
-Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
-
-## Accessibility Considerations
-
-Beyond contrast ratios (which are well-documented), consider:
-
-- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
-- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
-- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
-- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
-
----
-
-**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
@@ -1,107 +0,0 @@
-# UX Writing
-
-## The Button Label Problem
-
-**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
-
-| Bad | Good | Why |
-|-----|------|-----|
-| OK | Save changes | Says what will happen |
-| Submit | Create account | Outcome-focused |
-| Yes | Delete message | Confirms the action |
-| Cancel | Keep editing | Clarifies what "cancel" means |
-| Click here | Download PDF | Describes the destination |
-
-**For destructive actions**, name the destruction:
-- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
-- "Delete 5 items" not "Delete selected" (show the count)
-
-## Error Messages: The Formula
-
-Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
-
-### Error Message Templates
-
-| Situation | Template |
-|-----------|----------|
-| **Format error** | "[Field] needs to be [format]. Example: [example]" |
-| **Missing required** | "Please enter [what's missing]" |
-| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
-| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
-| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
-
-### Don't Blame the User
-
-Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
-
-## Empty States Are Opportunities
-
-Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
-
-## Voice vs Tone
-
-**Voice** is your brand's personality, consistent everywhere.
-**Tone** adapts to the moment.
-
-| Moment | Tone Shift |
-|--------|------------|
-| Success | Celebratory, brief: "Done! Your changes are live." |
-| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
-| Loading | Reassuring: "Saving your work..." |
-| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
-
-**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
-
-## Writing for Accessibility
-
-**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
-
-## Writing for Translation
-
-### Plan for Expansion
-
-German text is ~30% longer than English. Allocate space:
-
-| Language | Expansion |
-|----------|-----------|
-| German | +30% |
-| French | +20% |
-| Finnish | +30-40% |
-| Chinese | -30% (fewer chars, but same width) |
-
-### Translation-Friendly Patterns
-
-Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
-
-## Consistency: The Terminology Problem
-
-Pick one term and stick with it:
-
-| Inconsistent | Consistent |
-|--------------|------------|
-| Delete / Remove / Trash | Delete |
-| Settings / Preferences / Options | Settings |
-| Sign in / Log in / Enter | Sign in |
-| Create / Add / New | Create |
-
-Build a terminology glossary and enforce it. Variety creates confusion.
-
-## Avoid Redundant Copy
-
-If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
-
-## Loading States
-
-Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
-
-## Confirmation Dialogs: Use Sparingly
-
-Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
-
-## Form Instructions
-
-Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
-
----
-
-**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
@@ -1,284 +0,0 @@
-#!/usr/bin/env node
-/**
- * Cleans up deprecated Impeccable skill files, symlinks, and
- * skills-lock.json entries left over from previous versions.
- *
- * Safe to run repeatedly -- it is a no-op when nothing needs cleaning.
- *
- * Usage (from the project root):
- * node {{scripts_path}}/cleanup-deprecated.mjs
- *
- * What it does:
- * 1. Finds every harness-specific skills directory (.claude/skills,
- * .cursor/skills, .agents/skills, etc.).
- * 2. For each deprecated skill name (with and without i- prefix),
- * checks if the directory exists and its SKILL.md mentions
- * "impeccable" (to avoid deleting unrelated user skills).
- * 3. Deletes confirmed matches (files, directories, or symlinks).
- * 4. Removes the corresponding entries from skills-lock.json.
- */
-
-import { existsSync, readFileSync, writeFileSync, rmSync, readdirSync, statSync, lstatSync, unlinkSync } from 'node:fs';
-import { join, resolve } from 'node:path';
-
-// Skills that were renamed, merged, or folded in v2.0, v2.1, and v3.0.
-const DEPRECATED_NAMES = [
- // v2.0 renames
- 'frontend-design', // renamed to impeccable
- 'teach-impeccable', // folded into /impeccable teach
- // v2.1 merges
- 'arrange', // renamed to layout
- 'normalize', // merged into polish
- 'onboard', // merged into harden
- 'extract', // merged into /impeccable extract
- // v3.0 consolidation: all standalone skills -> /impeccable sub-commands
- 'adapt',
- 'animate',
- 'audit',
- 'bolder',
- 'clarify',
- 'colorize',
- 'critique',
- 'delight',
- 'distill',
- 'harden',
- 'layout',
- 'optimize',
- 'overdrive',
- 'polish',
- 'quieter',
- 'shape',
- 'typeset',
-];
-
-// All known harness directories that may contain a skills/ subfolder.
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Per-skill fingerprints for SKILL.md bodies that never mentioned
-// "impeccable" in their v2.x source. Used as a last-resort match
-// when no skills-lock.json exists and the word heuristic fails.
-// The strings are lifted verbatim from the v2.x frontmatter
-// descriptions, so collisions with hand-written user skills are
-// vanishingly unlikely.
-const SKILL_FINGERPRINTS = {
- harden: 'Make interfaces production-ready: error handling, empty states',
- optimize: 'Diagnoses and fixes UI performance across loading speed',
-};
-
-/**
- * Walk up from startDir until we find a directory that looks like a
- * project root (has package.json, .git, or skills-lock.json).
- */
-export function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- const { root } = { root: '/' };
- while (dir !== root) {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Load skills-lock.json from the project root, or null if missing/unreadable.
- */
-export function loadLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return null;
- try {
- return JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return null;
- }
-}
-
-/**
- * Check whether a skill directory belongs to Impeccable. Three layered
- * signals, in order of reliability:
- * 1. Lock source equals "pbakaus/impeccable" (authoritative).
- * 2. SKILL.md body contains the word "impeccable".
- * 3. SKILL.md body contains a per-skill fingerprint (for harden and
- * optimize, whose v2.x SKILL.md never mentioned the pack name).
- */
-export function isImpeccableSkill(skillDir, { skillName, lock } = {}) {
- // 1. Authoritative: the lock file claims this skill is ours.
- if (skillName && lock?.skills?.[skillName]?.source === 'pbakaus/impeccable') {
- return true;
- }
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) return false;
- let content;
- try {
- content = readFileSync(skillMd, 'utf-8');
- } catch {
- return false;
- }
- // 2. Word-level content heuristic.
- if (/impeccable/i.test(content)) return true;
- // 3. Per-skill fingerprint for old skills that never mentioned the pack.
- // Strip the i- prefix so both `harden` and `i-harden` resolve to the
- // same fingerprint entry.
- const unprefixed = skillName?.startsWith('i-') ? skillName.slice(2) : skillName;
- const fingerprint = unprefixed && SKILL_FINGERPRINTS[unprefixed];
- if (fingerprint && content.includes(fingerprint)) return true;
- return false;
-}
-
-/**
- * Build the full list of names to check: each deprecated name, plus
- * its i-prefixed variant.
- */
-export function buildTargetNames() {
- const names = [];
- for (const name of DEPRECATED_NAMES) {
- names.push(name);
- names.push(`i-${name}`);
- }
- return names;
-}
-
-/**
- * Find every skills directory across all harness dirs in the project.
- * Returns absolute paths that exist on disk.
- */
-export function findSkillsDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const candidate = join(projectRoot, harness, 'skills');
- if (existsSync(candidate)) {
- dirs.push(candidate);
- }
- }
- return dirs;
-}
-
-/**
- * Remove deprecated skill directories/symlinks from all harness dirs.
- * Reads skills-lock.json so the authoritative "source" field can
- * drive deletion even when SKILL.md never mentions impeccable.
- * Returns an array of paths that were deleted.
- */
-export function removeDeprecatedSkills(projectRoot, lock) {
- if (lock === undefined) lock = loadLock(projectRoot);
- const targets = buildTargetNames();
- const skillsDirs = findSkillsDirs(projectRoot);
- const deleted = [];
-
- for (const skillsDir of skillsDirs) {
- for (const name of targets) {
- const skillPath = join(skillsDir, name);
-
- // Use lstat to detect symlinks (existsSync follows symlinks and
- // returns false for dangling ones).
- let stat;
- try {
- stat = lstatSync(skillPath);
- } catch {
- continue; // does not exist at all
- }
-
- if (stat.isSymbolicLink()) {
- // Symlink: check the target if it's alive, otherwise treat
- // dangling symlinks to deprecated names as safe to remove.
- const targetAlive = existsSync(skillPath);
- const isMatch = targetAlive
- ? isImpeccableSkill(skillPath, { skillName: name, lock })
- : true;
- if (isMatch) {
- unlinkSync(skillPath);
- deleted.push(skillPath);
- }
- continue;
- }
-
- // Regular directory -- verify it belongs to impeccable
- if (isImpeccableSkill(skillPath, { skillName: name, lock })) {
- rmSync(skillPath, { recursive: true, force: true });
- deleted.push(skillPath);
- }
- }
- }
-
- return deleted;
-}
-
-/**
- * Remove deprecated entries from skills-lock.json.
- * Only removes entries whose source is "pbakaus/impeccable".
- * Returns the list of removed skill names.
- */
-export function cleanSkillsLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return [];
-
- let lock;
- try {
- lock = JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return [];
- }
-
- if (!lock.skills || typeof lock.skills !== 'object') return [];
-
- const targets = buildTargetNames();
- const removed = [];
-
- for (const name of targets) {
- const entry = lock.skills[name];
- if (!entry) continue;
- // Only remove if it belongs to impeccable
- if (entry.source === 'pbakaus/impeccable') {
- delete lock.skills[name];
- removed.push(name);
- }
- }
-
- if (removed.length > 0) {
- writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\n', 'utf-8');
- }
-
- return removed;
-}
-
-/**
- * Run the full cleanup. Returns a summary object.
- *
- * Order matters: read the lock and delete directories first, then
- * strip lock entries. Otherwise the authoritative signal is gone by
- * the time directory deletion runs.
- */
-export function cleanup(projectRoot) {
- const root = projectRoot || findProjectRoot();
- const lock = loadLock(root);
- const deletedPaths = removeDeprecatedSkills(root, lock);
- const removedLockEntries = cleanSkillsLock(root);
- return { deletedPaths, removedLockEntries, projectRoot: root };
-}
-
-// CLI entry point
-if (process.argv[1] && resolve(process.argv[1]) === resolve(new URL(import.meta.url).pathname)) {
- const result = cleanup();
- if (result.deletedPaths.length === 0 && result.removedLockEntries.length === 0) {
- console.log('No deprecated Impeccable skills found. Nothing to clean up.');
- } else {
- if (result.deletedPaths.length > 0) {
- console.log(`Removed ${result.deletedPaths.length} deprecated skill(s):`);
- for (const p of result.deletedPaths) console.log(` - ${p}`);
- }
- if (result.removedLockEntries.length > 0) {
- console.log(`Cleaned ${result.removedLockEntries.length} entry/entries from skills-lock.json:`);
- for (const name of result.removedLockEntries) console.log(` - ${name}`);
- }
- }
-}
@@ -1,94 +0,0 @@
-{
- "craft": {
- "description": "Full confirmed-brief-then-build flow. Runs multi-round shape discovery first, resolves visual probe and north-star mock gates when available, then builds and visually iterates. Use when building a new feature end-to-end.",
- "argumentHint": "[feature description]"
- },
- "teach": {
- "description": "Gathers design context for a project. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles) and, when code exists to analyze, DESIGN.md (visual: colors, typography, components). Every other command reads these files before doing work. Use once per project.",
- "argumentHint": ""
- },
- "document": {
- "description": "Generate a DESIGN.md file that captures the current visual design system. Auto-extracts colors, typography, spacing, radii, and component patterns from the codebase, then asks the user to confirm descriptive language for atmosphere and color character. Follows the Google Stitch DESIGN.md format so the file is tool-compatible. Use when you need a visual design spec an AI agent can follow to stay on-brand.",
- "argumentHint": ""
- },
- "extract": {
- "description": "Pull reusable patterns, components, and design tokens into the design system. Identifies repeated patterns and consolidates them. Use when you have drift across the codebase and want to bring things back to a consistent system.",
- "argumentHint": "[target]"
- },
- "live": {
- "description": "Interactive live variant mode. Select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via HMR. Requires a running dev server. Use when you want to visually experiment with design alternatives in real time.",
- "argumentHint": ""
- },
- "adapt": {
- "description": "Adapt designs to work across different screen sizes, devices, contexts, or platforms. Implements breakpoints, fluid layouts, and touch targets. Use when the user mentions responsive design, mobile layouts, breakpoints, viewport adaptation, or cross-device compatibility.",
- "argumentHint": "[target] [context (mobile, tablet, print...)]"
- },
- "animate": {
- "description": "Review a feature and enhance it with purposeful animations, micro-interactions, and motion effects that improve usability and delight. Use when the user mentions adding animation, transitions, micro-interactions, motion design, hover effects, or making the UI feel more alive.",
- "argumentHint": "[target]"
- },
- "audit": {
- "description": "Run technical quality checks across accessibility, performance, theming, responsive design, and anti-patterns. Generates a scored report with P0-P3 severity ratings and actionable plan. Use when the user wants an accessibility check, performance audit, or technical quality review.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "bolder": {
- "description": "Amplify safe or boring designs to make them more visually interesting and stimulating. Increases impact while maintaining usability. Use when the user says the design looks bland, generic, too safe, lacks personality, or wants more visual impact and character.",
- "argumentHint": "[target]"
- },
- "clarify": {
- "description": "Improve unclear UX copy, error messages, microcopy, labels, and instructions to make interfaces easier to understand. Use when the user mentions confusing text, unclear labels, bad error messages, hard-to-follow instructions, or wanting better UX writing.",
- "argumentHint": "[target]"
- },
- "colorize": {
- "description": "Add strategic color to features that are too monochromatic or lack visual interest, making interfaces more engaging and expressive. Use when the user mentions the design looking gray, dull, lacking warmth, needing more color, or wanting a more vibrant or expressive palette.",
- "argumentHint": "[target]"
- },
- "critique": {
- "description": "Evaluate design from a UX perspective, assessing visual hierarchy, information architecture, emotional resonance, cognitive load, and overall quality with quantitative scoring, persona-based testing, automated anti-pattern detection, and actionable feedback. Use when the user asks to review, critique, evaluate, or give feedback on a design or component.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "delight": {
- "description": "Add moments of joy, personality, and unexpected touches that make interfaces memorable and enjoyable to use. Elevates functional to delightful. Use when the user asks to add polish, personality, animations, micro-interactions, delight, or make an interface feel fun or memorable.",
- "argumentHint": "[target]"
- },
- "distill": {
- "description": "Strip designs to their essence by removing unnecessary complexity. Great design is simple, powerful, and clean. Use when the user asks to simplify, declutter, reduce noise, remove elements, or make a UI cleaner and more focused.",
- "argumentHint": "[target]"
- },
- "harden": {
- "description": "Make interfaces production-ready: error handling, i18n, text overflow, edge case management, and resilience under real-world data. Use when the user asks to harden, make production-ready, handle edge cases, add error states, or fix overflow and i18n issues.",
- "argumentHint": "[target]"
- },
- "onboard": {
- "description": "Design onboarding flows, first-run experiences, and empty states that guide new users to value. Covers welcome screens, account setup, progressive disclosure, contextual tooltips, feature announcements, and activation moments. Use when the user mentions onboarding, first-time users, empty states, activation, getting started, new user flows, or the aha moment.",
- "argumentHint": "[target]"
- },
- "layout": {
- "description": "Improve layout, spacing, and visual rhythm. Fixes monotonous grids, inconsistent spacing, and weak visual hierarchy. Use when the user mentions layout feeling off, spacing issues, visual hierarchy, crowded UI, alignment problems, or wanting better composition.",
- "argumentHint": "[target]"
- },
- "optimize": {
- "description": "Diagnoses and fixes UI performance across loading speed, rendering, animations, images, and bundle size. Use when the user mentions slow, laggy, janky, performance, bundle size, load time, or wants a faster, smoother experience.",
- "argumentHint": "[target]"
- },
- "overdrive": {
- "description": "Pushes interfaces past conventional limits with technically ambitious implementations — shaders, spring physics, scroll-driven reveals, 60fps animations. Use when the user wants to wow, impress, go all-out, or make something that feels extraordinary.",
- "argumentHint": "[target]"
- },
- "polish": {
- "description": "Performs a final quality pass fixing alignment, spacing, consistency, and micro-detail issues before shipping. Use when the user mentions polish, finishing touches, pre-launch review, something looks off, or wants to go from good to great.",
- "argumentHint": "[target]"
- },
- "quieter": {
- "description": "Tones down visually aggressive or overstimulating designs, reducing intensity while preserving quality. Use when the user mentions too bold, too loud, overwhelming, aggressive, garish, or wants a calmer, more refined aesthetic.",
- "argumentHint": "[target]"
- },
- "shape": {
- "description": "Plan UX and UI before code. Runs a required multi-round discovery interview, uses visual probes when available, and produces a user-confirmed design brief for implementation.",
- "argumentHint": "[feature to shape]"
- },
- "typeset": {
- "description": "Improves typography by fixing font choices, hierarchy, sizing, weight, and readability so text feels intentional. Use when the user mentions fonts, type, readability, text hierarchy, sizing looks off, or wants more polished, intentional typography.",
- "argumentHint": "[target]"
- }
-}
@@ -1,242 +0,0 @@
-#!/usr/bin/env node
-/**
- * Critique persistence helper.
- *
- * Each run of /impeccable critique writes a per-target snapshot to
- * .impeccable/critique/<timestamp>__<slug>.md
- * with a small YAML frontmatter carrying the score + P0/P1 counts.
- *
- * /impeccable polish reads the latest matching snapshot at start as its
- * fix backlog. No other skill auto-reads critique output.
- *
- * The slug is derived mechanically from the *resolved* primary artifact
- * (file path or URL), never from the user's natural-language phrasing.
- * Slug stability across runs is what lets the trend display work.
- *
- * CLI entry points (called from skill instructions):
- * node critique-storage.mjs slug <resolved-target>
- * node critique-storage.mjs write <slug> <snapshot-body-file>
- * node critique-storage.mjs latest <slug>
- * node critique-storage.mjs trend <slug> [limit]
- *
- * Note: there is intentionally no `ignore` subcommand. ignore.md is a plain
- * markdown file; the model reads it directly with its file-read tool. This
- * helper only exists for operations the model can't trivially do inline
- * (normalizing paths, generating filenames, globbing + parsing frontmatter).
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath, pathToFileURL } from 'node:url';
-import { getCritiqueDir } from './impeccable-paths.mjs';
-
-const SLUG_MAX = 50;
-
-/**
- * Mechanically derive a slug from a resolved target. Returns null if the
- * input doesn't look like a stable identifier (empty, project root, etc).
- *
- * Accepts file paths and URLs. The model resolves "the homepage" to a
- * concrete artifact before calling this — we never slug a natural-language
- * phrase.
- */
-export function slugFromTarget(resolved, { cwd = process.cwd() } = {}) {
- if (!resolved || typeof resolved !== 'string') return null;
- const trimmed = resolved.trim();
- if (!trimmed) return null;
-
- // URL
- if (/^https?:\/\//i.test(trimmed)) {
- let url;
- try { url = new URL(trimmed); } catch { return null; }
- const hostPath = `${url.hostname}${url.pathname}`;
- return kebab(hostPath);
- }
-
- // File path. Make it project-relative so two devs critiquing the same
- // checkout get the same slug regardless of where their repo is cloned.
- const abs = path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- let rel = path.relative(cwd, abs);
- // If the target is outside cwd, fall back to the basename so we still
- // produce a stable slug (vs the absolute path, which would include
- // home dirs / usernames).
- if (rel.startsWith('..') || path.isAbsolute(rel)) {
- rel = path.basename(abs);
- }
- if (!rel || rel === '.' || rel === '') return null;
- return kebab(rel);
-}
-
-function kebab(s) {
- const slug = s
- .toLowerCase()
- .replace(/[/\\.]+/g, '-')
- .replace(/[^a-z0-9-]+/g, '-')
- .replace(/-+/g, '-')
- .replace(/^-|-$/g, '');
- if (!slug) return null;
- // Cap from the tail — the tail (filename) is more identifying than the
- // top-level directory.
- return slug.length <= SLUG_MAX ? slug : slug.slice(slug.length - SLUG_MAX).replace(/^-/, '');
-}
-
-/**
- * Filename-safe UTC ISO timestamp: hyphens for separators, trailing Z.
- * Plain colons aren't allowed on Windows filesystems.
- */
-export function nowFilenameStamp(date = new Date()) {
- const iso = date.toISOString(); // 2026-05-12T18:30:00.123Z
- return iso.replace(/[:.]/g, '-').replace(/-\d+Z$/, 'Z');
-}
-
-/**
- * Write a snapshot for `slug`. `meta` carries the small structured frontmatter
- * keys read back by readTrend(). `body` is the human-readable critique
- * report (everything below the frontmatter).
- *
- * Returns the absolute path written.
- */
-export function writeSnapshot({ slug, meta, body, cwd = process.cwd(), now = new Date() }) {
- if (!slug) throw new Error('writeSnapshot requires a slug');
- const dir = getCritiqueDir(cwd);
- fs.mkdirSync(dir, { recursive: true });
- const timestamp = nowFilenameStamp(now);
- const filePath = path.join(dir, `${timestamp}__${slug}.md`);
- // Spread `meta` first so internally computed `timestamp` and `slug`
- // always win. Otherwise a caller-supplied meta blob (parsed from the
- // IMPECCABLE_CRITIQUE_META env var) could clobber them, leaving the
- // filename in disagreement with its frontmatter and corrupting trends.
- const front = serializeFrontmatter({ ...meta, timestamp, slug });
- fs.writeFileSync(filePath, `${front}\n${body.trim()}\n`, 'utf-8');
- return filePath;
-}
-
-function serializeFrontmatter(obj) {
- const lines = ['---'];
- for (const [key, value] of Object.entries(obj)) {
- if (value === undefined || value === null) continue;
- const str = typeof value === 'string' ? value : String(value);
- // Quote strings that contain : or # to keep parsing simple.
- const needsQuotes = typeof value === 'string' && /[:#]/.test(str);
- lines.push(`${key}: ${needsQuotes ? JSON.stringify(str) : str}`);
- }
- lines.push('---');
- return lines.join('\n');
-}
-
-function parseFrontmatter(text) {
- const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
- if (!match) return {};
- const out = {};
- for (const line of match[1].split(/\r?\n/)) {
- const colon = line.indexOf(':');
- if (colon < 0) continue;
- const key = line.slice(0, colon).trim();
- let value = line.slice(colon + 1).trim();
- if (/^".*"$/.test(value)) {
- try { value = JSON.parse(value); } catch { /* leave as-is */ }
- } else if (/^-?\d+$/.test(value)) {
- value = Number(value);
- }
- out[key] = value;
- }
- return out;
-}
-
-/**
- * Return all snapshot files for `slug`, sorted oldest → newest.
- */
-function listSnapshotsForSlug(slug, cwd) {
- const dir = getCritiqueDir(cwd);
- if (!fs.existsSync(dir)) return [];
- const suffix = `__${slug}.md`;
- return fs.readdirSync(dir)
- .filter((f) => f.endsWith(suffix))
- .sort()
- .map((f) => path.join(dir, f));
-}
-
-/**
- * Return the most recent snapshot for `slug`, or null. Polish reads this
- * to find its fix backlog when the slug matches.
- */
-export function readLatestSnapshot(slug, { cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- if (!all.length) return null;
- const latest = all[all.length - 1];
- const body = fs.readFileSync(latest, 'utf-8');
- return { path: latest, body, meta: parseFrontmatter(body) };
-}
-
-/**
- * Return the last `limit` snapshots' frontmatter, oldest → newest.
- * Critique appends a one-line trend to its output using this.
- */
-export function readTrend(slug, { limit = 5, cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- const slice = all.slice(-limit);
- return slice.map((file) => parseFrontmatter(fs.readFileSync(file, 'utf-8')));
-}
-
-// ---- CLI ---------------------------------------------------------------
-
-function main(argv) {
- const [cmd, ...args] = argv;
- switch (cmd) {
- case 'slug': {
- const slug = slugFromTarget(args[0]);
- if (!slug) { process.stderr.write('no stable slug for input\n'); process.exit(1); }
- process.stdout.write(`${slug}\n`);
- return;
- }
- case 'write': {
- const [slug, bodyFile] = args;
- if (!slug || !bodyFile) { process.stderr.write('usage: write <slug> <body-file>\n'); process.exit(1); }
- const raw = fs.readFileSync(bodyFile, 'utf-8');
- // The body file may be a full report. The caller passes the meta as
- // a JSON object on stdin if it wants structured frontmatter; otherwise
- // we write with minimal metadata.
- let meta = {};
- const metaArg = process.env.IMPECCABLE_CRITIQUE_META;
- if (metaArg) {
- try { meta = JSON.parse(metaArg); } catch { /* ignore */ }
- }
- const out = writeSnapshot({ slug, meta, body: raw });
- process.stdout.write(`${out}\n`);
- return;
- }
- case 'latest': {
- const latest = readLatestSnapshot(args[0]);
- if (!latest) { process.exit(2); }
- process.stdout.write(latest.body);
- return;
- }
- case 'trend': {
- const rows = readTrend(args[0], { limit: args[1] ? Number(args[1]) : 5 });
- process.stdout.write(JSON.stringify(rows, null, 2) + '\n');
- return;
- }
- default:
- process.stderr.write('usage: critique-storage.mjs <slug|write|latest|trend> [args]\n');
- process.exit(1);
- }
-}
-
-function isMainModule() {
- if (!process.argv[1]) return false;
- try {
- return fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1]);
- } catch {
- // pathToFileURL normalizes Windows paths; keep it as a fallback for any
- // environment where realpath is unavailable.
- return import.meta.url === pathToFileURL(process.argv[1]).href;
- }
-}
-
-// Why the realpath check: generated skills are often reached through symlinked
-// harness directories (for example a demo repo's `.agents` -> source `.agents`).
-// Node resolves import.meta.url to the real file, while process.argv[1] keeps
-// the symlink path. Comparing canonical paths prevents a silent exit-0 no-op.
-if (isMainModule()) {
- main(process.argv.slice(2));
-}
@@ -1,820 +0,0 @@
-// Parse a DESIGN.md (Stitch-spec format) into a structured JSON model that
-// the live-mode design-system panel can render. Deterministic, dependency-free.
-//
-// Two-layer: YAML frontmatter (machine-readable tokens) + markdown body
-// (prose with six canonical H2 sections). When frontmatter is present, it's
-// exposed on `model.frontmatter` alongside the prose-scraped sections;
-// consumers can prefer frontmatter values and fall back to prose.
-
-const CANONICAL_SECTIONS = [
- 'Overview',
- 'Colors',
- 'Typography',
- 'Elevation',
- 'Components',
- "Do's and Don'ts",
-];
-
-// ---------- Frontmatter (Stitch YAML subset) ----------
-
-function parseFrontmatter(md) {
- const lines = md.split(/\r?\n/);
- if (lines[0]?.trim() !== '---') return { frontmatter: null, body: md };
-
- let end = -1;
- for (let i = 1; i < lines.length; i++) {
- if (lines[i].trim() === '---') { end = i; break; }
- }
- if (end === -1) return { frontmatter: null, body: md };
-
- const yaml = lines.slice(1, end).join('\n');
- const body = lines.slice(end + 1).join('\n');
- try {
- return { frontmatter: parseYamlSubset(yaml), body };
- } catch {
- return { frontmatter: null, body: md };
- }
-}
-
-// Minimal YAML reader for the Stitch frontmatter subset: scalar maps with
-// one level of nested objects (typography roles, components). Indent-based,
-// 2-space convention. No arrays, no anchors, no multi-line scalars — Stitch's
-// schema doesn't need them and accepting them would require a real YAML
-// dependency we don't want to vendor.
-function parseYamlSubset(yaml) {
- const lines = yaml.split(/\r?\n/);
- const root = {};
- const stack = [{ indent: -1, obj: root }];
-
- for (const raw of lines) {
- // Skip blanks and line-only comments. Don't strip inline comments:
- // unquoted hex values start with `#` and can't be safely distinguished
- // from a comment after whitespace.
- if (!raw.trim() || /^\s*#/.test(raw)) continue;
-
- const indent = raw.match(/^\s*/)[0].length;
- const content = raw.slice(indent);
-
- const colonIdx = findTopLevelColon(content);
- if (colonIdx === -1) continue;
-
- while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
- stack.pop();
- }
-
- const key = content.slice(0, colonIdx).trim();
- const rest = content.slice(colonIdx + 1).trim();
- const parent = stack[stack.length - 1].obj;
-
- if (rest === '') {
- const obj = {};
- parent[key] = obj;
- stack.push({ indent, obj });
- } else {
- parent[key] = parseScalar(rest);
- }
- }
-
- return root;
-}
-
-function findTopLevelColon(s) {
- let inQuote = null;
- for (let i = 0; i < s.length; i++) {
- const ch = s[i];
- if (inQuote) {
- if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
- } else if (ch === '"' || ch === "'") {
- inQuote = ch;
- } else if (ch === ':') {
- return i;
- }
- }
- return -1;
-}
-
-function parseScalar(raw) {
- const s = raw.trim();
- if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
- return s.slice(1, -1);
- }
- if (s === 'true') return true;
- if (s === 'false') return false;
- if (s === 'null' || s === '~') return null;
- if (/^-?\d+$/.test(s)) return Number(s);
- if (/^-?\d*\.\d+$/.test(s)) return Number(s);
- return s;
-}
-
-const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
-const OKLCH_RE = /oklch\([^)]+\)/gi;
-const RGBA_RE = /rgba?\([^)]+\)/gi;
-const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
-const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
-
-// ---------- Section splitting ----------
-
-function splitSections(md) {
- const lines = md.split(/\r?\n/);
- let title = null;
- const sections = {};
- let current = null;
-
- for (const raw of lines) {
- const line = raw.trimEnd();
-
- if (!title && line.startsWith('# ') && !line.startsWith('## ')) {
- title = line.replace(/^#\s+/, '').trim();
- continue;
- }
-
- const h2 = line.match(/^##\s+(?:\d+\.\s*)?([^:\n]+?)(?::\s*(.+))?$/);
- if (h2) {
- const rawName = normalizeApostrophes(h2[1].trim());
- const subtitle = h2[2] ? h2[2].trim() : null;
- const canonical = matchCanonicalSection(rawName);
- if (canonical) {
- current = { name: canonical, subtitle, lines: [] };
- sections[canonical] = current;
- continue;
- }
- // non-canonical H2 — ignore but stop feeding into current
- current = null;
- continue;
- }
-
- if (current) current.lines.push(raw);
- }
-
- return { title, sections };
-}
-
-function normalizeApostrophes(s) {
- return s.replace(/[\u2018\u2019]/g, "'");
-}
-
-function matchCanonicalSection(name) {
- const normalized = normalizeApostrophes(name).toLowerCase();
- // Exact match first
- for (const c of CANONICAL_SECTIONS) {
- if (normalizeApostrophes(c).toLowerCase() === normalized) return c;
- }
- // Keyword-contained match: "Overview & Creative North Star" -> "Overview",
- // "Elevation & Depth" -> "Elevation", etc.
- for (const c of CANONICAL_SECTIONS) {
- const key = normalizeApostrophes(c).toLowerCase();
- const pattern = new RegExp(`\\b${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
- if (pattern.test(normalized)) return c;
- }
- return null;
-}
-
-// ---------- Subsection splitting (inside a canonical section) ----------
-
-function splitSubsections(lines) {
- const subs = [];
- let current = { name: null, lines: [] };
- subs.push(current);
-
- for (const raw of lines) {
- const h3 = raw.match(/^###\s+(.+?)\s*$/);
- if (h3) {
- current = { name: h3[1].trim(), lines: [] };
- subs.push(current);
- continue;
- }
- current.lines.push(raw);
- }
-
- return subs;
-}
-
-// ---------- Generic helpers ----------
-
-function collectParagraphs(lines) {
- const paragraphs = [];
- let buf = [];
- const flush = () => {
- if (buf.length) {
- paragraphs.push(buf.join(' ').trim());
- buf = [];
- }
- };
- for (const raw of lines) {
- const trimmed = raw.trim();
- if (trimmed === '') { flush(); continue; }
- // Horizontal rules (---, ***) and headings/bullets end a paragraph.
- if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { flush(); continue; }
- if (raw.startsWith('#') || raw.match(/^[-*]\s/)) { flush(); continue; }
- buf.push(trimmed);
- }
- flush();
- return paragraphs.filter(Boolean);
-}
-
-function collectBullets(lines) {
- const bullets = [];
- let current = null;
- for (const raw of lines) {
- const m = raw.match(/^\s*[-*]\s+(.+)$/);
- if (m) {
- if (current) bullets.push(current);
- current = m[1];
- continue;
- }
- // continuation of a bullet (indented line)
- if (current && raw.match(/^\s{2,}\S/)) {
- current += ' ' + raw.trim();
- continue;
- }
- // blank line ends a bullet
- if (raw.trim() === '' && current) {
- bullets.push(current);
- current = null;
- }
- }
- if (current) bullets.push(current);
- return bullets;
-}
-
-function stripBold(s) {
- return s.replace(/\*\*(.+?)\*\*/g, '$1');
-}
-
-function extractNamedRules(lines) {
- const rules = [];
- const seen = new Set();
-
- // Style A (Impeccable): "**The X Rule.** body body body" — can span lines.
- const joined = lines.join('\n');
- const inlineStart = /\*\*(The [^*]+?Rule)\.\*\*/g;
- const inlineMatches = [];
- let m;
- while ((m = inlineStart.exec(joined)) !== null) {
- inlineMatches.push({ name: m[1], start: m.index, end: inlineStart.lastIndex });
- }
- for (let i = 0; i < inlineMatches.length; i++) {
- const mm = inlineMatches[i];
- const bodyEnd = i + 1 < inlineMatches.length ? inlineMatches[i + 1].start : joined.length;
- const body = joined
- .slice(mm.end, bodyEnd)
- .replace(/\n##[^\n]*$/s, '')
- .replace(/\n###[^\n]*$/s, '')
- .trim();
- const name = stripBold(mm.name).trim();
- seen.add(name.toLowerCase());
- rules.push({ name, body: stripBold(body) });
- }
-
- // Style B (Stitch): `### The "X" Rule` or `### The X Fallback`, body is the
- // bullets/paragraphs until the next heading. Accept Rule / Fallback / Principle.
- for (let i = 0; i < lines.length; i++) {
- const h3 = lines[i].match(/^###\s+(.+?)\s*$/);
- if (!h3) continue;
- const headerName = stripBold(h3[1]).replace(/["“”]/g, '').trim();
- if (!/^The\b.*\b(Rule|Fallback|Principle)\b/i.test(headerName)) continue;
- if (seen.has(headerName.toLowerCase())) continue;
-
- const bodyLines = [];
- for (let j = i + 1; j < lines.length; j++) {
- if (/^##\s|^###\s/.test(lines[j])) break;
- bodyLines.push(lines[j]);
- }
- const body = stripBold(bodyLines.join('\n').replace(/\n+/g, ' ')).trim();
- if (body) {
- seen.add(headerName.toLowerCase());
- rules.push({ name: headerName, body });
- }
- }
-
- // Style C (Stitch bullet form): "* **The Layering Principle:** body"
- // Colon/period lives inside the bold, so match "**...**" then inspect.
- for (const b of collectBullets(lines)) {
- const mm = b.match(/^\*\*([^*]+?)\*\*\s*(.+)$/);
- if (!mm) continue;
- const nameRaw = mm[1].replace(/[.:]\s*$/, '').replace(/["“”]/g, '').trim();
- if (!/^The\b.+\b(Rule|Fallback|Principle)$/i.test(nameRaw)) continue;
- if (seen.has(nameRaw.toLowerCase())) continue;
- seen.add(nameRaw.toLowerCase());
- rules.push({ name: nameRaw, body: stripBold(mm[2]).trim() });
- }
-
- return rules;
-}
-
-// ---------- Per-section extractors ----------
-
-function extractOverview(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
- const northStar = text.match(/\*\*Creative North Star:\s*"([^"]+)"\*\*/);
- const keyChars = [];
- const keyCharMatch = text.match(/\*\*Key Characteristics:\*\*\s*\n([\s\S]+?)(?:\n##|\n###|$)/);
- if (keyCharMatch) {
- for (const line of keyCharMatch[1].split('\n')) {
- const m = line.match(/^\s*[-*]\s+(.+)$/);
- if (m) keyChars.push(stripBold(m[1].trim()));
- }
- }
-
- // Philosophy paragraphs: everything that isn't a rule header or key-char block
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) =>
- !p.startsWith('**Creative North Star') &&
- !p.startsWith('**Key Characteristics')
- );
-
- return {
- subtitle: section.subtitle,
- creativeNorthStar: northStar ? northStar[1] : null,
- philosophy: paragraphs,
- keyCharacteristics: keyChars,
- };
-}
-
-function extractColors(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ');
- const groups = [];
- const ROLE_KEYWORDS = /^(primary|secondary|tertiary|neutral|accent)\b/i;
-
- for (const sub of subs.slice(1)) {
- if (!sub.name || /Named Rules?/i.test(sub.name) || /^The\s/i.test(sub.name)) continue;
-
- const bullets = collectBullets(sub.lines);
- const parsed = bullets.map((b) => parseColorBullet(b)).filter(Boolean);
- if (parsed.length === 0) continue;
-
- // If every bullet starts with a role keyword (Primary/Secondary/...), promote
- // each bullet to its own group. Otherwise keep the subsection as the group.
- const allRoleBullets =
- parsed.length > 0 && parsed.every((p) => p.name && ROLE_KEYWORDS.test(p.name));
-
- if (allRoleBullets) {
- for (const p of parsed) {
- groups.push({ role: p.name, colors: [p] });
- }
- } else {
- groups.push({ role: sub.name, colors: parsed });
- }
- }
-
- // If the Colors section has no subsections at all (unlikely), fall back to
- // scanning the whole section as a flat bullet list.
- if (groups.length === 0) {
- const flat = collectBullets(section.lines)
- .map((b) => parseColorBullet(b))
- .filter(Boolean);
- if (flat.length) {
- for (const p of flat) {
- if (p.name && ROLE_KEYWORDS.test(p.name)) {
- groups.push({ role: p.name, colors: [p] });
- } else {
- const fallback = groups.find((g) => g.role === 'Palette');
- if (fallback) fallback.colors.push(p);
- else groups.push({ role: 'Palette', colors: [p] });
- }
- }
- }
- }
-
- return {
- subtitle: section.subtitle,
- description: description || null,
- groups,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function parseColorBullet(bullet) {
- const text = bullet.trim();
-
- // Case 1 (Impeccable): **Name** (value-with-maybe-nested-parens): description
- const bold = text.match(/^\*\*(.+?)\*\*\s*(.*)$/);
- if (bold && bold[2].startsWith('(')) {
- const value = extractParenGroup(bold[2]);
- if (value !== null) {
- const after = bold[2].slice(value.length + 2).trimStart();
- if (after.startsWith(':')) {
- return buildColor(bold[1], value, after.slice(1).trim());
- }
- }
- }
-
- // Case 2 (Stitch): **Name (values):** description — value embedded in bold.
- const stitch = text.match(/^\*\*([^*]+?)\s*\(([^)]+)\):\*\*\s*(.*)$/);
- if (stitch) {
- return buildColor(stitch[1].trim(), stitch[2], stitch[3]);
- }
-
- // Case 3: bullet without bold, just hex/oklch inside.
- const values = collectColorValues(text);
- if (values.length) {
- return buildColor(null, values.join(' to '), text);
- }
- return null;
-}
-
-function extractParenGroup(s) {
- if (s[0] !== '(') return null;
- let depth = 0;
- for (let i = 0; i < s.length; i++) {
- if (s[i] === '(') depth++;
- else if (s[i] === ')') {
- depth--;
- if (depth === 0) return s.slice(1, i);
- }
- }
- return null;
-}
-
-function buildColor(name, rawValue, description) {
- const values = collectColorValues(rawValue);
- const primary = values[0] ?? rawValue.trim();
- return {
- name: name ? stripBold(name).trim() : null,
- value: primary,
- valueRange: values.length > 1 ? values : null,
- format: detectFormat(primary),
- description: stripBold(description || '').trim() || null,
- };
-}
-
-function collectColorValues(s) {
- const out = [];
- s.replace(HEX_RE, (v) => {
- out.push(v);
- return v;
- });
- s.replace(OKLCH_RE, (v) => {
- out.push(v);
- return v;
- });
- return out;
-}
-
-function detectFormat(v) {
- if (!v) return 'unknown';
- if (v.startsWith('#')) return 'hex';
- if (/^oklch/i.test(v)) return 'oklch';
- if (/^rgb/i.test(v)) return 'rgb';
- return 'unknown';
-}
-
-function scanInlineColors(lines) {
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '');
- const color = parseColorBullet(trimmed);
- if (color) out.push(color);
- }
- return out;
-}
-
-function parseStitchInlineGroups(lines) {
- // Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
- // Each bullet IS its own role. Group them under the spoken role name.
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
- const m = trimmed.match(
- /^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
- );
- if (m) {
- const role = m[1];
- const color = buildColor(role, m[2], m[3]);
- out.push({ role, colors: [color] });
- }
- }
- return out;
-}
-
-function extractTypography(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
-
- const fonts = {};
- // Pattern A: **Display Font:** Family (with fallback)
- const fontLineRe = /\*\*([\w\s/]+?)Font:\*\*\s*([^\n(]+?)(?:\s*\(with\s+([^)]+)\))?\s*$/gm;
- let fm;
- while ((fm = fontLineRe.exec(text)) !== null) {
- const rawRole = fm[1].trim().toLowerCase().replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || 'display';
- fonts[role] = {
- family: fm[2].trim(),
- fallback: fm[3] ? fm[3].trim() : null,
- };
- }
-
- // Pattern B (Stitch): * **Display & Headlines (Noto Serif):** description
- if (Object.keys(fonts).length === 0) {
- const stitchRe = /\*\*([\w\s&/]+?)\s*\(([^)]+)\):\*\*\s*(.+)/g;
- let sm;
- while ((sm = stitchRe.exec(text)) !== null) {
- const rawRole = sm[1]
- .trim()
- .toLowerCase()
- .replace(/\s*&\s*/g, '-')
- .replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || rawRole;
- fonts[role] = { family: sm[2].trim(), fallback: null, purpose: sm[3].trim() };
- }
- }
-
- // Character paragraph — either a **Character:** label, or fall back to the
- // first free paragraph under the section header (Stitch style).
- const characterMatch = text.match(/\*\*Character:\*\*\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\n|\n###|\n##|$)/);
- let character = characterMatch ? characterMatch[1].replace(/\n/g, ' ').trim() : null;
- if (!character) {
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) => !/^\*\*[\w\s/&]+Font/i.test(p) && !/^\*\*[\w\s/&]+\([^)]+\)/.test(p)
- );
- if (paragraphs.length) character = paragraphs[0];
- }
-
- // Hierarchy bullets under ### Hierarchy
- const subs = splitSubsections(section.lines);
- let hierarchy = [];
- const hierSub = subs.find((s) => s.name && /hierarch/i.test(s.name));
- if (hierSub) {
- const bullets = collectBullets(hierSub.lines);
- hierarchy = bullets.map(parseTypeBullet).filter(Boolean);
- }
-
- return {
- subtitle: section.subtitle,
- fonts,
- character,
- hierarchy,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function normalizeFontRole(raw) {
- // Canonical roles the panel cares about: display, body, label, mono.
- // Stitch often writes compound roles like "display-&-headlines" or "ui-&-body"
- // — collapse them to the first canonical role present.
- const tokens = raw.split(/[-/&\s]+/).filter(Boolean);
- const priority = ['display', 'headline', 'body', 'ui', 'label', 'mono'];
- const canonical = { headline: 'display', ui: 'body' };
- for (const p of priority) {
- if (tokens.includes(p)) return canonical[p] || p;
- }
- return null;
-}
-
-function parseTypeBullet(bullet) {
- // - **Display** (family, weight 300, italic, clamp(...), line-height 1): purpose
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(([^)]+)\):\s*(.*)$/);
- if (!m) return null;
- const name = m[1].trim();
- const specs = m[2].split(',').map((s) => s.trim());
- return {
- name,
- specs,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractElevation(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ') || null;
-
- const shadows = [];
- const seen = new Set();
- const dedupe = (entry) => {
- const key = (entry.name || '') + '::' + entry.value;
- if (seen.has(key)) return;
- seen.add(key);
- shadows.push(entry);
- };
-
- for (const b of collectBullets(section.lines)) {
- const parsed = parseShadowBullet(b);
- if (parsed) dedupe(parsed);
- }
-
- // Fallback: extract shadows written inline in prose. Stitch style is
- // "...use an extra-diffused shadow: `box-shadow: 0 12px 40px rgba(...)`."
- for (const p of collectParagraphs(section.lines)) {
- for (const inline of extractInlineShadows(p)) dedupe(inline);
- }
- for (const b of collectBullets(section.lines)) {
- for (const inline of extractInlineShadows(b)) dedupe(inline);
- }
-
- return {
- subtitle: section.subtitle,
- description,
- shadows,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function extractInlineShadows(text) {
- // Find `box-shadow: ...` anywhere in prose and capture the value. Work on the
- // raw string so it handles both backtick-fenced and unfenced variants.
- const out = [];
- const re = /box-shadow\s*:\s*([^`;\n]+)/gi;
- let m;
- while ((m = re.exec(text)) !== null) {
- const value = m[1].replace(/[`.)]+$/, '').trim();
- if (!value) continue;
- // Name heuristic: the noun immediately before the shadow phrase.
- // e.g. "an extra-diffused shadow: ..." -> "extra-diffused shadow"
- const before = text.slice(0, m.index);
- const nameMatch = before.match(/\b([A-Za-z][A-Za-z\- ]{2,40})\s+shadow\b[^A-Za-z0-9]*$/i);
- let name = null;
- if (nameMatch) {
- const stripped = nameMatch[1]
- .replace(/^(?:use|using|apply|applying|is|are|looks? like)\s+/i, '')
- .replace(/^(?:a|an|the)\s+/i, '')
- .trim();
- if (stripped) {
- name =
- stripped.charAt(0).toUpperCase() + stripped.slice(1) + ' shadow';
- }
- }
- out.push({
- name,
- value,
- purpose: null,
- });
- }
- return out;
-}
-
-function parseShadowBullet(bullet) {
- // - **Name** (`box-shadow: value`): purpose
- // - **Name** (`value`): purpose
- // Only accept if the paren content looks like a shadow value (contains px,
- // rem, rgba, or box-shadow). This filters out `**Rule Name:**` bullets.
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(`?([^`]+?)`?\):\s*(.*)$/);
- if (!m) return null;
- const rawValue = m[2].replace(/^box-shadow:\s*/i, '').trim();
- const looksLikeShadow =
- /box-shadow|rgba?\(|\bpx\b|\brem\b|^-?\d+\s/i.test(rawValue) &&
- /\d/.test(rawValue);
- if (!looksLikeShadow) return null;
- const name = stripBold(m[1]).trim();
- return {
- name,
- value: rawValue,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractComponents(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const components = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
-
- const bullets = collectBullets(sub.lines);
- const paragraphs = collectParagraphs(sub.lines);
-
- const variants = [];
- const properties = {};
-
- for (const b of bullets) {
- // - **Key:** value
- const m = b.match(/^\*\*(.+?):?\*\*:?\s*(.+)$/);
- if (m) {
- const key = stripBold(m[1]).trim();
- const value = stripBold(m[2]).trim();
- // Heuristic: "Primary", "Secondary", "Hover", "Focus" etc are variants;
- // "Shape", "Background", "Padding" are properties.
- if (/^(primary|secondary|tertiary|ghost|hover|focus|active|disabled|default|error|selected|unselected|state)$/i.test(key.split(/[\s/]/)[0])) {
- variants.push({ name: key, description: value });
- } else {
- properties[key.toLowerCase()] = value;
- }
- }
- }
-
- components.push({
- name: sub.name,
- description: paragraphs.join(' ') || null,
- properties,
- variants,
- });
- }
-
- return {
- subtitle: section.subtitle,
- components,
- };
-}
-
-function extractDosDonts(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const dos = [];
- const donts = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
- const subName = normalizeApostrophes(sub.name);
- const bullets = collectBullets(sub.lines).map((b) => stripBold(b).trim());
- if (/^do'?t?:?$/i.test(subName) || /^do:?$/i.test(subName)) {
- dos.push(...bullets);
- } else if (/^don'?t:?$/i.test(subName)) {
- donts.push(...bullets);
- }
- }
-
- // Classify by bullet prefix as a backup (catches loose bullets outside H3 wrappers)
- for (const b of collectBullets(section.lines)) {
- const stripped = normalizeApostrophes(stripBold(b).trim());
- if (/^don'?t\b/i.test(stripped)) {
- if (!donts.some((d) => normalizeApostrophes(d) === stripped)) donts.push(stripped);
- } else if (/^do\b/i.test(stripped)) {
- if (!dos.some((d) => normalizeApostrophes(d) === stripped)) dos.push(stripped);
- }
- }
-
- return { dos, donts };
-}
-
-// ---------- Coverage assessment ----------
-
-function assessCoverage(model) {
- const report = {};
-
- report.overview = model.overview
- ? {
- northStar: Boolean(model.overview.creativeNorthStar),
- philosophy: model.overview.philosophy.length > 0,
- keyCharacteristics: model.overview.keyCharacteristics.length,
- }
- : 'missing';
-
- report.colors = model.colors
- ? {
- groups: model.colors.groups.length,
- totalColors: model.colors.groups.reduce((n, g) => n + g.colors.length, 0),
- rules: model.colors.rules.length,
- }
- : 'missing';
-
- report.typography = model.typography
- ? {
- fonts: Object.keys(model.typography.fonts).length,
- hierarchyEntries: model.typography.hierarchy.length,
- character: Boolean(model.typography.character),
- rules: model.typography.rules.length,
- }
- : 'missing';
-
- report.elevation = model.elevation
- ? {
- shadows: model.elevation.shadows.length,
- rules: model.elevation.rules.length,
- description: Boolean(model.elevation.description),
- }
- : 'missing';
-
- report.components = model.components
- ? {
- count: model.components.components.length,
- variantTotal: model.components.components.reduce((n, c) => n + c.variants.length, 0),
- }
- : 'missing';
-
- report.dosDonts = model.dosDonts
- ? {
- dos: model.dosDonts.dos.length,
- donts: model.dosDonts.donts.length,
- }
- : 'missing';
-
- return report;
-}
-
-// ---------- Main ----------
-
-export function parseDesignMd(md) {
- const { frontmatter, body } = parseFrontmatter(md);
- const { title, sections } = splitSections(body);
- return {
- schemaVersion: 2,
- title,
- frontmatter,
- overview: extractOverview(sections['Overview']),
- colors: extractColors(sections['Colors']),
- typography: extractTypography(sections['Typography']),
- elevation: extractElevation(sections['Elevation']),
- components: extractComponents(sections['Components']),
- dosDonts: extractDosDonts(sections["Do's and Don'ts"]),
- };
-}
-
-export { assessCoverage };
@@ -1,198 +0,0 @@
-/**
- * Scan a project tree for Content-Security-Policy signals and classify the
- * shape so the agent knows which patch template to propose.
- *
- * Used at first-time `live.mjs` setup. Mechanical (grep-based) — no network,
- * no dev server, no JS evaluation. The classification drives a user-facing
- * consent prompt; the agent does the actual patch writing.
- *
- * Shapes are named by patch mechanism, not framework origin:
- * - "append-arrays": CSP defined as structured directive arrays. Patch
- * appends a dev-only localhost entry. Covers:
- * - Monorepo helpers with additional*Src options
- * (e.g. createBaseNextConfig for Next)
- * - SvelteKit kit.csp.directives
- * - nuxt-security module's contentSecurityPolicy
- * - "append-string": CSP built as a literal value string. Patch splices
- * a dev-only token into script-src and connect-src.
- * Covers:
- * - Inline Next.js headers() with CSP string
- * - Nuxt routeRules / nitro.routeRules CSP headers
- * - "middleware": CSP set dynamically in middleware.{ts,js}.
- * Detected but not auto-patched in v1.
- * - "meta-tag": <meta http-equiv="Content-Security-Policy"> in
- * layout files. Detected but not auto-patched in v1.
- * - null: no CSP signals found; no patch needed.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const SKIP_DIRS = new Set([
- 'node_modules',
- '.git',
- '.next',
- '.turbo',
- '.svelte-kit',
- '.nuxt',
- '.astro',
- 'dist',
- 'build',
- 'out',
- '.vercel',
-]);
-
-const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.tsx', '.jsx']);
-const LAYOUT_EXTS = new Set(['.tsx', '.jsx', '.astro', '.vue', '.svelte', '.html']);
-const MAX_DEPTH = 6;
-const MAX_READ_BYTES = 64 * 1024;
-
-// append-arrays signals: CSP expressed as structured directive arrays
-const MONOREPO_HELPER_SIGNALS = [
- /\bbuildCSPConfig\b/,
- /\bbuildSecurityHeaders\b/,
- /\badditionalScriptSrc\b/,
- /\badditionalConnectSrc\b/,
- /\bcreateBaseNextConfig\b/,
-];
-const SVELTEKIT_CSP_SIGNALS = [
- /\bkit\s*:/,
- /\bcsp\s*:/,
- /\bdirectives\s*:/,
-];
-const NUXT_SECURITY_SIGNALS = [
- /['"]nuxt-security['"]/,
- /\bcontentSecurityPolicy\b/,
-];
-
-// append-string signals: CSP written as a literal value string
-const INLINE_HEADER_SIGNALS = [
- /["']Content-Security-Policy["']/i,
- /\bscript-src\b/,
- /\bconnect-src\b/,
-];
-const NUXT_ROUTE_RULES_SIGNALS = [
- /\brouteRules\b/,
- /Content-Security-Policy/i,
- /\bscript-src\b/,
-];
-
-const MIDDLEWARE_HINT = /headers\.set\(\s*["']Content-Security-Policy["']/i;
-const META_TAG_HINT = /http-equiv\s*=\s*["']Content-Security-Policy["']/i;
-
-/**
- * @param {string} cwd Project root.
- * @returns {{ shape: string|null, signals: string[] }}
- */
-export function detectCsp(cwd = process.cwd()) {
- const hits = { appendArrays: [], appendString: [], middleware: [], metaTag: [] };
-
- walk(cwd, cwd, 0, (absPath, relPath, body) => {
- const ext = path.extname(absPath);
- const base = path.basename(absPath).toLowerCase();
- const isConfig = (name) =>
- new RegExp('(^|/)' + name + '\\.config\\.').test(relPath);
-
- // === append-arrays candidates ===
-
- // Monorepo CSP helper: packages/*/src/.../(config|security)/*
- if (SCAN_EXTS.has(ext) &&
- /packages\/[^/]+\/src\/.*(config|next-config|security)/.test(relPath) &&
- MONOREPO_HELPER_SIGNALS.some((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // SvelteKit kit.csp.directives
- if (SCAN_EXTS.has(ext) && isConfig('svelte') &&
- SVELTEKIT_CSP_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // Nuxt nuxt-security module
- if (SCAN_EXTS.has(ext) && isConfig('nuxt') &&
- NUXT_SECURITY_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // === append-string candidates ===
-
- // Inline headers in Next/Nuxt/SvelteKit/Astro/Vite config
- if (SCAN_EXTS.has(ext) &&
- /(^|\/)(next|nuxt|vite|astro|svelte)\.config\./.test(relPath) &&
- INLINE_HEADER_SIGNALS.every((re) => re.test(body))) {
- // Nuxt routeRules is a sub-shape of append-string; we already covered
- // nuxt-security above via return, so any remaining Nuxt CSP match here
- // is a route-rules / inline-headers case. Either way, same patch
- // mechanism.
- hits.appendString.push(relPath);
- return;
- }
-
- // === detect-only shapes ===
-
- if ((base === 'middleware.ts' || base === 'middleware.js' || base === 'middleware.mjs') &&
- MIDDLEWARE_HINT.test(body)) {
- hits.middleware.push(relPath);
- }
-
- if (LAYOUT_EXTS.has(ext) && META_TAG_HINT.test(body)) {
- hits.metaTag.push(relPath);
- }
- });
-
- // Priority: append-arrays > append-string > middleware > meta-tag.
- // Structured patches are safer than string splices; runtime and HTML
- // injection patches are less reliable and v1 doesn't auto-apply them.
- if (hits.appendArrays.length > 0) {
- return { shape: 'append-arrays', signals: hits.appendArrays };
- }
- if (hits.appendString.length > 0) {
- return { shape: 'append-string', signals: hits.appendString };
- }
- if (hits.middleware.length > 0) {
- return { shape: 'middleware', signals: hits.middleware };
- }
- if (hits.metaTag.length > 0) {
- return { shape: 'meta-tag', signals: hits.metaTag };
- }
- return { shape: null, signals: [] };
-}
-
-function walk(root, dir, depth, visit) {
- if (depth > MAX_DEPTH) return;
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
-
- for (const entry of entries) {
- const abs = path.join(dir, entry.name);
- if (entry.isDirectory()) {
- if (SKIP_DIRS.has(entry.name)) continue;
- walk(root, abs, depth + 1, visit);
- continue;
- }
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name);
- if (!SCAN_EXTS.has(ext) && !LAYOUT_EXTS.has(ext)) continue;
- let body;
- try {
- const fd = fs.openSync(abs, 'r');
- try {
- const buf = Buffer.alloc(MAX_READ_BYTES);
- const n = fs.readSync(fd, buf, 0, MAX_READ_BYTES, 0);
- body = buf.slice(0, n).toString('utf-8');
- } finally { fs.closeSync(fd); }
- } catch { continue; }
- visit(abs, path.relative(root, abs), body);
- }
-}
-
-// CLI mode
-const _running = process.argv[1];
-if (_running?.endsWith('detect-csp.mjs') || _running?.endsWith('detect-csp.mjs/')) {
- const result = detectCsp(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
@@ -1,21 +0,0 @@
-#!/usr/bin/env node
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { pathToFileURL, fileURLToPath } from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const candidates = [
- path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
-];
-const detectorPath = candidates.find(p => fs.existsSync(p));
-
-if (!detectorPath) {
- process.stderr.write('Error: bundled detector not found.\n');
- process.exit(1);
-}
-
-const { detectCli } = await import(pathToFileURL(detectorPath));
-
-await detectCli();
@@ -1,1688 +0,0 @@
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
@@ -1,232 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
-import { detectHtml } from '../engines/static-html/detect-html.mjs';
-import { detectText } from '../engines/regex/detect-text.mjs';
-import {
- HTML_EXTENSIONS,
- buildImportGraph,
- detectFrameworkConfig,
- isPortListening,
- walkDir,
-} from '../node/file-system.mjs';
-
-// ---------------------------------------------------------------------------
-// Output formatting
-// ---------------------------------------------------------------------------
-
-function formatFindings(findings, jsonMode) {
- if (jsonMode) return JSON.stringify(findings, null, 2);
-
- const grouped = {};
- for (const f of findings) {
- if (!grouped[f.file]) grouped[f.file] = [];
- grouped[f.file].push(f);
- }
- const out = [];
- for (const [file, items] of Object.entries(grouped)) {
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
- out.push(`\n${file}${importNote}`);
- for (const item of items) {
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
- out.push(` → ${item.description}`);
- }
- }
- out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
- return out.join('\n');
-}
-
-// ---------------------------------------------------------------------------
-// Stdin handling
-// ---------------------------------------------------------------------------
-
-async function handleStdin() {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- const input = Buffer.concat(chunks).toString('utf-8');
- try {
- const parsed = JSON.parse(input);
- const fp = parsed?.tool_input?.file_path;
- if (fp && fs.existsSync(fp)) {
- return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
- ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
- }
- } catch { /* not JSON */ }
- return detectText(input, '<stdin>');
-}
-
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-async function confirm(question) {
- const rl = (await import('node:readline')).default.createInterface({
- input: process.stdin, output: process.stderr,
- });
- return new Promise((resolve) => {
- rl.question(`${question} [Y/n] `, (answer) => {
- rl.close();
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
- });
- });
-}
-
-function printUsage() {
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
-
-Scan files or URLs for UI anti-patterns and design quality issues.
-
-Options:
- --fast Regex-only mode (skip static HTML/CSS analysis, faster but misses linked stylesheets)
- --json Output results as JSON
- --help Show this help message
-
-Detection modes:
- HTML files Static HTML/CSS analysis (default, catches linked CSS)
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
- URLs Puppeteer full browser rendering (auto-detected)
- --fast Forces regex for all files
-
-Examples:
- impeccable detect src/
- impeccable detect index.html
- impeccable detect https://example.com
- impeccable detect --fast --json .`);
-}
-
-async function detectCli() {
- let args = process.argv.slice(2).map(arg => {
- if (arg === '-json') return '--json';
- if (arg === '-fast') return '--fast';
- return arg;
- });
- if (args[0] === 'detect') args = args.slice(1);
- const jsonMode = args.includes('--json');
- const helpMode = args.includes('--help');
- const fastMode = args.includes('--fast');
- const targets = args.filter(a => !a.startsWith('--'));
-
- if (helpMode) { printUsage(); process.exit(0); }
-
- let allFindings = [];
-
- if (!process.stdin.isTTY && targets.length === 0) {
- allFindings = await handleStdin();
- } else {
- const paths = targets.length > 0 ? targets : [process.cwd()];
- const urlTargetCount = paths.filter(target => /^https?:\/\//i.test(target)).length;
- const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
-
- try {
- for (const target of paths) {
- if (/^https?:\/\//i.test(target)) {
- try {
- const scanner = browserDetector
- ? (url) => browserDetector.detectUrl(url)
- : (url) => detectUrl(url);
- allFindings.push(...await scanner(target));
- } catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
- continue;
- }
-
- const resolved = path.resolve(target);
- let stat;
- try { stat = fs.statSync(resolved); }
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
-
- if (stat.isDirectory()) {
- // Check for framework dev server config (skip in JSON mode to avoid polluting output)
- if (!jsonMode) {
- const fwConfig = detectFrameworkConfig(resolved);
- if (fwConfig) {
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
- if (probe.listening && probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
- `For more accurate results, scan the running site:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- } else if (probe.listening && !probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
- );
- } else {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Start the dev server and scan via URL for best results:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- }
- }
- }
-
- const files = walkDir(resolved);
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
-
- // Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
- if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
- process.stderr.write(
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
- `Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
- `Use --fast to skip static HTML/CSS analysis, or target a specific subdirectory.\n`
- );
- const ok = await confirm('Continue?');
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
- }
-
- // Build import graph for multi-file awareness
- const graph = buildImportGraph(files);
- // Build reverse map: file -> set of files that import it
- const importedByMap = new Map();
- for (const [importer, imports] of graph) {
- for (const imported of imports) {
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
- importedByMap.get(imported).add(importer);
- }
- }
-
- for (const file of files) {
- const ext = path.extname(file).toLowerCase();
- let fileFindings;
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- fileFindings = await detectHtml(file);
- } else {
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
- }
- // Annotate findings with import context
- const importers = importedByMap.get(file);
- if (importers && importers.size > 0) {
- const importerNames = [...importers].map(f => path.basename(f));
- for (const f of fileFindings) {
- f.importedBy = importerNames;
- }
- }
- allFindings.push(...fileFindings);
- }
- } else if (stat.isFile()) {
- const ext = path.extname(resolved).toLowerCase();
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- allFindings.push(...await detectHtml(resolved));
- } else {
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
- }
- }
- }
- } finally {
- if (browserDetector) await browserDetector.close();
- }
- }
-
- if (allFindings.length > 0) {
- if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
- else process.stderr.write(formatFindings(allFindings, false) + '\n');
- process.exit(2);
- }
- if (jsonMode) process.stdout.write('[]\n');
- process.exit(0);
-}
-
-export { formatFindings, handleStdin, confirm, printUsage, detectCli };
@@ -1,4030 +0,0 @@
-/**
- * Anti-Pattern Browser Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * GENERATED -- do not edit. Source: cli/engine/browser/injected/index.mjs
- * Rebuild: node scripts/build-browser-detector.js
- *
- * Usage: <script src="detect-antipatterns-browser.js"></script>
- * Re-scan: window.impeccableScan()
- */
-(function () {
-if (typeof window === 'undefined') return;
-// --- cli/engine/shared/constants.mjs ---
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-// --- cli/engine/registry/antipatterns.mjs ---
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-// --- cli/engine/shared/color.mjs ---
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-// --- cli/engine/rules/checks.mjs ---
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-// --- cli/engine/browser/injected/index.mjs ---
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
-
-})();
@@ -1,43 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Anti-Pattern Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * Public API facade. Runtime engines live under cli/engine/engines/.
- */
-
-import { detectCli } from './cli/main.mjs';
-
-export { ANTIPATTERNS, RULE_ENGINE_SUPPORT, getAntipattern, getRulesForCategory, getRuleEngineSupport } from './registry/antipatterns.mjs';
-export { SAFE_TAGS, BORDER_SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS, KNOWN_SERIF_FONTS } from './shared/constants.mjs';
-export { isNeutralColor, parseRgb, relativeLuminance, contrastRatio, parseGradientColors, hasChroma, getHue, colorToHex } from './shared/color.mjs';
-export { isFullPage } from './shared/page.mjs';
-export {
- checkElementBorders,
- checkElementMotion,
- checkElementGlow,
- checkPageTypography,
- checkPageLayout,
- checkHtmlPatterns,
-} from './rules/checks.mjs';
-export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
-export { detectHtml } from './engines/static-html/detect-html.mjs';
-export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
-export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
-export {
- walkDir,
- SCANNABLE_EXTENSIONS,
- SKIP_DIRS,
- buildImportGraph,
- resolveImport,
- detectFrameworkConfig,
- isPortListening,
- FRAMEWORK_CONFIGS,
-} from './node/file-system.mjs';
-export { formatFindings, detectCli } from './cli/main.mjs';
-
-const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
-if (isMainModule) detectCli();
@@ -1,251 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { finding } from '../../findings.mjs';
-import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
-
-async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
- if (options?.visualContrast === false) return [];
- const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : 12;
- const scrollOffscreen = options?.visualContrastScrollOffscreen !== false;
- const existingLowContrastSelectors = new Set(
- serializedGroups
- .filter(group => group.findings?.some(f => f.type === 'low-contrast'))
- .map(group => group.selector)
- .filter(Boolean)
- );
-
- let browserAnalyses = [];
- const findings = [];
- if (options?.visualContrastBrowser !== false) {
- const browserFindings = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'browser-fallback',
- target,
- }, async () => {
- browserAnalyses = await page.evaluate(async ({ maxCandidates, scrollOffscreen }) => {
- if (typeof window.impeccableAnalyzeVisualContrast !== 'function') return [];
- return window.impeccableAnalyzeVisualContrast({ maxCandidates, scrollOffscreen });
- }, { maxCandidates, scrollOffscreen });
- return browserAnalyses
- .filter(result => result.finding && !existingLowContrastSelectors.has(result.selector))
- .map(result => result.finding);
- });
- findings.push(...browserFindings);
- }
-
- let candidates = browserAnalyses.length > 0 ? browserAnalyses : [];
- if (candidates.length === 0) {
- candidates = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'collect-candidates',
- target,
- }, () => page.evaluate(({ maxCandidates }) => {
- if (typeof window.impeccableCollectVisualContrastCandidates !== 'function') return [];
- return window.impeccableCollectVisualContrastCandidates({ maxCandidates });
- }, { maxCandidates }));
- }
-
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const browserResolvedSelectors = new Set(
- browserAnalyses
- .filter(result => result.status === 'fail' || result.status === 'pass')
- .map(result => result.selector)
- .filter(Boolean)
- );
- const filtered = candidates.filter(candidate =>
- !existingLowContrastSelectors.has(candidate.selector) &&
- !browserResolvedSelectors.has(candidate.selector)
- );
- if (options?.visualContrastPixel === false) return findings;
- for (const candidate of filtered) {
- const result = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'pixel-diff',
- target,
- }, async () => {
- const finding = await captureVisualContrastCandidate(page, candidate, viewport);
- return finding ? [finding] : [];
- });
- findings.push(...result);
- }
- return findings;
-}
-
-// ---------------------------------------------------------------------------
-// Puppeteer detection (for URLs)
-// ---------------------------------------------------------------------------
-
-async function detectUrl(url, options = {}) {
- const profile = options?.profile;
- const waitUntil = options?.waitUntil || 'networkidle0';
- const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const externalBrowser = options?.browser || null;
- let puppeteer;
- if (!externalBrowser) {
- try {
- puppeteer = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'import-puppeteer',
- target: url,
- }, () => import('puppeteer'));
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- }
-
- // Read the browser detection script — reuse it instead of reimplementing
- const browserScriptPath = path.resolve(
- path.dirname(fileURLToPath(import.meta.url)),
- '..',
- '..',
- 'detect-antipatterns-browser.js'
- );
- let browserScript;
- try {
- browserScript = profileStep(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'read-browser-script',
- target: url,
- }, () => fs.readFileSync(browserScriptPath, 'utf-8'));
- } catch {
- throw new Error(`Browser script not found at ${browserScriptPath}`);
- }
-
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
- // running in CI; local users keep the default hardened launch.
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
- const browser = externalBrowser || await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'launch-browser',
- target: url,
- }, () => puppeteer.default.launch({ headless: true, args: launchArgs }));
- const page = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'new-page',
- target: url,
- }, () => browser.newPage());
- let results = [];
- try {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'set-viewport',
- target: url,
- }, () => page.setViewport(viewport));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: `goto:${waitUntil}`,
- target: url,
- }, () => page.goto(url, { waitUntil, timeout: 30000 }));
- if (settleMs > 0) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'settle',
- target: url,
- }, () => new Promise(resolve => setTimeout(resolve, settleMs)));
- }
-
- // Inject the browser detection script and collect results
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'configure-pure-detect',
- target: url,
- }, () => page.evaluate(() => {
- window.__IMPECCABLE_CONFIG__ = {
- ...(window.__IMPECCABLE_CONFIG__ || {}),
- autoScan: false,
- };
- }));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'inject-browser-script',
- target: url,
- }, () => page.evaluate(browserScript));
- let serializedGroups = [];
- results = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'browser-scan',
- target: url,
- }, async () => {
- serializedGroups = await page.evaluate(() => {
- if (!window.impeccableDetect) return [];
- return window.impeccableDetect({ decorate: false, serialize: true });
- });
- return serializedGroups.flatMap(({ findings }) =>
- findings.map(f => ({ id: f.type, snippet: f.detail }))
- );
- });
- const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
- results.push(...visualFindings);
- } finally {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-page',
- target: url,
- }, () => page.close().catch(() => {}));
- if (!externalBrowser) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-browser',
- target: url,
- }, () => browser.close());
- }
- }
- return results.map(f => finding(f.id, url, f.snippet));
-}
-
-async function createBrowserDetector(options = {}) {
- let puppeteer;
- try {
- puppeteer = await import('puppeteer');
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- const launchArgs = options.launchArgs || (process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : []);
- const browser = options.browser || await puppeteer.default.launch({
- headless: options.headless ?? true,
- args: launchArgs,
- });
- const ownsBrowser = !options.browser;
- const defaults = {
- waitUntil: options.waitUntil || 'load',
- settleMs: Number.isFinite(options.settleMs) ? options.settleMs : 100,
- viewport: options.viewport || { width: 1280, height: 800 },
- };
- return {
- browser,
- async detectUrl(url, scanOptions = {}) {
- return detectUrl(url, {
- ...defaults,
- ...scanOptions,
- browser,
- });
- },
- async close() {
- if (ownsBrowser) await browser.close().catch(() => {});
- },
- };
-}
-
-export { runVisualContrastFallback, detectUrl, createBrowserDetector };
@@ -1,420 +0,0 @@
-import { GENERIC_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep } from '../../profile/profiler.mjs';
-
-// ---------------------------------------------------------------------------
-// Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
-// ---------------------------------------------------------------------------
-
-const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
-const hasBorderRadius = (line) => /border-radius/i.test(line);
-const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
-
-function isNeutralBorderColor(str) {
- const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
- if (!m) return false;
- const c = m[1].toLowerCase();
- if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
- const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
- if (hex) {
- const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
- if (shex) {
- const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- return false;
-}
-
-const REGEX_MATCHERS = [
- // --- Side-tab ---
- { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
- test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
- test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
- fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
- { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
- test: (m) => +m[1] >= 3,
- fmt: (m) => m[0] },
- // --- Border accent on rounded ---
- { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
- test: (m, line) => hasRounded(line) && +m[1] >= 1,
- fmt: (m) => m[0] },
- { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
- fmt: (m) => m[0] },
- // --- Overused font ---
- { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
- test: () => true,
- fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
- // --- Pure black background ---
- { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Gradient text ---
- { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
- test: (m, line) => /gradient/i.test(line),
- fmt: () => 'background-clip: text + gradient' },
- // --- Gradient text (Tailwind) ---
- { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
- test: (m, line) => /\bbg-gradient-to-/i.test(line),
- fmt: () => 'bg-clip-text + bg-gradient' },
- // --- Tailwind pure black background ---
- { id: 'pure-black-white', regex: /\bbg-black\b/g,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Tailwind gray on colored bg ---
- { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
- test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
- fmt: (m, line) => { const bg = line.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/); return `${m[0]} on ${bg?.[0] || '?'}`; } },
- // --- Tailwind AI palette ---
- { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
- fmt: (m) => `${m[0]} on heading` },
- { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
- fmt: (m) => `${m[0]} gradient` },
- // --- Bounce/elastic easing ---
- { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
- test: () => true,
- fmt: () => 'animate-bounce (Tailwind)' },
- { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
- test: (m) => {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
- },
- fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
- // --- Layout property transition ---
- { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition: ${found ? found.join(', ') : m[1].trim()}`;
- } },
- { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
- } },
-];
-
-const REGEX_ANALYZERS = [
- // Single font
- (content, filePath) => {
- const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
- const fonts = new Set();
- let m;
- while ((m = fontFamilyRe.exec(content)) !== null) {
- for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
- }
- }
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- while ((m = gfRe.exec(content)) !== null) {
- for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
- }
- if (fonts.size !== 1 || content.split('\n').length < 20) return [];
- const name = [...fonts][0];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
- return [finding('single-font', filePath, `only font used is ${name}`, line)];
- },
- // Flat type hierarchy
- (content, filePath) => {
- const sizes = new Set();
- const REM = 16;
- let m;
- const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
- while ((m = sizeRe.exec(content)) !== null) {
- const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
- if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
- }
- const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
- while ((m = clampRe.exec(content)) !== null) {
- sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
- sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
- }
- const TW = { 'text-xs': 12, 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24, 'text-3xl': 30, 'text-4xl': 36, 'text-5xl': 48, 'text-6xl': 60, 'text-7xl': 72, 'text-8xl': 96, 'text-9xl': 128 };
- for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
- if (sizes.size < 3) return [];
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio >= 2.0) return [];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (/font-size/i.test(lines[i]) || /\btext-(?:xs|sm|base|lg|xl|\d)/i.test(lines[i])) { line = i + 1; break; } }
- return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
- },
- // Monotonous spacing (regex)
- (content, filePath) => {
- const vals = [];
- let m;
- const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
- const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
- const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
- const rounded = vals.map(v => Math.round(v / 4) * 4);
- if (rounded.length < 10) return [];
- const counts = {};
- for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const pct = maxCount / rounded.length;
- const unique = [...new Set(rounded)].filter(v => v > 0);
- if (pct <= 0.6 || unique.length > 3) return [];
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
- },
- // Everything centered (regex)
- (content, filePath) => {
- const lines = content.split('\n');
- let centered = 0, total = 0;
- for (const line of lines) {
- if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
- total++;
- if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
- }
- }
- if (total < 5 || centered / total <= 0.7) return [];
- return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
- },
- // Dark glow (page-level: dark bg + colored box-shadow with blur)
- (content, filePath) => {
- // Check if page has a dark background
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
- if (!hasDarkBg) return [];
-
- // Check for colored box-shadow with blur > 4px
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let m;
- while ((m = shadowRe.exec(content)) !== null) {
- const val = m[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
- // Check blur: look for pattern like "0 0 20px" (third number > 4)
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- const lines = content.substring(0, m.index).split('\n');
- return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
- }
- }
- return [];
- },
-];
-
-// ---------------------------------------------------------------------------
-// Style block extraction (Vue/Svelte <style> blocks)
-// ---------------------------------------------------------------------------
-
-function extractStyleBlocks(content, ext) {
- ext = ext.toLowerCase();
- if (ext !== '.vue' && ext !== '.svelte') return [];
- const blocks = [];
- const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length + 1;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-// ---------------------------------------------------------------------------
-// CSS-in-JS extraction (styled-components, emotion)
-// ---------------------------------------------------------------------------
-
-const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
-
-function extractCSSinJS(content, ext) {
- ext = ext.toLowerCase();
- if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
- const blocks = [];
- const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null, options = {}) {
- const { profile, phase = 'regex-matchers' } = options || {};
- const findings = [];
- if (!profile) {
- for (const matcher of REGEX_MATCHERS) {
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- }
- return findings;
- }
-
- for (const matcher of REGEX_MATCHERS) {
- const matcherFindings = profileFindings(profile, {
- engine: 'regex',
- phase,
- ruleId: matcher.id,
- target: filePath,
- }, () => {
- const matches = [];
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- matches.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- return matches;
- });
- findings.push(...matcherFindings);
- }
- return findings;
-}
-
-function detectText(content, filePath, options = {}) {
- const profile = options?.profile;
- const findings = [];
- const lines = content.split('\n');
- const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
-
- // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
- // Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
- findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
- profile,
- phase: 'source',
- }));
-
- // Extract and scan <style> blocks from Vue/Svelte SFCs
- const styleBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'style-blocks',
- target: filePath,
- }, () => extractStyleBlocks(content, ext))
- : extractStyleBlocks(content, ext);
- for (const block of styleBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'style-block',
- }));
- }
-
- // Extract and scan CSS-in-JS template literals
- const cssJsBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'css-in-js',
- target: filePath,
- }, () => extractCSSinJS(content, ext))
- : extractCSSinJS(content, ext);
- for (const block of cssJsBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'css-in-js',
- }));
- }
-
- // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
- const deduped = [];
- for (const f of findings) {
- const isDupe = deduped.some(d =>
- d.antipattern === f.antipattern &&
- d.snippet === f.snippet &&
- Math.abs(d.line - f.line) <= 2
- );
- if (!isDupe) deduped.push(f);
- }
-
- // Page-level analyzers only run on full pages
- if (isFullPage(content)) {
- const analyzerIds = [
- 'single-font',
- 'flat-type-hierarchy',
- 'monotonous-spacing',
- 'everything-centered',
- 'dark-glow',
- ];
- for (let i = 0; i < REGEX_ANALYZERS.length; i++) {
- const analyzer = REGEX_ANALYZERS[i];
- deduped.push(...profileFindings(profile, {
- engine: 'regex',
- phase: 'page-analyzer',
- ruleId: analyzerIds[i] || `analyzer-${i + 1}`,
- target: filePath,
- }, () => analyzer(content, filePath)));
- }
- }
-
- return deduped;
-}
-
-export {
- REGEX_MATCHERS,
- REGEX_ANALYZERS,
- extractStyleBlocks,
- extractCSSinJS,
- runRegexMatchers,
- detectText,
-};
@@ -1,954 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { profileStep, recordProfileEvent } from '../../profile/profiler.mjs';
-import { parseAnyColor, resolveLengthPx, resolveVarRefs } from '../../rules/checks.mjs';
-
-// ---------------------------------------------------------------------------
-// jsdom CSS-variable border override map
-// ---------------------------------------------------------------------------
-//
-// jsdom's CSSOM silently drops any border shorthand that contains a var()
-// reference — the computed style for the element then shows empty width,
-// empty style, and a default black color. That's enough to hide the most
-// common real-world side-tab pattern in AI-generated pages:
-//
-// :root { --brand: #87a8ff; }
-// .card { border-left: 5px solid var(--brand); border-radius: 4px; }
-//
-// Real browsers (and therefore the browser detector path) resolve var()
-// natively, so this only affects the Node jsdom path.
-//
-// This pre-pass walks the stylesheets, finds any rule whose per-side or
-// all-sides border property contains var(), resolves the var() against
-// :root-level custom properties (read from the documentElement's computed
-// style, which jsdom DOES handle correctly), and attaches the resolved
-// width+color to every element that matches the rule's selector. The
-// Node-side `checkElementBorders` adapter consumes that map as a fallback
-// whenever jsdom's computed style came back empty.
-//
-// Limitations (intentional, to keep the pass simple):
-// * Only :root-level custom properties are resolved. Scoped overrides on
-// descendants are not tracked — uncommon in practice and would require
-// a per-element cascade walk.
-// * @media / @supports wrapped rules are ignored (jsdom often mishandles
-// these anyway).
-// * The fallback only fills sides that jsdom left empty, so any rule
-// whose border parses normally still wins via the computed style.
-
-const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
-
-// isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
-// CSS variables typically hold hex or named colors, so normalize those to
-// rgb() before handing the value off to the shared check. Anything we don't
-// recognise is passed through unchanged — isNeutralColor then treats it as
-// non-neutral, which is the safer default (matches the oklch-era bugfix).
-const NAMED_COLORS = {
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
-};
-
-function normalizeColorForCheck(value) {
- if (!value) return value;
- const v = value.trim();
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
- if (hex6) {
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
- if (hex3) {
- const [r, g, b] = [
- parseInt(hex3[1] + hex3[1], 16),
- parseInt(hex3[2] + hex3[2], 16),
- parseInt(hex3[3] + hex3[3], 16),
- ];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const named = NAMED_COLORS[v.toLowerCase()];
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
- return v;
-}
-
-function buildBorderOverrideMap(document, window) {
- const map = new Map();
- const rootStyle = window.getComputedStyle(document.documentElement);
-
- function resolveVar(value, depth = 0) {
- if (!value || depth > 10 || !value.includes('var(')) return value;
- return value.replace(
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
- (_, name, fallback) => {
- const v = rootStyle.getPropertyValue(name).trim();
- if (v) return resolveVar(v, depth + 1);
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
- return '';
- }
- );
- }
-
- function parseShorthand(text) {
- const m = text.trim().match(BORDER_SHORTHAND_RE);
- if (!m) return null;
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
- }
-
- // Read from the per-property accessors on rule.style. jsdom preserves
- // each border-* shorthand it parsed, even when the overall cssText has
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
- // `border-left: ...` loses the first declaration but keeps the second).
- const SIDE_PROPS = [
- ['borderLeft', 'Left'],
- ['borderRight', 'Right'],
- ['borderTop', 'Top'],
- ['borderBottom', 'Bottom'],
- ['borderInlineStart', 'Left'],
- ['borderInlineEnd', 'Right'],
- ];
-
- for (const sheet of document.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || []; } catch { continue; }
- for (const rule of rules) {
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
-
- const perSide = {};
-
- for (const [prop, side] of SIDE_PROPS) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const parsed = parseShorthand(resolveVar(val));
- if (parsed && parsed.color) perSide[side] = parsed;
- }
-
- // Uniform `border: <w> <style> var(...)` applies to every side the
- // per-side map didn't already claim.
- const borderAll = rule.style.border;
- if (borderAll && borderAll.includes('var(')) {
- const parsed = parseShorthand(resolveVar(borderAll));
- if (parsed && parsed.color) {
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
- if (!perSide[s]) perSide[s] = parsed;
- }
- }
- }
-
- // Longhand `border-*-color: var(...)` with width/style in separate
- // declarations. Rare in AI-generated pages, but cheap to cover.
- for (const [prop, side] of [
- ['borderLeftColor', 'Left'],
- ['borderRightColor', 'Right'],
- ['borderTopColor', 'Top'],
- ['borderBottomColor', 'Bottom'],
- ]) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const resolved = resolveVar(val).trim();
- if (!resolved) continue;
- // Width may or may not come from this rule — that's fine; the
- // adapter only substitutes the color when jsdom left it as a
- // literal var() string.
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
- }
-
- if (Object.keys(perSide).length === 0) continue;
-
- let matched;
- try { matched = document.querySelectorAll(rule.selectorText); }
- catch { continue; }
-
- for (const el of matched) {
- const existing = map.get(el);
- if (existing) {
- // Later rules overwrite earlier ones — approximates source-order
- // cascade for equal-specificity rules and is good enough for the
- // uncontested var()-dropped sides we're trying to recover.
- Object.assign(existing, perSide);
- } else {
- map.set(el, { ...perSide });
- }
- }
- }
- }
-
- return map;
-}
-
-// Strip `@layer NAME { … }` wrappers from a CSS / HTML source, leaving
-// the inner rules as flat CSS. jsdom doesn't implement CSS @layer, so
-// any rule inside a layer block becomes invisible to getComputedStyle.
-// Tailwind v4 makes this ubiquitous: every utility class lives in
-// `@layer utilities`, and Preflight lives in `@layer base`. Without
-// unwrapping, every Tailwind-styled element returns empty computed
-// styles. We walk the source character-by-character, balancing braces
-// so we correctly handle nested style rules inside the layer block.
-function unwrapCssAtLayer(source) {
- if (!source || !source.includes('@layer')) return source;
- // Find `@layer <name>? {` openers. The match starts at the @, and
- // we then balance braces from the opening { onward.
- const re = /@layer\b[^{;]*\{/g;
- let out = '';
- let lastIdx = 0;
- let m;
- while ((m = re.exec(source)) !== null) {
- const openStart = m.index;
- const openEnd = m.index + m[0].length; // position right after `{`
- let depth = 1;
- let i = openEnd;
- while (i < source.length && depth > 0) {
- const c = source.charCodeAt(i);
- if (c === 0x7b /* { */) depth++;
- else if (c === 0x7d /* } */) depth--;
- i++;
- }
- if (depth !== 0) {
- // Unbalanced — bail and return source unchanged.
- return source;
- }
- // Emit everything before the @layer, then the inner contents
- // (between the opening { and the matched closing }), then advance.
- out += source.slice(lastIdx, openStart);
- out += source.slice(openEnd, i - 1); // i-1 = position of the closing }
- lastIdx = i;
- re.lastIndex = i;
- }
- out += source.slice(lastIdx);
- return out;
-}
-
-// ---------------------------------------------------------------------------
-// Static HTML/CSS detection (default for local HTML files)
-// ---------------------------------------------------------------------------
-
-const STATIC_INHERITED_PROPS = new Set([
- 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight',
- 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'hyphens',
- 'webkitHyphens',
-]);
-
-const STATIC_DEFAULT_STYLE = {
- color: 'rgb(0, 0, 0)',
- backgroundColor: 'rgba(0, 0, 0, 0)',
- backgroundImage: 'none',
- borderTopWidth: '0px',
- borderRightWidth: '0px',
- borderBottomWidth: '0px',
- borderLeftWidth: '0px',
- borderTopColor: 'rgb(0, 0, 0)',
- borderRightColor: 'rgb(0, 0, 0)',
- borderBottomColor: 'rgb(0, 0, 0)',
- borderLeftColor: 'rgb(0, 0, 0)',
- borderRadius: '0px',
- boxShadow: 'none',
- fontFamily: '',
- fontSize: '16px',
- fontStyle: 'normal',
- fontWeight: '400',
- lineHeight: 'normal',
- letterSpacing: 'normal',
- textTransform: 'none',
- textAlign: 'start',
- hyphens: 'manual',
- webkitHyphens: 'manual',
- transitionProperty: '',
- transitionTimingFunction: '',
- animationName: '',
- animationTimingFunction: '',
- webkitBackgroundClip: '',
- backgroundClip: '',
- width: '',
- height: '',
- paddingTop: '0px',
- paddingRight: '0px',
- paddingBottom: '0px',
- paddingLeft: '0px',
- position: 'static',
- display: '',
-};
-
-const STATIC_PROP_MAP = {
- 'background-color': 'backgroundColor',
- 'background-image': 'backgroundImage',
- 'background-clip': 'backgroundClip',
- '-webkit-background-clip': 'webkitBackgroundClip',
- 'border-radius': 'borderRadius',
- 'border-top-width': 'borderTopWidth',
- 'border-right-width': 'borderRightWidth',
- 'border-bottom-width': 'borderBottomWidth',
- 'border-left-width': 'borderLeftWidth',
- 'border-top-color': 'borderTopColor',
- 'border-right-color': 'borderRightColor',
- 'border-bottom-color': 'borderBottomColor',
- 'border-left-color': 'borderLeftColor',
- 'box-shadow': 'boxShadow',
- 'font-family': 'fontFamily',
- 'font-size': 'fontSize',
- 'font-style': 'fontStyle',
- 'font-weight': 'fontWeight',
- 'line-height': 'lineHeight',
- 'letter-spacing': 'letterSpacing',
- 'text-transform': 'textTransform',
- 'text-align': 'textAlign',
- 'hyphens': 'hyphens',
- '-webkit-hyphens': 'webkitHyphens',
- 'transition-property': 'transitionProperty',
- 'transition-timing-function': 'transitionTimingFunction',
- 'animation-name': 'animationName',
- 'animation-timing-function': 'animationTimingFunction',
- 'width': 'width',
- 'height': 'height',
- 'padding-top': 'paddingTop',
- 'padding-right': 'paddingRight',
- 'padding-bottom': 'paddingBottom',
- 'padding-left': 'paddingLeft',
- 'position': 'position',
- 'display': 'display',
-};
-
-const STATIC_NAMED_COLORS = {
- black: { r: 0, g: 0, b: 0, a: 1 },
- white: { r: 255, g: 255, b: 255, a: 1 },
- transparent: { r: 0, g: 0, b: 0, a: 0 },
- gray: { r: 128, g: 128, b: 128, a: 1 },
- grey: { r: 128, g: 128, b: 128, a: 1 },
- silver: { r: 192, g: 192, b: 192, a: 1 },
- red: { r: 255, g: 0, b: 0, a: 1 },
- green: { r: 0, g: 128, b: 0, a: 1 },
- blue: { r: 0, g: 0, b: 255, a: 1 },
-};
-
-function splitCssList(value) {
- const parts = [];
- let depth = 0, quote = '', start = 0;
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; continue; }
- if (ch === '(' || ch === '[') depth++;
- else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);
- else if (ch === ',' && depth === 0) {
- parts.push(value.slice(start, i).trim());
- start = i + 1;
- }
- }
- const tail = value.slice(start).trim();
- if (tail) parts.push(tail);
- return parts;
-}
-
-function splitCssTokens(value) {
- const tokens = [];
- let depth = 0, quote = '', current = '';
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- current += ch;
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
- if (ch === '(') { depth++; current += ch; continue; }
- if (ch === ')') { depth = Math.max(0, depth - 1); current += ch; continue; }
- if (/\s/.test(ch) && depth === 0) {
- if (current) { tokens.push(current); current = ''; }
- continue;
- }
- current += ch;
- }
- if (current) tokens.push(current);
- return tokens;
-}
-
-function cssPropToCamel(prop) {
- if (!prop) return prop;
- const mapped = STATIC_PROP_MAP[prop];
- if (mapped) return mapped;
- return prop.replace(/-([a-z])/g, (_m, ch) => ch.toUpperCase());
-}
-
-function staticColorToCss(c) {
- if (!c) return '';
- if (c.a != null && c.a < 1) return `rgba(${c.r}, ${c.g}, ${c.b}, ${Number(c.a.toFixed(3))})`;
- return `rgb(${c.r}, ${c.g}, ${c.b})`;
-}
-
-function parseStaticColor(value) {
- const parsed = parseAnyColor(value);
- if (parsed) return parsed;
- const named = STATIC_NAMED_COLORS[String(value || '').trim().toLowerCase()];
- return named ? { ...named } : null;
-}
-
-function extractStaticColor(value) {
- if (!value) return '';
- const raw = String(value).trim();
- if (/^var\(/i.test(raw)) return raw;
- const colorLike = raw.match(/(?:rgba?\([^)]+\)|oklch\([^)]+\)|oklab\([^)]+\)|lch\([^)]+\)|lab\([^)]+\)|hsla?\([^)]+\)|hwb\([^)]+\)|#[0-9a-f]{3,8}\b|\b(?:black|white|gray|grey|silver|red|green|blue|transparent)\b)/i);
- if (!colorLike) return '';
- return colorLike[0];
-}
-
-function normalizeStaticCssValue(prop, value, customProps, parentStyle, currentStyle = null) {
- let resolved = resolveVarRefs(String(value || '').trim(), customProps);
- if (resolved === 'inherit') return parentStyle?.[prop] || STATIC_DEFAULT_STYLE[prop] || '';
- const isModernBorderColor = /^border[A-Z][a-z]+Color$/.test(prop) && /^(?:oklch|oklab|lch|lab|hsl|hwb)\(/i.test(resolved);
- if (!isModernBorderColor && (/color$/i.test(prop) || prop === 'color' || prop === 'backgroundColor')) {
- const parsed = parseStaticColor(resolved);
- if (parsed) resolved = staticColorToCss(parsed);
- }
- if (prop === 'fontSize') {
- const base = parseFloat(parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'letterSpacing') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'lineHeight' && resolved !== 'normal') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- return resolved;
-}
-
-function expandStaticBoxValues(tokens) {
- if (tokens.length === 0) return ['0px', '0px', '0px', '0px'];
- if (tokens.length === 1) return [tokens[0], tokens[0], tokens[0], tokens[0]];
- if (tokens.length === 2) return [tokens[0], tokens[1], tokens[0], tokens[1]];
- if (tokens.length === 3) return [tokens[0], tokens[1], tokens[2], tokens[1]];
- return [tokens[0], tokens[1], tokens[2], tokens[3]];
-}
-
-function parseStaticBorder(value) {
- const tokens = splitCssTokens(value);
- let width = '', color = '';
- for (const token of tokens) {
- if (!width && /^-?[\d.]+(?:px|rem|em|%)$/.test(token)) width = token;
- if (!color) color = extractStaticColor(token);
- }
- return { width, color };
-}
-
-function parseStaticFont(value) {
- const out = [];
- const slashParts = value.match(/(?:^|\s)([\d.]+(?:px|rem|em|%))(?:\/([^\s]+))?/);
- if (/\bitalic\b/i.test(value)) out.push(['fontStyle', 'italic']);
- const weight = value.match(/\b([1-9]00|bold|normal|lighter|bolder)\b/i);
- if (weight) out.push(['fontWeight', weight[1]]);
- if (slashParts) {
- out.push(['fontSize', slashParts[1]]);
- if (slashParts[2]) out.push(['lineHeight', slashParts[2]]);
- const familyStart = value.indexOf(slashParts[0]) + slashParts[0].length;
- const family = value.slice(familyStart).trim();
- if (family) out.push(['fontFamily', family]);
- }
- return out;
-}
-
-function parseStaticTransition(value) {
- const props = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const prop = tokens.find(token => /^[a-z-]+$/i.test(token) && !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none)$/.test(token) && !/s$/.test(token));
- if (prop) props.push(prop);
- }
- return {
- property: props.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function parseStaticAnimation(value) {
- const names = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const name = tokens.find(token =>
- /^[a-z_-][\w-]*$/i.test(token) &&
- !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none|running|paused)$/.test(token)
- );
- if (name) names.push(name);
- }
- return {
- name: names.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function expandStaticDeclaration(prop, value) {
- const p = prop.toLowerCase();
- const v = String(value || '').trim();
- if (!v) return [];
- if (p.startsWith('--')) return [[p, v]];
- if (p === 'background') {
- const out = [];
- const hasImage = /gradient|url\(/i.test(v);
- if (hasImage) out.push(['backgroundImage', v]);
- const beforeImage = hasImage ? v.split(/(?:repeating-)?(?:linear|radial|conic)-gradient\(|url\(/i)[0] : v;
- const color = extractStaticColor(hasImage ? beforeImage : v);
- if (color) out.push(['backgroundColor', color]);
- return out;
- }
- if (p === 'border') {
- const parsed = parseStaticBorder(v);
- const out = [];
- for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
- if (parsed.width) out.push([`border${side}Width`, parsed.width]);
- if (parsed.color) out.push([`border${side}Color`, parsed.color]);
- }
- return out;
- }
- const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
- if (sideMatch) {
- const parsed = parseStaticBorder(v);
- const side = sideMatch[1][0].toUpperCase() + sideMatch[1].slice(1);
- return [
- ...(parsed.width ? [[`border${side}Width`, parsed.width]] : []),
- ...(parsed.color ? [[`border${side}Color`, parsed.color]] : []),
- ];
- }
- if (p === 'border-width') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopWidth', vals[0]],
- ['borderRightWidth', vals[1]],
- ['borderBottomWidth', vals[2]],
- ['borderLeftWidth', vals[3]],
- ];
- }
- if (p === 'border-color') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopColor', vals[0]],
- ['borderRightColor', vals[1]],
- ['borderBottomColor', vals[2]],
- ['borderLeftColor', vals[3]],
- ];
- }
- if (p === 'padding') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['paddingTop', vals[0]],
- ['paddingRight', vals[1]],
- ['paddingBottom', vals[2]],
- ['paddingLeft', vals[3]],
- ];
- }
- if (p === 'font') return parseStaticFont(v);
- if (p === 'transition') {
- const parsed = parseStaticTransition(v);
- return [
- ...(parsed.property ? [['transitionProperty', parsed.property]] : []),
- ...(parsed.timing ? [['transitionTimingFunction', parsed.timing]] : []),
- ];
- }
- if (p === 'animation') {
- const parsed = parseStaticAnimation(v);
- return [
- ...(parsed.name ? [['animationName', parsed.name]] : []),
- ...(parsed.timing ? [['animationTimingFunction', parsed.timing]] : []),
- ];
- }
- const mapped = cssPropToCamel(p);
- if (STATIC_DEFAULT_STYLE[mapped] != null || STATIC_INHERITED_PROPS.has(mapped)) {
- return [[mapped, v]];
- }
- return [];
-}
-
-function compareStaticPriority(a, b) {
- if (!a) return true;
- if (!!b.important !== !!a.important) return !!b.important;
- if (!!b.inline !== !!a.inline) return !!b.inline;
- for (let i = 0; i < 3; i++) {
- if ((b.specificity[i] || 0) !== (a.specificity[i] || 0)) {
- return (b.specificity[i] || 0) > (a.specificity[i] || 0);
- }
- }
- return b.order >= a.order;
-}
-
-function staticSpecificity(selector) {
- const noWhere = selector.replace(/:where\([^)]*\)/g, '');
- const ids = (noWhere.match(/#[\w-]+/g) || []).length;
- const classes = (noWhere.match(/\.[\w-]+|\[[^\]]+\]|:(?!:)[\w-]+(?:\([^)]*\))?/g) || []).length;
- const stripped = noWhere
- .replace(/#[\w-]+/g, ' ')
- .replace(/\.[\w-]+|\[[^\]]+\]|:{1,2}[\w-]+(?:\([^)]*\))?/g, ' ')
- .replace(/[*>+~(),]/g, ' ');
- const types = (stripped.match(/\b[a-zA-Z][\w-]*\b/g) || []).length;
- return [ids, classes, types];
-}
-
-function applyStaticDeclaration(specified, node, prop, value, meta) {
- let map = specified.get(node);
- if (!map) { map = new Map(); specified.set(node, map); }
- for (const [expandedProp, expandedValue] of expandStaticDeclaration(prop, value)) {
- const existing = map.get(expandedProp);
- const next = { ...meta, prop: expandedProp, value: expandedValue };
- if (compareStaticPriority(existing, next)) map.set(expandedProp, next);
- }
-}
-
-function parseStaticStyleAttribute(styleText, orderBase = 0) {
- const decls = [];
- for (const part of String(styleText || '').split(';')) {
- const idx = part.indexOf(':');
- if (idx <= 0) continue;
- const prop = part.slice(0, idx).trim();
- let value = part.slice(idx + 1).trim();
- const important = /!important\s*$/i.test(value);
- value = value.replace(/\s*!important\s*$/i, '').trim();
- decls.push({ prop, value, important, order: orderBase + decls.length });
- }
- return decls;
-}
-
-function collectStaticCssRules(cssText, csstree) {
- const rules = [];
- let ast;
- try {
- ast = csstree.parse(cssText, { positions: false, parseValue: true, parseCustomProperty: false });
- } catch {
- return rules;
- }
- let order = 0;
- const walkList = (list, atRuleStack = []) => {
- list?.forEach?.(node => {
- if (node.type === 'Rule' && node.block) {
- if (atRuleStack.some(name => /keyframes$/i.test(name))) return;
- const selectorText = csstree.generate(node.prelude).trim();
- const declarations = [];
- node.block.children?.forEach?.(child => {
- if (child.type !== 'Declaration') return;
- declarations.push({
- prop: child.property,
- value: csstree.generate(child.value).trim(),
- important: !!child.important,
- });
- });
- for (const selector of splitCssList(selectorText)) {
- if (selector) rules.push({ selector, declarations, specificity: staticSpecificity(selector), order: order++ });
- }
- return;
- }
- if (node.type === 'Atrule' && node.block) {
- const name = String(node.name || '').toLowerCase();
- if (name === 'media' || name === 'supports' || name === 'layer') {
- walkList(node.block.children, [...atRuleStack, name]);
- }
- }
- });
- };
- walkList(ast.children);
- return rules;
-}
-
-class StaticElement {
- constructor(node, doc) {
- this.node = node;
- this._doc = doc;
- this.nodeType = 1;
- this.tagName = String(node.name || '').toUpperCase();
- this.nodeName = this.tagName;
- }
- get parentElement() {
- let cur = this.node.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- return cur ? this._doc.wrap(cur) : null;
- }
- get previousElementSibling() {
- let cur = this.node.prev;
- while (cur && cur.type !== 'tag') cur = cur.prev;
- return cur ? this._doc.wrap(cur) : null;
- }
- get children() {
- return (this.node.children || []).filter(child => child.type === 'tag').map(child => this._doc.wrap(child));
- }
- get childNodes() {
- return (this.node.children || []).map(child => {
- if (child.type === 'text') return { nodeType: 3, textContent: child.data || '' };
- if (child.type === 'tag') return this._doc.wrap(child);
- return { nodeType: 8, textContent: child.data || '' };
- });
- }
- get textContent() {
- return this._doc.domutils.textContent(this.node);
- }
- get className() {
- return this.getAttribute('class') || '';
- }
- get id() {
- return this.getAttribute('id') || '';
- }
- getAttribute(name) {
- return this.node.attribs?.[name] ?? null;
- }
- querySelector(selector) {
- try {
- const found = this._doc.selectOne(selector, this.node.children || []);
- return found ? this._doc.wrap(found) : null;
- } catch {
- return null;
- }
- }
- querySelectorAll(selector) {
- try {
- return this._doc.selectAll(selector, this.node.children || []).map(node => this._doc.wrap(node));
- } catch {
- return [];
- }
- }
- closest(selector) {
- let cur = this.node;
- while (cur && cur.type === 'tag') {
- try {
- if (this._doc.is(cur, selector)) return this._doc.wrap(cur);
- } catch {
- return null;
- }
- cur = cur.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- }
- return null;
- }
- contains(other) {
- let cur = other?.node || null;
- while (cur) {
- if (cur === this.node) return true;
- cur = cur.parent;
- }
- return false;
- }
-}
-
-class StaticDocument {
- constructor(root, modules) {
- this.root = root;
- this.selectAll = modules.selectAll;
- this.selectOne = modules.selectOne;
- this.is = modules.is;
- this.domutils = modules.domutils;
- this._wrappers = new WeakMap();
- this._styleMap = new WeakMap();
- }
- wrap(node) {
- let wrapped = this._wrappers.get(node);
- if (!wrapped) {
- wrapped = new StaticElement(node, this);
- this._wrappers.set(node, wrapped);
- }
- return wrapped;
- }
- querySelectorAll(selector) {
- try {
- return this.selectAll(selector, this.root.children || []).map(node => this.wrap(node));
- } catch {
- return [];
- }
- }
- querySelector(selector) {
- try {
- const found = this.selectOne(selector, this.root.children || []);
- return found ? this.wrap(found) : null;
- } catch {
- return null;
- }
- }
- get documentElement() {
- return this.querySelector('html');
- }
- get body() {
- return this.querySelector('body');
- }
- setStyle(node, style) {
- this._styleMap.set(node, style);
- }
- getStyle(el) {
- return this._styleMap.get(el.node) || makeStaticStyle();
- }
-}
-
-function makeStaticStyle(values = {}) {
- const style = { ...STATIC_DEFAULT_STYLE, ...values };
- style.getPropertyValue = (prop) => {
- const key = cssPropToCamel(prop);
- return style[key] || style[prop] || '';
- };
- return style;
-}
-
-function buildStaticWindow(staticDoc) {
- return {
- document: staticDoc,
- getComputedStyle: (el) => staticDoc.getStyle(el),
- };
-}
-
-function collectStaticCssText(root, fileDir, profile, filePath, modules) {
- const styleTexts = [];
- for (const styleEl of modules.selectAll('style', root.children || [])) {
- styleTexts.push(modules.domutils.textContent(styleEl));
- }
- const links = modules.selectAll('link', root.children || []);
- for (const link of links) {
- const rel = link.attribs?.rel || '';
- const href = link.attribs?.href || '';
- if (!/\bstylesheet\b/i.test(rel) || !href || /^(https?:)?\/\//i.test(href)) continue;
- const cssPath = path.resolve(fileDir, href);
- try {
- const css = profileStep(profile, {
- engine: 'static-html',
- phase: 'preprocess',
- ruleId: 'inline-linked-stylesheet',
- target: filePath,
- detail: href,
- }, () => fs.readFileSync(cssPath, 'utf-8'));
- styleTexts.push(css);
- } catch { /* skip unreadable */ }
- }
- return styleTexts.join('\n');
-}
-
-function buildStaticStyleMap(root, staticDoc, cssText, modules, profile, filePath) {
- const specified = new Map();
- const allNodes = modules.selectAll('*', root.children || []);
- const rules = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-css',
- ruleId: 'css-rules',
- target: filePath,
- }, () => collectStaticCssRules(cssText, modules.csstree));
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'css-selectors',
- target: filePath,
- }, () => {
- for (const rule of rules) {
- let matched;
- try {
- matched = modules.selectAll(rule.selector, root.children || []);
- } catch {
- recordProfileEvent(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'unsupported-selector',
- target: filePath,
- ms: 0,
- findings: 0,
- detail: rule.selector,
- });
- continue;
- }
- for (const node of matched) {
- for (const decl of rule.declarations) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: rule.specificity,
- order: rule.order,
- inline: false,
- });
- }
- }
- }
-
- let inlineOrder = rules.length + 1;
- for (const node of allNodes) {
- const styleText = node.attribs?.style;
- if (!styleText) continue;
- for (const decl of parseStaticStyleAttribute(styleText, inlineOrder)) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: [1, 0, 0],
- order: decl.order,
- inline: true,
- });
- }
- inlineOrder += 1000;
- }
- });
-
- const computeNode = (node, parentStyle = null, parentCustom = new Map()) => {
- const specifiedMap = specified.get(node) || new Map();
- const customProps = new Map(parentCustom);
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) customProps.set(prop, resolveVarRefs(decl.value, customProps));
- }
- const values = {};
- for (const prop of Object.keys(STATIC_DEFAULT_STYLE)) {
- if (STATIC_INHERITED_PROPS.has(prop) && parentStyle?.[prop] != null) values[prop] = parentStyle[prop];
- else values[prop] = STATIC_DEFAULT_STYLE[prop];
- }
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) continue;
- values[prop] = normalizeStaticCssValue(prop, decl.value, customProps, parentStyle, values);
- }
- const style = makeStaticStyle(values);
- staticDoc.setStyle(node, style);
- for (const child of node.children || []) {
- if (child.type === 'tag') computeNode(child, style, customProps);
- }
- };
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'cascade',
- ruleId: 'compute-styles',
- target: filePath,
- }, () => {
- for (const child of root.children || []) {
- if (child.type === 'tag') computeNode(child);
- }
- });
-}
-
-export {
- BORDER_SHORTHAND_RE,
- NAMED_COLORS,
- normalizeColorForCheck,
- buildBorderOverrideMap,
- unwrapCssAtLayer,
- STATIC_INHERITED_PROPS,
- STATIC_DEFAULT_STYLE,
- STATIC_PROP_MAP,
- STATIC_NAMED_COLORS,
- splitCssList,
- splitCssTokens,
- cssPropToCamel,
- staticColorToCss,
- parseStaticColor,
- extractStaticColor,
- normalizeStaticCssValue,
- expandStaticBoxValues,
- parseStaticBorder,
- parseStaticFont,
- parseStaticTransition,
- parseStaticAnimation,
- expandStaticDeclaration,
- compareStaticPriority,
- staticSpecificity,
- applyStaticDeclaration,
- parseStaticStyleAttribute,
- collectStaticCssRules,
- StaticElement,
- StaticDocument,
- makeStaticStyle,
- buildStaticWindow,
- collectStaticCssText,
- buildStaticStyleMap,
-};
@@ -1,174 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import {
- checkElementBorders,
- checkElementColors,
- checkElementGlow,
- checkElementHeroEyebrow,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementMotion,
- checkElementQuality,
- checkHtmlPatterns,
- checkPageLayout,
- checkPageQualityFromDoc,
- checkRepeatedSectionKickersFromDoc,
- resolveBackground,
- resolveBorderRadiusPx,
-} from '../../rules/checks.mjs';
-import { detectText } from '../regex/detect-text.mjs';
-import {
- StaticDocument,
- buildStaticStyleMap,
- buildStaticWindow,
- collectStaticCssText,
-} from './css-cascade.mjs';
-
-function checkStaticPageTypography(document, window) {
- const findings = [];
- const fonts = new Set();
- const overusedFound = new Set();
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span, div')) {
- const hasText = el.childNodes.some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const ff = window.getComputedStyle(el).fontFamily || '';
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
- if (fonts.size === 1 && document.querySelectorAll('*').length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div')) {
- const fontSize = parseFloat(window.getComputedStyle(el).fontSize);
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
- return findings;
-}
-
-const STATIC_ELEMENT_RULES = [
- { id: 'border-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementBorders(tag, style, null, resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window)) },
- { id: 'color-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementColors(el, style, tag, window, customPropMap, false) },
- { id: 'dark-glow', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window, customPropMap)) },
- { id: 'motion-rules', selector: '*', run: (el, tag, style) => checkElementMotion(tag, style) },
- { id: 'icon-tile-stack', selector: 'h1,h2,h3,h4,h5,h6', run: (el, tag, _style, window) => checkElementIconTile(el, tag, window) },
- { id: 'italic-serif-display', selector: 'h1,h2', run: (el, tag, style) => checkElementItalicSerif(el, style, tag) },
- { id: 'hero-eyebrow-chip', selector: 'h1', run: (el, tag, style, window, customPropMap) => checkElementHeroEyebrow(el, style, tag, window, customPropMap) },
- { id: 'quality-rules', selector: '*', run: (el, tag, style, window) => checkElementQuality(el, style, tag, window) },
-];
-
-async function detectHtml(filePath, options = {}) {
- const profile = options?.profile;
- const html = profileStep(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'read-html',
- target: filePath,
- }, () => fs.readFileSync(filePath, 'utf-8'));
-
- let modules;
- try {
- modules = await profileStepAsync(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'import-static-parser',
- target: filePath,
- }, async () => {
- const [htmlparser2, cssSelect, csstree, domutils] = await Promise.all([
- import('htmlparser2'),
- import('css-select'),
- import('css-tree'),
- import('domutils'),
- ]);
- return {
- parseDocument: htmlparser2.parseDocument,
- selectAll: cssSelect.selectAll,
- selectOne: cssSelect.selectOne,
- is: cssSelect.is,
- csstree,
- domutils,
- };
- });
- } catch {
- return detectText(html, filePath, options);
- }
-
- const resolvedPath = path.resolve(filePath);
- const fileDir = path.dirname(resolvedPath);
- const root = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-html',
- ruleId: 'parse-document',
- target: filePath,
- }, () => modules.parseDocument(html, { lowerCaseAttributeNames: false, lowerCaseTags: true }));
-
- const cssText = collectStaticCssText(root, fileDir, profile, filePath, modules);
- const document = new StaticDocument(root, modules);
- buildStaticStyleMap(root, document, cssText, modules, profile, filePath);
- const window = buildStaticWindow(document);
-
- const customPropMap = null;
-
- const findings = [];
- const runElementCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'element', ruleId, target: filePath }, callback)
- : callback();
-
- const visitedByRule = new Map();
- for (const rule of STATIC_ELEMENT_RULES) {
- const elements = document.querySelectorAll(rule.selector);
- visitedByRule.set(rule.id, elements.length);
- for (const el of elements) {
- const tag = el.tagName.toLowerCase();
- const style = window.getComputedStyle(el);
- for (const f of runElementCheck(rule.id, () => rule.run(el, tag, style, window, customPropMap))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
- }
-
- if (isFullPage(html)) {
- const runPageCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
- : callback();
- for (const f of runPageCheck('typography-rules', () => checkStaticPageTypography(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('repeated-section-kickers', () => checkRepeatedSectionKickersFromDoc(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('layout-rules', () => checkPageLayout(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('skipped-heading', () => checkPageQualityFromDoc(document))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('html-patterns', () => checkHtmlPatterns(html).filter(item =>
- item.id !== 'bounce-easing' && item.id !== 'layout-transition'
- ))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
-
- return findings;
-}
-
-export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -1,189 +0,0 @@
-function sanitizeScreenshotClip(clip, viewport) {
- if (!clip) return null;
- const x = Math.max(0, Math.floor(clip.x || 0));
- const y = Math.max(0, Math.floor(clip.y || 0));
- const width = Math.min(
- Math.max(1, Math.ceil(clip.width || 0)),
- Math.max(1, viewport?.width || 1600),
- );
- const height = Math.min(
- Math.max(1, Math.ceil(clip.height || 0)),
- 320,
- );
- if (width < 1 || height < 1) return null;
- return { x, y, width, height };
-}
-
-async function compareScreenshotContrast(page, beforeBase64, afterBase64, candidate) {
- return page.evaluate(async ({ beforeBase64, afterBase64, candidate }) => {
- const loadImage = (base64) => new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = () => reject(new Error('Could not decode contrast screenshot'));
- img.src = `data:image/png;base64,${base64}`;
- });
- const [before, after] = await Promise.all([loadImage(beforeBase64), loadImage(afterBase64)]);
- const width = Math.min(before.width, after.width);
- const height = Math.min(before.height, after.height);
- if (width < 1 || height < 1) return null;
-
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return null;
-
- ctx.drawImage(before, 0, 0, width, height);
- const beforePixels = ctx.getImageData(0, 0, width, height).data;
- ctx.clearRect(0, 0, width, height);
- ctx.drawImage(after, 0, 0, width, height);
- const afterPixels = ctx.getImageData(0, 0, width, height).data;
-
- const luminance = ({ r, g, b }) => {
- const convert = c => {
- const v = c / 255;
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
- };
- return 0.2126 * convert(r) + 0.7152 * convert(g) + 0.0722 * convert(b);
- };
- const ratio = (a, b) => {
- const l1 = luminance(a);
- const l2 = luminance(b);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
- };
-
- const cssTextColor = candidate.textColor && !candidate.preferRenderedForeground
- ? {
- r: candidate.textColor.r,
- g: candidate.textColor.g,
- b: candidate.textColor.b,
- }
- : null;
- const ratios = [];
- let glyphPixels = 0;
- let strongestDelta = 0;
- for (let i = 0; i < beforePixels.length; i += 4) {
- const delta = Math.abs(beforePixels[i] - afterPixels[i])
- + Math.abs(beforePixels[i + 1] - afterPixels[i + 1])
- + Math.abs(beforePixels[i + 2] - afterPixels[i + 2])
- + Math.abs(beforePixels[i + 3] - afterPixels[i + 3]);
- strongestDelta = Math.max(strongestDelta, delta);
- if (delta < 10) continue;
- glyphPixels++;
- const fg = cssTextColor || {
- r: beforePixels[i],
- g: beforePixels[i + 1],
- b: beforePixels[i + 2],
- };
- const bg = {
- r: afterPixels[i],
- g: afterPixels[i + 1],
- b: afterPixels[i + 2],
- };
- ratios.push(ratio(fg, bg));
- }
-
- if (ratios.length < 8) {
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: null,
- p10Ratio: null,
- medianRatio: null,
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: ratios[0],
- p10Ratio: pick(10),
- medianRatio: pick(50),
- };
- }, { beforeBase64, afterBase64, candidate });
-}
-
-async function captureVisualContrastCandidate(page, candidate, viewport) {
- const clip = sanitizeScreenshotClip(candidate.clip, viewport);
- if (!clip) return null;
-
- const beforeBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- const token = `impeccable-contrast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- const applied = await page.evaluate(({ selector, token, backgroundClipText }) => {
- let el;
- try {
- el = document.querySelector(selector);
- } catch {
- return false;
- }
- if (!el) return false;
- let style = document.getElementById('impeccable-visual-contrast-hide-style');
- if (!style) {
- style = document.createElement('style');
- style.id = 'impeccable-visual-contrast-hide-style';
- style.textContent = [
- '[data-impeccable-visual-contrast-target] {',
- ' color: transparent !important;',
- ' -webkit-text-fill-color: transparent !important;',
- ' text-shadow: none !important;',
- '}',
- '[data-impeccable-visual-contrast-target][data-impeccable-bgclip-text="true"] {',
- ' background-image: none !important;',
- '}',
- ].join('\n');
- document.head.appendChild(style);
- }
- el.setAttribute('data-impeccable-visual-contrast-target', token);
- if (backgroundClipText) el.setAttribute('data-impeccable-bgclip-text', 'true');
- return true;
- }, {
- selector: candidate.selector,
- token,
- backgroundClipText: candidate.backgroundClipText,
- });
- if (!applied) return null;
-
- let afterBase64;
- try {
- afterBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- } finally {
- await page.evaluate(({ selector }) => {
- try {
- const el = document.querySelector(selector);
- if (el) {
- el.removeAttribute('data-impeccable-visual-contrast-target');
- el.removeAttribute('data-impeccable-bgclip-text');
- }
- } catch {
- // Ignore invalid or stale selectors during cleanup.
- }
- }, { selector: candidate.selector }).catch(() => {});
- }
-
- const metrics = await compareScreenshotContrast(page, beforeBase64, afterBase64, candidate);
- if (!metrics || !Number.isFinite(metrics.p10Ratio) || metrics.glyphPixels < 8) return null;
- const measuredRatio = metrics.p10Ratio;
- if (measuredRatio >= candidate.threshold) return null;
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const reasonLabel = (candidate.reasons || []).slice(0, 3).join(', ') || 'visual background';
- return {
- id: 'low-contrast',
- snippet: `pixel contrast ${measuredRatio.toFixed(1)}:1 median ${metrics.medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) on ${reasonLabel}${textLabel}`,
- };
-}
-
-export {
- sanitizeScreenshotClip,
- compareScreenshotContrast,
- captureVisualContrastCandidate,
-};
@@ -1,12 +0,0 @@
-import { getAntipattern } from './registry/antipatterns.mjs';
-
-function getAP(id) {
- return getAntipattern(id);
-}
-
-function finding(id, filePath, snippet, line = 0) {
- const ap = getAP(id);
- return { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', file: filePath, line, snippet };
-}
-
-export { getAP, finding };
@@ -1,198 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-// ---------------------------------------------------------------------------
-// File walker
-// ---------------------------------------------------------------------------
-
-const SKIP_DIRS = new Set([
- 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
- '.svelte-kit', '__pycache__', '.turbo', '.vercel',
-]);
-
-const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
- '.jsx', '.tsx', '.js', '.ts',
- '.vue', '.svelte', '.astro',
-]);
-
-const HTML_EXTENSIONS = new Set(['.html', '.htm']);
-
-function walkDir(dir) {
- const files = [];
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
- for (const entry of entries) {
- if (SKIP_DIRS.has(entry.name)) continue;
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) files.push(...walkDir(full));
- else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
- }
- return files;
-}
-
-
-// ---------------------------------------------------------------------------
-// Import graph (multi-file awareness)
-// ---------------------------------------------------------------------------
-
-function resolveImport(specifier, fromDir, fileSet) {
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
- const base = path.resolve(fromDir, specifier);
- if (fileSet.has(base)) return base;
- for (const ext of SCANNABLE_EXTENSIONS) {
- const withExt = base + ext;
- if (fileSet.has(withExt)) return withExt;
- }
- // index file convention
- for (const ext of SCANNABLE_EXTENSIONS) {
- const indexFile = path.join(base, 'index' + ext);
- if (fileSet.has(indexFile)) return indexFile;
- }
- return null;
-}
-
-function buildImportGraph(files) {
- const fileSet = new Set(files);
- const graph = new Map();
-
- for (const file of files) {
- const content = fs.readFileSync(file, 'utf-8');
- const dir = path.dirname(file);
- const imports = new Set();
-
- // ES imports: import ... from '...' and import '...'
- const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
- let m;
- while ((m = esRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // CSS @import
- const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
- while ((m = cssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // SCSS @use / @forward
- const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
- while ((m = scssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- graph.set(file, imports);
- }
- return graph;
-}
-
-// ---------------------------------------------------------------------------
-// Framework dev server detection
-// ---------------------------------------------------------------------------
-
-const FRAMEWORK_CONFIGS = [
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /next/i } },
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-sveltekit-page', value: null } },
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /@vite\/client/ } },
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /astro/i } },
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
- portRe: /"port"\s*:\s*(\d+)/,
- fingerprint: { body: /ng-version/i } },
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
-];
-
-function detectFrameworkConfig(dir) {
- let entries;
- try { entries = fs.readdirSync(dir); } catch { return null; }
- const entrySet = new Set(entries);
-
- for (const cfg of FRAMEWORK_CONFIGS) {
- const match = cfg.files.find(f => entrySet.has(f));
- if (!match) continue;
-
- const configPath = path.join(dir, match);
- let port = cfg.defaultPort;
- try {
- const content = fs.readFileSync(configPath, 'utf-8');
- const portMatch = content.match(cfg.portRe);
- if (portMatch) port = parseInt(portMatch[1], 10);
- } catch { /* use default */ }
-
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
- }
- return null;
-}
-
-/**
- * Check if a port is listening and optionally verify it matches the expected framework.
- * Returns { listening: true, matched: true/false } or { listening: false }.
- */
-async function isPortListening(port, fingerprint = null) {
- if (!fingerprint) {
- // Simple TCP probe fallback
- const net = await import('node:net');
- return new Promise((resolve) => {
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
- sock.setTimeout(500);
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
- sock.on('error', () => resolve({ listening: false }));
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
- });
- }
-
- // HTTP probe with fingerprint matching
- try {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 2000);
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
- clearTimeout(timeout);
-
- // Check header fingerprint
- if (fingerprint.header) {
- const val = res.headers.get(fingerprint.header);
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
- return { listening: true, matched: true };
- }
- }
-
- // Check body fingerprint
- if (fingerprint.body) {
- const body = await res.text();
- if (fingerprint.body.test(body)) {
- return { listening: true, matched: true };
- }
- }
-
- // Port is listening but doesn't match the expected framework
- return { listening: true, matched: false };
- } catch {
- return { listening: false };
- }
-}
-
-export {
- SKIP_DIRS,
- SCANNABLE_EXTENSIONS,
- HTML_EXTENSIONS,
- walkDir,
- resolveImport,
- buildImportGraph,
- FRAMEWORK_CONFIGS,
- detectFrameworkConfig,
- isPortListening,
-};
@@ -1,166 +0,0 @@
-function profileNow() {
- return typeof performance !== 'undefined' && performance.now
- ? performance.now()
- : Date.now();
-}
-
-function createDetectorProfile() {
- return { events: [] };
-}
-
-function recordProfileEvent(profile, event) {
- if (!profile) return;
- const normalized = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- ms: Number.isFinite(event.ms) ? event.ms : 0,
- findings: Number.isFinite(event.findings) ? event.findings : 0,
- };
- if (event.detail) normalized.detail = event.detail;
- if (Array.isArray(event.findingIds) && event.findingIds.length) {
- normalized.findingIds = event.findingIds;
- }
- if (typeof profile === 'function') {
- profile(normalized);
- } else if (typeof profile.record === 'function') {
- profile.record(normalized);
- } else if (Array.isArray(profile.events)) {
- profile.events.push(normalized);
- } else if (Array.isArray(profile)) {
- profile.push(normalized);
- }
-}
-
-function extractFindingIds(findings) {
- if (!Array.isArray(findings) || findings.length === 0) return [];
- return [...new Set(findings.map(f => f?.id || f?.type || f?.antipattern).filter(Boolean))];
-}
-
-function profileFindings(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-function profileStep(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-async function profileFindingsAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = await callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-async function profileStepAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return await callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-function percentile(sortedValues, pct) {
- if (!sortedValues.length) return 0;
- const idx = Math.min(
- sortedValues.length - 1,
- Math.max(0, Math.ceil((pct / 100) * sortedValues.length) - 1),
- );
- return sortedValues[idx];
-}
-
-function summarizeDetectorProfile(profile) {
- const events = Array.isArray(profile)
- ? profile
- : (Array.isArray(profile?.events) ? profile.events : []);
- const groups = new Map();
- for (const event of events) {
- const key = [
- event.engine || 'unknown',
- event.phase || 'unknown',
- event.ruleId || 'unknown',
- event.target || '',
- ].join('\u0000');
- let group = groups.get(key);
- if (!group) {
- group = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- calls: 0,
- totalMs: 0,
- findings: 0,
- samples: [],
- };
- groups.set(key, group);
- }
- const ms = Number.isFinite(event.ms) ? event.ms : 0;
- group.calls += 1;
- group.totalMs += ms;
- group.findings += Number.isFinite(event.findings) ? event.findings : 0;
- group.samples.push(ms);
- }
- return [...groups.values()]
- .map(group => {
- const samples = group.samples.sort((a, b) => a - b);
- return {
- engine: group.engine,
- phase: group.phase,
- ruleId: group.ruleId,
- target: group.target,
- calls: group.calls,
- totalMs: Number(group.totalMs.toFixed(3)),
- avgMs: Number((group.totalMs / group.calls).toFixed(3)),
- p50: Number(percentile(samples, 50).toFixed(3)),
- p95: Number(percentile(samples, 95).toFixed(3)),
- findings: group.findings,
- };
- })
- .sort((a, b) => b.totalMs - a.totalMs);
-}
-
-export {
- profileNow,
- createDetectorProfile,
- recordProfileEvent,
- extractFindingIds,
- profileFindings,
- profileStep,
- profileFindingsAsync,
- profileStepAsync,
- percentile,
- summarizeDetectorProfile,
-};
@@ -1,278 +0,0 @@
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-const RULE_ENGINE_SUPPORT = {
- regex: new Set(['source', 'page-analyzer']),
- 'static-html': new Set(['element', 'page']),
- browser: new Set(['element', 'page', 'layout']),
- visual: new Set(['visual-contrast']),
-};
-
-function getAntipattern(id) {
- return ANTIPATTERNS.find(rule => rule.id === id);
-}
-
-function getRulesForCategory(category) {
- return ANTIPATTERNS.filter(rule => rule.category === category);
-}
-
-function getRuleEngineSupport(engine) {
- return RULE_ENGINE_SUPPORT[engine] || new Set();
-}
-
-export {
- ANTIPATTERNS,
- RULE_ENGINE_SUPPORT,
- getAntipattern,
- getRulesForCategory,
- getRuleEngineSupport,
-};
@@ -1,1948 +0,0 @@
-import {
- BORDER_SAFE_TAGS,
- GENERIC_FONTS,
- KNOWN_SERIF_FONTS,
- OVERUSED_FONTS,
- SAFE_TAGS,
- WCAG_LARGE_BOLD_TEXT_PX,
- WCAG_LARGE_TEXT_PX,
- isBrandFontOnOwnDomain,
-} from '../shared/constants.mjs';
-import {
- colorToHex,
- contrastRatio,
- getHue,
- hasChroma,
- isNeutralColor,
- parseGradientColors,
- parseRgb,
- relativeLuminance,
-} from '../shared/color.mjs';
-
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-export {
- checkBorders,
- isEmojiOnlyText,
- checkColors,
- isCardLikeFromProps,
- checkIconTile,
- resolveSerif,
- checkItalicSerif,
- isAccentColor,
- checkHeroEyebrow,
- checkRepeatedSectionKickers,
- checkMotion,
- checkGlow,
- checkHtmlPatterns,
- readOwnBackgroundColor,
- resolveBackground,
- resolveGradientStops,
- parseRadiusToPx,
- resolveBorderRadiusPx,
- checkElementBordersDOM,
- checkElementColorsDOM,
- checkElementIconTileDOM,
- checkElementItalicSerifDOM,
- checkElementHeroEyebrowDOM,
- buildCustomPropMap,
- resolveVarRefs,
- oklchToRgb,
- parseAnyColor,
- parseColorResolved,
- cleanInlineText,
- isRepeatedKickerCandidate,
- collectRepeatedSectionKickerCandidates,
- checkRepeatedSectionKickersDOM,
- checkElementMotionDOM,
- checkElementGlowDOM,
- checkElementAIPaletteDOM,
- resolveFontSizePx,
- resolveLengthPx,
- checkQuality,
- checkElementQualityDOM,
- checkPageQualityFromDoc,
- checkPageQualityDOM,
- checkElementQuality,
- checkElementBorders,
- checkElementColors,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementHeroEyebrow,
- checkRepeatedSectionKickersFromDoc,
- checkElementMotion,
- checkElementGlow,
- checkTypography,
- isCardLikeDOM,
- checkLayout,
- checkPageTypography,
- isCardLike,
- checkPageLayout,
-};
@@ -1,124 +0,0 @@
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-export {
- isNeutralColor,
- parseRgb,
- relativeLuminance,
- contrastRatio,
- parseGradientColors,
- hasChroma,
- getHue,
- colorToHex,
-};
@@ -1,101 +0,0 @@
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-export {
- SAFE_TAGS,
- BORDER_SAFE_TAGS,
- OVERUSED_FONTS,
- GOOGLE_DOMAINS,
- VERCEL_DOMAINS,
- GITHUB_DOMAINS,
- BRAND_FONT_DOMAINS,
- isBrandFontOnOwnDomain,
- GENERIC_FONTS,
- WCAG_LARGE_TEXT_PX,
- WCAG_LARGE_BOLD_TEXT_PX,
- KNOWN_SERIF_FONTS,
-};
@@ -1,7 +0,0 @@
-/** Check if content looks like a full page (not a component/partial) */
-function isFullPage(content) {
- const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
- return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
-}
-
-export { isFullPage };
@@ -1,110 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-export const IMPECCABLE_DIR = '.impeccable';
-export const LIVE_DIR = 'live';
-export const CRITIQUE_DIR = 'critique';
-
-export function getImpeccableDir(cwd = process.cwd()) {
- return path.join(cwd, IMPECCABLE_DIR);
-}
-
-export function getDesignSidecarPath(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), 'design.json');
-}
-
-export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {
- const candidates = [
- getDesignSidecarPath(cwd),
- path.join(cwd, 'DESIGN.json'),
- ];
- const contextLegacy = path.join(contextDir, 'DESIGN.json');
- if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
- return candidates;
-}
-
-export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
- return firstExisting(getDesignSidecarCandidates(cwd, contextDir));
-}
-
-export function getLiveDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), LIVE_DIR);
-}
-
-export function getLiveConfigPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'config.json');
-}
-
-export function getLegacyLiveConfigPath(scriptsDir) {
- return path.join(scriptsDir, 'config.json');
-}
-
-export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {
- if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
- const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
- return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
- }
- const primary = getLiveConfigPath(cwd);
- if (fs.existsSync(primary)) return primary;
- if (scriptsDir) {
- const legacy = getLegacyLiveConfigPath(scriptsDir);
- if (fs.existsSync(legacy)) return legacy;
- }
- return primary;
-}
-
-export function getLiveServerPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'server.json');
-}
-
-export function getLegacyLiveServerPath(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live.json');
-}
-
-export function readLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try {
- return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };
- } catch {
- /* try next */
- }
- }
- return null;
-}
-
-export function writeLiveServerInfo(cwd = process.cwd(), info) {
- const filePath = getLiveServerPath(cwd);
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- fs.writeFileSync(filePath, JSON.stringify(info));
- return filePath;
-}
-
-export function removeLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try { fs.unlinkSync(filePath); } catch {}
- }
-}
-
-export function getLiveSessionsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'sessions');
-}
-
-export function getLegacyLiveSessionsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'sessions');
-}
-
-export function getLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'annotations');
-}
-
-export function getCritiqueDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), CRITIQUE_DIR);
-}
-
-export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'annotations');
-}
-
-function firstExisting(paths) {
- return paths.find((filePath) => fs.existsSync(filePath)) || null;
-}
@@ -1,69 +0,0 @@
-/**
- * Decide whether a given file is "generated" (regenerated by a build step,
- * unsafe to write variants into) or "source" (safe to edit, changes persist).
- *
- * Why this matters: when the user picks an element on a page whose underlying
- * file is regenerated by a build step (e.g. `scripts/build-sub-pages.js`
- * rewriting `public/docs/*.html`), writing variants or accepted changes into
- * that file is silent data loss — the next build wipes them.
- *
- * Signals, in order of reliability:
- * 1. Git check-ignore: gitignored files are assumed generated.
- * 2. File-header markers ("GENERATED", "DO NOT EDIT", "AUTO-GENERATED")
- * within the first ~300 characters — catches non-git projects.
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-
-const HEADER_SCAN_BYTES = 300;
-const HEADER_MARKERS = [
- /@generated\b/i,
- /\bGENERATED\s+FILE\b/,
- /\bAUTO-?GENERATED\b/i,
- /\bDO\s+NOT\s+EDIT\b/i,
-];
-
-/**
- * @param {string} filePath - absolute or cwd-relative path
- * @param {object} [options]
- * @param {string} [options.cwd] - project root (defaults to process.cwd())
- */
-export function isGeneratedFile(filePath, options = {}) {
- const cwd = options.cwd || process.cwd();
- const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
-
- if (isGitIgnored(absPath, cwd)) return true;
- if (hasGeneratedHeader(absPath)) return true;
- return false;
-}
-
-function isGitIgnored(absPath, cwd) {
- try {
- execSync(`git check-ignore --quiet ${JSON.stringify(absPath)}`, {
- cwd,
- stdio: 'ignore',
- });
- return true; // exit 0 = ignored
- } catch (err) {
- // Exit code 1 = not ignored. Exit code 128 = not a git repo or other error.
- // In both cases, treat as "not known to be ignored."
- return false;
- }
-}
-
-function hasGeneratedHeader(absPath) {
- let fd;
- try {
- fd = fs.openSync(absPath, 'r');
- const buf = Buffer.alloc(HEADER_SCAN_BYTES);
- const bytesRead = fs.readSync(fd, buf, 0, HEADER_SCAN_BYTES, 0);
- const head = buf.slice(0, bytesRead).toString('utf-8');
- return HEADER_MARKERS.some((re) => re.test(head));
- } catch {
- return false;
- } finally {
- if (fd !== undefined) { try { fs.closeSync(fd); } catch {} }
- }
-}
@@ -1,595 +0,0 @@
-/**
- * CLI helper: deterministic accept/discard of variant sessions.
- *
- * Usage:
- * node live-accept.mjs --id SESSION_ID --discard
- * node live-accept.mjs --id SESSION_ID --variant N
- *
- * For discard: removes the entire variant wrapper and restores the original.
- * For accept: replaces the wrapper with the chosen variant's content. If the
- * session had a colocated <style> block, it's preserved with carbonize markers
- * for a background agent to integrate into the project's CSS.
- *
- * Output: JSON to stdout.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-export async function acceptCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-accept.mjs [options]
-
-Deterministic accept/discard for live variant sessions.
-
-Modes:
- --discard Remove variants, restore original
- --variant N Accept variant N, discard the rest
-
-Required:
- --id SESSION_ID Session ID of the variant wrapper
-
-Output (JSON):
- { handled, file, carbonize }`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const variantNum = argVal(args, '--variant');
- const paramValuesRaw = argVal(args, '--param-values');
- const isDiscard = args.includes('--discard');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }
-
- let paramValues = null;
- if (paramValuesRaw) {
- try { paramValues = JSON.parse(paramValuesRaw); }
- catch { paramValues = null; } // malformed blob: skip the comment rather than failing the accept
- }
-
- // Find the file containing this session's markers
- const found = findSessionFile(id, process.cwd());
- if (!found) {
- console.log(JSON.stringify({ handled: false, error: 'Session markers not found for id: ' + id }));
- process.exit(0);
- }
-
- const { file: targetFile, content, lines } = found;
- const relFile = path.relative(process.cwd(), targetFile);
-
- // Bail if the session lives in a generated file. The agent manually wrote
- // the wrapper there for preview, and is responsible for writing the
- // accepted variant to true source (or cleaning up on discard). See
- // "Handle fallback" in live.md.
- if (isGeneratedFile(targetFile, { cwd: process.cwd() })) {
- console.log(JSON.stringify({
- handled: false,
- mode: 'fallback',
- file: relFile,
- hint: 'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.',
- }));
- process.exit(0);
- }
-
- if (isDiscard) {
- const result = handleDiscard(id, lines, targetFile);
- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));
- } else {
- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);
- // Single-line attention-grabber when cleanup is required. The full
- // five-step checklist lives in reference/live.md (loaded once per
- // session); repeating it per-event would waste tokens.
- if (result.carbonize) {
- result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + relFile + '. See reference/live.md "Required after accept".';
- }
- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));
- }
-}
-
-// ---------------------------------------------------------------------------
-// Discard
-// ---------------------------------------------------------------------------
-
-function handleDiscard(id, lines, targetFile) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const original = extractOriginal(lines, block);
- const isJsx = detectCommentSyntax(targetFile).open === '{/*';
- const replaceRange = expandReplaceRange(block, lines, isJsx);
-
- // Restore at the line we're actually replacing FROM, not the marker line.
- // For JSX wrappers the marker comments live INSIDE the outer `<div>`, so
- // `block.start` sits 2 spaces deeper than the original element. Using that
- // as the deindent base would push the restored content 2 spaces too far
- // right on every JSX/TSX session. `replaceRange.start` is the outer wrapper
- // line, which is at the original element's indent for both HTML and JSX.
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
- const restored = deindentContent(original, indent);
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...restored,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
- return {};
-}
-
-// ---------------------------------------------------------------------------
-// Accept
-// ---------------------------------------------------------------------------
-
-function handleAccept(id, variantNum, lines, targetFile, paramValues) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const commentSyntax = detectCommentSyntax(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- // Anchor indent on the line we're replacing FROM (the outer wrapper),
- // not on `block.start` — for JSX that's the marker comment 2 spaces
- // deeper than the original element. See handleDiscard for the full
- // rationale.
- const replaceRange = expandReplaceRange(block, lines, isJsx);
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
-
- // Extract the chosen variant's inner content
- const variantContent = extractVariant(lines, block, variantNum);
- if (!variantContent) return { handled: false, error: 'Variant ' + variantNum + ' not found' };
-
- // Extract CSS block if present
- const cssContent = extractCss(lines, block, id);
-
- // Check if carbonizing is needed:
- // - CSS block exists, OR
- // - variant HTML contains helper classes/attributes that need cleanup
- const variantText = variantContent.join('\n');
- const hasHelperAttrs = variantText.includes('data-impeccable-variant');
- const needsCarbonize = !!(cssContent || hasHelperAttrs);
-
- // Build the replacement
- const restored = deindentContent(variantContent, indent);
- const replacement = [];
-
- if (cssContent) {
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
- // JSX targets need the CSS body wrapped in a template literal so that the
- // `{` and `}` in CSS rules don't get parsed as JSX expressions.
- replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
- // Re-indent CSS content to match
- for (const cssLine of cssContent) {
- replacement.push(indent + cssLine.trimStart());
- }
- replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
- if (paramValues && Object.keys(paramValues).length > 0) {
- // Preserve the user's knob positions for the carbonize-cleanup agent
- // to bake into the final CSS when it collapses scoped rules.
- replacement.push(indent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close);
- }
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close);
- }
-
- // Keep the `@scope ([data-impeccable-variant="N"])` selectors in the
- // carbonize CSS block working visually by re-wrapping the accepted content
- // in a data-impeccable-variant="N" div with `display: contents` (so layout
- // isn't affected). The carbonize agent strips this attribute + wrapper when
- // it moves the CSS to a proper stylesheet.
- //
- // Style attribute syntax has to follow the host file's flavor — JSX files
- // need the object form, otherwise React 19 throws "Failed to set indexed
- // property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
- if (cssContent) {
- const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
- replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
- replacement.push(...restored);
- replacement.push(indent + '</div>');
- } else {
- replacement.push(...restored);
- }
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...replacement,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- return { carbonize: needsCarbonize };
-}
-
-// ---------------------------------------------------------------------------
-// Parsing helpers
-// ---------------------------------------------------------------------------
-
-/**
- * Find the start/end marker lines for a session.
- * Returns { start, end } (0-indexed line numbers) or null.
- */
-function findMarkerBlock(id, lines) {
- let start = -1;
- let end = -1;
- const startPattern = 'impeccable-variants-start ' + id;
- const endPattern = 'impeccable-variants-end ' + id;
-
- for (let i = 0; i < lines.length; i++) {
- if (start === -1 && lines[i].includes(startPattern)) start = i;
- if (lines[i].includes(endPattern)) { end = i; break; }
- }
-
- return (start !== -1 && end !== -1) ? { start, end } : null;
-}
-
-/**
- * Compute the line range to REPLACE (vs. just the marker range to extract
- * from). For JSX/TSX wrappers, live-wrap places the marker comments INSIDE
- * the `<div data-impeccable-variants="ID">` outer wrapper so the picked
- * element's JSX slot keeps a single child — a Fragment `<></>` would have
- * solved the multi-sibling case but failed inside `asChild` / cloneElement
- * parents with "Invalid prop supplied to React.Fragment".
- *
- * That means the marker block is enclosed by the wrapper `<div>` opener
- * (with `data-impeccable-variants="ID"`) and its matching `</div>`. We
- * walk back to the opener and forward to the closer so accept/discard
- * remove the entire scaffold, not just the inner markers.
- *
- * Marker lines themselves stay where they were so extractOriginal /
- * extractVariant / extractCss continue to walk the same range.
- */
-function expandReplaceRange(block, lines, isJsx) {
- if (!isJsx) return { start: block.start, end: block.end };
-
- let { start, end } = block;
-
- // Walk back for the wrapper `<div data-impeccable-variants="..."` opener.
- // The attr may sit on a continuation line of a multi-line opening tag, so
- // also walk to the line that actually contains `<div`.
- for (let i = start - 1; i >= Math.max(0, start - 12); i--) {
- if (/data-impeccable-variants=/.test(lines[i])) {
- let opener = i;
- while (opener > 0 && !/<div\b/.test(lines[opener])) opener--;
- start = opener;
- break;
- }
- }
-
- // Walk forward to the matching `</div>` by div-depth tracking from the
- // wrapper opener. Operate on JOINED text instead of per-line: a
- // multi-line self-closing JSX `<div\n className="spacer"\n/>` would
- // fool per-line regex tracking (the `<div` line matches openRe but the
- // `/>` line never matches selfCloseRe since it needs `<div` on the same
- // line). That left depth permanently over-counted and the wrapper's
- // outer `</div>` orphaned after accept/discard. Single regex with
- // `[^>]*?` (which spans newlines in JS) handles either form correctly.
- const joined = lines.slice(start).join('\n');
- // Match either `<div … />` (self-close, group 1 is `/`), `<div … >`
- // (open, group 1 is empty), or `</div>`.
- const tagRe = /<div\b[^>]*?(\/?)>|<\/div\s*>/g;
- let depth = 0;
- let m;
- while ((m = tagRe.exec(joined)) !== null) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && m[1] === '/';
- if (isClose) depth--;
- else if (!isSelfClose) depth++;
- if (depth <= 0) {
- // m.index is offset within `joined`; convert back to a file line.
- const linesBefore = joined.slice(0, m.index + m[0].length).split('\n').length - 1;
- const candidateEnd = start + linesBefore;
- if (candidateEnd >= end) {
- end = candidateEnd;
- break;
- }
- }
- }
-
- return { start, end };
-}
-
-/**
- * Join wrapper lines into a single string with `<style>` elements removed so
- * marker matching and div-depth tracking aren't confused by:
- * - CSS `@scope ([data-impeccable-variant="N"])` strings that look like the
- * HTML marker we're searching for
- * - JSX self-closing `<style ... />` (no separate `</style>` to close on)
- * - Same-line `<style>…</style>` blocks
- * - Multi-line `<style>\n…\n</style>` blocks
- */
-function stripStyleAndJoin(lines, block) {
- const out = [];
- let inStyle = false;
- for (let i = block.start; i <= block.end; i++) {
- let line = lines[i];
-
- if (!inStyle) {
- // Strip any complete <style> elements on this line (self-closed or
- // same-line-closed), including their body content.
- line = line
- .replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/g, '')
- .replace(/<style\b[^>]*\/\s*>/g, '');
-
- // If a <style> opener remains (multi-line body starts here), strip from
- // the opener to end-of-line and flip into skip mode.
- const openerIdx = line.search(/<style\b/);
- if (openerIdx !== -1) {
- line = line.slice(0, openerIdx);
- inStyle = true;
- }
- out.push(line);
- } else {
- // In multi-line style body; drop everything until we see </style>.
- const closeIdx = line.search(/<\/style\s*>/);
- if (closeIdx !== -1) {
- inStyle = false;
- out.push(line.slice(closeIdx).replace(/<\/style\s*>/, ''));
- }
- // else: skip line entirely
- }
- }
- return out.join('\n');
-}
-
-/**
- * Find the inner content of `<TAG ...attrMatch...>…</TAG>` inside `text`,
- * handling nested same-tag elements via depth counting. `attrMatch` is a
- * regex source fragment that must appear inside the opener tag.
- * Returns the inner string (may be empty), or null if not found.
- */
-function extractInnerByAttr(text, attrMatch) {
- const openerRe = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*' + attrMatch + '[^>]*>');
- const openMatch = text.match(openerRe);
- if (!openMatch) return null;
-
- const tagName = openMatch[1];
- const innerStart = openMatch.index + openMatch[0].length;
-
- // Match any opener or closer of this tag name after innerStart.
- // (Does not match self-closing <TAG … />, which doesn't contribute to depth.)
- const tagRe = new RegExp('<(?:/)?' + tagName + '\\b[^>]*>', 'g');
- tagRe.lastIndex = innerStart;
-
- let depth = 1;
- let m;
- while ((m = tagRe.exec(text))) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && /\/\s*>$/.test(m[0]);
- if (isClose) {
- depth--;
- if (depth === 0) return text.slice(innerStart, m.index);
- } else if (!isSelfClose) {
- depth++;
- }
- }
- return null;
-}
-
-/**
- * Extract the original element content from within the variant wrapper.
- * Returns an array of lines.
- */
-function extractOriginal(lines, block) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="original"');
- if (inner === null) return [];
- return inner.split('\n');
-}
-
-/**
- * Extract a specific variant's inner content (stripping the wrapper div).
- * Returns an array of lines, or null if not found.
- */
-function extractVariant(lines, block, variantNum) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + variantNum + '"');
- if (inner === null) return null;
- const result = inner.split('\n');
- // Collapse a lone empty leading/trailing line (common after string splice).
- while (result.length > 1 && result[0].trim() === '') result.shift();
- while (result.length > 1 && result[result.length - 1].trim() === '') result.pop();
- return result.length > 0 ? result : null;
-}
-
-/**
- * Extract the colocated <style> block content (between the style tags).
- * Returns an array of CSS lines, or null if no style block found.
- *
- * Handles three shapes of `<style data-impeccable-css="ID" ...>`:
- * 1. Self-closing: `<style ... />` — no body; return null (nothing to carbonize).
- * 2. Same-line open+close: `<style>...</style>` — return the inner content.
- * 3. Multi-line: `<style>` on one line, `</style>` on a later line — return
- * the lines between them.
- */
-function extractCss(lines, block, id) {
- const styleAttr = 'data-impeccable-css="' + id + '"';
- let inStyle = false;
- const content = [];
-
- for (let i = block.start; i <= block.end; i++) {
- const line = lines[i];
-
- if (!inStyle && line.includes(styleAttr)) {
- // Self-closing: nothing to carbonize.
- if (/<style\b[^>]*\/\s*>/.test(line)) return null;
- // Same-line open + close: extract inner text.
- const sameLine = line.match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/);
- if (sameLine) {
- const inner = stripJsxTemplateWrap(sameLine[1]);
- return inner.length > 0 ? inner.split('\n') : null;
- }
- inStyle = true;
- continue; // skip the <style> opening tag
- }
-
- if (inStyle) {
- // Detect </style> anywhere on the line — JSX template-literal closes
- // (`}</style>`) put the close mid-line, and we don't want to absorb the
- // template-literal punctuation as CSS content.
- const closeIdx = line.indexOf('</style>');
- if (closeIdx !== -1) break;
- content.push(line);
- }
- }
-
- if (content.length === 0) return null;
- return stripJsxTemplateLines(content);
-}
-
-/**
- * Strip a JSX template-literal wrap (`{` … `}`) from CSS extracted out of a
- * `<style>` element in a JSX/TSX file. The agent may write the wrap with
- * `{` and `}` directly attached to the `<style>` tags, on their own lines,
- * or attached to the first/last CSS lines — all three are JSX-legal.
- *
- * Stripping is required because handleAccept re-wraps the CSS itself when
- * carbonizing. Without this, two consecutive accepts (or a previously-
- * accepted variants block being carbonized) would produce nested
- * `{` `{` … `}` `}`, which oxc rejects with "Expected `}` but found `@`".
- */
-function stripJsxTemplateLines(content) {
- const out = content.slice();
-
- // Drop any leading blank lines so we don't miss a `{` line buried below
- // them; same for trailing.
- while (out.length > 0 && out[0].trim() === '') out.shift();
- while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
- if (out.length === 0) return null;
-
- // Leading `{`: own line, or attached to the first CSS line.
- const firstTrim = out[0].trimStart();
- if (firstTrim === '{`') {
- out.shift();
- } else if (firstTrim.startsWith('{`')) {
- const idx = out[0].indexOf('{`');
- out[0] = out[0].slice(0, idx) + out[0].slice(idx + 2);
- if (out[0].trim() === '') out.shift();
- }
- if (out.length === 0) return null;
-
- // Trailing `` ` `` `}`: own line, or attached to the last CSS line.
- const lastIdx = out.length - 1;
- const lastTrim = out[lastIdx].trimEnd();
- if (lastTrim === '`}') {
- out.pop();
- } else if (lastTrim.endsWith('`}')) {
- const text = out[lastIdx];
- const idx = text.lastIndexOf('`}');
- out[lastIdx] = text.slice(0, idx) + text.slice(idx + 2);
- if (out[lastIdx].trim() === '') out.pop();
- }
-
- return out.length > 0 ? out : null;
-}
-
-function stripJsxTemplateWrap(text) {
- const lines = text.split('\n');
- const stripped = stripJsxTemplateLines(lines);
- return stripped ? stripped.join('\n') : '';
-}
-
-/**
- * De-indent content that was indented by live-wrap.mjs.
- * The wrap script adds `indent + ' '` (4 extra spaces) to each line.
- * We restore to just `indent` level.
- */
-function deindentContent(contentLines, baseIndent) {
- // Find the minimum indentation in the content to determine how much was added
- let minIndent = Infinity;
- for (const line of contentLines) {
- if (line.trim() === '') continue;
- const leadingSpaces = line.match(/^(\s*)/)[1].length;
- minIndent = Math.min(minIndent, leadingSpaces);
- }
- if (minIndent === Infinity) minIndent = 0;
-
- // Strip the extra indentation and re-add base indent
- return contentLines.map(line => {
- if (line.trim() === '') return '';
- return baseIndent + line.slice(minIndent);
- });
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- return { open: '<!--', close: '-->' };
-}
-
-// ---------------------------------------------------------------------------
-// File search (find the file containing session markers)
-// ---------------------------------------------------------------------------
-
-function findSessionFile(id, cwd) {
- const marker = 'impeccable-variants-start ' + id;
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, marker, seen, 0);
- if (result) {
- const content = fs.readFileSync(result, 'utf-8');
- return { file: result, content, lines: content.split('\n') };
- }
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth) {
- if (depth > 5) return null;
- let realDir;
- try { realDir = fs.realpathSync(dir); } catch { return null; }
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- if (!EXTENSIONS.includes(path.extname(entry.name).toLowerCase())) continue;
- const filePath = path.join(dir, entry.name);
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip */ }
- }
-
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
- if (result) return result;
- }
-
- return null;
-}
-
-// ---------------------------------------------------------------------------
-// Utilities
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-accept.mjs') || _running?.endsWith('live-accept.mjs/')) {
- acceptCli();
-}
-
-export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax };
@@ -1,123 +0,0 @@
-/**
- * Browser-side durable session helpers for Impeccable live mode.
- *
- * Kept separate from live-browser.js so recovery state can be tested without
- * booting the full overlay UI. Served before live-browser.js and attached to
- * window.__IMPECCABLE_LIVE_SESSION__.
- */
-(function (root) {
- 'use strict';
-
- function createLiveBrowserSessionState({ prefix, storage, idFactory }) {
- if (!prefix) throw new Error('prefix required');
- const store = storage || root.localStorage;
- const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };
- const sessionKey = prefix + '-session';
- const handledKey = sessionKey + '-handled';
- const scrollKey = sessionKey + '-scroll';
- let checkpointRevision = 0;
- const owner = makeId();
-
- function safeRead(key) {
- try { return store.getItem(key); } catch { return null; }
- }
-
- function safeWrite(key, value) {
- try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }
- }
-
- function safeRemove(key) {
- try { store.removeItem(key); } catch { /* unavailable storage */ }
- }
-
- function loadSession() {
- try {
- const raw = safeRead(sessionKey);
- if (!raw) return null;
- const parsed = JSON.parse(raw);
- if (Number.isInteger(parsed.checkpointRevision)) {
- checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);
- }
- return parsed;
- } catch { return null; }
- }
-
- function saveSession(session) {
- if (!session || !session.id) return;
- const payload = {
- ...session,
- checkpointRevision,
- };
- safeWrite(sessionKey, JSON.stringify(payload));
- }
-
- function clearSession() {
- safeRemove(sessionKey);
- }
-
- function nextCheckpointRevision() {
- checkpointRevision += 1;
- const existing = loadSession();
- if (existing?.id) saveSession(existing);
- return checkpointRevision;
- }
-
- function seedCheckpointRevision(value) {
- if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);
- return checkpointRevision;
- }
-
- function currentCheckpointRevision() {
- return checkpointRevision;
- }
-
- function markHandled(id) {
- if (!id) return;
- safeWrite(handledKey, id);
- }
-
- function isHandled(id) {
- return !!id && safeRead(handledKey) === id;
- }
-
- function clearHandled() {
- safeRemove(handledKey);
- }
-
- function writeScrollY(y) {
- safeWrite(scrollKey, String(y));
- }
-
- function readScrollY() {
- const raw = safeRead(scrollKey);
- if (raw == null) return null;
- const n = parseFloat(raw);
- return isFinite(n) ? n : null;
- }
-
- function clearScrollY() {
- safeRemove(scrollKey);
- }
-
- return {
- owner,
- sessionKey,
- handledKey,
- scrollKey,
- saveSession,
- loadSession,
- clearSession,
- nextCheckpointRevision,
- seedCheckpointRevision,
- currentCheckpointRevision,
- markHandled,
- isHandled,
- clearHandled,
- writeScrollY,
- readScrollY,
- clearScrollY,
- };
- }
-
- root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };
-})(typeof window !== 'undefined' ? window : globalThis);
@@ -1,4860 +0,0 @@
-/**
- * Impeccable Live Variant Mode — Browser Script
- *
- * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
- * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
- * before this code.
- *
- * UI: a single floating bar that morphs between three states —
- * configure (pick action + go), generating (progressive dots), and cycling
- * (prev/next + accept/discard). Feels like Spotlight, not a modal.
- */
-(function () {
- 'use strict';
- if (typeof window === 'undefined') return;
-
- // Guard against double-init. Bun's HTML loader may process the <script> tag
- // and create a bundled copy alongside the external load, or HMR may re-execute.
- // Check BEFORE reading token/port to catch all cases.
- if (window.__IMPECCABLE_LIVE_INIT__) return;
- window.__IMPECCABLE_LIVE_INIT__ = true;
-
- const TOKEN = window.__IMPECCABLE_TOKEN__;
- const PORT = window.__IMPECCABLE_PORT__;
- if (!TOKEN || !PORT) {
- window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
- return;
- }
-
- // ---------------------------------------------------------------------------
- // Design tokens
- // ---------------------------------------------------------------------------
-
- // Brand magenta is pinned to the site token (--color-accent in main.css)
- // so Accept / knobs / cycle-dots match the site's accent, not a washed
- // theme-adjusted one.
- const C = {
- brand: 'oklch(60% 0.25 350)',
- brandHov: 'oklch(52% 0.25 350)',
- brandSoft: 'oklch(60% 0.25 350 / 0.15)',
- ink: 'oklch(15% 0.01 350)',
- ash: 'oklch(55% 0 0)',
- paper: 'oklch(98% 0.005 350 / 0.92)',
- paperSolid:'oklch(98% 0.005 350)',
- mist: 'oklch(90% 0.01 350 / 0.6)',
- white: 'oklch(99% 0 0)',
- };
- const FONT = 'system-ui, -apple-system, sans-serif';
- const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
- // z-index: detect overlays use 99999, so our UI must be above them
- const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };
- const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
- const PREFIX = 'impeccable-live';
- const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
- prefix: PREFIX,
- storage: localStorage,
- idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),
- });
- if (!sessionState) {
- console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');
- window.__IMPECCABLE_LIVE_INIT__ = false;
- return;
- }
- const HIGHLIGHT_TRANSITION =
- 'top 140ms ' + EASE +
- ', left 140ms ' + EASE +
- ', width 140ms ' + EASE +
- ', height 140ms ' + EASE +
- ', opacity 150ms ease';
- const TOOLTIP_TRANSITION =
- 'top 140ms ' + EASE + ', left 140ms ' + EASE + ', opacity 150ms ease';
-
- const SKIP_TAGS = new Set([
- 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
- ]);
-
- // SVG icons stack above each chip label. All strokes use currentColor so the
- // icon recolors to C.brand when its chip is selected. 20x20 render, 24-viewBox,
- // 1.5 stroke — visually consistent with the Foundation grid on the homepage.
- const ICON_ATTRS = 'width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block"';
- const ICONS = {
- impeccable: `<svg ${ICON_ATTRS}><path d="M4 20l4-1L18 9l-3-3L5 16z"/><path d="M14 7l3 3"/></svg>`,
- bolder: `<svg ${ICON_ATTRS}><rect x="6" y="12" width="4" height="7" rx="0.5"/><rect x="14" y="5" width="4" height="14" rx="0.5"/></svg>`,
- quieter: `<svg ${ICON_ATTRS}><rect x="6" y="5" width="4" height="14" rx="0.5"/><rect x="14" y="12" width="4" height="7" rx="0.5"/></svg>`,
- distill: `<svg ${ICON_ATTRS}><path d="M4 5h16l-6 8v7l-4-2v-5z"/></svg>`,
- polish: `<svg ${ICON_ATTRS}><path d="M15 3l1 3 3 1-3 1-1 3-1-3-3-1 3-1z"/><path d="M7 13l0.6 1.8 1.8 0.6-1.8 0.6-0.6 1.8-0.6-1.8-1.8-0.6 1.8-0.6z"/></svg>`,
- typeset: `<svg ${ICON_ATTRS}><path d="M5 6h14" stroke-width="2.6"/><path d="M5 12h9" stroke-width="1.9"/><path d="M5 18h5" stroke-width="1.3"/></svg>`,
- colorize: `<svg ${ICON_ATTRS}><circle cx="9" cy="10" r="5"/><circle cx="15" cy="10" r="5"/><circle cx="12" cy="15" r="5"/></svg>`,
- layout: `<svg ${ICON_ATTRS}><rect x="3" y="4" width="8" height="16" rx="0.5"/><rect x="13" y="4" width="8" height="7" rx="0.5"/><rect x="13" y="13" width="8" height="7" rx="0.5"/></svg>`,
- adapt: `<svg ${ICON_ATTRS}><rect x="2.5" y="5" width="12" height="11" rx="1"/><line x1="2.5" y1="19" x2="14.5" y2="19"/><rect x="16.5" y="8" width="5" height="11" rx="1"/></svg>`,
- animate: `<svg ${ICON_ATTRS}><path d="M3 18c4-4 6-10 10-10"/><path d="M13 8c3 0 5 5 8 10"/><circle cx="13" cy="8" r="1.6" fill="currentColor" stroke="none"/></svg>`,
- delight: `<svg ${ICON_ATTRS}><path d="M12 3l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>`,
- overdrive: `<svg ${ICON_ATTRS}><path d="M13 3L5 13h5l-1 8 9-12h-6z"/></svg>`,
- };
-
- const ACTIONS = [
- { value: 'impeccable', label: 'Freeform' },
- { value: 'bolder', label: 'Bolder' },
- { value: 'quieter', label: 'Quieter' },
- { value: 'distill', label: 'Distill' },
- { value: 'polish', label: 'Polish' },
- { value: 'typeset', label: 'Typeset' },
- { value: 'colorize', label: 'Colorize' },
- { value: 'layout', label: 'Layout' },
- { value: 'adapt', label: 'Adapt' },
- { value: 'animate', label: 'Animate' },
- { value: 'delight', label: 'Delight' },
- { value: 'overdrive', label: 'Overdrive' },
- ];
-
- // ---------------------------------------------------------------------------
- // State
- // ---------------------------------------------------------------------------
-
- let state = 'IDLE';
- let hoveredElement = null;
- let selectedElement = null;
- let currentSessionId = null;
- let expectedVariants = 0;
- let arrivedVariants = 0;
- let visibleVariant = 0;
- let variantObserver = null;
- let hasProjectContext = false;
- let selectedAction = 'impeccable';
- let selectedCount = 3;
- const browserOwner = sessionState.owner;
- let checkpointTimer = null;
-
- // Scroll lock — holds window.scrollY at a fixed value while the session is
- // active, so HMR DOM patches and variant swaps can't drift the page. See
- // startScrollLock / stopScrollLock below.
- let scrollLockObserver = null;
- let scrollLockTargetY = null;
- let scrollLockRaf = null;
- let scrollLockAbort = null;
-
- // Dedicated key for scroll position — SEPARATE from LS_KEY so that
- // saveSession's state updates don't clobber a carefully-captured scrollY.
- // (Previously: saveSession wrote scrollY alongside state, so every call
- // during resume overwrote the pre-reload value with whatever the browser
- // had landed on, typically 0.)
- function writeScrollY(y) { sessionState.writeScrollY(y); }
- function readScrollY() { return sessionState.readScrollY(); }
- function clearScrollY() { sessionState.clearScrollY(); }
-
- // Pre-empt the browser: apply manual scroll restoration and jump to the
- // saved scrollY at script-parse time. Retries on fonts.ready and load
- // are essential: scrollTo(y) clamps to the current document.scrollHeight,
- // which is often hundreds of pixels short of the final value until
- // async-loaded fonts swap in and reflow.
- try {
- history.scrollRestoration = 'manual';
- const savedY = readScrollY();
- if (savedY != null) {
- const apply = () => {
- if (Math.abs(window.scrollY - savedY) > 0.5) {
- console.log('[impeccable.scroll] early restore', { from: window.scrollY, to: savedY });
- window.scrollTo(0, savedY);
- }
- };
- apply();
- if (document.fonts?.ready) document.fonts.ready.then(apply).catch(() => {});
- window.addEventListener('load', apply, { once: true });
- }
- } catch {}
-
- // UI refs
- let highlightEl = null;
- let tooltipEl = null;
- let barEl = null;
- let pickerEl = null;
- let toastEl = null;
- let scrollRaf = null;
-
- // ---------------------------------------------------------------------------
- // Helpers
- // ---------------------------------------------------------------------------
-
- function own(el) {
- return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
- }
-
- function pickable(el) {
- if (!el || el.nodeType !== 1) return false;
- if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
- if (own(el)) return false;
- const r = el.getBoundingClientRect();
- return r.width >= 20 && r.height >= 20;
- }
-
- function desc(el) {
- if (!el) return '';
- let s = el.tagName.toLowerCase();
- if (el.id) s += '#' + el.id;
- else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
- return s;
- }
-
- function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
-
- // Modal-aware chrome: keep our floating UI clickable inside Radix /
- // Headless UI / vaul portals.
- //
- // Two host-page behaviors break us when the picked element lives inside a
- // modal dialog:
- //
- // 1. Modal scroll-lock disables outside pointer events. Radix's
- // `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
- // while a modal is open and only restores `auto` on the layer. Our
- // chrome inherits `none` from <body> and becomes unclickable.
- // 2. The dialog's outside-interaction handler (Radix's
- // `usePointerDownOutside`) listens at document level and dismisses
- // the dialog whenever a `pointerdown` lands outside the layer node.
- // Our chrome is a sibling of <body>, so Radix classifies our clicks
- // as outside and tears the dialog down mid-task.
- //
- // We can't reliably re-parent our chrome into the dialog subtree (z-index
- // stacking, scroll containers, theming all become host-page concerns), so
- // we defang both behaviors at our root:
- //
- // - `pointer-events: auto !important` overrides the inherited `none`.
- // - Stop `pointerdown` / `mousedown` propagation so the document-level
- // dismiss listener never fires for our clicks.
- // - Stop `focusin` propagation so any focus shifts inside our chrome
- // don't read as "focus moved outside the dialog" to focus traps.
- //
- // Click events still bubble normally — only the early pointer/focus
- // signals that drive outside-interaction detection are silenced.
- function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
- if (!rootEl) return;
- if (setPointerEvents) {
- rootEl.style.setProperty('pointer-events', 'auto', 'important');
- }
- const stop = (e) => e.stopPropagation();
- rootEl.addEventListener('pointerdown', stop);
- rootEl.addEventListener('mousedown', stop);
- rootEl.addEventListener('focusin', stop);
- }
-
- // ---------------------------------------------------------------------------
- // Highlight overlay
- // ---------------------------------------------------------------------------
-
- function initHighlight() {
- highlightEl = document.createElement('div');
- highlightEl.id = PREFIX + '-highlight';
- Object.assign(highlightEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- border: '2px solid ' + C.brand, borderRadius: '3px',
- pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
- transition: HIGHLIGHT_TRANSITION,
- display: 'none', opacity: '0',
- });
- document.body.appendChild(highlightEl);
-
- tooltipEl = document.createElement('div');
- tooltipEl.id = PREFIX + '-tooltip';
- Object.assign(tooltipEl.style, {
- position: 'fixed',
- background: C.ink, color: C.white,
- fontFamily: MONO, fontSize: '10px', fontWeight: '500',
- padding: '2px 6px', borderRadius: '3px',
- zIndex: Z.highlight + 1, pointerEvents: 'none',
- whiteSpace: 'nowrap', display: 'none',
- letterSpacing: '0.02em',
- transition: TOOLTIP_TRANSITION,
- });
- document.body.appendChild(tooltipEl);
- }
-
- function showHighlight(el) {
- if (!el || !highlightEl) return;
- const r = el.getBoundingClientRect();
- const top = (r.top - 2) + 'px', left = (r.left - 2) + 'px';
- const width = (r.width + 4) + 'px', height = (r.height + 4) + 'px';
- const tipTop = r.top - 20;
- const tipY = (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px';
- const tipX = Math.max(4, r.left) + 'px';
- tooltipEl.textContent = desc(el);
-
- const hiWasHidden = highlightEl.style.display === 'none' || highlightEl.style.opacity === '0';
- if (hiWasHidden) {
- // Snap to first target without animating from (0,0), then fade in.
- highlightEl.style.transition = 'none';
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block' });
- tooltipEl.style.transition = 'none';
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block' });
- void highlightEl.offsetWidth;
- highlightEl.style.transition = HIGHLIGHT_TRANSITION;
- highlightEl.style.opacity = '1';
- tooltipEl.style.transition = TOOLTIP_TRANSITION;
- tooltipEl.style.opacity = '1';
- } else {
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block', opacity: '1' });
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block', opacity: '1' });
- }
- }
-
- function hideHighlight() {
- if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
- if (tooltipEl) { tooltipEl.style.opacity = '0'; tooltipEl.style.display = 'none'; }
- }
-
- // ---------------------------------------------------------------------------
- // Annotation overlay (comment pins + magenta strokes)
- //
- // Active while state === 'CONFIGURING'. The overlay is a fixed-positioned
- // sibling of <body> mirroring selectedElement's bounding rect. Click (no
- // drag) drops a comment pin; drag paints a magenta SVG stroke. All coords
- // are stored in element-local CSS px so they survive scroll / resize and
- // correlate directly with the captured PNG.
- // ---------------------------------------------------------------------------
-
- const DRAG_THRESHOLD = 5; // px — below this, treat pointerup as a click
- const PIN_DBL_CLICK_MS = 300; // two clicks on the same pin within this delete it
- let annotOverlayEl = null;
- let annotSvgEl = null;
- let annotPinsEl = null;
- let annotClearChipEl = null;
- let annotState = { comments: [], strokes: [] };
- let annotActive = false;
- // `annotPointer` is either:
- // { kind: 'new', x0, y0, moved, strokeEl, strokePoints } creating a stroke/pin
- // { kind: 'pin', idx, startPointer, startPin, moved } dragging an existing pin
- let annotPointer = null;
- let annotEditing = null; // { idx, input, wrapEl }
- let annotLastPinClick = { idx: -1, time: 0 }; // for click-click-to-delete
-
- function initAnnotOverlay() {
- annotOverlayEl = document.createElement('div');
- annotOverlayEl.id = PREFIX + '-annot';
- Object.assign(annotOverlayEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- pointerEvents: 'auto', zIndex: Z.highlight + 2,
- display: 'none', overflow: 'visible',
- cursor: 'crosshair', touchAction: 'none',
- });
-
- annotSvgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- annotSvgEl.id = PREFIX + '-annot-svg';
- Object.assign(annotSvgEl.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%',
- // The SVG itself doesn't absorb clicks; individual hit-paths opt-in via
- // pointer-events=stroke so gaps still fall through to the overlay.
- pointerEvents: 'none', overflow: 'visible',
- });
- annotOverlayEl.appendChild(annotSvgEl);
-
- annotPinsEl = document.createElement('div');
- annotPinsEl.id = PREFIX + '-annot-pins';
- Object.assign(annotPinsEl.style, {
- position: 'absolute', inset: '0',
- pointerEvents: 'none',
- });
- annotOverlayEl.appendChild(annotPinsEl);
-
- annotClearChipEl = document.createElement('div');
- annotClearChipEl.id = PREFIX + '-annot-clear';
- annotClearChipEl.dataset.annotClear = 'true';
- annotClearChipEl.textContent = 'Clear';
- Object.assign(annotClearChipEl.style, {
- position: 'absolute', top: '8px', right: '8px',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '10px', fontWeight: '500',
- letterSpacing: '0.08em', textTransform: 'uppercase',
- padding: '5px 12px', borderRadius: '999px',
- cursor: 'pointer', pointerEvents: 'auto',
- display: 'none', userSelect: 'none',
- boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
- });
- annotOverlayEl.appendChild(annotClearChipEl);
-
- annotOverlayEl.addEventListener('pointerdown', onAnnotDown);
- annotOverlayEl.addEventListener('pointermove', onAnnotMove);
- annotOverlayEl.addEventListener('pointerup', onAnnotUp);
- annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
- document.body.appendChild(annotOverlayEl);
- // Modal-host friendliness: pointer-events is already 'auto' on this
- // overlay; we only need to silence the host's outside-interaction
- // listeners. Don't override pointer-events here (the overlay toggles
- // visibility via display:none, which is fine).
- defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
- }
-
- function updateClearChip() {
- if (!annotClearChipEl) return;
- const hasAny = annotState.comments.length > 0 || annotState.strokes.length > 0;
- annotClearChipEl.style.display = hasAny ? 'block' : 'none';
- }
-
- function showAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- annotActive = true;
- positionAnnotOverlay(el);
- annotOverlayEl.style.display = 'block';
- }
-
- function hideAnnotOverlay() {
- annotActive = false;
- if (annotOverlayEl) annotOverlayEl.style.display = 'none';
- // Drop any in-progress edit without touching annotState — clearAnnotations
- // (if the caller is exiting configure mode) handles state reset.
- annotEditing = null;
- }
-
- function positionAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- const r = el.getBoundingClientRect();
- Object.assign(annotOverlayEl.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- annotSvgEl.setAttribute('viewBox', '0 0 ' + r.width + ' ' + r.height);
- }
-
- function clearAnnotations() {
- annotState.comments = [];
- annotState.strokes = [];
- if (annotSvgEl) while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- if (annotPinsEl) annotPinsEl.innerHTML = '';
- annotPointer = null;
- annotEditing = null;
- annotLastPinClick = { idx: -1, time: 0 };
- updateClearChip();
- }
-
- // Rebuild the SVG layer. Each stroke gets a wider invisible hit path
- // beneath the visible magenta path so clicks register on thin lines.
- function redrawStrokes() {
- while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- annotState.strokes.forEach((s, idx) => {
- const d = pointsToPath(s.points);
- const hit = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- hit.setAttribute('d', d);
- hit.setAttribute('stroke', 'transparent');
- hit.setAttribute('stroke-width', '16');
- hit.setAttribute('stroke-linecap', 'round');
- hit.setAttribute('stroke-linejoin', 'round');
- hit.setAttribute('fill', 'none');
- hit.setAttribute('pointer-events', 'stroke');
- hit.style.cursor = 'pointer';
- hit.dataset.annotStroke = String(idx);
- annotSvgEl.appendChild(hit);
- const visible = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- visible.setAttribute('d', d);
- visible.setAttribute('stroke', C.brand);
- visible.setAttribute('stroke-width', '3');
- visible.setAttribute('stroke-linecap', 'round');
- visible.setAttribute('stroke-linejoin', 'round');
- visible.setAttribute('fill', 'none');
- visible.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(visible);
- });
- updateClearChip();
- }
-
- function localCoords(e) {
- const rect = annotOverlayEl.getBoundingClientRect();
- return { x: e.clientX - rect.left, y: e.clientY - rect.top };
- }
-
- function onAnnotDown(e) {
- if (!annotActive) return;
-
- // 1) Clear chip → wipe all annotations
- if (e.target.closest?.('[data-annot-clear]')) {
- if (annotEditing) annotEditing = null;
- clearAnnotations();
- renderAllPins();
- redrawStrokes();
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 2) Stroke hit path → delete that stroke
- const strokeHit = e.target.closest?.('[data-annot-stroke]');
- if (strokeHit) {
- const idx = parseInt(strokeHit.dataset.annotStroke, 10);
- if (Number.isInteger(idx)) {
- annotState.strokes.splice(idx, 1);
- redrawStrokes();
- }
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 3) Pin → drag, edit, or delete-on-double-click
- const pinWrap = e.target.closest?.('[data-annot-pin]');
- if (pinWrap) {
- const idx = parseInt(pinWrap.dataset.annotPin, 10);
- if (!Number.isInteger(idx)) return;
- // Double-click (two pointerdowns on the same pin within window) → delete.
- const now = Date.now();
- if (annotLastPinClick.idx === idx && now - annotLastPinClick.time < PIN_DBL_CLICK_MS) {
- if (annotEditing && annotEditing.idx === idx) annotEditing = null;
- annotState.comments.splice(idx, 1);
- annotLastPinClick = { idx: -1, time: 0 };
- renderAllPins();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- annotLastPinClick = { idx, time: now };
- // If editing a different pin, commit that edit before starting here.
- if (annotEditing && annotEditing.idx !== idx) finalizeEditingPin();
- // If already editing THIS pin and the user clicked the dot, let the
- // input keep focus (don't start a drag — the click wasn't meant as one).
- if (annotEditing && annotEditing.idx === idx) return;
- const p = localCoords(e);
- const pin = annotState.comments[idx];
- annotPointer = {
- kind: 'pin', idx,
- startPointer: p,
- startPin: { x: pin.x, y: pin.y },
- moved: false,
- };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 4) Empty area → commit any open edit, then start new annotation
- if (annotEditing) {
- finalizeEditingPin();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- const p = localCoords(e);
- annotPointer = { kind: 'new', x0: p.x, y0: p.y, moved: false, strokeEl: null, strokePoints: null };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- }
-
- function onAnnotMove(e) {
- if (!annotActive || !annotPointer) return;
- const p = localCoords(e);
-
- if (annotPointer.kind === 'pin') {
- const dx = p.x - annotPointer.startPointer.x;
- const dy = p.y - annotPointer.startPointer.y;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- }
- const pin = annotState.comments[annotPointer.idx];
- if (!pin) { annotPointer = null; return; }
- pin.x = annotPointer.startPin.x + dx;
- pin.y = annotPointer.startPin.y + dy;
- renderAllPins();
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const dx = p.x - annotPointer.x0, dy = p.y - annotPointer.y0;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- const strokeEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- strokeEl.setAttribute('stroke', C.brand);
- strokeEl.setAttribute('stroke-width', '3');
- strokeEl.setAttribute('stroke-linecap', 'round');
- strokeEl.setAttribute('stroke-linejoin', 'round');
- strokeEl.setAttribute('fill', 'none');
- strokeEl.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(strokeEl);
- annotPointer.strokeEl = strokeEl;
- annotPointer.strokePoints = [[annotPointer.x0, annotPointer.y0]];
- }
- annotPointer.strokePoints.push([p.x, p.y]);
- annotPointer.strokeEl.setAttribute('d', pointsToPath(annotPointer.strokePoints));
- e.stopPropagation();
- }
-
- function onAnnotUp(e) {
- if (!annotActive || !annotPointer) return;
-
- if (annotPointer.kind === 'pin') {
- const wasDrag = annotPointer.moved;
- const idx = annotPointer.idx;
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- if (wasDrag) {
- // A drag is an intentional reposition; a follow-up click shouldn't be
- // interpreted as a double-click-to-delete.
- annotLastPinClick = { idx: -1, time: 0 };
- } else {
- beginEditPin(idx);
- }
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const wasDrag = annotPointer.moved;
- if (wasDrag) {
- annotState.strokes.push({ points: annotPointer.strokePoints });
- // Swap the temporary preview SVG path for the full render with hit paths.
- redrawStrokes();
- } else {
- const idx = annotState.comments.length;
- annotState.comments.push({ x: annotPointer.x0, y: annotPointer.y0, text: '' });
- renderAllPins();
- beginEditPin(idx);
- }
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- e.stopPropagation();
- }
-
- function pointsToPath(points) {
- if (!points || points.length === 0) return '';
- let d = 'M' + points[0][0].toFixed(1) + ' ' + points[0][1].toFixed(1);
- for (let i = 1; i < points.length; i++) {
- d += ' L' + points[i][0].toFixed(1) + ' ' + points[i][1].toFixed(1);
- }
- return d;
- }
-
- function renderAllPins() {
- annotPinsEl.innerHTML = '';
- annotState.comments.forEach((c, idx) => {
- annotPinsEl.appendChild(buildPinElement(c, idx));
- });
- updateClearChip();
- }
-
- function buildPinElement(comment, idx) {
- const interactive = idx >= 0;
- const wrap = document.createElement('div');
- if (interactive) wrap.dataset.annotPin = String(idx);
- Object.assign(wrap.style, {
- position: 'absolute',
- left: (comment.x - 7) + 'px', top: (comment.y - 7) + 'px',
- pointerEvents: interactive ? 'auto' : 'none',
- display: 'flex', alignItems: 'flex-start', gap: '6px',
- cursor: interactive ? 'grab' : 'default',
- touchAction: 'none',
- });
- const dot = document.createElement('div');
- Object.assign(dot.style, {
- width: '14px', height: '14px', borderRadius: '50%',
- background: C.brand, border: '2px solid ' + C.white,
- boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
- flexShrink: '0',
- });
- wrap.appendChild(dot);
-
- if (comment.text) {
- const bubble = document.createElement('div');
- bubble.textContent = comment.text;
- Object.assign(bubble.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- marginTop: '-2px', maxWidth: '220px',
- pointerEvents: 'none', whiteSpace: 'pre-wrap',
- wordBreak: 'break-word',
- });
- wrap.appendChild(bubble);
- }
- return wrap;
- }
-
- function beginEditPin(idx) {
- const wrapEl = annotPinsEl.querySelector('[data-annot-pin="' + idx + '"]');
- if (!wrapEl) return;
- // Strip any existing bubble (but keep the dot)
- wrapEl.querySelectorAll('div:not(:first-child)').forEach(n => n.remove());
- const input = document.createElement('input');
- input.type = 'text';
- input.placeholder = 'Note…';
- Object.assign(input.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- border: '1px solid ' + C.brand,
- outline: 'none', marginTop: '-2px',
- width: '220px', pointerEvents: 'auto',
- });
- const originalText = annotState.comments[idx].text || '';
- input.value = originalText;
- wrapEl.appendChild(input);
- annotEditing = { idx, input, wrapEl, originalText };
- input.addEventListener('keydown', onAnnotInputKey, true);
- input.addEventListener('blur', () => {
- // Fires on both focus-loss and programmatic blur; commit unless we
- // already handled it.
- if (annotEditing && annotEditing.input === input) finalizeEditingPin();
- });
- // Stop clicks/pointerdowns inside the input from bubbling to the overlay
- ['pointerdown', 'click'].forEach(ev => {
- input.addEventListener(ev, e => e.stopPropagation());
- });
- setTimeout(() => input.focus(), 0);
- }
-
- function onAnnotInputKey(e) {
- if (e.key === 'Enter') {
- e.preventDefault(); e.stopPropagation();
- finalizeEditingPin();
- } else if (e.key === 'Escape') {
- e.preventDefault(); e.stopPropagation();
- cancelEditingPin();
- } else {
- // Keep arrows / backspace from hitting global handlers
- e.stopPropagation();
- }
- }
-
- function finalizeEditingPin() {
- if (!annotEditing) return;
- const { idx, input } = annotEditing;
- const text = input.value.trim();
- annotEditing = null;
- if (text) annotState.comments[idx].text = text;
- else annotState.comments.splice(idx, 1);
- renderAllPins();
- }
-
- function cancelEditingPin() {
- if (!annotEditing) return;
- const { idx, originalText } = annotEditing;
- annotEditing = null;
- // If the pin had text before this edit, revert to it. If it was a
- // just-created empty pin, Escape removes it.
- if (originalText) {
- annotState.comments[idx].text = originalText;
- } else {
- annotState.comments.splice(idx, 1);
- }
- renderAllPins();
- }
-
- // Build a detached annotation subtree suitable for injection into the clone
- // modern-screenshot creates. Coordinates are element-local so this slots
- // straight into an element that's been made position:relative. Takes an
- // explicit snapshot so it works after annotState has been cleared.
- function buildAnnotationsForCapture(rect, snapshot) {
- const comments = snapshot ? snapshot.comments : annotState.comments;
- const strokes = snapshot ? snapshot.strokes : annotState.strokes;
- if (comments.length === 0 && strokes.length === 0) return null;
- const wrap = document.createElement('div');
- Object.assign(wrap.style, {
- position: 'absolute', top: '0', left: '0',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none', overflow: 'visible',
- });
- if (strokes.length > 0) {
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- svg.setAttribute('viewBox', '0 0 ' + rect.width + ' ' + rect.height);
- Object.assign(svg.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%', overflow: 'visible',
- });
- for (const s of strokes) {
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- path.setAttribute('stroke', C.brand);
- path.setAttribute('stroke-width', '3');
- path.setAttribute('stroke-linecap', 'round');
- path.setAttribute('stroke-linejoin', 'round');
- path.setAttribute('fill', 'none');
- path.setAttribute('d', pointsToPath(s.points));
- svg.appendChild(path);
- }
- wrap.appendChild(svg);
- }
- for (const c of comments) {
- // idx=-1 means non-interactive; pointerEvents stay off in the clone
- wrap.appendChild(buildPinElement(c, -1));
- }
- return wrap;
- }
-
- // ---------------------------------------------------------------------------
- // Element context extraction
- // ---------------------------------------------------------------------------
-
- function extractContext(el) {
- const cs = getComputedStyle(el);
- const r = el.getBoundingClientRect();
- const props = {};
- for (const sheet of document.styleSheets) {
- try {
- for (const rule of sheet.cssRules) {
- if (rule.style) for (let i = 0; i < rule.style.length; i++) {
- const p = rule.style[i];
- if (p.startsWith('--') && !props[p]) {
- const v = cs.getPropertyValue(p).trim();
- if (v) props[p] = v;
- }
- }
- }
- } catch { /* cross-origin */ }
- }
- return {
- tagName: el.tagName.toLowerCase(), id: el.id || null,
- classes: [...el.classList],
- textContent: (el.textContent || '').slice(0, 500),
- outerHTML: el.outerHTML.slice(0, 10000),
- computedStyles: {
- 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
- 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
- 'color': cs.color, 'background': cs.background,
- 'background-color': cs.backgroundColor,
- 'padding': cs.padding, 'margin': cs.margin,
- 'display': cs.display, 'position': cs.position,
- 'gap': cs.gap, 'border-radius': cs.borderRadius,
- 'box-shadow': cs.boxShadow,
- },
- cssCustomProperties: props,
- parentContext: el.parentElement
- ? '<' + el.parentElement.tagName.toLowerCase()
- + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
- + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
- + '>'
- : null,
- boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
- };
- }
-
- // ---------------------------------------------------------------------------
- // The Bar — one floating element, three modes
- // ---------------------------------------------------------------------------
-
- // Contextual-bar palette. Cached at init so every build*Row reads a
- // consistent set of colors; detectPageTheme runs once rather than on every
- // phase transition.
- let BP = null;
-
- // Bar shadow variants. The default projects down + subtle around. When
- // the Tune popover opens below the bar, a downward shadow lands on the
- // dark popover and reads as a bright ghost line. We swap to UP-only while
- // tune is open below so the popover's top edge is clean.
- const BAR_SHADOW_DEFAULT = '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_UP = '0 -4px 20px oklch(0% 0 0 / 0.08), 0 -1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_DOWN = BAR_SHADOW_DEFAULT;
-
- function initBar() {
- BP = barPaletteForTheme(detectPageTheme());
- barEl = document.createElement('div');
- barEl.id = PREFIX + '-bar';
- Object.assign(barEl.style, {
- position: 'fixed', zIndex: Z.bar,
- display: 'none', opacity: '0',
- transform: 'translateY(6px)',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- background: BP.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + BP.hairline,
- borderRadius: '10px',
- boxShadow: BAR_SHADOW_DEFAULT,
- transition: 'box-shadow 0.2s ease, opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- fontFamily: FONT, fontSize: '13px', color: BP.text,
- padding: '6px',
- maxWidth: '520px', minWidth: '320px',
- });
- document.body.appendChild(barEl);
- defangOutsideHandlers(barEl);
- }
-
- function positionBar() {
- if (!barEl || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- const barH = barEl.offsetHeight || 44;
- const barW = barEl.offsetWidth || 380;
- const GLOBAL_BAR_RESERVE = 64; // global bar height + bottom margin + breathing room
- const GAP = 8;
-
- // Prefer below the element; fall back to above; if neither fits (element
- // taller than viewport), pin to a stable viewport anchor so the bar
- // doesn't teleport between top and bottom as the user scrolls.
- let top;
- const belowTop = r.bottom + GAP;
- const aboveTop = r.top - barH - GAP;
- if (belowTop + barH + GAP <= window.innerHeight - GLOBAL_BAR_RESERVE) {
- top = belowTop;
- } else if (aboveTop >= GAP) {
- top = aboveTop;
- } else {
- top = window.innerHeight - barH - GLOBAL_BAR_RESERVE;
- }
-
- let left = r.left + (r.width - barW) / 2;
- if (left < GAP) left = GAP;
- if (left + barW > window.innerWidth - GAP) left = window.innerWidth - barW - GAP;
- Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
- }
-
- function showBar(mode) {
- barEl.innerHTML = '';
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- barEl.style.display = 'block';
- positionBar();
- requestAnimationFrame(() => {
- barEl.style.opacity = '1';
- barEl.style.transform = 'translateY(0)';
- });
- }
-
- function hideBar() {
- if (!barEl) return;
- barEl.style.opacity = '0';
- barEl.style.transform = 'translateY(6px)';
- setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
- hideActionPicker();
- closeTunePopover();
- }
-
- function updateBarContent(mode) {
- if (!barEl || barEl.style.display === 'none') return;
- barEl.innerHTML = '';
- // Reset bar styling to the theme-aware palette
- barEl.style.background = BP.surface;
- barEl.style.border = '1px solid ' + BP.hairline;
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- else if (mode === 'saving') barEl.appendChild(buildSavingRow());
- else if (mode === 'confirmed') {
- barEl.appendChild(buildConfirmedRow());
- barEl.style.background = 'oklch(95% 0.05 145)';
- barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
- }
- }
-
- // --- Configure row ---
-
- function buildConfigureRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
-
- // Action pill
- const pill = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '4px',
- padding: '5px 10px', borderRadius: '6px',
- background: BP.mark, color: BP.markText,
- fontFamily: FONT, fontSize: '12px', fontWeight: '500',
- border: 'none', cursor: 'pointer',
- transition: 'background 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap', flexShrink: '0',
- });
- pill.textContent = actionLabel() + ' \u25BE';
- pill.addEventListener('mouseenter', () => pill.style.background = BP.accent);
- pill.addEventListener('mouseleave', () => pill.style.background = BP.mark);
- pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
- pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
- pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
- row.appendChild(pill);
-
- // Freeform input. Focus state shows an accent-colored border only —
- // an earlier version tinted the background with `BP.accentSoft`, which
- // composited against the dark bar surface to a murky purple where the
- // browser's default placeholder gray was unreadable. Placeholder color
- // is set explicitly via a one-shot stylesheet keyed off this input's id
- // so it picks up the bar's `textDim` token in both themes.
- const input = document.createElement('input');
- input.id = PREFIX + '-input';
- input.type = 'text';
- input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
- Object.assign(input.style, {
- flex: '1', minWidth: '0',
- padding: '5px 8px', borderRadius: '6px',
- border: '1px solid transparent', background: 'transparent',
- fontFamily: FONT, fontSize: '12px', color: BP.text,
- outline: 'none',
- transition: 'border-color 0.15s ease',
- });
- if (!document.getElementById(PREFIX + '-input-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-input-style';
- s.textContent =
- '#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
- document.head.appendChild(s);
- }
- input.addEventListener('focus', () => {
- input.style.borderColor = BP.accent;
- });
- input.addEventListener('blur', () => {
- input.style.borderColor = 'transparent';
- });
- input.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
- if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; return; }
- // Let arrow keys pass through to the element picker when the input is empty
- if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && !input.value) return;
- e.stopPropagation();
- });
- row.appendChild(input);
-
- // Variant count toggle
- const count = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: MONO, fontSize: '11px', fontWeight: '600',
- color: BP.textDim, cursor: 'pointer',
- transition: 'color 0.12s ease, border-color 0.12s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- count.textContent = '\u00D7' + selectedCount;
- count.title = 'Variants: click to change';
- count.addEventListener('mouseenter', () => { count.style.color = BP.text; count.style.borderColor = BP.text; });
- count.addEventListener('mouseleave', () => { count.style.color = BP.textDim; count.style.borderColor = BP.hairline; });
- count.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
- count.textContent = '\u00D7' + selectedCount;
- });
- row.appendChild(count);
-
- // Go button
- const go = el('button', {
- padding: '5px 12px', borderRadius: '6px',
- border: 'none', background: BP.accent, color: BP.mark,
- fontFamily: FONT, fontSize: '12px', fontWeight: '600',
- cursor: 'pointer',
- transition: 'filter 0.12s ease, transform 0.1s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- go.textContent = 'Go \u2192';
- go.addEventListener('mouseenter', () => go.style.filter = 'brightness(1.1)');
- go.addEventListener('mouseleave', () => go.style.filter = 'none');
- go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
- go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
- go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
- row.appendChild(go);
-
- // Auto-focus input after a beat
- setTimeout(() => input.focus(), 60);
- return row;
- }
-
- // --- Generating row ---
-
- function buildGeneratingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 4px',
- });
-
- // Action label
- const label = el('span', {
- fontWeight: '600', fontSize: '12px', color: BP.text,
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- label.textContent = actionLabel();
- row.appendChild(label);
-
- // Dots
- row.appendChild(buildDots(false));
-
- // Status
- const status = el('span', {
- fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',
- marginLeft: 'auto',
- });
- // Variants currently arrive atomically in a single file edit, so a
- // per-variant counter would lie. Say what's true.
- status.textContent = arrivedVariants < expectedVariants
- ? 'Generating ' + expectedVariants + ' variants...'
- : 'Done';
- row.appendChild(status);
-
- return row;
- }
-
- // --- Cycling row ---
-
- const TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';
-
- function buildCyclingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '6px',
- padding: '1px 2px',
- });
-
- // Prev
- const prev = navBtn('\u2190');
- prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
- if (visibleVariant <= 1) prev.style.opacity = '0.3';
- row.appendChild(prev);
-
- // Dots (clickable)
- row.appendChild(buildDots(true));
-
- // Counter
- const counter = el('span', {
- fontFamily: MONO, fontSize: '11px', fontWeight: '500',
- color: BP.textDim, minWidth: '24px', textAlign: 'center',
- });
- counter.textContent = visibleVariant + '/' + arrivedVariants;
- row.appendChild(counter);
-
- // Next
- const next = navBtn('\u2192');
- next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
- if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
- row.appendChild(next);
-
- // Tune chip — only when the visible variant exposes params
- const visParams = parseVariantParams(getVisibleVariantEl());
- const hasParams = visParams.length > 0;
- if (hasParams) {
- const tune = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '6px',
- padding: '4px 10px', borderRadius: '5px',
- border: '1px solid transparent',
- background: tuneOpen ? BP.accentSoft : 'transparent',
- color: tuneOpen ? BP.accent : BP.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'color 0.12s ease, background 0.12s ease',
- whiteSpace: 'nowrap',
- });
- tune.innerHTML = TUNE_ICON_SVG;
- const tuneLabel = document.createElement('span');
- tuneLabel.textContent = 'Tune';
- tune.appendChild(tuneLabel);
- const tuneBadge = document.createElement('span');
- Object.assign(tuneBadge.style, {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- minWidth: '16px', height: '16px', padding: '0 4px',
- borderRadius: '999px',
- background: tuneOpen ? C.brand : BP.hairline,
- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',
- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',
- lineHeight: '1',
- boxSizing: 'border-box',
- });
- tuneBadge.textContent = String(visParams.length);
- tune.appendChild(tuneBadge);
- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';
- tune.addEventListener('mouseenter', () => {
- if (!tuneOpen) tune.style.background = BP.accentSoft;
- });
- tune.addEventListener('mouseleave', () => {
- if (!tuneOpen) tune.style.background = 'transparent';
- });
- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });
- tune.dataset.iceqTune = '1';
- row.appendChild(tune);
- }
-
- // Spacer
- row.appendChild(el('div', { flex: '1' }));
-
- // Accept — primary action, uses the site's saturated brand magenta
- // with paper-white text, not the theme-muted BP.accent.
- const accept = el('button', {
- padding: '5px 14px', borderRadius: '5px',
- border: 'none', background: C.brand, color: 'oklch(98% 0 0)',
- fontFamily: FONT, fontSize: '11px', fontWeight: '600',
- cursor: 'pointer', transition: 'filter 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap',
- });
- accept.textContent = '\u2713 Accept';
- accept.addEventListener('mouseenter', () => accept.style.filter = 'brightness(1.08)');
- accept.addEventListener('mouseleave', () => accept.style.filter = 'none');
- accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');
- accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');
- accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
- row.appendChild(accept);
-
- // Discard
- const discard = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: FONT, fontSize: '11px', color: BP.textDim,
- cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
- });
- discard.textContent = '\u2715';
- discard.title = 'Discard all variants';
- discard.addEventListener('mouseenter', () => { discard.style.color = BP.text; discard.style.borderColor = BP.text; });
- discard.addEventListener('mouseleave', () => { discard.style.color = BP.textDim; discard.style.borderColor = BP.hairline; });
- discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
- row.appendChild(discard);
-
- return row;
- }
-
- // --- Shared UI builders ---
-
- // --- Saving row (waiting for agent to process accept/discard) ---
-
- function buildSavingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const spinner = el('div', {
- width: '14px', height: '14px', borderRadius: '50%',
- border: '2px solid ' + BP.hairline,
- borderTopColor: BP.accent,
- animation: 'impeccable-spin 0.6s linear infinite',
- flexShrink: '0',
- });
- row.appendChild(spinner);
- const label = el('span', {
- fontSize: '12px', color: BP.textDim, fontWeight: '500',
- });
- label.textContent = 'Applying variant...';
- row.appendChild(label);
-
- // Inject the keyframes if not already present
- if (!document.getElementById(PREFIX + '-keyframes')) {
- const style = document.createElement('style');
- style.id = PREFIX + '-keyframes';
- style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
- document.head.appendChild(style);
- }
- return row;
- }
-
- // --- Confirmed row (green success, auto-dismisses) ---
-
- function buildConfirmedRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const check = el('span', {
- fontSize: '15px', lineHeight: '1', flexShrink: '0',
- color: 'oklch(45% 0.15 145)',
- });
- check.textContent = '\u2713';
- row.appendChild(check);
- const label = el('span', {
- fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
- });
- label.textContent = 'Variant applied';
- row.appendChild(label);
- return row;
- }
-
- // --- Shared UI builders ---
-
- function buildDots(clickable) {
- const container = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
- for (let i = 1; i <= expectedVariants; i++) {
- const arrived = i <= arrivedVariants;
- const active = i === visibleVariant;
- // active: solid site-brand magenta dot. arrived+inactive: muted neutral.
- // pending (not yet arrived): faint outline ring. No borders on arrived
- // dots — the previous "accent ring + ash fill" combo read as noisy
- // magenta chips, especially when all variants had arrived and every
- // dot wore an accent ring.
- const dotBg = active ? C.brand
- : arrived ? BP.textDim
- : 'transparent';
- const dotBorder = arrived ? 'none' : '1.5px solid ' + BP.hairline;
- const dot = el('div', {
- width: active ? '8px' : '6px',
- height: active ? '8px' : '6px',
- borderRadius: '50%',
- background: dotBg,
- border: dotBorder,
- boxSizing: 'border-box',
- transition: 'all 0.2s ' + EASE,
- cursor: (clickable && arrived) ? 'pointer' : 'default',
- transform: arrived ? 'scale(1)' : 'scale(0.85)',
- opacity: arrived ? (active ? '1' : '0.6') : '0.4',
- });
- if (clickable && arrived) {
- const idx = i;
- dot.addEventListener('click', (e) => {
- e.stopPropagation();
- visibleVariant = idx;
- showVariantInDOM(currentSessionId, idx);
- updateSelectedElement();
- updateBarContent('cycling');
- });
- }
- container.appendChild(dot);
- }
- return container;
- }
-
- function navBtn(text) {
- const b = el('button', {
- width: '26px', height: '26px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- color: BP.text, fontFamily: FONT, fontSize: '13px',
- cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
- transition: 'border-color 0.12s ease, background 0.12s ease',
- padding: '0', lineHeight: '1',
- });
- b.textContent = text;
- b.addEventListener('mouseenter', () => { b.style.borderColor = BP.text; });
- b.addEventListener('mouseleave', () => { b.style.borderColor = BP.hairline; });
- return b;
- }
-
- function actionLabel() {
- const a = ACTIONS.find(a => a.value === selectedAction);
- return a ? a.label : 'Freeform';
- }
-
- function el(tag, styles) {
- const e = document.createElement(tag);
- if (styles) Object.assign(e.style, styles);
- return e;
- }
-
- // ---------------------------------------------------------------------------
- // Action picker popover
- // ---------------------------------------------------------------------------
-
- function initActionPicker() {
- const P = barPaletteForTheme(detectPageTheme());
- pickerEl = document.createElement('div');
- pickerEl.id = PREFIX + '-picker';
- Object.assign(pickerEl.style, {
- position: 'fixed', zIndex: Z.picker,
- display: 'none', opacity: '0',
- transform: 'scale(0.96) translateY(4px)',
- transformOrigin: 'bottom left',
- transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
- background: P.surface,
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
- padding: '6px',
- fontFamily: FONT,
- backdropFilter: 'blur(10px)',
- WebkitBackdropFilter: 'blur(10px)',
- });
-
- // Build the chip grid
- const grid = el('div', {
- display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
- });
-
- ACTIONS.forEach(action => {
- const chip = el('button', {
- display: 'flex', flexDirection: 'column', alignItems: 'center',
- gap: '4px',
- padding: '8px 6px', borderRadius: '6px',
- border: 'none',
- background: action.value === selectedAction ? P.accentSoft : 'transparent',
- color: action.value === selectedAction ? P.accent : P.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.1s ease, color 0.1s ease',
- textAlign: 'center', whiteSpace: 'nowrap',
- });
- const iconWrap = el('span', {
- display: 'flex', alignItems: 'center', justifyContent: 'center',
- height: '20px', opacity: '0.9',
- });
- iconWrap.innerHTML = ICONS[action.value] || '';
- const labelEl = el('span', { lineHeight: '1' });
- labelEl.textContent = action.label;
- chip.appendChild(iconWrap);
- chip.appendChild(labelEl);
- chip.dataset.action = action.value;
- chip.addEventListener('mouseenter', () => {
- if (action.value !== selectedAction) chip.style.background = P.accentSoft;
- });
- chip.addEventListener('mouseleave', () => {
- chip.style.background = action.value === selectedAction ? P.accentSoft : 'transparent';
- });
- chip.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedAction = action.value;
- hideActionPicker();
- updateBarContent('configure');
- });
- grid.appendChild(chip);
- });
-
- pickerEl.appendChild(grid);
- document.body.appendChild(pickerEl);
- defangOutsideHandlers(pickerEl);
-
- // Cache the palette on the picker so toggleActionPicker's state refresh
- // uses the same theme-aware colors when it repaints chips.
- pickerEl.__iceq_palette = P;
- }
-
- function toggleActionPicker() {
- if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
- // Rebuild chips to reflect current selection
- const P = pickerEl.__iceq_palette || barPaletteForTheme(detectPageTheme());
- pickerEl.querySelectorAll('button').forEach(chip => {
- const isActive = chip.dataset.action === selectedAction;
- chip.style.background = isActive ? P.accentSoft : 'transparent';
- chip.style.color = isActive ? P.accent : P.text;
- });
- // Position above the bar
- const barRect = barEl.getBoundingClientRect();
- const pickerH = 170; // approximate; grows with icon + label rows
- let top = barRect.top - pickerH - 6;
- if (top < 8) top = barRect.bottom + 6;
- Object.assign(pickerEl.style, {
- top: top + 'px', left: barRect.left + 'px',
- display: 'block',
- });
- requestAnimationFrame(() => {
- pickerEl.style.opacity = '1';
- pickerEl.style.transform = 'scale(1) translateY(0)';
- });
- }
-
- function hideActionPicker() {
- if (!pickerEl) return;
- pickerEl.style.opacity = '0';
- pickerEl.style.transform = 'scale(0.96) translateY(4px)';
- setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
- }
-
- // ---------------------------------------------------------------------------
- // Params panel (per-variant coarse controls)
- //
- // Variants may declare a parameter manifest via a JSON attribute on the
- // variant wrapper:
- //
- // <div data-impeccable-variant="1"
- // data-impeccable-params='[{"id":"density","kind":"steps",...}]'>
- //
- // The panel docks to the right edge of the outline during CYCLING and
- // exposes 2-5 coarse knobs. Values apply to the variant wrapper so scoped
- // CSS can respond instantly without regeneration:
- //
- // range / numeric toggle → CSS var (`--p-<id>`) used via var(--p-foo, N)
- // steps / boolean toggle → data-p-<id> attribute used via :scope[data-p-foo="..."]
- //
- // On variant switch, values reset to that variant's declared defaults.
- // On accept, current values are sent in the event payload so the agent
- // can bake them into the source-file write.
- // ---------------------------------------------------------------------------
-
- let paramsPanelEl = null; // outer wrapper (overflow:hidden, clips the slide)
- let paramsPanelInner = null; // translating content (carries bg, padding, knobs)
- let paramsPanelBody = null; // grid holding the knob cells
- let paramsCurrentValues = {}; // {paramId: value} — mirror of the visible variant's live values
- let tuneOpen = false; // whether the Tune popover is open right now
-
- // Theme-aware Tune popover. Appears as a drawer that slides out from the
- // contextual bar's bar-facing edge (below if the bar sits below the
- // element, above otherwise). Same width as the bar. Auto-wraps to extra
- // rows when the knobs exceed one row. The bar's border-radius on the
- // popover side goes flat while open so the two shapes read as one.
- let paramsPanelPalette = null;
-
- function initParamsPanel() {
- paramsPanelPalette = barPaletteForTheme(detectPageTheme());
- const P = paramsPanelPalette;
-
- // Single element, always in the DOM. The slide animation is a CSS mask
- // with mask-size growing from 0% to 100% along the bar-facing axis — no
- // display toggle, no opacity toggle, no transform trickery. The mask
- // hides everything initially; as it grows, content is revealed from
- // the bar edge outward.
- paramsPanelEl = document.createElement('div');
- paramsPanelEl.id = PREFIX + '-params-panel';
- Object.assign(paramsPanelEl.style, {
- position: 'fixed', zIndex: String(Z.bar - 1),
- background: P.surfaceDeep,
- color: P.text,
- fontFamily: FONT,
- padding: '14px 18px',
- boxSizing: 'border-box',
- borderRadius: '0 0 10px 10px',
- pointerEvents: 'none',
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
-
- // clip-path is the same conceptual reveal as mask but with rock-solid
- // transition support across engines. Closed state clips from the far
- // edge; open = inset(0) shows everything.
- clipPath: 'inset(0 0 100% 0)',
- transition: 'clip-path 0.44s ' + EASE,
-
- // Park off-screen until positionParamsPanel places it. These are NOT
- // in the transition list, so they snap instantly — no fly-in from the
- // top-left when first shown.
- top: '-9999px', left: '-9999px', width: '0',
- });
-
- paramsPanelBody = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
- gap: '12px 16px',
- });
-
- paramsPanelEl.appendChild(paramsPanelBody);
- document.body.appendChild(paramsPanelEl);
- // Don't override pointer-events: the panel toggles between 'none' (closed,
- // click-through) and 'auto' (open) on its own. Just silence the host's
- // outside-interaction listeners while the panel is open.
- defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
- paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
- }
-
- function getVisibleVariantEl() {
- if (!currentSessionId) return null;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return null;
- return wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"]');
- }
-
- function parseVariantParams(variantEl) {
- if (!variantEl) return [];
- const raw = variantEl.getAttribute('data-impeccable-params');
- if (!raw) return [];
- try {
- const parsed = JSON.parse(raw);
- return Array.isArray(parsed) ? parsed : [];
- } catch (err) {
- console.warn('[impeccable] Invalid data-impeccable-params JSON:', err.message);
- return [];
- }
- }
-
- function applyParamValue(variantEl, param, value) {
- if (!variantEl) return;
- const attr = 'data-p-' + param.id;
- if (param.kind === 'range') {
- variantEl.style.setProperty('--p-' + param.id, String(value));
- } else if (param.kind === 'toggle') {
- const on = !!value;
- variantEl.style.setProperty('--p-' + param.id, on ? '1' : '0');
- if (on) variantEl.setAttribute(attr, 'on');
- else variantEl.removeAttribute(attr);
- } else if (param.kind === 'steps') {
- variantEl.setAttribute(attr, String(value));
- }
- }
-
- function applyParamDefaults(variantEl, params) {
- paramsCurrentValues = {};
- for (const p of params) {
- paramsCurrentValues[p.id] = p.default;
- applyParamValue(variantEl, p, p.default);
- }
- }
-
- function formatRangeValue(input) {
- const max = parseFloat(input.max), min = parseFloat(input.min);
- const v = parseFloat(input.value);
- if (!isFinite(v)) return input.value;
- return (max - min) <= 2 ? v.toFixed(2) : String(Math.round(v));
- }
-
- function buildParamsPanel(variantEl, params) {
- const P = paramsPanelPalette || barPaletteForTheme(detectPageTheme());
- paramsPanelBody.innerHTML = '';
- for (const p of params) {
- const row = el('div', { display: 'flex', flexDirection: 'column', gap: '6px' });
- const labelRow = el('div', {
- display: 'flex', justifyContent: 'space-between',
- alignItems: 'baseline', gap: '8px',
- });
- const lbl = el('span', {
- fontSize: '10.5px', fontWeight: '600', color: P.text,
- letterSpacing: '0.03em',
- });
- lbl.textContent = p.label || p.id;
- labelRow.appendChild(lbl);
- const readout = el('span', {
- fontSize: '10.5px', color: P.textDim,
- fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
- });
- labelRow.appendChild(readout);
- row.appendChild(labelRow);
-
- if (p.kind === 'range') {
- const input = document.createElement('input');
- input.type = 'range';
- input.min = String(p.min != null ? p.min : 0);
- input.max = String(p.max != null ? p.max : 1);
- input.step = String(p.step != null ? p.step : 0.05);
- input.value = String(p.default);
- Object.assign(input.style, {
- width: '100%', accentColor: C.brand, cursor: 'pointer',
- });
- readout.textContent = formatRangeValue(input);
- input.addEventListener('input', (e) => {
- e.stopPropagation();
- const v = parseFloat(input.value);
- paramsCurrentValues[p.id] = v;
- readout.textContent = formatRangeValue(input);
- applyParamValue(variantEl, p, v);
- queueCheckpoint('param_changed');
- });
- row.appendChild(input);
- } else if (p.kind === 'toggle') {
- const initial = !!p.default;
- readout.textContent = initial ? 'On' : 'Off';
- const track = el('button', {
- position: 'relative', width: '36px', height: '20px',
- borderRadius: '10px', border: 'none', padding: '0',
- cursor: 'pointer',
- background: initial ? C.brand : P.hairline,
- transition: 'background 0.15s ease',
- alignSelf: 'flex-start',
- });
- const knob = el('span', {
- position: 'absolute', top: '2px',
- left: initial ? '18px' : '2px',
- width: '16px', height: '16px', borderRadius: '50%',
- background: 'oklch(98% 0 0)',
- transition: 'left 0.18s ' + EASE,
- boxShadow: '0 1px 2px oklch(0% 0 0 / 0.2)',
- });
- track.appendChild(knob);
- track.addEventListener('click', (e) => {
- e.stopPropagation();
- const next = !paramsCurrentValues[p.id];
- paramsCurrentValues[p.id] = next;
- track.style.background = next ? C.brand : P.hairline;
- knob.style.left = next ? '18px' : '2px';
- readout.textContent = next ? 'On' : 'Off';
- applyParamValue(variantEl, p, next);
- queueCheckpoint('param_changed');
- });
- row.appendChild(track);
- } else if (p.kind === 'steps') {
- const opts = (p.options || []).map(o =>
- typeof o === 'string' ? { value: o, label: o } : o
- );
- const activeOpt = opts.find(o => o.value === p.default) || opts[0];
- readout.textContent = activeOpt ? activeOpt.label : String(p.default);
- const segRow = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(' + opts.length + ', 1fr)',
- gap: '1px', padding: '2px',
- background: P.hairline, borderRadius: '5px',
- });
- const segBtns = [];
- opts.forEach(o => {
- const active = o.value === p.default;
- const b = el('button', {
- padding: '5px 4px', border: 'none', borderRadius: '3px',
- background: active ? C.brand : 'transparent',
- color: active ? 'oklch(98% 0 0)' : P.text,
- fontFamily: FONT, fontSize: '10.5px', fontWeight: '500',
- cursor: 'pointer', whiteSpace: 'nowrap',
- transition: 'background 0.1s ease, color 0.1s ease',
- });
- b.textContent = o.label;
- b.addEventListener('click', (e) => {
- e.stopPropagation();
- paramsCurrentValues[p.id] = o.value;
- readout.textContent = o.label;
- segBtns.forEach(({ btn, val }) => {
- const on = val === o.value;
- btn.style.background = on ? C.brand : 'transparent';
- btn.style.color = on ? 'oklch(98% 0 0)' : P.text;
- });
- applyParamValue(variantEl, p, o.value);
- queueCheckpoint('param_changed');
- });
- segRow.appendChild(b);
- segBtns.push({ btn: b, val: o.value });
- });
- row.appendChild(segRow);
- }
-
- paramsPanelBody.appendChild(row);
- }
- }
-
- // Decide which way the popover opens: away from the picked element. If the
- // bar landed below the element, popover slides DOWN from the bar's bottom.
- // If the bar landed above, popover slides UP from the bar's top.
- function popoverDirection() {
- if (!barEl || !selectedElement) return 'below';
- const br = barEl.getBoundingClientRect();
- const er = selectedElement.getBoundingClientRect();
- return br.top >= er.bottom - 4 ? 'below' : 'above';
- }
-
- // The popover overlaps the bar by OVERLAP px on the bar-facing side. With
- // popover z-index below bar, that overlap sits behind bar (invisible) and
- // reinforces the "tucked behind" feel. Padding compensates so the real
- // content starts flush with bar's outer edge.
- const TUNE_OVERLAP = 6;
-
- // Closed clip-path depends on direction: for 'below' clip from the far
- // (bottom) edge so the reveal grows downward from the bar; for 'above'
- // clip from the top edge so the reveal grows upward from the bar.
- function closedClipPath(direction) {
- return direction === 'below' ? 'inset(0 0 100% 0)' : 'inset(100% 0 0 0)';
- }
-
- function setClipPath(value, withTransition) {
- const saved = paramsPanelEl.style.transition;
- if (!withTransition) paramsPanelEl.style.transition = 'none';
- paramsPanelEl.style.clipPath = value;
- if (!withTransition) {
- void paramsPanelEl.offsetHeight;
- paramsPanelEl.style.transition = saved;
- }
- }
-
- function positionParamsPanel() {
- if (!paramsPanelEl || !barEl || barEl.style.display === 'none') return;
- const br = barEl.getBoundingClientRect();
- const direction = popoverDirection();
- const prevDirection = paramsPanelEl.dataset.tuneDirection;
-
- // top/left/width are NOT in the transition list, so they snap instantly.
- paramsPanelEl.style.left = br.left + 'px';
- paramsPanelEl.style.width = br.width + 'px';
-
- if (direction === 'below') {
- paramsPanelEl.style.top = (br.bottom - TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '0 0 10px 10px';
- paramsPanelEl.style.paddingTop = (14 + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.paddingBottom = '14px';
- } else {
- const ih = paramsPanelEl.offsetHeight || 80;
- paramsPanelEl.style.top = (br.top - ih + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '10px 10px 0 0';
- paramsPanelEl.style.paddingTop = '14px';
- paramsPanelEl.style.paddingBottom = (14 + TUNE_OVERLAP) + 'px';
- }
- paramsPanelEl.dataset.tuneDirection = direction;
-
- // If currently closed and direction flipped (or first-time setup),
- // snap the clip-path to the new direction's closed pose without
- // transitioning (so the clip doesn't slide across the element).
- if (!tuneOpen && (!prevDirection || prevDirection !== direction)) {
- setClipPath(closedClipPath(direction), false);
- }
- }
-
- function showParamsPanel() {
- if (!paramsPanelEl) return;
- positionParamsPanel();
- paramsPanelEl.style.pointerEvents = 'auto';
- // rAF so the positioning paint commits before the transition fires.
- requestAnimationFrame(() => {
- setClipPath('inset(0 0 0 0)', true);
- });
- }
-
- function hideParamsPanel() {
- if (!paramsPanelEl) return;
- paramsPanelEl.style.pointerEvents = 'none';
- const direction = paramsPanelEl.dataset.tuneDirection || 'below';
- setClipPath(closedClipPath(direction), true);
- }
-
- // Build/rebuild the panel's contents for the current variant AND apply
- // its defaults to the variant wrapper (so scoped CSS responds even before
- // the user opens the popover). Visibility is governed by tuneOpen.
- function refreshParamsPanel() {
- if (state !== 'CYCLING') {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- if (tuneOpen) {
- // If already visible (variant cycled while open), refresh in place
- // instead of re-running the clip-path animation.
- const alreadyVisible = paramsPanelEl.style.display === 'block'
- && paramsPanelEl.style.opacity === '1';
- if (alreadyVisible) positionParamsPanel();
- else showParamsPanel();
- } else {
- hideParamsPanel();
- }
- }
-
- function toggleTunePopover() {
- if (tuneOpen) { closeTunePopover(); return; }
- openTunePopover();
- }
-
- function openTunePopover() {
- if (state !== 'CYCLING') return;
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) return;
- // Build fresh to ensure the current variant's controls are shown.
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- tuneOpen = true;
- showParamsPanel();
- // Kill the bar's shadow on the popover-facing side so the dark popover
- // doesn't pick up a bright glow line.
- if (barEl) {
- const direction = paramsPanelEl?.dataset.tuneDirection || 'below';
- barEl.style.boxShadow = direction === 'below' ? BAR_SHADOW_UP : BAR_SHADOW_DOWN;
- }
- // Re-render the bar so the Tune chip picks up the active styling.
- updateBarContent('cycling');
- }
-
- function closeTunePopover() {
- tuneOpen = false;
- hideParamsPanel();
- if (barEl) barEl.style.boxShadow = BAR_SHADOW_DEFAULT;
- if (barEl && barEl.style.display !== 'none' && state === 'CYCLING') {
- updateBarContent('cycling');
- }
- }
-
- // ---------------------------------------------------------------------------
- // Variant cycling in DOM
- // ---------------------------------------------------------------------------
-
- function showVariantInDOM(sessionId, num) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
- for (const child of wrapper.children) {
- const v = child.dataset ? child.dataset.impeccableVariant : null;
- if (!v) continue;
- child.style.display = (v === String(num)) ? '' : 'none';
- }
- // Unconditional refresh — covers first-reveal (no-op if state isn't
- // CYCLING yet, the subsequent CYCLING transition triggers its own
- // refresh) and every cycle step.
- refreshParamsPanel();
- }
-
- /**
- * No-HMR fallback: fetch the raw source file from the live server,
- * parse it, extract the variant wrapper, and inject it into the live DOM.
- * This works even when the dev server caches HTML (Bun, static servers).
- */
- function injectVariantsFromSource(filePath, sessionId) {
- const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
- fetch(url)
- .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
- .then(html => {
- // Parse the raw source HTML
- const parser = new DOMParser();
- const doc = parser.parseFromString(html, 'text/html');
- const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!srcWrapper) {
- console.error('[impeccable] Variant wrapper not found in source file.');
- return;
- }
-
- // Find the original element in the live DOM.
- // The original is inside the wrapper in the source. We find the
- // corresponding element in the live DOM by matching the first child's
- // tag + classes from the original snapshot.
- const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
- if (!origContent) return;
-
- const tag = origContent.tagName.toLowerCase();
- const cls = origContent.className;
- let liveEl = null;
- if (origContent.id) {
- liveEl = document.getElementById(origContent.id);
- } else if (cls) {
- // Find by tag + exact class match
- const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
- for (const c of candidates) {
- if (c.className === cls && !own(c)) { liveEl = c; break; }
- }
- }
-
- if (!liveEl) {
- console.error('[impeccable] Could not find original element in live DOM.');
- return;
- }
-
- const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;
-
- // Replace the live element with the full wrapper from source
- const wrapper = srcWrapper.cloneNode(true);
- liveEl.parentElement.replaceChild(wrapper, liveEl);
-
- // Update state: count variants, preserving the user's current variant
- // when a late HMR/source reinjection lands after they have cycled.
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants
- ? previousVisibleVariant
- : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);
- showVariantInDOM(sessionId, visibleVariant);
-
- // Update selectedElement to the visible variant's content
- selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;
-
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- saveSession();
- console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
- })
- .catch(err => {
- console.error('[impeccable] Failed to fetch source:', err);
- showToast('Could not load variants. Try refreshing the page.', 5000);
- });
- }
-
- function cycleVariant(dir) {
- const next = visibleVariant + dir;
- if (next < 1 || next > arrivedVariants) return;
- visibleVariant = next;
- showVariantInDOM(currentSessionId, next); // calls refreshParamsPanel itself
- updateSelectedElement();
- updateBarContent('cycling');
- saveSession();
- queueCheckpoint('variant_changed');
- }
-
- function updateSelectedElement() {
- if (!currentSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return;
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- function readVisibleVariantFromDOM(sessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return 0;
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- for (const variant of variants) {
- if (variant.style.display === 'none') continue;
- const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);
- if (idx > 0) return idx;
- }
- return 0;
- }
-
- // Resolve the element that represents the variant's visible content.
- // Contract: each variant div should contain exactly one top-level element
- // (the full replacement). In practice a model may ship loose siblings or
- // lead with <style>/<script>. Be defensive: skip non-visual elements, and
- // if the variant has multiple element children, use the variant div itself
- // (it wraps all of them and gets correct bounds).
- function pickVariantContent(wrapper, index) {
- if (!wrapper) return null;
- const variantDiv = wrapper.querySelector('[data-impeccable-variant="' + index + '"]');
- if (!variantDiv) return null;
- const NON_VISUAL = new Set(['STYLE', 'SCRIPT', 'LINK', 'META', 'TEMPLATE']);
- const visual = [];
- for (const child of variantDiv.children) {
- if (!NON_VISUAL.has(child.tagName)) visual.push(child);
- }
- if (visual.length === 1) return visual[0];
- return variantDiv;
- }
-
- // Hold window.scrollY at a fixed value across DOM mutations inside the
- // session's wrapper (HMR patches, variant inserts, cycle swaps).
- function startScrollLock(sessionId, initialTargetY) {
- stopScrollLock();
- scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)
- ? initialTargetY
- : window.scrollY;
- console.log('[impeccable.scroll] startScrollLock', { sessionId, scrollY: window.scrollY, targetY: scrollLockTargetY, initialOverride: initialTargetY });
-
- try { history.scrollRestoration = 'manual'; } catch {}
-
- const prevHtmlAnchor = document.documentElement.style.overflowAnchor;
- const prevBodyAnchor = document.body.style.overflowAnchor;
- document.documentElement.style.overflowAnchor = 'none';
- document.body.style.overflowAnchor = 'none';
-
- const correct = (why) => {
- scrollLockRaf = null;
- if (scrollLockTargetY == null) return;
- const before = window.scrollY;
- const delta = before - scrollLockTargetY;
- if (Math.abs(delta) < 0.5) {
- console.log('[impeccable.scroll] correct noop', { why, scrollY: before, targetY: scrollLockTargetY });
- return;
- }
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] corrected', { why, from: before, to: scrollLockTargetY, delta, nowAt: window.scrollY });
- };
- const schedule = (why) => {
- if (scrollLockRaf != null) return;
- scrollLockRaf = requestAnimationFrame(() => correct(why));
- };
-
- scrollLockObserver = new MutationObserver((mutations) => {
- for (const m of mutations) {
- if (m.target?.closest?.('[data-impeccable-variants="' + sessionId + '"]')) {
- const childAdds = Array.from(m.addedNodes).map(n => n.nodeType === 1 ? (n.tagName + (n.dataset?.impeccableVariant ? ('[variant=' + n.dataset.impeccableVariant + ']') : '')) : n.nodeType).join(',');
- console.log('[impeccable.scroll] mutation inside wrapper', { type: m.type, target: m.target?.tagName, adds: childAdds, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('mutation-in-wrapper');
- return;
- }
- for (const n of m.addedNodes) {
- if (n.nodeType === 1 && (n.matches?.('[data-impeccable-variants="' + sessionId + '"]') || n.querySelector?.('[data-impeccable-variants="' + sessionId + '"]'))) {
- console.log('[impeccable.scroll] wrapper node added', { tag: n.tagName, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('wrapper-added');
- return;
- }
- }
- }
- });
- scrollLockObserver.observe(document.body, { childList: true, subtree: true });
-
- scrollLockAbort = new AbortController();
- scrollLockAbort.signal.addEventListener('abort', () => {
- document.documentElement.style.overflowAnchor = prevHtmlAnchor;
- document.body.style.overflowAnchor = prevBodyAnchor;
- }, { once: true });
- const sig = { signal: scrollLockAbort.signal };
- // Track whether the most recent scroll came from a user gesture. We
- // gate user-scroll re-anchoring on this flag so programmatic smooth
- // scrolls (browser reload-restore, scrollIntoView from other scripts)
- // don't accidentally update our target.
- let userGestureAt = 0;
- const USER_GESTURE_WINDOW_MS = 250;
-
- const reanchor = (why) => {
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- const prevTarget = scrollLockTargetY;
- scrollLockTargetY = window.scrollY;
- writeScrollY(scrollLockTargetY);
- console.log('[impeccable.scroll] reanchor', { why, prevTarget, newTarget: scrollLockTargetY });
- };
- const markGesture = (why) => {
- userGestureAt = performance.now();
- reanchor(why);
- };
- window.addEventListener('wheel', () => markGesture('wheel'), { passive: true, ...sig });
- window.addEventListener('touchstart', () => markGesture('touchstart'), { passive: true, ...sig });
- window.addEventListener('touchmove', () => markGesture('touchmove'), { passive: true, ...sig });
- window.addEventListener('keydown', (e) => {
- if (['PageDown', 'PageUp', ' ', 'End', 'Home', 'ArrowDown', 'ArrowUp'].includes(e.key)) markGesture('key:' + e.key);
- }, sig);
-
- // Correct on EVERY scroll event: whether it's the browser's
- // post-reload animated restore or some other script calling
- // scrollIntoView, we want to snap back immediately. Only skip if a
- // user gesture fired in the last 250ms.
- let lastLoggedScrollY = window.scrollY;
- window.addEventListener('scroll', () => {
- const now = window.scrollY;
- if (Math.abs(now - lastLoggedScrollY) > 5) {
- console.log('[impeccable.scroll] scroll event', { from: lastLoggedScrollY, to: now, targetY: scrollLockTargetY });
- lastLoggedScrollY = now;
- }
- if (scrollLockTargetY == null) return;
- if (performance.now() - userGestureAt < USER_GESTURE_WINDOW_MS) return;
- if (Math.abs(now - scrollLockTargetY) < 0.5) return;
- console.log('[impeccable.scroll] scroll-event snap', { from: now, to: scrollLockTargetY });
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- }, { passive: true, ...sig });
-
- // Apply target synchronously, not via rAF — racing the browser's
- // restore or a smooth-scroll animation means we want to win now.
- if (Math.abs(window.scrollY - scrollLockTargetY) > 0.5) {
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] startScrollLock initial apply', { to: scrollLockTargetY });
- }
- }
-
- function stopScrollLock() {
- if (scrollLockObserver) { scrollLockObserver.disconnect(); scrollLockObserver = null; }
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }
- scrollLockTargetY = null;
- // NOTE: do NOT clear the persistent scroll key here. startScrollLock
- // calls us as a reset, and clearing the key would nuke the Go-time
- // scrollY that the next resume needs to read.
- }
-
- // ---------------------------------------------------------------------------
- // MutationObserver for progressive variant reveal
- // ---------------------------------------------------------------------------
-
- function startVariantObserver(sessionId) {
- let updating = false; // re-entrancy guard
-
- const obs = new MutationObserver((mutations) => {
- if (updating) return;
-
- // Only react to mutations that add nodes with data-impeccable-variant,
- // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
- let dominated = false;
- for (const m of mutations) {
- if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
- for (const n of m.addedNodes) {
- if (n.nodeType !== 1) continue;
- // Direct hit: the added node itself is the wrapper or a variant.
- if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
- dominated = true; break;
- }
- // Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
- // a whole subtree where the wrapper is a descendant of the added
- // node. Without this check, the observer ignores those mutations
- // and the session stays in GENERATING forever.
- if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
- dominated = true; break;
- }
- }
- if (dominated) break;
- }
- if (!dominated) return;
-
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
-
- // Re-anchor selectedElement if it was detached by live-wrap's HMR swap.
- // Without this, the shader / highlight / bar track a zero-rect phantom
- // and the overlay appears frozen.
- if (selectedElement && !document.body.contains(selectedElement)) {
- selectedElement = pickVariantContent(wrapper, 'original') || wrapper;
- }
-
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- const count = variants.length;
-
- // Nothing new
- if (count <= arrivedVariants) return;
-
- updating = true;
- arrivedVariants = count;
- if (visibleVariant === 0 && arrivedVariants > 0) {
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;
- showVariantInDOM(sessionId, visibleVariant);
- // showVariantInDOM hid the original (display:none); if we were still
- // anchored to the original's content, its boundingRect is now zero
- // and the bar snaps to (0,0). Re-point at the visible variant instead.
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- if (expected > 0) expectedVariants = expected;
-
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- } else if (state === 'GENERATING') {
- updateBarContent('generating');
- }
- saveSession();
- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');
- updating = false;
- });
-
- obs.observe(document.body, { childList: true, subtree: true });
- return obs;
- }
-
- // ---------------------------------------------------------------------------
- // Bar scroll tracking
- // ---------------------------------------------------------------------------
-
- function startScrollTracking() {
- function tick() {
- if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
- positionBar();
- showHighlight(selectedElement);
- if (tuneOpen) positionParamsPanel();
- }
- if (annotActive) positionAnnotOverlay(selectedElement);
- // Shader overlay (via debug P toggle or generation) is repositioned
- // by its own branch below; debug no longer has a separate overlay.
- if (shaderState) positionShaderOverlay();
- scrollRaf = requestAnimationFrame(tick);
- }
- scrollRaf = requestAnimationFrame(tick);
- }
-
- function stopScrollTracking() {
- if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
- }
-
- // ---------------------------------------------------------------------------
- // SSE (server→browser) + fetch POST (browser→server)
- // Zero-dependency replacement for WebSocket.
- // ---------------------------------------------------------------------------
-
- let evtSource = null;
- let sseRetries = 0;
- const SSE_MAX_RETRIES = 20; // generous: heartbeats keep the connection alive, so retries mean real trouble
-
- function connectSSE() {
- evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
-
- evtSource.onopen = () => {
- sseRetries = 0; // reset on successful (re)connect
- };
-
- evtSource.onmessage = (e) => {
- sseRetries = 0; // reset on any successful message
- let msg; try { msg = JSON.parse(e.data); } catch { return; }
- switch (msg.type) {
- case 'connected':
- hasProjectContext = !!msg.hasProjectContext;
- if (!hasProjectContext) showToast('No PRODUCT.md found. Variants will be brand-agnostic. Run /impeccable teach to generate one.', 7000);
- console.log('[impeccable] Live mode connected.');
- if (state === 'IDLE') state = 'PICKING';
- break;
- case 'done':
- // Variants already arrived via HMR → normal transition.
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- if (state === 'GENERATING') {
- state = 'CYCLING';
- updateBarContent('cycling');
- refreshParamsPanel();
- }
- break;
- }
- // Variants are in source but not in the DOM yet. Common when the
- // picked element lived inside conditional render (closed modal,
- // hidden tab, a route the user navigated away from). The variant
- // MutationObserver stays armed and auto-transitions to CYCLING
- // the moment the wrapper actually mounts. Nudge the user toward
- // that path with a toast — better than the prior force-reload
- // which reset framework state and left the session stuck.
- setTimeout(() => {
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
- if (state !== 'GENERATING') return;
- showToast(
- "Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
- 15000,
- );
- }, 2000);
- break;
- case 'error':
- console.error('[impeccable] Error:', msg.message);
- showToast('Error: ' + msg.message, 5000);
- hideBar();
- state = 'PICKING';
- break;
- }
- };
-
- evtSource.onerror = () => {
- sseRetries++;
- if (sseRetries <= SSE_MAX_RETRIES) {
- console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
- return; // EventSource auto-reconnects
- }
- // Server is gone. Clean up gracefully.
- console.log('[impeccable] Live server unreachable. Cleaning up UI.');
- evtSource.close();
- evtSource = null;
- handleServerLost();
- };
- }
-
- /** Server died or became unreachable. Reset UI to a clean state. */
- function handleServerLost() {
- const recoveryState = currentSessionId ? state : 'IDLE';
- if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
- showToast('Live server disconnected. Session ended.', 5000);
- }
- hideBar();
- hideHighlight();
- hideShaderOverlay();
- hideAnnotOverlay();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- // Preserve local session state on server loss. The durable journal is the
- // source of truth, but localStorage plus the variant wrapper lets the UI
- // resume after a helper restart or page reload instead of treating a
- // transient disconnect as an explicit discard.
- selectedElement = null;
- selectedAction = 'impeccable';
- state = recoveryState;
- if (currentSessionId) saveSession();
- }
-
- function sendEvent(msg, opts) {
- msg.token = TOKEN;
- function handleFailure(err) {
- console.error('[impeccable] Failed to send event:', err);
- if (opts && opts.throwOnError) throw err;
- return null;
- }
- return fetch('http://localhost:' + PORT + '/events', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(msg),
- }).then(res => {
- if (res.ok) return res;
- return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));
- }).catch(handleFailure);
- }
-
- function checkpointPayload(reason) {
- return {
- type: 'checkpoint',
- id: currentSessionId,
- revision: sessionState.nextCheckpointRevision(),
- owner: browserOwner,
- phase: String(state || '').toLowerCase(),
- reason,
- pageUrl: location.pathname,
- expectedVariants,
- arrivedVariants,
- visibleVariant,
- paramValues: { ...paramsCurrentValues },
- };
- }
-
- function sendCheckpoint(reason) {
- if (!currentSessionId) return Promise.resolve(null);
- return sendEvent(checkpointPayload(reason)).catch(() => null);
- }
-
- function queueCheckpoint(reason) {
- if (!currentSessionId) return;
- if (checkpointTimer) clearTimeout(checkpointTimer);
- checkpointTimer = setTimeout(() => {
- checkpointTimer = null;
- sendCheckpoint(reason);
- }, 120);
- }
-
- // ---------------------------------------------------------------------------
- // Event handlers
- // ---------------------------------------------------------------------------
-
- function handleMouseMove(e) {
- if (state !== 'PICKING' || !pickActive) return;
- const target = document.elementFromPoint(e.clientX, e.clientY);
- if (!target || !pickable(target) || target === hoveredElement) return;
- hoveredElement = target;
- showHighlight(target);
- }
-
- function handleClick(e) {
- // Close action picker on any outside click
- if (pickerEl?.style.display !== 'none' && !own(e.target)) {
- hideActionPicker();
- }
- // Close Tune popover on outside click (anything outside panel + bar)
- if (tuneOpen && paramsPanelEl && !paramsPanelEl.contains(e.target) && barEl && !barEl.contains(e.target)) {
- closeTunePopover();
- }
- // In CONFIGURING: click outside the bar and selected element returns to PICKING
- if (state === 'CONFIGURING' && !own(e.target) && selectedElement && !selectedElement.contains(e.target)) {
- hideBar();
- stopScrollTracking();
- hideAnnotOverlay();
- clearAnnotations();
- state = 'PICKING';
- hoveredElement = null;
- hideHighlight();
- return;
- }
- if (state !== 'PICKING' || !pickActive) return;
- if (own(e.target)) return;
- if (!hoveredElement || !pickable(hoveredElement)) return;
- e.preventDefault();
- e.stopPropagation();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- maybePrefetchPage();
- maybeWarnConditionalAncestor(selectedElement);
- }
-
- /**
- * Surface a brief, non-blocking heads-up when the picked element lives
- * inside a container whose visibility is gated by ephemeral state — modals,
- * collapsible panels, popovers, off-screen tab panels. If HMR remounts the
- * parent during generation (Vite Fast Refresh, SvelteKit page reload), the
- * variants land in source but stay invisible until the user re-opens the
- * container. Telling the user upfront is much friendlier than the silent
- * timeout-then-toast that they'd otherwise hit.
- *
- * Heuristic, intentionally narrow — only fires for unambiguous cases so
- * we don't cry wolf on every nested element.
- */
- function maybeWarnConditionalAncestor(el) {
- let node = el?.parentElement;
- let depth = 0;
- while (node && depth < 12) {
- // 1. Active dialog / modal
- if (node.getAttribute && node.getAttribute('role') === 'dialog'
- && node.getAttribute('aria-modal') === 'true') {
- showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 2. Common Radix / shadcn / headless-ui open-state attribute
- if (node.dataset && node.dataset.state === 'open') {
- showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 3. Tab panel — only meaningful when the page also shows ANOTHER
- // tab as selected. A single tabpanel with no tablist is just a static
- // section in disguise and isn't conditional.
- if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
- const list = document.querySelector('[role="tablist"]');
- if (list) {
- const tabs = list.querySelectorAll('[role="tab"]');
- if (tabs.length > 1) {
- showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
- return;
- }
- }
- }
- // 4. Collapsible: aria-expanded sibling. Look for the trigger button.
- if (node.id) {
- const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
- if (trigger) {
- showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
- return;
- }
- }
- node = node.parentElement;
- depth++;
- }
- }
-
- // Fire a lightweight prefetch event the first time the user selects an
- // element on a given route. The agent uses this to Read the underlying file
- // into context before Go is hit, shaving the read off the critical path.
- // Dedupe per session by pathname — clicking around on the same page doesn't
- // re-fire.
- //
- // DISABLED: quick-Go workflows pay an extra harness round trip because
- // prefetch + generate arrive as two events instead of one. Re-enable with
- // a browser-side debounce (~800–1000ms, cancelled on Go) if we want to
- // resurrect this. Server validator and skill dispatch remain in place so
- // flipping this flag is the only change needed.
- const PREFETCH_ENABLED = false;
- const prefetchedPaths = new Set();
- function maybePrefetchPage() {
- if (!PREFETCH_ENABLED) return;
- const path = location.pathname;
- if (prefetchedPaths.has(path)) return;
- prefetchedPaths.add(path);
- sendEvent({ type: 'prefetch', pageUrl: path });
- }
-
- function handleKeyDown(e) {
- // When the annotation input is focused, let it handle its own keys.
- if (annotEditing && annotEditing.input && e.target === annotEditing.input) return;
- if (e.key === 'Escape') {
- e.preventDefault();
- if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
- if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); hideAnnotOverlay(); clearAnnotations(); state = 'PICKING'; return; }
- if (state === 'CYCLING') { handleDiscard(); return; }
- if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
- if (state === 'PICKING') {
- // Use togglePick so the "Pick" button in the global bar also flips
- // off, otherwise the bar stays lit while nothing else is active.
- if (pickActive) togglePick();
- else { hideHighlight(); state = 'IDLE'; }
- return;
- }
- }
-
- // Arrow/Enter nav works in PICKING (hover) and CONFIGURING (selected, input empty)
- var navEl = (state === 'PICKING') ? hoveredElement : (state === 'CONFIGURING') ? selectedElement : null;
- if (navEl && (e.key === 'ArrowUp' || e.key === 'ArrowDown' || (e.key === 'Enter' && state === 'PICKING'))) {
- let next = null;
- if (e.key === 'ArrowDown' && !e.shiftKey) {
- next = navEl.nextElementSibling;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'ArrowUp' && !e.shiftKey) {
- next = navEl.previousElementSibling;
- while (next && !pickable(next)) next = next.previousElementSibling;
- } else if (e.key === 'ArrowUp' && e.shiftKey) {
- next = navEl.parentElement;
- if (next && !pickable(next)) next = null;
- } else if (e.key === 'ArrowDown' && e.shiftKey) {
- next = navEl.firstElementChild;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'Enter') {
- e.preventDefault();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- return;
- }
- if (next) {
- e.preventDefault();
- if (state === 'PICKING') {
- hoveredElement = next;
- } else {
- // CONFIGURING: re-select the new element and refresh the bar
- selectedElement = next;
- clearAnnotations();
- showAnnotOverlay(next);
- showBar('configure');
- startScrollTracking();
- }
- showHighlight(next);
- next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
- }
- return;
- }
-
- if (state === 'CYCLING') {
- if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
- if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
- if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
- }
- }
-
- function handleGo() {
- if (!selectedElement || state !== 'CONFIGURING') return;
- const input = document.getElementById(PREFIX + '-input');
- const prompt = input ? input.value.trim() : '';
-
- // Commit any pending pin edit BEFORE we snapshot annotations.
- if (annotEditing) finalizeEditingPin();
-
- currentSessionId = id8();
- expectedVariants = selectedCount;
- arrivedVariants = 0;
- visibleVariant = 0;
-
- // Flip to GENERATING immediately so the bar morphs without waiting on
- // capture + upload. The event is emitted from captureAndEmit() once the
- // screenshot is uploaded (or capture fails — we still emit, just without
- // screenshotPath).
- const elForCapture = selectedElement;
- const captureRect = elForCapture.getBoundingClientRect();
- const snapshot = {
- comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),
- strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),
- };
- const basePayload = {
- type: 'generate', id: currentSessionId,
- action: selectedAction,
- freeformPrompt: prompt || undefined,
- count: selectedCount,
- pageUrl: location.pathname,
- element: extractContext(elForCapture),
- };
- if (snapshot.comments.length > 0) basePayload.comments = snapshot.comments;
- if (snapshot.strokes.length > 0) basePayload.strokes = snapshot.strokes;
-
- // Hide the interactive overlay so it doesn't linger during generation.
- hideAnnotOverlay();
- clearAnnotations();
-
- state = 'GENERATING';
- showBar('generating');
- saveSession();
- sendCheckpoint('generate_started');
- writeScrollY(window.scrollY);
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
- console.log('[impeccable.scroll] Go pressed', { scrollY: window.scrollY, sessionId: currentSessionId });
- startScrollLock(currentSessionId);
-
- captureAndEmit(elForCapture, basePayload, snapshot, captureRect);
- }
-
- // ---------------------------------------------------------------------------
- // Screenshot capture + upload
- // ---------------------------------------------------------------------------
-
- let msLoadPromise = null;
- function loadModernScreenshot() {
- if (window.modernScreenshot) return Promise.resolve(window.modernScreenshot);
- if (msLoadPromise) return msLoadPromise;
- msLoadPromise = new Promise((resolve, reject) => {
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/modern-screenshot.js';
- s.onload = () => resolve(window.modernScreenshot);
- s.onerror = () => { msLoadPromise = null; reject(new Error('modern-screenshot failed to load')); };
- document.head.appendChild(s);
- });
- return msLoadPromise;
- }
-
- // Collect @font-face rules from every stylesheet on the page. Cross-origin
- // sheets (Google Fonts, Typekit, etc.) throw SecurityError on .cssRules
- // access, so modern-screenshot can't embed them on its own — the resulting
- // SVG falls back to system fonts and text re-wraps + renders with different
- // weight. We fetch the raw CSS text (CORS-permitted for these providers),
- // extract @font-face blocks, inline the referenced font files as base64
- // data URIs (SVGs rasterized via canvas can't fetch external resources,
- // so URLs inside the SVG silently fail without this), and pass the result
- // to modern-screenshot as font.cssText.
- const FONT_EXT_RE = /\.(woff2?|ttf|otf|eot)(\?.*)?$/i;
- const FONT_MIME = {
- woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', eot: 'application/vnd.ms-fontobject',
- };
- function bufferToBase64(buf) {
- const bytes = new Uint8Array(buf);
- let binary = '';
- const CHUNK = 0x8000;
- for (let i = 0; i < bytes.length; i += CHUNK) {
- binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
- }
- return btoa(binary);
- }
- async function inlineFontUrls(cssText) {
- const urlRe = /url\((['"]?)(https?:\/\/[^'")\s]+)\1\)/g;
- const urls = new Set();
- let m;
- while ((m = urlRe.exec(cssText))) {
- if (FONT_EXT_RE.test(m[2])) urls.add(m[2]);
- }
- const map = new Map();
- await Promise.all([...urls].map(async (url) => {
- try {
- const res = await fetch(url);
- if (!res.ok) return;
- const buf = await res.arrayBuffer();
- const ext = url.toLowerCase().match(FONT_EXT_RE)?.[1] || 'woff2';
- const mime = FONT_MIME[ext] || 'application/octet-stream';
- map.set(url, 'data:' + mime + ';base64,' + bufferToBase64(buf));
- } catch { /* skip; fall through to URL */ }
- }));
- return cssText.replace(urlRe, (orig, q, url) => {
- const data = map.get(url);
- return data ? 'url(' + q + data + q + ')' : orig;
- });
- }
- async function collectFontCssText() {
- const chunks = [];
- const fontFaceRe = /@font-face\s*\{[^}]*\}/g;
- for (const sheet of document.styleSheets) {
- try {
- const rules = sheet.cssRules;
- for (const rule of rules) {
- if (rule.constructor.name === 'CSSFontFaceRule' || rule.cssText?.startsWith('@font-face')) {
- chunks.push(rule.cssText);
- }
- }
- } catch {
- if (!sheet.href) continue;
- try {
- const res = await fetch(sheet.href);
- if (!res.ok) continue;
- const text = await res.text();
- let m2;
- while ((m2 = fontFaceRe.exec(text))) chunks.push(m2[0]);
- } catch { /* ignore; capture is best-effort */ }
- }
- }
- if (chunks.length === 0) return '';
- return inlineFontUrls(chunks.join('\n'));
- }
-
- // True if `s` is a computed color string that renders as nothing
- // (explicit `transparent`, or `rgba(...)` with alpha 0).
- function isTransparentColor(s) {
- if (!s) return true;
- if (s === 'transparent') return true;
- const m = /rgba?\(([^)]+)\)/.exec(s);
- if (!m) return false;
- const parts = m[1].split(',').map((p) => p.trim());
- if (parts.length === 4) return parseFloat(parts[3]) === 0;
- return false;
- }
-
- // modern-screenshot force-sets `background-color: X !important` on the
- // cloned root whenever `backgroundColor` is passed, clobbering the
- // element's own background. So we only pass it when the element is
- // genuinely transparent (no own color, no own image) — in that case
- // we resolve up the DOM to the nearest opaque ancestor so the capture
- // sits on the page's real background instead of rendering black.
- function resolveCanvasBackground(el) {
- const own = getComputedStyle(el);
- if (!isTransparentColor(own.backgroundColor)) return null;
- if (own.backgroundImage && own.backgroundImage !== 'none') return null;
- let node = el.parentElement;
- while (node) {
- const cs = getComputedStyle(node);
- if (!isTransparentColor(cs.backgroundColor)) return cs.backgroundColor;
- node = node.parentElement;
- }
- // The walk already passed through <body> and <html>; if they had been
- // opaque we would have returned. Falling through with the previous
- // `getComputedStyle(body).backgroundColor || …` chain is a trap: that
- // call returns the literal string `"rgba(0, 0, 0, 0)"` for a page that
- // never set its own bg, which is truthy and short-circuits the chain to
- // transparent-black — modern-screenshot then renders the capture on a
- // black canvas and the shader overlay flashes solid black during load.
- // The browser canvas defaults to white, so we do too.
- return '#ffffff';
- }
-
- // Capture the element (with current annotations baked in) and return a PNG
- // Blob. Shared between the Go flow (uploads it to the server) and the
- // debug toggle (displays it as an overlay for side-by-side comparison).
- async function captureElementToBlob(el, snapshot, rect) {
- try { if (document.fonts?.ready) await document.fonts.ready; } catch {}
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- let annotNode = null;
- let savedPosition = null;
- if (hasAnnotations) {
- const pos = getComputedStyle(el).position;
- if (pos === 'static') {
- savedPosition = el.style.position;
- el.style.position = 'relative';
- }
- annotNode = buildAnnotationsForCapture(rect, snapshot);
- el.appendChild(annotNode);
- }
- try {
- const ms = await loadModernScreenshot();
- const fontCssText = await collectFontCssText();
- const backgroundColor = resolveCanvasBackground(el);
- return await ms.domToBlob(el, {
- scale: Math.min(window.devicePixelRatio || 1, 2),
- font: fontCssText ? { cssText: fontCssText } : undefined,
- ...(backgroundColor ? { backgroundColor } : {}),
- });
- } finally {
- if (annotNode) annotNode.remove();
- if (savedPosition !== null) el.style.position = savedPosition;
- }
- }
-
- async function captureAndEmit(el, basePayload, snapshot, rect) {
- let screenshotPath;
- let blob;
- try {
- blob = await captureElementToBlob(el, snapshot, rect);
- } catch (err) {
- console.warn('[impeccable] capture failed, proceeding without screenshot:', err);
- }
- // Light up the shader overlay the moment capture is ready — no reason to
- // wait for the upload to complete before the user sees something alive.
- if (blob && state === 'GENERATING') {
- showShaderOverlay(el, blob, rect);
- }
- // Only upload + forward the screenshot when annotations (comments/strokes)
- // are present. Without annotations the image is pure visual anchoring —
- // it biases the model toward the current rendering and works against the
- // three-distinct-directions brief.
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- if (blob && hasAnnotations) {
- try {
- const uploadRes = await fetch(
- 'http://localhost:' + PORT + '/annotation?token=' + encodeURIComponent(TOKEN) +
- '&eventId=' + encodeURIComponent(basePayload.id),
- { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: blob },
- );
- if (uploadRes.ok) {
- const { path: p } = await uploadRes.json();
- screenshotPath = p;
- } else {
- console.warn('[impeccable] annotation upload failed:', uploadRes.status);
- }
- } catch (err) {
- console.warn('[impeccable] annotation upload failed:', err);
- }
- }
- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);
- }
-
- // ---------------------------------------------------------------------------
- // Shader overlay — renders the captured screenshot as a WebGL texture and
- // runs an editorial "ink-wash" fragment shader over it during generation.
- // A single rolling band sweeps top-to-bottom, desaturating + tinting magenta
- // and leaving a soft trail. Makes the wait feel like a letterpress scan
- // instead of a dead spinner.
- // ---------------------------------------------------------------------------
-
- const SHADER_VS = `attribute vec2 a_position;
-attribute vec2 a_uv;
-varying vec2 v_uv;
-void main() {
- v_uv = a_uv;
- gl_Position = vec4(a_position, 0.0, 1.0);
-}`;
-
- const SHADER_FS = `precision highp float;
-uniform sampler2D u_texture;
-uniform float u_time;
-uniform vec2 u_resolution;
-uniform vec3 u_accent;
-varying vec2 v_uv;
-
-// Asymmetric roller band. Product of two one-sided smoothsteps — peaks at
-// d=0 with a short sharp leading ramp and a longer soft trailing tail. Clean
-// outside the [-leadW, trailW] range (no rogue "trail=1 everywhere below"
-// failure that reversed-edge smoothstep would give).
-float bandAt(float d, float leadW, float trailW) {
- float above = smoothstep(-leadW, 0.0, d);
- float below = 1.0 - smoothstep(0.0, trailW, d);
- return above * below;
-}
-
-void main() {
- vec2 uv = v_uv;
- // Roller sweeps top-to-bottom with small overshoot so each cycle enters
- // and exits the element cleanly.
- float phase = fract(u_time / 3.4);
- float y = phase * 1.25 - 0.12;
- float band = bandAt(uv.y - y, 0.05, 0.32);
-
- // Halftone cell grid (fixed ~10 px pitch).
- float cellPx = 10.0;
- vec2 gridUv = uv * u_resolution / cellPx;
- vec2 cellId = floor(gridUv);
- vec2 cellUv = fract(gridUv) - 0.5;
- vec2 sampleCenter = (cellId + 0.5) * cellPx / u_resolution;
- vec3 cellImg = texture2D(u_texture, sampleCenter).rgb;
- float luma = dot(cellImg, vec3(0.299, 0.587, 0.114));
- // Darker cells → bigger magenta dots (classic risograph halftone curve).
- float radius = sqrt(clamp(1.0 - luma, 0.0, 1.0)) * 0.56;
- float dotMask = smoothstep(radius + 0.06, radius, length(cellUv));
- vec3 paper = vec3(0.975, 0.965, 0.955);
- vec3 dotLayer = mix(paper, u_accent, dotMask);
-
- // Blend the halftone layer in where the roller is passing; leave the
- // element pristine elsewhere.
- vec3 base = texture2D(u_texture, uv).rgb;
- gl_FragColor = vec4(mix(base, dotLayer, band), 1.0);
-}`;
-
- // Editorial Magenta converted to approximate sRGB 0-1 (matches oklch(60% 0.25 350))
- const SHADER_ACCENT = [0.82, 0.16, 0.47];
- let shaderState = null; // { canvas, gl, program, texture, rafId, startTime }
-
- function compileShader(gl, type, source) {
- const sh = gl.createShader(type);
- gl.shaderSource(sh, source);
- gl.compileShader(sh);
- if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
- const info = gl.getShaderInfoLog(sh);
- gl.deleteShader(sh);
- throw new Error('shader compile failed: ' + info);
- }
- return sh;
- }
-
- function positionShaderOverlay() {
- if (!shaderState || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- Object.assign(shaderState.canvas.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- }
-
- function hideShaderOverlay() {
- if (!shaderState) return;
- if (shaderState.rafId) cancelAnimationFrame(shaderState.rafId);
- if (shaderState.canvas) shaderState.canvas.remove();
- const lose = shaderState.gl?.getExtension?.('WEBGL_lose_context');
- try { lose?.loseContext(); } catch {}
- shaderState = null;
- }
-
- async function showShaderOverlay(el, blob, rect) {
- hideShaderOverlay();
- if (!blob || !el) return;
- const canvas = document.createElement('canvas');
- canvas.id = PREFIX + '-shader';
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
- canvas.width = Math.max(1, Math.floor(rect.width * dpr));
- canvas.height = Math.max(1, Math.floor(rect.height * dpr));
- Object.assign(canvas.style, {
- position: 'fixed',
- top: rect.top + 'px', left: rect.left + 'px',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none',
- zIndex: Z.bar - 1,
- });
- document.body.appendChild(canvas);
-
- const gl = canvas.getContext('webgl', { premultipliedAlpha: false, preserveDrawingBuffer: false })
- || canvas.getContext('experimental-webgl');
- if (!gl) {
- // WebGL unavailable — fall back to a plain <img> overlay so the user
- // still sees something meaningful during generation.
- canvas.remove();
- const img = document.createElement('img');
- img.src = URL.createObjectURL(blob);
- img.id = PREFIX + '-shader';
- // Copy positioning via cssText. Object.assign across CSSStyleDeclaration
- // throws in modern Chromium because the source's indexed properties
- // (style[0], [1], ...) are read-only and the engine forbids writing
- // them on the destination.
- img.style.cssText = canvas.style.cssText;
- img.style.outline = '2px dashed ' + C.brand;
- img.style.outlineOffset = '-2px';
- document.body.appendChild(img);
- shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
- return;
- }
-
- let program, texture;
- try {
- const vs = compileShader(gl, gl.VERTEX_SHADER, SHADER_VS);
- const fs = compileShader(gl, gl.FRAGMENT_SHADER, SHADER_FS);
- program = gl.createProgram();
- gl.attachShader(program, vs);
- gl.attachShader(program, fs);
- gl.linkProgram(program);
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- throw new Error('program link failed: ' + gl.getProgramInfoLog(program));
- }
- // Full-screen quad
- const buf = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
- -1, -1, 0, 1,
- 1, -1, 1, 1,
- -1, 1, 0, 0,
- -1, 1, 0, 0,
- 1, -1, 1, 1,
- 1, 1, 1, 0,
- ]), gl.STATIC_DRAW);
- const posLoc = gl.getAttribLocation(program, 'a_position');
- const uvLoc = gl.getAttribLocation(program, 'a_uv');
- gl.enableVertexAttribArray(posLoc);
- gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 16, 0);
- gl.enableVertexAttribArray(uvLoc);
- gl.vertexAttribPointer(uvLoc, 2, gl.FLOAT, false, 16, 8);
- } catch (err) {
- console.warn('[impeccable] shader setup failed:', err);
- canvas.remove();
- return;
- }
-
- // Upload the screenshot as a texture
- let bitmap;
- try {
- bitmap = await createImageBitmap(blob);
- } catch {
- // Safari fallback: go via a regular Image
- const imgUrl = URL.createObjectURL(blob);
- const img = new Image();
- img.src = imgUrl;
- await new Promise((r, rej) => { img.onload = r; img.onerror = rej; });
- bitmap = img;
- URL.revokeObjectURL(imgUrl);
- }
- texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
- if (bitmap.close) bitmap.close();
-
- const uTime = gl.getUniformLocation(program, 'u_time');
- const uRes = gl.getUniformLocation(program, 'u_resolution');
- const uAccent = gl.getUniformLocation(program, 'u_accent');
- const uTex = gl.getUniformLocation(program, 'u_texture');
- const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-
- shaderState = { canvas, gl, program, texture, rafId: 0, startTime: performance.now(), reduced };
- function frame() {
- if (!shaderState) return;
- const elapsed = (performance.now() - shaderState.startTime) / 1000;
- const t = shaderState.reduced ? 0.0 : elapsed;
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.useProgram(program);
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.uniform1i(uTex, 0);
- gl.uniform1f(uTime, t);
- gl.uniform2f(uRes, canvas.width, canvas.height);
- gl.uniform3f(uAccent, SHADER_ACCENT[0], SHADER_ACCENT[1], SHADER_ACCENT[2]);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- shaderState.rafId = requestAnimationFrame(frame);
- }
- frame();
- }
-
- function handleAccept() {
- if (!currentSessionId || arrivedVariants === 0) return;
- const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);
- if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;
- const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };
- if (Object.keys(paramsCurrentValues).length > 0) {
- acceptPayload.paramValues = { ...paramsCurrentValues };
- }
- // The accepted variant is already the only visible child of the wrapper
- // (all other variants are display:none). HMR from the source rewrite will
- // replace the wrapper imminently. Don't eagerly replaceChild here — React
- // reconciliation races with our mutation and throws NotFoundError in Next
- // 16 / Turbopack. Schedule a fallback that runs the manual swap only if
- // HMR hasn't cleaned up by then (keeps static-server flows working).
- const acceptedSessionId = currentSessionId;
- const acceptedVariant = visibleVariant;
-
- state = 'SAVING';
- updateBarContent('saving');
-
- sendEvent(acceptPayload, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- confirmAcceptAfterReceipt();
- })
- .catch(() => {
- state = 'CYCLING';
- updateBarContent('cycling');
- showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);
- });
-
- function confirmAcceptAfterReceipt() {
- state = 'CONFIRMED';
- updateBarContent('confirmed');
- scheduleAcceptCleanup();
- }
-
- function scheduleAcceptCleanup() {
- setTimeout(function() {
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }, 1800);
-
- // Static-server / no-HMR fallback: if the wrapper is still around 2s after
- // the cleanup above, swap it out manually. By now React has either moved
- // on or the app isn't React at all. Preserve the `data-impeccable-variant="N"`
- // div (with display:contents) so @scope rules anchored to the variant
- // attribute keep matching until reload replaces it with the carbonize block.
- setTimeout(function() {
- const wrapper = document.querySelector('[data-impeccable-variants="' + acceptedSessionId + '"]');
- if (!wrapper) return;
- const accepted = wrapper.querySelector('[data-impeccable-variant="' + acceptedVariant + '"]');
- if (accepted && accepted.firstElementChild) {
- const parent = wrapper.parentElement;
- if (!parent) return;
- accepted.style.display = 'contents';
- parent.replaceChild(accepted, wrapper);
- }
- }, 2000);
- }
- }
-
- function handleDiscard() {
- if (!currentSessionId) return;
- sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- cleanup();
- })
- .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));
- }
-
- // ---------------------------------------------------------------------------
- // Session persistence via live-browser-session.js
- // ---------------------------------------------------------------------------
- // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
-
- function saveSession() {
- if (!currentSessionId) return;
- // NOTE: scrollY is stored under a separate key (writeScrollY). Storing
- // it here would overwrite the Go-time value every time state changes.
- sessionState.saveSession({
- id: currentSessionId,
- state,
- action: selectedAction,
- count: selectedCount,
- expected: expectedVariants,
- arrived: arrivedVariants,
- visible: visibleVariant,
- });
- }
-
- function loadSession() {
- return sessionState.loadSession();
- }
-
- function clearSession() {
- sessionState.clearSession();
- }
-
- /** Mark session as handled (accepted/discarded). The agent will clean up
- * the source, but until it does the wrapper is still in the HTML. This
- * prevents resumeSession from picking it up again after reload. */
- function markSessionHandled() {
- if (!currentSessionId) return;
- sessionState.markHandled(currentSessionId);
- }
-
- function isSessionHandled(id) {
- return sessionState.isHandled(id);
- }
-
- function clearHandled() {
- sessionState.clearHandled();
- }
-
- function cleanup() {
- // Hide the wrapper immediately so variants disappear. DON'T structurally
- // mutate the DOM yet — HMR from the agent's source rewrite is on its way,
- // and a manual replaceChild under React causes NotFoundError when the
- // reconciler later tries to remove a wrapper we already removed.
- // Schedule a 2s fallback that does the manual swap only if HMR hasn't
- // replaced the wrapper by then (keeps static-server / no-HMR flows alive).
- const cleanupSessionId = currentSessionId;
- if (cleanupSessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (wrapper) wrapper.style.display = 'none';
- }
- setTimeout(function() {
- if (!cleanupSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (!wrapper) return;
- const orig = wrapper.querySelector('[data-impeccable-variant="original"]');
- if (orig) {
- const content = orig.firstElementChild;
- if (content) {
- wrapper.parentElement.replaceChild(content, wrapper);
- return;
- }
- }
- wrapper.remove();
- }, 2000);
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }
-
- // ---------------------------------------------------------------------------
- // Toast
- // ---------------------------------------------------------------------------
-
- function showToast(message, duration) {
- if (toastEl) toastEl.remove();
- // Stack the toast above the global bar (which sits at bottom:14px) so
- // the two never overlap. Read the bar's actual rect — its height varies
- // with hover-expanded labels — and fall back to a sensible default
- // when the bar isn't mounted yet.
- const barRect = globalBarEl?.getBoundingClientRect();
- const barTopFromBottom = barRect && barRect.height > 0
- ? Math.max(16, window.innerHeight - barRect.top + 12)
- : 16;
- toastEl = el('div', {
- position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
- transform: 'translateX(-50%) translateY(8px)',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px',
- padding: '8px 16px', borderRadius: '8px',
- zIndex: Z.toast, opacity: '0',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
- pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
- });
- toastEl.id = PREFIX + '-toast';
- toastEl.textContent = message;
- document.body.appendChild(toastEl);
- requestAnimationFrame(() => {
- toastEl.style.opacity = '1';
- toastEl.style.transform = 'translateX(-50%) translateY(0)';
- });
- setTimeout(() => {
- if (toastEl) {
- toastEl.style.opacity = '0';
- toastEl.style.transform = 'translateX(-50%) translateY(8px)';
- setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
- }
- }, duration);
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- // Resume an active variant session after HMR/page reload.
- // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
- // variants before HMR fired. Pick up where we left off.
- function resumeSession() {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) { clearSession(); clearHandled(); return false; }
-
- const sessionId = wrapper.dataset.impeccableVariants;
-
- // Don't resume if this session was already accepted/discarded
- if (isSessionHandled(sessionId)) return false;
-
- currentSessionId = sessionId;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
-
- // Restore state from localStorage if available
- const saved = loadSession();
- if (saved && saved.id === sessionId) {
- visibleVariant = (saved.visible > 0 && saved.visible <= arrivedVariants) ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
- if (saved.action) selectedAction = saved.action;
- if (saved.count) selectedCount = saved.count;
- } else {
- visibleVariant = arrivedVariants > 0 ? 1 : 0;
- }
-
- // Find the visible variant's content element for highlight positioning.
- // Try the visible variant first, fall back to the original's content.
- const visEl = visibleVariant > 0 ? pickVariantContent(wrapper, visibleVariant) : null;
- const origEl = pickVariantContent(wrapper, 'original');
- selectedElement = visEl || origEl || wrapper.parentElement;
-
- // Set display state BEFORE starting observer (avoid triggering it)
- if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
-
- state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
- showBar(state === 'CYCLING' ? 'cycling' : 'generating');
- startScrollTracking();
- // Build the params panel for the restored visible variant. Previously
- // this was missed on page-reload resume: showVariantInDOM above fires
- // refreshParamsPanel, but state was still IDLE at that moment so it
- // hid. Now that state is CYCLING, re-fire.
- if (state === 'CYCLING') refreshParamsPanel();
- saveSession();
- queueCheckpoint('browser_resumed');
-
- // Start observing for more variants AFTER initial setup
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
-
- // Hold the target at its saved viewport top through any subsequent
- // HMR patches, variant inserts, or cycle swaps.
- startScrollLock(currentSessionId, readScrollY());
-
- // If we reloaded mid-generation (Bun's HTML HMR destroys the shader
- // canvas), re-capture the original's content and restart the shader so
- // the wait doesn't go dead.
- if (state === 'GENERATING' && origEl) {
- (async () => {
- try {
- const rect = origEl.getBoundingClientRect();
- if (rect.width === 0 || rect.height === 0) return;
- const blob = await captureElementToBlob(origEl, null, rect);
- if (blob && state === 'GENERATING') {
- showShaderOverlay(origEl, blob, rect);
- }
- } catch (err) {
- console.warn('[impeccable] shader resume failed:', err);
- }
- })();
- }
- return true;
- }
-
- // ---------------------------------------------------------------------------
- // Global bar (always visible at bottom)
- // ---------------------------------------------------------------------------
-
- let globalBarEl = null;
- let detectActive = false;
- let pickActive = true;
- let detectCount = 0;
- let detectScriptLoaded = false;
-
- // Theme-aware color palette for the global bar. We detect the page's
- // ambient background and invert — dark bar on light pages, light bar on
- // dark pages. This keeps the bar from fighting with the host design.
- function detectPageTheme() {
- try {
- // Dev override: set localStorage 'impeccable-dev-theme' to 'light' or
- // 'dark' to preview the opposite palette without actually changing the
- // page bg. Used for screenshots and theme QA.
- const override = localStorage.getItem('impeccable-dev-theme');
- if (override === 'light' || override === 'dark') return override;
-
- // Walk body → html, taking the first opaque background. The browser's
- // default body / html background is `rgba(0, 0, 0, 0)`, which a naive
- // regex would read as black and mislabel a perfectly white page as
- // dark. Honoring alpha avoids that — and falling through to <html>
- // catches the common pattern of a bg only on <html> (or only on body).
- function readOpaque(el) {
- if (!el) return null;
- const bg = getComputedStyle(el).backgroundColor;
- const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
- if (!m) return null;
- const alpha = m[4] == null ? 1 : parseFloat(m[4]);
- if (alpha < 0.5) return null; // transparent / nearly transparent → skip
- return [+m[1], +m[2], +m[3]];
- }
-
- const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
- // Both transparent → fall back to the browser's effective canvas color.
- // White is the universal default; only one in a thousand sites swaps it
- // via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
- // us catch that case.
- if (!rgb) {
- return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
- }
- const [r, g, b] = rgb;
- // Perceptual luminance (Rec. 709)
- const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
- return L > 0.55 ? 'light' : 'dark';
- } catch { return 'light'; }
- }
-
- function barPaletteForTheme(theme) {
- if (theme === 'dark') {
- // Light bar on dark page
- return {
- surface: 'oklch(98% 0 0 / 0.92)',
- surfaceDeep: 'oklch(92% 0.005 60 / 0.96)', // slightly deeper, faint warm
- hairline: 'oklch(70% 0 0 / 0.35)',
- text: 'oklch(15% 0 0)',
- textDim: 'oklch(45% 0 0)',
- accent: 'oklch(60% 0.25 350)',
- accentSoft: 'oklch(60% 0.25 350 / 0.18)',
- mark: 'oklch(98% 0 0)', // logo mark fill
- markText: 'oklch(15% 0 0)', // logo "/" color
- exitHover: 'oklch(85% 0 0 / 0.5)',
- };
- }
- // Dark bar on light page. Bar is a warm charcoal, logo slab is much
- // deeper so the rounded-right shape reads as a clear sculpted mark.
- return {
- surface: 'oklch(26% 0 0 / 0.94)',
- surfaceDeep: 'oklch(18% 0 0 / 0.96)', // darker sand for Tune popover
- hairline: 'oklch(42% 0 0 / 0.5)',
- text: 'oklch(96% 0 0)',
- textDim: 'oklch(72% 0 0)',
- accent: 'oklch(72% 0.22 350)',
- accentSoft: 'oklch(72% 0.22 350 / 0.22)',
- mark: 'oklch(8% 0 0)',
- markText: 'oklch(96% 0 0)',
- exitHover: 'oklch(36% 0 0 / 0.6)',
- };
- }
-
- // Impeccable logo mark — matches the site-header SVG (rounded square + "/").
- function brandMarkSvg(fill, ink, size = 18) {
- return `<svg width="${size}" height="${size}" viewBox="0 0 32 32" aria-hidden="true">
- <rect width="32" height="32" rx="7" fill="${fill}"/>
- <text x="16" y="24" font-family="system-ui, -apple-system, sans-serif" font-size="22" font-weight="500" fill="${ink}" text-anchor="middle">/</text>
- </svg>`;
- }
-
- function initGlobalBar() {
- const theme = detectPageTheme();
- const P = barPaletteForTheme(theme);
-
- // Custom focus-visible for bar buttons. Browser default is a heavy
- // blue ring that looks jarring on the dark capsule. Replace with a
- // soft accent-tinted inner ring that respects the bar's palette.
- if (!document.getElementById(PREFIX + '-bar-focus-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-bar-focus-style';
- s.textContent =
- '#' + PREFIX + '-global-bar button:focus { outline: none; }' +
- '#' + PREFIX + '-global-bar button:focus-visible {' +
- ' outline: none;' +
- ' box-shadow: 0 0 0 2px ' + P.accentSoft + ', 0 0 0 3px ' + P.accent + ';' +
- '}';
- document.head.appendChild(s);
- }
-
- globalBarEl = el('div', {
- position: 'fixed', bottom: '14px', left: '50%',
- transform: 'translateX(-50%) translateY(20px)',
- zIndex: Z.bar + 5,
- display: 'flex', alignItems: 'stretch',
- gap: '2px',
- background: P.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 4px 20px oklch(0% 0 0 / 0.12), 0 1px 3px oklch(0% 0 0 / 0.08)',
- fontFamily: FONT, fontSize: '12px', lineHeight: '1',
- opacity: '0',
- overflow: 'hidden', // clip the full-bleed brand mark to the bar radius
- transition: 'opacity 0.3s ' + EASE + ', transform 0.3s ' + EASE,
- });
- globalBarEl.id = PREFIX + '-global-bar';
- globalBarEl.dataset.theme = theme;
-
- // Brand mark — fills bar height on the left. Left side inherits the bar's
- // rounded corner via overflow:hidden; right side is a clean hard edge since
- // the near-black/charcoal contrast does the shape-defining work.
- const brand = el('span', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- alignSelf: 'stretch',
- padding: '0 12px 0 14px',
- background: P.mark,
- color: P.markText,
- fontFamily: 'system-ui, -apple-system, sans-serif',
- fontWeight: '500',
- fontSize: '18px', lineHeight: '1',
- });
- brand.textContent = '/';
- brand.title = 'Impeccable';
- globalBarEl.appendChild(brand);
-
- // Inner wrapper: holds the toggles with normal bar padding.
- const inner = el('div', {
- display: 'flex', alignItems: 'center',
- padding: '4px 5px', gap: '2px',
- });
- inner.id = PREFIX + '-global-bar-inner';
- globalBarEl.appendChild(inner);
-
- // --- button factory: icon-only at rest, label slides in on hover/active ---
- function makeIconBtn({ id, svg, label, ariaLabel, labelFont, onClick }) {
- const b = el('button', {
- position: 'relative',
- display: 'inline-flex', alignItems: 'center',
- padding: '6px 8px', borderRadius: '7px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '11.5px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.15s ease, color 0.15s ease',
- whiteSpace: 'nowrap', overflow: 'hidden',
- });
- b.id = id;
- b.title = ariaLabel || label || '';
- b.setAttribute('aria-label', ariaLabel || label || '');
- b.innerHTML = svg + (label
- ? `<span class="icon-btn-label" style="display:inline-block;max-width:0;opacity:0;margin-left:0;overflow:hidden;font-family:${labelFont || FONT};transition:max-width 0.25s ${EASE}, opacity 0.2s ease, margin-left 0.25s ${EASE};">${label}</span>`
- : '');
- const labelEl = b.querySelector('.icon-btn-label');
- const expand = () => {
- if (!labelEl) return;
- labelEl.style.maxWidth = '120px'; labelEl.style.opacity = '1'; labelEl.style.marginLeft = '6px';
- };
- const collapse = () => {
- if (!labelEl || b.dataset.active === 'true') return;
- labelEl.style.maxWidth = '0'; labelEl.style.opacity = '0'; labelEl.style.marginLeft = '0';
- };
- // Per-button hover only changes color (no layout). The label expand/
- // collapse is driven by the bar-level mouseenter/mouseleave so moving
- // the mouse between adjacent buttons doesn't trigger per-button width
- // thrashing — the whole bar grows once and shrinks once.
- b.addEventListener('mouseenter', () => { if (b.dataset.active !== 'true') b.style.color = P.text; });
- b.addEventListener('mouseleave', () => { if (b.dataset.active !== 'true') b.style.color = P.textDim; });
- b.addEventListener('click', onClick);
- b._expandLabel = expand;
- b._collapseLabel = collapse;
- return b;
- }
-
- // Pick toggle — starts active (primary intent when entering live mode).
- const pickBtn = makeIconBtn({
- id: PREFIX + '-pick-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',
- label: 'Pick',
- ariaLabel: 'Pick element',
- onClick: () => togglePick(),
- });
- pickBtn.style.background = P.accentSoft;
- pickBtn.style.color = P.accent;
- pickBtn.dataset.active = 'true';
- pickBtn._expandLabel();
- inner.appendChild(pickBtn);
-
- // Detect toggle
- const detectBtn = makeIconBtn({
- id: PREFIX + '-detect-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',
- label: 'Detect',
- ariaLabel: 'Detect anti-patterns',
- onClick: () => toggleDetect(),
- });
- const detectBadge = el('span', {
- fontSize: '10px', fontWeight: '600',
- padding: '0px 5px', borderRadius: '7px', lineHeight: '16px',
- background: P.accent, color: P.surface.includes('18%') ? 'oklch(18% 0 0)' : 'oklch(98% 0 0)',
- display: 'none', fontFamily: MONO, marginLeft: '4px',
- });
- detectBadge.id = PREFIX + '-detect-badge';
- detectBtn.appendChild(detectBadge);
- inner.appendChild(detectBtn);
-
- // DESIGN.md panel toggle — quartet of color squares as the mark.
- const designBtn = makeIconBtn({
- id: PREFIX + '-design-toggle',
- svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px ${P.hairline};flex-shrink:0">
- <span style="background:oklch(60% 0.25 350)"></span>
- <span style="background:oklch(60% 0.15 45)"></span>
- <span style="background:oklch(55% 0.12 250)"></span>
- <span style="background:oklch(30% 0 0)"></span>
- </span>`,
- label: 'DESIGN.md',
- ariaLabel: 'Toggle DESIGN.md panel',
- labelFont: MONO,
- onClick: () => toggleDesignPanel(),
- });
- inner.appendChild(designBtn);
-
- // Thin divider before the exit button
- const divider = el('span', {
- width: '1px', height: '18px',
- background: P.hairline,
- margin: '0 4px 0 2px',
- });
- inner.appendChild(divider);
-
- // Exit × on the right — intentionally subtle (textDim at rest, text on
- // hover) so it sits behind the active toggles in visual hierarchy.
- //
- // Explicit padding + box-sizing here is load-bearing: a host page like
- // `button { padding: 0.5rem 1rem; }` (very common in resets) would
- // otherwise inflate this 24x24 button into 56x40 and push the SVG out
- // of the visible bar — the X stays invisible even though the styles in
- // DevTools look fine. Every other chrome button sets padding inline;
- // this one needed it too.
- const exitBtn = el('button', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- padding: '0', boxSizing: 'border-box',
- width: '24px', height: '24px', borderRadius: '6px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
- cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
- });
- exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
- exitBtn.title = 'Exit live mode';
- exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
- exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
- exitBtn.addEventListener('click', () => { sendEvent({ type: 'exit' }); teardown(); });
- inner.appendChild(exitBtn);
-
- // Bar-level hover: expand every toggle's label at once; collapse on leave.
- // Buttons with dataset.active="true" ignore collapse (their label stays).
- const toggles = [pickBtn, detectBtn, designBtn];
- globalBarEl.addEventListener('mouseenter', () => {
- toggles.forEach((t) => t._expandLabel && t._expandLabel());
- });
- globalBarEl.addEventListener('mouseleave', () => {
- toggles.forEach((t) => t._collapseLabel && t._collapseLabel());
- });
-
- document.body.appendChild(globalBarEl);
- defangOutsideHandlers(globalBarEl);
-
- requestAnimationFrame(() => {
- globalBarEl.style.opacity = '1';
- globalBarEl.style.transform = 'translateX(-50%) translateY(0)';
- });
-
- // Listen for detection results AND ready signal
- window.addEventListener('message', onDetectMessage);
- }
-
- function updateGlobalBarState() {
- const detectToggle = document.getElementById(PREFIX + '-detect-toggle');
- const detectBadge = document.getElementById(PREFIX + '-detect-badge');
- const pickToggle = document.getElementById(PREFIX + '-pick-toggle');
- const designToggle = document.getElementById(PREFIX + '-design-toggle');
- const theme = globalBarEl?.dataset.theme || 'light';
- const P = barPaletteForTheme(theme);
-
- // Sync one toggle's active state, colors, and slide-label visibility.
- function sync(btn, active) {
- if (!btn) return;
- btn.style.background = active ? P.accentSoft : 'transparent';
- btn.style.color = active ? P.accent : P.textDim;
- btn.dataset.active = active ? 'true' : 'false';
- if (active && btn._expandLabel) btn._expandLabel();
- else if (!active && btn._collapseLabel) btn._collapseLabel();
- }
- sync(pickToggle, pickActive);
- sync(detectToggle, detectActive);
- sync(designToggle, designState.open);
-
- // If the bar is currently under the cursor, keep all labels expanded —
- // otherwise clicking a toggle that deactivates (e.g. closing DESIGN.md)
- // would collapse its label while the user's mouse is still on the bar.
- if (globalBarEl && globalBarEl.matches(':hover')) {
- [pickToggle, detectToggle, designToggle].forEach((t) => t?._expandLabel?.());
- }
-
- if (detectBadge) {
- detectBadge.style.display = (detectActive && detectCount > 0) ? 'inline' : 'none';
- detectBadge.textContent = detectCount;
- }
-
- // When pick is active, make detect overlays click-through so the picker works
- document.querySelectorAll('.impeccable-overlay').forEach(o => {
- o.style.pointerEvents = pickActive ? 'none' : '';
- });
- }
-
- let detectReady = false; // true once detect script posts 'impeccable-ready'
- let detectPendingScan = false; // scan requested before script was ready
-
- function toggleDetect() {
- detectActive = !detectActive;
- updateGlobalBarState();
-
- if (detectActive) {
- if (!detectScriptLoaded) {
- detectPendingScan = true;
- loadDetectScript();
- } else if (detectReady) {
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- } else {
- detectPendingScan = true;
- }
- } else {
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- detectCount = 0;
- updateGlobalBarState();
- }
- }
-
- function togglePick() {
- pickActive = !pickActive;
- updateGlobalBarState();
-
- if (!pickActive) {
- // Disabling pick clears any in-flight selection and UI: highlight,
- // contextual bar, selectedElement. Otherwise a stale selection sits
- // on screen with no obvious way to dismiss.
- hideHighlight();
- hideBar();
- hideActionPicker();
- selectedElement = null;
- if (state === 'PICKING' || state === 'CONFIGURING') state = 'IDLE';
- } else {
- if (state === 'IDLE') state = 'PICKING';
- }
- }
-
- function loadDetectScript() {
- if (detectScriptLoaded) return;
- detectScriptLoaded = true;
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/detect.js';
- s.dataset.impeccableExtension = 'true';
- document.head.appendChild(s);
- }
-
- function onDetectMessage(e) {
- if (!e.data || typeof e.data.source !== 'string') return;
- // Detection script is loaded and ready
- if (e.data.source === 'impeccable-ready') {
- detectReady = true;
- if (detectPendingScan && detectActive) {
- detectPendingScan = false;
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- }
- }
- // Scan results arrived
- if (e.data.source === 'impeccable-results') {
- detectCount = e.data.count || 0;
- updateGlobalBarState();
- }
- }
-
- /** Full teardown: remove all UI, disconnect SSE, clean up. */
- function teardown() {
- cleanup();
- hideBar();
- if (globalBarEl) {
- globalBarEl.style.transform = 'translateY(100%)';
- setTimeout(() => { if (globalBarEl) globalBarEl.remove(); globalBarEl = null; }, 300);
- }
- if (highlightEl) { highlightEl.remove(); highlightEl = null; }
- if (tooltipEl) { tooltipEl.remove(); tooltipEl = null; }
- if (barEl) { barEl.remove(); barEl = null; }
- if (pickerEl) { pickerEl.remove(); pickerEl = null; }
- if (paramsPanelEl) { paramsPanelEl.remove(); paramsPanelEl = null; paramsPanelInner = null; paramsPanelBody = null; }
- if (evtSource) { evtSource.close(); evtSource = null; }
- document.removeEventListener('mousemove', handleMouseMove, true);
- document.removeEventListener('click', handleClick, true);
- document.removeEventListener('keydown', handleKeyDown, true);
- window.removeEventListener('message', onDetectMessage);
- // Remove detection overlays
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- state = 'IDLE';
- window.__IMPECCABLE_LIVE_INIT__ = false;
- console.log('[impeccable] Live mode exited.');
- }
-
- // ---------------------------------------------------------------------------
- // Design System Panel — visualizes the project's .impeccable/design.json sidecar
- // ---------------------------------------------------------------------------
-
- const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';
- const DESIGN_PANEL_WIDTH = 440;
-
- let designHost = null;
- let designShadow = null;
- let designState = {
- open: false,
- tab: 'visual', // 'visual' | 'raw'
- parsed: null, // parseDesignMd output (frontmatter + body sections)
- sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)
- hasMd: false,
- hasSidecar: false,
- present: null, // true/false once fetch resolves
- raw: null, // raw DESIGN.md for the raw tab
- mdNewerThanJson: false, // stale-hint flag
- loading: false,
- error: null,
- collapsed: { // narrative-section accordion state
- rules: true, dosdonts: true, overview: true,
- },
- };
-
- function loadDesignPrefs() {
- // `open` is intentionally NOT persisted — the panel always starts closed
- // so live mode doesn't auto-slide a big panel over the page on startup.
- try {
- const raw = localStorage.getItem(DESIGN_PREFS_KEY);
- if (!raw) return;
- const prefs = JSON.parse(raw);
- if (prefs.tab === 'visual' || prefs.tab === 'raw') designState.tab = prefs.tab;
- if (prefs.collapsed && typeof prefs.collapsed === 'object') {
- Object.assign(designState.collapsed, prefs.collapsed);
- }
- } catch { /* ignore */ }
- }
-
- function saveDesignPrefs() {
- try {
- localStorage.setItem(DESIGN_PREFS_KEY, JSON.stringify({
- tab: designState.tab,
- collapsed: designState.collapsed,
- }));
- } catch { /* ignore */ }
- }
-
- function initDesignPanel() {
- designHost = document.createElement('div');
- designHost.id = PREFIX + '-design-host';
- Object.assign(designHost.style, {
- position: 'fixed', top: '0', left: '0',
- width: '0', height: '0',
- zIndex: String(Z.bar + 10),
- pointerEvents: 'none',
- });
- designShadow = designHost.attachShadow({ mode: 'open' });
-
- const style = document.createElement('style');
- // Theme-match the bar: dark chrome on light pages, light chrome on dark pages.
- const theme = detectPageTheme();
- style.textContent = designPanelCss(barPaletteForTheme(theme));
- designShadow.appendChild(style);
-
- const root = document.createElement('div');
- root.className = 'root';
- designShadow.appendChild(root);
-
- document.body.appendChild(designHost);
- // The host is pointer-events: none; the panel inside the shadow DOM
- // manages its own auto/none. Events bubble through the shadow boundary,
- // so attaching here silences host-page outside-interaction handlers
- // without touching the host's click-through behavior.
- defangOutsideHandlers(designHost, { setPointerEvents: false });
-
- loadDesignPrefs();
- renderDesignChrome();
- if (designState.open) {
- fetchDesignSystem();
- }
- }
-
- // Neutral panel palette — deliberately NOT Impeccable-branded. The panel is
- // a viewer of the project's design system, not an Impeccable surface.
- const DP = {
- canvas: 'oklch(94% 0 0)', // panel background
- tile: 'oklch(98.5% 0 0)', // card-on-canvas
- tileAlt: 'oklch(96% 0 0)', // subtler tile for inner surfaces
- ink: 'oklch(15% 0 0)',
- ink2: 'oklch(35% 0 0)',
- meta: 'oklch(55% 0 0)',
- hairline: 'oklch(88% 0 0)',
- hairlineSoft: 'oklch(92% 0 0)',
- amber: 'oklch(70% 0.13 65)', // stale-hint accent
- amberBg: 'oklch(95% 0.05 80)',
- };
-
- function designPanelCss(BP) {
- // BP = bar palette (theme-aware, matches the global bar).
- // DP = internal content palette (neutral, so tiles render colors true).
- return `
- :host, .root { all: initial; }
- .root {
- font-family: ${FONT};
- color: ${DP.ink};
- pointer-events: none;
- }
- .root * { box-sizing: border-box; }
- button { font: inherit; color: inherit; }
-
- /* --- Panel shell: chrome matches the bar; body canvas stays neutral --- */
- .panel {
- position: fixed; top: 12px; bottom: 72px; right: 12px;
- width: ${DESIGN_PANEL_WIDTH}px; max-width: calc(100vw - 24px);
- background: ${BP.surface};
- border: 1px solid ${BP.hairline};
- border-radius: 14px;
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- box-shadow: 0 20px 60px oklch(0% 0 0 / 0.18), 0 4px 12px oklch(0% 0 0 / 0.08);
- display: flex; flex-direction: column;
- transform: translateX(calc(100% + 24px));
- opacity: 0;
- transition: transform 0.35s ${EASE}, opacity 0.25s ${EASE};
- pointer-events: none;
- overflow: hidden;
- }
- .panel[data-open="true"] { transform: translateX(0); opacity: 1; pointer-events: auto; }
-
- .panel-header {
- display: flex; align-items: center; gap: 10px;
- padding: 10px 10px 10px 14px;
- background: transparent;
- border-bottom: 1px solid ${BP.hairline};
- }
- .panel-title {
- flex: 1; min-width: 0;
- font-family: ${MONO};
- font-size: 11.5px; font-weight: 600;
- letter-spacing: 0.02em;
- color: ${BP.text};
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
- }
- .panel-close {
- border: none; background: transparent; color: ${BP.textDim};
- width: 26px; height: 26px; border-radius: 7px;
- display: inline-flex; align-items: center; justify-content: center;
- cursor: pointer; transition: background 0.15s ease, color 0.15s ease;
- }
- .panel-close:hover { background: ${BP.hairline}; color: ${BP.text}; }
-
- .tabs {
- display: inline-flex; padding: 2px;
- background: ${BP.hairline};
- border-radius: 7px;
- gap: 2px;
- }
- .tab {
- border: none; background: transparent;
- padding: 4px 10px; border-radius: 5px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 600; letter-spacing: 0.08em;
- text-transform: uppercase;
- color: ${BP.textDim}; cursor: pointer;
- transition: background 0.15s ease, color 0.15s ease;
- }
- .tab[data-active="true"] { background: ${BP.surface}; color: ${BP.text}; }
-
- .panel-body {
- flex: 1; overflow-y: auto;
- padding: 12px 12px 20px;
- background: ${DP.canvas};
- scrollbar-width: thin;
- scrollbar-color: ${DP.hairline} transparent;
- }
- .panel-body::-webkit-scrollbar { width: 8px; }
- .panel-body::-webkit-scrollbar-thumb { background: ${DP.hairline}; border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
-
- /* --- States --- */
- .empty, .loading, .error {
- margin: 16px 4px;
- padding: 28px 20px; text-align: center;
- background: ${DP.tile}; border-radius: 14px;
- color: ${DP.ink2}; font-size: 13px; line-height: 1.55;
- }
- .empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
- .empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
- .error { color: oklch(45% 0.15 25); }
-
- /* --- Stale hint --- */
- .stale {
- display: flex; align-items: center; gap: 8px;
- margin: 8px 4px 12px;
- padding: 8px 12px;
- background: ${DP.amberBg};
- border-radius: 10px;
- font-size: 11.5px; color: ${DP.ink2};
- }
- .stale-dot { width: 8px; height: 8px; border-radius: 50%; background: ${DP.amber}; flex-shrink: 0; }
- .stale-text { flex: 1; min-width: 0; }
- .stale-text strong { color: ${DP.ink}; font-weight: 600; }
-
- /* --- Parsed-md fallback banner --- */
- .parsed-md-cta {
- margin: 8px 4px 14px;
- padding: 14px 16px;
- background: ${DP.tile};
- border: 1px dashed ${DP.hairline};
- border-radius: 12px;
- font-size: 12px; color: ${DP.ink2}; line-height: 1.55;
- }
- .parsed-md-cta strong { color: ${DP.ink}; display: block; margin-bottom: 4px; font-size: 13px; font-weight: 600; }
- .parsed-md-cta code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; font-size: 11.5px; color: ${DP.ink}; }
-
- /* --- Tile primitives --- */
- .tile {
- position: relative;
- background: ${DP.tile};
- border-radius: 16px;
- padding: 16px;
- margin: 0 4px 10px;
- }
- .tile-row { margin: 0 4px 10px; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
- .tile-row .tile { margin: 0; }
- .tile-meta {
- display: flex; align-items: baseline; justify-content: space-between;
- gap: 10px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase;
- color: ${DP.meta};
- }
- .tile-meta .name { color: ${DP.ink}; font-weight: 600; letter-spacing: 0.05em; text-transform: none; font-family: ${FONT}; font-size: 12.5px; }
-
- /* --- Color tile --- */
- .c-tile { cursor: pointer; transition: transform 0.2s ${EASE}; }
- .c-tile:hover { transform: translateY(-1px); }
- .c-hero {
- height: 72px; border-radius: 10px; margin-top: 10px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.05);
- }
- .c-ramp {
- display: flex; gap: 0; height: 14px; border-radius: 4px; overflow: hidden;
- margin-top: 8px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.04);
- }
- .c-ramp > span { flex: 1; }
- .c-desc { margin-top: 8px; font-size: 11.5px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Type tile --- */
- .t-tile { }
- .t-specimen {
- margin: 4px 0 6px;
- color: ${DP.ink};
- line-height: 0.9;
- }
- .t-family { margin-top: 4px; font-size: 12px; font-weight: 600; color: ${DP.ink}; }
- .t-purpose { margin-top: 4px; font-size: 11px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Shadow tile --- */
- .s-tile { }
- .s-surface {
- height: 60px; margin: 8px 2px 10px;
- background: ${DP.tile};
- border-radius: 10px;
- }
- .s-value { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; word-break: break-all; line-height: 1.4; }
- .s-purpose { margin-top: 4px; font-size: 11px; color: ${DP.ink2}; line-height: 1.45; }
-
- /* --- Radii strip --- */
- .r-strip { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
- .r-item { display: flex; flex-direction: column; align-items: center; gap: 4px; flex: 1; min-width: 60px; }
- .r-sample { width: 44px; height: 44px; background: ${DP.canvas}; box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.08); }
- .r-label { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; text-transform: uppercase; }
- .r-val { font-family: ${MONO}; font-size: 10px; color: ${DP.ink}; }
-
- /* --- Component tile (hosts live primitives) --- */
- .cmp-tile { }
- .cmp-stage {
- margin: 12px -4px 0;
- padding: 18px 16px 10px;
- border-top: 1px solid ${DP.hairlineSoft};
- display: flex; flex-direction: column; align-items: center; justify-content: center;
- gap: 14px;
- min-height: 68px;
- }
- .cmp-stage + .cmp-stage { border-top: 1px dashed ${DP.hairlineSoft}; }
- .cmp-sublabel { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.06em; }
- .cmp-kind { font-family: ${MONO}; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; }
-
- /* --- Collapsible --- */
- .coll {
- margin: 0 4px 8px;
- background: ${DP.tile};
- border-radius: 12px;
- overflow: hidden;
- }
- .coll-head {
- display: flex; align-items: center; gap: 10px;
- width: 100%;
- padding: 12px 14px;
- background: transparent; border: none;
- cursor: pointer; text-align: left;
- font-family: ${FONT}; font-size: 12.5px; font-weight: 600; color: ${DP.ink};
- transition: background 0.12s ease;
- }
- .coll-head:hover { background: ${DP.tileAlt}; }
- .coll-chev {
- width: 12px; height: 12px; flex-shrink: 0;
- color: ${DP.meta};
- transition: transform 0.2s ${EASE};
- }
- .coll[data-open="true"] .coll-chev { transform: rotate(90deg); }
- .coll-count { margin-left: auto; font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; }
- .coll-body { padding: 0 14px 14px; display: none; }
- .coll[data-open="true"] .coll-body { display: block; }
-
- .rule-card {
- padding: 10px 0;
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .rule-card:first-child { border-top: none; padding-top: 2px; }
- .rule-card .name { font-size: 11.5px; font-weight: 700; color: ${DP.ink}; margin-bottom: 3px; }
- .rule-card .name .section { font-family: ${MONO}; font-size: 9px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; margin-left: 8px; }
- .rule-card .body { font-size: 11.5px; color: ${DP.ink2}; line-height: 1.5; }
-
- .coll .dos { display: grid; gap: 0; margin-top: 2px; }
- .coll .do, .coll .dont {
- position: relative;
- padding: 8px 0 8px 22px;
- font-size: 11.5px; line-height: 1.5; color: ${DP.ink2};
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .coll .do:first-child, .coll .dont:first-child,
- .coll .do:first-of-type { border-top: none; }
- .coll .do + .dont { border-top: 1px solid ${DP.hairlineSoft}; }
- .coll .do::before, .coll .dont::before {
- content: ''; position: absolute; left: 4px; top: 13px;
- width: 8px; height: 8px; border-radius: 50%;
- }
- .coll .do::before { background: oklch(62% 0.16 145); }
- .coll .dont::before { background: oklch(58% 0.22 25); }
-
- .coll .overview-body {
- font-size: 12px; line-height: 1.55; color: ${DP.ink2};
- }
- .coll .overview-body .north-star {
- display: block; font-family: ${FONT}; font-style: italic;
- font-size: 15px; line-height: 1.3; color: ${DP.ink};
- margin-bottom: 8px;
- }
- .coll .overview-body p { margin: 0 0 8px; }
- .coll .overview-body ul { margin: 6px 0 0; padding-left: 16px; font-size: 11.5px; }
- .coll .overview-body li { margin-bottom: 3px; }
-
- /* --- raw tab markdown (unchanged layout, neutralized palette) --- */
- .md { padding: 4px 10px 20px; font-size: 13px; line-height: 1.6; color: ${DP.ink}; }
- .md h1, .md h2, .md h3, .md h4 { margin: 20px 0 8px; color: ${DP.ink}; font-weight: 600; }
- .md h1 { font-size: 18px; }
- .md h2 { font-size: 15px; padding-bottom: 4px; border-bottom: 1px solid ${DP.hairlineSoft}; }
- .md h3 { font-size: 13px; }
- .md h4 { font-size: 12px; color: ${DP.meta}; }
- .md p { margin: 0 0 10px; }
- .md ul, .md ol { margin: 0 0 10px; padding-left: 20px; }
- .md li { margin-bottom: 4px; }
- .md code { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; }
- .md pre { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 10px 12px; border-radius: 8px; overflow-x: auto; margin: 0 0 10px; }
- .md pre code { background: none; padding: 0; }
- .md strong { font-weight: 700; }
- .md em { font-style: italic; }
- .md a { color: ${DP.ink}; text-decoration: underline; }
- .md hr { border: none; border-top: 1px solid ${DP.hairlineSoft}; margin: 16px 0; }
- `;
- }
-
- function renderDesignChrome() {
- const root = designShadow.querySelector('.root');
- root.innerHTML = '';
-
- // (Panel toggle lives in the global bar — no floating FAB.)
- // Panel
- const panel = document.createElement('aside');
- panel.className = 'panel';
- panel.setAttribute('data-open', designState.open ? 'true' : 'false');
- panel.appendChild(buildDesignHeader());
- const body = document.createElement('div');
- body.className = 'panel-body';
- body.id = 'panel-body';
- panel.appendChild(body);
- root.appendChild(panel);
-
- renderDesignBody();
- }
-
- function buildDesignHeader() {
- const header = document.createElement('div');
- header.className = 'panel-header';
-
- const title = document.createElement('div');
- title.className = 'panel-title';
- title.textContent = 'DESIGN.md';
- header.appendChild(title);
-
- const tabs = document.createElement('div');
- tabs.className = 'tabs';
- for (const t of [['visual', 'Visual'], ['raw', 'Raw']]) {
- const btn = document.createElement('button');
- btn.className = 'tab';
- btn.textContent = t[1];
- btn.setAttribute('data-active', designState.tab === t[0] ? 'true' : 'false');
- btn.addEventListener('click', () => {
- if (designState.tab === t[0]) return;
- designState.tab = t[0];
- saveDesignPrefs();
- renderDesignChrome();
- if (t[0] === 'raw' && designState.raw === null && !designState.loading) {
- fetchDesignSystem(); // raw is part of the same fetch pair
- }
- });
- tabs.appendChild(btn);
- }
- header.appendChild(tabs);
-
- const close = document.createElement('button');
- close.className = 'panel-close';
- close.innerHTML = '✕';
- close.setAttribute('aria-label', 'Close panel');
- close.addEventListener('click', toggleDesignPanel);
- header.appendChild(close);
-
- return header;
- }
-
- function toggleDesignPanel() {
- designState.open = !designState.open;
- renderDesignChrome();
- updateGlobalBarState();
- if (designState.open && designState.present === null && !designState.loading) {
- fetchDesignSystem();
- }
- }
-
- async function fetchDesignSystem() {
- designState.loading = true;
- designState.error = null;
- renderDesignBody();
- try {
- const [jsonRes, rawRes] = await Promise.all([
- fetch(`http://localhost:${PORT}/design-system.json?token=${TOKEN}`, { cache: 'no-store' }),
- fetch(`http://localhost:${PORT}/design-system/raw?token=${TOKEN}`, { cache: 'no-store' }),
- ]);
- const jsonData = await jsonRes.json();
- designState.present = jsonData.present === true;
- designState.parsed = jsonData.parsed || null;
- designState.sidecar = jsonData.sidecar || null;
- designState.hasMd = !!jsonData.hasMd;
- designState.hasSidecar = !!jsonData.hasSidecar;
- designState.mdNewerThanJson = !!jsonData.mdNewerThanJson;
- designState.raw = designState.present && rawRes.ok ? await rawRes.text() : null;
- designState.error = jsonData.parseError || jsonData.sidecarError || null;
- } catch (err) {
- designState.error = err?.message || 'Failed to load design system.';
- } finally {
- designState.loading = false;
- renderDesignChrome(); // refresh title from data
- }
- }
-
- function renderDesignBody() {
- const body = designShadow.querySelector('#panel-body');
- if (!body) return;
- body.innerHTML = '';
-
- if (designState.loading) {
- body.appendChild(msgDiv('loading', 'Loading design system…'));
- return;
- }
- if (designState.error) {
- body.appendChild(msgDiv('error', designState.error));
- return;
- }
- if (designState.present === false) {
- const empty = document.createElement('div');
- empty.className = 'empty';
- empty.innerHTML = `<strong>No DESIGN.md yet</strong>Create one by running <code>/impeccable document</code> in your terminal, then re-open this panel.`;
- body.appendChild(empty);
- return;
- }
-
- if (designState.tab === 'raw') {
- renderRawTab(body, designState.raw || '');
- return;
- }
-
- // Visual tab — single unified render path.
- if (designState.mdNewerThanJson) body.appendChild(renderStaleHint());
- if (designState.hasMd && !designState.hasSidecar) {
- body.appendChild(renderParsedMdCta());
- }
- renderDesignVisual(body, designState.parsed, designState.sidecar);
- }
-
- function msgDiv(cls, text) {
- const d = document.createElement('div');
- d.className = cls;
- d.textContent = text;
- return d;
- }
-
- function renderStaleHint() {
- const box = document.createElement('div');
- box.className = 'stale';
- box.innerHTML = `
- <span class="stale-dot"></span>
- <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>
- `;
- return box;
- }
-
- function renderParsedMdCta() {
- const box = document.createElement('div');
- box.className = 'parsed-md-cta';
- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;
- return box;
- }
-
- // --- Unified render: merge parsed DESIGN.md frontmatter with sidecar v2 ---
-
- function renderDesignVisual(body, parsed, sidecar) {
- const frontmatter = parsed?.frontmatter || {};
- const extensions = sidecar?.extensions || {};
- const proseColors = parsed?.colors || null;
-
- const colors = buildColorModels(frontmatter.colors, extensions.colorMeta, proseColors);
- if (colors.length) renderColorTiles(body, colors);
-
- const types = buildTypographyModels(frontmatter.typography, extensions.typographyMeta);
- if (types.length) renderTypeTiles(body, types);
-
- const radii = buildRadiiModels(frontmatter.rounded);
- if (radii.length) renderRadiiTile(body, radii);
-
- if (extensions.shadows?.length) renderShadowTiles(body, extensions.shadows);
-
- const components = sidecar?.components || [];
- if (components.length) renderComponentTiles(body, components);
-
- // Narrative: sidecar wins if present (richer, agent-curated). Otherwise
- // synthesize from prose sections.
- const narrative = sidecar?.narrative || synthesizeNarrative(parsed);
- if (narrative.rules?.length) body.appendChild(renderRulesCollapsible(narrative.rules));
- if ((narrative.dos?.length || narrative.donts?.length)) body.appendChild(renderDosDontsCollapsible(narrative));
- if (narrative.overview || narrative.northStar || narrative.keyCharacteristics?.length) {
- body.appendChild(renderOverviewCollapsible(narrative));
- }
-
- if (body.childElementCount === 0) {
- body.appendChild(msgDiv('empty', 'No design system data available.'));
- }
- }
-
- // Frontmatter primitives + sidecar colorMeta → tile-ready color models.
- // A matching prose bullet (when the slug sits in the bullet text) supplies
- // description as a last-resort fallback.
- function buildColorModels(fmColors, colorMeta, proseColors) {
- if (!fmColors) return [];
- const meta = colorMeta || {};
- return Object.entries(fmColors).map(([key, value]) => {
- const m = meta[key] || {};
- return {
- role: m.role || humanizeKey(key),
- name: m.displayName || humanizeKey(key),
- value: value,
- canonical: m.canonical || null,
- description: m.description || findProseDescription(proseColors, key, m.displayName),
- tonalRamp: m.tonalRamp || null,
- };
- });
- }
-
- function buildTypographyModels(fmTypography, typographyMeta) {
- if (!fmTypography) return [];
- const meta = typographyMeta || {};
- return Object.entries(fmTypography).map(([key, spec]) => {
- const m = meta[key] || {};
- const { family, fallback } = splitFontFamily(spec?.fontFamily);
- return {
- role: key,
- name: m.displayName || humanizeKey(key),
- family,
- fallback,
- weight: spec?.fontWeight ?? 400,
- // fontStyle isn't in Stitch's frontmatter schema; the sidecar carries
- // it when a role is rendered in italic (e.g. display italic).
- style: m.style || 'normal',
- sampleSize: spec?.fontSize || '1rem',
- lineHeight: spec?.lineHeight != null ? String(spec.lineHeight) : '',
- letterSpacing: spec?.letterSpacing,
- purpose: m.purpose,
- };
- });
- }
-
- function buildRadiiModels(fmRounded) {
- if (!fmRounded) return [];
- return Object.entries(fmRounded).map(([name, value]) => ({ name, value }));
- }
-
- function splitFontFamily(stack) {
- if (!stack || typeof stack !== 'string') return { family: '', fallback: '' };
- const parts = stack.split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, ''));
- return { family: parts[0] || '', fallback: parts.slice(1).join(', ') };
- }
-
- function humanizeKey(k) {
- return String(k || '').replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
- }
-
- function findProseDescription(proseColors, key, displayName) {
- if (!proseColors || !proseColors.groups) return null;
- const needles = [key, displayName].filter(Boolean).map((s) => s.toLowerCase());
- for (const g of proseColors.groups) {
- for (const c of g.colors || []) {
- const hay = String(c.name || '').toLowerCase();
- if (hay && needles.some((n) => hay.includes(n) || n.includes(hay))) {
- return c.description || null;
- }
- }
- }
- return null;
- }
-
- function synthesizeNarrative(parsed) {
- if (!parsed) return {};
- const md = parsed;
- return {
- northStar: md.overview?.creativeNorthStar,
- overview: (md.overview?.philosophy || []).join(' '),
- keyCharacteristics: md.overview?.keyCharacteristics || [],
- rules: [
- ...(md.colors?.rules || []).map((r) => ({ ...r, section: 'colors' })),
- ...(md.typography?.rules || []).map((r) => ({ ...r, section: 'typography' })),
- ...(md.elevation?.rules || []).map((r) => ({ ...r, section: 'elevation' })),
- ],
- dos: md.dosDonts?.dos || [],
- donts: md.dosDonts?.donts || [],
- };
- }
-
- function renderColorTiles(body, colors) {
- for (const c of colors) {
- const tile = document.createElement('div');
- tile.className = 'tile c-tile';
- tile.title = 'Click to copy';
- tile.addEventListener('click', () => copyToClipboard(c.value));
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(c.name || c.role || 'Color')}</span><span>${escapeHtml(c.value || '')}</span>`;
- tile.appendChild(meta);
-
- const hero = document.createElement('div');
- hero.className = 'c-hero';
- hero.style.background = c.value;
- tile.appendChild(hero);
-
- const ramp = synthesizeRamp(c);
- if (ramp.length) {
- const r = document.createElement('div');
- r.className = 'c-ramp';
- r.innerHTML = ramp.map((v) => `<span style="background:${cssSafe(v)}"></span>`).join('');
- tile.appendChild(r);
- }
-
- if (c.description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = c.description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function synthesizeRamp(c) {
- if (c.tonalRamp?.length) return c.tonalRamp;
- // If base value is OKLCH, synthesize an 8-step ramp across lightness.
- const m = typeof c.value === 'string' && c.value.match(/^oklch\(\s*([\d.]+)%\s+([\d.]+)\s+([\d.]+)\s*(?:\/\s*([\d.]+))?\s*\)$/i);
- if (!m) return [];
- const [, , chroma, hue] = m;
- const steps = [20, 32, 44, 56, 68, 80, 90, 96];
- return steps.map((l) => `oklch(${l}% ${chroma} ${hue})`);
- }
-
- function renderTypeTiles(body, types) {
- for (const t of types) {
- const tile = document.createElement('div');
- tile.className = 'tile t-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span>${escapeHtml(t.role || '')}</span><span>${escapeHtml(t.weight || '')} ${escapeHtml(t.style === 'italic' ? 'italic' : '')}</span>`;
- tile.appendChild(meta);
-
- const specimen = document.createElement('div');
- specimen.className = 't-specimen';
- specimen.textContent = 'Aa';
- specimen.style.fontFamily = fontStack(t);
- specimen.style.fontWeight = String(t.weight || 400);
- specimen.style.fontStyle = t.style || 'normal';
- specimen.style.fontSize = '56px'; // Fixed specimen size — compare faces, not scales.
- specimen.style.letterSpacing = 'normal';
- specimen.style.textTransform = 'none';
- tile.appendChild(specimen);
-
- // The system's actual sample size for this role, shown as small mono meta below.
- if (t.sampleSize) {
- const scale = document.createElement('div');
- scale.style.cssText = 'font-family:' + MONO + '; font-size: 10px; color:' + DP.meta + '; margin-top: 2px;';
- scale.textContent = t.sampleSize;
- tile.appendChild(scale);
- }
-
- const family = document.createElement('div');
- family.className = 't-family';
- family.textContent = t.family || t.name || '';
- tile.appendChild(family);
-
- if (t.purpose) {
- const p = document.createElement('div');
- p.className = 't-purpose';
- p.textContent = t.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function fontStack(t) {
- const fam = t.family || '';
- const fb = t.fallback || '';
- if (fam && /[,\s]/.test(fam) && !fam.includes("'") && !fam.includes('"')) {
- return `"${fam}", ${fb}`;
- }
- return fam && fb ? `"${fam}", ${fb}` : (fam || fb);
- }
-
- function renderRadiiTile(body, radii) {
- const tile = document.createElement('div');
- tile.className = 'tile';
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">Corner Radii</span><span>${radii.length}</span>`;
- tile.appendChild(meta);
-
- const strip = document.createElement('div');
- strip.className = 'r-strip';
- for (const r of radii) {
- const item = document.createElement('div');
- item.className = 'r-item';
- const s = document.createElement('div');
- s.className = 'r-sample';
- s.style.borderRadius = r.value || '0';
- item.appendChild(s);
- const lbl = document.createElement('div');
- lbl.className = 'r-label';
- lbl.textContent = r.name || '';
- item.appendChild(lbl);
- const val = document.createElement('div');
- val.className = 'r-val';
- val.textContent = r.value || '';
- item.appendChild(val);
- strip.appendChild(item);
- }
- tile.appendChild(strip);
- body.appendChild(tile);
- }
-
- function renderShadowTiles(body, shadows) {
- for (const sh of shadows) {
- const tile = document.createElement('div');
- tile.className = 'tile s-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(sh.name || 'Shadow')}</span><span>Elevation</span>`;
- tile.appendChild(meta);
-
- const surface = document.createElement('div');
- surface.className = 's-surface';
- surface.style.boxShadow = sh.value || 'none';
- tile.appendChild(surface);
-
- const val = document.createElement('div');
- val.className = 's-value';
- val.textContent = sh.value || '';
- tile.appendChild(val);
-
- if (sh.purpose) {
- const p = document.createElement('div');
- p.className = 's-purpose';
- p.textContent = sh.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function renderComponentTiles(body, components) {
- // Group consecutive components that share a kind into one tile. This avoids
- // a pile of one-component tiles (e.g., three button variants = three tiles)
- // and reads more like a proper category.
- const groups = groupByKind(components);
-
- for (const group of groups) {
- const tile = document.createElement('div');
- tile.className = 'tile cmp-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- const groupTitle = group.length === 1
- ? (group[0].name || group[0].kind || 'Component')
- : titleForKind(group[0].kind, group.length);
- meta.innerHTML = `<span class="name">${escapeHtml(groupTitle)}</span><span class="cmp-kind">${escapeHtml(group[0].kind || '')}</span>`;
- tile.appendChild(meta);
-
- for (const c of group) {
- const stage = document.createElement('div');
- stage.className = 'cmp-stage';
-
- // Render the component in its own shadow root so its CSS can't bleed.
- const host = document.createElement('div');
- const sub = host.attachShadow({ mode: 'open' });
- const style = document.createElement('style');
- style.textContent = c.css || '';
- sub.appendChild(style);
- const container = document.createElement('div');
- container.innerHTML = c.html || '';
- sub.appendChild(container);
- stage.appendChild(host);
-
- // Show component name as a sublabel only when the tile groups >1 item,
- // or when the component's display name differs from its kind.
- const showSublabel = group.length > 1;
- if (showSublabel) {
- const lbl = document.createElement('div');
- lbl.className = 'cmp-sublabel';
- lbl.textContent = c.name || '';
- stage.appendChild(lbl);
- }
- tile.appendChild(stage);
- }
-
- // Single shared description if all items carry the same one; otherwise
- // skip — per-item descriptions clutter a grouped tile.
- if (group.length === 1 && group[0].description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = group[0].description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function groupByKind(components) {
- const groups = [];
- for (const c of components) {
- const last = groups[groups.length - 1];
- if (last && last[0].kind && c.kind === last[0].kind) {
- last.push(c);
- } else {
- groups.push([c]);
- }
- }
- return groups;
- }
-
- function titleForKind(kind, count) {
- const labels = {
- button: 'Buttons',
- input: 'Inputs',
- nav: 'Navigation',
- chip: 'Chips',
- card: 'Cards',
- custom: 'Components',
- };
- return labels[kind] || (kind ? kind.charAt(0).toUpperCase() + kind.slice(1) + 's' : 'Components');
- }
-
- // --- Collapsibles ---------------------------------------------------------
-
- function buildCollapsible(key, label, count) {
- const wrap = document.createElement('div');
- wrap.className = 'coll';
- wrap.setAttribute('data-open', designState.collapsed[key] ? 'false' : 'true');
-
- const head = document.createElement('button');
- head.className = 'coll-head';
- head.innerHTML = `
- <svg class="coll-chev" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 2.5L8 6 4 9.5"/></svg>
- <span>${escapeHtml(label)}</span>
- ${count != null ? `<span class="coll-count">${escapeHtml(String(count))}</span>` : ''}
- `;
- head.addEventListener('click', () => {
- designState.collapsed[key] = !designState.collapsed[key];
- saveDesignPrefs();
- renderDesignBody();
- });
- wrap.appendChild(head);
-
- const body = document.createElement('div');
- body.className = 'coll-body';
- wrap.appendChild(body);
- return { wrap, body };
- }
-
- function renderRulesCollapsible(rules) {
- const { wrap, body } = buildCollapsible('rules', 'Named Rules', rules.length);
- for (const r of rules) {
- const card = document.createElement('div');
- card.className = 'rule-card';
- const name = document.createElement('div');
- name.className = 'name';
- name.innerHTML = `${escapeHtml(r.name)}${r.section ? `<span class="section">${escapeHtml(r.section)}</span>` : ''}`;
- card.appendChild(name);
- const b = document.createElement('div');
- b.className = 'body';
- b.textContent = r.body || '';
- card.appendChild(b);
- body.appendChild(card);
- }
- return wrap;
- }
-
- function renderDosDontsCollapsible(n) {
- const total = (n.dos?.length || 0) + (n.donts?.length || 0);
- const { wrap, body } = buildCollapsible('dosdonts', "Do's and Don'ts", total);
- const grid = document.createElement('div');
- grid.className = 'dos';
- for (const d of n.dos || []) {
- const el = document.createElement('div');
- el.className = 'do';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- for (const d of n.donts || []) {
- const el = document.createElement('div');
- el.className = 'dont';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- body.appendChild(grid);
- return wrap;
- }
-
- function renderOverviewCollapsible(n) {
- const { wrap, body } = buildCollapsible('overview', 'Overview', null);
- const ov = document.createElement('div');
- ov.className = 'overview-body';
- if (n.northStar) {
- const star = document.createElement('span');
- star.className = 'north-star';
- star.textContent = '“' + n.northStar + '”';
- ov.appendChild(star);
- }
- if (n.overview) {
- const p = document.createElement('p');
- p.innerHTML = inlineMd(n.overview);
- ov.appendChild(p);
- }
- if (n.keyCharacteristics?.length) {
- const ul = document.createElement('ul');
- ul.innerHTML = n.keyCharacteristics.map((k) => `<li>${inlineMd(k)}</li>`).join('');
- ov.appendChild(ul);
- }
- body.appendChild(ov);
- return wrap;
- }
-
- function cssSafe(v) {
- // Strip anything outside valid CSS value chars to prevent injection via
- // .impeccable/design.json values rendered into inline style strings.
- return String(v).replace(/[<>"'`\n]/g, '');
- }
-
- // --- Raw tab: minimal markdown renderer (subset) --------------------------
-
- function renderRawTab(body, md) {
- const wrap = document.createElement('div');
- wrap.className = 'md';
- wrap.innerHTML = renderMarkdown(md);
- body.appendChild(wrap);
- }
-
- function renderMarkdown(md) {
- const lines = md.split(/\r?\n/);
- const out = [];
- let i = 0;
- let inCode = false;
- let codeBuf = [];
- let paraBuf = [];
- let listBuf = []; // array of { indent, html }
- let listType = null; // 'ul' | 'ol'
-
- const flushPara = () => {
- if (paraBuf.length) {
- out.push(`<p>${inlineMd(paraBuf.join(' '))}</p>`);
- paraBuf = [];
- }
- };
- const flushList = () => {
- if (listBuf.length) {
- out.push(buildListHtml(listBuf, listType));
- listBuf = [];
- listType = null;
- }
- };
- const flushAll = () => { flushPara(); flushList(); };
-
- for (; i < lines.length; i++) {
- const line = lines[i];
-
- // Code fence
- const fence = line.match(/^```(\w*)\s*$/);
- if (fence) {
- if (!inCode) { flushAll(); inCode = true; codeBuf = []; }
- else {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- inCode = false;
- }
- continue;
- }
- if (inCode) { codeBuf.push(line); continue; }
-
- if (line.trim() === '') { flushAll(); continue; }
-
- const hr = line.match(/^\s*(?:---+|\*\*\*+)\s*$/);
- if (hr) { flushAll(); out.push('<hr />'); continue; }
-
- const heading = line.match(/^(#{1,4})\s+(.+)$/);
- if (heading) {
- flushAll();
- const lvl = heading[1].length;
- out.push(`<h${lvl}>${inlineMd(heading[2])}</h${lvl}>`);
- continue;
- }
-
- const bullet = line.match(/^(\s*)([-*])\s+(.+)$/);
- const ordered = line.match(/^(\s*)(\d+)\.\s+(.+)$/);
- if (bullet || ordered) {
- flushPara();
- const m = bullet || ordered;
- const indent = Math.floor(m[1].length / 2);
- const t = bullet ? 'ul' : 'ol';
- if (listType && listType !== t) flushList();
- listType = t;
- listBuf.push({ indent, html: inlineMd(m[3]) });
- continue;
- }
-
- paraBuf.push(line);
- }
- flushAll();
- if (inCode && codeBuf.length) {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- }
- return out.join('\n');
- }
-
- function buildListHtml(items, type) {
- // Nest by indent (one level deep is plenty for DESIGN.md).
- let html = `<${type}>`;
- let lastIndent = 0;
- for (const it of items) {
- if (it.indent > lastIndent) html += `<${type}>`;
- else if (it.indent < lastIndent) html += `</${type}>`.repeat(lastIndent - it.indent);
- html += `<li>${it.html}</li>`;
- lastIndent = it.indent;
- }
- html += `</${type}>`.repeat(lastIndent + 1);
- return html;
- }
-
- function inlineMd(text) {
- // Order matters: escape first, then re-inject tags.
- let s = escapeHtml(text);
- // Code spans
- s = s.replace(/`([^`]+)`/g, (_, code) => `<code>${code}</code>`);
- // Links [text](url)
- s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, t, u) => `<a href="${u}" target="_blank" rel="noopener noreferrer">${t}</a>`);
- // Bold
- s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
- // Italic (only single *…*, skip if inside bold already handled)
- s = s.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em>$2</em>');
- return s;
- }
-
- function highlightBold(text) {
- return inlineMd(text);
- }
-
- function escapeHtml(s) {
- return String(s)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
-
- function copyToClipboard(text) {
- if (!text) return;
- try {
- navigator.clipboard.writeText(text);
- showToast('Copied: ' + text);
- } catch { /* ignore */ }
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- function init() {
- try { history.scrollRestoration = 'manual'; } catch {}
- initHighlight();
- initAnnotOverlay();
- initBar();
- initActionPicker();
- initParamsPanel();
- initGlobalBar();
- initDesignPanel();
- document.addEventListener('mousemove', handleMouseMove, true);
- document.addEventListener('click', handleClick, true);
- document.addEventListener('keydown', handleKeyDown, true);
- connectSSE();
-
- // Check for an active session to resume (variant wrapper already in DOM after HMR)
- if (!resumeSession()) {
- console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
- // SvelteKit (and any framework that hydrates after HTML parse) may add
- // the variant wrapper AFTER init runs. Watch for it and retry resume
- // once it appears. Disconnect on first hit.
- const scout = new MutationObserver(() => {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) return;
- scout.disconnect();
- if (resumeSession()) {
- console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
- }
- });
- scout.observe(document.body, { childList: true, subtree: true });
- } else {
- console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
- }
- }
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
- } else {
- init();
- }
-})();
@@ -1,75 +0,0 @@
-#!/usr/bin/env node
-/**
- * Canonical durable completion acknowledgement for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function parseArgs(argv) {
- const out = { status: 'complete' };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';
- else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }
- else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function completeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help || !args.id) {
- console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);
- process.exit(args.help ? 0 : 1);
- }
-
- const serverInfo = readServerInfo();
- const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;
- if (serverResult?.ok) {
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const snapshot = store.getSnapshot(args.id, { includeCompleted: true });
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const event = args.status === 'discarded'
- ? { type: 'discarded', id: args.id }
- : args.status === 'agent_error'
- ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }
- : { type: 'complete', id: args.id };
- const snapshot = store.appendEvent(event);
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));
-}
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function completeThroughServer(info, args) {
- const type = args.status === 'discarded'
- ? 'discarded'
- : args.status === 'agent_error'
- ? 'error'
- : 'complete';
- try {
- const res = await fetch(`http://localhost:${info.port}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),
- });
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {
- completeCli();
-}
@@ -1,18 +0,0 @@
-export function completionTypeForAcceptResult(eventType, acceptResult) {
- if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';
- if (acceptResult?.handled === true) return 'complete';
- if (acceptResult?.mode === 'error') return 'error';
- return 'agent_done';
-}
-
-export function completionAckForAcceptResult(eventId, completionType, acceptResult) {
- const ack = { ok: true, type: completionType };
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) {
- ack.final = false;
- ack.requiresComplete = true;
- ack.nextCommand = `live-complete.mjs --id ${eventId}`;
- ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';
- }
- return ack;
-}
@@ -1,446 +0,0 @@
-/**
- * CLI helper: insert/remove the live variant mode script tag in the project's
- * main HTML entry point.
- *
- * On first live run, the agent generates `.impeccable/live/config.json`
- * with the project's insertion target (framework-specific). On
- * every subsequent run, this script handles insert/remove deterministically
- * with zero LLM involvement.
- *
- * Usage:
- * node live-inject.mjs --port PORT # Insert the live script tag
- * node live-inject.mjs --remove # Remove the live script tag
- * node live-inject.mjs --check # Check whether live config exists
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { resolveLiveConfigPath } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });
-const MARKER_OPEN_TEXT = 'impeccable-live-start';
-const MARKER_CLOSE_TEXT = 'impeccable-live-end';
-
-/**
- * Hard-excluded directory patterns. These are NEVER user-facing pages and
- * matching them would silently inject tracking scripts into third-party
- * code. The user cannot turn these off via config — they are the floor.
- */
-const HARD_EXCLUDES = [
- '**/node_modules/**',
- '**/.git/**',
-];
-
-export async function injectCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-inject.mjs [options]
-
-Insert or remove the live mode script tag in the project's HTML entry point.
-Reads configuration from .impeccable/live/config.json.
-
-Modes:
- --port PORT Insert script tag pointing at http://localhost:PORT/live.js
- --remove Remove the script tag (if present)
- --check Print whether .impeccable/live/config.json exists and its content
-
-Output (JSON):
- { ok, file, inserted|removed, config? }`);
- process.exit(0);
- }
-
- if (args.includes('--check')) {
- if (!fs.existsSync(CONFIG_PATH)) {
- console.log(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(0);
- }
- let cfg;
- try {
- cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- try {
- validateConfig(cfg);
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- console.log(JSON.stringify({ ok: true, config: cfg, path: CONFIG_PATH }));
- return;
- }
-
- // Load config
- if (!fs.existsSync(CONFIG_PATH)) {
- console.error(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(1);
- }
- const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- validateConfig(config);
-
- const resolvedFiles = resolveFiles(process.cwd(), config);
-
- if (args.includes('--remove')) {
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const detagged = removeTag(content, config.commentSyntax);
- const updated = revertCspMeta(detagged);
- if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- removed: detagged !== content,
- cspReverted: updated !== detagged,
- };
- });
- console.log(JSON.stringify({ ok: true, results }));
- return;
- }
-
- // Insert mode — need --port
- const portIdx = args.indexOf('--port');
- const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : NaN;
- if (!Number.isFinite(port)) {
- console.error(JSON.stringify({ ok: false, error: 'missing_port' }));
- process.exit(1);
- }
-
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
- const withTag = insertTag(withoutOld, config, port);
- if (withTag === withoutOld) {
- return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
- }
- const updated = patchCspMeta(withTag, port);
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- inserted: true,
- cspPatched: updated !== withTag,
- };
- });
- const anyInserted = results.some((r) => r.inserted);
- console.log(JSON.stringify({ ok: anyInserted, port, results }));
- if (!anyInserted) process.exit(1);
-}
-
-/**
- * Expand config.files (which may contain glob patterns) into a literal list
- * of existing file paths relative to rootDir. Literal entries pass through;
- * glob patterns are expanded via fs.globSync. HARD_EXCLUDES and config.exclude
- * are applied as filters. Duplicates are removed. Order is preserved by
- * first appearance.
- */
-export function resolveFiles(rootDir, config) {
- const patterns = config.files;
- const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
- const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
- const excludeRegexes = allExcludes.map(globToRegex);
-
- const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
- const isGlob = (s) => /[*?[]/.test(s);
-
- const seen = new Set();
- const out = [];
- for (const pat of patterns) {
- if (!isGlob(pat)) {
- // Literal path — include even if it doesn't exist yet; the caller
- // reports file_not_found per-entry. Exclude list doesn't apply to
- // explicit literal entries (user named it on purpose).
- if (!seen.has(pat)) {
- seen.add(pat);
- out.push(pat);
- }
- continue;
- }
- let matches;
- try {
- matches = fs.globSync(pat, { cwd: rootDir, withFileTypes: true });
- } catch {
- continue;
- }
- for (const ent of matches) {
- if (!ent.isFile || !ent.isFile()) continue;
- const abs = path.join(ent.parentPath || ent.path || rootDir, ent.name);
- const rel = path.relative(rootDir, abs).split(path.sep).join('/');
- if (isExcluded(rel)) continue;
- if (seen.has(rel)) continue;
- seen.add(rel);
- out.push(rel);
- }
- }
- return out;
-}
-
-/**
- * Convert a glob pattern to a RegExp. Supports:
- * ** → any number of path segments (including zero)
- * * → any chars except `/`
- * ? → any single char except `/`
- * Paths are normalized to forward slashes before matching.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- // ** — any number of segments, including zero. Handle the common
- // **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
- if (pattern[i + 2] === '/') {
- re += '(?:.*/)?';
- i += 3;
- } else {
- re += '.*';
- i += 2;
- }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Core operations
-// ---------------------------------------------------------------------------
-
-function validateConfig(cfg) {
- if (!cfg || typeof cfg !== 'object') throw new Error('config.json must be an object');
- if (!Array.isArray(cfg.files) || cfg.files.length === 0) {
- throw new Error('config.files (non-empty string array) required');
- }
- if (!cfg.files.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.files must contain only non-empty strings');
- }
- if (cfg.exclude !== undefined) {
- if (!Array.isArray(cfg.exclude)) {
- throw new Error('config.exclude, if present, must be a string array');
- }
- if (!cfg.exclude.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.exclude must contain only non-empty strings');
- }
- }
- if (typeof cfg.insertBefore !== 'string' && typeof cfg.insertAfter !== 'string') {
- throw new Error('config.insertBefore or config.insertAfter (string) required');
- }
- if (cfg.commentSyntax !== 'html' && cfg.commentSyntax !== 'jsx') {
- throw new Error("config.commentSyntax must be 'html' or 'jsx'");
- }
- if (cfg.cspChecked !== undefined && typeof cfg.cspChecked !== 'boolean') {
- throw new Error("config.cspChecked, if present, must be a boolean");
- }
-}
-
-function commentOpen(syntax) { return syntax === 'jsx' ? '{/*' : '<!--'; }
-function commentClose(syntax) { return syntax === 'jsx' ? '*/}' : '-->'; }
-
-function buildTagBlock(syntax, port) {
- const open = commentOpen(syntax);
- const close = commentClose(syntax);
- return (
- open + ' ' + MARKER_OPEN_TEXT + ' ' + close + '\n' +
- '<script src="http://localhost:' + port + '/live.js"></script>\n' +
- open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n'
- );
-}
-
-function insertTag(content, config, port) {
- const block = buildTagBlock(config.commentSyntax, port);
- // insertBefore: match the LAST occurrence. Anchors like `</body>` naturally
- // belong at the end, and the same literal can appear earlier in code blocks
- // within rendered documentation pages.
- if (config.insertBefore) {
- const idx = content.lastIndexOf(config.insertBefore);
- if (idx === -1) return content;
- return content.slice(0, idx) + block + content.slice(idx);
- }
- // insertAfter: match the FIRST occurrence — typical anchors like `<head>` or
- // `<body>` open near the top of the document.
- const idx = content.indexOf(config.insertAfter);
- if (idx === -1) return content;
- const after = idx + config.insertAfter.length;
- // Preserve a single trailing newline if the anchor didn't end with one
- const prefix = content[after] === '\n' ? content.slice(0, after + 1) : content.slice(0, after) + '\n';
- return prefix + block + content.slice(prefix.length);
-}
-
-/**
- * Remove the live script block. Matches either HTML or JSX comment markers
- * regardless of config (so stale tags from a wrong config can still be cleaned).
- *
- * Indent-preserving: captures any whitespace immediately preceding the opener
- * marker and re-emits it in place of the removed block. `insertTag` inserted
- * the block *after* the original line's indent and *before* the anchor (e.g.
- * `</body>`), which moved the indent onto the opener line and left the anchor
- * unindented. Replacing the whole block (plus its trailing newline) with just
- * the captured indent hands the indent back to the anchor that follows.
- */
-function removeTag(content, _syntax) {
- const patterns = [
- /([ \t]*)<!--\s*impeccable-live-start\s*-->[\s\S]*?<!--\s*impeccable-live-end\s*-->[ \t]*\n/,
- /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}[ \t]*\n/,
- ];
- for (const pat of patterns) {
- const next = content.replace(pat, '$1');
- if (next !== content) return next;
- }
- return content;
-}
-
-// ---------------------------------------------------------------------------
-// Content-Security-Policy meta-tag patcher
-//
-// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
-// the cross-origin load of /live.js (and the SSE/POST connection back to
-// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
-//
-// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
-// and stash the original `content` value in a `data-impeccable-csp-original`
-// attribute (base64) so revert is exact.
-//
-// On remove: detect the marker attribute, decode it, restore the original
-// content value verbatim, drop the marker.
-//
-// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
-// shared helpers) is NOT patched here — those need framework-specific config
-// edits and are handled via the existing detect-csp.mjs reference output.
-// Only the in-source meta-tag form gets the auto-patch.
-// ---------------------------------------------------------------------------
-
-const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
-
-function findCspMetaTags(content) {
- const out = [];
- const tagRe = /<meta\s+([^>]*?)\/?>/gis;
- let m;
- while ((m = tagRe.exec(content)) !== null) {
- const attrs = m[1];
- if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
- out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
- }
- return out;
-}
-
-function getAttr(attrs, name) {
- const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
- const m = attrs.match(re);
- return m ? { quote: m[1], value: m[2], full: m[0] } : null;
-}
-
-function appendOriginToDirective(csp, directive, origin) {
- const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
- const m = csp.match(re);
- if (m) {
- const tokens = m[4].trim().split(/\s+/);
- if (tokens.includes(origin)) return csp;
- return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
- }
- // Directive missing — add it. Use 'self' + origin so we don't inadvertently
- // narrow the policy compared to the default-src fallback (most users with
- // an explicit CSP have 'self' there).
- return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
-}
-
-export function patchCspMeta(content, port) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
- const origin = `http://localhost:${port}`;
-
- // Walk last-to-first so prior splices don't invalidate later indices.
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const attrs = tag.attrs;
- if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
- const contentAttr = getAttr(attrs, 'content');
- if (!contentAttr) continue;
-
- const original = contentAttr.value;
- let patched = original;
- patched = appendOriginToDirective(patched, 'script-src', origin);
- patched = appendOriginToDirective(patched, 'connect-src', origin);
- // The shader overlay during 'generating' creates a screenshot via
- // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
- // those. Add `blob:` so the overlay doesn't throw a CSP violation.
- patched = appendOriginToDirective(patched, 'img-src', 'blob:');
- if (patched === original) continue;
-
- const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
- const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
- // The tagRe captures any whitespace between the last attribute and the
- // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
- // a replace would land it BEFORE that trailing space, leaving a double
- // space inside attrs and clobbering the space before `/>`. Split off
- // the trailing whitespace, splice the marker into the attribute body,
- // and re-append the original trailing whitespace so a self-closing
- // `<meta … />` round-trips byte-for-byte.
- const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
- const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
- const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
- const newTag = tag.full.replace(attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-export function revertCspMeta(content) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
-
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
- if (!origAttr) continue;
- const contentAttr = getAttr(tag.attrs, 'content');
- if (!contentAttr) continue;
-
- let originalValue;
- try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
- catch { continue; }
-
- const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
- let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
- // Drop the marker attribute and any single space immediately preceding it.
- newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
- const newTag = tag.full.replace(tag.attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
- injectCli();
-}
-
-export { insertTag, removeTag, validateConfig, buildTagBlock };
-// patchCspMeta + revertCspMeta are exported above where they're defined.
@@ -1,200 +0,0 @@
-/**
- * CLI client for the live variant mode poll/reply protocol.
- *
- * Usage:
- * npx impeccable poll # Block until browser event, print JSON
- * npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
- * npx impeccable poll --reply <id> done # Reply "done" to event <id>
- * npx impeccable poll --reply <id> error "msg" # Reply with error
- */
-
-import { execFileSync } from 'node:child_process';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-// Node's built-in fetch (undici under the hood) enforces a 300s headers
-// timeout that can't be lowered per-request. We cap each request below
-// that ceiling and loop in `pollOnce` to synthesize a long poll without
-// depending on the standalone undici package.
-const PER_REQUEST_TIMEOUT_MS = 270_000;
-
-function readServerInfo() {
- const record = readLiveServerInfo(process.cwd());
- if (!record) {
- console.error('No running live server found. Start one with: npx impeccable live');
- process.exit(1);
- }
- return record.info;
-}
-
-export function buildPollReplyPayload(token, { id, type, message, file, data }) {
- return { token, id, type, message, file, data };
-}
-
-async function postReply(base, token, reply) {
- const res = await fetch(`${base}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(buildPollReplyPayload(token, reply)),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error || res.statusText);
- }
-}
-
-export async function pollCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable poll [options]
-
-Wait for a browser event from the live variant server, or reply to one.
-
-Modes:
- poll Block until a browser event arrives, print JSON
- poll --reply <id> done Reply "done" to event <id>
- poll --reply <id> error "msg" Reply with an error message
-
-Options:
- --timeout=MS Long-poll timeout in ms (default: 600000). Use the default unless the user asked to pause live; never use a short timeout to end the chat turn
- --help Show this help message`);
- process.exit(0);
- }
-
- const info = readServerInfo();
- const base = `http://localhost:${info.port}`;
-
- // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
- const replyIdx = args.indexOf('--reply');
- if (replyIdx !== -1) {
- const id = args[replyIdx + 1];
- const status = args[replyIdx + 2] || 'done';
- const fileIdx = args.indexOf('--file');
- const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
- // Message is any remaining positional arg that isn't a flag
- const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
-
- if (!id) {
- console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
- process.exit(1);
- }
-
- try {
- await postReply(base, info.token, { id, type: status, message, file: filePath });
-
- // Success — silent exit (agent doesn't need output for replies)
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Reply failed:', err.message);
- }
- process.exit(1);
- }
- return;
- }
-
- // Poll mode: block until browser event. Default 10 min. Node's built-in
- // fetch enforces a 300s headers timeout, so we loop in slices under that
- // ceiling and keep re-polling until we get a real event or the user's
- // total timeout runs out.
- const timeoutArg = args.find(a => a.startsWith('--timeout='));
- const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600000;
-
- const deadline = Date.now() + totalTimeout;
- let event;
- try {
- while (true) {
- const remaining = deadline - Date.now();
- if (remaining <= 0) {
- event = { type: 'timeout' };
- break;
- }
- const slice = Math.min(remaining, PER_REQUEST_TIMEOUT_MS);
- const res = await fetch(`${base}/poll?token=${info.token}&timeout=${slice}`);
-
- if (res.status === 401) {
- console.error('Authentication failed. The server token may have changed.');
- console.error('Try restarting: npx impeccable live stop && npx impeccable live');
- process.exit(1);
- }
-
- if (!res.ok) {
- console.error(`Poll failed: ${res.status} ${res.statusText}`);
- process.exit(1);
- }
-
- const next = await res.json();
- // Server-side timeout means no browser event arrived in this slice.
- // Loop and re-poll until we get a real event or we hit the user's
- // total deadline.
- if (next?.type === 'timeout' && Date.now() < deadline) continue;
- event = next;
- break;
- }
-
- // Auto-handle accept/discard via deterministic script
- if (event.type === 'accept' || event.type === 'discard') {
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const acceptScript = path.join(__dirname, 'live-accept.mjs');
- const scriptArgs = event.type === 'discard'
- ? ['--id', event.id, '--discard']
- : ['--id', event.id, '--variant', event.variantId];
- if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
- scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
- }
- try {
- const out = execFileSync(
- 'node',
- [acceptScript, ...scriptArgs],
- { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 }
- );
- event._acceptResult = JSON.parse(out.trim());
- } catch (err) {
- event._acceptResult = { handled: false, mode: 'error', error: err.message };
- }
-
- const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
- try {
- await postReply(base, info.token, {
- id: event.id,
- type: completionType,
- message: event._acceptResult?.error,
- file: event._acceptResult?.file,
- data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
- });
- } catch (err) {
- event._completionAck = { ok: false, error: err.message };
- }
- if (!event._completionAck) {
- event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
- }
- }
-
- // Second signal path: stderr banner in case the agent parses stdout
- // JSON but skips nested fields. One line is enough — the full checklist
- // is in reference/live.md.
- if (event._acceptResult?.carbonize === true) {
- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
- }
-
- // Print the event as JSON — the agent reads this from stdout
- console.log(JSON.stringify(event));
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Poll failed:', err.message);
- }
- process.exit(1);
- }
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
- pollCli();
-}
@@ -1,48 +0,0 @@
-#!/usr/bin/env node
-/**
- * Recover the next agent action from the durable live-session journal.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-
-function parseArgs(argv) {
- const out = { id: null };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function resumeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help) {
- console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });
- const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;
- if (!snapshot) {
- console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));
- return;
- }
-
- const pending = snapshot.pendingEvent || null;
- const nextAction = pending
- ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`
- : snapshot.phase === 'carbonize_required'
- ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`
- : snapshot.phase === 'accept_requested'
- ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`
- : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;
-
- console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {
- resumeCli();
-}
@@ -1,838 +0,0 @@
-#!/usr/bin/env node
-/**
- * Live variant mode server (self-contained, zero dependencies).
- *
- * Serves the browser script (/live.js), the detection overlay (/detect.js),
- * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
- * browser→server events. Agent communicates via HTTP long-poll (/poll).
- *
- * Usage:
- * node <scripts_path>/live-server.mjs # start
- * node <scripts_path>/live-server.mjs stop # stop + remove injected live.js tag
- * node <scripts_path>/live-server.mjs stop --keep-inject # stop only
- * node <scripts_path>/live-server.mjs --help
- */
-
-import http from 'node:http';
-import { randomUUID } from 'node:crypto';
-import { spawn, execFileSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import net from 'node:net';
-import { fileURLToPath } from 'node:url';
-import { parseDesignMd } from './design-parser.mjs';
-import { resolveContextDir } from './load-context.mjs';
-import { createLiveSessionStore } from './live-session-store.mjs';
-import {
- getDesignSidecarPath,
- getLiveAnnotationsDir,
- readLiveServerInfo,
- removeLiveServerInfo,
- resolveDesignSidecarPath,
- writeLiveServerInfo,
-} from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated
-// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
-// DESIGN.json fallback for existing projects.
-const CONTEXT_DIR = resolveContextDir(process.cwd());
-const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anyway
-const SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s
-
-// ---------------------------------------------------------------------------
-// Port detection
-// ---------------------------------------------------------------------------
-
-async function findOpenPort(start = 8400) {
- return new Promise((resolve) => {
- const srv = net.createServer();
- srv.listen(start, '127.0.0.1', () => {
- const port = srv.address().port;
- srv.close(() => resolve(port));
- });
- srv.on('error', () => resolve(findOpenPort(start + 1)));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Session state
-// ---------------------------------------------------------------------------
-
-const state = {
- token: null,
- port: null,
- sseClients: new Set(), // SSE response objects (server→browser push)
- pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
- pendingPolls: [], // agent poll callbacks waiting for browser events
- exitTimer: null,
- sessionDir: null, // per-session tmp dir for annotation screenshots
- sessionStore: null,
- leaseTimer: null,
-};
-
-// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;
-// cap at 10 MB to guard against runaway writes from a misbehaving client.
-const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
-
-function enqueueEvent(event) {
- if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;
- state.pendingEvents.push({ event, leaseUntil: 0 });
- flushPendingPolls();
-}
-
-function restorePendingEventsFromStore() {
- if (!state.sessionStore) return;
- for (const snapshot of state.sessionStore.listActiveSessions()) {
- if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);
- }
-}
-
-function findAvailablePendingEvent(now = Date.now()) {
- return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);
-}
-
-function leaseEvent(entry, leaseMs) {
- if (!entry.event?.id) {
- const idx = state.pendingEvents.indexOf(entry);
- if (idx !== -1) state.pendingEvents.splice(idx, 1);
- return entry.event;
- }
- entry.leaseUntil = Date.now() + leaseMs;
- return entry.event;
-}
-
-function acknowledgePendingEvent(id) {
- if (!id) return false;
- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);
- if (idx === -1) return false;
- state.pendingEvents.splice(idx, 1);
- scheduleLeaseFlush();
- return true;
-}
-
-function scheduleLeaseFlush() {
- if (state.leaseTimer) {
- clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- }
- if (state.pendingPolls.length === 0) return;
- const now = Date.now();
- const nextLeaseUntil = state.pendingEvents
- .map((entry) => entry.leaseUntil || 0)
- .filter((leaseUntil) => leaseUntil > now)
- .sort((a, b) => a - b)[0];
- if (!nextLeaseUntil) return;
- state.leaseTimer = setTimeout(() => {
- state.leaseTimer = null;
- flushPendingPolls();
- }, Math.max(0, nextLeaseUntil - now));
-}
-
-function flushPendingPolls() {
- while (state.pendingPolls.length > 0) {
- const entry = findAvailablePendingEvent();
- if (!entry) {
- scheduleLeaseFlush();
- return;
- }
- const poll = state.pendingPolls.shift();
- poll.resolve(leaseEvent(entry, poll.leaseMs));
- }
- scheduleLeaseFlush();
-}
-
-/** Push a message to all connected SSE clients. */
-function broadcast(msg) {
- const data = 'data: ' + JSON.stringify(msg) + '\n\n';
- for (const res of state.sseClients) {
- try { res.write(data); } catch { /* client gone */ }
- }
-}
-
-// ---------------------------------------------------------------------------
-// Load scripts
-// ---------------------------------------------------------------------------
-
-function loadBrowserScripts() {
- // Detection script: prefer the skill-bundled detector, then fall back to
- // source/npm package locations for local development and older installs.
- // This one IS cached — detect.js rarely changes during a session.
- const detectPaths = [
- path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(process.cwd(), 'node_modules', 'impeccable', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- ];
- let detectScript = '';
- for (const p of detectPaths) {
- try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
- }
-
- // live-browser.js: DO NOT cache. Return the path so the /live.js handler
- // can re-read on every request. Editing the browser script during iteration
- // should land on the next tab reload, not require a server restart.
- const sessionPath = path.join(__dirname, 'live-browser-session.js');
- const livePath = path.join(__dirname, 'live-browser.js');
- for (const p of [sessionPath, livePath]) {
- if (!fs.existsSync(p)) {
- process.stderr.write('Error: live browser script not found at ' + p + '\n');
- process.exit(1);
- }
- }
-
- return { detectScript, sessionPath, livePath };
-}
-
-function hasProjectContext() {
- // PRODUCT.md carries brand voice / anti-references — that's what determines
- // whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
- // concern, surfaced by the design panel's own empty state. Legacy
- // .impeccable.md is auto-migrated to PRODUCT.md by load-context.mjs.
- try {
- fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
- return true;
- } catch { return false; }
-}
-
-function statOrNull(filePath) {
- try { return fs.statSync(filePath); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// Validation (inline — no external import needed for self-contained script)
-// ---------------------------------------------------------------------------
-
-const VISUAL_ACTIONS = [
- 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
- 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
-];
-
-// Browser generates ids via crypto.randomUUID().slice(0, 8) (8 hex chars)
-// and variantIds via String(small integer). Restrict to those shapes so
-// any value that reaches a downstream child_process or DOM selector is
-// inert by construction.
-const ID_PATTERN = /^[0-9a-f]{8}$/;
-const VARIANT_ID_PATTERN = /^[0-9]{1,3}$/;
-
-function isValidId(v) { return typeof v === 'string' && ID_PATTERN.test(v); }
-function isValidVariantId(v) { return typeof v === 'string' && VARIANT_ID_PATTERN.test(v); }
-
-function validateEvent(msg) {
- if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
- switch (msg.type) {
- case 'generate':
- if (!isValidId(msg.id)) return 'generate: missing or malformed id';
- if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
- if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
- if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
- // Optional annotation fields (all-or-nothing: if any present, all must be well-formed).
- if (msg.screenshotPath !== undefined && typeof msg.screenshotPath !== 'string') return 'generate: screenshotPath must be string';
- if (msg.comments !== undefined && !Array.isArray(msg.comments)) return 'generate: comments must be array';
- if (msg.strokes !== undefined && !Array.isArray(msg.strokes)) return 'generate: strokes must be array';
- return null;
- case 'accept':
- if (!isValidId(msg.id)) return 'accept: missing or malformed id';
- if (!isValidVariantId(msg.variantId)) return 'accept: missing or malformed variantId';
- if (msg.paramValues !== undefined) {
- if (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues)) {
- return 'accept: paramValues must be an object';
- }
- }
- return null;
- case 'discard':
- return isValidId(msg.id) ? null : 'discard: missing or malformed id';
- case 'checkpoint':
- if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';
- if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';
- if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {
- return 'checkpoint: paramValues must be an object';
- }
- return null;
- case 'exit':
- return null;
- case 'prefetch':
- if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return 'prefetch: missing pageUrl';
- return null;
- default:
- return 'Unknown event type: ' + msg.type;
- }
-}
-
-// ---------------------------------------------------------------------------
-// HTTP request handler
-// ---------------------------------------------------------------------------
-
-function createRequestHandler({ detectScript, sessionPath, livePath }) {
- return (req, res) => {
- const url = new URL(req.url, `http://localhost:${state.port}`);
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
- if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
-
- const p = url.pathname;
-
- // --- Scripts ---
- if (p === '/live.js') {
- // Re-read from disk each request so edits to live-browser.js land on
- // the next tab reload. No-store headers prevent browser caching across
- // sessions — during iteration, a cached old script silently breaks
- // every subsequent session.
- let sessionScript;
- let liveScript;
- try {
- sessionScript = fs.readFileSync(sessionPath, 'utf-8');
- liveScript = fs.readFileSync(livePath, 'utf-8');
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'text/plain' });
- res.end('Error reading live browser scripts: ' + err.message);
- return;
- }
- const body =
- `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
- `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
- sessionScript + '\n' +
- liveScript;
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
- 'Pragma': 'no-cache',
- });
- res.end(body);
- return;
- }
- if (p === '/detect.js' || p === '/') {
- if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
- res.writeHead(200, { 'Content-Type': 'application/javascript' });
- res.end(detectScript);
- return;
- }
-
- // --- Vendored modern-screenshot (UMD build) ---
- // Lazy-loaded by live.js when the user clicks Go; exposes
- // window.modernScreenshot.domToBlob(...) for capture.
- if (p === '/modern-screenshot.js') {
- const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
- try {
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'public, max-age=31536000, immutable',
- });
- res.end(fs.readFileSync(vendorPath));
- } catch {
- res.writeHead(404); res.end('Vendor script not found');
- }
- return;
- }
-
- // --- Annotation upload (browser → server, raw PNG body) ---
- // Client generates the eventId, POSTs the PNG, then POSTs the generate
- // event with screenshotPath already set. Keeps bytes out of the SSE/poll
- // bridge and preserves the "one shot from the user's POV" UX.
- if (p === '/annotation' && req.method === 'POST') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const eventId = url.searchParams.get('eventId');
- if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid eventId' }));
- return;
- }
- if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
- res.writeHead(415, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
- return;
- }
- if (!state.sessionDir) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Session dir unavailable' }));
- return;
- }
- const chunks = [];
- let total = 0;
- let aborted = false;
- req.on('data', (c) => {
- if (aborted) return;
- total += c.length;
- if (total > MAX_ANNOTATION_BYTES) {
- aborted = true;
- res.writeHead(413, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Payload too large' }));
- req.destroy();
- return;
- }
- chunks.push(c);
- });
- req.on('end', () => {
- if (aborted) return;
- const absPath = path.join(state.sessionDir, eventId + '.png');
- try {
- fs.writeFileSync(absPath, Buffer.concat(chunks));
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Write failed: ' + err.message }));
- return;
- }
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true, path: absPath }));
- });
- req.on('error', () => {
- if (!aborted) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Upload failed' }));
- }
- });
- return;
- }
-
- // --- Health ---
- if (p === '/status') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
- const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok',
- port: state.port,
- connectedClients: state.sseClients.size,
- pendingEvents: state.pendingEvents.map((entry) => ({
- id: entry.event?.id,
- type: entry.event?.type,
- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),
- leaseUntil: entry.leaseUntil || null,
- })),
- activeSessions: sessions,
- }));
- return;
- }
-
- if (p === '/health') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok', port: state.port, mode: 'variant',
- hasProjectContext: hasProjectContext(),
- connectedClients: state.sseClients.size,
- }));
- return;
- }
-
- // --- Design system (unified v2 response) + raw ---
- // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json
- // sidecar when present. Panel merges them:
- // { present, parsed, sidecar, hasMd, hasSidecar,
- // mdNewerThanJson, parseError?, sidecarError? }
- // - parsed: output of parseDesignMd (frontmatter
- // + six canonical sections) when DESIGN.md exists.
- // - sidecar: .impeccable/design.json contents when present.
- // Expected shape: schemaVersion 2, carrying
- // extensions + components + narrative.
- // /design-system/raw returns DESIGN.md markdown verbatim
- if (p === '/design-system.json' || p === '/design-system/raw') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
-
- const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
- const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
- const mdStat = statOrNull(mdPath);
- const jsonStat = statOrNull(jsonPath);
-
- if (p === '/design-system/raw') {
- if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
- res.end(fs.readFileSync(mdPath, 'utf-8'));
- return;
- }
-
- if (!mdStat && !jsonStat) {
- res.writeHead(404, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ present: false }));
- return;
- }
-
- const response = {
- present: true,
- hasMd: !!mdStat,
- hasSidecar: !!jsonStat,
- mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
- };
-
- if (mdStat) {
- try {
- response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
- } catch (err) {
- response.parseError = err.message;
- }
- }
-
- if (jsonStat) {
- try {
- response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
- } catch (err) {
- response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;
- }
- }
-
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(response));
- return;
- }
-
- // --- Source file (no-HMR fallback) ---
- if (p === '/source') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const filePath = url.searchParams.get('path');
- if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
- const absPath = path.resolve(process.cwd(), filePath);
- if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
- let content;
- try { content = fs.readFileSync(absPath, 'utf-8'); }
- catch { res.writeHead(404); res.end('File not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
- res.end(content);
- return;
- }
-
- // --- SSE: server→browser push (replaces WebSocket) ---
- if (p === '/events' && req.method === 'GET') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- 'Connection': 'keep-alive',
- });
- res.write('data: ' + JSON.stringify({
- type: 'connected',
- hasProjectContext: hasProjectContext(),
- }) + '\n\n');
-
- state.sseClients.add(res);
- clearTimeout(state.exitTimer);
-
- // Keepalive: SSE comment every 30s prevents silent connection drops.
- const heartbeat = setInterval(() => {
- try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
- }, SSE_HEARTBEAT_INTERVAL);
-
- req.on('close', () => {
- clearInterval(heartbeat);
- state.sseClients.delete(res);
- if (state.sseClients.size === 0) {
- clearTimeout(state.exitTimer);
- state.exitTimer = setTimeout(() => {
- if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
- }, 8000);
- }
- });
- return;
- }
-
- // --- Browser→server events (replaces WebSocket messages) ---
- if (p === '/events' && req.method === 'POST') {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const error = validateEvent(msg);
- if (error) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error }));
- return;
- }
- if (state.sessionStore && msg.id) {
- try {
- state.sessionStore.appendEvent(msg);
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
- return;
- }
- }
- if (msg.type !== 'checkpoint') enqueueEvent(msg);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
- return;
- }
-
- // --- Stop ---
- if (p === '/stop') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.end('stopping');
- shutdown();
- return;
- }
-
- // --- Agent poll ---
- if (p === '/poll' && req.method === 'GET') {
- handlePollGet(req, res, url);
- return;
- }
- if (p === '/poll' && req.method === 'POST') {
- handlePollPost(req, res);
- return;
- }
-
- res.writeHead(404); res.end('Not found');
- };
-}
-
-// ---------------------------------------------------------------------------
-// Agent poll endpoints (unchanged from WS version)
-// ---------------------------------------------------------------------------
-
-function handlePollGet(req, res, url) {
- const token = url.searchParams.get('token');
- if (token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
- const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
- const available = findAvailablePendingEvent();
- if (available) {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(leaseEvent(available, leaseMs)));
- return;
- }
- const poll = { resolve, leaseMs };
- const timer = setTimeout(() => {
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ type: 'timeout' }));
- }, timeout);
- function resolve(event) {
- clearTimeout(timer);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(event));
- }
- state.pendingPolls.push(poll);
- scheduleLeaseFlush();
- req.on('close', () => {
- clearTimeout(timer);
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- });
-}
-
-function handlePollPost(req, res) {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- acknowledgePendingEvent(msg.id);
- if (state.sessionStore && msg.id) {
- try {
- const eventType = msg.type === 'discard' || msg.type === 'discarded'
- ? 'discarded'
- : msg.type === 'complete'
- ? 'complete'
- : msg.type === 'error'
- ? 'agent_error'
- : 'agent_done';
- state.sessionStore.appendEvent({
- type: eventType,
- id: msg.id,
- file: msg.file,
- message: msg.message,
- carbonize: msg.data?.carbonize === true,
- });
- } catch { /* keep reply path best-effort; browser still needs SSE */ }
- }
- flushPendingPolls();
- // Forward the reply to the browser via SSE
- broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Lifecycle
-// ---------------------------------------------------------------------------
-
-let httpServer = null;
-
-function shutdown() {
- removeLiveServerInfo(process.cwd());
- if (state.leaseTimer) clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- if (state.sessionDir) {
- try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}
- }
- for (const res of state.sseClients) { try { res.end(); } catch {} }
- state.sseClients.clear();
- for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });
- state.pendingPolls.length = 0;
- if (httpServer) httpServer.close();
- process.exit(0);
-}
-
-// ---------------------------------------------------------------------------
-// Main
-// ---------------------------------------------------------------------------
-
-const args = process.argv.slice(2);
-
-if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-server.mjs [options]
-
-Start the live variant mode server (zero dependencies).
-
-Commands:
- (default) Start the server (foreground)
- stop Stop the server and remove the injected live.js script tag
- stop --keep-inject Stop the server only (leave the script tag in the HTML entry)
-
-Options:
- --background Start detached, print connection JSON to stdout, then exit
- --port=PORT Use a specific port (default: auto-detect starting at 8400)
- --keep-inject Only with stop: skip live-inject.mjs --remove
- --help Show this help
-
-Endpoints:
- /live.js Browser script (element picker + variant cycling)
- /detect.js Detection overlay (backwards compatible)
- /modern-screenshot.js Vendored modern-screenshot UMD build (lazy-loaded by live.js)
- /annotation POST raw image/png to stage a variant screenshot
- /events SSE stream (server→browser) + POST (browser→server)
- /poll Long-poll for agent CLI
- /source Raw source file reader (no-HMR fallback)
- /status Durable recovery status (token-protected)
- /health Health check`);
- process.exit(0);
-}
-
-if (args.includes('stop')) {
- const keepInject = args.includes('--keep-inject');
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);
- if (res.ok) console.log(`Stopped live server on port ${info.port}.`);
- } catch {
- console.log('No running live server found.');
- }
- if (!keepInject) {
- const injectPath = path.join(__dirname, 'live-inject.mjs');
- try {
- const out = execFileSync(process.execPath, [injectPath, '--remove'], {
- encoding: 'utf-8',
- cwd: process.cwd(),
- });
- const line = out.trim().split('\n').filter(Boolean).pop();
- if (line) {
- try {
- const j = JSON.parse(line);
- if (j.removed === true) {
- console.log(`Removed live script tag from ${j.file}.`);
- }
- } catch {
- /* ignore non-JSON lines */
- }
- }
- } catch (err) {
- const detail = err.stderr?.toString?.().trim?.()
- || err.stdout?.toString?.().trim?.()
- || err.message
- || String(err);
- console.warn(`Note: could not remove live script tag (${detail.split('\n')[0]})`);
- }
- }
- process.exit(0);
-}
-
-// --background: spawn a detached child server, wait for it to be ready,
-// print the connection JSON, then exit. This keeps the startup command
-// simple (no shell backgrounding or chained commands).
-if (args.includes('--background')) {
- const childArgs = args.filter(a => a !== '--background');
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), ...childArgs], {
- detached: true,
- stdio: 'ignore',
- cwd: process.cwd(),
- });
- child.unref();
-
- // Poll for the PID file (the child writes it once the HTTP server is listening).
- const deadline = Date.now() + 10_000;
- while (Date.now() < deadline) {
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- if (info.pid !== process.pid) {
- // Output JSON so the agent can read port + token from stdout.
- console.log(JSON.stringify(info));
- process.exit(0);
- }
- } catch { /* not ready yet */ }
- await new Promise(r => setTimeout(r, 200));
- }
- console.error('Timed out waiting for live server to start.');
- process.exit(1);
-}
-
-// Check for existing session
-const existingRecord = readLiveServerInfo(process.cwd());
-if (existingRecord?.info) {
- const existing = existingRecord.info;
- try {
- process.kill(existing.pid, 0);
- console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
- console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');
- process.exit(1);
- } catch {
- try { fs.unlinkSync(existingRecord.path); } catch {}
- }
-}
-
-state.token = randomUUID();
-state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });
-restorePendingEventsFromStore();
-const portArg = args.find(a => a.startsWith('--port='));
-state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
-// Annotation screenshots live in the project root so the agent's Read tool
-// doesn't trip a per-file permission prompt. Sessioned by token so concurrent
-// projects (or quick restarts) don't collide.
-const annotRoot = getLiveAnnotationsDir(process.cwd());
-fs.mkdirSync(annotRoot, { recursive: true });
-state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));
-
-const { detectScript, sessionPath, livePath } = loadBrowserScripts();
-httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));
-
-httpServer.listen(state.port, '127.0.0.1', () => {
- writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });
- const url = `http://localhost:${state.port}`;
- console.log(`\nImpeccable live server running on ${url}`);
- console.log(`Token: ${state.token}\n`);
- console.log(`Inject: <script src="${url}/live.js"><\/script>`);
- console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
-});
-
-process.on('SIGINT', shutdown);
-process.on('SIGTERM', shutdown);
@@ -1,254 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';
-
-const COMPLETED_PHASES = new Set(['completed', 'discarded']);
-
-export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {
- const rootDir = getLiveSessionsDir(cwd);
- const legacyRootDir = getLegacyLiveSessionsDir(cwd);
- fs.mkdirSync(rootDir, { recursive: true });
- const snapshotCache = new Map();
-
- function loadCachedOrRebuild(id) {
- const cached = snapshotCache.get(id);
- if (cached) return cached;
- const journalPath = getReadableJournalPath(id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- return rebuilt;
- }
-
- function getReadableJournalPath(id) {
- const primary = getJournalPath(rootDir, id);
- if (fs.existsSync(primary)) return primary;
- const legacy = getJournalPath(legacyRootDir, id);
- if (fs.existsSync(legacy)) return legacy;
- return primary;
- }
-
- return {
- rootDir,
- legacyRootDir,
- appendEvent(event) {
- const normalized = normalizeEvent(event, sessionId);
- const journalPath = getJournalPath(rootDir, normalized.id);
- const snapshotPath = getSnapshotPath(rootDir, normalized.id);
- const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);
- if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {
- fs.copyFileSync(legacyJournalPath, journalPath);
- }
- const prior = loadCachedOrRebuild(normalized.id);
- const seq = prior.nextSeq;
- const entry = {
- seq,
- id: normalized.id,
- type: normalized.type,
- ts: new Date().toISOString(),
- event: normalized,
- };
- fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');
- const next = applyEvent(prior.snapshot, entry, prior.diagnostics);
- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });
- writeSnapshot(snapshotPath, next);
- return next;
- },
- getSnapshot(id = sessionId, opts = {}) {
- if (!id) throw new Error('session id required');
- const journalPath = getReadableJournalPath(id);
- const snapshotPath = getSnapshotPath(rootDir, id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- writeSnapshot(snapshotPath, rebuilt.snapshot);
- if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;
- return rebuilt.snapshot;
- },
- listActiveSessions() {
- const ids = new Set();
- for (const dir of [legacyRootDir, rootDir]) {
- if (!fs.existsSync(dir)) continue;
- for (const name of fs.readdirSync(dir)) {
- if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));
- }
- }
- return [...ids]
- .sort()
- .map((id) => this.getSnapshot(id))
- .filter(Boolean);
- },
- };
-}
-
-function normalizeEvent(event, fallbackId) {
- if (!event || typeof event !== 'object') throw new Error('event object required');
- const id = event.id || fallbackId;
- if (!id || typeof id !== 'string') throw new Error('event id required');
- if (!event.type || typeof event.type !== 'string') throw new Error('event type required');
- return { ...event, id };
-}
-
-function getJournalPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.jsonl');
-}
-
-function getSnapshotPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.snapshot.json');
-}
-
-function safeSessionId(id) {
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);
- return id;
-}
-
-function baseSnapshot(id) {
- return {
- id,
- phase: 'new',
- pageUrl: null,
- sourceFile: null,
- expectedVariants: 0,
- arrivedVariants: 0,
- visibleVariant: null,
- paramValues: {},
- pendingEventSeq: null,
- pendingEvent: null,
- deliveryLease: null,
- checkpointRevision: 0,
- activeOwner: null,
- sourceMarkers: {},
- fallbackMode: null,
- annotationArtifacts: [],
- diagnostics: [],
- updatedAt: null,
- };
-}
-
-function rebuildSnapshotFromJournal(journalPath, id) {
- let snapshot = baseSnapshot(id);
- const diagnostics = [];
- let nextSeq = 1;
- if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };
-
- const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- if (!line.trim()) continue;
- try {
- const entry = JSON.parse(line);
- if (!entry || typeof entry !== 'object') throw new Error('entry is not object');
- if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);
- snapshot = applyEvent(snapshot, entry);
- } catch (err) {
- diagnostics.push({
- error: 'journal_parse_failed',
- line: i + 1,
- message: err.message,
- });
- }
- }
- snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];
- return { snapshot, diagnostics, nextSeq };
-}
-
-function applyEvent(snapshot, entry, inheritedDiagnostics = []) {
- const event = entry.event || entry;
- const next = {
- ...snapshot,
- paramValues: { ...(snapshot.paramValues || {}) },
- sourceMarkers: { ...(snapshot.sourceMarkers || {}) },
- annotationArtifacts: [...(snapshot.annotationArtifacts || [])],
- diagnostics: [...(snapshot.diagnostics || [])],
- updatedAt: entry.ts || new Date().toISOString(),
- };
-
- if (inheritedDiagnostics.length && next.diagnostics.length === 0) {
- next.diagnostics = [...inheritedDiagnostics];
- }
-
- switch (event.type) {
- case 'generate':
- next.phase = 'generate_requested';
- next.pageUrl = event.pageUrl ?? next.pageUrl;
- next.expectedVariants = event.count ?? next.expectedVariants;
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });
- break;
- case 'variants_ready':
- case 'agent_done':
- next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';
- next.sourceFile = event.file ?? next.sourceFile;
- next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- if (event.carbonize === true) {
- next.diagnostics.push({
- error: 'carbonize_cleanup_required',
- file: event.file || null,
- message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',
- });
- }
- break;
- case 'checkpoint':
- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {
- next.phase = event.phase ?? next.phase;
- next.checkpointRevision = event.revision ?? next.checkpointRevision;
- next.activeOwner = event.owner ?? next.activeOwner;
- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;
- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- } else {
- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });
- }
- break;
- case 'accept':
- case 'accept_intent':
- next.phase = 'accept_requested';
- next.visibleVariant = Number(event.variantId ?? next.visibleVariant);
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discard':
- next.phase = 'discard_requested';
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discarded':
- next.phase = 'discarded';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'complete':
- next.phase = 'completed';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'agent_error':
- next.phase = 'agent_error';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });
- break;
- default:
- next.diagnostics.push({ error: 'unknown_event_type', type: event.type });
- break;
- }
- return next;
-}
-
-function toPendingEvent(event) {
- const pending = { ...event };
- delete pending.token;
- return pending;
-}
-
-function upsertArtifact(artifacts, artifact) {
- if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {
- artifacts.push(artifact);
- }
-}
-
-function writeSnapshot(snapshotPath, snapshot) {
- fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');
-}
@@ -1,47 +0,0 @@
-#!/usr/bin/env node
-/**
- * Print durable recovery status for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function fetchServerStatus(info) {
- if (!info) return null;
- try {
- const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-export async function statusCli() {
- const info = readServerInfo();
- const server = await fetchServerStatus(info);
- const store = createLiveSessionStore({ cwd: process.cwd() });
- const activeSessions = store.listActiveSessions();
- const payload = {
- liveServer: server ? {
- status: server.status,
- port: server.port,
- connectedClients: server.connectedClients,
- pendingEvents: server.pendingEvents,
- } : null,
- activeSessions: server?.activeSessions || activeSessions,
- recoveryHint: server
- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'
- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',
- };
- console.log(JSON.stringify(payload, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {
- statusCli();
-}
@@ -1,632 +0,0 @@
-/**
- * CLI helper: find an element in source and wrap it in a variant container.
- *
- * Usage:
- * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
- *
- * Searches project files for the element matching the query (class name, ID, or
- * text snippet), wraps it with the variant scaffolding, and prints the file path
- * + line range where the agent should insert variant HTML.
- *
- * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-export async function wrapCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable wrap [options]
-
-Find an element in source and wrap it in a variant container.
-
-Required:
- --id ID Session ID for the variant wrapper
- --count N Number of expected variants (1-8)
-
-Element identification (at least one required):
- --element-id ID HTML id attribute of the element
- --classes A,B,C Comma-separated CSS class names
- --tag TAG Tag name (div, section, etc.)
- --query TEXT Fallback: raw text to search for
-
-Optional:
- --file PATH Source file to search in (skips auto-detection)
- --text TEXT Picked element's textContent. Used to disambiguate when
- classes/tag match multiple sibling elements (e.g. a list
- of <Card>s with the same className). Pass the first ~80
- chars of event.element.textContent.
- --help Show this help message
-
-Output (JSON):
- { file, startLine, endLine, insertLine, commentSyntax }
-
-The agent should insert variant HTML at insertLine.`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const count = parseInt(argVal(args, '--count') || '3');
- const elementId = argVal(args, '--element-id');
- const classes = argVal(args, '--classes');
- const tag = argVal(args, '--tag');
- const query = argVal(args, '--query');
- const filePath = argVal(args, '--file');
- const text = argVal(args, '--text');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!elementId && !classes && !query) {
- console.error('Need at least one of: --element-id, --classes, --query');
- process.exit(1);
- }
-
- // Build search queries in priority order (most specific first)
- const queries = buildSearchQueries(elementId, classes, tag, query);
-
- const genOpts = { cwd: process.cwd() };
-
- // Find the source file. Generated files are excluded from auto-search so we
- // don't silently write variants into a file the next build will wipe.
- let targetFile = filePath;
- let matchedQuery = null;
- if (!targetFile) {
- for (const q of queries) {
- targetFile = findFileWithQuery(q, process.cwd(), genOpts);
- if (targetFile) { matchedQuery = q; break; }
- }
- if (!targetFile) {
- // Nothing in source. Did the element show up in a generated file? That
- // tells the agent "fall back to the agent-driven flow" vs "element just
- // doesn't exist in this project."
- let generatedHit = null;
- for (const q of queries) {
- generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
- if (generatedHit) break;
- }
- if (generatedHit) {
- console.error(JSON.stringify({
- error: 'element_not_in_source',
- fallback: 'agent-driven',
- generatedMatch: path.relative(process.cwd(), generatedHit),
- hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
- }));
- } else {
- console.error(JSON.stringify({
- error: 'element_not_found',
- fallback: 'agent-driven',
- hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
- }));
- }
- process.exit(1);
- }
- } else {
- if (isGeneratedFile(targetFile, genOpts)) {
- console.error(JSON.stringify({
- error: 'file_is_generated',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
- hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- matchedQuery = queries[0];
- }
-
- const content = fs.readFileSync(targetFile, 'utf-8');
- const lines = content.split('\n');
-
- // Find the element, trying each query in priority order. When `--text` is
- // supplied, collect every candidate the queries surface and disambiguate
- // by the picked element's textContent. Without `--text`, fall back to the
- // legacy first-match behavior so unmodified callers keep working.
- let match = null;
- if (text) {
- const candidates = [];
- for (const q of queries) {
- const all = findAllElements(lines, q, tag);
- for (const c of all) {
- if (!candidates.some((x) => x.startLine === c.startLine)) {
- candidates.push(c);
- }
- }
- // Once a more-specific query (ID, full className combo) yielded a unique
- // result, stop — falling through to the loose tag+single-class query
- // would readmit the siblings we just disambiguated past.
- if (candidates.length === 1) break;
- }
- if (candidates.length === 0) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- if (candidates.length === 1) {
- match = candidates[0];
- } else {
- const filtered = filterByText(candidates, lines, text);
- if (filtered.length === 1) {
- match = filtered[0];
- } else if (filtered.length === 0) {
- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the
- // browser-side textContent doesn't appear literally in source. Fall
- // back to first-match rather than refusing — this is the same
- // behavior unmodified callers see, just preserved.
- match = candidates[0];
- } else {
- // Multiple candidates ALSO match the text. Truly ambiguous — refuse
- // rather than pick wrong, and hand the agent the candidate locations
- // so it can disambiguate by reading the file.
- console.error(JSON.stringify({
- error: 'element_ambiguous',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), targetFile),
- candidates: filtered.map((c) => ({
- startLine: c.startLine + 1,
- endLine: c.endLine + 1,
- })),
- hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- }
- } else {
- for (const q of queries) {
- match = findElement(lines, q, tag);
- if (match) break;
- }
- if (!match) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- }
-
- const { startLine, endLine } = match;
- const commentSyntax = detectCommentSyntax(targetFile);
- const styleMode = detectStyleMode(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- const indent = lines[startLine].match(/^(\s*)/)[1];
-
- // Extract the original element. Reindent under the wrapper while preserving
- // the relative depth between lines — `l.trimStart()` would strip ALL leading
- // whitespace and collapse e.g. `<aside>`/` <h1>`/`</aside>` (6/8/6 spaces)
- // to a single uniform indent, so on accept/discard the round-trip restores
- // the inner element at its parent's depth instead of nested inside it.
- // Strip only the COMMON minimum leading whitespace across the picked lines;
- // `deindentContent` on the accept side already mirrors this convention.
- const originalLines = lines.slice(startLine, endLine + 1);
- const originalBaseIndent = minLeadingSpaces(originalLines);
- const reindentOriginal = (extra) => originalLines
- .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
- .join('\n');
- const originalIndented = reindentOriginal(' ');
-
- // Wrapper attributes differ by syntax. HTML allows plain string attrs;
- // JSX requires object-literal style and parses string attrs as HTML (which
- // either type-errors or renders a literal CSS string).
- const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
-
- // JSX/TSX guard: the picked element occupies a single JSX child slot
- // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
- // any other expression position). Replacing it with `comment + <div> +
- // comment` yields three adjacent siblings — invalid JSX. We can't use a
- // Fragment `<></>` either: parents that clone children (Radix `asChild`,
- // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
- // they try to pass an `id` through.
- //
- // Solution: keep the wrapper `<div>` as the single JSX-slot child and
- // tuck both marker comments INSIDE it. accept/discard then expands its
- // replacement range to include the wrapper's `<div>` open / close lines
- // so the entire scaffold gets removed cleanly.
- const wrapperLines = isJsx ? [
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- reindentOriginal(' '),
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- indent + '</div>',
- ] : [
- indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- originalIndented,
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + '</div>',
- indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- ];
-
- // Replace the original element with the wrapper
- const newLines = [
- ...lines.slice(0, startLine),
- ...wrapperLines,
- ...lines.slice(endLine + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- // Calculate insert line (the "insert below this line" comment).
- // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
- // the insert marker (HTML: start-comment + outer-div + Original-comment +
- // original-div + content + close-original-div; JSX: outer-div +
- // start-comment + Original-comment + original-div + content +
- // close-original-div). Multi-line originals push the marker by their
- // extra line count.
- const insertLine = startLine + 6 + (originalLines.length - 1);
-
- console.log(JSON.stringify({
- file: path.relative(process.cwd(), targetFile),
- startLine: startLine + 1, // 1-indexed for the agent
- // wrapperLines is an array but one element (the original-content slot)
- // is a `\n`-joined multi-line string, so the actual file-row count is
- // wrapperLines.length + (originalLines.length - 1). Without the offset,
- // endLine pointed inside the wrapper for any picked element that
- // spanned more than one source line.
- endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexed
- insertLine: insertLine + 1, // 1-indexed: where variants go
- commentSyntax: commentSyntax,
- styleMode: styleMode.mode,
- styleTag: styleMode.styleTag,
- cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
- cssAuthoring: buildCssAuthoring(styleMode, count),
- originalLineCount: originalLines.length,
- }));
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-/**
- * Build search query strings in priority order (most specific first).
- * ID is most reliable, then specific class combos, then single classes, then raw query.
- */
-function buildSearchQueries(elementId, classes, tag, query) {
- const queries = [];
-
- // 1. ID is the most specific
- if (elementId) {
- queries.push('id="' + elementId + '"');
- }
-
- // 2. Full class attribute match (for elements with distinctive multi-class combos).
- // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
- // convention the file uses will match.
- if (classes) {
- const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
- if (classList.length > 1) {
- const joined = classList.join(' ');
- const sorted = [...classList].sort((a, b) => b.length - a.length);
- queries.push('class="' + joined + '"');
- queries.push('className="' + joined + '"');
- queries.push(sorted[0]); // most distinctive single class, fallback
- } else if (classList.length === 1) {
- queries.push(classList[0]);
- }
- }
-
- // 3. Tag + class combo (e.g., <section class="hero">).
- // Same dual-emit for JSX compatibility.
- if (tag && classes) {
- const firstClass = classes.split(',')[0].trim();
- queries.push('<' + tag + ' class="' + firstClass);
- queries.push('<' + tag + ' className="' + firstClass);
- }
-
- // 4. Raw fallback query
- if (query) {
- queries.push(query);
- }
-
- return queries;
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- // HTML, Vue, Svelte, Astro all use HTML comments
- return { open: '<!--', close: '-->' };
-}
-
-function detectStyleMode(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.astro') {
- return {
- mode: 'astro-global-prefixed',
- styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',
- };
- }
- return {
- mode: 'scoped',
- styleTag: '<style data-impeccable-css="SESSION_ID">',
- };
-}
-
-function buildCssSelectorPrefixExamples(styleMode, count) {
- if (styleMode !== 'astro-global-prefixed') return [];
- return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);
-}
-
-function buildCssAuthoring(styleMode, count) {
- const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
- if (styleMode.mode === 'astro-global-prefixed') {
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'global-prefixed',
- rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',
- selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),
- requirements: [
- 'Use the styleTag exactly; the is:inline attribute is required for this file.',
- 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',
- 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
- ],
- forbidden: [
- 'Do not use @scope for this styleMode.',
- ],
- };
- }
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'scope-rule',
- rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',
- selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),
- requirements: [
- 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',
- 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
- 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
- ],
- forbidden: [
- 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',
- 'Do not add is:inline to the style tag for this styleMode.',
- ],
- };
-}
-
-/**
- * Search project files for the query string (class name, ID, etc.)
- * Returns the first matching file path, or null.
- */
-function findFileWithQuery(query, cwd, genOpts = {}) {
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, query, seen, 0, genOpts);
- if (result) return result;
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth, genOpts) {
- if (depth > 5) return null; // don't go too deep
- const realDir = fs.realpathSync(dir);
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- // Check files first
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name).toLowerCase();
- if (!EXTENSIONS.includes(ext)) continue;
-
- const filePath = path.join(dir, entry.name);
- if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip unreadable files */ }
- }
-
- // Then recurse into directories. Always skip node_modules and .git (never
- // project content). dist/build/out are left to the isGeneratedFile guard so
- // the includeGenerated second-pass can still find the element there and
- // report `generatedMatch`.
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
- if (result) return result;
- }
-
- return null;
-}
-
-/**
- * Regex that matches a tag opener on a line. Allows the tag name to be
- * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
- * openers (e.g. `<section\n className="..."\n>`) are recognised.
- */
-const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
-
-/**
- * Find the element's start and end line in the file.
- *
- * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
- * `id="..."`), or a raw text snippet. Because a query can appear on a
- * continuation line of a multi-line tag (e.g. the `className="..."` row of a
- * `<section\n className="..."\n>` JSX tag), we walk backward from the match
- * line to find the actual tag opener. When `tag` is provided, opener candidates
- * must match that tag name.
- */
-/**
- * Return the smallest leading-whitespace count across a set of lines,
- * ignoring blank lines (whose indent isn't load-bearing). Used to compute
- * the common base indent of a multi-line picked element so reindenting
- * under the wrapper preserves the relative depth between lines.
- */
-function minLeadingSpaces(lines) {
- let min = Infinity;
- for (const l of lines) {
- if (l.trim() === '') continue;
- const m = l.match(/^(\s*)/);
- if (m && m[1].length < min) min = m[1].length;
- }
- return min === Infinity ? 0 : min;
-}
-
-function findElement(lines, query, tag = null) {
- // Iterate all matches — the first substring hit isn't always the right one.
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
-
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- // Skip lines already inside a variant wrapper
- if (lines[i].includes('data-impeccable-variant')) continue;
-
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
-
- const endLine = findClosingLine(lines, openerLine);
- return { startLine: openerLine, endLine };
- }
-
- return null;
-}
-
-/**
- * Like findElement, but returns every match. Used for ambiguity detection
- * when the agent passes --text: when the same className appears on multiple
- * sibling elements (a list of cards, repeated section variants, etc.),
- * first-match silently lands on the wrong branch. Returning all matches lets
- * the caller narrow by textContent or fail with a structured ambiguity error.
- */
-function findAllElements(lines, query, tag = null) {
- const out = [];
- const seen = new Set();
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- if (lines[i].includes('data-impeccable-variant')) continue;
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
- if (seen.has(openerLine)) continue; // multiple matches inside the same element
- seen.add(openerLine);
- const endLine = findClosingLine(lines, openerLine);
- out.push({ startLine: openerLine, endLine });
- }
- return out;
-}
-
-/**
- * Narrow a candidate set to those whose source body matches a meaningful
- * prefix of the picked element's textContent. The compare strips tags and
- * JSX expressions, then checks two whitespace normalizations side-by-side:
- *
- * - single-space ("hero two second card body")
- * - no-whitespace ("herotwosecondcardbody")
- *
- * Both are needed because `el.textContent` concatenates sibling text without
- * inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
- * `"Hero TwoSecond…"`), while the source has whitespace between tags. If
- * EITHER normalization matches, the candidate keeps. A snippet shorter than
- * 8 chars after stripping is too weak to disambiguate — the caller falls
- * back to first-match.
- */
-function filterByText(candidates, lines, text) {
- const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
- // Too short to disambiguate. Return [] so the caller's `filtered.length
- // === 0` branch fires (fall back to first-match) — the previous
- // `candidates.slice()` return forced `filtered.length > 1` and surfaced
- // a spurious `element_ambiguous` error on every short-text picker event
- // with multiple candidates.
- if (trimmed.length < 8) return [];
- const targetSpaced = trimmed;
- const targetCompact = trimmed.replace(/\s+/g, '');
-
- return candidates.filter((c) => {
- const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
- const inner = body
- .replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
- .replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
- .toLowerCase();
- const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
- const sourceCompact = inner.replace(/\s+/g, '');
- return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
- });
-}
-
-/**
- * Resolve a match line to the real tag opener. If the match line itself opens
- * a tag, return it. Otherwise walk up to 10 lines backward looking for the
- * first tag opener. If `tag` is specified, the opener must match that tag
- * name; an opener with a different tag name aborts the backward walk for this
- * match (we don't jump across element boundaries).
- *
- * Returns the line index of the opener, or -1 if none can be resolved.
- */
-function findOpenerLine(lines, matchLine, tag) {
- const self = lines[matchLine].match(OPENER_RE);
- if (self) {
- if (!tag || self[1] === tag) return matchLine;
- return -1;
- }
- const MAX_BACKWALK = 10;
- for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
- const opener = lines[i].match(OPENER_RE);
- if (!opener) continue;
- if (!tag || opener[1] === tag) return i;
- // Different tag name than requested — abort; we're inside a non-target opener.
- return -1;
- }
- return -1;
-}
-
-/**
- * Starting from a line with an opening tag, find the line with the matching
- * closing tag by counting tag nesting depth.
- */
-function findClosingLine(lines, start) {
- const openMatch = lines[start].match(OPENER_RE);
- if (!openMatch) return start; // caller passed a non-opener; nothing to span
-
- const tagName = openMatch[1];
- let depth = 0;
- const openRe = new RegExp('<' + tagName + '(?=[\\s/>]|$)', 'g');
- const selfCloseRe = new RegExp('<' + tagName + '[^>]*/>', 'g');
- const closeRe = new RegExp('</' + tagName + '\\s*>', 'g');
-
- for (let i = start; i < lines.length; i++) {
- const line = lines[i];
- const opens = (line.match(openRe) || []).length;
- const selfCloses = (line.match(selfCloseRe) || []).length;
- const closes = (line.match(closeRe) || []).length;
-
- depth += opens - selfCloses - closes;
-
- if (depth <= 0) return i;
- }
-
- // If we can't find the close, return a reasonable guess
- return Math.min(start + 50, lines.length - 1);
-}
-
-// Auto-execute when run directly (node live-wrap.mjs ...)
-const _running = process.argv[1];
-if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {
- wrapCli();
-}
-
-// Test exports (used by tests/live-wrap.test.mjs)
-export { buildSearchQueries, findElement, findClosingLine, detectCommentSyntax };
@@ -1,247 +0,0 @@
-/**
- * CLI entry point: prepare everything needed to enter the live variant poll loop.
- *
- * Does (all in one command):
- * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)
- * 2. Start the live server in the background (or reuse a running one)
- * 3. Inject the browser script tag into the project's entry file
- * 4. Read PRODUCT.md / DESIGN.md for project context
- * 5. Print a single JSON blob with everything the agent needs
- *
- * After this, the agent's only remaining steps are:
- * - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll
- * - Enter the poll loop: `node live-poll.mjs`
- *
- * Usage:
- * node live.mjs # Prepare everything, print JSON, exit
- * node live.mjs --help
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { loadContext } from './load-context.mjs';
-import { resolveFiles } from './live-inject.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-async function liveCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live.mjs
-
-Prepare everything for live variant mode in a single command:
- - Checks .impeccable/live/config.json (required, created once per project)
- - Starts (or reuses) the live server in the background
- - Injects the browser script tag
- - Reads PRODUCT.md / DESIGN.md for project context
-
-On success, prints a JSON blob with:
- { ok, serverPort, serverToken, pageFile, hasContext, context }
-
-On config_missing, prints:
- { ok: false, error: "config_missing", configPath, hint }
-
-The agent should then:
- 1. If config_missing, create the config and re-run this script
- 2. Optionally open the project's dev/preview URL in the browser (see reference/live.md—not serverPort)
- 3. Enter the poll loop: node live-poll.mjs`);
- process.exit(0);
- }
-
- // 1. Check config (fail fast if missing — no point starting anything else)
- const checkOut = runScript('live-inject.mjs', ['--check']);
- const checkResult = safeParse(checkOut);
- if (!checkResult || !checkResult.ok) {
- console.log(JSON.stringify(checkResult || { ok: false, error: 'check_failed', raw: checkOut }));
- process.exit(0);
- }
-
- // 2. Start server (or reuse existing)
- const serverInfo = ensureServerRunning();
- if (!serverInfo) {
- console.log(JSON.stringify({ ok: false, error: 'server_start_failed' }));
- process.exit(1);
- }
-
- // 3. Inject the script tag at the current port
- const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)]);
- const injectResult = safeParse(injectOut);
- if (!injectResult || !injectResult.ok) {
- console.log(JSON.stringify({
- ok: false,
- error: 'inject_failed',
- detail: injectResult || injectOut,
- serverPort: serverInfo.port,
- }));
- process.exit(1);
- }
-
- // 4. Load PRODUCT.md + DESIGN.md context (auto-migrates legacy .impeccable.md)
- const ctx = loadContext(process.cwd());
-
- // 5. Compute drift-heal: compare resolved inject targets against the
- // project's HTML files. Orphans are HTML files not covered by config.
- // Warning only — the agent decides whether to act.
- const resolvedFiles = resolveFiles(process.cwd(), checkResult.config);
- const drift = scanForDrift(process.cwd(), resolvedFiles, checkResult.config);
-
- // 6. Emit everything the agent needs
- console.log(JSON.stringify({
- ok: true,
- serverPort: serverInfo.port,
- serverToken: serverInfo.token,
- pageFiles: resolvedFiles,
- configDrift: drift,
- hasProduct: ctx.hasProduct,
- product: ctx.product,
- productPath: ctx.productPath,
- hasDesign: ctx.hasDesign,
- design: ctx.design,
- designPath: ctx.designPath,
- migrated: ctx.migrated,
- }, null, 2));
-}
-
-/**
- * Drift-heal scan. Walks the project for HTML files under common
- * page-source directories (public/, src/, app/, pages/) and reports any
- * that aren't covered by the resolved inject targets. This is purely
- * advisory — the agent can ignore it, or suggest the user add the
- * orphans to config.files.
- *
- * Skipped if config.files already contains at least one glob pattern
- * covering everything in practice (signaled by the orphan count being 0).
- */
-function scanForDrift(rootDir, resolvedFiles, config) {
- const SCAN_ROOTS = ['public', 'src', 'app', 'pages'];
- const IGNORE_DIRS = new Set([
- 'node_modules', '.git', '.next', '.nuxt', '.svelte-kit', '.astro',
- '.turbo', '.vercel', '.cache', 'coverage', 'dist', 'build',
- ]);
-
- const resolvedSet = new Set(resolvedFiles.map((f) => f.split(path.sep).join('/')));
-
- // Files matching the user's `exclude` globs are intentional omissions,
- // not drift. Compile them to regexes so the orphan list stays signal.
- const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
- .map((p) => globToRegex(p));
- const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
-
- const orphans = [];
-
- const walk = (dir, relBase) => {
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
- for (const e of entries) {
- const rel = relBase ? `${relBase}/${e.name}` : e.name;
- if (e.isDirectory()) {
- if (IGNORE_DIRS.has(e.name) || e.name.startsWith('.')) continue;
- walk(path.join(dir, e.name), rel);
- } else if (e.isFile() && e.name.endsWith('.html')) {
- if (resolvedSet.has(rel)) continue;
- if (isUserExcluded(rel)) continue;
- orphans.push(rel);
- }
- }
- };
-
- for (const root of SCAN_ROOTS) {
- const abs = path.join(rootDir, root);
- if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
- walk(abs, root);
- }
- }
-
- if (orphans.length === 0) return null;
- const capped = orphans.slice(0, 20);
- return {
- orphans: capped,
- orphanCount: orphans.length,
- hint: `${orphans.length} HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like "public/**/*.html".`,
- };
-}
-
-/**
- * Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
- * to avoid a circular import (live-inject.mjs already imports nothing
- * from live.mjs). The two must stay in sync.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
- else { re += '.*'; i += 2; }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function runScript(name, args) {
- const scriptPath = path.join(__dirname, name);
- const cmd = `node "${scriptPath}" ${args.map(a => `"${a}"`).join(' ')}`;
- try {
- return execSync(cmd, { encoding: 'utf-8', cwd: process.cwd(), timeout: 15_000 });
- } catch (err) {
- // execSync throws on non-zero exit; return stdout if any
- return err.stdout || err.message || '';
- }
-}
-
-function safeParse(out) {
- try { return JSON.parse(String(out).trim()); } catch { return null; }
-}
-
-/**
- * Return { pid, port, token } for the running live server, starting one if needed.
- */
-function ensureServerRunning() {
- // Try to reuse an existing server
- try {
- const existing = readLiveServerInfo(process.cwd())?.info;
- if (existing && existing.pid) {
- try {
- process.kill(existing.pid, 0); // throws if dead
- return existing;
- } catch { /* stale PID file — the server script will clean it up */ }
- }
- } catch { /* no PID file */ }
-
- // Start a new server
- const out = runScript('live-server.mjs', ['--background']);
- return safeParse(out);
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live.mjs') || _running?.endsWith('live.mjs/')) {
- liveCli();
-}
@@ -1,141 +0,0 @@
-/**
- * Shared context loader for every impeccable command that needs to know
- * "who is this for" and "what does this look like".
- *
- * Input: project root (process.cwd()).
- *
- * Output (JSON to stdout):
- * {
- * hasProduct: boolean, // PRODUCT.md found (or auto-migrated)
- * product: string | null, // PRODUCT.md contents
- * productPath: string | null, // relative path
- * hasDesign: boolean, // DESIGN.md found
- * design: string | null, // DESIGN.md contents
- * designPath: string | null,
- * migrated: boolean, // true if we auto-renamed .impeccable.md -> PRODUCT.md
- * contextDir: string, // absolute path of the directory the files were found in
- * }
- *
- * Filename matching is case-insensitive for PRODUCT.md and DESIGN.md. The
- * Google DESIGN.md convention is uppercase at repo root; Kiro-style and
- * lowercase variants are also matched so users don't get punished for case.
- *
- * Lookup directory resolution (first match wins):
- * 1. process.env.IMPECCABLE_CONTEXT_DIR (absolute or relative to cwd)
- * 2. cwd, if PRODUCT.md / DESIGN.md / .impeccable.md is there (back-compat)
- * 3. Auto-fallback subdirectories of cwd: .agents/context/, then docs/
- * 4. cwd as a default "no context found" location
- *
- * Legacy `.impeccable.md` -> PRODUCT.md migration only fires at cwd root;
- * fallback directories are read-only as far as auto-rename is concerned.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
-const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
-const LEGACY_NAMES = ['.impeccable.md'];
-const FALLBACK_DIRS = ['.agents/context', 'docs'];
-
-/**
- * Resolve the directory that holds PRODUCT.md / DESIGN.md for
- * this project. Exported so other scripts (e.g. live-server.mjs) can read the
- * design files from the same location the loader uses.
- */
-export function resolveContextDir(cwd = process.cwd()) {
- // 1. Explicit override
- const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
- if (envDir && envDir.trim()) {
- const trimmed = envDir.trim();
- return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- }
-
- // 2. cwd wins if any canonical or legacy file is there. We check legacy too
- // so the auto-migration path in loadContext stays predictable.
- if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES, ...LEGACY_NAMES])) {
- return cwd;
- }
-
- // 3. Auto-fallback subdirs. Match if PRODUCT.md or DESIGN.md is present;
- // legacy `.impeccable.md` does not pull the lookup into a fallback dir.
- for (const rel of FALLBACK_DIRS) {
- const candidate = path.resolve(cwd, rel);
- if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
- return candidate;
- }
- }
-
- // 4. Nothing found — keep the historical "default to cwd" behaviour so the
- // caller's `hasProduct === false` branch still fires the same way.
- return cwd;
-}
-
-export function loadContext(cwd = process.cwd()) {
- let migrated = false;
- const contextDir = resolveContextDir(cwd);
-
- // 1. Look for PRODUCT.md (case-insensitive) in the resolved dir
- let productPath = firstExisting(contextDir, PRODUCT_NAMES);
-
- // 2. Legacy: if no PRODUCT.md but .impeccable.md exists at cwd root, rename
- // it in place. We only migrate at the root — fallback dirs are read-only
- // so we don't surprise users by mutating files under docs/ or .agents/.
- if (!productPath && contextDir === cwd) {
- const legacyPath = firstExisting(cwd, LEGACY_NAMES);
- if (legacyPath) {
- const newPath = path.join(cwd, 'PRODUCT.md');
- try {
- fs.renameSync(legacyPath, newPath);
- productPath = newPath;
- migrated = true;
- } catch {
- // Rename failed (permissions, etc.) — fall back to reading legacy in place
- productPath = legacyPath;
- }
- }
- }
-
- // 3. DESIGN.md (case-insensitive)
- const designPath = firstExisting(contextDir, DESIGN_NAMES);
-
- const product = productPath ? safeRead(productPath) : null;
- const design = designPath ? safeRead(designPath) : null;
-
- return {
- hasProduct: !!product,
- product,
- productPath: productPath ? path.relative(cwd, productPath) : null,
- hasDesign: !!design,
- design,
- designPath: designPath ? path.relative(cwd, designPath) : null,
- migrated,
- contextDir,
- };
-}
-
-function firstExisting(dir, names) {
- for (const name of names) {
- const abs = path.join(dir, name);
- if (fs.existsSync(abs)) return abs;
- }
- return null;
-}
-
-function safeRead(p) {
- try { return fs.readFileSync(p, 'utf-8'); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// CLI mode — print the context as JSON
-// ---------------------------------------------------------------------------
-
-function cli() {
- const result = loadContext(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('load-context.mjs') || _running?.endsWith('load-context.mjs/')) {
- cli();
-}
@@ -1,14 +0,0 @@
@@ -1,214 +0,0 @@
-#!/usr/bin/env node
-/**
- * Pin/unpin sub-commands as standalone skill shortcuts.
- *
- * Usage:
- * node <scripts_path>/pin.mjs pin <command>
- * node <scripts_path>/pin.mjs unpin <command>
- *
- * `pin audit` creates a lightweight /audit skill that redirects to /impeccable audit.
- * `unpin audit` removes that shortcut.
- *
- * The script discovers harness directories (.claude/skills, .cursor/skills, etc.)
- * in the project root and creates/removes the pin in all of them.
- */
-
-import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
-import { join, resolve, dirname } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-// All known harness directories
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Valid sub-command names
-const VALID_COMMANDS = [
- 'craft', 'teach', 'extract', 'document', 'shape',
- 'critique', 'audit',
- 'polish', 'bolder', 'quieter', 'distill', 'harden', 'onboard', 'live',
- 'animate', 'colorize', 'typeset', 'layout', 'delight', 'overdrive',
- 'clarify', 'adapt', 'optimize',
-];
-
-// Marker to identify pinned skills (so unpin doesn't delete user skills)
-const PIN_MARKER = '<!-- impeccable-pinned-skill -->';
-
-/**
- * Walk up from startDir to find a project root.
- */
-function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- while (dir !== '/') {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Find harness skill directories that have an impeccable skill installed.
- */
-function findHarnessDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const skillsDir = join(projectRoot, harness, 'skills');
- // Only pin in harness dirs that already have impeccable installed
- const impeccableDir = join(skillsDir, 'impeccable');
- if (existsSync(impeccableDir) || existsSync(join(skillsDir, 'i-impeccable'))) {
- dirs.push(skillsDir);
- }
- }
- return dirs;
-}
-
-/**
- * Load command metadata (descriptions for pinned skills).
- */
-function loadCommandMetadata() {
- const metadataPath = join(__dirname, 'command-metadata.json');
- if (existsSync(metadataPath)) {
- return JSON.parse(readFileSync(metadataPath, 'utf-8'));
- }
- return {};
-}
-
-/**
- * Generate a pinned skill's SKILL.md content.
- */
-function generatePinnedSkill(command, metadata) {
- const desc = metadata[command]?.description || `Shortcut for /impeccable ${command}.`;
- const hint = metadata[command]?.argumentHint || '[target]';
-
- return `---
-name: ${command}
-description: "${desc}"
-argument-hint: "${hint}"
-user-invocable: true
----
-
-${PIN_MARKER}
-
-This is a pinned shortcut for \`{{command_prefix}}impeccable ${command}\`.
-
-Invoke {{command_prefix}}impeccable ${command}, passing along any arguments provided here, and follow its instructions.
-`;
-}
-
-/**
- * Pin a command: create shortcut skill in all harness dirs.
- */
-function pin(command, projectRoot) {
- const metadata = loadCommandMetadata();
- const harnessDirs = findHarnessDirs(projectRoot);
-
- if (harnessDirs.length === 0) {
- console.log('No harness directories with impeccable installed found.');
- return false;
- }
-
- const content = generatePinnedSkill(command, metadata);
- let created = 0;
-
- for (const skillsDir of harnessDirs) {
- // Check if skill already exists (and isn't a pin)
- const skillDir = join(skillsDir, command);
- if (existsSync(skillDir)) {
- const existingMd = join(skillDir, 'SKILL.md');
- if (existsSync(existingMd)) {
- const existing = readFileSync(existingMd, 'utf-8');
- if (!existing.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (non-pinned skill already exists)`);
- continue;
- }
- }
- }
-
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(join(skillDir, 'SKILL.md'), content, 'utf-8');
- console.log(` + ${skillDir}`);
- created++;
- }
-
- if (created > 0) {
- console.log(`\nPinned '${command}' as a standalone shortcut in ${created} location(s).`);
- console.log(`You can now use /${command} directly.`);
- }
-
- return created > 0;
-}
-
-/**
- * Unpin a command: remove shortcut skill from all harness dirs.
- */
-function unpin(command, projectRoot) {
- const harnessDirs = findHarnessDirs(projectRoot);
- let removed = 0;
-
- for (const skillsDir of harnessDirs) {
- const skillDir = join(skillsDir, command);
- if (!existsSync(skillDir)) continue;
-
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) continue;
-
- // Safety: only remove if it's a pinned skill
- const content = readFileSync(skillMd, 'utf-8');
- if (!content.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (not a pinned skill)`);
- continue;
- }
-
- rmSync(skillDir, { recursive: true, force: true });
- console.log(` - ${skillDir}`);
- removed++;
- }
-
- if (removed > 0) {
- console.log(`\nUnpinned '${command}' from ${removed} location(s).`);
- console.log(`Use /impeccable ${command} to access it.`);
- } else {
- console.log(`No pinned '${command}' shortcut found.`);
- }
-
- return removed > 0;
-}
-
-// --- CLI ---
-const [,, action, command] = process.argv;
-
-if (!action || !command) {
- console.log('Usage: node pin.mjs <pin|unpin> <command>');
- console.log(`\nAvailable commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-if (action !== 'pin' && action !== 'unpin') {
- console.error(`Unknown action: ${action}. Use 'pin' or 'unpin'.`);
- process.exit(1);
-}
-
-if (!VALID_COMMANDS.includes(command)) {
- console.error(`Unknown command: ${command}`);
- console.error(`Available commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-const root = findProjectRoot();
-
-if (action === 'pin') {
- pin(command, root);
-} else {
- unpin(command, root);
-}
@@ -1,92 +0,0 @@
-name = "impeccable_asset_producer"
-description = "Produces clean reusable raster assets from approved Impeccable mock references without redesigning the direction."
-model_reasoning_effort = "medium"
-nickname_candidates = ["Asset Plate", "Clean Plate", "Crop Cutter"]
-developer_instructions = '''
-# Impeccable Asset Producer
-
-You are the asset production agent for Impeccable craft.
-
-Your job is production cleanup, not new art direction. Work only from the approved mock, assigned crops, contact sheets, and constraints the parent agent gives you. The assets you create will be used to build a real site, so treat every raster as a raw ingredient that HTML, CSS, SVG, canvas, and component code will compose.
-
-## Core Rule
-
-Do not redesign. Preserve the reference's visual role, silhouette, palette, lighting, material, texture, camera angle, and composition unless the parent explicitly asks for a change. Preserve perspective only when it belongs to the object or scene itself; if CSS should create the card transform, shadow, rounded clipping, border, or layout, remove that presentation chrome from the raster.
-
-## Input Contract
-
-Expect:
-
-- Approved mock path or screenshot reference.
-- Crop paths or a contact sheet with crop ids.
-- Output directory.
-- Required dimensions, format, transparency needs, and avoid list.
-- Notes on what should remain semantic HTML/CSS/SVG instead of raster.
-
-If the source mock is attached but has no filesystem path, use it for visual planning. Ask for a path only before cropping or writing assets.
-
-Use defaults unless contradicted:
-
-- `.webp` for opaque photos, backgrounds, and textures.
-- `.png` for transparent cutouts, seals, tickets, and illustrations.
-- Target production size or at least 2x display size when dimensions are known. Do not use small full-page mock crop size as the default shipping size.
-- Remove UI text, navigation, buttons, labels, and body copy by default.
-- Keep physical marks only when the parent says they are part of the asset.
-- Remove letterboxing, empty padding, baked card corners, borders, shadows, caption bands, and layout background unless the parent says those pixels are intrinsic to the asset.
-- Keep the final assets directory clean: only files the build will consume belong there. Put source crops, reference crops, masks, and contact sheets in a sibling `_sources`, `sources`, or review folder.
-
-Ask blockers once, globally. Missing source path/crops or output directory blocks production. Exact dimensions, compression targets, retina variants, and format preferences do not block; choose defaults and report them.
-
-## Workflow
-
-1. Inventory the full approved mock or every assigned crop.
-2. Put each visual role in exactly one bucket:
- - `produce`: needs generation, image editing, cleanup, cutout work, or a clean plate before it can ship.
- - `direct`: can ship as a crop, format conversion, compression pass, or sourced replacement with no generative cleanup.
- - `semantic`: build in HTML/CSS/SVG/canvas, no raster output.
-3. Treat full-page mock crops as references, not production-resolution source assets. Put a role in `direct` only when the provided source is already a clean, sufficiently large source asset with no semantic text or presentation chrome.
-4. Give the parent an execution order for the `produce` bucket.
-5. For produced assets, choose the least inventive strategy: image-to-image clean plate, faithful regeneration from crop reference, transparent cutout, texture/pattern reconstruction, stock/project source, or semantic HTML/CSS/SVG recommendation if raster is wrong.
-6. Treat every crop as binding reference. In Codex, use the imagegen skill and built-in `image_gen` path by default when generation or editing is needed.
-7. Remove baked-in UI text, navigation, buttons, body copy, and mock chrome unless the text is part of the asset.
-8. Think through the final DOM/CSS representation before generating. If CSS will own radius, clipping, shadows, borders, perspective, responsive cropping, captions, or card frames, do not bake those into the bitmap.
-9. Save outputs non-destructively in the requested project directory.
-10. Compare each output against its source crop. If a review/QA tool is available, run it before the final manifest, then retry each major/fatal finding once before finalizing.
-
-Use `direct` only for provided source assets that can already ship after crop tightening, conversion, compression, or naming. Do not ship a small crop from the full-page mock as `direct` just because it looks close.
-
-Use `texture/pattern extraction` only when the source region is already clean enough to sample as texture. If UI, cards, labels, headings, body copy, or footer chrome must be removed to make a reusable texture or background, classify it as crop-derived cleanup or clean-plate work.
-
-Use `semantic` for dashboards, charts, controls, screenshots of whole UI sections, data widgets, card chrome, app frames, icon toolbars, logos, wordmarks, and anything the final implementation can render crisply in HTML/CSS/SVG/canvas. Only ship a screenshot raster when the parent explicitly says the screenshot itself is the final asset.
-
-Semantic does not mean ignored. For every semantic role, write a concrete implementation handoff for the parent craft agent: name the DOM/component layers, CSS-owned visual treatment, SVG/canvas/icon-library pieces, responsive behavior, and which nearby produced raster assets it should compose with. For logos and icons, prefer inline SVG/vector or icon-library implementation unless the parent provides a production logo raster.
-
-For transparency, prefer true alpha output when the tool supports it. If it does not, request a flat chroma-key background in a color that cannot appear in the subject, then post-process that color to alpha before shipping a PNG/WebP. Do not ship the keyed background as the final asset.
-
-## Prompt Pattern
-
-Use this shape for image-to-image work:
-
-```text
-Use the provided crop as the approved visual reference.
-Recreate the same asset as a clean reusable production image at the target component aspect ratio and at least 2x display resolution.
-Preserve silhouette, object/scene perspective, camera angle, palette, lighting, material, texture, and visual role.
-Remove baked-in UI copy, navigation, buttons, labels, body text, watermarks, and mock chrome unless explicitly part of the asset.
-Remove letterboxing, padding, card borders, rounded clipping, CSS shadows, perspective transforms, caption bands, and layout backgrounds that the implementation should create in code.
-Do not add new objects. Do not change the concept. Do not redesign the composition.
-```
-
-For transparent cutouts, use the imagegen skill's built-in-first chroma-key workflow unless the parent explicitly authorizes a true native transparency fallback.
-
-## Output Contract
-
-Return a complete manifest, grouped by `produce`, `direct`, and `semantic`. For each asset include: `id`, `source_crop`, `output_path` when applicable, `strategy`, `prompt_used` when applicable, `dimensions`, `format`, `transparency`, `deviations`, and `qa_status`.
-
-For each semantic row include `id`, `implementation`, `notes`, and `qa_status`. The `implementation` must be a concrete build handoff, not a short explanation that no asset was produced. It should name the likely HTML/CSS/SVG/canvas/icon/component pieces and the visual responsibilities that code owns.
-
-`qa_status` must be `accepted`, `needs_parent_review`, or `blocked`. Use `accepted` only after visual comparison passes. Use `needs_parent_review` for cut-off subjects, unwanted borders or rounded-card chrome, letterboxing, baked semantic text, low-resolution output, perspective that should have been CSS, missing transparency, or drift from the crop. Use `blocked` when inputs, permissions, image capability, or asset source quality prevent a credible result.
-
-End with `execution_order`, `blockers`, and `assumptions` sections. Keep blockers global and minimal. Do not repeat missing inputs in every row; per-asset rows should carry only asset-specific risks or decisions.
-
-Do not modify implementation code. Do not edit the approved mock. Do not produce final page copy. The parent craft agent owns implementation and final mock fidelity.
-'''
@@ -1,165 +0,0 @@
----
-name: impeccable
-description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
-version: 3.1.1
-license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
----
-
-Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
-
-## Setup
-
-Before any design work or file edits:
-
-1. Load context (PRODUCT.md / DESIGN.md) via the loader script.
-2. Identify the register and load the matching register reference (brand.md or product.md).
-3. **If the user invoked a sub-command (e.g. `craft`, `shape`, `audit`), load its reference file too.** This is non-negotiable: `craft` without `craft.md` loaded means you'll skip the shape-and-confirm step the user expects.
-
-Skipping these produces generic output that ignores the project.
-
-### 1. Context gathering
-
-Two files, case-insensitive. The loader looks at the project root by default and falls back to `.agents/context/` and `docs/` if the root is clean. Override with `IMPECCABLE_CONTEXT_DIR=path/to/dir` (absolute or relative to cwd).
-
-- **PRODUCT.md**: required. Users, brand, tone, anti-references, strategic principles.
-- **DESIGN.md**: optional, strongly recommended. Colors, typography, elevation, components.
-
-Load both in one call:
-
-```bash
-node .cursor/skills/impeccable/scripts/load-context.mjs
-```
-
-Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`. The output's `contextDir` field tells you where the files were resolved from.
-
-If the output is already in this session's conversation history, don't re-run. Exceptions requiring a fresh load: you just ran `/impeccable teach` or `/impeccable document` (they rewrite the files), or the user manually edited one.
-
-`/impeccable live` already warms context via `live.mjs`. If you've run `live.mjs`, don't also run `load-context.mjs` this session.
-
-If PRODUCT.md is missing, empty, or placeholder (`[TODO]` markers, <200 chars): run `/impeccable teach`, then resume the user's original task with the fresh context. If the original task was `/impeccable craft`, resume into `/impeccable shape` before any implementation work.
-
-If DESIGN.md is missing: nudge once per session (*"Run `/impeccable document` for more on-brand output"*), then proceed.
-
-### 2. Register
-
-Every design task is **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboard, tool: design SERVES the product).
-
-Identify before designing. Priority: (1) cue in the task itself ("landing page" vs "dashboard"); (2) the surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. First match wins.
-
-If PRODUCT.md lacks the `register` field (legacy), infer it once from its "Users" and "Product Purpose" sections, then cache the inferred value for the session. Suggest the user run `/impeccable teach` to add the field explicitly.
-
-Load the matching reference: [reference/brand.md](reference/brand.md) or [reference/product.md](reference/product.md). The shared design laws below apply to both.
-
-## Shared design laws
-
-Apply to every design, both registers. Match implementation complexity to the aesthetic vision: maximalism needs elaborate code, minimalism needs precision. Interpret creatively. Vary across projects; never converge on the same choices. the model is capable of extraordinary work. Don't hold back.
-
-### Color
-
-- Use OKLCH. Reduce chroma as lightness approaches 0 or 100; high chroma at extremes looks garish.
-- Never use `#000` or `#fff`. Tint every neutral toward the brand hue (chroma 0.005–0.01 is enough).
-- Pick a **color strategy** before picking colors. Four steps on the commitment axis:
- - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism.
- - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages.
- - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz.
- - **Drenched**: the surface IS the color. Brand heroes, campaign pages.
-- The "one accent ≤10%" rule is Restrained only. Committed / Full palette / Drenched exceed it on purpose. Don't collapse every design to Restrained by reflex.
-
-### Theme
-
-Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe."
-
-Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does.
-
-"Observability dashboard" does not force an answer. "SRE glancing at incident severity on a 27-inch monitor at 2am in a dim room" does. Run the sentence, not the category.
-
-### Typography
-
-- Cap body line length at 65–75ch.
-- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales.
-
-### Layout
-
-- Vary spacing for rhythm. Same padding everywhere is monotony.
-- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
-- Don't wrap everything in a container. Most things don't need one.
-
-### Motion
-
-- Don't animate CSS layout properties.
-- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
-
-### Absolute bans
-
-Match-and-refuse. If you're about to write any of these, rewrite the element with different structure.
-
-- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing.
-- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size.
-- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing.
-- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché.
-- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly.
-- **Modal as first thought.** Modals are usually laziness. Exhaust inline / progressive alternatives first.
-
-### Copy
-
-- Every word earns its place. No restated headings, no intros that repeat the title.
-- **No em dashes.** Use commas, colons, semicolons, periods, or parentheses. Also not `--`.
-
-### The AI slop test
-
-If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference.
-
-**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses.
-
-- **First-order:** if someone could guess the theme + palette from the category alone ("observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black"), it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
-- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families.
-
-## Commands
-
-| Command | Category | Description | Reference |
-|---|---|---|---|
-| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) |
-| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) |
-| `teach` | Build | Set up PRODUCT.md and DESIGN.md context | [reference/teach.md](reference/teach.md) |
-| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) |
-| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) |
-| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) |
-| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) |
-| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) |
-| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) |
-| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) |
-| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) |
-| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) |
-| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) |
-| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) |
-| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) |
-| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) |
-| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) |
-| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) |
-| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) |
-| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) |
-| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) |
-| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
-| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
-
-### Routing rules
-
-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
-3. **First word doesn't match**: general design invocation. Apply the setup steps, shared design laws, and the loaded register reference, using the full argument as context.
-
-Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `/impeccable`.
-
-If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `teach` as a blocker, finish teach, refresh context, then resume the original command and target.
-
-## Pin / Unpin
-
-**Pin** creates a standalone shortcut so `/<command>` invokes `/impeccable <command>` directly. **Unpin** removes it. The script writes to every harness directory present in the project.
-
-```bash
-node .cursor/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
-```
-
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
@@ -1,190 +0,0 @@
-> **Additional context needed**: target platforms/devices and usage contexts.
-
-Adapt an existing design to a different context: another screen size, device, platform, or use case. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context.
-
-
----
-
-## Assess Adaptation Challenge
-
-Understand what needs adaptation and why:
-
-1. **Identify the source context**:
- - What was it designed for originally? (Desktop web? Mobile app?)
- - What assumptions were made? (Large screen? Mouse input? Fast connection?)
- - What works well in current context?
-
-2. **Understand target context**:
- - **Device**: Mobile, tablet, desktop, TV, watch, print?
- - **Input method**: Touch, mouse, keyboard, voice, gamepad?
- - **Screen constraints**: Size, resolution, orientation?
- - **Connection**: Fast wifi, slow 3G, offline?
- - **Usage context**: On-the-go vs desk, quick glance vs focused reading?
- - **User expectations**: What do users expect on this platform?
-
-3. **Identify adaptation challenges**:
- - What won't fit? (Content, navigation, features)
- - What won't work? (Hover states on touch, tiny touch targets)
- - What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop)
-
-**CRITICAL**: Adaptation is rethinking the experience for the new context, not scaling pixels.
-
-## Plan Adaptation Strategy
-
-Create context-appropriate strategy:
-
-### Mobile Adaptation (Desktop → Mobile)
-
-**Layout Strategy**:
-- Single column instead of multi-column
-- Vertical stacking instead of side-by-side
-- Full-width components instead of fixed widths
-- Bottom navigation instead of top/side navigation
-
-**Interaction Strategy**:
-- Touch targets 44x44px minimum (not hover-dependent)
-- Swipe gestures where appropriate (lists, carousels)
-- Bottom sheets instead of dropdowns
-- Thumbs-first design (controls within thumb reach)
-- Larger tap areas with more spacing
-
-**Content Strategy**:
-- Progressive disclosure (don't show everything at once)
-- Prioritize primary content (secondary content in tabs/accordions)
-- Shorter text (more concise)
-- Larger text (16px minimum)
-
-**Navigation Strategy**:
-- Hamburger menu or bottom navigation
-- Reduce navigation complexity
-- Sticky headers for context
-- Back button in navigation flow
-
-### Tablet Adaptation (Hybrid Approach)
-
-**Layout Strategy**:
-- Two-column layouts (not single or three-column)
-- Side panels for secondary content
-- Master-detail views (list + detail)
-- Adaptive based on orientation (portrait vs landscape)
-
-**Interaction Strategy**:
-- Support both touch and pointer
-- Touch targets 44x44px but allow denser layouts than phone
-- Side navigation drawers
-- Multi-column forms where appropriate
-
-### Desktop Adaptation (Mobile → Desktop)
-
-**Layout Strategy**:
-- Multi-column layouts (use horizontal space)
-- Side navigation always visible
-- Multiple information panels simultaneously
-- Fixed widths with max-width constraints (don't stretch to 4K)
-
-**Interaction Strategy**:
-- Hover states for additional information
-- Keyboard shortcuts
-- Right-click context menus
-- Drag and drop where helpful
-- Multi-select with Shift/Cmd
-
-**Content Strategy**:
-- Show more information upfront (less progressive disclosure)
-- Data tables with many columns
-- Richer visualizations
-- More detailed descriptions
-
-### Print Adaptation (Screen → Print)
-
-**Layout Strategy**:
-- Page breaks at logical points
-- Remove navigation, footer, interactive elements
-- Black and white (or limited color)
-- Proper margins for binding
-
-**Content Strategy**:
-- Expand shortened content (show full URLs, hidden sections)
-- Add page numbers, headers, footers
-- Include metadata (print date, page title)
-- Convert charts to print-friendly versions
-
-### Email Adaptation (Web → Email)
-
-**Layout Strategy**:
-- Narrow width (600px max)
-- Single column only
-- Inline CSS (no external stylesheets)
-- Table-based layouts (for email client compatibility)
-
-**Interaction Strategy**:
-- Large, obvious CTAs (buttons not text links)
-- No hover states (not reliable)
-- Deep links to web app for complex interactions
-
-## Implement Adaptations
-
-Apply changes systematically:
-
-### Responsive Breakpoints
-
-Choose appropriate breakpoints:
-- Mobile: 320px-767px
-- Tablet: 768px-1023px
-- Desktop: 1024px+
-- Or content-driven breakpoints (where design breaks)
-
-### Layout Adaptation Techniques
-
-- **CSS Grid/Flexbox**: Reflow layouts automatically
-- **Container Queries**: Adapt based on container, not viewport
-- **`clamp()`**: Fluid sizing between min and max
-- **Media queries**: Different styles for different contexts
-- **Display properties**: Show/hide elements per context
-
-### Touch Adaptation
-
-- Increase touch target sizes (44x44px minimum)
-- Add more spacing between interactive elements
-- Remove hover-dependent interactions
-- Add touch feedback (ripples, highlights)
-- Consider thumb zones (easier to reach bottom than top)
-
-### Content Adaptation
-
-- Use `display: none` sparingly (still downloads)
-- Progressive enhancement (core content first, enhancements on larger screens)
-- Lazy loading for off-screen content
-- Responsive images (`srcset`, `picture` element)
-
-### Navigation Adaptation
-
-- Transform complex nav to hamburger/drawer on mobile
-- Bottom nav bar for mobile apps
-- Persistent side navigation on desktop
-- Breadcrumbs on smaller screens for context
-
-**IMPORTANT**: Test on real devices. Device emulation in DevTools is helpful but not perfect.
-
-**NEVER**:
-- Hide core functionality on mobile (if it matters, make it work)
-- Assume desktop = powerful device (consider accessibility, older machines)
-- Use different information architecture across contexts (confusing)
-- Break user expectations for platform (mobile users expect mobile patterns)
-- Forget landscape orientation on mobile/tablet
-- Use generic breakpoints blindly (use content-driven breakpoints)
-- Ignore touch on desktop (many desktop devices have touch)
-
-## Verify Adaptations
-
-Test thoroughly across contexts:
-
-- **Real devices**: Test on actual phones, tablets, desktops
-- **Different orientations**: Portrait and landscape
-- **Different browsers**: Safari, Chrome, Firefox, Edge
-- **Different OS**: iOS, Android, Windows, macOS
-- **Different input methods**: Touch, mouse, keyboard
-- **Edge cases**: Very small screens (320px), very large screens (4K)
-- **Slow connections**: Test on throttled network
-
-When the adaptation feels native to each context, hand off to `/impeccable polish` for the final pass.
@@ -1,175 +0,0 @@
-> **Additional context needed**: performance constraints.
-
-Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it.
-
----
-
-## Register
-
-Brand: orchestrated page-load sequences, staggered reveals, scroll-driven animation. Motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions.
-
-Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it.
-
----
-
-## Assess Animation Opportunities
-
-Analyze where motion would improve the experience:
-
-1. **Identify static areas**:
- - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.)
- - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes)
- - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious
- - **Lack of delight**: Functional but joyless interactions
- - **Missed guidance**: Opportunities to direct attention or explain behavior
-
-2. **Understand the context**:
- - What's the personality? (Playful vs serious, energetic vs calm)
- - What's the performance budget? (Mobile-first? Complex page?)
- - Who's the audience? (Motion-sensitive users? Power users who want speed?)
- - What matters most? (One hero animation vs many micro-interactions?)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them.
-
-## Plan Animation Strategy
-
-Create a purposeful animation plan:
-
-- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?)
-- **Feedback layer**: Which interactions need acknowledgment?
-- **Transition layer**: Which state changes need smoothing?
-- **Delight layer**: Where can we surprise and delight?
-
-**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments.
-
-## Implement Animations
-
-Add motion systematically across these categories:
-
-### Entrance Animations
-- **Page load choreography**: Stagger element reveals (100-150ms delays), fade + slide combinations
-- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects)
-- **Content reveals**: Scroll-triggered animations using intersection observer
-- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management
-
-### Micro-interactions
-- **Button feedback**:
- - Hover: Subtle scale (1.02-1.05), color shift, shadow increase
- - Click: Quick scale down then up (0.95 → 1), ripple effect
- - Loading: Spinner or pulse state
-- **Form interactions**:
- - Input focus: Border color transition, slight scale or glow
- - Validation: Shake on error, check mark on success, smooth color transitions
-- **Toggle switches**: Smooth slide + color transition (200-300ms)
-- **Checkboxes/radio**: Check mark animation, ripple effect
-- **Like/favorite**: Scale + rotation, particle effects, color transition
-
-### State Transitions
-- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms)
-- **Expand/collapse**: Height transition with overflow handling, icon rotation
-- **Loading states**: Skeleton screen fades, spinner animations, progress bars
-- **Success/error**: Color transitions, icon animations, gentle scale pulse
-- **Enable/disable**: Opacity transitions, cursor changes
-
-### Navigation & Flow
-- **Page transitions**: Crossfade between routes, shared element transitions
-- **Tab switching**: Slide indicator, content fade/slide
-- **Carousel/slider**: Smooth transforms, snap points, momentum
-- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators
-
-### Feedback & Guidance
-- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights
-- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning
-- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation
-- **Focus flow**: Highlight path through form or workflow
-
-### Delight Moments
-- **Empty states**: Subtle floating animations on illustrations
-- **Completed actions**: Confetti, check mark flourish, success celebrations
-- **Easter eggs**: Hidden interactions for discovery
-- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches
-
-## Technical Implementation
-
-Use appropriate techniques for each animation:
-
-### Timing & Easing
-
-**Durations by purpose:**
-- **100-150ms**: Instant feedback (button press, toggle)
-- **200-300ms**: State changes (hover, menu open)
-- **300-500ms**: Layout changes (accordion, modal)
-- **500-800ms**: Entrance animations (page load)
-
-**Easing curves (use these, not CSS defaults):**
-```css
-/* Recommended: natural deceleration */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */
-
-/* AVOID: feel dated and tacky */
-/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */
-/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */
-```
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-### CSS Animations
-```css
-/* Prefer for simple, declarative animations */
-- transitions for state changes
-- @keyframes for complex sequences
-- transform and opacity for reliable movement
-- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth
-```
-
-### JavaScript Animation
-```javascript
-/* Use for complex, interactive animations */
-- Web Animations API for programmatic control
-- Framer Motion for React
-- GSAP for complex sequences
-```
-
-### Performance
-- **Motion materials**: Use transform/opacity for reliable movement, but use blur, filters, masks, shadows, and color shifts when they materially improve the effect
-- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- **will-change**: Add sparingly for known expensive animations
-- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate
-- **Monitor FPS**: Ensure 60fps on target devices
-
-### Accessibility
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**NEVER**:
-- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself
-- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work
-- Use durations over 500ms for feedback (it feels laggy)
-- Animate without purpose (every animation needs a reason)
-- Ignore `prefers-reduced-motion` (this is an accessibility violation)
-- Animate everything (animation fatigue makes interfaces feel exhausting)
-- Block interaction during animations unless intentional
-
-## Verify Quality
-
-Test animations thoroughly:
-
-- **Smooth at 60fps**: No jank on target devices
-- **Feels natural**: Easing curves feel organic, not robotic
-- **Appropriate timing**: Not too fast (jarring) or too slow (laggy)
-- **Reduced motion works**: Animations disabled or simplified appropriately
-- **Doesn't block**: Users can interact during/after animations
-- **Adds value**: Makes interface clearer or more delightful
-
-When the motion clarifies state instead of decorating it, hand off to `/impeccable polish` for the final pass.
@@ -1,133 +0,0 @@
-Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues; document them for other commands to address.
-
-This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation.
-
-## Diagnostic Scan
-
-Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below.
-
-### 1. Accessibility (A11y)
-
-**Check for**:
-- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA)
-- **Missing ARIA**: Interactive elements without proper roles, labels, or states
-- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps
-- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons
-- **Alt text**: Missing or poor image descriptions
-- **Form issues**: Inputs without labels, poor error messaging, missing required indicators
-
-**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA)
-
-### 2. Performance
-
-**Check for**:
-- **Layout thrashing**: Reading/writing layout properties in loops
-- **Expensive animations**: Casual layout-property animation, unbounded blur/filter/shadow effects, or effects that visibly drop frames
-- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change
-- **Bundle size**: Unnecessary imports, unused dependencies
-- **Render performance**: Unnecessary re-renders, missing memoization
-
-**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized)
-
-### 3. Theming
-
-**Check for**:
-- **Hard-coded colors**: Colors not using design tokens
-- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme
-- **Inconsistent tokens**: Using wrong tokens, mixing token types
-- **Theme switching issues**: Values that don't update on theme change
-
-**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly)
-
-### 4. Responsive Design
-
-**Check for**:
-- **Fixed widths**: Hard-coded widths that break on mobile
-- **Touch targets**: Interactive elements < 44x44px
-- **Horizontal scroll**: Content overflow on narrow viewports
-- **Text scaling**: Layouts that break when text size increases
-- **Missing breakpoints**: No mobile/tablet variants
-
-**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets)
-
-### 5. Anti-Patterns (CRITICAL)
-
-Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy).
-
-**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design)
-
-## Generate Report
-
-### Audit Health Score
-
-| # | Dimension | Score | Key Finding |
-|---|-----------|-------|-------------|
-| 1 | Accessibility | ? | [most critical a11y issue or "--"] |
-| 2 | Performance | ? | |
-| 3 | Responsive Design | ? | |
-| 4 | Theming | ? | |
-| 5 | Anti-Patterns | ? | |
-| **Total** | | **??/20** | **[Rating band]** |
-
-**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues)
-
-### Anti-Patterns Verdict
-**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest.
-
-### Executive Summary
-- Audit Health Score: **??/20** ([rating band])
-- Total issues found (count by severity: P0/P1/P2/P3)
-- Top 3-5 critical issues
-- Recommended next steps
-
-### Detailed Findings by Severity
-
-Tag every issue with **P0-P3 severity**:
-- **P0 Blocking**: Prevents task completion. Fix immediately
-- **P1 Major**: Significant difficulty or WCAG AA violation. Fix before release
-- **P2 Minor**: Annoyance, workaround exists. Fix in next pass
-- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits
-
-For each issue, document:
-- **[P?] Issue name**
-- **Location**: Component, file, line
-- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern
-- **Impact**: How it affects users
-- **WCAG/Standard**: Which standard it violates (if applicable)
-- **Recommendation**: How to fix it
-- **Suggested command**: Which command to use (prefer: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-### Patterns & Systemic Issues
-
-Identify recurring problems that indicate systemic gaps rather than one-off mistakes:
-- "Hard-coded colors appear in 15+ components, should use design tokens"
-- "Touch targets consistently too small (<44px) throughout mobile experience"
-
-### Positive Findings
-
-Note what's working well: good practices to maintain and replicate.
-
-## Recommended Actions
-
-List recommended commands in priority order (P0 first, then P1, then P2):
-
-1. **[P?] `/command-name`**: Brief description (specific context from audit findings)
-2. **[P?] `/command-name`**: Brief description (specific context)
-
-**Rules**: Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset. Map findings to the most appropriate command. End with `/impeccable polish` as the final step if any fixes were recommended.
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable audit` after fixes to see your score improve.
-
-**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters.
-
-**NEVER**:
-- Report issues without explaining impact (why does this matter?)
-- Provide generic recommendations (be specific and actionable)
-- Skip positive findings (celebrate what works)
-- Forget to prioritize (everything can't be P0)
-- Report false positives without verification
-
@@ -1,113 +0,0 @@
-When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact and personality through stronger hierarchy, committed scale, and decisive type.
-
----
-
-## Register
-
-Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
-
-Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too safe or boring:
-
-1. **Identify weakness sources**:
- - **Generic choices**: System fonts, basic colors, standard layouts
- - **Timid scale**: Everything is medium-sized with no drama
- - **Low contrast**: Everything has similar visual weight
- - **Static**: No motion, no energy, no life
- - **Predictable**: Standard patterns with no surprises
- - **Flat hierarchy**: Nothing stands out or commands attention
-
-2. **Understand the context**:
- - What's the brand personality? (How far can we push?)
- - What's the purpose? (Marketing can be bolder than financial dashboards)
- - Who's the audience? (What will resonate?)
- - What are the constraints? (Brand guidelines, accessibility, performance)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
-
-**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
-
-## Plan Amplification
-
-Create a strategy to increase impact while maintaining coherence:
-
-- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
-- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
-- **Risk budget**: How experimental can we be? Push boundaries within constraints.
-- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
-
-**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration.
-
-## Amplify the Design
-
-Systematically increase impact across these dimensions:
-
-### Typography Amplification
-- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and [typography.md](typography.md) for inspiration)
-- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
-- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
-- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
-
-### Color Intensification
-- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
-- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop
-- **Dominant color strategy**: Let one bold color own 60% of the design
-- **Sharp accents**: High-contrast accent colors that pop
-- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
-- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
-
-### Spatial Drama
-- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
-- **Break the grid**: Let hero elements escape containers and cross boundaries
-- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
-- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
-- **Overlap**: Layer elements intentionally for depth
-
-### Visual Effects
-- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
-- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
-- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop)
-- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
-- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
-
-### Motion & Animation
-- **Entrance choreography**: Staggered, dramatic page load animations with 50-100ms delays
-- **Scroll effects**: Parallax, reveal animations, scroll-triggered sequences
-- **Micro-interactions**: Satisfying hover effects, click feedback, state changes
-- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect)
-
-### Composition Boldness
-- **Hero moments**: Create clear focal points with dramatic treatment
-- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
-- **Full-bleed elements**: Use full viewport width/height for impact
-- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
-
-**NEVER**:
-- Add effects randomly without purpose (chaos ≠ bold)
-- Sacrifice readability for aesthetics (body text must be readable)
-- Make everything bold (then nothing is bold; you need contrast)
-- Ignore accessibility (bold design must still meet WCAG standards)
-- Overwhelm with motion (animation fatigue is real)
-- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
-
-## Verify Quality
-
-Ensure amplification maintains usability and coherence:
-
-- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over.
-- **Still functional**: Can users accomplish tasks without distraction?
-- **Coherent**: Does everything feel intentional and unified?
-- **Memorable**: Will users remember this experience?
-- **Performant**: Do all these effects run smoothly?
-- **Accessible**: Does it still meet accessibility standards?
-
-**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects."
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,118 +0,0 @@
-# Brand register
-
-When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made.
-
-The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look.
-
-## The brand slop test
-
-If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?"
-
-Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home.
-
-**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register.
-
-Then the inverse test: in one sentence, describe what you're about to build the way a competitor would describe theirs. If that sentence fits the modal landing page in the category, restart.
-
-## Typography
-
-### Font selection procedure
-
-Every project. Never skip.
-
-1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words.
-2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture.
-3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy."
-4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over.
-
-### Reflex-reject list
-
-Training-data defaults. Ban list. Look further:
-
-Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif
-
-### Reflex-reject aesthetic lanes
-
-Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further.
-
-- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery.
-
-(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.)
-
-The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md).
-
-### Pairing and voice
-
-Distinctive + refined is the goal. The specific shape depends on the brand:
-
-- **Editorial / long-form / luxury**: display serif + sans body (a magazine shape).
-- **Tech / dev tools / fintech**: one committed sans, usually; custom-tight tracking, strong weight contrast inside a single family.
-- **Consumer / food / travel**: warmer pairings, often a humanist sans plus a script or display serif.
-- **Creative studios / agencies**: rule-breaking welcome. Mono-only, or display-only, or custom-drawn type as voice.
-
-Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair.
-
-Vary across projects. If the last brief was a serif-display landing page, this one isn't.
-
-### Scale
-
-Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted.
-
-Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room.
-
-## Color
-
-Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register.
-
-- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige.
-- Palette IS voice. A calm brand and a restless brand should not share palette mechanics.
-- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit.
-- Don't converge across projects. If the last brand surface was restrained-on-cream, this one is not.
-- When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette.
-
-## Layout
-
-- Asymmetric compositions are one option. Break the grid intentionally for emphasis.
-- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings.
-- Alternative: a strict, visible grid as the voice (brutalist / Swiss / tech-spec aesthetics). Either asymmetric or rigorously-gridded can be "designed"; the failure mode is splitting the difference into a generic centered stack.
-- Don't default to centering everything. Left-aligned with asymmetric layouts feels more designed; a strict grid reads as confident structure. A centered-stack hero with icon-title-subtitle cards reads as template.
-- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness.
-
-## Imagery
-
-Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo.
-
-**When the brief implies imagery (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product), you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy.
-
-- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `<div>` placeholders.
-- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel".
-- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one.
-- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish".
-
-"Imagery" here is broader than stock photography: product screenshots, custom data visualizations, generated SVG, and canvas/WebGL scenes are all imagery. Text-only pages where typography alone carries the entire visual weight are the failure mode.
-
-## Motion
-
-- One well-orchestrated page-load with staggered reveals beats scattered micro-interactions, when the brand invites it. Tech-minimal brands often skip entrance motion entirely; the restraint is the voice.
-- For collapsing/expanding sections, transition `grid-template-rows` rather than `height`.
-
-## Brand bans (on top of the shared absolute bans)
-
-- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume.
-- Large rounded-corner icons above every heading. Screams template.
-- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.)
-- All-caps body copy. Reserve caps for short labels and headings.
-- Timid palettes and average layouts. Safe = invisible.
-- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs.
-- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic.
-- Repeated tiny uppercase tracked labels above every section heading. A single strong kicker can be voice; repeating it as section grammar is AI scaffolding unless it's a deliberate, named brand system.
-
-## Brand permissions
-
-Brand can afford things product can't. Take them.
-
-- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography.
-- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing.
-- Typographic risk. Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines, a single oversize word as a hero.
-- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics.
-- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment.
@@ -1,174 +0,0 @@
-> **Additional context needed**: audience technical level and users' mental state in context.
-
-Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task.
-
-
----
-
-## Assess Current Copy
-
-Identify what makes the text unclear or ineffective:
-
-1. **Find clarity problems**:
- - **Jargon**: Technical terms users won't understand
- - **Ambiguity**: Multiple interpretations possible
- - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file"
- - **Length**: Too wordy or too terse
- - **Assumptions**: Assuming user knowledge they don't have
- - **Missing context**: Users don't know what to do or why
- - **Tone mismatch**: Too formal, too casual, or inappropriate for situation
-
-2. **Understand the context**:
- - Who's the audience? (Technical? General? First-time users?)
- - What's the user's mental state? (Stressed during error? Confident during success?)
- - What's the action? (What do we want users to do?)
- - What's the constraint? (Character limits? Space limitations?)
-
-**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets.
-
-## Plan Copy Improvements
-
-Create a strategy for clearer communication:
-
-- **Primary message**: What's the ONE thing users need to know?
-- **Action needed**: What should users do next (if anything)?
-- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?)
-- **Constraints**: Length limits, brand voice, localization considerations
-
-**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words.
-
-## Improve Copy Systematically
-
-Refine text across these common areas:
-
-### Error Messages
-**Bad**: "Error 403: Forbidden"
-**Good**: "You don't have permission to view this page. Contact your admin for access."
-
-**Bad**: "Invalid input"
-**Good**: "Email addresses need an @ symbol. Try: name@example.com"
-
-**Principles**:
-- Explain what went wrong in plain language
-- Suggest how to fix it
-- Don't blame the user
-- Include examples when helpful
-- Link to help/support if applicable
-
-### Form Labels & Instructions
-**Bad**: "DOB (MM/DD/YYYY)"
-**Good**: "Date of birth" (with placeholder showing format)
-
-**Bad**: "Enter value here"
-**Good**: "Your email address" or "Company name"
-
-**Principles**:
-- Use clear, specific labels (not generic placeholders)
-- Show format expectations with examples
-- Explain why you're asking (when not obvious)
-- Put instructions before the field, not after
-- Keep required field indicators clear
-
-### Button & CTA Text
-**Bad**: "Click here" | "Submit" | "OK"
-**Good**: "Create account" | "Save changes" | "Got it, thanks"
-
-**Principles**:
-- Describe the action specifically
-- Use active voice (verb + noun)
-- Match user's mental model
-- Be specific ("Save" is better than "OK")
-
-### Help Text & Tooltips
-**Bad**: "This is the username field"
-**Good**: "Choose a username. You can change this later in Settings."
-
-**Principles**:
-- Add value (don't just repeat the label)
-- Answer the implicit question ("What is this?" or "Why do you need this?")
-- Keep it brief but complete
-- Link to detailed docs if needed
-
-### Empty States
-**Bad**: "No items"
-**Good**: "No projects yet. Create your first project to get started."
-
-**Principles**:
-- Explain why it's empty (if not obvious)
-- Show next action clearly
-- Make it welcoming, not dead-end
-
-### Success Messages
-**Bad**: "Success"
-**Good**: "Settings saved! Your changes will take effect immediately."
-
-**Principles**:
-- Confirm what happened
-- Explain what happens next (if relevant)
-- Be brief but complete
-- Match the user's emotional moment (celebrate big wins)
-
-### Loading States
-**Bad**: "Loading..." (for 30+ seconds)
-**Good**: "Analyzing your data... this usually takes 30-60 seconds"
-
-**Principles**:
-- Set expectations (how long?)
-- Explain what's happening (when it's not obvious)
-- Show progress when possible
-- Offer escape hatch if appropriate ("Cancel")
-
-### Confirmation Dialogs
-**Bad**: "Are you sure?"
-**Good**: "Delete 'Project Alpha'? This can't be undone."
-
-**Principles**:
-- State the specific action
-- Explain consequences (especially for destructive actions)
-- Use clear button labels ("Delete project" not "Yes")
-- Don't overuse confirmations (only for risky actions)
-
-### Navigation & Wayfinding
-**Bad**: Generic labels like "Items" | "Things" | "Stuff"
-**Good**: Specific labels like "Your projects" | "Team members" | "Settings"
-
-**Principles**:
-- Be specific and descriptive
-- Use language users understand (not internal jargon)
-- Make hierarchy clear
-- Consider information scent (breadcrumbs, current location)
-
-## Apply Clarity Principles
-
-Every piece of copy should follow these rules:
-
-1. **Be specific**: "Enter email" not "Enter value"
-2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity)
-3. **Be active**: "Save changes" not "Changes will be saved"
-4. **Be human**: "Oops, something went wrong" not "System error encountered"
-5. **Tell users what to do**, not just what happened
-6. **Be consistent**: Use same terms throughout (don't vary for variety)
-
-**NEVER**:
-- Use jargon without explanation
-- Blame users ("You made an error" → "This field is required")
-- Be vague ("Something went wrong" without explanation)
-- Use passive voice unnecessarily
-- Write overly long explanations (be concise)
-- Use humor for errors (be empathetic instead)
-- Assume technical knowledge
-- Vary terminology (pick one term and stick with it)
-- Repeat information (headers restating intros, redundant explanations)
-- Use placeholders as the only labels (they disappear when users type)
-
-## Verify Improvements
-
-Test that copy improvements work:
-
-- **Comprehension**: Can users understand without context?
-- **Actionability**: Do users know what to do next?
-- **Brevity**: Is it as short as possible while remaining clear?
-- **Consistency**: Does it match terminology elsewhere?
-- **Tone**: Is it appropriate for the situation?
-
-When the copy reads cleanly, hand off to `/impeccable polish` for the final pass.
@@ -1,105 +0,0 @@
-# Codex: Visual Direction & Asset Production
-
-This file is loaded by `/impeccable craft` when the harness has native image generation (currently Codex via `image_gen`). Other harnesses skip it. It covers the two craft steps that depend on real image generation: landing the visual direction, and producing the raster assets the implementation will compose.
-
-Read this *before* generating any images. The order matters, and the per-step user pauses are what keep generated imagery from drifting away from the brief.
-
-### Four stop points before code
-
-Steps A through D each end with the user. Do not advance past any of them on your own read of the situation.
-
-1. **STOP after Step A questions.** Wait for answers.
-2. **STOP after Step B palette generation.** Wait for "confirm palette."
-3. **STOP after Step C mocks.** Wait for direction approval or delegation.
-4. **Only after Step D approves a direction** do you return to craft.md Step 4 and write code.
-
-Prior shape approval does **not** satisfy any of these. Shape's "confirm or override" advances you into Step A; it is not a substitute for it.
-
-## Step A: Explore Directions with the User
-
-Before generating anything, run a brief direction conversation grounded in the shape brief.
-
-**Step A is required even when shape just produced a confirmed brief.** The shape questions and Step A questions cover different ground: shape pins purpose, content, scope; Step A pins palette, atmosphere, and named visual references for the comps you're about to generate. The only time you can skip Step A is when the user has already answered these exact palette/atmosphere/reference questions in the same session.
-
-Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions:
-
-- "Brief says 'editorial restraint, Klim-adjacent.' Are we closer to a quiet specimen page or a magazine-spread feel with hero imagery?"
-- "Palette strategy from shape was 'Committed.' Want it warm-grounded (deep oxblood + cream) or cool-grounded (slate + paper white)?"
-
-**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded.
-
-## Step B: Generate the Brand Palette First
-
-Generate **one** palette artifact before any mocks. This is a small, focused image: typography pairing on the chosen background, primary + accent color swatches, one signature ornament or motif. Single image, single pass.
-
-Why palette first: mocks generated against a vague color sense produce noise that drowns out the structural decisions. A confirmed palette is the first concrete contract for everything downstream.
-
-Show the palette to the user. Ask one question: "This is the palette I'm locking in for the mocks. Confirm, or call out what to shift?"
-
-**STOP and wait for confirmation.** Do not generate mocks against an unconfirmed palette. "Probably good enough" is the wrong call here; the palette is the contract for everything downstream.
-
-## Step C: Generate 1-3 Visual Mocks Against the Palette
-
-Once the palette is confirmed, generate **1 to 3** high-fidelity north-star comps. Each mock must use the confirmed palette and typography. Mocks differ in *structural* direction (hierarchy, topology, density, composition), not in color or motif.
-
-- Brand work: push visual identity, composition, mood, and signature motifs.
-- Product work: push hierarchy, topology, density, tone, grounded in realistic product structure.
-- Landing pages and long-form brand surfaces: show enough of the second fold to establish the system beyond the hero.
-
-Use the `image_gen` tool directly (or via the imagegen skill when available). Don't ask the user to install anything.
-
-## Step D: Approval Loop
-
-Show the comps. Ask what carries forward. Iterate until **one direction is approved** or the user explicitly delegates.
-
-**STOP and wait for the approval or the delegation.** Do not begin Step E or return to craft.md Step 4 until a single direction is named. If the user delegates, pick the strongest direction and explain it from the brief, not personal taste.
-
-Before moving to assets, summarize what to carry into code and what *not* to literalize from the mock. This is the handoff between visual exploration and semantic implementation.
-
-## Step E: Mock Fidelity Inventory
-
-Inventory the approved mock's major visible ingredients. For each, decide implementation: semantic HTML/CSS/SVG, generated raster, sourced raster, icon library, canvas/WebGL, or accepted omission.
-
-Common ingredients to inventory:
-
-- Hero silhouette and dominant composition
-- Signature motifs (planets, devices, portraits, charts, route lines, insets, badges, etc.)
-- Nav and primary CTA treatment
-- Section sequence, especially the second fold
-- Image-native content the concept depends on
-- Typography, density, color/material treatment, motion cues
-
-Treat the mock as a north star, not a screenshot to trace. Don't rasterize core UI text. But if the live result lacks the mock's major ingredients, the implementation is wrong.
-
-If a photographic, architectural, product, or place-led mock becomes generic CSS scenery, decorative diagrams, bullets, or copy, stop and fix it. That's a broken implementation, not a harmless interpretation.
-
-Don't substitute a different hero composition or visual driver post-approval without user sign-off.
-
-## Step F: Asset Slicing via the Asset Producer
-
-Raster ingredients identified in Step E need clean production assets. Use the bundled `impeccable_asset_producer` subagent rather than producing inline.
-
-Spawn it as a scoped subagent. If you do not have explicit permission to use agents, stop and ask:
-
-```text
-Asset production will work better as a scoped subagent job. Should I spawn the Impeccable asset producer subagent for this step?
-```
-
-Pass to the agent:
-
-- Approved mock path or screenshot reference
-- Crop paths or a contact sheet with crop ids
-- Output directory
-- Required dimensions, format, transparency needs
-- Avoid list
-- Notes on what should remain semantic HTML/CSS/SVG instead of raster
-
-Attach image generation capability to the spawned agent when the harness supports it. Do **not** load image-generation reference material into the parent thread.
-
-Inline asset production is allowed only if the user declines subagents, the harness cannot spawn the authorized agent, or the user explicitly asks for single-thread mode.
-
-Prefer HTML/CSS/SVG/canvas when they can credibly reproduce an ingredient; reach for real, generated, or stock imagery when the mock or subject matter calls for actual visual content.
-
-## After This File
-
-Once Steps A through F are complete, return to `craft.md` Step 5 (Build to Production Quality). The implementation builds against the confirmed palette, approved mock, and the assets the producer wrote.
@@ -1,106 +0,0 @@
-# Cognitive Load Assessment
-
-Cognitive load is the total mental effort required to use an interface. Overloaded users make mistakes, get frustrated, and leave. This reference helps identify and fix cognitive overload.
-
----
-
-## Three Types of Cognitive Load
-
-### Intrinsic Load: The Task Itself
-Complexity inherent to what the user is trying to do. You can't eliminate this, but you can structure it.
-
-**Manage it by**:
-- Breaking complex tasks into discrete steps
-- Providing scaffolding (templates, defaults, examples)
-- Progressive disclosure: show what's needed now, hide the rest
-- Grouping related decisions together
-
-### Extraneous Load: Bad Design
-Mental effort caused by poor design choices. **Eliminate this ruthlessly.** It's pure waste.
-
-**Common sources**:
-- Confusing navigation that requires mental mapping
-- Unclear labels that force users to guess meaning
-- Visual clutter competing for attention
-- Inconsistent patterns that prevent learning
-- Unnecessary steps between user intent and result
-
-### Germane Load: Learning Effort
-Mental effort spent building understanding. This is *good* cognitive load; it leads to mastery.
-
-**Support it by**:
-- Progressive disclosure that reveals complexity gradually
-- Consistent patterns that reward learning
-- Feedback that confirms correct understanding
-- Onboarding that teaches through action, not walls of text
-
----
-
-## Cognitive Load Checklist
-
-Evaluate the interface against these 8 items:
-
-- [ ] **Single focus**: Can the user complete their primary task without distraction from competing elements?
-- [ ] **Chunking**: Is information presented in digestible groups (≤4 items per group)?
-- [ ] **Grouping**: Are related items visually grouped together (proximity, borders, shared background)?
-- [ ] **Visual hierarchy**: Is it immediately clear what's most important on the screen?
-- [ ] **One thing at a time**: Can the user focus on a single decision before moving to the next?
-- [ ] **Minimal choices**: Are decisions simplified (≤4 visible options at any decision point)?
-- [ ] **Working memory**: Does the user need to remember information from a previous screen to act on the current one?
-- [ ] **Progressive disclosure**: Is complexity revealed only when the user needs it?
-
-**Scoring**: Count the failed items. 0–1 failures = low cognitive load (good). 2–3 = moderate (address soon). 4+ = high cognitive load (critical fix needed).
-
----
-
-## The Working Memory Rule
-
-**Humans can hold ≤4 items in working memory at once** (Miller's Law revised by Cowan, 2001).
-
-At any decision point, count the number of distinct options, actions, or pieces of information a user must simultaneously consider:
-- **≤4 items**: Within working memory limits, manageable
-- **5–7 items**: Pushing the boundary; consider grouping or progressive disclosure
-- **8+ items**: Overloaded; users will skip, misclick, or abandon
-
-**Practical applications**:
-- Navigation menus: ≤5 top-level items (group the rest under clear categories)
-- Form sections: ≤4 fields visible per group before a visual break
-- Action buttons: 1 primary, 1–2 secondary, group the rest in a menu
-- Dashboard widgets: ≤4 key metrics visible without scrolling
-- Pricing tiers: ≤3 options (more causes analysis paralysis)
-
----
-
-## Common Cognitive Load Violations
-
-### 1. The Wall of Options
-**Problem**: Presenting 10+ choices at once with no hierarchy.
-**Fix**: Group into categories, highlight recommended, use progressive disclosure.
-
-### 2. The Memory Bridge
-**Problem**: User must remember info from step 1 to complete step 3.
-**Fix**: Keep relevant context visible, or repeat it where it's needed.
-
-### 3. The Hidden Navigation
-**Problem**: User must build a mental map of where things are.
-**Fix**: Always show current location (breadcrumbs, active states, progress indicators).
-
-### 4. The Jargon Barrier
-**Problem**: Technical or domain language forces translation effort.
-**Fix**: Use plain language. If domain terms are unavoidable, define them inline.
-
-### 5. The Visual Noise Floor
-**Problem**: Every element has the same visual weight; nothing stands out.
-**Fix**: Establish clear hierarchy: one primary element, 2–3 secondary, everything else muted.
-
-### 6. The Inconsistent Pattern
-**Problem**: Similar actions work differently in different places.
-**Fix**: Standardize interaction patterns. Same type of action = same type of UI.
-
-### 7. The Multi-Task Demand
-**Problem**: Interface requires processing multiple simultaneous inputs (reading + deciding + navigating).
-**Fix**: Sequence the steps. Let the user do one thing at a time.
-
-### 8. The Context Switch
-**Problem**: User must jump between screens/tabs/modals to gather info for a single decision.
-**Fix**: Co-locate the information needed for each decision. Reduce back-and-forth.
@@ -1,105 +0,0 @@
-# Color & Contrast
-
-## Color Spaces: Use OKLCH
-
-**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark.
-
-The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish.
-
-The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand.
-
-## Building Functional Palettes
-
-### Tinted Neutrals
-
-**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces.
-
-The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette.
-
-**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects.
-
-### Palette Structure
-
-A complete system needs:
-
-| Role | Purpose | Example |
-|------|---------|---------|
-| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades |
-| **Neutral** | Text, backgrounds, borders | 9-11 shade scale |
-| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each |
-| **Surface** | Cards, modals, overlays | 2-3 elevation levels |
-
-**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise.
-
-### The 60-30-10 Rule (Applied Correctly)
-
-This rule is about **visual weight**, not pixel count:
-
-- **60%**: Neutral backgrounds, white space, base surfaces
-- **30%**: Secondary colors: text, borders, inactive states
-- **10%**: Accent: CTAs, highlights, focus states
-
-The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power.
-
-## Contrast & Accessibility
-
-### WCAG Requirements
-
-| Content Type | AA Minimum | AAA Target |
-|--------------|------------|------------|
-| Body text | 4.5:1 | 7:1 |
-| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 |
-| UI components, icons | 3:1 | 4.5:1 |
-| Non-essential decorations | None | None |
-
-**The gotcha**: Placeholder text still needs 4.5:1. That light gray placeholder you see everywhere? Usually fails WCAG.
-
-### Dangerous Color Combinations
-
-These commonly fail contrast or cause readability issues:
-
-- Light gray text on white (the #1 accessibility fail)
-- **Gray text on any colored background**: gray looks washed out and dead on color. Use a darker shade of the background color, or transparency
-- Red text on green background (or vice versa): 8% of men can't distinguish these
-- Blue text on red background (vibrates visually)
-- Yellow text on white (almost always fails)
-- Thin light text on images (unpredictable contrast)
-
-### Never Use Pure Gray or Pure Black
-
-Pure gray (`oklch(50% 0 0)`) and pure black (`#000`) don't exist in nature; real shadows and surfaces always have a color cast. Even a chroma of 0.005-0.01 is enough to feel natural without being obviously tinted. (See tinted neutrals example above.)
-
-### Testing
-
-Don't trust your eyes. Use tools:
-
-- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/)
-- Browser DevTools → Rendering → Emulate vision deficiencies
-- [Polypane](https://polypane.app/) for real-time testing
-
-## Theming: Light & Dark Mode
-
-### Dark Mode Is Not Inverted Light Mode
-
-You can't just swap colors. Dark mode requires different design decisions:
-
-| Light Mode | Dark Mode |
-|------------|-----------|
-| Shadows for depth | Lighter surfaces for depth (no shadows) |
-| Dark text on light | Light text on dark (reduce font weight) |
-| Vibrant accents | Desaturate accents slightly |
-| White backgrounds | Never pure black; use dark gray (oklch 12-18%) |
-
-In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light.
-
-### Token Hierarchy
-
-Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same.
-
-## Alpha Is A Design Smell
-
-Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed.
-
----
-
-**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Using pure black (#000) for large areas. Skipping color blindness testing (8% of men affected).
@@ -1,154 +0,0 @@
-> **Additional context needed**: existing brand colors.
-
-Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit.
-
----
-
-## Register
-
-Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it.
-
-Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen.
-
----
-
-## Assess Color Opportunity
-
-Analyze the current state and identify opportunities:
-
-1. **Understand current state**:
- - **Color absence**: Pure grayscale? Limited neutrals? One timid accent?
- - **Missed opportunities**: Where could color add meaning, hierarchy, or delight?
- - **Context**: What's appropriate for this domain and audience?
- - **Brand**: Are there existing brand colors we should use?
-
-2. **Identify where color adds value**:
- - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue)
- - **Hierarchy**: Drawing attention to important elements
- - **Categorization**: Different sections, types, or states
- - **Emotional tone**: Warmth, energy, trust, creativity
- - **Wayfinding**: Helping users navigate and understand structure
- - **Delight**: Moments of visual interest and personality
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose.
-
-## Plan Color Strategy
-
-Create a purposeful color introduction plan:
-
-- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals)
-- **Dominant color**: Which color owns 60% of colored elements?
-- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%)
-- **Application strategy**: Where does each color appear and why?
-
-**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more.
-
-## Introduce Color Strategically
-
-Add color systematically across these dimensions:
-
-### Semantic Color
-- **State indicators**:
- - Success: Green tones (emerald, forest, mint)
- - Error: Red/pink tones (rose, crimson, coral)
- - Warning: Orange/amber tones
- - Info: Blue tones (sky, ocean, indigo)
- - Neutral: Gray/slate for inactive states
-
-- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.)
-- **Progress indicators**: Colored bars, rings, or charts showing completion or health
-
-### Accent Color Application
-- **Primary actions**: Color the most important buttons/CTAs
-- **Links**: Add color to clickable text (maintain accessibility)
-- **Icons**: Colorize key icons for recognition and personality
-- **Headers/titles**: Add color to section headers or key labels
-- **Hover states**: Introduce color on interaction
-
-### Background & Surfaces
-- **Tinted backgrounds**: Replace pure gray (`#f5f5f5`) with warm neutrals (`oklch(97% 0.01 60)`) or cool tints (`oklch(97% 0.01 250)`)
-- **Colored sections**: Use subtle background colors to separate areas
-- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue)
-- **Cards & surfaces**: Tint cards or surfaces slightly for warmth
-
-**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
-
-### Data Visualization
-- **Charts & graphs**: Use color to encode categories or values
-- **Heatmaps**: Color intensity shows density or importance
-- **Comparison**: Color coding for different datasets or timeframes
-
-### Borders & Accents
-- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`)
-- **Underlines**: Color underlines for emphasis or active states
-- **Dividers**: Subtle colored dividers instead of gray lines
-- **Focus rings**: Colored focus indicators matching brand
-- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe
-
-**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe.
-
-### Typography Color
-- **Colored headings**: Use brand colors for section headings (maintain contrast)
-- **Highlight text**: Color for emphasis or categories
-- **Labels & tags**: Small colored labels for metadata or categories
-
-### Decorative Elements
-- **Illustrations**: Add colored illustrations or icons
-- **Shapes**: Geometric shapes in brand colors as background elements
-- **Gradients**: Colorful gradient overlays or mesh backgrounds
-- **Blobs/organic shapes**: Soft colored shapes for visual interest
-
-## Balance & Refinement
-
-Ensure color addition improves rather than overwhelms:
-
-### Maintain Hierarchy
-- **Dominant color** (60%): Primary brand color or most used accent
-- **Secondary color** (30%): Supporting color for variety
-- **Accent color** (10%): High contrast for key moments
-- **Neutrals** (remaining): Gray/black/white for structure
-
-### Accessibility
-- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components)
-- **Don't rely on color alone**: Use icons, labels, or patterns alongside color
-- **Test for color blindness**: Verify red/green combinations work for all users
-
-### Cohesion
-- **Consistent palette**: Use colors from defined palette, not arbitrary choices
-- **Systematic application**: Same color meanings throughout (green always = success)
-- **Temperature consistency**: Warm palette stays warm, cool stays cool
-
-**NEVER**:
-- Use every color in the rainbow (choose 2-4 colors beyond neutrals)
-- Apply color randomly without semantic meaning
-- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead
-- Use pure gray for neutrals. Add subtle color tint (warm or cool) for depth
-- Use pure black (`#000`) or pure white (`#fff`) for large areas
-- Violate WCAG contrast requirements
-- Use color as the only indicator (accessibility issue)
-- Make everything colorful (defeats the purpose)
-- Default to purple-blue gradients (AI slop aesthetic)
-
-## Verify Color Addition
-
-Test that colorization improves the experience:
-
-- **Better hierarchy**: Does color guide attention appropriately?
-- **Clearer meaning**: Does color help users understand states/categories?
-- **More engaging**: Does the interface feel warmer and more inviting?
-- **Still accessible**: Do all color combinations meet WCAG standards?
-- **Not overwhelming**: Is color balanced and purposeful?
-
-When the palette earns its place, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage.
-
-```json
-{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"}
-```
-
-Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract.
@@ -1,123 +0,0 @@
-# Craft Flow
-
-Build a feature with impeccable UX and UI quality: shape the design, land the visual direction, build real production code, inspect and improve in-browser until it meets a high-end studio bar.
-
-Before writing code, you need: PRODUCT.md loaded, register identified and the matching reference loaded, and a confirmed design direction for this task (either from `shape` or supplied by the user). PRODUCT.md is project context, not a task-specific brief.
-
-Treat any approved visual direction (generated mock or stated reference) as a concrete contract for composition, hierarchy, density, atmosphere, signature motifs, and distinctive visual moves. Don't let mocks replace structure, copy, accessibility, or state design. But if the live result lacks the approved direction's major ingredients, the implementation is wrong.
-
-### Gates: do not compress
-
-Craft has **multiple user gates**, not one. When the harness has native image generation (Codex via `image_gen`), the gate sequence before code is:
-
-1. **Shape brief confirmed** (Step 1)
-2. **Direction questions answered** (codex.md Step A)
-3. **Palette confirmed** (codex.md Step B)
-4. **One mock direction approved or delegated** (codex.md Step D)
-
-You must stop at every gate. **Shape confirmation alone is NOT a green light to start coding.** It is the green light to begin codex.md Step A. Compressing gates 2 through 4 because the shape brief felt complete is the dominant failure mode of this flow.
-
-When the harness lacks native image generation, gates 2-4 collapse into the brief itself, and shape confirmation does advance straight to code.
-
-## Step 0: Project Foundation
-
-Before shape, before code: figure out what kind of project you're working in.
-
-Look at the working directory. Run `ls`. Check for:
-
-- An existing framework: `astro.config.mjs/ts`, `next.config.js/ts`, `nuxt.config.ts`, `svelte.config.js`, `vite.config.js/ts`, `package.json` with framework deps, `Cargo.toml` + Leptos/Yew, `Gemfile` + Rails. **If found, use it.** Do not start a parallel build, do not introduce a second framework, do not write to `dist/` or `build/` directly. Whatever pipeline the project has, respect it.
-- An existing component library or design system: `src/components/`, `app/components/`, a `tokens.css` / `theme.ts`, an `astro.config` `integrations`. Read what's there before adding to it.
-- An existing icon set: `lucide-react`, `@phosphor-icons/react`, `@iconify/*`, hand-rolled SVG sprites in `assets/icons/`. **Use what's already in the project**; don't introduce a second set.
-
-If the directory is empty (greenfield), don't pick a framework silently. Ask the user via the AskUserQuestion tool, with sensible defaults framed by the brief:
-
-```text
-What should this be built on?
- - Astro (default for content-led brand sites, landing pages, marketing surfaces)
- - SvelteKit / Next.js / Nuxt (when the brief implies an app surface or significant interactivity)
- - Single index.html (one-shot demo, prototype, or a deliberately framework-free experiment)
-```
-
-Default: Astro for brand briefs, the project's existing framework for product briefs. Ask once; don't re-ask mid-task.
-
-## Step 1: Shape the Design
-
-Run /impeccable shape, passing along whatever feature description the user provided. Shape is **required** for craft; it is what produces a confirmed direction.
-
-Present the shape output and stop. Wait for the user to confirm, override, or course-correct before writing code.
-
-If the user already supplied a confirmed brief or ran shape separately, use it and skip this step.
-
-When the original prompt + PRODUCT.md already answer scope, content, and visual direction with no real ambiguity, the shape output can be **compact** (3-5 bullets stating what you're building and the visual lane, ending with one or two specific questions or "confirm or override"). The full 10-section structured brief is reserved for genuinely ambiguous, multi-screen, or stakeholder-heavy tasks. Don't pad a clear brief into a long one to look thorough; equally, don't skip the pause to look efficient.
-
-If the harness has native image generation (Codex), a compact shape's "confirm or override" advances to **Step 3 and the codex.md flow**, not to Step 4. Phrase the closing line accordingly: "Confirm or override; once we lock direction, I'll run a couple of palette and reference questions before generating any mocks." This stops the model from reading shape confirmation as code-green.
-
-## Step 2: Load References
-
-Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult:
-
-- [spatial-design.md](spatial-design.md) for layout and spacing
-- [typography.md](typography.md) for type hierarchy
-
-Then add references based on the brief's needs:
-- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md)
-- Animation or transitions? Consult [motion-design.md](motion-design.md)
-- Color-heavy or themed? Consult [color-and-contrast.md](color-and-contrast.md)
-- Responsive requirements? Consult [responsive-design.md](responsive-design.md)
-- Heavy on copy, labels, or errors? Consult [ux-writing.md](ux-writing.md)
-
-## Step 3: Visual Direction & Assets (Harness-Gated)
-
-If the harness has **native image generation** (currently Codex via `image_gen`), this step is mandatory. **Stop and load [codex.md](codex.md)**. It covers palette generation, mock exploration, the approval loop, mock-fidelity inventory, and asset slicing via the `impeccable_asset_producer` subagent. Follow Steps A-F in that file, then return here for Step 4.
-
-If the harness lacks native image generation, **state in one line that the visual-direction-by-generation step is being skipped because the harness lacks native image generation, then proceed**. The one-line announcement is required; it forces a conscious decision instead of letting the step quietly evaporate. The brief is your only visual reference. Implement directly from it, treating any named anchor references and the brief's "Design Direction" as the contract.
-
-Whether you generated mocks or not: don't replace required imagery with generic cards, bullets, emoji, fake metrics, decorative CSS panels, or filler copy. Image-led briefs (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product) need real or sourced imagery in the build, not CSS scenery.
-
-## Step 4: Build to Production Quality
-
-**Precondition.** If Step 3 routed you to codex.md (native image generation available), Steps A through D in that file must be complete before any code: questions answered, palette confirmed, mocks generated, one direction approved or delegated. **Do not mention implementation, file paths, or patch plans until that's done.** A confirmed shape brief is not enough; the model that compressed those gates is the model that already failed this flow.
-
-Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration.
-
-### Production bar
-
-- **Real content.** No placeholder copy, placeholder images, dead links, fake controls, or unused scaffold at presentation time.
-- **Preserve the approved mock's major ingredients.** Missing hero objects, world/product imagery, section structure, CTA/nav treatment, or distinctive motifs are blocking defects unless the user accepted the change.
-- **Semantic first.** Real headings, landmarks, labels, form associations, button/link semantics, accessible names, state announcements where needed.
-- **Deliberate spacing and alignment.** No default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment.
-- **Intentional typography.** Chosen loading strategy, clear hierarchy, readable measure, stable line breaks, no overflow at any width.
-- **Realistic state coverage.** Default, hover, focus-visible, active, disabled, loading, error, success, empty, overflow, long/short text, first-run.
-- **Finished interaction quality.** Keyboard paths, touch targets, feedback timing, scroll behavior, state transitions, no hover-only functionality.
-- **Coherent icon set.** Use the project's established set; otherwise pick one library or use accessible text. Don't mix.
-- **Respect the build pipeline.** Edit source files and run the project's build (`npm run build` or equivalent). Don't write to `build/` / `dist/` / `.next/` with `cat`, heredoc, or Bash redirects; that skips asset hashing, image optimization, code splitting, and CSS extraction, and produces output the dev server won't serve.
-- **Verify image URLs before referencing them.** Use image-search MCP or web-fetch when available; guessed photo IDs ship as broken-image placeholders. Without verification, prefer fewer images you're confident about.
-- **Optimized imagery and media.** Correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset`/`picture` for raster, no project-referenced asset left outside the workspace.
-- **Premium motion.** Use atmospheric blur, filter, mask, shadow, reveal when they improve the experience. Avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion.
-- **Maintainable.** Reusable local patterns, clear component boundaries, project conventions. No rasterized UI text or one-off hacks when a local pattern exists.
-- **Technically clean.** Production build passes, no console errors, no avoidable layout shift, no needless dependencies, no broken asset paths.
-- **Ask when uncertain.** If a discovery materially changes the brief or approved direction, stop and ask. Don't guess.
-
-## Step 5: Iterate Visually
-
-Look at what you built like a designer would. Your eyes are whatever the harness gives you: a connected browser, a screenshotting tool, Playwright, or asking the user. Use them for responsive testing (mobile, tablet, desktop minimum) and general visual validation.
-
-If your tool returns a file path, read the PNG back into the conversation. A screenshot you didn't read doesn't count.
-
-For long-form brand surfaces, inspect major sections individually. Thumbnails hide spacing, clipping, and cascade defects.
-
-After the first pass, write an honest critique against the brief, the approved mock's major ingredients (hero silhouette, motifs, imagery, nav/CTA, density), and impeccable's DON'Ts. Patch material defects and re-inspect. **Don't invent defects to demonstrate iteration.** A confident "first pass clean, shipping" beats a fake fix.
-
-Actively check: responsive behavior (composes, not shrinks), every state (empty / error / loading / edge), craft details (spacing, alignment, hierarchy, contrast, motion timing, focus), performance basics. The exit bar: defensible in a high-end studio review.
-
-Detector or QA output is defect evidence only; never proof the work is finished.
-
-## Step 6: Present
-
-Present the result to the user:
-- Show the feature in its primary state
-- Summarize the browser/viewports checked and the most important fixes made after inspection
-- Walk through the key states (empty, error, responsive)
-- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients.
-- Note any remaining limitations or follow-up risks honestly
-- Ask: "What's working? What isn't?"
@@ -1,236 +0,0 @@
-### Purpose
-
-Resolve one stable target, run two independent assessments, synthesize a design critique, persist a snapshot, and ask the user what to improve next. The chat response is the primary deliverable; the snapshot is an archive/backlog for future commands.
-
-### Hard Invariants
-
-- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
-- Assessment A must finish before detector findings enter the parent synthesis context. Detector output is deterministic, but it still anchors judgment.
-- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize.
-- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
-- Viewable targets require browser inspection when available.
-- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
-- Do not claim a user-visible overlay exists unless script injection succeeded and the detector ran in the page.
-
-### Setup
-
-1. **Resolve the target** to a concrete file path or URL. Prefer a source path over a dev-server URL when both identify the same surface; ports drift, paths do not.
- - "the homepage" -> `site/pages/index.astro` or `index.html`
- - "the settings modal" -> the primary component file
- - "this page" -> the current URL or source file
-2. **Compute the slug**:
- ```bash
- node .cursor/skills/impeccable/scripts/critique-storage.mjs slug "<resolved-path-or-url>"
- ```
- Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique.
-3. **Read `.impeccable/critique/ignore.md`** if it exists. Drop matching findings silently; it is the only prior-run input critique consumes.
-
-### Assessment Orchestration
-
-Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis.
-
-If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
-
-### Assessment A: Design Review
-
-Read relevant source files and visually inspect the live page when browser automation is available. Think like a design director.
-
-Evaluate:
-- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill.
-- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases.
-- **Cognitive load**: consult [cognitive-load](cognitive-load.md); report checklist failures and decision points with >4 visible options.
-- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments.
-- **Nielsen heuristics**: consult [heuristics-scoring](heuristics-scoring.md); score all 10 heuristics 0-4.
-
-Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions.
-
-### Assessment B: Detector + Browser Evidence
-
-Run the bundled detector and browser visualization evidence. Assessment B is mandatory and must remain isolated from Assessment A until both are complete.
-
-CLI scan:
-```bash
-node .cursor/skills/impeccable/scripts/detect.mjs --json [--fast] [target]
-```
-
-- Pass markup files/directories as `[target]`; do not pass CSS-only files.
-- For URLs, skip CLI scan and use browser visualization.
-- For 200+ scannable files, use `--fast`; for 500+, narrow scope or ask.
-- Exit code 0 = clean; 2 = findings.
-- If the detector entrypoint is missing or fails to load, report deterministic scan unavailable and continue with browser/manual review.
-
-Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
-
-1. Create a fresh tab and navigate.
-2. Preflight mutable injection by setting `document.title` and appending a `<script>` tag. Read-only evaluate APIs do not count.
-3. If mutation is unavailable, skip live server, browser presentation, and injection; report fallback signal.
-4. If mutation is available, start `node .cursor/skills/impeccable/scripts/live-server.mjs --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then stop the live server.
-5. For multi-view targets, inject on 3-5 representative pages.
-
-Return: CLI findings JSON/counts, browser console findings if applicable, false positives, and skipped/failed browser steps with concrete reasons.
-
-After Assessment B returns usable CLI findings, reuse them. Do not rerun `detect.mjs` in the parent unless Assessment B failed, was truncated, or omitted count, rule names, or file locations.
-
-### Generate Combined Critique Report
-
-Synthesize both assessments into a single report. Do NOT simply concatenate. Weave the findings together, noting where the LLM review and detector agree, where the detector caught issues the LLM missed, and where detector findings are false positives.
-
-The chat response is the primary user-facing deliverable. Present the full structured critique below in chat; do not replace it with a summary and a link. The persisted snapshot is only an archive/backlog for later commands.
-
-Structure your feedback as a design director would:
-
-#### Design Health Score
-> *Consult [heuristics-scoring](heuristics-scoring.md)*
-
-Present the Nielsen's 10 heuristics scores as a table:
-
-| # | Heuristic | Score | Key Issue |
-|---|-----------|-------|-----------|
-| 1 | Visibility of System Status | ? | [specific finding or "n/a" if solid] |
-| 2 | Match System / Real World | ? | |
-| 3 | User Control and Freedom | ? | |
-| 4 | Consistency and Standards | ? | |
-| 5 | Error Prevention | ? | |
-| 6 | Recognition Rather Than Recall | ? | |
-| 7 | Flexibility and Efficiency | ? | |
-| 8 | Aesthetic and Minimalist Design | ? | |
-| 9 | Error Recovery | ? | |
-| 10 | Help and Documentation | ? | |
-| **Total** | | **??/40** | **[Rating band]** |
-
-Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32.
-
-#### Anti-Patterns Verdict
-
-**Start here.** Does this look AI-generated?
-
-**LLM assessment**: Your own evaluation of AI slop tells. Cover overall aesthetic feel, layout sameness, generic composition, missed opportunities for personality.
-
-**Deterministic scan**: Summarize what the automated detector found, with counts and file locations. Note any additional issues the detector caught that you missed, and flag any false positives.
-
-**Visual overlays** (if injection succeeded): Tell the user that overlays are now visible in the **[Human]** tab in their browser, highlighting the detected issues. Summarize what the console output reported. If browser visualization was attempted but injection failed, say that no reliable user-visible overlay is available and report the fallback signal instead.
-
-#### Overall Impression
-A brief gut reaction: what works, what doesn't, and the single biggest opportunity.
-
-#### What's Working
-Highlight 2-3 things done well. Be specific about why they work.
-
-#### Priority Issues
-The 3-5 most impactful design problems, ordered by importance.
-
-For each issue, tag with **P0-P3 severity** (consult [heuristics-scoring](heuristics-scoring.md) for severity definitions):
-- **[P?] What**: Name the problem clearly
-- **Why it matters**: How this hurts users or undermines goals
-- **Fix**: What to do about it (be concrete)
-- **Suggested command**: Which command could address this (from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-#### Persona Red Flags
-> *Consult [personas](personas.md)*
-
-Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `.cursorrules` contains a `## Design Context` section from `impeccable teach`, also generate 1-2 project-specific personas from the audience/brand info.
-
-For each selected persona, walk through the primary user action and list specific red flags found:
-
-**Alex (Power User)**: No keyboard shortcuts detected. Form requires 8 clicks for primary action. Forced modal onboarding. High abandonment risk.
-
-**Jordan (First-Timer)**: Icon-only nav in sidebar. Technical jargon in error messages ("404 Not Found"). No visible help. Will abandon at step 2.
-
-Be specific. Name the exact elements and interactions that fail each persona. Don't write generic persona descriptions; write what broke for them.
-
-#### Minor Observations
-Quick notes on smaller issues worth addressing.
-
-#### Questions to Consider
-Provocative questions that might unlock better solutions:
-- "What if the primary action were more prominent?"
-- "Does this need to feel this complex?"
-- "What would a confident version of this look like?"
-
-**Remember**:
-- Be direct. Vague feedback wastes everyone's time.
-- Be specific. "The submit button," not "some elements."
-- Say what's wrong AND why it matters to users.
-- Give concrete suggestions. Cut "consider exploring..." entirely.
-- Prioritize ruthlessly. If everything is important, nothing is.
-- Don't soften criticism. Developers need honest feedback to ship great design.
-
-### Persist the Snapshot
-
-Once the report above is finalized, write it to `.impeccable/critique/` so the user can refer back, and so `/impeccable polish` can pick up the priority issues without a copy-paste.
-
-Skip this step if the Setup slug was null (vague or root-level target).
-
-1. **Write the body to a temp file** so you can pipe it to the helper. Use the full critique report (heuristic table, anti-patterns verdict, priority issues, persona red flags, minor observations, and questions), but stop before the "Ask the User" / "Recommended Actions" sections that come later.
-
-2. **Pass the structured metadata** through `IMPECCABLE_CRITIQUE_META` (JSON), then run the write command:
- ```bash
- IMPECCABLE_CRITIQUE_META='{"target":"<user phrasing>","total_score":<n>,"p0_count":<n>,"p1_count":<n>}' \
- node .cursor/skills/impeccable/scripts/critique-storage.mjs write <slug> <body-file>
- ```
- The helper prints the absolute path it wrote.
-
-3. **Delete the temp body file** after the write attempt completes, whether the write succeeded or failed. If deletion fails, mention `temp-file cleanup failed: <reason>` briefly in the final output, but do not block the critique.
-
-4. **Read the trend** for context:
- ```bash
- node .cursor/skills/impeccable/scripts/critique-storage.mjs trend <slug> 5
- ```
- This returns a JSON array of the last 5 frontmatter entries (including the one you just wrote).
-
-5. **Append a single line to the user-visible output**, after the report and before the questions:
-
- > **Trend for `<slug>` (last 5 runs): 24 → 28 → 32 → 29 → 32**
- > Wrote `.impeccable/critique/<filename>`.
-
- If this is the first run for the slug, the trend is just one score; say so: "First run for this target, no trend yet."
-
-This is fire-and-forget. Do not show the user the helper's JSON output; only the human-readable trend line and the written path. Failures here should not block the rest of the flow; print the error and move on.
-
-### Ask the User
-
-**After presenting findings**, use targeted questions based on what was actually found. ask the user directly to clarify what you cannot infer. These answers will shape the action plan.
-
-Ask questions along these lines (adapt to the specific findings; do NOT ask generic questions):
-
-1. **Priority direction**: Based on the issues found, ask which category matters most to the user right now. For example: "I found problems with visual hierarchy, color usage, and information overload. Which area should we tackle first?" Offer the top 2-3 issue categories as options.
-
-2. **Design intent**: If the critique found a tonal mismatch, ask whether it was intentional. For example: "The interface feels clinical and corporate. Is that the intended tone, or should it feel warmer/bolder/more playful?" Offer 2-3 tonal directions as options based on what would fix the issues found.
-
-3. **Scope**: Ask how much the user wants to take on. For example: "I found N issues. Want to address everything, or focus on the top 3?" Offer scope options like "Top 3 only", "All issues", "Critical issues only".
-
-4. **Constraints** (optional; only ask if relevant): If the findings touch many areas, ask if anything is off-limits. For example: "Should any sections stay as-is?" This prevents the plan from touching things the user considers done.
-
-**Rules for questions**:
-- Every question must reference specific findings from the report. Never ask generic "who is your audience?" questions.
-- Keep it to 2-4 questions maximum. Respect the user's time.
-- Offer concrete options, not open-ended prompts.
-- If findings are straightforward (e.g., only 1-2 clear issues), skip questions and go directly to Recommended Actions.
-
-### Recommended Actions
-
-**After receiving the user's answers**, present a prioritized action summary reflecting the user's priorities and scope from Ask the User.
-
-#### Action Summary
-
-List recommended commands in priority order, based on the user's answers:
-
-1. **`/command-name`**: Brief description of what to fix (specific context from critique findings)
-2. **`/command-name`**: Brief description (specific context)
-...
-
-**Rules for recommendations**:
-- Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset
-- Order by the user's stated priorities first, then by impact
-- Each item's description should carry enough context that the command knows what to focus on
-- Map each Priority Issue to the appropriate command
-- Skip commands that would address zero issues
-- If the user chose a limited scope, only include items within that scope
-- If the user marked areas as off-limits, exclude commands that would touch those areas
-- End with `/impeccable polish` as the final step if any fixes were recommended
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable critique` after fixes to see your score improve.
@@ -1,302 +0,0 @@
-> **Additional context needed**: what's appropriate for the domain (playful vs professional vs quirky vs elegant).
-
-Find the moments where personality and unexpected polish would turn a functional interface into one users remember and tell other people about. Add only where the moment earns it; delight everywhere reads as noise.
-
----
-
-## Register
-
-Brand: delight can be distributed across copy voice, section transitions, discovery rewards, seasonal touches, personality across the whole surface.
-
-Product: delight at specific moments, not pages. Completion, first-time actions, error recovery, milestone crossings. Reliability and consistency carry the rest of the experience; delight pushed everywhere reads as noise.
-
----
-
-## Assess Delight Opportunities
-
-Identify where delight would enhance (not distract from) the experience:
-
-1. **Find natural delight moments**:
- - **Success states**: Completed actions (save, send, publish)
- - **Empty states**: First-time experiences, onboarding
- - **Loading states**: Waiting periods that could be entertaining
- - **Achievements**: Milestones, streaks, completions
- - **Interactions**: Hover states, clicks, drags
- - **Errors**: Softening frustrating moments
- - **Easter eggs**: Hidden discoveries for curious users
-
-2. **Understand the context**:
- - What's the brand personality? (Playful? Professional? Quirky? Elegant?)
- - Who's the audience? (Tech-savvy? Creative? Corporate?)
- - What's the emotional context? (Accomplishment? Exploration? Frustration?)
- - What's appropriate? (Banking app ≠ gaming app)
-
-3. **Define delight strategy**:
- - **Subtle sophistication**: Refined micro-interactions (luxury brands)
- - **Playful personality**: Whimsical illustrations and copy (consumer apps)
- - **Helpful surprises**: Anticipating needs before users ask (productivity tools)
- - **Sensory richness**: Satisfying sounds, smooth animations (creative tools)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Delight should enhance usability, never obscure it. If users notice the delight more than accomplishing their goal, you've gone too far.
-
-## Delight Principles
-
-Follow these guidelines:
-
-### Delight Amplifies, Never Blocks
-- Delight moments should be quick (< 1 second)
-- Never delay core functionality for delight
-- Make delight skippable or subtle
-- Respect user's time and task focus
-
-### Surprise and Discovery
-- Hide delightful details for users to discover
-- Reward exploration and curiosity
-- Don't announce every delight moment
-- Let users share discoveries with others
-
-### Appropriate to Context
-- Match delight to emotional moment (celebrate success, empathize with errors)
-- Respect the user's state (don't be playful during critical errors)
-- Match brand personality and audience expectations
-- Cultural sensitivity (what's delightful varies by culture)
-
-### Compound Over Time
-- Delight should remain fresh with repeated use
-- Vary responses (not same animation every time)
-- Reveal deeper layers with continued use
-- Build anticipation through patterns
-
-## Delight Techniques
-
-Add personality and joy through these methods:
-
-### Micro-interactions & Animation
-
-**Button delight**:
-```css
-/* Satisfying button press */
-.button {
- transition: transform 0.1s, box-shadow 0.1s;
-}
-.button:active {
- transform: translateY(2px);
- box-shadow: 0 2px 4px rgba(0,0,0,0.2);
-}
-
-/* Ripple effect on click */
-/* Smooth lift on hover */
-.button:hover {
- transform: translateY(-2px);
- transition: transform 0.2s cubic-bezier(0.25, 1, 0.5, 1); /* ease-out-quart */
-}
-```
-
-**Loading delight**:
-- Playful loading animations (not just spinners)
-- Personality in loading messages (write product-specific ones, not generic AI filler)
-- Progress indication with encouraging messages
-- Skeleton screens with subtle animations
-
-**Success animations**:
-- Checkmark draw animation
-- Confetti burst for major achievements
-- Gentle scale + fade for confirmation
-- Satisfying sound effects (subtle)
-
-**Hover surprises**:
-- Icons that animate on hover
-- Color shifts or glow effects
-- Tooltip reveals with personality
-- Cursor changes (custom cursors for branded experiences)
-
-### Personality in Copy
-
-**Playful error messages**:
-```
-"Error 404"
-"This page is playing hide and seek. (And winning)"
-
-"Connection failed"
-"Looks like the internet took a coffee break. Want to retry?"
-```
-
-**Encouraging empty states**:
-```
-"No projects"
-"Your canvas awaits. Create something amazing."
-
-"No messages"
-"Inbox zero! You're crushing it today."
-```
-
-**Playful labels & tooltips**:
-```
-"Delete"
-"Send to void" (for playful brand)
-
-"Help"
-"Rescue me" (tooltip)
-```
-
-**IMPORTANT**: Match copy personality to brand. Banks shouldn't be wacky, but they can be warm.
-
-### Illustrations & Visual Personality
-
-**Custom illustrations**:
-- Empty state illustrations (not stock icons)
-- Error state illustrations (friendly monsters, quirky characters)
-- Loading state illustrations (animated characters)
-- Success state illustrations (celebrations)
-
-**Icon personality**:
-- Custom icon set matching brand personality
-- Animated icons (subtle motion on hover/click)
-- Illustrative icons (more detailed than generic)
-- Consistent style across all icons
-
-**Background effects**:
-- Subtle particle effects
-- Gradient mesh backgrounds
-- Geometric patterns
-- Parallax depth
-- Time-of-day themes (morning vs night)
-
-### Satisfying Interactions
-
-**Drag and drop delight**:
-- Lift effect on drag (shadow, scale)
-- Snap animation when dropped
-- Satisfying placement sound
-- Undo toast ("Dropped in wrong place? [Undo]")
-
-**Toggle switches**:
-- Smooth slide with spring physics
-- Color transition
-- Haptic feedback on mobile
-- Optional sound effect
-
-**Progress & achievements**:
-- Streak counters with celebratory milestones
-- Progress bars that "celebrate" at 100%
-- Badge unlocks with animation
-- Playful stats ("You're on fire! 5 days in a row")
-
-**Form interactions**:
-- Input fields that animate on focus
-- Checkboxes with a satisfying scale pulse when checked
-- Success state that celebrates valid input
-- Auto-grow textareas
-
-### Sound Design
-
-**Subtle audio cues** (when appropriate):
-- Notification sounds (distinctive but not annoying)
-- Success sounds (satisfying "ding")
-- Error sounds (empathetic, not harsh)
-- Typing sounds for chat/messaging
-- Ambient background audio (very subtle)
-
-**IMPORTANT**:
-- Respect system sound settings
-- Provide mute option
-- Keep volumes quiet (subtle cues, not alarms)
-- Don't play on every interaction (sound fatigue is real)
-
-### Easter Eggs & Hidden Delights
-
-**Discovery rewards**:
-- Konami code unlocks special theme
-- Hidden keyboard shortcuts (Cmd+K for special features)
-- Hover reveals on logos or illustrations
-- Alt text jokes on images (for screen reader users too!)
-- Console messages for developers ("Like what you see? We're hiring!")
-
-**Seasonal touches**:
-- Holiday themes (subtle, tasteful)
-- Seasonal color shifts
-- Weather-based variations
-- Time-based changes (dark at night, light during day)
-
-**Contextual personality**:
-- Different messages based on time of day
-- Responses to specific user actions
-- Randomized variations (not same every time)
-- Progressive reveals with continued use
-
-### Loading & Waiting States
-
-**Make waiting engaging**:
-- Interesting loading messages that rotate
-- Progress bars with personality
-- Mini-games during long loads
-- Fun facts or tips while waiting
-- Countdown with encouraging messages
-
-```
-Loading messages: write ones specific to your product, not generic AI filler:
-- "Crunching your latest numbers..."
-- "Syncing with your team's changes..."
-- "Preparing your dashboard..."
-- "Checking for updates since yesterday..."
-```
-
-**WARNING**: Avoid cliched loading messages like "Herding pixels", "Teaching robots to dance", "Consulting the magic 8-ball", "Counting backwards from infinity". These are AI-slop copy, instantly recognizable as machine-generated. Write messages that are specific to what your product actually does.
-
-### Celebration Moments
-
-**Success celebrations**:
-- Confetti for major milestones
-- Animated checkmarks for completions
-- Progress bar celebrations at 100%
-- "Achievement unlocked" style notifications
-- Personalized messages ("You published your 10th article!")
-
-**Milestone recognition**:
-- First-time actions get special treatment
-- Streak tracking and celebration
-- Progress toward goals
-- Anniversary celebrations
-
-## Implementation Patterns
-
-**Animation libraries**:
-- Framer Motion (React)
-- GSAP (universal)
-- Lottie (After Effects animations)
-- Canvas confetti (party effects)
-
-**Sound libraries**:
-- Howler.js (audio management)
-- Use-sound (React hook)
-
-**Physics libraries**:
-- React Spring (spring physics)
-- Popmotion (animation primitives)
-
-**IMPORTANT**: File size matters. Compress images, optimize animations, lazy load delight features.
-
-**NEVER**:
-- Delay core functionality for delight
-- Force users through delightful moments (make skippable)
-- Use delight to hide poor UX
-- Overdo it (less is more)
-- Ignore accessibility (animate responsibly, provide alternatives)
-- Make every interaction delightful (special moments should be special)
-- Sacrifice performance for delight
-- Be inappropriate for context (read the room)
-
-## Verify Delight Quality
-
-Test that delight actually delights:
-
-- **User reactions**: Do users smile? Share screenshots?
-- **Doesn't annoy**: Still pleasant after 100th time?
-- **Doesn't block**: Can users opt out or skip?
-- **Performant**: No jank, no slowdown
-- **Appropriate**: Matches brand and context
-- **Accessible**: Works with reduced motion, screen readers
-
-When the moments feel earned, hand off to `/impeccable polish` for the final pass.
@@ -1,111 +0,0 @@
-Strip a design to its essence. Remove anything that doesn't earn its place: redundant elements, repeated information, decorative noise, cosmetic complexity.
-
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel complex or cluttered:
-
-1. **Identify complexity sources**:
- - **Too many elements**: Competing buttons, redundant information, visual clutter
- - **Excessive variation**: Too many colors, fonts, sizes, styles without purpose
- - **Information overload**: Everything visible at once, no progressive disclosure
- - **Visual noise**: Unnecessary borders, shadows, backgrounds, decorations
- - **Confusing hierarchy**: Unclear what matters most
- - **Feature creep**: Too many options, actions, or paths forward
-
-2. **Find the essence**:
- - What's the primary user goal? (There should be ONE)
- - What's actually necessary vs nice-to-have?
- - What can be removed, hidden, or combined?
- - What's the 20% that delivers 80% of value?
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Simplicity is not about removing features. It's about removing obstacles between users and their goals. Every element should justify its existence.
-
-## Plan Simplification
-
-Create a ruthless editing strategy:
-
-- **Core purpose**: What's the ONE thing this should accomplish?
-- **Essential elements**: What's truly necessary to achieve that purpose?
-- **Progressive disclosure**: What can be hidden until needed?
-- **Consolidation opportunities**: What can be combined or integrated?
-
-**IMPORTANT**: Simplification is hard. It requires saying no to good ideas to make room for great execution. Be ruthless.
-
-## Simplify the Design
-
-Systematically remove complexity across these dimensions:
-
-### Information Architecture
-- **Reduce scope**: Remove secondary actions, optional features, redundant information
-- **Progressive disclosure**: Hide complexity behind clear entry points (accordions, modals, step-through flows)
-- **Combine related actions**: Merge similar buttons, consolidate forms, group related content
-- **Clear hierarchy**: ONE primary action, few secondary actions, everything else tertiary or hidden
-- **Remove redundancy**: If it's said elsewhere, don't repeat it here
-
-### Visual Simplification
-- **Reduce color palette**: Use 1-2 colors plus neutrals, not 5-7 colors
-- **Limit typography**: One font family, 3-4 sizes maximum, 2-3 weights
-- **Remove decorations**: Eliminate borders, shadows, backgrounds that don't serve hierarchy or function
-- **Flatten structure**: Reduce nesting, remove unnecessary containers; never nest cards inside cards
-- **Remove unnecessary cards**: Cards aren't needed for basic layout; use spacing and alignment instead
-- **Consistent spacing**: Use one spacing scale, remove arbitrary gaps
-
-### Layout Simplification
-- **Linear flow**: Replace complex grids with simple vertical flow where possible
-- **Remove sidebars**: Move secondary content inline or hide it
-- **Full-width**: Use available space generously instead of complex multi-column layouts
-- **Consistent alignment**: Pick left or center, stick with it
-- **Generous white space**: Let content breathe, don't pack everything tight
-
-### Interaction Simplification
-- **Reduce choices**: Fewer buttons, fewer options, clearer path forward (paradox of choice is real)
-- **Smart defaults**: Make common choices automatic, only ask when necessary
-- **Inline actions**: Replace modal flows with inline editing where possible
-- **Remove steps**: Can signup be one step instead of three? Can checkout be simplified?
-- **Clear CTAs**: ONE obvious next step, not five competing actions
-
-### Content Simplification
-- **Shorter copy**: Cut every sentence in half, then do it again
-- **Active voice**: "Save changes" not "Changes will be saved"
-- **Remove jargon**: Plain language always wins
-- **Scannable structure**: Short paragraphs, bullet points, clear headings
-- **Essential information only**: Remove marketing fluff, legalese, hedging
-- **Remove redundant copy**: No headers restating intros, no repeated explanations, say it once
-
-### Code Simplification
-- **Remove unused code**: Dead CSS, unused components, orphaned files
-- **Flatten component trees**: Reduce nesting depth
-- **Consolidate styles**: Merge similar styles, use utilities consistently
-- **Reduce variants**: Does that component need 12 variations, or can 3 cover 90% of cases?
-
-**NEVER**:
-- Remove necessary functionality (simplicity ≠ feature-less)
-- Sacrifice accessibility for simplicity (clear labels and ARIA still required)
-- Make things so simple they're unclear (mystery ≠ minimalism)
-- Remove information users need to make decisions
-- Eliminate hierarchy completely (some things should stand out)
-- Oversimplify complex domains (match complexity to actual task complexity)
-
-## Verify Simplification
-
-Ensure simplification improves usability:
-
-- **Faster task completion**: Can users accomplish goals more quickly?
-- **Reduced cognitive load**: Is it easier to understand what to do?
-- **Still complete**: Are all necessary features still accessible?
-- **Clearer hierarchy**: Is it obvious what matters most?
-- **Better performance**: Does simpler design load faster?
-
-## Document Removed Complexity
-
-If you removed features or options:
-- Document why they were removed
-- Consider if they need alternative access points
-- Note any user feedback to monitor
-
-When the cuts feel right, hand off to `/impeccable polish` for the final pass. As Antoine de Saint-Exupéry put it: "Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away."
@@ -1,427 +0,0 @@
-Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
-
-DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
-
-## The frontmatter: token schema
-
-The YAML frontmatter is the machine-readable layer. It's what Stitch's linter validates and what the live panel renders tiles from. Keep it tight; every entry should correspond to a token the project actually uses.
-
-```yaml
----
-name: <project title>
-description: <one-line tagline>
-colors:
- primary: "#b8422e"
- neutral-bg: "#faf7f2"
- # ...one entry per extracted color; key = descriptive slug
-typography:
- display:
- fontFamily: "Cormorant Garamond, Georgia, serif"
- fontSize: "clamp(2.5rem, 7vw, 4.5rem)"
- fontWeight: 300
- lineHeight: 1
- letterSpacing: "normal"
- body:
- # ...
-rounded:
- sm: "4px"
- md: "8px"
-spacing:
- sm: "8px"
- md: "16px"
-components:
- button-primary:
- backgroundColor: "{colors.primary}"
- textColor: "{colors.neutral-bg}"
- rounded: "{rounded.sm}"
- padding: "16px 48px"
- button-primary-hover:
- backgroundColor: "{colors.primary-deep}"
----
-```
-
-Rules that matter:
-
-- **Token refs** use `{path.to.token}` (e.g. `{colors.primary}`, `{rounded.md}`). Components may reference primitives; primitives may not reference each other.
-- **Stitch validates colors as hex sRGB only** (`#RGB` / `#RGBA` / `#RRGGBB` / `#RRGGBBAA`); OKLCH/HSL/P3 trigger a linter warning, not a hard error. YAML accepts the string either way and our own parser is format-agnostic. Choose based on project posture: (a) if the project has an "OKLCH-only" doctrine or uses Display-P3 values that don't round-trip through sRGB, put OKLCH directly in the frontmatter and accept the Stitch linter warning; (b) if the project wants strict Stitch compliance or plans to use their Tailwind/DTCG export pipeline, put hex in the frontmatter and keep OKLCH in prose as the canonical reference. Never split the source of truth without explicit reason.
-- **Component sub-tokens** are limited to 8 props: `backgroundColor`, `textColor`, `typography`, `rounded`, `padding`, `size`, `height`, `width`. Shadows, motion, focus rings, backdrop-filter: none of those fit. Carry them in the sidecar (Step 4b).
-- **Scale keys are open-ended.** Use whatever names the project already uses (`warm-ash-cream`, `surface-container-low`). Don't rename to Material defaults.
-- **Variants are naming convention, not schema.** `button-primary` / `button-primary-hover` / `button-primary-active` as sibling keys.
-
-## The markdown body: six sections (exact order)
-
-1. `## Overview`
-2. `## Colors`
-3. `## Typography`
-4. `## Elevation`
-5. `## Components`
-6. `## Do's and Don'ts`
-
-Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] Palette` (Stitch's own outputs do this), but the literal word in each header (Overview, Colors, Typography, Elevation, Components, Do's and Don'ts) must be present. Do NOT add extra top-level sections (Layout Principles, Responsive Behavior, Motion, Agent Prompt Guide). Fold that content into the six spec sections where it naturally belongs.
-
-## When to run
-
-- The user just ran `/impeccable teach` and needs the visual side documented.
-- The skill noticed no `DESIGN.md` exists and nudged the user to create one.
-- An existing `DESIGN.md` is stale (the design has drifted).
-- Before a large redesign, to capture the current state as a reference.
-
-If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user the existing file and ask the user directly to clarify what you cannot infer. whether to refresh, overwrite, or merge.
-
-## Two paths
-
-- **Scan mode** (default): the project has design tokens, components, or rendered output. Extract, then confirm descriptive language. Use when there's code to analyze.
-- **Seed mode**: the project is pre-implementation (fresh teach, nothing built yet). Interview for five high-level answers, write a minimal DESIGN.md marked `<!-- SEED -->`. Re-run in scan mode once there's code.
-
-Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode; don't silently switch. `/impeccable document --seed` forces seed mode regardless of code presence.
-
-## Scan mode (approach C: auto-extract, then confirm descriptive language)
-
-### Step 1: Find the design assets
-
-Search the codebase in priority order:
-
-1. **CSS custom properties**: grep for `--color-`, `--font-`, `--spacing-`, `--radius-`, `--shadow-`, `--ease-`, `--duration-` declarations in CSS files (usually `src/styles/`, `public/css/`, `app/globals.css`, etc.). Record name, value, and the file it's defined in.
-2. **Tailwind config**: if `tailwind.config.{js,ts,mjs}` exists, read the `theme.extend` block for colors, fontFamily, spacing, borderRadius, boxShadow.
-3. **CSS-in-JS theme files**: styled-components, emotion, vanilla-extract, stitches; look for `theme.ts`, `tokens.ts`, or equivalent.
-4. **Design token files**: `tokens.json`, `design-tokens.json`, Style Dictionary output, W3C token community group format.
-5. **Component library**: scan the main button, card, input, navigation, dialog components. Note their variant APIs and default styles.
-6. **Global stylesheet**: the root CSS file usually has the base typography and color assignments.
-7. **Visible rendered output**: if browser automation tools are available, load the live site and sample computed styles from key elements (body, h1, a, button, .card). This catches values that tokens miss.
-
-### Step 2: Auto-extract what can be auto-extracted
-
-Build a structured draft from the discovered tokens. For each token class:
-
-- **Colors**: Group into Primary / Secondary / Tertiary / Neutral (the Material-derived roles Stitch uses). If the project only has one accent, express it as Primary + Neutral; omit Secondary and Tertiary rather than inventing them.
-- **Typography**: Map observed sizes and weights to the Material hierarchy (display / headline / title / body / label). Note font-family stacks and the scale ratio.
-- **Elevation**: Catalogue the shadow vocabulary. If the project is flat and uses tonal layering instead, that's a valid answer; state it explicitly.
-- **Components**: For each common component (button, card, input, chip, list item, tooltip, nav), extract shape (radius), color assignment, hover/focus treatment, internal padding.
-- **Spacing + layout**: Fold into Overview or relevant Components. The spec does NOT have a Layout section.
-
-### Step 2b: Stage the frontmatter
-
-From the auto-extracted tokens, draft the YAML frontmatter now (you'll write it at the top of DESIGN.md in Step 4). This is the machine-readable layer: what the live panel and Stitch's linter consume.
-
-- **Colors**: one entry per extracted color. Key = descriptive slug (`warm-ash-cream`, `editorial-magenta`, not `blue-800`). Value = whichever format the project treats as canonical (OKLCH or hex; see the frontmatter rules above). Don't split the source of truth: one format in the frontmatter, don't redefine the same token in prose with a different value.
-- **Typography**: one entry per role (`display`, `headline`, `title`, `body`, `label`). Typography is an object; include only the props that are real for the project (`fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `fontFeature`, `fontVariation`).
-- **Rounded / Spacing**: whatever scale steps the project actually uses, keyed by whatever scale name the project uses (`sm` / `md` / `lg`, or `surface-sm`, or numeric steps).
-- **Components**: one entry per variant (`button-primary`, `button-primary-hover`, `button-ghost`). Reference primitives via `{colors.X}`, `{rounded.Y}`. If a variant needs a property Stitch's 8-prop set doesn't cover (shadow, focus ring, backdrop-filter), carry the full snippet in the sidecar instead.
-
-Skip anything the project doesn't have. Empty scale keys or fabricated tokens pollute the spec.
-
-### Step 3: Ask the user for qualitative language
-
-The following require creative input that cannot be auto-extracted. Group them into one `AskUserQuestion` interaction:
-
-- **Creative North Star**: a single named metaphor for the whole system ("The Editorial Sanctuary", "The Golden State Curator", "The Lab Notebook"). Offer 2-3 options that honor PRODUCT.md's brand personality.
-- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, anti-references (what the system should not feel like).
-- **Color character** (for auto-extracted colors): descriptive names ("Deep Muted Teal-Navy", not "blue-800"). Suggest 2-3 options per key color based on hue/saturation.
-- **Elevation philosophy**: flat/layered/lifted. If shadows exist, is their role ambient or structural?
-- **Component philosophy**: the feel of buttons, cards, inputs in one phrase ("tactile and confident" vs. "refined and restrained").
-
-Quote a line from PRODUCT.md when possible so the user sees their own strategic language carry forward.
-
-### Step 4: Write DESIGN.md
-
-The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the structure below. Headers must match character-for-character. Optional evocative subtitles (e.g. `## 2. Colors: The Coastal Palette`) are allowed.
-
-```markdown
----
-name: [Project Title]
-description: [one-line tagline]
-colors:
- # ... staged frontmatter from Step 2b
----
-
-# Design System: [Project Title]
-
-## 1. Overview
-
-**Creative North Star: "[Named metaphor in quotes]"**
-
-[2-3 paragraph holistic description: personality, density, aesthetic philosophy. Start from the North Star and work outward. State what this system explicitly rejects (pulled from PRODUCT.md's anti-references). End with a short **Key Characteristics:** bullet list.]
-
-## 2. Colors
-
-[Describe the palette character in one sentence.]
-
-### Primary
-- **[Descriptive Name]** (#HEX / oklch(...)): [Where and why this color is used. Be specific about context, not just role.]
-
-### Secondary (optional; omit if the project has only one accent)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Tertiary (optional)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Neutral
-- **[Descriptive Name]** (#HEX): [Text / background / border / divider role.]
-- [...]
-
-### Named Rules (optional, powerful)
-**The [Rule Name] Rule.** [Short, forceful prohibition or doctrine, e.g. "The One Voice Rule. The primary accent is used on ≤10% of any given screen. Its rarity is the point."]
-
-## 3. Typography
-
-**Display Font:** [Family] (with [fallback])
-**Body Font:** [Family] (with [fallback])
-**Label/Mono Font:** [Family, if distinct]
-
-**Character:** [1-2 sentence personality description of the pairing.]
-
-### Hierarchy
-- **Display** ([weight], [size/clamp], [line-height]): [Purpose; where it appears.]
-- **Headline** ([weight], [size], [line-height]): [Purpose.]
-- **Title** ([weight], [size], [line-height]): [Purpose.]
-- **Body** ([weight], [size], [line-height]): [Purpose. Include max line length like 65–75ch if relevant.]
-- **Label** ([weight], [size], [letter-spacing], [case if uppercase]): [Purpose.]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [Short doctrine about type use.]
-
-## 4. Elevation
-
-[One paragraph: does this system use shadows, tonal layering, or a hybrid? If "no shadows", say so explicitly and describe how depth is conveyed instead.]
-
-### Shadow Vocabulary (if applicable)
-- **[Role name]** (`box-shadow: [exact value]`): [When to use it.]
-- [...]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [e.g. "The Flat-By-Default Rule. Surfaces are flat at rest. Shadows appear only as a response to state (hover, elevation, focus)."]
-
-## 5. Components
-
-For each component, lead with a short character line, then specify shape, color assignment, states, and any distinctive behavior.
-
-### Buttons
-- **Shape:** [radius described, exact value in parens]
-- **Primary:** [color assignment + padding, in semantic + exact terms]
-- **Hover / Focus:** [transitions, treatments]
-- **Secondary / Ghost / Tertiary (if applicable):** [brief description]
-
-### Chips (if used)
-- **Style:** [background, text color, border treatment]
-- **State:** [selected / unselected, filter / action variants]
-
-### Cards / Containers
-- **Corner Style:** [radius]
-- **Background:** [colors used]
-- **Shadow Strategy:** [reference Elevation section]
-- **Border:** [if any]
-- **Internal Padding:** [scale]
-
-### Inputs / Fields
-- **Style:** [stroke, background, radius]
-- **Focus:** [treatment, e.g. glow, border shift, etc.]
-- **Error / Disabled:** [if applicable]
-
-### Navigation
-- **Style, typography, default/hover/active states, mobile treatment.**
-
-### [Signature Component] (optional; if the project has a distinctive custom component worth documenting)
-[Description.]
-
-## 6. Do's and Don'ts
-
-Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: include exact colors, pixel values, and named anti-patterns the user mentioned in PRODUCT.md. **Every anti-reference in PRODUCT.md should show up here as a "Don't" with the same language**, so the visual spec carries the strategic line through. Quote PRODUCT.md directly where possible: if PRODUCT.md says *"avoid dark mode with purple gradients, neon accents, glassmorphism"*, the Don'ts here should repeat that by name.
-
-### Do:
-- **Do** [specific prescription with exact values / named rule].
-- **Do** [...]
-
-### Don't:
-- **Don't** [specific prohibition, e.g. "use border-left greater than 1px as a colored stripe"].
-- **Don't** [...]
-- **Don't** [...]
-```
-
-### Step 4b: Write .impeccable/design.json sidecar (extensions only)
-
-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.
-
-Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.
-
-#### Schema
-
-```json
-{
- "schemaVersion": 2,
- "generatedAt": "ISO-8601 string",
- "title": "Design System: [Project Title]",
- "extensions": {
- "colorMeta": {
- "primary": { "role": "primary", "displayName": "Editorial Magenta", "canonical": "oklch(60% 0.25 350)", "tonalRamp": ["...", "...", "..."] },
- "warm-ash-cream": { "role": "neutral", "displayName": "Warm Ash Cream", "canonical": "oklch(96% 0.005 350)", "tonalRamp": ["...", "...", "..."] }
- },
- "typographyMeta": {
- "display": { "displayName": "Display", "purpose": "Hero headlines only." }
- },
- "shadows": [
- { "name": "ambient-low", "value": "0 4px 24px rgba(0,0,0,0.12)", "purpose": "Diffuse hover glow under accent elements." }
- ],
- "motion": [
- { "name": "ease-standard", "value": "cubic-bezier(0.4, 0, 0.2, 1)", "purpose": "Default easing for state transitions." }
- ],
- "breakpoints": [
- { "name": "sm", "value": "640px" }
- ]
- },
- "components": [
- {
- "name": "Primary Button",
- "kind": "button | input | nav | chip | card | custom",
- "refersTo": "button-primary",
- "description": "One-line what and when.",
- "html": "<button class=\"ds-btn-primary\">GET STARTED</button>",
- "css": ".ds-btn-primary { background: #191c1d; color: #fff; padding: 16px 48px; letter-spacing: 0.05em; text-transform: uppercase; font-weight: 500; border: none; border-radius: 0; transition: background 0.2s, transform 0.2s; } .ds-btn-primary:hover { background: oklch(60% 0.25 350); transform: translateY(-2px); }"
- }
- ],
- "narrative": {
- "northStar": "The Editorial Sanctuary",
- "overview": "2-3 paragraphs of the philosophy, pulled from DESIGN.md Overview section.",
- "keyCharacteristics": ["...", "..."],
- "rules": [{ "name": "The One Voice Rule", "body": "...", "section": "colors|typography|elevation" }],
- "dos": ["Do use ..."],
- "donts": ["Don't use ..."]
- }
-}
-```
-
-**What changed from schemaVersion 1.** The old sidecar carried token primitive arrays (`tokens.colors[]`, `tokens.typography[]`, etc.). Those values now live in the frontmatter. The sidecar only carries metadata that can't live in the frontmatter (tonal ramps, canonical OKLCH when the hex is an approximation, display names, role hints), keyed by the frontmatter token name (`colorMeta.<token-name>`, `typographyMeta.<token-name>`). Components still carry full HTML/CSS because Stitch's 8-prop set can't hold them.
-
-#### Component translation rules
-
-The `html` and `css` fields must be **self-contained, drop-in snippets** that render correctly when injected into a shadow DOM. The panel applies them directly: no post-processing, no framework runtime.
-
-1. **Tailwind expansion.** If the source uses Tailwind (className="bg-primary text-white rounded-lg px-6 py-3"), expand every utility to literal CSS properties in the `css` string. Do **not** reference Tailwind classes; do **not** assume a Tailwind CSS bundle is loaded. Each component is self-contained.
-2. **Token resolution.** If the project exposes tokens as CSS custom properties on `:root` (e.g. `--color-primary`, `--radius-md`), reference them via `var(--color-primary)`; they inherit through the shadow DOM and stay live-bound. If tokens live only in JS theme objects (styled-components, CSS-in-JS), resolve to literal values at generation time.
-3. **Icons.** Inline as SVG. Do not reference Lucide/Heroicons packages, icon fonts, or `<img src="...">`. A typical icon is 16-24px; copy the SVG path data directly.
-4. **States.** Include `:hover`, `:focus-visible`, and (if meaningful) `:active` rules inline. A static default-only snapshot makes the panel feel dead. Hover + focus rules in the CSS make it feel alive.
-5. **Reset bloat.** Extract only the component's *distinctive* CSS (background, color, padding, border-radius, typography, transition). Skip universal resets (`box-sizing: border-box`, `line-height: inherit`, `-webkit-font-smoothing`). The panel already has a neutral canvas; don't re-ship resets.
-6. **Scoped class names.** Prefix every class with `ds-` (e.g. `ds-btn-primary`, `ds-input-search`) so component CSS doesn't collide with other components' CSS in the same shadow DOM.
-
-#### What to include
-
-Aim for a tight set of **5-10 components** that best represent the visual system:
-
-- **Canonical primitives (always include if the project has them):** button (each variant as a separate component entry), input/text field, navigation, chip/tag, card.
-- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.
-- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.
-
-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.
-
-#### Tonal ramps
-
-For each color token, generate an 8-step `tonalRamp` array: dark to light, same hue and chroma, stepped lightness from ~15% to ~95%. The panel renders this as a strip under the swatch. If the project already defines a tonal scale (Material `surface-container-low` family, Tailwind-style `blue-50..blue-900`), use those values. Otherwise synthesize in OKLCH.
-
-#### Narrative mapping
-
-Pull directly from the DESIGN.md you just wrote:
-
-- `narrative.northStar` → the `**Creative North Star: "..."**` line from Overview
-- `narrative.overview` → the philosophy paragraphs from Overview
-- `narrative.keyCharacteristics` → the bulleted `**Key Characteristics:**` list
-- `narrative.rules` → every `**The [Name] Rule.** [body]` across all sections, tagged with `section`
-- `narrative.dos` / `narrative.donts` → the bullet lists from Do's and Don'ts verbatim
-
-Do not reword. The panel shows these as secondary collapsible context; the same voice that's in the Markdown carries through.
-
-### Step 5: Confirm, refine, and refresh session cache
-
-1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).
-2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.
-3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"
-4. **Refresh the session cache.** Run `node .cursor/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.
-
-## Seed mode
-
-For projects with no visual system to extract yet. Produces a minimal scaffold, not a full spec.
-
-### Step 1: Confirm seed mode
-
-Before interviewing: "There's no existing visual system to scan. I'll ask five quick questions to seed a starter DESIGN.md. You can re-run `/impeccable document` once there's code, to capture the real tokens and components. OK?"
-
-If the user prefers to skip, stop. No file.
-
-### Step 2: Five questions
-
-Group into one `AskUserQuestion` interaction. Options must be concrete.
-
-1. **Color strategy.** Pick one:
- - Restrained: tinted neutrals + one accent ≤10%
- - Committed: one saturated color carries 30–60% of the surface
- - Full palette: 3–4 named color roles, each deliberate
- - Drenched: the surface IS the color
-
- Then: one hue family or anchor reference ("deep teal", "mustard", "Klim #ff4500 orange").
-
-2. **Typography direction.** Pick one (specific fonts come later):
- - Serif display + sans body
- - Single sans (warm / technical / geometric / humanist; pick a feel)
- - Display + mono
- - Mono-forward
- - Editorial script + sans
-
-3. **Motion energy.** Pick one:
- - Restrained: state changes only
- - Responsive: feedback + transitions, no choreography
- - Choreographed: orchestrated entrances, scroll-driven sequences
-
-4. **Three named references.** Brands, products, printed objects. Not adjectives.
-
-5. **One anti-reference.** What it should NOT feel like. Also named.
-
-### Step 3: Write seed DESIGN.md
-
-Use the six-section spec from Scan mode. Populate what the interview answers; leave the rest as honest placeholders. The seed is a scaffold, not a fabricated spec.
-
-Lead the file with:
-
-```markdown
-<!-- SEED: re-run /impeccable document once there's code to capture the actual tokens and components. -->
-```
-
-Per-section guidance in seed mode:
-
-- **Overview**: Creative North Star and philosophy phrased from the answers (color strategy + motion energy + references). Reference the user's anti-reference directly.
-- **Colors**: Color strategy as a Named Rule (e.g. *"The Drenched Rule. The surface IS the color."*). Hue family or anchor reference. No hex values; mark as `[to be resolved during implementation]`.
-- **Typography**: the direction the user picked (e.g. "Serif display + sans body"). No font names yet: `[font pairing to be chosen at implementation]`.
-- **Elevation**: inferred from motion energy. Restrained/Responsive → flat by default; Choreographed → layered. One sentence.
-- **Components**: omit entirely; no components exist yet.
-- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.
-
-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.
-
-### Step 4: Confirm and refresh session cache
-
-1. Show the seed DESIGN.md. Call out that it is a seed (the marker is the literal commitment).
-2. Tell the user: "Re-run `/impeccable document` once you have some code. That pass will extract real tokens and generate the sidecar."
-3. Run `node .cursor/skills/impeccable/scripts/load-context.mjs` once so the seed lands in conversation for the rest of the session.
-
-## Style guidelines
-
-- **Frontmatter first, prose second.** Tokens go in the YAML frontmatter; prose contextualizes them. Don't redefine a token value in two places; the frontmatter is normative.
-- **Cite PRODUCT.md anti-references by name** in the Do's and Don'ts section. If PRODUCT.md lists "SaaS landing-page clichés" or "generic AI tool marketing" as anti-references, the DESIGN.md Don'ts should repeat those phrases verbatim so the visual spec enforces the strategic line.
-- **Match the spec, don't invent new sections.** The six section names are fixed. If you have Layout/Motion/Responsive content to document, fold it into Overview (philosophy-level rules) or Components (per-component behavior).
-- **Descriptive > technical**: "Gently curved edges (8px radius)" > "rounded-lg". Include the technical value in parens, lead with the description.
-- **Functional > decorative**: for each token, explain WHERE and WHY it's used, not just WHAT it is.
-- **Exact values in parens**: hex codes, px/rem values, font weights; always the number in parens alongside the description.
-- **Use Named Rules**: `**The [Name] Rule.** [short doctrine]`. These are memorable, citable, and much stickier for AI consumers than bullet lists. Stitch's own outputs use them heavily ("The No-Line Rule", "The Ghost Border Fallback"). Aim for 1-3 per section.
-- **Be forceful**. The voice of a design director. "Prohibited", "forbidden", "never", "always", not "consider", "might", "prefer". Match PRODUCT.md's tone.
-- **Concrete anti-pattern tests**. Stitch writes things like *"If it looks like a 2014 app, the shadow is too dark and the blur is too small."* A one-sentence audit test beats a paragraph of principle.
-- **Reference PRODUCT.md**. The anti-references section of PRODUCT.md should directly inform the Do's and Don'ts section here. Quote or paraphrase.
-- **Group colors by role**, not by hex-order or hue-order. Primary / Secondary / Tertiary / Neutral is the spec ordering.
-
-## Pitfalls
-
-- Don't paste raw CSS class names. Translate to descriptive language.
-- Don't extract every token. Stop at what's actually reused; one-offs pollute the system.
-- Don't invent components that don't exist. If the project only has buttons and cards, only document those.
-- Don't overwrite an existing DESIGN.md without asking.
-- Don't duplicate content from PRODUCT.md. DESIGN.md is strictly visual.
-- Don't add a "Layout Principles" or "Motion" or "Responsive Behavior" top-level section. The spec has six, not nine. Fold that content where it belongs.
-- Don't rename sections even slightly. "Colors" not "Color Palette & Roles". "Typography" not "Typography Rules". Tooling parsing depends on exact headers.
-- Don't duplicate token values between frontmatter and prose. If a color is in `colors.primary` as hex, the prose can name it and describe its role but should not reassert a different hex. The frontmatter is normative.
-- Don't invent frontmatter token groups outside Stitch's schema (no `motion:`, `breakpoints:`, `shadows:` at the top level). Stitch's Zod schema only accepts `colors`, `typography`, `rounded`, `spacing`, `components`. Anything else belongs in the sidecar's `extensions`.
@@ -1,69 +0,0 @@
-# Extract Flow
-
-Identify reusable patterns, components, and design tokens, then extract and consolidate them into the design system for systematic reuse.
-
-## Step 1: Discover the Design System
-
-Find the design system, component library, or shared UI directory. Understand its structure: component organization, naming conventions, design token structure, import/export conventions.
-
-**CRITICAL**: If no design system exists, ask the user directly to clarify what you cannot infer. before creating one. Understand the preferred location and structure first.
-
-## Step 2: Identify Patterns
-
-Look for extraction opportunities in the target area:
-
-- **Repeated components**: Similar UI patterns used 3+ times (buttons, cards, inputs)
-- **Hard-coded values**: Colors, spacing, typography, shadows that should be tokens
-- **Inconsistent variations**: Multiple implementations of the same concept
-- **Composition patterns**: Layout or interaction patterns that repeat (form rows, toolbar groups, empty states)
-- **Type styles**: Repeated font-size + weight + line-height combinations
-- **Animation patterns**: Repeated easing, duration, or keyframe combinations
-
-Assess value: only extract things used 3+ times with the same intent. Premature abstraction is worse than duplication.
-
-## Step 3: Plan Extraction
-
-Create a systematic plan:
-
-- **Components to extract**: Which UI elements become reusable components?
-- **Tokens to create**: Which hard-coded values become design tokens?
-- **Variants to support**: What variations does each component need?
-- **Naming conventions**: Component names, token names, prop names that match existing patterns
-- **Migration path**: How to refactor existing uses to consume the new shared versions
-
-**IMPORTANT**: Design systems grow incrementally. Extract what is clearly reusable now, not everything that might someday be reusable.
-
-## Step 4: Extract & Enrich
-
-Build improved, reusable versions:
-
-- **Components**: Clear props API with sensible defaults, proper variants for different use cases, accessibility built in (ARIA, keyboard navigation, focus management), documentation and usage examples
-- **Design tokens**: Clear naming (primitive vs semantic), proper hierarchy and organization, documentation of when to use each token
-- **Patterns**: When to use this pattern, code examples, variations and combinations
-
-## Step 5: Migrate
-
-Replace existing uses with the new shared versions:
-
-- **Find all instances**: Search for the patterns you extracted
-- **Replace systematically**: Update each use to consume the shared version
-- **Test thoroughly**: Ensure visual and functional parity
-- **Delete dead code**: Remove the old implementations
-
-## Step 6: Document
-
-Update design system documentation:
-
-- Add new components to the component library
-- Document token usage and values
-- Add examples and guidelines
-- Update any Storybook or component catalog
-
-**NEVER**:
-- Extract one-off, context-specific implementations without generalization
-- Create components so generic they are useless
-- Extract without considering existing design system conventions
-- Skip proper TypeScript types or prop documentation
-- Create tokens for every single value (tokens should have semantic meaning)
-- Extract things that differ in intent (two buttons that look similar but serve different purposes should stay separate)
-
@@ -1,347 +0,0 @@
-Designs that only work with perfect data aren't production-ready. Harden the interface against the inputs, errors, languages, and network conditions that real users will throw at it.
-
-## Assess Hardening Needs
-
-Identify weaknesses and edge cases:
-
-1. **Test with extreme inputs**:
- - Very long text (names, descriptions, titles)
- - Very short text (empty, single character)
- - Special characters (emoji, RTL text, accents)
- - Large numbers (millions, billions)
- - Many items (1000+ list items, 50+ options)
- - No data (empty states)
-
-2. **Test error scenarios**:
- - Network failures (offline, slow, timeout)
- - API errors (400, 401, 403, 404, 500)
- - Validation errors
- - Permission errors
- - Rate limiting
- - Concurrent operations
-
-3. **Test internationalization**:
- - Long translations (German is often 30% longer than English)
- - RTL languages (Arabic, Hebrew)
- - Character sets (Chinese, Japanese, Korean, emoji)
- - Date/time formats
- - Number formats (1,000 vs 1.000)
- - Currency symbols
-
-**CRITICAL**: Designs that only work with perfect data aren't production-ready. Harden against reality.
-
-## Hardening Dimensions
-
-Systematically improve resilience:
-
-### Text Overflow & Wrapping
-
-**Long text handling**:
-```css
-/* Single line with ellipsis */
-.truncate {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* Multi-line with clamp */
-.line-clamp {
- display: -webkit-box;
- -webkit-line-clamp: 3;
- -webkit-box-orient: vertical;
- overflow: hidden;
-}
-
-/* Allow wrapping */
-.wrap {
- word-wrap: break-word;
- overflow-wrap: break-word;
- hyphens: auto;
-}
-```
-
-**Flex/Grid overflow**:
-```css
-/* Prevent flex items from overflowing */
-.flex-item {
- min-width: 0; /* Allow shrinking below content size */
- overflow: hidden;
-}
-
-/* Prevent grid items from overflowing */
-.grid-item {
- min-width: 0;
- min-height: 0;
-}
-```
-
-**Responsive text sizing**:
-- Use `clamp()` for fluid typography
-- Set minimum readable sizes (14px on mobile)
-- Test text scaling (zoom to 200%)
-- Ensure containers expand with text
-
-### Internationalization (i18n)
-
-**Text expansion**:
-- Add 30-40% space budget for translations
-- Use flexbox/grid that adapts to content
-- Test with longest language (usually German)
-- Avoid fixed widths on text containers
-
-```jsx
-// ❌ Bad: Assumes short English text
-<button className="w-24">Submit</button>
-
-// ✅ Good: Adapts to content
-<button className="px-4 py-2">Submit</button>
-```
-
-**RTL (Right-to-Left) support**:
-```css
-/* Use logical properties */
-margin-inline-start: 1rem; /* Not margin-left */
-padding-inline: 1rem; /* Not padding-left/right */
-border-inline-end: 1px solid; /* Not border-right */
-
-/* Or use dir attribute */
-[dir="rtl"] .arrow { transform: scaleX(-1); }
-```
-
-**Character set support**:
-- Use UTF-8 encoding everywhere
-- Test with Chinese/Japanese/Korean (CJK) characters
-- Test with emoji (they can be 2-4 bytes)
-- Handle different scripts (Latin, Cyrillic, Arabic, etc.)
-
-**Date/Time formatting**:
-```javascript
-// ✅ Use Intl API for proper formatting
-new Intl.DateTimeFormat('en-US').format(date); // 1/15/2024
-new Intl.DateTimeFormat('de-DE').format(date); // 15.1.2024
-
-new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: 'USD'
-}).format(1234.56); // $1,234.56
-```
-
-**Pluralization**:
-```javascript
-// ❌ Bad: Assumes English pluralization
-`${count} item${count !== 1 ? 's' : ''}`
-
-// ✅ Good: Use proper i18n library
-t('items', { count }) // Handles complex plural rules
-```
-
-### Error Handling
-
-**Network errors**:
-- Show clear error messages
-- Provide retry button
-- Explain what happened
-- Offer offline mode (if applicable)
-- Handle timeout scenarios
-
-```jsx
-// Error states with recovery
-{error && (
- <ErrorMessage>
- <p>Failed to load data. {error.message}</p>
- <button onClick={retry}>Try again</button>
- </ErrorMessage>
-)}
-```
-
-**Form validation errors**:
-- Inline errors near fields
-- Clear, specific messages
-- Suggest corrections
-- Don't block submission unnecessarily
-- Preserve user input on error
-
-**API errors**:
-- Handle each status code appropriately
- - 400: Show validation errors
- - 401: Redirect to login
- - 403: Show permission error
- - 404: Show not found state
- - 429: Show rate limit message
- - 500: Show generic error, offer support
-
-**Graceful degradation**:
-- Core functionality works without JavaScript
-- Images have alt text
-- Progressive enhancement
-- Fallbacks for unsupported features
-
-### Edge Cases & Boundary Conditions
-
-**Empty states**:
-- No items in list
-- No search results
-- No notifications
-- No data to display
-- Provide clear next action
-
-**Loading states**:
-- Initial load
-- Pagination load
-- Refresh
-- Show what's loading ("Loading your projects...")
-- Time estimates for long operations
-
-**Large datasets**:
-- Pagination or virtual scrolling
-- Search/filter capabilities
-- Performance optimization
-- Don't load all 10,000 items at once
-
-**Concurrent operations**:
-- Prevent double-submission (disable button while loading)
-- Handle race conditions
-- Optimistic updates with rollback
-- Conflict resolution
-
-**Permission states**:
-- No permission to view
-- No permission to edit
-- Read-only mode
-- Clear explanation of why
-
-**Browser compatibility**:
-- Polyfills for modern features
-- Fallbacks for unsupported CSS
-- Feature detection (not browser detection)
-- Test in target browsers
-
-### Input Validation & Sanitization
-
-**Client-side validation**:
-- Required fields
-- Format validation (email, phone, URL)
-- Length limits
-- Pattern matching
-- Custom validation rules
-
-**Server-side validation** (always):
-- Never trust client-side only
-- Validate and sanitize all inputs
-- Protect against injection attacks
-- Rate limiting
-
-**Constraint handling**:
-```html
-<!-- Set clear constraints -->
-<input
- type="text"
- maxlength="100"
- pattern="[A-Za-z0-9]+"
- required
- aria-describedby="username-hint"
-/>
-<small id="username-hint">
- Letters and numbers only, up to 100 characters
-</small>
-```
-
-### Accessibility Resilience
-
-**Keyboard navigation**:
-- All functionality accessible via keyboard
-- Logical tab order
-- Focus management in modals
-- Skip links for long content
-
-**Screen reader support**:
-- Proper ARIA labels
-- Announce dynamic changes (live regions)
-- Descriptive alt text
-- Semantic HTML
-
-**Motion sensitivity**:
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**High contrast mode**:
-- Test in Windows high contrast mode
-- Don't rely only on color
-- Provide alternative visual cues
-
-### Performance Resilience
-
-**Slow connections**:
-- Progressive image loading
-- Skeleton screens
-- Optimistic UI updates
-- Offline support (service workers)
-
-**Memory leaks**:
-- Clean up event listeners
-- Cancel subscriptions
-- Clear timers/intervals
-- Abort pending requests on unmount
-
-**Throttling & Debouncing**:
-```javascript
-// Debounce search input
-const debouncedSearch = debounce(handleSearch, 300);
-
-// Throttle scroll handler
-const throttledScroll = throttle(handleScroll, 100);
-```
-
-## Testing Strategies
-
-**Manual testing**:
-- Test with extreme data (very long, very short, empty)
-- Test in different languages
-- Test offline
-- Test slow connection (throttle to 3G)
-- Test with screen reader
-- Test keyboard-only navigation
-- Test on old browsers
-
-**Automated testing**:
-- Unit tests for edge cases
-- Integration tests for error scenarios
-- E2E tests for critical paths
-- Visual regression tests
-- Accessibility tests (axe, WAVE)
-
-**IMPORTANT**: Hardening is about expecting the unexpected. Real users will do things you never imagined.
-
-**NEVER**:
-- Assume perfect input (validate everything)
-- Ignore internationalization (design for global)
-- Leave error messages generic ("Error occurred")
-- Forget offline scenarios
-- Trust client-side validation alone
-- Use fixed widths for text
-- Assume English-length text
-- Block entire interface when one component errors
-
-## Verify Hardening
-
-Test thoroughly with edge cases:
-
-- **Long text**: Try names with 100+ characters
-- **Emoji**: Use emoji in all text fields
-- **RTL**: Test with Arabic or Hebrew
-- **CJK**: Test with Chinese/Japanese/Korean
-- **Network issues**: Disable internet, throttle connection
-- **Large datasets**: Test with 1000+ items
-- **Concurrent actions**: Click submit 10 times rapidly
-- **Errors**: Force API errors, test all error states
-- **Empty**: Remove all data, test empty states
-
-When edge cases are covered, hand off to `/impeccable polish` for the final pass.
@@ -1,234 +0,0 @@
-# Heuristics Scoring Guide
-
-Score each of Nielsen's 10 Usability Heuristics on a 0–4 scale. Be honest: a 4 means genuinely excellent, not "good enough."
-
-## Nielsen's 10 Heuristics
-
-### 1. Visibility of System Status
-
-Keep users informed about what's happening through timely, appropriate feedback.
-
-**Check for**:
-- Loading indicators during async operations
-- Confirmation of user actions (save, submit, delete)
-- Progress indicators for multi-step processes
-- Current location in navigation (breadcrumbs, active states)
-- Form validation feedback (inline, not just on submit)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No feedback; user is guessing what happened |
-| 1 | Rare feedback; most actions produce no visible response |
-| 2 | Partial; some states communicated, major gaps remain |
-| 3 | Good; most operations give clear feedback, minor gaps |
-| 4 | Excellent; every action confirms, progress is always visible |
-
-### 2. Match Between System and Real World
-
-Speak the user's language. Follow real-world conventions. Information appears in natural, logical order.
-
-**Check for**:
-- Familiar terminology (no unexplained jargon)
-- Logical information order matching user expectations
-- Recognizable icons and metaphors
-- Domain-appropriate language for the target audience
-- Natural reading flow (left-to-right, top-to-bottom priority)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Pure tech jargon, alien to users |
-| 1 | Mostly confusing; requires domain expertise to navigate |
-| 2 | Mixed; some plain language, some jargon leaks through |
-| 3 | Mostly natural; occasional term needs context |
-| 4 | Speaks the user's language fluently throughout |
-
-### 3. User Control and Freedom
-
-Users need a clear "emergency exit" from unwanted states without extended dialogue.
-
-**Check for**:
-- Undo/redo functionality
-- Cancel buttons on forms and modals
-- Clear navigation back to safety (home, previous)
-- Easy way to clear filters, search, selections
-- Escape from long or multi-step processes
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Users get trapped; no way out without refreshing |
-| 1 | Difficult exits; must find obscure paths to escape |
-| 2 | Some exits; main flows have escape, edge cases don't |
-| 3 | Good control; users can exit and undo most actions |
-| 4 | Full control; undo, cancel, back, and escape everywhere |
-
-### 4. Consistency and Standards
-
-Users shouldn't wonder whether different words, situations, or actions mean the same thing.
-
-**Check for**:
-- Consistent terminology throughout the interface
-- Same actions produce same results everywhere
-- Platform conventions followed (standard UI patterns)
-- Visual consistency (colors, typography, spacing, components)
-- Consistent interaction patterns (same gesture = same behavior)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Inconsistent everywhere; feels like different products stitched together |
-| 1 | Many inconsistencies; similar things look/behave differently |
-| 2 | Partially consistent; main flows match, details diverge |
-| 3 | Mostly consistent; occasional deviation, nothing confusing |
-| 4 | Fully consistent; cohesive system, predictable behavior |
-
-### 5. Error Prevention
-
-Better than good error messages is a design that prevents problems in the first place.
-
-**Check for**:
-- Confirmation before destructive actions (delete, overwrite)
-- Constraints preventing invalid input (date pickers, dropdowns)
-- Smart defaults that reduce errors
-- Clear labels that prevent misunderstanding
-- Autosave and draft recovery
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Errors easy to make; no guardrails anywhere |
-| 1 | Few safeguards; some inputs validated, most aren't |
-| 2 | Partial prevention; common errors caught, edge cases slip |
-| 3 | Good prevention; most error paths blocked proactively |
-| 4 | Excellent; errors nearly impossible through smart constraints |
-
-### 6. Recognition Rather Than Recall
-
-Minimize memory load. Make objects, actions, and options visible or easily retrievable.
-
-**Check for**:
-- Visible options (not buried in hidden menus)
-- Contextual help when needed (tooltips, inline hints)
-- Recent items and history
-- Autocomplete and suggestions
-- Labels on icons (not icon-only navigation)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Heavy memorization; users must remember paths and commands |
-| 1 | Mostly recall; many hidden features, few visible cues |
-| 2 | Some aids; main actions visible, secondary features hidden |
-| 3 | Good recognition; most things discoverable, few memory demands |
-| 4 | Everything discoverable; users never need to memorize |
-
-### 7. Flexibility and Efficiency of Use
-
-Accelerators, invisible to novices, speed up expert interaction.
-
-**Check for**:
-- Keyboard shortcuts for common actions
-- Customizable interface elements
-- Recent items and favorites
-- Bulk/batch actions
-- Power user features that don't complicate the basics
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | One rigid path; no shortcuts or alternatives |
-| 1 | Limited flexibility; few alternatives to the main path |
-| 2 | Some shortcuts; basic keyboard support, limited bulk actions |
-| 3 | Good accelerators; keyboard nav, some customization |
-| 4 | Highly flexible; multiple paths, power features, customizable |
-
-### 8. Aesthetic and Minimalist Design
-
-Interfaces should not contain irrelevant or rarely needed information. Every element should serve a purpose.
-
-**Check for**:
-- Only necessary information visible at each step
-- Clear visual hierarchy directing attention
-- Purposeful use of color and emphasis
-- No decorative clutter competing for attention
-- Focused, uncluttered layouts
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Overwhelming; everything competes for attention equally |
-| 1 | Cluttered; too much noise, hard to find what matters |
-| 2 | Some clutter; main content clear, periphery noisy |
-| 3 | Mostly clean; focused design, minor visual noise |
-| 4 | Perfectly minimal; every element earns its pixel |
-
-### 9. Help Users Recognize, Diagnose, and Recover from Errors
-
-Error messages should use plain language, precisely indicate the problem, and constructively suggest a solution.
-
-**Check for**:
-- Plain language error messages (no error codes for users)
-- Specific problem identification ("Email is missing @" not "Invalid input")
-- Actionable recovery suggestions
-- Errors displayed near the source of the problem
-- Non-blocking error handling (don't wipe the form)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Cryptic errors; codes, jargon, or no message at all |
-| 1 | Vague errors; "Something went wrong" with no guidance |
-| 2 | Clear but unhelpful; names the problem but not the fix |
-| 3 | Clear with suggestions; identifies problem and offers next steps |
-| 4 | Perfect recovery; pinpoints issue, suggests fix, preserves user work |
-
-### 10. Help and Documentation
-
-Even if the system is usable without docs, help should be easy to find, task-focused, and concise.
-
-**Check for**:
-- Searchable help or documentation
-- Contextual help (tooltips, inline hints, guided tours)
-- Task-focused organization (not feature-organized)
-- Concise, scannable content
-- Easy access without leaving current context
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No help available anywhere |
-| 1 | Help exists but hard to find or irrelevant |
-| 2 | Basic help; FAQ or docs exist, not contextual |
-| 3 | Good documentation; searchable, mostly task-focused |
-| 4 | Excellent contextual help; right info at the right moment |
-
----
-
-## Score Summary
-
-**Total possible**: 40 points (10 heuristics × 4 max)
-
-| Score Range | Rating | What It Means |
-|-------------|--------|---------------|
-| 36–40 | Excellent | Minor polish only; ship it |
-| 28–35 | Good | Address weak areas, solid foundation |
-| 20–27 | Acceptable | Significant improvements needed before users are happy |
-| 12–19 | Poor | Major UX overhaul required; core experience broken |
-| 0–11 | Critical | Redesign needed; unusable in current state |
-
----
-
-## Issue Severity (P0–P3)
-
-Tag each individual issue found during scoring with a priority level:
-
-| Priority | Name | Description | Action |
-|----------|------|-------------|--------|
-| **P0** | Blocking | Prevents task completion entirely | Fix immediately; this is a showstopper |
-| **P1** | Major | Causes significant difficulty or confusion | Fix before release |
-| **P2** | Minor | Annoyance, but workaround exists | Fix in next pass |
-| **P3** | Polish | Nice-to-fix, no real user impact | Fix if time permits |
-
-**Tip**: If you're unsure between two levels, ask: "Would a user contact support about this?" If yes, it's at least P1.
@@ -1,195 +0,0 @@
-# Interaction Design
-
-## The Eight Interactive States
-
-Every interactive element needs these states designed:
-
-| State | When | Visual Treatment |
-|-------|------|------------------|
-| **Default** | At rest | Base styling |
-| **Hover** | Pointer over (not touch) | Subtle lift, color shift |
-| **Focus** | Keyboard/programmatic focus | Visible ring (see below) |
-| **Active** | Being pressed | Pressed in, darker |
-| **Disabled** | Not interactive | Reduced opacity, no pointer |
-| **Loading** | Processing | Spinner, skeleton |
-| **Error** | Invalid state | Red border, icon, message |
-| **Success** | Completed | Green check, confirmation |
-
-**The common miss**: Designing hover without focus, or vice versa. They're different. Keyboard users never see hover states.
-
-## Focus Rings: Do Them Right
-
-**Never `outline: none` without replacement.** It's an accessibility violation. Instead, use `:focus-visible` to show focus only for keyboard users:
-
-```css
-/* Hide focus ring for mouse/touch */
-button:focus {
- outline: none;
-}
-
-/* Show focus ring for keyboard */
-button:focus-visible {
- outline: 2px solid var(--color-accent);
- outline-offset: 2px;
-}
-```
-
-**Focus ring design**:
-- High contrast (3:1 minimum against adjacent colors)
-- 2-3px thick
-- Offset from element (not inside it)
-- Consistent across all interactive elements
-
-## Form Design: The Non-Obvious
-
-**Placeholders aren't labels.** They disappear on input. Always use visible `<label>` elements. **Validate on blur**, not on every keystroke (exception: password strength). Place errors **below** fields with `aria-describedby` connecting them.
-
-## Loading States
-
-**Optimistic updates**: Show success immediately, rollback on failure. Use for low-stakes actions (likes, follows), not payments or destructive actions. **Skeleton screens > spinners**: they preview content shape and feel faster than generic spinners.
-
-## Modals: The Inert Approach
-
-Focus trapping in modals used to require complex JavaScript. Now use the `inert` attribute:
-
-```html
-<!-- When modal is open -->
-<main inert>
- <!-- Content behind modal can't be focused or clicked -->
-</main>
-<dialog open>
- <h2>Modal Title</h2>
- <!-- Focus stays inside modal -->
-</dialog>
-```
-
-Or use the native `<dialog>` element:
-
-```javascript
-const dialog = document.querySelector('dialog');
-dialog.showModal(); // Opens with focus trap, closes on Escape
-```
-
-## The Popover API
-
-For tooltips, dropdowns, and non-modal overlays, use native popovers:
-
-```html
-<button popovertarget="menu">Open menu</button>
-<div id="menu" popover>
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-**Benefits**: Light-dismiss (click outside closes), proper stacking, no z-index wars, accessible by default.
-
-## Dropdown & Overlay Positioning
-
-Dropdowns rendered with `position: absolute` inside a container that has `overflow: hidden` or `overflow: auto` will be clipped. This is the single most common dropdown bug in generated code.
-
-### CSS Anchor Positioning
-
-The modern solution uses the CSS Anchor Positioning API to tether an overlay to its trigger without JavaScript:
-
-```css
-.trigger {
- anchor-name: --menu-trigger;
-}
-
-.dropdown {
- position: fixed;
- position-anchor: --menu-trigger;
- position-area: block-end span-inline-end;
- margin-top: 4px;
-}
-
-/* Flip above if no room below */
-@position-try --flip-above {
- position-area: block-start span-inline-end;
- margin-bottom: 4px;
-}
-```
-
-Because the dropdown uses `position: fixed`, it escapes any `overflow` clipping on ancestor elements. The `@position-try` block handles viewport edges automatically. **Browser support**: Chrome 125+, Edge 125+. Not yet in Firefox or Safari - use a fallback for those browsers.
-
-### Popover + Anchor Combo
-
-Combining the Popover API with anchor positioning gives you stacking, light-dismiss, accessibility, and correct positioning in one pattern:
-
-```html
-<button popovertarget="menu" class="trigger">Open</button>
-<div id="menu" popover class="dropdown">
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-The `popover` attribute places the element in the **top layer**, which sits above all other content regardless of z-index or overflow. No portal needed.
-
-### Portal / Teleport Pattern
-
-In component frameworks, render the dropdown at the document root and position it with JavaScript:
-
-- **React**: `createPortal(dropdown, document.body)`
-- **Vue**: `<Teleport to="body">`
-- **Svelte**: Use a portal library or mount to `document.body`
-
-Calculate position from the trigger's `getBoundingClientRect()`, then apply `position: fixed` with `top` and `left` values. Recalculate on scroll and resize.
-
-### Fixed Positioning Fallback
-
-For browsers without anchor positioning support, `position: fixed` with manual coordinates avoids overflow clipping:
-
-```css
-.dropdown {
- position: fixed;
- /* top/left set via JS from trigger's getBoundingClientRect() */
-}
-```
-
-Check viewport boundaries before rendering. If the dropdown would overflow the bottom edge, flip it above the trigger. If it would overflow the right edge, align it to the trigger's right side instead.
-
-### Anti-Patterns
-
-- **`position: absolute` inside `overflow: hidden`** - The dropdown will be clipped. Use `position: fixed` or the top layer instead.
-- **Arbitrary z-index values** like `z-index: 9999` - Use a semantic z-index scale: `dropdown (100) -> sticky (200) -> modal-backdrop (300) -> modal (400) -> toast (500) -> tooltip (600)`.
-- **Rendering dropdown markup inline** without an escape hatch from the parent's stacking context. Either use `popover` (top layer), a portal, or `position: fixed`.
-
-## Destructive Actions: Undo > Confirm
-
-**Undo is better than confirmation dialogs.** Users click through confirmations mindlessly. Remove from UI immediately, show undo toast, actually delete after toast expires. Use confirmation only for truly irreversible actions (account deletion), high-cost actions, or batch operations.
-
-## Keyboard Navigation Patterns
-
-### Roving Tabindex
-
-For component groups (tabs, menu items, radio groups), one item is tabbable; arrow keys move within:
-
-```html
-<div role="tablist">
- <button role="tab" tabindex="0">Tab 1</button>
- <button role="tab" tabindex="-1">Tab 2</button>
- <button role="tab" tabindex="-1">Tab 3</button>
-</div>
-```
-
-Arrow keys move `tabindex="0"` between items. Tab moves to the next component entirely.
-
-### Skip Links
-
-Provide skip links (`<a href="#main-content">Skip to main content</a>`) for keyboard users to jump past navigation. Hide off-screen, show on focus.
-
-## Gesture Discoverability
-
-Swipe-to-delete and similar gestures are invisible. Hint at their existence:
-
-- **Partially reveal**: Show delete button peeking from edge
-- **Onboarding**: Coach marks on first use
-- **Alternative**: Always provide a visible fallback (menu with "Delete")
-
-Don't rely on gestures as the only way to perform actions.
-
----
-
-**Avoid**: Removing focus indicators without alternatives. Using placeholder text as labels. Touch targets <44x44px. Generic error messages. Custom controls without ARIA/keyboard support.
@@ -1,141 +0,0 @@
-Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids, the centered-stack default) and fix the structure, not the surface.
-
----
-
-## Register
-
-Brand: asymmetric compositions, fluid spacing with `clamp()`, intentional grid-breaking for emphasis. Rhythm through contrast: tight groupings paired with generous separations.
-
-Product: predictable grids, consistent densities, familiar navigation patterns. Responsive behavior is structural (collapse sidebar, responsive table), not fluid typography. Consistency IS an affordance.
-
----
-
-## Assess Current Layout
-
-Analyze what's weak about the current spatial design:
-
-1. **Spacing**:
- - Is spacing consistent or arbitrary? (Random padding/margin values)
- - Is all spacing the same? (Equal padding everywhere = no rhythm)
- - Are related elements grouped tightly, with generous space between groups?
-
-2. **Visual hierarchy**:
- - Apply the squint test: blur your (metaphorical) eyes. Can you still identify the most important element, second most important, and clear groupings?
- - Is hierarchy achieved effectively? (Space and weight alone can be enough; is the current approach working?)
- - Does whitespace guide the eye to what matters?
-
-3. **Grid & structure**:
- - Is there a clear underlying structure, or does the layout feel random?
- - Are identical card grids used everywhere? (Icon + heading + text, repeated endlessly)
- - Is everything centered? (Left-aligned with asymmetric layouts feels more designed, but not a hard and fast rule)
-
-4. **Rhythm & variety**:
- - Does the layout have visual rhythm? (Alternating tight/generous spacing)
- - Is every section structured the same way? (Monotonous repetition)
- - Are there intentional moments of surprise or emphasis?
-
-5. **Density**:
- - Is the layout too cramped? (Not enough breathing room)
- - Is the layout too sparse? (Excessive whitespace without purpose)
- - Does density match the content type? (Data-dense UIs need tighter spacing; marketing pages need more air)
-
-**CRITICAL**: Layout problems are often the root cause of interfaces feeling "off" even when colors and fonts are fine. Space is a design material; use it with intention.
-
-## Plan Layout Improvements
-
-Consult the [spatial design reference](spatial-design.md) for detailed guidance on grids, rhythm, and container queries.
-
-Create a systematic plan:
-
-- **Spacing system**: Use a consistent scale (a framework's built-in scale like Tailwind's, rem-based tokens, or a custom system). The specific values matter less than consistency.
-- **Hierarchy strategy**: How will space communicate importance?
-- **Layout approach**: What structure fits the content? Flex for 1D, Grid for 2D, named areas for complex page layouts.
-- **Rhythm**: Where should spacing be tight vs generous?
-
-## Improve Layout Systematically
-
-### Establish a Spacing System
-
-- Use a consistent spacing scale (framework scales like Tailwind, rem-based tokens, or a custom scale all work). What matters is that values come from a defined set, not arbitrary numbers.
-- Name tokens semantically if using custom properties: `--space-xs` through `--space-xl`, not `--spacing-8`
-- Use `gap` for sibling spacing instead of margins; eliminates margin collapse hacks
-- Apply `clamp()` for fluid spacing that breathes on larger screens
-
-### Create Visual Rhythm
-
-- **Tight grouping** for related elements (8-12px between siblings)
-- **Generous separation** between distinct sections (48-96px)
-- **Varied spacing** within sections (not every row needs the same gap)
-- **Asymmetric compositions**: break the predictable centered-content pattern when it makes sense
-
-### Choose the Right Layout Tool
-
-- **Use Flexbox for 1D layouts**: Rows of items, nav bars, button groups, card contents, most component internals. Flex is simpler and more appropriate for the majority of layout tasks.
-- **Use Grid for 2D layouts**: Page-level structure, dashboards, data-dense interfaces, anything where rows AND columns need coordinated control.
-- **Don't default to Grid** when Flexbox with `flex-wrap` would be simpler and more flexible.
-- Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints.
-- Use named grid areas (`grid-template-areas`) for complex page layouts; redefine at breakpoints.
-
-### Break Card Grid Monotony
-
-- Don't default to card grids for everything; spacing and alignment create visual grouping naturally
-- Use cards only when content is truly distinct and actionable. Never nest cards inside cards
-- Vary card sizes, span columns, or mix cards with non-card content to break repetition
-
-### Strengthen Visual Hierarchy
-
-- Use the fewest dimensions needed for clear hierarchy. Space alone can be enough; generous whitespace around an element draws the eye. Some of the most polished designs achieve rhythm with just space and weight. Add color or size contrast only when simpler means aren't sufficient.
-- Be aware of reading flow: in LTR languages, the eye naturally scans top-left to bottom-right, but primary action placement depends on context (e.g., bottom-right in dialogs, top in navigation).
-- Create clear content groupings through proximity and separation.
-
-### Manage Depth & Elevation
-
-- Create a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip)
-- Build a consistent shadow scale (sm → md → lg → xl); shadows should be subtle
-- Use elevation to reinforce hierarchy, not as decoration
-
-### Optical Adjustments
-
-- If an icon looks visually off-center despite being geometrically centered, nudge it. But only if you're confident it actually looks wrong. Don't adjust speculatively.
-
-**NEVER**:
-- Use arbitrary spacing values outside your scale
-- Make all spacing equal (variety creates hierarchy)
-- Wrap everything in cards (not everything needs a container)
-- Nest cards inside cards (use spacing and dividers for hierarchy within)
-- Use identical card grids everywhere (icon + heading + text, repeated)
-- Center everything (left-aligned with asymmetry feels more designed)
-- Default to the hero metric layout (big number, small label, stats, gradient) as a template. If showing real user data, a prominent metric can work, but it should display actual data, not decorative numbers.
-- Default to CSS Grid when Flexbox would be simpler; use the simplest tool for the job
-- Use arbitrary z-index values (999, 9999); build a semantic scale
-
-## Verify Layout Improvements
-
-- **Squint test**: Can you identify primary, secondary, and groupings with blurred vision?
-- **Rhythm**: Does the page have a satisfying beat of tight and generous spacing?
-- **Hierarchy**: Is the most important content obvious within 2 seconds?
-- **Breathing room**: Does the layout feel comfortable, not cramped or wasteful?
-- **Consistency**: Is the spacing system applied uniformly?
-- **Responsiveness**: Does the layout adapt gracefully across screen sizes?
-
-When the rhythm and hierarchy land, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `density` param. Drive all spacing tokens in the variant's scoped CSS through `calc(var(--p-density, 1) * <base>)`: paddings, gaps, column widths. Users slide from airy to packed and see layout re-breathe with no regeneration.
-
-```json
-{"id":"density","kind":"range","min":0.6,"max":1.4,"step":0.05,"default":1,"label":"Density"}
-```
-
-For variants whose topology genuinely changes (stacked vs. side-by-side, grid vs. bento), use a `steps` param whose scoped CSS branches via `:scope[data-p-structure="X"]`. One structure param + one density param is a powerful combo; resist adding a third.
-
-```json
-{"id":"structure","kind":"steps","default":"grid","label":"Structure","options":[
- {"value":"stacked","label":"Stacked"},
- {"value":"grid","label":"Grid"},
- {"value":"bento","label":"Bento"}
-]}
-```
-
-See `reference/live.md` for the full params contract.
@@ -1,622 +0,0 @@
-Interactive live variant mode: select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via the dev server's HMR.
-
-## Prerequisites
-
-A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR a static HTML file open in the browser.
-
-## The contract (read once)
-
-Execute in order. No step skipped, no step reordered.
-
-1. `live.mjs`: boot.
-2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.
-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.
-5. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
-6. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
-7. On `exit`: run the cleanup at the bottom.
-
-Harness policy:
-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.
-- **Cursor**: run the poll in the **foreground** (blocking shell; not a background terminal, not a subagent). Cursor background terminals and subagents do not reliably resume the chat with poll stdout.
-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.
-- **Other harnesses**: foreground unless you know stdout reliably returns to this session.
-
-Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.
-
-## Start
-
-```bash
-node .cursor/skills/impeccable/scripts/live.mjs
-```
-
-Output JSON: `{ ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath, migrated }`. `pageFiles` is the list of HTML entries the live script was injected into. Keep PRODUCT.md and DESIGN.md in mind for variant generation; **DESIGN.md wins on visual decisions; PRODUCT.md wins on strategic/voice decisions.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt. If `migrated: true`, the loader auto-renamed legacy `.impeccable.md` to `PRODUCT.md`; mention this once and suggest `/impeccable document` for the matching DESIGN.md.
-
-`serverPort` and `serverToken` belong to the small **Impeccable live helper** HTTP server (serves `/live.js`, SSE, and `/poll`). That port is **not** your dev server and is usually not the URL you open to view the app. The browser page is whatever origin serves one of the `pageFiles` entries (Vite / Next / Bun / tunnel / LAN hostname).
-
-If output is `{ ok: false, error: "config_missing" | "config_invalid", path }`, this project hasn't been configured for live mode (or its config is stale). See **First-time setup** at the bottom.
-
-## Poll loop
-
-```
-LOOP:
- node .cursor/skills/impeccable/scripts/live-poll.mjs # default long timeout; no --timeout=
- Read JSON; dispatch on "type"
-
- "generate" → Handle Generate; reply done; LOOP
- "accept" → Handle Accept; complete carbonize cleanup if required; LOOP
- "discard" → Handle Discard; LOOP
- "prefetch" → Handle Prefetch; LOOP
- "timeout" → LOOP
- "exit" → break → Cleanup
-```
-
-## Recovery commands
-
-The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.
-
-Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:
-
-```bash
-node .cursor/skills/impeccable/scripts/live-status.mjs
-node .cursor/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID
-node .cursor/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID
-```
-
-- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.
-- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.
-- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.
-
-Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.
-
-## Handle `generate`
-
-Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.
-
-Speed matters; the user is watching a spinner. Minimize tool calls by using the `wrap` helper and writing all variants in a single edit.
-
-### 1. Read the screenshot (if present)
-
-`event.screenshotPath` is **only sent when the user placed at least one comment or stroke before Go.** When present, it's an absolute path to a PNG of the element as rendered with the annotations baked in. **Read it before planning**: annotations encode user intent not recoverable from `element.outerHTML` alone.
-
-When `screenshotPath` is absent, don't ask for one and don't go looking for the current rendering. The omission is deliberate: without annotations, a screenshot would anchor the model on the existing design and fight the three-distinct-directions brief. Work from `element.outerHTML`, the computed styles in `event.element`, and the freeform prompt if present.
-
-`event.comments` and `event.strokes` carry structured metadata alongside the visual. Treat the screenshot as primary; use the structured data for specifics worth quoting (e.g. the exact text of a comment).
-
-Reading annotations precisely:
-
-- **Comment position carries meaning.** Its `{x, y}` is element-local CSS px (same coord space as `element.boundingRect`). Find the child under that point and apply the comment text LOCALLY to that sub-element. A comment near the title is about the title, not a global description.
-- **Comments and strokes are independent annotations** unless clearly paired by overlap or tight proximity. Don't let the visual weight of a prominent stroke override the precise location of a textually-specific comment elsewhere.
-- **Strokes are gestures; read them by shape.** Closed loop = "this thing" (emphasis / focus); arrow = direction (move / point to); cross or slash = delete; free scribble = emphasis or delete depending on context. A loop around region X means "pay attention to X," not "only change pixels inside X."
-- **When a stroke's intent is ambiguous** (circle or arrow? emphasis or move?), state your reading in one sentence of rationale rather than silently guessing. If the uncertainty materially changes the brief, ask one short clarifying question before generating.
-
-### 2. Wrap the element
-
-```bash
-node .cursor/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"
-```
-
-Flag mapping. Keep them separate, don't collapse into `--query`:
-
-- `--element-id` ← `event.element.id`
-- `--classes` ← `event.element.classes` joined with commas
-- `--tag` ← `event.element.tagName`
-- `--text` ← first ~80 chars of `event.element.textContent` (trim, single-line). **Pass this every call.** When the picked element shares classes + tag with sibling components (a list of `<Card>`s, repeating sections), this is what disambiguates which branch in source to wrap. Without it, wrap silently lands on the first match and may rewrite the wrong element.
-
-The helper searches ID first, then classes, then tag + class combo. If `event.pageUrl` implies the file (e.g. `/` is usually `index.html`), pass `--file PATH` to skip the search. `--query` is a fallback for raw text search only; do not use it for normal element lookups.
-
-If `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.
-
-Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.
-
-`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:
-
-- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.
-- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.
-
-Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.
-
-**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:
-
-- `{ error: "file_is_generated", file, hint }`: user-supplied `--file` points at a generated file.
-- `{ error: "element_not_in_source", generatedMatch, hint }`: element exists only in a generated file (the next build would wipe any edits).
-- `{ error: "element_not_found", hint }`: element isn't in any project file; likely runtime-injected (JS component, dynamic render from data).
-
-All three carry `fallback: "agent-driven"`. Follow **Handle fallback** below.
-
-### 3. Load the action's reference
-
-If `event.action` is `impeccable` (the default freeform action), use SKILL.md's shared laws plus the loaded register reference (`brand.md` or `product.md`). Do not load a sub-command reference. **Freeform is not a pass to skip parameters:** you still follow the composition budget and the freeform bias in **§7 Parameters** below. Sub-command files list MUST-have signature knobs; freeform has no such file, so sizing knobs from surface weight and primary axes is entirely on you.
-
-Any other `event.action` (`bolder`, `quieter`, `distill`, `polish`, `typeset`, `colorize`, `layout`, `adapt`, `animate`, `delight`, `overdrive`): Read `reference/<action>.md` before planning. Each sub-command encodes a specific discipline; skipping its reference produces generic output. Those files may require specific params; layer them on top of the §7 budget, not instead of it.
-
-### 4. Plan three variants: identity first, then mode, then axes
-
-The wrong frame for live mode is "show three different design directions." Live runs on an existing surface; the brand has already been chosen. The job is variation **within identity**, not selection between identities. Failure mode: three editorial-typographic variants on a brief that wasn't editorial. Bigger failure mode: three off-brand variants the user can't accept because they don't look like their product.
-
-Four phases. Do them in order.
-
-#### Phase A: Extract the identity (non-skippable)
-
-The existing surface has an identity already. Read it before planning anything. Sources, in priority order:
-
-1. **DESIGN.md** if loaded: read the visual system fields (palette, type pairing, motion, components). This is the authoritative answer.
-2. **CSS custom properties** in the page's stylesheets (`:root { --color-...; --font-...; ... }`): these are de-facto tokens.
-3. **Computed styles** on the picked element and its parent: colors, fonts, spacing scales, corner radii.
-4. **Sibling components on the page**: what visual rhetoric do existing components use? (Asymmetric or centered? Dense or airy? Bold or quiet?)
-
-Write down what you see in **one sentence**. The sentence describes the surface that's actually on screen; it is not aspirational, not opinionated, not edited toward what the brand "should" be. Capture, in roughly this order:
-
-- The dominant surface color and accent color, by hex or token name (use the actual values, not categories like "warm" or "neutral").
-- The type pairing: the actual font names loaded, primary first.
-- The layout topology: how the dominant elements are arranged (stacked / side-by-side / grid / asymmetric / overlay).
-- The surface treatment: corners, borders, shadows, density of decoration.
-- The voice tone you read off the copy itself, not off the aesthetic feel.
-
-Be specific. "Modern" is not a color, "elegant" is not a type pairing, "clean" is not a layout. If you can't extract a real value for an axis, skip it rather than fabricate. The point is to record what is, not to describe what you wish it were.
-
-Do not include adjectives that name an aesthetic family ("editorial-leaning", "terminal-flavored", "brutalist"); those are conclusions, not data. They belong to Phase C lane selection in departure mode, not to identity description. Letting them sneak into Phase A is how the identity-lock collapses into a self-fulfilling prophecy.
-
-This sentence is the **identity lock**. Every variant must be readable as the same brand if rendered side by side. Skipping this phase is the primary cause of off-brand variants. Absence of DESIGN.md is never an excuse; extract from CSS and computed styles instead.
-
-#### Phase B: Pick mode (default vs departure)
-
-**Default mode**: the existing identity is preserved. Variants vary expression axes within it. *This is the right mode for ~90% of live sessions.* The user picked an element on a real product they're shipping; they expect variants of *their* hero, not three different brands' heroes.
-
-**Departure mode**: the existing identity is rejected. Variants propose alternatives consistent with PRODUCT.md voice. Trigger only when at least one is true:
-
-- PRODUCT.md anti-references explicitly call out the current surface ("the current `index.html` is itself an example"; "diffuse away from this"; "the page on screen is the failure"). Generic anti-references that describe what to avoid in general do **not** trigger departure mode; only ones that point at *this* surface specifically.
-- The user's freeform prompt explicitly asks for departure ("rebuild this from scratch", "what if it weren't editorial at all", "show me something completely different").
-
-If you're unsure, you're in default mode. The cost of being wrong about default is "three on-brand variants with similar feel": recoverable, the user picks none. The cost of being wrong about departure is "three off-brand variants": unrecoverable, the user is annoyed.
-
-#### Phase C: Plan three variants
-
-**Default mode.** Each variant commits to a different **primary axis** of difference, while preserving the identity sentence. The six axes:
-
-1. **Hierarchy**: which element commands the eye?
-2. **Layout topology**: stacked / side-by-side / grid / asymmetric / overlay
-3. **Typographic system**: pairing logic, scale ratio, case/weight strategy *within the available faces*
-4. **Color strategy**: which existing palette role carries the surface (Restrained / Committed / Full palette / Drenched). Use the brand's existing palette tokens, not new colors.
-5. **Density**: minimal / comfortable / dense
-6. **Structural decomposition**: merge, split, progressive disclosure
-
-Three variants → three DIFFERENT axes. The trio reads as *the same brand at three angles*. Do not introduce new fonts, new palette hues, or new aesthetic-family signals; those belong to departure mode.
-
-**While planning each variant, also name its 2–3 parameter knobs** (per the §7 budget table). Parameters are part of the design, not a decoration added afterward. If the variant explores density, expose a density knob. If it explores color commitment, expose a color-amount range. Deciding "what's tunable" during planning produces better knobs than retrofitting them onto finished HTML.
-
-**Departure mode.** Each variant anchors to a different **aesthetic direction**, derived from the brand's stated voice and register in PRODUCT.md. Do NOT pick from a fixed catalog of lane categories. The right three directions for this brand are not the same as the right three for another brand, and picking from a list is itself the training-data reflex (the model selects "Swiss-grid, Terminal, Industrial-signage" every time because those are the furthest-from-editorial items in any enumerated list).
-
-Instead, work from the brand:
-
-1. Read PRODUCT.md's Brand Personality words. What physical, spatial, or material experiences would embody those words if design were not involved? (A personality described as "specific, earned, unmistakable" evokes a hand-stamped letter, a numbered print, a watchmaker's loupe. A personality described as "restless, loud, unfiltered" evokes a concert poster, a spray-painted wall, a megaphone.)
-2. From those physical experiences, derive three visual directions that are genuinely different from each other AND from the current surface you're departing.
-3. Avoid the **reflex-reject lanes** in [brand.md](brand.md). Don't trade one monoculture for another. If you find yourself reaching for "Swiss-grid" or "Terminal" or "Industrial-signage" by reflex, you are pattern-matching a catalog in your training data, not reading the brand. Start over from the personality words.
-4. Each direction must be expressible in one concrete sentence that names a real-world referent ("a museum exhibition label system for a contemporary art gallery" not "clean and minimal"). If your sentence contains only adjectives, it's not concrete enough.
-5. **While planning each direction, also name its 2–3 parameter knobs** (per the §7 budget table). The same principle as default mode: decide "what's tunable" during planning, not after writing the HTML. A departure-mode hero with 0 parameters is not "bold creative vision," it's a missed opportunity for the user to fine-tune the direction they pick.
-
-#### Phase D: Squint test
-
-**Default mode squint.** Read each variant's identity sentence and compare to the locked identity from Phase A. If any variant has drifted to a different palette, type voice, or visual rhetoric, it has crossed into departure mode by accident; rework. Then check that each variant commits to a different primary axis. Three "tighter density" variants is failure.
-
-**Departure mode squint.** Two passes, family before sentence:
-
-1. **Family pass.** Label each variant with one design-family word of your own choosing (any concrete noun: *exhibition, storefront, cockpit, recipe-card, playbill, field-manual*). If any two variants share a label, or if the label could apply to the other variants equally well, rework. Do not use a fixed vocabulary list for the labels. *This pass is non-negotiable in departure mode and catches the monoculture failure that the sentence pass misses.*
-2. **Sentence pass.** Write three one-sentence descriptions side by side. If two of them rhyme ("both feature big type" / "both are stacks of sections" / "both center the CTA"), rework the offender.
-
-**When the primary axis is color or theme, forbid the trio from sharing theme + dominant hue.** Two dark-plus-one-dark is not distinct. Aim for three color worlds, not three shades of the same.
-
-**For action-specific invocations**, each variant must vary along the dimension the action names:
-
-- `bolder`: amplify a different dimension per variant (scale / saturation / structural change). Not three "slightly bigger" variants.
-- `quieter`: pull back a different dimension (color / ornament / spacing).
-- `distill`: remove a different class of excess (visual noise / redundant content / nested structure).
-- `polish`: target a different refinement axis (rhythm / hierarchy / micro-details like corner radii, focus states, optical kerning).
-- `typeset`: different type pairing AND different scale ratio each. Not three riffs on one pairing.
-- `colorize`: different hue family each (not shades of one hue). Vary chroma and contrast strategy.
-- `layout`: different structural arrangement (stacked / side-by-side / grid / asymmetric). Not spacing tweaks.
-- `adapt`: different target context per variant (mobile-first / tablet / desktop / print or low-data). Don't make three mobile layouts.
-- `animate`: different motion vocabulary (cascade stagger / clip wipe / scale-and-focus / morph / parallax). Not three staggered fades.
-- `delight`: different flavor of personality (unexpected micro-interaction / typographic surprise / illustrated accent / sonic-or-haptic moment / easter-egg interaction).
-- `overdrive`: different convention broken (scale / structure / motion / input model / state transitions). Skip `overdrive.md`'s "propose and ask" step; live mode is non-interactive.
-
-### 5. Apply the freeform prompt (if present)
-
-`event.freeformPrompt` is the user's ceiling on direction (all variants must honor it), but still explore meaningfully different *interpretations*. The interpretations stay within whichever mode you picked in Phase B.
-
-In **default mode**, the prompt narrows the axes you choose, not the identity. *"Make it feel more confident"* → variant 1 amplifies hierarchy (one element commands the eye), variant 2 commits the existing accent color (Committed strategy on the brand's hue), variant 3 tightens density and removes decorative slack. Three different axes, same brand.
-
-In **departure mode**, the prompt narrows the lanes you draw from, not the families. *"Make it feel like a newspaper front page"* would itself be a departure-mode prompt; honor it but pick three meaningfully different newspaper-adjacent lanes (broadsheet vs. tabloid vs. trade journal), and run the family pass to confirm they don't collapse into one.
-
-When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.
-
-### 6. Write all variants in a single edit
-
-Complete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).
-
-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).
-
-Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:
-
-```html
-<!-- Variants: insert below this line -->
-<style data-impeccable-css="SESSION_ID">
- /* rules matching cssAuthoring.rulePattern */
-</style>
-<div data-impeccable-variant="1">
- <!-- variant 1: full element replacement (single top-level element) -->
-</div>
-<div data-impeccable-variant="2" style="display: none">
- <!-- variant 2: full element replacement -->
-</div>
-<div data-impeccable-variant="3" style="display: none">
- <!-- variant 3: full element replacement -->
-</div>
-```
-
-**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.
-
-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.
-
-One edit, all variants; the browser's MutationObserver picks everything up in one pass.
-
-For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.
-
-**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:
-
-```tsx
-<style data-impeccable-css="SESSION_ID">{`
- @scope ([data-impeccable-variant="1"]) { ... }
- @scope ([data-impeccable-variant="2"]) { ... }
-`}</style>
-<div data-impeccable-variant="1">
- {/* variant 1 */}
-</div>
-<div data-impeccable-variant="2" style={{ display: 'none' }}>
- {/* variant 2 */}
-</div>
-```
-
-The wrap script already gives you a single-rooted JSX wrapper: a `<div data-impeccable-variants="…">` outer element with the marker comments tucked inside. Drop the variants block above into the "Variants: insert below this line" comment and the source stays valid TSX.
-
-### 7. Parameters (composition-sized, 0–4 per variant)
-
-Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement. The browser docks a small panel to the right of the outline with one control per parameter. The user drags/clicks and sees instant feedback: there is zero regeneration cost because the knob toggles a CSS variable or data attribute that the variant's scoped CSS is already authored against.
-
-**What “optional” does not mean.** Parameters are not nice-to-have decoration on large work. The word meant “omit controls that are redundant or cosmetic,” not “default to zero because three variants were enough work.”
-
-**When to add.** As soon as the variant’s scoped CSS has a meaningful continuous or stepped axis: density, color amount, type scale, motion intensity, column weight, and so on. If you can imagine the user muttering “a bit tighter” or “a touch more accent” **without** wanting a full regeneration, wire that axis. **Not** micro-margins or one-off nudges; those are not parameters.
-
-**Freeform (`action` is `impeccable`) bias.** You did not load a sub-command reference, so you must **choose** signature axes yourself. Match the budget table: for a hero or large composition, that means **2–3 axes per variant**, not 1. Prefer knobs that sit on the dimensions where your three variants actually differ (if density varies, expose it as a `steps` knob; if color commitment varies, expose it as a `range`). A hero that ships with **0** params is almost always a mistake, not a judgment call. A hero with exactly **1** param is underweight unless the design is genuinely a fixed-point comparison. Start from the budget table, not from zero.
-
-**Budget scales with the element's visual weight, not token budget.** Knobs need real estate to read as tunable; three sliders on a single control are noise.
-
-- **Leaf / tiny**: a single button, icon, input, bare heading, solitary paragraph: **0 params.**
-- **Small composition**: labeled input, simple card, short callout (≤ ~5 visual children): **0–1** params when one dominant axis is obvious; otherwise **0.**
-- **Medium composition**: section component, nav cluster, dense card, short feature block (6–15 visual children): **target 2**; **1** is acceptable if the block is simple; **0** only when variants are truly fixed points.
-- **Large composition**: hero section, full page region, spread layout, strong internal structure (16+ visual children or multiple sub-sections): **target 2–3**; **up to 4** when several independent axes (e.g. structure `steps` + `density` + one accent) are all authored in scoped CSS.
-
-**When in doubt, ask whether a dial exists before defaulting to zero.** The user can always request more variants, but the point of live mode is instant tuning without another Go. Crowding the panel is bad; **under-shipping** knobs on a dense composition is the more common failure for freeform. Count by **visual** children, not DOM depth; a shallow-but-wide hero is still large.
-
-**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.
-
-**How to declare.** Put a JSON manifest on the variant wrapper:
-
-```html
-<div data-impeccable-variant="1" data-impeccable-params='[
- {"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"},
- {"id":"density","kind":"steps","default":"snug","label":"Density","options":[
- {"value":"airy","label":"Airy"},
- {"value":"snug","label":"Snug"},
- {"value":"packed","label":"Packed"}
- ]},
- {"id":"serif","kind":"toggle","default":false,"label":"Serif display"}
-]'>
- ...variant content...
-</div>
-```
-
-**Three kinds:**
-
-- `range`: smooth slider. Drives a CSS custom property `--p-<id>` on the variant wrapper. Author CSS with `var(--p-color-amount, 0.5)`. Fields: `min`, `max`, `step`, `default` (number), `label`.
-- `steps`: segmented radio. Drives a data attribute `data-p-<id>` on the variant wrapper. Author CSS with `:scope[data-p-density="airy"] .grid { ... }`. Fields: `options` (array of `{value, label}`), `default` (string), `label`.
-- `toggle`: on/off switch. Drives BOTH a CSS var (`--p-<id>: 0|1`) and a data attribute (present when on, absent when off). Use whichever is more convenient. Fields: `default` (boolean), `label`.
-
-**Signature params per action.** For named sub-commands, read that action’s `reference/<action>.md` for one or two **MUST** params (e.g. `layout` → `density`). Those are non-negotiable when the design can express them. **Freeform has no file-level MUST**; the **Freeform (`impeccable`) bias** in this section is the stand-in. If the user’s action is both stylized and sub-command (e.g. `colorize`), the sub-command’s MUST list takes precedence for its axes; still respect the **Hard cap** and add no redundant duplicate knobs.
-
-**Reset on variant switch.** User dials density on v1, flips to v2, v2 starts at v2's declared defaults. Known limitation; preservation across variants may land later.
-
-**On accept**, the browser sends the user's current values in the accept event. `live-accept.mjs` writes them as a sibling comment:
-
-```html
-<!-- impeccable-param-values SESSION_ID: {"color-amount":0.7,"density":"packed"} -->
-```
-
-The carbonize cleanup step (see below) reads that comment and bakes the chosen values into the final CSS. For `steps`/`toggle` attribute selectors: keep only the branch matching the chosen value, drop the others, collapse `:scope[data-p-density="packed"] .grid` to a semantic class rule. For `range` vars: either substitute the literal or keep the var with the chosen value as its new default.
-
-### 8. Signal done
-
-```bash
-node .cursor/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
-```
-
-`RELATIVE_PATH` is relative to project root (`public/index.html`, `src/App.tsx`, etc.); the browser fetches source directly if the dev server lacks HMR.
-
-Then run `live-poll.mjs` again immediately.
-
-### Aborting an in-flight session
-
-If wrap or generation fails after the browser has flipped to GENERATING (e.g. wrap landed on the wrong source branch and you've already reverted it, or generation hit an unrecoverable error), tell the **browser** so its bar resets to PICKING:
-
-```bash
-node .cursor/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID error "Short reason"
-```
-
-Don't run `live-accept --discard` for this; that's a pure file mutator, the browser doesn't see it, and the bar gets stuck on the GENERATING dots forever (the user has to refresh). `--discard` is only correct when the **browser** initiated the discard (user clicked ✕ during CYCLING) and the agent is just running source-side cleanup the browser already triggered.
-
-## Handle fallback
-
-When wrap returns `fallback: "agent-driven"`, the deterministic flow doesn't apply. Pick up here.
-
-The goal is the same: give the user three variants to choose from AND persist the accepted one in a place the next build won't wipe. The difference is that you have to pick the right source file yourself.
-
-### Step 1: Identify where the element actually lives
-
-Use the error payload:
-
-- `element_not_in_source` with `generatedMatch: "public/docs/foo.html"`: the served HTML is generated. Find the generator (grep for writers of that path, e.g. `scripts/build-sub-pages.js`, an Astro/Next template) and locate the template or partial that emits this element.
-- `element_not_found`: the element is runtime-injected. Look for the component that renders it (React/Vue/Svelte), the JS that assembles it, or the data source that feeds it.
-- `file_is_generated` with `file: "..."`: user pointed at a generated file explicitly. Same resolution as `element_not_in_source`.
-
-Read the candidate source until you're confident where a change to the element would belong. If the change is purely visual, that source might be a shared stylesheet, not the template.
-
-### Step 2: Show three variants in the DOM for preview
-
-The browser bar is waiting for variants. Even without a wrapper in source, you still need to show something:
-
-1. Manually write the wrapper scaffold into the **served** file (the one the browser actually loaded). Use the same structure `live-wrap.mjs` produces; `<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents">…</div><!-- end -->`.
-2. Insert your three variant divs inside it, same shape as the deterministic path.
-3. Signal done with `--reply EVENT_ID done --file <served file>`. The browser's no-HMR fallback will fetch and inject.
-
-This served-file edit is **temporary**: next regen wipes it, and that's fine. The real work happens on accept.
-
-### Step 3: On accept, write to true source
-
-When the accept event arrives (`_acceptResult.handled` will usually be `false` here because accept also refuses to persist into generated files; see Handle accept for the carbonize branch), extract the accepted variant's content and write it into the source you identified in Step 1:
-
-- Structural change → edit the template / component source.
-- Visual-only change → add or update rules in the appropriate stylesheet; remove the inline `<style>` scope.
-- Dynamic from data → update the data source or the render logic.
-
-Then remove the temporary wrapper from the served file if it's still there.
-
-### Step 4: On discard, clean up the served file
-
-Remove the wrapper you inserted in Step 2. Nothing else to do.
-
-## Handle `accept`
-
-Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.
-
-- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.
-- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.
-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.
-- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.
-- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.
-
-### Required after accept (carbonize)
-
-When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.
-
-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.
-
-1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.
-2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).
-3. **Bake in parameter values while rewriting selectors.** For `@scope ([data-impeccable-variant="N"])` wrappers: retarget to real, semantic classes on the accepted HTML (`.why-visual--v2 .v2-label { … }`). For `:scope[data-p-<id>="VALUE"]` selectors: keep only the branch matching the chosen value from the param-values comment; drop the others (they're dead after accept). For `var(--p-<id>, DEFAULT)` in the CSS: either substitute the literal value, or if the param is still useful as a knob going forward, leave the var and update its initial declaration to the chosen value.
-4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; those are live-mode plumbing, not source.
-5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.
-
-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.
-
-A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.
-
-## Handle `discard`
-
-Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.
-
-## Handle `prefetch`
-
-Event: `{pageUrl}`. The browser fires this the first time the user selects an element on a given route, as a latency shortcut; it signals the user is likely about to Go on a page you haven't read yet.
-
-Resolve `pageUrl` to the underlying file:
-
-- Root `/` → the `pageFile` returned by `live.mjs` (usually `public/index.html` or equivalent).
-- Sub-routes (e.g. `/docs`, `/docs/live`) → the generated or source file for that route. Use your knowledge of the project layout (multi-page static sites often resolve `/foo` → `public/foo/index.html`; SPAs may map all routes to a single entry).
-
-Read the file into context, then poll again. No `--reply`: this is speculative pre-work; Go will come later. If you can't confidently resolve the route to a file, skip and poll again.
-
-Dedupe is the browser's job (one prefetch per unique pathname per session); trust it. If the same file shows up twice from different routes mapping to the same file, the second Read is cached anyway.
-
-## Exit
-
-The user can stop live mode by:
-- Saying "stop live mode" / "exit live" in chat
-- Closing the browser tab (SSE drops, poll returns `exit` after 8s)
-- The browser's exit button
-
-When the poll returns `exit`, proceed to cleanup. If the poll is still running as a background task, kill it first.
-
-## Cleanup
-
-```bash
-node .cursor/skills/impeccable/scripts/live-server.mjs stop
-```
-
-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.
-
-Then:
-- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).
-- Remove any leftover carbonize blocks (search for `impeccable-carbonize-start` markers).
-
-## First-time setup (config missing or invalid)
-
-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.
-
-Schema:
-
-```json
-{
- "files": ["<path-or-glob>", "<path-or-glob>", ...],
- "exclude": ["<optional-glob>", ...],
- "insertBefore": "</body>",
- "commentSyntax": "html",
- "cspChecked": true
-}
-```
-
-`files` is the inject target; **the HTML files the browser actually loads**, not necessarily source. Each entry is either a literal path (`"public/index.html"`) or a glob pattern (`"public/**/*.html"`). Tracked or generated doesn't matter here; wrap has its own generated-file guard and routes accepts through the fallback flow.
-
-`exclude` (optional) is a list of glob patterns matching files to skip, even if a `files` glob would have included them. Use for email templates, demo fixtures, or any HTML that isn't a live page.
-
-`cspChecked` tracks whether the CSP detection step below has already run. Absent on first setup; set to `true` after CSP is checked (whether patched, declined, or not needed).
-
-**Hard-excluded paths (cannot be overridden).** `**/node_modules/**` and `**/.git/**` are never matched regardless of what the user writes. These are vendor/metadata directories and injecting into them would silently instrument third-party code.
-
-**Glob syntax.** `**` matches any number of path segments (including zero), `*` matches any characters except `/`, `?` matches a single character except `/`. Paths are always relative to the project root with forward slashes.
-
-| Framework | `files` | `insertBefore` | `commentSyntax` |
-|-----------|---------|----------------|-----------------|
-| SPA with single shell (Vite / React / Plain HTML) | `["index.html"]` | `</body>` | `html` |
-| Next.js (App Router) | `["app/layout.tsx"]` | `</body>` | `jsx` |
-| Next.js (Pages) | `["pages/_document.tsx"]` | `</body>` | `jsx` |
-| Nuxt | `["app.vue"]` | `</body>` | `html` |
-| Svelte / SvelteKit | `["src/app.html"]` | `</body>` | `html` |
-| Astro | `[" <root layout .astro>"]` | `</body>` | `html` |
-| Multi-page (separate HTML per route) | `["public/**/*.html"]`: a glob covering the served directory | `</body>` | `html` |
-
-Pick an anchor that exists in every file (`</body>` almost always works). Use `insertAfter` if the anchor should match **after** a specific line.
-
-For multi-page sites, **prefer a glob over a literal file list**. New pages added later are picked up automatically on the next `live-inject.mjs` run; no config maintenance needed.
-
-For multi-page sites whose pages are *rebuilt* by a generator (Astro, static-site generators, custom scripts like `build-sub-pages.js`), the inject survives only until the next regeneration. Re-run `live.mjs` after each build. Accept is unaffected; it writes to true source via the fallback flow.
-
-### Drift-heal warning
-
-On every `live.mjs` boot, after inject, the project is scanned for HTML files under common page-source roots (`public/`, `src/`, `app/`, `pages/`). If any exist that aren't covered by the resolved `files` list, the output includes a `configDrift` field:
-
-```json
-{
- "ok": true,
- "serverPort": 8400,
- "pageFiles": [ "..." ],
- "configDrift": {
- "orphans": ["public/new-section/index.html", "public/docs/new-command.html"],
- "orphanCount": 2,
- "hint": "2 HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like \"public/**/*.html\"."
- }
-}
-```
-
-When `configDrift` is present, surface it to the user once per session before entering the poll loop:
-
-> Noticed N HTML file(s) in the project that aren't in `config.files`:
->
-> - `public/new-section/index.html`
-> - `public/docs/new-command.html`
->
-> Add them, or switch `files` to a glob like `["public/**/*.html"]` and let it track new pages automatically?
-
-Don't auto-update the config; let the user decide. `configDrift` is `null` when there's no drift.
-
-### CSP detection (first-time only)
-
-If `config.cspChecked === true`, skip this entire section. You already asked this user once; the answer sticks.
-
-Otherwise, run the detection helper:
-
-```bash
-node .cursor/skills/impeccable/scripts/detect-csp.mjs
-```
-
-Output: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.
-
-- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.
-- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:
- - Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)
- - SvelteKit `kit.csp.directives`
- - Nuxt `nuxt-security` module's `contentSecurityPolicy`
-- **`append-string`**: CSP written as a literal value string. Auto-patchable. See *append-string* below. Covers:
- - Inline `next.config.*` `headers()` with a CSP literal
- - Nuxt `routeRules` / `nitro.routeRules` headers
-- **`middleware`** or **`meta-tag`**: rarer. Detected but not auto-patched in v1. Show the user the detected files and ask them to add `http://localhost:8400` to `script-src` and `connect-src` manually, then mark `cspChecked: true` and proceed.
-
-#### Consent prompt template
-
-Use this phrasing so the experience is consistent across agents:
-
-> **CSP patch needed.** I detected a Content Security Policy in your project that blocks `http://localhost:8400`: the live picker won't load without an allowance. Here's the change I'd make:
->
-> ```diff
-> [file: <patchTarget>]
-> [exact diff, 2–5 lines]
-> ```
->
-> It's guarded by `NODE_ENV === "development"` so the extra entry only appears in dev and never reaches production. You can remove it any time by reverting this file. Apply? [y/n]
-
-On "no": skip the patch, mention live won't work until the user adds the allowance manually, still write `cspChecked: true` (the question's been asked).
-
-On "yes": apply the Shape-specific patch below, then write `cspChecked: true`.
-
-#### append-arrays
-
-CSP expressed as structured directive arrays. Patch mechanism: declare a dev-only array, spread it into the script-src and connect-src arrays.
-
-**Declare near the top of the file that holds the CSP arrays:**
-
-```ts
-// Dev-only allowance so impeccable live mode can load. Guarded by NODE_ENV.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? ["http://localhost:8400"] : [];
-```
-
-**Append `...__impeccableLiveDev` to the script-src and connect-src directive arrays.** Per-framework specifics:
-
-- **Next.js + monorepo helper**: edit the *app's* `next.config.*` (not the shared helper), appending to `additionalScriptSrc` and `additionalConnectSrc` passed into `createBaseNextConfig` (or equivalent). Keeps the shared package clean.
-- **SvelteKit**: edit `svelte.config.js`, appending to `kit.csp.directives['script-src']` and `kit.csp.directives['connect-src']`.
-- **Nuxt + nuxt-security**: edit `nuxt.config.*`, appending to `security.headers.contentSecurityPolicy['script-src']` and `['connect-src']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-turborepo/expected-after-patch.ts` (Next.js)
-- `tests/framework-fixtures/sveltekit-csp/expected-after-patch.js` (SvelteKit)
-
-Idempotency: if `__impeccableLiveDev` already exists in the file, the patch is already applied; skip asking and just mark `cspChecked: true`.
-
-#### append-string
-
-CSP built as a literal value string. Two-point patch: declare a dev-only string near the top, interpolate it into the CSP at the `script-src` and `connect-src` directives.
-
-```ts
-// Dev-only allowance so impeccable live mode can load.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? " http://localhost:8400" : "";
-```
-
-Then in the CSP value string:
-- `script-src 'self' 'unsafe-inline'` → `` `script-src 'self' 'unsafe-inline'${__impeccableLiveDev}` ``
-- `connect-src 'self'` → `` `connect-src 'self'${__impeccableLiveDev}` ``
-
-(Leading space on the dev string so it concatenates cleanly into the existing value. Convert the literal CSP directives into template strings as part of the edit if they aren't already.)
-
-Per-framework specifics:
-- **Next.js inline `headers()`**: edit `next.config.*`, splicing the variable into the CSP value.
-- **Nuxt `routeRules`**: edit `nuxt.config.*`, splicing into the CSP in `routeRules['/**'].headers['Content-Security-Policy']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-inline-csp/expected-after-patch.js` (Next.js)
-- `tests/framework-fixtures/nuxt-csp/expected-after-patch.ts` (Nuxt)
-
-### Troubleshooting
-
-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.
-
-Then re-run `live.mjs`.
@@ -1,109 +0,0 @@
-# Motion Design
-
-## Duration: The 100/300/500 Rule
-
-Timing matters more than easing. These durations feel right for most UI:
-
-| Duration | Use Case | Examples |
-|----------|----------|----------|
-| **100-150ms** | Instant feedback | Button press, toggle, color change |
-| **200-300ms** | State changes | Menu open, tooltip, hover states |
-| **300-500ms** | Layout changes | Accordion, modal, drawer |
-| **500-800ms** | Entrance animations | Page load, hero reveals |
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-## Easing: Pick the Right Curve
-
-**Don't use `ease`.** It's a compromise that's rarely optimal. Instead:
-
-| Curve | Use For | CSS |
-|-------|---------|-----|
-| **ease-out** | Elements entering | `cubic-bezier(0.16, 1, 0.3, 1)` |
-| **ease-in** | Elements leaving | `cubic-bezier(0.7, 0, 0.84, 0)` |
-| **ease-in-out** | State toggles (there → back) | `cubic-bezier(0.65, 0, 0.35, 1)` |
-
-**For micro-interactions, use exponential curves.** They feel natural because they mimic real physics (friction, deceleration):
-
-```css
-/* Quart out - smooth, refined (recommended default) */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1);
-
-/* Quint out - slightly more dramatic */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1);
-
-/* Expo out - snappy, confident */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1);
-```
-
-**Avoid bounce and elastic curves.** They were trendy in 2015 but now feel tacky and amateurish. Real objects don't bounce when they stop; they decelerate smoothly. Overshoot effects draw attention to the animation itself rather than the content.
-
-## Premium Motion Materials
-
-Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties: blur reveals, backdrop-filter panels, saturation or brightness shifts, shadow bloom, SVG filters, masks, clip paths, gradient-position movement, and variable font or shader-driven effects.
-
-Use the right material for the effect:
-
-- **Transform / opacity**: movement, press feedback, simple reveals, list choreography.
-- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances, atmospheric transitions.
-- **Clip path / masks**: wipes, reveals, editorial cropping, product-like transitions.
-- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state.
-- **Grid-template rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly.
-
-The hard rule is not "transform and opacity only." The hard rule is: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify in-browser that the result is smooth on the target viewports. If blur/filter makes the interaction feel significantly more premium and remains smooth, use it.
-
-## Staggered Animations
-
-Use CSS custom properties for cleaner stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"` on each item. **Cap total stagger time**: 10 items at 50ms = 500ms total. For many items, reduce per-item delay or cap staggered count.
-
-## Reduced Motion
-
-This is not optional. Vestibular disorders affect ~35% of adults over 40.
-
-```css
-/* Define animations normally */
-.card {
- animation: slide-up 500ms ease-out;
-}
-
-/* Provide alternative for reduced motion */
-@media (prefers-reduced-motion: reduce) {
- .card {
- animation: fade-in 200ms ease-out; /* Crossfade instead of motion */
- }
-}
-
-/* Or disable entirely */
-@media (prefers-reduced-motion: reduce) {
- *, *::before, *::after {
- animation-duration: 0.01ms !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**What to preserve**: Functional animations like progress bars, loading spinners (slowed down), and focus indicators should still work, just without spatial movement.
-
-## Perceived Performance
-
-**Nobody cares how fast your site is, just how fast it feels.** Perception can be as effective as actual performance.
-
-**The 80ms threshold**: Our brains buffer sensory input for ~80ms to synchronize perception. Anything under 80ms feels instant and simultaneous. This is your target for micro-interactions.
-
-**Active vs passive time**: Passive waiting (staring at a spinner) feels longer than active engagement. Strategies to shift the balance:
-
-- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening.
-- **Early completion**: Show content progressively, don't wait for everything. Video buffering, progressive images, streaming HTML.
-- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Instagram likes work offline; the UI updates instantly, syncs later. Use for low-stakes actions; avoid for payments or destructive operations.
-
-**Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances, but ease-in toward a task's end compresses perceived time.
-
-**Caution**: Too-fast responses can decrease perceived value. Users may distrust instant results for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
-
-## Performance
-
-Don't use `will-change` preemptively, only when animation is imminent (`:hover`, `.animating`). For scroll-triggered animations, use Intersection Observer instead of scroll events; unobserve after animating once. Create motion tokens for consistency (durations, easings, common transitions).
-
----
-
-**Avoid**: Animating everything (animation fatigue is real). Using >500ms for UI feedback. Ignoring `prefers-reduced-motion`. Using animation to hide slow loading.
@@ -1,234 +0,0 @@
-> **Additional context needed**: the "aha moment" you want users to reach, and users' experience level.
-
-Get users to first value as fast as possible. Onboarding's job is not to teach the product. Its job is to get people to the moment that proves the product is worth their time.
-
-## Assess Onboarding Needs
-
-Understand what users need to learn and why:
-
-1. **Identify the challenge**:
- - What are users trying to accomplish?
- - What's confusing or unclear about current experience?
- - Where do users get stuck or drop off?
- - What's the "aha moment" we want users to reach?
-
-2. **Understand the users**:
- - What's their experience level? (Beginners, power users, mixed?)
- - What's their motivation? (Excited and exploring? Required by work?)
- - What's their time commitment? (5 minutes? 30 minutes?)
- - What alternatives do they know? (Coming from competitor? New to category?)
-
-3. **Define success**:
- - What's the minimum users need to learn to be successful?
- - What's the key action we want them to take? (First project? First invite?)
- - How do we know onboarding worked? (Completion rate? Time to value?)
-
-**CRITICAL**: Onboarding should get users to value as quickly as possible, not teach everything possible.
-
-## Onboarding Principles
-
-Follow these core principles:
-
-### Show, Don't Tell
-- Demonstrate with working examples, not just descriptions
-- Provide real functionality in onboarding, not separate tutorial mode
-- Use progressive disclosure, teach one thing at a time
-
-### Make It Optional (When Possible)
-- Let experienced users skip onboarding
-- Don't block access to product
-- Provide "Skip" or "I'll explore on my own" options
-
-### Time to Value
-- Get users to their "aha moment" ASAP
-- Front-load most important concepts
-- Teach 20% that delivers 80% of value
-- Save advanced features for contextual discovery
-
-### Context Over Ceremony
-- Teach features when users need them, not upfront
-- Empty states are onboarding opportunities
-- Tooltips and hints at point of use
-
-### Respect User Intelligence
-- Don't patronize or over-explain
-- Be concise and clear
-- Assume users can figure out standard patterns
-
-## Design Onboarding Experiences
-
-Create appropriate onboarding for the context:
-
-### Initial Product Onboarding
-
-**Welcome Screen**:
-- Clear value proposition (what is this product?)
-- What users will learn/accomplish
-- Time estimate (honest about commitment)
-- Option to skip (for experienced users)
-
-**Account Setup**:
-- Minimal required information (collect more later)
-- Explain why you're asking for each piece of information
-- Smart defaults where possible
-- Social login when appropriate
-
-**Core Concept Introduction**:
-- Introduce 1-3 core concepts (not everything)
-- Use simple language and examples
-- Interactive when possible (do, don't just read)
-- Progress indication (step 1 of 3)
-
-**First Success**:
-- Guide users to accomplish something real
-- Pre-populated examples or templates
-- Celebrate completion (but don't overdo it)
-- Clear next steps
-
-### Feature Discovery & Adoption
-
-**Empty States**:
-Instead of blank space, show:
-- What will appear here (description + screenshot/illustration)
-- Why it's valuable
-- Clear CTA to create first item
-- Example or template option
-
-Example:
-```
-No projects yet
-Projects help you organize your work and collaborate with your team.
-[Create your first project] or [Start from template]
-```
-
-**Contextual Tooltips**:
-- Appear at relevant moment (first time user sees feature)
-- Point directly at relevant UI element
-- Brief explanation + benefit
-- Dismissable (with "Don't show again" option)
-- Optional "Learn more" link
-
-**Feature Announcements**:
-- Highlight new features when they're released
-- Show what's new and why it matters
-- Let users try immediately
-- Dismissable
-
-**Progressive Onboarding**:
-- Teach features when users encounter them
-- Badges or indicators on new/unused features
-- Unlock complexity gradually (don't show all options immediately)
-
-### Guided Tours & Walkthroughs
-
-**When to use**:
-- Complex interfaces with many features
-- Significant changes to existing product
-- Industry-specific tools needing domain knowledge
-
-**How to design**:
-- Spotlight specific UI elements (dim rest of page)
-- Keep steps short (3-7 steps max per tour)
-- Allow users to click through tour freely
-- Include "Skip tour" option
-- Make replayable (help menu)
-
-**Best practices**:
-- Interactive over passive (let users click real buttons)
-- Focus on workflow, not features ("Create a project" not "This is the project button")
-- Provide sample data so actions work
-
-### Interactive Tutorials
-
-**When to use**:
-- Users need hands-on practice
-- Concepts are complex or unfamiliar
-- High stakes (better to practice in safe environment)
-
-**How to design**:
-- Sandbox environment with sample data
-- Clear objectives ("Create a chart showing sales by region")
-- Step-by-step guidance
-- Validation (confirm they did it right)
-- Graduation moment (you're ready!)
-
-### Documentation & Help
-
-**In-product help**:
-- Contextual help links throughout interface
-- Keyboard shortcut reference
-- Search-able help center
-- Video tutorials for complex workflows
-
-**Help patterns**:
-- `?` icon near complex features
-- "Learn more" links in tooltips
-- Keyboard shortcut hints (`⌘K` shown on search box)
-
-## Empty State Design
-
-Every empty state needs:
-
-### What Will Be Here
-"Your recent projects will appear here"
-
-### Why It Matters
-"Projects help you organize your work and collaborate with your team"
-
-### How to Get Started
-[Create project] or [Import from template]
-
-### Visual Interest
-Illustration or icon (not just text on blank page)
-
-### Contextual Help
-"Need help getting started? [Watch 2-min tutorial]"
-
-**Empty state types**:
-- **First use**: Never used this feature (emphasize value, provide template)
-- **User cleared**: Intentionally deleted everything (light touch, easy to recreate)
-- **No results**: Search or filter returned nothing (suggest different query, clear filters)
-- **No permissions**: Can't access (explain why, how to get access)
-- **Error state**: Failed to load (explain what happened, retry option)
-
-## Implementation Patterns
-
-### Technical approaches:
-
-**Tooltip libraries**: Tippy.js, Popper.js
-**Tour libraries**: Intro.js, Shepherd.js, React Joyride
-**Modal patterns**: Focus trap, backdrop, ESC to close
-**Progress tracking**: LocalStorage for "seen" states
-**Analytics**: Track completion, drop-off points
-
-**Storage patterns**:
-```javascript
-// Track which onboarding steps user has seen
-localStorage.setItem('onboarding-completed', 'true');
-localStorage.setItem('feature-tooltip-seen-reports', 'true');
-```
-
-**IMPORTANT**: Don't show same onboarding twice (annoying). Track completion and respect dismissals.
-
-**NEVER**:
-- Force users through long onboarding before they can use product
-- Patronize users with obvious explanations
-- Show same tooltip repeatedly (respect dismissals)
-- Block all UI during tour (let users explore)
-- Create separate tutorial mode disconnected from real product
-- Overwhelm with information upfront (progressive disclosure!)
-- Hide "Skip" or make it hard to find
-- Forget about returning users (don't show initial onboarding again)
-
-## Verify Onboarding Quality
-
-Test with real users:
-
-- **Time to completion**: Can users complete onboarding quickly?
-- **Comprehension**: Do users understand after completing?
-- **Action**: Do users take desired next step?
-- **Skip rate**: Are too many users skipping? (Maybe it's too long or not valuable)
-- **Completion rate**: Are users completing? (If low, simplify)
-- **Time to value**: How long until users get first value?
-
-When users hit the aha moment fast and don't drop off, hand off to `/impeccable polish` for the final pass.
@@ -1,258 +0,0 @@
-Performance is a feature. Identify the actual bottleneck for THIS interface, fix it, then measure. Don't optimize what isn't slow.
-
-## Assess Performance Issues
-
-Understand current performance and identify problems:
-
-1. **Measure current state**:
- - **Core Web Vitals**: LCP, FID/INP, CLS scores
- - **Load time**: Time to interactive, first contentful paint
- - **Bundle size**: JavaScript, CSS, image sizes
- - **Runtime performance**: Frame rate, memory usage, CPU usage
- - **Network**: Request count, payload sizes, waterfall
-
-2. **Identify bottlenecks**:
- - What's slow? (Initial load? Interactions? Animations?)
- - What's causing it? (Large images? Expensive JavaScript? Layout thrashing?)
- - How bad is it? (Perceivable? Annoying? Blocking?)
- - Who's affected? (All users? Mobile only? Slow connections?)
-
-**CRITICAL**: Measure before and after. Premature optimization wastes time. Optimize what actually matters.
-
-## Optimization Strategy
-
-Create systematic improvement plan:
-
-### Loading Performance
-
-**Optimize Images**:
-- Use modern formats (WebP, AVIF)
-- Proper sizing (don't load 3000px image for 300px display)
-- Lazy loading for below-fold images
-- Responsive images (`srcset`, `picture` element)
-- Compress images (80-85% quality is usually imperceptible)
-- Use CDN for faster delivery
-
-```html
-<img
- src="hero.webp"
- srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
- sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
- loading="lazy"
- alt="Hero image"
-/>
-```
-
-**Reduce JavaScript Bundle**:
-- Code splitting (route-based, component-based)
-- Tree shaking (remove unused code)
-- Remove unused dependencies
-- Lazy load non-critical code
-- Use dynamic imports for large components
-
-```javascript
-// Lazy load heavy component
-const HeavyChart = lazy(() => import('./HeavyChart'));
-```
-
-**Optimize CSS**:
-- Remove unused CSS
-- Critical CSS inline, rest async
-- Minimize CSS files
-- Use CSS containment for independent regions
-
-**Optimize Fonts**:
-- Use `font-display: swap` or `optional`
-- Subset fonts (only characters you need)
-- Preload critical fonts
-- Use system fonts when appropriate
-- Limit font weights loaded
-
-```css
-@font-face {
- font-family: 'CustomFont';
- src: url('/fonts/custom.woff2') format('woff2');
- font-display: swap; /* Show fallback immediately */
- unicode-range: U+0020-007F; /* Basic Latin only */
-}
-```
-
-**Optimize Loading Strategy**:
-- Critical resources first (async/defer non-critical)
-- Preload critical assets
-- Prefetch likely next pages
-- Service worker for offline/caching
-- HTTP/2 or HTTP/3 for multiplexing
-
-### Rendering Performance
-
-**Avoid Layout Thrashing**:
-```javascript
-// ❌ Bad: Alternating reads and writes (causes reflows)
-elements.forEach(el => {
- const height = el.offsetHeight; // Read (forces layout)
- el.style.height = height * 2; // Write
-});
-
-// ✅ Good: Batch reads, then batch writes
-const heights = elements.map(el => el.offsetHeight); // All reads
-elements.forEach((el, i) => {
- el.style.height = heights[i] * 2; // All writes
-});
-```
-
-**Optimize Rendering**:
-- Use CSS `contain` property for independent regions
-- Minimize DOM depth (flatter is faster)
-- Reduce DOM size (fewer elements)
-- Use `content-visibility: auto` for long lists
-- Virtual scrolling for very long lists (react-window, react-virtualized)
-
-**Reduce Paint & Composite**:
-- Use `transform` and `opacity` for reliable movement, but allow blur, filters, masks, clip paths, shadows, and color shifts when they create meaningful polish
-- Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- Use `will-change` sparingly for known expensive operations
-- Bound expensive paint areas for blur/filter/shadow effects (smaller and isolated is faster)
-
-### Animation Performance
-
-**GPU Acceleration**:
-```css
-/* ✅ GPU-accelerated (fast) */
-.animated {
- transform: translateX(100px);
- opacity: 0.5;
-}
-
-/* ❌ CPU-bound (slow) */
-.animated {
- left: 100px;
- width: 300px;
-}
-```
-
-**Smooth 60fps**:
-- Target 16ms per frame (60fps)
-- Use `requestAnimationFrame` for JS animations
-- Debounce/throttle scroll handlers
-- Use CSS animations when possible
-- Avoid long-running JavaScript during animations
-
-**Intersection Observer**:
-```javascript
-// Efficiently detect when elements enter viewport
-const observer = new IntersectionObserver((entries) => {
- entries.forEach(entry => {
- if (entry.isIntersecting) {
- // Element is visible, lazy load or animate
- }
- });
-});
-```
-
-### React/Framework Optimization
-
-**React-specific**:
-- Use `memo()` for expensive components
-- `useMemo()` and `useCallback()` for expensive computations
-- Virtualize long lists
-- Code split routes
-- Avoid inline function creation in render
-- Use React DevTools Profiler
-
-**Framework-agnostic**:
-- Minimize re-renders
-- Debounce expensive operations
-- Memoize computed values
-- Lazy load routes and components
-
-### Network Optimization
-
-**Reduce Requests**:
-- Combine small files
-- Use SVG sprites for icons
-- Inline small critical assets
-- Remove unused third-party scripts
-
-**Optimize APIs**:
-- Use pagination (don't load everything)
-- GraphQL to request only needed fields
-- Response compression (gzip, brotli)
-- HTTP caching headers
-- CDN for static assets
-
-**Optimize for Slow Connections**:
-- Adaptive loading based on connection (navigator.connection)
-- Optimistic UI updates
-- Request prioritization
-- Progressive enhancement
-
-## Core Web Vitals Optimization
-
-### Largest Contentful Paint (LCP < 2.5s)
-- Optimize hero images
-- Inline critical CSS
-- Preload key resources
-- Use CDN
-- Server-side rendering
-
-### First Input Delay (FID < 100ms) / INP (< 200ms)
-- Break up long tasks
-- Defer non-critical JavaScript
-- Use web workers for heavy computation
-- Reduce JavaScript execution time
-
-### Cumulative Layout Shift (CLS < 0.1)
-- Set dimensions on images and videos
-- Don't inject content above existing content
-- Use `aspect-ratio` CSS property
-- Reserve space for ads/embeds
-- Avoid animations that cause layout shifts
-
-```css
-/* Reserve space for image */
-.image-container {
- aspect-ratio: 16 / 9;
-}
-```
-
-## Performance Monitoring
-
-**Tools to use**:
-- Chrome DevTools (Lighthouse, Performance panel)
-- WebPageTest
-- Core Web Vitals (Chrome UX Report)
-- Bundle analyzers (webpack-bundle-analyzer)
-- Performance monitoring (Sentry, DataDog, New Relic)
-
-**Key metrics**:
-- LCP, FID/INP, CLS (Core Web Vitals)
-- Time to Interactive (TTI)
-- First Contentful Paint (FCP)
-- Total Blocking Time (TBT)
-- Bundle size
-- Request count
-
-**IMPORTANT**: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.
-
-**NEVER**:
-- Optimize without measuring (premature optimization)
-- Sacrifice accessibility for performance
-- Break functionality while optimizing
-- Use `will-change` everywhere (creates new layers, uses memory)
-- Lazy load above-fold content
-- Optimize micro-optimizations while ignoring major issues (optimize the biggest bottleneck first)
-- Forget about mobile performance (often slower devices, slower connections)
-
-## Verify Improvements
-
-Test that optimizations worked:
-
-- **Before/after metrics**: Compare Lighthouse scores
-- **Real user monitoring**: Track improvements for real users
-- **Different devices**: Test on low-end Android, not just flagship iPhone
-- **Slow connections**: Throttle to 3G, test experience
-- **No regressions**: Ensure functionality still works
-- **User perception**: Does it *feel* faster?
-
-When the user-facing numbers move, hand off to `/impeccable polish` for the final pass.
@@ -1,130 +0,0 @@
-Start your response with:
-
-```
-──────────── ⚡ OVERDRIVE ─────────────
-》》》 Entering overdrive mode...
-```
-
-Push an interface past conventional limits. This isn't just about visual effects. It's about using the full power of the browser to make any part of an interface feel extraordinary: a table that handles a million rows, a dialog that morphs from its trigger, a form that validates in real-time with streaming feedback, a page transition that feels cinematic.
-
-**EXTRA IMPORTANT FOR THIS COMMAND**: Context determines what "extraordinary" means. A particle system on a creative portfolio is impressive. The same particle system on a settings page is embarrassing. But a settings page with instant optimistic saves and animated state transitions? That's extraordinary too. Understand the project's personality and goals before deciding what's appropriate.
-
-### Propose Before Building
-
-This command has the highest potential to misfire. Do NOT jump straight into implementation. You MUST:
-
-1. **Think through 2-3 different directions**: consider different techniques, levels of ambition, and aesthetic approaches. For each direction, briefly describe what the result would look and feel like.
-2. **ask the user directly to clarify what you cannot infer.** to present these directions and get the user's pick before writing any code. Explain trade-offs (browser support, performance cost, complexity).
-3. Only proceed with the direction the user confirms.
-
-Skipping this step risks building something embarrassing that needs to be thrown away.
-
-### Iterate with Browser Automation
-
-Technically ambitious effects almost never work on the first try. You MUST actively use browser automation tools to preview your work, visually verify the result, and iterate. Do not assume the effect looks right, check it. Expect multiple rounds of refinement. The gap between "technically works" and "looks extraordinary" is closed through visual iteration, not code alone.
-
----
-
-## Assess What "Extraordinary" Means Here
-
-The right kind of technical ambition depends entirely on what you're working with. Before choosing a technique, ask: **what would make a user of THIS specific interface say "wow, that's nice"?**
-
-### For visual/marketing surfaces
-Pages, hero sections, landing pages, portfolios: the "wow" is often sensory: a scroll-driven reveal, a shader background, a cinematic page transition, generative art that responds to the cursor.
-
-### For functional UI
-Tables, forms, dialogs, navigation: the "wow" is in how it FEELS: a dialog that morphs from the button that triggered it via View Transitions, a data table that renders 100k rows at 60fps via virtual scrolling, a form with streaming validation that feels instant, drag-and-drop with spring physics.
-
-### For performance-critical UI
-The "wow" is invisible but felt: a search that filters 50k items without a flicker, a complex form that never blocks the main thread, an image editor that processes in near-real-time. The interface just never hesitates.
-
-### For data-heavy interfaces
-Charts and dashboards: the "wow" is in fluidity: GPU-accelerated rendering via Canvas/WebGL for massive datasets, animated transitions between data states, force-directed graph layouts that settle naturally.
-
-**The common thread**: something about the implementation goes beyond what users expect from a web interface. The technique serves the experience, not the other way around.
-
-## The Toolkit
-
-Organized by what you're trying to achieve, not by technology name.
-
-### Make transitions feel cinematic
-- **View Transitions API** (same-document: all browsers; cross-document: no Firefox): shared element morphing between states. A list item expanding into a detail page. A button morphing into a dialog. This is the closest thing to native FLIP animations.
-- **`@starting-style`** (all browsers): animate elements from `display: none` to visible with CSS only, including entry keyframes
-- **Spring physics**: natural motion with mass, tension, and damping instead of cubic-bezier. Libraries: motion (formerly Framer Motion), GSAP, or roll your own spring solver.
-
-### Tie animation to scroll position
-- **Scroll-driven animations** (`animation-timeline: scroll()`): CSS-only, no JS. Parallax, progress bars, reveal sequences all driven by scroll position. (Chrome/Edge/Safari; Firefox: flag only; always provide a static fallback)
-
-### Render beyond CSS
-- **WebGL** (all browsers): shader effects, post-processing, particle systems. Libraries: Three.js, OGL (lightweight), regl. Use for effects CSS can't express.
-- **WebGPU** (Chrome/Edge; Safari partial; Firefox: flag only): next-gen GPU compute. More powerful than WebGL but limited browser support. Always fall back to WebGL2.
-- **Canvas 2D / OffscreenCanvas**: custom rendering, pixel manipulation, or moving heavy rendering off the main thread entirely via Web Workers + OffscreenCanvas.
-- **SVG filter chains**: displacement maps, turbulence, morphology for organic distortion effects. CSS-animatable.
-
-### Make data feel alive
-- **Virtual scrolling**: render only visible rows for tables/lists with tens of thousands of items. No library required for simple cases; TanStack Virtual for complex ones.
-- **GPU-accelerated charts**: Canvas or WebGL-rendered data visualization for datasets too large for SVG/DOM. Libraries: deck.gl, regl-based custom renderers.
-- **Animated data transitions**: morph between chart states rather than replacing. D3's `transition()` or View Transitions for DOM-based charts.
-
-### Animate complex properties
-- **`@property`** (all browsers): register custom CSS properties with types, enabling animation of gradients, colors, and complex values that CSS can't normally interpolate.
-- **Web Animations API** (all browsers): JavaScript-driven animations with the performance of CSS. Composable, cancellable, reversible. The foundation for complex choreography.
-
-### Push performance boundaries
-- **Web Workers**: move computation off the main thread. Heavy data processing, image manipulation, search indexing: anything that would cause jank.
-- **OffscreenCanvas**: render in a Worker thread. The main thread stays free while complex visuals render in the background.
-- **WASM**: near-native performance for computation-heavy features. Image processing, physics simulations, codecs.
-
-### Interact with the device
-- **Web Audio API**: spatial audio, audio-reactive visualizations, sonic feedback. Requires user gesture to start.
-- **Device APIs**: orientation, ambient light, geolocation. Use sparingly and always with user permission.
-
-**NOTE**: This command is about enhancing how an interface FEELS, not changing what a product DOES. Adding real-time collaboration, offline support, or new backend capabilities are product decisions, not UI enhancements. Focus on making existing features feel extraordinary.
-
-## Implement with Discipline
-
-### Progressive enhancement is non-negotiable
-
-Every technique must degrade gracefully. The experience without the enhancement must still be good.
-
-```css
-@supports (animation-timeline: scroll()) {
- .hero { animation-timeline: scroll(); }
-}
-```
-
-```javascript
-if ('gpu' in navigator) { /* WebGPU */ }
-else if (canvas.getContext('webgl2')) { /* WebGL2 fallback */ }
-/* CSS-only fallback must still look good */
-```
-
-### Performance rules
-
-- Target 60fps. If dropping below 50, simplify.
-- Respect `prefers-reduced-motion`, always. Provide a beautiful static alternative.
-- Lazy-initialize heavy resources (WebGL contexts, WASM modules) only when near viewport.
-- Pause off-screen rendering. Kill what you can't see.
-- Test on real mid-range devices, not just your development machine.
-
-### Polish is the difference
-
-The gap between "cool" and "extraordinary" is in the last 20% of refinement: the easing curve on a spring animation, the timing offset in a staggered reveal, the subtle secondary motion that makes a transition feel physical. Don't ship the first version that works; ship the version that feels inevitable.
-
-**NEVER**:
-- Ignore `prefers-reduced-motion`. This is an accessibility requirement, not a suggestion
-- Ship effects that cause jank on mid-range devices
-- Use bleeding-edge APIs without a functional fallback
-- Add sound without explicit user opt-in
-- Use technical ambition to mask weak design fundamentals; fix those first with other commands
-- Layer multiple competing extraordinary moments. Focus creates impact, excess creates noise
-
-## Verify the Result
-
-- **The wow test**: Show it to someone who hasn't seen it. Do they react?
-- **The removal test**: Take it away. Does the experience feel diminished, or does nobody notice?
-- **The device test**: Run it on a phone, a tablet, a Chromebook. Still smooth?
-- **The accessibility test**: Enable reduced motion. Still beautiful?
-- **The context test**: Does this make sense for THIS brand and audience?
-
-"Technically extraordinary" isn't about using the newest API. It's about making an interface do something users didn't think a website could do.
@@ -1,179 +0,0 @@
-# Persona-Based Design Testing
-
-Test the interface through the eyes of 5 distinct user archetypes. Each persona exposes different failure modes that a single "design director" perspective would miss.
-
-**How to use**: Select 2–3 personas most relevant to the interface being critiqued. Walk through the primary user action as each persona. Report specific red flags, not generic concerns.
-
----
-
-## 1. Impatient Power User: "Alex"
-
-
-**Profile**: Expert with similar products. Expects efficiency, hates hand-holding. Will find shortcuts or leave.
-
-**Behaviors**:
-- Skips all onboarding and instructions
-- Looks for keyboard shortcuts immediately
-- Tries to bulk-select, batch-edit, and automate
-- Gets frustrated by required steps that feel unnecessary
-- Abandons if anything feels slow or patronizing
-
-**Test Questions**:
-- Can Alex complete the core task in under 60 seconds?
-- Are there keyboard shortcuts for common actions?
-- Can onboarding be skipped entirely?
-- Do modals have keyboard dismiss (Esc)?
-- Is there a "power user" path (shortcuts, bulk actions)?
-
-**Red Flags** (report these specifically):
-- Forced tutorials or unskippable onboarding
-- No keyboard navigation for primary actions
-- Slow animations that can't be skipped
-- One-item-at-a-time workflows where batch would be natural
-- Redundant confirmation steps for low-risk actions
-
----
-
-## 2. Confused First-Timer: "Jordan"
-
-**Profile**: Never used this type of product. Needs guidance at every step. Will abandon rather than figure it out.
-
-**Behaviors**:
-- Reads all instructions carefully
-- Hesitates before clicking anything unfamiliar
-- Looks for help or support constantly
-- Misunderstands jargon and abbreviations
-- Takes the most literal interpretation of any label
-
-**Test Questions**:
-- Is the first action obviously clear within 5 seconds?
-- Are all icons labeled with text?
-- Is there contextual help at decision points?
-- Does terminology assume prior knowledge?
-- Is there a clear "back" or "undo" at every step?
-
-**Red Flags** (report these specifically):
-- Icon-only navigation with no labels
-- Technical jargon without explanation
-- No visible help option or guidance
-- Ambiguous next steps after completing an action
-- No confirmation that an action succeeded
-
----
-
-## 3. Accessibility-Dependent User: "Sam"
-
-**Profile**: Uses screen reader (VoiceOver/NVDA), keyboard-only navigation. May have low vision, motor impairment, or cognitive differences.
-
-**Behaviors**:
-- Tabs through the interface linearly
-- Relies on ARIA labels and heading structure
-- Cannot see hover states or visual-only indicators
-- Needs adequate color contrast (4.5:1 minimum)
-- May use browser zoom up to 200%
-
-**Test Questions**:
-- Can the entire primary flow be completed keyboard-only?
-- Are all interactive elements focusable with visible focus indicators?
-- Do images have meaningful alt text?
-- Is color contrast WCAG AA compliant (4.5:1 for text)?
-- Does the screen reader announce state changes (loading, success, errors)?
-
-**Red Flags** (report these specifically):
-- Click-only interactions with no keyboard alternative
-- Missing or invisible focus indicators
-- Meaning conveyed by color alone (red = error, green = success)
-- Unlabeled form fields or buttons
-- Time-limited actions without extension option
-- Custom components that break screen reader flow
-
----
-
-## 4. Deliberate Stress Tester: "Riley"
-
-**Profile**: Methodical user who pushes interfaces beyond the happy path. Tests edge cases, tries unexpected inputs, and probes for gaps in the experience.
-
-**Behaviors**:
-- Tests edge cases intentionally (empty states, long strings, special characters)
-- Submits forms with unexpected data (emoji, RTL text, very long values)
-- Tries to break workflows by navigating backwards, refreshing mid-flow, or opening in multiple tabs
-- Looks for inconsistencies between what the UI promises and what actually happens
-- Documents problems methodically
-
-**Test Questions**:
-- What happens at the edges (0 items, 1000 items, very long text)?
-- Do error states recover gracefully or leave the UI in a broken state?
-- What happens on refresh mid-workflow? Is state preserved?
-- Are there features that appear to work but produce broken results?
-- How does the UI handle unexpected input (emoji, special chars, paste from Excel)?
-
-**Red Flags** (report these specifically):
-- Features that appear to work but silently fail or produce wrong results
-- Error handling that exposes technical details or leaves UI in a broken state
-- Empty states that show nothing useful ("No results" with no guidance)
-- Workflows that lose user data on refresh or navigation
-- Inconsistent behavior between similar interactions in different parts of the UI
-
----
-
-## 5. Distracted Mobile User: "Casey"
-
-**Profile**: Using phone one-handed on the go. Frequently interrupted. Possibly on a slow connection.
-
-**Behaviors**:
-- Uses thumb only; prefers bottom-of-screen actions
-- Gets interrupted mid-flow and returns later
-- Switches between apps frequently
-- Has limited attention span and low patience
-- Types as little as possible, prefers taps and selections
-
-**Test Questions**:
-- Are primary actions in the thumb zone (bottom half of screen)?
-- Is state preserved if the user leaves and returns?
-- Does it work on slow connections (3G)?
-- Can forms use autocomplete and smart defaults?
-- Are touch targets at least 44×44pt?
-
-**Red Flags** (report these specifically):
-- Important actions positioned at the top of the screen (unreachable by thumb)
-- No state persistence; progress lost on tab switch or interruption
-- Large text inputs required where selection would work
-- Heavy assets loading on every page (no lazy loading)
-- Tiny tap targets or targets too close together
-
----
-
-## Selecting Personas
-
-Choose personas based on the interface type:
-
-| Interface Type | Primary Personas | Why |
-|---------------|-----------------|-----|
-| Landing page / marketing | Jordan, Riley, Casey | First impressions, trust, mobile |
-| Dashboard / admin | Alex, Sam | Power users, accessibility |
-| E-commerce / checkout | Casey, Riley, Jordan | Mobile, edge cases, clarity |
-| Onboarding flow | Jordan, Casey | Confusion, interruption |
-| Data-heavy / analytics | Alex, Sam | Efficiency, keyboard nav |
-| Form-heavy / wizard | Jordan, Sam, Casey | Clarity, accessibility, mobile |
-
----
-
-## Project-Specific Personas
-
-If `.cursorrules` contains a `## Design Context` section (generated by `impeccable teach`), derive 1–2 additional personas from the audience and brand information:
-
-1. Read the target audience description
-2. Identify the primary user archetype not covered by the 5 predefined personas
-3. Create a persona following this template:
-
-```
-### [Role]: "[Name]"
-
-**Profile**: [2-3 key characteristics derived from Design Context]
-
-**Behaviors**: [3-4 specific behaviors based on the described audience]
-
-**Red Flags**: [3-4 things that would alienate this specific user type]
-```
-
-Only generate project-specific personas when real Design Context data is available. Don't invent audience details; use the 5 predefined personas when no context exists.
@@ -1,242 +0,0 @@
-> **Additional context needed**: quality bar (MVP vs flagship).
-
-Perform a meticulous final pass to catch all the small details that separate good work from great work. The difference between shipped and polished.
-
-Detector and automated QA output are defect evidence only. A clean script result is never proof that the design is strong; gather browser evidence and inspect the real interaction path.
-
-## Design System Discovery
-
-Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
-
-1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
-2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
-3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category: patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
-
-If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask. Never guess at design system principles.**
-
-## Pre-Polish Assessment
-
-Understand the current state and goals before touching anything:
-
-1. **Review completeness**:
- - Is it functionally complete?
- - Are there known issues to preserve (mark with TODOs)?
- - What's the quality bar? (MVP vs flagship feature?)
- - When does it ship? (How much time for polish?)
-
-2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish; a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
-
-3. **Identify polish areas**:
- - Visual inconsistencies
- - Spacing and alignment issues
- - Interaction state gaps
- - Copy inconsistencies
- - Edge cases and error states
- - Loading and transition smoothness
- - Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
-
-4. **Pull in any prior critique** (optional signal): If `/impeccable critique` has been run on the same target, its priority issues are a useful prior for what to address first. Resolve the target to a file path or URL, then:
- ```bash
- slug=$(node .cursor/skills/impeccable/scripts/critique-storage.mjs slug "<resolved>")
- node .cursor/skills/impeccable/scripts/critique-storage.mjs latest "$slug"
- ```
- Exit 0 with body = found; fold the P0/P1 items into your polish list and mention the snapshot path so the user sees what you read. Exit 2 = no snapshot, continue without it. The critique is one input among many. Do your own pass either way.
-
-5. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent; never perfect one corner while leaving another rough.
-
-**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
-
-## Polish Systematically
-
-Work through these dimensions methodically:
-
-### Visual Alignment & Spacing
-
-- **Pixel-perfect alignment**: Everything lines up to grid
-- **Consistent spacing**: All gaps use spacing scale (no random 13px gaps)
-- **Optical alignment**: Adjust for visual weight (icons may need offset for optical centering)
-- **Responsive consistency**: Spacing and alignment work at all breakpoints
-- **Grid adherence**: Elements snap to baseline grid
-
-**Check**:
-- Enable grid overlay and verify alignment
-- Check spacing with browser inspector
-- Test at multiple viewport sizes
-- Look for elements that "feel" off
-
-### Information Architecture & Flow
-
-Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
-
-- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
-- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere: modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
-- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
-- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
-- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
-
-### Typography Refinement
-
-- **Hierarchy consistency**: Same elements use same sizes/weights throughout
-- **Line length**: 45-75 characters for body text
-- **Line height**: Appropriate for font size and context
-- **Widows & orphans**: No single words on last line
-- **Hyphenation**: Appropriate for language and column width
-- **Kerning**: Adjust letter spacing where needed (especially headlines)
-- **Font loading**: No FOUT/FOIT flashes
-
-### Color & Contrast
-
-- **Contrast ratios**: All text meets WCAG standards
-- **Consistent token usage**: No hard-coded colors, all use design tokens
-- **Theme consistency**: Works in all theme variants
-- **Color meaning**: Same colors mean same things throughout
-- **Accessible focus**: Focus indicators visible with sufficient contrast
-- **Tinted neutrals**: No pure gray or pure black; add subtle color tint (0.01 chroma)
-- **Gray on color**: Never put gray text on colored backgrounds; use a shade of that color or transparency
-
-### Interaction States
-
-Every interactive element needs all states:
-
-- **Default**: Resting state
-- **Hover**: Subtle feedback (color, scale, shadow)
-- **Focus**: Keyboard focus indicator (never remove without replacement)
-- **Active**: Click/tap feedback
-- **Disabled**: Clearly non-interactive
-- **Loading**: Async action feedback
-- **Error**: Validation or error state
-- **Success**: Successful completion
-
-**Missing states create confusion and broken experiences**.
-
-### Micro-interactions & Transitions
-
-- **Smooth transitions**: All state changes animated appropriately (150-300ms)
-- **Consistent easing**: Use ease-out-quart/quint/expo for natural deceleration. Never bounce or elastic; they feel dated.
-- **No jank**: Smooth animations; use atmospheric blur/filter/mask/shadow effects when they add polish, but bound expensive paint areas and avoid casual layout-property animation
-- **Appropriate motion**: Motion serves purpose, not decoration
-- **Reduced motion**: Respects `prefers-reduced-motion`
-
-### Content & Copy
-
-- **Consistent terminology**: Same things called same names throughout
-- **Consistent capitalization**: Title Case vs Sentence case applied consistently
-- **Grammar & spelling**: No typos
-- **Appropriate length**: Not too wordy, not too terse
-- **Punctuation consistency**: Periods on sentences, not on labels (unless all labels have them)
-
-### Icons & Images
-
-- **Consistent style**: All icons from same family or matching style
-- **Appropriate sizing**: Icons sized consistently for context
-- **Proper alignment**: Icons align with adjacent text optically
-- **Alt text**: All images have descriptive alt text
-- **Loading states**: Images don't cause layout shift, proper aspect ratios
-- **Retina support**: 2x assets for high-DPI screens
-
-### Forms & Inputs
-
-- **Label consistency**: All inputs properly labeled
-- **Required indicators**: Clear and consistent
-- **Error messages**: Helpful and consistent
-- **Tab order**: Logical keyboard navigation
-- **Auto-focus**: Appropriate (don't overuse)
-- **Validation timing**: Consistent (on blur vs on submit)
-
-### Edge Cases & Error States
-
-- **Loading states**: All async actions have loading feedback
-- **Empty states**: Helpful empty states, not just blank space
-- **Error states**: Clear error messages with recovery paths
-- **Success states**: Confirmation of successful actions
-- **Long content**: Handles very long names, descriptions, etc.
-- **No content**: Handles missing data gracefully
-- **Offline**: Appropriate offline handling (if applicable)
-
-### Responsiveness
-
-- **All breakpoints**: Test mobile, tablet, desktop
-- **Touch targets**: 44x44px minimum on touch devices
-- **Readable text**: No text smaller than 14px on mobile
-- **No horizontal scroll**: Content fits viewport
-- **Appropriate reflow**: Content adapts logically
-
-### Performance
-
-- **Fast initial load**: Optimize critical path
-- **No layout shift**: Elements don't jump after load (CLS)
-- **Smooth interactions**: No lag or jank
-- **Optimized images**: Appropriate formats and sizes
-- **Lazy loading**: Off-screen content loads lazily
-
-### Code Quality
-
-- **Remove console logs**: No debug logging in production
-- **Remove commented code**: Clean up dead code
-- **Remove unused imports**: Clean up unused dependencies
-- **Consistent naming**: Variables and functions follow conventions
-- **Type safety**: No TypeScript `any` or ignored errors
-- **Accessibility**: Proper ARIA labels and semantic HTML
-
-## Polish Checklist
-
-Go through systematically:
-
-- [ ] Aligned to the design system (drift named and resolved by root cause)
-- [ ] Information architecture and flow shape match neighboring features
-- [ ] Visual alignment perfect at all breakpoints
-- [ ] Spacing uses design tokens consistently
-- [ ] Typography hierarchy consistent
-- [ ] All interactive states implemented
-- [ ] All transitions smooth (60fps)
-- [ ] Copy is consistent and polished
-- [ ] Icons are consistent and properly sized
-- [ ] All forms properly labeled and validated
-- [ ] Error states are helpful
-- [ ] Loading states are clear
-- [ ] Empty states are welcoming
-- [ ] Touch targets are 44x44px minimum
-- [ ] Contrast ratios meet WCAG AA
-- [ ] Keyboard navigation works
-- [ ] Focus indicators visible
-- [ ] No console errors or warnings
-- [ ] No layout shift on load
-- [ ] Works in all supported browsers
-- [ ] Respects reduced motion preference
-- [ ] Code is clean (no TODOs, console.logs, commented code)
-
-**IMPORTANT**: Polish is about details. Zoom in. Squint at it. Use it yourself. The little things add up.
-
-Sweat the details. Zoom in until the alignment is right and the spacing reads as deliberate. Then ship.
-
-**NEVER**:
-- Polish before it's functionally complete
-- Polish without aligning to the design system; that's decoration on drift
-- Guess at design system principles instead of asking when something is ambiguous
-- Spend hours on polish if it ships in 30 minutes (triage)
-- Introduce bugs while polishing (test thoroughly)
-- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
-- Perfect one thing while leaving others rough (consistent quality level)
-- Create new one-off components when design system equivalents exist
-- Hard-code values that should use design tokens
-- Introduce new patterns or flows that diverge from established ones
-
-## Final Verification
-
-Before marking as done:
-
-- **Use it yourself**: Actually interact with the feature.
-- **Test on real devices**: Not just browser DevTools.
-- **Ask someone else to review**: Fresh eyes catch things.
-- **Compare to design**: Match intended design.
-- **Check all states**: Don't just test happy path.
-- **Treat automation carefully**: Run detector or QA commands when they are available and relevant, fix their defects, but never cite a clean result as proof that the work is polished.
-
-## Clean Up
-
-After polishing, ensure code quality:
-
-- **Replace custom implementations**: If the design system provides a component you reimplemented, switch to the shared version.
-- **Remove orphaned code**: Delete unused styles, components, or files made obsolete by polish.
-- **Consolidate tokens**: If you introduced new values, check whether they should be tokens.
-- **Verify DRYness**: Look for duplication introduced during polishing and consolidate.
@@ -1,62 +0,0 @@
-# Product register
-
-When design SERVES the product: app UIs, admin dashboards, settings panels, data tables, tools, authenticated surfaces, anything where the user is in a task.
-
-## The product slop test
-
-Not "would someone say AI made this." Familiarity is often a feature here. The test is: would a user fluent in the category's best tools (Linear, Figma, Notion, Raycast, Stripe come to mind) sit down and trust this interface, or pause at every subtly-off component?
-
-Product UI's failure mode isn't flatness, it's strangeness without purpose: over-decorated buttons, mismatched form controls, gratuitous motion, display fonts where labels should be, invented affordances for standard tasks. The bar is earned familiarity. The tool should disappear into the task.
-
-## Typography
-
-- **System fonts are legitimate.** `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` gives you native feel on every platform. Inter is the common cross-platform default for a reason.
-- **One family is often right.** Product UIs don't need display/body pairing. A well-tuned sans carries headings, buttons, labels, body, data.
-- **Fixed rem scale, not fluid.** Clamp-sized headings don't serve product UI. Users view at consistent DPI, and a fluid h1 that shrinks in a sidebar looks worse, not better.
-- **Tighter scale ratio.** 1.125–1.2 between steps is typical. More type elements here than on brand surfaces; exaggerated contrast creates noise.
-- **Line length still applies for prose** (65–75ch). Data and compact UI can run denser; tables at 120ch+ are fine.
-
-## Color
-
-Product defaults to Restrained. A single surface can earn Committed (a dashboard where one category color carries a report, an onboarding flow with a drenched welcome screen), but Restrained is the floor.
-
-- State-rich semantic vocabulary: hover, focus, active, disabled, selected, loading, error, warning, success, info. Standardize these.
-- Accent color used for primary actions, current selection, and state indicators only, not decoration.
-- A second neutral layer for sidebars, toolbars, and panels (slightly cooler or warmer than the content surface).
-
-## Layout
-
-- Predictable grids. Consistency IS an affordance; users navigate faster when the structure is expected.
-- Familiar patterns are features. Standard navigation (top bar, side nav), breadcrumbs, tabs, and form layouts have established user expectations. Don't reinvent for flavor.
-- Responsive behavior is structural (collapse sidebar, responsive table, breakpoint-driven columns), not fluid typography.
-
-## Components
-
-Every interactive component has: default, hover, focus, active, disabled, loading, error. Don't ship with half of these.
-
-- Skeleton states for loading, not spinners in the middle of content.
-- Empty states that teach the interface, not "nothing here."
-- Consistent affordances across the surface. Same button shape. Same form-control vocabulary. Same icon style.
-
-## Motion
-
-- 150–250 ms on most transitions. Users are in flow; don't make them wait for choreography.
-- Motion conveys state, not decoration. State change, feedback, loading, reveal: nothing else.
-- No orchestrated page-load sequences. Product loads into a task; users don't want to watch it load.
-
-## Product bans (on top of the shared absolute bans)
-
-- Decorative motion that doesn't convey state.
-- Inconsistent component vocabulary across screens. If the "save" button looks different in two places, one is wrong.
-- Display fonts in UI labels, buttons, data.
-- Reinventing standard affordances for flavor (custom scrollbars, weird form controls, non-standard modals).
-- Heavy color or full-saturation accents on inactive states.
-
-## Product permissions
-
-Product can afford things brand surfaces can't.
-
-- System fonts and familiar sans defaults (Inter, SF Pro, system-ui stacks).
-- Standard navigation patterns: top bar + side nav, breadcrumbs, tabs, command palettes.
-- Density. Tables with many rows, panels with many labels, dense information when users need it.
-- Consistency over surprise. The same visual vocabulary screen to screen is a virtue; delight is saved for moments, not pages.
@@ -1,99 +0,0 @@
-Quiet design is harder than bold design. Subtlety needs precision. Reduce visual intensity in designs that are too loud, aggressive, or overstimulating without losing personality or making the result generic.
-
----
-
-## Register
-
-Brand: "quieter" means more restrained palette, more whitespace, more typographic air. Drama is reduced, not eliminated; the POV stays intact.
-
-Product: "quieter" means reducing visual noise. Fewer background accents, flatter cards, less color, less motion. The tool should disappear more completely into the task.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too intense:
-
-1. **Identify intensity sources**:
- - **Color saturation**: Overly bright or saturated colors
- - **Contrast extremes**: Too much high-contrast juxtaposition
- - **Visual weight**: Too many bold, heavy elements competing
- - **Animation excess**: Too much motion or overly dramatic effects
- - **Complexity**: Too many visual elements, patterns, or decorations
- - **Scale**: Everything is large and loud with no hierarchy
-
-2. **Understand the context**:
- - What's the purpose? (Marketing vs tool vs reading experience)
- - Who's the audience? (Some contexts need energy)
- - What's working? (Don't throw away good ideas)
- - What's the core message? (Preserve what matters)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Quieter" doesn't mean boring or generic. It means refined and easier on the eyes. Think luxury, not laziness.
-
-## Plan Refinement
-
-Create a strategy to reduce intensity while maintaining impact:
-
-- **Color approach**: Desaturate or shift to more restrained tones?
-- **Hierarchy approach**: Which elements should stay bold (very few), which should recede?
-- **Simplification approach**: What can be removed entirely?
-- **Sophistication approach**: How can we signal quality through restraint?
-
-**IMPORTANT**: Subtlety requires precision. Quiet without intent collapses to generic.
-
-## Refine the Design
-
-Systematically reduce intensity across these dimensions:
-
-### Color Refinement
-- **Reduce saturation**: Shift from fully saturated to 70-85% saturation
-- **Soften palette**: Replace bright colors with muted tones
-- **Reduce color variety**: Use fewer colors more thoughtfully
-- **Neutral dominance**: Let neutrals do more work, use color as accent (10% rule)
-- **Gentler contrasts**: High contrast only where it matters most
-- **Tinted grays**: Use warm or cool tinted grays instead of pure gray. Adds depth without loudness
-- **Never gray on color**: If you have gray text on a colored background, use a darker shade of that color or transparency instead
-
-### Visual Weight Reduction
-- **Typography**: Reduce font weights (900 → 600, 700 → 500), decrease sizes where appropriate
-- **Hierarchy through subtlety**: Use weight, size, and space instead of color and boldness
-- **White space**: Increase breathing room, reduce density
-- **Borders & lines**: Reduce thickness, decrease opacity, or remove entirely
-
-### Simplification
-- **Remove decorative elements**: Gradients, shadows, patterns, textures that don't serve purpose
-- **Simplify shapes**: Reduce border radius extremes, simplify custom shapes
-- **Reduce layering**: Flatten visual hierarchy where possible
-- **Clean up effects**: Reduce or remove blur effects, glows, multiple shadows
-
-### Motion Reduction
-- **Reduce animation intensity**: Shorter distances (10-20px instead of 40px), gentler easing
-- **Remove decorative animations**: Keep functional motion, remove flourishes
-- **Subtle micro-interactions**: Replace dramatic effects with gentle feedback
-- **Refined easing**: Use ease-out-quart for smooth, understated motion. Never bounce or elastic
-- **Remove animations entirely** if they're not serving a clear purpose
-
-### Composition Refinement
-- **Reduce scale jumps**: Smaller contrast between sizes creates calmer feeling
-- **Align to grid**: Bring rogue elements back into systematic alignment
-- **Even out spacing**: Replace extreme spacing variations with consistent rhythm
-
-**NEVER**:
-- Make everything the same size/weight (hierarchy still matters)
-- Remove all color (quiet ≠ grayscale)
-- Eliminate all personality (maintain character through refinement)
-- Sacrifice usability for aesthetics (functional elements still need clear affordances)
-- Make everything small and light (some anchors needed)
-
-## Verify Quality
-
-Ensure refinement maintains quality:
-
-- **Still functional**: Can users still accomplish tasks easily?
-- **Still distinctive**: Does it have character, or is it generic now?
-- **Better reading**: Is text easier to read for extended periods?
-- **Restrained, not absent**: Does the POV survive the cuts?
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,114 +0,0 @@
-# Responsive Design
-
-## Mobile-First: Write It Right
-
-Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
-
-## Breakpoints: Content-Driven
-
-Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
-
-## Detect Input Method, Not Just Screen Size
-
-**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
-
-```css
-/* Fine pointer (mouse, trackpad) */
-@media (pointer: fine) {
- .button { padding: 8px 16px; }
-}
-
-/* Coarse pointer (touch, stylus) */
-@media (pointer: coarse) {
- .button { padding: 12px 20px; } /* Larger touch target */
-}
-
-/* Device supports hover */
-@media (hover: hover) {
- .card:hover { transform: translateY(-2px); }
-}
-
-/* Device doesn't support hover (touch) */
-@media (hover: none) {
- .card { /* No hover state - use active instead */ }
-}
-```
-
-**Critical**: Don't rely on hover for functionality. Touch users can't hover.
-
-## Safe Areas: Handle the Notch
-
-Modern phones have notches, rounded corners, and home indicators. Use `env()`:
-
-```css
-body {
- padding-top: env(safe-area-inset-top);
- padding-bottom: env(safe-area-inset-bottom);
- padding-left: env(safe-area-inset-left);
- padding-right: env(safe-area-inset-right);
-}
-
-/* With fallback */
-.footer {
- padding-bottom: max(1rem, env(safe-area-inset-bottom));
-}
-```
-
-**Enable viewport-fit** in your meta tag:
-```html
-<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
-```
-
-## Responsive Images: Get It Right
-
-### srcset with Width Descriptors
-
-```html
-<img
- src="hero-800.jpg"
- srcset="
- hero-400.jpg 400w,
- hero-800.jpg 800w,
- hero-1200.jpg 1200w
- "
- sizes="(max-width: 768px) 100vw, 50vw"
- alt="Hero image"
->
-```
-
-**How it works**:
-- `srcset` lists available images with their actual widths (`w` descriptors)
-- `sizes` tells the browser how wide the image will display
-- Browser picks the best file based on viewport width AND device pixel ratio
-
-### Picture Element for Art Direction
-
-When you need different crops/compositions (not just resolutions):
-
-```html
-<picture>
- <source media="(min-width: 768px)" srcset="wide.jpg">
- <source media="(max-width: 767px)" srcset="tall.jpg">
- <img src="fallback.jpg" alt="...">
-</picture>
-```
-
-## Layout Adaptation Patterns
-
-**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
-
-## Testing: Don't Trust DevTools Alone
-
-DevTools device emulation is useful for layout but misses:
-
-- Actual touch interactions
-- Real CPU/memory constraints
-- Network latency patterns
-- Font rendering differences
-- Browser chrome/keyboard appearances
-
-**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
-
----
-
-**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
@@ -1,165 +0,0 @@
-Shape the UX and UI for a feature before any code is written. This command produces a **design brief**: a structured artifact that guides implementation through discovery, not guesswork.
-
-**Scope**: Design planning only. This command does NOT write code. It produces the thinking that makes code good.
-
-**Output**: A design brief that can be handed off to /impeccable craft, or directly to /impeccable for freeform implementation. When visual direction probes are used, the images are supporting artifacts, not the primary output.
-
-## Philosophy
-
-Most AI-generated UIs fail not because of bad code, but because of skipped thinking. They jump to "here's a card grid" without asking "what is the user trying to accomplish?" This command inverts that: understand deeply first, so implementation is precise.
-
-## Phase 1: Discovery Interview
-
-**Do NOT write any code or make any design decisions during this phase.** Your only job is to understand the feature deeply enough to make excellent design decisions later.
-
-This is a required interaction, not optional guidance. Ask these questions in conversation, adapting based on answers. Don't dump them all at once; have a natural dialogue. ask the user directly to clarify what you cannot infer.
-
-### Interview cadence
-
-Discovery includes at least one user-answer round unless PRODUCT.md, DESIGN.md, or an already-confirmed brief directly answers the needed inputs. With a sparse prompt, do **not** synthesize a complete brief for confirmation on the first response.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Treat PRODUCT.md and DESIGN.md as anchors; they reduce repeated questions but do **not** replace shape for craft. Shape is task-specific.
-- One round is the default. Add a second only if the first answers leave material gaps. Don't run a second round just to feel thorough.
-- Round 1 should clarify purpose, audience/context, content/scope, and (for brand) visual direction.
-- Round 2, when needed, fills in whatever's still genuinely missing.
-
-**Assert-then-confirm, not menu-with-escape.** When PRODUCT.md and the user's prompt make one option obvious, name it and ask the user to confirm or override. Don't enumerate "Restrained / Committed / Or something else?" as a real choice; "This reads as Restrained, confirm?" beats a four-option menu when the answer is already clear.
-
-### Purpose & Context
-- What is this feature for? What problem does it solve?
-- Who specifically will use it? (Not "users"; be specific: role, context, frequency)
-- What does success look like? How will you know this feature is working?
-- What's the user's state of mind when they reach this feature? (Rushed? Exploring? Anxious? Focused?)
-
-### Content & Data
-- What content or data does this feature display or collect?
-- What are the realistic ranges? (Minimum, typical, maximum, e.g., 0 items, 5 items, 500 items)
-- What are the edge cases? (Empty state, error state, first-time use, power user)
-- Is any content dynamic? What changes and how often?
-- What visual assets are real content here? Note required images, product shots, illustrations, maps, textures, diagrams, generated objects, or existing project assets.
-
-### Design Direction
-
-Force a visual decision on three fronts. Skip anything PRODUCT.md or DESIGN.md already answers; ask only what's missing.
-
-- **Color strategy for this surface.** Pick one: Restrained / Committed / Full palette / Drenched. Can override the project default if the surface earns it (e.g. a drenched hero inside an otherwise Restrained product).
-- **Theme via scene sentence.** Write one sentence of physical context for this surface: who uses it, where, under what ambient light, in what mood. The sentence forces dark vs light. If it doesn't, add detail until it does.
-- **Two or three named anchor references.** Specific products, brands, objects. Not adjectives like "modern" or "clean."
-
-### Scope
-
-Always ask. Sketch quality and shipped quality are different outputs; don't guess between them.
-
-- **Fidelity.** Sketch / mid-fi / high-fi / production-ready?
-- **Breadth.** One screen / a flow / a whole surface?
-- **Interactivity.** Static visual / interactive prototype / shipped-quality component?
-- **Time intent.** Quick exploration, or polish until it ships?
-
-Scope answers are task-scoped. Don't write them to PRODUCT.md or DESIGN.md; carry them through the design brief only.
-
-### Constraints
-- Are there technical constraints? (Framework, performance budget, browser support)
-- Are there content constraints? (Localization, dynamic text length, user-generated content)
-- Mobile/responsive requirements?
-- Accessibility requirements beyond WCAG AA?
-
-### Anti-Goals
-- What should this NOT be? What would be a wrong direction?
-- What's the biggest risk of getting this wrong?
-
-## Phase 1.5: Visual Direction Probe (Capability-Gated)
-
-After the discovery interview, generate a small set of visual direction probes **before** writing the final brief when all of these are true:
-
-- The work is **net-new** or directionally ambiguous enough that visual exploration will clarify the brief.
-- The requested fidelity is **mid-fi, high-fi, or production-ready**. Skip for sketch-only planning.
-- The current harness gives you native image generation (Codex's `image_gen`, an equivalent MCP tool, or similar). Don't ask the user to install APIs or tooling.
-
-When those conditions are met, this step is mandatory. If image generation isn't natively available, do not ask the user to install APIs or tooling. State in one line that the image step is skipped because the harness lacks native image generation, then proceed. The one-line announcement is required, not optional; it forces a conscious decision instead of letting the step quietly evaporate.
-
-Use probes to explore visual lanes, not to replace the brief.
-
-Do not skip probes because the final UI will be semantic, editable, code-native, responsive, or accessible. Those are implementation requirements, not reasons to avoid visual exploration.
-
-### What to generate
-
-Generate **2 to 4** distinct direction probes based on the discovery answers, especially:
-
-- Color strategy
-- Theme scene sentence
-- Named anchor references
-- Scope and fidelity
-
-The probes should differ in primary visual direction (hierarchy, topology, density, typographic voice, or color strategy), not just palette tweaks.
-
-### How to use the probes
-
-- Treat them as **direction tests**, not final designs.
-- Use them to pressure-test whether the brief is pointing at the right lane.
-- Ask the user which direction feels closest, what feels off, and what should carry forward.
-- If the probes reveal a mismatch, revise the brief inputs before finalizing the brief.
-
-### Important limits
-
-- Do **not** skip discovery because image generation is available.
-- Do **not** treat generated imagery as final UX specification, final copy, or final accessibility behavior.
-- Do **not** use this step for minor refinements of existing work. It's for shaping a new surface or clarifying a big directional choice.
-
-If image generation isn't natively available, announce the skip in one line and proceed to the design brief.
-
-## Phase 2: Design Brief
-
-After the interview and any required probes, present a brief and **end your response**. The user must confirm before any implementation runs. Do not present a brief and then continue to code in the same response, even if the brief feels obvious to you. The user's confirmation is the gate.
-
-**Choose the brief shape based on how clear the answers are:**
-
-- **Compact form (3-5 bullets)** when discovery was crisp and the original prompt + PRODUCT.md already pinned scope, content, and direction. State what you're building, the visual lane, and end with one or two specific questions or a clear "confirm or override?" prompt. This is the default for typical craft requests with a clear prompt.
-- **Full structured form (sections below)** when the task is genuinely ambiguous, multi-screen, or when the user asked for shape as a standalone step. Use this when the discipline of structure earns its weight.
-
-Don't pad a clear brief into a long one to look thorough. A 70-line brief restating answers the user just gave is noise, not rigor. Equally, don't skip the confirmation pause to look efficient: the pause is the point.
-
-Present the brief, then **stop and wait for explicit confirmation**. You are not the judge of whether the user already approved. Even when the brief feels obviously right, ask once and wait. The pause is what separates shape from premature implementation.
-
-### Brief Structure
-
-**1. Feature Summary** (2-3 sentences)
-What this is, who it's for, what it needs to accomplish.
-
-**2. Primary User Action**
-The single most important thing a user should do or understand here.
-
-**3. Design Direction**
-Color strategy (Restrained / Committed / Full palette / Drenched) + the theme scene sentence + 2–3 named anchor references. Reference PRODUCT.md and DESIGN.md where they already answer, and note any per-surface overrides.
-
-If you ran the Visual Direction Probe step, name which probe direction won and what changed in the brief because of it.
-
-**4. Scope**
-Fidelity, breadth, interactivity, and time intent from the Scope section of the interview. Task-scoped; these don't persist beyond the brief.
-
-**5. Layout Strategy**
-High-level spatial approach: what gets emphasis, what's secondary, how information flows. Describe the visual hierarchy and rhythm, not specific CSS.
-
-**6. Key States**
-List every state the feature needs: default, empty, loading, error, success, edge cases. For each, note what the user needs to see and feel.
-
-**7. Interaction Model**
-How users interact with this feature. What happens on click, hover, scroll? What feedback do they get? What's the flow from entry to completion?
-
-**8. Content Requirements**
-What copy, labels, empty state messages, error messages, and microcopy are needed. Note any dynamic content and its realistic ranges. For image-led surfaces, also list the required image/media roles and their likely source (project asset, generated raster, semantic SVG/CSS, canvas/WebGL, icon library, or accepted omission).
-
-**9. Recommended References**
-Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., spatial-design.md for complex layouts, motion-design.md for animated features, interaction-design.md for form-heavy features).
-
-**10. Open Questions**
-Anything genuinely unresolved. Don't list "open questions" you've already recommended a default for; assert the default and move on. If you'd write `Recommend: X` next to a question, just decide X.
-
----
-
-ask the user directly to clarify what you cannot infer. Ask for explicit confirmation of the brief before finishing.
-
-If the user disagrees with any part, revisit the relevant discovery questions. A shape run is incomplete until the user confirms direction.
-
-Once confirmed, the brief is complete. The user can now hand it to /impeccable, or use it to guide any other implementation approach. (If the user wants the full discovery-then-build flow in one step, they should use /impeccable craft instead, which runs this command internally.)
@@ -1,100 +0,0 @@
-# Spatial Design
-
-## Spacing Systems
-
-### Use 4pt Base, Not 8pt
-
-8pt systems are too coarse; you'll frequently need 12px (between 8 and 16). Use 4pt for granularity: 4, 8, 12, 16, 24, 32, 48, 64, 96px.
-
-### Name Tokens Semantically
-
-Name by relationship (`--space-sm`, `--space-lg`), not value (`--spacing-8`). Use `gap` instead of margins for sibling spacing; it eliminates margin collapse and cleanup hacks.
-
-## Grid Systems
-
-### The Self-Adjusting Grid
-
-Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Columns are at least 280px, as many as fit per row, leftovers stretch. For complex layouts, use named grid areas (`grid-template-areas`) and redefine them at breakpoints.
-
-## Visual Hierarchy
-
-### The Squint Test
-
-Blur your eyes (or screenshot and blur). Can you still identify:
-- The most important element?
-- The second most important?
-- Clear groupings?
-
-If everything looks the same weight blurred, you have a hierarchy problem.
-
-### Hierarchy Through Multiple Dimensions
-
-Don't rely on size alone. Combine:
-
-| Tool | Strong Hierarchy | Weak Hierarchy |
-|------|------------------|----------------|
-| **Size** | 3:1 ratio or more | <2:1 ratio |
-| **Weight** | Bold vs Regular | Medium vs Regular |
-| **Color** | High contrast | Similar tones |
-| **Position** | Top/left (primary) | Bottom/right |
-| **Space** | Surrounded by white space | Crowded |
-
-**The best hierarchy uses 2-3 dimensions at once**: A heading that's larger, bolder, AND has more space above it.
-
-### Cards Are Not Required
-
-Cards are overused. Spacing and alignment create visual grouping naturally. Use cards only when content is truly distinct and actionable, items need visual comparison in a grid, or content needs clear interaction boundaries. **Never nest cards inside cards.** Use spacing, typography, and subtle dividers for hierarchy within a card.
-
-## Container Queries
-
-Viewport queries are for page layouts. **Container queries are for components**:
-
-```css
-.card-container {
- container-type: inline-size;
-}
-
-.card {
- display: grid;
- gap: var(--space-md);
-}
-
-/* Card layout changes based on its container, not viewport */
-@container (min-width: 400px) {
- .card {
- grid-template-columns: 120px 1fr;
- }
-}
-```
-
-**Why this matters**: A card in a narrow sidebar stays compact, while the same card in a main content area expands automatically, without viewport hacks.
-
-## Optical Adjustments
-
-Text at `margin-left: 0` looks indented due to letterform whitespace; use negative margin (`-0.05em`) to optically align. Geometrically centered icons often look off-center; play icons need to shift right, arrows shift toward their direction.
-
-### Touch Targets vs Visual Size
-
-Buttons can look small but need large touch targets (44px minimum). Use padding or pseudo-elements:
-
-```css
-.icon-button {
- width: 24px; /* Visual size */
- height: 24px;
- position: relative;
-}
-
-.icon-button::before {
- content: '';
- position: absolute;
- inset: -10px; /* Expand tap target to 44px */
-}
-```
-
-## Depth & Elevation
-
-Create semantic z-index scales (dropdown → sticky → modal-backdrop → modal → toast → tooltip) instead of arbitrary numbers. For shadows, create a consistent elevation scale (sm → md → lg → xl). **Key insight**: Shadows should be subtle. If you can clearly see it, it's probably too strong.
-
----
-
-**Avoid**: Arbitrary spacing values outside your scale. Making all spacing equal (variety creates hierarchy). Creating hierarchy through size alone - combine size, weight, color, and space.
@@ -1,156 +0,0 @@
-# Teach Flow
-
-Gathers design context for a project and writes two complementary files at the project root:
-
-- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
-- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
-
-Every other impeccable command reads these files before doing any work.
-
-## Step 1: Load current state
-
-Run the shared loader first so you know what already exists:
-
-```bash
-node .cursor/skills/impeccable/scripts/load-context.mjs
-```
-
-The output tells you whether PRODUCT.md and/or DESIGN.md already exist. If `migrated: true`, legacy `.impeccable.md` was auto-renamed to `PRODUCT.md`. Mention this once to the user.
-
-Decision tree:
-- **Neither file exists (empty project or no context yet)**: do Steps 2-4 (write PRODUCT.md), then decide on DESIGN.md based on whether there's code to analyze.
-- **PRODUCT.md exists, DESIGN.md missing**: skip to Step 5 and offer to run `/impeccable document` for DESIGN.md.
-- **PRODUCT.md exists but has no `## Register` section (legacy)**: add it. Infer a hypothesis from the codebase (see Step 2), confirm with the user, write the field.
-- **Both exist**: ask the user directly to clarify what you cannot infer. Ask which file to refresh. Skip the one the user doesn't want changed.
-- **Just DESIGN.md exists (unusual)**: do Steps 2-4 to produce PRODUCT.md.
-
-Never silently overwrite an existing file. Always confirm first.
-
-If teach was invoked as a setup blocker by another command, such as `/impeccable craft landing page`, pause that command here. Complete teach, re-run the loader, then resume the original command with the freshly loaded context. For craft, resume into shape next; teach creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
-
-## Step 2: Explore the codebase
-
-Before asking questions, thoroughly scan the project to discover what you can:
-
-- **README and docs**: Project purpose, target audience, any stated goals
-- **Package.json / config files**: Tech stack, dependencies, existing design libraries
-- **Existing components**: Current design patterns, spacing, typography in use
-- **Brand assets**: Logos, favicons, color values already defined
-- **Design tokens / CSS variables**: Existing color palettes, font stacks, spacing scales
-- **Any style guides or brand documentation**
-
-Also form a **register hypothesis** from what you find:
-
-- Brand signals: `/`, `/about`, `/pricing`, `/blog/*`, `/docs/*`, hero sections, big typography, scroll-driven sections, landing-page-shaped content.
-- Product signals: `/app/*`, `/dashboard`, `/settings`, `/(auth)`, forms, data tables, side/top nav, app-shell components.
-
-Register is a hypothesis at this point, not a decision; Step 3 confirms it.
-
-Note what you've learned and what remains unclear. This exploration feeds both PRODUCT.md and DESIGN.md.
-
-## Step 3: Ask strategic questions (for PRODUCT.md)
-
-ask the user directly to clarify what you cannot infer. Ask only about what you couldn't infer from the codebase.
-
-### Interview mode, not confirmation mode
-
-If the repo is empty or the user's brief is sparse, run a short interview before proposing PRODUCT.md. Do **not** turn a one-sentence request into a complete inferred PRODUCT.md and ask for blanket confirmation.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Use inferred answers as hypotheses or options, not as finished facts.
-- Complete at least one real user-answer round before drafting PRODUCT.md, unless every required answer is directly discoverable from repo docs.
-- Round 1 should establish register, users/purpose, and desired outcome.
-- Round 2 should establish brand personality or references, anti-references, and accessibility needs.
-
-### Minimum viable interview
-
-Ask enough to complete PRODUCT.md. At minimum, cover register confirmation, users and purpose, brand personality, anti-references, and accessibility needs unless each answer is directly discoverable from repo context. After at least one interview round, you may propose inferred answers, but the user must confirm them before you write PRODUCT.md. Never synthesize PRODUCT.md from the original task prompt alone.
-
-### Register (ask first; it shapes everything below)
-
-Every design task is either **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboards, tools: design SERVES the product).
-
-If Step 2 produced a clear hypothesis, lead with it: *"From the codebase, this looks like a [brand / product] surface. Does that match your intent, or should we treat it differently?"*
-
-If the signal is genuinely split (e.g. a product with a big marketing landing), ask the user directly to clarify what you cannot infer. Ask which register describes the **primary** surface. The register can be overridden per task later, but PRODUCT.md carries one default.
-
-### Users & Purpose
-- Who uses this? What's their context when using it?
-- What job are they trying to get done?
-- For brand: what emotions should the interface evoke? (confidence, delight, calm, urgency)
-- For product: what workflow are they in? What's the primary task on any given screen?
-
-### Brand & Personality
-- How would you describe the brand personality in 3 words?
-- Reference sites or apps that capture the right feel? What specifically about them?
- - For brand, push for real-world references in the right lane (tech-minimal, editorial-magazine, consumer-warm, brutalist-grid, etc.), not generic "modern" adjectives.
- - For product, push for category best-tool references (Linear, Figma, Notion, Raycast, Stripe).
-- What should this explicitly NOT look like? Any anti-references?
-
-### Accessibility & Inclusion
-- Specific accessibility requirements? (WCAG level, known user needs)
-- Considerations for reduced motion, color blindness, or other accommodations?
-
-Skip questions where the answer is already clear. **Do NOT ask about colors, fonts, radii, or visual styling here.** Those belong in DESIGN.md, not PRODUCT.md.
-
-## Step 4: Write PRODUCT.md
-
-Write PRODUCT.md only after the user has confirmed the strategic answers from Step 3. If an inferred answer is uncertain or unconfirmed, ask before writing.
-
-Synthesize into a strategic document:
-
-```markdown
-# Product
-
-## Register
-
-product
-
-## Users
-[Who they are, their context, the job to be done]
-
-## Product Purpose
-[What this product does, why it exists, what success looks like]
-
-## Brand Personality
-[Voice, tone, 3-word personality, emotional goals]
-
-## Anti-references
-[What this should NOT look like. Specific bad-example sites or patterns to avoid.]
-
-## Design Principles
-[3-5 strategic principles derived from the conversation. Principles like "practice what you preach", "show, don't tell", "expert confidence". NOT visual rules like "use OKLCH" or "magenta accent".]
-
-## Accessibility & Inclusion
-[WCAG level, known user needs, considerations]
-```
-
-Register is either `brand` or `product` as a bare value. No prose, no commentary.
-
-Write to `PROJECT_ROOT/PRODUCT.md`. If `.impeccable.md` existed, the loader already renamed it; merge into that content rather than starting from scratch.
-
-## Step 5: Decide on DESIGN.md
-
-Offer `/impeccable document` either way. Two paths:
-
-- **Code exists** (CSS tokens, components, a running site): "I can generate a DESIGN.md that captures your visual system (colors, typography, components) so variants stay on-brand. Want to do that now?"
-- **Pre-implementation** (empty project): "I can seed a starter DESIGN.md from five quick questions about color strategy, type direction, motion energy, and references. You can re-run once there's code, to capture the real tokens. Want to do that now?"
-
-If the user agrees, delegate to `/impeccable document` (it auto-detects scan vs seed). Load its reference and follow that flow.
-
-If the user prefers to skip, mention they can run `/impeccable document` any time later.
-
-## Step 6: Confirm and wrap up
-
-Summarize:
-- Register captured (brand / product)
-- What was written (PRODUCT.md, DESIGN.md, or both)
-- The 3-5 strategic principles from PRODUCT.md that will guide future work
-- If DESIGN.md is pending, remind the user how to generate it later
-
-**Critical: re-run the loader to refresh session context.** After writing PRODUCT.md, run `node .cursor/skills/impeccable/scripts/load-context.mjs` one final time and let its full JSON output land in conversation. This ensures subsequent commands in this session use the freshly-written PRODUCT.md, not a stale earlier version.
-
-If teach was invoked as a blocker by another impeccable command (e.g. the user ran `/impeccable polish` with no PRODUCT.md), resume that original task now with the fresh context.
-
-Optionally ask the user directly to clarify what you cannot infer. Ask whether they'd like a brief summary of PRODUCT.md appended to .cursorrules for easier agent reference. If yes, append a short **Design Context** pointer section there.
@@ -1,124 +0,0 @@
-Typography carries most of the information on the page. Replace generic defaults (Inter, Roboto, system fallback at flat scale) with type that reflects the brand and scales with intentional contrast.
-
----
-
-## Register
-
-Brand: run the font selection procedure in [brand.md](brand.md). Pairing follows the brand's lane (display serif + sans body for editorial/luxury, one committed sans for tech, etc.). Fluid `clamp()` scale, ≥1.25 ratio between steps.
-
-Product: system fonts and familiar sans stacks are legitimate here. One well-tuned family typically carries the whole UI. Fixed `rem` scale, 1.125–1.2 ratio between more closely-spaced steps.
-
----
-
-## Assess Current Typography
-
-Analyze what's weak or generic about the current type:
-
-1. **Font choices**:
- - Are we using invisible defaults? (Inter, Roboto, Arial, Open Sans, system defaults)
- - Does the font match the brand personality? (A playful brand shouldn't use a corporate typeface)
- - Are there too many font families? (More than 2-3 is almost always a mess)
-
-2. **Hierarchy**:
- - Can you tell headings from body from captions at a glance?
- - Are font sizes too close together? (14px, 15px, 16px = muddy hierarchy)
- - Are weight contrasts strong enough? (Medium vs Regular is barely visible)
-
-3. **Sizing & scale**:
- - Is there a consistent type scale, or are sizes arbitrary?
- - Does body text meet minimum readability? (16px+)
- - Is the sizing strategy appropriate for the context? (Fixed `rem` scales for app UIs; fluid `clamp()` for marketing/content page headings)
-
-4. **Readability**:
- - Are line lengths comfortable? (45-75 characters ideal)
- - Is line-height appropriate for the font and context?
- - Is there enough contrast between text and background?
-
-5. **Consistency**:
- - Are the same elements styled the same way throughout?
- - Are font weights used consistently? (Not bold in one section, semibold in another for the same role)
- - Is letter-spacing intentional or default everywhere?
-
-**CRITICAL**: The goal isn't to make text "fancier." It's to make it clearer, more readable, and more intentional. Good typography is invisible; bad typography is distracting.
-
-## Plan Typography Improvements
-
-Consult the [typography reference](typography.md) for detailed guidance on scales, pairing, and loading strategies.
-
-Create a systematic plan:
-
-- **Font selection**: Do fonts need replacing? What fits the brand/context?
-- **Type scale**: Establish a modular scale (e.g., 1.25 ratio) with clear hierarchy
-- **Weight strategy**: Which weights serve which roles? (Regular for body, Semibold for labels, Bold for headings, or whatever fits)
-- **Spacing**: Line-heights, letter-spacing, and margins between typographic elements
-
-## Improve Typography Systematically
-
-### Font Selection
-
-If fonts need replacing:
-- Choose fonts that reflect the brand personality
-- Pair with genuine contrast (serif + sans, geometric + humanist), or use a single family in multiple weights
-- Ensure web font loading doesn't cause layout shift (`font-display: swap`, metric-matched fallbacks)
-
-### Establish Hierarchy
-
-Build a clear type scale:
-- **5 sizes cover most needs**: caption, secondary, body, subheading, heading
-- **Use a consistent ratio** between levels (1.25, 1.333, or 1.5)
-- **Combine dimensions**: Size + weight + color + space for strong hierarchy. Don't rely on size alone
-- **App UIs**: Use a fixed `rem`-based type scale, optionally adjusted at 1-2 breakpoints. Fluid sizing undermines the spatial predictability that dense, container-based layouts need
-- **Marketing / content pages**: Use fluid sizing via `clamp(min, preferred, max)` for headings and display text. Keep body text fixed
-
-### Fix Readability
-
-- Set `max-width` on text containers using `ch` units (`max-width: 65ch`)
-- Adjust line-height per context: tighter for headings (1.1-1.2), looser for body (1.5-1.7)
-- Increase line-height slightly for light-on-dark text
-- Ensure body text is at least 16px / 1rem
-
-### Refine Details
-
-- Use `tabular-nums` for data tables and numbers that should align
-- Apply proper `letter-spacing`: slightly open for small caps and uppercase, default or tight for large display text
-- Use semantic token names (`--text-body`, `--text-heading`), not value names (`--font-16`)
-- Set `font-kerning: normal` and consider OpenType features where appropriate
-
-### Weight Consistency
-
-- Define clear roles for each weight and stick to them
-- Don't use more than 3-4 weights (Regular, Medium, Semibold, Bold is plenty)
-- Load only the weights you actually use (each weight adds to page load)
-
-**NEVER**:
-- Use more than 2-3 font families
-- Pick sizes arbitrarily; commit to a scale
-- Set body text below 16px
-- Use decorative/display fonts for body text
-- Disable browser zoom (`user-scalable=no`)
-- Use `px` for font sizes; use `rem` to respect user settings
-- Default to Inter/Roboto/Open Sans when personality matters
-- Pair fonts that are similar but not identical (two geometric sans-serifs)
-
-## Verify Typography Improvements
-
-- **Hierarchy**: Can you identify heading vs body vs caption instantly?
-- **Readability**: Is body text comfortable to read in long passages?
-- **Consistency**: Are same-role elements styled identically throughout?
-- **Personality**: Does the typography reflect the brand?
-- **Performance**: Are web fonts loading efficiently without layout shift?
-- **Accessibility**: Does text meet WCAG contrast ratios? Is it zoomable to 200%?
-
-When the type carries the hierarchy on its own, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `scale` param controlling the hierarchy ratio. Express all font sizes in the variant's scoped CSS through `calc(var(--p-scale, 1) * <base>)` or, better, scale the type ramp via `clamp(min, calc(var(--p-scale, 1) * Npx), max)`. Users slide from subdued to commanding.
-
-```json
-{"id":"scale","kind":"range","min":0.85,"max":1.3,"step":0.05,"default":1,"label":"Scale"}
-```
-
-Where the variant riffs on a specific pairing, expose the pairing choice as a `steps` param (e.g. "serif display + sans body" vs. "mono display + sans body" vs. "all-sans"). Each branch routes through `:scope[data-p-pairing="X"]` selectors in scoped CSS.
-
-See `reference/live.md` for the full params contract.
@@ -1,159 +0,0 @@
-# Typography
-
-## Classic Typography Principles
-
-### Vertical Rhythm
-
-Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
-
-### Modular Scale & Hierarchy
-
-The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
-
-**Use fewer sizes with more contrast.** A 5-size system covers most needs:
-
-| Role | Typical Ratio | Use Case |
-|------|---------------|----------|
-| xs | 0.75rem | Captions, legal |
-| sm | 0.875rem | Secondary UI, metadata |
-| base | 1rem | Body text |
-| lg | 1.25-1.5rem | Subheadings, lead text |
-| xl+ | 2-4rem | Headlines, hero text |
-
-Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
-
-### Readability & Measure
-
-Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
-
-**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
-
-**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
-
-## Font Selection & Pairing
-
-The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
-
-### Anti-reflexes worth defending against
-
-- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
-- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
-- A children's product does NOT need a rounded display font. Kids' books use real type.
-- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
-
-**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
-
-### Pairing Principles
-
-**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
-
-When pairing, contrast on multiple axes:
-- Serif + Sans (structure contrast)
-- Geometric + Humanist (personality contrast)
-- Condensed display + Wide body (proportion contrast)
-
-**Never pair fonts that are similar but not identical** (e.g., two geometric sans-serifs). They create visual tension without clear hierarchy.
-
-### Web Font Loading
-
-The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
-
-```css
-/* 1. Use font-display: swap for visibility */
-@font-face {
- font-family: 'CustomFont';
- src: url('font.woff2') format('woff2');
- font-display: swap;
-}
-
-/* 2. Match fallback metrics to minimize shift */
-@font-face {
- font-family: 'CustomFont-Fallback';
- src: local('Arial');
- size-adjust: 105%; /* Scale to match x-height */
- ascent-override: 90%; /* Match ascender height */
- descent-override: 20%; /* Match descender depth */
- line-gap-override: 10%; /* Match line spacing */
-}
-
-body {
- font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
-}
-```
-
-Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
-
-**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
-
-**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
-
-**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
-
-## Modern Web Typography
-
-### Fluid Type
-
-Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
-
-**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
-
-**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
-
-**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
-
-**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
-
-### OpenType Features
-
-Most developers don't know these exist. Use them for polish:
-
-```css
-/* Tabular numbers for data alignment */
-.data-table { font-variant-numeric: tabular-nums; }
-
-/* Proper fractions */
-.recipe-amount { font-variant-numeric: diagonal-fractions; }
-
-/* Small caps for abbreviations */
-abbr { font-variant-caps: all-small-caps; }
-
-/* Disable ligatures in code */
-code { font-variant-ligatures: none; }
-
-/* Enable kerning (usually on by default, but be explicit) */
-body { font-kerning: normal; }
-```
-
-Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
-
-### Rendering polish
-
-```css
-/* Even out heading line lengths (browser picks better break points) */
-h1, h2, h3 { text-wrap: balance; }
-
-/* Reduce orphans and ragged endings in long prose */
-article p { text-wrap: pretty; }
-
-/* Variable fonts: pick the right optical-size master automatically */
-body { font-optical-sizing: auto; }
-```
-
-**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
-
-## Typography System Architecture
-
-Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
-
-## Accessibility Considerations
-
-Beyond contrast ratios (which are well-documented), consider:
-
-- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
-- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
-- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
-- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
-
----
-
-**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
@@ -1,107 +0,0 @@
-# UX Writing
-
-## The Button Label Problem
-
-**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
-
-| Bad | Good | Why |
-|-----|------|-----|
-| OK | Save changes | Says what will happen |
-| Submit | Create account | Outcome-focused |
-| Yes | Delete message | Confirms the action |
-| Cancel | Keep editing | Clarifies what "cancel" means |
-| Click here | Download PDF | Describes the destination |
-
-**For destructive actions**, name the destruction:
-- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
-- "Delete 5 items" not "Delete selected" (show the count)
-
-## Error Messages: The Formula
-
-Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
-
-### Error Message Templates
-
-| Situation | Template |
-|-----------|----------|
-| **Format error** | "[Field] needs to be [format]. Example: [example]" |
-| **Missing required** | "Please enter [what's missing]" |
-| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
-| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
-| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
-
-### Don't Blame the User
-
-Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
-
-## Empty States Are Opportunities
-
-Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
-
-## Voice vs Tone
-
-**Voice** is your brand's personality, consistent everywhere.
-**Tone** adapts to the moment.
-
-| Moment | Tone Shift |
-|--------|------------|
-| Success | Celebratory, brief: "Done! Your changes are live." |
-| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
-| Loading | Reassuring: "Saving your work..." |
-| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
-
-**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
-
-## Writing for Accessibility
-
-**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
-
-## Writing for Translation
-
-### Plan for Expansion
-
-German text is ~30% longer than English. Allocate space:
-
-| Language | Expansion |
-|----------|-----------|
-| German | +30% |
-| French | +20% |
-| Finnish | +30-40% |
-| Chinese | -30% (fewer chars, but same width) |
-
-### Translation-Friendly Patterns
-
-Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
-
-## Consistency: The Terminology Problem
-
-Pick one term and stick with it:
-
-| Inconsistent | Consistent |
-|--------------|------------|
-| Delete / Remove / Trash | Delete |
-| Settings / Preferences / Options | Settings |
-| Sign in / Log in / Enter | Sign in |
-| Create / Add / New | Create |
-
-Build a terminology glossary and enforce it. Variety creates confusion.
-
-## Avoid Redundant Copy
-
-If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
-
-## Loading States
-
-Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
-
-## Confirmation Dialogs: Use Sparingly
-
-Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
-
-## Form Instructions
-
-Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
-
----
-
-**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
@@ -1,284 +0,0 @@
-#!/usr/bin/env node
-/**
- * Cleans up deprecated Impeccable skill files, symlinks, and
- * skills-lock.json entries left over from previous versions.
- *
- * Safe to run repeatedly -- it is a no-op when nothing needs cleaning.
- *
- * Usage (from the project root):
- * node {{scripts_path}}/cleanup-deprecated.mjs
- *
- * What it does:
- * 1. Finds every harness-specific skills directory (.claude/skills,
- * .cursor/skills, .agents/skills, etc.).
- * 2. For each deprecated skill name (with and without i- prefix),
- * checks if the directory exists and its SKILL.md mentions
- * "impeccable" (to avoid deleting unrelated user skills).
- * 3. Deletes confirmed matches (files, directories, or symlinks).
- * 4. Removes the corresponding entries from skills-lock.json.
- */
-
-import { existsSync, readFileSync, writeFileSync, rmSync, readdirSync, statSync, lstatSync, unlinkSync } from 'node:fs';
-import { join, resolve } from 'node:path';
-
-// Skills that were renamed, merged, or folded in v2.0, v2.1, and v3.0.
-const DEPRECATED_NAMES = [
- // v2.0 renames
- 'frontend-design', // renamed to impeccable
- 'teach-impeccable', // folded into /impeccable teach
- // v2.1 merges
- 'arrange', // renamed to layout
- 'normalize', // merged into polish
- 'onboard', // merged into harden
- 'extract', // merged into /impeccable extract
- // v3.0 consolidation: all standalone skills -> /impeccable sub-commands
- 'adapt',
- 'animate',
- 'audit',
- 'bolder',
- 'clarify',
- 'colorize',
- 'critique',
- 'delight',
- 'distill',
- 'harden',
- 'layout',
- 'optimize',
- 'overdrive',
- 'polish',
- 'quieter',
- 'shape',
- 'typeset',
-];
-
-// All known harness directories that may contain a skills/ subfolder.
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Per-skill fingerprints for SKILL.md bodies that never mentioned
-// "impeccable" in their v2.x source. Used as a last-resort match
-// when no skills-lock.json exists and the word heuristic fails.
-// The strings are lifted verbatim from the v2.x frontmatter
-// descriptions, so collisions with hand-written user skills are
-// vanishingly unlikely.
-const SKILL_FINGERPRINTS = {
- harden: 'Make interfaces production-ready: error handling, empty states',
- optimize: 'Diagnoses and fixes UI performance across loading speed',
-};
-
-/**
- * Walk up from startDir until we find a directory that looks like a
- * project root (has package.json, .git, or skills-lock.json).
- */
-export function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- const { root } = { root: '/' };
- while (dir !== root) {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Load skills-lock.json from the project root, or null if missing/unreadable.
- */
-export function loadLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return null;
- try {
- return JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return null;
- }
-}
-
-/**
- * Check whether a skill directory belongs to Impeccable. Three layered
- * signals, in order of reliability:
- * 1. Lock source equals "pbakaus/impeccable" (authoritative).
- * 2. SKILL.md body contains the word "impeccable".
- * 3. SKILL.md body contains a per-skill fingerprint (for harden and
- * optimize, whose v2.x SKILL.md never mentioned the pack name).
- */
-export function isImpeccableSkill(skillDir, { skillName, lock } = {}) {
- // 1. Authoritative: the lock file claims this skill is ours.
- if (skillName && lock?.skills?.[skillName]?.source === 'pbakaus/impeccable') {
- return true;
- }
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) return false;
- let content;
- try {
- content = readFileSync(skillMd, 'utf-8');
- } catch {
- return false;
- }
- // 2. Word-level content heuristic.
- if (/impeccable/i.test(content)) return true;
- // 3. Per-skill fingerprint for old skills that never mentioned the pack.
- // Strip the i- prefix so both `harden` and `i-harden` resolve to the
- // same fingerprint entry.
- const unprefixed = skillName?.startsWith('i-') ? skillName.slice(2) : skillName;
- const fingerprint = unprefixed && SKILL_FINGERPRINTS[unprefixed];
- if (fingerprint && content.includes(fingerprint)) return true;
- return false;
-}
-
-/**
- * Build the full list of names to check: each deprecated name, plus
- * its i-prefixed variant.
- */
-export function buildTargetNames() {
- const names = [];
- for (const name of DEPRECATED_NAMES) {
- names.push(name);
- names.push(`i-${name}`);
- }
- return names;
-}
-
-/**
- * Find every skills directory across all harness dirs in the project.
- * Returns absolute paths that exist on disk.
- */
-export function findSkillsDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const candidate = join(projectRoot, harness, 'skills');
- if (existsSync(candidate)) {
- dirs.push(candidate);
- }
- }
- return dirs;
-}
-
-/**
- * Remove deprecated skill directories/symlinks from all harness dirs.
- * Reads skills-lock.json so the authoritative "source" field can
- * drive deletion even when SKILL.md never mentions impeccable.
- * Returns an array of paths that were deleted.
- */
-export function removeDeprecatedSkills(projectRoot, lock) {
- if (lock === undefined) lock = loadLock(projectRoot);
- const targets = buildTargetNames();
- const skillsDirs = findSkillsDirs(projectRoot);
- const deleted = [];
-
- for (const skillsDir of skillsDirs) {
- for (const name of targets) {
- const skillPath = join(skillsDir, name);
-
- // Use lstat to detect symlinks (existsSync follows symlinks and
- // returns false for dangling ones).
- let stat;
- try {
- stat = lstatSync(skillPath);
- } catch {
- continue; // does not exist at all
- }
-
- if (stat.isSymbolicLink()) {
- // Symlink: check the target if it's alive, otherwise treat
- // dangling symlinks to deprecated names as safe to remove.
- const targetAlive = existsSync(skillPath);
- const isMatch = targetAlive
- ? isImpeccableSkill(skillPath, { skillName: name, lock })
- : true;
- if (isMatch) {
- unlinkSync(skillPath);
- deleted.push(skillPath);
- }
- continue;
- }
-
- // Regular directory -- verify it belongs to impeccable
- if (isImpeccableSkill(skillPath, { skillName: name, lock })) {
- rmSync(skillPath, { recursive: true, force: true });
- deleted.push(skillPath);
- }
- }
- }
-
- return deleted;
-}
-
-/**
- * Remove deprecated entries from skills-lock.json.
- * Only removes entries whose source is "pbakaus/impeccable".
- * Returns the list of removed skill names.
- */
-export function cleanSkillsLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return [];
-
- let lock;
- try {
- lock = JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return [];
- }
-
- if (!lock.skills || typeof lock.skills !== 'object') return [];
-
- const targets = buildTargetNames();
- const removed = [];
-
- for (const name of targets) {
- const entry = lock.skills[name];
- if (!entry) continue;
- // Only remove if it belongs to impeccable
- if (entry.source === 'pbakaus/impeccable') {
- delete lock.skills[name];
- removed.push(name);
- }
- }
-
- if (removed.length > 0) {
- writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\n', 'utf-8');
- }
-
- return removed;
-}
-
-/**
- * Run the full cleanup. Returns a summary object.
- *
- * Order matters: read the lock and delete directories first, then
- * strip lock entries. Otherwise the authoritative signal is gone by
- * the time directory deletion runs.
- */
-export function cleanup(projectRoot) {
- const root = projectRoot || findProjectRoot();
- const lock = loadLock(root);
- const deletedPaths = removeDeprecatedSkills(root, lock);
- const removedLockEntries = cleanSkillsLock(root);
- return { deletedPaths, removedLockEntries, projectRoot: root };
-}
-
-// CLI entry point
-if (process.argv[1] && resolve(process.argv[1]) === resolve(new URL(import.meta.url).pathname)) {
- const result = cleanup();
- if (result.deletedPaths.length === 0 && result.removedLockEntries.length === 0) {
- console.log('No deprecated Impeccable skills found. Nothing to clean up.');
- } else {
- if (result.deletedPaths.length > 0) {
- console.log(`Removed ${result.deletedPaths.length} deprecated skill(s):`);
- for (const p of result.deletedPaths) console.log(` - ${p}`);
- }
- if (result.removedLockEntries.length > 0) {
- console.log(`Cleaned ${result.removedLockEntries.length} entry/entries from skills-lock.json:`);
- for (const name of result.removedLockEntries) console.log(` - ${name}`);
- }
- }
-}
@@ -1,94 +0,0 @@
-{
- "craft": {
- "description": "Full confirmed-brief-then-build flow. Runs multi-round shape discovery first, resolves visual probe and north-star mock gates when available, then builds and visually iterates. Use when building a new feature end-to-end.",
- "argumentHint": "[feature description]"
- },
- "teach": {
- "description": "Gathers design context for a project. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles) and, when code exists to analyze, DESIGN.md (visual: colors, typography, components). Every other command reads these files before doing work. Use once per project.",
- "argumentHint": ""
- },
- "document": {
- "description": "Generate a DESIGN.md file that captures the current visual design system. Auto-extracts colors, typography, spacing, radii, and component patterns from the codebase, then asks the user to confirm descriptive language for atmosphere and color character. Follows the Google Stitch DESIGN.md format so the file is tool-compatible. Use when you need a visual design spec an AI agent can follow to stay on-brand.",
- "argumentHint": ""
- },
- "extract": {
- "description": "Pull reusable patterns, components, and design tokens into the design system. Identifies repeated patterns and consolidates them. Use when you have drift across the codebase and want to bring things back to a consistent system.",
- "argumentHint": "[target]"
- },
- "live": {
- "description": "Interactive live variant mode. Select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via HMR. Requires a running dev server. Use when you want to visually experiment with design alternatives in real time.",
- "argumentHint": ""
- },
- "adapt": {
- "description": "Adapt designs to work across different screen sizes, devices, contexts, or platforms. Implements breakpoints, fluid layouts, and touch targets. Use when the user mentions responsive design, mobile layouts, breakpoints, viewport adaptation, or cross-device compatibility.",
- "argumentHint": "[target] [context (mobile, tablet, print...)]"
- },
- "animate": {
- "description": "Review a feature and enhance it with purposeful animations, micro-interactions, and motion effects that improve usability and delight. Use when the user mentions adding animation, transitions, micro-interactions, motion design, hover effects, or making the UI feel more alive.",
- "argumentHint": "[target]"
- },
- "audit": {
- "description": "Run technical quality checks across accessibility, performance, theming, responsive design, and anti-patterns. Generates a scored report with P0-P3 severity ratings and actionable plan. Use when the user wants an accessibility check, performance audit, or technical quality review.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "bolder": {
- "description": "Amplify safe or boring designs to make them more visually interesting and stimulating. Increases impact while maintaining usability. Use when the user says the design looks bland, generic, too safe, lacks personality, or wants more visual impact and character.",
- "argumentHint": "[target]"
- },
- "clarify": {
- "description": "Improve unclear UX copy, error messages, microcopy, labels, and instructions to make interfaces easier to understand. Use when the user mentions confusing text, unclear labels, bad error messages, hard-to-follow instructions, or wanting better UX writing.",
- "argumentHint": "[target]"
- },
- "colorize": {
- "description": "Add strategic color to features that are too monochromatic or lack visual interest, making interfaces more engaging and expressive. Use when the user mentions the design looking gray, dull, lacking warmth, needing more color, or wanting a more vibrant or expressive palette.",
- "argumentHint": "[target]"
- },
- "critique": {
- "description": "Evaluate design from a UX perspective, assessing visual hierarchy, information architecture, emotional resonance, cognitive load, and overall quality with quantitative scoring, persona-based testing, automated anti-pattern detection, and actionable feedback. Use when the user asks to review, critique, evaluate, or give feedback on a design or component.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "delight": {
- "description": "Add moments of joy, personality, and unexpected touches that make interfaces memorable and enjoyable to use. Elevates functional to delightful. Use when the user asks to add polish, personality, animations, micro-interactions, delight, or make an interface feel fun or memorable.",
- "argumentHint": "[target]"
- },
- "distill": {
- "description": "Strip designs to their essence by removing unnecessary complexity. Great design is simple, powerful, and clean. Use when the user asks to simplify, declutter, reduce noise, remove elements, or make a UI cleaner and more focused.",
- "argumentHint": "[target]"
- },
- "harden": {
- "description": "Make interfaces production-ready: error handling, i18n, text overflow, edge case management, and resilience under real-world data. Use when the user asks to harden, make production-ready, handle edge cases, add error states, or fix overflow and i18n issues.",
- "argumentHint": "[target]"
- },
- "onboard": {
- "description": "Design onboarding flows, first-run experiences, and empty states that guide new users to value. Covers welcome screens, account setup, progressive disclosure, contextual tooltips, feature announcements, and activation moments. Use when the user mentions onboarding, first-time users, empty states, activation, getting started, new user flows, or the aha moment.",
- "argumentHint": "[target]"
- },
- "layout": {
- "description": "Improve layout, spacing, and visual rhythm. Fixes monotonous grids, inconsistent spacing, and weak visual hierarchy. Use when the user mentions layout feeling off, spacing issues, visual hierarchy, crowded UI, alignment problems, or wanting better composition.",
- "argumentHint": "[target]"
- },
- "optimize": {
- "description": "Diagnoses and fixes UI performance across loading speed, rendering, animations, images, and bundle size. Use when the user mentions slow, laggy, janky, performance, bundle size, load time, or wants a faster, smoother experience.",
- "argumentHint": "[target]"
- },
- "overdrive": {
- "description": "Pushes interfaces past conventional limits with technically ambitious implementations — shaders, spring physics, scroll-driven reveals, 60fps animations. Use when the user wants to wow, impress, go all-out, or make something that feels extraordinary.",
- "argumentHint": "[target]"
- },
- "polish": {
- "description": "Performs a final quality pass fixing alignment, spacing, consistency, and micro-detail issues before shipping. Use when the user mentions polish, finishing touches, pre-launch review, something looks off, or wants to go from good to great.",
- "argumentHint": "[target]"
- },
- "quieter": {
- "description": "Tones down visually aggressive or overstimulating designs, reducing intensity while preserving quality. Use when the user mentions too bold, too loud, overwhelming, aggressive, garish, or wants a calmer, more refined aesthetic.",
- "argumentHint": "[target]"
- },
- "shape": {
- "description": "Plan UX and UI before code. Runs a required multi-round discovery interview, uses visual probes when available, and produces a user-confirmed design brief for implementation.",
- "argumentHint": "[feature to shape]"
- },
- "typeset": {
- "description": "Improves typography by fixing font choices, hierarchy, sizing, weight, and readability so text feels intentional. Use when the user mentions fonts, type, readability, text hierarchy, sizing looks off, or wants more polished, intentional typography.",
- "argumentHint": "[target]"
- }
-}
@@ -1,242 +0,0 @@
-#!/usr/bin/env node
-/**
- * Critique persistence helper.
- *
- * Each run of /impeccable critique writes a per-target snapshot to
- * .impeccable/critique/<timestamp>__<slug>.md
- * with a small YAML frontmatter carrying the score + P0/P1 counts.
- *
- * /impeccable polish reads the latest matching snapshot at start as its
- * fix backlog. No other skill auto-reads critique output.
- *
- * The slug is derived mechanically from the *resolved* primary artifact
- * (file path or URL), never from the user's natural-language phrasing.
- * Slug stability across runs is what lets the trend display work.
- *
- * CLI entry points (called from skill instructions):
- * node critique-storage.mjs slug <resolved-target>
- * node critique-storage.mjs write <slug> <snapshot-body-file>
- * node critique-storage.mjs latest <slug>
- * node critique-storage.mjs trend <slug> [limit]
- *
- * Note: there is intentionally no `ignore` subcommand. ignore.md is a plain
- * markdown file; the model reads it directly with its file-read tool. This
- * helper only exists for operations the model can't trivially do inline
- * (normalizing paths, generating filenames, globbing + parsing frontmatter).
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath, pathToFileURL } from 'node:url';
-import { getCritiqueDir } from './impeccable-paths.mjs';
-
-const SLUG_MAX = 50;
-
-/**
- * Mechanically derive a slug from a resolved target. Returns null if the
- * input doesn't look like a stable identifier (empty, project root, etc).
- *
- * Accepts file paths and URLs. The model resolves "the homepage" to a
- * concrete artifact before calling this — we never slug a natural-language
- * phrase.
- */
-export function slugFromTarget(resolved, { cwd = process.cwd() } = {}) {
- if (!resolved || typeof resolved !== 'string') return null;
- const trimmed = resolved.trim();
- if (!trimmed) return null;
-
- // URL
- if (/^https?:\/\//i.test(trimmed)) {
- let url;
- try { url = new URL(trimmed); } catch { return null; }
- const hostPath = `${url.hostname}${url.pathname}`;
- return kebab(hostPath);
- }
-
- // File path. Make it project-relative so two devs critiquing the same
- // checkout get the same slug regardless of where their repo is cloned.
- const abs = path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- let rel = path.relative(cwd, abs);
- // If the target is outside cwd, fall back to the basename so we still
- // produce a stable slug (vs the absolute path, which would include
- // home dirs / usernames).
- if (rel.startsWith('..') || path.isAbsolute(rel)) {
- rel = path.basename(abs);
- }
- if (!rel || rel === '.' || rel === '') return null;
- return kebab(rel);
-}
-
-function kebab(s) {
- const slug = s
- .toLowerCase()
- .replace(/[/\\.]+/g, '-')
- .replace(/[^a-z0-9-]+/g, '-')
- .replace(/-+/g, '-')
- .replace(/^-|-$/g, '');
- if (!slug) return null;
- // Cap from the tail — the tail (filename) is more identifying than the
- // top-level directory.
- return slug.length <= SLUG_MAX ? slug : slug.slice(slug.length - SLUG_MAX).replace(/^-/, '');
-}
-
-/**
- * Filename-safe UTC ISO timestamp: hyphens for separators, trailing Z.
- * Plain colons aren't allowed on Windows filesystems.
- */
-export function nowFilenameStamp(date = new Date()) {
- const iso = date.toISOString(); // 2026-05-12T18:30:00.123Z
- return iso.replace(/[:.]/g, '-').replace(/-\d+Z$/, 'Z');
-}
-
-/**
- * Write a snapshot for `slug`. `meta` carries the small structured frontmatter
- * keys read back by readTrend(). `body` is the human-readable critique
- * report (everything below the frontmatter).
- *
- * Returns the absolute path written.
- */
-export function writeSnapshot({ slug, meta, body, cwd = process.cwd(), now = new Date() }) {
- if (!slug) throw new Error('writeSnapshot requires a slug');
- const dir = getCritiqueDir(cwd);
- fs.mkdirSync(dir, { recursive: true });
- const timestamp = nowFilenameStamp(now);
- const filePath = path.join(dir, `${timestamp}__${slug}.md`);
- // Spread `meta` first so internally computed `timestamp` and `slug`
- // always win. Otherwise a caller-supplied meta blob (parsed from the
- // IMPECCABLE_CRITIQUE_META env var) could clobber them, leaving the
- // filename in disagreement with its frontmatter and corrupting trends.
- const front = serializeFrontmatter({ ...meta, timestamp, slug });
- fs.writeFileSync(filePath, `${front}\n${body.trim()}\n`, 'utf-8');
- return filePath;
-}
-
-function serializeFrontmatter(obj) {
- const lines = ['---'];
- for (const [key, value] of Object.entries(obj)) {
- if (value === undefined || value === null) continue;
- const str = typeof value === 'string' ? value : String(value);
- // Quote strings that contain : or # to keep parsing simple.
- const needsQuotes = typeof value === 'string' && /[:#]/.test(str);
- lines.push(`${key}: ${needsQuotes ? JSON.stringify(str) : str}`);
- }
- lines.push('---');
- return lines.join('\n');
-}
-
-function parseFrontmatter(text) {
- const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
- if (!match) return {};
- const out = {};
- for (const line of match[1].split(/\r?\n/)) {
- const colon = line.indexOf(':');
- if (colon < 0) continue;
- const key = line.slice(0, colon).trim();
- let value = line.slice(colon + 1).trim();
- if (/^".*"$/.test(value)) {
- try { value = JSON.parse(value); } catch { /* leave as-is */ }
- } else if (/^-?\d+$/.test(value)) {
- value = Number(value);
- }
- out[key] = value;
- }
- return out;
-}
-
-/**
- * Return all snapshot files for `slug`, sorted oldest → newest.
- */
-function listSnapshotsForSlug(slug, cwd) {
- const dir = getCritiqueDir(cwd);
- if (!fs.existsSync(dir)) return [];
- const suffix = `__${slug}.md`;
- return fs.readdirSync(dir)
- .filter((f) => f.endsWith(suffix))
- .sort()
- .map((f) => path.join(dir, f));
-}
-
-/**
- * Return the most recent snapshot for `slug`, or null. Polish reads this
- * to find its fix backlog when the slug matches.
- */
-export function readLatestSnapshot(slug, { cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- if (!all.length) return null;
- const latest = all[all.length - 1];
- const body = fs.readFileSync(latest, 'utf-8');
- return { path: latest, body, meta: parseFrontmatter(body) };
-}
-
-/**
- * Return the last `limit` snapshots' frontmatter, oldest → newest.
- * Critique appends a one-line trend to its output using this.
- */
-export function readTrend(slug, { limit = 5, cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- const slice = all.slice(-limit);
- return slice.map((file) => parseFrontmatter(fs.readFileSync(file, 'utf-8')));
-}
-
-// ---- CLI ---------------------------------------------------------------
-
-function main(argv) {
- const [cmd, ...args] = argv;
- switch (cmd) {
- case 'slug': {
- const slug = slugFromTarget(args[0]);
- if (!slug) { process.stderr.write('no stable slug for input\n'); process.exit(1); }
- process.stdout.write(`${slug}\n`);
- return;
- }
- case 'write': {
- const [slug, bodyFile] = args;
- if (!slug || !bodyFile) { process.stderr.write('usage: write <slug> <body-file>\n'); process.exit(1); }
- const raw = fs.readFileSync(bodyFile, 'utf-8');
- // The body file may be a full report. The caller passes the meta as
- // a JSON object on stdin if it wants structured frontmatter; otherwise
- // we write with minimal metadata.
- let meta = {};
- const metaArg = process.env.IMPECCABLE_CRITIQUE_META;
- if (metaArg) {
- try { meta = JSON.parse(metaArg); } catch { /* ignore */ }
- }
- const out = writeSnapshot({ slug, meta, body: raw });
- process.stdout.write(`${out}\n`);
- return;
- }
- case 'latest': {
- const latest = readLatestSnapshot(args[0]);
- if (!latest) { process.exit(2); }
- process.stdout.write(latest.body);
- return;
- }
- case 'trend': {
- const rows = readTrend(args[0], { limit: args[1] ? Number(args[1]) : 5 });
- process.stdout.write(JSON.stringify(rows, null, 2) + '\n');
- return;
- }
- default:
- process.stderr.write('usage: critique-storage.mjs <slug|write|latest|trend> [args]\n');
- process.exit(1);
- }
-}
-
-function isMainModule() {
- if (!process.argv[1]) return false;
- try {
- return fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1]);
- } catch {
- // pathToFileURL normalizes Windows paths; keep it as a fallback for any
- // environment where realpath is unavailable.
- return import.meta.url === pathToFileURL(process.argv[1]).href;
- }
-}
-
-// Why the realpath check: generated skills are often reached through symlinked
-// harness directories (for example a demo repo's `.agents` -> source `.agents`).
-// Node resolves import.meta.url to the real file, while process.argv[1] keeps
-// the symlink path. Comparing canonical paths prevents a silent exit-0 no-op.
-if (isMainModule()) {
- main(process.argv.slice(2));
-}
@@ -1,820 +0,0 @@
-// Parse a DESIGN.md (Stitch-spec format) into a structured JSON model that
-// the live-mode design-system panel can render. Deterministic, dependency-free.
-//
-// Two-layer: YAML frontmatter (machine-readable tokens) + markdown body
-// (prose with six canonical H2 sections). When frontmatter is present, it's
-// exposed on `model.frontmatter` alongside the prose-scraped sections;
-// consumers can prefer frontmatter values and fall back to prose.
-
-const CANONICAL_SECTIONS = [
- 'Overview',
- 'Colors',
- 'Typography',
- 'Elevation',
- 'Components',
- "Do's and Don'ts",
-];
-
-// ---------- Frontmatter (Stitch YAML subset) ----------
-
-function parseFrontmatter(md) {
- const lines = md.split(/\r?\n/);
- if (lines[0]?.trim() !== '---') return { frontmatter: null, body: md };
-
- let end = -1;
- for (let i = 1; i < lines.length; i++) {
- if (lines[i].trim() === '---') { end = i; break; }
- }
- if (end === -1) return { frontmatter: null, body: md };
-
- const yaml = lines.slice(1, end).join('\n');
- const body = lines.slice(end + 1).join('\n');
- try {
- return { frontmatter: parseYamlSubset(yaml), body };
- } catch {
- return { frontmatter: null, body: md };
- }
-}
-
-// Minimal YAML reader for the Stitch frontmatter subset: scalar maps with
-// one level of nested objects (typography roles, components). Indent-based,
-// 2-space convention. No arrays, no anchors, no multi-line scalars — Stitch's
-// schema doesn't need them and accepting them would require a real YAML
-// dependency we don't want to vendor.
-function parseYamlSubset(yaml) {
- const lines = yaml.split(/\r?\n/);
- const root = {};
- const stack = [{ indent: -1, obj: root }];
-
- for (const raw of lines) {
- // Skip blanks and line-only comments. Don't strip inline comments:
- // unquoted hex values start with `#` and can't be safely distinguished
- // from a comment after whitespace.
- if (!raw.trim() || /^\s*#/.test(raw)) continue;
-
- const indent = raw.match(/^\s*/)[0].length;
- const content = raw.slice(indent);
-
- const colonIdx = findTopLevelColon(content);
- if (colonIdx === -1) continue;
-
- while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
- stack.pop();
- }
-
- const key = content.slice(0, colonIdx).trim();
- const rest = content.slice(colonIdx + 1).trim();
- const parent = stack[stack.length - 1].obj;
-
- if (rest === '') {
- const obj = {};
- parent[key] = obj;
- stack.push({ indent, obj });
- } else {
- parent[key] = parseScalar(rest);
- }
- }
-
- return root;
-}
-
-function findTopLevelColon(s) {
- let inQuote = null;
- for (let i = 0; i < s.length; i++) {
- const ch = s[i];
- if (inQuote) {
- if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
- } else if (ch === '"' || ch === "'") {
- inQuote = ch;
- } else if (ch === ':') {
- return i;
- }
- }
- return -1;
-}
-
-function parseScalar(raw) {
- const s = raw.trim();
- if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
- return s.slice(1, -1);
- }
- if (s === 'true') return true;
- if (s === 'false') return false;
- if (s === 'null' || s === '~') return null;
- if (/^-?\d+$/.test(s)) return Number(s);
- if (/^-?\d*\.\d+$/.test(s)) return Number(s);
- return s;
-}
-
-const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
-const OKLCH_RE = /oklch\([^)]+\)/gi;
-const RGBA_RE = /rgba?\([^)]+\)/gi;
-const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
-const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
-
-// ---------- Section splitting ----------
-
-function splitSections(md) {
- const lines = md.split(/\r?\n/);
- let title = null;
- const sections = {};
- let current = null;
-
- for (const raw of lines) {
- const line = raw.trimEnd();
-
- if (!title && line.startsWith('# ') && !line.startsWith('## ')) {
- title = line.replace(/^#\s+/, '').trim();
- continue;
- }
-
- const h2 = line.match(/^##\s+(?:\d+\.\s*)?([^:\n]+?)(?::\s*(.+))?$/);
- if (h2) {
- const rawName = normalizeApostrophes(h2[1].trim());
- const subtitle = h2[2] ? h2[2].trim() : null;
- const canonical = matchCanonicalSection(rawName);
- if (canonical) {
- current = { name: canonical, subtitle, lines: [] };
- sections[canonical] = current;
- continue;
- }
- // non-canonical H2 — ignore but stop feeding into current
- current = null;
- continue;
- }
-
- if (current) current.lines.push(raw);
- }
-
- return { title, sections };
-}
-
-function normalizeApostrophes(s) {
- return s.replace(/[\u2018\u2019]/g, "'");
-}
-
-function matchCanonicalSection(name) {
- const normalized = normalizeApostrophes(name).toLowerCase();
- // Exact match first
- for (const c of CANONICAL_SECTIONS) {
- if (normalizeApostrophes(c).toLowerCase() === normalized) return c;
- }
- // Keyword-contained match: "Overview & Creative North Star" -> "Overview",
- // "Elevation & Depth" -> "Elevation", etc.
- for (const c of CANONICAL_SECTIONS) {
- const key = normalizeApostrophes(c).toLowerCase();
- const pattern = new RegExp(`\\b${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
- if (pattern.test(normalized)) return c;
- }
- return null;
-}
-
-// ---------- Subsection splitting (inside a canonical section) ----------
-
-function splitSubsections(lines) {
- const subs = [];
- let current = { name: null, lines: [] };
- subs.push(current);
-
- for (const raw of lines) {
- const h3 = raw.match(/^###\s+(.+?)\s*$/);
- if (h3) {
- current = { name: h3[1].trim(), lines: [] };
- subs.push(current);
- continue;
- }
- current.lines.push(raw);
- }
-
- return subs;
-}
-
-// ---------- Generic helpers ----------
-
-function collectParagraphs(lines) {
- const paragraphs = [];
- let buf = [];
- const flush = () => {
- if (buf.length) {
- paragraphs.push(buf.join(' ').trim());
- buf = [];
- }
- };
- for (const raw of lines) {
- const trimmed = raw.trim();
- if (trimmed === '') { flush(); continue; }
- // Horizontal rules (---, ***) and headings/bullets end a paragraph.
- if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { flush(); continue; }
- if (raw.startsWith('#') || raw.match(/^[-*]\s/)) { flush(); continue; }
- buf.push(trimmed);
- }
- flush();
- return paragraphs.filter(Boolean);
-}
-
-function collectBullets(lines) {
- const bullets = [];
- let current = null;
- for (const raw of lines) {
- const m = raw.match(/^\s*[-*]\s+(.+)$/);
- if (m) {
- if (current) bullets.push(current);
- current = m[1];
- continue;
- }
- // continuation of a bullet (indented line)
- if (current && raw.match(/^\s{2,}\S/)) {
- current += ' ' + raw.trim();
- continue;
- }
- // blank line ends a bullet
- if (raw.trim() === '' && current) {
- bullets.push(current);
- current = null;
- }
- }
- if (current) bullets.push(current);
- return bullets;
-}
-
-function stripBold(s) {
- return s.replace(/\*\*(.+?)\*\*/g, '$1');
-}
-
-function extractNamedRules(lines) {
- const rules = [];
- const seen = new Set();
-
- // Style A (Impeccable): "**The X Rule.** body body body" — can span lines.
- const joined = lines.join('\n');
- const inlineStart = /\*\*(The [^*]+?Rule)\.\*\*/g;
- const inlineMatches = [];
- let m;
- while ((m = inlineStart.exec(joined)) !== null) {
- inlineMatches.push({ name: m[1], start: m.index, end: inlineStart.lastIndex });
- }
- for (let i = 0; i < inlineMatches.length; i++) {
- const mm = inlineMatches[i];
- const bodyEnd = i + 1 < inlineMatches.length ? inlineMatches[i + 1].start : joined.length;
- const body = joined
- .slice(mm.end, bodyEnd)
- .replace(/\n##[^\n]*$/s, '')
- .replace(/\n###[^\n]*$/s, '')
- .trim();
- const name = stripBold(mm.name).trim();
- seen.add(name.toLowerCase());
- rules.push({ name, body: stripBold(body) });
- }
-
- // Style B (Stitch): `### The "X" Rule` or `### The X Fallback`, body is the
- // bullets/paragraphs until the next heading. Accept Rule / Fallback / Principle.
- for (let i = 0; i < lines.length; i++) {
- const h3 = lines[i].match(/^###\s+(.+?)\s*$/);
- if (!h3) continue;
- const headerName = stripBold(h3[1]).replace(/["“”]/g, '').trim();
- if (!/^The\b.*\b(Rule|Fallback|Principle)\b/i.test(headerName)) continue;
- if (seen.has(headerName.toLowerCase())) continue;
-
- const bodyLines = [];
- for (let j = i + 1; j < lines.length; j++) {
- if (/^##\s|^###\s/.test(lines[j])) break;
- bodyLines.push(lines[j]);
- }
- const body = stripBold(bodyLines.join('\n').replace(/\n+/g, ' ')).trim();
- if (body) {
- seen.add(headerName.toLowerCase());
- rules.push({ name: headerName, body });
- }
- }
-
- // Style C (Stitch bullet form): "* **The Layering Principle:** body"
- // Colon/period lives inside the bold, so match "**...**" then inspect.
- for (const b of collectBullets(lines)) {
- const mm = b.match(/^\*\*([^*]+?)\*\*\s*(.+)$/);
- if (!mm) continue;
- const nameRaw = mm[1].replace(/[.:]\s*$/, '').replace(/["“”]/g, '').trim();
- if (!/^The\b.+\b(Rule|Fallback|Principle)$/i.test(nameRaw)) continue;
- if (seen.has(nameRaw.toLowerCase())) continue;
- seen.add(nameRaw.toLowerCase());
- rules.push({ name: nameRaw, body: stripBold(mm[2]).trim() });
- }
-
- return rules;
-}
-
-// ---------- Per-section extractors ----------
-
-function extractOverview(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
- const northStar = text.match(/\*\*Creative North Star:\s*"([^"]+)"\*\*/);
- const keyChars = [];
- const keyCharMatch = text.match(/\*\*Key Characteristics:\*\*\s*\n([\s\S]+?)(?:\n##|\n###|$)/);
- if (keyCharMatch) {
- for (const line of keyCharMatch[1].split('\n')) {
- const m = line.match(/^\s*[-*]\s+(.+)$/);
- if (m) keyChars.push(stripBold(m[1].trim()));
- }
- }
-
- // Philosophy paragraphs: everything that isn't a rule header or key-char block
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) =>
- !p.startsWith('**Creative North Star') &&
- !p.startsWith('**Key Characteristics')
- );
-
- return {
- subtitle: section.subtitle,
- creativeNorthStar: northStar ? northStar[1] : null,
- philosophy: paragraphs,
- keyCharacteristics: keyChars,
- };
-}
-
-function extractColors(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ');
- const groups = [];
- const ROLE_KEYWORDS = /^(primary|secondary|tertiary|neutral|accent)\b/i;
-
- for (const sub of subs.slice(1)) {
- if (!sub.name || /Named Rules?/i.test(sub.name) || /^The\s/i.test(sub.name)) continue;
-
- const bullets = collectBullets(sub.lines);
- const parsed = bullets.map((b) => parseColorBullet(b)).filter(Boolean);
- if (parsed.length === 0) continue;
-
- // If every bullet starts with a role keyword (Primary/Secondary/...), promote
- // each bullet to its own group. Otherwise keep the subsection as the group.
- const allRoleBullets =
- parsed.length > 0 && parsed.every((p) => p.name && ROLE_KEYWORDS.test(p.name));
-
- if (allRoleBullets) {
- for (const p of parsed) {
- groups.push({ role: p.name, colors: [p] });
- }
- } else {
- groups.push({ role: sub.name, colors: parsed });
- }
- }
-
- // If the Colors section has no subsections at all (unlikely), fall back to
- // scanning the whole section as a flat bullet list.
- if (groups.length === 0) {
- const flat = collectBullets(section.lines)
- .map((b) => parseColorBullet(b))
- .filter(Boolean);
- if (flat.length) {
- for (const p of flat) {
- if (p.name && ROLE_KEYWORDS.test(p.name)) {
- groups.push({ role: p.name, colors: [p] });
- } else {
- const fallback = groups.find((g) => g.role === 'Palette');
- if (fallback) fallback.colors.push(p);
- else groups.push({ role: 'Palette', colors: [p] });
- }
- }
- }
- }
-
- return {
- subtitle: section.subtitle,
- description: description || null,
- groups,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function parseColorBullet(bullet) {
- const text = bullet.trim();
-
- // Case 1 (Impeccable): **Name** (value-with-maybe-nested-parens): description
- const bold = text.match(/^\*\*(.+?)\*\*\s*(.*)$/);
- if (bold && bold[2].startsWith('(')) {
- const value = extractParenGroup(bold[2]);
- if (value !== null) {
- const after = bold[2].slice(value.length + 2).trimStart();
- if (after.startsWith(':')) {
- return buildColor(bold[1], value, after.slice(1).trim());
- }
- }
- }
-
- // Case 2 (Stitch): **Name (values):** description — value embedded in bold.
- const stitch = text.match(/^\*\*([^*]+?)\s*\(([^)]+)\):\*\*\s*(.*)$/);
- if (stitch) {
- return buildColor(stitch[1].trim(), stitch[2], stitch[3]);
- }
-
- // Case 3: bullet without bold, just hex/oklch inside.
- const values = collectColorValues(text);
- if (values.length) {
- return buildColor(null, values.join(' to '), text);
- }
- return null;
-}
-
-function extractParenGroup(s) {
- if (s[0] !== '(') return null;
- let depth = 0;
- for (let i = 0; i < s.length; i++) {
- if (s[i] === '(') depth++;
- else if (s[i] === ')') {
- depth--;
- if (depth === 0) return s.slice(1, i);
- }
- }
- return null;
-}
-
-function buildColor(name, rawValue, description) {
- const values = collectColorValues(rawValue);
- const primary = values[0] ?? rawValue.trim();
- return {
- name: name ? stripBold(name).trim() : null,
- value: primary,
- valueRange: values.length > 1 ? values : null,
- format: detectFormat(primary),
- description: stripBold(description || '').trim() || null,
- };
-}
-
-function collectColorValues(s) {
- const out = [];
- s.replace(HEX_RE, (v) => {
- out.push(v);
- return v;
- });
- s.replace(OKLCH_RE, (v) => {
- out.push(v);
- return v;
- });
- return out;
-}
-
-function detectFormat(v) {
- if (!v) return 'unknown';
- if (v.startsWith('#')) return 'hex';
- if (/^oklch/i.test(v)) return 'oklch';
- if (/^rgb/i.test(v)) return 'rgb';
- return 'unknown';
-}
-
-function scanInlineColors(lines) {
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '');
- const color = parseColorBullet(trimmed);
- if (color) out.push(color);
- }
- return out;
-}
-
-function parseStitchInlineGroups(lines) {
- // Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
- // Each bullet IS its own role. Group them under the spoken role name.
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
- const m = trimmed.match(
- /^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
- );
- if (m) {
- const role = m[1];
- const color = buildColor(role, m[2], m[3]);
- out.push({ role, colors: [color] });
- }
- }
- return out;
-}
-
-function extractTypography(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
-
- const fonts = {};
- // Pattern A: **Display Font:** Family (with fallback)
- const fontLineRe = /\*\*([\w\s/]+?)Font:\*\*\s*([^\n(]+?)(?:\s*\(with\s+([^)]+)\))?\s*$/gm;
- let fm;
- while ((fm = fontLineRe.exec(text)) !== null) {
- const rawRole = fm[1].trim().toLowerCase().replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || 'display';
- fonts[role] = {
- family: fm[2].trim(),
- fallback: fm[3] ? fm[3].trim() : null,
- };
- }
-
- // Pattern B (Stitch): * **Display & Headlines (Noto Serif):** description
- if (Object.keys(fonts).length === 0) {
- const stitchRe = /\*\*([\w\s&/]+?)\s*\(([^)]+)\):\*\*\s*(.+)/g;
- let sm;
- while ((sm = stitchRe.exec(text)) !== null) {
- const rawRole = sm[1]
- .trim()
- .toLowerCase()
- .replace(/\s*&\s*/g, '-')
- .replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || rawRole;
- fonts[role] = { family: sm[2].trim(), fallback: null, purpose: sm[3].trim() };
- }
- }
-
- // Character paragraph — either a **Character:** label, or fall back to the
- // first free paragraph under the section header (Stitch style).
- const characterMatch = text.match(/\*\*Character:\*\*\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\n|\n###|\n##|$)/);
- let character = characterMatch ? characterMatch[1].replace(/\n/g, ' ').trim() : null;
- if (!character) {
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) => !/^\*\*[\w\s/&]+Font/i.test(p) && !/^\*\*[\w\s/&]+\([^)]+\)/.test(p)
- );
- if (paragraphs.length) character = paragraphs[0];
- }
-
- // Hierarchy bullets under ### Hierarchy
- const subs = splitSubsections(section.lines);
- let hierarchy = [];
- const hierSub = subs.find((s) => s.name && /hierarch/i.test(s.name));
- if (hierSub) {
- const bullets = collectBullets(hierSub.lines);
- hierarchy = bullets.map(parseTypeBullet).filter(Boolean);
- }
-
- return {
- subtitle: section.subtitle,
- fonts,
- character,
- hierarchy,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function normalizeFontRole(raw) {
- // Canonical roles the panel cares about: display, body, label, mono.
- // Stitch often writes compound roles like "display-&-headlines" or "ui-&-body"
- // — collapse them to the first canonical role present.
- const tokens = raw.split(/[-/&\s]+/).filter(Boolean);
- const priority = ['display', 'headline', 'body', 'ui', 'label', 'mono'];
- const canonical = { headline: 'display', ui: 'body' };
- for (const p of priority) {
- if (tokens.includes(p)) return canonical[p] || p;
- }
- return null;
-}
-
-function parseTypeBullet(bullet) {
- // - **Display** (family, weight 300, italic, clamp(...), line-height 1): purpose
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(([^)]+)\):\s*(.*)$/);
- if (!m) return null;
- const name = m[1].trim();
- const specs = m[2].split(',').map((s) => s.trim());
- return {
- name,
- specs,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractElevation(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ') || null;
-
- const shadows = [];
- const seen = new Set();
- const dedupe = (entry) => {
- const key = (entry.name || '') + '::' + entry.value;
- if (seen.has(key)) return;
- seen.add(key);
- shadows.push(entry);
- };
-
- for (const b of collectBullets(section.lines)) {
- const parsed = parseShadowBullet(b);
- if (parsed) dedupe(parsed);
- }
-
- // Fallback: extract shadows written inline in prose. Stitch style is
- // "...use an extra-diffused shadow: `box-shadow: 0 12px 40px rgba(...)`."
- for (const p of collectParagraphs(section.lines)) {
- for (const inline of extractInlineShadows(p)) dedupe(inline);
- }
- for (const b of collectBullets(section.lines)) {
- for (const inline of extractInlineShadows(b)) dedupe(inline);
- }
-
- return {
- subtitle: section.subtitle,
- description,
- shadows,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function extractInlineShadows(text) {
- // Find `box-shadow: ...` anywhere in prose and capture the value. Work on the
- // raw string so it handles both backtick-fenced and unfenced variants.
- const out = [];
- const re = /box-shadow\s*:\s*([^`;\n]+)/gi;
- let m;
- while ((m = re.exec(text)) !== null) {
- const value = m[1].replace(/[`.)]+$/, '').trim();
- if (!value) continue;
- // Name heuristic: the noun immediately before the shadow phrase.
- // e.g. "an extra-diffused shadow: ..." -> "extra-diffused shadow"
- const before = text.slice(0, m.index);
- const nameMatch = before.match(/\b([A-Za-z][A-Za-z\- ]{2,40})\s+shadow\b[^A-Za-z0-9]*$/i);
- let name = null;
- if (nameMatch) {
- const stripped = nameMatch[1]
- .replace(/^(?:use|using|apply|applying|is|are|looks? like)\s+/i, '')
- .replace(/^(?:a|an|the)\s+/i, '')
- .trim();
- if (stripped) {
- name =
- stripped.charAt(0).toUpperCase() + stripped.slice(1) + ' shadow';
- }
- }
- out.push({
- name,
- value,
- purpose: null,
- });
- }
- return out;
-}
-
-function parseShadowBullet(bullet) {
- // - **Name** (`box-shadow: value`): purpose
- // - **Name** (`value`): purpose
- // Only accept if the paren content looks like a shadow value (contains px,
- // rem, rgba, or box-shadow). This filters out `**Rule Name:**` bullets.
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(`?([^`]+?)`?\):\s*(.*)$/);
- if (!m) return null;
- const rawValue = m[2].replace(/^box-shadow:\s*/i, '').trim();
- const looksLikeShadow =
- /box-shadow|rgba?\(|\bpx\b|\brem\b|^-?\d+\s/i.test(rawValue) &&
- /\d/.test(rawValue);
- if (!looksLikeShadow) return null;
- const name = stripBold(m[1]).trim();
- return {
- name,
- value: rawValue,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractComponents(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const components = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
-
- const bullets = collectBullets(sub.lines);
- const paragraphs = collectParagraphs(sub.lines);
-
- const variants = [];
- const properties = {};
-
- for (const b of bullets) {
- // - **Key:** value
- const m = b.match(/^\*\*(.+?):?\*\*:?\s*(.+)$/);
- if (m) {
- const key = stripBold(m[1]).trim();
- const value = stripBold(m[2]).trim();
- // Heuristic: "Primary", "Secondary", "Hover", "Focus" etc are variants;
- // "Shape", "Background", "Padding" are properties.
- if (/^(primary|secondary|tertiary|ghost|hover|focus|active|disabled|default|error|selected|unselected|state)$/i.test(key.split(/[\s/]/)[0])) {
- variants.push({ name: key, description: value });
- } else {
- properties[key.toLowerCase()] = value;
- }
- }
- }
-
- components.push({
- name: sub.name,
- description: paragraphs.join(' ') || null,
- properties,
- variants,
- });
- }
-
- return {
- subtitle: section.subtitle,
- components,
- };
-}
-
-function extractDosDonts(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const dos = [];
- const donts = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
- const subName = normalizeApostrophes(sub.name);
- const bullets = collectBullets(sub.lines).map((b) => stripBold(b).trim());
- if (/^do'?t?:?$/i.test(subName) || /^do:?$/i.test(subName)) {
- dos.push(...bullets);
- } else if (/^don'?t:?$/i.test(subName)) {
- donts.push(...bullets);
- }
- }
-
- // Classify by bullet prefix as a backup (catches loose bullets outside H3 wrappers)
- for (const b of collectBullets(section.lines)) {
- const stripped = normalizeApostrophes(stripBold(b).trim());
- if (/^don'?t\b/i.test(stripped)) {
- if (!donts.some((d) => normalizeApostrophes(d) === stripped)) donts.push(stripped);
- } else if (/^do\b/i.test(stripped)) {
- if (!dos.some((d) => normalizeApostrophes(d) === stripped)) dos.push(stripped);
- }
- }
-
- return { dos, donts };
-}
-
-// ---------- Coverage assessment ----------
-
-function assessCoverage(model) {
- const report = {};
-
- report.overview = model.overview
- ? {
- northStar: Boolean(model.overview.creativeNorthStar),
- philosophy: model.overview.philosophy.length > 0,
- keyCharacteristics: model.overview.keyCharacteristics.length,
- }
- : 'missing';
-
- report.colors = model.colors
- ? {
- groups: model.colors.groups.length,
- totalColors: model.colors.groups.reduce((n, g) => n + g.colors.length, 0),
- rules: model.colors.rules.length,
- }
- : 'missing';
-
- report.typography = model.typography
- ? {
- fonts: Object.keys(model.typography.fonts).length,
- hierarchyEntries: model.typography.hierarchy.length,
- character: Boolean(model.typography.character),
- rules: model.typography.rules.length,
- }
- : 'missing';
-
- report.elevation = model.elevation
- ? {
- shadows: model.elevation.shadows.length,
- rules: model.elevation.rules.length,
- description: Boolean(model.elevation.description),
- }
- : 'missing';
-
- report.components = model.components
- ? {
- count: model.components.components.length,
- variantTotal: model.components.components.reduce((n, c) => n + c.variants.length, 0),
- }
- : 'missing';
-
- report.dosDonts = model.dosDonts
- ? {
- dos: model.dosDonts.dos.length,
- donts: model.dosDonts.donts.length,
- }
- : 'missing';
-
- return report;
-}
-
-// ---------- Main ----------
-
-export function parseDesignMd(md) {
- const { frontmatter, body } = parseFrontmatter(md);
- const { title, sections } = splitSections(body);
- return {
- schemaVersion: 2,
- title,
- frontmatter,
- overview: extractOverview(sections['Overview']),
- colors: extractColors(sections['Colors']),
- typography: extractTypography(sections['Typography']),
- elevation: extractElevation(sections['Elevation']),
- components: extractComponents(sections['Components']),
- dosDonts: extractDosDonts(sections["Do's and Don'ts"]),
- };
-}
-
-export { assessCoverage };
@@ -1,198 +0,0 @@
-/**
- * Scan a project tree for Content-Security-Policy signals and classify the
- * shape so the agent knows which patch template to propose.
- *
- * Used at first-time `live.mjs` setup. Mechanical (grep-based) — no network,
- * no dev server, no JS evaluation. The classification drives a user-facing
- * consent prompt; the agent does the actual patch writing.
- *
- * Shapes are named by patch mechanism, not framework origin:
- * - "append-arrays": CSP defined as structured directive arrays. Patch
- * appends a dev-only localhost entry. Covers:
- * - Monorepo helpers with additional*Src options
- * (e.g. createBaseNextConfig for Next)
- * - SvelteKit kit.csp.directives
- * - nuxt-security module's contentSecurityPolicy
- * - "append-string": CSP built as a literal value string. Patch splices
- * a dev-only token into script-src and connect-src.
- * Covers:
- * - Inline Next.js headers() with CSP string
- * - Nuxt routeRules / nitro.routeRules CSP headers
- * - "middleware": CSP set dynamically in middleware.{ts,js}.
- * Detected but not auto-patched in v1.
- * - "meta-tag": <meta http-equiv="Content-Security-Policy"> in
- * layout files. Detected but not auto-patched in v1.
- * - null: no CSP signals found; no patch needed.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const SKIP_DIRS = new Set([
- 'node_modules',
- '.git',
- '.next',
- '.turbo',
- '.svelte-kit',
- '.nuxt',
- '.astro',
- 'dist',
- 'build',
- 'out',
- '.vercel',
-]);
-
-const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.tsx', '.jsx']);
-const LAYOUT_EXTS = new Set(['.tsx', '.jsx', '.astro', '.vue', '.svelte', '.html']);
-const MAX_DEPTH = 6;
-const MAX_READ_BYTES = 64 * 1024;
-
-// append-arrays signals: CSP expressed as structured directive arrays
-const MONOREPO_HELPER_SIGNALS = [
- /\bbuildCSPConfig\b/,
- /\bbuildSecurityHeaders\b/,
- /\badditionalScriptSrc\b/,
- /\badditionalConnectSrc\b/,
- /\bcreateBaseNextConfig\b/,
-];
-const SVELTEKIT_CSP_SIGNALS = [
- /\bkit\s*:/,
- /\bcsp\s*:/,
- /\bdirectives\s*:/,
-];
-const NUXT_SECURITY_SIGNALS = [
- /['"]nuxt-security['"]/,
- /\bcontentSecurityPolicy\b/,
-];
-
-// append-string signals: CSP written as a literal value string
-const INLINE_HEADER_SIGNALS = [
- /["']Content-Security-Policy["']/i,
- /\bscript-src\b/,
- /\bconnect-src\b/,
-];
-const NUXT_ROUTE_RULES_SIGNALS = [
- /\brouteRules\b/,
- /Content-Security-Policy/i,
- /\bscript-src\b/,
-];
-
-const MIDDLEWARE_HINT = /headers\.set\(\s*["']Content-Security-Policy["']/i;
-const META_TAG_HINT = /http-equiv\s*=\s*["']Content-Security-Policy["']/i;
-
-/**
- * @param {string} cwd Project root.
- * @returns {{ shape: string|null, signals: string[] }}
- */
-export function detectCsp(cwd = process.cwd()) {
- const hits = { appendArrays: [], appendString: [], middleware: [], metaTag: [] };
-
- walk(cwd, cwd, 0, (absPath, relPath, body) => {
- const ext = path.extname(absPath);
- const base = path.basename(absPath).toLowerCase();
- const isConfig = (name) =>
- new RegExp('(^|/)' + name + '\\.config\\.').test(relPath);
-
- // === append-arrays candidates ===
-
- // Monorepo CSP helper: packages/*/src/.../(config|security)/*
- if (SCAN_EXTS.has(ext) &&
- /packages\/[^/]+\/src\/.*(config|next-config|security)/.test(relPath) &&
- MONOREPO_HELPER_SIGNALS.some((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // SvelteKit kit.csp.directives
- if (SCAN_EXTS.has(ext) && isConfig('svelte') &&
- SVELTEKIT_CSP_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // Nuxt nuxt-security module
- if (SCAN_EXTS.has(ext) && isConfig('nuxt') &&
- NUXT_SECURITY_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // === append-string candidates ===
-
- // Inline headers in Next/Nuxt/SvelteKit/Astro/Vite config
- if (SCAN_EXTS.has(ext) &&
- /(^|\/)(next|nuxt|vite|astro|svelte)\.config\./.test(relPath) &&
- INLINE_HEADER_SIGNALS.every((re) => re.test(body))) {
- // Nuxt routeRules is a sub-shape of append-string; we already covered
- // nuxt-security above via return, so any remaining Nuxt CSP match here
- // is a route-rules / inline-headers case. Either way, same patch
- // mechanism.
- hits.appendString.push(relPath);
- return;
- }
-
- // === detect-only shapes ===
-
- if ((base === 'middleware.ts' || base === 'middleware.js' || base === 'middleware.mjs') &&
- MIDDLEWARE_HINT.test(body)) {
- hits.middleware.push(relPath);
- }
-
- if (LAYOUT_EXTS.has(ext) && META_TAG_HINT.test(body)) {
- hits.metaTag.push(relPath);
- }
- });
-
- // Priority: append-arrays > append-string > middleware > meta-tag.
- // Structured patches are safer than string splices; runtime and HTML
- // injection patches are less reliable and v1 doesn't auto-apply them.
- if (hits.appendArrays.length > 0) {
- return { shape: 'append-arrays', signals: hits.appendArrays };
- }
- if (hits.appendString.length > 0) {
- return { shape: 'append-string', signals: hits.appendString };
- }
- if (hits.middleware.length > 0) {
- return { shape: 'middleware', signals: hits.middleware };
- }
- if (hits.metaTag.length > 0) {
- return { shape: 'meta-tag', signals: hits.metaTag };
- }
- return { shape: null, signals: [] };
-}
-
-function walk(root, dir, depth, visit) {
- if (depth > MAX_DEPTH) return;
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
-
- for (const entry of entries) {
- const abs = path.join(dir, entry.name);
- if (entry.isDirectory()) {
- if (SKIP_DIRS.has(entry.name)) continue;
- walk(root, abs, depth + 1, visit);
- continue;
- }
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name);
- if (!SCAN_EXTS.has(ext) && !LAYOUT_EXTS.has(ext)) continue;
- let body;
- try {
- const fd = fs.openSync(abs, 'r');
- try {
- const buf = Buffer.alloc(MAX_READ_BYTES);
- const n = fs.readSync(fd, buf, 0, MAX_READ_BYTES, 0);
- body = buf.slice(0, n).toString('utf-8');
- } finally { fs.closeSync(fd); }
- } catch { continue; }
- visit(abs, path.relative(root, abs), body);
- }
-}
-
-// CLI mode
-const _running = process.argv[1];
-if (_running?.endsWith('detect-csp.mjs') || _running?.endsWith('detect-csp.mjs/')) {
- const result = detectCsp(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
@@ -1,21 +0,0 @@
-#!/usr/bin/env node
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { pathToFileURL, fileURLToPath } from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const candidates = [
- path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
-];
-const detectorPath = candidates.find(p => fs.existsSync(p));
-
-if (!detectorPath) {
- process.stderr.write('Error: bundled detector not found.\n');
- process.exit(1);
-}
-
-const { detectCli } = await import(pathToFileURL(detectorPath));
-
-await detectCli();
@@ -1,1688 +0,0 @@
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
@@ -1,232 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
-import { detectHtml } from '../engines/static-html/detect-html.mjs';
-import { detectText } from '../engines/regex/detect-text.mjs';
-import {
- HTML_EXTENSIONS,
- buildImportGraph,
- detectFrameworkConfig,
- isPortListening,
- walkDir,
-} from '../node/file-system.mjs';
-
-// ---------------------------------------------------------------------------
-// Output formatting
-// ---------------------------------------------------------------------------
-
-function formatFindings(findings, jsonMode) {
- if (jsonMode) return JSON.stringify(findings, null, 2);
-
- const grouped = {};
- for (const f of findings) {
- if (!grouped[f.file]) grouped[f.file] = [];
- grouped[f.file].push(f);
- }
- const out = [];
- for (const [file, items] of Object.entries(grouped)) {
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
- out.push(`\n${file}${importNote}`);
- for (const item of items) {
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
- out.push(` → ${item.description}`);
- }
- }
- out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
- return out.join('\n');
-}
-
-// ---------------------------------------------------------------------------
-// Stdin handling
-// ---------------------------------------------------------------------------
-
-async function handleStdin() {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- const input = Buffer.concat(chunks).toString('utf-8');
- try {
- const parsed = JSON.parse(input);
- const fp = parsed?.tool_input?.file_path;
- if (fp && fs.existsSync(fp)) {
- return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
- ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
- }
- } catch { /* not JSON */ }
- return detectText(input, '<stdin>');
-}
-
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-async function confirm(question) {
- const rl = (await import('node:readline')).default.createInterface({
- input: process.stdin, output: process.stderr,
- });
- return new Promise((resolve) => {
- rl.question(`${question} [Y/n] `, (answer) => {
- rl.close();
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
- });
- });
-}
-
-function printUsage() {
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
-
-Scan files or URLs for UI anti-patterns and design quality issues.
-
-Options:
- --fast Regex-only mode (skip static HTML/CSS analysis, faster but misses linked stylesheets)
- --json Output results as JSON
- --help Show this help message
-
-Detection modes:
- HTML files Static HTML/CSS analysis (default, catches linked CSS)
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
- URLs Puppeteer full browser rendering (auto-detected)
- --fast Forces regex for all files
-
-Examples:
- impeccable detect src/
- impeccable detect index.html
- impeccable detect https://example.com
- impeccable detect --fast --json .`);
-}
-
-async function detectCli() {
- let args = process.argv.slice(2).map(arg => {
- if (arg === '-json') return '--json';
- if (arg === '-fast') return '--fast';
- return arg;
- });
- if (args[0] === 'detect') args = args.slice(1);
- const jsonMode = args.includes('--json');
- const helpMode = args.includes('--help');
- const fastMode = args.includes('--fast');
- const targets = args.filter(a => !a.startsWith('--'));
-
- if (helpMode) { printUsage(); process.exit(0); }
-
- let allFindings = [];
-
- if (!process.stdin.isTTY && targets.length === 0) {
- allFindings = await handleStdin();
- } else {
- const paths = targets.length > 0 ? targets : [process.cwd()];
- const urlTargetCount = paths.filter(target => /^https?:\/\//i.test(target)).length;
- const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
-
- try {
- for (const target of paths) {
- if (/^https?:\/\//i.test(target)) {
- try {
- const scanner = browserDetector
- ? (url) => browserDetector.detectUrl(url)
- : (url) => detectUrl(url);
- allFindings.push(...await scanner(target));
- } catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
- continue;
- }
-
- const resolved = path.resolve(target);
- let stat;
- try { stat = fs.statSync(resolved); }
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
-
- if (stat.isDirectory()) {
- // Check for framework dev server config (skip in JSON mode to avoid polluting output)
- if (!jsonMode) {
- const fwConfig = detectFrameworkConfig(resolved);
- if (fwConfig) {
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
- if (probe.listening && probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
- `For more accurate results, scan the running site:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- } else if (probe.listening && !probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
- );
- } else {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Start the dev server and scan via URL for best results:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- }
- }
- }
-
- const files = walkDir(resolved);
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
-
- // Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
- if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
- process.stderr.write(
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
- `Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
- `Use --fast to skip static HTML/CSS analysis, or target a specific subdirectory.\n`
- );
- const ok = await confirm('Continue?');
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
- }
-
- // Build import graph for multi-file awareness
- const graph = buildImportGraph(files);
- // Build reverse map: file -> set of files that import it
- const importedByMap = new Map();
- for (const [importer, imports] of graph) {
- for (const imported of imports) {
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
- importedByMap.get(imported).add(importer);
- }
- }
-
- for (const file of files) {
- const ext = path.extname(file).toLowerCase();
- let fileFindings;
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- fileFindings = await detectHtml(file);
- } else {
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
- }
- // Annotate findings with import context
- const importers = importedByMap.get(file);
- if (importers && importers.size > 0) {
- const importerNames = [...importers].map(f => path.basename(f));
- for (const f of fileFindings) {
- f.importedBy = importerNames;
- }
- }
- allFindings.push(...fileFindings);
- }
- } else if (stat.isFile()) {
- const ext = path.extname(resolved).toLowerCase();
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- allFindings.push(...await detectHtml(resolved));
- } else {
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
- }
- }
- }
- } finally {
- if (browserDetector) await browserDetector.close();
- }
- }
-
- if (allFindings.length > 0) {
- if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
- else process.stderr.write(formatFindings(allFindings, false) + '\n');
- process.exit(2);
- }
- if (jsonMode) process.stdout.write('[]\n');
- process.exit(0);
-}
-
-export { formatFindings, handleStdin, confirm, printUsage, detectCli };
@@ -1,4030 +0,0 @@
-/**
- * Anti-Pattern Browser Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * GENERATED -- do not edit. Source: cli/engine/browser/injected/index.mjs
- * Rebuild: node scripts/build-browser-detector.js
- *
- * Usage: <script src="detect-antipatterns-browser.js"></script>
- * Re-scan: window.impeccableScan()
- */
-(function () {
-if (typeof window === 'undefined') return;
-// --- cli/engine/shared/constants.mjs ---
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-// --- cli/engine/registry/antipatterns.mjs ---
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-// --- cli/engine/shared/color.mjs ---
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-// --- cli/engine/rules/checks.mjs ---
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-// --- cli/engine/browser/injected/index.mjs ---
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
-
-})();
@@ -1,43 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Anti-Pattern Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * Public API facade. Runtime engines live under cli/engine/engines/.
- */
-
-import { detectCli } from './cli/main.mjs';
-
-export { ANTIPATTERNS, RULE_ENGINE_SUPPORT, getAntipattern, getRulesForCategory, getRuleEngineSupport } from './registry/antipatterns.mjs';
-export { SAFE_TAGS, BORDER_SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS, KNOWN_SERIF_FONTS } from './shared/constants.mjs';
-export { isNeutralColor, parseRgb, relativeLuminance, contrastRatio, parseGradientColors, hasChroma, getHue, colorToHex } from './shared/color.mjs';
-export { isFullPage } from './shared/page.mjs';
-export {
- checkElementBorders,
- checkElementMotion,
- checkElementGlow,
- checkPageTypography,
- checkPageLayout,
- checkHtmlPatterns,
-} from './rules/checks.mjs';
-export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
-export { detectHtml } from './engines/static-html/detect-html.mjs';
-export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
-export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
-export {
- walkDir,
- SCANNABLE_EXTENSIONS,
- SKIP_DIRS,
- buildImportGraph,
- resolveImport,
- detectFrameworkConfig,
- isPortListening,
- FRAMEWORK_CONFIGS,
-} from './node/file-system.mjs';
-export { formatFindings, detectCli } from './cli/main.mjs';
-
-const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
-if (isMainModule) detectCli();
@@ -1,251 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { finding } from '../../findings.mjs';
-import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
-
-async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
- if (options?.visualContrast === false) return [];
- const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : 12;
- const scrollOffscreen = options?.visualContrastScrollOffscreen !== false;
- const existingLowContrastSelectors = new Set(
- serializedGroups
- .filter(group => group.findings?.some(f => f.type === 'low-contrast'))
- .map(group => group.selector)
- .filter(Boolean)
- );
-
- let browserAnalyses = [];
- const findings = [];
- if (options?.visualContrastBrowser !== false) {
- const browserFindings = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'browser-fallback',
- target,
- }, async () => {
- browserAnalyses = await page.evaluate(async ({ maxCandidates, scrollOffscreen }) => {
- if (typeof window.impeccableAnalyzeVisualContrast !== 'function') return [];
- return window.impeccableAnalyzeVisualContrast({ maxCandidates, scrollOffscreen });
- }, { maxCandidates, scrollOffscreen });
- return browserAnalyses
- .filter(result => result.finding && !existingLowContrastSelectors.has(result.selector))
- .map(result => result.finding);
- });
- findings.push(...browserFindings);
- }
-
- let candidates = browserAnalyses.length > 0 ? browserAnalyses : [];
- if (candidates.length === 0) {
- candidates = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'collect-candidates',
- target,
- }, () => page.evaluate(({ maxCandidates }) => {
- if (typeof window.impeccableCollectVisualContrastCandidates !== 'function') return [];
- return window.impeccableCollectVisualContrastCandidates({ maxCandidates });
- }, { maxCandidates }));
- }
-
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const browserResolvedSelectors = new Set(
- browserAnalyses
- .filter(result => result.status === 'fail' || result.status === 'pass')
- .map(result => result.selector)
- .filter(Boolean)
- );
- const filtered = candidates.filter(candidate =>
- !existingLowContrastSelectors.has(candidate.selector) &&
- !browserResolvedSelectors.has(candidate.selector)
- );
- if (options?.visualContrastPixel === false) return findings;
- for (const candidate of filtered) {
- const result = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'pixel-diff',
- target,
- }, async () => {
- const finding = await captureVisualContrastCandidate(page, candidate, viewport);
- return finding ? [finding] : [];
- });
- findings.push(...result);
- }
- return findings;
-}
-
-// ---------------------------------------------------------------------------
-// Puppeteer detection (for URLs)
-// ---------------------------------------------------------------------------
-
-async function detectUrl(url, options = {}) {
- const profile = options?.profile;
- const waitUntil = options?.waitUntil || 'networkidle0';
- const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const externalBrowser = options?.browser || null;
- let puppeteer;
- if (!externalBrowser) {
- try {
- puppeteer = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'import-puppeteer',
- target: url,
- }, () => import('puppeteer'));
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- }
-
- // Read the browser detection script — reuse it instead of reimplementing
- const browserScriptPath = path.resolve(
- path.dirname(fileURLToPath(import.meta.url)),
- '..',
- '..',
- 'detect-antipatterns-browser.js'
- );
- let browserScript;
- try {
- browserScript = profileStep(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'read-browser-script',
- target: url,
- }, () => fs.readFileSync(browserScriptPath, 'utf-8'));
- } catch {
- throw new Error(`Browser script not found at ${browserScriptPath}`);
- }
-
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
- // running in CI; local users keep the default hardened launch.
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
- const browser = externalBrowser || await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'launch-browser',
- target: url,
- }, () => puppeteer.default.launch({ headless: true, args: launchArgs }));
- const page = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'new-page',
- target: url,
- }, () => browser.newPage());
- let results = [];
- try {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'set-viewport',
- target: url,
- }, () => page.setViewport(viewport));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: `goto:${waitUntil}`,
- target: url,
- }, () => page.goto(url, { waitUntil, timeout: 30000 }));
- if (settleMs > 0) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'settle',
- target: url,
- }, () => new Promise(resolve => setTimeout(resolve, settleMs)));
- }
-
- // Inject the browser detection script and collect results
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'configure-pure-detect',
- target: url,
- }, () => page.evaluate(() => {
- window.__IMPECCABLE_CONFIG__ = {
- ...(window.__IMPECCABLE_CONFIG__ || {}),
- autoScan: false,
- };
- }));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'inject-browser-script',
- target: url,
- }, () => page.evaluate(browserScript));
- let serializedGroups = [];
- results = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'browser-scan',
- target: url,
- }, async () => {
- serializedGroups = await page.evaluate(() => {
- if (!window.impeccableDetect) return [];
- return window.impeccableDetect({ decorate: false, serialize: true });
- });
- return serializedGroups.flatMap(({ findings }) =>
- findings.map(f => ({ id: f.type, snippet: f.detail }))
- );
- });
- const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
- results.push(...visualFindings);
- } finally {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-page',
- target: url,
- }, () => page.close().catch(() => {}));
- if (!externalBrowser) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-browser',
- target: url,
- }, () => browser.close());
- }
- }
- return results.map(f => finding(f.id, url, f.snippet));
-}
-
-async function createBrowserDetector(options = {}) {
- let puppeteer;
- try {
- puppeteer = await import('puppeteer');
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- const launchArgs = options.launchArgs || (process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : []);
- const browser = options.browser || await puppeteer.default.launch({
- headless: options.headless ?? true,
- args: launchArgs,
- });
- const ownsBrowser = !options.browser;
- const defaults = {
- waitUntil: options.waitUntil || 'load',
- settleMs: Number.isFinite(options.settleMs) ? options.settleMs : 100,
- viewport: options.viewport || { width: 1280, height: 800 },
- };
- return {
- browser,
- async detectUrl(url, scanOptions = {}) {
- return detectUrl(url, {
- ...defaults,
- ...scanOptions,
- browser,
- });
- },
- async close() {
- if (ownsBrowser) await browser.close().catch(() => {});
- },
- };
-}
-
-export { runVisualContrastFallback, detectUrl, createBrowserDetector };
@@ -1,420 +0,0 @@
-import { GENERIC_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep } from '../../profile/profiler.mjs';
-
-// ---------------------------------------------------------------------------
-// Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
-// ---------------------------------------------------------------------------
-
-const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
-const hasBorderRadius = (line) => /border-radius/i.test(line);
-const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
-
-function isNeutralBorderColor(str) {
- const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
- if (!m) return false;
- const c = m[1].toLowerCase();
- if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
- const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
- if (hex) {
- const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
- if (shex) {
- const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- return false;
-}
-
-const REGEX_MATCHERS = [
- // --- Side-tab ---
- { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
- test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
- test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
- fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
- { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
- test: (m) => +m[1] >= 3,
- fmt: (m) => m[0] },
- // --- Border accent on rounded ---
- { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
- test: (m, line) => hasRounded(line) && +m[1] >= 1,
- fmt: (m) => m[0] },
- { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
- fmt: (m) => m[0] },
- // --- Overused font ---
- { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
- test: () => true,
- fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
- // --- Pure black background ---
- { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Gradient text ---
- { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
- test: (m, line) => /gradient/i.test(line),
- fmt: () => 'background-clip: text + gradient' },
- // --- Gradient text (Tailwind) ---
- { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
- test: (m, line) => /\bbg-gradient-to-/i.test(line),
- fmt: () => 'bg-clip-text + bg-gradient' },
- // --- Tailwind pure black background ---
- { id: 'pure-black-white', regex: /\bbg-black\b/g,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Tailwind gray on colored bg ---
- { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
- test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
- fmt: (m, line) => { const bg = line.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/); return `${m[0]} on ${bg?.[0] || '?'}`; } },
- // --- Tailwind AI palette ---
- { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
- fmt: (m) => `${m[0]} on heading` },
- { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
- fmt: (m) => `${m[0]} gradient` },
- // --- Bounce/elastic easing ---
- { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
- test: () => true,
- fmt: () => 'animate-bounce (Tailwind)' },
- { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
- test: (m) => {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
- },
- fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
- // --- Layout property transition ---
- { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition: ${found ? found.join(', ') : m[1].trim()}`;
- } },
- { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
- } },
-];
-
-const REGEX_ANALYZERS = [
- // Single font
- (content, filePath) => {
- const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
- const fonts = new Set();
- let m;
- while ((m = fontFamilyRe.exec(content)) !== null) {
- for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
- }
- }
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- while ((m = gfRe.exec(content)) !== null) {
- for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
- }
- if (fonts.size !== 1 || content.split('\n').length < 20) return [];
- const name = [...fonts][0];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
- return [finding('single-font', filePath, `only font used is ${name}`, line)];
- },
- // Flat type hierarchy
- (content, filePath) => {
- const sizes = new Set();
- const REM = 16;
- let m;
- const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
- while ((m = sizeRe.exec(content)) !== null) {
- const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
- if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
- }
- const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
- while ((m = clampRe.exec(content)) !== null) {
- sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
- sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
- }
- const TW = { 'text-xs': 12, 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24, 'text-3xl': 30, 'text-4xl': 36, 'text-5xl': 48, 'text-6xl': 60, 'text-7xl': 72, 'text-8xl': 96, 'text-9xl': 128 };
- for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
- if (sizes.size < 3) return [];
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio >= 2.0) return [];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (/font-size/i.test(lines[i]) || /\btext-(?:xs|sm|base|lg|xl|\d)/i.test(lines[i])) { line = i + 1; break; } }
- return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
- },
- // Monotonous spacing (regex)
- (content, filePath) => {
- const vals = [];
- let m;
- const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
- const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
- const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
- const rounded = vals.map(v => Math.round(v / 4) * 4);
- if (rounded.length < 10) return [];
- const counts = {};
- for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const pct = maxCount / rounded.length;
- const unique = [...new Set(rounded)].filter(v => v > 0);
- if (pct <= 0.6 || unique.length > 3) return [];
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
- },
- // Everything centered (regex)
- (content, filePath) => {
- const lines = content.split('\n');
- let centered = 0, total = 0;
- for (const line of lines) {
- if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
- total++;
- if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
- }
- }
- if (total < 5 || centered / total <= 0.7) return [];
- return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
- },
- // Dark glow (page-level: dark bg + colored box-shadow with blur)
- (content, filePath) => {
- // Check if page has a dark background
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
- if (!hasDarkBg) return [];
-
- // Check for colored box-shadow with blur > 4px
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let m;
- while ((m = shadowRe.exec(content)) !== null) {
- const val = m[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
- // Check blur: look for pattern like "0 0 20px" (third number > 4)
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- const lines = content.substring(0, m.index).split('\n');
- return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
- }
- }
- return [];
- },
-];
-
-// ---------------------------------------------------------------------------
-// Style block extraction (Vue/Svelte <style> blocks)
-// ---------------------------------------------------------------------------
-
-function extractStyleBlocks(content, ext) {
- ext = ext.toLowerCase();
- if (ext !== '.vue' && ext !== '.svelte') return [];
- const blocks = [];
- const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length + 1;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-// ---------------------------------------------------------------------------
-// CSS-in-JS extraction (styled-components, emotion)
-// ---------------------------------------------------------------------------
-
-const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
-
-function extractCSSinJS(content, ext) {
- ext = ext.toLowerCase();
- if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
- const blocks = [];
- const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null, options = {}) {
- const { profile, phase = 'regex-matchers' } = options || {};
- const findings = [];
- if (!profile) {
- for (const matcher of REGEX_MATCHERS) {
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- }
- return findings;
- }
-
- for (const matcher of REGEX_MATCHERS) {
- const matcherFindings = profileFindings(profile, {
- engine: 'regex',
- phase,
- ruleId: matcher.id,
- target: filePath,
- }, () => {
- const matches = [];
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- matches.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- return matches;
- });
- findings.push(...matcherFindings);
- }
- return findings;
-}
-
-function detectText(content, filePath, options = {}) {
- const profile = options?.profile;
- const findings = [];
- const lines = content.split('\n');
- const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
-
- // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
- // Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
- findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
- profile,
- phase: 'source',
- }));
-
- // Extract and scan <style> blocks from Vue/Svelte SFCs
- const styleBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'style-blocks',
- target: filePath,
- }, () => extractStyleBlocks(content, ext))
- : extractStyleBlocks(content, ext);
- for (const block of styleBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'style-block',
- }));
- }
-
- // Extract and scan CSS-in-JS template literals
- const cssJsBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'css-in-js',
- target: filePath,
- }, () => extractCSSinJS(content, ext))
- : extractCSSinJS(content, ext);
- for (const block of cssJsBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'css-in-js',
- }));
- }
-
- // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
- const deduped = [];
- for (const f of findings) {
- const isDupe = deduped.some(d =>
- d.antipattern === f.antipattern &&
- d.snippet === f.snippet &&
- Math.abs(d.line - f.line) <= 2
- );
- if (!isDupe) deduped.push(f);
- }
-
- // Page-level analyzers only run on full pages
- if (isFullPage(content)) {
- const analyzerIds = [
- 'single-font',
- 'flat-type-hierarchy',
- 'monotonous-spacing',
- 'everything-centered',
- 'dark-glow',
- ];
- for (let i = 0; i < REGEX_ANALYZERS.length; i++) {
- const analyzer = REGEX_ANALYZERS[i];
- deduped.push(...profileFindings(profile, {
- engine: 'regex',
- phase: 'page-analyzer',
- ruleId: analyzerIds[i] || `analyzer-${i + 1}`,
- target: filePath,
- }, () => analyzer(content, filePath)));
- }
- }
-
- return deduped;
-}
-
-export {
- REGEX_MATCHERS,
- REGEX_ANALYZERS,
- extractStyleBlocks,
- extractCSSinJS,
- runRegexMatchers,
- detectText,
-};
@@ -1,954 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { profileStep, recordProfileEvent } from '../../profile/profiler.mjs';
-import { parseAnyColor, resolveLengthPx, resolveVarRefs } from '../../rules/checks.mjs';
-
-// ---------------------------------------------------------------------------
-// jsdom CSS-variable border override map
-// ---------------------------------------------------------------------------
-//
-// jsdom's CSSOM silently drops any border shorthand that contains a var()
-// reference — the computed style for the element then shows empty width,
-// empty style, and a default black color. That's enough to hide the most
-// common real-world side-tab pattern in AI-generated pages:
-//
-// :root { --brand: #87a8ff; }
-// .card { border-left: 5px solid var(--brand); border-radius: 4px; }
-//
-// Real browsers (and therefore the browser detector path) resolve var()
-// natively, so this only affects the Node jsdom path.
-//
-// This pre-pass walks the stylesheets, finds any rule whose per-side or
-// all-sides border property contains var(), resolves the var() against
-// :root-level custom properties (read from the documentElement's computed
-// style, which jsdom DOES handle correctly), and attaches the resolved
-// width+color to every element that matches the rule's selector. The
-// Node-side `checkElementBorders` adapter consumes that map as a fallback
-// whenever jsdom's computed style came back empty.
-//
-// Limitations (intentional, to keep the pass simple):
-// * Only :root-level custom properties are resolved. Scoped overrides on
-// descendants are not tracked — uncommon in practice and would require
-// a per-element cascade walk.
-// * @media / @supports wrapped rules are ignored (jsdom often mishandles
-// these anyway).
-// * The fallback only fills sides that jsdom left empty, so any rule
-// whose border parses normally still wins via the computed style.
-
-const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
-
-// isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
-// CSS variables typically hold hex or named colors, so normalize those to
-// rgb() before handing the value off to the shared check. Anything we don't
-// recognise is passed through unchanged — isNeutralColor then treats it as
-// non-neutral, which is the safer default (matches the oklch-era bugfix).
-const NAMED_COLORS = {
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
-};
-
-function normalizeColorForCheck(value) {
- if (!value) return value;
- const v = value.trim();
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
- if (hex6) {
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
- if (hex3) {
- const [r, g, b] = [
- parseInt(hex3[1] + hex3[1], 16),
- parseInt(hex3[2] + hex3[2], 16),
- parseInt(hex3[3] + hex3[3], 16),
- ];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const named = NAMED_COLORS[v.toLowerCase()];
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
- return v;
-}
-
-function buildBorderOverrideMap(document, window) {
- const map = new Map();
- const rootStyle = window.getComputedStyle(document.documentElement);
-
- function resolveVar(value, depth = 0) {
- if (!value || depth > 10 || !value.includes('var(')) return value;
- return value.replace(
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
- (_, name, fallback) => {
- const v = rootStyle.getPropertyValue(name).trim();
- if (v) return resolveVar(v, depth + 1);
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
- return '';
- }
- );
- }
-
- function parseShorthand(text) {
- const m = text.trim().match(BORDER_SHORTHAND_RE);
- if (!m) return null;
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
- }
-
- // Read from the per-property accessors on rule.style. jsdom preserves
- // each border-* shorthand it parsed, even when the overall cssText has
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
- // `border-left: ...` loses the first declaration but keeps the second).
- const SIDE_PROPS = [
- ['borderLeft', 'Left'],
- ['borderRight', 'Right'],
- ['borderTop', 'Top'],
- ['borderBottom', 'Bottom'],
- ['borderInlineStart', 'Left'],
- ['borderInlineEnd', 'Right'],
- ];
-
- for (const sheet of document.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || []; } catch { continue; }
- for (const rule of rules) {
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
-
- const perSide = {};
-
- for (const [prop, side] of SIDE_PROPS) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const parsed = parseShorthand(resolveVar(val));
- if (parsed && parsed.color) perSide[side] = parsed;
- }
-
- // Uniform `border: <w> <style> var(...)` applies to every side the
- // per-side map didn't already claim.
- const borderAll = rule.style.border;
- if (borderAll && borderAll.includes('var(')) {
- const parsed = parseShorthand(resolveVar(borderAll));
- if (parsed && parsed.color) {
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
- if (!perSide[s]) perSide[s] = parsed;
- }
- }
- }
-
- // Longhand `border-*-color: var(...)` with width/style in separate
- // declarations. Rare in AI-generated pages, but cheap to cover.
- for (const [prop, side] of [
- ['borderLeftColor', 'Left'],
- ['borderRightColor', 'Right'],
- ['borderTopColor', 'Top'],
- ['borderBottomColor', 'Bottom'],
- ]) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const resolved = resolveVar(val).trim();
- if (!resolved) continue;
- // Width may or may not come from this rule — that's fine; the
- // adapter only substitutes the color when jsdom left it as a
- // literal var() string.
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
- }
-
- if (Object.keys(perSide).length === 0) continue;
-
- let matched;
- try { matched = document.querySelectorAll(rule.selectorText); }
- catch { continue; }
-
- for (const el of matched) {
- const existing = map.get(el);
- if (existing) {
- // Later rules overwrite earlier ones — approximates source-order
- // cascade for equal-specificity rules and is good enough for the
- // uncontested var()-dropped sides we're trying to recover.
- Object.assign(existing, perSide);
- } else {
- map.set(el, { ...perSide });
- }
- }
- }
- }
-
- return map;
-}
-
-// Strip `@layer NAME { … }` wrappers from a CSS / HTML source, leaving
-// the inner rules as flat CSS. jsdom doesn't implement CSS @layer, so
-// any rule inside a layer block becomes invisible to getComputedStyle.
-// Tailwind v4 makes this ubiquitous: every utility class lives in
-// `@layer utilities`, and Preflight lives in `@layer base`. Without
-// unwrapping, every Tailwind-styled element returns empty computed
-// styles. We walk the source character-by-character, balancing braces
-// so we correctly handle nested style rules inside the layer block.
-function unwrapCssAtLayer(source) {
- if (!source || !source.includes('@layer')) return source;
- // Find `@layer <name>? {` openers. The match starts at the @, and
- // we then balance braces from the opening { onward.
- const re = /@layer\b[^{;]*\{/g;
- let out = '';
- let lastIdx = 0;
- let m;
- while ((m = re.exec(source)) !== null) {
- const openStart = m.index;
- const openEnd = m.index + m[0].length; // position right after `{`
- let depth = 1;
- let i = openEnd;
- while (i < source.length && depth > 0) {
- const c = source.charCodeAt(i);
- if (c === 0x7b /* { */) depth++;
- else if (c === 0x7d /* } */) depth--;
- i++;
- }
- if (depth !== 0) {
- // Unbalanced — bail and return source unchanged.
- return source;
- }
- // Emit everything before the @layer, then the inner contents
- // (between the opening { and the matched closing }), then advance.
- out += source.slice(lastIdx, openStart);
- out += source.slice(openEnd, i - 1); // i-1 = position of the closing }
- lastIdx = i;
- re.lastIndex = i;
- }
- out += source.slice(lastIdx);
- return out;
-}
-
-// ---------------------------------------------------------------------------
-// Static HTML/CSS detection (default for local HTML files)
-// ---------------------------------------------------------------------------
-
-const STATIC_INHERITED_PROPS = new Set([
- 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight',
- 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'hyphens',
- 'webkitHyphens',
-]);
-
-const STATIC_DEFAULT_STYLE = {
- color: 'rgb(0, 0, 0)',
- backgroundColor: 'rgba(0, 0, 0, 0)',
- backgroundImage: 'none',
- borderTopWidth: '0px',
- borderRightWidth: '0px',
- borderBottomWidth: '0px',
- borderLeftWidth: '0px',
- borderTopColor: 'rgb(0, 0, 0)',
- borderRightColor: 'rgb(0, 0, 0)',
- borderBottomColor: 'rgb(0, 0, 0)',
- borderLeftColor: 'rgb(0, 0, 0)',
- borderRadius: '0px',
- boxShadow: 'none',
- fontFamily: '',
- fontSize: '16px',
- fontStyle: 'normal',
- fontWeight: '400',
- lineHeight: 'normal',
- letterSpacing: 'normal',
- textTransform: 'none',
- textAlign: 'start',
- hyphens: 'manual',
- webkitHyphens: 'manual',
- transitionProperty: '',
- transitionTimingFunction: '',
- animationName: '',
- animationTimingFunction: '',
- webkitBackgroundClip: '',
- backgroundClip: '',
- width: '',
- height: '',
- paddingTop: '0px',
- paddingRight: '0px',
- paddingBottom: '0px',
- paddingLeft: '0px',
- position: 'static',
- display: '',
-};
-
-const STATIC_PROP_MAP = {
- 'background-color': 'backgroundColor',
- 'background-image': 'backgroundImage',
- 'background-clip': 'backgroundClip',
- '-webkit-background-clip': 'webkitBackgroundClip',
- 'border-radius': 'borderRadius',
- 'border-top-width': 'borderTopWidth',
- 'border-right-width': 'borderRightWidth',
- 'border-bottom-width': 'borderBottomWidth',
- 'border-left-width': 'borderLeftWidth',
- 'border-top-color': 'borderTopColor',
- 'border-right-color': 'borderRightColor',
- 'border-bottom-color': 'borderBottomColor',
- 'border-left-color': 'borderLeftColor',
- 'box-shadow': 'boxShadow',
- 'font-family': 'fontFamily',
- 'font-size': 'fontSize',
- 'font-style': 'fontStyle',
- 'font-weight': 'fontWeight',
- 'line-height': 'lineHeight',
- 'letter-spacing': 'letterSpacing',
- 'text-transform': 'textTransform',
- 'text-align': 'textAlign',
- 'hyphens': 'hyphens',
- '-webkit-hyphens': 'webkitHyphens',
- 'transition-property': 'transitionProperty',
- 'transition-timing-function': 'transitionTimingFunction',
- 'animation-name': 'animationName',
- 'animation-timing-function': 'animationTimingFunction',
- 'width': 'width',
- 'height': 'height',
- 'padding-top': 'paddingTop',
- 'padding-right': 'paddingRight',
- 'padding-bottom': 'paddingBottom',
- 'padding-left': 'paddingLeft',
- 'position': 'position',
- 'display': 'display',
-};
-
-const STATIC_NAMED_COLORS = {
- black: { r: 0, g: 0, b: 0, a: 1 },
- white: { r: 255, g: 255, b: 255, a: 1 },
- transparent: { r: 0, g: 0, b: 0, a: 0 },
- gray: { r: 128, g: 128, b: 128, a: 1 },
- grey: { r: 128, g: 128, b: 128, a: 1 },
- silver: { r: 192, g: 192, b: 192, a: 1 },
- red: { r: 255, g: 0, b: 0, a: 1 },
- green: { r: 0, g: 128, b: 0, a: 1 },
- blue: { r: 0, g: 0, b: 255, a: 1 },
-};
-
-function splitCssList(value) {
- const parts = [];
- let depth = 0, quote = '', start = 0;
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; continue; }
- if (ch === '(' || ch === '[') depth++;
- else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);
- else if (ch === ',' && depth === 0) {
- parts.push(value.slice(start, i).trim());
- start = i + 1;
- }
- }
- const tail = value.slice(start).trim();
- if (tail) parts.push(tail);
- return parts;
-}
-
-function splitCssTokens(value) {
- const tokens = [];
- let depth = 0, quote = '', current = '';
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- current += ch;
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
- if (ch === '(') { depth++; current += ch; continue; }
- if (ch === ')') { depth = Math.max(0, depth - 1); current += ch; continue; }
- if (/\s/.test(ch) && depth === 0) {
- if (current) { tokens.push(current); current = ''; }
- continue;
- }
- current += ch;
- }
- if (current) tokens.push(current);
- return tokens;
-}
-
-function cssPropToCamel(prop) {
- if (!prop) return prop;
- const mapped = STATIC_PROP_MAP[prop];
- if (mapped) return mapped;
- return prop.replace(/-([a-z])/g, (_m, ch) => ch.toUpperCase());
-}
-
-function staticColorToCss(c) {
- if (!c) return '';
- if (c.a != null && c.a < 1) return `rgba(${c.r}, ${c.g}, ${c.b}, ${Number(c.a.toFixed(3))})`;
- return `rgb(${c.r}, ${c.g}, ${c.b})`;
-}
-
-function parseStaticColor(value) {
- const parsed = parseAnyColor(value);
- if (parsed) return parsed;
- const named = STATIC_NAMED_COLORS[String(value || '').trim().toLowerCase()];
- return named ? { ...named } : null;
-}
-
-function extractStaticColor(value) {
- if (!value) return '';
- const raw = String(value).trim();
- if (/^var\(/i.test(raw)) return raw;
- const colorLike = raw.match(/(?:rgba?\([^)]+\)|oklch\([^)]+\)|oklab\([^)]+\)|lch\([^)]+\)|lab\([^)]+\)|hsla?\([^)]+\)|hwb\([^)]+\)|#[0-9a-f]{3,8}\b|\b(?:black|white|gray|grey|silver|red|green|blue|transparent)\b)/i);
- if (!colorLike) return '';
- return colorLike[0];
-}
-
-function normalizeStaticCssValue(prop, value, customProps, parentStyle, currentStyle = null) {
- let resolved = resolveVarRefs(String(value || '').trim(), customProps);
- if (resolved === 'inherit') return parentStyle?.[prop] || STATIC_DEFAULT_STYLE[prop] || '';
- const isModernBorderColor = /^border[A-Z][a-z]+Color$/.test(prop) && /^(?:oklch|oklab|lch|lab|hsl|hwb)\(/i.test(resolved);
- if (!isModernBorderColor && (/color$/i.test(prop) || prop === 'color' || prop === 'backgroundColor')) {
- const parsed = parseStaticColor(resolved);
- if (parsed) resolved = staticColorToCss(parsed);
- }
- if (prop === 'fontSize') {
- const base = parseFloat(parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'letterSpacing') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'lineHeight' && resolved !== 'normal') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- return resolved;
-}
-
-function expandStaticBoxValues(tokens) {
- if (tokens.length === 0) return ['0px', '0px', '0px', '0px'];
- if (tokens.length === 1) return [tokens[0], tokens[0], tokens[0], tokens[0]];
- if (tokens.length === 2) return [tokens[0], tokens[1], tokens[0], tokens[1]];
- if (tokens.length === 3) return [tokens[0], tokens[1], tokens[2], tokens[1]];
- return [tokens[0], tokens[1], tokens[2], tokens[3]];
-}
-
-function parseStaticBorder(value) {
- const tokens = splitCssTokens(value);
- let width = '', color = '';
- for (const token of tokens) {
- if (!width && /^-?[\d.]+(?:px|rem|em|%)$/.test(token)) width = token;
- if (!color) color = extractStaticColor(token);
- }
- return { width, color };
-}
-
-function parseStaticFont(value) {
- const out = [];
- const slashParts = value.match(/(?:^|\s)([\d.]+(?:px|rem|em|%))(?:\/([^\s]+))?/);
- if (/\bitalic\b/i.test(value)) out.push(['fontStyle', 'italic']);
- const weight = value.match(/\b([1-9]00|bold|normal|lighter|bolder)\b/i);
- if (weight) out.push(['fontWeight', weight[1]]);
- if (slashParts) {
- out.push(['fontSize', slashParts[1]]);
- if (slashParts[2]) out.push(['lineHeight', slashParts[2]]);
- const familyStart = value.indexOf(slashParts[0]) + slashParts[0].length;
- const family = value.slice(familyStart).trim();
- if (family) out.push(['fontFamily', family]);
- }
- return out;
-}
-
-function parseStaticTransition(value) {
- const props = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const prop = tokens.find(token => /^[a-z-]+$/i.test(token) && !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none)$/.test(token) && !/s$/.test(token));
- if (prop) props.push(prop);
- }
- return {
- property: props.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function parseStaticAnimation(value) {
- const names = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const name = tokens.find(token =>
- /^[a-z_-][\w-]*$/i.test(token) &&
- !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none|running|paused)$/.test(token)
- );
- if (name) names.push(name);
- }
- return {
- name: names.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function expandStaticDeclaration(prop, value) {
- const p = prop.toLowerCase();
- const v = String(value || '').trim();
- if (!v) return [];
- if (p.startsWith('--')) return [[p, v]];
- if (p === 'background') {
- const out = [];
- const hasImage = /gradient|url\(/i.test(v);
- if (hasImage) out.push(['backgroundImage', v]);
- const beforeImage = hasImage ? v.split(/(?:repeating-)?(?:linear|radial|conic)-gradient\(|url\(/i)[0] : v;
- const color = extractStaticColor(hasImage ? beforeImage : v);
- if (color) out.push(['backgroundColor', color]);
- return out;
- }
- if (p === 'border') {
- const parsed = parseStaticBorder(v);
- const out = [];
- for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
- if (parsed.width) out.push([`border${side}Width`, parsed.width]);
- if (parsed.color) out.push([`border${side}Color`, parsed.color]);
- }
- return out;
- }
- const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
- if (sideMatch) {
- const parsed = parseStaticBorder(v);
- const side = sideMatch[1][0].toUpperCase() + sideMatch[1].slice(1);
- return [
- ...(parsed.width ? [[`border${side}Width`, parsed.width]] : []),
- ...(parsed.color ? [[`border${side}Color`, parsed.color]] : []),
- ];
- }
- if (p === 'border-width') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopWidth', vals[0]],
- ['borderRightWidth', vals[1]],
- ['borderBottomWidth', vals[2]],
- ['borderLeftWidth', vals[3]],
- ];
- }
- if (p === 'border-color') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopColor', vals[0]],
- ['borderRightColor', vals[1]],
- ['borderBottomColor', vals[2]],
- ['borderLeftColor', vals[3]],
- ];
- }
- if (p === 'padding') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['paddingTop', vals[0]],
- ['paddingRight', vals[1]],
- ['paddingBottom', vals[2]],
- ['paddingLeft', vals[3]],
- ];
- }
- if (p === 'font') return parseStaticFont(v);
- if (p === 'transition') {
- const parsed = parseStaticTransition(v);
- return [
- ...(parsed.property ? [['transitionProperty', parsed.property]] : []),
- ...(parsed.timing ? [['transitionTimingFunction', parsed.timing]] : []),
- ];
- }
- if (p === 'animation') {
- const parsed = parseStaticAnimation(v);
- return [
- ...(parsed.name ? [['animationName', parsed.name]] : []),
- ...(parsed.timing ? [['animationTimingFunction', parsed.timing]] : []),
- ];
- }
- const mapped = cssPropToCamel(p);
- if (STATIC_DEFAULT_STYLE[mapped] != null || STATIC_INHERITED_PROPS.has(mapped)) {
- return [[mapped, v]];
- }
- return [];
-}
-
-function compareStaticPriority(a, b) {
- if (!a) return true;
- if (!!b.important !== !!a.important) return !!b.important;
- if (!!b.inline !== !!a.inline) return !!b.inline;
- for (let i = 0; i < 3; i++) {
- if ((b.specificity[i] || 0) !== (a.specificity[i] || 0)) {
- return (b.specificity[i] || 0) > (a.specificity[i] || 0);
- }
- }
- return b.order >= a.order;
-}
-
-function staticSpecificity(selector) {
- const noWhere = selector.replace(/:where\([^)]*\)/g, '');
- const ids = (noWhere.match(/#[\w-]+/g) || []).length;
- const classes = (noWhere.match(/\.[\w-]+|\[[^\]]+\]|:(?!:)[\w-]+(?:\([^)]*\))?/g) || []).length;
- const stripped = noWhere
- .replace(/#[\w-]+/g, ' ')
- .replace(/\.[\w-]+|\[[^\]]+\]|:{1,2}[\w-]+(?:\([^)]*\))?/g, ' ')
- .replace(/[*>+~(),]/g, ' ');
- const types = (stripped.match(/\b[a-zA-Z][\w-]*\b/g) || []).length;
- return [ids, classes, types];
-}
-
-function applyStaticDeclaration(specified, node, prop, value, meta) {
- let map = specified.get(node);
- if (!map) { map = new Map(); specified.set(node, map); }
- for (const [expandedProp, expandedValue] of expandStaticDeclaration(prop, value)) {
- const existing = map.get(expandedProp);
- const next = { ...meta, prop: expandedProp, value: expandedValue };
- if (compareStaticPriority(existing, next)) map.set(expandedProp, next);
- }
-}
-
-function parseStaticStyleAttribute(styleText, orderBase = 0) {
- const decls = [];
- for (const part of String(styleText || '').split(';')) {
- const idx = part.indexOf(':');
- if (idx <= 0) continue;
- const prop = part.slice(0, idx).trim();
- let value = part.slice(idx + 1).trim();
- const important = /!important\s*$/i.test(value);
- value = value.replace(/\s*!important\s*$/i, '').trim();
- decls.push({ prop, value, important, order: orderBase + decls.length });
- }
- return decls;
-}
-
-function collectStaticCssRules(cssText, csstree) {
- const rules = [];
- let ast;
- try {
- ast = csstree.parse(cssText, { positions: false, parseValue: true, parseCustomProperty: false });
- } catch {
- return rules;
- }
- let order = 0;
- const walkList = (list, atRuleStack = []) => {
- list?.forEach?.(node => {
- if (node.type === 'Rule' && node.block) {
- if (atRuleStack.some(name => /keyframes$/i.test(name))) return;
- const selectorText = csstree.generate(node.prelude).trim();
- const declarations = [];
- node.block.children?.forEach?.(child => {
- if (child.type !== 'Declaration') return;
- declarations.push({
- prop: child.property,
- value: csstree.generate(child.value).trim(),
- important: !!child.important,
- });
- });
- for (const selector of splitCssList(selectorText)) {
- if (selector) rules.push({ selector, declarations, specificity: staticSpecificity(selector), order: order++ });
- }
- return;
- }
- if (node.type === 'Atrule' && node.block) {
- const name = String(node.name || '').toLowerCase();
- if (name === 'media' || name === 'supports' || name === 'layer') {
- walkList(node.block.children, [...atRuleStack, name]);
- }
- }
- });
- };
- walkList(ast.children);
- return rules;
-}
-
-class StaticElement {
- constructor(node, doc) {
- this.node = node;
- this._doc = doc;
- this.nodeType = 1;
- this.tagName = String(node.name || '').toUpperCase();
- this.nodeName = this.tagName;
- }
- get parentElement() {
- let cur = this.node.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- return cur ? this._doc.wrap(cur) : null;
- }
- get previousElementSibling() {
- let cur = this.node.prev;
- while (cur && cur.type !== 'tag') cur = cur.prev;
- return cur ? this._doc.wrap(cur) : null;
- }
- get children() {
- return (this.node.children || []).filter(child => child.type === 'tag').map(child => this._doc.wrap(child));
- }
- get childNodes() {
- return (this.node.children || []).map(child => {
- if (child.type === 'text') return { nodeType: 3, textContent: child.data || '' };
- if (child.type === 'tag') return this._doc.wrap(child);
- return { nodeType: 8, textContent: child.data || '' };
- });
- }
- get textContent() {
- return this._doc.domutils.textContent(this.node);
- }
- get className() {
- return this.getAttribute('class') || '';
- }
- get id() {
- return this.getAttribute('id') || '';
- }
- getAttribute(name) {
- return this.node.attribs?.[name] ?? null;
- }
- querySelector(selector) {
- try {
- const found = this._doc.selectOne(selector, this.node.children || []);
- return found ? this._doc.wrap(found) : null;
- } catch {
- return null;
- }
- }
- querySelectorAll(selector) {
- try {
- return this._doc.selectAll(selector, this.node.children || []).map(node => this._doc.wrap(node));
- } catch {
- return [];
- }
- }
- closest(selector) {
- let cur = this.node;
- while (cur && cur.type === 'tag') {
- try {
- if (this._doc.is(cur, selector)) return this._doc.wrap(cur);
- } catch {
- return null;
- }
- cur = cur.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- }
- return null;
- }
- contains(other) {
- let cur = other?.node || null;
- while (cur) {
- if (cur === this.node) return true;
- cur = cur.parent;
- }
- return false;
- }
-}
-
-class StaticDocument {
- constructor(root, modules) {
- this.root = root;
- this.selectAll = modules.selectAll;
- this.selectOne = modules.selectOne;
- this.is = modules.is;
- this.domutils = modules.domutils;
- this._wrappers = new WeakMap();
- this._styleMap = new WeakMap();
- }
- wrap(node) {
- let wrapped = this._wrappers.get(node);
- if (!wrapped) {
- wrapped = new StaticElement(node, this);
- this._wrappers.set(node, wrapped);
- }
- return wrapped;
- }
- querySelectorAll(selector) {
- try {
- return this.selectAll(selector, this.root.children || []).map(node => this.wrap(node));
- } catch {
- return [];
- }
- }
- querySelector(selector) {
- try {
- const found = this.selectOne(selector, this.root.children || []);
- return found ? this.wrap(found) : null;
- } catch {
- return null;
- }
- }
- get documentElement() {
- return this.querySelector('html');
- }
- get body() {
- return this.querySelector('body');
- }
- setStyle(node, style) {
- this._styleMap.set(node, style);
- }
- getStyle(el) {
- return this._styleMap.get(el.node) || makeStaticStyle();
- }
-}
-
-function makeStaticStyle(values = {}) {
- const style = { ...STATIC_DEFAULT_STYLE, ...values };
- style.getPropertyValue = (prop) => {
- const key = cssPropToCamel(prop);
- return style[key] || style[prop] || '';
- };
- return style;
-}
-
-function buildStaticWindow(staticDoc) {
- return {
- document: staticDoc,
- getComputedStyle: (el) => staticDoc.getStyle(el),
- };
-}
-
-function collectStaticCssText(root, fileDir, profile, filePath, modules) {
- const styleTexts = [];
- for (const styleEl of modules.selectAll('style', root.children || [])) {
- styleTexts.push(modules.domutils.textContent(styleEl));
- }
- const links = modules.selectAll('link', root.children || []);
- for (const link of links) {
- const rel = link.attribs?.rel || '';
- const href = link.attribs?.href || '';
- if (!/\bstylesheet\b/i.test(rel) || !href || /^(https?:)?\/\//i.test(href)) continue;
- const cssPath = path.resolve(fileDir, href);
- try {
- const css = profileStep(profile, {
- engine: 'static-html',
- phase: 'preprocess',
- ruleId: 'inline-linked-stylesheet',
- target: filePath,
- detail: href,
- }, () => fs.readFileSync(cssPath, 'utf-8'));
- styleTexts.push(css);
- } catch { /* skip unreadable */ }
- }
- return styleTexts.join('\n');
-}
-
-function buildStaticStyleMap(root, staticDoc, cssText, modules, profile, filePath) {
- const specified = new Map();
- const allNodes = modules.selectAll('*', root.children || []);
- const rules = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-css',
- ruleId: 'css-rules',
- target: filePath,
- }, () => collectStaticCssRules(cssText, modules.csstree));
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'css-selectors',
- target: filePath,
- }, () => {
- for (const rule of rules) {
- let matched;
- try {
- matched = modules.selectAll(rule.selector, root.children || []);
- } catch {
- recordProfileEvent(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'unsupported-selector',
- target: filePath,
- ms: 0,
- findings: 0,
- detail: rule.selector,
- });
- continue;
- }
- for (const node of matched) {
- for (const decl of rule.declarations) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: rule.specificity,
- order: rule.order,
- inline: false,
- });
- }
- }
- }
-
- let inlineOrder = rules.length + 1;
- for (const node of allNodes) {
- const styleText = node.attribs?.style;
- if (!styleText) continue;
- for (const decl of parseStaticStyleAttribute(styleText, inlineOrder)) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: [1, 0, 0],
- order: decl.order,
- inline: true,
- });
- }
- inlineOrder += 1000;
- }
- });
-
- const computeNode = (node, parentStyle = null, parentCustom = new Map()) => {
- const specifiedMap = specified.get(node) || new Map();
- const customProps = new Map(parentCustom);
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) customProps.set(prop, resolveVarRefs(decl.value, customProps));
- }
- const values = {};
- for (const prop of Object.keys(STATIC_DEFAULT_STYLE)) {
- if (STATIC_INHERITED_PROPS.has(prop) && parentStyle?.[prop] != null) values[prop] = parentStyle[prop];
- else values[prop] = STATIC_DEFAULT_STYLE[prop];
- }
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) continue;
- values[prop] = normalizeStaticCssValue(prop, decl.value, customProps, parentStyle, values);
- }
- const style = makeStaticStyle(values);
- staticDoc.setStyle(node, style);
- for (const child of node.children || []) {
- if (child.type === 'tag') computeNode(child, style, customProps);
- }
- };
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'cascade',
- ruleId: 'compute-styles',
- target: filePath,
- }, () => {
- for (const child of root.children || []) {
- if (child.type === 'tag') computeNode(child);
- }
- });
-}
-
-export {
- BORDER_SHORTHAND_RE,
- NAMED_COLORS,
- normalizeColorForCheck,
- buildBorderOverrideMap,
- unwrapCssAtLayer,
- STATIC_INHERITED_PROPS,
- STATIC_DEFAULT_STYLE,
- STATIC_PROP_MAP,
- STATIC_NAMED_COLORS,
- splitCssList,
- splitCssTokens,
- cssPropToCamel,
- staticColorToCss,
- parseStaticColor,
- extractStaticColor,
- normalizeStaticCssValue,
- expandStaticBoxValues,
- parseStaticBorder,
- parseStaticFont,
- parseStaticTransition,
- parseStaticAnimation,
- expandStaticDeclaration,
- compareStaticPriority,
- staticSpecificity,
- applyStaticDeclaration,
- parseStaticStyleAttribute,
- collectStaticCssRules,
- StaticElement,
- StaticDocument,
- makeStaticStyle,
- buildStaticWindow,
- collectStaticCssText,
- buildStaticStyleMap,
-};
@@ -1,174 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import {
- checkElementBorders,
- checkElementColors,
- checkElementGlow,
- checkElementHeroEyebrow,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementMotion,
- checkElementQuality,
- checkHtmlPatterns,
- checkPageLayout,
- checkPageQualityFromDoc,
- checkRepeatedSectionKickersFromDoc,
- resolveBackground,
- resolveBorderRadiusPx,
-} from '../../rules/checks.mjs';
-import { detectText } from '../regex/detect-text.mjs';
-import {
- StaticDocument,
- buildStaticStyleMap,
- buildStaticWindow,
- collectStaticCssText,
-} from './css-cascade.mjs';
-
-function checkStaticPageTypography(document, window) {
- const findings = [];
- const fonts = new Set();
- const overusedFound = new Set();
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span, div')) {
- const hasText = el.childNodes.some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const ff = window.getComputedStyle(el).fontFamily || '';
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
- if (fonts.size === 1 && document.querySelectorAll('*').length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div')) {
- const fontSize = parseFloat(window.getComputedStyle(el).fontSize);
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
- return findings;
-}
-
-const STATIC_ELEMENT_RULES = [
- { id: 'border-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementBorders(tag, style, null, resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window)) },
- { id: 'color-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementColors(el, style, tag, window, customPropMap, false) },
- { id: 'dark-glow', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window, customPropMap)) },
- { id: 'motion-rules', selector: '*', run: (el, tag, style) => checkElementMotion(tag, style) },
- { id: 'icon-tile-stack', selector: 'h1,h2,h3,h4,h5,h6', run: (el, tag, _style, window) => checkElementIconTile(el, tag, window) },
- { id: 'italic-serif-display', selector: 'h1,h2', run: (el, tag, style) => checkElementItalicSerif(el, style, tag) },
- { id: 'hero-eyebrow-chip', selector: 'h1', run: (el, tag, style, window, customPropMap) => checkElementHeroEyebrow(el, style, tag, window, customPropMap) },
- { id: 'quality-rules', selector: '*', run: (el, tag, style, window) => checkElementQuality(el, style, tag, window) },
-];
-
-async function detectHtml(filePath, options = {}) {
- const profile = options?.profile;
- const html = profileStep(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'read-html',
- target: filePath,
- }, () => fs.readFileSync(filePath, 'utf-8'));
-
- let modules;
- try {
- modules = await profileStepAsync(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'import-static-parser',
- target: filePath,
- }, async () => {
- const [htmlparser2, cssSelect, csstree, domutils] = await Promise.all([
- import('htmlparser2'),
- import('css-select'),
- import('css-tree'),
- import('domutils'),
- ]);
- return {
- parseDocument: htmlparser2.parseDocument,
- selectAll: cssSelect.selectAll,
- selectOne: cssSelect.selectOne,
- is: cssSelect.is,
- csstree,
- domutils,
- };
- });
- } catch {
- return detectText(html, filePath, options);
- }
-
- const resolvedPath = path.resolve(filePath);
- const fileDir = path.dirname(resolvedPath);
- const root = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-html',
- ruleId: 'parse-document',
- target: filePath,
- }, () => modules.parseDocument(html, { lowerCaseAttributeNames: false, lowerCaseTags: true }));
-
- const cssText = collectStaticCssText(root, fileDir, profile, filePath, modules);
- const document = new StaticDocument(root, modules);
- buildStaticStyleMap(root, document, cssText, modules, profile, filePath);
- const window = buildStaticWindow(document);
-
- const customPropMap = null;
-
- const findings = [];
- const runElementCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'element', ruleId, target: filePath }, callback)
- : callback();
-
- const visitedByRule = new Map();
- for (const rule of STATIC_ELEMENT_RULES) {
- const elements = document.querySelectorAll(rule.selector);
- visitedByRule.set(rule.id, elements.length);
- for (const el of elements) {
- const tag = el.tagName.toLowerCase();
- const style = window.getComputedStyle(el);
- for (const f of runElementCheck(rule.id, () => rule.run(el, tag, style, window, customPropMap))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
- }
-
- if (isFullPage(html)) {
- const runPageCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
- : callback();
- for (const f of runPageCheck('typography-rules', () => checkStaticPageTypography(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('repeated-section-kickers', () => checkRepeatedSectionKickersFromDoc(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('layout-rules', () => checkPageLayout(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('skipped-heading', () => checkPageQualityFromDoc(document))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('html-patterns', () => checkHtmlPatterns(html).filter(item =>
- item.id !== 'bounce-easing' && item.id !== 'layout-transition'
- ))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
-
- return findings;
-}
-
-export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -1,189 +0,0 @@
-function sanitizeScreenshotClip(clip, viewport) {
- if (!clip) return null;
- const x = Math.max(0, Math.floor(clip.x || 0));
- const y = Math.max(0, Math.floor(clip.y || 0));
- const width = Math.min(
- Math.max(1, Math.ceil(clip.width || 0)),
- Math.max(1, viewport?.width || 1600),
- );
- const height = Math.min(
- Math.max(1, Math.ceil(clip.height || 0)),
- 320,
- );
- if (width < 1 || height < 1) return null;
- return { x, y, width, height };
-}
-
-async function compareScreenshotContrast(page, beforeBase64, afterBase64, candidate) {
- return page.evaluate(async ({ beforeBase64, afterBase64, candidate }) => {
- const loadImage = (base64) => new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = () => reject(new Error('Could not decode contrast screenshot'));
- img.src = `data:image/png;base64,${base64}`;
- });
- const [before, after] = await Promise.all([loadImage(beforeBase64), loadImage(afterBase64)]);
- const width = Math.min(before.width, after.width);
- const height = Math.min(before.height, after.height);
- if (width < 1 || height < 1) return null;
-
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return null;
-
- ctx.drawImage(before, 0, 0, width, height);
- const beforePixels = ctx.getImageData(0, 0, width, height).data;
- ctx.clearRect(0, 0, width, height);
- ctx.drawImage(after, 0, 0, width, height);
- const afterPixels = ctx.getImageData(0, 0, width, height).data;
-
- const luminance = ({ r, g, b }) => {
- const convert = c => {
- const v = c / 255;
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
- };
- return 0.2126 * convert(r) + 0.7152 * convert(g) + 0.0722 * convert(b);
- };
- const ratio = (a, b) => {
- const l1 = luminance(a);
- const l2 = luminance(b);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
- };
-
- const cssTextColor = candidate.textColor && !candidate.preferRenderedForeground
- ? {
- r: candidate.textColor.r,
- g: candidate.textColor.g,
- b: candidate.textColor.b,
- }
- : null;
- const ratios = [];
- let glyphPixels = 0;
- let strongestDelta = 0;
- for (let i = 0; i < beforePixels.length; i += 4) {
- const delta = Math.abs(beforePixels[i] - afterPixels[i])
- + Math.abs(beforePixels[i + 1] - afterPixels[i + 1])
- + Math.abs(beforePixels[i + 2] - afterPixels[i + 2])
- + Math.abs(beforePixels[i + 3] - afterPixels[i + 3]);
- strongestDelta = Math.max(strongestDelta, delta);
- if (delta < 10) continue;
- glyphPixels++;
- const fg = cssTextColor || {
- r: beforePixels[i],
- g: beforePixels[i + 1],
- b: beforePixels[i + 2],
- };
- const bg = {
- r: afterPixels[i],
- g: afterPixels[i + 1],
- b: afterPixels[i + 2],
- };
- ratios.push(ratio(fg, bg));
- }
-
- if (ratios.length < 8) {
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: null,
- p10Ratio: null,
- medianRatio: null,
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: ratios[0],
- p10Ratio: pick(10),
- medianRatio: pick(50),
- };
- }, { beforeBase64, afterBase64, candidate });
-}
-
-async function captureVisualContrastCandidate(page, candidate, viewport) {
- const clip = sanitizeScreenshotClip(candidate.clip, viewport);
- if (!clip) return null;
-
- const beforeBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- const token = `impeccable-contrast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- const applied = await page.evaluate(({ selector, token, backgroundClipText }) => {
- let el;
- try {
- el = document.querySelector(selector);
- } catch {
- return false;
- }
- if (!el) return false;
- let style = document.getElementById('impeccable-visual-contrast-hide-style');
- if (!style) {
- style = document.createElement('style');
- style.id = 'impeccable-visual-contrast-hide-style';
- style.textContent = [
- '[data-impeccable-visual-contrast-target] {',
- ' color: transparent !important;',
- ' -webkit-text-fill-color: transparent !important;',
- ' text-shadow: none !important;',
- '}',
- '[data-impeccable-visual-contrast-target][data-impeccable-bgclip-text="true"] {',
- ' background-image: none !important;',
- '}',
- ].join('\n');
- document.head.appendChild(style);
- }
- el.setAttribute('data-impeccable-visual-contrast-target', token);
- if (backgroundClipText) el.setAttribute('data-impeccable-bgclip-text', 'true');
- return true;
- }, {
- selector: candidate.selector,
- token,
- backgroundClipText: candidate.backgroundClipText,
- });
- if (!applied) return null;
-
- let afterBase64;
- try {
- afterBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- } finally {
- await page.evaluate(({ selector }) => {
- try {
- const el = document.querySelector(selector);
- if (el) {
- el.removeAttribute('data-impeccable-visual-contrast-target');
- el.removeAttribute('data-impeccable-bgclip-text');
- }
- } catch {
- // Ignore invalid or stale selectors during cleanup.
- }
- }, { selector: candidate.selector }).catch(() => {});
- }
-
- const metrics = await compareScreenshotContrast(page, beforeBase64, afterBase64, candidate);
- if (!metrics || !Number.isFinite(metrics.p10Ratio) || metrics.glyphPixels < 8) return null;
- const measuredRatio = metrics.p10Ratio;
- if (measuredRatio >= candidate.threshold) return null;
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const reasonLabel = (candidate.reasons || []).slice(0, 3).join(', ') || 'visual background';
- return {
- id: 'low-contrast',
- snippet: `pixel contrast ${measuredRatio.toFixed(1)}:1 median ${metrics.medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) on ${reasonLabel}${textLabel}`,
- };
-}
-
-export {
- sanitizeScreenshotClip,
- compareScreenshotContrast,
- captureVisualContrastCandidate,
-};
@@ -1,12 +0,0 @@
-import { getAntipattern } from './registry/antipatterns.mjs';
-
-function getAP(id) {
- return getAntipattern(id);
-}
-
-function finding(id, filePath, snippet, line = 0) {
- const ap = getAP(id);
- return { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', file: filePath, line, snippet };
-}
-
-export { getAP, finding };
@@ -1,198 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-// ---------------------------------------------------------------------------
-// File walker
-// ---------------------------------------------------------------------------
-
-const SKIP_DIRS = new Set([
- 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
- '.svelte-kit', '__pycache__', '.turbo', '.vercel',
-]);
-
-const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
- '.jsx', '.tsx', '.js', '.ts',
- '.vue', '.svelte', '.astro',
-]);
-
-const HTML_EXTENSIONS = new Set(['.html', '.htm']);
-
-function walkDir(dir) {
- const files = [];
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
- for (const entry of entries) {
- if (SKIP_DIRS.has(entry.name)) continue;
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) files.push(...walkDir(full));
- else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
- }
- return files;
-}
-
-
-// ---------------------------------------------------------------------------
-// Import graph (multi-file awareness)
-// ---------------------------------------------------------------------------
-
-function resolveImport(specifier, fromDir, fileSet) {
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
- const base = path.resolve(fromDir, specifier);
- if (fileSet.has(base)) return base;
- for (const ext of SCANNABLE_EXTENSIONS) {
- const withExt = base + ext;
- if (fileSet.has(withExt)) return withExt;
- }
- // index file convention
- for (const ext of SCANNABLE_EXTENSIONS) {
- const indexFile = path.join(base, 'index' + ext);
- if (fileSet.has(indexFile)) return indexFile;
- }
- return null;
-}
-
-function buildImportGraph(files) {
- const fileSet = new Set(files);
- const graph = new Map();
-
- for (const file of files) {
- const content = fs.readFileSync(file, 'utf-8');
- const dir = path.dirname(file);
- const imports = new Set();
-
- // ES imports: import ... from '...' and import '...'
- const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
- let m;
- while ((m = esRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // CSS @import
- const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
- while ((m = cssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // SCSS @use / @forward
- const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
- while ((m = scssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- graph.set(file, imports);
- }
- return graph;
-}
-
-// ---------------------------------------------------------------------------
-// Framework dev server detection
-// ---------------------------------------------------------------------------
-
-const FRAMEWORK_CONFIGS = [
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /next/i } },
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-sveltekit-page', value: null } },
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /@vite\/client/ } },
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /astro/i } },
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
- portRe: /"port"\s*:\s*(\d+)/,
- fingerprint: { body: /ng-version/i } },
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
-];
-
-function detectFrameworkConfig(dir) {
- let entries;
- try { entries = fs.readdirSync(dir); } catch { return null; }
- const entrySet = new Set(entries);
-
- for (const cfg of FRAMEWORK_CONFIGS) {
- const match = cfg.files.find(f => entrySet.has(f));
- if (!match) continue;
-
- const configPath = path.join(dir, match);
- let port = cfg.defaultPort;
- try {
- const content = fs.readFileSync(configPath, 'utf-8');
- const portMatch = content.match(cfg.portRe);
- if (portMatch) port = parseInt(portMatch[1], 10);
- } catch { /* use default */ }
-
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
- }
- return null;
-}
-
-/**
- * Check if a port is listening and optionally verify it matches the expected framework.
- * Returns { listening: true, matched: true/false } or { listening: false }.
- */
-async function isPortListening(port, fingerprint = null) {
- if (!fingerprint) {
- // Simple TCP probe fallback
- const net = await import('node:net');
- return new Promise((resolve) => {
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
- sock.setTimeout(500);
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
- sock.on('error', () => resolve({ listening: false }));
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
- });
- }
-
- // HTTP probe with fingerprint matching
- try {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 2000);
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
- clearTimeout(timeout);
-
- // Check header fingerprint
- if (fingerprint.header) {
- const val = res.headers.get(fingerprint.header);
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
- return { listening: true, matched: true };
- }
- }
-
- // Check body fingerprint
- if (fingerprint.body) {
- const body = await res.text();
- if (fingerprint.body.test(body)) {
- return { listening: true, matched: true };
- }
- }
-
- // Port is listening but doesn't match the expected framework
- return { listening: true, matched: false };
- } catch {
- return { listening: false };
- }
-}
-
-export {
- SKIP_DIRS,
- SCANNABLE_EXTENSIONS,
- HTML_EXTENSIONS,
- walkDir,
- resolveImport,
- buildImportGraph,
- FRAMEWORK_CONFIGS,
- detectFrameworkConfig,
- isPortListening,
-};
@@ -1,166 +0,0 @@
-function profileNow() {
- return typeof performance !== 'undefined' && performance.now
- ? performance.now()
- : Date.now();
-}
-
-function createDetectorProfile() {
- return { events: [] };
-}
-
-function recordProfileEvent(profile, event) {
- if (!profile) return;
- const normalized = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- ms: Number.isFinite(event.ms) ? event.ms : 0,
- findings: Number.isFinite(event.findings) ? event.findings : 0,
- };
- if (event.detail) normalized.detail = event.detail;
- if (Array.isArray(event.findingIds) && event.findingIds.length) {
- normalized.findingIds = event.findingIds;
- }
- if (typeof profile === 'function') {
- profile(normalized);
- } else if (typeof profile.record === 'function') {
- profile.record(normalized);
- } else if (Array.isArray(profile.events)) {
- profile.events.push(normalized);
- } else if (Array.isArray(profile)) {
- profile.push(normalized);
- }
-}
-
-function extractFindingIds(findings) {
- if (!Array.isArray(findings) || findings.length === 0) return [];
- return [...new Set(findings.map(f => f?.id || f?.type || f?.antipattern).filter(Boolean))];
-}
-
-function profileFindings(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-function profileStep(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-async function profileFindingsAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = await callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-async function profileStepAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return await callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-function percentile(sortedValues, pct) {
- if (!sortedValues.length) return 0;
- const idx = Math.min(
- sortedValues.length - 1,
- Math.max(0, Math.ceil((pct / 100) * sortedValues.length) - 1),
- );
- return sortedValues[idx];
-}
-
-function summarizeDetectorProfile(profile) {
- const events = Array.isArray(profile)
- ? profile
- : (Array.isArray(profile?.events) ? profile.events : []);
- const groups = new Map();
- for (const event of events) {
- const key = [
- event.engine || 'unknown',
- event.phase || 'unknown',
- event.ruleId || 'unknown',
- event.target || '',
- ].join('\u0000');
- let group = groups.get(key);
- if (!group) {
- group = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- calls: 0,
- totalMs: 0,
- findings: 0,
- samples: [],
- };
- groups.set(key, group);
- }
- const ms = Number.isFinite(event.ms) ? event.ms : 0;
- group.calls += 1;
- group.totalMs += ms;
- group.findings += Number.isFinite(event.findings) ? event.findings : 0;
- group.samples.push(ms);
- }
- return [...groups.values()]
- .map(group => {
- const samples = group.samples.sort((a, b) => a - b);
- return {
- engine: group.engine,
- phase: group.phase,
- ruleId: group.ruleId,
- target: group.target,
- calls: group.calls,
- totalMs: Number(group.totalMs.toFixed(3)),
- avgMs: Number((group.totalMs / group.calls).toFixed(3)),
- p50: Number(percentile(samples, 50).toFixed(3)),
- p95: Number(percentile(samples, 95).toFixed(3)),
- findings: group.findings,
- };
- })
- .sort((a, b) => b.totalMs - a.totalMs);
-}
-
-export {
- profileNow,
- createDetectorProfile,
- recordProfileEvent,
- extractFindingIds,
- profileFindings,
- profileStep,
- profileFindingsAsync,
- profileStepAsync,
- percentile,
- summarizeDetectorProfile,
-};
@@ -1,278 +0,0 @@
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-const RULE_ENGINE_SUPPORT = {
- regex: new Set(['source', 'page-analyzer']),
- 'static-html': new Set(['element', 'page']),
- browser: new Set(['element', 'page', 'layout']),
- visual: new Set(['visual-contrast']),
-};
-
-function getAntipattern(id) {
- return ANTIPATTERNS.find(rule => rule.id === id);
-}
-
-function getRulesForCategory(category) {
- return ANTIPATTERNS.filter(rule => rule.category === category);
-}
-
-function getRuleEngineSupport(engine) {
- return RULE_ENGINE_SUPPORT[engine] || new Set();
-}
-
-export {
- ANTIPATTERNS,
- RULE_ENGINE_SUPPORT,
- getAntipattern,
- getRulesForCategory,
- getRuleEngineSupport,
-};
@@ -1,1948 +0,0 @@
-import {
- BORDER_SAFE_TAGS,
- GENERIC_FONTS,
- KNOWN_SERIF_FONTS,
- OVERUSED_FONTS,
- SAFE_TAGS,
- WCAG_LARGE_BOLD_TEXT_PX,
- WCAG_LARGE_TEXT_PX,
- isBrandFontOnOwnDomain,
-} from '../shared/constants.mjs';
-import {
- colorToHex,
- contrastRatio,
- getHue,
- hasChroma,
- isNeutralColor,
- parseGradientColors,
- parseRgb,
- relativeLuminance,
-} from '../shared/color.mjs';
-
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-export {
- checkBorders,
- isEmojiOnlyText,
- checkColors,
- isCardLikeFromProps,
- checkIconTile,
- resolveSerif,
- checkItalicSerif,
- isAccentColor,
- checkHeroEyebrow,
- checkRepeatedSectionKickers,
- checkMotion,
- checkGlow,
- checkHtmlPatterns,
- readOwnBackgroundColor,
- resolveBackground,
- resolveGradientStops,
- parseRadiusToPx,
- resolveBorderRadiusPx,
- checkElementBordersDOM,
- checkElementColorsDOM,
- checkElementIconTileDOM,
- checkElementItalicSerifDOM,
- checkElementHeroEyebrowDOM,
- buildCustomPropMap,
- resolveVarRefs,
- oklchToRgb,
- parseAnyColor,
- parseColorResolved,
- cleanInlineText,
- isRepeatedKickerCandidate,
- collectRepeatedSectionKickerCandidates,
- checkRepeatedSectionKickersDOM,
- checkElementMotionDOM,
- checkElementGlowDOM,
- checkElementAIPaletteDOM,
- resolveFontSizePx,
- resolveLengthPx,
- checkQuality,
- checkElementQualityDOM,
- checkPageQualityFromDoc,
- checkPageQualityDOM,
- checkElementQuality,
- checkElementBorders,
- checkElementColors,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementHeroEyebrow,
- checkRepeatedSectionKickersFromDoc,
- checkElementMotion,
- checkElementGlow,
- checkTypography,
- isCardLikeDOM,
- checkLayout,
- checkPageTypography,
- isCardLike,
- checkPageLayout,
-};
@@ -1,124 +0,0 @@
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-export {
- isNeutralColor,
- parseRgb,
- relativeLuminance,
- contrastRatio,
- parseGradientColors,
- hasChroma,
- getHue,
- colorToHex,
-};
@@ -1,101 +0,0 @@
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-export {
- SAFE_TAGS,
- BORDER_SAFE_TAGS,
- OVERUSED_FONTS,
- GOOGLE_DOMAINS,
- VERCEL_DOMAINS,
- GITHUB_DOMAINS,
- BRAND_FONT_DOMAINS,
- isBrandFontOnOwnDomain,
- GENERIC_FONTS,
- WCAG_LARGE_TEXT_PX,
- WCAG_LARGE_BOLD_TEXT_PX,
- KNOWN_SERIF_FONTS,
-};
@@ -1,7 +0,0 @@
-/** Check if content looks like a full page (not a component/partial) */
-function isFullPage(content) {
- const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
- return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
-}
-
-export { isFullPage };
@@ -1,110 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-export const IMPECCABLE_DIR = '.impeccable';
-export const LIVE_DIR = 'live';
-export const CRITIQUE_DIR = 'critique';
-
-export function getImpeccableDir(cwd = process.cwd()) {
- return path.join(cwd, IMPECCABLE_DIR);
-}
-
-export function getDesignSidecarPath(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), 'design.json');
-}
-
-export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {
- const candidates = [
- getDesignSidecarPath(cwd),
- path.join(cwd, 'DESIGN.json'),
- ];
- const contextLegacy = path.join(contextDir, 'DESIGN.json');
- if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
- return candidates;
-}
-
-export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
- return firstExisting(getDesignSidecarCandidates(cwd, contextDir));
-}
-
-export function getLiveDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), LIVE_DIR);
-}
-
-export function getLiveConfigPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'config.json');
-}
-
-export function getLegacyLiveConfigPath(scriptsDir) {
- return path.join(scriptsDir, 'config.json');
-}
-
-export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {
- if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
- const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
- return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
- }
- const primary = getLiveConfigPath(cwd);
- if (fs.existsSync(primary)) return primary;
- if (scriptsDir) {
- const legacy = getLegacyLiveConfigPath(scriptsDir);
- if (fs.existsSync(legacy)) return legacy;
- }
- return primary;
-}
-
-export function getLiveServerPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'server.json');
-}
-
-export function getLegacyLiveServerPath(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live.json');
-}
-
-export function readLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try {
- return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };
- } catch {
- /* try next */
- }
- }
- return null;
-}
-
-export function writeLiveServerInfo(cwd = process.cwd(), info) {
- const filePath = getLiveServerPath(cwd);
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- fs.writeFileSync(filePath, JSON.stringify(info));
- return filePath;
-}
-
-export function removeLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try { fs.unlinkSync(filePath); } catch {}
- }
-}
-
-export function getLiveSessionsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'sessions');
-}
-
-export function getLegacyLiveSessionsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'sessions');
-}
-
-export function getLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'annotations');
-}
-
-export function getCritiqueDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), CRITIQUE_DIR);
-}
-
-export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'annotations');
-}
-
-function firstExisting(paths) {
- return paths.find((filePath) => fs.existsSync(filePath)) || null;
-}
@@ -1,69 +0,0 @@
-/**
- * Decide whether a given file is "generated" (regenerated by a build step,
- * unsafe to write variants into) or "source" (safe to edit, changes persist).
- *
- * Why this matters: when the user picks an element on a page whose underlying
- * file is regenerated by a build step (e.g. `scripts/build-sub-pages.js`
- * rewriting `public/docs/*.html`), writing variants or accepted changes into
- * that file is silent data loss — the next build wipes them.
- *
- * Signals, in order of reliability:
- * 1. Git check-ignore: gitignored files are assumed generated.
- * 2. File-header markers ("GENERATED", "DO NOT EDIT", "AUTO-GENERATED")
- * within the first ~300 characters — catches non-git projects.
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-
-const HEADER_SCAN_BYTES = 300;
-const HEADER_MARKERS = [
- /@generated\b/i,
- /\bGENERATED\s+FILE\b/,
- /\bAUTO-?GENERATED\b/i,
- /\bDO\s+NOT\s+EDIT\b/i,
-];
-
-/**
- * @param {string} filePath - absolute or cwd-relative path
- * @param {object} [options]
- * @param {string} [options.cwd] - project root (defaults to process.cwd())
- */
-export function isGeneratedFile(filePath, options = {}) {
- const cwd = options.cwd || process.cwd();
- const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
-
- if (isGitIgnored(absPath, cwd)) return true;
- if (hasGeneratedHeader(absPath)) return true;
- return false;
-}
-
-function isGitIgnored(absPath, cwd) {
- try {
- execSync(`git check-ignore --quiet ${JSON.stringify(absPath)}`, {
- cwd,
- stdio: 'ignore',
- });
- return true; // exit 0 = ignored
- } catch (err) {
- // Exit code 1 = not ignored. Exit code 128 = not a git repo or other error.
- // In both cases, treat as "not known to be ignored."
- return false;
- }
-}
-
-function hasGeneratedHeader(absPath) {
- let fd;
- try {
- fd = fs.openSync(absPath, 'r');
- const buf = Buffer.alloc(HEADER_SCAN_BYTES);
- const bytesRead = fs.readSync(fd, buf, 0, HEADER_SCAN_BYTES, 0);
- const head = buf.slice(0, bytesRead).toString('utf-8');
- return HEADER_MARKERS.some((re) => re.test(head));
- } catch {
- return false;
- } finally {
- if (fd !== undefined) { try { fs.closeSync(fd); } catch {} }
- }
-}
@@ -1,595 +0,0 @@
-/**
- * CLI helper: deterministic accept/discard of variant sessions.
- *
- * Usage:
- * node live-accept.mjs --id SESSION_ID --discard
- * node live-accept.mjs --id SESSION_ID --variant N
- *
- * For discard: removes the entire variant wrapper and restores the original.
- * For accept: replaces the wrapper with the chosen variant's content. If the
- * session had a colocated <style> block, it's preserved with carbonize markers
- * for a background agent to integrate into the project's CSS.
- *
- * Output: JSON to stdout.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-export async function acceptCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-accept.mjs [options]
-
-Deterministic accept/discard for live variant sessions.
-
-Modes:
- --discard Remove variants, restore original
- --variant N Accept variant N, discard the rest
-
-Required:
- --id SESSION_ID Session ID of the variant wrapper
-
-Output (JSON):
- { handled, file, carbonize }`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const variantNum = argVal(args, '--variant');
- const paramValuesRaw = argVal(args, '--param-values');
- const isDiscard = args.includes('--discard');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }
-
- let paramValues = null;
- if (paramValuesRaw) {
- try { paramValues = JSON.parse(paramValuesRaw); }
- catch { paramValues = null; } // malformed blob: skip the comment rather than failing the accept
- }
-
- // Find the file containing this session's markers
- const found = findSessionFile(id, process.cwd());
- if (!found) {
- console.log(JSON.stringify({ handled: false, error: 'Session markers not found for id: ' + id }));
- process.exit(0);
- }
-
- const { file: targetFile, content, lines } = found;
- const relFile = path.relative(process.cwd(), targetFile);
-
- // Bail if the session lives in a generated file. The agent manually wrote
- // the wrapper there for preview, and is responsible for writing the
- // accepted variant to true source (or cleaning up on discard). See
- // "Handle fallback" in live.md.
- if (isGeneratedFile(targetFile, { cwd: process.cwd() })) {
- console.log(JSON.stringify({
- handled: false,
- mode: 'fallback',
- file: relFile,
- hint: 'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.',
- }));
- process.exit(0);
- }
-
- if (isDiscard) {
- const result = handleDiscard(id, lines, targetFile);
- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));
- } else {
- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);
- // Single-line attention-grabber when cleanup is required. The full
- // five-step checklist lives in reference/live.md (loaded once per
- // session); repeating it per-event would waste tokens.
- if (result.carbonize) {
- result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + relFile + '. See reference/live.md "Required after accept".';
- }
- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));
- }
-}
-
-// ---------------------------------------------------------------------------
-// Discard
-// ---------------------------------------------------------------------------
-
-function handleDiscard(id, lines, targetFile) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const original = extractOriginal(lines, block);
- const isJsx = detectCommentSyntax(targetFile).open === '{/*';
- const replaceRange = expandReplaceRange(block, lines, isJsx);
-
- // Restore at the line we're actually replacing FROM, not the marker line.
- // For JSX wrappers the marker comments live INSIDE the outer `<div>`, so
- // `block.start` sits 2 spaces deeper than the original element. Using that
- // as the deindent base would push the restored content 2 spaces too far
- // right on every JSX/TSX session. `replaceRange.start` is the outer wrapper
- // line, which is at the original element's indent for both HTML and JSX.
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
- const restored = deindentContent(original, indent);
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...restored,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
- return {};
-}
-
-// ---------------------------------------------------------------------------
-// Accept
-// ---------------------------------------------------------------------------
-
-function handleAccept(id, variantNum, lines, targetFile, paramValues) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const commentSyntax = detectCommentSyntax(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- // Anchor indent on the line we're replacing FROM (the outer wrapper),
- // not on `block.start` — for JSX that's the marker comment 2 spaces
- // deeper than the original element. See handleDiscard for the full
- // rationale.
- const replaceRange = expandReplaceRange(block, lines, isJsx);
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
-
- // Extract the chosen variant's inner content
- const variantContent = extractVariant(lines, block, variantNum);
- if (!variantContent) return { handled: false, error: 'Variant ' + variantNum + ' not found' };
-
- // Extract CSS block if present
- const cssContent = extractCss(lines, block, id);
-
- // Check if carbonizing is needed:
- // - CSS block exists, OR
- // - variant HTML contains helper classes/attributes that need cleanup
- const variantText = variantContent.join('\n');
- const hasHelperAttrs = variantText.includes('data-impeccable-variant');
- const needsCarbonize = !!(cssContent || hasHelperAttrs);
-
- // Build the replacement
- const restored = deindentContent(variantContent, indent);
- const replacement = [];
-
- if (cssContent) {
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
- // JSX targets need the CSS body wrapped in a template literal so that the
- // `{` and `}` in CSS rules don't get parsed as JSX expressions.
- replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
- // Re-indent CSS content to match
- for (const cssLine of cssContent) {
- replacement.push(indent + cssLine.trimStart());
- }
- replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
- if (paramValues && Object.keys(paramValues).length > 0) {
- // Preserve the user's knob positions for the carbonize-cleanup agent
- // to bake into the final CSS when it collapses scoped rules.
- replacement.push(indent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close);
- }
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close);
- }
-
- // Keep the `@scope ([data-impeccable-variant="N"])` selectors in the
- // carbonize CSS block working visually by re-wrapping the accepted content
- // in a data-impeccable-variant="N" div with `display: contents` (so layout
- // isn't affected). The carbonize agent strips this attribute + wrapper when
- // it moves the CSS to a proper stylesheet.
- //
- // Style attribute syntax has to follow the host file's flavor — JSX files
- // need the object form, otherwise React 19 throws "Failed to set indexed
- // property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
- if (cssContent) {
- const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
- replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
- replacement.push(...restored);
- replacement.push(indent + '</div>');
- } else {
- replacement.push(...restored);
- }
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...replacement,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- return { carbonize: needsCarbonize };
-}
-
-// ---------------------------------------------------------------------------
-// Parsing helpers
-// ---------------------------------------------------------------------------
-
-/**
- * Find the start/end marker lines for a session.
- * Returns { start, end } (0-indexed line numbers) or null.
- */
-function findMarkerBlock(id, lines) {
- let start = -1;
- let end = -1;
- const startPattern = 'impeccable-variants-start ' + id;
- const endPattern = 'impeccable-variants-end ' + id;
-
- for (let i = 0; i < lines.length; i++) {
- if (start === -1 && lines[i].includes(startPattern)) start = i;
- if (lines[i].includes(endPattern)) { end = i; break; }
- }
-
- return (start !== -1 && end !== -1) ? { start, end } : null;
-}
-
-/**
- * Compute the line range to REPLACE (vs. just the marker range to extract
- * from). For JSX/TSX wrappers, live-wrap places the marker comments INSIDE
- * the `<div data-impeccable-variants="ID">` outer wrapper so the picked
- * element's JSX slot keeps a single child — a Fragment `<></>` would have
- * solved the multi-sibling case but failed inside `asChild` / cloneElement
- * parents with "Invalid prop supplied to React.Fragment".
- *
- * That means the marker block is enclosed by the wrapper `<div>` opener
- * (with `data-impeccable-variants="ID"`) and its matching `</div>`. We
- * walk back to the opener and forward to the closer so accept/discard
- * remove the entire scaffold, not just the inner markers.
- *
- * Marker lines themselves stay where they were so extractOriginal /
- * extractVariant / extractCss continue to walk the same range.
- */
-function expandReplaceRange(block, lines, isJsx) {
- if (!isJsx) return { start: block.start, end: block.end };
-
- let { start, end } = block;
-
- // Walk back for the wrapper `<div data-impeccable-variants="..."` opener.
- // The attr may sit on a continuation line of a multi-line opening tag, so
- // also walk to the line that actually contains `<div`.
- for (let i = start - 1; i >= Math.max(0, start - 12); i--) {
- if (/data-impeccable-variants=/.test(lines[i])) {
- let opener = i;
- while (opener > 0 && !/<div\b/.test(lines[opener])) opener--;
- start = opener;
- break;
- }
- }
-
- // Walk forward to the matching `</div>` by div-depth tracking from the
- // wrapper opener. Operate on JOINED text instead of per-line: a
- // multi-line self-closing JSX `<div\n className="spacer"\n/>` would
- // fool per-line regex tracking (the `<div` line matches openRe but the
- // `/>` line never matches selfCloseRe since it needs `<div` on the same
- // line). That left depth permanently over-counted and the wrapper's
- // outer `</div>` orphaned after accept/discard. Single regex with
- // `[^>]*?` (which spans newlines in JS) handles either form correctly.
- const joined = lines.slice(start).join('\n');
- // Match either `<div … />` (self-close, group 1 is `/`), `<div … >`
- // (open, group 1 is empty), or `</div>`.
- const tagRe = /<div\b[^>]*?(\/?)>|<\/div\s*>/g;
- let depth = 0;
- let m;
- while ((m = tagRe.exec(joined)) !== null) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && m[1] === '/';
- if (isClose) depth--;
- else if (!isSelfClose) depth++;
- if (depth <= 0) {
- // m.index is offset within `joined`; convert back to a file line.
- const linesBefore = joined.slice(0, m.index + m[0].length).split('\n').length - 1;
- const candidateEnd = start + linesBefore;
- if (candidateEnd >= end) {
- end = candidateEnd;
- break;
- }
- }
- }
-
- return { start, end };
-}
-
-/**
- * Join wrapper lines into a single string with `<style>` elements removed so
- * marker matching and div-depth tracking aren't confused by:
- * - CSS `@scope ([data-impeccable-variant="N"])` strings that look like the
- * HTML marker we're searching for
- * - JSX self-closing `<style ... />` (no separate `</style>` to close on)
- * - Same-line `<style>…</style>` blocks
- * - Multi-line `<style>\n…\n</style>` blocks
- */
-function stripStyleAndJoin(lines, block) {
- const out = [];
- let inStyle = false;
- for (let i = block.start; i <= block.end; i++) {
- let line = lines[i];
-
- if (!inStyle) {
- // Strip any complete <style> elements on this line (self-closed or
- // same-line-closed), including their body content.
- line = line
- .replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/g, '')
- .replace(/<style\b[^>]*\/\s*>/g, '');
-
- // If a <style> opener remains (multi-line body starts here), strip from
- // the opener to end-of-line and flip into skip mode.
- const openerIdx = line.search(/<style\b/);
- if (openerIdx !== -1) {
- line = line.slice(0, openerIdx);
- inStyle = true;
- }
- out.push(line);
- } else {
- // In multi-line style body; drop everything until we see </style>.
- const closeIdx = line.search(/<\/style\s*>/);
- if (closeIdx !== -1) {
- inStyle = false;
- out.push(line.slice(closeIdx).replace(/<\/style\s*>/, ''));
- }
- // else: skip line entirely
- }
- }
- return out.join('\n');
-}
-
-/**
- * Find the inner content of `<TAG ...attrMatch...>…</TAG>` inside `text`,
- * handling nested same-tag elements via depth counting. `attrMatch` is a
- * regex source fragment that must appear inside the opener tag.
- * Returns the inner string (may be empty), or null if not found.
- */
-function extractInnerByAttr(text, attrMatch) {
- const openerRe = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*' + attrMatch + '[^>]*>');
- const openMatch = text.match(openerRe);
- if (!openMatch) return null;
-
- const tagName = openMatch[1];
- const innerStart = openMatch.index + openMatch[0].length;
-
- // Match any opener or closer of this tag name after innerStart.
- // (Does not match self-closing <TAG … />, which doesn't contribute to depth.)
- const tagRe = new RegExp('<(?:/)?' + tagName + '\\b[^>]*>', 'g');
- tagRe.lastIndex = innerStart;
-
- let depth = 1;
- let m;
- while ((m = tagRe.exec(text))) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && /\/\s*>$/.test(m[0]);
- if (isClose) {
- depth--;
- if (depth === 0) return text.slice(innerStart, m.index);
- } else if (!isSelfClose) {
- depth++;
- }
- }
- return null;
-}
-
-/**
- * Extract the original element content from within the variant wrapper.
- * Returns an array of lines.
- */
-function extractOriginal(lines, block) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="original"');
- if (inner === null) return [];
- return inner.split('\n');
-}
-
-/**
- * Extract a specific variant's inner content (stripping the wrapper div).
- * Returns an array of lines, or null if not found.
- */
-function extractVariant(lines, block, variantNum) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + variantNum + '"');
- if (inner === null) return null;
- const result = inner.split('\n');
- // Collapse a lone empty leading/trailing line (common after string splice).
- while (result.length > 1 && result[0].trim() === '') result.shift();
- while (result.length > 1 && result[result.length - 1].trim() === '') result.pop();
- return result.length > 0 ? result : null;
-}
-
-/**
- * Extract the colocated <style> block content (between the style tags).
- * Returns an array of CSS lines, or null if no style block found.
- *
- * Handles three shapes of `<style data-impeccable-css="ID" ...>`:
- * 1. Self-closing: `<style ... />` — no body; return null (nothing to carbonize).
- * 2. Same-line open+close: `<style>...</style>` — return the inner content.
- * 3. Multi-line: `<style>` on one line, `</style>` on a later line — return
- * the lines between them.
- */
-function extractCss(lines, block, id) {
- const styleAttr = 'data-impeccable-css="' + id + '"';
- let inStyle = false;
- const content = [];
-
- for (let i = block.start; i <= block.end; i++) {
- const line = lines[i];
-
- if (!inStyle && line.includes(styleAttr)) {
- // Self-closing: nothing to carbonize.
- if (/<style\b[^>]*\/\s*>/.test(line)) return null;
- // Same-line open + close: extract inner text.
- const sameLine = line.match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/);
- if (sameLine) {
- const inner = stripJsxTemplateWrap(sameLine[1]);
- return inner.length > 0 ? inner.split('\n') : null;
- }
- inStyle = true;
- continue; // skip the <style> opening tag
- }
-
- if (inStyle) {
- // Detect </style> anywhere on the line — JSX template-literal closes
- // (`}</style>`) put the close mid-line, and we don't want to absorb the
- // template-literal punctuation as CSS content.
- const closeIdx = line.indexOf('</style>');
- if (closeIdx !== -1) break;
- content.push(line);
- }
- }
-
- if (content.length === 0) return null;
- return stripJsxTemplateLines(content);
-}
-
-/**
- * Strip a JSX template-literal wrap (`{` … `}`) from CSS extracted out of a
- * `<style>` element in a JSX/TSX file. The agent may write the wrap with
- * `{` and `}` directly attached to the `<style>` tags, on their own lines,
- * or attached to the first/last CSS lines — all three are JSX-legal.
- *
- * Stripping is required because handleAccept re-wraps the CSS itself when
- * carbonizing. Without this, two consecutive accepts (or a previously-
- * accepted variants block being carbonized) would produce nested
- * `{` `{` … `}` `}`, which oxc rejects with "Expected `}` but found `@`".
- */
-function stripJsxTemplateLines(content) {
- const out = content.slice();
-
- // Drop any leading blank lines so we don't miss a `{` line buried below
- // them; same for trailing.
- while (out.length > 0 && out[0].trim() === '') out.shift();
- while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
- if (out.length === 0) return null;
-
- // Leading `{`: own line, or attached to the first CSS line.
- const firstTrim = out[0].trimStart();
- if (firstTrim === '{`') {
- out.shift();
- } else if (firstTrim.startsWith('{`')) {
- const idx = out[0].indexOf('{`');
- out[0] = out[0].slice(0, idx) + out[0].slice(idx + 2);
- if (out[0].trim() === '') out.shift();
- }
- if (out.length === 0) return null;
-
- // Trailing `` ` `` `}`: own line, or attached to the last CSS line.
- const lastIdx = out.length - 1;
- const lastTrim = out[lastIdx].trimEnd();
- if (lastTrim === '`}') {
- out.pop();
- } else if (lastTrim.endsWith('`}')) {
- const text = out[lastIdx];
- const idx = text.lastIndexOf('`}');
- out[lastIdx] = text.slice(0, idx) + text.slice(idx + 2);
- if (out[lastIdx].trim() === '') out.pop();
- }
-
- return out.length > 0 ? out : null;
-}
-
-function stripJsxTemplateWrap(text) {
- const lines = text.split('\n');
- const stripped = stripJsxTemplateLines(lines);
- return stripped ? stripped.join('\n') : '';
-}
-
-/**
- * De-indent content that was indented by live-wrap.mjs.
- * The wrap script adds `indent + ' '` (4 extra spaces) to each line.
- * We restore to just `indent` level.
- */
-function deindentContent(contentLines, baseIndent) {
- // Find the minimum indentation in the content to determine how much was added
- let minIndent = Infinity;
- for (const line of contentLines) {
- if (line.trim() === '') continue;
- const leadingSpaces = line.match(/^(\s*)/)[1].length;
- minIndent = Math.min(minIndent, leadingSpaces);
- }
- if (minIndent === Infinity) minIndent = 0;
-
- // Strip the extra indentation and re-add base indent
- return contentLines.map(line => {
- if (line.trim() === '') return '';
- return baseIndent + line.slice(minIndent);
- });
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- return { open: '<!--', close: '-->' };
-}
-
-// ---------------------------------------------------------------------------
-// File search (find the file containing session markers)
-// ---------------------------------------------------------------------------
-
-function findSessionFile(id, cwd) {
- const marker = 'impeccable-variants-start ' + id;
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, marker, seen, 0);
- if (result) {
- const content = fs.readFileSync(result, 'utf-8');
- return { file: result, content, lines: content.split('\n') };
- }
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth) {
- if (depth > 5) return null;
- let realDir;
- try { realDir = fs.realpathSync(dir); } catch { return null; }
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- if (!EXTENSIONS.includes(path.extname(entry.name).toLowerCase())) continue;
- const filePath = path.join(dir, entry.name);
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip */ }
- }
-
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
- if (result) return result;
- }
-
- return null;
-}
-
-// ---------------------------------------------------------------------------
-// Utilities
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-accept.mjs') || _running?.endsWith('live-accept.mjs/')) {
- acceptCli();
-}
-
-export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax };
@@ -1,123 +0,0 @@
-/**
- * Browser-side durable session helpers for Impeccable live mode.
- *
- * Kept separate from live-browser.js so recovery state can be tested without
- * booting the full overlay UI. Served before live-browser.js and attached to
- * window.__IMPECCABLE_LIVE_SESSION__.
- */
-(function (root) {
- 'use strict';
-
- function createLiveBrowserSessionState({ prefix, storage, idFactory }) {
- if (!prefix) throw new Error('prefix required');
- const store = storage || root.localStorage;
- const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };
- const sessionKey = prefix + '-session';
- const handledKey = sessionKey + '-handled';
- const scrollKey = sessionKey + '-scroll';
- let checkpointRevision = 0;
- const owner = makeId();
-
- function safeRead(key) {
- try { return store.getItem(key); } catch { return null; }
- }
-
- function safeWrite(key, value) {
- try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }
- }
-
- function safeRemove(key) {
- try { store.removeItem(key); } catch { /* unavailable storage */ }
- }
-
- function loadSession() {
- try {
- const raw = safeRead(sessionKey);
- if (!raw) return null;
- const parsed = JSON.parse(raw);
- if (Number.isInteger(parsed.checkpointRevision)) {
- checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);
- }
- return parsed;
- } catch { return null; }
- }
-
- function saveSession(session) {
- if (!session || !session.id) return;
- const payload = {
- ...session,
- checkpointRevision,
- };
- safeWrite(sessionKey, JSON.stringify(payload));
- }
-
- function clearSession() {
- safeRemove(sessionKey);
- }
-
- function nextCheckpointRevision() {
- checkpointRevision += 1;
- const existing = loadSession();
- if (existing?.id) saveSession(existing);
- return checkpointRevision;
- }
-
- function seedCheckpointRevision(value) {
- if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);
- return checkpointRevision;
- }
-
- function currentCheckpointRevision() {
- return checkpointRevision;
- }
-
- function markHandled(id) {
- if (!id) return;
- safeWrite(handledKey, id);
- }
-
- function isHandled(id) {
- return !!id && safeRead(handledKey) === id;
- }
-
- function clearHandled() {
- safeRemove(handledKey);
- }
-
- function writeScrollY(y) {
- safeWrite(scrollKey, String(y));
- }
-
- function readScrollY() {
- const raw = safeRead(scrollKey);
- if (raw == null) return null;
- const n = parseFloat(raw);
- return isFinite(n) ? n : null;
- }
-
- function clearScrollY() {
- safeRemove(scrollKey);
- }
-
- return {
- owner,
- sessionKey,
- handledKey,
- scrollKey,
- saveSession,
- loadSession,
- clearSession,
- nextCheckpointRevision,
- seedCheckpointRevision,
- currentCheckpointRevision,
- markHandled,
- isHandled,
- clearHandled,
- writeScrollY,
- readScrollY,
- clearScrollY,
- };
- }
-
- root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };
-})(typeof window !== 'undefined' ? window : globalThis);
@@ -1,4860 +0,0 @@
-/**
- * Impeccable Live Variant Mode — Browser Script
- *
- * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
- * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
- * before this code.
- *
- * UI: a single floating bar that morphs between three states —
- * configure (pick action + go), generating (progressive dots), and cycling
- * (prev/next + accept/discard). Feels like Spotlight, not a modal.
- */
-(function () {
- 'use strict';
- if (typeof window === 'undefined') return;
-
- // Guard against double-init. Bun's HTML loader may process the <script> tag
- // and create a bundled copy alongside the external load, or HMR may re-execute.
- // Check BEFORE reading token/port to catch all cases.
- if (window.__IMPECCABLE_LIVE_INIT__) return;
- window.__IMPECCABLE_LIVE_INIT__ = true;
-
- const TOKEN = window.__IMPECCABLE_TOKEN__;
- const PORT = window.__IMPECCABLE_PORT__;
- if (!TOKEN || !PORT) {
- window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
- return;
- }
-
- // ---------------------------------------------------------------------------
- // Design tokens
- // ---------------------------------------------------------------------------
-
- // Brand magenta is pinned to the site token (--color-accent in main.css)
- // so Accept / knobs / cycle-dots match the site's accent, not a washed
- // theme-adjusted one.
- const C = {
- brand: 'oklch(60% 0.25 350)',
- brandHov: 'oklch(52% 0.25 350)',
- brandSoft: 'oklch(60% 0.25 350 / 0.15)',
- ink: 'oklch(15% 0.01 350)',
- ash: 'oklch(55% 0 0)',
- paper: 'oklch(98% 0.005 350 / 0.92)',
- paperSolid:'oklch(98% 0.005 350)',
- mist: 'oklch(90% 0.01 350 / 0.6)',
- white: 'oklch(99% 0 0)',
- };
- const FONT = 'system-ui, -apple-system, sans-serif';
- const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
- // z-index: detect overlays use 99999, so our UI must be above them
- const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };
- const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
- const PREFIX = 'impeccable-live';
- const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
- prefix: PREFIX,
- storage: localStorage,
- idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),
- });
- if (!sessionState) {
- console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');
- window.__IMPECCABLE_LIVE_INIT__ = false;
- return;
- }
- const HIGHLIGHT_TRANSITION =
- 'top 140ms ' + EASE +
- ', left 140ms ' + EASE +
- ', width 140ms ' + EASE +
- ', height 140ms ' + EASE +
- ', opacity 150ms ease';
- const TOOLTIP_TRANSITION =
- 'top 140ms ' + EASE + ', left 140ms ' + EASE + ', opacity 150ms ease';
-
- const SKIP_TAGS = new Set([
- 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
- ]);
-
- // SVG icons stack above each chip label. All strokes use currentColor so the
- // icon recolors to C.brand when its chip is selected. 20x20 render, 24-viewBox,
- // 1.5 stroke — visually consistent with the Foundation grid on the homepage.
- const ICON_ATTRS = 'width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block"';
- const ICONS = {
- impeccable: `<svg ${ICON_ATTRS}><path d="M4 20l4-1L18 9l-3-3L5 16z"/><path d="M14 7l3 3"/></svg>`,
- bolder: `<svg ${ICON_ATTRS}><rect x="6" y="12" width="4" height="7" rx="0.5"/><rect x="14" y="5" width="4" height="14" rx="0.5"/></svg>`,
- quieter: `<svg ${ICON_ATTRS}><rect x="6" y="5" width="4" height="14" rx="0.5"/><rect x="14" y="12" width="4" height="7" rx="0.5"/></svg>`,
- distill: `<svg ${ICON_ATTRS}><path d="M4 5h16l-6 8v7l-4-2v-5z"/></svg>`,
- polish: `<svg ${ICON_ATTRS}><path d="M15 3l1 3 3 1-3 1-1 3-1-3-3-1 3-1z"/><path d="M7 13l0.6 1.8 1.8 0.6-1.8 0.6-0.6 1.8-0.6-1.8-1.8-0.6 1.8-0.6z"/></svg>`,
- typeset: `<svg ${ICON_ATTRS}><path d="M5 6h14" stroke-width="2.6"/><path d="M5 12h9" stroke-width="1.9"/><path d="M5 18h5" stroke-width="1.3"/></svg>`,
- colorize: `<svg ${ICON_ATTRS}><circle cx="9" cy="10" r="5"/><circle cx="15" cy="10" r="5"/><circle cx="12" cy="15" r="5"/></svg>`,
- layout: `<svg ${ICON_ATTRS}><rect x="3" y="4" width="8" height="16" rx="0.5"/><rect x="13" y="4" width="8" height="7" rx="0.5"/><rect x="13" y="13" width="8" height="7" rx="0.5"/></svg>`,
- adapt: `<svg ${ICON_ATTRS}><rect x="2.5" y="5" width="12" height="11" rx="1"/><line x1="2.5" y1="19" x2="14.5" y2="19"/><rect x="16.5" y="8" width="5" height="11" rx="1"/></svg>`,
- animate: `<svg ${ICON_ATTRS}><path d="M3 18c4-4 6-10 10-10"/><path d="M13 8c3 0 5 5 8 10"/><circle cx="13" cy="8" r="1.6" fill="currentColor" stroke="none"/></svg>`,
- delight: `<svg ${ICON_ATTRS}><path d="M12 3l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>`,
- overdrive: `<svg ${ICON_ATTRS}><path d="M13 3L5 13h5l-1 8 9-12h-6z"/></svg>`,
- };
-
- const ACTIONS = [
- { value: 'impeccable', label: 'Freeform' },
- { value: 'bolder', label: 'Bolder' },
- { value: 'quieter', label: 'Quieter' },
- { value: 'distill', label: 'Distill' },
- { value: 'polish', label: 'Polish' },
- { value: 'typeset', label: 'Typeset' },
- { value: 'colorize', label: 'Colorize' },
- { value: 'layout', label: 'Layout' },
- { value: 'adapt', label: 'Adapt' },
- { value: 'animate', label: 'Animate' },
- { value: 'delight', label: 'Delight' },
- { value: 'overdrive', label: 'Overdrive' },
- ];
-
- // ---------------------------------------------------------------------------
- // State
- // ---------------------------------------------------------------------------
-
- let state = 'IDLE';
- let hoveredElement = null;
- let selectedElement = null;
- let currentSessionId = null;
- let expectedVariants = 0;
- let arrivedVariants = 0;
- let visibleVariant = 0;
- let variantObserver = null;
- let hasProjectContext = false;
- let selectedAction = 'impeccable';
- let selectedCount = 3;
- const browserOwner = sessionState.owner;
- let checkpointTimer = null;
-
- // Scroll lock — holds window.scrollY at a fixed value while the session is
- // active, so HMR DOM patches and variant swaps can't drift the page. See
- // startScrollLock / stopScrollLock below.
- let scrollLockObserver = null;
- let scrollLockTargetY = null;
- let scrollLockRaf = null;
- let scrollLockAbort = null;
-
- // Dedicated key for scroll position — SEPARATE from LS_KEY so that
- // saveSession's state updates don't clobber a carefully-captured scrollY.
- // (Previously: saveSession wrote scrollY alongside state, so every call
- // during resume overwrote the pre-reload value with whatever the browser
- // had landed on, typically 0.)
- function writeScrollY(y) { sessionState.writeScrollY(y); }
- function readScrollY() { return sessionState.readScrollY(); }
- function clearScrollY() { sessionState.clearScrollY(); }
-
- // Pre-empt the browser: apply manual scroll restoration and jump to the
- // saved scrollY at script-parse time. Retries on fonts.ready and load
- // are essential: scrollTo(y) clamps to the current document.scrollHeight,
- // which is often hundreds of pixels short of the final value until
- // async-loaded fonts swap in and reflow.
- try {
- history.scrollRestoration = 'manual';
- const savedY = readScrollY();
- if (savedY != null) {
- const apply = () => {
- if (Math.abs(window.scrollY - savedY) > 0.5) {
- console.log('[impeccable.scroll] early restore', { from: window.scrollY, to: savedY });
- window.scrollTo(0, savedY);
- }
- };
- apply();
- if (document.fonts?.ready) document.fonts.ready.then(apply).catch(() => {});
- window.addEventListener('load', apply, { once: true });
- }
- } catch {}
-
- // UI refs
- let highlightEl = null;
- let tooltipEl = null;
- let barEl = null;
- let pickerEl = null;
- let toastEl = null;
- let scrollRaf = null;
-
- // ---------------------------------------------------------------------------
- // Helpers
- // ---------------------------------------------------------------------------
-
- function own(el) {
- return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
- }
-
- function pickable(el) {
- if (!el || el.nodeType !== 1) return false;
- if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
- if (own(el)) return false;
- const r = el.getBoundingClientRect();
- return r.width >= 20 && r.height >= 20;
- }
-
- function desc(el) {
- if (!el) return '';
- let s = el.tagName.toLowerCase();
- if (el.id) s += '#' + el.id;
- else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
- return s;
- }
-
- function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
-
- // Modal-aware chrome: keep our floating UI clickable inside Radix /
- // Headless UI / vaul portals.
- //
- // Two host-page behaviors break us when the picked element lives inside a
- // modal dialog:
- //
- // 1. Modal scroll-lock disables outside pointer events. Radix's
- // `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
- // while a modal is open and only restores `auto` on the layer. Our
- // chrome inherits `none` from <body> and becomes unclickable.
- // 2. The dialog's outside-interaction handler (Radix's
- // `usePointerDownOutside`) listens at document level and dismisses
- // the dialog whenever a `pointerdown` lands outside the layer node.
- // Our chrome is a sibling of <body>, so Radix classifies our clicks
- // as outside and tears the dialog down mid-task.
- //
- // We can't reliably re-parent our chrome into the dialog subtree (z-index
- // stacking, scroll containers, theming all become host-page concerns), so
- // we defang both behaviors at our root:
- //
- // - `pointer-events: auto !important` overrides the inherited `none`.
- // - Stop `pointerdown` / `mousedown` propagation so the document-level
- // dismiss listener never fires for our clicks.
- // - Stop `focusin` propagation so any focus shifts inside our chrome
- // don't read as "focus moved outside the dialog" to focus traps.
- //
- // Click events still bubble normally — only the early pointer/focus
- // signals that drive outside-interaction detection are silenced.
- function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
- if (!rootEl) return;
- if (setPointerEvents) {
- rootEl.style.setProperty('pointer-events', 'auto', 'important');
- }
- const stop = (e) => e.stopPropagation();
- rootEl.addEventListener('pointerdown', stop);
- rootEl.addEventListener('mousedown', stop);
- rootEl.addEventListener('focusin', stop);
- }
-
- // ---------------------------------------------------------------------------
- // Highlight overlay
- // ---------------------------------------------------------------------------
-
- function initHighlight() {
- highlightEl = document.createElement('div');
- highlightEl.id = PREFIX + '-highlight';
- Object.assign(highlightEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- border: '2px solid ' + C.brand, borderRadius: '3px',
- pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
- transition: HIGHLIGHT_TRANSITION,
- display: 'none', opacity: '0',
- });
- document.body.appendChild(highlightEl);
-
- tooltipEl = document.createElement('div');
- tooltipEl.id = PREFIX + '-tooltip';
- Object.assign(tooltipEl.style, {
- position: 'fixed',
- background: C.ink, color: C.white,
- fontFamily: MONO, fontSize: '10px', fontWeight: '500',
- padding: '2px 6px', borderRadius: '3px',
- zIndex: Z.highlight + 1, pointerEvents: 'none',
- whiteSpace: 'nowrap', display: 'none',
- letterSpacing: '0.02em',
- transition: TOOLTIP_TRANSITION,
- });
- document.body.appendChild(tooltipEl);
- }
-
- function showHighlight(el) {
- if (!el || !highlightEl) return;
- const r = el.getBoundingClientRect();
- const top = (r.top - 2) + 'px', left = (r.left - 2) + 'px';
- const width = (r.width + 4) + 'px', height = (r.height + 4) + 'px';
- const tipTop = r.top - 20;
- const tipY = (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px';
- const tipX = Math.max(4, r.left) + 'px';
- tooltipEl.textContent = desc(el);
-
- const hiWasHidden = highlightEl.style.display === 'none' || highlightEl.style.opacity === '0';
- if (hiWasHidden) {
- // Snap to first target without animating from (0,0), then fade in.
- highlightEl.style.transition = 'none';
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block' });
- tooltipEl.style.transition = 'none';
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block' });
- void highlightEl.offsetWidth;
- highlightEl.style.transition = HIGHLIGHT_TRANSITION;
- highlightEl.style.opacity = '1';
- tooltipEl.style.transition = TOOLTIP_TRANSITION;
- tooltipEl.style.opacity = '1';
- } else {
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block', opacity: '1' });
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block', opacity: '1' });
- }
- }
-
- function hideHighlight() {
- if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
- if (tooltipEl) { tooltipEl.style.opacity = '0'; tooltipEl.style.display = 'none'; }
- }
-
- // ---------------------------------------------------------------------------
- // Annotation overlay (comment pins + magenta strokes)
- //
- // Active while state === 'CONFIGURING'. The overlay is a fixed-positioned
- // sibling of <body> mirroring selectedElement's bounding rect. Click (no
- // drag) drops a comment pin; drag paints a magenta SVG stroke. All coords
- // are stored in element-local CSS px so they survive scroll / resize and
- // correlate directly with the captured PNG.
- // ---------------------------------------------------------------------------
-
- const DRAG_THRESHOLD = 5; // px — below this, treat pointerup as a click
- const PIN_DBL_CLICK_MS = 300; // two clicks on the same pin within this delete it
- let annotOverlayEl = null;
- let annotSvgEl = null;
- let annotPinsEl = null;
- let annotClearChipEl = null;
- let annotState = { comments: [], strokes: [] };
- let annotActive = false;
- // `annotPointer` is either:
- // { kind: 'new', x0, y0, moved, strokeEl, strokePoints } creating a stroke/pin
- // { kind: 'pin', idx, startPointer, startPin, moved } dragging an existing pin
- let annotPointer = null;
- let annotEditing = null; // { idx, input, wrapEl }
- let annotLastPinClick = { idx: -1, time: 0 }; // for click-click-to-delete
-
- function initAnnotOverlay() {
- annotOverlayEl = document.createElement('div');
- annotOverlayEl.id = PREFIX + '-annot';
- Object.assign(annotOverlayEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- pointerEvents: 'auto', zIndex: Z.highlight + 2,
- display: 'none', overflow: 'visible',
- cursor: 'crosshair', touchAction: 'none',
- });
-
- annotSvgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- annotSvgEl.id = PREFIX + '-annot-svg';
- Object.assign(annotSvgEl.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%',
- // The SVG itself doesn't absorb clicks; individual hit-paths opt-in via
- // pointer-events=stroke so gaps still fall through to the overlay.
- pointerEvents: 'none', overflow: 'visible',
- });
- annotOverlayEl.appendChild(annotSvgEl);
-
- annotPinsEl = document.createElement('div');
- annotPinsEl.id = PREFIX + '-annot-pins';
- Object.assign(annotPinsEl.style, {
- position: 'absolute', inset: '0',
- pointerEvents: 'none',
- });
- annotOverlayEl.appendChild(annotPinsEl);
-
- annotClearChipEl = document.createElement('div');
- annotClearChipEl.id = PREFIX + '-annot-clear';
- annotClearChipEl.dataset.annotClear = 'true';
- annotClearChipEl.textContent = 'Clear';
- Object.assign(annotClearChipEl.style, {
- position: 'absolute', top: '8px', right: '8px',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '10px', fontWeight: '500',
- letterSpacing: '0.08em', textTransform: 'uppercase',
- padding: '5px 12px', borderRadius: '999px',
- cursor: 'pointer', pointerEvents: 'auto',
- display: 'none', userSelect: 'none',
- boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
- });
- annotOverlayEl.appendChild(annotClearChipEl);
-
- annotOverlayEl.addEventListener('pointerdown', onAnnotDown);
- annotOverlayEl.addEventListener('pointermove', onAnnotMove);
- annotOverlayEl.addEventListener('pointerup', onAnnotUp);
- annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
- document.body.appendChild(annotOverlayEl);
- // Modal-host friendliness: pointer-events is already 'auto' on this
- // overlay; we only need to silence the host's outside-interaction
- // listeners. Don't override pointer-events here (the overlay toggles
- // visibility via display:none, which is fine).
- defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
- }
-
- function updateClearChip() {
- if (!annotClearChipEl) return;
- const hasAny = annotState.comments.length > 0 || annotState.strokes.length > 0;
- annotClearChipEl.style.display = hasAny ? 'block' : 'none';
- }
-
- function showAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- annotActive = true;
- positionAnnotOverlay(el);
- annotOverlayEl.style.display = 'block';
- }
-
- function hideAnnotOverlay() {
- annotActive = false;
- if (annotOverlayEl) annotOverlayEl.style.display = 'none';
- // Drop any in-progress edit without touching annotState — clearAnnotations
- // (if the caller is exiting configure mode) handles state reset.
- annotEditing = null;
- }
-
- function positionAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- const r = el.getBoundingClientRect();
- Object.assign(annotOverlayEl.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- annotSvgEl.setAttribute('viewBox', '0 0 ' + r.width + ' ' + r.height);
- }
-
- function clearAnnotations() {
- annotState.comments = [];
- annotState.strokes = [];
- if (annotSvgEl) while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- if (annotPinsEl) annotPinsEl.innerHTML = '';
- annotPointer = null;
- annotEditing = null;
- annotLastPinClick = { idx: -1, time: 0 };
- updateClearChip();
- }
-
- // Rebuild the SVG layer. Each stroke gets a wider invisible hit path
- // beneath the visible magenta path so clicks register on thin lines.
- function redrawStrokes() {
- while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- annotState.strokes.forEach((s, idx) => {
- const d = pointsToPath(s.points);
- const hit = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- hit.setAttribute('d', d);
- hit.setAttribute('stroke', 'transparent');
- hit.setAttribute('stroke-width', '16');
- hit.setAttribute('stroke-linecap', 'round');
- hit.setAttribute('stroke-linejoin', 'round');
- hit.setAttribute('fill', 'none');
- hit.setAttribute('pointer-events', 'stroke');
- hit.style.cursor = 'pointer';
- hit.dataset.annotStroke = String(idx);
- annotSvgEl.appendChild(hit);
- const visible = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- visible.setAttribute('d', d);
- visible.setAttribute('stroke', C.brand);
- visible.setAttribute('stroke-width', '3');
- visible.setAttribute('stroke-linecap', 'round');
- visible.setAttribute('stroke-linejoin', 'round');
- visible.setAttribute('fill', 'none');
- visible.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(visible);
- });
- updateClearChip();
- }
-
- function localCoords(e) {
- const rect = annotOverlayEl.getBoundingClientRect();
- return { x: e.clientX - rect.left, y: e.clientY - rect.top };
- }
-
- function onAnnotDown(e) {
- if (!annotActive) return;
-
- // 1) Clear chip → wipe all annotations
- if (e.target.closest?.('[data-annot-clear]')) {
- if (annotEditing) annotEditing = null;
- clearAnnotations();
- renderAllPins();
- redrawStrokes();
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 2) Stroke hit path → delete that stroke
- const strokeHit = e.target.closest?.('[data-annot-stroke]');
- if (strokeHit) {
- const idx = parseInt(strokeHit.dataset.annotStroke, 10);
- if (Number.isInteger(idx)) {
- annotState.strokes.splice(idx, 1);
- redrawStrokes();
- }
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 3) Pin → drag, edit, or delete-on-double-click
- const pinWrap = e.target.closest?.('[data-annot-pin]');
- if (pinWrap) {
- const idx = parseInt(pinWrap.dataset.annotPin, 10);
- if (!Number.isInteger(idx)) return;
- // Double-click (two pointerdowns on the same pin within window) → delete.
- const now = Date.now();
- if (annotLastPinClick.idx === idx && now - annotLastPinClick.time < PIN_DBL_CLICK_MS) {
- if (annotEditing && annotEditing.idx === idx) annotEditing = null;
- annotState.comments.splice(idx, 1);
- annotLastPinClick = { idx: -1, time: 0 };
- renderAllPins();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- annotLastPinClick = { idx, time: now };
- // If editing a different pin, commit that edit before starting here.
- if (annotEditing && annotEditing.idx !== idx) finalizeEditingPin();
- // If already editing THIS pin and the user clicked the dot, let the
- // input keep focus (don't start a drag — the click wasn't meant as one).
- if (annotEditing && annotEditing.idx === idx) return;
- const p = localCoords(e);
- const pin = annotState.comments[idx];
- annotPointer = {
- kind: 'pin', idx,
- startPointer: p,
- startPin: { x: pin.x, y: pin.y },
- moved: false,
- };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 4) Empty area → commit any open edit, then start new annotation
- if (annotEditing) {
- finalizeEditingPin();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- const p = localCoords(e);
- annotPointer = { kind: 'new', x0: p.x, y0: p.y, moved: false, strokeEl: null, strokePoints: null };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- }
-
- function onAnnotMove(e) {
- if (!annotActive || !annotPointer) return;
- const p = localCoords(e);
-
- if (annotPointer.kind === 'pin') {
- const dx = p.x - annotPointer.startPointer.x;
- const dy = p.y - annotPointer.startPointer.y;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- }
- const pin = annotState.comments[annotPointer.idx];
- if (!pin) { annotPointer = null; return; }
- pin.x = annotPointer.startPin.x + dx;
- pin.y = annotPointer.startPin.y + dy;
- renderAllPins();
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const dx = p.x - annotPointer.x0, dy = p.y - annotPointer.y0;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- const strokeEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- strokeEl.setAttribute('stroke', C.brand);
- strokeEl.setAttribute('stroke-width', '3');
- strokeEl.setAttribute('stroke-linecap', 'round');
- strokeEl.setAttribute('stroke-linejoin', 'round');
- strokeEl.setAttribute('fill', 'none');
- strokeEl.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(strokeEl);
- annotPointer.strokeEl = strokeEl;
- annotPointer.strokePoints = [[annotPointer.x0, annotPointer.y0]];
- }
- annotPointer.strokePoints.push([p.x, p.y]);
- annotPointer.strokeEl.setAttribute('d', pointsToPath(annotPointer.strokePoints));
- e.stopPropagation();
- }
-
- function onAnnotUp(e) {
- if (!annotActive || !annotPointer) return;
-
- if (annotPointer.kind === 'pin') {
- const wasDrag = annotPointer.moved;
- const idx = annotPointer.idx;
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- if (wasDrag) {
- // A drag is an intentional reposition; a follow-up click shouldn't be
- // interpreted as a double-click-to-delete.
- annotLastPinClick = { idx: -1, time: 0 };
- } else {
- beginEditPin(idx);
- }
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const wasDrag = annotPointer.moved;
- if (wasDrag) {
- annotState.strokes.push({ points: annotPointer.strokePoints });
- // Swap the temporary preview SVG path for the full render with hit paths.
- redrawStrokes();
- } else {
- const idx = annotState.comments.length;
- annotState.comments.push({ x: annotPointer.x0, y: annotPointer.y0, text: '' });
- renderAllPins();
- beginEditPin(idx);
- }
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- e.stopPropagation();
- }
-
- function pointsToPath(points) {
- if (!points || points.length === 0) return '';
- let d = 'M' + points[0][0].toFixed(1) + ' ' + points[0][1].toFixed(1);
- for (let i = 1; i < points.length; i++) {
- d += ' L' + points[i][0].toFixed(1) + ' ' + points[i][1].toFixed(1);
- }
- return d;
- }
-
- function renderAllPins() {
- annotPinsEl.innerHTML = '';
- annotState.comments.forEach((c, idx) => {
- annotPinsEl.appendChild(buildPinElement(c, idx));
- });
- updateClearChip();
- }
-
- function buildPinElement(comment, idx) {
- const interactive = idx >= 0;
- const wrap = document.createElement('div');
- if (interactive) wrap.dataset.annotPin = String(idx);
- Object.assign(wrap.style, {
- position: 'absolute',
- left: (comment.x - 7) + 'px', top: (comment.y - 7) + 'px',
- pointerEvents: interactive ? 'auto' : 'none',
- display: 'flex', alignItems: 'flex-start', gap: '6px',
- cursor: interactive ? 'grab' : 'default',
- touchAction: 'none',
- });
- const dot = document.createElement('div');
- Object.assign(dot.style, {
- width: '14px', height: '14px', borderRadius: '50%',
- background: C.brand, border: '2px solid ' + C.white,
- boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
- flexShrink: '0',
- });
- wrap.appendChild(dot);
-
- if (comment.text) {
- const bubble = document.createElement('div');
- bubble.textContent = comment.text;
- Object.assign(bubble.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- marginTop: '-2px', maxWidth: '220px',
- pointerEvents: 'none', whiteSpace: 'pre-wrap',
- wordBreak: 'break-word',
- });
- wrap.appendChild(bubble);
- }
- return wrap;
- }
-
- function beginEditPin(idx) {
- const wrapEl = annotPinsEl.querySelector('[data-annot-pin="' + idx + '"]');
- if (!wrapEl) return;
- // Strip any existing bubble (but keep the dot)
- wrapEl.querySelectorAll('div:not(:first-child)').forEach(n => n.remove());
- const input = document.createElement('input');
- input.type = 'text';
- input.placeholder = 'Note…';
- Object.assign(input.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- border: '1px solid ' + C.brand,
- outline: 'none', marginTop: '-2px',
- width: '220px', pointerEvents: 'auto',
- });
- const originalText = annotState.comments[idx].text || '';
- input.value = originalText;
- wrapEl.appendChild(input);
- annotEditing = { idx, input, wrapEl, originalText };
- input.addEventListener('keydown', onAnnotInputKey, true);
- input.addEventListener('blur', () => {
- // Fires on both focus-loss and programmatic blur; commit unless we
- // already handled it.
- if (annotEditing && annotEditing.input === input) finalizeEditingPin();
- });
- // Stop clicks/pointerdowns inside the input from bubbling to the overlay
- ['pointerdown', 'click'].forEach(ev => {
- input.addEventListener(ev, e => e.stopPropagation());
- });
- setTimeout(() => input.focus(), 0);
- }
-
- function onAnnotInputKey(e) {
- if (e.key === 'Enter') {
- e.preventDefault(); e.stopPropagation();
- finalizeEditingPin();
- } else if (e.key === 'Escape') {
- e.preventDefault(); e.stopPropagation();
- cancelEditingPin();
- } else {
- // Keep arrows / backspace from hitting global handlers
- e.stopPropagation();
- }
- }
-
- function finalizeEditingPin() {
- if (!annotEditing) return;
- const { idx, input } = annotEditing;
- const text = input.value.trim();
- annotEditing = null;
- if (text) annotState.comments[idx].text = text;
- else annotState.comments.splice(idx, 1);
- renderAllPins();
- }
-
- function cancelEditingPin() {
- if (!annotEditing) return;
- const { idx, originalText } = annotEditing;
- annotEditing = null;
- // If the pin had text before this edit, revert to it. If it was a
- // just-created empty pin, Escape removes it.
- if (originalText) {
- annotState.comments[idx].text = originalText;
- } else {
- annotState.comments.splice(idx, 1);
- }
- renderAllPins();
- }
-
- // Build a detached annotation subtree suitable for injection into the clone
- // modern-screenshot creates. Coordinates are element-local so this slots
- // straight into an element that's been made position:relative. Takes an
- // explicit snapshot so it works after annotState has been cleared.
- function buildAnnotationsForCapture(rect, snapshot) {
- const comments = snapshot ? snapshot.comments : annotState.comments;
- const strokes = snapshot ? snapshot.strokes : annotState.strokes;
- if (comments.length === 0 && strokes.length === 0) return null;
- const wrap = document.createElement('div');
- Object.assign(wrap.style, {
- position: 'absolute', top: '0', left: '0',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none', overflow: 'visible',
- });
- if (strokes.length > 0) {
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- svg.setAttribute('viewBox', '0 0 ' + rect.width + ' ' + rect.height);
- Object.assign(svg.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%', overflow: 'visible',
- });
- for (const s of strokes) {
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- path.setAttribute('stroke', C.brand);
- path.setAttribute('stroke-width', '3');
- path.setAttribute('stroke-linecap', 'round');
- path.setAttribute('stroke-linejoin', 'round');
- path.setAttribute('fill', 'none');
- path.setAttribute('d', pointsToPath(s.points));
- svg.appendChild(path);
- }
- wrap.appendChild(svg);
- }
- for (const c of comments) {
- // idx=-1 means non-interactive; pointerEvents stay off in the clone
- wrap.appendChild(buildPinElement(c, -1));
- }
- return wrap;
- }
-
- // ---------------------------------------------------------------------------
- // Element context extraction
- // ---------------------------------------------------------------------------
-
- function extractContext(el) {
- const cs = getComputedStyle(el);
- const r = el.getBoundingClientRect();
- const props = {};
- for (const sheet of document.styleSheets) {
- try {
- for (const rule of sheet.cssRules) {
- if (rule.style) for (let i = 0; i < rule.style.length; i++) {
- const p = rule.style[i];
- if (p.startsWith('--') && !props[p]) {
- const v = cs.getPropertyValue(p).trim();
- if (v) props[p] = v;
- }
- }
- }
- } catch { /* cross-origin */ }
- }
- return {
- tagName: el.tagName.toLowerCase(), id: el.id || null,
- classes: [...el.classList],
- textContent: (el.textContent || '').slice(0, 500),
- outerHTML: el.outerHTML.slice(0, 10000),
- computedStyles: {
- 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
- 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
- 'color': cs.color, 'background': cs.background,
- 'background-color': cs.backgroundColor,
- 'padding': cs.padding, 'margin': cs.margin,
- 'display': cs.display, 'position': cs.position,
- 'gap': cs.gap, 'border-radius': cs.borderRadius,
- 'box-shadow': cs.boxShadow,
- },
- cssCustomProperties: props,
- parentContext: el.parentElement
- ? '<' + el.parentElement.tagName.toLowerCase()
- + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
- + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
- + '>'
- : null,
- boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
- };
- }
-
- // ---------------------------------------------------------------------------
- // The Bar — one floating element, three modes
- // ---------------------------------------------------------------------------
-
- // Contextual-bar palette. Cached at init so every build*Row reads a
- // consistent set of colors; detectPageTheme runs once rather than on every
- // phase transition.
- let BP = null;
-
- // Bar shadow variants. The default projects down + subtle around. When
- // the Tune popover opens below the bar, a downward shadow lands on the
- // dark popover and reads as a bright ghost line. We swap to UP-only while
- // tune is open below so the popover's top edge is clean.
- const BAR_SHADOW_DEFAULT = '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_UP = '0 -4px 20px oklch(0% 0 0 / 0.08), 0 -1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_DOWN = BAR_SHADOW_DEFAULT;
-
- function initBar() {
- BP = barPaletteForTheme(detectPageTheme());
- barEl = document.createElement('div');
- barEl.id = PREFIX + '-bar';
- Object.assign(barEl.style, {
- position: 'fixed', zIndex: Z.bar,
- display: 'none', opacity: '0',
- transform: 'translateY(6px)',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- background: BP.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + BP.hairline,
- borderRadius: '10px',
- boxShadow: BAR_SHADOW_DEFAULT,
- transition: 'box-shadow 0.2s ease, opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- fontFamily: FONT, fontSize: '13px', color: BP.text,
- padding: '6px',
- maxWidth: '520px', minWidth: '320px',
- });
- document.body.appendChild(barEl);
- defangOutsideHandlers(barEl);
- }
-
- function positionBar() {
- if (!barEl || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- const barH = barEl.offsetHeight || 44;
- const barW = barEl.offsetWidth || 380;
- const GLOBAL_BAR_RESERVE = 64; // global bar height + bottom margin + breathing room
- const GAP = 8;
-
- // Prefer below the element; fall back to above; if neither fits (element
- // taller than viewport), pin to a stable viewport anchor so the bar
- // doesn't teleport between top and bottom as the user scrolls.
- let top;
- const belowTop = r.bottom + GAP;
- const aboveTop = r.top - barH - GAP;
- if (belowTop + barH + GAP <= window.innerHeight - GLOBAL_BAR_RESERVE) {
- top = belowTop;
- } else if (aboveTop >= GAP) {
- top = aboveTop;
- } else {
- top = window.innerHeight - barH - GLOBAL_BAR_RESERVE;
- }
-
- let left = r.left + (r.width - barW) / 2;
- if (left < GAP) left = GAP;
- if (left + barW > window.innerWidth - GAP) left = window.innerWidth - barW - GAP;
- Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
- }
-
- function showBar(mode) {
- barEl.innerHTML = '';
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- barEl.style.display = 'block';
- positionBar();
- requestAnimationFrame(() => {
- barEl.style.opacity = '1';
- barEl.style.transform = 'translateY(0)';
- });
- }
-
- function hideBar() {
- if (!barEl) return;
- barEl.style.opacity = '0';
- barEl.style.transform = 'translateY(6px)';
- setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
- hideActionPicker();
- closeTunePopover();
- }
-
- function updateBarContent(mode) {
- if (!barEl || barEl.style.display === 'none') return;
- barEl.innerHTML = '';
- // Reset bar styling to the theme-aware palette
- barEl.style.background = BP.surface;
- barEl.style.border = '1px solid ' + BP.hairline;
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- else if (mode === 'saving') barEl.appendChild(buildSavingRow());
- else if (mode === 'confirmed') {
- barEl.appendChild(buildConfirmedRow());
- barEl.style.background = 'oklch(95% 0.05 145)';
- barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
- }
- }
-
- // --- Configure row ---
-
- function buildConfigureRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
-
- // Action pill
- const pill = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '4px',
- padding: '5px 10px', borderRadius: '6px',
- background: BP.mark, color: BP.markText,
- fontFamily: FONT, fontSize: '12px', fontWeight: '500',
- border: 'none', cursor: 'pointer',
- transition: 'background 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap', flexShrink: '0',
- });
- pill.textContent = actionLabel() + ' \u25BE';
- pill.addEventListener('mouseenter', () => pill.style.background = BP.accent);
- pill.addEventListener('mouseleave', () => pill.style.background = BP.mark);
- pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
- pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
- pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
- row.appendChild(pill);
-
- // Freeform input. Focus state shows an accent-colored border only —
- // an earlier version tinted the background with `BP.accentSoft`, which
- // composited against the dark bar surface to a murky purple where the
- // browser's default placeholder gray was unreadable. Placeholder color
- // is set explicitly via a one-shot stylesheet keyed off this input's id
- // so it picks up the bar's `textDim` token in both themes.
- const input = document.createElement('input');
- input.id = PREFIX + '-input';
- input.type = 'text';
- input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
- Object.assign(input.style, {
- flex: '1', minWidth: '0',
- padding: '5px 8px', borderRadius: '6px',
- border: '1px solid transparent', background: 'transparent',
- fontFamily: FONT, fontSize: '12px', color: BP.text,
- outline: 'none',
- transition: 'border-color 0.15s ease',
- });
- if (!document.getElementById(PREFIX + '-input-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-input-style';
- s.textContent =
- '#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
- document.head.appendChild(s);
- }
- input.addEventListener('focus', () => {
- input.style.borderColor = BP.accent;
- });
- input.addEventListener('blur', () => {
- input.style.borderColor = 'transparent';
- });
- input.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
- if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; return; }
- // Let arrow keys pass through to the element picker when the input is empty
- if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && !input.value) return;
- e.stopPropagation();
- });
- row.appendChild(input);
-
- // Variant count toggle
- const count = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: MONO, fontSize: '11px', fontWeight: '600',
- color: BP.textDim, cursor: 'pointer',
- transition: 'color 0.12s ease, border-color 0.12s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- count.textContent = '\u00D7' + selectedCount;
- count.title = 'Variants: click to change';
- count.addEventListener('mouseenter', () => { count.style.color = BP.text; count.style.borderColor = BP.text; });
- count.addEventListener('mouseleave', () => { count.style.color = BP.textDim; count.style.borderColor = BP.hairline; });
- count.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
- count.textContent = '\u00D7' + selectedCount;
- });
- row.appendChild(count);
-
- // Go button
- const go = el('button', {
- padding: '5px 12px', borderRadius: '6px',
- border: 'none', background: BP.accent, color: BP.mark,
- fontFamily: FONT, fontSize: '12px', fontWeight: '600',
- cursor: 'pointer',
- transition: 'filter 0.12s ease, transform 0.1s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- go.textContent = 'Go \u2192';
- go.addEventListener('mouseenter', () => go.style.filter = 'brightness(1.1)');
- go.addEventListener('mouseleave', () => go.style.filter = 'none');
- go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
- go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
- go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
- row.appendChild(go);
-
- // Auto-focus input after a beat
- setTimeout(() => input.focus(), 60);
- return row;
- }
-
- // --- Generating row ---
-
- function buildGeneratingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 4px',
- });
-
- // Action label
- const label = el('span', {
- fontWeight: '600', fontSize: '12px', color: BP.text,
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- label.textContent = actionLabel();
- row.appendChild(label);
-
- // Dots
- row.appendChild(buildDots(false));
-
- // Status
- const status = el('span', {
- fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',
- marginLeft: 'auto',
- });
- // Variants currently arrive atomically in a single file edit, so a
- // per-variant counter would lie. Say what's true.
- status.textContent = arrivedVariants < expectedVariants
- ? 'Generating ' + expectedVariants + ' variants...'
- : 'Done';
- row.appendChild(status);
-
- return row;
- }
-
- // --- Cycling row ---
-
- const TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';
-
- function buildCyclingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '6px',
- padding: '1px 2px',
- });
-
- // Prev
- const prev = navBtn('\u2190');
- prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
- if (visibleVariant <= 1) prev.style.opacity = '0.3';
- row.appendChild(prev);
-
- // Dots (clickable)
- row.appendChild(buildDots(true));
-
- // Counter
- const counter = el('span', {
- fontFamily: MONO, fontSize: '11px', fontWeight: '500',
- color: BP.textDim, minWidth: '24px', textAlign: 'center',
- });
- counter.textContent = visibleVariant + '/' + arrivedVariants;
- row.appendChild(counter);
-
- // Next
- const next = navBtn('\u2192');
- next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
- if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
- row.appendChild(next);
-
- // Tune chip — only when the visible variant exposes params
- const visParams = parseVariantParams(getVisibleVariantEl());
- const hasParams = visParams.length > 0;
- if (hasParams) {
- const tune = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '6px',
- padding: '4px 10px', borderRadius: '5px',
- border: '1px solid transparent',
- background: tuneOpen ? BP.accentSoft : 'transparent',
- color: tuneOpen ? BP.accent : BP.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'color 0.12s ease, background 0.12s ease',
- whiteSpace: 'nowrap',
- });
- tune.innerHTML = TUNE_ICON_SVG;
- const tuneLabel = document.createElement('span');
- tuneLabel.textContent = 'Tune';
- tune.appendChild(tuneLabel);
- const tuneBadge = document.createElement('span');
- Object.assign(tuneBadge.style, {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- minWidth: '16px', height: '16px', padding: '0 4px',
- borderRadius: '999px',
- background: tuneOpen ? C.brand : BP.hairline,
- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',
- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',
- lineHeight: '1',
- boxSizing: 'border-box',
- });
- tuneBadge.textContent = String(visParams.length);
- tune.appendChild(tuneBadge);
- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';
- tune.addEventListener('mouseenter', () => {
- if (!tuneOpen) tune.style.background = BP.accentSoft;
- });
- tune.addEventListener('mouseleave', () => {
- if (!tuneOpen) tune.style.background = 'transparent';
- });
- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });
- tune.dataset.iceqTune = '1';
- row.appendChild(tune);
- }
-
- // Spacer
- row.appendChild(el('div', { flex: '1' }));
-
- // Accept — primary action, uses the site's saturated brand magenta
- // with paper-white text, not the theme-muted BP.accent.
- const accept = el('button', {
- padding: '5px 14px', borderRadius: '5px',
- border: 'none', background: C.brand, color: 'oklch(98% 0 0)',
- fontFamily: FONT, fontSize: '11px', fontWeight: '600',
- cursor: 'pointer', transition: 'filter 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap',
- });
- accept.textContent = '\u2713 Accept';
- accept.addEventListener('mouseenter', () => accept.style.filter = 'brightness(1.08)');
- accept.addEventListener('mouseleave', () => accept.style.filter = 'none');
- accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');
- accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');
- accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
- row.appendChild(accept);
-
- // Discard
- const discard = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: FONT, fontSize: '11px', color: BP.textDim,
- cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
- });
- discard.textContent = '\u2715';
- discard.title = 'Discard all variants';
- discard.addEventListener('mouseenter', () => { discard.style.color = BP.text; discard.style.borderColor = BP.text; });
- discard.addEventListener('mouseleave', () => { discard.style.color = BP.textDim; discard.style.borderColor = BP.hairline; });
- discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
- row.appendChild(discard);
-
- return row;
- }
-
- // --- Shared UI builders ---
-
- // --- Saving row (waiting for agent to process accept/discard) ---
-
- function buildSavingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const spinner = el('div', {
- width: '14px', height: '14px', borderRadius: '50%',
- border: '2px solid ' + BP.hairline,
- borderTopColor: BP.accent,
- animation: 'impeccable-spin 0.6s linear infinite',
- flexShrink: '0',
- });
- row.appendChild(spinner);
- const label = el('span', {
- fontSize: '12px', color: BP.textDim, fontWeight: '500',
- });
- label.textContent = 'Applying variant...';
- row.appendChild(label);
-
- // Inject the keyframes if not already present
- if (!document.getElementById(PREFIX + '-keyframes')) {
- const style = document.createElement('style');
- style.id = PREFIX + '-keyframes';
- style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
- document.head.appendChild(style);
- }
- return row;
- }
-
- // --- Confirmed row (green success, auto-dismisses) ---
-
- function buildConfirmedRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const check = el('span', {
- fontSize: '15px', lineHeight: '1', flexShrink: '0',
- color: 'oklch(45% 0.15 145)',
- });
- check.textContent = '\u2713';
- row.appendChild(check);
- const label = el('span', {
- fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
- });
- label.textContent = 'Variant applied';
- row.appendChild(label);
- return row;
- }
-
- // --- Shared UI builders ---
-
- function buildDots(clickable) {
- const container = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
- for (let i = 1; i <= expectedVariants; i++) {
- const arrived = i <= arrivedVariants;
- const active = i === visibleVariant;
- // active: solid site-brand magenta dot. arrived+inactive: muted neutral.
- // pending (not yet arrived): faint outline ring. No borders on arrived
- // dots — the previous "accent ring + ash fill" combo read as noisy
- // magenta chips, especially when all variants had arrived and every
- // dot wore an accent ring.
- const dotBg = active ? C.brand
- : arrived ? BP.textDim
- : 'transparent';
- const dotBorder = arrived ? 'none' : '1.5px solid ' + BP.hairline;
- const dot = el('div', {
- width: active ? '8px' : '6px',
- height: active ? '8px' : '6px',
- borderRadius: '50%',
- background: dotBg,
- border: dotBorder,
- boxSizing: 'border-box',
- transition: 'all 0.2s ' + EASE,
- cursor: (clickable && arrived) ? 'pointer' : 'default',
- transform: arrived ? 'scale(1)' : 'scale(0.85)',
- opacity: arrived ? (active ? '1' : '0.6') : '0.4',
- });
- if (clickable && arrived) {
- const idx = i;
- dot.addEventListener('click', (e) => {
- e.stopPropagation();
- visibleVariant = idx;
- showVariantInDOM(currentSessionId, idx);
- updateSelectedElement();
- updateBarContent('cycling');
- });
- }
- container.appendChild(dot);
- }
- return container;
- }
-
- function navBtn(text) {
- const b = el('button', {
- width: '26px', height: '26px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- color: BP.text, fontFamily: FONT, fontSize: '13px',
- cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
- transition: 'border-color 0.12s ease, background 0.12s ease',
- padding: '0', lineHeight: '1',
- });
- b.textContent = text;
- b.addEventListener('mouseenter', () => { b.style.borderColor = BP.text; });
- b.addEventListener('mouseleave', () => { b.style.borderColor = BP.hairline; });
- return b;
- }
-
- function actionLabel() {
- const a = ACTIONS.find(a => a.value === selectedAction);
- return a ? a.label : 'Freeform';
- }
-
- function el(tag, styles) {
- const e = document.createElement(tag);
- if (styles) Object.assign(e.style, styles);
- return e;
- }
-
- // ---------------------------------------------------------------------------
- // Action picker popover
- // ---------------------------------------------------------------------------
-
- function initActionPicker() {
- const P = barPaletteForTheme(detectPageTheme());
- pickerEl = document.createElement('div');
- pickerEl.id = PREFIX + '-picker';
- Object.assign(pickerEl.style, {
- position: 'fixed', zIndex: Z.picker,
- display: 'none', opacity: '0',
- transform: 'scale(0.96) translateY(4px)',
- transformOrigin: 'bottom left',
- transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
- background: P.surface,
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
- padding: '6px',
- fontFamily: FONT,
- backdropFilter: 'blur(10px)',
- WebkitBackdropFilter: 'blur(10px)',
- });
-
- // Build the chip grid
- const grid = el('div', {
- display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
- });
-
- ACTIONS.forEach(action => {
- const chip = el('button', {
- display: 'flex', flexDirection: 'column', alignItems: 'center',
- gap: '4px',
- padding: '8px 6px', borderRadius: '6px',
- border: 'none',
- background: action.value === selectedAction ? P.accentSoft : 'transparent',
- color: action.value === selectedAction ? P.accent : P.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.1s ease, color 0.1s ease',
- textAlign: 'center', whiteSpace: 'nowrap',
- });
- const iconWrap = el('span', {
- display: 'flex', alignItems: 'center', justifyContent: 'center',
- height: '20px', opacity: '0.9',
- });
- iconWrap.innerHTML = ICONS[action.value] || '';
- const labelEl = el('span', { lineHeight: '1' });
- labelEl.textContent = action.label;
- chip.appendChild(iconWrap);
- chip.appendChild(labelEl);
- chip.dataset.action = action.value;
- chip.addEventListener('mouseenter', () => {
- if (action.value !== selectedAction) chip.style.background = P.accentSoft;
- });
- chip.addEventListener('mouseleave', () => {
- chip.style.background = action.value === selectedAction ? P.accentSoft : 'transparent';
- });
- chip.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedAction = action.value;
- hideActionPicker();
- updateBarContent('configure');
- });
- grid.appendChild(chip);
- });
-
- pickerEl.appendChild(grid);
- document.body.appendChild(pickerEl);
- defangOutsideHandlers(pickerEl);
-
- // Cache the palette on the picker so toggleActionPicker's state refresh
- // uses the same theme-aware colors when it repaints chips.
- pickerEl.__iceq_palette = P;
- }
-
- function toggleActionPicker() {
- if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
- // Rebuild chips to reflect current selection
- const P = pickerEl.__iceq_palette || barPaletteForTheme(detectPageTheme());
- pickerEl.querySelectorAll('button').forEach(chip => {
- const isActive = chip.dataset.action === selectedAction;
- chip.style.background = isActive ? P.accentSoft : 'transparent';
- chip.style.color = isActive ? P.accent : P.text;
- });
- // Position above the bar
- const barRect = barEl.getBoundingClientRect();
- const pickerH = 170; // approximate; grows with icon + label rows
- let top = barRect.top - pickerH - 6;
- if (top < 8) top = barRect.bottom + 6;
- Object.assign(pickerEl.style, {
- top: top + 'px', left: barRect.left + 'px',
- display: 'block',
- });
- requestAnimationFrame(() => {
- pickerEl.style.opacity = '1';
- pickerEl.style.transform = 'scale(1) translateY(0)';
- });
- }
-
- function hideActionPicker() {
- if (!pickerEl) return;
- pickerEl.style.opacity = '0';
- pickerEl.style.transform = 'scale(0.96) translateY(4px)';
- setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
- }
-
- // ---------------------------------------------------------------------------
- // Params panel (per-variant coarse controls)
- //
- // Variants may declare a parameter manifest via a JSON attribute on the
- // variant wrapper:
- //
- // <div data-impeccable-variant="1"
- // data-impeccable-params='[{"id":"density","kind":"steps",...}]'>
- //
- // The panel docks to the right edge of the outline during CYCLING and
- // exposes 2-5 coarse knobs. Values apply to the variant wrapper so scoped
- // CSS can respond instantly without regeneration:
- //
- // range / numeric toggle → CSS var (`--p-<id>`) used via var(--p-foo, N)
- // steps / boolean toggle → data-p-<id> attribute used via :scope[data-p-foo="..."]
- //
- // On variant switch, values reset to that variant's declared defaults.
- // On accept, current values are sent in the event payload so the agent
- // can bake them into the source-file write.
- // ---------------------------------------------------------------------------
-
- let paramsPanelEl = null; // outer wrapper (overflow:hidden, clips the slide)
- let paramsPanelInner = null; // translating content (carries bg, padding, knobs)
- let paramsPanelBody = null; // grid holding the knob cells
- let paramsCurrentValues = {}; // {paramId: value} — mirror of the visible variant's live values
- let tuneOpen = false; // whether the Tune popover is open right now
-
- // Theme-aware Tune popover. Appears as a drawer that slides out from the
- // contextual bar's bar-facing edge (below if the bar sits below the
- // element, above otherwise). Same width as the bar. Auto-wraps to extra
- // rows when the knobs exceed one row. The bar's border-radius on the
- // popover side goes flat while open so the two shapes read as one.
- let paramsPanelPalette = null;
-
- function initParamsPanel() {
- paramsPanelPalette = barPaletteForTheme(detectPageTheme());
- const P = paramsPanelPalette;
-
- // Single element, always in the DOM. The slide animation is a CSS mask
- // with mask-size growing from 0% to 100% along the bar-facing axis — no
- // display toggle, no opacity toggle, no transform trickery. The mask
- // hides everything initially; as it grows, content is revealed from
- // the bar edge outward.
- paramsPanelEl = document.createElement('div');
- paramsPanelEl.id = PREFIX + '-params-panel';
- Object.assign(paramsPanelEl.style, {
- position: 'fixed', zIndex: String(Z.bar - 1),
- background: P.surfaceDeep,
- color: P.text,
- fontFamily: FONT,
- padding: '14px 18px',
- boxSizing: 'border-box',
- borderRadius: '0 0 10px 10px',
- pointerEvents: 'none',
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
-
- // clip-path is the same conceptual reveal as mask but with rock-solid
- // transition support across engines. Closed state clips from the far
- // edge; open = inset(0) shows everything.
- clipPath: 'inset(0 0 100% 0)',
- transition: 'clip-path 0.44s ' + EASE,
-
- // Park off-screen until positionParamsPanel places it. These are NOT
- // in the transition list, so they snap instantly — no fly-in from the
- // top-left when first shown.
- top: '-9999px', left: '-9999px', width: '0',
- });
-
- paramsPanelBody = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
- gap: '12px 16px',
- });
-
- paramsPanelEl.appendChild(paramsPanelBody);
- document.body.appendChild(paramsPanelEl);
- // Don't override pointer-events: the panel toggles between 'none' (closed,
- // click-through) and 'auto' (open) on its own. Just silence the host's
- // outside-interaction listeners while the panel is open.
- defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
- paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
- }
-
- function getVisibleVariantEl() {
- if (!currentSessionId) return null;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return null;
- return wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"]');
- }
-
- function parseVariantParams(variantEl) {
- if (!variantEl) return [];
- const raw = variantEl.getAttribute('data-impeccable-params');
- if (!raw) return [];
- try {
- const parsed = JSON.parse(raw);
- return Array.isArray(parsed) ? parsed : [];
- } catch (err) {
- console.warn('[impeccable] Invalid data-impeccable-params JSON:', err.message);
- return [];
- }
- }
-
- function applyParamValue(variantEl, param, value) {
- if (!variantEl) return;
- const attr = 'data-p-' + param.id;
- if (param.kind === 'range') {
- variantEl.style.setProperty('--p-' + param.id, String(value));
- } else if (param.kind === 'toggle') {
- const on = !!value;
- variantEl.style.setProperty('--p-' + param.id, on ? '1' : '0');
- if (on) variantEl.setAttribute(attr, 'on');
- else variantEl.removeAttribute(attr);
- } else if (param.kind === 'steps') {
- variantEl.setAttribute(attr, String(value));
- }
- }
-
- function applyParamDefaults(variantEl, params) {
- paramsCurrentValues = {};
- for (const p of params) {
- paramsCurrentValues[p.id] = p.default;
- applyParamValue(variantEl, p, p.default);
- }
- }
-
- function formatRangeValue(input) {
- const max = parseFloat(input.max), min = parseFloat(input.min);
- const v = parseFloat(input.value);
- if (!isFinite(v)) return input.value;
- return (max - min) <= 2 ? v.toFixed(2) : String(Math.round(v));
- }
-
- function buildParamsPanel(variantEl, params) {
- const P = paramsPanelPalette || barPaletteForTheme(detectPageTheme());
- paramsPanelBody.innerHTML = '';
- for (const p of params) {
- const row = el('div', { display: 'flex', flexDirection: 'column', gap: '6px' });
- const labelRow = el('div', {
- display: 'flex', justifyContent: 'space-between',
- alignItems: 'baseline', gap: '8px',
- });
- const lbl = el('span', {
- fontSize: '10.5px', fontWeight: '600', color: P.text,
- letterSpacing: '0.03em',
- });
- lbl.textContent = p.label || p.id;
- labelRow.appendChild(lbl);
- const readout = el('span', {
- fontSize: '10.5px', color: P.textDim,
- fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
- });
- labelRow.appendChild(readout);
- row.appendChild(labelRow);
-
- if (p.kind === 'range') {
- const input = document.createElement('input');
- input.type = 'range';
- input.min = String(p.min != null ? p.min : 0);
- input.max = String(p.max != null ? p.max : 1);
- input.step = String(p.step != null ? p.step : 0.05);
- input.value = String(p.default);
- Object.assign(input.style, {
- width: '100%', accentColor: C.brand, cursor: 'pointer',
- });
- readout.textContent = formatRangeValue(input);
- input.addEventListener('input', (e) => {
- e.stopPropagation();
- const v = parseFloat(input.value);
- paramsCurrentValues[p.id] = v;
- readout.textContent = formatRangeValue(input);
- applyParamValue(variantEl, p, v);
- queueCheckpoint('param_changed');
- });
- row.appendChild(input);
- } else if (p.kind === 'toggle') {
- const initial = !!p.default;
- readout.textContent = initial ? 'On' : 'Off';
- const track = el('button', {
- position: 'relative', width: '36px', height: '20px',
- borderRadius: '10px', border: 'none', padding: '0',
- cursor: 'pointer',
- background: initial ? C.brand : P.hairline,
- transition: 'background 0.15s ease',
- alignSelf: 'flex-start',
- });
- const knob = el('span', {
- position: 'absolute', top: '2px',
- left: initial ? '18px' : '2px',
- width: '16px', height: '16px', borderRadius: '50%',
- background: 'oklch(98% 0 0)',
- transition: 'left 0.18s ' + EASE,
- boxShadow: '0 1px 2px oklch(0% 0 0 / 0.2)',
- });
- track.appendChild(knob);
- track.addEventListener('click', (e) => {
- e.stopPropagation();
- const next = !paramsCurrentValues[p.id];
- paramsCurrentValues[p.id] = next;
- track.style.background = next ? C.brand : P.hairline;
- knob.style.left = next ? '18px' : '2px';
- readout.textContent = next ? 'On' : 'Off';
- applyParamValue(variantEl, p, next);
- queueCheckpoint('param_changed');
- });
- row.appendChild(track);
- } else if (p.kind === 'steps') {
- const opts = (p.options || []).map(o =>
- typeof o === 'string' ? { value: o, label: o } : o
- );
- const activeOpt = opts.find(o => o.value === p.default) || opts[0];
- readout.textContent = activeOpt ? activeOpt.label : String(p.default);
- const segRow = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(' + opts.length + ', 1fr)',
- gap: '1px', padding: '2px',
- background: P.hairline, borderRadius: '5px',
- });
- const segBtns = [];
- opts.forEach(o => {
- const active = o.value === p.default;
- const b = el('button', {
- padding: '5px 4px', border: 'none', borderRadius: '3px',
- background: active ? C.brand : 'transparent',
- color: active ? 'oklch(98% 0 0)' : P.text,
- fontFamily: FONT, fontSize: '10.5px', fontWeight: '500',
- cursor: 'pointer', whiteSpace: 'nowrap',
- transition: 'background 0.1s ease, color 0.1s ease',
- });
- b.textContent = o.label;
- b.addEventListener('click', (e) => {
- e.stopPropagation();
- paramsCurrentValues[p.id] = o.value;
- readout.textContent = o.label;
- segBtns.forEach(({ btn, val }) => {
- const on = val === o.value;
- btn.style.background = on ? C.brand : 'transparent';
- btn.style.color = on ? 'oklch(98% 0 0)' : P.text;
- });
- applyParamValue(variantEl, p, o.value);
- queueCheckpoint('param_changed');
- });
- segRow.appendChild(b);
- segBtns.push({ btn: b, val: o.value });
- });
- row.appendChild(segRow);
- }
-
- paramsPanelBody.appendChild(row);
- }
- }
-
- // Decide which way the popover opens: away from the picked element. If the
- // bar landed below the element, popover slides DOWN from the bar's bottom.
- // If the bar landed above, popover slides UP from the bar's top.
- function popoverDirection() {
- if (!barEl || !selectedElement) return 'below';
- const br = barEl.getBoundingClientRect();
- const er = selectedElement.getBoundingClientRect();
- return br.top >= er.bottom - 4 ? 'below' : 'above';
- }
-
- // The popover overlaps the bar by OVERLAP px on the bar-facing side. With
- // popover z-index below bar, that overlap sits behind bar (invisible) and
- // reinforces the "tucked behind" feel. Padding compensates so the real
- // content starts flush with bar's outer edge.
- const TUNE_OVERLAP = 6;
-
- // Closed clip-path depends on direction: for 'below' clip from the far
- // (bottom) edge so the reveal grows downward from the bar; for 'above'
- // clip from the top edge so the reveal grows upward from the bar.
- function closedClipPath(direction) {
- return direction === 'below' ? 'inset(0 0 100% 0)' : 'inset(100% 0 0 0)';
- }
-
- function setClipPath(value, withTransition) {
- const saved = paramsPanelEl.style.transition;
- if (!withTransition) paramsPanelEl.style.transition = 'none';
- paramsPanelEl.style.clipPath = value;
- if (!withTransition) {
- void paramsPanelEl.offsetHeight;
- paramsPanelEl.style.transition = saved;
- }
- }
-
- function positionParamsPanel() {
- if (!paramsPanelEl || !barEl || barEl.style.display === 'none') return;
- const br = barEl.getBoundingClientRect();
- const direction = popoverDirection();
- const prevDirection = paramsPanelEl.dataset.tuneDirection;
-
- // top/left/width are NOT in the transition list, so they snap instantly.
- paramsPanelEl.style.left = br.left + 'px';
- paramsPanelEl.style.width = br.width + 'px';
-
- if (direction === 'below') {
- paramsPanelEl.style.top = (br.bottom - TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '0 0 10px 10px';
- paramsPanelEl.style.paddingTop = (14 + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.paddingBottom = '14px';
- } else {
- const ih = paramsPanelEl.offsetHeight || 80;
- paramsPanelEl.style.top = (br.top - ih + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '10px 10px 0 0';
- paramsPanelEl.style.paddingTop = '14px';
- paramsPanelEl.style.paddingBottom = (14 + TUNE_OVERLAP) + 'px';
- }
- paramsPanelEl.dataset.tuneDirection = direction;
-
- // If currently closed and direction flipped (or first-time setup),
- // snap the clip-path to the new direction's closed pose without
- // transitioning (so the clip doesn't slide across the element).
- if (!tuneOpen && (!prevDirection || prevDirection !== direction)) {
- setClipPath(closedClipPath(direction), false);
- }
- }
-
- function showParamsPanel() {
- if (!paramsPanelEl) return;
- positionParamsPanel();
- paramsPanelEl.style.pointerEvents = 'auto';
- // rAF so the positioning paint commits before the transition fires.
- requestAnimationFrame(() => {
- setClipPath('inset(0 0 0 0)', true);
- });
- }
-
- function hideParamsPanel() {
- if (!paramsPanelEl) return;
- paramsPanelEl.style.pointerEvents = 'none';
- const direction = paramsPanelEl.dataset.tuneDirection || 'below';
- setClipPath(closedClipPath(direction), true);
- }
-
- // Build/rebuild the panel's contents for the current variant AND apply
- // its defaults to the variant wrapper (so scoped CSS responds even before
- // the user opens the popover). Visibility is governed by tuneOpen.
- function refreshParamsPanel() {
- if (state !== 'CYCLING') {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- if (tuneOpen) {
- // If already visible (variant cycled while open), refresh in place
- // instead of re-running the clip-path animation.
- const alreadyVisible = paramsPanelEl.style.display === 'block'
- && paramsPanelEl.style.opacity === '1';
- if (alreadyVisible) positionParamsPanel();
- else showParamsPanel();
- } else {
- hideParamsPanel();
- }
- }
-
- function toggleTunePopover() {
- if (tuneOpen) { closeTunePopover(); return; }
- openTunePopover();
- }
-
- function openTunePopover() {
- if (state !== 'CYCLING') return;
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) return;
- // Build fresh to ensure the current variant's controls are shown.
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- tuneOpen = true;
- showParamsPanel();
- // Kill the bar's shadow on the popover-facing side so the dark popover
- // doesn't pick up a bright glow line.
- if (barEl) {
- const direction = paramsPanelEl?.dataset.tuneDirection || 'below';
- barEl.style.boxShadow = direction === 'below' ? BAR_SHADOW_UP : BAR_SHADOW_DOWN;
- }
- // Re-render the bar so the Tune chip picks up the active styling.
- updateBarContent('cycling');
- }
-
- function closeTunePopover() {
- tuneOpen = false;
- hideParamsPanel();
- if (barEl) barEl.style.boxShadow = BAR_SHADOW_DEFAULT;
- if (barEl && barEl.style.display !== 'none' && state === 'CYCLING') {
- updateBarContent('cycling');
- }
- }
-
- // ---------------------------------------------------------------------------
- // Variant cycling in DOM
- // ---------------------------------------------------------------------------
-
- function showVariantInDOM(sessionId, num) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
- for (const child of wrapper.children) {
- const v = child.dataset ? child.dataset.impeccableVariant : null;
- if (!v) continue;
- child.style.display = (v === String(num)) ? '' : 'none';
- }
- // Unconditional refresh — covers first-reveal (no-op if state isn't
- // CYCLING yet, the subsequent CYCLING transition triggers its own
- // refresh) and every cycle step.
- refreshParamsPanel();
- }
-
- /**
- * No-HMR fallback: fetch the raw source file from the live server,
- * parse it, extract the variant wrapper, and inject it into the live DOM.
- * This works even when the dev server caches HTML (Bun, static servers).
- */
- function injectVariantsFromSource(filePath, sessionId) {
- const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
- fetch(url)
- .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
- .then(html => {
- // Parse the raw source HTML
- const parser = new DOMParser();
- const doc = parser.parseFromString(html, 'text/html');
- const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!srcWrapper) {
- console.error('[impeccable] Variant wrapper not found in source file.');
- return;
- }
-
- // Find the original element in the live DOM.
- // The original is inside the wrapper in the source. We find the
- // corresponding element in the live DOM by matching the first child's
- // tag + classes from the original snapshot.
- const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
- if (!origContent) return;
-
- const tag = origContent.tagName.toLowerCase();
- const cls = origContent.className;
- let liveEl = null;
- if (origContent.id) {
- liveEl = document.getElementById(origContent.id);
- } else if (cls) {
- // Find by tag + exact class match
- const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
- for (const c of candidates) {
- if (c.className === cls && !own(c)) { liveEl = c; break; }
- }
- }
-
- if (!liveEl) {
- console.error('[impeccable] Could not find original element in live DOM.');
- return;
- }
-
- const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;
-
- // Replace the live element with the full wrapper from source
- const wrapper = srcWrapper.cloneNode(true);
- liveEl.parentElement.replaceChild(wrapper, liveEl);
-
- // Update state: count variants, preserving the user's current variant
- // when a late HMR/source reinjection lands after they have cycled.
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants
- ? previousVisibleVariant
- : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);
- showVariantInDOM(sessionId, visibleVariant);
-
- // Update selectedElement to the visible variant's content
- selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;
-
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- saveSession();
- console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
- })
- .catch(err => {
- console.error('[impeccable] Failed to fetch source:', err);
- showToast('Could not load variants. Try refreshing the page.', 5000);
- });
- }
-
- function cycleVariant(dir) {
- const next = visibleVariant + dir;
- if (next < 1 || next > arrivedVariants) return;
- visibleVariant = next;
- showVariantInDOM(currentSessionId, next); // calls refreshParamsPanel itself
- updateSelectedElement();
- updateBarContent('cycling');
- saveSession();
- queueCheckpoint('variant_changed');
- }
-
- function updateSelectedElement() {
- if (!currentSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return;
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- function readVisibleVariantFromDOM(sessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return 0;
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- for (const variant of variants) {
- if (variant.style.display === 'none') continue;
- const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);
- if (idx > 0) return idx;
- }
- return 0;
- }
-
- // Resolve the element that represents the variant's visible content.
- // Contract: each variant div should contain exactly one top-level element
- // (the full replacement). In practice a model may ship loose siblings or
- // lead with <style>/<script>. Be defensive: skip non-visual elements, and
- // if the variant has multiple element children, use the variant div itself
- // (it wraps all of them and gets correct bounds).
- function pickVariantContent(wrapper, index) {
- if (!wrapper) return null;
- const variantDiv = wrapper.querySelector('[data-impeccable-variant="' + index + '"]');
- if (!variantDiv) return null;
- const NON_VISUAL = new Set(['STYLE', 'SCRIPT', 'LINK', 'META', 'TEMPLATE']);
- const visual = [];
- for (const child of variantDiv.children) {
- if (!NON_VISUAL.has(child.tagName)) visual.push(child);
- }
- if (visual.length === 1) return visual[0];
- return variantDiv;
- }
-
- // Hold window.scrollY at a fixed value across DOM mutations inside the
- // session's wrapper (HMR patches, variant inserts, cycle swaps).
- function startScrollLock(sessionId, initialTargetY) {
- stopScrollLock();
- scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)
- ? initialTargetY
- : window.scrollY;
- console.log('[impeccable.scroll] startScrollLock', { sessionId, scrollY: window.scrollY, targetY: scrollLockTargetY, initialOverride: initialTargetY });
-
- try { history.scrollRestoration = 'manual'; } catch {}
-
- const prevHtmlAnchor = document.documentElement.style.overflowAnchor;
- const prevBodyAnchor = document.body.style.overflowAnchor;
- document.documentElement.style.overflowAnchor = 'none';
- document.body.style.overflowAnchor = 'none';
-
- const correct = (why) => {
- scrollLockRaf = null;
- if (scrollLockTargetY == null) return;
- const before = window.scrollY;
- const delta = before - scrollLockTargetY;
- if (Math.abs(delta) < 0.5) {
- console.log('[impeccable.scroll] correct noop', { why, scrollY: before, targetY: scrollLockTargetY });
- return;
- }
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] corrected', { why, from: before, to: scrollLockTargetY, delta, nowAt: window.scrollY });
- };
- const schedule = (why) => {
- if (scrollLockRaf != null) return;
- scrollLockRaf = requestAnimationFrame(() => correct(why));
- };
-
- scrollLockObserver = new MutationObserver((mutations) => {
- for (const m of mutations) {
- if (m.target?.closest?.('[data-impeccable-variants="' + sessionId + '"]')) {
- const childAdds = Array.from(m.addedNodes).map(n => n.nodeType === 1 ? (n.tagName + (n.dataset?.impeccableVariant ? ('[variant=' + n.dataset.impeccableVariant + ']') : '')) : n.nodeType).join(',');
- console.log('[impeccable.scroll] mutation inside wrapper', { type: m.type, target: m.target?.tagName, adds: childAdds, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('mutation-in-wrapper');
- return;
- }
- for (const n of m.addedNodes) {
- if (n.nodeType === 1 && (n.matches?.('[data-impeccable-variants="' + sessionId + '"]') || n.querySelector?.('[data-impeccable-variants="' + sessionId + '"]'))) {
- console.log('[impeccable.scroll] wrapper node added', { tag: n.tagName, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('wrapper-added');
- return;
- }
- }
- }
- });
- scrollLockObserver.observe(document.body, { childList: true, subtree: true });
-
- scrollLockAbort = new AbortController();
- scrollLockAbort.signal.addEventListener('abort', () => {
- document.documentElement.style.overflowAnchor = prevHtmlAnchor;
- document.body.style.overflowAnchor = prevBodyAnchor;
- }, { once: true });
- const sig = { signal: scrollLockAbort.signal };
- // Track whether the most recent scroll came from a user gesture. We
- // gate user-scroll re-anchoring on this flag so programmatic smooth
- // scrolls (browser reload-restore, scrollIntoView from other scripts)
- // don't accidentally update our target.
- let userGestureAt = 0;
- const USER_GESTURE_WINDOW_MS = 250;
-
- const reanchor = (why) => {
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- const prevTarget = scrollLockTargetY;
- scrollLockTargetY = window.scrollY;
- writeScrollY(scrollLockTargetY);
- console.log('[impeccable.scroll] reanchor', { why, prevTarget, newTarget: scrollLockTargetY });
- };
- const markGesture = (why) => {
- userGestureAt = performance.now();
- reanchor(why);
- };
- window.addEventListener('wheel', () => markGesture('wheel'), { passive: true, ...sig });
- window.addEventListener('touchstart', () => markGesture('touchstart'), { passive: true, ...sig });
- window.addEventListener('touchmove', () => markGesture('touchmove'), { passive: true, ...sig });
- window.addEventListener('keydown', (e) => {
- if (['PageDown', 'PageUp', ' ', 'End', 'Home', 'ArrowDown', 'ArrowUp'].includes(e.key)) markGesture('key:' + e.key);
- }, sig);
-
- // Correct on EVERY scroll event: whether it's the browser's
- // post-reload animated restore or some other script calling
- // scrollIntoView, we want to snap back immediately. Only skip if a
- // user gesture fired in the last 250ms.
- let lastLoggedScrollY = window.scrollY;
- window.addEventListener('scroll', () => {
- const now = window.scrollY;
- if (Math.abs(now - lastLoggedScrollY) > 5) {
- console.log('[impeccable.scroll] scroll event', { from: lastLoggedScrollY, to: now, targetY: scrollLockTargetY });
- lastLoggedScrollY = now;
- }
- if (scrollLockTargetY == null) return;
- if (performance.now() - userGestureAt < USER_GESTURE_WINDOW_MS) return;
- if (Math.abs(now - scrollLockTargetY) < 0.5) return;
- console.log('[impeccable.scroll] scroll-event snap', { from: now, to: scrollLockTargetY });
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- }, { passive: true, ...sig });
-
- // Apply target synchronously, not via rAF — racing the browser's
- // restore or a smooth-scroll animation means we want to win now.
- if (Math.abs(window.scrollY - scrollLockTargetY) > 0.5) {
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] startScrollLock initial apply', { to: scrollLockTargetY });
- }
- }
-
- function stopScrollLock() {
- if (scrollLockObserver) { scrollLockObserver.disconnect(); scrollLockObserver = null; }
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }
- scrollLockTargetY = null;
- // NOTE: do NOT clear the persistent scroll key here. startScrollLock
- // calls us as a reset, and clearing the key would nuke the Go-time
- // scrollY that the next resume needs to read.
- }
-
- // ---------------------------------------------------------------------------
- // MutationObserver for progressive variant reveal
- // ---------------------------------------------------------------------------
-
- function startVariantObserver(sessionId) {
- let updating = false; // re-entrancy guard
-
- const obs = new MutationObserver((mutations) => {
- if (updating) return;
-
- // Only react to mutations that add nodes with data-impeccable-variant,
- // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
- let dominated = false;
- for (const m of mutations) {
- if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
- for (const n of m.addedNodes) {
- if (n.nodeType !== 1) continue;
- // Direct hit: the added node itself is the wrapper or a variant.
- if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
- dominated = true; break;
- }
- // Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
- // a whole subtree where the wrapper is a descendant of the added
- // node. Without this check, the observer ignores those mutations
- // and the session stays in GENERATING forever.
- if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
- dominated = true; break;
- }
- }
- if (dominated) break;
- }
- if (!dominated) return;
-
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
-
- // Re-anchor selectedElement if it was detached by live-wrap's HMR swap.
- // Without this, the shader / highlight / bar track a zero-rect phantom
- // and the overlay appears frozen.
- if (selectedElement && !document.body.contains(selectedElement)) {
- selectedElement = pickVariantContent(wrapper, 'original') || wrapper;
- }
-
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- const count = variants.length;
-
- // Nothing new
- if (count <= arrivedVariants) return;
-
- updating = true;
- arrivedVariants = count;
- if (visibleVariant === 0 && arrivedVariants > 0) {
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;
- showVariantInDOM(sessionId, visibleVariant);
- // showVariantInDOM hid the original (display:none); if we were still
- // anchored to the original's content, its boundingRect is now zero
- // and the bar snaps to (0,0). Re-point at the visible variant instead.
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- if (expected > 0) expectedVariants = expected;
-
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- } else if (state === 'GENERATING') {
- updateBarContent('generating');
- }
- saveSession();
- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');
- updating = false;
- });
-
- obs.observe(document.body, { childList: true, subtree: true });
- return obs;
- }
-
- // ---------------------------------------------------------------------------
- // Bar scroll tracking
- // ---------------------------------------------------------------------------
-
- function startScrollTracking() {
- function tick() {
- if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
- positionBar();
- showHighlight(selectedElement);
- if (tuneOpen) positionParamsPanel();
- }
- if (annotActive) positionAnnotOverlay(selectedElement);
- // Shader overlay (via debug P toggle or generation) is repositioned
- // by its own branch below; debug no longer has a separate overlay.
- if (shaderState) positionShaderOverlay();
- scrollRaf = requestAnimationFrame(tick);
- }
- scrollRaf = requestAnimationFrame(tick);
- }
-
- function stopScrollTracking() {
- if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
- }
-
- // ---------------------------------------------------------------------------
- // SSE (server→browser) + fetch POST (browser→server)
- // Zero-dependency replacement for WebSocket.
- // ---------------------------------------------------------------------------
-
- let evtSource = null;
- let sseRetries = 0;
- const SSE_MAX_RETRIES = 20; // generous: heartbeats keep the connection alive, so retries mean real trouble
-
- function connectSSE() {
- evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
-
- evtSource.onopen = () => {
- sseRetries = 0; // reset on successful (re)connect
- };
-
- evtSource.onmessage = (e) => {
- sseRetries = 0; // reset on any successful message
- let msg; try { msg = JSON.parse(e.data); } catch { return; }
- switch (msg.type) {
- case 'connected':
- hasProjectContext = !!msg.hasProjectContext;
- if (!hasProjectContext) showToast('No PRODUCT.md found. Variants will be brand-agnostic. Run /impeccable teach to generate one.', 7000);
- console.log('[impeccable] Live mode connected.');
- if (state === 'IDLE') state = 'PICKING';
- break;
- case 'done':
- // Variants already arrived via HMR → normal transition.
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- if (state === 'GENERATING') {
- state = 'CYCLING';
- updateBarContent('cycling');
- refreshParamsPanel();
- }
- break;
- }
- // Variants are in source but not in the DOM yet. Common when the
- // picked element lived inside conditional render (closed modal,
- // hidden tab, a route the user navigated away from). The variant
- // MutationObserver stays armed and auto-transitions to CYCLING
- // the moment the wrapper actually mounts. Nudge the user toward
- // that path with a toast — better than the prior force-reload
- // which reset framework state and left the session stuck.
- setTimeout(() => {
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
- if (state !== 'GENERATING') return;
- showToast(
- "Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
- 15000,
- );
- }, 2000);
- break;
- case 'error':
- console.error('[impeccable] Error:', msg.message);
- showToast('Error: ' + msg.message, 5000);
- hideBar();
- state = 'PICKING';
- break;
- }
- };
-
- evtSource.onerror = () => {
- sseRetries++;
- if (sseRetries <= SSE_MAX_RETRIES) {
- console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
- return; // EventSource auto-reconnects
- }
- // Server is gone. Clean up gracefully.
- console.log('[impeccable] Live server unreachable. Cleaning up UI.');
- evtSource.close();
- evtSource = null;
- handleServerLost();
- };
- }
-
- /** Server died or became unreachable. Reset UI to a clean state. */
- function handleServerLost() {
- const recoveryState = currentSessionId ? state : 'IDLE';
- if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
- showToast('Live server disconnected. Session ended.', 5000);
- }
- hideBar();
- hideHighlight();
- hideShaderOverlay();
- hideAnnotOverlay();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- // Preserve local session state on server loss. The durable journal is the
- // source of truth, but localStorage plus the variant wrapper lets the UI
- // resume after a helper restart or page reload instead of treating a
- // transient disconnect as an explicit discard.
- selectedElement = null;
- selectedAction = 'impeccable';
- state = recoveryState;
- if (currentSessionId) saveSession();
- }
-
- function sendEvent(msg, opts) {
- msg.token = TOKEN;
- function handleFailure(err) {
- console.error('[impeccable] Failed to send event:', err);
- if (opts && opts.throwOnError) throw err;
- return null;
- }
- return fetch('http://localhost:' + PORT + '/events', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(msg),
- }).then(res => {
- if (res.ok) return res;
- return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));
- }).catch(handleFailure);
- }
-
- function checkpointPayload(reason) {
- return {
- type: 'checkpoint',
- id: currentSessionId,
- revision: sessionState.nextCheckpointRevision(),
- owner: browserOwner,
- phase: String(state || '').toLowerCase(),
- reason,
- pageUrl: location.pathname,
- expectedVariants,
- arrivedVariants,
- visibleVariant,
- paramValues: { ...paramsCurrentValues },
- };
- }
-
- function sendCheckpoint(reason) {
- if (!currentSessionId) return Promise.resolve(null);
- return sendEvent(checkpointPayload(reason)).catch(() => null);
- }
-
- function queueCheckpoint(reason) {
- if (!currentSessionId) return;
- if (checkpointTimer) clearTimeout(checkpointTimer);
- checkpointTimer = setTimeout(() => {
- checkpointTimer = null;
- sendCheckpoint(reason);
- }, 120);
- }
-
- // ---------------------------------------------------------------------------
- // Event handlers
- // ---------------------------------------------------------------------------
-
- function handleMouseMove(e) {
- if (state !== 'PICKING' || !pickActive) return;
- const target = document.elementFromPoint(e.clientX, e.clientY);
- if (!target || !pickable(target) || target === hoveredElement) return;
- hoveredElement = target;
- showHighlight(target);
- }
-
- function handleClick(e) {
- // Close action picker on any outside click
- if (pickerEl?.style.display !== 'none' && !own(e.target)) {
- hideActionPicker();
- }
- // Close Tune popover on outside click (anything outside panel + bar)
- if (tuneOpen && paramsPanelEl && !paramsPanelEl.contains(e.target) && barEl && !barEl.contains(e.target)) {
- closeTunePopover();
- }
- // In CONFIGURING: click outside the bar and selected element returns to PICKING
- if (state === 'CONFIGURING' && !own(e.target) && selectedElement && !selectedElement.contains(e.target)) {
- hideBar();
- stopScrollTracking();
- hideAnnotOverlay();
- clearAnnotations();
- state = 'PICKING';
- hoveredElement = null;
- hideHighlight();
- return;
- }
- if (state !== 'PICKING' || !pickActive) return;
- if (own(e.target)) return;
- if (!hoveredElement || !pickable(hoveredElement)) return;
- e.preventDefault();
- e.stopPropagation();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- maybePrefetchPage();
- maybeWarnConditionalAncestor(selectedElement);
- }
-
- /**
- * Surface a brief, non-blocking heads-up when the picked element lives
- * inside a container whose visibility is gated by ephemeral state — modals,
- * collapsible panels, popovers, off-screen tab panels. If HMR remounts the
- * parent during generation (Vite Fast Refresh, SvelteKit page reload), the
- * variants land in source but stay invisible until the user re-opens the
- * container. Telling the user upfront is much friendlier than the silent
- * timeout-then-toast that they'd otherwise hit.
- *
- * Heuristic, intentionally narrow — only fires for unambiguous cases so
- * we don't cry wolf on every nested element.
- */
- function maybeWarnConditionalAncestor(el) {
- let node = el?.parentElement;
- let depth = 0;
- while (node && depth < 12) {
- // 1. Active dialog / modal
- if (node.getAttribute && node.getAttribute('role') === 'dialog'
- && node.getAttribute('aria-modal') === 'true') {
- showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 2. Common Radix / shadcn / headless-ui open-state attribute
- if (node.dataset && node.dataset.state === 'open') {
- showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 3. Tab panel — only meaningful when the page also shows ANOTHER
- // tab as selected. A single tabpanel with no tablist is just a static
- // section in disguise and isn't conditional.
- if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
- const list = document.querySelector('[role="tablist"]');
- if (list) {
- const tabs = list.querySelectorAll('[role="tab"]');
- if (tabs.length > 1) {
- showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
- return;
- }
- }
- }
- // 4. Collapsible: aria-expanded sibling. Look for the trigger button.
- if (node.id) {
- const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
- if (trigger) {
- showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
- return;
- }
- }
- node = node.parentElement;
- depth++;
- }
- }
-
- // Fire a lightweight prefetch event the first time the user selects an
- // element on a given route. The agent uses this to Read the underlying file
- // into context before Go is hit, shaving the read off the critical path.
- // Dedupe per session by pathname — clicking around on the same page doesn't
- // re-fire.
- //
- // DISABLED: quick-Go workflows pay an extra harness round trip because
- // prefetch + generate arrive as two events instead of one. Re-enable with
- // a browser-side debounce (~800–1000ms, cancelled on Go) if we want to
- // resurrect this. Server validator and skill dispatch remain in place so
- // flipping this flag is the only change needed.
- const PREFETCH_ENABLED = false;
- const prefetchedPaths = new Set();
- function maybePrefetchPage() {
- if (!PREFETCH_ENABLED) return;
- const path = location.pathname;
- if (prefetchedPaths.has(path)) return;
- prefetchedPaths.add(path);
- sendEvent({ type: 'prefetch', pageUrl: path });
- }
-
- function handleKeyDown(e) {
- // When the annotation input is focused, let it handle its own keys.
- if (annotEditing && annotEditing.input && e.target === annotEditing.input) return;
- if (e.key === 'Escape') {
- e.preventDefault();
- if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
- if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); hideAnnotOverlay(); clearAnnotations(); state = 'PICKING'; return; }
- if (state === 'CYCLING') { handleDiscard(); return; }
- if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
- if (state === 'PICKING') {
- // Use togglePick so the "Pick" button in the global bar also flips
- // off, otherwise the bar stays lit while nothing else is active.
- if (pickActive) togglePick();
- else { hideHighlight(); state = 'IDLE'; }
- return;
- }
- }
-
- // Arrow/Enter nav works in PICKING (hover) and CONFIGURING (selected, input empty)
- var navEl = (state === 'PICKING') ? hoveredElement : (state === 'CONFIGURING') ? selectedElement : null;
- if (navEl && (e.key === 'ArrowUp' || e.key === 'ArrowDown' || (e.key === 'Enter' && state === 'PICKING'))) {
- let next = null;
- if (e.key === 'ArrowDown' && !e.shiftKey) {
- next = navEl.nextElementSibling;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'ArrowUp' && !e.shiftKey) {
- next = navEl.previousElementSibling;
- while (next && !pickable(next)) next = next.previousElementSibling;
- } else if (e.key === 'ArrowUp' && e.shiftKey) {
- next = navEl.parentElement;
- if (next && !pickable(next)) next = null;
- } else if (e.key === 'ArrowDown' && e.shiftKey) {
- next = navEl.firstElementChild;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'Enter') {
- e.preventDefault();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- return;
- }
- if (next) {
- e.preventDefault();
- if (state === 'PICKING') {
- hoveredElement = next;
- } else {
- // CONFIGURING: re-select the new element and refresh the bar
- selectedElement = next;
- clearAnnotations();
- showAnnotOverlay(next);
- showBar('configure');
- startScrollTracking();
- }
- showHighlight(next);
- next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
- }
- return;
- }
-
- if (state === 'CYCLING') {
- if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
- if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
- if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
- }
- }
-
- function handleGo() {
- if (!selectedElement || state !== 'CONFIGURING') return;
- const input = document.getElementById(PREFIX + '-input');
- const prompt = input ? input.value.trim() : '';
-
- // Commit any pending pin edit BEFORE we snapshot annotations.
- if (annotEditing) finalizeEditingPin();
-
- currentSessionId = id8();
- expectedVariants = selectedCount;
- arrivedVariants = 0;
- visibleVariant = 0;
-
- // Flip to GENERATING immediately so the bar morphs without waiting on
- // capture + upload. The event is emitted from captureAndEmit() once the
- // screenshot is uploaded (or capture fails — we still emit, just without
- // screenshotPath).
- const elForCapture = selectedElement;
- const captureRect = elForCapture.getBoundingClientRect();
- const snapshot = {
- comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),
- strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),
- };
- const basePayload = {
- type: 'generate', id: currentSessionId,
- action: selectedAction,
- freeformPrompt: prompt || undefined,
- count: selectedCount,
- pageUrl: location.pathname,
- element: extractContext(elForCapture),
- };
- if (snapshot.comments.length > 0) basePayload.comments = snapshot.comments;
- if (snapshot.strokes.length > 0) basePayload.strokes = snapshot.strokes;
-
- // Hide the interactive overlay so it doesn't linger during generation.
- hideAnnotOverlay();
- clearAnnotations();
-
- state = 'GENERATING';
- showBar('generating');
- saveSession();
- sendCheckpoint('generate_started');
- writeScrollY(window.scrollY);
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
- console.log('[impeccable.scroll] Go pressed', { scrollY: window.scrollY, sessionId: currentSessionId });
- startScrollLock(currentSessionId);
-
- captureAndEmit(elForCapture, basePayload, snapshot, captureRect);
- }
-
- // ---------------------------------------------------------------------------
- // Screenshot capture + upload
- // ---------------------------------------------------------------------------
-
- let msLoadPromise = null;
- function loadModernScreenshot() {
- if (window.modernScreenshot) return Promise.resolve(window.modernScreenshot);
- if (msLoadPromise) return msLoadPromise;
- msLoadPromise = new Promise((resolve, reject) => {
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/modern-screenshot.js';
- s.onload = () => resolve(window.modernScreenshot);
- s.onerror = () => { msLoadPromise = null; reject(new Error('modern-screenshot failed to load')); };
- document.head.appendChild(s);
- });
- return msLoadPromise;
- }
-
- // Collect @font-face rules from every stylesheet on the page. Cross-origin
- // sheets (Google Fonts, Typekit, etc.) throw SecurityError on .cssRules
- // access, so modern-screenshot can't embed them on its own — the resulting
- // SVG falls back to system fonts and text re-wraps + renders with different
- // weight. We fetch the raw CSS text (CORS-permitted for these providers),
- // extract @font-face blocks, inline the referenced font files as base64
- // data URIs (SVGs rasterized via canvas can't fetch external resources,
- // so URLs inside the SVG silently fail without this), and pass the result
- // to modern-screenshot as font.cssText.
- const FONT_EXT_RE = /\.(woff2?|ttf|otf|eot)(\?.*)?$/i;
- const FONT_MIME = {
- woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', eot: 'application/vnd.ms-fontobject',
- };
- function bufferToBase64(buf) {
- const bytes = new Uint8Array(buf);
- let binary = '';
- const CHUNK = 0x8000;
- for (let i = 0; i < bytes.length; i += CHUNK) {
- binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
- }
- return btoa(binary);
- }
- async function inlineFontUrls(cssText) {
- const urlRe = /url\((['"]?)(https?:\/\/[^'")\s]+)\1\)/g;
- const urls = new Set();
- let m;
- while ((m = urlRe.exec(cssText))) {
- if (FONT_EXT_RE.test(m[2])) urls.add(m[2]);
- }
- const map = new Map();
- await Promise.all([...urls].map(async (url) => {
- try {
- const res = await fetch(url);
- if (!res.ok) return;
- const buf = await res.arrayBuffer();
- const ext = url.toLowerCase().match(FONT_EXT_RE)?.[1] || 'woff2';
- const mime = FONT_MIME[ext] || 'application/octet-stream';
- map.set(url, 'data:' + mime + ';base64,' + bufferToBase64(buf));
- } catch { /* skip; fall through to URL */ }
- }));
- return cssText.replace(urlRe, (orig, q, url) => {
- const data = map.get(url);
- return data ? 'url(' + q + data + q + ')' : orig;
- });
- }
- async function collectFontCssText() {
- const chunks = [];
- const fontFaceRe = /@font-face\s*\{[^}]*\}/g;
- for (const sheet of document.styleSheets) {
- try {
- const rules = sheet.cssRules;
- for (const rule of rules) {
- if (rule.constructor.name === 'CSSFontFaceRule' || rule.cssText?.startsWith('@font-face')) {
- chunks.push(rule.cssText);
- }
- }
- } catch {
- if (!sheet.href) continue;
- try {
- const res = await fetch(sheet.href);
- if (!res.ok) continue;
- const text = await res.text();
- let m2;
- while ((m2 = fontFaceRe.exec(text))) chunks.push(m2[0]);
- } catch { /* ignore; capture is best-effort */ }
- }
- }
- if (chunks.length === 0) return '';
- return inlineFontUrls(chunks.join('\n'));
- }
-
- // True if `s` is a computed color string that renders as nothing
- // (explicit `transparent`, or `rgba(...)` with alpha 0).
- function isTransparentColor(s) {
- if (!s) return true;
- if (s === 'transparent') return true;
- const m = /rgba?\(([^)]+)\)/.exec(s);
- if (!m) return false;
- const parts = m[1].split(',').map((p) => p.trim());
- if (parts.length === 4) return parseFloat(parts[3]) === 0;
- return false;
- }
-
- // modern-screenshot force-sets `background-color: X !important` on the
- // cloned root whenever `backgroundColor` is passed, clobbering the
- // element's own background. So we only pass it when the element is
- // genuinely transparent (no own color, no own image) — in that case
- // we resolve up the DOM to the nearest opaque ancestor so the capture
- // sits on the page's real background instead of rendering black.
- function resolveCanvasBackground(el) {
- const own = getComputedStyle(el);
- if (!isTransparentColor(own.backgroundColor)) return null;
- if (own.backgroundImage && own.backgroundImage !== 'none') return null;
- let node = el.parentElement;
- while (node) {
- const cs = getComputedStyle(node);
- if (!isTransparentColor(cs.backgroundColor)) return cs.backgroundColor;
- node = node.parentElement;
- }
- // The walk already passed through <body> and <html>; if they had been
- // opaque we would have returned. Falling through with the previous
- // `getComputedStyle(body).backgroundColor || …` chain is a trap: that
- // call returns the literal string `"rgba(0, 0, 0, 0)"` for a page that
- // never set its own bg, which is truthy and short-circuits the chain to
- // transparent-black — modern-screenshot then renders the capture on a
- // black canvas and the shader overlay flashes solid black during load.
- // The browser canvas defaults to white, so we do too.
- return '#ffffff';
- }
-
- // Capture the element (with current annotations baked in) and return a PNG
- // Blob. Shared between the Go flow (uploads it to the server) and the
- // debug toggle (displays it as an overlay for side-by-side comparison).
- async function captureElementToBlob(el, snapshot, rect) {
- try { if (document.fonts?.ready) await document.fonts.ready; } catch {}
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- let annotNode = null;
- let savedPosition = null;
- if (hasAnnotations) {
- const pos = getComputedStyle(el).position;
- if (pos === 'static') {
- savedPosition = el.style.position;
- el.style.position = 'relative';
- }
- annotNode = buildAnnotationsForCapture(rect, snapshot);
- el.appendChild(annotNode);
- }
- try {
- const ms = await loadModernScreenshot();
- const fontCssText = await collectFontCssText();
- const backgroundColor = resolveCanvasBackground(el);
- return await ms.domToBlob(el, {
- scale: Math.min(window.devicePixelRatio || 1, 2),
- font: fontCssText ? { cssText: fontCssText } : undefined,
- ...(backgroundColor ? { backgroundColor } : {}),
- });
- } finally {
- if (annotNode) annotNode.remove();
- if (savedPosition !== null) el.style.position = savedPosition;
- }
- }
-
- async function captureAndEmit(el, basePayload, snapshot, rect) {
- let screenshotPath;
- let blob;
- try {
- blob = await captureElementToBlob(el, snapshot, rect);
- } catch (err) {
- console.warn('[impeccable] capture failed, proceeding without screenshot:', err);
- }
- // Light up the shader overlay the moment capture is ready — no reason to
- // wait for the upload to complete before the user sees something alive.
- if (blob && state === 'GENERATING') {
- showShaderOverlay(el, blob, rect);
- }
- // Only upload + forward the screenshot when annotations (comments/strokes)
- // are present. Without annotations the image is pure visual anchoring —
- // it biases the model toward the current rendering and works against the
- // three-distinct-directions brief.
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- if (blob && hasAnnotations) {
- try {
- const uploadRes = await fetch(
- 'http://localhost:' + PORT + '/annotation?token=' + encodeURIComponent(TOKEN) +
- '&eventId=' + encodeURIComponent(basePayload.id),
- { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: blob },
- );
- if (uploadRes.ok) {
- const { path: p } = await uploadRes.json();
- screenshotPath = p;
- } else {
- console.warn('[impeccable] annotation upload failed:', uploadRes.status);
- }
- } catch (err) {
- console.warn('[impeccable] annotation upload failed:', err);
- }
- }
- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);
- }
-
- // ---------------------------------------------------------------------------
- // Shader overlay — renders the captured screenshot as a WebGL texture and
- // runs an editorial "ink-wash" fragment shader over it during generation.
- // A single rolling band sweeps top-to-bottom, desaturating + tinting magenta
- // and leaving a soft trail. Makes the wait feel like a letterpress scan
- // instead of a dead spinner.
- // ---------------------------------------------------------------------------
-
- const SHADER_VS = `attribute vec2 a_position;
-attribute vec2 a_uv;
-varying vec2 v_uv;
-void main() {
- v_uv = a_uv;
- gl_Position = vec4(a_position, 0.0, 1.0);
-}`;
-
- const SHADER_FS = `precision highp float;
-uniform sampler2D u_texture;
-uniform float u_time;
-uniform vec2 u_resolution;
-uniform vec3 u_accent;
-varying vec2 v_uv;
-
-// Asymmetric roller band. Product of two one-sided smoothsteps — peaks at
-// d=0 with a short sharp leading ramp and a longer soft trailing tail. Clean
-// outside the [-leadW, trailW] range (no rogue "trail=1 everywhere below"
-// failure that reversed-edge smoothstep would give).
-float bandAt(float d, float leadW, float trailW) {
- float above = smoothstep(-leadW, 0.0, d);
- float below = 1.0 - smoothstep(0.0, trailW, d);
- return above * below;
-}
-
-void main() {
- vec2 uv = v_uv;
- // Roller sweeps top-to-bottom with small overshoot so each cycle enters
- // and exits the element cleanly.
- float phase = fract(u_time / 3.4);
- float y = phase * 1.25 - 0.12;
- float band = bandAt(uv.y - y, 0.05, 0.32);
-
- // Halftone cell grid (fixed ~10 px pitch).
- float cellPx = 10.0;
- vec2 gridUv = uv * u_resolution / cellPx;
- vec2 cellId = floor(gridUv);
- vec2 cellUv = fract(gridUv) - 0.5;
- vec2 sampleCenter = (cellId + 0.5) * cellPx / u_resolution;
- vec3 cellImg = texture2D(u_texture, sampleCenter).rgb;
- float luma = dot(cellImg, vec3(0.299, 0.587, 0.114));
- // Darker cells → bigger magenta dots (classic risograph halftone curve).
- float radius = sqrt(clamp(1.0 - luma, 0.0, 1.0)) * 0.56;
- float dotMask = smoothstep(radius + 0.06, radius, length(cellUv));
- vec3 paper = vec3(0.975, 0.965, 0.955);
- vec3 dotLayer = mix(paper, u_accent, dotMask);
-
- // Blend the halftone layer in where the roller is passing; leave the
- // element pristine elsewhere.
- vec3 base = texture2D(u_texture, uv).rgb;
- gl_FragColor = vec4(mix(base, dotLayer, band), 1.0);
-}`;
-
- // Editorial Magenta converted to approximate sRGB 0-1 (matches oklch(60% 0.25 350))
- const SHADER_ACCENT = [0.82, 0.16, 0.47];
- let shaderState = null; // { canvas, gl, program, texture, rafId, startTime }
-
- function compileShader(gl, type, source) {
- const sh = gl.createShader(type);
- gl.shaderSource(sh, source);
- gl.compileShader(sh);
- if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
- const info = gl.getShaderInfoLog(sh);
- gl.deleteShader(sh);
- throw new Error('shader compile failed: ' + info);
- }
- return sh;
- }
-
- function positionShaderOverlay() {
- if (!shaderState || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- Object.assign(shaderState.canvas.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- }
-
- function hideShaderOverlay() {
- if (!shaderState) return;
- if (shaderState.rafId) cancelAnimationFrame(shaderState.rafId);
- if (shaderState.canvas) shaderState.canvas.remove();
- const lose = shaderState.gl?.getExtension?.('WEBGL_lose_context');
- try { lose?.loseContext(); } catch {}
- shaderState = null;
- }
-
- async function showShaderOverlay(el, blob, rect) {
- hideShaderOverlay();
- if (!blob || !el) return;
- const canvas = document.createElement('canvas');
- canvas.id = PREFIX + '-shader';
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
- canvas.width = Math.max(1, Math.floor(rect.width * dpr));
- canvas.height = Math.max(1, Math.floor(rect.height * dpr));
- Object.assign(canvas.style, {
- position: 'fixed',
- top: rect.top + 'px', left: rect.left + 'px',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none',
- zIndex: Z.bar - 1,
- });
- document.body.appendChild(canvas);
-
- const gl = canvas.getContext('webgl', { premultipliedAlpha: false, preserveDrawingBuffer: false })
- || canvas.getContext('experimental-webgl');
- if (!gl) {
- // WebGL unavailable — fall back to a plain <img> overlay so the user
- // still sees something meaningful during generation.
- canvas.remove();
- const img = document.createElement('img');
- img.src = URL.createObjectURL(blob);
- img.id = PREFIX + '-shader';
- // Copy positioning via cssText. Object.assign across CSSStyleDeclaration
- // throws in modern Chromium because the source's indexed properties
- // (style[0], [1], ...) are read-only and the engine forbids writing
- // them on the destination.
- img.style.cssText = canvas.style.cssText;
- img.style.outline = '2px dashed ' + C.brand;
- img.style.outlineOffset = '-2px';
- document.body.appendChild(img);
- shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
- return;
- }
-
- let program, texture;
- try {
- const vs = compileShader(gl, gl.VERTEX_SHADER, SHADER_VS);
- const fs = compileShader(gl, gl.FRAGMENT_SHADER, SHADER_FS);
- program = gl.createProgram();
- gl.attachShader(program, vs);
- gl.attachShader(program, fs);
- gl.linkProgram(program);
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- throw new Error('program link failed: ' + gl.getProgramInfoLog(program));
- }
- // Full-screen quad
- const buf = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
- -1, -1, 0, 1,
- 1, -1, 1, 1,
- -1, 1, 0, 0,
- -1, 1, 0, 0,
- 1, -1, 1, 1,
- 1, 1, 1, 0,
- ]), gl.STATIC_DRAW);
- const posLoc = gl.getAttribLocation(program, 'a_position');
- const uvLoc = gl.getAttribLocation(program, 'a_uv');
- gl.enableVertexAttribArray(posLoc);
- gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 16, 0);
- gl.enableVertexAttribArray(uvLoc);
- gl.vertexAttribPointer(uvLoc, 2, gl.FLOAT, false, 16, 8);
- } catch (err) {
- console.warn('[impeccable] shader setup failed:', err);
- canvas.remove();
- return;
- }
-
- // Upload the screenshot as a texture
- let bitmap;
- try {
- bitmap = await createImageBitmap(blob);
- } catch {
- // Safari fallback: go via a regular Image
- const imgUrl = URL.createObjectURL(blob);
- const img = new Image();
- img.src = imgUrl;
- await new Promise((r, rej) => { img.onload = r; img.onerror = rej; });
- bitmap = img;
- URL.revokeObjectURL(imgUrl);
- }
- texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
- if (bitmap.close) bitmap.close();
-
- const uTime = gl.getUniformLocation(program, 'u_time');
- const uRes = gl.getUniformLocation(program, 'u_resolution');
- const uAccent = gl.getUniformLocation(program, 'u_accent');
- const uTex = gl.getUniformLocation(program, 'u_texture');
- const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-
- shaderState = { canvas, gl, program, texture, rafId: 0, startTime: performance.now(), reduced };
- function frame() {
- if (!shaderState) return;
- const elapsed = (performance.now() - shaderState.startTime) / 1000;
- const t = shaderState.reduced ? 0.0 : elapsed;
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.useProgram(program);
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.uniform1i(uTex, 0);
- gl.uniform1f(uTime, t);
- gl.uniform2f(uRes, canvas.width, canvas.height);
- gl.uniform3f(uAccent, SHADER_ACCENT[0], SHADER_ACCENT[1], SHADER_ACCENT[2]);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- shaderState.rafId = requestAnimationFrame(frame);
- }
- frame();
- }
-
- function handleAccept() {
- if (!currentSessionId || arrivedVariants === 0) return;
- const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);
- if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;
- const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };
- if (Object.keys(paramsCurrentValues).length > 0) {
- acceptPayload.paramValues = { ...paramsCurrentValues };
- }
- // The accepted variant is already the only visible child of the wrapper
- // (all other variants are display:none). HMR from the source rewrite will
- // replace the wrapper imminently. Don't eagerly replaceChild here — React
- // reconciliation races with our mutation and throws NotFoundError in Next
- // 16 / Turbopack. Schedule a fallback that runs the manual swap only if
- // HMR hasn't cleaned up by then (keeps static-server flows working).
- const acceptedSessionId = currentSessionId;
- const acceptedVariant = visibleVariant;
-
- state = 'SAVING';
- updateBarContent('saving');
-
- sendEvent(acceptPayload, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- confirmAcceptAfterReceipt();
- })
- .catch(() => {
- state = 'CYCLING';
- updateBarContent('cycling');
- showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);
- });
-
- function confirmAcceptAfterReceipt() {
- state = 'CONFIRMED';
- updateBarContent('confirmed');
- scheduleAcceptCleanup();
- }
-
- function scheduleAcceptCleanup() {
- setTimeout(function() {
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }, 1800);
-
- // Static-server / no-HMR fallback: if the wrapper is still around 2s after
- // the cleanup above, swap it out manually. By now React has either moved
- // on or the app isn't React at all. Preserve the `data-impeccable-variant="N"`
- // div (with display:contents) so @scope rules anchored to the variant
- // attribute keep matching until reload replaces it with the carbonize block.
- setTimeout(function() {
- const wrapper = document.querySelector('[data-impeccable-variants="' + acceptedSessionId + '"]');
- if (!wrapper) return;
- const accepted = wrapper.querySelector('[data-impeccable-variant="' + acceptedVariant + '"]');
- if (accepted && accepted.firstElementChild) {
- const parent = wrapper.parentElement;
- if (!parent) return;
- accepted.style.display = 'contents';
- parent.replaceChild(accepted, wrapper);
- }
- }, 2000);
- }
- }
-
- function handleDiscard() {
- if (!currentSessionId) return;
- sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- cleanup();
- })
- .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));
- }
-
- // ---------------------------------------------------------------------------
- // Session persistence via live-browser-session.js
- // ---------------------------------------------------------------------------
- // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
-
- function saveSession() {
- if (!currentSessionId) return;
- // NOTE: scrollY is stored under a separate key (writeScrollY). Storing
- // it here would overwrite the Go-time value every time state changes.
- sessionState.saveSession({
- id: currentSessionId,
- state,
- action: selectedAction,
- count: selectedCount,
- expected: expectedVariants,
- arrived: arrivedVariants,
- visible: visibleVariant,
- });
- }
-
- function loadSession() {
- return sessionState.loadSession();
- }
-
- function clearSession() {
- sessionState.clearSession();
- }
-
- /** Mark session as handled (accepted/discarded). The agent will clean up
- * the source, but until it does the wrapper is still in the HTML. This
- * prevents resumeSession from picking it up again after reload. */
- function markSessionHandled() {
- if (!currentSessionId) return;
- sessionState.markHandled(currentSessionId);
- }
-
- function isSessionHandled(id) {
- return sessionState.isHandled(id);
- }
-
- function clearHandled() {
- sessionState.clearHandled();
- }
-
- function cleanup() {
- // Hide the wrapper immediately so variants disappear. DON'T structurally
- // mutate the DOM yet — HMR from the agent's source rewrite is on its way,
- // and a manual replaceChild under React causes NotFoundError when the
- // reconciler later tries to remove a wrapper we already removed.
- // Schedule a 2s fallback that does the manual swap only if HMR hasn't
- // replaced the wrapper by then (keeps static-server / no-HMR flows alive).
- const cleanupSessionId = currentSessionId;
- if (cleanupSessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (wrapper) wrapper.style.display = 'none';
- }
- setTimeout(function() {
- if (!cleanupSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (!wrapper) return;
- const orig = wrapper.querySelector('[data-impeccable-variant="original"]');
- if (orig) {
- const content = orig.firstElementChild;
- if (content) {
- wrapper.parentElement.replaceChild(content, wrapper);
- return;
- }
- }
- wrapper.remove();
- }, 2000);
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }
-
- // ---------------------------------------------------------------------------
- // Toast
- // ---------------------------------------------------------------------------
-
- function showToast(message, duration) {
- if (toastEl) toastEl.remove();
- // Stack the toast above the global bar (which sits at bottom:14px) so
- // the two never overlap. Read the bar's actual rect — its height varies
- // with hover-expanded labels — and fall back to a sensible default
- // when the bar isn't mounted yet.
- const barRect = globalBarEl?.getBoundingClientRect();
- const barTopFromBottom = barRect && barRect.height > 0
- ? Math.max(16, window.innerHeight - barRect.top + 12)
- : 16;
- toastEl = el('div', {
- position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
- transform: 'translateX(-50%) translateY(8px)',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px',
- padding: '8px 16px', borderRadius: '8px',
- zIndex: Z.toast, opacity: '0',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
- pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
- });
- toastEl.id = PREFIX + '-toast';
- toastEl.textContent = message;
- document.body.appendChild(toastEl);
- requestAnimationFrame(() => {
- toastEl.style.opacity = '1';
- toastEl.style.transform = 'translateX(-50%) translateY(0)';
- });
- setTimeout(() => {
- if (toastEl) {
- toastEl.style.opacity = '0';
- toastEl.style.transform = 'translateX(-50%) translateY(8px)';
- setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
- }
- }, duration);
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- // Resume an active variant session after HMR/page reload.
- // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
- // variants before HMR fired. Pick up where we left off.
- function resumeSession() {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) { clearSession(); clearHandled(); return false; }
-
- const sessionId = wrapper.dataset.impeccableVariants;
-
- // Don't resume if this session was already accepted/discarded
- if (isSessionHandled(sessionId)) return false;
-
- currentSessionId = sessionId;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
-
- // Restore state from localStorage if available
- const saved = loadSession();
- if (saved && saved.id === sessionId) {
- visibleVariant = (saved.visible > 0 && saved.visible <= arrivedVariants) ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
- if (saved.action) selectedAction = saved.action;
- if (saved.count) selectedCount = saved.count;
- } else {
- visibleVariant = arrivedVariants > 0 ? 1 : 0;
- }
-
- // Find the visible variant's content element for highlight positioning.
- // Try the visible variant first, fall back to the original's content.
- const visEl = visibleVariant > 0 ? pickVariantContent(wrapper, visibleVariant) : null;
- const origEl = pickVariantContent(wrapper, 'original');
- selectedElement = visEl || origEl || wrapper.parentElement;
-
- // Set display state BEFORE starting observer (avoid triggering it)
- if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
-
- state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
- showBar(state === 'CYCLING' ? 'cycling' : 'generating');
- startScrollTracking();
- // Build the params panel for the restored visible variant. Previously
- // this was missed on page-reload resume: showVariantInDOM above fires
- // refreshParamsPanel, but state was still IDLE at that moment so it
- // hid. Now that state is CYCLING, re-fire.
- if (state === 'CYCLING') refreshParamsPanel();
- saveSession();
- queueCheckpoint('browser_resumed');
-
- // Start observing for more variants AFTER initial setup
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
-
- // Hold the target at its saved viewport top through any subsequent
- // HMR patches, variant inserts, or cycle swaps.
- startScrollLock(currentSessionId, readScrollY());
-
- // If we reloaded mid-generation (Bun's HTML HMR destroys the shader
- // canvas), re-capture the original's content and restart the shader so
- // the wait doesn't go dead.
- if (state === 'GENERATING' && origEl) {
- (async () => {
- try {
- const rect = origEl.getBoundingClientRect();
- if (rect.width === 0 || rect.height === 0) return;
- const blob = await captureElementToBlob(origEl, null, rect);
- if (blob && state === 'GENERATING') {
- showShaderOverlay(origEl, blob, rect);
- }
- } catch (err) {
- console.warn('[impeccable] shader resume failed:', err);
- }
- })();
- }
- return true;
- }
-
- // ---------------------------------------------------------------------------
- // Global bar (always visible at bottom)
- // ---------------------------------------------------------------------------
-
- let globalBarEl = null;
- let detectActive = false;
- let pickActive = true;
- let detectCount = 0;
- let detectScriptLoaded = false;
-
- // Theme-aware color palette for the global bar. We detect the page's
- // ambient background and invert — dark bar on light pages, light bar on
- // dark pages. This keeps the bar from fighting with the host design.
- function detectPageTheme() {
- try {
- // Dev override: set localStorage 'impeccable-dev-theme' to 'light' or
- // 'dark' to preview the opposite palette without actually changing the
- // page bg. Used for screenshots and theme QA.
- const override = localStorage.getItem('impeccable-dev-theme');
- if (override === 'light' || override === 'dark') return override;
-
- // Walk body → html, taking the first opaque background. The browser's
- // default body / html background is `rgba(0, 0, 0, 0)`, which a naive
- // regex would read as black and mislabel a perfectly white page as
- // dark. Honoring alpha avoids that — and falling through to <html>
- // catches the common pattern of a bg only on <html> (or only on body).
- function readOpaque(el) {
- if (!el) return null;
- const bg = getComputedStyle(el).backgroundColor;
- const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
- if (!m) return null;
- const alpha = m[4] == null ? 1 : parseFloat(m[4]);
- if (alpha < 0.5) return null; // transparent / nearly transparent → skip
- return [+m[1], +m[2], +m[3]];
- }
-
- const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
- // Both transparent → fall back to the browser's effective canvas color.
- // White is the universal default; only one in a thousand sites swaps it
- // via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
- // us catch that case.
- if (!rgb) {
- return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
- }
- const [r, g, b] = rgb;
- // Perceptual luminance (Rec. 709)
- const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
- return L > 0.55 ? 'light' : 'dark';
- } catch { return 'light'; }
- }
-
- function barPaletteForTheme(theme) {
- if (theme === 'dark') {
- // Light bar on dark page
- return {
- surface: 'oklch(98% 0 0 / 0.92)',
- surfaceDeep: 'oklch(92% 0.005 60 / 0.96)', // slightly deeper, faint warm
- hairline: 'oklch(70% 0 0 / 0.35)',
- text: 'oklch(15% 0 0)',
- textDim: 'oklch(45% 0 0)',
- accent: 'oklch(60% 0.25 350)',
- accentSoft: 'oklch(60% 0.25 350 / 0.18)',
- mark: 'oklch(98% 0 0)', // logo mark fill
- markText: 'oklch(15% 0 0)', // logo "/" color
- exitHover: 'oklch(85% 0 0 / 0.5)',
- };
- }
- // Dark bar on light page. Bar is a warm charcoal, logo slab is much
- // deeper so the rounded-right shape reads as a clear sculpted mark.
- return {
- surface: 'oklch(26% 0 0 / 0.94)',
- surfaceDeep: 'oklch(18% 0 0 / 0.96)', // darker sand for Tune popover
- hairline: 'oklch(42% 0 0 / 0.5)',
- text: 'oklch(96% 0 0)',
- textDim: 'oklch(72% 0 0)',
- accent: 'oklch(72% 0.22 350)',
- accentSoft: 'oklch(72% 0.22 350 / 0.22)',
- mark: 'oklch(8% 0 0)',
- markText: 'oklch(96% 0 0)',
- exitHover: 'oklch(36% 0 0 / 0.6)',
- };
- }
-
- // Impeccable logo mark — matches the site-header SVG (rounded square + "/").
- function brandMarkSvg(fill, ink, size = 18) {
- return `<svg width="${size}" height="${size}" viewBox="0 0 32 32" aria-hidden="true">
- <rect width="32" height="32" rx="7" fill="${fill}"/>
- <text x="16" y="24" font-family="system-ui, -apple-system, sans-serif" font-size="22" font-weight="500" fill="${ink}" text-anchor="middle">/</text>
- </svg>`;
- }
-
- function initGlobalBar() {
- const theme = detectPageTheme();
- const P = barPaletteForTheme(theme);
-
- // Custom focus-visible for bar buttons. Browser default is a heavy
- // blue ring that looks jarring on the dark capsule. Replace with a
- // soft accent-tinted inner ring that respects the bar's palette.
- if (!document.getElementById(PREFIX + '-bar-focus-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-bar-focus-style';
- s.textContent =
- '#' + PREFIX + '-global-bar button:focus { outline: none; }' +
- '#' + PREFIX + '-global-bar button:focus-visible {' +
- ' outline: none;' +
- ' box-shadow: 0 0 0 2px ' + P.accentSoft + ', 0 0 0 3px ' + P.accent + ';' +
- '}';
- document.head.appendChild(s);
- }
-
- globalBarEl = el('div', {
- position: 'fixed', bottom: '14px', left: '50%',
- transform: 'translateX(-50%) translateY(20px)',
- zIndex: Z.bar + 5,
- display: 'flex', alignItems: 'stretch',
- gap: '2px',
- background: P.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 4px 20px oklch(0% 0 0 / 0.12), 0 1px 3px oklch(0% 0 0 / 0.08)',
- fontFamily: FONT, fontSize: '12px', lineHeight: '1',
- opacity: '0',
- overflow: 'hidden', // clip the full-bleed brand mark to the bar radius
- transition: 'opacity 0.3s ' + EASE + ', transform 0.3s ' + EASE,
- });
- globalBarEl.id = PREFIX + '-global-bar';
- globalBarEl.dataset.theme = theme;
-
- // Brand mark — fills bar height on the left. Left side inherits the bar's
- // rounded corner via overflow:hidden; right side is a clean hard edge since
- // the near-black/charcoal contrast does the shape-defining work.
- const brand = el('span', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- alignSelf: 'stretch',
- padding: '0 12px 0 14px',
- background: P.mark,
- color: P.markText,
- fontFamily: 'system-ui, -apple-system, sans-serif',
- fontWeight: '500',
- fontSize: '18px', lineHeight: '1',
- });
- brand.textContent = '/';
- brand.title = 'Impeccable';
- globalBarEl.appendChild(brand);
-
- // Inner wrapper: holds the toggles with normal bar padding.
- const inner = el('div', {
- display: 'flex', alignItems: 'center',
- padding: '4px 5px', gap: '2px',
- });
- inner.id = PREFIX + '-global-bar-inner';
- globalBarEl.appendChild(inner);
-
- // --- button factory: icon-only at rest, label slides in on hover/active ---
- function makeIconBtn({ id, svg, label, ariaLabel, labelFont, onClick }) {
- const b = el('button', {
- position: 'relative',
- display: 'inline-flex', alignItems: 'center',
- padding: '6px 8px', borderRadius: '7px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '11.5px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.15s ease, color 0.15s ease',
- whiteSpace: 'nowrap', overflow: 'hidden',
- });
- b.id = id;
- b.title = ariaLabel || label || '';
- b.setAttribute('aria-label', ariaLabel || label || '');
- b.innerHTML = svg + (label
- ? `<span class="icon-btn-label" style="display:inline-block;max-width:0;opacity:0;margin-left:0;overflow:hidden;font-family:${labelFont || FONT};transition:max-width 0.25s ${EASE}, opacity 0.2s ease, margin-left 0.25s ${EASE};">${label}</span>`
- : '');
- const labelEl = b.querySelector('.icon-btn-label');
- const expand = () => {
- if (!labelEl) return;
- labelEl.style.maxWidth = '120px'; labelEl.style.opacity = '1'; labelEl.style.marginLeft = '6px';
- };
- const collapse = () => {
- if (!labelEl || b.dataset.active === 'true') return;
- labelEl.style.maxWidth = '0'; labelEl.style.opacity = '0'; labelEl.style.marginLeft = '0';
- };
- // Per-button hover only changes color (no layout). The label expand/
- // collapse is driven by the bar-level mouseenter/mouseleave so moving
- // the mouse between adjacent buttons doesn't trigger per-button width
- // thrashing — the whole bar grows once and shrinks once.
- b.addEventListener('mouseenter', () => { if (b.dataset.active !== 'true') b.style.color = P.text; });
- b.addEventListener('mouseleave', () => { if (b.dataset.active !== 'true') b.style.color = P.textDim; });
- b.addEventListener('click', onClick);
- b._expandLabel = expand;
- b._collapseLabel = collapse;
- return b;
- }
-
- // Pick toggle — starts active (primary intent when entering live mode).
- const pickBtn = makeIconBtn({
- id: PREFIX + '-pick-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',
- label: 'Pick',
- ariaLabel: 'Pick element',
- onClick: () => togglePick(),
- });
- pickBtn.style.background = P.accentSoft;
- pickBtn.style.color = P.accent;
- pickBtn.dataset.active = 'true';
- pickBtn._expandLabel();
- inner.appendChild(pickBtn);
-
- // Detect toggle
- const detectBtn = makeIconBtn({
- id: PREFIX + '-detect-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',
- label: 'Detect',
- ariaLabel: 'Detect anti-patterns',
- onClick: () => toggleDetect(),
- });
- const detectBadge = el('span', {
- fontSize: '10px', fontWeight: '600',
- padding: '0px 5px', borderRadius: '7px', lineHeight: '16px',
- background: P.accent, color: P.surface.includes('18%') ? 'oklch(18% 0 0)' : 'oklch(98% 0 0)',
- display: 'none', fontFamily: MONO, marginLeft: '4px',
- });
- detectBadge.id = PREFIX + '-detect-badge';
- detectBtn.appendChild(detectBadge);
- inner.appendChild(detectBtn);
-
- // DESIGN.md panel toggle — quartet of color squares as the mark.
- const designBtn = makeIconBtn({
- id: PREFIX + '-design-toggle',
- svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px ${P.hairline};flex-shrink:0">
- <span style="background:oklch(60% 0.25 350)"></span>
- <span style="background:oklch(60% 0.15 45)"></span>
- <span style="background:oklch(55% 0.12 250)"></span>
- <span style="background:oklch(30% 0 0)"></span>
- </span>`,
- label: 'DESIGN.md',
- ariaLabel: 'Toggle DESIGN.md panel',
- labelFont: MONO,
- onClick: () => toggleDesignPanel(),
- });
- inner.appendChild(designBtn);
-
- // Thin divider before the exit button
- const divider = el('span', {
- width: '1px', height: '18px',
- background: P.hairline,
- margin: '0 4px 0 2px',
- });
- inner.appendChild(divider);
-
- // Exit × on the right — intentionally subtle (textDim at rest, text on
- // hover) so it sits behind the active toggles in visual hierarchy.
- //
- // Explicit padding + box-sizing here is load-bearing: a host page like
- // `button { padding: 0.5rem 1rem; }` (very common in resets) would
- // otherwise inflate this 24x24 button into 56x40 and push the SVG out
- // of the visible bar — the X stays invisible even though the styles in
- // DevTools look fine. Every other chrome button sets padding inline;
- // this one needed it too.
- const exitBtn = el('button', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- padding: '0', boxSizing: 'border-box',
- width: '24px', height: '24px', borderRadius: '6px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
- cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
- });
- exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
- exitBtn.title = 'Exit live mode';
- exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
- exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
- exitBtn.addEventListener('click', () => { sendEvent({ type: 'exit' }); teardown(); });
- inner.appendChild(exitBtn);
-
- // Bar-level hover: expand every toggle's label at once; collapse on leave.
- // Buttons with dataset.active="true" ignore collapse (their label stays).
- const toggles = [pickBtn, detectBtn, designBtn];
- globalBarEl.addEventListener('mouseenter', () => {
- toggles.forEach((t) => t._expandLabel && t._expandLabel());
- });
- globalBarEl.addEventListener('mouseleave', () => {
- toggles.forEach((t) => t._collapseLabel && t._collapseLabel());
- });
-
- document.body.appendChild(globalBarEl);
- defangOutsideHandlers(globalBarEl);
-
- requestAnimationFrame(() => {
- globalBarEl.style.opacity = '1';
- globalBarEl.style.transform = 'translateX(-50%) translateY(0)';
- });
-
- // Listen for detection results AND ready signal
- window.addEventListener('message', onDetectMessage);
- }
-
- function updateGlobalBarState() {
- const detectToggle = document.getElementById(PREFIX + '-detect-toggle');
- const detectBadge = document.getElementById(PREFIX + '-detect-badge');
- const pickToggle = document.getElementById(PREFIX + '-pick-toggle');
- const designToggle = document.getElementById(PREFIX + '-design-toggle');
- const theme = globalBarEl?.dataset.theme || 'light';
- const P = barPaletteForTheme(theme);
-
- // Sync one toggle's active state, colors, and slide-label visibility.
- function sync(btn, active) {
- if (!btn) return;
- btn.style.background = active ? P.accentSoft : 'transparent';
- btn.style.color = active ? P.accent : P.textDim;
- btn.dataset.active = active ? 'true' : 'false';
- if (active && btn._expandLabel) btn._expandLabel();
- else if (!active && btn._collapseLabel) btn._collapseLabel();
- }
- sync(pickToggle, pickActive);
- sync(detectToggle, detectActive);
- sync(designToggle, designState.open);
-
- // If the bar is currently under the cursor, keep all labels expanded —
- // otherwise clicking a toggle that deactivates (e.g. closing DESIGN.md)
- // would collapse its label while the user's mouse is still on the bar.
- if (globalBarEl && globalBarEl.matches(':hover')) {
- [pickToggle, detectToggle, designToggle].forEach((t) => t?._expandLabel?.());
- }
-
- if (detectBadge) {
- detectBadge.style.display = (detectActive && detectCount > 0) ? 'inline' : 'none';
- detectBadge.textContent = detectCount;
- }
-
- // When pick is active, make detect overlays click-through so the picker works
- document.querySelectorAll('.impeccable-overlay').forEach(o => {
- o.style.pointerEvents = pickActive ? 'none' : '';
- });
- }
-
- let detectReady = false; // true once detect script posts 'impeccable-ready'
- let detectPendingScan = false; // scan requested before script was ready
-
- function toggleDetect() {
- detectActive = !detectActive;
- updateGlobalBarState();
-
- if (detectActive) {
- if (!detectScriptLoaded) {
- detectPendingScan = true;
- loadDetectScript();
- } else if (detectReady) {
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- } else {
- detectPendingScan = true;
- }
- } else {
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- detectCount = 0;
- updateGlobalBarState();
- }
- }
-
- function togglePick() {
- pickActive = !pickActive;
- updateGlobalBarState();
-
- if (!pickActive) {
- // Disabling pick clears any in-flight selection and UI: highlight,
- // contextual bar, selectedElement. Otherwise a stale selection sits
- // on screen with no obvious way to dismiss.
- hideHighlight();
- hideBar();
- hideActionPicker();
- selectedElement = null;
- if (state === 'PICKING' || state === 'CONFIGURING') state = 'IDLE';
- } else {
- if (state === 'IDLE') state = 'PICKING';
- }
- }
-
- function loadDetectScript() {
- if (detectScriptLoaded) return;
- detectScriptLoaded = true;
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/detect.js';
- s.dataset.impeccableExtension = 'true';
- document.head.appendChild(s);
- }
-
- function onDetectMessage(e) {
- if (!e.data || typeof e.data.source !== 'string') return;
- // Detection script is loaded and ready
- if (e.data.source === 'impeccable-ready') {
- detectReady = true;
- if (detectPendingScan && detectActive) {
- detectPendingScan = false;
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- }
- }
- // Scan results arrived
- if (e.data.source === 'impeccable-results') {
- detectCount = e.data.count || 0;
- updateGlobalBarState();
- }
- }
-
- /** Full teardown: remove all UI, disconnect SSE, clean up. */
- function teardown() {
- cleanup();
- hideBar();
- if (globalBarEl) {
- globalBarEl.style.transform = 'translateY(100%)';
- setTimeout(() => { if (globalBarEl) globalBarEl.remove(); globalBarEl = null; }, 300);
- }
- if (highlightEl) { highlightEl.remove(); highlightEl = null; }
- if (tooltipEl) { tooltipEl.remove(); tooltipEl = null; }
- if (barEl) { barEl.remove(); barEl = null; }
- if (pickerEl) { pickerEl.remove(); pickerEl = null; }
- if (paramsPanelEl) { paramsPanelEl.remove(); paramsPanelEl = null; paramsPanelInner = null; paramsPanelBody = null; }
- if (evtSource) { evtSource.close(); evtSource = null; }
- document.removeEventListener('mousemove', handleMouseMove, true);
- document.removeEventListener('click', handleClick, true);
- document.removeEventListener('keydown', handleKeyDown, true);
- window.removeEventListener('message', onDetectMessage);
- // Remove detection overlays
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- state = 'IDLE';
- window.__IMPECCABLE_LIVE_INIT__ = false;
- console.log('[impeccable] Live mode exited.');
- }
-
- // ---------------------------------------------------------------------------
- // Design System Panel — visualizes the project's .impeccable/design.json sidecar
- // ---------------------------------------------------------------------------
-
- const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';
- const DESIGN_PANEL_WIDTH = 440;
-
- let designHost = null;
- let designShadow = null;
- let designState = {
- open: false,
- tab: 'visual', // 'visual' | 'raw'
- parsed: null, // parseDesignMd output (frontmatter + body sections)
- sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)
- hasMd: false,
- hasSidecar: false,
- present: null, // true/false once fetch resolves
- raw: null, // raw DESIGN.md for the raw tab
- mdNewerThanJson: false, // stale-hint flag
- loading: false,
- error: null,
- collapsed: { // narrative-section accordion state
- rules: true, dosdonts: true, overview: true,
- },
- };
-
- function loadDesignPrefs() {
- // `open` is intentionally NOT persisted — the panel always starts closed
- // so live mode doesn't auto-slide a big panel over the page on startup.
- try {
- const raw = localStorage.getItem(DESIGN_PREFS_KEY);
- if (!raw) return;
- const prefs = JSON.parse(raw);
- if (prefs.tab === 'visual' || prefs.tab === 'raw') designState.tab = prefs.tab;
- if (prefs.collapsed && typeof prefs.collapsed === 'object') {
- Object.assign(designState.collapsed, prefs.collapsed);
- }
- } catch { /* ignore */ }
- }
-
- function saveDesignPrefs() {
- try {
- localStorage.setItem(DESIGN_PREFS_KEY, JSON.stringify({
- tab: designState.tab,
- collapsed: designState.collapsed,
- }));
- } catch { /* ignore */ }
- }
-
- function initDesignPanel() {
- designHost = document.createElement('div');
- designHost.id = PREFIX + '-design-host';
- Object.assign(designHost.style, {
- position: 'fixed', top: '0', left: '0',
- width: '0', height: '0',
- zIndex: String(Z.bar + 10),
- pointerEvents: 'none',
- });
- designShadow = designHost.attachShadow({ mode: 'open' });
-
- const style = document.createElement('style');
- // Theme-match the bar: dark chrome on light pages, light chrome on dark pages.
- const theme = detectPageTheme();
- style.textContent = designPanelCss(barPaletteForTheme(theme));
- designShadow.appendChild(style);
-
- const root = document.createElement('div');
- root.className = 'root';
- designShadow.appendChild(root);
-
- document.body.appendChild(designHost);
- // The host is pointer-events: none; the panel inside the shadow DOM
- // manages its own auto/none. Events bubble through the shadow boundary,
- // so attaching here silences host-page outside-interaction handlers
- // without touching the host's click-through behavior.
- defangOutsideHandlers(designHost, { setPointerEvents: false });
-
- loadDesignPrefs();
- renderDesignChrome();
- if (designState.open) {
- fetchDesignSystem();
- }
- }
-
- // Neutral panel palette — deliberately NOT Impeccable-branded. The panel is
- // a viewer of the project's design system, not an Impeccable surface.
- const DP = {
- canvas: 'oklch(94% 0 0)', // panel background
- tile: 'oklch(98.5% 0 0)', // card-on-canvas
- tileAlt: 'oklch(96% 0 0)', // subtler tile for inner surfaces
- ink: 'oklch(15% 0 0)',
- ink2: 'oklch(35% 0 0)',
- meta: 'oklch(55% 0 0)',
- hairline: 'oklch(88% 0 0)',
- hairlineSoft: 'oklch(92% 0 0)',
- amber: 'oklch(70% 0.13 65)', // stale-hint accent
- amberBg: 'oklch(95% 0.05 80)',
- };
-
- function designPanelCss(BP) {
- // BP = bar palette (theme-aware, matches the global bar).
- // DP = internal content palette (neutral, so tiles render colors true).
- return `
- :host, .root { all: initial; }
- .root {
- font-family: ${FONT};
- color: ${DP.ink};
- pointer-events: none;
- }
- .root * { box-sizing: border-box; }
- button { font: inherit; color: inherit; }
-
- /* --- Panel shell: chrome matches the bar; body canvas stays neutral --- */
- .panel {
- position: fixed; top: 12px; bottom: 72px; right: 12px;
- width: ${DESIGN_PANEL_WIDTH}px; max-width: calc(100vw - 24px);
- background: ${BP.surface};
- border: 1px solid ${BP.hairline};
- border-radius: 14px;
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- box-shadow: 0 20px 60px oklch(0% 0 0 / 0.18), 0 4px 12px oklch(0% 0 0 / 0.08);
- display: flex; flex-direction: column;
- transform: translateX(calc(100% + 24px));
- opacity: 0;
- transition: transform 0.35s ${EASE}, opacity 0.25s ${EASE};
- pointer-events: none;
- overflow: hidden;
- }
- .panel[data-open="true"] { transform: translateX(0); opacity: 1; pointer-events: auto; }
-
- .panel-header {
- display: flex; align-items: center; gap: 10px;
- padding: 10px 10px 10px 14px;
- background: transparent;
- border-bottom: 1px solid ${BP.hairline};
- }
- .panel-title {
- flex: 1; min-width: 0;
- font-family: ${MONO};
- font-size: 11.5px; font-weight: 600;
- letter-spacing: 0.02em;
- color: ${BP.text};
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
- }
- .panel-close {
- border: none; background: transparent; color: ${BP.textDim};
- width: 26px; height: 26px; border-radius: 7px;
- display: inline-flex; align-items: center; justify-content: center;
- cursor: pointer; transition: background 0.15s ease, color 0.15s ease;
- }
- .panel-close:hover { background: ${BP.hairline}; color: ${BP.text}; }
-
- .tabs {
- display: inline-flex; padding: 2px;
- background: ${BP.hairline};
- border-radius: 7px;
- gap: 2px;
- }
- .tab {
- border: none; background: transparent;
- padding: 4px 10px; border-radius: 5px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 600; letter-spacing: 0.08em;
- text-transform: uppercase;
- color: ${BP.textDim}; cursor: pointer;
- transition: background 0.15s ease, color 0.15s ease;
- }
- .tab[data-active="true"] { background: ${BP.surface}; color: ${BP.text}; }
-
- .panel-body {
- flex: 1; overflow-y: auto;
- padding: 12px 12px 20px;
- background: ${DP.canvas};
- scrollbar-width: thin;
- scrollbar-color: ${DP.hairline} transparent;
- }
- .panel-body::-webkit-scrollbar { width: 8px; }
- .panel-body::-webkit-scrollbar-thumb { background: ${DP.hairline}; border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
-
- /* --- States --- */
- .empty, .loading, .error {
- margin: 16px 4px;
- padding: 28px 20px; text-align: center;
- background: ${DP.tile}; border-radius: 14px;
- color: ${DP.ink2}; font-size: 13px; line-height: 1.55;
- }
- .empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
- .empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
- .error { color: oklch(45% 0.15 25); }
-
- /* --- Stale hint --- */
- .stale {
- display: flex; align-items: center; gap: 8px;
- margin: 8px 4px 12px;
- padding: 8px 12px;
- background: ${DP.amberBg};
- border-radius: 10px;
- font-size: 11.5px; color: ${DP.ink2};
- }
- .stale-dot { width: 8px; height: 8px; border-radius: 50%; background: ${DP.amber}; flex-shrink: 0; }
- .stale-text { flex: 1; min-width: 0; }
- .stale-text strong { color: ${DP.ink}; font-weight: 600; }
-
- /* --- Parsed-md fallback banner --- */
- .parsed-md-cta {
- margin: 8px 4px 14px;
- padding: 14px 16px;
- background: ${DP.tile};
- border: 1px dashed ${DP.hairline};
- border-radius: 12px;
- font-size: 12px; color: ${DP.ink2}; line-height: 1.55;
- }
- .parsed-md-cta strong { color: ${DP.ink}; display: block; margin-bottom: 4px; font-size: 13px; font-weight: 600; }
- .parsed-md-cta code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; font-size: 11.5px; color: ${DP.ink}; }
-
- /* --- Tile primitives --- */
- .tile {
- position: relative;
- background: ${DP.tile};
- border-radius: 16px;
- padding: 16px;
- margin: 0 4px 10px;
- }
- .tile-row { margin: 0 4px 10px; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
- .tile-row .tile { margin: 0; }
- .tile-meta {
- display: flex; align-items: baseline; justify-content: space-between;
- gap: 10px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase;
- color: ${DP.meta};
- }
- .tile-meta .name { color: ${DP.ink}; font-weight: 600; letter-spacing: 0.05em; text-transform: none; font-family: ${FONT}; font-size: 12.5px; }
-
- /* --- Color tile --- */
- .c-tile { cursor: pointer; transition: transform 0.2s ${EASE}; }
- .c-tile:hover { transform: translateY(-1px); }
- .c-hero {
- height: 72px; border-radius: 10px; margin-top: 10px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.05);
- }
- .c-ramp {
- display: flex; gap: 0; height: 14px; border-radius: 4px; overflow: hidden;
- margin-top: 8px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.04);
- }
- .c-ramp > span { flex: 1; }
- .c-desc { margin-top: 8px; font-size: 11.5px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Type tile --- */
- .t-tile { }
- .t-specimen {
- margin: 4px 0 6px;
- color: ${DP.ink};
- line-height: 0.9;
- }
- .t-family { margin-top: 4px; font-size: 12px; font-weight: 600; color: ${DP.ink}; }
- .t-purpose { margin-top: 4px; font-size: 11px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Shadow tile --- */
- .s-tile { }
- .s-surface {
- height: 60px; margin: 8px 2px 10px;
- background: ${DP.tile};
- border-radius: 10px;
- }
- .s-value { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; word-break: break-all; line-height: 1.4; }
- .s-purpose { margin-top: 4px; font-size: 11px; color: ${DP.ink2}; line-height: 1.45; }
-
- /* --- Radii strip --- */
- .r-strip { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
- .r-item { display: flex; flex-direction: column; align-items: center; gap: 4px; flex: 1; min-width: 60px; }
- .r-sample { width: 44px; height: 44px; background: ${DP.canvas}; box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.08); }
- .r-label { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; text-transform: uppercase; }
- .r-val { font-family: ${MONO}; font-size: 10px; color: ${DP.ink}; }
-
- /* --- Component tile (hosts live primitives) --- */
- .cmp-tile { }
- .cmp-stage {
- margin: 12px -4px 0;
- padding: 18px 16px 10px;
- border-top: 1px solid ${DP.hairlineSoft};
- display: flex; flex-direction: column; align-items: center; justify-content: center;
- gap: 14px;
- min-height: 68px;
- }
- .cmp-stage + .cmp-stage { border-top: 1px dashed ${DP.hairlineSoft}; }
- .cmp-sublabel { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.06em; }
- .cmp-kind { font-family: ${MONO}; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; }
-
- /* --- Collapsible --- */
- .coll {
- margin: 0 4px 8px;
- background: ${DP.tile};
- border-radius: 12px;
- overflow: hidden;
- }
- .coll-head {
- display: flex; align-items: center; gap: 10px;
- width: 100%;
- padding: 12px 14px;
- background: transparent; border: none;
- cursor: pointer; text-align: left;
- font-family: ${FONT}; font-size: 12.5px; font-weight: 600; color: ${DP.ink};
- transition: background 0.12s ease;
- }
- .coll-head:hover { background: ${DP.tileAlt}; }
- .coll-chev {
- width: 12px; height: 12px; flex-shrink: 0;
- color: ${DP.meta};
- transition: transform 0.2s ${EASE};
- }
- .coll[data-open="true"] .coll-chev { transform: rotate(90deg); }
- .coll-count { margin-left: auto; font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; }
- .coll-body { padding: 0 14px 14px; display: none; }
- .coll[data-open="true"] .coll-body { display: block; }
-
- .rule-card {
- padding: 10px 0;
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .rule-card:first-child { border-top: none; padding-top: 2px; }
- .rule-card .name { font-size: 11.5px; font-weight: 700; color: ${DP.ink}; margin-bottom: 3px; }
- .rule-card .name .section { font-family: ${MONO}; font-size: 9px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; margin-left: 8px; }
- .rule-card .body { font-size: 11.5px; color: ${DP.ink2}; line-height: 1.5; }
-
- .coll .dos { display: grid; gap: 0; margin-top: 2px; }
- .coll .do, .coll .dont {
- position: relative;
- padding: 8px 0 8px 22px;
- font-size: 11.5px; line-height: 1.5; color: ${DP.ink2};
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .coll .do:first-child, .coll .dont:first-child,
- .coll .do:first-of-type { border-top: none; }
- .coll .do + .dont { border-top: 1px solid ${DP.hairlineSoft}; }
- .coll .do::before, .coll .dont::before {
- content: ''; position: absolute; left: 4px; top: 13px;
- width: 8px; height: 8px; border-radius: 50%;
- }
- .coll .do::before { background: oklch(62% 0.16 145); }
- .coll .dont::before { background: oklch(58% 0.22 25); }
-
- .coll .overview-body {
- font-size: 12px; line-height: 1.55; color: ${DP.ink2};
- }
- .coll .overview-body .north-star {
- display: block; font-family: ${FONT}; font-style: italic;
- font-size: 15px; line-height: 1.3; color: ${DP.ink};
- margin-bottom: 8px;
- }
- .coll .overview-body p { margin: 0 0 8px; }
- .coll .overview-body ul { margin: 6px 0 0; padding-left: 16px; font-size: 11.5px; }
- .coll .overview-body li { margin-bottom: 3px; }
-
- /* --- raw tab markdown (unchanged layout, neutralized palette) --- */
- .md { padding: 4px 10px 20px; font-size: 13px; line-height: 1.6; color: ${DP.ink}; }
- .md h1, .md h2, .md h3, .md h4 { margin: 20px 0 8px; color: ${DP.ink}; font-weight: 600; }
- .md h1 { font-size: 18px; }
- .md h2 { font-size: 15px; padding-bottom: 4px; border-bottom: 1px solid ${DP.hairlineSoft}; }
- .md h3 { font-size: 13px; }
- .md h4 { font-size: 12px; color: ${DP.meta}; }
- .md p { margin: 0 0 10px; }
- .md ul, .md ol { margin: 0 0 10px; padding-left: 20px; }
- .md li { margin-bottom: 4px; }
- .md code { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; }
- .md pre { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 10px 12px; border-radius: 8px; overflow-x: auto; margin: 0 0 10px; }
- .md pre code { background: none; padding: 0; }
- .md strong { font-weight: 700; }
- .md em { font-style: italic; }
- .md a { color: ${DP.ink}; text-decoration: underline; }
- .md hr { border: none; border-top: 1px solid ${DP.hairlineSoft}; margin: 16px 0; }
- `;
- }
-
- function renderDesignChrome() {
- const root = designShadow.querySelector('.root');
- root.innerHTML = '';
-
- // (Panel toggle lives in the global bar — no floating FAB.)
- // Panel
- const panel = document.createElement('aside');
- panel.className = 'panel';
- panel.setAttribute('data-open', designState.open ? 'true' : 'false');
- panel.appendChild(buildDesignHeader());
- const body = document.createElement('div');
- body.className = 'panel-body';
- body.id = 'panel-body';
- panel.appendChild(body);
- root.appendChild(panel);
-
- renderDesignBody();
- }
-
- function buildDesignHeader() {
- const header = document.createElement('div');
- header.className = 'panel-header';
-
- const title = document.createElement('div');
- title.className = 'panel-title';
- title.textContent = 'DESIGN.md';
- header.appendChild(title);
-
- const tabs = document.createElement('div');
- tabs.className = 'tabs';
- for (const t of [['visual', 'Visual'], ['raw', 'Raw']]) {
- const btn = document.createElement('button');
- btn.className = 'tab';
- btn.textContent = t[1];
- btn.setAttribute('data-active', designState.tab === t[0] ? 'true' : 'false');
- btn.addEventListener('click', () => {
- if (designState.tab === t[0]) return;
- designState.tab = t[0];
- saveDesignPrefs();
- renderDesignChrome();
- if (t[0] === 'raw' && designState.raw === null && !designState.loading) {
- fetchDesignSystem(); // raw is part of the same fetch pair
- }
- });
- tabs.appendChild(btn);
- }
- header.appendChild(tabs);
-
- const close = document.createElement('button');
- close.className = 'panel-close';
- close.innerHTML = '✕';
- close.setAttribute('aria-label', 'Close panel');
- close.addEventListener('click', toggleDesignPanel);
- header.appendChild(close);
-
- return header;
- }
-
- function toggleDesignPanel() {
- designState.open = !designState.open;
- renderDesignChrome();
- updateGlobalBarState();
- if (designState.open && designState.present === null && !designState.loading) {
- fetchDesignSystem();
- }
- }
-
- async function fetchDesignSystem() {
- designState.loading = true;
- designState.error = null;
- renderDesignBody();
- try {
- const [jsonRes, rawRes] = await Promise.all([
- fetch(`http://localhost:${PORT}/design-system.json?token=${TOKEN}`, { cache: 'no-store' }),
- fetch(`http://localhost:${PORT}/design-system/raw?token=${TOKEN}`, { cache: 'no-store' }),
- ]);
- const jsonData = await jsonRes.json();
- designState.present = jsonData.present === true;
- designState.parsed = jsonData.parsed || null;
- designState.sidecar = jsonData.sidecar || null;
- designState.hasMd = !!jsonData.hasMd;
- designState.hasSidecar = !!jsonData.hasSidecar;
- designState.mdNewerThanJson = !!jsonData.mdNewerThanJson;
- designState.raw = designState.present && rawRes.ok ? await rawRes.text() : null;
- designState.error = jsonData.parseError || jsonData.sidecarError || null;
- } catch (err) {
- designState.error = err?.message || 'Failed to load design system.';
- } finally {
- designState.loading = false;
- renderDesignChrome(); // refresh title from data
- }
- }
-
- function renderDesignBody() {
- const body = designShadow.querySelector('#panel-body');
- if (!body) return;
- body.innerHTML = '';
-
- if (designState.loading) {
- body.appendChild(msgDiv('loading', 'Loading design system…'));
- return;
- }
- if (designState.error) {
- body.appendChild(msgDiv('error', designState.error));
- return;
- }
- if (designState.present === false) {
- const empty = document.createElement('div');
- empty.className = 'empty';
- empty.innerHTML = `<strong>No DESIGN.md yet</strong>Create one by running <code>/impeccable document</code> in your terminal, then re-open this panel.`;
- body.appendChild(empty);
- return;
- }
-
- if (designState.tab === 'raw') {
- renderRawTab(body, designState.raw || '');
- return;
- }
-
- // Visual tab — single unified render path.
- if (designState.mdNewerThanJson) body.appendChild(renderStaleHint());
- if (designState.hasMd && !designState.hasSidecar) {
- body.appendChild(renderParsedMdCta());
- }
- renderDesignVisual(body, designState.parsed, designState.sidecar);
- }
-
- function msgDiv(cls, text) {
- const d = document.createElement('div');
- d.className = cls;
- d.textContent = text;
- return d;
- }
-
- function renderStaleHint() {
- const box = document.createElement('div');
- box.className = 'stale';
- box.innerHTML = `
- <span class="stale-dot"></span>
- <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>
- `;
- return box;
- }
-
- function renderParsedMdCta() {
- const box = document.createElement('div');
- box.className = 'parsed-md-cta';
- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;
- return box;
- }
-
- // --- Unified render: merge parsed DESIGN.md frontmatter with sidecar v2 ---
-
- function renderDesignVisual(body, parsed, sidecar) {
- const frontmatter = parsed?.frontmatter || {};
- const extensions = sidecar?.extensions || {};
- const proseColors = parsed?.colors || null;
-
- const colors = buildColorModels(frontmatter.colors, extensions.colorMeta, proseColors);
- if (colors.length) renderColorTiles(body, colors);
-
- const types = buildTypographyModels(frontmatter.typography, extensions.typographyMeta);
- if (types.length) renderTypeTiles(body, types);
-
- const radii = buildRadiiModels(frontmatter.rounded);
- if (radii.length) renderRadiiTile(body, radii);
-
- if (extensions.shadows?.length) renderShadowTiles(body, extensions.shadows);
-
- const components = sidecar?.components || [];
- if (components.length) renderComponentTiles(body, components);
-
- // Narrative: sidecar wins if present (richer, agent-curated). Otherwise
- // synthesize from prose sections.
- const narrative = sidecar?.narrative || synthesizeNarrative(parsed);
- if (narrative.rules?.length) body.appendChild(renderRulesCollapsible(narrative.rules));
- if ((narrative.dos?.length || narrative.donts?.length)) body.appendChild(renderDosDontsCollapsible(narrative));
- if (narrative.overview || narrative.northStar || narrative.keyCharacteristics?.length) {
- body.appendChild(renderOverviewCollapsible(narrative));
- }
-
- if (body.childElementCount === 0) {
- body.appendChild(msgDiv('empty', 'No design system data available.'));
- }
- }
-
- // Frontmatter primitives + sidecar colorMeta → tile-ready color models.
- // A matching prose bullet (when the slug sits in the bullet text) supplies
- // description as a last-resort fallback.
- function buildColorModels(fmColors, colorMeta, proseColors) {
- if (!fmColors) return [];
- const meta = colorMeta || {};
- return Object.entries(fmColors).map(([key, value]) => {
- const m = meta[key] || {};
- return {
- role: m.role || humanizeKey(key),
- name: m.displayName || humanizeKey(key),
- value: value,
- canonical: m.canonical || null,
- description: m.description || findProseDescription(proseColors, key, m.displayName),
- tonalRamp: m.tonalRamp || null,
- };
- });
- }
-
- function buildTypographyModels(fmTypography, typographyMeta) {
- if (!fmTypography) return [];
- const meta = typographyMeta || {};
- return Object.entries(fmTypography).map(([key, spec]) => {
- const m = meta[key] || {};
- const { family, fallback } = splitFontFamily(spec?.fontFamily);
- return {
- role: key,
- name: m.displayName || humanizeKey(key),
- family,
- fallback,
- weight: spec?.fontWeight ?? 400,
- // fontStyle isn't in Stitch's frontmatter schema; the sidecar carries
- // it when a role is rendered in italic (e.g. display italic).
- style: m.style || 'normal',
- sampleSize: spec?.fontSize || '1rem',
- lineHeight: spec?.lineHeight != null ? String(spec.lineHeight) : '',
- letterSpacing: spec?.letterSpacing,
- purpose: m.purpose,
- };
- });
- }
-
- function buildRadiiModels(fmRounded) {
- if (!fmRounded) return [];
- return Object.entries(fmRounded).map(([name, value]) => ({ name, value }));
- }
-
- function splitFontFamily(stack) {
- if (!stack || typeof stack !== 'string') return { family: '', fallback: '' };
- const parts = stack.split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, ''));
- return { family: parts[0] || '', fallback: parts.slice(1).join(', ') };
- }
-
- function humanizeKey(k) {
- return String(k || '').replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
- }
-
- function findProseDescription(proseColors, key, displayName) {
- if (!proseColors || !proseColors.groups) return null;
- const needles = [key, displayName].filter(Boolean).map((s) => s.toLowerCase());
- for (const g of proseColors.groups) {
- for (const c of g.colors || []) {
- const hay = String(c.name || '').toLowerCase();
- if (hay && needles.some((n) => hay.includes(n) || n.includes(hay))) {
- return c.description || null;
- }
- }
- }
- return null;
- }
-
- function synthesizeNarrative(parsed) {
- if (!parsed) return {};
- const md = parsed;
- return {
- northStar: md.overview?.creativeNorthStar,
- overview: (md.overview?.philosophy || []).join(' '),
- keyCharacteristics: md.overview?.keyCharacteristics || [],
- rules: [
- ...(md.colors?.rules || []).map((r) => ({ ...r, section: 'colors' })),
- ...(md.typography?.rules || []).map((r) => ({ ...r, section: 'typography' })),
- ...(md.elevation?.rules || []).map((r) => ({ ...r, section: 'elevation' })),
- ],
- dos: md.dosDonts?.dos || [],
- donts: md.dosDonts?.donts || [],
- };
- }
-
- function renderColorTiles(body, colors) {
- for (const c of colors) {
- const tile = document.createElement('div');
- tile.className = 'tile c-tile';
- tile.title = 'Click to copy';
- tile.addEventListener('click', () => copyToClipboard(c.value));
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(c.name || c.role || 'Color')}</span><span>${escapeHtml(c.value || '')}</span>`;
- tile.appendChild(meta);
-
- const hero = document.createElement('div');
- hero.className = 'c-hero';
- hero.style.background = c.value;
- tile.appendChild(hero);
-
- const ramp = synthesizeRamp(c);
- if (ramp.length) {
- const r = document.createElement('div');
- r.className = 'c-ramp';
- r.innerHTML = ramp.map((v) => `<span style="background:${cssSafe(v)}"></span>`).join('');
- tile.appendChild(r);
- }
-
- if (c.description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = c.description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function synthesizeRamp(c) {
- if (c.tonalRamp?.length) return c.tonalRamp;
- // If base value is OKLCH, synthesize an 8-step ramp across lightness.
- const m = typeof c.value === 'string' && c.value.match(/^oklch\(\s*([\d.]+)%\s+([\d.]+)\s+([\d.]+)\s*(?:\/\s*([\d.]+))?\s*\)$/i);
- if (!m) return [];
- const [, , chroma, hue] = m;
- const steps = [20, 32, 44, 56, 68, 80, 90, 96];
- return steps.map((l) => `oklch(${l}% ${chroma} ${hue})`);
- }
-
- function renderTypeTiles(body, types) {
- for (const t of types) {
- const tile = document.createElement('div');
- tile.className = 'tile t-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span>${escapeHtml(t.role || '')}</span><span>${escapeHtml(t.weight || '')} ${escapeHtml(t.style === 'italic' ? 'italic' : '')}</span>`;
- tile.appendChild(meta);
-
- const specimen = document.createElement('div');
- specimen.className = 't-specimen';
- specimen.textContent = 'Aa';
- specimen.style.fontFamily = fontStack(t);
- specimen.style.fontWeight = String(t.weight || 400);
- specimen.style.fontStyle = t.style || 'normal';
- specimen.style.fontSize = '56px'; // Fixed specimen size — compare faces, not scales.
- specimen.style.letterSpacing = 'normal';
- specimen.style.textTransform = 'none';
- tile.appendChild(specimen);
-
- // The system's actual sample size for this role, shown as small mono meta below.
- if (t.sampleSize) {
- const scale = document.createElement('div');
- scale.style.cssText = 'font-family:' + MONO + '; font-size: 10px; color:' + DP.meta + '; margin-top: 2px;';
- scale.textContent = t.sampleSize;
- tile.appendChild(scale);
- }
-
- const family = document.createElement('div');
- family.className = 't-family';
- family.textContent = t.family || t.name || '';
- tile.appendChild(family);
-
- if (t.purpose) {
- const p = document.createElement('div');
- p.className = 't-purpose';
- p.textContent = t.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function fontStack(t) {
- const fam = t.family || '';
- const fb = t.fallback || '';
- if (fam && /[,\s]/.test(fam) && !fam.includes("'") && !fam.includes('"')) {
- return `"${fam}", ${fb}`;
- }
- return fam && fb ? `"${fam}", ${fb}` : (fam || fb);
- }
-
- function renderRadiiTile(body, radii) {
- const tile = document.createElement('div');
- tile.className = 'tile';
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">Corner Radii</span><span>${radii.length}</span>`;
- tile.appendChild(meta);
-
- const strip = document.createElement('div');
- strip.className = 'r-strip';
- for (const r of radii) {
- const item = document.createElement('div');
- item.className = 'r-item';
- const s = document.createElement('div');
- s.className = 'r-sample';
- s.style.borderRadius = r.value || '0';
- item.appendChild(s);
- const lbl = document.createElement('div');
- lbl.className = 'r-label';
- lbl.textContent = r.name || '';
- item.appendChild(lbl);
- const val = document.createElement('div');
- val.className = 'r-val';
- val.textContent = r.value || '';
- item.appendChild(val);
- strip.appendChild(item);
- }
- tile.appendChild(strip);
- body.appendChild(tile);
- }
-
- function renderShadowTiles(body, shadows) {
- for (const sh of shadows) {
- const tile = document.createElement('div');
- tile.className = 'tile s-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(sh.name || 'Shadow')}</span><span>Elevation</span>`;
- tile.appendChild(meta);
-
- const surface = document.createElement('div');
- surface.className = 's-surface';
- surface.style.boxShadow = sh.value || 'none';
- tile.appendChild(surface);
-
- const val = document.createElement('div');
- val.className = 's-value';
- val.textContent = sh.value || '';
- tile.appendChild(val);
-
- if (sh.purpose) {
- const p = document.createElement('div');
- p.className = 's-purpose';
- p.textContent = sh.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function renderComponentTiles(body, components) {
- // Group consecutive components that share a kind into one tile. This avoids
- // a pile of one-component tiles (e.g., three button variants = three tiles)
- // and reads more like a proper category.
- const groups = groupByKind(components);
-
- for (const group of groups) {
- const tile = document.createElement('div');
- tile.className = 'tile cmp-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- const groupTitle = group.length === 1
- ? (group[0].name || group[0].kind || 'Component')
- : titleForKind(group[0].kind, group.length);
- meta.innerHTML = `<span class="name">${escapeHtml(groupTitle)}</span><span class="cmp-kind">${escapeHtml(group[0].kind || '')}</span>`;
- tile.appendChild(meta);
-
- for (const c of group) {
- const stage = document.createElement('div');
- stage.className = 'cmp-stage';
-
- // Render the component in its own shadow root so its CSS can't bleed.
- const host = document.createElement('div');
- const sub = host.attachShadow({ mode: 'open' });
- const style = document.createElement('style');
- style.textContent = c.css || '';
- sub.appendChild(style);
- const container = document.createElement('div');
- container.innerHTML = c.html || '';
- sub.appendChild(container);
- stage.appendChild(host);
-
- // Show component name as a sublabel only when the tile groups >1 item,
- // or when the component's display name differs from its kind.
- const showSublabel = group.length > 1;
- if (showSublabel) {
- const lbl = document.createElement('div');
- lbl.className = 'cmp-sublabel';
- lbl.textContent = c.name || '';
- stage.appendChild(lbl);
- }
- tile.appendChild(stage);
- }
-
- // Single shared description if all items carry the same one; otherwise
- // skip — per-item descriptions clutter a grouped tile.
- if (group.length === 1 && group[0].description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = group[0].description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function groupByKind(components) {
- const groups = [];
- for (const c of components) {
- const last = groups[groups.length - 1];
- if (last && last[0].kind && c.kind === last[0].kind) {
- last.push(c);
- } else {
- groups.push([c]);
- }
- }
- return groups;
- }
-
- function titleForKind(kind, count) {
- const labels = {
- button: 'Buttons',
- input: 'Inputs',
- nav: 'Navigation',
- chip: 'Chips',
- card: 'Cards',
- custom: 'Components',
- };
- return labels[kind] || (kind ? kind.charAt(0).toUpperCase() + kind.slice(1) + 's' : 'Components');
- }
-
- // --- Collapsibles ---------------------------------------------------------
-
- function buildCollapsible(key, label, count) {
- const wrap = document.createElement('div');
- wrap.className = 'coll';
- wrap.setAttribute('data-open', designState.collapsed[key] ? 'false' : 'true');
-
- const head = document.createElement('button');
- head.className = 'coll-head';
- head.innerHTML = `
- <svg class="coll-chev" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 2.5L8 6 4 9.5"/></svg>
- <span>${escapeHtml(label)}</span>
- ${count != null ? `<span class="coll-count">${escapeHtml(String(count))}</span>` : ''}
- `;
- head.addEventListener('click', () => {
- designState.collapsed[key] = !designState.collapsed[key];
- saveDesignPrefs();
- renderDesignBody();
- });
- wrap.appendChild(head);
-
- const body = document.createElement('div');
- body.className = 'coll-body';
- wrap.appendChild(body);
- return { wrap, body };
- }
-
- function renderRulesCollapsible(rules) {
- const { wrap, body } = buildCollapsible('rules', 'Named Rules', rules.length);
- for (const r of rules) {
- const card = document.createElement('div');
- card.className = 'rule-card';
- const name = document.createElement('div');
- name.className = 'name';
- name.innerHTML = `${escapeHtml(r.name)}${r.section ? `<span class="section">${escapeHtml(r.section)}</span>` : ''}`;
- card.appendChild(name);
- const b = document.createElement('div');
- b.className = 'body';
- b.textContent = r.body || '';
- card.appendChild(b);
- body.appendChild(card);
- }
- return wrap;
- }
-
- function renderDosDontsCollapsible(n) {
- const total = (n.dos?.length || 0) + (n.donts?.length || 0);
- const { wrap, body } = buildCollapsible('dosdonts', "Do's and Don'ts", total);
- const grid = document.createElement('div');
- grid.className = 'dos';
- for (const d of n.dos || []) {
- const el = document.createElement('div');
- el.className = 'do';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- for (const d of n.donts || []) {
- const el = document.createElement('div');
- el.className = 'dont';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- body.appendChild(grid);
- return wrap;
- }
-
- function renderOverviewCollapsible(n) {
- const { wrap, body } = buildCollapsible('overview', 'Overview', null);
- const ov = document.createElement('div');
- ov.className = 'overview-body';
- if (n.northStar) {
- const star = document.createElement('span');
- star.className = 'north-star';
- star.textContent = '“' + n.northStar + '”';
- ov.appendChild(star);
- }
- if (n.overview) {
- const p = document.createElement('p');
- p.innerHTML = inlineMd(n.overview);
- ov.appendChild(p);
- }
- if (n.keyCharacteristics?.length) {
- const ul = document.createElement('ul');
- ul.innerHTML = n.keyCharacteristics.map((k) => `<li>${inlineMd(k)}</li>`).join('');
- ov.appendChild(ul);
- }
- body.appendChild(ov);
- return wrap;
- }
-
- function cssSafe(v) {
- // Strip anything outside valid CSS value chars to prevent injection via
- // .impeccable/design.json values rendered into inline style strings.
- return String(v).replace(/[<>"'`\n]/g, '');
- }
-
- // --- Raw tab: minimal markdown renderer (subset) --------------------------
-
- function renderRawTab(body, md) {
- const wrap = document.createElement('div');
- wrap.className = 'md';
- wrap.innerHTML = renderMarkdown(md);
- body.appendChild(wrap);
- }
-
- function renderMarkdown(md) {
- const lines = md.split(/\r?\n/);
- const out = [];
- let i = 0;
- let inCode = false;
- let codeBuf = [];
- let paraBuf = [];
- let listBuf = []; // array of { indent, html }
- let listType = null; // 'ul' | 'ol'
-
- const flushPara = () => {
- if (paraBuf.length) {
- out.push(`<p>${inlineMd(paraBuf.join(' '))}</p>`);
- paraBuf = [];
- }
- };
- const flushList = () => {
- if (listBuf.length) {
- out.push(buildListHtml(listBuf, listType));
- listBuf = [];
- listType = null;
- }
- };
- const flushAll = () => { flushPara(); flushList(); };
-
- for (; i < lines.length; i++) {
- const line = lines[i];
-
- // Code fence
- const fence = line.match(/^```(\w*)\s*$/);
- if (fence) {
- if (!inCode) { flushAll(); inCode = true; codeBuf = []; }
- else {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- inCode = false;
- }
- continue;
- }
- if (inCode) { codeBuf.push(line); continue; }
-
- if (line.trim() === '') { flushAll(); continue; }
-
- const hr = line.match(/^\s*(?:---+|\*\*\*+)\s*$/);
- if (hr) { flushAll(); out.push('<hr />'); continue; }
-
- const heading = line.match(/^(#{1,4})\s+(.+)$/);
- if (heading) {
- flushAll();
- const lvl = heading[1].length;
- out.push(`<h${lvl}>${inlineMd(heading[2])}</h${lvl}>`);
- continue;
- }
-
- const bullet = line.match(/^(\s*)([-*])\s+(.+)$/);
- const ordered = line.match(/^(\s*)(\d+)\.\s+(.+)$/);
- if (bullet || ordered) {
- flushPara();
- const m = bullet || ordered;
- const indent = Math.floor(m[1].length / 2);
- const t = bullet ? 'ul' : 'ol';
- if (listType && listType !== t) flushList();
- listType = t;
- listBuf.push({ indent, html: inlineMd(m[3]) });
- continue;
- }
-
- paraBuf.push(line);
- }
- flushAll();
- if (inCode && codeBuf.length) {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- }
- return out.join('\n');
- }
-
- function buildListHtml(items, type) {
- // Nest by indent (one level deep is plenty for DESIGN.md).
- let html = `<${type}>`;
- let lastIndent = 0;
- for (const it of items) {
- if (it.indent > lastIndent) html += `<${type}>`;
- else if (it.indent < lastIndent) html += `</${type}>`.repeat(lastIndent - it.indent);
- html += `<li>${it.html}</li>`;
- lastIndent = it.indent;
- }
- html += `</${type}>`.repeat(lastIndent + 1);
- return html;
- }
-
- function inlineMd(text) {
- // Order matters: escape first, then re-inject tags.
- let s = escapeHtml(text);
- // Code spans
- s = s.replace(/`([^`]+)`/g, (_, code) => `<code>${code}</code>`);
- // Links [text](url)
- s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, t, u) => `<a href="${u}" target="_blank" rel="noopener noreferrer">${t}</a>`);
- // Bold
- s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
- // Italic (only single *…*, skip if inside bold already handled)
- s = s.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em>$2</em>');
- return s;
- }
-
- function highlightBold(text) {
- return inlineMd(text);
- }
-
- function escapeHtml(s) {
- return String(s)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
-
- function copyToClipboard(text) {
- if (!text) return;
- try {
- navigator.clipboard.writeText(text);
- showToast('Copied: ' + text);
- } catch { /* ignore */ }
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- function init() {
- try { history.scrollRestoration = 'manual'; } catch {}
- initHighlight();
- initAnnotOverlay();
- initBar();
- initActionPicker();
- initParamsPanel();
- initGlobalBar();
- initDesignPanel();
- document.addEventListener('mousemove', handleMouseMove, true);
- document.addEventListener('click', handleClick, true);
- document.addEventListener('keydown', handleKeyDown, true);
- connectSSE();
-
- // Check for an active session to resume (variant wrapper already in DOM after HMR)
- if (!resumeSession()) {
- console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
- // SvelteKit (and any framework that hydrates after HTML parse) may add
- // the variant wrapper AFTER init runs. Watch for it and retry resume
- // once it appears. Disconnect on first hit.
- const scout = new MutationObserver(() => {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) return;
- scout.disconnect();
- if (resumeSession()) {
- console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
- }
- });
- scout.observe(document.body, { childList: true, subtree: true });
- } else {
- console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
- }
- }
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
- } else {
- init();
- }
-})();
@@ -1,75 +0,0 @@
-#!/usr/bin/env node
-/**
- * Canonical durable completion acknowledgement for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function parseArgs(argv) {
- const out = { status: 'complete' };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';
- else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }
- else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function completeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help || !args.id) {
- console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);
- process.exit(args.help ? 0 : 1);
- }
-
- const serverInfo = readServerInfo();
- const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;
- if (serverResult?.ok) {
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const snapshot = store.getSnapshot(args.id, { includeCompleted: true });
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const event = args.status === 'discarded'
- ? { type: 'discarded', id: args.id }
- : args.status === 'agent_error'
- ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }
- : { type: 'complete', id: args.id };
- const snapshot = store.appendEvent(event);
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));
-}
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function completeThroughServer(info, args) {
- const type = args.status === 'discarded'
- ? 'discarded'
- : args.status === 'agent_error'
- ? 'error'
- : 'complete';
- try {
- const res = await fetch(`http://localhost:${info.port}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),
- });
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {
- completeCli();
-}
@@ -1,18 +0,0 @@
-export function completionTypeForAcceptResult(eventType, acceptResult) {
- if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';
- if (acceptResult?.handled === true) return 'complete';
- if (acceptResult?.mode === 'error') return 'error';
- return 'agent_done';
-}
-
-export function completionAckForAcceptResult(eventId, completionType, acceptResult) {
- const ack = { ok: true, type: completionType };
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) {
- ack.final = false;
- ack.requiresComplete = true;
- ack.nextCommand = `live-complete.mjs --id ${eventId}`;
- ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';
- }
- return ack;
-}
@@ -1,446 +0,0 @@
-/**
- * CLI helper: insert/remove the live variant mode script tag in the project's
- * main HTML entry point.
- *
- * On first live run, the agent generates `.impeccable/live/config.json`
- * with the project's insertion target (framework-specific). On
- * every subsequent run, this script handles insert/remove deterministically
- * with zero LLM involvement.
- *
- * Usage:
- * node live-inject.mjs --port PORT # Insert the live script tag
- * node live-inject.mjs --remove # Remove the live script tag
- * node live-inject.mjs --check # Check whether live config exists
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { resolveLiveConfigPath } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });
-const MARKER_OPEN_TEXT = 'impeccable-live-start';
-const MARKER_CLOSE_TEXT = 'impeccable-live-end';
-
-/**
- * Hard-excluded directory patterns. These are NEVER user-facing pages and
- * matching them would silently inject tracking scripts into third-party
- * code. The user cannot turn these off via config — they are the floor.
- */
-const HARD_EXCLUDES = [
- '**/node_modules/**',
- '**/.git/**',
-];
-
-export async function injectCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-inject.mjs [options]
-
-Insert or remove the live mode script tag in the project's HTML entry point.
-Reads configuration from .impeccable/live/config.json.
-
-Modes:
- --port PORT Insert script tag pointing at http://localhost:PORT/live.js
- --remove Remove the script tag (if present)
- --check Print whether .impeccable/live/config.json exists and its content
-
-Output (JSON):
- { ok, file, inserted|removed, config? }`);
- process.exit(0);
- }
-
- if (args.includes('--check')) {
- if (!fs.existsSync(CONFIG_PATH)) {
- console.log(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(0);
- }
- let cfg;
- try {
- cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- try {
- validateConfig(cfg);
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- console.log(JSON.stringify({ ok: true, config: cfg, path: CONFIG_PATH }));
- return;
- }
-
- // Load config
- if (!fs.existsSync(CONFIG_PATH)) {
- console.error(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(1);
- }
- const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- validateConfig(config);
-
- const resolvedFiles = resolveFiles(process.cwd(), config);
-
- if (args.includes('--remove')) {
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const detagged = removeTag(content, config.commentSyntax);
- const updated = revertCspMeta(detagged);
- if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- removed: detagged !== content,
- cspReverted: updated !== detagged,
- };
- });
- console.log(JSON.stringify({ ok: true, results }));
- return;
- }
-
- // Insert mode — need --port
- const portIdx = args.indexOf('--port');
- const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : NaN;
- if (!Number.isFinite(port)) {
- console.error(JSON.stringify({ ok: false, error: 'missing_port' }));
- process.exit(1);
- }
-
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
- const withTag = insertTag(withoutOld, config, port);
- if (withTag === withoutOld) {
- return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
- }
- const updated = patchCspMeta(withTag, port);
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- inserted: true,
- cspPatched: updated !== withTag,
- };
- });
- const anyInserted = results.some((r) => r.inserted);
- console.log(JSON.stringify({ ok: anyInserted, port, results }));
- if (!anyInserted) process.exit(1);
-}
-
-/**
- * Expand config.files (which may contain glob patterns) into a literal list
- * of existing file paths relative to rootDir. Literal entries pass through;
- * glob patterns are expanded via fs.globSync. HARD_EXCLUDES and config.exclude
- * are applied as filters. Duplicates are removed. Order is preserved by
- * first appearance.
- */
-export function resolveFiles(rootDir, config) {
- const patterns = config.files;
- const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
- const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
- const excludeRegexes = allExcludes.map(globToRegex);
-
- const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
- const isGlob = (s) => /[*?[]/.test(s);
-
- const seen = new Set();
- const out = [];
- for (const pat of patterns) {
- if (!isGlob(pat)) {
- // Literal path — include even if it doesn't exist yet; the caller
- // reports file_not_found per-entry. Exclude list doesn't apply to
- // explicit literal entries (user named it on purpose).
- if (!seen.has(pat)) {
- seen.add(pat);
- out.push(pat);
- }
- continue;
- }
- let matches;
- try {
- matches = fs.globSync(pat, { cwd: rootDir, withFileTypes: true });
- } catch {
- continue;
- }
- for (const ent of matches) {
- if (!ent.isFile || !ent.isFile()) continue;
- const abs = path.join(ent.parentPath || ent.path || rootDir, ent.name);
- const rel = path.relative(rootDir, abs).split(path.sep).join('/');
- if (isExcluded(rel)) continue;
- if (seen.has(rel)) continue;
- seen.add(rel);
- out.push(rel);
- }
- }
- return out;
-}
-
-/**
- * Convert a glob pattern to a RegExp. Supports:
- * ** → any number of path segments (including zero)
- * * → any chars except `/`
- * ? → any single char except `/`
- * Paths are normalized to forward slashes before matching.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- // ** — any number of segments, including zero. Handle the common
- // **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
- if (pattern[i + 2] === '/') {
- re += '(?:.*/)?';
- i += 3;
- } else {
- re += '.*';
- i += 2;
- }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Core operations
-// ---------------------------------------------------------------------------
-
-function validateConfig(cfg) {
- if (!cfg || typeof cfg !== 'object') throw new Error('config.json must be an object');
- if (!Array.isArray(cfg.files) || cfg.files.length === 0) {
- throw new Error('config.files (non-empty string array) required');
- }
- if (!cfg.files.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.files must contain only non-empty strings');
- }
- if (cfg.exclude !== undefined) {
- if (!Array.isArray(cfg.exclude)) {
- throw new Error('config.exclude, if present, must be a string array');
- }
- if (!cfg.exclude.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.exclude must contain only non-empty strings');
- }
- }
- if (typeof cfg.insertBefore !== 'string' && typeof cfg.insertAfter !== 'string') {
- throw new Error('config.insertBefore or config.insertAfter (string) required');
- }
- if (cfg.commentSyntax !== 'html' && cfg.commentSyntax !== 'jsx') {
- throw new Error("config.commentSyntax must be 'html' or 'jsx'");
- }
- if (cfg.cspChecked !== undefined && typeof cfg.cspChecked !== 'boolean') {
- throw new Error("config.cspChecked, if present, must be a boolean");
- }
-}
-
-function commentOpen(syntax) { return syntax === 'jsx' ? '{/*' : '<!--'; }
-function commentClose(syntax) { return syntax === 'jsx' ? '*/}' : '-->'; }
-
-function buildTagBlock(syntax, port) {
- const open = commentOpen(syntax);
- const close = commentClose(syntax);
- return (
- open + ' ' + MARKER_OPEN_TEXT + ' ' + close + '\n' +
- '<script src="http://localhost:' + port + '/live.js"></script>\n' +
- open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n'
- );
-}
-
-function insertTag(content, config, port) {
- const block = buildTagBlock(config.commentSyntax, port);
- // insertBefore: match the LAST occurrence. Anchors like `</body>` naturally
- // belong at the end, and the same literal can appear earlier in code blocks
- // within rendered documentation pages.
- if (config.insertBefore) {
- const idx = content.lastIndexOf(config.insertBefore);
- if (idx === -1) return content;
- return content.slice(0, idx) + block + content.slice(idx);
- }
- // insertAfter: match the FIRST occurrence — typical anchors like `<head>` or
- // `<body>` open near the top of the document.
- const idx = content.indexOf(config.insertAfter);
- if (idx === -1) return content;
- const after = idx + config.insertAfter.length;
- // Preserve a single trailing newline if the anchor didn't end with one
- const prefix = content[after] === '\n' ? content.slice(0, after + 1) : content.slice(0, after) + '\n';
- return prefix + block + content.slice(prefix.length);
-}
-
-/**
- * Remove the live script block. Matches either HTML or JSX comment markers
- * regardless of config (so stale tags from a wrong config can still be cleaned).
- *
- * Indent-preserving: captures any whitespace immediately preceding the opener
- * marker and re-emits it in place of the removed block. `insertTag` inserted
- * the block *after* the original line's indent and *before* the anchor (e.g.
- * `</body>`), which moved the indent onto the opener line and left the anchor
- * unindented. Replacing the whole block (plus its trailing newline) with just
- * the captured indent hands the indent back to the anchor that follows.
- */
-function removeTag(content, _syntax) {
- const patterns = [
- /([ \t]*)<!--\s*impeccable-live-start\s*-->[\s\S]*?<!--\s*impeccable-live-end\s*-->[ \t]*\n/,
- /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}[ \t]*\n/,
- ];
- for (const pat of patterns) {
- const next = content.replace(pat, '$1');
- if (next !== content) return next;
- }
- return content;
-}
-
-// ---------------------------------------------------------------------------
-// Content-Security-Policy meta-tag patcher
-//
-// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
-// the cross-origin load of /live.js (and the SSE/POST connection back to
-// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
-//
-// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
-// and stash the original `content` value in a `data-impeccable-csp-original`
-// attribute (base64) so revert is exact.
-//
-// On remove: detect the marker attribute, decode it, restore the original
-// content value verbatim, drop the marker.
-//
-// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
-// shared helpers) is NOT patched here — those need framework-specific config
-// edits and are handled via the existing detect-csp.mjs reference output.
-// Only the in-source meta-tag form gets the auto-patch.
-// ---------------------------------------------------------------------------
-
-const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
-
-function findCspMetaTags(content) {
- const out = [];
- const tagRe = /<meta\s+([^>]*?)\/?>/gis;
- let m;
- while ((m = tagRe.exec(content)) !== null) {
- const attrs = m[1];
- if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
- out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
- }
- return out;
-}
-
-function getAttr(attrs, name) {
- const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
- const m = attrs.match(re);
- return m ? { quote: m[1], value: m[2], full: m[0] } : null;
-}
-
-function appendOriginToDirective(csp, directive, origin) {
- const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
- const m = csp.match(re);
- if (m) {
- const tokens = m[4].trim().split(/\s+/);
- if (tokens.includes(origin)) return csp;
- return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
- }
- // Directive missing — add it. Use 'self' + origin so we don't inadvertently
- // narrow the policy compared to the default-src fallback (most users with
- // an explicit CSP have 'self' there).
- return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
-}
-
-export function patchCspMeta(content, port) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
- const origin = `http://localhost:${port}`;
-
- // Walk last-to-first so prior splices don't invalidate later indices.
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const attrs = tag.attrs;
- if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
- const contentAttr = getAttr(attrs, 'content');
- if (!contentAttr) continue;
-
- const original = contentAttr.value;
- let patched = original;
- patched = appendOriginToDirective(patched, 'script-src', origin);
- patched = appendOriginToDirective(patched, 'connect-src', origin);
- // The shader overlay during 'generating' creates a screenshot via
- // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
- // those. Add `blob:` so the overlay doesn't throw a CSP violation.
- patched = appendOriginToDirective(patched, 'img-src', 'blob:');
- if (patched === original) continue;
-
- const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
- const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
- // The tagRe captures any whitespace between the last attribute and the
- // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
- // a replace would land it BEFORE that trailing space, leaving a double
- // space inside attrs and clobbering the space before `/>`. Split off
- // the trailing whitespace, splice the marker into the attribute body,
- // and re-append the original trailing whitespace so a self-closing
- // `<meta … />` round-trips byte-for-byte.
- const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
- const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
- const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
- const newTag = tag.full.replace(attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-export function revertCspMeta(content) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
-
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
- if (!origAttr) continue;
- const contentAttr = getAttr(tag.attrs, 'content');
- if (!contentAttr) continue;
-
- let originalValue;
- try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
- catch { continue; }
-
- const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
- let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
- // Drop the marker attribute and any single space immediately preceding it.
- newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
- const newTag = tag.full.replace(tag.attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
- injectCli();
-}
-
-export { insertTag, removeTag, validateConfig, buildTagBlock };
-// patchCspMeta + revertCspMeta are exported above where they're defined.
@@ -1,200 +0,0 @@
-/**
- * CLI client for the live variant mode poll/reply protocol.
- *
- * Usage:
- * npx impeccable poll # Block until browser event, print JSON
- * npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
- * npx impeccable poll --reply <id> done # Reply "done" to event <id>
- * npx impeccable poll --reply <id> error "msg" # Reply with error
- */
-
-import { execFileSync } from 'node:child_process';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-// Node's built-in fetch (undici under the hood) enforces a 300s headers
-// timeout that can't be lowered per-request. We cap each request below
-// that ceiling and loop in `pollOnce` to synthesize a long poll without
-// depending on the standalone undici package.
-const PER_REQUEST_TIMEOUT_MS = 270_000;
-
-function readServerInfo() {
- const record = readLiveServerInfo(process.cwd());
- if (!record) {
- console.error('No running live server found. Start one with: npx impeccable live');
- process.exit(1);
- }
- return record.info;
-}
-
-export function buildPollReplyPayload(token, { id, type, message, file, data }) {
- return { token, id, type, message, file, data };
-}
-
-async function postReply(base, token, reply) {
- const res = await fetch(`${base}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(buildPollReplyPayload(token, reply)),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error || res.statusText);
- }
-}
-
-export async function pollCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable poll [options]
-
-Wait for a browser event from the live variant server, or reply to one.
-
-Modes:
- poll Block until a browser event arrives, print JSON
- poll --reply <id> done Reply "done" to event <id>
- poll --reply <id> error "msg" Reply with an error message
-
-Options:
- --timeout=MS Long-poll timeout in ms (default: 600000). Use the default unless the user asked to pause live; never use a short timeout to end the chat turn
- --help Show this help message`);
- process.exit(0);
- }
-
- const info = readServerInfo();
- const base = `http://localhost:${info.port}`;
-
- // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
- const replyIdx = args.indexOf('--reply');
- if (replyIdx !== -1) {
- const id = args[replyIdx + 1];
- const status = args[replyIdx + 2] || 'done';
- const fileIdx = args.indexOf('--file');
- const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
- // Message is any remaining positional arg that isn't a flag
- const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
-
- if (!id) {
- console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
- process.exit(1);
- }
-
- try {
- await postReply(base, info.token, { id, type: status, message, file: filePath });
-
- // Success — silent exit (agent doesn't need output for replies)
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Reply failed:', err.message);
- }
- process.exit(1);
- }
- return;
- }
-
- // Poll mode: block until browser event. Default 10 min. Node's built-in
- // fetch enforces a 300s headers timeout, so we loop in slices under that
- // ceiling and keep re-polling until we get a real event or the user's
- // total timeout runs out.
- const timeoutArg = args.find(a => a.startsWith('--timeout='));
- const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600000;
-
- const deadline = Date.now() + totalTimeout;
- let event;
- try {
- while (true) {
- const remaining = deadline - Date.now();
- if (remaining <= 0) {
- event = { type: 'timeout' };
- break;
- }
- const slice = Math.min(remaining, PER_REQUEST_TIMEOUT_MS);
- const res = await fetch(`${base}/poll?token=${info.token}&timeout=${slice}`);
-
- if (res.status === 401) {
- console.error('Authentication failed. The server token may have changed.');
- console.error('Try restarting: npx impeccable live stop && npx impeccable live');
- process.exit(1);
- }
-
- if (!res.ok) {
- console.error(`Poll failed: ${res.status} ${res.statusText}`);
- process.exit(1);
- }
-
- const next = await res.json();
- // Server-side timeout means no browser event arrived in this slice.
- // Loop and re-poll until we get a real event or we hit the user's
- // total deadline.
- if (next?.type === 'timeout' && Date.now() < deadline) continue;
- event = next;
- break;
- }
-
- // Auto-handle accept/discard via deterministic script
- if (event.type === 'accept' || event.type === 'discard') {
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const acceptScript = path.join(__dirname, 'live-accept.mjs');
- const scriptArgs = event.type === 'discard'
- ? ['--id', event.id, '--discard']
- : ['--id', event.id, '--variant', event.variantId];
- if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
- scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
- }
- try {
- const out = execFileSync(
- 'node',
- [acceptScript, ...scriptArgs],
- { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 }
- );
- event._acceptResult = JSON.parse(out.trim());
- } catch (err) {
- event._acceptResult = { handled: false, mode: 'error', error: err.message };
- }
-
- const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
- try {
- await postReply(base, info.token, {
- id: event.id,
- type: completionType,
- message: event._acceptResult?.error,
- file: event._acceptResult?.file,
- data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
- });
- } catch (err) {
- event._completionAck = { ok: false, error: err.message };
- }
- if (!event._completionAck) {
- event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
- }
- }
-
- // Second signal path: stderr banner in case the agent parses stdout
- // JSON but skips nested fields. One line is enough — the full checklist
- // is in reference/live.md.
- if (event._acceptResult?.carbonize === true) {
- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
- }
-
- // Print the event as JSON — the agent reads this from stdout
- console.log(JSON.stringify(event));
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Poll failed:', err.message);
- }
- process.exit(1);
- }
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
- pollCli();
-}
@@ -1,48 +0,0 @@
-#!/usr/bin/env node
-/**
- * Recover the next agent action from the durable live-session journal.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-
-function parseArgs(argv) {
- const out = { id: null };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function resumeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help) {
- console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });
- const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;
- if (!snapshot) {
- console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));
- return;
- }
-
- const pending = snapshot.pendingEvent || null;
- const nextAction = pending
- ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`
- : snapshot.phase === 'carbonize_required'
- ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`
- : snapshot.phase === 'accept_requested'
- ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`
- : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;
-
- console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {
- resumeCli();
-}
@@ -1,838 +0,0 @@
-#!/usr/bin/env node
-/**
- * Live variant mode server (self-contained, zero dependencies).
- *
- * Serves the browser script (/live.js), the detection overlay (/detect.js),
- * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
- * browser→server events. Agent communicates via HTTP long-poll (/poll).
- *
- * Usage:
- * node <scripts_path>/live-server.mjs # start
- * node <scripts_path>/live-server.mjs stop # stop + remove injected live.js tag
- * node <scripts_path>/live-server.mjs stop --keep-inject # stop only
- * node <scripts_path>/live-server.mjs --help
- */
-
-import http from 'node:http';
-import { randomUUID } from 'node:crypto';
-import { spawn, execFileSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import net from 'node:net';
-import { fileURLToPath } from 'node:url';
-import { parseDesignMd } from './design-parser.mjs';
-import { resolveContextDir } from './load-context.mjs';
-import { createLiveSessionStore } from './live-session-store.mjs';
-import {
- getDesignSidecarPath,
- getLiveAnnotationsDir,
- readLiveServerInfo,
- removeLiveServerInfo,
- resolveDesignSidecarPath,
- writeLiveServerInfo,
-} from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated
-// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
-// DESIGN.json fallback for existing projects.
-const CONTEXT_DIR = resolveContextDir(process.cwd());
-const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anyway
-const SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s
-
-// ---------------------------------------------------------------------------
-// Port detection
-// ---------------------------------------------------------------------------
-
-async function findOpenPort(start = 8400) {
- return new Promise((resolve) => {
- const srv = net.createServer();
- srv.listen(start, '127.0.0.1', () => {
- const port = srv.address().port;
- srv.close(() => resolve(port));
- });
- srv.on('error', () => resolve(findOpenPort(start + 1)));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Session state
-// ---------------------------------------------------------------------------
-
-const state = {
- token: null,
- port: null,
- sseClients: new Set(), // SSE response objects (server→browser push)
- pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
- pendingPolls: [], // agent poll callbacks waiting for browser events
- exitTimer: null,
- sessionDir: null, // per-session tmp dir for annotation screenshots
- sessionStore: null,
- leaseTimer: null,
-};
-
-// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;
-// cap at 10 MB to guard against runaway writes from a misbehaving client.
-const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
-
-function enqueueEvent(event) {
- if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;
- state.pendingEvents.push({ event, leaseUntil: 0 });
- flushPendingPolls();
-}
-
-function restorePendingEventsFromStore() {
- if (!state.sessionStore) return;
- for (const snapshot of state.sessionStore.listActiveSessions()) {
- if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);
- }
-}
-
-function findAvailablePendingEvent(now = Date.now()) {
- return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);
-}
-
-function leaseEvent(entry, leaseMs) {
- if (!entry.event?.id) {
- const idx = state.pendingEvents.indexOf(entry);
- if (idx !== -1) state.pendingEvents.splice(idx, 1);
- return entry.event;
- }
- entry.leaseUntil = Date.now() + leaseMs;
- return entry.event;
-}
-
-function acknowledgePendingEvent(id) {
- if (!id) return false;
- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);
- if (idx === -1) return false;
- state.pendingEvents.splice(idx, 1);
- scheduleLeaseFlush();
- return true;
-}
-
-function scheduleLeaseFlush() {
- if (state.leaseTimer) {
- clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- }
- if (state.pendingPolls.length === 0) return;
- const now = Date.now();
- const nextLeaseUntil = state.pendingEvents
- .map((entry) => entry.leaseUntil || 0)
- .filter((leaseUntil) => leaseUntil > now)
- .sort((a, b) => a - b)[0];
- if (!nextLeaseUntil) return;
- state.leaseTimer = setTimeout(() => {
- state.leaseTimer = null;
- flushPendingPolls();
- }, Math.max(0, nextLeaseUntil - now));
-}
-
-function flushPendingPolls() {
- while (state.pendingPolls.length > 0) {
- const entry = findAvailablePendingEvent();
- if (!entry) {
- scheduleLeaseFlush();
- return;
- }
- const poll = state.pendingPolls.shift();
- poll.resolve(leaseEvent(entry, poll.leaseMs));
- }
- scheduleLeaseFlush();
-}
-
-/** Push a message to all connected SSE clients. */
-function broadcast(msg) {
- const data = 'data: ' + JSON.stringify(msg) + '\n\n';
- for (const res of state.sseClients) {
- try { res.write(data); } catch { /* client gone */ }
- }
-}
-
-// ---------------------------------------------------------------------------
-// Load scripts
-// ---------------------------------------------------------------------------
-
-function loadBrowserScripts() {
- // Detection script: prefer the skill-bundled detector, then fall back to
- // source/npm package locations for local development and older installs.
- // This one IS cached — detect.js rarely changes during a session.
- const detectPaths = [
- path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(process.cwd(), 'node_modules', 'impeccable', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- ];
- let detectScript = '';
- for (const p of detectPaths) {
- try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
- }
-
- // live-browser.js: DO NOT cache. Return the path so the /live.js handler
- // can re-read on every request. Editing the browser script during iteration
- // should land on the next tab reload, not require a server restart.
- const sessionPath = path.join(__dirname, 'live-browser-session.js');
- const livePath = path.join(__dirname, 'live-browser.js');
- for (const p of [sessionPath, livePath]) {
- if (!fs.existsSync(p)) {
- process.stderr.write('Error: live browser script not found at ' + p + '\n');
- process.exit(1);
- }
- }
-
- return { detectScript, sessionPath, livePath };
-}
-
-function hasProjectContext() {
- // PRODUCT.md carries brand voice / anti-references — that's what determines
- // whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
- // concern, surfaced by the design panel's own empty state. Legacy
- // .impeccable.md is auto-migrated to PRODUCT.md by load-context.mjs.
- try {
- fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
- return true;
- } catch { return false; }
-}
-
-function statOrNull(filePath) {
- try { return fs.statSync(filePath); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// Validation (inline — no external import needed for self-contained script)
-// ---------------------------------------------------------------------------
-
-const VISUAL_ACTIONS = [
- 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
- 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
-];
-
-// Browser generates ids via crypto.randomUUID().slice(0, 8) (8 hex chars)
-// and variantIds via String(small integer). Restrict to those shapes so
-// any value that reaches a downstream child_process or DOM selector is
-// inert by construction.
-const ID_PATTERN = /^[0-9a-f]{8}$/;
-const VARIANT_ID_PATTERN = /^[0-9]{1,3}$/;
-
-function isValidId(v) { return typeof v === 'string' && ID_PATTERN.test(v); }
-function isValidVariantId(v) { return typeof v === 'string' && VARIANT_ID_PATTERN.test(v); }
-
-function validateEvent(msg) {
- if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
- switch (msg.type) {
- case 'generate':
- if (!isValidId(msg.id)) return 'generate: missing or malformed id';
- if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
- if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
- if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
- // Optional annotation fields (all-or-nothing: if any present, all must be well-formed).
- if (msg.screenshotPath !== undefined && typeof msg.screenshotPath !== 'string') return 'generate: screenshotPath must be string';
- if (msg.comments !== undefined && !Array.isArray(msg.comments)) return 'generate: comments must be array';
- if (msg.strokes !== undefined && !Array.isArray(msg.strokes)) return 'generate: strokes must be array';
- return null;
- case 'accept':
- if (!isValidId(msg.id)) return 'accept: missing or malformed id';
- if (!isValidVariantId(msg.variantId)) return 'accept: missing or malformed variantId';
- if (msg.paramValues !== undefined) {
- if (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues)) {
- return 'accept: paramValues must be an object';
- }
- }
- return null;
- case 'discard':
- return isValidId(msg.id) ? null : 'discard: missing or malformed id';
- case 'checkpoint':
- if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';
- if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';
- if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {
- return 'checkpoint: paramValues must be an object';
- }
- return null;
- case 'exit':
- return null;
- case 'prefetch':
- if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return 'prefetch: missing pageUrl';
- return null;
- default:
- return 'Unknown event type: ' + msg.type;
- }
-}
-
-// ---------------------------------------------------------------------------
-// HTTP request handler
-// ---------------------------------------------------------------------------
-
-function createRequestHandler({ detectScript, sessionPath, livePath }) {
- return (req, res) => {
- const url = new URL(req.url, `http://localhost:${state.port}`);
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
- if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
-
- const p = url.pathname;
-
- // --- Scripts ---
- if (p === '/live.js') {
- // Re-read from disk each request so edits to live-browser.js land on
- // the next tab reload. No-store headers prevent browser caching across
- // sessions — during iteration, a cached old script silently breaks
- // every subsequent session.
- let sessionScript;
- let liveScript;
- try {
- sessionScript = fs.readFileSync(sessionPath, 'utf-8');
- liveScript = fs.readFileSync(livePath, 'utf-8');
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'text/plain' });
- res.end('Error reading live browser scripts: ' + err.message);
- return;
- }
- const body =
- `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
- `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
- sessionScript + '\n' +
- liveScript;
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
- 'Pragma': 'no-cache',
- });
- res.end(body);
- return;
- }
- if (p === '/detect.js' || p === '/') {
- if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
- res.writeHead(200, { 'Content-Type': 'application/javascript' });
- res.end(detectScript);
- return;
- }
-
- // --- Vendored modern-screenshot (UMD build) ---
- // Lazy-loaded by live.js when the user clicks Go; exposes
- // window.modernScreenshot.domToBlob(...) for capture.
- if (p === '/modern-screenshot.js') {
- const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
- try {
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'public, max-age=31536000, immutable',
- });
- res.end(fs.readFileSync(vendorPath));
- } catch {
- res.writeHead(404); res.end('Vendor script not found');
- }
- return;
- }
-
- // --- Annotation upload (browser → server, raw PNG body) ---
- // Client generates the eventId, POSTs the PNG, then POSTs the generate
- // event with screenshotPath already set. Keeps bytes out of the SSE/poll
- // bridge and preserves the "one shot from the user's POV" UX.
- if (p === '/annotation' && req.method === 'POST') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const eventId = url.searchParams.get('eventId');
- if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid eventId' }));
- return;
- }
- if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
- res.writeHead(415, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
- return;
- }
- if (!state.sessionDir) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Session dir unavailable' }));
- return;
- }
- const chunks = [];
- let total = 0;
- let aborted = false;
- req.on('data', (c) => {
- if (aborted) return;
- total += c.length;
- if (total > MAX_ANNOTATION_BYTES) {
- aborted = true;
- res.writeHead(413, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Payload too large' }));
- req.destroy();
- return;
- }
- chunks.push(c);
- });
- req.on('end', () => {
- if (aborted) return;
- const absPath = path.join(state.sessionDir, eventId + '.png');
- try {
- fs.writeFileSync(absPath, Buffer.concat(chunks));
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Write failed: ' + err.message }));
- return;
- }
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true, path: absPath }));
- });
- req.on('error', () => {
- if (!aborted) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Upload failed' }));
- }
- });
- return;
- }
-
- // --- Health ---
- if (p === '/status') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
- const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok',
- port: state.port,
- connectedClients: state.sseClients.size,
- pendingEvents: state.pendingEvents.map((entry) => ({
- id: entry.event?.id,
- type: entry.event?.type,
- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),
- leaseUntil: entry.leaseUntil || null,
- })),
- activeSessions: sessions,
- }));
- return;
- }
-
- if (p === '/health') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok', port: state.port, mode: 'variant',
- hasProjectContext: hasProjectContext(),
- connectedClients: state.sseClients.size,
- }));
- return;
- }
-
- // --- Design system (unified v2 response) + raw ---
- // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json
- // sidecar when present. Panel merges them:
- // { present, parsed, sidecar, hasMd, hasSidecar,
- // mdNewerThanJson, parseError?, sidecarError? }
- // - parsed: output of parseDesignMd (frontmatter
- // + six canonical sections) when DESIGN.md exists.
- // - sidecar: .impeccable/design.json contents when present.
- // Expected shape: schemaVersion 2, carrying
- // extensions + components + narrative.
- // /design-system/raw returns DESIGN.md markdown verbatim
- if (p === '/design-system.json' || p === '/design-system/raw') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
-
- const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
- const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
- const mdStat = statOrNull(mdPath);
- const jsonStat = statOrNull(jsonPath);
-
- if (p === '/design-system/raw') {
- if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
- res.end(fs.readFileSync(mdPath, 'utf-8'));
- return;
- }
-
- if (!mdStat && !jsonStat) {
- res.writeHead(404, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ present: false }));
- return;
- }
-
- const response = {
- present: true,
- hasMd: !!mdStat,
- hasSidecar: !!jsonStat,
- mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
- };
-
- if (mdStat) {
- try {
- response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
- } catch (err) {
- response.parseError = err.message;
- }
- }
-
- if (jsonStat) {
- try {
- response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
- } catch (err) {
- response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;
- }
- }
-
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(response));
- return;
- }
-
- // --- Source file (no-HMR fallback) ---
- if (p === '/source') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const filePath = url.searchParams.get('path');
- if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
- const absPath = path.resolve(process.cwd(), filePath);
- if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
- let content;
- try { content = fs.readFileSync(absPath, 'utf-8'); }
- catch { res.writeHead(404); res.end('File not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
- res.end(content);
- return;
- }
-
- // --- SSE: server→browser push (replaces WebSocket) ---
- if (p === '/events' && req.method === 'GET') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- 'Connection': 'keep-alive',
- });
- res.write('data: ' + JSON.stringify({
- type: 'connected',
- hasProjectContext: hasProjectContext(),
- }) + '\n\n');
-
- state.sseClients.add(res);
- clearTimeout(state.exitTimer);
-
- // Keepalive: SSE comment every 30s prevents silent connection drops.
- const heartbeat = setInterval(() => {
- try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
- }, SSE_HEARTBEAT_INTERVAL);
-
- req.on('close', () => {
- clearInterval(heartbeat);
- state.sseClients.delete(res);
- if (state.sseClients.size === 0) {
- clearTimeout(state.exitTimer);
- state.exitTimer = setTimeout(() => {
- if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
- }, 8000);
- }
- });
- return;
- }
-
- // --- Browser→server events (replaces WebSocket messages) ---
- if (p === '/events' && req.method === 'POST') {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const error = validateEvent(msg);
- if (error) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error }));
- return;
- }
- if (state.sessionStore && msg.id) {
- try {
- state.sessionStore.appendEvent(msg);
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
- return;
- }
- }
- if (msg.type !== 'checkpoint') enqueueEvent(msg);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
- return;
- }
-
- // --- Stop ---
- if (p === '/stop') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.end('stopping');
- shutdown();
- return;
- }
-
- // --- Agent poll ---
- if (p === '/poll' && req.method === 'GET') {
- handlePollGet(req, res, url);
- return;
- }
- if (p === '/poll' && req.method === 'POST') {
- handlePollPost(req, res);
- return;
- }
-
- res.writeHead(404); res.end('Not found');
- };
-}
-
-// ---------------------------------------------------------------------------
-// Agent poll endpoints (unchanged from WS version)
-// ---------------------------------------------------------------------------
-
-function handlePollGet(req, res, url) {
- const token = url.searchParams.get('token');
- if (token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
- const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
- const available = findAvailablePendingEvent();
- if (available) {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(leaseEvent(available, leaseMs)));
- return;
- }
- const poll = { resolve, leaseMs };
- const timer = setTimeout(() => {
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ type: 'timeout' }));
- }, timeout);
- function resolve(event) {
- clearTimeout(timer);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(event));
- }
- state.pendingPolls.push(poll);
- scheduleLeaseFlush();
- req.on('close', () => {
- clearTimeout(timer);
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- });
-}
-
-function handlePollPost(req, res) {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- acknowledgePendingEvent(msg.id);
- if (state.sessionStore && msg.id) {
- try {
- const eventType = msg.type === 'discard' || msg.type === 'discarded'
- ? 'discarded'
- : msg.type === 'complete'
- ? 'complete'
- : msg.type === 'error'
- ? 'agent_error'
- : 'agent_done';
- state.sessionStore.appendEvent({
- type: eventType,
- id: msg.id,
- file: msg.file,
- message: msg.message,
- carbonize: msg.data?.carbonize === true,
- });
- } catch { /* keep reply path best-effort; browser still needs SSE */ }
- }
- flushPendingPolls();
- // Forward the reply to the browser via SSE
- broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Lifecycle
-// ---------------------------------------------------------------------------
-
-let httpServer = null;
-
-function shutdown() {
- removeLiveServerInfo(process.cwd());
- if (state.leaseTimer) clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- if (state.sessionDir) {
- try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}
- }
- for (const res of state.sseClients) { try { res.end(); } catch {} }
- state.sseClients.clear();
- for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });
- state.pendingPolls.length = 0;
- if (httpServer) httpServer.close();
- process.exit(0);
-}
-
-// ---------------------------------------------------------------------------
-// Main
-// ---------------------------------------------------------------------------
-
-const args = process.argv.slice(2);
-
-if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-server.mjs [options]
-
-Start the live variant mode server (zero dependencies).
-
-Commands:
- (default) Start the server (foreground)
- stop Stop the server and remove the injected live.js script tag
- stop --keep-inject Stop the server only (leave the script tag in the HTML entry)
-
-Options:
- --background Start detached, print connection JSON to stdout, then exit
- --port=PORT Use a specific port (default: auto-detect starting at 8400)
- --keep-inject Only with stop: skip live-inject.mjs --remove
- --help Show this help
-
-Endpoints:
- /live.js Browser script (element picker + variant cycling)
- /detect.js Detection overlay (backwards compatible)
- /modern-screenshot.js Vendored modern-screenshot UMD build (lazy-loaded by live.js)
- /annotation POST raw image/png to stage a variant screenshot
- /events SSE stream (server→browser) + POST (browser→server)
- /poll Long-poll for agent CLI
- /source Raw source file reader (no-HMR fallback)
- /status Durable recovery status (token-protected)
- /health Health check`);
- process.exit(0);
-}
-
-if (args.includes('stop')) {
- const keepInject = args.includes('--keep-inject');
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);
- if (res.ok) console.log(`Stopped live server on port ${info.port}.`);
- } catch {
- console.log('No running live server found.');
- }
- if (!keepInject) {
- const injectPath = path.join(__dirname, 'live-inject.mjs');
- try {
- const out = execFileSync(process.execPath, [injectPath, '--remove'], {
- encoding: 'utf-8',
- cwd: process.cwd(),
- });
- const line = out.trim().split('\n').filter(Boolean).pop();
- if (line) {
- try {
- const j = JSON.parse(line);
- if (j.removed === true) {
- console.log(`Removed live script tag from ${j.file}.`);
- }
- } catch {
- /* ignore non-JSON lines */
- }
- }
- } catch (err) {
- const detail = err.stderr?.toString?.().trim?.()
- || err.stdout?.toString?.().trim?.()
- || err.message
- || String(err);
- console.warn(`Note: could not remove live script tag (${detail.split('\n')[0]})`);
- }
- }
- process.exit(0);
-}
-
-// --background: spawn a detached child server, wait for it to be ready,
-// print the connection JSON, then exit. This keeps the startup command
-// simple (no shell backgrounding or chained commands).
-if (args.includes('--background')) {
- const childArgs = args.filter(a => a !== '--background');
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), ...childArgs], {
- detached: true,
- stdio: 'ignore',
- cwd: process.cwd(),
- });
- child.unref();
-
- // Poll for the PID file (the child writes it once the HTTP server is listening).
- const deadline = Date.now() + 10_000;
- while (Date.now() < deadline) {
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- if (info.pid !== process.pid) {
- // Output JSON so the agent can read port + token from stdout.
- console.log(JSON.stringify(info));
- process.exit(0);
- }
- } catch { /* not ready yet */ }
- await new Promise(r => setTimeout(r, 200));
- }
- console.error('Timed out waiting for live server to start.');
- process.exit(1);
-}
-
-// Check for existing session
-const existingRecord = readLiveServerInfo(process.cwd());
-if (existingRecord?.info) {
- const existing = existingRecord.info;
- try {
- process.kill(existing.pid, 0);
- console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
- console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');
- process.exit(1);
- } catch {
- try { fs.unlinkSync(existingRecord.path); } catch {}
- }
-}
-
-state.token = randomUUID();
-state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });
-restorePendingEventsFromStore();
-const portArg = args.find(a => a.startsWith('--port='));
-state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
-// Annotation screenshots live in the project root so the agent's Read tool
-// doesn't trip a per-file permission prompt. Sessioned by token so concurrent
-// projects (or quick restarts) don't collide.
-const annotRoot = getLiveAnnotationsDir(process.cwd());
-fs.mkdirSync(annotRoot, { recursive: true });
-state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));
-
-const { detectScript, sessionPath, livePath } = loadBrowserScripts();
-httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));
-
-httpServer.listen(state.port, '127.0.0.1', () => {
- writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });
- const url = `http://localhost:${state.port}`;
- console.log(`\nImpeccable live server running on ${url}`);
- console.log(`Token: ${state.token}\n`);
- console.log(`Inject: <script src="${url}/live.js"><\/script>`);
- console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
-});
-
-process.on('SIGINT', shutdown);
-process.on('SIGTERM', shutdown);
@@ -1,254 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';
-
-const COMPLETED_PHASES = new Set(['completed', 'discarded']);
-
-export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {
- const rootDir = getLiveSessionsDir(cwd);
- const legacyRootDir = getLegacyLiveSessionsDir(cwd);
- fs.mkdirSync(rootDir, { recursive: true });
- const snapshotCache = new Map();
-
- function loadCachedOrRebuild(id) {
- const cached = snapshotCache.get(id);
- if (cached) return cached;
- const journalPath = getReadableJournalPath(id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- return rebuilt;
- }
-
- function getReadableJournalPath(id) {
- const primary = getJournalPath(rootDir, id);
- if (fs.existsSync(primary)) return primary;
- const legacy = getJournalPath(legacyRootDir, id);
- if (fs.existsSync(legacy)) return legacy;
- return primary;
- }
-
- return {
- rootDir,
- legacyRootDir,
- appendEvent(event) {
- const normalized = normalizeEvent(event, sessionId);
- const journalPath = getJournalPath(rootDir, normalized.id);
- const snapshotPath = getSnapshotPath(rootDir, normalized.id);
- const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);
- if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {
- fs.copyFileSync(legacyJournalPath, journalPath);
- }
- const prior = loadCachedOrRebuild(normalized.id);
- const seq = prior.nextSeq;
- const entry = {
- seq,
- id: normalized.id,
- type: normalized.type,
- ts: new Date().toISOString(),
- event: normalized,
- };
- fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');
- const next = applyEvent(prior.snapshot, entry, prior.diagnostics);
- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });
- writeSnapshot(snapshotPath, next);
- return next;
- },
- getSnapshot(id = sessionId, opts = {}) {
- if (!id) throw new Error('session id required');
- const journalPath = getReadableJournalPath(id);
- const snapshotPath = getSnapshotPath(rootDir, id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- writeSnapshot(snapshotPath, rebuilt.snapshot);
- if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;
- return rebuilt.snapshot;
- },
- listActiveSessions() {
- const ids = new Set();
- for (const dir of [legacyRootDir, rootDir]) {
- if (!fs.existsSync(dir)) continue;
- for (const name of fs.readdirSync(dir)) {
- if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));
- }
- }
- return [...ids]
- .sort()
- .map((id) => this.getSnapshot(id))
- .filter(Boolean);
- },
- };
-}
-
-function normalizeEvent(event, fallbackId) {
- if (!event || typeof event !== 'object') throw new Error('event object required');
- const id = event.id || fallbackId;
- if (!id || typeof id !== 'string') throw new Error('event id required');
- if (!event.type || typeof event.type !== 'string') throw new Error('event type required');
- return { ...event, id };
-}
-
-function getJournalPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.jsonl');
-}
-
-function getSnapshotPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.snapshot.json');
-}
-
-function safeSessionId(id) {
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);
- return id;
-}
-
-function baseSnapshot(id) {
- return {
- id,
- phase: 'new',
- pageUrl: null,
- sourceFile: null,
- expectedVariants: 0,
- arrivedVariants: 0,
- visibleVariant: null,
- paramValues: {},
- pendingEventSeq: null,
- pendingEvent: null,
- deliveryLease: null,
- checkpointRevision: 0,
- activeOwner: null,
- sourceMarkers: {},
- fallbackMode: null,
- annotationArtifacts: [],
- diagnostics: [],
- updatedAt: null,
- };
-}
-
-function rebuildSnapshotFromJournal(journalPath, id) {
- let snapshot = baseSnapshot(id);
- const diagnostics = [];
- let nextSeq = 1;
- if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };
-
- const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- if (!line.trim()) continue;
- try {
- const entry = JSON.parse(line);
- if (!entry || typeof entry !== 'object') throw new Error('entry is not object');
- if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);
- snapshot = applyEvent(snapshot, entry);
- } catch (err) {
- diagnostics.push({
- error: 'journal_parse_failed',
- line: i + 1,
- message: err.message,
- });
- }
- }
- snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];
- return { snapshot, diagnostics, nextSeq };
-}
-
-function applyEvent(snapshot, entry, inheritedDiagnostics = []) {
- const event = entry.event || entry;
- const next = {
- ...snapshot,
- paramValues: { ...(snapshot.paramValues || {}) },
- sourceMarkers: { ...(snapshot.sourceMarkers || {}) },
- annotationArtifacts: [...(snapshot.annotationArtifacts || [])],
- diagnostics: [...(snapshot.diagnostics || [])],
- updatedAt: entry.ts || new Date().toISOString(),
- };
-
- if (inheritedDiagnostics.length && next.diagnostics.length === 0) {
- next.diagnostics = [...inheritedDiagnostics];
- }
-
- switch (event.type) {
- case 'generate':
- next.phase = 'generate_requested';
- next.pageUrl = event.pageUrl ?? next.pageUrl;
- next.expectedVariants = event.count ?? next.expectedVariants;
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });
- break;
- case 'variants_ready':
- case 'agent_done':
- next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';
- next.sourceFile = event.file ?? next.sourceFile;
- next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- if (event.carbonize === true) {
- next.diagnostics.push({
- error: 'carbonize_cleanup_required',
- file: event.file || null,
- message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',
- });
- }
- break;
- case 'checkpoint':
- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {
- next.phase = event.phase ?? next.phase;
- next.checkpointRevision = event.revision ?? next.checkpointRevision;
- next.activeOwner = event.owner ?? next.activeOwner;
- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;
- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- } else {
- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });
- }
- break;
- case 'accept':
- case 'accept_intent':
- next.phase = 'accept_requested';
- next.visibleVariant = Number(event.variantId ?? next.visibleVariant);
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discard':
- next.phase = 'discard_requested';
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discarded':
- next.phase = 'discarded';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'complete':
- next.phase = 'completed';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'agent_error':
- next.phase = 'agent_error';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });
- break;
- default:
- next.diagnostics.push({ error: 'unknown_event_type', type: event.type });
- break;
- }
- return next;
-}
-
-function toPendingEvent(event) {
- const pending = { ...event };
- delete pending.token;
- return pending;
-}
-
-function upsertArtifact(artifacts, artifact) {
- if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {
- artifacts.push(artifact);
- }
-}
-
-function writeSnapshot(snapshotPath, snapshot) {
- fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');
-}
@@ -1,47 +0,0 @@
-#!/usr/bin/env node
-/**
- * Print durable recovery status for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function fetchServerStatus(info) {
- if (!info) return null;
- try {
- const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-export async function statusCli() {
- const info = readServerInfo();
- const server = await fetchServerStatus(info);
- const store = createLiveSessionStore({ cwd: process.cwd() });
- const activeSessions = store.listActiveSessions();
- const payload = {
- liveServer: server ? {
- status: server.status,
- port: server.port,
- connectedClients: server.connectedClients,
- pendingEvents: server.pendingEvents,
- } : null,
- activeSessions: server?.activeSessions || activeSessions,
- recoveryHint: server
- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'
- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',
- };
- console.log(JSON.stringify(payload, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {
- statusCli();
-}
@@ -1,632 +0,0 @@
-/**
- * CLI helper: find an element in source and wrap it in a variant container.
- *
- * Usage:
- * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
- *
- * Searches project files for the element matching the query (class name, ID, or
- * text snippet), wraps it with the variant scaffolding, and prints the file path
- * + line range where the agent should insert variant HTML.
- *
- * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-export async function wrapCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable wrap [options]
-
-Find an element in source and wrap it in a variant container.
-
-Required:
- --id ID Session ID for the variant wrapper
- --count N Number of expected variants (1-8)
-
-Element identification (at least one required):
- --element-id ID HTML id attribute of the element
- --classes A,B,C Comma-separated CSS class names
- --tag TAG Tag name (div, section, etc.)
- --query TEXT Fallback: raw text to search for
-
-Optional:
- --file PATH Source file to search in (skips auto-detection)
- --text TEXT Picked element's textContent. Used to disambiguate when
- classes/tag match multiple sibling elements (e.g. a list
- of <Card>s with the same className). Pass the first ~80
- chars of event.element.textContent.
- --help Show this help message
-
-Output (JSON):
- { file, startLine, endLine, insertLine, commentSyntax }
-
-The agent should insert variant HTML at insertLine.`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const count = parseInt(argVal(args, '--count') || '3');
- const elementId = argVal(args, '--element-id');
- const classes = argVal(args, '--classes');
- const tag = argVal(args, '--tag');
- const query = argVal(args, '--query');
- const filePath = argVal(args, '--file');
- const text = argVal(args, '--text');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!elementId && !classes && !query) {
- console.error('Need at least one of: --element-id, --classes, --query');
- process.exit(1);
- }
-
- // Build search queries in priority order (most specific first)
- const queries = buildSearchQueries(elementId, classes, tag, query);
-
- const genOpts = { cwd: process.cwd() };
-
- // Find the source file. Generated files are excluded from auto-search so we
- // don't silently write variants into a file the next build will wipe.
- let targetFile = filePath;
- let matchedQuery = null;
- if (!targetFile) {
- for (const q of queries) {
- targetFile = findFileWithQuery(q, process.cwd(), genOpts);
- if (targetFile) { matchedQuery = q; break; }
- }
- if (!targetFile) {
- // Nothing in source. Did the element show up in a generated file? That
- // tells the agent "fall back to the agent-driven flow" vs "element just
- // doesn't exist in this project."
- let generatedHit = null;
- for (const q of queries) {
- generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
- if (generatedHit) break;
- }
- if (generatedHit) {
- console.error(JSON.stringify({
- error: 'element_not_in_source',
- fallback: 'agent-driven',
- generatedMatch: path.relative(process.cwd(), generatedHit),
- hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
- }));
- } else {
- console.error(JSON.stringify({
- error: 'element_not_found',
- fallback: 'agent-driven',
- hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
- }));
- }
- process.exit(1);
- }
- } else {
- if (isGeneratedFile(targetFile, genOpts)) {
- console.error(JSON.stringify({
- error: 'file_is_generated',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
- hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- matchedQuery = queries[0];
- }
-
- const content = fs.readFileSync(targetFile, 'utf-8');
- const lines = content.split('\n');
-
- // Find the element, trying each query in priority order. When `--text` is
- // supplied, collect every candidate the queries surface and disambiguate
- // by the picked element's textContent. Without `--text`, fall back to the
- // legacy first-match behavior so unmodified callers keep working.
- let match = null;
- if (text) {
- const candidates = [];
- for (const q of queries) {
- const all = findAllElements(lines, q, tag);
- for (const c of all) {
- if (!candidates.some((x) => x.startLine === c.startLine)) {
- candidates.push(c);
- }
- }
- // Once a more-specific query (ID, full className combo) yielded a unique
- // result, stop — falling through to the loose tag+single-class query
- // would readmit the siblings we just disambiguated past.
- if (candidates.length === 1) break;
- }
- if (candidates.length === 0) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- if (candidates.length === 1) {
- match = candidates[0];
- } else {
- const filtered = filterByText(candidates, lines, text);
- if (filtered.length === 1) {
- match = filtered[0];
- } else if (filtered.length === 0) {
- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the
- // browser-side textContent doesn't appear literally in source. Fall
- // back to first-match rather than refusing — this is the same
- // behavior unmodified callers see, just preserved.
- match = candidates[0];
- } else {
- // Multiple candidates ALSO match the text. Truly ambiguous — refuse
- // rather than pick wrong, and hand the agent the candidate locations
- // so it can disambiguate by reading the file.
- console.error(JSON.stringify({
- error: 'element_ambiguous',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), targetFile),
- candidates: filtered.map((c) => ({
- startLine: c.startLine + 1,
- endLine: c.endLine + 1,
- })),
- hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- }
- } else {
- for (const q of queries) {
- match = findElement(lines, q, tag);
- if (match) break;
- }
- if (!match) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- }
-
- const { startLine, endLine } = match;
- const commentSyntax = detectCommentSyntax(targetFile);
- const styleMode = detectStyleMode(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- const indent = lines[startLine].match(/^(\s*)/)[1];
-
- // Extract the original element. Reindent under the wrapper while preserving
- // the relative depth between lines — `l.trimStart()` would strip ALL leading
- // whitespace and collapse e.g. `<aside>`/` <h1>`/`</aside>` (6/8/6 spaces)
- // to a single uniform indent, so on accept/discard the round-trip restores
- // the inner element at its parent's depth instead of nested inside it.
- // Strip only the COMMON minimum leading whitespace across the picked lines;
- // `deindentContent` on the accept side already mirrors this convention.
- const originalLines = lines.slice(startLine, endLine + 1);
- const originalBaseIndent = minLeadingSpaces(originalLines);
- const reindentOriginal = (extra) => originalLines
- .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
- .join('\n');
- const originalIndented = reindentOriginal(' ');
-
- // Wrapper attributes differ by syntax. HTML allows plain string attrs;
- // JSX requires object-literal style and parses string attrs as HTML (which
- // either type-errors or renders a literal CSS string).
- const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
-
- // JSX/TSX guard: the picked element occupies a single JSX child slot
- // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
- // any other expression position). Replacing it with `comment + <div> +
- // comment` yields three adjacent siblings — invalid JSX. We can't use a
- // Fragment `<></>` either: parents that clone children (Radix `asChild`,
- // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
- // they try to pass an `id` through.
- //
- // Solution: keep the wrapper `<div>` as the single JSX-slot child and
- // tuck both marker comments INSIDE it. accept/discard then expands its
- // replacement range to include the wrapper's `<div>` open / close lines
- // so the entire scaffold gets removed cleanly.
- const wrapperLines = isJsx ? [
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- reindentOriginal(' '),
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- indent + '</div>',
- ] : [
- indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- originalIndented,
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + '</div>',
- indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- ];
-
- // Replace the original element with the wrapper
- const newLines = [
- ...lines.slice(0, startLine),
- ...wrapperLines,
- ...lines.slice(endLine + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- // Calculate insert line (the "insert below this line" comment).
- // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
- // the insert marker (HTML: start-comment + outer-div + Original-comment +
- // original-div + content + close-original-div; JSX: outer-div +
- // start-comment + Original-comment + original-div + content +
- // close-original-div). Multi-line originals push the marker by their
- // extra line count.
- const insertLine = startLine + 6 + (originalLines.length - 1);
-
- console.log(JSON.stringify({
- file: path.relative(process.cwd(), targetFile),
- startLine: startLine + 1, // 1-indexed for the agent
- // wrapperLines is an array but one element (the original-content slot)
- // is a `\n`-joined multi-line string, so the actual file-row count is
- // wrapperLines.length + (originalLines.length - 1). Without the offset,
- // endLine pointed inside the wrapper for any picked element that
- // spanned more than one source line.
- endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexed
- insertLine: insertLine + 1, // 1-indexed: where variants go
- commentSyntax: commentSyntax,
- styleMode: styleMode.mode,
- styleTag: styleMode.styleTag,
- cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
- cssAuthoring: buildCssAuthoring(styleMode, count),
- originalLineCount: originalLines.length,
- }));
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-/**
- * Build search query strings in priority order (most specific first).
- * ID is most reliable, then specific class combos, then single classes, then raw query.
- */
-function buildSearchQueries(elementId, classes, tag, query) {
- const queries = [];
-
- // 1. ID is the most specific
- if (elementId) {
- queries.push('id="' + elementId + '"');
- }
-
- // 2. Full class attribute match (for elements with distinctive multi-class combos).
- // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
- // convention the file uses will match.
- if (classes) {
- const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
- if (classList.length > 1) {
- const joined = classList.join(' ');
- const sorted = [...classList].sort((a, b) => b.length - a.length);
- queries.push('class="' + joined + '"');
- queries.push('className="' + joined + '"');
- queries.push(sorted[0]); // most distinctive single class, fallback
- } else if (classList.length === 1) {
- queries.push(classList[0]);
- }
- }
-
- // 3. Tag + class combo (e.g., <section class="hero">).
- // Same dual-emit for JSX compatibility.
- if (tag && classes) {
- const firstClass = classes.split(',')[0].trim();
- queries.push('<' + tag + ' class="' + firstClass);
- queries.push('<' + tag + ' className="' + firstClass);
- }
-
- // 4. Raw fallback query
- if (query) {
- queries.push(query);
- }
-
- return queries;
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- // HTML, Vue, Svelte, Astro all use HTML comments
- return { open: '<!--', close: '-->' };
-}
-
-function detectStyleMode(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.astro') {
- return {
- mode: 'astro-global-prefixed',
- styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',
- };
- }
- return {
- mode: 'scoped',
- styleTag: '<style data-impeccable-css="SESSION_ID">',
- };
-}
-
-function buildCssSelectorPrefixExamples(styleMode, count) {
- if (styleMode !== 'astro-global-prefixed') return [];
- return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);
-}
-
-function buildCssAuthoring(styleMode, count) {
- const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
- if (styleMode.mode === 'astro-global-prefixed') {
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'global-prefixed',
- rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',
- selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),
- requirements: [
- 'Use the styleTag exactly; the is:inline attribute is required for this file.',
- 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',
- 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
- ],
- forbidden: [
- 'Do not use @scope for this styleMode.',
- ],
- };
- }
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'scope-rule',
- rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',
- selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),
- requirements: [
- 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',
- 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
- 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
- ],
- forbidden: [
- 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',
- 'Do not add is:inline to the style tag for this styleMode.',
- ],
- };
-}
-
-/**
- * Search project files for the query string (class name, ID, etc.)
- * Returns the first matching file path, or null.
- */
-function findFileWithQuery(query, cwd, genOpts = {}) {
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, query, seen, 0, genOpts);
- if (result) return result;
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth, genOpts) {
- if (depth > 5) return null; // don't go too deep
- const realDir = fs.realpathSync(dir);
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- // Check files first
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name).toLowerCase();
- if (!EXTENSIONS.includes(ext)) continue;
-
- const filePath = path.join(dir, entry.name);
- if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip unreadable files */ }
- }
-
- // Then recurse into directories. Always skip node_modules and .git (never
- // project content). dist/build/out are left to the isGeneratedFile guard so
- // the includeGenerated second-pass can still find the element there and
- // report `generatedMatch`.
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
- if (result) return result;
- }
-
- return null;
-}
-
-/**
- * Regex that matches a tag opener on a line. Allows the tag name to be
- * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
- * openers (e.g. `<section\n className="..."\n>`) are recognised.
- */
-const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
-
-/**
- * Find the element's start and end line in the file.
- *
- * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
- * `id="..."`), or a raw text snippet. Because a query can appear on a
- * continuation line of a multi-line tag (e.g. the `className="..."` row of a
- * `<section\n className="..."\n>` JSX tag), we walk backward from the match
- * line to find the actual tag opener. When `tag` is provided, opener candidates
- * must match that tag name.
- */
-/**
- * Return the smallest leading-whitespace count across a set of lines,
- * ignoring blank lines (whose indent isn't load-bearing). Used to compute
- * the common base indent of a multi-line picked element so reindenting
- * under the wrapper preserves the relative depth between lines.
- */
-function minLeadingSpaces(lines) {
- let min = Infinity;
- for (const l of lines) {
- if (l.trim() === '') continue;
- const m = l.match(/^(\s*)/);
- if (m && m[1].length < min) min = m[1].length;
- }
- return min === Infinity ? 0 : min;
-}
-
-function findElement(lines, query, tag = null) {
- // Iterate all matches — the first substring hit isn't always the right one.
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
-
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- // Skip lines already inside a variant wrapper
- if (lines[i].includes('data-impeccable-variant')) continue;
-
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
-
- const endLine = findClosingLine(lines, openerLine);
- return { startLine: openerLine, endLine };
- }
-
- return null;
-}
-
-/**
- * Like findElement, but returns every match. Used for ambiguity detection
- * when the agent passes --text: when the same className appears on multiple
- * sibling elements (a list of cards, repeated section variants, etc.),
- * first-match silently lands on the wrong branch. Returning all matches lets
- * the caller narrow by textContent or fail with a structured ambiguity error.
- */
-function findAllElements(lines, query, tag = null) {
- const out = [];
- const seen = new Set();
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- if (lines[i].includes('data-impeccable-variant')) continue;
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
- if (seen.has(openerLine)) continue; // multiple matches inside the same element
- seen.add(openerLine);
- const endLine = findClosingLine(lines, openerLine);
- out.push({ startLine: openerLine, endLine });
- }
- return out;
-}
-
-/**
- * Narrow a candidate set to those whose source body matches a meaningful
- * prefix of the picked element's textContent. The compare strips tags and
- * JSX expressions, then checks two whitespace normalizations side-by-side:
- *
- * - single-space ("hero two second card body")
- * - no-whitespace ("herotwosecondcardbody")
- *
- * Both are needed because `el.textContent` concatenates sibling text without
- * inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
- * `"Hero TwoSecond…"`), while the source has whitespace between tags. If
- * EITHER normalization matches, the candidate keeps. A snippet shorter than
- * 8 chars after stripping is too weak to disambiguate — the caller falls
- * back to first-match.
- */
-function filterByText(candidates, lines, text) {
- const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
- // Too short to disambiguate. Return [] so the caller's `filtered.length
- // === 0` branch fires (fall back to first-match) — the previous
- // `candidates.slice()` return forced `filtered.length > 1` and surfaced
- // a spurious `element_ambiguous` error on every short-text picker event
- // with multiple candidates.
- if (trimmed.length < 8) return [];
- const targetSpaced = trimmed;
- const targetCompact = trimmed.replace(/\s+/g, '');
-
- return candidates.filter((c) => {
- const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
- const inner = body
- .replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
- .replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
- .toLowerCase();
- const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
- const sourceCompact = inner.replace(/\s+/g, '');
- return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
- });
-}
-
-/**
- * Resolve a match line to the real tag opener. If the match line itself opens
- * a tag, return it. Otherwise walk up to 10 lines backward looking for the
- * first tag opener. If `tag` is specified, the opener must match that tag
- * name; an opener with a different tag name aborts the backward walk for this
- * match (we don't jump across element boundaries).
- *
- * Returns the line index of the opener, or -1 if none can be resolved.
- */
-function findOpenerLine(lines, matchLine, tag) {
- const self = lines[matchLine].match(OPENER_RE);
- if (self) {
- if (!tag || self[1] === tag) return matchLine;
- return -1;
- }
- const MAX_BACKWALK = 10;
- for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
- const opener = lines[i].match(OPENER_RE);
- if (!opener) continue;
- if (!tag || opener[1] === tag) return i;
- // Different tag name than requested — abort; we're inside a non-target opener.
- return -1;
- }
- return -1;
-}
-
-/**
- * Starting from a line with an opening tag, find the line with the matching
- * closing tag by counting tag nesting depth.
- */
-function findClosingLine(lines, start) {
- const openMatch = lines[start].match(OPENER_RE);
- if (!openMatch) return start; // caller passed a non-opener; nothing to span
-
- const tagName = openMatch[1];
- let depth = 0;
- const openRe = new RegExp('<' + tagName + '(?=[\\s/>]|$)', 'g');
- const selfCloseRe = new RegExp('<' + tagName + '[^>]*/>', 'g');
- const closeRe = new RegExp('</' + tagName + '\\s*>', 'g');
-
- for (let i = start; i < lines.length; i++) {
- const line = lines[i];
- const opens = (line.match(openRe) || []).length;
- const selfCloses = (line.match(selfCloseRe) || []).length;
- const closes = (line.match(closeRe) || []).length;
-
- depth += opens - selfCloses - closes;
-
- if (depth <= 0) return i;
- }
-
- // If we can't find the close, return a reasonable guess
- return Math.min(start + 50, lines.length - 1);
-}
-
-// Auto-execute when run directly (node live-wrap.mjs ...)
-const _running = process.argv[1];
-if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {
- wrapCli();
-}
-
-// Test exports (used by tests/live-wrap.test.mjs)
-export { buildSearchQueries, findElement, findClosingLine, detectCommentSyntax };
@@ -1,247 +0,0 @@
-/**
- * CLI entry point: prepare everything needed to enter the live variant poll loop.
- *
- * Does (all in one command):
- * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)
- * 2. Start the live server in the background (or reuse a running one)
- * 3. Inject the browser script tag into the project's entry file
- * 4. Read PRODUCT.md / DESIGN.md for project context
- * 5. Print a single JSON blob with everything the agent needs
- *
- * After this, the agent's only remaining steps are:
- * - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll
- * - Enter the poll loop: `node live-poll.mjs`
- *
- * Usage:
- * node live.mjs # Prepare everything, print JSON, exit
- * node live.mjs --help
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { loadContext } from './load-context.mjs';
-import { resolveFiles } from './live-inject.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-async function liveCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live.mjs
-
-Prepare everything for live variant mode in a single command:
- - Checks .impeccable/live/config.json (required, created once per project)
- - Starts (or reuses) the live server in the background
- - Injects the browser script tag
- - Reads PRODUCT.md / DESIGN.md for project context
-
-On success, prints a JSON blob with:
- { ok, serverPort, serverToken, pageFile, hasContext, context }
-
-On config_missing, prints:
- { ok: false, error: "config_missing", configPath, hint }
-
-The agent should then:
- 1. If config_missing, create the config and re-run this script
- 2. Optionally open the project's dev/preview URL in the browser (see reference/live.md—not serverPort)
- 3. Enter the poll loop: node live-poll.mjs`);
- process.exit(0);
- }
-
- // 1. Check config (fail fast if missing — no point starting anything else)
- const checkOut = runScript('live-inject.mjs', ['--check']);
- const checkResult = safeParse(checkOut);
- if (!checkResult || !checkResult.ok) {
- console.log(JSON.stringify(checkResult || { ok: false, error: 'check_failed', raw: checkOut }));
- process.exit(0);
- }
-
- // 2. Start server (or reuse existing)
- const serverInfo = ensureServerRunning();
- if (!serverInfo) {
- console.log(JSON.stringify({ ok: false, error: 'server_start_failed' }));
- process.exit(1);
- }
-
- // 3. Inject the script tag at the current port
- const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)]);
- const injectResult = safeParse(injectOut);
- if (!injectResult || !injectResult.ok) {
- console.log(JSON.stringify({
- ok: false,
- error: 'inject_failed',
- detail: injectResult || injectOut,
- serverPort: serverInfo.port,
- }));
- process.exit(1);
- }
-
- // 4. Load PRODUCT.md + DESIGN.md context (auto-migrates legacy .impeccable.md)
- const ctx = loadContext(process.cwd());
-
- // 5. Compute drift-heal: compare resolved inject targets against the
- // project's HTML files. Orphans are HTML files not covered by config.
- // Warning only — the agent decides whether to act.
- const resolvedFiles = resolveFiles(process.cwd(), checkResult.config);
- const drift = scanForDrift(process.cwd(), resolvedFiles, checkResult.config);
-
- // 6. Emit everything the agent needs
- console.log(JSON.stringify({
- ok: true,
- serverPort: serverInfo.port,
- serverToken: serverInfo.token,
- pageFiles: resolvedFiles,
- configDrift: drift,
- hasProduct: ctx.hasProduct,
- product: ctx.product,
- productPath: ctx.productPath,
- hasDesign: ctx.hasDesign,
- design: ctx.design,
- designPath: ctx.designPath,
- migrated: ctx.migrated,
- }, null, 2));
-}
-
-/**
- * Drift-heal scan. Walks the project for HTML files under common
- * page-source directories (public/, src/, app/, pages/) and reports any
- * that aren't covered by the resolved inject targets. This is purely
- * advisory — the agent can ignore it, or suggest the user add the
- * orphans to config.files.
- *
- * Skipped if config.files already contains at least one glob pattern
- * covering everything in practice (signaled by the orphan count being 0).
- */
-function scanForDrift(rootDir, resolvedFiles, config) {
- const SCAN_ROOTS = ['public', 'src', 'app', 'pages'];
- const IGNORE_DIRS = new Set([
- 'node_modules', '.git', '.next', '.nuxt', '.svelte-kit', '.astro',
- '.turbo', '.vercel', '.cache', 'coverage', 'dist', 'build',
- ]);
-
- const resolvedSet = new Set(resolvedFiles.map((f) => f.split(path.sep).join('/')));
-
- // Files matching the user's `exclude` globs are intentional omissions,
- // not drift. Compile them to regexes so the orphan list stays signal.
- const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
- .map((p) => globToRegex(p));
- const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
-
- const orphans = [];
-
- const walk = (dir, relBase) => {
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
- for (const e of entries) {
- const rel = relBase ? `${relBase}/${e.name}` : e.name;
- if (e.isDirectory()) {
- if (IGNORE_DIRS.has(e.name) || e.name.startsWith('.')) continue;
- walk(path.join(dir, e.name), rel);
- } else if (e.isFile() && e.name.endsWith('.html')) {
- if (resolvedSet.has(rel)) continue;
- if (isUserExcluded(rel)) continue;
- orphans.push(rel);
- }
- }
- };
-
- for (const root of SCAN_ROOTS) {
- const abs = path.join(rootDir, root);
- if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
- walk(abs, root);
- }
- }
-
- if (orphans.length === 0) return null;
- const capped = orphans.slice(0, 20);
- return {
- orphans: capped,
- orphanCount: orphans.length,
- hint: `${orphans.length} HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like "public/**/*.html".`,
- };
-}
-
-/**
- * Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
- * to avoid a circular import (live-inject.mjs already imports nothing
- * from live.mjs). The two must stay in sync.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
- else { re += '.*'; i += 2; }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function runScript(name, args) {
- const scriptPath = path.join(__dirname, name);
- const cmd = `node "${scriptPath}" ${args.map(a => `"${a}"`).join(' ')}`;
- try {
- return execSync(cmd, { encoding: 'utf-8', cwd: process.cwd(), timeout: 15_000 });
- } catch (err) {
- // execSync throws on non-zero exit; return stdout if any
- return err.stdout || err.message || '';
- }
-}
-
-function safeParse(out) {
- try { return JSON.parse(String(out).trim()); } catch { return null; }
-}
-
-/**
- * Return { pid, port, token } for the running live server, starting one if needed.
- */
-function ensureServerRunning() {
- // Try to reuse an existing server
- try {
- const existing = readLiveServerInfo(process.cwd())?.info;
- if (existing && existing.pid) {
- try {
- process.kill(existing.pid, 0); // throws if dead
- return existing;
- } catch { /* stale PID file — the server script will clean it up */ }
- }
- } catch { /* no PID file */ }
-
- // Start a new server
- const out = runScript('live-server.mjs', ['--background']);
- return safeParse(out);
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live.mjs') || _running?.endsWith('live.mjs/')) {
- liveCli();
-}
@@ -1,141 +0,0 @@
-/**
- * Shared context loader for every impeccable command that needs to know
- * "who is this for" and "what does this look like".
- *
- * Input: project root (process.cwd()).
- *
- * Output (JSON to stdout):
- * {
- * hasProduct: boolean, // PRODUCT.md found (or auto-migrated)
- * product: string | null, // PRODUCT.md contents
- * productPath: string | null, // relative path
- * hasDesign: boolean, // DESIGN.md found
- * design: string | null, // DESIGN.md contents
- * designPath: string | null,
- * migrated: boolean, // true if we auto-renamed .impeccable.md -> PRODUCT.md
- * contextDir: string, // absolute path of the directory the files were found in
- * }
- *
- * Filename matching is case-insensitive for PRODUCT.md and DESIGN.md. The
- * Google DESIGN.md convention is uppercase at repo root; Kiro-style and
- * lowercase variants are also matched so users don't get punished for case.
- *
- * Lookup directory resolution (first match wins):
- * 1. process.env.IMPECCABLE_CONTEXT_DIR (absolute or relative to cwd)
- * 2. cwd, if PRODUCT.md / DESIGN.md / .impeccable.md is there (back-compat)
- * 3. Auto-fallback subdirectories of cwd: .agents/context/, then docs/
- * 4. cwd as a default "no context found" location
- *
- * Legacy `.impeccable.md` -> PRODUCT.md migration only fires at cwd root;
- * fallback directories are read-only as far as auto-rename is concerned.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
-const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
-const LEGACY_NAMES = ['.impeccable.md'];
-const FALLBACK_DIRS = ['.agents/context', 'docs'];
-
-/**
- * Resolve the directory that holds PRODUCT.md / DESIGN.md for
- * this project. Exported so other scripts (e.g. live-server.mjs) can read the
- * design files from the same location the loader uses.
- */
-export function resolveContextDir(cwd = process.cwd()) {
- // 1. Explicit override
- const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
- if (envDir && envDir.trim()) {
- const trimmed = envDir.trim();
- return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- }
-
- // 2. cwd wins if any canonical or legacy file is there. We check legacy too
- // so the auto-migration path in loadContext stays predictable.
- if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES, ...LEGACY_NAMES])) {
- return cwd;
- }
-
- // 3. Auto-fallback subdirs. Match if PRODUCT.md or DESIGN.md is present;
- // legacy `.impeccable.md` does not pull the lookup into a fallback dir.
- for (const rel of FALLBACK_DIRS) {
- const candidate = path.resolve(cwd, rel);
- if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
- return candidate;
- }
- }
-
- // 4. Nothing found — keep the historical "default to cwd" behaviour so the
- // caller's `hasProduct === false` branch still fires the same way.
- return cwd;
-}
-
-export function loadContext(cwd = process.cwd()) {
- let migrated = false;
- const contextDir = resolveContextDir(cwd);
-
- // 1. Look for PRODUCT.md (case-insensitive) in the resolved dir
- let productPath = firstExisting(contextDir, PRODUCT_NAMES);
-
- // 2. Legacy: if no PRODUCT.md but .impeccable.md exists at cwd root, rename
- // it in place. We only migrate at the root — fallback dirs are read-only
- // so we don't surprise users by mutating files under docs/ or .agents/.
- if (!productPath && contextDir === cwd) {
- const legacyPath = firstExisting(cwd, LEGACY_NAMES);
- if (legacyPath) {
- const newPath = path.join(cwd, 'PRODUCT.md');
- try {
- fs.renameSync(legacyPath, newPath);
- productPath = newPath;
- migrated = true;
- } catch {
- // Rename failed (permissions, etc.) — fall back to reading legacy in place
- productPath = legacyPath;
- }
- }
- }
-
- // 3. DESIGN.md (case-insensitive)
- const designPath = firstExisting(contextDir, DESIGN_NAMES);
-
- const product = productPath ? safeRead(productPath) : null;
- const design = designPath ? safeRead(designPath) : null;
-
- return {
- hasProduct: !!product,
- product,
- productPath: productPath ? path.relative(cwd, productPath) : null,
- hasDesign: !!design,
- design,
- designPath: designPath ? path.relative(cwd, designPath) : null,
- migrated,
- contextDir,
- };
-}
-
-function firstExisting(dir, names) {
- for (const name of names) {
- const abs = path.join(dir, name);
- if (fs.existsSync(abs)) return abs;
- }
- return null;
-}
-
-function safeRead(p) {
- try { return fs.readFileSync(p, 'utf-8'); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// CLI mode — print the context as JSON
-// ---------------------------------------------------------------------------
-
-function cli() {
- const result = loadContext(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('load-context.mjs') || _running?.endsWith('load-context.mjs/')) {
- cli();
-}
@@ -1,14 +0,0 @@
@@ -1,214 +0,0 @@
-#!/usr/bin/env node
-/**
- * Pin/unpin sub-commands as standalone skill shortcuts.
- *
- * Usage:
- * node <scripts_path>/pin.mjs pin <command>
- * node <scripts_path>/pin.mjs unpin <command>
- *
- * `pin audit` creates a lightweight /audit skill that redirects to /impeccable audit.
- * `unpin audit` removes that shortcut.
- *
- * The script discovers harness directories (.claude/skills, .cursor/skills, etc.)
- * in the project root and creates/removes the pin in all of them.
- */
-
-import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
-import { join, resolve, dirname } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-// All known harness directories
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Valid sub-command names
-const VALID_COMMANDS = [
- 'craft', 'teach', 'extract', 'document', 'shape',
- 'critique', 'audit',
- 'polish', 'bolder', 'quieter', 'distill', 'harden', 'onboard', 'live',
- 'animate', 'colorize', 'typeset', 'layout', 'delight', 'overdrive',
- 'clarify', 'adapt', 'optimize',
-];
-
-// Marker to identify pinned skills (so unpin doesn't delete user skills)
-const PIN_MARKER = '<!-- impeccable-pinned-skill -->';
-
-/**
- * Walk up from startDir to find a project root.
- */
-function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- while (dir !== '/') {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Find harness skill directories that have an impeccable skill installed.
- */
-function findHarnessDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const skillsDir = join(projectRoot, harness, 'skills');
- // Only pin in harness dirs that already have impeccable installed
- const impeccableDir = join(skillsDir, 'impeccable');
- if (existsSync(impeccableDir) || existsSync(join(skillsDir, 'i-impeccable'))) {
- dirs.push(skillsDir);
- }
- }
- return dirs;
-}
-
-/**
- * Load command metadata (descriptions for pinned skills).
- */
-function loadCommandMetadata() {
- const metadataPath = join(__dirname, 'command-metadata.json');
- if (existsSync(metadataPath)) {
- return JSON.parse(readFileSync(metadataPath, 'utf-8'));
- }
- return {};
-}
-
-/**
- * Generate a pinned skill's SKILL.md content.
- */
-function generatePinnedSkill(command, metadata) {
- const desc = metadata[command]?.description || `Shortcut for /impeccable ${command}.`;
- const hint = metadata[command]?.argumentHint || '[target]';
-
- return `---
-name: ${command}
-description: "${desc}"
-argument-hint: "${hint}"
-user-invocable: true
----
-
-${PIN_MARKER}
-
-This is a pinned shortcut for \`{{command_prefix}}impeccable ${command}\`.
-
-Invoke {{command_prefix}}impeccable ${command}, passing along any arguments provided here, and follow its instructions.
-`;
-}
-
-/**
- * Pin a command: create shortcut skill in all harness dirs.
- */
-function pin(command, projectRoot) {
- const metadata = loadCommandMetadata();
- const harnessDirs = findHarnessDirs(projectRoot);
-
- if (harnessDirs.length === 0) {
- console.log('No harness directories with impeccable installed found.');
- return false;
- }
-
- const content = generatePinnedSkill(command, metadata);
- let created = 0;
-
- for (const skillsDir of harnessDirs) {
- // Check if skill already exists (and isn't a pin)
- const skillDir = join(skillsDir, command);
- if (existsSync(skillDir)) {
- const existingMd = join(skillDir, 'SKILL.md');
- if (existsSync(existingMd)) {
- const existing = readFileSync(existingMd, 'utf-8');
- if (!existing.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (non-pinned skill already exists)`);
- continue;
- }
- }
- }
-
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(join(skillDir, 'SKILL.md'), content, 'utf-8');
- console.log(` + ${skillDir}`);
- created++;
- }
-
- if (created > 0) {
- console.log(`\nPinned '${command}' as a standalone shortcut in ${created} location(s).`);
- console.log(`You can now use /${command} directly.`);
- }
-
- return created > 0;
-}
-
-/**
- * Unpin a command: remove shortcut skill from all harness dirs.
- */
-function unpin(command, projectRoot) {
- const harnessDirs = findHarnessDirs(projectRoot);
- let removed = 0;
-
- for (const skillsDir of harnessDirs) {
- const skillDir = join(skillsDir, command);
- if (!existsSync(skillDir)) continue;
-
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) continue;
-
- // Safety: only remove if it's a pinned skill
- const content = readFileSync(skillMd, 'utf-8');
- if (!content.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (not a pinned skill)`);
- continue;
- }
-
- rmSync(skillDir, { recursive: true, force: true });
- console.log(` - ${skillDir}`);
- removed++;
- }
-
- if (removed > 0) {
- console.log(`\nUnpinned '${command}' from ${removed} location(s).`);
- console.log(`Use /impeccable ${command} to access it.`);
- } else {
- console.log(`No pinned '${command}' shortcut found.`);
- }
-
- return removed > 0;
-}
-
-// --- CLI ---
-const [,, action, command] = process.argv;
-
-if (!action || !command) {
- console.log('Usage: node pin.mjs <pin|unpin> <command>');
- console.log(`\nAvailable commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-if (action !== 'pin' && action !== 'unpin') {
- console.error(`Unknown action: ${action}. Use 'pin' or 'unpin'.`);
- process.exit(1);
-}
-
-if (!VALID_COMMANDS.includes(command)) {
- console.error(`Unknown command: ${command}`);
- console.error(`Available commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-const root = findProjectRoot();
-
-if (action === 'pin') {
- pin(command, root);
-} else {
- unpin(command, root);
-}
@@ -1,164 +0,0 @@
----
-name: impeccable
-description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
-version: 3.1.1
----
-
-Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
-
-## Setup
-
-Before any design work or file edits:
-
-1. Load context (PRODUCT.md / DESIGN.md) via the loader script.
-2. Identify the register and load the matching register reference (brand.md or product.md).
-3. **If the user invoked a sub-command (e.g. `craft`, `shape`, `audit`), load its reference file too.** This is non-negotiable: `craft` without `craft.md` loaded means you'll skip the shape-and-confirm step the user expects.
-
-Skipping these produces generic output that ignores the project.
-
-### 1. Context gathering
-
-Two files, case-insensitive. The loader looks at the project root by default and falls back to `.agents/context/` and `docs/` if the root is clean. Override with `IMPECCABLE_CONTEXT_DIR=path/to/dir` (absolute or relative to cwd).
-
-- **PRODUCT.md**: required. Users, brand, tone, anti-references, strategic principles.
-- **DESIGN.md**: optional, strongly recommended. Colors, typography, elevation, components.
-
-Load both in one call:
-
-```bash
-node .gemini/skills/impeccable/scripts/load-context.mjs
-```
-
-Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`. The output's `contextDir` field tells you where the files were resolved from.
-
-If the output is already in this session's conversation history, don't re-run. Exceptions requiring a fresh load: you just ran `/impeccable teach` or `/impeccable document` (they rewrite the files), or the user manually edited one.
-
-`/impeccable live` already warms context via `live.mjs`. If you've run `live.mjs`, don't also run `load-context.mjs` this session.
-
-If PRODUCT.md is missing, empty, or placeholder (`[TODO]` markers, <200 chars): run `/impeccable teach`, then resume the user's original task with the fresh context. If the original task was `/impeccable craft`, resume into `/impeccable shape` before any implementation work.
-
-If DESIGN.md is missing: nudge once per session (*"Run `/impeccable document` for more on-brand output"*), then proceed.
-
-### 2. Register
-
-Every design task is **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboard, tool: design SERVES the product).
-
-Identify before designing. Priority: (1) cue in the task itself ("landing page" vs "dashboard"); (2) the surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. First match wins.
-
-If PRODUCT.md lacks the `register` field (legacy), infer it once from its "Users" and "Product Purpose" sections, then cache the inferred value for the session. Suggest the user run `/impeccable teach` to add the field explicitly.
-
-Load the matching reference: [reference/brand.md](reference/brand.md) or [reference/product.md](reference/product.md). The shared design laws below apply to both.
-
-## Shared design laws
-
-Apply to every design, both registers. Match implementation complexity to the aesthetic vision: maximalism needs elaborate code, minimalism needs precision. Interpret creatively. Vary across projects; never converge on the same choices. Gemini is capable of extraordinary work. Don't hold back.
-
-### Color
-
-- Use OKLCH. Reduce chroma as lightness approaches 0 or 100; high chroma at extremes looks garish.
-- Never use `#000` or `#fff`. Tint every neutral toward the brand hue (chroma 0.005–0.01 is enough).
-- Pick a **color strategy** before picking colors. Four steps on the commitment axis:
- - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism.
- - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages.
- - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz.
- - **Drenched**: the surface IS the color. Brand heroes, campaign pages.
-- The "one accent ≤10%" rule is Restrained only. Committed / Full palette / Drenched exceed it on purpose. Don't collapse every design to Restrained by reflex.
-
-### Theme
-
-Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe."
-
-Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does.
-
-"Observability dashboard" does not force an answer. "SRE glancing at incident severity on a 27-inch monitor at 2am in a dim room" does. Run the sentence, not the category.
-
-### Typography
-
-- Cap body line length at 65–75ch.
-- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales.
-
-### Layout
-
-- Vary spacing for rhythm. Same padding everywhere is monotony.
-- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
-- Don't wrap everything in a container. Most things don't need one.
-
-### Motion
-
-- Don't animate CSS layout properties.
-- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
-
-### Absolute bans
-
-Match-and-refuse. If you're about to write any of these, rewrite the element with different structure.
-
-- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing.
-- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size.
-- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing.
-- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché.
-- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly.
-- **Modal as first thought.** Modals are usually laziness. Exhaust inline / progressive alternatives first.
-
-### Copy
-
-- Every word earns its place. No restated headings, no intros that repeat the title.
-- **No em dashes.** Use commas, colons, semicolons, periods, or parentheses. Also not `--`.
-
-### The AI slop test
-
-If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference.
-
-**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses.
-
-- **First-order:** if someone could guess the theme + palette from the category alone ("observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black"), it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
-- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families.
-
-## Commands
-
-| Command | Category | Description | Reference |
-|---|---|---|---|
-| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) |
-| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) |
-| `teach` | Build | Set up PRODUCT.md and DESIGN.md context | [reference/teach.md](reference/teach.md) |
-| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) |
-| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) |
-| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) |
-| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) |
-| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) |
-| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) |
-| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) |
-| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) |
-| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) |
-| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) |
-| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) |
-| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) |
-| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) |
-| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) |
-| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) |
-| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) |
-| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) |
-| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) |
-| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
-| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
-
-### Routing rules
-
-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
-3. **First word doesn't match**: general design invocation. Apply the setup steps, shared design laws, and the loaded register reference, using the full argument as context.
-
-Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `/impeccable`.
-
-If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `teach` as a blocker, finish teach, refresh context, then resume the original command and target.
-
-## Pin / Unpin
-
-**Pin** creates a standalone shortcut so `/<command>` invokes `/impeccable <command>` directly. **Unpin** removes it. The script writes to every harness directory present in the project.
-
-```bash
-node .gemini/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
-```
-
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
@@ -1,190 +0,0 @@
-> **Additional context needed**: target platforms/devices and usage contexts.
-
-Adapt an existing design to a different context: another screen size, device, platform, or use case. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context.
-
-
----
-
-## Assess Adaptation Challenge
-
-Understand what needs adaptation and why:
-
-1. **Identify the source context**:
- - What was it designed for originally? (Desktop web? Mobile app?)
- - What assumptions were made? (Large screen? Mouse input? Fast connection?)
- - What works well in current context?
-
-2. **Understand target context**:
- - **Device**: Mobile, tablet, desktop, TV, watch, print?
- - **Input method**: Touch, mouse, keyboard, voice, gamepad?
- - **Screen constraints**: Size, resolution, orientation?
- - **Connection**: Fast wifi, slow 3G, offline?
- - **Usage context**: On-the-go vs desk, quick glance vs focused reading?
- - **User expectations**: What do users expect on this platform?
-
-3. **Identify adaptation challenges**:
- - What won't fit? (Content, navigation, features)
- - What won't work? (Hover states on touch, tiny touch targets)
- - What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop)
-
-**CRITICAL**: Adaptation is rethinking the experience for the new context, not scaling pixels.
-
-## Plan Adaptation Strategy
-
-Create context-appropriate strategy:
-
-### Mobile Adaptation (Desktop → Mobile)
-
-**Layout Strategy**:
-- Single column instead of multi-column
-- Vertical stacking instead of side-by-side
-- Full-width components instead of fixed widths
-- Bottom navigation instead of top/side navigation
-
-**Interaction Strategy**:
-- Touch targets 44x44px minimum (not hover-dependent)
-- Swipe gestures where appropriate (lists, carousels)
-- Bottom sheets instead of dropdowns
-- Thumbs-first design (controls within thumb reach)
-- Larger tap areas with more spacing
-
-**Content Strategy**:
-- Progressive disclosure (don't show everything at once)
-- Prioritize primary content (secondary content in tabs/accordions)
-- Shorter text (more concise)
-- Larger text (16px minimum)
-
-**Navigation Strategy**:
-- Hamburger menu or bottom navigation
-- Reduce navigation complexity
-- Sticky headers for context
-- Back button in navigation flow
-
-### Tablet Adaptation (Hybrid Approach)
-
-**Layout Strategy**:
-- Two-column layouts (not single or three-column)
-- Side panels for secondary content
-- Master-detail views (list + detail)
-- Adaptive based on orientation (portrait vs landscape)
-
-**Interaction Strategy**:
-- Support both touch and pointer
-- Touch targets 44x44px but allow denser layouts than phone
-- Side navigation drawers
-- Multi-column forms where appropriate
-
-### Desktop Adaptation (Mobile → Desktop)
-
-**Layout Strategy**:
-- Multi-column layouts (use horizontal space)
-- Side navigation always visible
-- Multiple information panels simultaneously
-- Fixed widths with max-width constraints (don't stretch to 4K)
-
-**Interaction Strategy**:
-- Hover states for additional information
-- Keyboard shortcuts
-- Right-click context menus
-- Drag and drop where helpful
-- Multi-select with Shift/Cmd
-
-**Content Strategy**:
-- Show more information upfront (less progressive disclosure)
-- Data tables with many columns
-- Richer visualizations
-- More detailed descriptions
-
-### Print Adaptation (Screen → Print)
-
-**Layout Strategy**:
-- Page breaks at logical points
-- Remove navigation, footer, interactive elements
-- Black and white (or limited color)
-- Proper margins for binding
-
-**Content Strategy**:
-- Expand shortened content (show full URLs, hidden sections)
-- Add page numbers, headers, footers
-- Include metadata (print date, page title)
-- Convert charts to print-friendly versions
-
-### Email Adaptation (Web → Email)
-
-**Layout Strategy**:
-- Narrow width (600px max)
-- Single column only
-- Inline CSS (no external stylesheets)
-- Table-based layouts (for email client compatibility)
-
-**Interaction Strategy**:
-- Large, obvious CTAs (buttons not text links)
-- No hover states (not reliable)
-- Deep links to web app for complex interactions
-
-## Implement Adaptations
-
-Apply changes systematically:
-
-### Responsive Breakpoints
-
-Choose appropriate breakpoints:
-- Mobile: 320px-767px
-- Tablet: 768px-1023px
-- Desktop: 1024px+
-- Or content-driven breakpoints (where design breaks)
-
-### Layout Adaptation Techniques
-
-- **CSS Grid/Flexbox**: Reflow layouts automatically
-- **Container Queries**: Adapt based on container, not viewport
-- **`clamp()`**: Fluid sizing between min and max
-- **Media queries**: Different styles for different contexts
-- **Display properties**: Show/hide elements per context
-
-### Touch Adaptation
-
-- Increase touch target sizes (44x44px minimum)
-- Add more spacing between interactive elements
-- Remove hover-dependent interactions
-- Add touch feedback (ripples, highlights)
-- Consider thumb zones (easier to reach bottom than top)
-
-### Content Adaptation
-
-- Use `display: none` sparingly (still downloads)
-- Progressive enhancement (core content first, enhancements on larger screens)
-- Lazy loading for off-screen content
-- Responsive images (`srcset`, `picture` element)
-
-### Navigation Adaptation
-
-- Transform complex nav to hamburger/drawer on mobile
-- Bottom nav bar for mobile apps
-- Persistent side navigation on desktop
-- Breadcrumbs on smaller screens for context
-
-**IMPORTANT**: Test on real devices. Device emulation in DevTools is helpful but not perfect.
-
-**NEVER**:
-- Hide core functionality on mobile (if it matters, make it work)
-- Assume desktop = powerful device (consider accessibility, older machines)
-- Use different information architecture across contexts (confusing)
-- Break user expectations for platform (mobile users expect mobile patterns)
-- Forget landscape orientation on mobile/tablet
-- Use generic breakpoints blindly (use content-driven breakpoints)
-- Ignore touch on desktop (many desktop devices have touch)
-
-## Verify Adaptations
-
-Test thoroughly across contexts:
-
-- **Real devices**: Test on actual phones, tablets, desktops
-- **Different orientations**: Portrait and landscape
-- **Different browsers**: Safari, Chrome, Firefox, Edge
-- **Different OS**: iOS, Android, Windows, macOS
-- **Different input methods**: Touch, mouse, keyboard
-- **Edge cases**: Very small screens (320px), very large screens (4K)
-- **Slow connections**: Test on throttled network
-
-When the adaptation feels native to each context, hand off to `/impeccable polish` for the final pass.
@@ -1,175 +0,0 @@
-> **Additional context needed**: performance constraints.
-
-Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it.
-
----
-
-## Register
-
-Brand: orchestrated page-load sequences, staggered reveals, scroll-driven animation. Motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions.
-
-Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it.
-
----
-
-## Assess Animation Opportunities
-
-Analyze where motion would improve the experience:
-
-1. **Identify static areas**:
- - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.)
- - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes)
- - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious
- - **Lack of delight**: Functional but joyless interactions
- - **Missed guidance**: Opportunities to direct attention or explain behavior
-
-2. **Understand the context**:
- - What's the personality? (Playful vs serious, energetic vs calm)
- - What's the performance budget? (Mobile-first? Complex page?)
- - Who's the audience? (Motion-sensitive users? Power users who want speed?)
- - What matters most? (One hero animation vs many micro-interactions?)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them.
-
-## Plan Animation Strategy
-
-Create a purposeful animation plan:
-
-- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?)
-- **Feedback layer**: Which interactions need acknowledgment?
-- **Transition layer**: Which state changes need smoothing?
-- **Delight layer**: Where can we surprise and delight?
-
-**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments.
-
-## Implement Animations
-
-Add motion systematically across these categories:
-
-### Entrance Animations
-- **Page load choreography**: Stagger element reveals (100-150ms delays), fade + slide combinations
-- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects)
-- **Content reveals**: Scroll-triggered animations using intersection observer
-- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management
-
-### Micro-interactions
-- **Button feedback**:
- - Hover: Subtle scale (1.02-1.05), color shift, shadow increase
- - Click: Quick scale down then up (0.95 → 1), ripple effect
- - Loading: Spinner or pulse state
-- **Form interactions**:
- - Input focus: Border color transition, slight scale or glow
- - Validation: Shake on error, check mark on success, smooth color transitions
-- **Toggle switches**: Smooth slide + color transition (200-300ms)
-- **Checkboxes/radio**: Check mark animation, ripple effect
-- **Like/favorite**: Scale + rotation, particle effects, color transition
-
-### State Transitions
-- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms)
-- **Expand/collapse**: Height transition with overflow handling, icon rotation
-- **Loading states**: Skeleton screen fades, spinner animations, progress bars
-- **Success/error**: Color transitions, icon animations, gentle scale pulse
-- **Enable/disable**: Opacity transitions, cursor changes
-
-### Navigation & Flow
-- **Page transitions**: Crossfade between routes, shared element transitions
-- **Tab switching**: Slide indicator, content fade/slide
-- **Carousel/slider**: Smooth transforms, snap points, momentum
-- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators
-
-### Feedback & Guidance
-- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights
-- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning
-- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation
-- **Focus flow**: Highlight path through form or workflow
-
-### Delight Moments
-- **Empty states**: Subtle floating animations on illustrations
-- **Completed actions**: Confetti, check mark flourish, success celebrations
-- **Easter eggs**: Hidden interactions for discovery
-- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches
-
-## Technical Implementation
-
-Use appropriate techniques for each animation:
-
-### Timing & Easing
-
-**Durations by purpose:**
-- **100-150ms**: Instant feedback (button press, toggle)
-- **200-300ms**: State changes (hover, menu open)
-- **300-500ms**: Layout changes (accordion, modal)
-- **500-800ms**: Entrance animations (page load)
-
-**Easing curves (use these, not CSS defaults):**
-```css
-/* Recommended: natural deceleration */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */
-
-/* AVOID: feel dated and tacky */
-/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */
-/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */
-```
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-### CSS Animations
-```css
-/* Prefer for simple, declarative animations */
-- transitions for state changes
-- @keyframes for complex sequences
-- transform and opacity for reliable movement
-- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth
-```
-
-### JavaScript Animation
-```javascript
-/* Use for complex, interactive animations */
-- Web Animations API for programmatic control
-- Framer Motion for React
-- GSAP for complex sequences
-```
-
-### Performance
-- **Motion materials**: Use transform/opacity for reliable movement, but use blur, filters, masks, shadows, and color shifts when they materially improve the effect
-- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- **will-change**: Add sparingly for known expensive animations
-- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate
-- **Monitor FPS**: Ensure 60fps on target devices
-
-### Accessibility
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**NEVER**:
-- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself
-- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work
-- Use durations over 500ms for feedback (it feels laggy)
-- Animate without purpose (every animation needs a reason)
-- Ignore `prefers-reduced-motion` (this is an accessibility violation)
-- Animate everything (animation fatigue makes interfaces feel exhausting)
-- Block interaction during animations unless intentional
-
-## Verify Quality
-
-Test animations thoroughly:
-
-- **Smooth at 60fps**: No jank on target devices
-- **Feels natural**: Easing curves feel organic, not robotic
-- **Appropriate timing**: Not too fast (jarring) or too slow (laggy)
-- **Reduced motion works**: Animations disabled or simplified appropriately
-- **Doesn't block**: Users can interact during/after animations
-- **Adds value**: Makes interface clearer or more delightful
-
-When the motion clarifies state instead of decorating it, hand off to `/impeccable polish` for the final pass.
@@ -1,133 +0,0 @@
-Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues; document them for other commands to address.
-
-This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation.
-
-## Diagnostic Scan
-
-Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below.
-
-### 1. Accessibility (A11y)
-
-**Check for**:
-- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA)
-- **Missing ARIA**: Interactive elements without proper roles, labels, or states
-- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps
-- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons
-- **Alt text**: Missing or poor image descriptions
-- **Form issues**: Inputs without labels, poor error messaging, missing required indicators
-
-**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA)
-
-### 2. Performance
-
-**Check for**:
-- **Layout thrashing**: Reading/writing layout properties in loops
-- **Expensive animations**: Casual layout-property animation, unbounded blur/filter/shadow effects, or effects that visibly drop frames
-- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change
-- **Bundle size**: Unnecessary imports, unused dependencies
-- **Render performance**: Unnecessary re-renders, missing memoization
-
-**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized)
-
-### 3. Theming
-
-**Check for**:
-- **Hard-coded colors**: Colors not using design tokens
-- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme
-- **Inconsistent tokens**: Using wrong tokens, mixing token types
-- **Theme switching issues**: Values that don't update on theme change
-
-**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly)
-
-### 4. Responsive Design
-
-**Check for**:
-- **Fixed widths**: Hard-coded widths that break on mobile
-- **Touch targets**: Interactive elements < 44x44px
-- **Horizontal scroll**: Content overflow on narrow viewports
-- **Text scaling**: Layouts that break when text size increases
-- **Missing breakpoints**: No mobile/tablet variants
-
-**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets)
-
-### 5. Anti-Patterns (CRITICAL)
-
-Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy).
-
-**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design)
-
-## Generate Report
-
-### Audit Health Score
-
-| # | Dimension | Score | Key Finding |
-|---|-----------|-------|-------------|
-| 1 | Accessibility | ? | [most critical a11y issue or "--"] |
-| 2 | Performance | ? | |
-| 3 | Responsive Design | ? | |
-| 4 | Theming | ? | |
-| 5 | Anti-Patterns | ? | |
-| **Total** | | **??/20** | **[Rating band]** |
-
-**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues)
-
-### Anti-Patterns Verdict
-**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest.
-
-### Executive Summary
-- Audit Health Score: **??/20** ([rating band])
-- Total issues found (count by severity: P0/P1/P2/P3)
-- Top 3-5 critical issues
-- Recommended next steps
-
-### Detailed Findings by Severity
-
-Tag every issue with **P0-P3 severity**:
-- **P0 Blocking**: Prevents task completion. Fix immediately
-- **P1 Major**: Significant difficulty or WCAG AA violation. Fix before release
-- **P2 Minor**: Annoyance, workaround exists. Fix in next pass
-- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits
-
-For each issue, document:
-- **[P?] Issue name**
-- **Location**: Component, file, line
-- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern
-- **Impact**: How it affects users
-- **WCAG/Standard**: Which standard it violates (if applicable)
-- **Recommendation**: How to fix it
-- **Suggested command**: Which command to use (prefer: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-### Patterns & Systemic Issues
-
-Identify recurring problems that indicate systemic gaps rather than one-off mistakes:
-- "Hard-coded colors appear in 15+ components, should use design tokens"
-- "Touch targets consistently too small (<44px) throughout mobile experience"
-
-### Positive Findings
-
-Note what's working well: good practices to maintain and replicate.
-
-## Recommended Actions
-
-List recommended commands in priority order (P0 first, then P1, then P2):
-
-1. **[P?] `/command-name`**: Brief description (specific context from audit findings)
-2. **[P?] `/command-name`**: Brief description (specific context)
-
-**Rules**: Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset. Map findings to the most appropriate command. End with `/impeccable polish` as the final step if any fixes were recommended.
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable audit` after fixes to see your score improve.
-
-**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters.
-
-**NEVER**:
-- Report issues without explaining impact (why does this matter?)
-- Provide generic recommendations (be specific and actionable)
-- Skip positive findings (celebrate what works)
-- Forget to prioritize (everything can't be P0)
-- Report false positives without verification
-
@@ -1,113 +0,0 @@
-When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact and personality through stronger hierarchy, committed scale, and decisive type.
-
----
-
-## Register
-
-Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
-
-Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too safe or boring:
-
-1. **Identify weakness sources**:
- - **Generic choices**: System fonts, basic colors, standard layouts
- - **Timid scale**: Everything is medium-sized with no drama
- - **Low contrast**: Everything has similar visual weight
- - **Static**: No motion, no energy, no life
- - **Predictable**: Standard patterns with no surprises
- - **Flat hierarchy**: Nothing stands out or commands attention
-
-2. **Understand the context**:
- - What's the brand personality? (How far can we push?)
- - What's the purpose? (Marketing can be bolder than financial dashboards)
- - Who's the audience? (What will resonate?)
- - What are the constraints? (Brand guidelines, accessibility, performance)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
-
-**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
-
-## Plan Amplification
-
-Create a strategy to increase impact while maintaining coherence:
-
-- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
-- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
-- **Risk budget**: How experimental can we be? Push boundaries within constraints.
-- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
-
-**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration.
-
-## Amplify the Design
-
-Systematically increase impact across these dimensions:
-
-### Typography Amplification
-- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and [typography.md](typography.md) for inspiration)
-- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
-- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
-- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
-
-### Color Intensification
-- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
-- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop
-- **Dominant color strategy**: Let one bold color own 60% of the design
-- **Sharp accents**: High-contrast accent colors that pop
-- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
-- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
-
-### Spatial Drama
-- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
-- **Break the grid**: Let hero elements escape containers and cross boundaries
-- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
-- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
-- **Overlap**: Layer elements intentionally for depth
-
-### Visual Effects
-- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
-- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
-- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop)
-- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
-- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
-
-### Motion & Animation
-- **Entrance choreography**: Staggered, dramatic page load animations with 50-100ms delays
-- **Scroll effects**: Parallax, reveal animations, scroll-triggered sequences
-- **Micro-interactions**: Satisfying hover effects, click feedback, state changes
-- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect)
-
-### Composition Boldness
-- **Hero moments**: Create clear focal points with dramatic treatment
-- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
-- **Full-bleed elements**: Use full viewport width/height for impact
-- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
-
-**NEVER**:
-- Add effects randomly without purpose (chaos ≠ bold)
-- Sacrifice readability for aesthetics (body text must be readable)
-- Make everything bold (then nothing is bold; you need contrast)
-- Ignore accessibility (bold design must still meet WCAG standards)
-- Overwhelm with motion (animation fatigue is real)
-- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
-
-## Verify Quality
-
-Ensure amplification maintains usability and coherence:
-
-- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over.
-- **Still functional**: Can users accomplish tasks without distraction?
-- **Coherent**: Does everything feel intentional and unified?
-- **Memorable**: Will users remember this experience?
-- **Performant**: Do all these effects run smoothly?
-- **Accessible**: Does it still meet accessibility standards?
-
-**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects."
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,118 +0,0 @@
-# Brand register
-
-When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made.
-
-The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look.
-
-## The brand slop test
-
-If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?"
-
-Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home.
-
-**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register.
-
-Then the inverse test: in one sentence, describe what you're about to build the way a competitor would describe theirs. If that sentence fits the modal landing page in the category, restart.
-
-## Typography
-
-### Font selection procedure
-
-Every project. Never skip.
-
-1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words.
-2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture.
-3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy."
-4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over.
-
-### Reflex-reject list
-
-Training-data defaults. Ban list. Look further:
-
-Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif
-
-### Reflex-reject aesthetic lanes
-
-Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further.
-
-- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery.
-
-(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.)
-
-The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md).
-
-### Pairing and voice
-
-Distinctive + refined is the goal. The specific shape depends on the brand:
-
-- **Editorial / long-form / luxury**: display serif + sans body (a magazine shape).
-- **Tech / dev tools / fintech**: one committed sans, usually; custom-tight tracking, strong weight contrast inside a single family.
-- **Consumer / food / travel**: warmer pairings, often a humanist sans plus a script or display serif.
-- **Creative studios / agencies**: rule-breaking welcome. Mono-only, or display-only, or custom-drawn type as voice.
-
-Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair.
-
-Vary across projects. If the last brief was a serif-display landing page, this one isn't.
-
-### Scale
-
-Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted.
-
-Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room.
-
-## Color
-
-Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register.
-
-- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige.
-- Palette IS voice. A calm brand and a restless brand should not share palette mechanics.
-- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit.
-- Don't converge across projects. If the last brand surface was restrained-on-cream, this one is not.
-- When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette.
-
-## Layout
-
-- Asymmetric compositions are one option. Break the grid intentionally for emphasis.
-- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings.
-- Alternative: a strict, visible grid as the voice (brutalist / Swiss / tech-spec aesthetics). Either asymmetric or rigorously-gridded can be "designed"; the failure mode is splitting the difference into a generic centered stack.
-- Don't default to centering everything. Left-aligned with asymmetric layouts feels more designed; a strict grid reads as confident structure. A centered-stack hero with icon-title-subtitle cards reads as template.
-- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness.
-
-## Imagery
-
-Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo.
-
-**When the brief implies imagery (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product), you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy.
-
-- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `<div>` placeholders.
-- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel".
-- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one.
-- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish".
-
-"Imagery" here is broader than stock photography: product screenshots, custom data visualizations, generated SVG, and canvas/WebGL scenes are all imagery. Text-only pages where typography alone carries the entire visual weight are the failure mode.
-
-## Motion
-
-- One well-orchestrated page-load with staggered reveals beats scattered micro-interactions, when the brand invites it. Tech-minimal brands often skip entrance motion entirely; the restraint is the voice.
-- For collapsing/expanding sections, transition `grid-template-rows` rather than `height`.
-
-## Brand bans (on top of the shared absolute bans)
-
-- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume.
-- Large rounded-corner icons above every heading. Screams template.
-- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.)
-- All-caps body copy. Reserve caps for short labels and headings.
-- Timid palettes and average layouts. Safe = invisible.
-- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs.
-- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic.
-- Repeated tiny uppercase tracked labels above every section heading. A single strong kicker can be voice; repeating it as section grammar is AI scaffolding unless it's a deliberate, named brand system.
-
-## Brand permissions
-
-Brand can afford things product can't. Take them.
-
-- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography.
-- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing.
-- Typographic risk. Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines, a single oversize word as a hero.
-- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics.
-- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment.
@@ -1,174 +0,0 @@
-> **Additional context needed**: audience technical level and users' mental state in context.
-
-Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task.
-
-
----
-
-## Assess Current Copy
-
-Identify what makes the text unclear or ineffective:
-
-1. **Find clarity problems**:
- - **Jargon**: Technical terms users won't understand
- - **Ambiguity**: Multiple interpretations possible
- - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file"
- - **Length**: Too wordy or too terse
- - **Assumptions**: Assuming user knowledge they don't have
- - **Missing context**: Users don't know what to do or why
- - **Tone mismatch**: Too formal, too casual, or inappropriate for situation
-
-2. **Understand the context**:
- - Who's the audience? (Technical? General? First-time users?)
- - What's the user's mental state? (Stressed during error? Confident during success?)
- - What's the action? (What do we want users to do?)
- - What's the constraint? (Character limits? Space limitations?)
-
-**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets.
-
-## Plan Copy Improvements
-
-Create a strategy for clearer communication:
-
-- **Primary message**: What's the ONE thing users need to know?
-- **Action needed**: What should users do next (if anything)?
-- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?)
-- **Constraints**: Length limits, brand voice, localization considerations
-
-**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words.
-
-## Improve Copy Systematically
-
-Refine text across these common areas:
-
-### Error Messages
-**Bad**: "Error 403: Forbidden"
-**Good**: "You don't have permission to view this page. Contact your admin for access."
-
-**Bad**: "Invalid input"
-**Good**: "Email addresses need an @ symbol. Try: name@example.com"
-
-**Principles**:
-- Explain what went wrong in plain language
-- Suggest how to fix it
-- Don't blame the user
-- Include examples when helpful
-- Link to help/support if applicable
-
-### Form Labels & Instructions
-**Bad**: "DOB (MM/DD/YYYY)"
-**Good**: "Date of birth" (with placeholder showing format)
-
-**Bad**: "Enter value here"
-**Good**: "Your email address" or "Company name"
-
-**Principles**:
-- Use clear, specific labels (not generic placeholders)
-- Show format expectations with examples
-- Explain why you're asking (when not obvious)
-- Put instructions before the field, not after
-- Keep required field indicators clear
-
-### Button & CTA Text
-**Bad**: "Click here" | "Submit" | "OK"
-**Good**: "Create account" | "Save changes" | "Got it, thanks"
-
-**Principles**:
-- Describe the action specifically
-- Use active voice (verb + noun)
-- Match user's mental model
-- Be specific ("Save" is better than "OK")
-
-### Help Text & Tooltips
-**Bad**: "This is the username field"
-**Good**: "Choose a username. You can change this later in Settings."
-
-**Principles**:
-- Add value (don't just repeat the label)
-- Answer the implicit question ("What is this?" or "Why do you need this?")
-- Keep it brief but complete
-- Link to detailed docs if needed
-
-### Empty States
-**Bad**: "No items"
-**Good**: "No projects yet. Create your first project to get started."
-
-**Principles**:
-- Explain why it's empty (if not obvious)
-- Show next action clearly
-- Make it welcoming, not dead-end
-
-### Success Messages
-**Bad**: "Success"
-**Good**: "Settings saved! Your changes will take effect immediately."
-
-**Principles**:
-- Confirm what happened
-- Explain what happens next (if relevant)
-- Be brief but complete
-- Match the user's emotional moment (celebrate big wins)
-
-### Loading States
-**Bad**: "Loading..." (for 30+ seconds)
-**Good**: "Analyzing your data... this usually takes 30-60 seconds"
-
-**Principles**:
-- Set expectations (how long?)
-- Explain what's happening (when it's not obvious)
-- Show progress when possible
-- Offer escape hatch if appropriate ("Cancel")
-
-### Confirmation Dialogs
-**Bad**: "Are you sure?"
-**Good**: "Delete 'Project Alpha'? This can't be undone."
-
-**Principles**:
-- State the specific action
-- Explain consequences (especially for destructive actions)
-- Use clear button labels ("Delete project" not "Yes")
-- Don't overuse confirmations (only for risky actions)
-
-### Navigation & Wayfinding
-**Bad**: Generic labels like "Items" | "Things" | "Stuff"
-**Good**: Specific labels like "Your projects" | "Team members" | "Settings"
-
-**Principles**:
-- Be specific and descriptive
-- Use language users understand (not internal jargon)
-- Make hierarchy clear
-- Consider information scent (breadcrumbs, current location)
-
-## Apply Clarity Principles
-
-Every piece of copy should follow these rules:
-
-1. **Be specific**: "Enter email" not "Enter value"
-2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity)
-3. **Be active**: "Save changes" not "Changes will be saved"
-4. **Be human**: "Oops, something went wrong" not "System error encountered"
-5. **Tell users what to do**, not just what happened
-6. **Be consistent**: Use same terms throughout (don't vary for variety)
-
-**NEVER**:
-- Use jargon without explanation
-- Blame users ("You made an error" → "This field is required")
-- Be vague ("Something went wrong" without explanation)
-- Use passive voice unnecessarily
-- Write overly long explanations (be concise)
-- Use humor for errors (be empathetic instead)
-- Assume technical knowledge
-- Vary terminology (pick one term and stick with it)
-- Repeat information (headers restating intros, redundant explanations)
-- Use placeholders as the only labels (they disappear when users type)
-
-## Verify Improvements
-
-Test that copy improvements work:
-
-- **Comprehension**: Can users understand without context?
-- **Actionability**: Do users know what to do next?
-- **Brevity**: Is it as short as possible while remaining clear?
-- **Consistency**: Does it match terminology elsewhere?
-- **Tone**: Is it appropriate for the situation?
-
-When the copy reads cleanly, hand off to `/impeccable polish` for the final pass.
@@ -1,105 +0,0 @@
-# Codex: Visual Direction & Asset Production
-
-This file is loaded by `/impeccable craft` when the harness has native image generation (currently Codex via `image_gen`). Other harnesses skip it. It covers the two craft steps that depend on real image generation: landing the visual direction, and producing the raster assets the implementation will compose.
-
-Read this *before* generating any images. The order matters, and the per-step user pauses are what keep generated imagery from drifting away from the brief.
-
-### Four stop points before code
-
-Steps A through D each end with the user. Do not advance past any of them on your own read of the situation.
-
-1. **STOP after Step A questions.** Wait for answers.
-2. **STOP after Step B palette generation.** Wait for "confirm palette."
-3. **STOP after Step C mocks.** Wait for direction approval or delegation.
-4. **Only after Step D approves a direction** do you return to craft.md Step 4 and write code.
-
-Prior shape approval does **not** satisfy any of these. Shape's "confirm or override" advances you into Step A; it is not a substitute for it.
-
-## Step A: Explore Directions with the User
-
-Before generating anything, run a brief direction conversation grounded in the shape brief.
-
-**Step A is required even when shape just produced a confirmed brief.** The shape questions and Step A questions cover different ground: shape pins purpose, content, scope; Step A pins palette, atmosphere, and named visual references for the comps you're about to generate. The only time you can skip Step A is when the user has already answered these exact palette/atmosphere/reference questions in the same session.
-
-Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions:
-
-- "Brief says 'editorial restraint, Klim-adjacent.' Are we closer to a quiet specimen page or a magazine-spread feel with hero imagery?"
-- "Palette strategy from shape was 'Committed.' Want it warm-grounded (deep oxblood + cream) or cool-grounded (slate + paper white)?"
-
-**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded.
-
-## Step B: Generate the Brand Palette First
-
-Generate **one** palette artifact before any mocks. This is a small, focused image: typography pairing on the chosen background, primary + accent color swatches, one signature ornament or motif. Single image, single pass.
-
-Why palette first: mocks generated against a vague color sense produce noise that drowns out the structural decisions. A confirmed palette is the first concrete contract for everything downstream.
-
-Show the palette to the user. Ask one question: "This is the palette I'm locking in for the mocks. Confirm, or call out what to shift?"
-
-**STOP and wait for confirmation.** Do not generate mocks against an unconfirmed palette. "Probably good enough" is the wrong call here; the palette is the contract for everything downstream.
-
-## Step C: Generate 1-3 Visual Mocks Against the Palette
-
-Once the palette is confirmed, generate **1 to 3** high-fidelity north-star comps. Each mock must use the confirmed palette and typography. Mocks differ in *structural* direction (hierarchy, topology, density, composition), not in color or motif.
-
-- Brand work: push visual identity, composition, mood, and signature motifs.
-- Product work: push hierarchy, topology, density, tone, grounded in realistic product structure.
-- Landing pages and long-form brand surfaces: show enough of the second fold to establish the system beyond the hero.
-
-Use the `image_gen` tool directly (or via the imagegen skill when available). Don't ask the user to install anything.
-
-## Step D: Approval Loop
-
-Show the comps. Ask what carries forward. Iterate until **one direction is approved** or the user explicitly delegates.
-
-**STOP and wait for the approval or the delegation.** Do not begin Step E or return to craft.md Step 4 until a single direction is named. If the user delegates, pick the strongest direction and explain it from the brief, not personal taste.
-
-Before moving to assets, summarize what to carry into code and what *not* to literalize from the mock. This is the handoff between visual exploration and semantic implementation.
-
-## Step E: Mock Fidelity Inventory
-
-Inventory the approved mock's major visible ingredients. For each, decide implementation: semantic HTML/CSS/SVG, generated raster, sourced raster, icon library, canvas/WebGL, or accepted omission.
-
-Common ingredients to inventory:
-
-- Hero silhouette and dominant composition
-- Signature motifs (planets, devices, portraits, charts, route lines, insets, badges, etc.)
-- Nav and primary CTA treatment
-- Section sequence, especially the second fold
-- Image-native content the concept depends on
-- Typography, density, color/material treatment, motion cues
-
-Treat the mock as a north star, not a screenshot to trace. Don't rasterize core UI text. But if the live result lacks the mock's major ingredients, the implementation is wrong.
-
-If a photographic, architectural, product, or place-led mock becomes generic CSS scenery, decorative diagrams, bullets, or copy, stop and fix it. That's a broken implementation, not a harmless interpretation.
-
-Don't substitute a different hero composition or visual driver post-approval without user sign-off.
-
-## Step F: Asset Slicing via the Asset Producer
-
-Raster ingredients identified in Step E need clean production assets. Use the bundled `impeccable_asset_producer` subagent rather than producing inline.
-
-Spawn it as a scoped subagent. If you do not have explicit permission to use agents, stop and ask:
-
-```text
-Asset production will work better as a scoped subagent job. Should I spawn the Impeccable asset producer subagent for this step?
-```
-
-Pass to the agent:
-
-- Approved mock path or screenshot reference
-- Crop paths or a contact sheet with crop ids
-- Output directory
-- Required dimensions, format, transparency needs
-- Avoid list
-- Notes on what should remain semantic HTML/CSS/SVG instead of raster
-
-Attach image generation capability to the spawned agent when the harness supports it. Do **not** load image-generation reference material into the parent thread.
-
-Inline asset production is allowed only if the user declines subagents, the harness cannot spawn the authorized agent, or the user explicitly asks for single-thread mode.
-
-Prefer HTML/CSS/SVG/canvas when they can credibly reproduce an ingredient; reach for real, generated, or stock imagery when the mock or subject matter calls for actual visual content.
-
-## After This File
-
-Once Steps A through F are complete, return to `craft.md` Step 5 (Build to Production Quality). The implementation builds against the confirmed palette, approved mock, and the assets the producer wrote.
@@ -1,106 +0,0 @@
-# Cognitive Load Assessment
-
-Cognitive load is the total mental effort required to use an interface. Overloaded users make mistakes, get frustrated, and leave. This reference helps identify and fix cognitive overload.
-
----
-
-## Three Types of Cognitive Load
-
-### Intrinsic Load: The Task Itself
-Complexity inherent to what the user is trying to do. You can't eliminate this, but you can structure it.
-
-**Manage it by**:
-- Breaking complex tasks into discrete steps
-- Providing scaffolding (templates, defaults, examples)
-- Progressive disclosure: show what's needed now, hide the rest
-- Grouping related decisions together
-
-### Extraneous Load: Bad Design
-Mental effort caused by poor design choices. **Eliminate this ruthlessly.** It's pure waste.
-
-**Common sources**:
-- Confusing navigation that requires mental mapping
-- Unclear labels that force users to guess meaning
-- Visual clutter competing for attention
-- Inconsistent patterns that prevent learning
-- Unnecessary steps between user intent and result
-
-### Germane Load: Learning Effort
-Mental effort spent building understanding. This is *good* cognitive load; it leads to mastery.
-
-**Support it by**:
-- Progressive disclosure that reveals complexity gradually
-- Consistent patterns that reward learning
-- Feedback that confirms correct understanding
-- Onboarding that teaches through action, not walls of text
-
----
-
-## Cognitive Load Checklist
-
-Evaluate the interface against these 8 items:
-
-- [ ] **Single focus**: Can the user complete their primary task without distraction from competing elements?
-- [ ] **Chunking**: Is information presented in digestible groups (≤4 items per group)?
-- [ ] **Grouping**: Are related items visually grouped together (proximity, borders, shared background)?
-- [ ] **Visual hierarchy**: Is it immediately clear what's most important on the screen?
-- [ ] **One thing at a time**: Can the user focus on a single decision before moving to the next?
-- [ ] **Minimal choices**: Are decisions simplified (≤4 visible options at any decision point)?
-- [ ] **Working memory**: Does the user need to remember information from a previous screen to act on the current one?
-- [ ] **Progressive disclosure**: Is complexity revealed only when the user needs it?
-
-**Scoring**: Count the failed items. 0–1 failures = low cognitive load (good). 2–3 = moderate (address soon). 4+ = high cognitive load (critical fix needed).
-
----
-
-## The Working Memory Rule
-
-**Humans can hold ≤4 items in working memory at once** (Miller's Law revised by Cowan, 2001).
-
-At any decision point, count the number of distinct options, actions, or pieces of information a user must simultaneously consider:
-- **≤4 items**: Within working memory limits, manageable
-- **5–7 items**: Pushing the boundary; consider grouping or progressive disclosure
-- **8+ items**: Overloaded; users will skip, misclick, or abandon
-
-**Practical applications**:
-- Navigation menus: ≤5 top-level items (group the rest under clear categories)
-- Form sections: ≤4 fields visible per group before a visual break
-- Action buttons: 1 primary, 1–2 secondary, group the rest in a menu
-- Dashboard widgets: ≤4 key metrics visible without scrolling
-- Pricing tiers: ≤3 options (more causes analysis paralysis)
-
----
-
-## Common Cognitive Load Violations
-
-### 1. The Wall of Options
-**Problem**: Presenting 10+ choices at once with no hierarchy.
-**Fix**: Group into categories, highlight recommended, use progressive disclosure.
-
-### 2. The Memory Bridge
-**Problem**: User must remember info from step 1 to complete step 3.
-**Fix**: Keep relevant context visible, or repeat it where it's needed.
-
-### 3. The Hidden Navigation
-**Problem**: User must build a mental map of where things are.
-**Fix**: Always show current location (breadcrumbs, active states, progress indicators).
-
-### 4. The Jargon Barrier
-**Problem**: Technical or domain language forces translation effort.
-**Fix**: Use plain language. If domain terms are unavoidable, define them inline.
-
-### 5. The Visual Noise Floor
-**Problem**: Every element has the same visual weight; nothing stands out.
-**Fix**: Establish clear hierarchy: one primary element, 2–3 secondary, everything else muted.
-
-### 6. The Inconsistent Pattern
-**Problem**: Similar actions work differently in different places.
-**Fix**: Standardize interaction patterns. Same type of action = same type of UI.
-
-### 7. The Multi-Task Demand
-**Problem**: Interface requires processing multiple simultaneous inputs (reading + deciding + navigating).
-**Fix**: Sequence the steps. Let the user do one thing at a time.
-
-### 8. The Context Switch
-**Problem**: User must jump between screens/tabs/modals to gather info for a single decision.
-**Fix**: Co-locate the information needed for each decision. Reduce back-and-forth.
@@ -1,105 +0,0 @@
-# Color & Contrast
-
-## Color Spaces: Use OKLCH
-
-**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark.
-
-The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish.
-
-The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand.
-
-## Building Functional Palettes
-
-### Tinted Neutrals
-
-**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces.
-
-The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette.
-
-**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects.
-
-### Palette Structure
-
-A complete system needs:
-
-| Role | Purpose | Example |
-|------|---------|---------|
-| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades |
-| **Neutral** | Text, backgrounds, borders | 9-11 shade scale |
-| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each |
-| **Surface** | Cards, modals, overlays | 2-3 elevation levels |
-
-**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise.
-
-### The 60-30-10 Rule (Applied Correctly)
-
-This rule is about **visual weight**, not pixel count:
-
-- **60%**: Neutral backgrounds, white space, base surfaces
-- **30%**: Secondary colors: text, borders, inactive states
-- **10%**: Accent: CTAs, highlights, focus states
-
-The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power.
-
-## Contrast & Accessibility
-
-### WCAG Requirements
-
-| Content Type | AA Minimum | AAA Target |
-|--------------|------------|------------|
-| Body text | 4.5:1 | 7:1 |
-| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 |
-| UI components, icons | 3:1 | 4.5:1 |
-| Non-essential decorations | None | None |
-
-**The gotcha**: Placeholder text still needs 4.5:1. That light gray placeholder you see everywhere? Usually fails WCAG.
-
-### Dangerous Color Combinations
-
-These commonly fail contrast or cause readability issues:
-
-- Light gray text on white (the #1 accessibility fail)
-- **Gray text on any colored background**: gray looks washed out and dead on color. Use a darker shade of the background color, or transparency
-- Red text on green background (or vice versa): 8% of men can't distinguish these
-- Blue text on red background (vibrates visually)
-- Yellow text on white (almost always fails)
-- Thin light text on images (unpredictable contrast)
-
-### Never Use Pure Gray or Pure Black
-
-Pure gray (`oklch(50% 0 0)`) and pure black (`#000`) don't exist in nature; real shadows and surfaces always have a color cast. Even a chroma of 0.005-0.01 is enough to feel natural without being obviously tinted. (See tinted neutrals example above.)
-
-### Testing
-
-Don't trust your eyes. Use tools:
-
-- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/)
-- Browser DevTools → Rendering → Emulate vision deficiencies
-- [Polypane](https://polypane.app/) for real-time testing
-
-## Theming: Light & Dark Mode
-
-### Dark Mode Is Not Inverted Light Mode
-
-You can't just swap colors. Dark mode requires different design decisions:
-
-| Light Mode | Dark Mode |
-|------------|-----------|
-| Shadows for depth | Lighter surfaces for depth (no shadows) |
-| Dark text on light | Light text on dark (reduce font weight) |
-| Vibrant accents | Desaturate accents slightly |
-| White backgrounds | Never pure black; use dark gray (oklch 12-18%) |
-
-In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light.
-
-### Token Hierarchy
-
-Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same.
-
-## Alpha Is A Design Smell
-
-Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed.
-
----
-
-**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Using pure black (#000) for large areas. Skipping color blindness testing (8% of men affected).
@@ -1,154 +0,0 @@
-> **Additional context needed**: existing brand colors.
-
-Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit.
-
----
-
-## Register
-
-Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it.
-
-Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen.
-
----
-
-## Assess Color Opportunity
-
-Analyze the current state and identify opportunities:
-
-1. **Understand current state**:
- - **Color absence**: Pure grayscale? Limited neutrals? One timid accent?
- - **Missed opportunities**: Where could color add meaning, hierarchy, or delight?
- - **Context**: What's appropriate for this domain and audience?
- - **Brand**: Are there existing brand colors we should use?
-
-2. **Identify where color adds value**:
- - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue)
- - **Hierarchy**: Drawing attention to important elements
- - **Categorization**: Different sections, types, or states
- - **Emotional tone**: Warmth, energy, trust, creativity
- - **Wayfinding**: Helping users navigate and understand structure
- - **Delight**: Moments of visual interest and personality
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose.
-
-## Plan Color Strategy
-
-Create a purposeful color introduction plan:
-
-- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals)
-- **Dominant color**: Which color owns 60% of colored elements?
-- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%)
-- **Application strategy**: Where does each color appear and why?
-
-**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more.
-
-## Introduce Color Strategically
-
-Add color systematically across these dimensions:
-
-### Semantic Color
-- **State indicators**:
- - Success: Green tones (emerald, forest, mint)
- - Error: Red/pink tones (rose, crimson, coral)
- - Warning: Orange/amber tones
- - Info: Blue tones (sky, ocean, indigo)
- - Neutral: Gray/slate for inactive states
-
-- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.)
-- **Progress indicators**: Colored bars, rings, or charts showing completion or health
-
-### Accent Color Application
-- **Primary actions**: Color the most important buttons/CTAs
-- **Links**: Add color to clickable text (maintain accessibility)
-- **Icons**: Colorize key icons for recognition and personality
-- **Headers/titles**: Add color to section headers or key labels
-- **Hover states**: Introduce color on interaction
-
-### Background & Surfaces
-- **Tinted backgrounds**: Replace pure gray (`#f5f5f5`) with warm neutrals (`oklch(97% 0.01 60)`) or cool tints (`oklch(97% 0.01 250)`)
-- **Colored sections**: Use subtle background colors to separate areas
-- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue)
-- **Cards & surfaces**: Tint cards or surfaces slightly for warmth
-
-**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
-
-### Data Visualization
-- **Charts & graphs**: Use color to encode categories or values
-- **Heatmaps**: Color intensity shows density or importance
-- **Comparison**: Color coding for different datasets or timeframes
-
-### Borders & Accents
-- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`)
-- **Underlines**: Color underlines for emphasis or active states
-- **Dividers**: Subtle colored dividers instead of gray lines
-- **Focus rings**: Colored focus indicators matching brand
-- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe
-
-**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe.
-
-### Typography Color
-- **Colored headings**: Use brand colors for section headings (maintain contrast)
-- **Highlight text**: Color for emphasis or categories
-- **Labels & tags**: Small colored labels for metadata or categories
-
-### Decorative Elements
-- **Illustrations**: Add colored illustrations or icons
-- **Shapes**: Geometric shapes in brand colors as background elements
-- **Gradients**: Colorful gradient overlays or mesh backgrounds
-- **Blobs/organic shapes**: Soft colored shapes for visual interest
-
-## Balance & Refinement
-
-Ensure color addition improves rather than overwhelms:
-
-### Maintain Hierarchy
-- **Dominant color** (60%): Primary brand color or most used accent
-- **Secondary color** (30%): Supporting color for variety
-- **Accent color** (10%): High contrast for key moments
-- **Neutrals** (remaining): Gray/black/white for structure
-
-### Accessibility
-- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components)
-- **Don't rely on color alone**: Use icons, labels, or patterns alongside color
-- **Test for color blindness**: Verify red/green combinations work for all users
-
-### Cohesion
-- **Consistent palette**: Use colors from defined palette, not arbitrary choices
-- **Systematic application**: Same color meanings throughout (green always = success)
-- **Temperature consistency**: Warm palette stays warm, cool stays cool
-
-**NEVER**:
-- Use every color in the rainbow (choose 2-4 colors beyond neutrals)
-- Apply color randomly without semantic meaning
-- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead
-- Use pure gray for neutrals. Add subtle color tint (warm or cool) for depth
-- Use pure black (`#000`) or pure white (`#fff`) for large areas
-- Violate WCAG contrast requirements
-- Use color as the only indicator (accessibility issue)
-- Make everything colorful (defeats the purpose)
-- Default to purple-blue gradients (AI slop aesthetic)
-
-## Verify Color Addition
-
-Test that colorization improves the experience:
-
-- **Better hierarchy**: Does color guide attention appropriately?
-- **Clearer meaning**: Does color help users understand states/categories?
-- **More engaging**: Does the interface feel warmer and more inviting?
-- **Still accessible**: Do all color combinations meet WCAG standards?
-- **Not overwhelming**: Is color balanced and purposeful?
-
-When the palette earns its place, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage.
-
-```json
-{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"}
-```
-
-Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract.
@@ -1,123 +0,0 @@
-# Craft Flow
-
-Build a feature with impeccable UX and UI quality: shape the design, land the visual direction, build real production code, inspect and improve in-browser until it meets a high-end studio bar.
-
-Before writing code, you need: PRODUCT.md loaded, register identified and the matching reference loaded, and a confirmed design direction for this task (either from `shape` or supplied by the user). PRODUCT.md is project context, not a task-specific brief.
-
-Treat any approved visual direction (generated mock or stated reference) as a concrete contract for composition, hierarchy, density, atmosphere, signature motifs, and distinctive visual moves. Don't let mocks replace structure, copy, accessibility, or state design. But if the live result lacks the approved direction's major ingredients, the implementation is wrong.
-
-### Gates: do not compress
-
-Craft has **multiple user gates**, not one. When the harness has native image generation (Codex via `image_gen`), the gate sequence before code is:
-
-1. **Shape brief confirmed** (Step 1)
-2. **Direction questions answered** (codex.md Step A)
-3. **Palette confirmed** (codex.md Step B)
-4. **One mock direction approved or delegated** (codex.md Step D)
-
-You must stop at every gate. **Shape confirmation alone is NOT a green light to start coding.** It is the green light to begin codex.md Step A. Compressing gates 2 through 4 because the shape brief felt complete is the dominant failure mode of this flow.
-
-When the harness lacks native image generation, gates 2-4 collapse into the brief itself, and shape confirmation does advance straight to code.
-
-## Step 0: Project Foundation
-
-Before shape, before code: figure out what kind of project you're working in.
-
-Look at the working directory. Run `ls`. Check for:
-
-- An existing framework: `astro.config.mjs/ts`, `next.config.js/ts`, `nuxt.config.ts`, `svelte.config.js`, `vite.config.js/ts`, `package.json` with framework deps, `Cargo.toml` + Leptos/Yew, `Gemfile` + Rails. **If found, use it.** Do not start a parallel build, do not introduce a second framework, do not write to `dist/` or `build/` directly. Whatever pipeline the project has, respect it.
-- An existing component library or design system: `src/components/`, `app/components/`, a `tokens.css` / `theme.ts`, an `astro.config` `integrations`. Read what's there before adding to it.
-- An existing icon set: `lucide-react`, `@phosphor-icons/react`, `@iconify/*`, hand-rolled SVG sprites in `assets/icons/`. **Use what's already in the project**; don't introduce a second set.
-
-If the directory is empty (greenfield), don't pick a framework silently. Ask the user via the AskUserQuestion tool, with sensible defaults framed by the brief:
-
-```text
-What should this be built on?
- - Astro (default for content-led brand sites, landing pages, marketing surfaces)
- - SvelteKit / Next.js / Nuxt (when the brief implies an app surface or significant interactivity)
- - Single index.html (one-shot demo, prototype, or a deliberately framework-free experiment)
-```
-
-Default: Astro for brand briefs, the project's existing framework for product briefs. Ask once; don't re-ask mid-task.
-
-## Step 1: Shape the Design
-
-Run /impeccable shape, passing along whatever feature description the user provided. Shape is **required** for craft; it is what produces a confirmed direction.
-
-Present the shape output and stop. Wait for the user to confirm, override, or course-correct before writing code.
-
-If the user already supplied a confirmed brief or ran shape separately, use it and skip this step.
-
-When the original prompt + PRODUCT.md already answer scope, content, and visual direction with no real ambiguity, the shape output can be **compact** (3-5 bullets stating what you're building and the visual lane, ending with one or two specific questions or "confirm or override"). The full 10-section structured brief is reserved for genuinely ambiguous, multi-screen, or stakeholder-heavy tasks. Don't pad a clear brief into a long one to look thorough; equally, don't skip the pause to look efficient.
-
-If the harness has native image generation (Codex), a compact shape's "confirm or override" advances to **Step 3 and the codex.md flow**, not to Step 4. Phrase the closing line accordingly: "Confirm or override; once we lock direction, I'll run a couple of palette and reference questions before generating any mocks." This stops the model from reading shape confirmation as code-green.
-
-## Step 2: Load References
-
-Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult:
-
-- [spatial-design.md](spatial-design.md) for layout and spacing
-- [typography.md](typography.md) for type hierarchy
-
-Then add references based on the brief's needs:
-- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md)
-- Animation or transitions? Consult [motion-design.md](motion-design.md)
-- Color-heavy or themed? Consult [color-and-contrast.md](color-and-contrast.md)
-- Responsive requirements? Consult [responsive-design.md](responsive-design.md)
-- Heavy on copy, labels, or errors? Consult [ux-writing.md](ux-writing.md)
-
-## Step 3: Visual Direction & Assets (Harness-Gated)
-
-If the harness has **native image generation** (currently Codex via `image_gen`), this step is mandatory. **Stop and load [codex.md](codex.md)**. It covers palette generation, mock exploration, the approval loop, mock-fidelity inventory, and asset slicing via the `impeccable_asset_producer` subagent. Follow Steps A-F in that file, then return here for Step 4.
-
-If the harness lacks native image generation, **state in one line that the visual-direction-by-generation step is being skipped because the harness lacks native image generation, then proceed**. The one-line announcement is required; it forces a conscious decision instead of letting the step quietly evaporate. The brief is your only visual reference. Implement directly from it, treating any named anchor references and the brief's "Design Direction" as the contract.
-
-Whether you generated mocks or not: don't replace required imagery with generic cards, bullets, emoji, fake metrics, decorative CSS panels, or filler copy. Image-led briefs (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product) need real or sourced imagery in the build, not CSS scenery.
-
-## Step 4: Build to Production Quality
-
-**Precondition.** If Step 3 routed you to codex.md (native image generation available), Steps A through D in that file must be complete before any code: questions answered, palette confirmed, mocks generated, one direction approved or delegated. **Do not mention implementation, file paths, or patch plans until that's done.** A confirmed shape brief is not enough; the model that compressed those gates is the model that already failed this flow.
-
-Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration.
-
-### Production bar
-
-- **Real content.** No placeholder copy, placeholder images, dead links, fake controls, or unused scaffold at presentation time.
-- **Preserve the approved mock's major ingredients.** Missing hero objects, world/product imagery, section structure, CTA/nav treatment, or distinctive motifs are blocking defects unless the user accepted the change.
-- **Semantic first.** Real headings, landmarks, labels, form associations, button/link semantics, accessible names, state announcements where needed.
-- **Deliberate spacing and alignment.** No default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment.
-- **Intentional typography.** Chosen loading strategy, clear hierarchy, readable measure, stable line breaks, no overflow at any width.
-- **Realistic state coverage.** Default, hover, focus-visible, active, disabled, loading, error, success, empty, overflow, long/short text, first-run.
-- **Finished interaction quality.** Keyboard paths, touch targets, feedback timing, scroll behavior, state transitions, no hover-only functionality.
-- **Coherent icon set.** Use the project's established set; otherwise pick one library or use accessible text. Don't mix.
-- **Respect the build pipeline.** Edit source files and run the project's build (`npm run build` or equivalent). Don't write to `build/` / `dist/` / `.next/` with `cat`, heredoc, or Bash redirects; that skips asset hashing, image optimization, code splitting, and CSS extraction, and produces output the dev server won't serve.
-- **Verify image URLs before referencing them.** Use image-search MCP or web-fetch when available; guessed photo IDs ship as broken-image placeholders. Without verification, prefer fewer images you're confident about.
-- **Optimized imagery and media.** Correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset`/`picture` for raster, no project-referenced asset left outside the workspace.
-- **Premium motion.** Use atmospheric blur, filter, mask, shadow, reveal when they improve the experience. Avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion.
-- **Maintainable.** Reusable local patterns, clear component boundaries, project conventions. No rasterized UI text or one-off hacks when a local pattern exists.
-- **Technically clean.** Production build passes, no console errors, no avoidable layout shift, no needless dependencies, no broken asset paths.
-- **Ask when uncertain.** If a discovery materially changes the brief or approved direction, stop and ask. Don't guess.
-
-## Step 5: Iterate Visually
-
-Look at what you built like a designer would. Your eyes are whatever the harness gives you: a connected browser, a screenshotting tool, Playwright, or asking the user. Use them for responsive testing (mobile, tablet, desktop minimum) and general visual validation.
-
-If your tool returns a file path, read the PNG back into the conversation. A screenshot you didn't read doesn't count.
-
-For long-form brand surfaces, inspect major sections individually. Thumbnails hide spacing, clipping, and cascade defects.
-
-After the first pass, write an honest critique against the brief, the approved mock's major ingredients (hero silhouette, motifs, imagery, nav/CTA, density), and impeccable's DON'Ts. Patch material defects and re-inspect. **Don't invent defects to demonstrate iteration.** A confident "first pass clean, shipping" beats a fake fix.
-
-Actively check: responsive behavior (composes, not shrinks), every state (empty / error / loading / edge), craft details (spacing, alignment, hierarchy, contrast, motion timing, focus), performance basics. The exit bar: defensible in a high-end studio review.
-
-Detector or QA output is defect evidence only; never proof the work is finished.
-
-## Step 6: Present
-
-Present the result to the user:
-- Show the feature in its primary state
-- Summarize the browser/viewports checked and the most important fixes made after inspection
-- Walk through the key states (empty, error, responsive)
-- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients.
-- Note any remaining limitations or follow-up risks honestly
-- Ask: "What's working? What isn't?"
@@ -1,236 +0,0 @@
-### Purpose
-
-Resolve one stable target, run two independent assessments, synthesize a design critique, persist a snapshot, and ask the user what to improve next. The chat response is the primary deliverable; the snapshot is an archive/backlog for future commands.
-
-### Hard Invariants
-
-- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
-- Assessment A must finish before detector findings enter the parent synthesis context. Detector output is deterministic, but it still anchors judgment.
-- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize.
-- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
-- Viewable targets require browser inspection when available.
-- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
-- Do not claim a user-visible overlay exists unless script injection succeeded and the detector ran in the page.
-
-### Setup
-
-1. **Resolve the target** to a concrete file path or URL. Prefer a source path over a dev-server URL when both identify the same surface; ports drift, paths do not.
- - "the homepage" -> `site/pages/index.astro` or `index.html`
- - "the settings modal" -> the primary component file
- - "this page" -> the current URL or source file
-2. **Compute the slug**:
- ```bash
- node .gemini/skills/impeccable/scripts/critique-storage.mjs slug "<resolved-path-or-url>"
- ```
- Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique.
-3. **Read `.impeccable/critique/ignore.md`** if it exists. Drop matching findings silently; it is the only prior-run input critique consumes.
-
-### Assessment Orchestration
-
-Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis.
-
-If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
-
-### Assessment A: Design Review
-
-Read relevant source files and visually inspect the live page when browser automation is available. Think like a design director.
-
-Evaluate:
-- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill.
-- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases.
-- **Cognitive load**: consult [cognitive-load](cognitive-load.md); report checklist failures and decision points with >4 visible options.
-- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments.
-- **Nielsen heuristics**: consult [heuristics-scoring](heuristics-scoring.md); score all 10 heuristics 0-4.
-
-Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions.
-
-### Assessment B: Detector + Browser Evidence
-
-Run the bundled detector and browser visualization evidence. Assessment B is mandatory and must remain isolated from Assessment A until both are complete.
-
-CLI scan:
-```bash
-node .gemini/skills/impeccable/scripts/detect.mjs --json [--fast] [target]
-```
-
-- Pass markup files/directories as `[target]`; do not pass CSS-only files.
-- For URLs, skip CLI scan and use browser visualization.
-- For 200+ scannable files, use `--fast`; for 500+, narrow scope or ask.
-- Exit code 0 = clean; 2 = findings.
-- If the detector entrypoint is missing or fails to load, report deterministic scan unavailable and continue with browser/manual review.
-
-Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
-
-1. Create a fresh tab and navigate.
-2. Preflight mutable injection by setting `document.title` and appending a `<script>` tag. Read-only evaluate APIs do not count.
-3. If mutation is unavailable, skip live server, browser presentation, and injection; report fallback signal.
-4. If mutation is available, start `node .gemini/skills/impeccable/scripts/live-server.mjs --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then stop the live server.
-5. For multi-view targets, inject on 3-5 representative pages.
-
-Return: CLI findings JSON/counts, browser console findings if applicable, false positives, and skipped/failed browser steps with concrete reasons.
-
-After Assessment B returns usable CLI findings, reuse them. Do not rerun `detect.mjs` in the parent unless Assessment B failed, was truncated, or omitted count, rule names, or file locations.
-
-### Generate Combined Critique Report
-
-Synthesize both assessments into a single report. Do NOT simply concatenate. Weave the findings together, noting where the LLM review and detector agree, where the detector caught issues the LLM missed, and where detector findings are false positives.
-
-The chat response is the primary user-facing deliverable. Present the full structured critique below in chat; do not replace it with a summary and a link. The persisted snapshot is only an archive/backlog for later commands.
-
-Structure your feedback as a design director would:
-
-#### Design Health Score
-> *Consult [heuristics-scoring](heuristics-scoring.md)*
-
-Present the Nielsen's 10 heuristics scores as a table:
-
-| # | Heuristic | Score | Key Issue |
-|---|-----------|-------|-----------|
-| 1 | Visibility of System Status | ? | [specific finding or "n/a" if solid] |
-| 2 | Match System / Real World | ? | |
-| 3 | User Control and Freedom | ? | |
-| 4 | Consistency and Standards | ? | |
-| 5 | Error Prevention | ? | |
-| 6 | Recognition Rather Than Recall | ? | |
-| 7 | Flexibility and Efficiency | ? | |
-| 8 | Aesthetic and Minimalist Design | ? | |
-| 9 | Error Recovery | ? | |
-| 10 | Help and Documentation | ? | |
-| **Total** | | **??/40** | **[Rating band]** |
-
-Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32.
-
-#### Anti-Patterns Verdict
-
-**Start here.** Does this look AI-generated?
-
-**LLM assessment**: Your own evaluation of AI slop tells. Cover overall aesthetic feel, layout sameness, generic composition, missed opportunities for personality.
-
-**Deterministic scan**: Summarize what the automated detector found, with counts and file locations. Note any additional issues the detector caught that you missed, and flag any false positives.
-
-**Visual overlays** (if injection succeeded): Tell the user that overlays are now visible in the **[Human]** tab in their browser, highlighting the detected issues. Summarize what the console output reported. If browser visualization was attempted but injection failed, say that no reliable user-visible overlay is available and report the fallback signal instead.
-
-#### Overall Impression
-A brief gut reaction: what works, what doesn't, and the single biggest opportunity.
-
-#### What's Working
-Highlight 2-3 things done well. Be specific about why they work.
-
-#### Priority Issues
-The 3-5 most impactful design problems, ordered by importance.
-
-For each issue, tag with **P0-P3 severity** (consult [heuristics-scoring](heuristics-scoring.md) for severity definitions):
-- **[P?] What**: Name the problem clearly
-- **Why it matters**: How this hurts users or undermines goals
-- **Fix**: What to do about it (be concrete)
-- **Suggested command**: Which command could address this (from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-#### Persona Red Flags
-> *Consult [personas](personas.md)*
-
-Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `GEMINI.md` contains a `## Design Context` section from `impeccable teach`, also generate 1-2 project-specific personas from the audience/brand info.
-
-For each selected persona, walk through the primary user action and list specific red flags found:
-
-**Alex (Power User)**: No keyboard shortcuts detected. Form requires 8 clicks for primary action. Forced modal onboarding. High abandonment risk.
-
-**Jordan (First-Timer)**: Icon-only nav in sidebar. Technical jargon in error messages ("404 Not Found"). No visible help. Will abandon at step 2.
-
-Be specific. Name the exact elements and interactions that fail each persona. Don't write generic persona descriptions; write what broke for them.
-
-#### Minor Observations
-Quick notes on smaller issues worth addressing.
-
-#### Questions to Consider
-Provocative questions that might unlock better solutions:
-- "What if the primary action were more prominent?"
-- "Does this need to feel this complex?"
-- "What would a confident version of this look like?"
-
-**Remember**:
-- Be direct. Vague feedback wastes everyone's time.
-- Be specific. "The submit button," not "some elements."
-- Say what's wrong AND why it matters to users.
-- Give concrete suggestions. Cut "consider exploring..." entirely.
-- Prioritize ruthlessly. If everything is important, nothing is.
-- Don't soften criticism. Developers need honest feedback to ship great design.
-
-### Persist the Snapshot
-
-Once the report above is finalized, write it to `.impeccable/critique/` so the user can refer back, and so `/impeccable polish` can pick up the priority issues without a copy-paste.
-
-Skip this step if the Setup slug was null (vague or root-level target).
-
-1. **Write the body to a temp file** so you can pipe it to the helper. Use the full critique report (heuristic table, anti-patterns verdict, priority issues, persona red flags, minor observations, and questions), but stop before the "Ask the User" / "Recommended Actions" sections that come later.
-
-2. **Pass the structured metadata** through `IMPECCABLE_CRITIQUE_META` (JSON), then run the write command:
- ```bash
- IMPECCABLE_CRITIQUE_META='{"target":"<user phrasing>","total_score":<n>,"p0_count":<n>,"p1_count":<n>}' \
- node .gemini/skills/impeccable/scripts/critique-storage.mjs write <slug> <body-file>
- ```
- The helper prints the absolute path it wrote.
-
-3. **Delete the temp body file** after the write attempt completes, whether the write succeeded or failed. If deletion fails, mention `temp-file cleanup failed: <reason>` briefly in the final output, but do not block the critique.
-
-4. **Read the trend** for context:
- ```bash
- node .gemini/skills/impeccable/scripts/critique-storage.mjs trend <slug> 5
- ```
- This returns a JSON array of the last 5 frontmatter entries (including the one you just wrote).
-
-5. **Append a single line to the user-visible output**, after the report and before the questions:
-
- > **Trend for `<slug>` (last 5 runs): 24 → 28 → 32 → 29 → 32**
- > Wrote `.impeccable/critique/<filename>`.
-
- If this is the first run for the slug, the trend is just one score; say so: "First run for this target, no trend yet."
-
-This is fire-and-forget. Do not show the user the helper's JSON output; only the human-readable trend line and the written path. Failures here should not block the rest of the flow; print the error and move on.
-
-### Ask the User
-
-**After presenting findings**, use targeted questions based on what was actually found. ask the user directly to clarify what you cannot infer. These answers will shape the action plan.
-
-Ask questions along these lines (adapt to the specific findings; do NOT ask generic questions):
-
-1. **Priority direction**: Based on the issues found, ask which category matters most to the user right now. For example: "I found problems with visual hierarchy, color usage, and information overload. Which area should we tackle first?" Offer the top 2-3 issue categories as options.
-
-2. **Design intent**: If the critique found a tonal mismatch, ask whether it was intentional. For example: "The interface feels clinical and corporate. Is that the intended tone, or should it feel warmer/bolder/more playful?" Offer 2-3 tonal directions as options based on what would fix the issues found.
-
-3. **Scope**: Ask how much the user wants to take on. For example: "I found N issues. Want to address everything, or focus on the top 3?" Offer scope options like "Top 3 only", "All issues", "Critical issues only".
-
-4. **Constraints** (optional; only ask if relevant): If the findings touch many areas, ask if anything is off-limits. For example: "Should any sections stay as-is?" This prevents the plan from touching things the user considers done.
-
-**Rules for questions**:
-- Every question must reference specific findings from the report. Never ask generic "who is your audience?" questions.
-- Keep it to 2-4 questions maximum. Respect the user's time.
-- Offer concrete options, not open-ended prompts.
-- If findings are straightforward (e.g., only 1-2 clear issues), skip questions and go directly to Recommended Actions.
-
-### Recommended Actions
-
-**After receiving the user's answers**, present a prioritized action summary reflecting the user's priorities and scope from Ask the User.
-
-#### Action Summary
-
-List recommended commands in priority order, based on the user's answers:
-
-1. **`/command-name`**: Brief description of what to fix (specific context from critique findings)
-2. **`/command-name`**: Brief description (specific context)
-...
-
-**Rules for recommendations**:
-- Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset
-- Order by the user's stated priorities first, then by impact
-- Each item's description should carry enough context that the command knows what to focus on
-- Map each Priority Issue to the appropriate command
-- Skip commands that would address zero issues
-- If the user chose a limited scope, only include items within that scope
-- If the user marked areas as off-limits, exclude commands that would touch those areas
-- End with `/impeccable polish` as the final step if any fixes were recommended
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable critique` after fixes to see your score improve.
@@ -1,302 +0,0 @@
-> **Additional context needed**: what's appropriate for the domain (playful vs professional vs quirky vs elegant).
-
-Find the moments where personality and unexpected polish would turn a functional interface into one users remember and tell other people about. Add only where the moment earns it; delight everywhere reads as noise.
-
----
-
-## Register
-
-Brand: delight can be distributed across copy voice, section transitions, discovery rewards, seasonal touches, personality across the whole surface.
-
-Product: delight at specific moments, not pages. Completion, first-time actions, error recovery, milestone crossings. Reliability and consistency carry the rest of the experience; delight pushed everywhere reads as noise.
-
----
-
-## Assess Delight Opportunities
-
-Identify where delight would enhance (not distract from) the experience:
-
-1. **Find natural delight moments**:
- - **Success states**: Completed actions (save, send, publish)
- - **Empty states**: First-time experiences, onboarding
- - **Loading states**: Waiting periods that could be entertaining
- - **Achievements**: Milestones, streaks, completions
- - **Interactions**: Hover states, clicks, drags
- - **Errors**: Softening frustrating moments
- - **Easter eggs**: Hidden discoveries for curious users
-
-2. **Understand the context**:
- - What's the brand personality? (Playful? Professional? Quirky? Elegant?)
- - Who's the audience? (Tech-savvy? Creative? Corporate?)
- - What's the emotional context? (Accomplishment? Exploration? Frustration?)
- - What's appropriate? (Banking app ≠ gaming app)
-
-3. **Define delight strategy**:
- - **Subtle sophistication**: Refined micro-interactions (luxury brands)
- - **Playful personality**: Whimsical illustrations and copy (consumer apps)
- - **Helpful surprises**: Anticipating needs before users ask (productivity tools)
- - **Sensory richness**: Satisfying sounds, smooth animations (creative tools)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Delight should enhance usability, never obscure it. If users notice the delight more than accomplishing their goal, you've gone too far.
-
-## Delight Principles
-
-Follow these guidelines:
-
-### Delight Amplifies, Never Blocks
-- Delight moments should be quick (< 1 second)
-- Never delay core functionality for delight
-- Make delight skippable or subtle
-- Respect user's time and task focus
-
-### Surprise and Discovery
-- Hide delightful details for users to discover
-- Reward exploration and curiosity
-- Don't announce every delight moment
-- Let users share discoveries with others
-
-### Appropriate to Context
-- Match delight to emotional moment (celebrate success, empathize with errors)
-- Respect the user's state (don't be playful during critical errors)
-- Match brand personality and audience expectations
-- Cultural sensitivity (what's delightful varies by culture)
-
-### Compound Over Time
-- Delight should remain fresh with repeated use
-- Vary responses (not same animation every time)
-- Reveal deeper layers with continued use
-- Build anticipation through patterns
-
-## Delight Techniques
-
-Add personality and joy through these methods:
-
-### Micro-interactions & Animation
-
-**Button delight**:
-```css
-/* Satisfying button press */
-.button {
- transition: transform 0.1s, box-shadow 0.1s;
-}
-.button:active {
- transform: translateY(2px);
- box-shadow: 0 2px 4px rgba(0,0,0,0.2);
-}
-
-/* Ripple effect on click */
-/* Smooth lift on hover */
-.button:hover {
- transform: translateY(-2px);
- transition: transform 0.2s cubic-bezier(0.25, 1, 0.5, 1); /* ease-out-quart */
-}
-```
-
-**Loading delight**:
-- Playful loading animations (not just spinners)
-- Personality in loading messages (write product-specific ones, not generic AI filler)
-- Progress indication with encouraging messages
-- Skeleton screens with subtle animations
-
-**Success animations**:
-- Checkmark draw animation
-- Confetti burst for major achievements
-- Gentle scale + fade for confirmation
-- Satisfying sound effects (subtle)
-
-**Hover surprises**:
-- Icons that animate on hover
-- Color shifts or glow effects
-- Tooltip reveals with personality
-- Cursor changes (custom cursors for branded experiences)
-
-### Personality in Copy
-
-**Playful error messages**:
-```
-"Error 404"
-"This page is playing hide and seek. (And winning)"
-
-"Connection failed"
-"Looks like the internet took a coffee break. Want to retry?"
-```
-
-**Encouraging empty states**:
-```
-"No projects"
-"Your canvas awaits. Create something amazing."
-
-"No messages"
-"Inbox zero! You're crushing it today."
-```
-
-**Playful labels & tooltips**:
-```
-"Delete"
-"Send to void" (for playful brand)
-
-"Help"
-"Rescue me" (tooltip)
-```
-
-**IMPORTANT**: Match copy personality to brand. Banks shouldn't be wacky, but they can be warm.
-
-### Illustrations & Visual Personality
-
-**Custom illustrations**:
-- Empty state illustrations (not stock icons)
-- Error state illustrations (friendly monsters, quirky characters)
-- Loading state illustrations (animated characters)
-- Success state illustrations (celebrations)
-
-**Icon personality**:
-- Custom icon set matching brand personality
-- Animated icons (subtle motion on hover/click)
-- Illustrative icons (more detailed than generic)
-- Consistent style across all icons
-
-**Background effects**:
-- Subtle particle effects
-- Gradient mesh backgrounds
-- Geometric patterns
-- Parallax depth
-- Time-of-day themes (morning vs night)
-
-### Satisfying Interactions
-
-**Drag and drop delight**:
-- Lift effect on drag (shadow, scale)
-- Snap animation when dropped
-- Satisfying placement sound
-- Undo toast ("Dropped in wrong place? [Undo]")
-
-**Toggle switches**:
-- Smooth slide with spring physics
-- Color transition
-- Haptic feedback on mobile
-- Optional sound effect
-
-**Progress & achievements**:
-- Streak counters with celebratory milestones
-- Progress bars that "celebrate" at 100%
-- Badge unlocks with animation
-- Playful stats ("You're on fire! 5 days in a row")
-
-**Form interactions**:
-- Input fields that animate on focus
-- Checkboxes with a satisfying scale pulse when checked
-- Success state that celebrates valid input
-- Auto-grow textareas
-
-### Sound Design
-
-**Subtle audio cues** (when appropriate):
-- Notification sounds (distinctive but not annoying)
-- Success sounds (satisfying "ding")
-- Error sounds (empathetic, not harsh)
-- Typing sounds for chat/messaging
-- Ambient background audio (very subtle)
-
-**IMPORTANT**:
-- Respect system sound settings
-- Provide mute option
-- Keep volumes quiet (subtle cues, not alarms)
-- Don't play on every interaction (sound fatigue is real)
-
-### Easter Eggs & Hidden Delights
-
-**Discovery rewards**:
-- Konami code unlocks special theme
-- Hidden keyboard shortcuts (Cmd+K for special features)
-- Hover reveals on logos or illustrations
-- Alt text jokes on images (for screen reader users too!)
-- Console messages for developers ("Like what you see? We're hiring!")
-
-**Seasonal touches**:
-- Holiday themes (subtle, tasteful)
-- Seasonal color shifts
-- Weather-based variations
-- Time-based changes (dark at night, light during day)
-
-**Contextual personality**:
-- Different messages based on time of day
-- Responses to specific user actions
-- Randomized variations (not same every time)
-- Progressive reveals with continued use
-
-### Loading & Waiting States
-
-**Make waiting engaging**:
-- Interesting loading messages that rotate
-- Progress bars with personality
-- Mini-games during long loads
-- Fun facts or tips while waiting
-- Countdown with encouraging messages
-
-```
-Loading messages: write ones specific to your product, not generic AI filler:
-- "Crunching your latest numbers..."
-- "Syncing with your team's changes..."
-- "Preparing your dashboard..."
-- "Checking for updates since yesterday..."
-```
-
-**WARNING**: Avoid cliched loading messages like "Herding pixels", "Teaching robots to dance", "Consulting the magic 8-ball", "Counting backwards from infinity". These are AI-slop copy, instantly recognizable as machine-generated. Write messages that are specific to what your product actually does.
-
-### Celebration Moments
-
-**Success celebrations**:
-- Confetti for major milestones
-- Animated checkmarks for completions
-- Progress bar celebrations at 100%
-- "Achievement unlocked" style notifications
-- Personalized messages ("You published your 10th article!")
-
-**Milestone recognition**:
-- First-time actions get special treatment
-- Streak tracking and celebration
-- Progress toward goals
-- Anniversary celebrations
-
-## Implementation Patterns
-
-**Animation libraries**:
-- Framer Motion (React)
-- GSAP (universal)
-- Lottie (After Effects animations)
-- Canvas confetti (party effects)
-
-**Sound libraries**:
-- Howler.js (audio management)
-- Use-sound (React hook)
-
-**Physics libraries**:
-- React Spring (spring physics)
-- Popmotion (animation primitives)
-
-**IMPORTANT**: File size matters. Compress images, optimize animations, lazy load delight features.
-
-**NEVER**:
-- Delay core functionality for delight
-- Force users through delightful moments (make skippable)
-- Use delight to hide poor UX
-- Overdo it (less is more)
-- Ignore accessibility (animate responsibly, provide alternatives)
-- Make every interaction delightful (special moments should be special)
-- Sacrifice performance for delight
-- Be inappropriate for context (read the room)
-
-## Verify Delight Quality
-
-Test that delight actually delights:
-
-- **User reactions**: Do users smile? Share screenshots?
-- **Doesn't annoy**: Still pleasant after 100th time?
-- **Doesn't block**: Can users opt out or skip?
-- **Performant**: No jank, no slowdown
-- **Appropriate**: Matches brand and context
-- **Accessible**: Works with reduced motion, screen readers
-
-When the moments feel earned, hand off to `/impeccable polish` for the final pass.
@@ -1,111 +0,0 @@
-Strip a design to its essence. Remove anything that doesn't earn its place: redundant elements, repeated information, decorative noise, cosmetic complexity.
-
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel complex or cluttered:
-
-1. **Identify complexity sources**:
- - **Too many elements**: Competing buttons, redundant information, visual clutter
- - **Excessive variation**: Too many colors, fonts, sizes, styles without purpose
- - **Information overload**: Everything visible at once, no progressive disclosure
- - **Visual noise**: Unnecessary borders, shadows, backgrounds, decorations
- - **Confusing hierarchy**: Unclear what matters most
- - **Feature creep**: Too many options, actions, or paths forward
-
-2. **Find the essence**:
- - What's the primary user goal? (There should be ONE)
- - What's actually necessary vs nice-to-have?
- - What can be removed, hidden, or combined?
- - What's the 20% that delivers 80% of value?
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Simplicity is not about removing features. It's about removing obstacles between users and their goals. Every element should justify its existence.
-
-## Plan Simplification
-
-Create a ruthless editing strategy:
-
-- **Core purpose**: What's the ONE thing this should accomplish?
-- **Essential elements**: What's truly necessary to achieve that purpose?
-- **Progressive disclosure**: What can be hidden until needed?
-- **Consolidation opportunities**: What can be combined or integrated?
-
-**IMPORTANT**: Simplification is hard. It requires saying no to good ideas to make room for great execution. Be ruthless.
-
-## Simplify the Design
-
-Systematically remove complexity across these dimensions:
-
-### Information Architecture
-- **Reduce scope**: Remove secondary actions, optional features, redundant information
-- **Progressive disclosure**: Hide complexity behind clear entry points (accordions, modals, step-through flows)
-- **Combine related actions**: Merge similar buttons, consolidate forms, group related content
-- **Clear hierarchy**: ONE primary action, few secondary actions, everything else tertiary or hidden
-- **Remove redundancy**: If it's said elsewhere, don't repeat it here
-
-### Visual Simplification
-- **Reduce color palette**: Use 1-2 colors plus neutrals, not 5-7 colors
-- **Limit typography**: One font family, 3-4 sizes maximum, 2-3 weights
-- **Remove decorations**: Eliminate borders, shadows, backgrounds that don't serve hierarchy or function
-- **Flatten structure**: Reduce nesting, remove unnecessary containers; never nest cards inside cards
-- **Remove unnecessary cards**: Cards aren't needed for basic layout; use spacing and alignment instead
-- **Consistent spacing**: Use one spacing scale, remove arbitrary gaps
-
-### Layout Simplification
-- **Linear flow**: Replace complex grids with simple vertical flow where possible
-- **Remove sidebars**: Move secondary content inline or hide it
-- **Full-width**: Use available space generously instead of complex multi-column layouts
-- **Consistent alignment**: Pick left or center, stick with it
-- **Generous white space**: Let content breathe, don't pack everything tight
-
-### Interaction Simplification
-- **Reduce choices**: Fewer buttons, fewer options, clearer path forward (paradox of choice is real)
-- **Smart defaults**: Make common choices automatic, only ask when necessary
-- **Inline actions**: Replace modal flows with inline editing where possible
-- **Remove steps**: Can signup be one step instead of three? Can checkout be simplified?
-- **Clear CTAs**: ONE obvious next step, not five competing actions
-
-### Content Simplification
-- **Shorter copy**: Cut every sentence in half, then do it again
-- **Active voice**: "Save changes" not "Changes will be saved"
-- **Remove jargon**: Plain language always wins
-- **Scannable structure**: Short paragraphs, bullet points, clear headings
-- **Essential information only**: Remove marketing fluff, legalese, hedging
-- **Remove redundant copy**: No headers restating intros, no repeated explanations, say it once
-
-### Code Simplification
-- **Remove unused code**: Dead CSS, unused components, orphaned files
-- **Flatten component trees**: Reduce nesting depth
-- **Consolidate styles**: Merge similar styles, use utilities consistently
-- **Reduce variants**: Does that component need 12 variations, or can 3 cover 90% of cases?
-
-**NEVER**:
-- Remove necessary functionality (simplicity ≠ feature-less)
-- Sacrifice accessibility for simplicity (clear labels and ARIA still required)
-- Make things so simple they're unclear (mystery ≠ minimalism)
-- Remove information users need to make decisions
-- Eliminate hierarchy completely (some things should stand out)
-- Oversimplify complex domains (match complexity to actual task complexity)
-
-## Verify Simplification
-
-Ensure simplification improves usability:
-
-- **Faster task completion**: Can users accomplish goals more quickly?
-- **Reduced cognitive load**: Is it easier to understand what to do?
-- **Still complete**: Are all necessary features still accessible?
-- **Clearer hierarchy**: Is it obvious what matters most?
-- **Better performance**: Does simpler design load faster?
-
-## Document Removed Complexity
-
-If you removed features or options:
-- Document why they were removed
-- Consider if they need alternative access points
-- Note any user feedback to monitor
-
-When the cuts feel right, hand off to `/impeccable polish` for the final pass. As Antoine de Saint-Exupéry put it: "Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away."
@@ -1,427 +0,0 @@
-Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
-
-DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
-
-## The frontmatter: token schema
-
-The YAML frontmatter is the machine-readable layer. It's what Stitch's linter validates and what the live panel renders tiles from. Keep it tight; every entry should correspond to a token the project actually uses.
-
-```yaml
----
-name: <project title>
-description: <one-line tagline>
-colors:
- primary: "#b8422e"
- neutral-bg: "#faf7f2"
- # ...one entry per extracted color; key = descriptive slug
-typography:
- display:
- fontFamily: "Cormorant Garamond, Georgia, serif"
- fontSize: "clamp(2.5rem, 7vw, 4.5rem)"
- fontWeight: 300
- lineHeight: 1
- letterSpacing: "normal"
- body:
- # ...
-rounded:
- sm: "4px"
- md: "8px"
-spacing:
- sm: "8px"
- md: "16px"
-components:
- button-primary:
- backgroundColor: "{colors.primary}"
- textColor: "{colors.neutral-bg}"
- rounded: "{rounded.sm}"
- padding: "16px 48px"
- button-primary-hover:
- backgroundColor: "{colors.primary-deep}"
----
-```
-
-Rules that matter:
-
-- **Token refs** use `{path.to.token}` (e.g. `{colors.primary}`, `{rounded.md}`). Components may reference primitives; primitives may not reference each other.
-- **Stitch validates colors as hex sRGB only** (`#RGB` / `#RGBA` / `#RRGGBB` / `#RRGGBBAA`); OKLCH/HSL/P3 trigger a linter warning, not a hard error. YAML accepts the string either way and our own parser is format-agnostic. Choose based on project posture: (a) if the project has an "OKLCH-only" doctrine or uses Display-P3 values that don't round-trip through sRGB, put OKLCH directly in the frontmatter and accept the Stitch linter warning; (b) if the project wants strict Stitch compliance or plans to use their Tailwind/DTCG export pipeline, put hex in the frontmatter and keep OKLCH in prose as the canonical reference. Never split the source of truth without explicit reason.
-- **Component sub-tokens** are limited to 8 props: `backgroundColor`, `textColor`, `typography`, `rounded`, `padding`, `size`, `height`, `width`. Shadows, motion, focus rings, backdrop-filter: none of those fit. Carry them in the sidecar (Step 4b).
-- **Scale keys are open-ended.** Use whatever names the project already uses (`warm-ash-cream`, `surface-container-low`). Don't rename to Material defaults.
-- **Variants are naming convention, not schema.** `button-primary` / `button-primary-hover` / `button-primary-active` as sibling keys.
-
-## The markdown body: six sections (exact order)
-
-1. `## Overview`
-2. `## Colors`
-3. `## Typography`
-4. `## Elevation`
-5. `## Components`
-6. `## Do's and Don'ts`
-
-Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] Palette` (Stitch's own outputs do this), but the literal word in each header (Overview, Colors, Typography, Elevation, Components, Do's and Don'ts) must be present. Do NOT add extra top-level sections (Layout Principles, Responsive Behavior, Motion, Agent Prompt Guide). Fold that content into the six spec sections where it naturally belongs.
-
-## When to run
-
-- The user just ran `/impeccable teach` and needs the visual side documented.
-- The skill noticed no `DESIGN.md` exists and nudged the user to create one.
-- An existing `DESIGN.md` is stale (the design has drifted).
-- Before a large redesign, to capture the current state as a reference.
-
-If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user the existing file and ask the user directly to clarify what you cannot infer. whether to refresh, overwrite, or merge.
-
-## Two paths
-
-- **Scan mode** (default): the project has design tokens, components, or rendered output. Extract, then confirm descriptive language. Use when there's code to analyze.
-- **Seed mode**: the project is pre-implementation (fresh teach, nothing built yet). Interview for five high-level answers, write a minimal DESIGN.md marked `<!-- SEED -->`. Re-run in scan mode once there's code.
-
-Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode; don't silently switch. `/impeccable document --seed` forces seed mode regardless of code presence.
-
-## Scan mode (approach C: auto-extract, then confirm descriptive language)
-
-### Step 1: Find the design assets
-
-Search the codebase in priority order:
-
-1. **CSS custom properties**: grep for `--color-`, `--font-`, `--spacing-`, `--radius-`, `--shadow-`, `--ease-`, `--duration-` declarations in CSS files (usually `src/styles/`, `public/css/`, `app/globals.css`, etc.). Record name, value, and the file it's defined in.
-2. **Tailwind config**: if `tailwind.config.{js,ts,mjs}` exists, read the `theme.extend` block for colors, fontFamily, spacing, borderRadius, boxShadow.
-3. **CSS-in-JS theme files**: styled-components, emotion, vanilla-extract, stitches; look for `theme.ts`, `tokens.ts`, or equivalent.
-4. **Design token files**: `tokens.json`, `design-tokens.json`, Style Dictionary output, W3C token community group format.
-5. **Component library**: scan the main button, card, input, navigation, dialog components. Note their variant APIs and default styles.
-6. **Global stylesheet**: the root CSS file usually has the base typography and color assignments.
-7. **Visible rendered output**: if browser automation tools are available, load the live site and sample computed styles from key elements (body, h1, a, button, .card). This catches values that tokens miss.
-
-### Step 2: Auto-extract what can be auto-extracted
-
-Build a structured draft from the discovered tokens. For each token class:
-
-- **Colors**: Group into Primary / Secondary / Tertiary / Neutral (the Material-derived roles Stitch uses). If the project only has one accent, express it as Primary + Neutral; omit Secondary and Tertiary rather than inventing them.
-- **Typography**: Map observed sizes and weights to the Material hierarchy (display / headline / title / body / label). Note font-family stacks and the scale ratio.
-- **Elevation**: Catalogue the shadow vocabulary. If the project is flat and uses tonal layering instead, that's a valid answer; state it explicitly.
-- **Components**: For each common component (button, card, input, chip, list item, tooltip, nav), extract shape (radius), color assignment, hover/focus treatment, internal padding.
-- **Spacing + layout**: Fold into Overview or relevant Components. The spec does NOT have a Layout section.
-
-### Step 2b: Stage the frontmatter
-
-From the auto-extracted tokens, draft the YAML frontmatter now (you'll write it at the top of DESIGN.md in Step 4). This is the machine-readable layer: what the live panel and Stitch's linter consume.
-
-- **Colors**: one entry per extracted color. Key = descriptive slug (`warm-ash-cream`, `editorial-magenta`, not `blue-800`). Value = whichever format the project treats as canonical (OKLCH or hex; see the frontmatter rules above). Don't split the source of truth: one format in the frontmatter, don't redefine the same token in prose with a different value.
-- **Typography**: one entry per role (`display`, `headline`, `title`, `body`, `label`). Typography is an object; include only the props that are real for the project (`fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `fontFeature`, `fontVariation`).
-- **Rounded / Spacing**: whatever scale steps the project actually uses, keyed by whatever scale name the project uses (`sm` / `md` / `lg`, or `surface-sm`, or numeric steps).
-- **Components**: one entry per variant (`button-primary`, `button-primary-hover`, `button-ghost`). Reference primitives via `{colors.X}`, `{rounded.Y}`. If a variant needs a property Stitch's 8-prop set doesn't cover (shadow, focus ring, backdrop-filter), carry the full snippet in the sidecar instead.
-
-Skip anything the project doesn't have. Empty scale keys or fabricated tokens pollute the spec.
-
-### Step 3: Ask the user for qualitative language
-
-The following require creative input that cannot be auto-extracted. Group them into one `AskUserQuestion` interaction:
-
-- **Creative North Star**: a single named metaphor for the whole system ("The Editorial Sanctuary", "The Golden State Curator", "The Lab Notebook"). Offer 2-3 options that honor PRODUCT.md's brand personality.
-- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, anti-references (what the system should not feel like).
-- **Color character** (for auto-extracted colors): descriptive names ("Deep Muted Teal-Navy", not "blue-800"). Suggest 2-3 options per key color based on hue/saturation.
-- **Elevation philosophy**: flat/layered/lifted. If shadows exist, is their role ambient or structural?
-- **Component philosophy**: the feel of buttons, cards, inputs in one phrase ("tactile and confident" vs. "refined and restrained").
-
-Quote a line from PRODUCT.md when possible so the user sees their own strategic language carry forward.
-
-### Step 4: Write DESIGN.md
-
-The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the structure below. Headers must match character-for-character. Optional evocative subtitles (e.g. `## 2. Colors: The Coastal Palette`) are allowed.
-
-```markdown
----
-name: [Project Title]
-description: [one-line tagline]
-colors:
- # ... staged frontmatter from Step 2b
----
-
-# Design System: [Project Title]
-
-## 1. Overview
-
-**Creative North Star: "[Named metaphor in quotes]"**
-
-[2-3 paragraph holistic description: personality, density, aesthetic philosophy. Start from the North Star and work outward. State what this system explicitly rejects (pulled from PRODUCT.md's anti-references). End with a short **Key Characteristics:** bullet list.]
-
-## 2. Colors
-
-[Describe the palette character in one sentence.]
-
-### Primary
-- **[Descriptive Name]** (#HEX / oklch(...)): [Where and why this color is used. Be specific about context, not just role.]
-
-### Secondary (optional; omit if the project has only one accent)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Tertiary (optional)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Neutral
-- **[Descriptive Name]** (#HEX): [Text / background / border / divider role.]
-- [...]
-
-### Named Rules (optional, powerful)
-**The [Rule Name] Rule.** [Short, forceful prohibition or doctrine, e.g. "The One Voice Rule. The primary accent is used on ≤10% of any given screen. Its rarity is the point."]
-
-## 3. Typography
-
-**Display Font:** [Family] (with [fallback])
-**Body Font:** [Family] (with [fallback])
-**Label/Mono Font:** [Family, if distinct]
-
-**Character:** [1-2 sentence personality description of the pairing.]
-
-### Hierarchy
-- **Display** ([weight], [size/clamp], [line-height]): [Purpose; where it appears.]
-- **Headline** ([weight], [size], [line-height]): [Purpose.]
-- **Title** ([weight], [size], [line-height]): [Purpose.]
-- **Body** ([weight], [size], [line-height]): [Purpose. Include max line length like 65–75ch if relevant.]
-- **Label** ([weight], [size], [letter-spacing], [case if uppercase]): [Purpose.]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [Short doctrine about type use.]
-
-## 4. Elevation
-
-[One paragraph: does this system use shadows, tonal layering, or a hybrid? If "no shadows", say so explicitly and describe how depth is conveyed instead.]
-
-### Shadow Vocabulary (if applicable)
-- **[Role name]** (`box-shadow: [exact value]`): [When to use it.]
-- [...]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [e.g. "The Flat-By-Default Rule. Surfaces are flat at rest. Shadows appear only as a response to state (hover, elevation, focus)."]
-
-## 5. Components
-
-For each component, lead with a short character line, then specify shape, color assignment, states, and any distinctive behavior.
-
-### Buttons
-- **Shape:** [radius described, exact value in parens]
-- **Primary:** [color assignment + padding, in semantic + exact terms]
-- **Hover / Focus:** [transitions, treatments]
-- **Secondary / Ghost / Tertiary (if applicable):** [brief description]
-
-### Chips (if used)
-- **Style:** [background, text color, border treatment]
-- **State:** [selected / unselected, filter / action variants]
-
-### Cards / Containers
-- **Corner Style:** [radius]
-- **Background:** [colors used]
-- **Shadow Strategy:** [reference Elevation section]
-- **Border:** [if any]
-- **Internal Padding:** [scale]
-
-### Inputs / Fields
-- **Style:** [stroke, background, radius]
-- **Focus:** [treatment, e.g. glow, border shift, etc.]
-- **Error / Disabled:** [if applicable]
-
-### Navigation
-- **Style, typography, default/hover/active states, mobile treatment.**
-
-### [Signature Component] (optional; if the project has a distinctive custom component worth documenting)
-[Description.]
-
-## 6. Do's and Don'ts
-
-Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: include exact colors, pixel values, and named anti-patterns the user mentioned in PRODUCT.md. **Every anti-reference in PRODUCT.md should show up here as a "Don't" with the same language**, so the visual spec carries the strategic line through. Quote PRODUCT.md directly where possible: if PRODUCT.md says *"avoid dark mode with purple gradients, neon accents, glassmorphism"*, the Don'ts here should repeat that by name.
-
-### Do:
-- **Do** [specific prescription with exact values / named rule].
-- **Do** [...]
-
-### Don't:
-- **Don't** [specific prohibition, e.g. "use border-left greater than 1px as a colored stripe"].
-- **Don't** [...]
-- **Don't** [...]
-```
-
-### Step 4b: Write .impeccable/design.json sidecar (extensions only)
-
-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.
-
-Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.
-
-#### Schema
-
-```json
-{
- "schemaVersion": 2,
- "generatedAt": "ISO-8601 string",
- "title": "Design System: [Project Title]",
- "extensions": {
- "colorMeta": {
- "primary": { "role": "primary", "displayName": "Editorial Magenta", "canonical": "oklch(60% 0.25 350)", "tonalRamp": ["...", "...", "..."] },
- "warm-ash-cream": { "role": "neutral", "displayName": "Warm Ash Cream", "canonical": "oklch(96% 0.005 350)", "tonalRamp": ["...", "...", "..."] }
- },
- "typographyMeta": {
- "display": { "displayName": "Display", "purpose": "Hero headlines only." }
- },
- "shadows": [
- { "name": "ambient-low", "value": "0 4px 24px rgba(0,0,0,0.12)", "purpose": "Diffuse hover glow under accent elements." }
- ],
- "motion": [
- { "name": "ease-standard", "value": "cubic-bezier(0.4, 0, 0.2, 1)", "purpose": "Default easing for state transitions." }
- ],
- "breakpoints": [
- { "name": "sm", "value": "640px" }
- ]
- },
- "components": [
- {
- "name": "Primary Button",
- "kind": "button | input | nav | chip | card | custom",
- "refersTo": "button-primary",
- "description": "One-line what and when.",
- "html": "<button class=\"ds-btn-primary\">GET STARTED</button>",
- "css": ".ds-btn-primary { background: #191c1d; color: #fff; padding: 16px 48px; letter-spacing: 0.05em; text-transform: uppercase; font-weight: 500; border: none; border-radius: 0; transition: background 0.2s, transform 0.2s; } .ds-btn-primary:hover { background: oklch(60% 0.25 350); transform: translateY(-2px); }"
- }
- ],
- "narrative": {
- "northStar": "The Editorial Sanctuary",
- "overview": "2-3 paragraphs of the philosophy, pulled from DESIGN.md Overview section.",
- "keyCharacteristics": ["...", "..."],
- "rules": [{ "name": "The One Voice Rule", "body": "...", "section": "colors|typography|elevation" }],
- "dos": ["Do use ..."],
- "donts": ["Don't use ..."]
- }
-}
-```
-
-**What changed from schemaVersion 1.** The old sidecar carried token primitive arrays (`tokens.colors[]`, `tokens.typography[]`, etc.). Those values now live in the frontmatter. The sidecar only carries metadata that can't live in the frontmatter (tonal ramps, canonical OKLCH when the hex is an approximation, display names, role hints), keyed by the frontmatter token name (`colorMeta.<token-name>`, `typographyMeta.<token-name>`). Components still carry full HTML/CSS because Stitch's 8-prop set can't hold them.
-
-#### Component translation rules
-
-The `html` and `css` fields must be **self-contained, drop-in snippets** that render correctly when injected into a shadow DOM. The panel applies them directly: no post-processing, no framework runtime.
-
-1. **Tailwind expansion.** If the source uses Tailwind (className="bg-primary text-white rounded-lg px-6 py-3"), expand every utility to literal CSS properties in the `css` string. Do **not** reference Tailwind classes; do **not** assume a Tailwind CSS bundle is loaded. Each component is self-contained.
-2. **Token resolution.** If the project exposes tokens as CSS custom properties on `:root` (e.g. `--color-primary`, `--radius-md`), reference them via `var(--color-primary)`; they inherit through the shadow DOM and stay live-bound. If tokens live only in JS theme objects (styled-components, CSS-in-JS), resolve to literal values at generation time.
-3. **Icons.** Inline as SVG. Do not reference Lucide/Heroicons packages, icon fonts, or `<img src="...">`. A typical icon is 16-24px; copy the SVG path data directly.
-4. **States.** Include `:hover`, `:focus-visible`, and (if meaningful) `:active` rules inline. A static default-only snapshot makes the panel feel dead. Hover + focus rules in the CSS make it feel alive.
-5. **Reset bloat.** Extract only the component's *distinctive* CSS (background, color, padding, border-radius, typography, transition). Skip universal resets (`box-sizing: border-box`, `line-height: inherit`, `-webkit-font-smoothing`). The panel already has a neutral canvas; don't re-ship resets.
-6. **Scoped class names.** Prefix every class with `ds-` (e.g. `ds-btn-primary`, `ds-input-search`) so component CSS doesn't collide with other components' CSS in the same shadow DOM.
-
-#### What to include
-
-Aim for a tight set of **5-10 components** that best represent the visual system:
-
-- **Canonical primitives (always include if the project has them):** button (each variant as a separate component entry), input/text field, navigation, chip/tag, card.
-- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.
-- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.
-
-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.
-
-#### Tonal ramps
-
-For each color token, generate an 8-step `tonalRamp` array: dark to light, same hue and chroma, stepped lightness from ~15% to ~95%. The panel renders this as a strip under the swatch. If the project already defines a tonal scale (Material `surface-container-low` family, Tailwind-style `blue-50..blue-900`), use those values. Otherwise synthesize in OKLCH.
-
-#### Narrative mapping
-
-Pull directly from the DESIGN.md you just wrote:
-
-- `narrative.northStar` → the `**Creative North Star: "..."**` line from Overview
-- `narrative.overview` → the philosophy paragraphs from Overview
-- `narrative.keyCharacteristics` → the bulleted `**Key Characteristics:**` list
-- `narrative.rules` → every `**The [Name] Rule.** [body]` across all sections, tagged with `section`
-- `narrative.dos` / `narrative.donts` → the bullet lists from Do's and Don'ts verbatim
-
-Do not reword. The panel shows these as secondary collapsible context; the same voice that's in the Markdown carries through.
-
-### Step 5: Confirm, refine, and refresh session cache
-
-1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).
-2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.
-3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"
-4. **Refresh the session cache.** Run `node .gemini/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.
-
-## Seed mode
-
-For projects with no visual system to extract yet. Produces a minimal scaffold, not a full spec.
-
-### Step 1: Confirm seed mode
-
-Before interviewing: "There's no existing visual system to scan. I'll ask five quick questions to seed a starter DESIGN.md. You can re-run `/impeccable document` once there's code, to capture the real tokens and components. OK?"
-
-If the user prefers to skip, stop. No file.
-
-### Step 2: Five questions
-
-Group into one `AskUserQuestion` interaction. Options must be concrete.
-
-1. **Color strategy.** Pick one:
- - Restrained: tinted neutrals + one accent ≤10%
- - Committed: one saturated color carries 30–60% of the surface
- - Full palette: 3–4 named color roles, each deliberate
- - Drenched: the surface IS the color
-
- Then: one hue family or anchor reference ("deep teal", "mustard", "Klim #ff4500 orange").
-
-2. **Typography direction.** Pick one (specific fonts come later):
- - Serif display + sans body
- - Single sans (warm / technical / geometric / humanist; pick a feel)
- - Display + mono
- - Mono-forward
- - Editorial script + sans
-
-3. **Motion energy.** Pick one:
- - Restrained: state changes only
- - Responsive: feedback + transitions, no choreography
- - Choreographed: orchestrated entrances, scroll-driven sequences
-
-4. **Three named references.** Brands, products, printed objects. Not adjectives.
-
-5. **One anti-reference.** What it should NOT feel like. Also named.
-
-### Step 3: Write seed DESIGN.md
-
-Use the six-section spec from Scan mode. Populate what the interview answers; leave the rest as honest placeholders. The seed is a scaffold, not a fabricated spec.
-
-Lead the file with:
-
-```markdown
-<!-- SEED: re-run /impeccable document once there's code to capture the actual tokens and components. -->
-```
-
-Per-section guidance in seed mode:
-
-- **Overview**: Creative North Star and philosophy phrased from the answers (color strategy + motion energy + references). Reference the user's anti-reference directly.
-- **Colors**: Color strategy as a Named Rule (e.g. *"The Drenched Rule. The surface IS the color."*). Hue family or anchor reference. No hex values; mark as `[to be resolved during implementation]`.
-- **Typography**: the direction the user picked (e.g. "Serif display + sans body"). No font names yet: `[font pairing to be chosen at implementation]`.
-- **Elevation**: inferred from motion energy. Restrained/Responsive → flat by default; Choreographed → layered. One sentence.
-- **Components**: omit entirely; no components exist yet.
-- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.
-
-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.
-
-### Step 4: Confirm and refresh session cache
-
-1. Show the seed DESIGN.md. Call out that it is a seed (the marker is the literal commitment).
-2. Tell the user: "Re-run `/impeccable document` once you have some code. That pass will extract real tokens and generate the sidecar."
-3. Run `node .gemini/skills/impeccable/scripts/load-context.mjs` once so the seed lands in conversation for the rest of the session.
-
-## Style guidelines
-
-- **Frontmatter first, prose second.** Tokens go in the YAML frontmatter; prose contextualizes them. Don't redefine a token value in two places; the frontmatter is normative.
-- **Cite PRODUCT.md anti-references by name** in the Do's and Don'ts section. If PRODUCT.md lists "SaaS landing-page clichés" or "generic AI tool marketing" as anti-references, the DESIGN.md Don'ts should repeat those phrases verbatim so the visual spec enforces the strategic line.
-- **Match the spec, don't invent new sections.** The six section names are fixed. If you have Layout/Motion/Responsive content to document, fold it into Overview (philosophy-level rules) or Components (per-component behavior).
-- **Descriptive > technical**: "Gently curved edges (8px radius)" > "rounded-lg". Include the technical value in parens, lead with the description.
-- **Functional > decorative**: for each token, explain WHERE and WHY it's used, not just WHAT it is.
-- **Exact values in parens**: hex codes, px/rem values, font weights; always the number in parens alongside the description.
-- **Use Named Rules**: `**The [Name] Rule.** [short doctrine]`. These are memorable, citable, and much stickier for AI consumers than bullet lists. Stitch's own outputs use them heavily ("The No-Line Rule", "The Ghost Border Fallback"). Aim for 1-3 per section.
-- **Be forceful**. The voice of a design director. "Prohibited", "forbidden", "never", "always", not "consider", "might", "prefer". Match PRODUCT.md's tone.
-- **Concrete anti-pattern tests**. Stitch writes things like *"If it looks like a 2014 app, the shadow is too dark and the blur is too small."* A one-sentence audit test beats a paragraph of principle.
-- **Reference PRODUCT.md**. The anti-references section of PRODUCT.md should directly inform the Do's and Don'ts section here. Quote or paraphrase.
-- **Group colors by role**, not by hex-order or hue-order. Primary / Secondary / Tertiary / Neutral is the spec ordering.
-
-## Pitfalls
-
-- Don't paste raw CSS class names. Translate to descriptive language.
-- Don't extract every token. Stop at what's actually reused; one-offs pollute the system.
-- Don't invent components that don't exist. If the project only has buttons and cards, only document those.
-- Don't overwrite an existing DESIGN.md without asking.
-- Don't duplicate content from PRODUCT.md. DESIGN.md is strictly visual.
-- Don't add a "Layout Principles" or "Motion" or "Responsive Behavior" top-level section. The spec has six, not nine. Fold that content where it belongs.
-- Don't rename sections even slightly. "Colors" not "Color Palette & Roles". "Typography" not "Typography Rules". Tooling parsing depends on exact headers.
-- Don't duplicate token values between frontmatter and prose. If a color is in `colors.primary` as hex, the prose can name it and describe its role but should not reassert a different hex. The frontmatter is normative.
-- Don't invent frontmatter token groups outside Stitch's schema (no `motion:`, `breakpoints:`, `shadows:` at the top level). Stitch's Zod schema only accepts `colors`, `typography`, `rounded`, `spacing`, `components`. Anything else belongs in the sidecar's `extensions`.
@@ -1,69 +0,0 @@
-# Extract Flow
-
-Identify reusable patterns, components, and design tokens, then extract and consolidate them into the design system for systematic reuse.
-
-## Step 1: Discover the Design System
-
-Find the design system, component library, or shared UI directory. Understand its structure: component organization, naming conventions, design token structure, import/export conventions.
-
-**CRITICAL**: If no design system exists, ask the user directly to clarify what you cannot infer. before creating one. Understand the preferred location and structure first.
-
-## Step 2: Identify Patterns
-
-Look for extraction opportunities in the target area:
-
-- **Repeated components**: Similar UI patterns used 3+ times (buttons, cards, inputs)
-- **Hard-coded values**: Colors, spacing, typography, shadows that should be tokens
-- **Inconsistent variations**: Multiple implementations of the same concept
-- **Composition patterns**: Layout or interaction patterns that repeat (form rows, toolbar groups, empty states)
-- **Type styles**: Repeated font-size + weight + line-height combinations
-- **Animation patterns**: Repeated easing, duration, or keyframe combinations
-
-Assess value: only extract things used 3+ times with the same intent. Premature abstraction is worse than duplication.
-
-## Step 3: Plan Extraction
-
-Create a systematic plan:
-
-- **Components to extract**: Which UI elements become reusable components?
-- **Tokens to create**: Which hard-coded values become design tokens?
-- **Variants to support**: What variations does each component need?
-- **Naming conventions**: Component names, token names, prop names that match existing patterns
-- **Migration path**: How to refactor existing uses to consume the new shared versions
-
-**IMPORTANT**: Design systems grow incrementally. Extract what is clearly reusable now, not everything that might someday be reusable.
-
-## Step 4: Extract & Enrich
-
-Build improved, reusable versions:
-
-- **Components**: Clear props API with sensible defaults, proper variants for different use cases, accessibility built in (ARIA, keyboard navigation, focus management), documentation and usage examples
-- **Design tokens**: Clear naming (primitive vs semantic), proper hierarchy and organization, documentation of when to use each token
-- **Patterns**: When to use this pattern, code examples, variations and combinations
-
-## Step 5: Migrate
-
-Replace existing uses with the new shared versions:
-
-- **Find all instances**: Search for the patterns you extracted
-- **Replace systematically**: Update each use to consume the shared version
-- **Test thoroughly**: Ensure visual and functional parity
-- **Delete dead code**: Remove the old implementations
-
-## Step 6: Document
-
-Update design system documentation:
-
-- Add new components to the component library
-- Document token usage and values
-- Add examples and guidelines
-- Update any Storybook or component catalog
-
-**NEVER**:
-- Extract one-off, context-specific implementations without generalization
-- Create components so generic they are useless
-- Extract without considering existing design system conventions
-- Skip proper TypeScript types or prop documentation
-- Create tokens for every single value (tokens should have semantic meaning)
-- Extract things that differ in intent (two buttons that look similar but serve different purposes should stay separate)
-
@@ -1,347 +0,0 @@
-Designs that only work with perfect data aren't production-ready. Harden the interface against the inputs, errors, languages, and network conditions that real users will throw at it.
-
-## Assess Hardening Needs
-
-Identify weaknesses and edge cases:
-
-1. **Test with extreme inputs**:
- - Very long text (names, descriptions, titles)
- - Very short text (empty, single character)
- - Special characters (emoji, RTL text, accents)
- - Large numbers (millions, billions)
- - Many items (1000+ list items, 50+ options)
- - No data (empty states)
-
-2. **Test error scenarios**:
- - Network failures (offline, slow, timeout)
- - API errors (400, 401, 403, 404, 500)
- - Validation errors
- - Permission errors
- - Rate limiting
- - Concurrent operations
-
-3. **Test internationalization**:
- - Long translations (German is often 30% longer than English)
- - RTL languages (Arabic, Hebrew)
- - Character sets (Chinese, Japanese, Korean, emoji)
- - Date/time formats
- - Number formats (1,000 vs 1.000)
- - Currency symbols
-
-**CRITICAL**: Designs that only work with perfect data aren't production-ready. Harden against reality.
-
-## Hardening Dimensions
-
-Systematically improve resilience:
-
-### Text Overflow & Wrapping
-
-**Long text handling**:
-```css
-/* Single line with ellipsis */
-.truncate {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* Multi-line with clamp */
-.line-clamp {
- display: -webkit-box;
- -webkit-line-clamp: 3;
- -webkit-box-orient: vertical;
- overflow: hidden;
-}
-
-/* Allow wrapping */
-.wrap {
- word-wrap: break-word;
- overflow-wrap: break-word;
- hyphens: auto;
-}
-```
-
-**Flex/Grid overflow**:
-```css
-/* Prevent flex items from overflowing */
-.flex-item {
- min-width: 0; /* Allow shrinking below content size */
- overflow: hidden;
-}
-
-/* Prevent grid items from overflowing */
-.grid-item {
- min-width: 0;
- min-height: 0;
-}
-```
-
-**Responsive text sizing**:
-- Use `clamp()` for fluid typography
-- Set minimum readable sizes (14px on mobile)
-- Test text scaling (zoom to 200%)
-- Ensure containers expand with text
-
-### Internationalization (i18n)
-
-**Text expansion**:
-- Add 30-40% space budget for translations
-- Use flexbox/grid that adapts to content
-- Test with longest language (usually German)
-- Avoid fixed widths on text containers
-
-```jsx
-// ❌ Bad: Assumes short English text
-<button className="w-24">Submit</button>
-
-// ✅ Good: Adapts to content
-<button className="px-4 py-2">Submit</button>
-```
-
-**RTL (Right-to-Left) support**:
-```css
-/* Use logical properties */
-margin-inline-start: 1rem; /* Not margin-left */
-padding-inline: 1rem; /* Not padding-left/right */
-border-inline-end: 1px solid; /* Not border-right */
-
-/* Or use dir attribute */
-[dir="rtl"] .arrow { transform: scaleX(-1); }
-```
-
-**Character set support**:
-- Use UTF-8 encoding everywhere
-- Test with Chinese/Japanese/Korean (CJK) characters
-- Test with emoji (they can be 2-4 bytes)
-- Handle different scripts (Latin, Cyrillic, Arabic, etc.)
-
-**Date/Time formatting**:
-```javascript
-// ✅ Use Intl API for proper formatting
-new Intl.DateTimeFormat('en-US').format(date); // 1/15/2024
-new Intl.DateTimeFormat('de-DE').format(date); // 15.1.2024
-
-new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: 'USD'
-}).format(1234.56); // $1,234.56
-```
-
-**Pluralization**:
-```javascript
-// ❌ Bad: Assumes English pluralization
-`${count} item${count !== 1 ? 's' : ''}`
-
-// ✅ Good: Use proper i18n library
-t('items', { count }) // Handles complex plural rules
-```
-
-### Error Handling
-
-**Network errors**:
-- Show clear error messages
-- Provide retry button
-- Explain what happened
-- Offer offline mode (if applicable)
-- Handle timeout scenarios
-
-```jsx
-// Error states with recovery
-{error && (
- <ErrorMessage>
- <p>Failed to load data. {error.message}</p>
- <button onClick={retry}>Try again</button>
- </ErrorMessage>
-)}
-```
-
-**Form validation errors**:
-- Inline errors near fields
-- Clear, specific messages
-- Suggest corrections
-- Don't block submission unnecessarily
-- Preserve user input on error
-
-**API errors**:
-- Handle each status code appropriately
- - 400: Show validation errors
- - 401: Redirect to login
- - 403: Show permission error
- - 404: Show not found state
- - 429: Show rate limit message
- - 500: Show generic error, offer support
-
-**Graceful degradation**:
-- Core functionality works without JavaScript
-- Images have alt text
-- Progressive enhancement
-- Fallbacks for unsupported features
-
-### Edge Cases & Boundary Conditions
-
-**Empty states**:
-- No items in list
-- No search results
-- No notifications
-- No data to display
-- Provide clear next action
-
-**Loading states**:
-- Initial load
-- Pagination load
-- Refresh
-- Show what's loading ("Loading your projects...")
-- Time estimates for long operations
-
-**Large datasets**:
-- Pagination or virtual scrolling
-- Search/filter capabilities
-- Performance optimization
-- Don't load all 10,000 items at once
-
-**Concurrent operations**:
-- Prevent double-submission (disable button while loading)
-- Handle race conditions
-- Optimistic updates with rollback
-- Conflict resolution
-
-**Permission states**:
-- No permission to view
-- No permission to edit
-- Read-only mode
-- Clear explanation of why
-
-**Browser compatibility**:
-- Polyfills for modern features
-- Fallbacks for unsupported CSS
-- Feature detection (not browser detection)
-- Test in target browsers
-
-### Input Validation & Sanitization
-
-**Client-side validation**:
-- Required fields
-- Format validation (email, phone, URL)
-- Length limits
-- Pattern matching
-- Custom validation rules
-
-**Server-side validation** (always):
-- Never trust client-side only
-- Validate and sanitize all inputs
-- Protect against injection attacks
-- Rate limiting
-
-**Constraint handling**:
-```html
-<!-- Set clear constraints -->
-<input
- type="text"
- maxlength="100"
- pattern="[A-Za-z0-9]+"
- required
- aria-describedby="username-hint"
-/>
-<small id="username-hint">
- Letters and numbers only, up to 100 characters
-</small>
-```
-
-### Accessibility Resilience
-
-**Keyboard navigation**:
-- All functionality accessible via keyboard
-- Logical tab order
-- Focus management in modals
-- Skip links for long content
-
-**Screen reader support**:
-- Proper ARIA labels
-- Announce dynamic changes (live regions)
-- Descriptive alt text
-- Semantic HTML
-
-**Motion sensitivity**:
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**High contrast mode**:
-- Test in Windows high contrast mode
-- Don't rely only on color
-- Provide alternative visual cues
-
-### Performance Resilience
-
-**Slow connections**:
-- Progressive image loading
-- Skeleton screens
-- Optimistic UI updates
-- Offline support (service workers)
-
-**Memory leaks**:
-- Clean up event listeners
-- Cancel subscriptions
-- Clear timers/intervals
-- Abort pending requests on unmount
-
-**Throttling & Debouncing**:
-```javascript
-// Debounce search input
-const debouncedSearch = debounce(handleSearch, 300);
-
-// Throttle scroll handler
-const throttledScroll = throttle(handleScroll, 100);
-```
-
-## Testing Strategies
-
-**Manual testing**:
-- Test with extreme data (very long, very short, empty)
-- Test in different languages
-- Test offline
-- Test slow connection (throttle to 3G)
-- Test with screen reader
-- Test keyboard-only navigation
-- Test on old browsers
-
-**Automated testing**:
-- Unit tests for edge cases
-- Integration tests for error scenarios
-- E2E tests for critical paths
-- Visual regression tests
-- Accessibility tests (axe, WAVE)
-
-**IMPORTANT**: Hardening is about expecting the unexpected. Real users will do things you never imagined.
-
-**NEVER**:
-- Assume perfect input (validate everything)
-- Ignore internationalization (design for global)
-- Leave error messages generic ("Error occurred")
-- Forget offline scenarios
-- Trust client-side validation alone
-- Use fixed widths for text
-- Assume English-length text
-- Block entire interface when one component errors
-
-## Verify Hardening
-
-Test thoroughly with edge cases:
-
-- **Long text**: Try names with 100+ characters
-- **Emoji**: Use emoji in all text fields
-- **RTL**: Test with Arabic or Hebrew
-- **CJK**: Test with Chinese/Japanese/Korean
-- **Network issues**: Disable internet, throttle connection
-- **Large datasets**: Test with 1000+ items
-- **Concurrent actions**: Click submit 10 times rapidly
-- **Errors**: Force API errors, test all error states
-- **Empty**: Remove all data, test empty states
-
-When edge cases are covered, hand off to `/impeccable polish` for the final pass.
@@ -1,234 +0,0 @@
-# Heuristics Scoring Guide
-
-Score each of Nielsen's 10 Usability Heuristics on a 0–4 scale. Be honest: a 4 means genuinely excellent, not "good enough."
-
-## Nielsen's 10 Heuristics
-
-### 1. Visibility of System Status
-
-Keep users informed about what's happening through timely, appropriate feedback.
-
-**Check for**:
-- Loading indicators during async operations
-- Confirmation of user actions (save, submit, delete)
-- Progress indicators for multi-step processes
-- Current location in navigation (breadcrumbs, active states)
-- Form validation feedback (inline, not just on submit)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No feedback; user is guessing what happened |
-| 1 | Rare feedback; most actions produce no visible response |
-| 2 | Partial; some states communicated, major gaps remain |
-| 3 | Good; most operations give clear feedback, minor gaps |
-| 4 | Excellent; every action confirms, progress is always visible |
-
-### 2. Match Between System and Real World
-
-Speak the user's language. Follow real-world conventions. Information appears in natural, logical order.
-
-**Check for**:
-- Familiar terminology (no unexplained jargon)
-- Logical information order matching user expectations
-- Recognizable icons and metaphors
-- Domain-appropriate language for the target audience
-- Natural reading flow (left-to-right, top-to-bottom priority)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Pure tech jargon, alien to users |
-| 1 | Mostly confusing; requires domain expertise to navigate |
-| 2 | Mixed; some plain language, some jargon leaks through |
-| 3 | Mostly natural; occasional term needs context |
-| 4 | Speaks the user's language fluently throughout |
-
-### 3. User Control and Freedom
-
-Users need a clear "emergency exit" from unwanted states without extended dialogue.
-
-**Check for**:
-- Undo/redo functionality
-- Cancel buttons on forms and modals
-- Clear navigation back to safety (home, previous)
-- Easy way to clear filters, search, selections
-- Escape from long or multi-step processes
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Users get trapped; no way out without refreshing |
-| 1 | Difficult exits; must find obscure paths to escape |
-| 2 | Some exits; main flows have escape, edge cases don't |
-| 3 | Good control; users can exit and undo most actions |
-| 4 | Full control; undo, cancel, back, and escape everywhere |
-
-### 4. Consistency and Standards
-
-Users shouldn't wonder whether different words, situations, or actions mean the same thing.
-
-**Check for**:
-- Consistent terminology throughout the interface
-- Same actions produce same results everywhere
-- Platform conventions followed (standard UI patterns)
-- Visual consistency (colors, typography, spacing, components)
-- Consistent interaction patterns (same gesture = same behavior)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Inconsistent everywhere; feels like different products stitched together |
-| 1 | Many inconsistencies; similar things look/behave differently |
-| 2 | Partially consistent; main flows match, details diverge |
-| 3 | Mostly consistent; occasional deviation, nothing confusing |
-| 4 | Fully consistent; cohesive system, predictable behavior |
-
-### 5. Error Prevention
-
-Better than good error messages is a design that prevents problems in the first place.
-
-**Check for**:
-- Confirmation before destructive actions (delete, overwrite)
-- Constraints preventing invalid input (date pickers, dropdowns)
-- Smart defaults that reduce errors
-- Clear labels that prevent misunderstanding
-- Autosave and draft recovery
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Errors easy to make; no guardrails anywhere |
-| 1 | Few safeguards; some inputs validated, most aren't |
-| 2 | Partial prevention; common errors caught, edge cases slip |
-| 3 | Good prevention; most error paths blocked proactively |
-| 4 | Excellent; errors nearly impossible through smart constraints |
-
-### 6. Recognition Rather Than Recall
-
-Minimize memory load. Make objects, actions, and options visible or easily retrievable.
-
-**Check for**:
-- Visible options (not buried in hidden menus)
-- Contextual help when needed (tooltips, inline hints)
-- Recent items and history
-- Autocomplete and suggestions
-- Labels on icons (not icon-only navigation)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Heavy memorization; users must remember paths and commands |
-| 1 | Mostly recall; many hidden features, few visible cues |
-| 2 | Some aids; main actions visible, secondary features hidden |
-| 3 | Good recognition; most things discoverable, few memory demands |
-| 4 | Everything discoverable; users never need to memorize |
-
-### 7. Flexibility and Efficiency of Use
-
-Accelerators, invisible to novices, speed up expert interaction.
-
-**Check for**:
-- Keyboard shortcuts for common actions
-- Customizable interface elements
-- Recent items and favorites
-- Bulk/batch actions
-- Power user features that don't complicate the basics
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | One rigid path; no shortcuts or alternatives |
-| 1 | Limited flexibility; few alternatives to the main path |
-| 2 | Some shortcuts; basic keyboard support, limited bulk actions |
-| 3 | Good accelerators; keyboard nav, some customization |
-| 4 | Highly flexible; multiple paths, power features, customizable |
-
-### 8. Aesthetic and Minimalist Design
-
-Interfaces should not contain irrelevant or rarely needed information. Every element should serve a purpose.
-
-**Check for**:
-- Only necessary information visible at each step
-- Clear visual hierarchy directing attention
-- Purposeful use of color and emphasis
-- No decorative clutter competing for attention
-- Focused, uncluttered layouts
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Overwhelming; everything competes for attention equally |
-| 1 | Cluttered; too much noise, hard to find what matters |
-| 2 | Some clutter; main content clear, periphery noisy |
-| 3 | Mostly clean; focused design, minor visual noise |
-| 4 | Perfectly minimal; every element earns its pixel |
-
-### 9. Help Users Recognize, Diagnose, and Recover from Errors
-
-Error messages should use plain language, precisely indicate the problem, and constructively suggest a solution.
-
-**Check for**:
-- Plain language error messages (no error codes for users)
-- Specific problem identification ("Email is missing @" not "Invalid input")
-- Actionable recovery suggestions
-- Errors displayed near the source of the problem
-- Non-blocking error handling (don't wipe the form)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Cryptic errors; codes, jargon, or no message at all |
-| 1 | Vague errors; "Something went wrong" with no guidance |
-| 2 | Clear but unhelpful; names the problem but not the fix |
-| 3 | Clear with suggestions; identifies problem and offers next steps |
-| 4 | Perfect recovery; pinpoints issue, suggests fix, preserves user work |
-
-### 10. Help and Documentation
-
-Even if the system is usable without docs, help should be easy to find, task-focused, and concise.
-
-**Check for**:
-- Searchable help or documentation
-- Contextual help (tooltips, inline hints, guided tours)
-- Task-focused organization (not feature-organized)
-- Concise, scannable content
-- Easy access without leaving current context
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No help available anywhere |
-| 1 | Help exists but hard to find or irrelevant |
-| 2 | Basic help; FAQ or docs exist, not contextual |
-| 3 | Good documentation; searchable, mostly task-focused |
-| 4 | Excellent contextual help; right info at the right moment |
-
----
-
-## Score Summary
-
-**Total possible**: 40 points (10 heuristics × 4 max)
-
-| Score Range | Rating | What It Means |
-|-------------|--------|---------------|
-| 36–40 | Excellent | Minor polish only; ship it |
-| 28–35 | Good | Address weak areas, solid foundation |
-| 20–27 | Acceptable | Significant improvements needed before users are happy |
-| 12–19 | Poor | Major UX overhaul required; core experience broken |
-| 0–11 | Critical | Redesign needed; unusable in current state |
-
----
-
-## Issue Severity (P0–P3)
-
-Tag each individual issue found during scoring with a priority level:
-
-| Priority | Name | Description | Action |
-|----------|------|-------------|--------|
-| **P0** | Blocking | Prevents task completion entirely | Fix immediately; this is a showstopper |
-| **P1** | Major | Causes significant difficulty or confusion | Fix before release |
-| **P2** | Minor | Annoyance, but workaround exists | Fix in next pass |
-| **P3** | Polish | Nice-to-fix, no real user impact | Fix if time permits |
-
-**Tip**: If you're unsure between two levels, ask: "Would a user contact support about this?" If yes, it's at least P1.
@@ -1,195 +0,0 @@
-# Interaction Design
-
-## The Eight Interactive States
-
-Every interactive element needs these states designed:
-
-| State | When | Visual Treatment |
-|-------|------|------------------|
-| **Default** | At rest | Base styling |
-| **Hover** | Pointer over (not touch) | Subtle lift, color shift |
-| **Focus** | Keyboard/programmatic focus | Visible ring (see below) |
-| **Active** | Being pressed | Pressed in, darker |
-| **Disabled** | Not interactive | Reduced opacity, no pointer |
-| **Loading** | Processing | Spinner, skeleton |
-| **Error** | Invalid state | Red border, icon, message |
-| **Success** | Completed | Green check, confirmation |
-
-**The common miss**: Designing hover without focus, or vice versa. They're different. Keyboard users never see hover states.
-
-## Focus Rings: Do Them Right
-
-**Never `outline: none` without replacement.** It's an accessibility violation. Instead, use `:focus-visible` to show focus only for keyboard users:
-
-```css
-/* Hide focus ring for mouse/touch */
-button:focus {
- outline: none;
-}
-
-/* Show focus ring for keyboard */
-button:focus-visible {
- outline: 2px solid var(--color-accent);
- outline-offset: 2px;
-}
-```
-
-**Focus ring design**:
-- High contrast (3:1 minimum against adjacent colors)
-- 2-3px thick
-- Offset from element (not inside it)
-- Consistent across all interactive elements
-
-## Form Design: The Non-Obvious
-
-**Placeholders aren't labels.** They disappear on input. Always use visible `<label>` elements. **Validate on blur**, not on every keystroke (exception: password strength). Place errors **below** fields with `aria-describedby` connecting them.
-
-## Loading States
-
-**Optimistic updates**: Show success immediately, rollback on failure. Use for low-stakes actions (likes, follows), not payments or destructive actions. **Skeleton screens > spinners**: they preview content shape and feel faster than generic spinners.
-
-## Modals: The Inert Approach
-
-Focus trapping in modals used to require complex JavaScript. Now use the `inert` attribute:
-
-```html
-<!-- When modal is open -->
-<main inert>
- <!-- Content behind modal can't be focused or clicked -->
-</main>
-<dialog open>
- <h2>Modal Title</h2>
- <!-- Focus stays inside modal -->
-</dialog>
-```
-
-Or use the native `<dialog>` element:
-
-```javascript
-const dialog = document.querySelector('dialog');
-dialog.showModal(); // Opens with focus trap, closes on Escape
-```
-
-## The Popover API
-
-For tooltips, dropdowns, and non-modal overlays, use native popovers:
-
-```html
-<button popovertarget="menu">Open menu</button>
-<div id="menu" popover>
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-**Benefits**: Light-dismiss (click outside closes), proper stacking, no z-index wars, accessible by default.
-
-## Dropdown & Overlay Positioning
-
-Dropdowns rendered with `position: absolute` inside a container that has `overflow: hidden` or `overflow: auto` will be clipped. This is the single most common dropdown bug in generated code.
-
-### CSS Anchor Positioning
-
-The modern solution uses the CSS Anchor Positioning API to tether an overlay to its trigger without JavaScript:
-
-```css
-.trigger {
- anchor-name: --menu-trigger;
-}
-
-.dropdown {
- position: fixed;
- position-anchor: --menu-trigger;
- position-area: block-end span-inline-end;
- margin-top: 4px;
-}
-
-/* Flip above if no room below */
-@position-try --flip-above {
- position-area: block-start span-inline-end;
- margin-bottom: 4px;
-}
-```
-
-Because the dropdown uses `position: fixed`, it escapes any `overflow` clipping on ancestor elements. The `@position-try` block handles viewport edges automatically. **Browser support**: Chrome 125+, Edge 125+. Not yet in Firefox or Safari - use a fallback for those browsers.
-
-### Popover + Anchor Combo
-
-Combining the Popover API with anchor positioning gives you stacking, light-dismiss, accessibility, and correct positioning in one pattern:
-
-```html
-<button popovertarget="menu" class="trigger">Open</button>
-<div id="menu" popover class="dropdown">
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-The `popover` attribute places the element in the **top layer**, which sits above all other content regardless of z-index or overflow. No portal needed.
-
-### Portal / Teleport Pattern
-
-In component frameworks, render the dropdown at the document root and position it with JavaScript:
-
-- **React**: `createPortal(dropdown, document.body)`
-- **Vue**: `<Teleport to="body">`
-- **Svelte**: Use a portal library or mount to `document.body`
-
-Calculate position from the trigger's `getBoundingClientRect()`, then apply `position: fixed` with `top` and `left` values. Recalculate on scroll and resize.
-
-### Fixed Positioning Fallback
-
-For browsers without anchor positioning support, `position: fixed` with manual coordinates avoids overflow clipping:
-
-```css
-.dropdown {
- position: fixed;
- /* top/left set via JS from trigger's getBoundingClientRect() */
-}
-```
-
-Check viewport boundaries before rendering. If the dropdown would overflow the bottom edge, flip it above the trigger. If it would overflow the right edge, align it to the trigger's right side instead.
-
-### Anti-Patterns
-
-- **`position: absolute` inside `overflow: hidden`** - The dropdown will be clipped. Use `position: fixed` or the top layer instead.
-- **Arbitrary z-index values** like `z-index: 9999` - Use a semantic z-index scale: `dropdown (100) -> sticky (200) -> modal-backdrop (300) -> modal (400) -> toast (500) -> tooltip (600)`.
-- **Rendering dropdown markup inline** without an escape hatch from the parent's stacking context. Either use `popover` (top layer), a portal, or `position: fixed`.
-
-## Destructive Actions: Undo > Confirm
-
-**Undo is better than confirmation dialogs.** Users click through confirmations mindlessly. Remove from UI immediately, show undo toast, actually delete after toast expires. Use confirmation only for truly irreversible actions (account deletion), high-cost actions, or batch operations.
-
-## Keyboard Navigation Patterns
-
-### Roving Tabindex
-
-For component groups (tabs, menu items, radio groups), one item is tabbable; arrow keys move within:
-
-```html
-<div role="tablist">
- <button role="tab" tabindex="0">Tab 1</button>
- <button role="tab" tabindex="-1">Tab 2</button>
- <button role="tab" tabindex="-1">Tab 3</button>
-</div>
-```
-
-Arrow keys move `tabindex="0"` between items. Tab moves to the next component entirely.
-
-### Skip Links
-
-Provide skip links (`<a href="#main-content">Skip to main content</a>`) for keyboard users to jump past navigation. Hide off-screen, show on focus.
-
-## Gesture Discoverability
-
-Swipe-to-delete and similar gestures are invisible. Hint at their existence:
-
-- **Partially reveal**: Show delete button peeking from edge
-- **Onboarding**: Coach marks on first use
-- **Alternative**: Always provide a visible fallback (menu with "Delete")
-
-Don't rely on gestures as the only way to perform actions.
-
----
-
-**Avoid**: Removing focus indicators without alternatives. Using placeholder text as labels. Touch targets <44x44px. Generic error messages. Custom controls without ARIA/keyboard support.
@@ -1,141 +0,0 @@
-Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids, the centered-stack default) and fix the structure, not the surface.
-
----
-
-## Register
-
-Brand: asymmetric compositions, fluid spacing with `clamp()`, intentional grid-breaking for emphasis. Rhythm through contrast: tight groupings paired with generous separations.
-
-Product: predictable grids, consistent densities, familiar navigation patterns. Responsive behavior is structural (collapse sidebar, responsive table), not fluid typography. Consistency IS an affordance.
-
----
-
-## Assess Current Layout
-
-Analyze what's weak about the current spatial design:
-
-1. **Spacing**:
- - Is spacing consistent or arbitrary? (Random padding/margin values)
- - Is all spacing the same? (Equal padding everywhere = no rhythm)
- - Are related elements grouped tightly, with generous space between groups?
-
-2. **Visual hierarchy**:
- - Apply the squint test: blur your (metaphorical) eyes. Can you still identify the most important element, second most important, and clear groupings?
- - Is hierarchy achieved effectively? (Space and weight alone can be enough; is the current approach working?)
- - Does whitespace guide the eye to what matters?
-
-3. **Grid & structure**:
- - Is there a clear underlying structure, or does the layout feel random?
- - Are identical card grids used everywhere? (Icon + heading + text, repeated endlessly)
- - Is everything centered? (Left-aligned with asymmetric layouts feels more designed, but not a hard and fast rule)
-
-4. **Rhythm & variety**:
- - Does the layout have visual rhythm? (Alternating tight/generous spacing)
- - Is every section structured the same way? (Monotonous repetition)
- - Are there intentional moments of surprise or emphasis?
-
-5. **Density**:
- - Is the layout too cramped? (Not enough breathing room)
- - Is the layout too sparse? (Excessive whitespace without purpose)
- - Does density match the content type? (Data-dense UIs need tighter spacing; marketing pages need more air)
-
-**CRITICAL**: Layout problems are often the root cause of interfaces feeling "off" even when colors and fonts are fine. Space is a design material; use it with intention.
-
-## Plan Layout Improvements
-
-Consult the [spatial design reference](spatial-design.md) for detailed guidance on grids, rhythm, and container queries.
-
-Create a systematic plan:
-
-- **Spacing system**: Use a consistent scale (a framework's built-in scale like Tailwind's, rem-based tokens, or a custom system). The specific values matter less than consistency.
-- **Hierarchy strategy**: How will space communicate importance?
-- **Layout approach**: What structure fits the content? Flex for 1D, Grid for 2D, named areas for complex page layouts.
-- **Rhythm**: Where should spacing be tight vs generous?
-
-## Improve Layout Systematically
-
-### Establish a Spacing System
-
-- Use a consistent spacing scale (framework scales like Tailwind, rem-based tokens, or a custom scale all work). What matters is that values come from a defined set, not arbitrary numbers.
-- Name tokens semantically if using custom properties: `--space-xs` through `--space-xl`, not `--spacing-8`
-- Use `gap` for sibling spacing instead of margins; eliminates margin collapse hacks
-- Apply `clamp()` for fluid spacing that breathes on larger screens
-
-### Create Visual Rhythm
-
-- **Tight grouping** for related elements (8-12px between siblings)
-- **Generous separation** between distinct sections (48-96px)
-- **Varied spacing** within sections (not every row needs the same gap)
-- **Asymmetric compositions**: break the predictable centered-content pattern when it makes sense
-
-### Choose the Right Layout Tool
-
-- **Use Flexbox for 1D layouts**: Rows of items, nav bars, button groups, card contents, most component internals. Flex is simpler and more appropriate for the majority of layout tasks.
-- **Use Grid for 2D layouts**: Page-level structure, dashboards, data-dense interfaces, anything where rows AND columns need coordinated control.
-- **Don't default to Grid** when Flexbox with `flex-wrap` would be simpler and more flexible.
-- Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints.
-- Use named grid areas (`grid-template-areas`) for complex page layouts; redefine at breakpoints.
-
-### Break Card Grid Monotony
-
-- Don't default to card grids for everything; spacing and alignment create visual grouping naturally
-- Use cards only when content is truly distinct and actionable. Never nest cards inside cards
-- Vary card sizes, span columns, or mix cards with non-card content to break repetition
-
-### Strengthen Visual Hierarchy
-
-- Use the fewest dimensions needed for clear hierarchy. Space alone can be enough; generous whitespace around an element draws the eye. Some of the most polished designs achieve rhythm with just space and weight. Add color or size contrast only when simpler means aren't sufficient.
-- Be aware of reading flow: in LTR languages, the eye naturally scans top-left to bottom-right, but primary action placement depends on context (e.g., bottom-right in dialogs, top in navigation).
-- Create clear content groupings through proximity and separation.
-
-### Manage Depth & Elevation
-
-- Create a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip)
-- Build a consistent shadow scale (sm → md → lg → xl); shadows should be subtle
-- Use elevation to reinforce hierarchy, not as decoration
-
-### Optical Adjustments
-
-- If an icon looks visually off-center despite being geometrically centered, nudge it. But only if you're confident it actually looks wrong. Don't adjust speculatively.
-
-**NEVER**:
-- Use arbitrary spacing values outside your scale
-- Make all spacing equal (variety creates hierarchy)
-- Wrap everything in cards (not everything needs a container)
-- Nest cards inside cards (use spacing and dividers for hierarchy within)
-- Use identical card grids everywhere (icon + heading + text, repeated)
-- Center everything (left-aligned with asymmetry feels more designed)
-- Default to the hero metric layout (big number, small label, stats, gradient) as a template. If showing real user data, a prominent metric can work, but it should display actual data, not decorative numbers.
-- Default to CSS Grid when Flexbox would be simpler; use the simplest tool for the job
-- Use arbitrary z-index values (999, 9999); build a semantic scale
-
-## Verify Layout Improvements
-
-- **Squint test**: Can you identify primary, secondary, and groupings with blurred vision?
-- **Rhythm**: Does the page have a satisfying beat of tight and generous spacing?
-- **Hierarchy**: Is the most important content obvious within 2 seconds?
-- **Breathing room**: Does the layout feel comfortable, not cramped or wasteful?
-- **Consistency**: Is the spacing system applied uniformly?
-- **Responsiveness**: Does the layout adapt gracefully across screen sizes?
-
-When the rhythm and hierarchy land, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `density` param. Drive all spacing tokens in the variant's scoped CSS through `calc(var(--p-density, 1) * <base>)`: paddings, gaps, column widths. Users slide from airy to packed and see layout re-breathe with no regeneration.
-
-```json
-{"id":"density","kind":"range","min":0.6,"max":1.4,"step":0.05,"default":1,"label":"Density"}
-```
-
-For variants whose topology genuinely changes (stacked vs. side-by-side, grid vs. bento), use a `steps` param whose scoped CSS branches via `:scope[data-p-structure="X"]`. One structure param + one density param is a powerful combo; resist adding a third.
-
-```json
-{"id":"structure","kind":"steps","default":"grid","label":"Structure","options":[
- {"value":"stacked","label":"Stacked"},
- {"value":"grid","label":"Grid"},
- {"value":"bento","label":"Bento"}
-]}
-```
-
-See `reference/live.md` for the full params contract.
@@ -1,622 +0,0 @@
-Interactive live variant mode: select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via the dev server's HMR.
-
-## Prerequisites
-
-A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR a static HTML file open in the browser.
-
-## The contract (read once)
-
-Execute in order. No step skipped, no step reordered.
-
-1. `live.mjs`: boot.
-2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.
-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.
-5. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
-6. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
-7. On `exit`: run the cleanup at the bottom.
-
-Harness policy:
-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.
-- **Cursor**: run the poll in the **foreground** (blocking shell; not a background terminal, not a subagent). Cursor background terminals and subagents do not reliably resume the chat with poll stdout.
-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.
-- **Other harnesses**: foreground unless you know stdout reliably returns to this session.
-
-Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.
-
-## Start
-
-```bash
-node .gemini/skills/impeccable/scripts/live.mjs
-```
-
-Output JSON: `{ ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath, migrated }`. `pageFiles` is the list of HTML entries the live script was injected into. Keep PRODUCT.md and DESIGN.md in mind for variant generation; **DESIGN.md wins on visual decisions; PRODUCT.md wins on strategic/voice decisions.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt. If `migrated: true`, the loader auto-renamed legacy `.impeccable.md` to `PRODUCT.md`; mention this once and suggest `/impeccable document` for the matching DESIGN.md.
-
-`serverPort` and `serverToken` belong to the small **Impeccable live helper** HTTP server (serves `/live.js`, SSE, and `/poll`). That port is **not** your dev server and is usually not the URL you open to view the app. The browser page is whatever origin serves one of the `pageFiles` entries (Vite / Next / Bun / tunnel / LAN hostname).
-
-If output is `{ ok: false, error: "config_missing" | "config_invalid", path }`, this project hasn't been configured for live mode (or its config is stale). See **First-time setup** at the bottom.
-
-## Poll loop
-
-```
-LOOP:
- node .gemini/skills/impeccable/scripts/live-poll.mjs # default long timeout; no --timeout=
- Read JSON; dispatch on "type"
-
- "generate" → Handle Generate; reply done; LOOP
- "accept" → Handle Accept; complete carbonize cleanup if required; LOOP
- "discard" → Handle Discard; LOOP
- "prefetch" → Handle Prefetch; LOOP
- "timeout" → LOOP
- "exit" → break → Cleanup
-```
-
-## Recovery commands
-
-The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.
-
-Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:
-
-```bash
-node .gemini/skills/impeccable/scripts/live-status.mjs
-node .gemini/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID
-node .gemini/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID
-```
-
-- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.
-- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.
-- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.
-
-Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.
-
-## Handle `generate`
-
-Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.
-
-Speed matters; the user is watching a spinner. Minimize tool calls by using the `wrap` helper and writing all variants in a single edit.
-
-### 1. Read the screenshot (if present)
-
-`event.screenshotPath` is **only sent when the user placed at least one comment or stroke before Go.** When present, it's an absolute path to a PNG of the element as rendered with the annotations baked in. **Read it before planning**: annotations encode user intent not recoverable from `element.outerHTML` alone.
-
-When `screenshotPath` is absent, don't ask for one and don't go looking for the current rendering. The omission is deliberate: without annotations, a screenshot would anchor the model on the existing design and fight the three-distinct-directions brief. Work from `element.outerHTML`, the computed styles in `event.element`, and the freeform prompt if present.
-
-`event.comments` and `event.strokes` carry structured metadata alongside the visual. Treat the screenshot as primary; use the structured data for specifics worth quoting (e.g. the exact text of a comment).
-
-Reading annotations precisely:
-
-- **Comment position carries meaning.** Its `{x, y}` is element-local CSS px (same coord space as `element.boundingRect`). Find the child under that point and apply the comment text LOCALLY to that sub-element. A comment near the title is about the title, not a global description.
-- **Comments and strokes are independent annotations** unless clearly paired by overlap or tight proximity. Don't let the visual weight of a prominent stroke override the precise location of a textually-specific comment elsewhere.
-- **Strokes are gestures; read them by shape.** Closed loop = "this thing" (emphasis / focus); arrow = direction (move / point to); cross or slash = delete; free scribble = emphasis or delete depending on context. A loop around region X means "pay attention to X," not "only change pixels inside X."
-- **When a stroke's intent is ambiguous** (circle or arrow? emphasis or move?), state your reading in one sentence of rationale rather than silently guessing. If the uncertainty materially changes the brief, ask one short clarifying question before generating.
-
-### 2. Wrap the element
-
-```bash
-node .gemini/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"
-```
-
-Flag mapping. Keep them separate, don't collapse into `--query`:
-
-- `--element-id` ← `event.element.id`
-- `--classes` ← `event.element.classes` joined with commas
-- `--tag` ← `event.element.tagName`
-- `--text` ← first ~80 chars of `event.element.textContent` (trim, single-line). **Pass this every call.** When the picked element shares classes + tag with sibling components (a list of `<Card>`s, repeating sections), this is what disambiguates which branch in source to wrap. Without it, wrap silently lands on the first match and may rewrite the wrong element.
-
-The helper searches ID first, then classes, then tag + class combo. If `event.pageUrl` implies the file (e.g. `/` is usually `index.html`), pass `--file PATH` to skip the search. `--query` is a fallback for raw text search only; do not use it for normal element lookups.
-
-If `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.
-
-Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.
-
-`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:
-
-- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.
-- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.
-
-Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.
-
-**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:
-
-- `{ error: "file_is_generated", file, hint }`: user-supplied `--file` points at a generated file.
-- `{ error: "element_not_in_source", generatedMatch, hint }`: element exists only in a generated file (the next build would wipe any edits).
-- `{ error: "element_not_found", hint }`: element isn't in any project file; likely runtime-injected (JS component, dynamic render from data).
-
-All three carry `fallback: "agent-driven"`. Follow **Handle fallback** below.
-
-### 3. Load the action's reference
-
-If `event.action` is `impeccable` (the default freeform action), use SKILL.md's shared laws plus the loaded register reference (`brand.md` or `product.md`). Do not load a sub-command reference. **Freeform is not a pass to skip parameters:** you still follow the composition budget and the freeform bias in **§7 Parameters** below. Sub-command files list MUST-have signature knobs; freeform has no such file, so sizing knobs from surface weight and primary axes is entirely on you.
-
-Any other `event.action` (`bolder`, `quieter`, `distill`, `polish`, `typeset`, `colorize`, `layout`, `adapt`, `animate`, `delight`, `overdrive`): Read `reference/<action>.md` before planning. Each sub-command encodes a specific discipline; skipping its reference produces generic output. Those files may require specific params; layer them on top of the §7 budget, not instead of it.
-
-### 4. Plan three variants: identity first, then mode, then axes
-
-The wrong frame for live mode is "show three different design directions." Live runs on an existing surface; the brand has already been chosen. The job is variation **within identity**, not selection between identities. Failure mode: three editorial-typographic variants on a brief that wasn't editorial. Bigger failure mode: three off-brand variants the user can't accept because they don't look like their product.
-
-Four phases. Do them in order.
-
-#### Phase A: Extract the identity (non-skippable)
-
-The existing surface has an identity already. Read it before planning anything. Sources, in priority order:
-
-1. **DESIGN.md** if loaded: read the visual system fields (palette, type pairing, motion, components). This is the authoritative answer.
-2. **CSS custom properties** in the page's stylesheets (`:root { --color-...; --font-...; ... }`): these are de-facto tokens.
-3. **Computed styles** on the picked element and its parent: colors, fonts, spacing scales, corner radii.
-4. **Sibling components on the page**: what visual rhetoric do existing components use? (Asymmetric or centered? Dense or airy? Bold or quiet?)
-
-Write down what you see in **one sentence**. The sentence describes the surface that's actually on screen; it is not aspirational, not opinionated, not edited toward what the brand "should" be. Capture, in roughly this order:
-
-- The dominant surface color and accent color, by hex or token name (use the actual values, not categories like "warm" or "neutral").
-- The type pairing: the actual font names loaded, primary first.
-- The layout topology: how the dominant elements are arranged (stacked / side-by-side / grid / asymmetric / overlay).
-- The surface treatment: corners, borders, shadows, density of decoration.
-- The voice tone you read off the copy itself, not off the aesthetic feel.
-
-Be specific. "Modern" is not a color, "elegant" is not a type pairing, "clean" is not a layout. If you can't extract a real value for an axis, skip it rather than fabricate. The point is to record what is, not to describe what you wish it were.
-
-Do not include adjectives that name an aesthetic family ("editorial-leaning", "terminal-flavored", "brutalist"); those are conclusions, not data. They belong to Phase C lane selection in departure mode, not to identity description. Letting them sneak into Phase A is how the identity-lock collapses into a self-fulfilling prophecy.
-
-This sentence is the **identity lock**. Every variant must be readable as the same brand if rendered side by side. Skipping this phase is the primary cause of off-brand variants. Absence of DESIGN.md is never an excuse; extract from CSS and computed styles instead.
-
-#### Phase B: Pick mode (default vs departure)
-
-**Default mode**: the existing identity is preserved. Variants vary expression axes within it. *This is the right mode for ~90% of live sessions.* The user picked an element on a real product they're shipping; they expect variants of *their* hero, not three different brands' heroes.
-
-**Departure mode**: the existing identity is rejected. Variants propose alternatives consistent with PRODUCT.md voice. Trigger only when at least one is true:
-
-- PRODUCT.md anti-references explicitly call out the current surface ("the current `index.html` is itself an example"; "diffuse away from this"; "the page on screen is the failure"). Generic anti-references that describe what to avoid in general do **not** trigger departure mode; only ones that point at *this* surface specifically.
-- The user's freeform prompt explicitly asks for departure ("rebuild this from scratch", "what if it weren't editorial at all", "show me something completely different").
-
-If you're unsure, you're in default mode. The cost of being wrong about default is "three on-brand variants with similar feel": recoverable, the user picks none. The cost of being wrong about departure is "three off-brand variants": unrecoverable, the user is annoyed.
-
-#### Phase C: Plan three variants
-
-**Default mode.** Each variant commits to a different **primary axis** of difference, while preserving the identity sentence. The six axes:
-
-1. **Hierarchy**: which element commands the eye?
-2. **Layout topology**: stacked / side-by-side / grid / asymmetric / overlay
-3. **Typographic system**: pairing logic, scale ratio, case/weight strategy *within the available faces*
-4. **Color strategy**: which existing palette role carries the surface (Restrained / Committed / Full palette / Drenched). Use the brand's existing palette tokens, not new colors.
-5. **Density**: minimal / comfortable / dense
-6. **Structural decomposition**: merge, split, progressive disclosure
-
-Three variants → three DIFFERENT axes. The trio reads as *the same brand at three angles*. Do not introduce new fonts, new palette hues, or new aesthetic-family signals; those belong to departure mode.
-
-**While planning each variant, also name its 2–3 parameter knobs** (per the §7 budget table). Parameters are part of the design, not a decoration added afterward. If the variant explores density, expose a density knob. If it explores color commitment, expose a color-amount range. Deciding "what's tunable" during planning produces better knobs than retrofitting them onto finished HTML.
-
-**Departure mode.** Each variant anchors to a different **aesthetic direction**, derived from the brand's stated voice and register in PRODUCT.md. Do NOT pick from a fixed catalog of lane categories. The right three directions for this brand are not the same as the right three for another brand, and picking from a list is itself the training-data reflex (the model selects "Swiss-grid, Terminal, Industrial-signage" every time because those are the furthest-from-editorial items in any enumerated list).
-
-Instead, work from the brand:
-
-1. Read PRODUCT.md's Brand Personality words. What physical, spatial, or material experiences would embody those words if design were not involved? (A personality described as "specific, earned, unmistakable" evokes a hand-stamped letter, a numbered print, a watchmaker's loupe. A personality described as "restless, loud, unfiltered" evokes a concert poster, a spray-painted wall, a megaphone.)
-2. From those physical experiences, derive three visual directions that are genuinely different from each other AND from the current surface you're departing.
-3. Avoid the **reflex-reject lanes** in [brand.md](brand.md). Don't trade one monoculture for another. If you find yourself reaching for "Swiss-grid" or "Terminal" or "Industrial-signage" by reflex, you are pattern-matching a catalog in your training data, not reading the brand. Start over from the personality words.
-4. Each direction must be expressible in one concrete sentence that names a real-world referent ("a museum exhibition label system for a contemporary art gallery" not "clean and minimal"). If your sentence contains only adjectives, it's not concrete enough.
-5. **While planning each direction, also name its 2–3 parameter knobs** (per the §7 budget table). The same principle as default mode: decide "what's tunable" during planning, not after writing the HTML. A departure-mode hero with 0 parameters is not "bold creative vision," it's a missed opportunity for the user to fine-tune the direction they pick.
-
-#### Phase D: Squint test
-
-**Default mode squint.** Read each variant's identity sentence and compare to the locked identity from Phase A. If any variant has drifted to a different palette, type voice, or visual rhetoric, it has crossed into departure mode by accident; rework. Then check that each variant commits to a different primary axis. Three "tighter density" variants is failure.
-
-**Departure mode squint.** Two passes, family before sentence:
-
-1. **Family pass.** Label each variant with one design-family word of your own choosing (any concrete noun: *exhibition, storefront, cockpit, recipe-card, playbill, field-manual*). If any two variants share a label, or if the label could apply to the other variants equally well, rework. Do not use a fixed vocabulary list for the labels. *This pass is non-negotiable in departure mode and catches the monoculture failure that the sentence pass misses.*
-2. **Sentence pass.** Write three one-sentence descriptions side by side. If two of them rhyme ("both feature big type" / "both are stacks of sections" / "both center the CTA"), rework the offender.
-
-**When the primary axis is color or theme, forbid the trio from sharing theme + dominant hue.** Two dark-plus-one-dark is not distinct. Aim for three color worlds, not three shades of the same.
-
-**For action-specific invocations**, each variant must vary along the dimension the action names:
-
-- `bolder`: amplify a different dimension per variant (scale / saturation / structural change). Not three "slightly bigger" variants.
-- `quieter`: pull back a different dimension (color / ornament / spacing).
-- `distill`: remove a different class of excess (visual noise / redundant content / nested structure).
-- `polish`: target a different refinement axis (rhythm / hierarchy / micro-details like corner radii, focus states, optical kerning).
-- `typeset`: different type pairing AND different scale ratio each. Not three riffs on one pairing.
-- `colorize`: different hue family each (not shades of one hue). Vary chroma and contrast strategy.
-- `layout`: different structural arrangement (stacked / side-by-side / grid / asymmetric). Not spacing tweaks.
-- `adapt`: different target context per variant (mobile-first / tablet / desktop / print or low-data). Don't make three mobile layouts.
-- `animate`: different motion vocabulary (cascade stagger / clip wipe / scale-and-focus / morph / parallax). Not three staggered fades.
-- `delight`: different flavor of personality (unexpected micro-interaction / typographic surprise / illustrated accent / sonic-or-haptic moment / easter-egg interaction).
-- `overdrive`: different convention broken (scale / structure / motion / input model / state transitions). Skip `overdrive.md`'s "propose and ask" step; live mode is non-interactive.
-
-### 5. Apply the freeform prompt (if present)
-
-`event.freeformPrompt` is the user's ceiling on direction (all variants must honor it), but still explore meaningfully different *interpretations*. The interpretations stay within whichever mode you picked in Phase B.
-
-In **default mode**, the prompt narrows the axes you choose, not the identity. *"Make it feel more confident"* → variant 1 amplifies hierarchy (one element commands the eye), variant 2 commits the existing accent color (Committed strategy on the brand's hue), variant 3 tightens density and removes decorative slack. Three different axes, same brand.
-
-In **departure mode**, the prompt narrows the lanes you draw from, not the families. *"Make it feel like a newspaper front page"* would itself be a departure-mode prompt; honor it but pick three meaningfully different newspaper-adjacent lanes (broadsheet vs. tabloid vs. trade journal), and run the family pass to confirm they don't collapse into one.
-
-When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.
-
-### 6. Write all variants in a single edit
-
-Complete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).
-
-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).
-
-Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:
-
-```html
-<!-- Variants: insert below this line -->
-<style data-impeccable-css="SESSION_ID">
- /* rules matching cssAuthoring.rulePattern */
-</style>
-<div data-impeccable-variant="1">
- <!-- variant 1: full element replacement (single top-level element) -->
-</div>
-<div data-impeccable-variant="2" style="display: none">
- <!-- variant 2: full element replacement -->
-</div>
-<div data-impeccable-variant="3" style="display: none">
- <!-- variant 3: full element replacement -->
-</div>
-```
-
-**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.
-
-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.
-
-One edit, all variants; the browser's MutationObserver picks everything up in one pass.
-
-For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.
-
-**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:
-
-```tsx
-<style data-impeccable-css="SESSION_ID">{`
- @scope ([data-impeccable-variant="1"]) { ... }
- @scope ([data-impeccable-variant="2"]) { ... }
-`}</style>
-<div data-impeccable-variant="1">
- {/* variant 1 */}
-</div>
-<div data-impeccable-variant="2" style={{ display: 'none' }}>
- {/* variant 2 */}
-</div>
-```
-
-The wrap script already gives you a single-rooted JSX wrapper: a `<div data-impeccable-variants="…">` outer element with the marker comments tucked inside. Drop the variants block above into the "Variants: insert below this line" comment and the source stays valid TSX.
-
-### 7. Parameters (composition-sized, 0–4 per variant)
-
-Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement. The browser docks a small panel to the right of the outline with one control per parameter. The user drags/clicks and sees instant feedback: there is zero regeneration cost because the knob toggles a CSS variable or data attribute that the variant's scoped CSS is already authored against.
-
-**What “optional” does not mean.** Parameters are not nice-to-have decoration on large work. The word meant “omit controls that are redundant or cosmetic,” not “default to zero because three variants were enough work.”
-
-**When to add.** As soon as the variant’s scoped CSS has a meaningful continuous or stepped axis: density, color amount, type scale, motion intensity, column weight, and so on. If you can imagine the user muttering “a bit tighter” or “a touch more accent” **without** wanting a full regeneration, wire that axis. **Not** micro-margins or one-off nudges; those are not parameters.
-
-**Freeform (`action` is `impeccable`) bias.** You did not load a sub-command reference, so you must **choose** signature axes yourself. Match the budget table: for a hero or large composition, that means **2–3 axes per variant**, not 1. Prefer knobs that sit on the dimensions where your three variants actually differ (if density varies, expose it as a `steps` knob; if color commitment varies, expose it as a `range`). A hero that ships with **0** params is almost always a mistake, not a judgment call. A hero with exactly **1** param is underweight unless the design is genuinely a fixed-point comparison. Start from the budget table, not from zero.
-
-**Budget scales with the element's visual weight, not token budget.** Knobs need real estate to read as tunable; three sliders on a single control are noise.
-
-- **Leaf / tiny**: a single button, icon, input, bare heading, solitary paragraph: **0 params.**
-- **Small composition**: labeled input, simple card, short callout (≤ ~5 visual children): **0–1** params when one dominant axis is obvious; otherwise **0.**
-- **Medium composition**: section component, nav cluster, dense card, short feature block (6–15 visual children): **target 2**; **1** is acceptable if the block is simple; **0** only when variants are truly fixed points.
-- **Large composition**: hero section, full page region, spread layout, strong internal structure (16+ visual children or multiple sub-sections): **target 2–3**; **up to 4** when several independent axes (e.g. structure `steps` + `density` + one accent) are all authored in scoped CSS.
-
-**When in doubt, ask whether a dial exists before defaulting to zero.** The user can always request more variants, but the point of live mode is instant tuning without another Go. Crowding the panel is bad; **under-shipping** knobs on a dense composition is the more common failure for freeform. Count by **visual** children, not DOM depth; a shallow-but-wide hero is still large.
-
-**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.
-
-**How to declare.** Put a JSON manifest on the variant wrapper:
-
-```html
-<div data-impeccable-variant="1" data-impeccable-params='[
- {"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"},
- {"id":"density","kind":"steps","default":"snug","label":"Density","options":[
- {"value":"airy","label":"Airy"},
- {"value":"snug","label":"Snug"},
- {"value":"packed","label":"Packed"}
- ]},
- {"id":"serif","kind":"toggle","default":false,"label":"Serif display"}
-]'>
- ...variant content...
-</div>
-```
-
-**Three kinds:**
-
-- `range`: smooth slider. Drives a CSS custom property `--p-<id>` on the variant wrapper. Author CSS with `var(--p-color-amount, 0.5)`. Fields: `min`, `max`, `step`, `default` (number), `label`.
-- `steps`: segmented radio. Drives a data attribute `data-p-<id>` on the variant wrapper. Author CSS with `:scope[data-p-density="airy"] .grid { ... }`. Fields: `options` (array of `{value, label}`), `default` (string), `label`.
-- `toggle`: on/off switch. Drives BOTH a CSS var (`--p-<id>: 0|1`) and a data attribute (present when on, absent when off). Use whichever is more convenient. Fields: `default` (boolean), `label`.
-
-**Signature params per action.** For named sub-commands, read that action’s `reference/<action>.md` for one or two **MUST** params (e.g. `layout` → `density`). Those are non-negotiable when the design can express them. **Freeform has no file-level MUST**; the **Freeform (`impeccable`) bias** in this section is the stand-in. If the user’s action is both stylized and sub-command (e.g. `colorize`), the sub-command’s MUST list takes precedence for its axes; still respect the **Hard cap** and add no redundant duplicate knobs.
-
-**Reset on variant switch.** User dials density on v1, flips to v2, v2 starts at v2's declared defaults. Known limitation; preservation across variants may land later.
-
-**On accept**, the browser sends the user's current values in the accept event. `live-accept.mjs` writes them as a sibling comment:
-
-```html
-<!-- impeccable-param-values SESSION_ID: {"color-amount":0.7,"density":"packed"} -->
-```
-
-The carbonize cleanup step (see below) reads that comment and bakes the chosen values into the final CSS. For `steps`/`toggle` attribute selectors: keep only the branch matching the chosen value, drop the others, collapse `:scope[data-p-density="packed"] .grid` to a semantic class rule. For `range` vars: either substitute the literal or keep the var with the chosen value as its new default.
-
-### 8. Signal done
-
-```bash
-node .gemini/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
-```
-
-`RELATIVE_PATH` is relative to project root (`public/index.html`, `src/App.tsx`, etc.); the browser fetches source directly if the dev server lacks HMR.
-
-Then run `live-poll.mjs` again immediately.
-
-### Aborting an in-flight session
-
-If wrap or generation fails after the browser has flipped to GENERATING (e.g. wrap landed on the wrong source branch and you've already reverted it, or generation hit an unrecoverable error), tell the **browser** so its bar resets to PICKING:
-
-```bash
-node .gemini/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID error "Short reason"
-```
-
-Don't run `live-accept --discard` for this; that's a pure file mutator, the browser doesn't see it, and the bar gets stuck on the GENERATING dots forever (the user has to refresh). `--discard` is only correct when the **browser** initiated the discard (user clicked ✕ during CYCLING) and the agent is just running source-side cleanup the browser already triggered.
-
-## Handle fallback
-
-When wrap returns `fallback: "agent-driven"`, the deterministic flow doesn't apply. Pick up here.
-
-The goal is the same: give the user three variants to choose from AND persist the accepted one in a place the next build won't wipe. The difference is that you have to pick the right source file yourself.
-
-### Step 1: Identify where the element actually lives
-
-Use the error payload:
-
-- `element_not_in_source` with `generatedMatch: "public/docs/foo.html"`: the served HTML is generated. Find the generator (grep for writers of that path, e.g. `scripts/build-sub-pages.js`, an Astro/Next template) and locate the template or partial that emits this element.
-- `element_not_found`: the element is runtime-injected. Look for the component that renders it (React/Vue/Svelte), the JS that assembles it, or the data source that feeds it.
-- `file_is_generated` with `file: "..."`: user pointed at a generated file explicitly. Same resolution as `element_not_in_source`.
-
-Read the candidate source until you're confident where a change to the element would belong. If the change is purely visual, that source might be a shared stylesheet, not the template.
-
-### Step 2: Show three variants in the DOM for preview
-
-The browser bar is waiting for variants. Even without a wrapper in source, you still need to show something:
-
-1. Manually write the wrapper scaffold into the **served** file (the one the browser actually loaded). Use the same structure `live-wrap.mjs` produces; `<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents">…</div><!-- end -->`.
-2. Insert your three variant divs inside it, same shape as the deterministic path.
-3. Signal done with `--reply EVENT_ID done --file <served file>`. The browser's no-HMR fallback will fetch and inject.
-
-This served-file edit is **temporary**: next regen wipes it, and that's fine. The real work happens on accept.
-
-### Step 3: On accept, write to true source
-
-When the accept event arrives (`_acceptResult.handled` will usually be `false` here because accept also refuses to persist into generated files; see Handle accept for the carbonize branch), extract the accepted variant's content and write it into the source you identified in Step 1:
-
-- Structural change → edit the template / component source.
-- Visual-only change → add or update rules in the appropriate stylesheet; remove the inline `<style>` scope.
-- Dynamic from data → update the data source or the render logic.
-
-Then remove the temporary wrapper from the served file if it's still there.
-
-### Step 4: On discard, clean up the served file
-
-Remove the wrapper you inserted in Step 2. Nothing else to do.
-
-## Handle `accept`
-
-Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.
-
-- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.
-- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.
-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.
-- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.
-- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.
-
-### Required after accept (carbonize)
-
-When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.
-
-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.
-
-1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.
-2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).
-3. **Bake in parameter values while rewriting selectors.** For `@scope ([data-impeccable-variant="N"])` wrappers: retarget to real, semantic classes on the accepted HTML (`.why-visual--v2 .v2-label { … }`). For `:scope[data-p-<id>="VALUE"]` selectors: keep only the branch matching the chosen value from the param-values comment; drop the others (they're dead after accept). For `var(--p-<id>, DEFAULT)` in the CSS: either substitute the literal value, or if the param is still useful as a knob going forward, leave the var and update its initial declaration to the chosen value.
-4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; those are live-mode plumbing, not source.
-5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.
-
-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.
-
-A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.
-
-## Handle `discard`
-
-Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.
-
-## Handle `prefetch`
-
-Event: `{pageUrl}`. The browser fires this the first time the user selects an element on a given route, as a latency shortcut; it signals the user is likely about to Go on a page you haven't read yet.
-
-Resolve `pageUrl` to the underlying file:
-
-- Root `/` → the `pageFile` returned by `live.mjs` (usually `public/index.html` or equivalent).
-- Sub-routes (e.g. `/docs`, `/docs/live`) → the generated or source file for that route. Use your knowledge of the project layout (multi-page static sites often resolve `/foo` → `public/foo/index.html`; SPAs may map all routes to a single entry).
-
-Read the file into context, then poll again. No `--reply`: this is speculative pre-work; Go will come later. If you can't confidently resolve the route to a file, skip and poll again.
-
-Dedupe is the browser's job (one prefetch per unique pathname per session); trust it. If the same file shows up twice from different routes mapping to the same file, the second Read is cached anyway.
-
-## Exit
-
-The user can stop live mode by:
-- Saying "stop live mode" / "exit live" in chat
-- Closing the browser tab (SSE drops, poll returns `exit` after 8s)
-- The browser's exit button
-
-When the poll returns `exit`, proceed to cleanup. If the poll is still running as a background task, kill it first.
-
-## Cleanup
-
-```bash
-node .gemini/skills/impeccable/scripts/live-server.mjs stop
-```
-
-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.
-
-Then:
-- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).
-- Remove any leftover carbonize blocks (search for `impeccable-carbonize-start` markers).
-
-## First-time setup (config missing or invalid)
-
-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.
-
-Schema:
-
-```json
-{
- "files": ["<path-or-glob>", "<path-or-glob>", ...],
- "exclude": ["<optional-glob>", ...],
- "insertBefore": "</body>",
- "commentSyntax": "html",
- "cspChecked": true
-}
-```
-
-`files` is the inject target; **the HTML files the browser actually loads**, not necessarily source. Each entry is either a literal path (`"public/index.html"`) or a glob pattern (`"public/**/*.html"`). Tracked or generated doesn't matter here; wrap has its own generated-file guard and routes accepts through the fallback flow.
-
-`exclude` (optional) is a list of glob patterns matching files to skip, even if a `files` glob would have included them. Use for email templates, demo fixtures, or any HTML that isn't a live page.
-
-`cspChecked` tracks whether the CSP detection step below has already run. Absent on first setup; set to `true` after CSP is checked (whether patched, declined, or not needed).
-
-**Hard-excluded paths (cannot be overridden).** `**/node_modules/**` and `**/.git/**` are never matched regardless of what the user writes. These are vendor/metadata directories and injecting into them would silently instrument third-party code.
-
-**Glob syntax.** `**` matches any number of path segments (including zero), `*` matches any characters except `/`, `?` matches a single character except `/`. Paths are always relative to the project root with forward slashes.
-
-| Framework | `files` | `insertBefore` | `commentSyntax` |
-|-----------|---------|----------------|-----------------|
-| SPA with single shell (Vite / React / Plain HTML) | `["index.html"]` | `</body>` | `html` |
-| Next.js (App Router) | `["app/layout.tsx"]` | `</body>` | `jsx` |
-| Next.js (Pages) | `["pages/_document.tsx"]` | `</body>` | `jsx` |
-| Nuxt | `["app.vue"]` | `</body>` | `html` |
-| Svelte / SvelteKit | `["src/app.html"]` | `</body>` | `html` |
-| Astro | `[" <root layout .astro>"]` | `</body>` | `html` |
-| Multi-page (separate HTML per route) | `["public/**/*.html"]`: a glob covering the served directory | `</body>` | `html` |
-
-Pick an anchor that exists in every file (`</body>` almost always works). Use `insertAfter` if the anchor should match **after** a specific line.
-
-For multi-page sites, **prefer a glob over a literal file list**. New pages added later are picked up automatically on the next `live-inject.mjs` run; no config maintenance needed.
-
-For multi-page sites whose pages are *rebuilt* by a generator (Astro, static-site generators, custom scripts like `build-sub-pages.js`), the inject survives only until the next regeneration. Re-run `live.mjs` after each build. Accept is unaffected; it writes to true source via the fallback flow.
-
-### Drift-heal warning
-
-On every `live.mjs` boot, after inject, the project is scanned for HTML files under common page-source roots (`public/`, `src/`, `app/`, `pages/`). If any exist that aren't covered by the resolved `files` list, the output includes a `configDrift` field:
-
-```json
-{
- "ok": true,
- "serverPort": 8400,
- "pageFiles": [ "..." ],
- "configDrift": {
- "orphans": ["public/new-section/index.html", "public/docs/new-command.html"],
- "orphanCount": 2,
- "hint": "2 HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like \"public/**/*.html\"."
- }
-}
-```
-
-When `configDrift` is present, surface it to the user once per session before entering the poll loop:
-
-> Noticed N HTML file(s) in the project that aren't in `config.files`:
->
-> - `public/new-section/index.html`
-> - `public/docs/new-command.html`
->
-> Add them, or switch `files` to a glob like `["public/**/*.html"]` and let it track new pages automatically?
-
-Don't auto-update the config; let the user decide. `configDrift` is `null` when there's no drift.
-
-### CSP detection (first-time only)
-
-If `config.cspChecked === true`, skip this entire section. You already asked this user once; the answer sticks.
-
-Otherwise, run the detection helper:
-
-```bash
-node .gemini/skills/impeccable/scripts/detect-csp.mjs
-```
-
-Output: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.
-
-- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.
-- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:
- - Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)
- - SvelteKit `kit.csp.directives`
- - Nuxt `nuxt-security` module's `contentSecurityPolicy`
-- **`append-string`**: CSP written as a literal value string. Auto-patchable. See *append-string* below. Covers:
- - Inline `next.config.*` `headers()` with a CSP literal
- - Nuxt `routeRules` / `nitro.routeRules` headers
-- **`middleware`** or **`meta-tag`**: rarer. Detected but not auto-patched in v1. Show the user the detected files and ask them to add `http://localhost:8400` to `script-src` and `connect-src` manually, then mark `cspChecked: true` and proceed.
-
-#### Consent prompt template
-
-Use this phrasing so the experience is consistent across agents:
-
-> **CSP patch needed.** I detected a Content Security Policy in your project that blocks `http://localhost:8400`: the live picker won't load without an allowance. Here's the change I'd make:
->
-> ```diff
-> [file: <patchTarget>]
-> [exact diff, 2–5 lines]
-> ```
->
-> It's guarded by `NODE_ENV === "development"` so the extra entry only appears in dev and never reaches production. You can remove it any time by reverting this file. Apply? [y/n]
-
-On "no": skip the patch, mention live won't work until the user adds the allowance manually, still write `cspChecked: true` (the question's been asked).
-
-On "yes": apply the Shape-specific patch below, then write `cspChecked: true`.
-
-#### append-arrays
-
-CSP expressed as structured directive arrays. Patch mechanism: declare a dev-only array, spread it into the script-src and connect-src arrays.
-
-**Declare near the top of the file that holds the CSP arrays:**
-
-```ts
-// Dev-only allowance so impeccable live mode can load. Guarded by NODE_ENV.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? ["http://localhost:8400"] : [];
-```
-
-**Append `...__impeccableLiveDev` to the script-src and connect-src directive arrays.** Per-framework specifics:
-
-- **Next.js + monorepo helper**: edit the *app's* `next.config.*` (not the shared helper), appending to `additionalScriptSrc` and `additionalConnectSrc` passed into `createBaseNextConfig` (or equivalent). Keeps the shared package clean.
-- **SvelteKit**: edit `svelte.config.js`, appending to `kit.csp.directives['script-src']` and `kit.csp.directives['connect-src']`.
-- **Nuxt + nuxt-security**: edit `nuxt.config.*`, appending to `security.headers.contentSecurityPolicy['script-src']` and `['connect-src']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-turborepo/expected-after-patch.ts` (Next.js)
-- `tests/framework-fixtures/sveltekit-csp/expected-after-patch.js` (SvelteKit)
-
-Idempotency: if `__impeccableLiveDev` already exists in the file, the patch is already applied; skip asking and just mark `cspChecked: true`.
-
-#### append-string
-
-CSP built as a literal value string. Two-point patch: declare a dev-only string near the top, interpolate it into the CSP at the `script-src` and `connect-src` directives.
-
-```ts
-// Dev-only allowance so impeccable live mode can load.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? " http://localhost:8400" : "";
-```
-
-Then in the CSP value string:
-- `script-src 'self' 'unsafe-inline'` → `` `script-src 'self' 'unsafe-inline'${__impeccableLiveDev}` ``
-- `connect-src 'self'` → `` `connect-src 'self'${__impeccableLiveDev}` ``
-
-(Leading space on the dev string so it concatenates cleanly into the existing value. Convert the literal CSP directives into template strings as part of the edit if they aren't already.)
-
-Per-framework specifics:
-- **Next.js inline `headers()`**: edit `next.config.*`, splicing the variable into the CSP value.
-- **Nuxt `routeRules`**: edit `nuxt.config.*`, splicing into the CSP in `routeRules['/**'].headers['Content-Security-Policy']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-inline-csp/expected-after-patch.js` (Next.js)
-- `tests/framework-fixtures/nuxt-csp/expected-after-patch.ts` (Nuxt)
-
-### Troubleshooting
-
-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.
-
-Then re-run `live.mjs`.
@@ -1,109 +0,0 @@
-# Motion Design
-
-## Duration: The 100/300/500 Rule
-
-Timing matters more than easing. These durations feel right for most UI:
-
-| Duration | Use Case | Examples |
-|----------|----------|----------|
-| **100-150ms** | Instant feedback | Button press, toggle, color change |
-| **200-300ms** | State changes | Menu open, tooltip, hover states |
-| **300-500ms** | Layout changes | Accordion, modal, drawer |
-| **500-800ms** | Entrance animations | Page load, hero reveals |
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-## Easing: Pick the Right Curve
-
-**Don't use `ease`.** It's a compromise that's rarely optimal. Instead:
-
-| Curve | Use For | CSS |
-|-------|---------|-----|
-| **ease-out** | Elements entering | `cubic-bezier(0.16, 1, 0.3, 1)` |
-| **ease-in** | Elements leaving | `cubic-bezier(0.7, 0, 0.84, 0)` |
-| **ease-in-out** | State toggles (there → back) | `cubic-bezier(0.65, 0, 0.35, 1)` |
-
-**For micro-interactions, use exponential curves.** They feel natural because they mimic real physics (friction, deceleration):
-
-```css
-/* Quart out - smooth, refined (recommended default) */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1);
-
-/* Quint out - slightly more dramatic */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1);
-
-/* Expo out - snappy, confident */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1);
-```
-
-**Avoid bounce and elastic curves.** They were trendy in 2015 but now feel tacky and amateurish. Real objects don't bounce when they stop; they decelerate smoothly. Overshoot effects draw attention to the animation itself rather than the content.
-
-## Premium Motion Materials
-
-Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties: blur reveals, backdrop-filter panels, saturation or brightness shifts, shadow bloom, SVG filters, masks, clip paths, gradient-position movement, and variable font or shader-driven effects.
-
-Use the right material for the effect:
-
-- **Transform / opacity**: movement, press feedback, simple reveals, list choreography.
-- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances, atmospheric transitions.
-- **Clip path / masks**: wipes, reveals, editorial cropping, product-like transitions.
-- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state.
-- **Grid-template rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly.
-
-The hard rule is not "transform and opacity only." The hard rule is: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify in-browser that the result is smooth on the target viewports. If blur/filter makes the interaction feel significantly more premium and remains smooth, use it.
-
-## Staggered Animations
-
-Use CSS custom properties for cleaner stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"` on each item. **Cap total stagger time**: 10 items at 50ms = 500ms total. For many items, reduce per-item delay or cap staggered count.
-
-## Reduced Motion
-
-This is not optional. Vestibular disorders affect ~35% of adults over 40.
-
-```css
-/* Define animations normally */
-.card {
- animation: slide-up 500ms ease-out;
-}
-
-/* Provide alternative for reduced motion */
-@media (prefers-reduced-motion: reduce) {
- .card {
- animation: fade-in 200ms ease-out; /* Crossfade instead of motion */
- }
-}
-
-/* Or disable entirely */
-@media (prefers-reduced-motion: reduce) {
- *, *::before, *::after {
- animation-duration: 0.01ms !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**What to preserve**: Functional animations like progress bars, loading spinners (slowed down), and focus indicators should still work, just without spatial movement.
-
-## Perceived Performance
-
-**Nobody cares how fast your site is, just how fast it feels.** Perception can be as effective as actual performance.
-
-**The 80ms threshold**: Our brains buffer sensory input for ~80ms to synchronize perception. Anything under 80ms feels instant and simultaneous. This is your target for micro-interactions.
-
-**Active vs passive time**: Passive waiting (staring at a spinner) feels longer than active engagement. Strategies to shift the balance:
-
-- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening.
-- **Early completion**: Show content progressively, don't wait for everything. Video buffering, progressive images, streaming HTML.
-- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Instagram likes work offline; the UI updates instantly, syncs later. Use for low-stakes actions; avoid for payments or destructive operations.
-
-**Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances, but ease-in toward a task's end compresses perceived time.
-
-**Caution**: Too-fast responses can decrease perceived value. Users may distrust instant results for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
-
-## Performance
-
-Don't use `will-change` preemptively, only when animation is imminent (`:hover`, `.animating`). For scroll-triggered animations, use Intersection Observer instead of scroll events; unobserve after animating once. Create motion tokens for consistency (durations, easings, common transitions).
-
----
-
-**Avoid**: Animating everything (animation fatigue is real). Using >500ms for UI feedback. Ignoring `prefers-reduced-motion`. Using animation to hide slow loading.
@@ -1,234 +0,0 @@
-> **Additional context needed**: the "aha moment" you want users to reach, and users' experience level.
-
-Get users to first value as fast as possible. Onboarding's job is not to teach the product. Its job is to get people to the moment that proves the product is worth their time.
-
-## Assess Onboarding Needs
-
-Understand what users need to learn and why:
-
-1. **Identify the challenge**:
- - What are users trying to accomplish?
- - What's confusing or unclear about current experience?
- - Where do users get stuck or drop off?
- - What's the "aha moment" we want users to reach?
-
-2. **Understand the users**:
- - What's their experience level? (Beginners, power users, mixed?)
- - What's their motivation? (Excited and exploring? Required by work?)
- - What's their time commitment? (5 minutes? 30 minutes?)
- - What alternatives do they know? (Coming from competitor? New to category?)
-
-3. **Define success**:
- - What's the minimum users need to learn to be successful?
- - What's the key action we want them to take? (First project? First invite?)
- - How do we know onboarding worked? (Completion rate? Time to value?)
-
-**CRITICAL**: Onboarding should get users to value as quickly as possible, not teach everything possible.
-
-## Onboarding Principles
-
-Follow these core principles:
-
-### Show, Don't Tell
-- Demonstrate with working examples, not just descriptions
-- Provide real functionality in onboarding, not separate tutorial mode
-- Use progressive disclosure, teach one thing at a time
-
-### Make It Optional (When Possible)
-- Let experienced users skip onboarding
-- Don't block access to product
-- Provide "Skip" or "I'll explore on my own" options
-
-### Time to Value
-- Get users to their "aha moment" ASAP
-- Front-load most important concepts
-- Teach 20% that delivers 80% of value
-- Save advanced features for contextual discovery
-
-### Context Over Ceremony
-- Teach features when users need them, not upfront
-- Empty states are onboarding opportunities
-- Tooltips and hints at point of use
-
-### Respect User Intelligence
-- Don't patronize or over-explain
-- Be concise and clear
-- Assume users can figure out standard patterns
-
-## Design Onboarding Experiences
-
-Create appropriate onboarding for the context:
-
-### Initial Product Onboarding
-
-**Welcome Screen**:
-- Clear value proposition (what is this product?)
-- What users will learn/accomplish
-- Time estimate (honest about commitment)
-- Option to skip (for experienced users)
-
-**Account Setup**:
-- Minimal required information (collect more later)
-- Explain why you're asking for each piece of information
-- Smart defaults where possible
-- Social login when appropriate
-
-**Core Concept Introduction**:
-- Introduce 1-3 core concepts (not everything)
-- Use simple language and examples
-- Interactive when possible (do, don't just read)
-- Progress indication (step 1 of 3)
-
-**First Success**:
-- Guide users to accomplish something real
-- Pre-populated examples or templates
-- Celebrate completion (but don't overdo it)
-- Clear next steps
-
-### Feature Discovery & Adoption
-
-**Empty States**:
-Instead of blank space, show:
-- What will appear here (description + screenshot/illustration)
-- Why it's valuable
-- Clear CTA to create first item
-- Example or template option
-
-Example:
-```
-No projects yet
-Projects help you organize your work and collaborate with your team.
-[Create your first project] or [Start from template]
-```
-
-**Contextual Tooltips**:
-- Appear at relevant moment (first time user sees feature)
-- Point directly at relevant UI element
-- Brief explanation + benefit
-- Dismissable (with "Don't show again" option)
-- Optional "Learn more" link
-
-**Feature Announcements**:
-- Highlight new features when they're released
-- Show what's new and why it matters
-- Let users try immediately
-- Dismissable
-
-**Progressive Onboarding**:
-- Teach features when users encounter them
-- Badges or indicators on new/unused features
-- Unlock complexity gradually (don't show all options immediately)
-
-### Guided Tours & Walkthroughs
-
-**When to use**:
-- Complex interfaces with many features
-- Significant changes to existing product
-- Industry-specific tools needing domain knowledge
-
-**How to design**:
-- Spotlight specific UI elements (dim rest of page)
-- Keep steps short (3-7 steps max per tour)
-- Allow users to click through tour freely
-- Include "Skip tour" option
-- Make replayable (help menu)
-
-**Best practices**:
-- Interactive over passive (let users click real buttons)
-- Focus on workflow, not features ("Create a project" not "This is the project button")
-- Provide sample data so actions work
-
-### Interactive Tutorials
-
-**When to use**:
-- Users need hands-on practice
-- Concepts are complex or unfamiliar
-- High stakes (better to practice in safe environment)
-
-**How to design**:
-- Sandbox environment with sample data
-- Clear objectives ("Create a chart showing sales by region")
-- Step-by-step guidance
-- Validation (confirm they did it right)
-- Graduation moment (you're ready!)
-
-### Documentation & Help
-
-**In-product help**:
-- Contextual help links throughout interface
-- Keyboard shortcut reference
-- Search-able help center
-- Video tutorials for complex workflows
-
-**Help patterns**:
-- `?` icon near complex features
-- "Learn more" links in tooltips
-- Keyboard shortcut hints (`⌘K` shown on search box)
-
-## Empty State Design
-
-Every empty state needs:
-
-### What Will Be Here
-"Your recent projects will appear here"
-
-### Why It Matters
-"Projects help you organize your work and collaborate with your team"
-
-### How to Get Started
-[Create project] or [Import from template]
-
-### Visual Interest
-Illustration or icon (not just text on blank page)
-
-### Contextual Help
-"Need help getting started? [Watch 2-min tutorial]"
-
-**Empty state types**:
-- **First use**: Never used this feature (emphasize value, provide template)
-- **User cleared**: Intentionally deleted everything (light touch, easy to recreate)
-- **No results**: Search or filter returned nothing (suggest different query, clear filters)
-- **No permissions**: Can't access (explain why, how to get access)
-- **Error state**: Failed to load (explain what happened, retry option)
-
-## Implementation Patterns
-
-### Technical approaches:
-
-**Tooltip libraries**: Tippy.js, Popper.js
-**Tour libraries**: Intro.js, Shepherd.js, React Joyride
-**Modal patterns**: Focus trap, backdrop, ESC to close
-**Progress tracking**: LocalStorage for "seen" states
-**Analytics**: Track completion, drop-off points
-
-**Storage patterns**:
-```javascript
-// Track which onboarding steps user has seen
-localStorage.setItem('onboarding-completed', 'true');
-localStorage.setItem('feature-tooltip-seen-reports', 'true');
-```
-
-**IMPORTANT**: Don't show same onboarding twice (annoying). Track completion and respect dismissals.
-
-**NEVER**:
-- Force users through long onboarding before they can use product
-- Patronize users with obvious explanations
-- Show same tooltip repeatedly (respect dismissals)
-- Block all UI during tour (let users explore)
-- Create separate tutorial mode disconnected from real product
-- Overwhelm with information upfront (progressive disclosure!)
-- Hide "Skip" or make it hard to find
-- Forget about returning users (don't show initial onboarding again)
-
-## Verify Onboarding Quality
-
-Test with real users:
-
-- **Time to completion**: Can users complete onboarding quickly?
-- **Comprehension**: Do users understand after completing?
-- **Action**: Do users take desired next step?
-- **Skip rate**: Are too many users skipping? (Maybe it's too long or not valuable)
-- **Completion rate**: Are users completing? (If low, simplify)
-- **Time to value**: How long until users get first value?
-
-When users hit the aha moment fast and don't drop off, hand off to `/impeccable polish` for the final pass.
@@ -1,258 +0,0 @@
-Performance is a feature. Identify the actual bottleneck for THIS interface, fix it, then measure. Don't optimize what isn't slow.
-
-## Assess Performance Issues
-
-Understand current performance and identify problems:
-
-1. **Measure current state**:
- - **Core Web Vitals**: LCP, FID/INP, CLS scores
- - **Load time**: Time to interactive, first contentful paint
- - **Bundle size**: JavaScript, CSS, image sizes
- - **Runtime performance**: Frame rate, memory usage, CPU usage
- - **Network**: Request count, payload sizes, waterfall
-
-2. **Identify bottlenecks**:
- - What's slow? (Initial load? Interactions? Animations?)
- - What's causing it? (Large images? Expensive JavaScript? Layout thrashing?)
- - How bad is it? (Perceivable? Annoying? Blocking?)
- - Who's affected? (All users? Mobile only? Slow connections?)
-
-**CRITICAL**: Measure before and after. Premature optimization wastes time. Optimize what actually matters.
-
-## Optimization Strategy
-
-Create systematic improvement plan:
-
-### Loading Performance
-
-**Optimize Images**:
-- Use modern formats (WebP, AVIF)
-- Proper sizing (don't load 3000px image for 300px display)
-- Lazy loading for below-fold images
-- Responsive images (`srcset`, `picture` element)
-- Compress images (80-85% quality is usually imperceptible)
-- Use CDN for faster delivery
-
-```html
-<img
- src="hero.webp"
- srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
- sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
- loading="lazy"
- alt="Hero image"
-/>
-```
-
-**Reduce JavaScript Bundle**:
-- Code splitting (route-based, component-based)
-- Tree shaking (remove unused code)
-- Remove unused dependencies
-- Lazy load non-critical code
-- Use dynamic imports for large components
-
-```javascript
-// Lazy load heavy component
-const HeavyChart = lazy(() => import('./HeavyChart'));
-```
-
-**Optimize CSS**:
-- Remove unused CSS
-- Critical CSS inline, rest async
-- Minimize CSS files
-- Use CSS containment for independent regions
-
-**Optimize Fonts**:
-- Use `font-display: swap` or `optional`
-- Subset fonts (only characters you need)
-- Preload critical fonts
-- Use system fonts when appropriate
-- Limit font weights loaded
-
-```css
-@font-face {
- font-family: 'CustomFont';
- src: url('/fonts/custom.woff2') format('woff2');
- font-display: swap; /* Show fallback immediately */
- unicode-range: U+0020-007F; /* Basic Latin only */
-}
-```
-
-**Optimize Loading Strategy**:
-- Critical resources first (async/defer non-critical)
-- Preload critical assets
-- Prefetch likely next pages
-- Service worker for offline/caching
-- HTTP/2 or HTTP/3 for multiplexing
-
-### Rendering Performance
-
-**Avoid Layout Thrashing**:
-```javascript
-// ❌ Bad: Alternating reads and writes (causes reflows)
-elements.forEach(el => {
- const height = el.offsetHeight; // Read (forces layout)
- el.style.height = height * 2; // Write
-});
-
-// ✅ Good: Batch reads, then batch writes
-const heights = elements.map(el => el.offsetHeight); // All reads
-elements.forEach((el, i) => {
- el.style.height = heights[i] * 2; // All writes
-});
-```
-
-**Optimize Rendering**:
-- Use CSS `contain` property for independent regions
-- Minimize DOM depth (flatter is faster)
-- Reduce DOM size (fewer elements)
-- Use `content-visibility: auto` for long lists
-- Virtual scrolling for very long lists (react-window, react-virtualized)
-
-**Reduce Paint & Composite**:
-- Use `transform` and `opacity` for reliable movement, but allow blur, filters, masks, clip paths, shadows, and color shifts when they create meaningful polish
-- Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- Use `will-change` sparingly for known expensive operations
-- Bound expensive paint areas for blur/filter/shadow effects (smaller and isolated is faster)
-
-### Animation Performance
-
-**GPU Acceleration**:
-```css
-/* ✅ GPU-accelerated (fast) */
-.animated {
- transform: translateX(100px);
- opacity: 0.5;
-}
-
-/* ❌ CPU-bound (slow) */
-.animated {
- left: 100px;
- width: 300px;
-}
-```
-
-**Smooth 60fps**:
-- Target 16ms per frame (60fps)
-- Use `requestAnimationFrame` for JS animations
-- Debounce/throttle scroll handlers
-- Use CSS animations when possible
-- Avoid long-running JavaScript during animations
-
-**Intersection Observer**:
-```javascript
-// Efficiently detect when elements enter viewport
-const observer = new IntersectionObserver((entries) => {
- entries.forEach(entry => {
- if (entry.isIntersecting) {
- // Element is visible, lazy load or animate
- }
- });
-});
-```
-
-### React/Framework Optimization
-
-**React-specific**:
-- Use `memo()` for expensive components
-- `useMemo()` and `useCallback()` for expensive computations
-- Virtualize long lists
-- Code split routes
-- Avoid inline function creation in render
-- Use React DevTools Profiler
-
-**Framework-agnostic**:
-- Minimize re-renders
-- Debounce expensive operations
-- Memoize computed values
-- Lazy load routes and components
-
-### Network Optimization
-
-**Reduce Requests**:
-- Combine small files
-- Use SVG sprites for icons
-- Inline small critical assets
-- Remove unused third-party scripts
-
-**Optimize APIs**:
-- Use pagination (don't load everything)
-- GraphQL to request only needed fields
-- Response compression (gzip, brotli)
-- HTTP caching headers
-- CDN for static assets
-
-**Optimize for Slow Connections**:
-- Adaptive loading based on connection (navigator.connection)
-- Optimistic UI updates
-- Request prioritization
-- Progressive enhancement
-
-## Core Web Vitals Optimization
-
-### Largest Contentful Paint (LCP < 2.5s)
-- Optimize hero images
-- Inline critical CSS
-- Preload key resources
-- Use CDN
-- Server-side rendering
-
-### First Input Delay (FID < 100ms) / INP (< 200ms)
-- Break up long tasks
-- Defer non-critical JavaScript
-- Use web workers for heavy computation
-- Reduce JavaScript execution time
-
-### Cumulative Layout Shift (CLS < 0.1)
-- Set dimensions on images and videos
-- Don't inject content above existing content
-- Use `aspect-ratio` CSS property
-- Reserve space for ads/embeds
-- Avoid animations that cause layout shifts
-
-```css
-/* Reserve space for image */
-.image-container {
- aspect-ratio: 16 / 9;
-}
-```
-
-## Performance Monitoring
-
-**Tools to use**:
-- Chrome DevTools (Lighthouse, Performance panel)
-- WebPageTest
-- Core Web Vitals (Chrome UX Report)
-- Bundle analyzers (webpack-bundle-analyzer)
-- Performance monitoring (Sentry, DataDog, New Relic)
-
-**Key metrics**:
-- LCP, FID/INP, CLS (Core Web Vitals)
-- Time to Interactive (TTI)
-- First Contentful Paint (FCP)
-- Total Blocking Time (TBT)
-- Bundle size
-- Request count
-
-**IMPORTANT**: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.
-
-**NEVER**:
-- Optimize without measuring (premature optimization)
-- Sacrifice accessibility for performance
-- Break functionality while optimizing
-- Use `will-change` everywhere (creates new layers, uses memory)
-- Lazy load above-fold content
-- Optimize micro-optimizations while ignoring major issues (optimize the biggest bottleneck first)
-- Forget about mobile performance (often slower devices, slower connections)
-
-## Verify Improvements
-
-Test that optimizations worked:
-
-- **Before/after metrics**: Compare Lighthouse scores
-- **Real user monitoring**: Track improvements for real users
-- **Different devices**: Test on low-end Android, not just flagship iPhone
-- **Slow connections**: Throttle to 3G, test experience
-- **No regressions**: Ensure functionality still works
-- **User perception**: Does it *feel* faster?
-
-When the user-facing numbers move, hand off to `/impeccable polish` for the final pass.
@@ -1,130 +0,0 @@
-Start your response with:
-
-```
-──────────── ⚡ OVERDRIVE ─────────────
-》》》 Entering overdrive mode...
-```
-
-Push an interface past conventional limits. This isn't just about visual effects. It's about using the full power of the browser to make any part of an interface feel extraordinary: a table that handles a million rows, a dialog that morphs from its trigger, a form that validates in real-time with streaming feedback, a page transition that feels cinematic.
-
-**EXTRA IMPORTANT FOR THIS COMMAND**: Context determines what "extraordinary" means. A particle system on a creative portfolio is impressive. The same particle system on a settings page is embarrassing. But a settings page with instant optimistic saves and animated state transitions? That's extraordinary too. Understand the project's personality and goals before deciding what's appropriate.
-
-### Propose Before Building
-
-This command has the highest potential to misfire. Do NOT jump straight into implementation. You MUST:
-
-1. **Think through 2-3 different directions**: consider different techniques, levels of ambition, and aesthetic approaches. For each direction, briefly describe what the result would look and feel like.
-2. **ask the user directly to clarify what you cannot infer.** to present these directions and get the user's pick before writing any code. Explain trade-offs (browser support, performance cost, complexity).
-3. Only proceed with the direction the user confirms.
-
-Skipping this step risks building something embarrassing that needs to be thrown away.
-
-### Iterate with Browser Automation
-
-Technically ambitious effects almost never work on the first try. You MUST actively use browser automation tools to preview your work, visually verify the result, and iterate. Do not assume the effect looks right, check it. Expect multiple rounds of refinement. The gap between "technically works" and "looks extraordinary" is closed through visual iteration, not code alone.
-
----
-
-## Assess What "Extraordinary" Means Here
-
-The right kind of technical ambition depends entirely on what you're working with. Before choosing a technique, ask: **what would make a user of THIS specific interface say "wow, that's nice"?**
-
-### For visual/marketing surfaces
-Pages, hero sections, landing pages, portfolios: the "wow" is often sensory: a scroll-driven reveal, a shader background, a cinematic page transition, generative art that responds to the cursor.
-
-### For functional UI
-Tables, forms, dialogs, navigation: the "wow" is in how it FEELS: a dialog that morphs from the button that triggered it via View Transitions, a data table that renders 100k rows at 60fps via virtual scrolling, a form with streaming validation that feels instant, drag-and-drop with spring physics.
-
-### For performance-critical UI
-The "wow" is invisible but felt: a search that filters 50k items without a flicker, a complex form that never blocks the main thread, an image editor that processes in near-real-time. The interface just never hesitates.
-
-### For data-heavy interfaces
-Charts and dashboards: the "wow" is in fluidity: GPU-accelerated rendering via Canvas/WebGL for massive datasets, animated transitions between data states, force-directed graph layouts that settle naturally.
-
-**The common thread**: something about the implementation goes beyond what users expect from a web interface. The technique serves the experience, not the other way around.
-
-## The Toolkit
-
-Organized by what you're trying to achieve, not by technology name.
-
-### Make transitions feel cinematic
-- **View Transitions API** (same-document: all browsers; cross-document: no Firefox): shared element morphing between states. A list item expanding into a detail page. A button morphing into a dialog. This is the closest thing to native FLIP animations.
-- **`@starting-style`** (all browsers): animate elements from `display: none` to visible with CSS only, including entry keyframes
-- **Spring physics**: natural motion with mass, tension, and damping instead of cubic-bezier. Libraries: motion (formerly Framer Motion), GSAP, or roll your own spring solver.
-
-### Tie animation to scroll position
-- **Scroll-driven animations** (`animation-timeline: scroll()`): CSS-only, no JS. Parallax, progress bars, reveal sequences all driven by scroll position. (Chrome/Edge/Safari; Firefox: flag only; always provide a static fallback)
-
-### Render beyond CSS
-- **WebGL** (all browsers): shader effects, post-processing, particle systems. Libraries: Three.js, OGL (lightweight), regl. Use for effects CSS can't express.
-- **WebGPU** (Chrome/Edge; Safari partial; Firefox: flag only): next-gen GPU compute. More powerful than WebGL but limited browser support. Always fall back to WebGL2.
-- **Canvas 2D / OffscreenCanvas**: custom rendering, pixel manipulation, or moving heavy rendering off the main thread entirely via Web Workers + OffscreenCanvas.
-- **SVG filter chains**: displacement maps, turbulence, morphology for organic distortion effects. CSS-animatable.
-
-### Make data feel alive
-- **Virtual scrolling**: render only visible rows for tables/lists with tens of thousands of items. No library required for simple cases; TanStack Virtual for complex ones.
-- **GPU-accelerated charts**: Canvas or WebGL-rendered data visualization for datasets too large for SVG/DOM. Libraries: deck.gl, regl-based custom renderers.
-- **Animated data transitions**: morph between chart states rather than replacing. D3's `transition()` or View Transitions for DOM-based charts.
-
-### Animate complex properties
-- **`@property`** (all browsers): register custom CSS properties with types, enabling animation of gradients, colors, and complex values that CSS can't normally interpolate.
-- **Web Animations API** (all browsers): JavaScript-driven animations with the performance of CSS. Composable, cancellable, reversible. The foundation for complex choreography.
-
-### Push performance boundaries
-- **Web Workers**: move computation off the main thread. Heavy data processing, image manipulation, search indexing: anything that would cause jank.
-- **OffscreenCanvas**: render in a Worker thread. The main thread stays free while complex visuals render in the background.
-- **WASM**: near-native performance for computation-heavy features. Image processing, physics simulations, codecs.
-
-### Interact with the device
-- **Web Audio API**: spatial audio, audio-reactive visualizations, sonic feedback. Requires user gesture to start.
-- **Device APIs**: orientation, ambient light, geolocation. Use sparingly and always with user permission.
-
-**NOTE**: This command is about enhancing how an interface FEELS, not changing what a product DOES. Adding real-time collaboration, offline support, or new backend capabilities are product decisions, not UI enhancements. Focus on making existing features feel extraordinary.
-
-## Implement with Discipline
-
-### Progressive enhancement is non-negotiable
-
-Every technique must degrade gracefully. The experience without the enhancement must still be good.
-
-```css
-@supports (animation-timeline: scroll()) {
- .hero { animation-timeline: scroll(); }
-}
-```
-
-```javascript
-if ('gpu' in navigator) { /* WebGPU */ }
-else if (canvas.getContext('webgl2')) { /* WebGL2 fallback */ }
-/* CSS-only fallback must still look good */
-```
-
-### Performance rules
-
-- Target 60fps. If dropping below 50, simplify.
-- Respect `prefers-reduced-motion`, always. Provide a beautiful static alternative.
-- Lazy-initialize heavy resources (WebGL contexts, WASM modules) only when near viewport.
-- Pause off-screen rendering. Kill what you can't see.
-- Test on real mid-range devices, not just your development machine.
-
-### Polish is the difference
-
-The gap between "cool" and "extraordinary" is in the last 20% of refinement: the easing curve on a spring animation, the timing offset in a staggered reveal, the subtle secondary motion that makes a transition feel physical. Don't ship the first version that works; ship the version that feels inevitable.
-
-**NEVER**:
-- Ignore `prefers-reduced-motion`. This is an accessibility requirement, not a suggestion
-- Ship effects that cause jank on mid-range devices
-- Use bleeding-edge APIs without a functional fallback
-- Add sound without explicit user opt-in
-- Use technical ambition to mask weak design fundamentals; fix those first with other commands
-- Layer multiple competing extraordinary moments. Focus creates impact, excess creates noise
-
-## Verify the Result
-
-- **The wow test**: Show it to someone who hasn't seen it. Do they react?
-- **The removal test**: Take it away. Does the experience feel diminished, or does nobody notice?
-- **The device test**: Run it on a phone, a tablet, a Chromebook. Still smooth?
-- **The accessibility test**: Enable reduced motion. Still beautiful?
-- **The context test**: Does this make sense for THIS brand and audience?
-
-"Technically extraordinary" isn't about using the newest API. It's about making an interface do something users didn't think a website could do.
@@ -1,179 +0,0 @@
-# Persona-Based Design Testing
-
-Test the interface through the eyes of 5 distinct user archetypes. Each persona exposes different failure modes that a single "design director" perspective would miss.
-
-**How to use**: Select 2–3 personas most relevant to the interface being critiqued. Walk through the primary user action as each persona. Report specific red flags, not generic concerns.
-
----
-
-## 1. Impatient Power User: "Alex"
-
-
-**Profile**: Expert with similar products. Expects efficiency, hates hand-holding. Will find shortcuts or leave.
-
-**Behaviors**:
-- Skips all onboarding and instructions
-- Looks for keyboard shortcuts immediately
-- Tries to bulk-select, batch-edit, and automate
-- Gets frustrated by required steps that feel unnecessary
-- Abandons if anything feels slow or patronizing
-
-**Test Questions**:
-- Can Alex complete the core task in under 60 seconds?
-- Are there keyboard shortcuts for common actions?
-- Can onboarding be skipped entirely?
-- Do modals have keyboard dismiss (Esc)?
-- Is there a "power user" path (shortcuts, bulk actions)?
-
-**Red Flags** (report these specifically):
-- Forced tutorials or unskippable onboarding
-- No keyboard navigation for primary actions
-- Slow animations that can't be skipped
-- One-item-at-a-time workflows where batch would be natural
-- Redundant confirmation steps for low-risk actions
-
----
-
-## 2. Confused First-Timer: "Jordan"
-
-**Profile**: Never used this type of product. Needs guidance at every step. Will abandon rather than figure it out.
-
-**Behaviors**:
-- Reads all instructions carefully
-- Hesitates before clicking anything unfamiliar
-- Looks for help or support constantly
-- Misunderstands jargon and abbreviations
-- Takes the most literal interpretation of any label
-
-**Test Questions**:
-- Is the first action obviously clear within 5 seconds?
-- Are all icons labeled with text?
-- Is there contextual help at decision points?
-- Does terminology assume prior knowledge?
-- Is there a clear "back" or "undo" at every step?
-
-**Red Flags** (report these specifically):
-- Icon-only navigation with no labels
-- Technical jargon without explanation
-- No visible help option or guidance
-- Ambiguous next steps after completing an action
-- No confirmation that an action succeeded
-
----
-
-## 3. Accessibility-Dependent User: "Sam"
-
-**Profile**: Uses screen reader (VoiceOver/NVDA), keyboard-only navigation. May have low vision, motor impairment, or cognitive differences.
-
-**Behaviors**:
-- Tabs through the interface linearly
-- Relies on ARIA labels and heading structure
-- Cannot see hover states or visual-only indicators
-- Needs adequate color contrast (4.5:1 minimum)
-- May use browser zoom up to 200%
-
-**Test Questions**:
-- Can the entire primary flow be completed keyboard-only?
-- Are all interactive elements focusable with visible focus indicators?
-- Do images have meaningful alt text?
-- Is color contrast WCAG AA compliant (4.5:1 for text)?
-- Does the screen reader announce state changes (loading, success, errors)?
-
-**Red Flags** (report these specifically):
-- Click-only interactions with no keyboard alternative
-- Missing or invisible focus indicators
-- Meaning conveyed by color alone (red = error, green = success)
-- Unlabeled form fields or buttons
-- Time-limited actions without extension option
-- Custom components that break screen reader flow
-
----
-
-## 4. Deliberate Stress Tester: "Riley"
-
-**Profile**: Methodical user who pushes interfaces beyond the happy path. Tests edge cases, tries unexpected inputs, and probes for gaps in the experience.
-
-**Behaviors**:
-- Tests edge cases intentionally (empty states, long strings, special characters)
-- Submits forms with unexpected data (emoji, RTL text, very long values)
-- Tries to break workflows by navigating backwards, refreshing mid-flow, or opening in multiple tabs
-- Looks for inconsistencies between what the UI promises and what actually happens
-- Documents problems methodically
-
-**Test Questions**:
-- What happens at the edges (0 items, 1000 items, very long text)?
-- Do error states recover gracefully or leave the UI in a broken state?
-- What happens on refresh mid-workflow? Is state preserved?
-- Are there features that appear to work but produce broken results?
-- How does the UI handle unexpected input (emoji, special chars, paste from Excel)?
-
-**Red Flags** (report these specifically):
-- Features that appear to work but silently fail or produce wrong results
-- Error handling that exposes technical details or leaves UI in a broken state
-- Empty states that show nothing useful ("No results" with no guidance)
-- Workflows that lose user data on refresh or navigation
-- Inconsistent behavior between similar interactions in different parts of the UI
-
----
-
-## 5. Distracted Mobile User: "Casey"
-
-**Profile**: Using phone one-handed on the go. Frequently interrupted. Possibly on a slow connection.
-
-**Behaviors**:
-- Uses thumb only; prefers bottom-of-screen actions
-- Gets interrupted mid-flow and returns later
-- Switches between apps frequently
-- Has limited attention span and low patience
-- Types as little as possible, prefers taps and selections
-
-**Test Questions**:
-- Are primary actions in the thumb zone (bottom half of screen)?
-- Is state preserved if the user leaves and returns?
-- Does it work on slow connections (3G)?
-- Can forms use autocomplete and smart defaults?
-- Are touch targets at least 44×44pt?
-
-**Red Flags** (report these specifically):
-- Important actions positioned at the top of the screen (unreachable by thumb)
-- No state persistence; progress lost on tab switch or interruption
-- Large text inputs required where selection would work
-- Heavy assets loading on every page (no lazy loading)
-- Tiny tap targets or targets too close together
-
----
-
-## Selecting Personas
-
-Choose personas based on the interface type:
-
-| Interface Type | Primary Personas | Why |
-|---------------|-----------------|-----|
-| Landing page / marketing | Jordan, Riley, Casey | First impressions, trust, mobile |
-| Dashboard / admin | Alex, Sam | Power users, accessibility |
-| E-commerce / checkout | Casey, Riley, Jordan | Mobile, edge cases, clarity |
-| Onboarding flow | Jordan, Casey | Confusion, interruption |
-| Data-heavy / analytics | Alex, Sam | Efficiency, keyboard nav |
-| Form-heavy / wizard | Jordan, Sam, Casey | Clarity, accessibility, mobile |
-
----
-
-## Project-Specific Personas
-
-If `GEMINI.md` contains a `## Design Context` section (generated by `impeccable teach`), derive 1–2 additional personas from the audience and brand information:
-
-1. Read the target audience description
-2. Identify the primary user archetype not covered by the 5 predefined personas
-3. Create a persona following this template:
-
-```
-### [Role]: "[Name]"
-
-**Profile**: [2-3 key characteristics derived from Design Context]
-
-**Behaviors**: [3-4 specific behaviors based on the described audience]
-
-**Red Flags**: [3-4 things that would alienate this specific user type]
-```
-
-Only generate project-specific personas when real Design Context data is available. Don't invent audience details; use the 5 predefined personas when no context exists.
@@ -1,242 +0,0 @@
-> **Additional context needed**: quality bar (MVP vs flagship).
-
-Perform a meticulous final pass to catch all the small details that separate good work from great work. The difference between shipped and polished.
-
-Detector and automated QA output are defect evidence only. A clean script result is never proof that the design is strong; gather browser evidence and inspect the real interaction path.
-
-## Design System Discovery
-
-Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
-
-1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
-2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
-3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category: patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
-
-If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask. Never guess at design system principles.**
-
-## Pre-Polish Assessment
-
-Understand the current state and goals before touching anything:
-
-1. **Review completeness**:
- - Is it functionally complete?
- - Are there known issues to preserve (mark with TODOs)?
- - What's the quality bar? (MVP vs flagship feature?)
- - When does it ship? (How much time for polish?)
-
-2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish; a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
-
-3. **Identify polish areas**:
- - Visual inconsistencies
- - Spacing and alignment issues
- - Interaction state gaps
- - Copy inconsistencies
- - Edge cases and error states
- - Loading and transition smoothness
- - Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
-
-4. **Pull in any prior critique** (optional signal): If `/impeccable critique` has been run on the same target, its priority issues are a useful prior for what to address first. Resolve the target to a file path or URL, then:
- ```bash
- slug=$(node .gemini/skills/impeccable/scripts/critique-storage.mjs slug "<resolved>")
- node .gemini/skills/impeccable/scripts/critique-storage.mjs latest "$slug"
- ```
- Exit 0 with body = found; fold the P0/P1 items into your polish list and mention the snapshot path so the user sees what you read. Exit 2 = no snapshot, continue without it. The critique is one input among many. Do your own pass either way.
-
-5. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent; never perfect one corner while leaving another rough.
-
-**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
-
-## Polish Systematically
-
-Work through these dimensions methodically:
-
-### Visual Alignment & Spacing
-
-- **Pixel-perfect alignment**: Everything lines up to grid
-- **Consistent spacing**: All gaps use spacing scale (no random 13px gaps)
-- **Optical alignment**: Adjust for visual weight (icons may need offset for optical centering)
-- **Responsive consistency**: Spacing and alignment work at all breakpoints
-- **Grid adherence**: Elements snap to baseline grid
-
-**Check**:
-- Enable grid overlay and verify alignment
-- Check spacing with browser inspector
-- Test at multiple viewport sizes
-- Look for elements that "feel" off
-
-### Information Architecture & Flow
-
-Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
-
-- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
-- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere: modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
-- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
-- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
-- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
-
-### Typography Refinement
-
-- **Hierarchy consistency**: Same elements use same sizes/weights throughout
-- **Line length**: 45-75 characters for body text
-- **Line height**: Appropriate for font size and context
-- **Widows & orphans**: No single words on last line
-- **Hyphenation**: Appropriate for language and column width
-- **Kerning**: Adjust letter spacing where needed (especially headlines)
-- **Font loading**: No FOUT/FOIT flashes
-
-### Color & Contrast
-
-- **Contrast ratios**: All text meets WCAG standards
-- **Consistent token usage**: No hard-coded colors, all use design tokens
-- **Theme consistency**: Works in all theme variants
-- **Color meaning**: Same colors mean same things throughout
-- **Accessible focus**: Focus indicators visible with sufficient contrast
-- **Tinted neutrals**: No pure gray or pure black; add subtle color tint (0.01 chroma)
-- **Gray on color**: Never put gray text on colored backgrounds; use a shade of that color or transparency
-
-### Interaction States
-
-Every interactive element needs all states:
-
-- **Default**: Resting state
-- **Hover**: Subtle feedback (color, scale, shadow)
-- **Focus**: Keyboard focus indicator (never remove without replacement)
-- **Active**: Click/tap feedback
-- **Disabled**: Clearly non-interactive
-- **Loading**: Async action feedback
-- **Error**: Validation or error state
-- **Success**: Successful completion
-
-**Missing states create confusion and broken experiences**.
-
-### Micro-interactions & Transitions
-
-- **Smooth transitions**: All state changes animated appropriately (150-300ms)
-- **Consistent easing**: Use ease-out-quart/quint/expo for natural deceleration. Never bounce or elastic; they feel dated.
-- **No jank**: Smooth animations; use atmospheric blur/filter/mask/shadow effects when they add polish, but bound expensive paint areas and avoid casual layout-property animation
-- **Appropriate motion**: Motion serves purpose, not decoration
-- **Reduced motion**: Respects `prefers-reduced-motion`
-
-### Content & Copy
-
-- **Consistent terminology**: Same things called same names throughout
-- **Consistent capitalization**: Title Case vs Sentence case applied consistently
-- **Grammar & spelling**: No typos
-- **Appropriate length**: Not too wordy, not too terse
-- **Punctuation consistency**: Periods on sentences, not on labels (unless all labels have them)
-
-### Icons & Images
-
-- **Consistent style**: All icons from same family or matching style
-- **Appropriate sizing**: Icons sized consistently for context
-- **Proper alignment**: Icons align with adjacent text optically
-- **Alt text**: All images have descriptive alt text
-- **Loading states**: Images don't cause layout shift, proper aspect ratios
-- **Retina support**: 2x assets for high-DPI screens
-
-### Forms & Inputs
-
-- **Label consistency**: All inputs properly labeled
-- **Required indicators**: Clear and consistent
-- **Error messages**: Helpful and consistent
-- **Tab order**: Logical keyboard navigation
-- **Auto-focus**: Appropriate (don't overuse)
-- **Validation timing**: Consistent (on blur vs on submit)
-
-### Edge Cases & Error States
-
-- **Loading states**: All async actions have loading feedback
-- **Empty states**: Helpful empty states, not just blank space
-- **Error states**: Clear error messages with recovery paths
-- **Success states**: Confirmation of successful actions
-- **Long content**: Handles very long names, descriptions, etc.
-- **No content**: Handles missing data gracefully
-- **Offline**: Appropriate offline handling (if applicable)
-
-### Responsiveness
-
-- **All breakpoints**: Test mobile, tablet, desktop
-- **Touch targets**: 44x44px minimum on touch devices
-- **Readable text**: No text smaller than 14px on mobile
-- **No horizontal scroll**: Content fits viewport
-- **Appropriate reflow**: Content adapts logically
-
-### Performance
-
-- **Fast initial load**: Optimize critical path
-- **No layout shift**: Elements don't jump after load (CLS)
-- **Smooth interactions**: No lag or jank
-- **Optimized images**: Appropriate formats and sizes
-- **Lazy loading**: Off-screen content loads lazily
-
-### Code Quality
-
-- **Remove console logs**: No debug logging in production
-- **Remove commented code**: Clean up dead code
-- **Remove unused imports**: Clean up unused dependencies
-- **Consistent naming**: Variables and functions follow conventions
-- **Type safety**: No TypeScript `any` or ignored errors
-- **Accessibility**: Proper ARIA labels and semantic HTML
-
-## Polish Checklist
-
-Go through systematically:
-
-- [ ] Aligned to the design system (drift named and resolved by root cause)
-- [ ] Information architecture and flow shape match neighboring features
-- [ ] Visual alignment perfect at all breakpoints
-- [ ] Spacing uses design tokens consistently
-- [ ] Typography hierarchy consistent
-- [ ] All interactive states implemented
-- [ ] All transitions smooth (60fps)
-- [ ] Copy is consistent and polished
-- [ ] Icons are consistent and properly sized
-- [ ] All forms properly labeled and validated
-- [ ] Error states are helpful
-- [ ] Loading states are clear
-- [ ] Empty states are welcoming
-- [ ] Touch targets are 44x44px minimum
-- [ ] Contrast ratios meet WCAG AA
-- [ ] Keyboard navigation works
-- [ ] Focus indicators visible
-- [ ] No console errors or warnings
-- [ ] No layout shift on load
-- [ ] Works in all supported browsers
-- [ ] Respects reduced motion preference
-- [ ] Code is clean (no TODOs, console.logs, commented code)
-
-**IMPORTANT**: Polish is about details. Zoom in. Squint at it. Use it yourself. The little things add up.
-
-Sweat the details. Zoom in until the alignment is right and the spacing reads as deliberate. Then ship.
-
-**NEVER**:
-- Polish before it's functionally complete
-- Polish without aligning to the design system; that's decoration on drift
-- Guess at design system principles instead of asking when something is ambiguous
-- Spend hours on polish if it ships in 30 minutes (triage)
-- Introduce bugs while polishing (test thoroughly)
-- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
-- Perfect one thing while leaving others rough (consistent quality level)
-- Create new one-off components when design system equivalents exist
-- Hard-code values that should use design tokens
-- Introduce new patterns or flows that diverge from established ones
-
-## Final Verification
-
-Before marking as done:
-
-- **Use it yourself**: Actually interact with the feature.
-- **Test on real devices**: Not just browser DevTools.
-- **Ask someone else to review**: Fresh eyes catch things.
-- **Compare to design**: Match intended design.
-- **Check all states**: Don't just test happy path.
-- **Treat automation carefully**: Run detector or QA commands when they are available and relevant, fix their defects, but never cite a clean result as proof that the work is polished.
-
-## Clean Up
-
-After polishing, ensure code quality:
-
-- **Replace custom implementations**: If the design system provides a component you reimplemented, switch to the shared version.
-- **Remove orphaned code**: Delete unused styles, components, or files made obsolete by polish.
-- **Consolidate tokens**: If you introduced new values, check whether they should be tokens.
-- **Verify DRYness**: Look for duplication introduced during polishing and consolidate.
@@ -1,62 +0,0 @@
-# Product register
-
-When design SERVES the product: app UIs, admin dashboards, settings panels, data tables, tools, authenticated surfaces, anything where the user is in a task.
-
-## The product slop test
-
-Not "would someone say AI made this." Familiarity is often a feature here. The test is: would a user fluent in the category's best tools (Linear, Figma, Notion, Raycast, Stripe come to mind) sit down and trust this interface, or pause at every subtly-off component?
-
-Product UI's failure mode isn't flatness, it's strangeness without purpose: over-decorated buttons, mismatched form controls, gratuitous motion, display fonts where labels should be, invented affordances for standard tasks. The bar is earned familiarity. The tool should disappear into the task.
-
-## Typography
-
-- **System fonts are legitimate.** `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` gives you native feel on every platform. Inter is the common cross-platform default for a reason.
-- **One family is often right.** Product UIs don't need display/body pairing. A well-tuned sans carries headings, buttons, labels, body, data.
-- **Fixed rem scale, not fluid.** Clamp-sized headings don't serve product UI. Users view at consistent DPI, and a fluid h1 that shrinks in a sidebar looks worse, not better.
-- **Tighter scale ratio.** 1.125–1.2 between steps is typical. More type elements here than on brand surfaces; exaggerated contrast creates noise.
-- **Line length still applies for prose** (65–75ch). Data and compact UI can run denser; tables at 120ch+ are fine.
-
-## Color
-
-Product defaults to Restrained. A single surface can earn Committed (a dashboard where one category color carries a report, an onboarding flow with a drenched welcome screen), but Restrained is the floor.
-
-- State-rich semantic vocabulary: hover, focus, active, disabled, selected, loading, error, warning, success, info. Standardize these.
-- Accent color used for primary actions, current selection, and state indicators only, not decoration.
-- A second neutral layer for sidebars, toolbars, and panels (slightly cooler or warmer than the content surface).
-
-## Layout
-
-- Predictable grids. Consistency IS an affordance; users navigate faster when the structure is expected.
-- Familiar patterns are features. Standard navigation (top bar, side nav), breadcrumbs, tabs, and form layouts have established user expectations. Don't reinvent for flavor.
-- Responsive behavior is structural (collapse sidebar, responsive table, breakpoint-driven columns), not fluid typography.
-
-## Components
-
-Every interactive component has: default, hover, focus, active, disabled, loading, error. Don't ship with half of these.
-
-- Skeleton states for loading, not spinners in the middle of content.
-- Empty states that teach the interface, not "nothing here."
-- Consistent affordances across the surface. Same button shape. Same form-control vocabulary. Same icon style.
-
-## Motion
-
-- 150–250 ms on most transitions. Users are in flow; don't make them wait for choreography.
-- Motion conveys state, not decoration. State change, feedback, loading, reveal: nothing else.
-- No orchestrated page-load sequences. Product loads into a task; users don't want to watch it load.
-
-## Product bans (on top of the shared absolute bans)
-
-- Decorative motion that doesn't convey state.
-- Inconsistent component vocabulary across screens. If the "save" button looks different in two places, one is wrong.
-- Display fonts in UI labels, buttons, data.
-- Reinventing standard affordances for flavor (custom scrollbars, weird form controls, non-standard modals).
-- Heavy color or full-saturation accents on inactive states.
-
-## Product permissions
-
-Product can afford things brand surfaces can't.
-
-- System fonts and familiar sans defaults (Inter, SF Pro, system-ui stacks).
-- Standard navigation patterns: top bar + side nav, breadcrumbs, tabs, command palettes.
-- Density. Tables with many rows, panels with many labels, dense information when users need it.
-- Consistency over surprise. The same visual vocabulary screen to screen is a virtue; delight is saved for moments, not pages.
@@ -1,99 +0,0 @@
-Quiet design is harder than bold design. Subtlety needs precision. Reduce visual intensity in designs that are too loud, aggressive, or overstimulating without losing personality or making the result generic.
-
----
-
-## Register
-
-Brand: "quieter" means more restrained palette, more whitespace, more typographic air. Drama is reduced, not eliminated; the POV stays intact.
-
-Product: "quieter" means reducing visual noise. Fewer background accents, flatter cards, less color, less motion. The tool should disappear more completely into the task.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too intense:
-
-1. **Identify intensity sources**:
- - **Color saturation**: Overly bright or saturated colors
- - **Contrast extremes**: Too much high-contrast juxtaposition
- - **Visual weight**: Too many bold, heavy elements competing
- - **Animation excess**: Too much motion or overly dramatic effects
- - **Complexity**: Too many visual elements, patterns, or decorations
- - **Scale**: Everything is large and loud with no hierarchy
-
-2. **Understand the context**:
- - What's the purpose? (Marketing vs tool vs reading experience)
- - Who's the audience? (Some contexts need energy)
- - What's working? (Don't throw away good ideas)
- - What's the core message? (Preserve what matters)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Quieter" doesn't mean boring or generic. It means refined and easier on the eyes. Think luxury, not laziness.
-
-## Plan Refinement
-
-Create a strategy to reduce intensity while maintaining impact:
-
-- **Color approach**: Desaturate or shift to more restrained tones?
-- **Hierarchy approach**: Which elements should stay bold (very few), which should recede?
-- **Simplification approach**: What can be removed entirely?
-- **Sophistication approach**: How can we signal quality through restraint?
-
-**IMPORTANT**: Subtlety requires precision. Quiet without intent collapses to generic.
-
-## Refine the Design
-
-Systematically reduce intensity across these dimensions:
-
-### Color Refinement
-- **Reduce saturation**: Shift from fully saturated to 70-85% saturation
-- **Soften palette**: Replace bright colors with muted tones
-- **Reduce color variety**: Use fewer colors more thoughtfully
-- **Neutral dominance**: Let neutrals do more work, use color as accent (10% rule)
-- **Gentler contrasts**: High contrast only where it matters most
-- **Tinted grays**: Use warm or cool tinted grays instead of pure gray. Adds depth without loudness
-- **Never gray on color**: If you have gray text on a colored background, use a darker shade of that color or transparency instead
-
-### Visual Weight Reduction
-- **Typography**: Reduce font weights (900 → 600, 700 → 500), decrease sizes where appropriate
-- **Hierarchy through subtlety**: Use weight, size, and space instead of color and boldness
-- **White space**: Increase breathing room, reduce density
-- **Borders & lines**: Reduce thickness, decrease opacity, or remove entirely
-
-### Simplification
-- **Remove decorative elements**: Gradients, shadows, patterns, textures that don't serve purpose
-- **Simplify shapes**: Reduce border radius extremes, simplify custom shapes
-- **Reduce layering**: Flatten visual hierarchy where possible
-- **Clean up effects**: Reduce or remove blur effects, glows, multiple shadows
-
-### Motion Reduction
-- **Reduce animation intensity**: Shorter distances (10-20px instead of 40px), gentler easing
-- **Remove decorative animations**: Keep functional motion, remove flourishes
-- **Subtle micro-interactions**: Replace dramatic effects with gentle feedback
-- **Refined easing**: Use ease-out-quart for smooth, understated motion. Never bounce or elastic
-- **Remove animations entirely** if they're not serving a clear purpose
-
-### Composition Refinement
-- **Reduce scale jumps**: Smaller contrast between sizes creates calmer feeling
-- **Align to grid**: Bring rogue elements back into systematic alignment
-- **Even out spacing**: Replace extreme spacing variations with consistent rhythm
-
-**NEVER**:
-- Make everything the same size/weight (hierarchy still matters)
-- Remove all color (quiet ≠ grayscale)
-- Eliminate all personality (maintain character through refinement)
-- Sacrifice usability for aesthetics (functional elements still need clear affordances)
-- Make everything small and light (some anchors needed)
-
-## Verify Quality
-
-Ensure refinement maintains quality:
-
-- **Still functional**: Can users still accomplish tasks easily?
-- **Still distinctive**: Does it have character, or is it generic now?
-- **Better reading**: Is text easier to read for extended periods?
-- **Restrained, not absent**: Does the POV survive the cuts?
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,114 +0,0 @@
-# Responsive Design
-
-## Mobile-First: Write It Right
-
-Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
-
-## Breakpoints: Content-Driven
-
-Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
-
-## Detect Input Method, Not Just Screen Size
-
-**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
-
-```css
-/* Fine pointer (mouse, trackpad) */
-@media (pointer: fine) {
- .button { padding: 8px 16px; }
-}
-
-/* Coarse pointer (touch, stylus) */
-@media (pointer: coarse) {
- .button { padding: 12px 20px; } /* Larger touch target */
-}
-
-/* Device supports hover */
-@media (hover: hover) {
- .card:hover { transform: translateY(-2px); }
-}
-
-/* Device doesn't support hover (touch) */
-@media (hover: none) {
- .card { /* No hover state - use active instead */ }
-}
-```
-
-**Critical**: Don't rely on hover for functionality. Touch users can't hover.
-
-## Safe Areas: Handle the Notch
-
-Modern phones have notches, rounded corners, and home indicators. Use `env()`:
-
-```css
-body {
- padding-top: env(safe-area-inset-top);
- padding-bottom: env(safe-area-inset-bottom);
- padding-left: env(safe-area-inset-left);
- padding-right: env(safe-area-inset-right);
-}
-
-/* With fallback */
-.footer {
- padding-bottom: max(1rem, env(safe-area-inset-bottom));
-}
-```
-
-**Enable viewport-fit** in your meta tag:
-```html
-<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
-```
-
-## Responsive Images: Get It Right
-
-### srcset with Width Descriptors
-
-```html
-<img
- src="hero-800.jpg"
- srcset="
- hero-400.jpg 400w,
- hero-800.jpg 800w,
- hero-1200.jpg 1200w
- "
- sizes="(max-width: 768px) 100vw, 50vw"
- alt="Hero image"
->
-```
-
-**How it works**:
-- `srcset` lists available images with their actual widths (`w` descriptors)
-- `sizes` tells the browser how wide the image will display
-- Browser picks the best file based on viewport width AND device pixel ratio
-
-### Picture Element for Art Direction
-
-When you need different crops/compositions (not just resolutions):
-
-```html
-<picture>
- <source media="(min-width: 768px)" srcset="wide.jpg">
- <source media="(max-width: 767px)" srcset="tall.jpg">
- <img src="fallback.jpg" alt="...">
-</picture>
-```
-
-## Layout Adaptation Patterns
-
-**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
-
-## Testing: Don't Trust DevTools Alone
-
-DevTools device emulation is useful for layout but misses:
-
-- Actual touch interactions
-- Real CPU/memory constraints
-- Network latency patterns
-- Font rendering differences
-- Browser chrome/keyboard appearances
-
-**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
-
----
-
-**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
@@ -1,165 +0,0 @@
-Shape the UX and UI for a feature before any code is written. This command produces a **design brief**: a structured artifact that guides implementation through discovery, not guesswork.
-
-**Scope**: Design planning only. This command does NOT write code. It produces the thinking that makes code good.
-
-**Output**: A design brief that can be handed off to /impeccable craft, or directly to /impeccable for freeform implementation. When visual direction probes are used, the images are supporting artifacts, not the primary output.
-
-## Philosophy
-
-Most AI-generated UIs fail not because of bad code, but because of skipped thinking. They jump to "here's a card grid" without asking "what is the user trying to accomplish?" This command inverts that: understand deeply first, so implementation is precise.
-
-## Phase 1: Discovery Interview
-
-**Do NOT write any code or make any design decisions during this phase.** Your only job is to understand the feature deeply enough to make excellent design decisions later.
-
-This is a required interaction, not optional guidance. Ask these questions in conversation, adapting based on answers. Don't dump them all at once; have a natural dialogue. ask the user directly to clarify what you cannot infer.
-
-### Interview cadence
-
-Discovery includes at least one user-answer round unless PRODUCT.md, DESIGN.md, or an already-confirmed brief directly answers the needed inputs. With a sparse prompt, do **not** synthesize a complete brief for confirmation on the first response.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Treat PRODUCT.md and DESIGN.md as anchors; they reduce repeated questions but do **not** replace shape for craft. Shape is task-specific.
-- One round is the default. Add a second only if the first answers leave material gaps. Don't run a second round just to feel thorough.
-- Round 1 should clarify purpose, audience/context, content/scope, and (for brand) visual direction.
-- Round 2, when needed, fills in whatever's still genuinely missing.
-
-**Assert-then-confirm, not menu-with-escape.** When PRODUCT.md and the user's prompt make one option obvious, name it and ask the user to confirm or override. Don't enumerate "Restrained / Committed / Or something else?" as a real choice; "This reads as Restrained, confirm?" beats a four-option menu when the answer is already clear.
-
-### Purpose & Context
-- What is this feature for? What problem does it solve?
-- Who specifically will use it? (Not "users"; be specific: role, context, frequency)
-- What does success look like? How will you know this feature is working?
-- What's the user's state of mind when they reach this feature? (Rushed? Exploring? Anxious? Focused?)
-
-### Content & Data
-- What content or data does this feature display or collect?
-- What are the realistic ranges? (Minimum, typical, maximum, e.g., 0 items, 5 items, 500 items)
-- What are the edge cases? (Empty state, error state, first-time use, power user)
-- Is any content dynamic? What changes and how often?
-- What visual assets are real content here? Note required images, product shots, illustrations, maps, textures, diagrams, generated objects, or existing project assets.
-
-### Design Direction
-
-Force a visual decision on three fronts. Skip anything PRODUCT.md or DESIGN.md already answers; ask only what's missing.
-
-- **Color strategy for this surface.** Pick one: Restrained / Committed / Full palette / Drenched. Can override the project default if the surface earns it (e.g. a drenched hero inside an otherwise Restrained product).
-- **Theme via scene sentence.** Write one sentence of physical context for this surface: who uses it, where, under what ambient light, in what mood. The sentence forces dark vs light. If it doesn't, add detail until it does.
-- **Two or three named anchor references.** Specific products, brands, objects. Not adjectives like "modern" or "clean."
-
-### Scope
-
-Always ask. Sketch quality and shipped quality are different outputs; don't guess between them.
-
-- **Fidelity.** Sketch / mid-fi / high-fi / production-ready?
-- **Breadth.** One screen / a flow / a whole surface?
-- **Interactivity.** Static visual / interactive prototype / shipped-quality component?
-- **Time intent.** Quick exploration, or polish until it ships?
-
-Scope answers are task-scoped. Don't write them to PRODUCT.md or DESIGN.md; carry them through the design brief only.
-
-### Constraints
-- Are there technical constraints? (Framework, performance budget, browser support)
-- Are there content constraints? (Localization, dynamic text length, user-generated content)
-- Mobile/responsive requirements?
-- Accessibility requirements beyond WCAG AA?
-
-### Anti-Goals
-- What should this NOT be? What would be a wrong direction?
-- What's the biggest risk of getting this wrong?
-
-## Phase 1.5: Visual Direction Probe (Capability-Gated)
-
-After the discovery interview, generate a small set of visual direction probes **before** writing the final brief when all of these are true:
-
-- The work is **net-new** or directionally ambiguous enough that visual exploration will clarify the brief.
-- The requested fidelity is **mid-fi, high-fi, or production-ready**. Skip for sketch-only planning.
-- The current harness gives you native image generation (Codex's `image_gen`, an equivalent MCP tool, or similar). Don't ask the user to install APIs or tooling.
-
-When those conditions are met, this step is mandatory. If image generation isn't natively available, do not ask the user to install APIs or tooling. State in one line that the image step is skipped because the harness lacks native image generation, then proceed. The one-line announcement is required, not optional; it forces a conscious decision instead of letting the step quietly evaporate.
-
-Use probes to explore visual lanes, not to replace the brief.
-
-Do not skip probes because the final UI will be semantic, editable, code-native, responsive, or accessible. Those are implementation requirements, not reasons to avoid visual exploration.
-
-### What to generate
-
-Generate **2 to 4** distinct direction probes based on the discovery answers, especially:
-
-- Color strategy
-- Theme scene sentence
-- Named anchor references
-- Scope and fidelity
-
-The probes should differ in primary visual direction (hierarchy, topology, density, typographic voice, or color strategy), not just palette tweaks.
-
-### How to use the probes
-
-- Treat them as **direction tests**, not final designs.
-- Use them to pressure-test whether the brief is pointing at the right lane.
-- Ask the user which direction feels closest, what feels off, and what should carry forward.
-- If the probes reveal a mismatch, revise the brief inputs before finalizing the brief.
-
-### Important limits
-
-- Do **not** skip discovery because image generation is available.
-- Do **not** treat generated imagery as final UX specification, final copy, or final accessibility behavior.
-- Do **not** use this step for minor refinements of existing work. It's for shaping a new surface or clarifying a big directional choice.
-
-If image generation isn't natively available, announce the skip in one line and proceed to the design brief.
-
-## Phase 2: Design Brief
-
-After the interview and any required probes, present a brief and **end your response**. The user must confirm before any implementation runs. Do not present a brief and then continue to code in the same response, even if the brief feels obvious to you. The user's confirmation is the gate.
-
-**Choose the brief shape based on how clear the answers are:**
-
-- **Compact form (3-5 bullets)** when discovery was crisp and the original prompt + PRODUCT.md already pinned scope, content, and direction. State what you're building, the visual lane, and end with one or two specific questions or a clear "confirm or override?" prompt. This is the default for typical craft requests with a clear prompt.
-- **Full structured form (sections below)** when the task is genuinely ambiguous, multi-screen, or when the user asked for shape as a standalone step. Use this when the discipline of structure earns its weight.
-
-Don't pad a clear brief into a long one to look thorough. A 70-line brief restating answers the user just gave is noise, not rigor. Equally, don't skip the confirmation pause to look efficient: the pause is the point.
-
-Present the brief, then **stop and wait for explicit confirmation**. You are not the judge of whether the user already approved. Even when the brief feels obviously right, ask once and wait. The pause is what separates shape from premature implementation.
-
-### Brief Structure
-
-**1. Feature Summary** (2-3 sentences)
-What this is, who it's for, what it needs to accomplish.
-
-**2. Primary User Action**
-The single most important thing a user should do or understand here.
-
-**3. Design Direction**
-Color strategy (Restrained / Committed / Full palette / Drenched) + the theme scene sentence + 2–3 named anchor references. Reference PRODUCT.md and DESIGN.md where they already answer, and note any per-surface overrides.
-
-If you ran the Visual Direction Probe step, name which probe direction won and what changed in the brief because of it.
-
-**4. Scope**
-Fidelity, breadth, interactivity, and time intent from the Scope section of the interview. Task-scoped; these don't persist beyond the brief.
-
-**5. Layout Strategy**
-High-level spatial approach: what gets emphasis, what's secondary, how information flows. Describe the visual hierarchy and rhythm, not specific CSS.
-
-**6. Key States**
-List every state the feature needs: default, empty, loading, error, success, edge cases. For each, note what the user needs to see and feel.
-
-**7. Interaction Model**
-How users interact with this feature. What happens on click, hover, scroll? What feedback do they get? What's the flow from entry to completion?
-
-**8. Content Requirements**
-What copy, labels, empty state messages, error messages, and microcopy are needed. Note any dynamic content and its realistic ranges. For image-led surfaces, also list the required image/media roles and their likely source (project asset, generated raster, semantic SVG/CSS, canvas/WebGL, icon library, or accepted omission).
-
-**9. Recommended References**
-Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., spatial-design.md for complex layouts, motion-design.md for animated features, interaction-design.md for form-heavy features).
-
-**10. Open Questions**
-Anything genuinely unresolved. Don't list "open questions" you've already recommended a default for; assert the default and move on. If you'd write `Recommend: X` next to a question, just decide X.
-
----
-
-ask the user directly to clarify what you cannot infer. Ask for explicit confirmation of the brief before finishing.
-
-If the user disagrees with any part, revisit the relevant discovery questions. A shape run is incomplete until the user confirms direction.
-
-Once confirmed, the brief is complete. The user can now hand it to /impeccable, or use it to guide any other implementation approach. (If the user wants the full discovery-then-build flow in one step, they should use /impeccable craft instead, which runs this command internally.)
@@ -1,100 +0,0 @@
-# Spatial Design
-
-## Spacing Systems
-
-### Use 4pt Base, Not 8pt
-
-8pt systems are too coarse; you'll frequently need 12px (between 8 and 16). Use 4pt for granularity: 4, 8, 12, 16, 24, 32, 48, 64, 96px.
-
-### Name Tokens Semantically
-
-Name by relationship (`--space-sm`, `--space-lg`), not value (`--spacing-8`). Use `gap` instead of margins for sibling spacing; it eliminates margin collapse and cleanup hacks.
-
-## Grid Systems
-
-### The Self-Adjusting Grid
-
-Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Columns are at least 280px, as many as fit per row, leftovers stretch. For complex layouts, use named grid areas (`grid-template-areas`) and redefine them at breakpoints.
-
-## Visual Hierarchy
-
-### The Squint Test
-
-Blur your eyes (or screenshot and blur). Can you still identify:
-- The most important element?
-- The second most important?
-- Clear groupings?
-
-If everything looks the same weight blurred, you have a hierarchy problem.
-
-### Hierarchy Through Multiple Dimensions
-
-Don't rely on size alone. Combine:
-
-| Tool | Strong Hierarchy | Weak Hierarchy |
-|------|------------------|----------------|
-| **Size** | 3:1 ratio or more | <2:1 ratio |
-| **Weight** | Bold vs Regular | Medium vs Regular |
-| **Color** | High contrast | Similar tones |
-| **Position** | Top/left (primary) | Bottom/right |
-| **Space** | Surrounded by white space | Crowded |
-
-**The best hierarchy uses 2-3 dimensions at once**: A heading that's larger, bolder, AND has more space above it.
-
-### Cards Are Not Required
-
-Cards are overused. Spacing and alignment create visual grouping naturally. Use cards only when content is truly distinct and actionable, items need visual comparison in a grid, or content needs clear interaction boundaries. **Never nest cards inside cards.** Use spacing, typography, and subtle dividers for hierarchy within a card.
-
-## Container Queries
-
-Viewport queries are for page layouts. **Container queries are for components**:
-
-```css
-.card-container {
- container-type: inline-size;
-}
-
-.card {
- display: grid;
- gap: var(--space-md);
-}
-
-/* Card layout changes based on its container, not viewport */
-@container (min-width: 400px) {
- .card {
- grid-template-columns: 120px 1fr;
- }
-}
-```
-
-**Why this matters**: A card in a narrow sidebar stays compact, while the same card in a main content area expands automatically, without viewport hacks.
-
-## Optical Adjustments
-
-Text at `margin-left: 0` looks indented due to letterform whitespace; use negative margin (`-0.05em`) to optically align. Geometrically centered icons often look off-center; play icons need to shift right, arrows shift toward their direction.
-
-### Touch Targets vs Visual Size
-
-Buttons can look small but need large touch targets (44px minimum). Use padding or pseudo-elements:
-
-```css
-.icon-button {
- width: 24px; /* Visual size */
- height: 24px;
- position: relative;
-}
-
-.icon-button::before {
- content: '';
- position: absolute;
- inset: -10px; /* Expand tap target to 44px */
-}
-```
-
-## Depth & Elevation
-
-Create semantic z-index scales (dropdown → sticky → modal-backdrop → modal → toast → tooltip) instead of arbitrary numbers. For shadows, create a consistent elevation scale (sm → md → lg → xl). **Key insight**: Shadows should be subtle. If you can clearly see it, it's probably too strong.
-
----
-
-**Avoid**: Arbitrary spacing values outside your scale. Making all spacing equal (variety creates hierarchy). Creating hierarchy through size alone - combine size, weight, color, and space.
@@ -1,156 +0,0 @@
-# Teach Flow
-
-Gathers design context for a project and writes two complementary files at the project root:
-
-- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
-- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
-
-Every other impeccable command reads these files before doing any work.
-
-## Step 1: Load current state
-
-Run the shared loader first so you know what already exists:
-
-```bash
-node .gemini/skills/impeccable/scripts/load-context.mjs
-```
-
-The output tells you whether PRODUCT.md and/or DESIGN.md already exist. If `migrated: true`, legacy `.impeccable.md` was auto-renamed to `PRODUCT.md`. Mention this once to the user.
-
-Decision tree:
-- **Neither file exists (empty project or no context yet)**: do Steps 2-4 (write PRODUCT.md), then decide on DESIGN.md based on whether there's code to analyze.
-- **PRODUCT.md exists, DESIGN.md missing**: skip to Step 5 and offer to run `/impeccable document` for DESIGN.md.
-- **PRODUCT.md exists but has no `## Register` section (legacy)**: add it. Infer a hypothesis from the codebase (see Step 2), confirm with the user, write the field.
-- **Both exist**: ask the user directly to clarify what you cannot infer. Ask which file to refresh. Skip the one the user doesn't want changed.
-- **Just DESIGN.md exists (unusual)**: do Steps 2-4 to produce PRODUCT.md.
-
-Never silently overwrite an existing file. Always confirm first.
-
-If teach was invoked as a setup blocker by another command, such as `/impeccable craft landing page`, pause that command here. Complete teach, re-run the loader, then resume the original command with the freshly loaded context. For craft, resume into shape next; teach creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
-
-## Step 2: Explore the codebase
-
-Before asking questions, thoroughly scan the project to discover what you can:
-
-- **README and docs**: Project purpose, target audience, any stated goals
-- **Package.json / config files**: Tech stack, dependencies, existing design libraries
-- **Existing components**: Current design patterns, spacing, typography in use
-- **Brand assets**: Logos, favicons, color values already defined
-- **Design tokens / CSS variables**: Existing color palettes, font stacks, spacing scales
-- **Any style guides or brand documentation**
-
-Also form a **register hypothesis** from what you find:
-
-- Brand signals: `/`, `/about`, `/pricing`, `/blog/*`, `/docs/*`, hero sections, big typography, scroll-driven sections, landing-page-shaped content.
-- Product signals: `/app/*`, `/dashboard`, `/settings`, `/(auth)`, forms, data tables, side/top nav, app-shell components.
-
-Register is a hypothesis at this point, not a decision; Step 3 confirms it.
-
-Note what you've learned and what remains unclear. This exploration feeds both PRODUCT.md and DESIGN.md.
-
-## Step 3: Ask strategic questions (for PRODUCT.md)
-
-ask the user directly to clarify what you cannot infer. Ask only about what you couldn't infer from the codebase.
-
-### Interview mode, not confirmation mode
-
-If the repo is empty or the user's brief is sparse, run a short interview before proposing PRODUCT.md. Do **not** turn a one-sentence request into a complete inferred PRODUCT.md and ask for blanket confirmation.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Use inferred answers as hypotheses or options, not as finished facts.
-- Complete at least one real user-answer round before drafting PRODUCT.md, unless every required answer is directly discoverable from repo docs.
-- Round 1 should establish register, users/purpose, and desired outcome.
-- Round 2 should establish brand personality or references, anti-references, and accessibility needs.
-
-### Minimum viable interview
-
-Ask enough to complete PRODUCT.md. At minimum, cover register confirmation, users and purpose, brand personality, anti-references, and accessibility needs unless each answer is directly discoverable from repo context. After at least one interview round, you may propose inferred answers, but the user must confirm them before you write PRODUCT.md. Never synthesize PRODUCT.md from the original task prompt alone.
-
-### Register (ask first; it shapes everything below)
-
-Every design task is either **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboards, tools: design SERVES the product).
-
-If Step 2 produced a clear hypothesis, lead with it: *"From the codebase, this looks like a [brand / product] surface. Does that match your intent, or should we treat it differently?"*
-
-If the signal is genuinely split (e.g. a product with a big marketing landing), ask the user directly to clarify what you cannot infer. Ask which register describes the **primary** surface. The register can be overridden per task later, but PRODUCT.md carries one default.
-
-### Users & Purpose
-- Who uses this? What's their context when using it?
-- What job are they trying to get done?
-- For brand: what emotions should the interface evoke? (confidence, delight, calm, urgency)
-- For product: what workflow are they in? What's the primary task on any given screen?
-
-### Brand & Personality
-- How would you describe the brand personality in 3 words?
-- Reference sites or apps that capture the right feel? What specifically about them?
- - For brand, push for real-world references in the right lane (tech-minimal, editorial-magazine, consumer-warm, brutalist-grid, etc.), not generic "modern" adjectives.
- - For product, push for category best-tool references (Linear, Figma, Notion, Raycast, Stripe).
-- What should this explicitly NOT look like? Any anti-references?
-
-### Accessibility & Inclusion
-- Specific accessibility requirements? (WCAG level, known user needs)
-- Considerations for reduced motion, color blindness, or other accommodations?
-
-Skip questions where the answer is already clear. **Do NOT ask about colors, fonts, radii, or visual styling here.** Those belong in DESIGN.md, not PRODUCT.md.
-
-## Step 4: Write PRODUCT.md
-
-Write PRODUCT.md only after the user has confirmed the strategic answers from Step 3. If an inferred answer is uncertain or unconfirmed, ask before writing.
-
-Synthesize into a strategic document:
-
-```markdown
-# Product
-
-## Register
-
-product
-
-## Users
-[Who they are, their context, the job to be done]
-
-## Product Purpose
-[What this product does, why it exists, what success looks like]
-
-## Brand Personality
-[Voice, tone, 3-word personality, emotional goals]
-
-## Anti-references
-[What this should NOT look like. Specific bad-example sites or patterns to avoid.]
-
-## Design Principles
-[3-5 strategic principles derived from the conversation. Principles like "practice what you preach", "show, don't tell", "expert confidence". NOT visual rules like "use OKLCH" or "magenta accent".]
-
-## Accessibility & Inclusion
-[WCAG level, known user needs, considerations]
-```
-
-Register is either `brand` or `product` as a bare value. No prose, no commentary.
-
-Write to `PROJECT_ROOT/PRODUCT.md`. If `.impeccable.md` existed, the loader already renamed it; merge into that content rather than starting from scratch.
-
-## Step 5: Decide on DESIGN.md
-
-Offer `/impeccable document` either way. Two paths:
-
-- **Code exists** (CSS tokens, components, a running site): "I can generate a DESIGN.md that captures your visual system (colors, typography, components) so variants stay on-brand. Want to do that now?"
-- **Pre-implementation** (empty project): "I can seed a starter DESIGN.md from five quick questions about color strategy, type direction, motion energy, and references. You can re-run once there's code, to capture the real tokens. Want to do that now?"
-
-If the user agrees, delegate to `/impeccable document` (it auto-detects scan vs seed). Load its reference and follow that flow.
-
-If the user prefers to skip, mention they can run `/impeccable document` any time later.
-
-## Step 6: Confirm and wrap up
-
-Summarize:
-- Register captured (brand / product)
-- What was written (PRODUCT.md, DESIGN.md, or both)
-- The 3-5 strategic principles from PRODUCT.md that will guide future work
-- If DESIGN.md is pending, remind the user how to generate it later
-
-**Critical: re-run the loader to refresh session context.** After writing PRODUCT.md, run `node .gemini/skills/impeccable/scripts/load-context.mjs` one final time and let its full JSON output land in conversation. This ensures subsequent commands in this session use the freshly-written PRODUCT.md, not a stale earlier version.
-
-If teach was invoked as a blocker by another impeccable command (e.g. the user ran `/impeccable polish` with no PRODUCT.md), resume that original task now with the fresh context.
-
-Optionally ask the user directly to clarify what you cannot infer. Ask whether they'd like a brief summary of PRODUCT.md appended to GEMINI.md for easier agent reference. If yes, append a short **Design Context** pointer section there.
@@ -1,124 +0,0 @@
-Typography carries most of the information on the page. Replace generic defaults (Inter, Roboto, system fallback at flat scale) with type that reflects the brand and scales with intentional contrast.
-
----
-
-## Register
-
-Brand: run the font selection procedure in [brand.md](brand.md). Pairing follows the brand's lane (display serif + sans body for editorial/luxury, one committed sans for tech, etc.). Fluid `clamp()` scale, ≥1.25 ratio between steps.
-
-Product: system fonts and familiar sans stacks are legitimate here. One well-tuned family typically carries the whole UI. Fixed `rem` scale, 1.125–1.2 ratio between more closely-spaced steps.
-
----
-
-## Assess Current Typography
-
-Analyze what's weak or generic about the current type:
-
-1. **Font choices**:
- - Are we using invisible defaults? (Inter, Roboto, Arial, Open Sans, system defaults)
- - Does the font match the brand personality? (A playful brand shouldn't use a corporate typeface)
- - Are there too many font families? (More than 2-3 is almost always a mess)
-
-2. **Hierarchy**:
- - Can you tell headings from body from captions at a glance?
- - Are font sizes too close together? (14px, 15px, 16px = muddy hierarchy)
- - Are weight contrasts strong enough? (Medium vs Regular is barely visible)
-
-3. **Sizing & scale**:
- - Is there a consistent type scale, or are sizes arbitrary?
- - Does body text meet minimum readability? (16px+)
- - Is the sizing strategy appropriate for the context? (Fixed `rem` scales for app UIs; fluid `clamp()` for marketing/content page headings)
-
-4. **Readability**:
- - Are line lengths comfortable? (45-75 characters ideal)
- - Is line-height appropriate for the font and context?
- - Is there enough contrast between text and background?
-
-5. **Consistency**:
- - Are the same elements styled the same way throughout?
- - Are font weights used consistently? (Not bold in one section, semibold in another for the same role)
- - Is letter-spacing intentional or default everywhere?
-
-**CRITICAL**: The goal isn't to make text "fancier." It's to make it clearer, more readable, and more intentional. Good typography is invisible; bad typography is distracting.
-
-## Plan Typography Improvements
-
-Consult the [typography reference](typography.md) for detailed guidance on scales, pairing, and loading strategies.
-
-Create a systematic plan:
-
-- **Font selection**: Do fonts need replacing? What fits the brand/context?
-- **Type scale**: Establish a modular scale (e.g., 1.25 ratio) with clear hierarchy
-- **Weight strategy**: Which weights serve which roles? (Regular for body, Semibold for labels, Bold for headings, or whatever fits)
-- **Spacing**: Line-heights, letter-spacing, and margins between typographic elements
-
-## Improve Typography Systematically
-
-### Font Selection
-
-If fonts need replacing:
-- Choose fonts that reflect the brand personality
-- Pair with genuine contrast (serif + sans, geometric + humanist), or use a single family in multiple weights
-- Ensure web font loading doesn't cause layout shift (`font-display: swap`, metric-matched fallbacks)
-
-### Establish Hierarchy
-
-Build a clear type scale:
-- **5 sizes cover most needs**: caption, secondary, body, subheading, heading
-- **Use a consistent ratio** between levels (1.25, 1.333, or 1.5)
-- **Combine dimensions**: Size + weight + color + space for strong hierarchy. Don't rely on size alone
-- **App UIs**: Use a fixed `rem`-based type scale, optionally adjusted at 1-2 breakpoints. Fluid sizing undermines the spatial predictability that dense, container-based layouts need
-- **Marketing / content pages**: Use fluid sizing via `clamp(min, preferred, max)` for headings and display text. Keep body text fixed
-
-### Fix Readability
-
-- Set `max-width` on text containers using `ch` units (`max-width: 65ch`)
-- Adjust line-height per context: tighter for headings (1.1-1.2), looser for body (1.5-1.7)
-- Increase line-height slightly for light-on-dark text
-- Ensure body text is at least 16px / 1rem
-
-### Refine Details
-
-- Use `tabular-nums` for data tables and numbers that should align
-- Apply proper `letter-spacing`: slightly open for small caps and uppercase, default or tight for large display text
-- Use semantic token names (`--text-body`, `--text-heading`), not value names (`--font-16`)
-- Set `font-kerning: normal` and consider OpenType features where appropriate
-
-### Weight Consistency
-
-- Define clear roles for each weight and stick to them
-- Don't use more than 3-4 weights (Regular, Medium, Semibold, Bold is plenty)
-- Load only the weights you actually use (each weight adds to page load)
-
-**NEVER**:
-- Use more than 2-3 font families
-- Pick sizes arbitrarily; commit to a scale
-- Set body text below 16px
-- Use decorative/display fonts for body text
-- Disable browser zoom (`user-scalable=no`)
-- Use `px` for font sizes; use `rem` to respect user settings
-- Default to Inter/Roboto/Open Sans when personality matters
-- Pair fonts that are similar but not identical (two geometric sans-serifs)
-
-## Verify Typography Improvements
-
-- **Hierarchy**: Can you identify heading vs body vs caption instantly?
-- **Readability**: Is body text comfortable to read in long passages?
-- **Consistency**: Are same-role elements styled identically throughout?
-- **Personality**: Does the typography reflect the brand?
-- **Performance**: Are web fonts loading efficiently without layout shift?
-- **Accessibility**: Does text meet WCAG contrast ratios? Is it zoomable to 200%?
-
-When the type carries the hierarchy on its own, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `scale` param controlling the hierarchy ratio. Express all font sizes in the variant's scoped CSS through `calc(var(--p-scale, 1) * <base>)` or, better, scale the type ramp via `clamp(min, calc(var(--p-scale, 1) * Npx), max)`. Users slide from subdued to commanding.
-
-```json
-{"id":"scale","kind":"range","min":0.85,"max":1.3,"step":0.05,"default":1,"label":"Scale"}
-```
-
-Where the variant riffs on a specific pairing, expose the pairing choice as a `steps` param (e.g. "serif display + sans body" vs. "mono display + sans body" vs. "all-sans"). Each branch routes through `:scope[data-p-pairing="X"]` selectors in scoped CSS.
-
-See `reference/live.md` for the full params contract.
@@ -1,159 +0,0 @@
-# Typography
-
-## Classic Typography Principles
-
-### Vertical Rhythm
-
-Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
-
-### Modular Scale & Hierarchy
-
-The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
-
-**Use fewer sizes with more contrast.** A 5-size system covers most needs:
-
-| Role | Typical Ratio | Use Case |
-|------|---------------|----------|
-| xs | 0.75rem | Captions, legal |
-| sm | 0.875rem | Secondary UI, metadata |
-| base | 1rem | Body text |
-| lg | 1.25-1.5rem | Subheadings, lead text |
-| xl+ | 2-4rem | Headlines, hero text |
-
-Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
-
-### Readability & Measure
-
-Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
-
-**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
-
-**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
-
-## Font Selection & Pairing
-
-The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
-
-### Anti-reflexes worth defending against
-
-- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
-- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
-- A children's product does NOT need a rounded display font. Kids' books use real type.
-- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
-
-**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
-
-### Pairing Principles
-
-**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
-
-When pairing, contrast on multiple axes:
-- Serif + Sans (structure contrast)
-- Geometric + Humanist (personality contrast)
-- Condensed display + Wide body (proportion contrast)
-
-**Never pair fonts that are similar but not identical** (e.g., two geometric sans-serifs). They create visual tension without clear hierarchy.
-
-### Web Font Loading
-
-The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
-
-```css
-/* 1. Use font-display: swap for visibility */
-@font-face {
- font-family: 'CustomFont';
- src: url('font.woff2') format('woff2');
- font-display: swap;
-}
-
-/* 2. Match fallback metrics to minimize shift */
-@font-face {
- font-family: 'CustomFont-Fallback';
- src: local('Arial');
- size-adjust: 105%; /* Scale to match x-height */
- ascent-override: 90%; /* Match ascender height */
- descent-override: 20%; /* Match descender depth */
- line-gap-override: 10%; /* Match line spacing */
-}
-
-body {
- font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
-}
-```
-
-Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
-
-**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
-
-**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
-
-**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
-
-## Modern Web Typography
-
-### Fluid Type
-
-Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
-
-**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
-
-**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
-
-**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
-
-**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
-
-### OpenType Features
-
-Most developers don't know these exist. Use them for polish:
-
-```css
-/* Tabular numbers for data alignment */
-.data-table { font-variant-numeric: tabular-nums; }
-
-/* Proper fractions */
-.recipe-amount { font-variant-numeric: diagonal-fractions; }
-
-/* Small caps for abbreviations */
-abbr { font-variant-caps: all-small-caps; }
-
-/* Disable ligatures in code */
-code { font-variant-ligatures: none; }
-
-/* Enable kerning (usually on by default, but be explicit) */
-body { font-kerning: normal; }
-```
-
-Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
-
-### Rendering polish
-
-```css
-/* Even out heading line lengths (browser picks better break points) */
-h1, h2, h3 { text-wrap: balance; }
-
-/* Reduce orphans and ragged endings in long prose */
-article p { text-wrap: pretty; }
-
-/* Variable fonts: pick the right optical-size master automatically */
-body { font-optical-sizing: auto; }
-```
-
-**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
-
-## Typography System Architecture
-
-Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
-
-## Accessibility Considerations
-
-Beyond contrast ratios (which are well-documented), consider:
-
-- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
-- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
-- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
-- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
-
----
-
-**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
@@ -1,107 +0,0 @@
-# UX Writing
-
-## The Button Label Problem
-
-**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
-
-| Bad | Good | Why |
-|-----|------|-----|
-| OK | Save changes | Says what will happen |
-| Submit | Create account | Outcome-focused |
-| Yes | Delete message | Confirms the action |
-| Cancel | Keep editing | Clarifies what "cancel" means |
-| Click here | Download PDF | Describes the destination |
-
-**For destructive actions**, name the destruction:
-- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
-- "Delete 5 items" not "Delete selected" (show the count)
-
-## Error Messages: The Formula
-
-Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
-
-### Error Message Templates
-
-| Situation | Template |
-|-----------|----------|
-| **Format error** | "[Field] needs to be [format]. Example: [example]" |
-| **Missing required** | "Please enter [what's missing]" |
-| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
-| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
-| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
-
-### Don't Blame the User
-
-Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
-
-## Empty States Are Opportunities
-
-Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
-
-## Voice vs Tone
-
-**Voice** is your brand's personality, consistent everywhere.
-**Tone** adapts to the moment.
-
-| Moment | Tone Shift |
-|--------|------------|
-| Success | Celebratory, brief: "Done! Your changes are live." |
-| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
-| Loading | Reassuring: "Saving your work..." |
-| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
-
-**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
-
-## Writing for Accessibility
-
-**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
-
-## Writing for Translation
-
-### Plan for Expansion
-
-German text is ~30% longer than English. Allocate space:
-
-| Language | Expansion |
-|----------|-----------|
-| German | +30% |
-| French | +20% |
-| Finnish | +30-40% |
-| Chinese | -30% (fewer chars, but same width) |
-
-### Translation-Friendly Patterns
-
-Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
-
-## Consistency: The Terminology Problem
-
-Pick one term and stick with it:
-
-| Inconsistent | Consistent |
-|--------------|------------|
-| Delete / Remove / Trash | Delete |
-| Settings / Preferences / Options | Settings |
-| Sign in / Log in / Enter | Sign in |
-| Create / Add / New | Create |
-
-Build a terminology glossary and enforce it. Variety creates confusion.
-
-## Avoid Redundant Copy
-
-If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
-
-## Loading States
-
-Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
-
-## Confirmation Dialogs: Use Sparingly
-
-Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
-
-## Form Instructions
-
-Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
-
----
-
-**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
@@ -1,284 +0,0 @@
-#!/usr/bin/env node
-/**
- * Cleans up deprecated Impeccable skill files, symlinks, and
- * skills-lock.json entries left over from previous versions.
- *
- * Safe to run repeatedly -- it is a no-op when nothing needs cleaning.
- *
- * Usage (from the project root):
- * node {{scripts_path}}/cleanup-deprecated.mjs
- *
- * What it does:
- * 1. Finds every harness-specific skills directory (.claude/skills,
- * .cursor/skills, .agents/skills, etc.).
- * 2. For each deprecated skill name (with and without i- prefix),
- * checks if the directory exists and its SKILL.md mentions
- * "impeccable" (to avoid deleting unrelated user skills).
- * 3. Deletes confirmed matches (files, directories, or symlinks).
- * 4. Removes the corresponding entries from skills-lock.json.
- */
-
-import { existsSync, readFileSync, writeFileSync, rmSync, readdirSync, statSync, lstatSync, unlinkSync } from 'node:fs';
-import { join, resolve } from 'node:path';
-
-// Skills that were renamed, merged, or folded in v2.0, v2.1, and v3.0.
-const DEPRECATED_NAMES = [
- // v2.0 renames
- 'frontend-design', // renamed to impeccable
- 'teach-impeccable', // folded into /impeccable teach
- // v2.1 merges
- 'arrange', // renamed to layout
- 'normalize', // merged into polish
- 'onboard', // merged into harden
- 'extract', // merged into /impeccable extract
- // v3.0 consolidation: all standalone skills -> /impeccable sub-commands
- 'adapt',
- 'animate',
- 'audit',
- 'bolder',
- 'clarify',
- 'colorize',
- 'critique',
- 'delight',
- 'distill',
- 'harden',
- 'layout',
- 'optimize',
- 'overdrive',
- 'polish',
- 'quieter',
- 'shape',
- 'typeset',
-];
-
-// All known harness directories that may contain a skills/ subfolder.
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Per-skill fingerprints for SKILL.md bodies that never mentioned
-// "impeccable" in their v2.x source. Used as a last-resort match
-// when no skills-lock.json exists and the word heuristic fails.
-// The strings are lifted verbatim from the v2.x frontmatter
-// descriptions, so collisions with hand-written user skills are
-// vanishingly unlikely.
-const SKILL_FINGERPRINTS = {
- harden: 'Make interfaces production-ready: error handling, empty states',
- optimize: 'Diagnoses and fixes UI performance across loading speed',
-};
-
-/**
- * Walk up from startDir until we find a directory that looks like a
- * project root (has package.json, .git, or skills-lock.json).
- */
-export function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- const { root } = { root: '/' };
- while (dir !== root) {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Load skills-lock.json from the project root, or null if missing/unreadable.
- */
-export function loadLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return null;
- try {
- return JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return null;
- }
-}
-
-/**
- * Check whether a skill directory belongs to Impeccable. Three layered
- * signals, in order of reliability:
- * 1. Lock source equals "pbakaus/impeccable" (authoritative).
- * 2. SKILL.md body contains the word "impeccable".
- * 3. SKILL.md body contains a per-skill fingerprint (for harden and
- * optimize, whose v2.x SKILL.md never mentioned the pack name).
- */
-export function isImpeccableSkill(skillDir, { skillName, lock } = {}) {
- // 1. Authoritative: the lock file claims this skill is ours.
- if (skillName && lock?.skills?.[skillName]?.source === 'pbakaus/impeccable') {
- return true;
- }
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) return false;
- let content;
- try {
- content = readFileSync(skillMd, 'utf-8');
- } catch {
- return false;
- }
- // 2. Word-level content heuristic.
- if (/impeccable/i.test(content)) return true;
- // 3. Per-skill fingerprint for old skills that never mentioned the pack.
- // Strip the i- prefix so both `harden` and `i-harden` resolve to the
- // same fingerprint entry.
- const unprefixed = skillName?.startsWith('i-') ? skillName.slice(2) : skillName;
- const fingerprint = unprefixed && SKILL_FINGERPRINTS[unprefixed];
- if (fingerprint && content.includes(fingerprint)) return true;
- return false;
-}
-
-/**
- * Build the full list of names to check: each deprecated name, plus
- * its i-prefixed variant.
- */
-export function buildTargetNames() {
- const names = [];
- for (const name of DEPRECATED_NAMES) {
- names.push(name);
- names.push(`i-${name}`);
- }
- return names;
-}
-
-/**
- * Find every skills directory across all harness dirs in the project.
- * Returns absolute paths that exist on disk.
- */
-export function findSkillsDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const candidate = join(projectRoot, harness, 'skills');
- if (existsSync(candidate)) {
- dirs.push(candidate);
- }
- }
- return dirs;
-}
-
-/**
- * Remove deprecated skill directories/symlinks from all harness dirs.
- * Reads skills-lock.json so the authoritative "source" field can
- * drive deletion even when SKILL.md never mentions impeccable.
- * Returns an array of paths that were deleted.
- */
-export function removeDeprecatedSkills(projectRoot, lock) {
- if (lock === undefined) lock = loadLock(projectRoot);
- const targets = buildTargetNames();
- const skillsDirs = findSkillsDirs(projectRoot);
- const deleted = [];
-
- for (const skillsDir of skillsDirs) {
- for (const name of targets) {
- const skillPath = join(skillsDir, name);
-
- // Use lstat to detect symlinks (existsSync follows symlinks and
- // returns false for dangling ones).
- let stat;
- try {
- stat = lstatSync(skillPath);
- } catch {
- continue; // does not exist at all
- }
-
- if (stat.isSymbolicLink()) {
- // Symlink: check the target if it's alive, otherwise treat
- // dangling symlinks to deprecated names as safe to remove.
- const targetAlive = existsSync(skillPath);
- const isMatch = targetAlive
- ? isImpeccableSkill(skillPath, { skillName: name, lock })
- : true;
- if (isMatch) {
- unlinkSync(skillPath);
- deleted.push(skillPath);
- }
- continue;
- }
-
- // Regular directory -- verify it belongs to impeccable
- if (isImpeccableSkill(skillPath, { skillName: name, lock })) {
- rmSync(skillPath, { recursive: true, force: true });
- deleted.push(skillPath);
- }
- }
- }
-
- return deleted;
-}
-
-/**
- * Remove deprecated entries from skills-lock.json.
- * Only removes entries whose source is "pbakaus/impeccable".
- * Returns the list of removed skill names.
- */
-export function cleanSkillsLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return [];
-
- let lock;
- try {
- lock = JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return [];
- }
-
- if (!lock.skills || typeof lock.skills !== 'object') return [];
-
- const targets = buildTargetNames();
- const removed = [];
-
- for (const name of targets) {
- const entry = lock.skills[name];
- if (!entry) continue;
- // Only remove if it belongs to impeccable
- if (entry.source === 'pbakaus/impeccable') {
- delete lock.skills[name];
- removed.push(name);
- }
- }
-
- if (removed.length > 0) {
- writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\n', 'utf-8');
- }
-
- return removed;
-}
-
-/**
- * Run the full cleanup. Returns a summary object.
- *
- * Order matters: read the lock and delete directories first, then
- * strip lock entries. Otherwise the authoritative signal is gone by
- * the time directory deletion runs.
- */
-export function cleanup(projectRoot) {
- const root = projectRoot || findProjectRoot();
- const lock = loadLock(root);
- const deletedPaths = removeDeprecatedSkills(root, lock);
- const removedLockEntries = cleanSkillsLock(root);
- return { deletedPaths, removedLockEntries, projectRoot: root };
-}
-
-// CLI entry point
-if (process.argv[1] && resolve(process.argv[1]) === resolve(new URL(import.meta.url).pathname)) {
- const result = cleanup();
- if (result.deletedPaths.length === 0 && result.removedLockEntries.length === 0) {
- console.log('No deprecated Impeccable skills found. Nothing to clean up.');
- } else {
- if (result.deletedPaths.length > 0) {
- console.log(`Removed ${result.deletedPaths.length} deprecated skill(s):`);
- for (const p of result.deletedPaths) console.log(` - ${p}`);
- }
- if (result.removedLockEntries.length > 0) {
- console.log(`Cleaned ${result.removedLockEntries.length} entry/entries from skills-lock.json:`);
- for (const name of result.removedLockEntries) console.log(` - ${name}`);
- }
- }
-}
@@ -1,94 +0,0 @@
-{
- "craft": {
- "description": "Full confirmed-brief-then-build flow. Runs multi-round shape discovery first, resolves visual probe and north-star mock gates when available, then builds and visually iterates. Use when building a new feature end-to-end.",
- "argumentHint": "[feature description]"
- },
- "teach": {
- "description": "Gathers design context for a project. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles) and, when code exists to analyze, DESIGN.md (visual: colors, typography, components). Every other command reads these files before doing work. Use once per project.",
- "argumentHint": ""
- },
- "document": {
- "description": "Generate a DESIGN.md file that captures the current visual design system. Auto-extracts colors, typography, spacing, radii, and component patterns from the codebase, then asks the user to confirm descriptive language for atmosphere and color character. Follows the Google Stitch DESIGN.md format so the file is tool-compatible. Use when you need a visual design spec an AI agent can follow to stay on-brand.",
- "argumentHint": ""
- },
- "extract": {
- "description": "Pull reusable patterns, components, and design tokens into the design system. Identifies repeated patterns and consolidates them. Use when you have drift across the codebase and want to bring things back to a consistent system.",
- "argumentHint": "[target]"
- },
- "live": {
- "description": "Interactive live variant mode. Select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via HMR. Requires a running dev server. Use when you want to visually experiment with design alternatives in real time.",
- "argumentHint": ""
- },
- "adapt": {
- "description": "Adapt designs to work across different screen sizes, devices, contexts, or platforms. Implements breakpoints, fluid layouts, and touch targets. Use when the user mentions responsive design, mobile layouts, breakpoints, viewport adaptation, or cross-device compatibility.",
- "argumentHint": "[target] [context (mobile, tablet, print...)]"
- },
- "animate": {
- "description": "Review a feature and enhance it with purposeful animations, micro-interactions, and motion effects that improve usability and delight. Use when the user mentions adding animation, transitions, micro-interactions, motion design, hover effects, or making the UI feel more alive.",
- "argumentHint": "[target]"
- },
- "audit": {
- "description": "Run technical quality checks across accessibility, performance, theming, responsive design, and anti-patterns. Generates a scored report with P0-P3 severity ratings and actionable plan. Use when the user wants an accessibility check, performance audit, or technical quality review.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "bolder": {
- "description": "Amplify safe or boring designs to make them more visually interesting and stimulating. Increases impact while maintaining usability. Use when the user says the design looks bland, generic, too safe, lacks personality, or wants more visual impact and character.",
- "argumentHint": "[target]"
- },
- "clarify": {
- "description": "Improve unclear UX copy, error messages, microcopy, labels, and instructions to make interfaces easier to understand. Use when the user mentions confusing text, unclear labels, bad error messages, hard-to-follow instructions, or wanting better UX writing.",
- "argumentHint": "[target]"
- },
- "colorize": {
- "description": "Add strategic color to features that are too monochromatic or lack visual interest, making interfaces more engaging and expressive. Use when the user mentions the design looking gray, dull, lacking warmth, needing more color, or wanting a more vibrant or expressive palette.",
- "argumentHint": "[target]"
- },
- "critique": {
- "description": "Evaluate design from a UX perspective, assessing visual hierarchy, information architecture, emotional resonance, cognitive load, and overall quality with quantitative scoring, persona-based testing, automated anti-pattern detection, and actionable feedback. Use when the user asks to review, critique, evaluate, or give feedback on a design or component.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "delight": {
- "description": "Add moments of joy, personality, and unexpected touches that make interfaces memorable and enjoyable to use. Elevates functional to delightful. Use when the user asks to add polish, personality, animations, micro-interactions, delight, or make an interface feel fun or memorable.",
- "argumentHint": "[target]"
- },
- "distill": {
- "description": "Strip designs to their essence by removing unnecessary complexity. Great design is simple, powerful, and clean. Use when the user asks to simplify, declutter, reduce noise, remove elements, or make a UI cleaner and more focused.",
- "argumentHint": "[target]"
- },
- "harden": {
- "description": "Make interfaces production-ready: error handling, i18n, text overflow, edge case management, and resilience under real-world data. Use when the user asks to harden, make production-ready, handle edge cases, add error states, or fix overflow and i18n issues.",
- "argumentHint": "[target]"
- },
- "onboard": {
- "description": "Design onboarding flows, first-run experiences, and empty states that guide new users to value. Covers welcome screens, account setup, progressive disclosure, contextual tooltips, feature announcements, and activation moments. Use when the user mentions onboarding, first-time users, empty states, activation, getting started, new user flows, or the aha moment.",
- "argumentHint": "[target]"
- },
- "layout": {
- "description": "Improve layout, spacing, and visual rhythm. Fixes monotonous grids, inconsistent spacing, and weak visual hierarchy. Use when the user mentions layout feeling off, spacing issues, visual hierarchy, crowded UI, alignment problems, or wanting better composition.",
- "argumentHint": "[target]"
- },
- "optimize": {
- "description": "Diagnoses and fixes UI performance across loading speed, rendering, animations, images, and bundle size. Use when the user mentions slow, laggy, janky, performance, bundle size, load time, or wants a faster, smoother experience.",
- "argumentHint": "[target]"
- },
- "overdrive": {
- "description": "Pushes interfaces past conventional limits with technically ambitious implementations — shaders, spring physics, scroll-driven reveals, 60fps animations. Use when the user wants to wow, impress, go all-out, or make something that feels extraordinary.",
- "argumentHint": "[target]"
- },
- "polish": {
- "description": "Performs a final quality pass fixing alignment, spacing, consistency, and micro-detail issues before shipping. Use when the user mentions polish, finishing touches, pre-launch review, something looks off, or wants to go from good to great.",
- "argumentHint": "[target]"
- },
- "quieter": {
- "description": "Tones down visually aggressive or overstimulating designs, reducing intensity while preserving quality. Use when the user mentions too bold, too loud, overwhelming, aggressive, garish, or wants a calmer, more refined aesthetic.",
- "argumentHint": "[target]"
- },
- "shape": {
- "description": "Plan UX and UI before code. Runs a required multi-round discovery interview, uses visual probes when available, and produces a user-confirmed design brief for implementation.",
- "argumentHint": "[feature to shape]"
- },
- "typeset": {
- "description": "Improves typography by fixing font choices, hierarchy, sizing, weight, and readability so text feels intentional. Use when the user mentions fonts, type, readability, text hierarchy, sizing looks off, or wants more polished, intentional typography.",
- "argumentHint": "[target]"
- }
-}
@@ -1,242 +0,0 @@
-#!/usr/bin/env node
-/**
- * Critique persistence helper.
- *
- * Each run of /impeccable critique writes a per-target snapshot to
- * .impeccable/critique/<timestamp>__<slug>.md
- * with a small YAML frontmatter carrying the score + P0/P1 counts.
- *
- * /impeccable polish reads the latest matching snapshot at start as its
- * fix backlog. No other skill auto-reads critique output.
- *
- * The slug is derived mechanically from the *resolved* primary artifact
- * (file path or URL), never from the user's natural-language phrasing.
- * Slug stability across runs is what lets the trend display work.
- *
- * CLI entry points (called from skill instructions):
- * node critique-storage.mjs slug <resolved-target>
- * node critique-storage.mjs write <slug> <snapshot-body-file>
- * node critique-storage.mjs latest <slug>
- * node critique-storage.mjs trend <slug> [limit]
- *
- * Note: there is intentionally no `ignore` subcommand. ignore.md is a plain
- * markdown file; the model reads it directly with its file-read tool. This
- * helper only exists for operations the model can't trivially do inline
- * (normalizing paths, generating filenames, globbing + parsing frontmatter).
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath, pathToFileURL } from 'node:url';
-import { getCritiqueDir } from './impeccable-paths.mjs';
-
-const SLUG_MAX = 50;
-
-/**
- * Mechanically derive a slug from a resolved target. Returns null if the
- * input doesn't look like a stable identifier (empty, project root, etc).
- *
- * Accepts file paths and URLs. The model resolves "the homepage" to a
- * concrete artifact before calling this — we never slug a natural-language
- * phrase.
- */
-export function slugFromTarget(resolved, { cwd = process.cwd() } = {}) {
- if (!resolved || typeof resolved !== 'string') return null;
- const trimmed = resolved.trim();
- if (!trimmed) return null;
-
- // URL
- if (/^https?:\/\//i.test(trimmed)) {
- let url;
- try { url = new URL(trimmed); } catch { return null; }
- const hostPath = `${url.hostname}${url.pathname}`;
- return kebab(hostPath);
- }
-
- // File path. Make it project-relative so two devs critiquing the same
- // checkout get the same slug regardless of where their repo is cloned.
- const abs = path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- let rel = path.relative(cwd, abs);
- // If the target is outside cwd, fall back to the basename so we still
- // produce a stable slug (vs the absolute path, which would include
- // home dirs / usernames).
- if (rel.startsWith('..') || path.isAbsolute(rel)) {
- rel = path.basename(abs);
- }
- if (!rel || rel === '.' || rel === '') return null;
- return kebab(rel);
-}
-
-function kebab(s) {
- const slug = s
- .toLowerCase()
- .replace(/[/\\.]+/g, '-')
- .replace(/[^a-z0-9-]+/g, '-')
- .replace(/-+/g, '-')
- .replace(/^-|-$/g, '');
- if (!slug) return null;
- // Cap from the tail — the tail (filename) is more identifying than the
- // top-level directory.
- return slug.length <= SLUG_MAX ? slug : slug.slice(slug.length - SLUG_MAX).replace(/^-/, '');
-}
-
-/**
- * Filename-safe UTC ISO timestamp: hyphens for separators, trailing Z.
- * Plain colons aren't allowed on Windows filesystems.
- */
-export function nowFilenameStamp(date = new Date()) {
- const iso = date.toISOString(); // 2026-05-12T18:30:00.123Z
- return iso.replace(/[:.]/g, '-').replace(/-\d+Z$/, 'Z');
-}
-
-/**
- * Write a snapshot for `slug`. `meta` carries the small structured frontmatter
- * keys read back by readTrend(). `body` is the human-readable critique
- * report (everything below the frontmatter).
- *
- * Returns the absolute path written.
- */
-export function writeSnapshot({ slug, meta, body, cwd = process.cwd(), now = new Date() }) {
- if (!slug) throw new Error('writeSnapshot requires a slug');
- const dir = getCritiqueDir(cwd);
- fs.mkdirSync(dir, { recursive: true });
- const timestamp = nowFilenameStamp(now);
- const filePath = path.join(dir, `${timestamp}__${slug}.md`);
- // Spread `meta` first so internally computed `timestamp` and `slug`
- // always win. Otherwise a caller-supplied meta blob (parsed from the
- // IMPECCABLE_CRITIQUE_META env var) could clobber them, leaving the
- // filename in disagreement with its frontmatter and corrupting trends.
- const front = serializeFrontmatter({ ...meta, timestamp, slug });
- fs.writeFileSync(filePath, `${front}\n${body.trim()}\n`, 'utf-8');
- return filePath;
-}
-
-function serializeFrontmatter(obj) {
- const lines = ['---'];
- for (const [key, value] of Object.entries(obj)) {
- if (value === undefined || value === null) continue;
- const str = typeof value === 'string' ? value : String(value);
- // Quote strings that contain : or # to keep parsing simple.
- const needsQuotes = typeof value === 'string' && /[:#]/.test(str);
- lines.push(`${key}: ${needsQuotes ? JSON.stringify(str) : str}`);
- }
- lines.push('---');
- return lines.join('\n');
-}
-
-function parseFrontmatter(text) {
- const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
- if (!match) return {};
- const out = {};
- for (const line of match[1].split(/\r?\n/)) {
- const colon = line.indexOf(':');
- if (colon < 0) continue;
- const key = line.slice(0, colon).trim();
- let value = line.slice(colon + 1).trim();
- if (/^".*"$/.test(value)) {
- try { value = JSON.parse(value); } catch { /* leave as-is */ }
- } else if (/^-?\d+$/.test(value)) {
- value = Number(value);
- }
- out[key] = value;
- }
- return out;
-}
-
-/**
- * Return all snapshot files for `slug`, sorted oldest → newest.
- */
-function listSnapshotsForSlug(slug, cwd) {
- const dir = getCritiqueDir(cwd);
- if (!fs.existsSync(dir)) return [];
- const suffix = `__${slug}.md`;
- return fs.readdirSync(dir)
- .filter((f) => f.endsWith(suffix))
- .sort()
- .map((f) => path.join(dir, f));
-}
-
-/**
- * Return the most recent snapshot for `slug`, or null. Polish reads this
- * to find its fix backlog when the slug matches.
- */
-export function readLatestSnapshot(slug, { cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- if (!all.length) return null;
- const latest = all[all.length - 1];
- const body = fs.readFileSync(latest, 'utf-8');
- return { path: latest, body, meta: parseFrontmatter(body) };
-}
-
-/**
- * Return the last `limit` snapshots' frontmatter, oldest → newest.
- * Critique appends a one-line trend to its output using this.
- */
-export function readTrend(slug, { limit = 5, cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- const slice = all.slice(-limit);
- return slice.map((file) => parseFrontmatter(fs.readFileSync(file, 'utf-8')));
-}
-
-// ---- CLI ---------------------------------------------------------------
-
-function main(argv) {
- const [cmd, ...args] = argv;
- switch (cmd) {
- case 'slug': {
- const slug = slugFromTarget(args[0]);
- if (!slug) { process.stderr.write('no stable slug for input\n'); process.exit(1); }
- process.stdout.write(`${slug}\n`);
- return;
- }
- case 'write': {
- const [slug, bodyFile] = args;
- if (!slug || !bodyFile) { process.stderr.write('usage: write <slug> <body-file>\n'); process.exit(1); }
- const raw = fs.readFileSync(bodyFile, 'utf-8');
- // The body file may be a full report. The caller passes the meta as
- // a JSON object on stdin if it wants structured frontmatter; otherwise
- // we write with minimal metadata.
- let meta = {};
- const metaArg = process.env.IMPECCABLE_CRITIQUE_META;
- if (metaArg) {
- try { meta = JSON.parse(metaArg); } catch { /* ignore */ }
- }
- const out = writeSnapshot({ slug, meta, body: raw });
- process.stdout.write(`${out}\n`);
- return;
- }
- case 'latest': {
- const latest = readLatestSnapshot(args[0]);
- if (!latest) { process.exit(2); }
- process.stdout.write(latest.body);
- return;
- }
- case 'trend': {
- const rows = readTrend(args[0], { limit: args[1] ? Number(args[1]) : 5 });
- process.stdout.write(JSON.stringify(rows, null, 2) + '\n');
- return;
- }
- default:
- process.stderr.write('usage: critique-storage.mjs <slug|write|latest|trend> [args]\n');
- process.exit(1);
- }
-}
-
-function isMainModule() {
- if (!process.argv[1]) return false;
- try {
- return fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1]);
- } catch {
- // pathToFileURL normalizes Windows paths; keep it as a fallback for any
- // environment where realpath is unavailable.
- return import.meta.url === pathToFileURL(process.argv[1]).href;
- }
-}
-
-// Why the realpath check: generated skills are often reached through symlinked
-// harness directories (for example a demo repo's `.agents` -> source `.agents`).
-// Node resolves import.meta.url to the real file, while process.argv[1] keeps
-// the symlink path. Comparing canonical paths prevents a silent exit-0 no-op.
-if (isMainModule()) {
- main(process.argv.slice(2));
-}
@@ -1,820 +0,0 @@
-// Parse a DESIGN.md (Stitch-spec format) into a structured JSON model that
-// the live-mode design-system panel can render. Deterministic, dependency-free.
-//
-// Two-layer: YAML frontmatter (machine-readable tokens) + markdown body
-// (prose with six canonical H2 sections). When frontmatter is present, it's
-// exposed on `model.frontmatter` alongside the prose-scraped sections;
-// consumers can prefer frontmatter values and fall back to prose.
-
-const CANONICAL_SECTIONS = [
- 'Overview',
- 'Colors',
- 'Typography',
- 'Elevation',
- 'Components',
- "Do's and Don'ts",
-];
-
-// ---------- Frontmatter (Stitch YAML subset) ----------
-
-function parseFrontmatter(md) {
- const lines = md.split(/\r?\n/);
- if (lines[0]?.trim() !== '---') return { frontmatter: null, body: md };
-
- let end = -1;
- for (let i = 1; i < lines.length; i++) {
- if (lines[i].trim() === '---') { end = i; break; }
- }
- if (end === -1) return { frontmatter: null, body: md };
-
- const yaml = lines.slice(1, end).join('\n');
- const body = lines.slice(end + 1).join('\n');
- try {
- return { frontmatter: parseYamlSubset(yaml), body };
- } catch {
- return { frontmatter: null, body: md };
- }
-}
-
-// Minimal YAML reader for the Stitch frontmatter subset: scalar maps with
-// one level of nested objects (typography roles, components). Indent-based,
-// 2-space convention. No arrays, no anchors, no multi-line scalars — Stitch's
-// schema doesn't need them and accepting them would require a real YAML
-// dependency we don't want to vendor.
-function parseYamlSubset(yaml) {
- const lines = yaml.split(/\r?\n/);
- const root = {};
- const stack = [{ indent: -1, obj: root }];
-
- for (const raw of lines) {
- // Skip blanks and line-only comments. Don't strip inline comments:
- // unquoted hex values start with `#` and can't be safely distinguished
- // from a comment after whitespace.
- if (!raw.trim() || /^\s*#/.test(raw)) continue;
-
- const indent = raw.match(/^\s*/)[0].length;
- const content = raw.slice(indent);
-
- const colonIdx = findTopLevelColon(content);
- if (colonIdx === -1) continue;
-
- while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
- stack.pop();
- }
-
- const key = content.slice(0, colonIdx).trim();
- const rest = content.slice(colonIdx + 1).trim();
- const parent = stack[stack.length - 1].obj;
-
- if (rest === '') {
- const obj = {};
- parent[key] = obj;
- stack.push({ indent, obj });
- } else {
- parent[key] = parseScalar(rest);
- }
- }
-
- return root;
-}
-
-function findTopLevelColon(s) {
- let inQuote = null;
- for (let i = 0; i < s.length; i++) {
- const ch = s[i];
- if (inQuote) {
- if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
- } else if (ch === '"' || ch === "'") {
- inQuote = ch;
- } else if (ch === ':') {
- return i;
- }
- }
- return -1;
-}
-
-function parseScalar(raw) {
- const s = raw.trim();
- if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
- return s.slice(1, -1);
- }
- if (s === 'true') return true;
- if (s === 'false') return false;
- if (s === 'null' || s === '~') return null;
- if (/^-?\d+$/.test(s)) return Number(s);
- if (/^-?\d*\.\d+$/.test(s)) return Number(s);
- return s;
-}
-
-const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
-const OKLCH_RE = /oklch\([^)]+\)/gi;
-const RGBA_RE = /rgba?\([^)]+\)/gi;
-const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
-const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
-
-// ---------- Section splitting ----------
-
-function splitSections(md) {
- const lines = md.split(/\r?\n/);
- let title = null;
- const sections = {};
- let current = null;
-
- for (const raw of lines) {
- const line = raw.trimEnd();
-
- if (!title && line.startsWith('# ') && !line.startsWith('## ')) {
- title = line.replace(/^#\s+/, '').trim();
- continue;
- }
-
- const h2 = line.match(/^##\s+(?:\d+\.\s*)?([^:\n]+?)(?::\s*(.+))?$/);
- if (h2) {
- const rawName = normalizeApostrophes(h2[1].trim());
- const subtitle = h2[2] ? h2[2].trim() : null;
- const canonical = matchCanonicalSection(rawName);
- if (canonical) {
- current = { name: canonical, subtitle, lines: [] };
- sections[canonical] = current;
- continue;
- }
- // non-canonical H2 — ignore but stop feeding into current
- current = null;
- continue;
- }
-
- if (current) current.lines.push(raw);
- }
-
- return { title, sections };
-}
-
-function normalizeApostrophes(s) {
- return s.replace(/[\u2018\u2019]/g, "'");
-}
-
-function matchCanonicalSection(name) {
- const normalized = normalizeApostrophes(name).toLowerCase();
- // Exact match first
- for (const c of CANONICAL_SECTIONS) {
- if (normalizeApostrophes(c).toLowerCase() === normalized) return c;
- }
- // Keyword-contained match: "Overview & Creative North Star" -> "Overview",
- // "Elevation & Depth" -> "Elevation", etc.
- for (const c of CANONICAL_SECTIONS) {
- const key = normalizeApostrophes(c).toLowerCase();
- const pattern = new RegExp(`\\b${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
- if (pattern.test(normalized)) return c;
- }
- return null;
-}
-
-// ---------- Subsection splitting (inside a canonical section) ----------
-
-function splitSubsections(lines) {
- const subs = [];
- let current = { name: null, lines: [] };
- subs.push(current);
-
- for (const raw of lines) {
- const h3 = raw.match(/^###\s+(.+?)\s*$/);
- if (h3) {
- current = { name: h3[1].trim(), lines: [] };
- subs.push(current);
- continue;
- }
- current.lines.push(raw);
- }
-
- return subs;
-}
-
-// ---------- Generic helpers ----------
-
-function collectParagraphs(lines) {
- const paragraphs = [];
- let buf = [];
- const flush = () => {
- if (buf.length) {
- paragraphs.push(buf.join(' ').trim());
- buf = [];
- }
- };
- for (const raw of lines) {
- const trimmed = raw.trim();
- if (trimmed === '') { flush(); continue; }
- // Horizontal rules (---, ***) and headings/bullets end a paragraph.
- if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { flush(); continue; }
- if (raw.startsWith('#') || raw.match(/^[-*]\s/)) { flush(); continue; }
- buf.push(trimmed);
- }
- flush();
- return paragraphs.filter(Boolean);
-}
-
-function collectBullets(lines) {
- const bullets = [];
- let current = null;
- for (const raw of lines) {
- const m = raw.match(/^\s*[-*]\s+(.+)$/);
- if (m) {
- if (current) bullets.push(current);
- current = m[1];
- continue;
- }
- // continuation of a bullet (indented line)
- if (current && raw.match(/^\s{2,}\S/)) {
- current += ' ' + raw.trim();
- continue;
- }
- // blank line ends a bullet
- if (raw.trim() === '' && current) {
- bullets.push(current);
- current = null;
- }
- }
- if (current) bullets.push(current);
- return bullets;
-}
-
-function stripBold(s) {
- return s.replace(/\*\*(.+?)\*\*/g, '$1');
-}
-
-function extractNamedRules(lines) {
- const rules = [];
- const seen = new Set();
-
- // Style A (Impeccable): "**The X Rule.** body body body" — can span lines.
- const joined = lines.join('\n');
- const inlineStart = /\*\*(The [^*]+?Rule)\.\*\*/g;
- const inlineMatches = [];
- let m;
- while ((m = inlineStart.exec(joined)) !== null) {
- inlineMatches.push({ name: m[1], start: m.index, end: inlineStart.lastIndex });
- }
- for (let i = 0; i < inlineMatches.length; i++) {
- const mm = inlineMatches[i];
- const bodyEnd = i + 1 < inlineMatches.length ? inlineMatches[i + 1].start : joined.length;
- const body = joined
- .slice(mm.end, bodyEnd)
- .replace(/\n##[^\n]*$/s, '')
- .replace(/\n###[^\n]*$/s, '')
- .trim();
- const name = stripBold(mm.name).trim();
- seen.add(name.toLowerCase());
- rules.push({ name, body: stripBold(body) });
- }
-
- // Style B (Stitch): `### The "X" Rule` or `### The X Fallback`, body is the
- // bullets/paragraphs until the next heading. Accept Rule / Fallback / Principle.
- for (let i = 0; i < lines.length; i++) {
- const h3 = lines[i].match(/^###\s+(.+?)\s*$/);
- if (!h3) continue;
- const headerName = stripBold(h3[1]).replace(/["“”]/g, '').trim();
- if (!/^The\b.*\b(Rule|Fallback|Principle)\b/i.test(headerName)) continue;
- if (seen.has(headerName.toLowerCase())) continue;
-
- const bodyLines = [];
- for (let j = i + 1; j < lines.length; j++) {
- if (/^##\s|^###\s/.test(lines[j])) break;
- bodyLines.push(lines[j]);
- }
- const body = stripBold(bodyLines.join('\n').replace(/\n+/g, ' ')).trim();
- if (body) {
- seen.add(headerName.toLowerCase());
- rules.push({ name: headerName, body });
- }
- }
-
- // Style C (Stitch bullet form): "* **The Layering Principle:** body"
- // Colon/period lives inside the bold, so match "**...**" then inspect.
- for (const b of collectBullets(lines)) {
- const mm = b.match(/^\*\*([^*]+?)\*\*\s*(.+)$/);
- if (!mm) continue;
- const nameRaw = mm[1].replace(/[.:]\s*$/, '').replace(/["“”]/g, '').trim();
- if (!/^The\b.+\b(Rule|Fallback|Principle)$/i.test(nameRaw)) continue;
- if (seen.has(nameRaw.toLowerCase())) continue;
- seen.add(nameRaw.toLowerCase());
- rules.push({ name: nameRaw, body: stripBold(mm[2]).trim() });
- }
-
- return rules;
-}
-
-// ---------- Per-section extractors ----------
-
-function extractOverview(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
- const northStar = text.match(/\*\*Creative North Star:\s*"([^"]+)"\*\*/);
- const keyChars = [];
- const keyCharMatch = text.match(/\*\*Key Characteristics:\*\*\s*\n([\s\S]+?)(?:\n##|\n###|$)/);
- if (keyCharMatch) {
- for (const line of keyCharMatch[1].split('\n')) {
- const m = line.match(/^\s*[-*]\s+(.+)$/);
- if (m) keyChars.push(stripBold(m[1].trim()));
- }
- }
-
- // Philosophy paragraphs: everything that isn't a rule header or key-char block
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) =>
- !p.startsWith('**Creative North Star') &&
- !p.startsWith('**Key Characteristics')
- );
-
- return {
- subtitle: section.subtitle,
- creativeNorthStar: northStar ? northStar[1] : null,
- philosophy: paragraphs,
- keyCharacteristics: keyChars,
- };
-}
-
-function extractColors(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ');
- const groups = [];
- const ROLE_KEYWORDS = /^(primary|secondary|tertiary|neutral|accent)\b/i;
-
- for (const sub of subs.slice(1)) {
- if (!sub.name || /Named Rules?/i.test(sub.name) || /^The\s/i.test(sub.name)) continue;
-
- const bullets = collectBullets(sub.lines);
- const parsed = bullets.map((b) => parseColorBullet(b)).filter(Boolean);
- if (parsed.length === 0) continue;
-
- // If every bullet starts with a role keyword (Primary/Secondary/...), promote
- // each bullet to its own group. Otherwise keep the subsection as the group.
- const allRoleBullets =
- parsed.length > 0 && parsed.every((p) => p.name && ROLE_KEYWORDS.test(p.name));
-
- if (allRoleBullets) {
- for (const p of parsed) {
- groups.push({ role: p.name, colors: [p] });
- }
- } else {
- groups.push({ role: sub.name, colors: parsed });
- }
- }
-
- // If the Colors section has no subsections at all (unlikely), fall back to
- // scanning the whole section as a flat bullet list.
- if (groups.length === 0) {
- const flat = collectBullets(section.lines)
- .map((b) => parseColorBullet(b))
- .filter(Boolean);
- if (flat.length) {
- for (const p of flat) {
- if (p.name && ROLE_KEYWORDS.test(p.name)) {
- groups.push({ role: p.name, colors: [p] });
- } else {
- const fallback = groups.find((g) => g.role === 'Palette');
- if (fallback) fallback.colors.push(p);
- else groups.push({ role: 'Palette', colors: [p] });
- }
- }
- }
- }
-
- return {
- subtitle: section.subtitle,
- description: description || null,
- groups,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function parseColorBullet(bullet) {
- const text = bullet.trim();
-
- // Case 1 (Impeccable): **Name** (value-with-maybe-nested-parens): description
- const bold = text.match(/^\*\*(.+?)\*\*\s*(.*)$/);
- if (bold && bold[2].startsWith('(')) {
- const value = extractParenGroup(bold[2]);
- if (value !== null) {
- const after = bold[2].slice(value.length + 2).trimStart();
- if (after.startsWith(':')) {
- return buildColor(bold[1], value, after.slice(1).trim());
- }
- }
- }
-
- // Case 2 (Stitch): **Name (values):** description — value embedded in bold.
- const stitch = text.match(/^\*\*([^*]+?)\s*\(([^)]+)\):\*\*\s*(.*)$/);
- if (stitch) {
- return buildColor(stitch[1].trim(), stitch[2], stitch[3]);
- }
-
- // Case 3: bullet without bold, just hex/oklch inside.
- const values = collectColorValues(text);
- if (values.length) {
- return buildColor(null, values.join(' to '), text);
- }
- return null;
-}
-
-function extractParenGroup(s) {
- if (s[0] !== '(') return null;
- let depth = 0;
- for (let i = 0; i < s.length; i++) {
- if (s[i] === '(') depth++;
- else if (s[i] === ')') {
- depth--;
- if (depth === 0) return s.slice(1, i);
- }
- }
- return null;
-}
-
-function buildColor(name, rawValue, description) {
- const values = collectColorValues(rawValue);
- const primary = values[0] ?? rawValue.trim();
- return {
- name: name ? stripBold(name).trim() : null,
- value: primary,
- valueRange: values.length > 1 ? values : null,
- format: detectFormat(primary),
- description: stripBold(description || '').trim() || null,
- };
-}
-
-function collectColorValues(s) {
- const out = [];
- s.replace(HEX_RE, (v) => {
- out.push(v);
- return v;
- });
- s.replace(OKLCH_RE, (v) => {
- out.push(v);
- return v;
- });
- return out;
-}
-
-function detectFormat(v) {
- if (!v) return 'unknown';
- if (v.startsWith('#')) return 'hex';
- if (/^oklch/i.test(v)) return 'oklch';
- if (/^rgb/i.test(v)) return 'rgb';
- return 'unknown';
-}
-
-function scanInlineColors(lines) {
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '');
- const color = parseColorBullet(trimmed);
- if (color) out.push(color);
- }
- return out;
-}
-
-function parseStitchInlineGroups(lines) {
- // Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
- // Each bullet IS its own role. Group them under the spoken role name.
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
- const m = trimmed.match(
- /^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
- );
- if (m) {
- const role = m[1];
- const color = buildColor(role, m[2], m[3]);
- out.push({ role, colors: [color] });
- }
- }
- return out;
-}
-
-function extractTypography(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
-
- const fonts = {};
- // Pattern A: **Display Font:** Family (with fallback)
- const fontLineRe = /\*\*([\w\s/]+?)Font:\*\*\s*([^\n(]+?)(?:\s*\(with\s+([^)]+)\))?\s*$/gm;
- let fm;
- while ((fm = fontLineRe.exec(text)) !== null) {
- const rawRole = fm[1].trim().toLowerCase().replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || 'display';
- fonts[role] = {
- family: fm[2].trim(),
- fallback: fm[3] ? fm[3].trim() : null,
- };
- }
-
- // Pattern B (Stitch): * **Display & Headlines (Noto Serif):** description
- if (Object.keys(fonts).length === 0) {
- const stitchRe = /\*\*([\w\s&/]+?)\s*\(([^)]+)\):\*\*\s*(.+)/g;
- let sm;
- while ((sm = stitchRe.exec(text)) !== null) {
- const rawRole = sm[1]
- .trim()
- .toLowerCase()
- .replace(/\s*&\s*/g, '-')
- .replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || rawRole;
- fonts[role] = { family: sm[2].trim(), fallback: null, purpose: sm[3].trim() };
- }
- }
-
- // Character paragraph — either a **Character:** label, or fall back to the
- // first free paragraph under the section header (Stitch style).
- const characterMatch = text.match(/\*\*Character:\*\*\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\n|\n###|\n##|$)/);
- let character = characterMatch ? characterMatch[1].replace(/\n/g, ' ').trim() : null;
- if (!character) {
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) => !/^\*\*[\w\s/&]+Font/i.test(p) && !/^\*\*[\w\s/&]+\([^)]+\)/.test(p)
- );
- if (paragraphs.length) character = paragraphs[0];
- }
-
- // Hierarchy bullets under ### Hierarchy
- const subs = splitSubsections(section.lines);
- let hierarchy = [];
- const hierSub = subs.find((s) => s.name && /hierarch/i.test(s.name));
- if (hierSub) {
- const bullets = collectBullets(hierSub.lines);
- hierarchy = bullets.map(parseTypeBullet).filter(Boolean);
- }
-
- return {
- subtitle: section.subtitle,
- fonts,
- character,
- hierarchy,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function normalizeFontRole(raw) {
- // Canonical roles the panel cares about: display, body, label, mono.
- // Stitch often writes compound roles like "display-&-headlines" or "ui-&-body"
- // — collapse them to the first canonical role present.
- const tokens = raw.split(/[-/&\s]+/).filter(Boolean);
- const priority = ['display', 'headline', 'body', 'ui', 'label', 'mono'];
- const canonical = { headline: 'display', ui: 'body' };
- for (const p of priority) {
- if (tokens.includes(p)) return canonical[p] || p;
- }
- return null;
-}
-
-function parseTypeBullet(bullet) {
- // - **Display** (family, weight 300, italic, clamp(...), line-height 1): purpose
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(([^)]+)\):\s*(.*)$/);
- if (!m) return null;
- const name = m[1].trim();
- const specs = m[2].split(',').map((s) => s.trim());
- return {
- name,
- specs,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractElevation(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ') || null;
-
- const shadows = [];
- const seen = new Set();
- const dedupe = (entry) => {
- const key = (entry.name || '') + '::' + entry.value;
- if (seen.has(key)) return;
- seen.add(key);
- shadows.push(entry);
- };
-
- for (const b of collectBullets(section.lines)) {
- const parsed = parseShadowBullet(b);
- if (parsed) dedupe(parsed);
- }
-
- // Fallback: extract shadows written inline in prose. Stitch style is
- // "...use an extra-diffused shadow: `box-shadow: 0 12px 40px rgba(...)`."
- for (const p of collectParagraphs(section.lines)) {
- for (const inline of extractInlineShadows(p)) dedupe(inline);
- }
- for (const b of collectBullets(section.lines)) {
- for (const inline of extractInlineShadows(b)) dedupe(inline);
- }
-
- return {
- subtitle: section.subtitle,
- description,
- shadows,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function extractInlineShadows(text) {
- // Find `box-shadow: ...` anywhere in prose and capture the value. Work on the
- // raw string so it handles both backtick-fenced and unfenced variants.
- const out = [];
- const re = /box-shadow\s*:\s*([^`;\n]+)/gi;
- let m;
- while ((m = re.exec(text)) !== null) {
- const value = m[1].replace(/[`.)]+$/, '').trim();
- if (!value) continue;
- // Name heuristic: the noun immediately before the shadow phrase.
- // e.g. "an extra-diffused shadow: ..." -> "extra-diffused shadow"
- const before = text.slice(0, m.index);
- const nameMatch = before.match(/\b([A-Za-z][A-Za-z\- ]{2,40})\s+shadow\b[^A-Za-z0-9]*$/i);
- let name = null;
- if (nameMatch) {
- const stripped = nameMatch[1]
- .replace(/^(?:use|using|apply|applying|is|are|looks? like)\s+/i, '')
- .replace(/^(?:a|an|the)\s+/i, '')
- .trim();
- if (stripped) {
- name =
- stripped.charAt(0).toUpperCase() + stripped.slice(1) + ' shadow';
- }
- }
- out.push({
- name,
- value,
- purpose: null,
- });
- }
- return out;
-}
-
-function parseShadowBullet(bullet) {
- // - **Name** (`box-shadow: value`): purpose
- // - **Name** (`value`): purpose
- // Only accept if the paren content looks like a shadow value (contains px,
- // rem, rgba, or box-shadow). This filters out `**Rule Name:**` bullets.
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(`?([^`]+?)`?\):\s*(.*)$/);
- if (!m) return null;
- const rawValue = m[2].replace(/^box-shadow:\s*/i, '').trim();
- const looksLikeShadow =
- /box-shadow|rgba?\(|\bpx\b|\brem\b|^-?\d+\s/i.test(rawValue) &&
- /\d/.test(rawValue);
- if (!looksLikeShadow) return null;
- const name = stripBold(m[1]).trim();
- return {
- name,
- value: rawValue,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractComponents(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const components = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
-
- const bullets = collectBullets(sub.lines);
- const paragraphs = collectParagraphs(sub.lines);
-
- const variants = [];
- const properties = {};
-
- for (const b of bullets) {
- // - **Key:** value
- const m = b.match(/^\*\*(.+?):?\*\*:?\s*(.+)$/);
- if (m) {
- const key = stripBold(m[1]).trim();
- const value = stripBold(m[2]).trim();
- // Heuristic: "Primary", "Secondary", "Hover", "Focus" etc are variants;
- // "Shape", "Background", "Padding" are properties.
- if (/^(primary|secondary|tertiary|ghost|hover|focus|active|disabled|default|error|selected|unselected|state)$/i.test(key.split(/[\s/]/)[0])) {
- variants.push({ name: key, description: value });
- } else {
- properties[key.toLowerCase()] = value;
- }
- }
- }
-
- components.push({
- name: sub.name,
- description: paragraphs.join(' ') || null,
- properties,
- variants,
- });
- }
-
- return {
- subtitle: section.subtitle,
- components,
- };
-}
-
-function extractDosDonts(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const dos = [];
- const donts = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
- const subName = normalizeApostrophes(sub.name);
- const bullets = collectBullets(sub.lines).map((b) => stripBold(b).trim());
- if (/^do'?t?:?$/i.test(subName) || /^do:?$/i.test(subName)) {
- dos.push(...bullets);
- } else if (/^don'?t:?$/i.test(subName)) {
- donts.push(...bullets);
- }
- }
-
- // Classify by bullet prefix as a backup (catches loose bullets outside H3 wrappers)
- for (const b of collectBullets(section.lines)) {
- const stripped = normalizeApostrophes(stripBold(b).trim());
- if (/^don'?t\b/i.test(stripped)) {
- if (!donts.some((d) => normalizeApostrophes(d) === stripped)) donts.push(stripped);
- } else if (/^do\b/i.test(stripped)) {
- if (!dos.some((d) => normalizeApostrophes(d) === stripped)) dos.push(stripped);
- }
- }
-
- return { dos, donts };
-}
-
-// ---------- Coverage assessment ----------
-
-function assessCoverage(model) {
- const report = {};
-
- report.overview = model.overview
- ? {
- northStar: Boolean(model.overview.creativeNorthStar),
- philosophy: model.overview.philosophy.length > 0,
- keyCharacteristics: model.overview.keyCharacteristics.length,
- }
- : 'missing';
-
- report.colors = model.colors
- ? {
- groups: model.colors.groups.length,
- totalColors: model.colors.groups.reduce((n, g) => n + g.colors.length, 0),
- rules: model.colors.rules.length,
- }
- : 'missing';
-
- report.typography = model.typography
- ? {
- fonts: Object.keys(model.typography.fonts).length,
- hierarchyEntries: model.typography.hierarchy.length,
- character: Boolean(model.typography.character),
- rules: model.typography.rules.length,
- }
- : 'missing';
-
- report.elevation = model.elevation
- ? {
- shadows: model.elevation.shadows.length,
- rules: model.elevation.rules.length,
- description: Boolean(model.elevation.description),
- }
- : 'missing';
-
- report.components = model.components
- ? {
- count: model.components.components.length,
- variantTotal: model.components.components.reduce((n, c) => n + c.variants.length, 0),
- }
- : 'missing';
-
- report.dosDonts = model.dosDonts
- ? {
- dos: model.dosDonts.dos.length,
- donts: model.dosDonts.donts.length,
- }
- : 'missing';
-
- return report;
-}
-
-// ---------- Main ----------
-
-export function parseDesignMd(md) {
- const { frontmatter, body } = parseFrontmatter(md);
- const { title, sections } = splitSections(body);
- return {
- schemaVersion: 2,
- title,
- frontmatter,
- overview: extractOverview(sections['Overview']),
- colors: extractColors(sections['Colors']),
- typography: extractTypography(sections['Typography']),
- elevation: extractElevation(sections['Elevation']),
- components: extractComponents(sections['Components']),
- dosDonts: extractDosDonts(sections["Do's and Don'ts"]),
- };
-}
-
-export { assessCoverage };
@@ -1,198 +0,0 @@
-/**
- * Scan a project tree for Content-Security-Policy signals and classify the
- * shape so the agent knows which patch template to propose.
- *
- * Used at first-time `live.mjs` setup. Mechanical (grep-based) — no network,
- * no dev server, no JS evaluation. The classification drives a user-facing
- * consent prompt; the agent does the actual patch writing.
- *
- * Shapes are named by patch mechanism, not framework origin:
- * - "append-arrays": CSP defined as structured directive arrays. Patch
- * appends a dev-only localhost entry. Covers:
- * - Monorepo helpers with additional*Src options
- * (e.g. createBaseNextConfig for Next)
- * - SvelteKit kit.csp.directives
- * - nuxt-security module's contentSecurityPolicy
- * - "append-string": CSP built as a literal value string. Patch splices
- * a dev-only token into script-src and connect-src.
- * Covers:
- * - Inline Next.js headers() with CSP string
- * - Nuxt routeRules / nitro.routeRules CSP headers
- * - "middleware": CSP set dynamically in middleware.{ts,js}.
- * Detected but not auto-patched in v1.
- * - "meta-tag": <meta http-equiv="Content-Security-Policy"> in
- * layout files. Detected but not auto-patched in v1.
- * - null: no CSP signals found; no patch needed.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const SKIP_DIRS = new Set([
- 'node_modules',
- '.git',
- '.next',
- '.turbo',
- '.svelte-kit',
- '.nuxt',
- '.astro',
- 'dist',
- 'build',
- 'out',
- '.vercel',
-]);
-
-const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.tsx', '.jsx']);
-const LAYOUT_EXTS = new Set(['.tsx', '.jsx', '.astro', '.vue', '.svelte', '.html']);
-const MAX_DEPTH = 6;
-const MAX_READ_BYTES = 64 * 1024;
-
-// append-arrays signals: CSP expressed as structured directive arrays
-const MONOREPO_HELPER_SIGNALS = [
- /\bbuildCSPConfig\b/,
- /\bbuildSecurityHeaders\b/,
- /\badditionalScriptSrc\b/,
- /\badditionalConnectSrc\b/,
- /\bcreateBaseNextConfig\b/,
-];
-const SVELTEKIT_CSP_SIGNALS = [
- /\bkit\s*:/,
- /\bcsp\s*:/,
- /\bdirectives\s*:/,
-];
-const NUXT_SECURITY_SIGNALS = [
- /['"]nuxt-security['"]/,
- /\bcontentSecurityPolicy\b/,
-];
-
-// append-string signals: CSP written as a literal value string
-const INLINE_HEADER_SIGNALS = [
- /["']Content-Security-Policy["']/i,
- /\bscript-src\b/,
- /\bconnect-src\b/,
-];
-const NUXT_ROUTE_RULES_SIGNALS = [
- /\brouteRules\b/,
- /Content-Security-Policy/i,
- /\bscript-src\b/,
-];
-
-const MIDDLEWARE_HINT = /headers\.set\(\s*["']Content-Security-Policy["']/i;
-const META_TAG_HINT = /http-equiv\s*=\s*["']Content-Security-Policy["']/i;
-
-/**
- * @param {string} cwd Project root.
- * @returns {{ shape: string|null, signals: string[] }}
- */
-export function detectCsp(cwd = process.cwd()) {
- const hits = { appendArrays: [], appendString: [], middleware: [], metaTag: [] };
-
- walk(cwd, cwd, 0, (absPath, relPath, body) => {
- const ext = path.extname(absPath);
- const base = path.basename(absPath).toLowerCase();
- const isConfig = (name) =>
- new RegExp('(^|/)' + name + '\\.config\\.').test(relPath);
-
- // === append-arrays candidates ===
-
- // Monorepo CSP helper: packages/*/src/.../(config|security)/*
- if (SCAN_EXTS.has(ext) &&
- /packages\/[^/]+\/src\/.*(config|next-config|security)/.test(relPath) &&
- MONOREPO_HELPER_SIGNALS.some((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // SvelteKit kit.csp.directives
- if (SCAN_EXTS.has(ext) && isConfig('svelte') &&
- SVELTEKIT_CSP_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // Nuxt nuxt-security module
- if (SCAN_EXTS.has(ext) && isConfig('nuxt') &&
- NUXT_SECURITY_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // === append-string candidates ===
-
- // Inline headers in Next/Nuxt/SvelteKit/Astro/Vite config
- if (SCAN_EXTS.has(ext) &&
- /(^|\/)(next|nuxt|vite|astro|svelte)\.config\./.test(relPath) &&
- INLINE_HEADER_SIGNALS.every((re) => re.test(body))) {
- // Nuxt routeRules is a sub-shape of append-string; we already covered
- // nuxt-security above via return, so any remaining Nuxt CSP match here
- // is a route-rules / inline-headers case. Either way, same patch
- // mechanism.
- hits.appendString.push(relPath);
- return;
- }
-
- // === detect-only shapes ===
-
- if ((base === 'middleware.ts' || base === 'middleware.js' || base === 'middleware.mjs') &&
- MIDDLEWARE_HINT.test(body)) {
- hits.middleware.push(relPath);
- }
-
- if (LAYOUT_EXTS.has(ext) && META_TAG_HINT.test(body)) {
- hits.metaTag.push(relPath);
- }
- });
-
- // Priority: append-arrays > append-string > middleware > meta-tag.
- // Structured patches are safer than string splices; runtime and HTML
- // injection patches are less reliable and v1 doesn't auto-apply them.
- if (hits.appendArrays.length > 0) {
- return { shape: 'append-arrays', signals: hits.appendArrays };
- }
- if (hits.appendString.length > 0) {
- return { shape: 'append-string', signals: hits.appendString };
- }
- if (hits.middleware.length > 0) {
- return { shape: 'middleware', signals: hits.middleware };
- }
- if (hits.metaTag.length > 0) {
- return { shape: 'meta-tag', signals: hits.metaTag };
- }
- return { shape: null, signals: [] };
-}
-
-function walk(root, dir, depth, visit) {
- if (depth > MAX_DEPTH) return;
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
-
- for (const entry of entries) {
- const abs = path.join(dir, entry.name);
- if (entry.isDirectory()) {
- if (SKIP_DIRS.has(entry.name)) continue;
- walk(root, abs, depth + 1, visit);
- continue;
- }
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name);
- if (!SCAN_EXTS.has(ext) && !LAYOUT_EXTS.has(ext)) continue;
- let body;
- try {
- const fd = fs.openSync(abs, 'r');
- try {
- const buf = Buffer.alloc(MAX_READ_BYTES);
- const n = fs.readSync(fd, buf, 0, MAX_READ_BYTES, 0);
- body = buf.slice(0, n).toString('utf-8');
- } finally { fs.closeSync(fd); }
- } catch { continue; }
- visit(abs, path.relative(root, abs), body);
- }
-}
-
-// CLI mode
-const _running = process.argv[1];
-if (_running?.endsWith('detect-csp.mjs') || _running?.endsWith('detect-csp.mjs/')) {
- const result = detectCsp(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
@@ -1,21 +0,0 @@
-#!/usr/bin/env node
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { pathToFileURL, fileURLToPath } from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const candidates = [
- path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
-];
-const detectorPath = candidates.find(p => fs.existsSync(p));
-
-if (!detectorPath) {
- process.stderr.write('Error: bundled detector not found.\n');
- process.exit(1);
-}
-
-const { detectCli } = await import(pathToFileURL(detectorPath));
-
-await detectCli();
@@ -1,1688 +0,0 @@
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
@@ -1,232 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
-import { detectHtml } from '../engines/static-html/detect-html.mjs';
-import { detectText } from '../engines/regex/detect-text.mjs';
-import {
- HTML_EXTENSIONS,
- buildImportGraph,
- detectFrameworkConfig,
- isPortListening,
- walkDir,
-} from '../node/file-system.mjs';
-
-// ---------------------------------------------------------------------------
-// Output formatting
-// ---------------------------------------------------------------------------
-
-function formatFindings(findings, jsonMode) {
- if (jsonMode) return JSON.stringify(findings, null, 2);
-
- const grouped = {};
- for (const f of findings) {
- if (!grouped[f.file]) grouped[f.file] = [];
- grouped[f.file].push(f);
- }
- const out = [];
- for (const [file, items] of Object.entries(grouped)) {
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
- out.push(`\n${file}${importNote}`);
- for (const item of items) {
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
- out.push(` → ${item.description}`);
- }
- }
- out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
- return out.join('\n');
-}
-
-// ---------------------------------------------------------------------------
-// Stdin handling
-// ---------------------------------------------------------------------------
-
-async function handleStdin() {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- const input = Buffer.concat(chunks).toString('utf-8');
- try {
- const parsed = JSON.parse(input);
- const fp = parsed?.tool_input?.file_path;
- if (fp && fs.existsSync(fp)) {
- return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
- ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
- }
- } catch { /* not JSON */ }
- return detectText(input, '<stdin>');
-}
-
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-async function confirm(question) {
- const rl = (await import('node:readline')).default.createInterface({
- input: process.stdin, output: process.stderr,
- });
- return new Promise((resolve) => {
- rl.question(`${question} [Y/n] `, (answer) => {
- rl.close();
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
- });
- });
-}
-
-function printUsage() {
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
-
-Scan files or URLs for UI anti-patterns and design quality issues.
-
-Options:
- --fast Regex-only mode (skip static HTML/CSS analysis, faster but misses linked stylesheets)
- --json Output results as JSON
- --help Show this help message
-
-Detection modes:
- HTML files Static HTML/CSS analysis (default, catches linked CSS)
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
- URLs Puppeteer full browser rendering (auto-detected)
- --fast Forces regex for all files
-
-Examples:
- impeccable detect src/
- impeccable detect index.html
- impeccable detect https://example.com
- impeccable detect --fast --json .`);
-}
-
-async function detectCli() {
- let args = process.argv.slice(2).map(arg => {
- if (arg === '-json') return '--json';
- if (arg === '-fast') return '--fast';
- return arg;
- });
- if (args[0] === 'detect') args = args.slice(1);
- const jsonMode = args.includes('--json');
- const helpMode = args.includes('--help');
- const fastMode = args.includes('--fast');
- const targets = args.filter(a => !a.startsWith('--'));
-
- if (helpMode) { printUsage(); process.exit(0); }
-
- let allFindings = [];
-
- if (!process.stdin.isTTY && targets.length === 0) {
- allFindings = await handleStdin();
- } else {
- const paths = targets.length > 0 ? targets : [process.cwd()];
- const urlTargetCount = paths.filter(target => /^https?:\/\//i.test(target)).length;
- const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
-
- try {
- for (const target of paths) {
- if (/^https?:\/\//i.test(target)) {
- try {
- const scanner = browserDetector
- ? (url) => browserDetector.detectUrl(url)
- : (url) => detectUrl(url);
- allFindings.push(...await scanner(target));
- } catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
- continue;
- }
-
- const resolved = path.resolve(target);
- let stat;
- try { stat = fs.statSync(resolved); }
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
-
- if (stat.isDirectory()) {
- // Check for framework dev server config (skip in JSON mode to avoid polluting output)
- if (!jsonMode) {
- const fwConfig = detectFrameworkConfig(resolved);
- if (fwConfig) {
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
- if (probe.listening && probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
- `For more accurate results, scan the running site:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- } else if (probe.listening && !probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
- );
- } else {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Start the dev server and scan via URL for best results:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- }
- }
- }
-
- const files = walkDir(resolved);
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
-
- // Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
- if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
- process.stderr.write(
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
- `Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
- `Use --fast to skip static HTML/CSS analysis, or target a specific subdirectory.\n`
- );
- const ok = await confirm('Continue?');
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
- }
-
- // Build import graph for multi-file awareness
- const graph = buildImportGraph(files);
- // Build reverse map: file -> set of files that import it
- const importedByMap = new Map();
- for (const [importer, imports] of graph) {
- for (const imported of imports) {
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
- importedByMap.get(imported).add(importer);
- }
- }
-
- for (const file of files) {
- const ext = path.extname(file).toLowerCase();
- let fileFindings;
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- fileFindings = await detectHtml(file);
- } else {
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
- }
- // Annotate findings with import context
- const importers = importedByMap.get(file);
- if (importers && importers.size > 0) {
- const importerNames = [...importers].map(f => path.basename(f));
- for (const f of fileFindings) {
- f.importedBy = importerNames;
- }
- }
- allFindings.push(...fileFindings);
- }
- } else if (stat.isFile()) {
- const ext = path.extname(resolved).toLowerCase();
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- allFindings.push(...await detectHtml(resolved));
- } else {
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
- }
- }
- }
- } finally {
- if (browserDetector) await browserDetector.close();
- }
- }
-
- if (allFindings.length > 0) {
- if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
- else process.stderr.write(formatFindings(allFindings, false) + '\n');
- process.exit(2);
- }
- if (jsonMode) process.stdout.write('[]\n');
- process.exit(0);
-}
-
-export { formatFindings, handleStdin, confirm, printUsage, detectCli };
@@ -1,4030 +0,0 @@
-/**
- * Anti-Pattern Browser Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * GENERATED -- do not edit. Source: cli/engine/browser/injected/index.mjs
- * Rebuild: node scripts/build-browser-detector.js
- *
- * Usage: <script src="detect-antipatterns-browser.js"></script>
- * Re-scan: window.impeccableScan()
- */
-(function () {
-if (typeof window === 'undefined') return;
-// --- cli/engine/shared/constants.mjs ---
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-// --- cli/engine/registry/antipatterns.mjs ---
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-// --- cli/engine/shared/color.mjs ---
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-// --- cli/engine/rules/checks.mjs ---
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-// --- cli/engine/browser/injected/index.mjs ---
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
-
-})();
@@ -1,43 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Anti-Pattern Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * Public API facade. Runtime engines live under cli/engine/engines/.
- */
-
-import { detectCli } from './cli/main.mjs';
-
-export { ANTIPATTERNS, RULE_ENGINE_SUPPORT, getAntipattern, getRulesForCategory, getRuleEngineSupport } from './registry/antipatterns.mjs';
-export { SAFE_TAGS, BORDER_SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS, KNOWN_SERIF_FONTS } from './shared/constants.mjs';
-export { isNeutralColor, parseRgb, relativeLuminance, contrastRatio, parseGradientColors, hasChroma, getHue, colorToHex } from './shared/color.mjs';
-export { isFullPage } from './shared/page.mjs';
-export {
- checkElementBorders,
- checkElementMotion,
- checkElementGlow,
- checkPageTypography,
- checkPageLayout,
- checkHtmlPatterns,
-} from './rules/checks.mjs';
-export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
-export { detectHtml } from './engines/static-html/detect-html.mjs';
-export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
-export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
-export {
- walkDir,
- SCANNABLE_EXTENSIONS,
- SKIP_DIRS,
- buildImportGraph,
- resolveImport,
- detectFrameworkConfig,
- isPortListening,
- FRAMEWORK_CONFIGS,
-} from './node/file-system.mjs';
-export { formatFindings, detectCli } from './cli/main.mjs';
-
-const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
-if (isMainModule) detectCli();
@@ -1,251 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { finding } from '../../findings.mjs';
-import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
-
-async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
- if (options?.visualContrast === false) return [];
- const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : 12;
- const scrollOffscreen = options?.visualContrastScrollOffscreen !== false;
- const existingLowContrastSelectors = new Set(
- serializedGroups
- .filter(group => group.findings?.some(f => f.type === 'low-contrast'))
- .map(group => group.selector)
- .filter(Boolean)
- );
-
- let browserAnalyses = [];
- const findings = [];
- if (options?.visualContrastBrowser !== false) {
- const browserFindings = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'browser-fallback',
- target,
- }, async () => {
- browserAnalyses = await page.evaluate(async ({ maxCandidates, scrollOffscreen }) => {
- if (typeof window.impeccableAnalyzeVisualContrast !== 'function') return [];
- return window.impeccableAnalyzeVisualContrast({ maxCandidates, scrollOffscreen });
- }, { maxCandidates, scrollOffscreen });
- return browserAnalyses
- .filter(result => result.finding && !existingLowContrastSelectors.has(result.selector))
- .map(result => result.finding);
- });
- findings.push(...browserFindings);
- }
-
- let candidates = browserAnalyses.length > 0 ? browserAnalyses : [];
- if (candidates.length === 0) {
- candidates = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'collect-candidates',
- target,
- }, () => page.evaluate(({ maxCandidates }) => {
- if (typeof window.impeccableCollectVisualContrastCandidates !== 'function') return [];
- return window.impeccableCollectVisualContrastCandidates({ maxCandidates });
- }, { maxCandidates }));
- }
-
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const browserResolvedSelectors = new Set(
- browserAnalyses
- .filter(result => result.status === 'fail' || result.status === 'pass')
- .map(result => result.selector)
- .filter(Boolean)
- );
- const filtered = candidates.filter(candidate =>
- !existingLowContrastSelectors.has(candidate.selector) &&
- !browserResolvedSelectors.has(candidate.selector)
- );
- if (options?.visualContrastPixel === false) return findings;
- for (const candidate of filtered) {
- const result = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'pixel-diff',
- target,
- }, async () => {
- const finding = await captureVisualContrastCandidate(page, candidate, viewport);
- return finding ? [finding] : [];
- });
- findings.push(...result);
- }
- return findings;
-}
-
-// ---------------------------------------------------------------------------
-// Puppeteer detection (for URLs)
-// ---------------------------------------------------------------------------
-
-async function detectUrl(url, options = {}) {
- const profile = options?.profile;
- const waitUntil = options?.waitUntil || 'networkidle0';
- const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const externalBrowser = options?.browser || null;
- let puppeteer;
- if (!externalBrowser) {
- try {
- puppeteer = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'import-puppeteer',
- target: url,
- }, () => import('puppeteer'));
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- }
-
- // Read the browser detection script — reuse it instead of reimplementing
- const browserScriptPath = path.resolve(
- path.dirname(fileURLToPath(import.meta.url)),
- '..',
- '..',
- 'detect-antipatterns-browser.js'
- );
- let browserScript;
- try {
- browserScript = profileStep(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'read-browser-script',
- target: url,
- }, () => fs.readFileSync(browserScriptPath, 'utf-8'));
- } catch {
- throw new Error(`Browser script not found at ${browserScriptPath}`);
- }
-
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
- // running in CI; local users keep the default hardened launch.
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
- const browser = externalBrowser || await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'launch-browser',
- target: url,
- }, () => puppeteer.default.launch({ headless: true, args: launchArgs }));
- const page = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'new-page',
- target: url,
- }, () => browser.newPage());
- let results = [];
- try {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'set-viewport',
- target: url,
- }, () => page.setViewport(viewport));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: `goto:${waitUntil}`,
- target: url,
- }, () => page.goto(url, { waitUntil, timeout: 30000 }));
- if (settleMs > 0) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'settle',
- target: url,
- }, () => new Promise(resolve => setTimeout(resolve, settleMs)));
- }
-
- // Inject the browser detection script and collect results
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'configure-pure-detect',
- target: url,
- }, () => page.evaluate(() => {
- window.__IMPECCABLE_CONFIG__ = {
- ...(window.__IMPECCABLE_CONFIG__ || {}),
- autoScan: false,
- };
- }));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'inject-browser-script',
- target: url,
- }, () => page.evaluate(browserScript));
- let serializedGroups = [];
- results = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'browser-scan',
- target: url,
- }, async () => {
- serializedGroups = await page.evaluate(() => {
- if (!window.impeccableDetect) return [];
- return window.impeccableDetect({ decorate: false, serialize: true });
- });
- return serializedGroups.flatMap(({ findings }) =>
- findings.map(f => ({ id: f.type, snippet: f.detail }))
- );
- });
- const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
- results.push(...visualFindings);
- } finally {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-page',
- target: url,
- }, () => page.close().catch(() => {}));
- if (!externalBrowser) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-browser',
- target: url,
- }, () => browser.close());
- }
- }
- return results.map(f => finding(f.id, url, f.snippet));
-}
-
-async function createBrowserDetector(options = {}) {
- let puppeteer;
- try {
- puppeteer = await import('puppeteer');
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- const launchArgs = options.launchArgs || (process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : []);
- const browser = options.browser || await puppeteer.default.launch({
- headless: options.headless ?? true,
- args: launchArgs,
- });
- const ownsBrowser = !options.browser;
- const defaults = {
- waitUntil: options.waitUntil || 'load',
- settleMs: Number.isFinite(options.settleMs) ? options.settleMs : 100,
- viewport: options.viewport || { width: 1280, height: 800 },
- };
- return {
- browser,
- async detectUrl(url, scanOptions = {}) {
- return detectUrl(url, {
- ...defaults,
- ...scanOptions,
- browser,
- });
- },
- async close() {
- if (ownsBrowser) await browser.close().catch(() => {});
- },
- };
-}
-
-export { runVisualContrastFallback, detectUrl, createBrowserDetector };
@@ -1,420 +0,0 @@
-import { GENERIC_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep } from '../../profile/profiler.mjs';
-
-// ---------------------------------------------------------------------------
-// Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
-// ---------------------------------------------------------------------------
-
-const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
-const hasBorderRadius = (line) => /border-radius/i.test(line);
-const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
-
-function isNeutralBorderColor(str) {
- const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
- if (!m) return false;
- const c = m[1].toLowerCase();
- if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
- const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
- if (hex) {
- const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
- if (shex) {
- const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- return false;
-}
-
-const REGEX_MATCHERS = [
- // --- Side-tab ---
- { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
- test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
- test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
- fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
- { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
- test: (m) => +m[1] >= 3,
- fmt: (m) => m[0] },
- // --- Border accent on rounded ---
- { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
- test: (m, line) => hasRounded(line) && +m[1] >= 1,
- fmt: (m) => m[0] },
- { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
- fmt: (m) => m[0] },
- // --- Overused font ---
- { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
- test: () => true,
- fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
- // --- Pure black background ---
- { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Gradient text ---
- { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
- test: (m, line) => /gradient/i.test(line),
- fmt: () => 'background-clip: text + gradient' },
- // --- Gradient text (Tailwind) ---
- { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
- test: (m, line) => /\bbg-gradient-to-/i.test(line),
- fmt: () => 'bg-clip-text + bg-gradient' },
- // --- Tailwind pure black background ---
- { id: 'pure-black-white', regex: /\bbg-black\b/g,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Tailwind gray on colored bg ---
- { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
- test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
- fmt: (m, line) => { const bg = line.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/); return `${m[0]} on ${bg?.[0] || '?'}`; } },
- // --- Tailwind AI palette ---
- { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
- fmt: (m) => `${m[0]} on heading` },
- { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
- fmt: (m) => `${m[0]} gradient` },
- // --- Bounce/elastic easing ---
- { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
- test: () => true,
- fmt: () => 'animate-bounce (Tailwind)' },
- { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
- test: (m) => {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
- },
- fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
- // --- Layout property transition ---
- { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition: ${found ? found.join(', ') : m[1].trim()}`;
- } },
- { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
- } },
-];
-
-const REGEX_ANALYZERS = [
- // Single font
- (content, filePath) => {
- const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
- const fonts = new Set();
- let m;
- while ((m = fontFamilyRe.exec(content)) !== null) {
- for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
- }
- }
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- while ((m = gfRe.exec(content)) !== null) {
- for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
- }
- if (fonts.size !== 1 || content.split('\n').length < 20) return [];
- const name = [...fonts][0];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
- return [finding('single-font', filePath, `only font used is ${name}`, line)];
- },
- // Flat type hierarchy
- (content, filePath) => {
- const sizes = new Set();
- const REM = 16;
- let m;
- const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
- while ((m = sizeRe.exec(content)) !== null) {
- const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
- if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
- }
- const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
- while ((m = clampRe.exec(content)) !== null) {
- sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
- sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
- }
- const TW = { 'text-xs': 12, 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24, 'text-3xl': 30, 'text-4xl': 36, 'text-5xl': 48, 'text-6xl': 60, 'text-7xl': 72, 'text-8xl': 96, 'text-9xl': 128 };
- for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
- if (sizes.size < 3) return [];
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio >= 2.0) return [];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (/font-size/i.test(lines[i]) || /\btext-(?:xs|sm|base|lg|xl|\d)/i.test(lines[i])) { line = i + 1; break; } }
- return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
- },
- // Monotonous spacing (regex)
- (content, filePath) => {
- const vals = [];
- let m;
- const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
- const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
- const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
- const rounded = vals.map(v => Math.round(v / 4) * 4);
- if (rounded.length < 10) return [];
- const counts = {};
- for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const pct = maxCount / rounded.length;
- const unique = [...new Set(rounded)].filter(v => v > 0);
- if (pct <= 0.6 || unique.length > 3) return [];
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
- },
- // Everything centered (regex)
- (content, filePath) => {
- const lines = content.split('\n');
- let centered = 0, total = 0;
- for (const line of lines) {
- if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
- total++;
- if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
- }
- }
- if (total < 5 || centered / total <= 0.7) return [];
- return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
- },
- // Dark glow (page-level: dark bg + colored box-shadow with blur)
- (content, filePath) => {
- // Check if page has a dark background
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
- if (!hasDarkBg) return [];
-
- // Check for colored box-shadow with blur > 4px
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let m;
- while ((m = shadowRe.exec(content)) !== null) {
- const val = m[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
- // Check blur: look for pattern like "0 0 20px" (third number > 4)
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- const lines = content.substring(0, m.index).split('\n');
- return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
- }
- }
- return [];
- },
-];
-
-// ---------------------------------------------------------------------------
-// Style block extraction (Vue/Svelte <style> blocks)
-// ---------------------------------------------------------------------------
-
-function extractStyleBlocks(content, ext) {
- ext = ext.toLowerCase();
- if (ext !== '.vue' && ext !== '.svelte') return [];
- const blocks = [];
- const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length + 1;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-// ---------------------------------------------------------------------------
-// CSS-in-JS extraction (styled-components, emotion)
-// ---------------------------------------------------------------------------
-
-const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
-
-function extractCSSinJS(content, ext) {
- ext = ext.toLowerCase();
- if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
- const blocks = [];
- const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null, options = {}) {
- const { profile, phase = 'regex-matchers' } = options || {};
- const findings = [];
- if (!profile) {
- for (const matcher of REGEX_MATCHERS) {
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- }
- return findings;
- }
-
- for (const matcher of REGEX_MATCHERS) {
- const matcherFindings = profileFindings(profile, {
- engine: 'regex',
- phase,
- ruleId: matcher.id,
- target: filePath,
- }, () => {
- const matches = [];
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- matches.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- return matches;
- });
- findings.push(...matcherFindings);
- }
- return findings;
-}
-
-function detectText(content, filePath, options = {}) {
- const profile = options?.profile;
- const findings = [];
- const lines = content.split('\n');
- const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
-
- // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
- // Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
- findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
- profile,
- phase: 'source',
- }));
-
- // Extract and scan <style> blocks from Vue/Svelte SFCs
- const styleBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'style-blocks',
- target: filePath,
- }, () => extractStyleBlocks(content, ext))
- : extractStyleBlocks(content, ext);
- for (const block of styleBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'style-block',
- }));
- }
-
- // Extract and scan CSS-in-JS template literals
- const cssJsBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'css-in-js',
- target: filePath,
- }, () => extractCSSinJS(content, ext))
- : extractCSSinJS(content, ext);
- for (const block of cssJsBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'css-in-js',
- }));
- }
-
- // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
- const deduped = [];
- for (const f of findings) {
- const isDupe = deduped.some(d =>
- d.antipattern === f.antipattern &&
- d.snippet === f.snippet &&
- Math.abs(d.line - f.line) <= 2
- );
- if (!isDupe) deduped.push(f);
- }
-
- // Page-level analyzers only run on full pages
- if (isFullPage(content)) {
- const analyzerIds = [
- 'single-font',
- 'flat-type-hierarchy',
- 'monotonous-spacing',
- 'everything-centered',
- 'dark-glow',
- ];
- for (let i = 0; i < REGEX_ANALYZERS.length; i++) {
- const analyzer = REGEX_ANALYZERS[i];
- deduped.push(...profileFindings(profile, {
- engine: 'regex',
- phase: 'page-analyzer',
- ruleId: analyzerIds[i] || `analyzer-${i + 1}`,
- target: filePath,
- }, () => analyzer(content, filePath)));
- }
- }
-
- return deduped;
-}
-
-export {
- REGEX_MATCHERS,
- REGEX_ANALYZERS,
- extractStyleBlocks,
- extractCSSinJS,
- runRegexMatchers,
- detectText,
-};
@@ -1,954 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { profileStep, recordProfileEvent } from '../../profile/profiler.mjs';
-import { parseAnyColor, resolveLengthPx, resolveVarRefs } from '../../rules/checks.mjs';
-
-// ---------------------------------------------------------------------------
-// jsdom CSS-variable border override map
-// ---------------------------------------------------------------------------
-//
-// jsdom's CSSOM silently drops any border shorthand that contains a var()
-// reference — the computed style for the element then shows empty width,
-// empty style, and a default black color. That's enough to hide the most
-// common real-world side-tab pattern in AI-generated pages:
-//
-// :root { --brand: #87a8ff; }
-// .card { border-left: 5px solid var(--brand); border-radius: 4px; }
-//
-// Real browsers (and therefore the browser detector path) resolve var()
-// natively, so this only affects the Node jsdom path.
-//
-// This pre-pass walks the stylesheets, finds any rule whose per-side or
-// all-sides border property contains var(), resolves the var() against
-// :root-level custom properties (read from the documentElement's computed
-// style, which jsdom DOES handle correctly), and attaches the resolved
-// width+color to every element that matches the rule's selector. The
-// Node-side `checkElementBorders` adapter consumes that map as a fallback
-// whenever jsdom's computed style came back empty.
-//
-// Limitations (intentional, to keep the pass simple):
-// * Only :root-level custom properties are resolved. Scoped overrides on
-// descendants are not tracked — uncommon in practice and would require
-// a per-element cascade walk.
-// * @media / @supports wrapped rules are ignored (jsdom often mishandles
-// these anyway).
-// * The fallback only fills sides that jsdom left empty, so any rule
-// whose border parses normally still wins via the computed style.
-
-const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
-
-// isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
-// CSS variables typically hold hex or named colors, so normalize those to
-// rgb() before handing the value off to the shared check. Anything we don't
-// recognise is passed through unchanged — isNeutralColor then treats it as
-// non-neutral, which is the safer default (matches the oklch-era bugfix).
-const NAMED_COLORS = {
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
-};
-
-function normalizeColorForCheck(value) {
- if (!value) return value;
- const v = value.trim();
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
- if (hex6) {
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
- if (hex3) {
- const [r, g, b] = [
- parseInt(hex3[1] + hex3[1], 16),
- parseInt(hex3[2] + hex3[2], 16),
- parseInt(hex3[3] + hex3[3], 16),
- ];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const named = NAMED_COLORS[v.toLowerCase()];
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
- return v;
-}
-
-function buildBorderOverrideMap(document, window) {
- const map = new Map();
- const rootStyle = window.getComputedStyle(document.documentElement);
-
- function resolveVar(value, depth = 0) {
- if (!value || depth > 10 || !value.includes('var(')) return value;
- return value.replace(
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
- (_, name, fallback) => {
- const v = rootStyle.getPropertyValue(name).trim();
- if (v) return resolveVar(v, depth + 1);
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
- return '';
- }
- );
- }
-
- function parseShorthand(text) {
- const m = text.trim().match(BORDER_SHORTHAND_RE);
- if (!m) return null;
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
- }
-
- // Read from the per-property accessors on rule.style. jsdom preserves
- // each border-* shorthand it parsed, even when the overall cssText has
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
- // `border-left: ...` loses the first declaration but keeps the second).
- const SIDE_PROPS = [
- ['borderLeft', 'Left'],
- ['borderRight', 'Right'],
- ['borderTop', 'Top'],
- ['borderBottom', 'Bottom'],
- ['borderInlineStart', 'Left'],
- ['borderInlineEnd', 'Right'],
- ];
-
- for (const sheet of document.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || []; } catch { continue; }
- for (const rule of rules) {
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
-
- const perSide = {};
-
- for (const [prop, side] of SIDE_PROPS) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const parsed = parseShorthand(resolveVar(val));
- if (parsed && parsed.color) perSide[side] = parsed;
- }
-
- // Uniform `border: <w> <style> var(...)` applies to every side the
- // per-side map didn't already claim.
- const borderAll = rule.style.border;
- if (borderAll && borderAll.includes('var(')) {
- const parsed = parseShorthand(resolveVar(borderAll));
- if (parsed && parsed.color) {
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
- if (!perSide[s]) perSide[s] = parsed;
- }
- }
- }
-
- // Longhand `border-*-color: var(...)` with width/style in separate
- // declarations. Rare in AI-generated pages, but cheap to cover.
- for (const [prop, side] of [
- ['borderLeftColor', 'Left'],
- ['borderRightColor', 'Right'],
- ['borderTopColor', 'Top'],
- ['borderBottomColor', 'Bottom'],
- ]) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const resolved = resolveVar(val).trim();
- if (!resolved) continue;
- // Width may or may not come from this rule — that's fine; the
- // adapter only substitutes the color when jsdom left it as a
- // literal var() string.
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
- }
-
- if (Object.keys(perSide).length === 0) continue;
-
- let matched;
- try { matched = document.querySelectorAll(rule.selectorText); }
- catch { continue; }
-
- for (const el of matched) {
- const existing = map.get(el);
- if (existing) {
- // Later rules overwrite earlier ones — approximates source-order
- // cascade for equal-specificity rules and is good enough for the
- // uncontested var()-dropped sides we're trying to recover.
- Object.assign(existing, perSide);
- } else {
- map.set(el, { ...perSide });
- }
- }
- }
- }
-
- return map;
-}
-
-// Strip `@layer NAME { … }` wrappers from a CSS / HTML source, leaving
-// the inner rules as flat CSS. jsdom doesn't implement CSS @layer, so
-// any rule inside a layer block becomes invisible to getComputedStyle.
-// Tailwind v4 makes this ubiquitous: every utility class lives in
-// `@layer utilities`, and Preflight lives in `@layer base`. Without
-// unwrapping, every Tailwind-styled element returns empty computed
-// styles. We walk the source character-by-character, balancing braces
-// so we correctly handle nested style rules inside the layer block.
-function unwrapCssAtLayer(source) {
- if (!source || !source.includes('@layer')) return source;
- // Find `@layer <name>? {` openers. The match starts at the @, and
- // we then balance braces from the opening { onward.
- const re = /@layer\b[^{;]*\{/g;
- let out = '';
- let lastIdx = 0;
- let m;
- while ((m = re.exec(source)) !== null) {
- const openStart = m.index;
- const openEnd = m.index + m[0].length; // position right after `{`
- let depth = 1;
- let i = openEnd;
- while (i < source.length && depth > 0) {
- const c = source.charCodeAt(i);
- if (c === 0x7b /* { */) depth++;
- else if (c === 0x7d /* } */) depth--;
- i++;
- }
- if (depth !== 0) {
- // Unbalanced — bail and return source unchanged.
- return source;
- }
- // Emit everything before the @layer, then the inner contents
- // (between the opening { and the matched closing }), then advance.
- out += source.slice(lastIdx, openStart);
- out += source.slice(openEnd, i - 1); // i-1 = position of the closing }
- lastIdx = i;
- re.lastIndex = i;
- }
- out += source.slice(lastIdx);
- return out;
-}
-
-// ---------------------------------------------------------------------------
-// Static HTML/CSS detection (default for local HTML files)
-// ---------------------------------------------------------------------------
-
-const STATIC_INHERITED_PROPS = new Set([
- 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight',
- 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'hyphens',
- 'webkitHyphens',
-]);
-
-const STATIC_DEFAULT_STYLE = {
- color: 'rgb(0, 0, 0)',
- backgroundColor: 'rgba(0, 0, 0, 0)',
- backgroundImage: 'none',
- borderTopWidth: '0px',
- borderRightWidth: '0px',
- borderBottomWidth: '0px',
- borderLeftWidth: '0px',
- borderTopColor: 'rgb(0, 0, 0)',
- borderRightColor: 'rgb(0, 0, 0)',
- borderBottomColor: 'rgb(0, 0, 0)',
- borderLeftColor: 'rgb(0, 0, 0)',
- borderRadius: '0px',
- boxShadow: 'none',
- fontFamily: '',
- fontSize: '16px',
- fontStyle: 'normal',
- fontWeight: '400',
- lineHeight: 'normal',
- letterSpacing: 'normal',
- textTransform: 'none',
- textAlign: 'start',
- hyphens: 'manual',
- webkitHyphens: 'manual',
- transitionProperty: '',
- transitionTimingFunction: '',
- animationName: '',
- animationTimingFunction: '',
- webkitBackgroundClip: '',
- backgroundClip: '',
- width: '',
- height: '',
- paddingTop: '0px',
- paddingRight: '0px',
- paddingBottom: '0px',
- paddingLeft: '0px',
- position: 'static',
- display: '',
-};
-
-const STATIC_PROP_MAP = {
- 'background-color': 'backgroundColor',
- 'background-image': 'backgroundImage',
- 'background-clip': 'backgroundClip',
- '-webkit-background-clip': 'webkitBackgroundClip',
- 'border-radius': 'borderRadius',
- 'border-top-width': 'borderTopWidth',
- 'border-right-width': 'borderRightWidth',
- 'border-bottom-width': 'borderBottomWidth',
- 'border-left-width': 'borderLeftWidth',
- 'border-top-color': 'borderTopColor',
- 'border-right-color': 'borderRightColor',
- 'border-bottom-color': 'borderBottomColor',
- 'border-left-color': 'borderLeftColor',
- 'box-shadow': 'boxShadow',
- 'font-family': 'fontFamily',
- 'font-size': 'fontSize',
- 'font-style': 'fontStyle',
- 'font-weight': 'fontWeight',
- 'line-height': 'lineHeight',
- 'letter-spacing': 'letterSpacing',
- 'text-transform': 'textTransform',
- 'text-align': 'textAlign',
- 'hyphens': 'hyphens',
- '-webkit-hyphens': 'webkitHyphens',
- 'transition-property': 'transitionProperty',
- 'transition-timing-function': 'transitionTimingFunction',
- 'animation-name': 'animationName',
- 'animation-timing-function': 'animationTimingFunction',
- 'width': 'width',
- 'height': 'height',
- 'padding-top': 'paddingTop',
- 'padding-right': 'paddingRight',
- 'padding-bottom': 'paddingBottom',
- 'padding-left': 'paddingLeft',
- 'position': 'position',
- 'display': 'display',
-};
-
-const STATIC_NAMED_COLORS = {
- black: { r: 0, g: 0, b: 0, a: 1 },
- white: { r: 255, g: 255, b: 255, a: 1 },
- transparent: { r: 0, g: 0, b: 0, a: 0 },
- gray: { r: 128, g: 128, b: 128, a: 1 },
- grey: { r: 128, g: 128, b: 128, a: 1 },
- silver: { r: 192, g: 192, b: 192, a: 1 },
- red: { r: 255, g: 0, b: 0, a: 1 },
- green: { r: 0, g: 128, b: 0, a: 1 },
- blue: { r: 0, g: 0, b: 255, a: 1 },
-};
-
-function splitCssList(value) {
- const parts = [];
- let depth = 0, quote = '', start = 0;
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; continue; }
- if (ch === '(' || ch === '[') depth++;
- else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);
- else if (ch === ',' && depth === 0) {
- parts.push(value.slice(start, i).trim());
- start = i + 1;
- }
- }
- const tail = value.slice(start).trim();
- if (tail) parts.push(tail);
- return parts;
-}
-
-function splitCssTokens(value) {
- const tokens = [];
- let depth = 0, quote = '', current = '';
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- current += ch;
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
- if (ch === '(') { depth++; current += ch; continue; }
- if (ch === ')') { depth = Math.max(0, depth - 1); current += ch; continue; }
- if (/\s/.test(ch) && depth === 0) {
- if (current) { tokens.push(current); current = ''; }
- continue;
- }
- current += ch;
- }
- if (current) tokens.push(current);
- return tokens;
-}
-
-function cssPropToCamel(prop) {
- if (!prop) return prop;
- const mapped = STATIC_PROP_MAP[prop];
- if (mapped) return mapped;
- return prop.replace(/-([a-z])/g, (_m, ch) => ch.toUpperCase());
-}
-
-function staticColorToCss(c) {
- if (!c) return '';
- if (c.a != null && c.a < 1) return `rgba(${c.r}, ${c.g}, ${c.b}, ${Number(c.a.toFixed(3))})`;
- return `rgb(${c.r}, ${c.g}, ${c.b})`;
-}
-
-function parseStaticColor(value) {
- const parsed = parseAnyColor(value);
- if (parsed) return parsed;
- const named = STATIC_NAMED_COLORS[String(value || '').trim().toLowerCase()];
- return named ? { ...named } : null;
-}
-
-function extractStaticColor(value) {
- if (!value) return '';
- const raw = String(value).trim();
- if (/^var\(/i.test(raw)) return raw;
- const colorLike = raw.match(/(?:rgba?\([^)]+\)|oklch\([^)]+\)|oklab\([^)]+\)|lch\([^)]+\)|lab\([^)]+\)|hsla?\([^)]+\)|hwb\([^)]+\)|#[0-9a-f]{3,8}\b|\b(?:black|white|gray|grey|silver|red|green|blue|transparent)\b)/i);
- if (!colorLike) return '';
- return colorLike[0];
-}
-
-function normalizeStaticCssValue(prop, value, customProps, parentStyle, currentStyle = null) {
- let resolved = resolveVarRefs(String(value || '').trim(), customProps);
- if (resolved === 'inherit') return parentStyle?.[prop] || STATIC_DEFAULT_STYLE[prop] || '';
- const isModernBorderColor = /^border[A-Z][a-z]+Color$/.test(prop) && /^(?:oklch|oklab|lch|lab|hsl|hwb)\(/i.test(resolved);
- if (!isModernBorderColor && (/color$/i.test(prop) || prop === 'color' || prop === 'backgroundColor')) {
- const parsed = parseStaticColor(resolved);
- if (parsed) resolved = staticColorToCss(parsed);
- }
- if (prop === 'fontSize') {
- const base = parseFloat(parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'letterSpacing') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'lineHeight' && resolved !== 'normal') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- return resolved;
-}
-
-function expandStaticBoxValues(tokens) {
- if (tokens.length === 0) return ['0px', '0px', '0px', '0px'];
- if (tokens.length === 1) return [tokens[0], tokens[0], tokens[0], tokens[0]];
- if (tokens.length === 2) return [tokens[0], tokens[1], tokens[0], tokens[1]];
- if (tokens.length === 3) return [tokens[0], tokens[1], tokens[2], tokens[1]];
- return [tokens[0], tokens[1], tokens[2], tokens[3]];
-}
-
-function parseStaticBorder(value) {
- const tokens = splitCssTokens(value);
- let width = '', color = '';
- for (const token of tokens) {
- if (!width && /^-?[\d.]+(?:px|rem|em|%)$/.test(token)) width = token;
- if (!color) color = extractStaticColor(token);
- }
- return { width, color };
-}
-
-function parseStaticFont(value) {
- const out = [];
- const slashParts = value.match(/(?:^|\s)([\d.]+(?:px|rem|em|%))(?:\/([^\s]+))?/);
- if (/\bitalic\b/i.test(value)) out.push(['fontStyle', 'italic']);
- const weight = value.match(/\b([1-9]00|bold|normal|lighter|bolder)\b/i);
- if (weight) out.push(['fontWeight', weight[1]]);
- if (slashParts) {
- out.push(['fontSize', slashParts[1]]);
- if (slashParts[2]) out.push(['lineHeight', slashParts[2]]);
- const familyStart = value.indexOf(slashParts[0]) + slashParts[0].length;
- const family = value.slice(familyStart).trim();
- if (family) out.push(['fontFamily', family]);
- }
- return out;
-}
-
-function parseStaticTransition(value) {
- const props = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const prop = tokens.find(token => /^[a-z-]+$/i.test(token) && !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none)$/.test(token) && !/s$/.test(token));
- if (prop) props.push(prop);
- }
- return {
- property: props.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function parseStaticAnimation(value) {
- const names = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const name = tokens.find(token =>
- /^[a-z_-][\w-]*$/i.test(token) &&
- !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none|running|paused)$/.test(token)
- );
- if (name) names.push(name);
- }
- return {
- name: names.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function expandStaticDeclaration(prop, value) {
- const p = prop.toLowerCase();
- const v = String(value || '').trim();
- if (!v) return [];
- if (p.startsWith('--')) return [[p, v]];
- if (p === 'background') {
- const out = [];
- const hasImage = /gradient|url\(/i.test(v);
- if (hasImage) out.push(['backgroundImage', v]);
- const beforeImage = hasImage ? v.split(/(?:repeating-)?(?:linear|radial|conic)-gradient\(|url\(/i)[0] : v;
- const color = extractStaticColor(hasImage ? beforeImage : v);
- if (color) out.push(['backgroundColor', color]);
- return out;
- }
- if (p === 'border') {
- const parsed = parseStaticBorder(v);
- const out = [];
- for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
- if (parsed.width) out.push([`border${side}Width`, parsed.width]);
- if (parsed.color) out.push([`border${side}Color`, parsed.color]);
- }
- return out;
- }
- const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
- if (sideMatch) {
- const parsed = parseStaticBorder(v);
- const side = sideMatch[1][0].toUpperCase() + sideMatch[1].slice(1);
- return [
- ...(parsed.width ? [[`border${side}Width`, parsed.width]] : []),
- ...(parsed.color ? [[`border${side}Color`, parsed.color]] : []),
- ];
- }
- if (p === 'border-width') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopWidth', vals[0]],
- ['borderRightWidth', vals[1]],
- ['borderBottomWidth', vals[2]],
- ['borderLeftWidth', vals[3]],
- ];
- }
- if (p === 'border-color') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopColor', vals[0]],
- ['borderRightColor', vals[1]],
- ['borderBottomColor', vals[2]],
- ['borderLeftColor', vals[3]],
- ];
- }
- if (p === 'padding') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['paddingTop', vals[0]],
- ['paddingRight', vals[1]],
- ['paddingBottom', vals[2]],
- ['paddingLeft', vals[3]],
- ];
- }
- if (p === 'font') return parseStaticFont(v);
- if (p === 'transition') {
- const parsed = parseStaticTransition(v);
- return [
- ...(parsed.property ? [['transitionProperty', parsed.property]] : []),
- ...(parsed.timing ? [['transitionTimingFunction', parsed.timing]] : []),
- ];
- }
- if (p === 'animation') {
- const parsed = parseStaticAnimation(v);
- return [
- ...(parsed.name ? [['animationName', parsed.name]] : []),
- ...(parsed.timing ? [['animationTimingFunction', parsed.timing]] : []),
- ];
- }
- const mapped = cssPropToCamel(p);
- if (STATIC_DEFAULT_STYLE[mapped] != null || STATIC_INHERITED_PROPS.has(mapped)) {
- return [[mapped, v]];
- }
- return [];
-}
-
-function compareStaticPriority(a, b) {
- if (!a) return true;
- if (!!b.important !== !!a.important) return !!b.important;
- if (!!b.inline !== !!a.inline) return !!b.inline;
- for (let i = 0; i < 3; i++) {
- if ((b.specificity[i] || 0) !== (a.specificity[i] || 0)) {
- return (b.specificity[i] || 0) > (a.specificity[i] || 0);
- }
- }
- return b.order >= a.order;
-}
-
-function staticSpecificity(selector) {
- const noWhere = selector.replace(/:where\([^)]*\)/g, '');
- const ids = (noWhere.match(/#[\w-]+/g) || []).length;
- const classes = (noWhere.match(/\.[\w-]+|\[[^\]]+\]|:(?!:)[\w-]+(?:\([^)]*\))?/g) || []).length;
- const stripped = noWhere
- .replace(/#[\w-]+/g, ' ')
- .replace(/\.[\w-]+|\[[^\]]+\]|:{1,2}[\w-]+(?:\([^)]*\))?/g, ' ')
- .replace(/[*>+~(),]/g, ' ');
- const types = (stripped.match(/\b[a-zA-Z][\w-]*\b/g) || []).length;
- return [ids, classes, types];
-}
-
-function applyStaticDeclaration(specified, node, prop, value, meta) {
- let map = specified.get(node);
- if (!map) { map = new Map(); specified.set(node, map); }
- for (const [expandedProp, expandedValue] of expandStaticDeclaration(prop, value)) {
- const existing = map.get(expandedProp);
- const next = { ...meta, prop: expandedProp, value: expandedValue };
- if (compareStaticPriority(existing, next)) map.set(expandedProp, next);
- }
-}
-
-function parseStaticStyleAttribute(styleText, orderBase = 0) {
- const decls = [];
- for (const part of String(styleText || '').split(';')) {
- const idx = part.indexOf(':');
- if (idx <= 0) continue;
- const prop = part.slice(0, idx).trim();
- let value = part.slice(idx + 1).trim();
- const important = /!important\s*$/i.test(value);
- value = value.replace(/\s*!important\s*$/i, '').trim();
- decls.push({ prop, value, important, order: orderBase + decls.length });
- }
- return decls;
-}
-
-function collectStaticCssRules(cssText, csstree) {
- const rules = [];
- let ast;
- try {
- ast = csstree.parse(cssText, { positions: false, parseValue: true, parseCustomProperty: false });
- } catch {
- return rules;
- }
- let order = 0;
- const walkList = (list, atRuleStack = []) => {
- list?.forEach?.(node => {
- if (node.type === 'Rule' && node.block) {
- if (atRuleStack.some(name => /keyframes$/i.test(name))) return;
- const selectorText = csstree.generate(node.prelude).trim();
- const declarations = [];
- node.block.children?.forEach?.(child => {
- if (child.type !== 'Declaration') return;
- declarations.push({
- prop: child.property,
- value: csstree.generate(child.value).trim(),
- important: !!child.important,
- });
- });
- for (const selector of splitCssList(selectorText)) {
- if (selector) rules.push({ selector, declarations, specificity: staticSpecificity(selector), order: order++ });
- }
- return;
- }
- if (node.type === 'Atrule' && node.block) {
- const name = String(node.name || '').toLowerCase();
- if (name === 'media' || name === 'supports' || name === 'layer') {
- walkList(node.block.children, [...atRuleStack, name]);
- }
- }
- });
- };
- walkList(ast.children);
- return rules;
-}
-
-class StaticElement {
- constructor(node, doc) {
- this.node = node;
- this._doc = doc;
- this.nodeType = 1;
- this.tagName = String(node.name || '').toUpperCase();
- this.nodeName = this.tagName;
- }
- get parentElement() {
- let cur = this.node.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- return cur ? this._doc.wrap(cur) : null;
- }
- get previousElementSibling() {
- let cur = this.node.prev;
- while (cur && cur.type !== 'tag') cur = cur.prev;
- return cur ? this._doc.wrap(cur) : null;
- }
- get children() {
- return (this.node.children || []).filter(child => child.type === 'tag').map(child => this._doc.wrap(child));
- }
- get childNodes() {
- return (this.node.children || []).map(child => {
- if (child.type === 'text') return { nodeType: 3, textContent: child.data || '' };
- if (child.type === 'tag') return this._doc.wrap(child);
- return { nodeType: 8, textContent: child.data || '' };
- });
- }
- get textContent() {
- return this._doc.domutils.textContent(this.node);
- }
- get className() {
- return this.getAttribute('class') || '';
- }
- get id() {
- return this.getAttribute('id') || '';
- }
- getAttribute(name) {
- return this.node.attribs?.[name] ?? null;
- }
- querySelector(selector) {
- try {
- const found = this._doc.selectOne(selector, this.node.children || []);
- return found ? this._doc.wrap(found) : null;
- } catch {
- return null;
- }
- }
- querySelectorAll(selector) {
- try {
- return this._doc.selectAll(selector, this.node.children || []).map(node => this._doc.wrap(node));
- } catch {
- return [];
- }
- }
- closest(selector) {
- let cur = this.node;
- while (cur && cur.type === 'tag') {
- try {
- if (this._doc.is(cur, selector)) return this._doc.wrap(cur);
- } catch {
- return null;
- }
- cur = cur.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- }
- return null;
- }
- contains(other) {
- let cur = other?.node || null;
- while (cur) {
- if (cur === this.node) return true;
- cur = cur.parent;
- }
- return false;
- }
-}
-
-class StaticDocument {
- constructor(root, modules) {
- this.root = root;
- this.selectAll = modules.selectAll;
- this.selectOne = modules.selectOne;
- this.is = modules.is;
- this.domutils = modules.domutils;
- this._wrappers = new WeakMap();
- this._styleMap = new WeakMap();
- }
- wrap(node) {
- let wrapped = this._wrappers.get(node);
- if (!wrapped) {
- wrapped = new StaticElement(node, this);
- this._wrappers.set(node, wrapped);
- }
- return wrapped;
- }
- querySelectorAll(selector) {
- try {
- return this.selectAll(selector, this.root.children || []).map(node => this.wrap(node));
- } catch {
- return [];
- }
- }
- querySelector(selector) {
- try {
- const found = this.selectOne(selector, this.root.children || []);
- return found ? this.wrap(found) : null;
- } catch {
- return null;
- }
- }
- get documentElement() {
- return this.querySelector('html');
- }
- get body() {
- return this.querySelector('body');
- }
- setStyle(node, style) {
- this._styleMap.set(node, style);
- }
- getStyle(el) {
- return this._styleMap.get(el.node) || makeStaticStyle();
- }
-}
-
-function makeStaticStyle(values = {}) {
- const style = { ...STATIC_DEFAULT_STYLE, ...values };
- style.getPropertyValue = (prop) => {
- const key = cssPropToCamel(prop);
- return style[key] || style[prop] || '';
- };
- return style;
-}
-
-function buildStaticWindow(staticDoc) {
- return {
- document: staticDoc,
- getComputedStyle: (el) => staticDoc.getStyle(el),
- };
-}
-
-function collectStaticCssText(root, fileDir, profile, filePath, modules) {
- const styleTexts = [];
- for (const styleEl of modules.selectAll('style', root.children || [])) {
- styleTexts.push(modules.domutils.textContent(styleEl));
- }
- const links = modules.selectAll('link', root.children || []);
- for (const link of links) {
- const rel = link.attribs?.rel || '';
- const href = link.attribs?.href || '';
- if (!/\bstylesheet\b/i.test(rel) || !href || /^(https?:)?\/\//i.test(href)) continue;
- const cssPath = path.resolve(fileDir, href);
- try {
- const css = profileStep(profile, {
- engine: 'static-html',
- phase: 'preprocess',
- ruleId: 'inline-linked-stylesheet',
- target: filePath,
- detail: href,
- }, () => fs.readFileSync(cssPath, 'utf-8'));
- styleTexts.push(css);
- } catch { /* skip unreadable */ }
- }
- return styleTexts.join('\n');
-}
-
-function buildStaticStyleMap(root, staticDoc, cssText, modules, profile, filePath) {
- const specified = new Map();
- const allNodes = modules.selectAll('*', root.children || []);
- const rules = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-css',
- ruleId: 'css-rules',
- target: filePath,
- }, () => collectStaticCssRules(cssText, modules.csstree));
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'css-selectors',
- target: filePath,
- }, () => {
- for (const rule of rules) {
- let matched;
- try {
- matched = modules.selectAll(rule.selector, root.children || []);
- } catch {
- recordProfileEvent(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'unsupported-selector',
- target: filePath,
- ms: 0,
- findings: 0,
- detail: rule.selector,
- });
- continue;
- }
- for (const node of matched) {
- for (const decl of rule.declarations) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: rule.specificity,
- order: rule.order,
- inline: false,
- });
- }
- }
- }
-
- let inlineOrder = rules.length + 1;
- for (const node of allNodes) {
- const styleText = node.attribs?.style;
- if (!styleText) continue;
- for (const decl of parseStaticStyleAttribute(styleText, inlineOrder)) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: [1, 0, 0],
- order: decl.order,
- inline: true,
- });
- }
- inlineOrder += 1000;
- }
- });
-
- const computeNode = (node, parentStyle = null, parentCustom = new Map()) => {
- const specifiedMap = specified.get(node) || new Map();
- const customProps = new Map(parentCustom);
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) customProps.set(prop, resolveVarRefs(decl.value, customProps));
- }
- const values = {};
- for (const prop of Object.keys(STATIC_DEFAULT_STYLE)) {
- if (STATIC_INHERITED_PROPS.has(prop) && parentStyle?.[prop] != null) values[prop] = parentStyle[prop];
- else values[prop] = STATIC_DEFAULT_STYLE[prop];
- }
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) continue;
- values[prop] = normalizeStaticCssValue(prop, decl.value, customProps, parentStyle, values);
- }
- const style = makeStaticStyle(values);
- staticDoc.setStyle(node, style);
- for (const child of node.children || []) {
- if (child.type === 'tag') computeNode(child, style, customProps);
- }
- };
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'cascade',
- ruleId: 'compute-styles',
- target: filePath,
- }, () => {
- for (const child of root.children || []) {
- if (child.type === 'tag') computeNode(child);
- }
- });
-}
-
-export {
- BORDER_SHORTHAND_RE,
- NAMED_COLORS,
- normalizeColorForCheck,
- buildBorderOverrideMap,
- unwrapCssAtLayer,
- STATIC_INHERITED_PROPS,
- STATIC_DEFAULT_STYLE,
- STATIC_PROP_MAP,
- STATIC_NAMED_COLORS,
- splitCssList,
- splitCssTokens,
- cssPropToCamel,
- staticColorToCss,
- parseStaticColor,
- extractStaticColor,
- normalizeStaticCssValue,
- expandStaticBoxValues,
- parseStaticBorder,
- parseStaticFont,
- parseStaticTransition,
- parseStaticAnimation,
- expandStaticDeclaration,
- compareStaticPriority,
- staticSpecificity,
- applyStaticDeclaration,
- parseStaticStyleAttribute,
- collectStaticCssRules,
- StaticElement,
- StaticDocument,
- makeStaticStyle,
- buildStaticWindow,
- collectStaticCssText,
- buildStaticStyleMap,
-};
@@ -1,174 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import {
- checkElementBorders,
- checkElementColors,
- checkElementGlow,
- checkElementHeroEyebrow,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementMotion,
- checkElementQuality,
- checkHtmlPatterns,
- checkPageLayout,
- checkPageQualityFromDoc,
- checkRepeatedSectionKickersFromDoc,
- resolveBackground,
- resolveBorderRadiusPx,
-} from '../../rules/checks.mjs';
-import { detectText } from '../regex/detect-text.mjs';
-import {
- StaticDocument,
- buildStaticStyleMap,
- buildStaticWindow,
- collectStaticCssText,
-} from './css-cascade.mjs';
-
-function checkStaticPageTypography(document, window) {
- const findings = [];
- const fonts = new Set();
- const overusedFound = new Set();
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span, div')) {
- const hasText = el.childNodes.some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const ff = window.getComputedStyle(el).fontFamily || '';
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
- if (fonts.size === 1 && document.querySelectorAll('*').length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div')) {
- const fontSize = parseFloat(window.getComputedStyle(el).fontSize);
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
- return findings;
-}
-
-const STATIC_ELEMENT_RULES = [
- { id: 'border-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementBorders(tag, style, null, resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window)) },
- { id: 'color-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementColors(el, style, tag, window, customPropMap, false) },
- { id: 'dark-glow', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window, customPropMap)) },
- { id: 'motion-rules', selector: '*', run: (el, tag, style) => checkElementMotion(tag, style) },
- { id: 'icon-tile-stack', selector: 'h1,h2,h3,h4,h5,h6', run: (el, tag, _style, window) => checkElementIconTile(el, tag, window) },
- { id: 'italic-serif-display', selector: 'h1,h2', run: (el, tag, style) => checkElementItalicSerif(el, style, tag) },
- { id: 'hero-eyebrow-chip', selector: 'h1', run: (el, tag, style, window, customPropMap) => checkElementHeroEyebrow(el, style, tag, window, customPropMap) },
- { id: 'quality-rules', selector: '*', run: (el, tag, style, window) => checkElementQuality(el, style, tag, window) },
-];
-
-async function detectHtml(filePath, options = {}) {
- const profile = options?.profile;
- const html = profileStep(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'read-html',
- target: filePath,
- }, () => fs.readFileSync(filePath, 'utf-8'));
-
- let modules;
- try {
- modules = await profileStepAsync(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'import-static-parser',
- target: filePath,
- }, async () => {
- const [htmlparser2, cssSelect, csstree, domutils] = await Promise.all([
- import('htmlparser2'),
- import('css-select'),
- import('css-tree'),
- import('domutils'),
- ]);
- return {
- parseDocument: htmlparser2.parseDocument,
- selectAll: cssSelect.selectAll,
- selectOne: cssSelect.selectOne,
- is: cssSelect.is,
- csstree,
- domutils,
- };
- });
- } catch {
- return detectText(html, filePath, options);
- }
-
- const resolvedPath = path.resolve(filePath);
- const fileDir = path.dirname(resolvedPath);
- const root = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-html',
- ruleId: 'parse-document',
- target: filePath,
- }, () => modules.parseDocument(html, { lowerCaseAttributeNames: false, lowerCaseTags: true }));
-
- const cssText = collectStaticCssText(root, fileDir, profile, filePath, modules);
- const document = new StaticDocument(root, modules);
- buildStaticStyleMap(root, document, cssText, modules, profile, filePath);
- const window = buildStaticWindow(document);
-
- const customPropMap = null;
-
- const findings = [];
- const runElementCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'element', ruleId, target: filePath }, callback)
- : callback();
-
- const visitedByRule = new Map();
- for (const rule of STATIC_ELEMENT_RULES) {
- const elements = document.querySelectorAll(rule.selector);
- visitedByRule.set(rule.id, elements.length);
- for (const el of elements) {
- const tag = el.tagName.toLowerCase();
- const style = window.getComputedStyle(el);
- for (const f of runElementCheck(rule.id, () => rule.run(el, tag, style, window, customPropMap))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
- }
-
- if (isFullPage(html)) {
- const runPageCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
- : callback();
- for (const f of runPageCheck('typography-rules', () => checkStaticPageTypography(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('repeated-section-kickers', () => checkRepeatedSectionKickersFromDoc(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('layout-rules', () => checkPageLayout(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('skipped-heading', () => checkPageQualityFromDoc(document))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('html-patterns', () => checkHtmlPatterns(html).filter(item =>
- item.id !== 'bounce-easing' && item.id !== 'layout-transition'
- ))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
-
- return findings;
-}
-
-export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -1,189 +0,0 @@
-function sanitizeScreenshotClip(clip, viewport) {
- if (!clip) return null;
- const x = Math.max(0, Math.floor(clip.x || 0));
- const y = Math.max(0, Math.floor(clip.y || 0));
- const width = Math.min(
- Math.max(1, Math.ceil(clip.width || 0)),
- Math.max(1, viewport?.width || 1600),
- );
- const height = Math.min(
- Math.max(1, Math.ceil(clip.height || 0)),
- 320,
- );
- if (width < 1 || height < 1) return null;
- return { x, y, width, height };
-}
-
-async function compareScreenshotContrast(page, beforeBase64, afterBase64, candidate) {
- return page.evaluate(async ({ beforeBase64, afterBase64, candidate }) => {
- const loadImage = (base64) => new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = () => reject(new Error('Could not decode contrast screenshot'));
- img.src = `data:image/png;base64,${base64}`;
- });
- const [before, after] = await Promise.all([loadImage(beforeBase64), loadImage(afterBase64)]);
- const width = Math.min(before.width, after.width);
- const height = Math.min(before.height, after.height);
- if (width < 1 || height < 1) return null;
-
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return null;
-
- ctx.drawImage(before, 0, 0, width, height);
- const beforePixels = ctx.getImageData(0, 0, width, height).data;
- ctx.clearRect(0, 0, width, height);
- ctx.drawImage(after, 0, 0, width, height);
- const afterPixels = ctx.getImageData(0, 0, width, height).data;
-
- const luminance = ({ r, g, b }) => {
- const convert = c => {
- const v = c / 255;
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
- };
- return 0.2126 * convert(r) + 0.7152 * convert(g) + 0.0722 * convert(b);
- };
- const ratio = (a, b) => {
- const l1 = luminance(a);
- const l2 = luminance(b);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
- };
-
- const cssTextColor = candidate.textColor && !candidate.preferRenderedForeground
- ? {
- r: candidate.textColor.r,
- g: candidate.textColor.g,
- b: candidate.textColor.b,
- }
- : null;
- const ratios = [];
- let glyphPixels = 0;
- let strongestDelta = 0;
- for (let i = 0; i < beforePixels.length; i += 4) {
- const delta = Math.abs(beforePixels[i] - afterPixels[i])
- + Math.abs(beforePixels[i + 1] - afterPixels[i + 1])
- + Math.abs(beforePixels[i + 2] - afterPixels[i + 2])
- + Math.abs(beforePixels[i + 3] - afterPixels[i + 3]);
- strongestDelta = Math.max(strongestDelta, delta);
- if (delta < 10) continue;
- glyphPixels++;
- const fg = cssTextColor || {
- r: beforePixels[i],
- g: beforePixels[i + 1],
- b: beforePixels[i + 2],
- };
- const bg = {
- r: afterPixels[i],
- g: afterPixels[i + 1],
- b: afterPixels[i + 2],
- };
- ratios.push(ratio(fg, bg));
- }
-
- if (ratios.length < 8) {
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: null,
- p10Ratio: null,
- medianRatio: null,
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: ratios[0],
- p10Ratio: pick(10),
- medianRatio: pick(50),
- };
- }, { beforeBase64, afterBase64, candidate });
-}
-
-async function captureVisualContrastCandidate(page, candidate, viewport) {
- const clip = sanitizeScreenshotClip(candidate.clip, viewport);
- if (!clip) return null;
-
- const beforeBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- const token = `impeccable-contrast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- const applied = await page.evaluate(({ selector, token, backgroundClipText }) => {
- let el;
- try {
- el = document.querySelector(selector);
- } catch {
- return false;
- }
- if (!el) return false;
- let style = document.getElementById('impeccable-visual-contrast-hide-style');
- if (!style) {
- style = document.createElement('style');
- style.id = 'impeccable-visual-contrast-hide-style';
- style.textContent = [
- '[data-impeccable-visual-contrast-target] {',
- ' color: transparent !important;',
- ' -webkit-text-fill-color: transparent !important;',
- ' text-shadow: none !important;',
- '}',
- '[data-impeccable-visual-contrast-target][data-impeccable-bgclip-text="true"] {',
- ' background-image: none !important;',
- '}',
- ].join('\n');
- document.head.appendChild(style);
- }
- el.setAttribute('data-impeccable-visual-contrast-target', token);
- if (backgroundClipText) el.setAttribute('data-impeccable-bgclip-text', 'true');
- return true;
- }, {
- selector: candidate.selector,
- token,
- backgroundClipText: candidate.backgroundClipText,
- });
- if (!applied) return null;
-
- let afterBase64;
- try {
- afterBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- } finally {
- await page.evaluate(({ selector }) => {
- try {
- const el = document.querySelector(selector);
- if (el) {
- el.removeAttribute('data-impeccable-visual-contrast-target');
- el.removeAttribute('data-impeccable-bgclip-text');
- }
- } catch {
- // Ignore invalid or stale selectors during cleanup.
- }
- }, { selector: candidate.selector }).catch(() => {});
- }
-
- const metrics = await compareScreenshotContrast(page, beforeBase64, afterBase64, candidate);
- if (!metrics || !Number.isFinite(metrics.p10Ratio) || metrics.glyphPixels < 8) return null;
- const measuredRatio = metrics.p10Ratio;
- if (measuredRatio >= candidate.threshold) return null;
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const reasonLabel = (candidate.reasons || []).slice(0, 3).join(', ') || 'visual background';
- return {
- id: 'low-contrast',
- snippet: `pixel contrast ${measuredRatio.toFixed(1)}:1 median ${metrics.medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) on ${reasonLabel}${textLabel}`,
- };
-}
-
-export {
- sanitizeScreenshotClip,
- compareScreenshotContrast,
- captureVisualContrastCandidate,
-};
@@ -1,12 +0,0 @@
-import { getAntipattern } from './registry/antipatterns.mjs';
-
-function getAP(id) {
- return getAntipattern(id);
-}
-
-function finding(id, filePath, snippet, line = 0) {
- const ap = getAP(id);
- return { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', file: filePath, line, snippet };
-}
-
-export { getAP, finding };
@@ -1,198 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-// ---------------------------------------------------------------------------
-// File walker
-// ---------------------------------------------------------------------------
-
-const SKIP_DIRS = new Set([
- 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
- '.svelte-kit', '__pycache__', '.turbo', '.vercel',
-]);
-
-const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
- '.jsx', '.tsx', '.js', '.ts',
- '.vue', '.svelte', '.astro',
-]);
-
-const HTML_EXTENSIONS = new Set(['.html', '.htm']);
-
-function walkDir(dir) {
- const files = [];
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
- for (const entry of entries) {
- if (SKIP_DIRS.has(entry.name)) continue;
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) files.push(...walkDir(full));
- else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
- }
- return files;
-}
-
-
-// ---------------------------------------------------------------------------
-// Import graph (multi-file awareness)
-// ---------------------------------------------------------------------------
-
-function resolveImport(specifier, fromDir, fileSet) {
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
- const base = path.resolve(fromDir, specifier);
- if (fileSet.has(base)) return base;
- for (const ext of SCANNABLE_EXTENSIONS) {
- const withExt = base + ext;
- if (fileSet.has(withExt)) return withExt;
- }
- // index file convention
- for (const ext of SCANNABLE_EXTENSIONS) {
- const indexFile = path.join(base, 'index' + ext);
- if (fileSet.has(indexFile)) return indexFile;
- }
- return null;
-}
-
-function buildImportGraph(files) {
- const fileSet = new Set(files);
- const graph = new Map();
-
- for (const file of files) {
- const content = fs.readFileSync(file, 'utf-8');
- const dir = path.dirname(file);
- const imports = new Set();
-
- // ES imports: import ... from '...' and import '...'
- const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
- let m;
- while ((m = esRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // CSS @import
- const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
- while ((m = cssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // SCSS @use / @forward
- const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
- while ((m = scssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- graph.set(file, imports);
- }
- return graph;
-}
-
-// ---------------------------------------------------------------------------
-// Framework dev server detection
-// ---------------------------------------------------------------------------
-
-const FRAMEWORK_CONFIGS = [
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /next/i } },
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-sveltekit-page', value: null } },
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /@vite\/client/ } },
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /astro/i } },
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
- portRe: /"port"\s*:\s*(\d+)/,
- fingerprint: { body: /ng-version/i } },
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
-];
-
-function detectFrameworkConfig(dir) {
- let entries;
- try { entries = fs.readdirSync(dir); } catch { return null; }
- const entrySet = new Set(entries);
-
- for (const cfg of FRAMEWORK_CONFIGS) {
- const match = cfg.files.find(f => entrySet.has(f));
- if (!match) continue;
-
- const configPath = path.join(dir, match);
- let port = cfg.defaultPort;
- try {
- const content = fs.readFileSync(configPath, 'utf-8');
- const portMatch = content.match(cfg.portRe);
- if (portMatch) port = parseInt(portMatch[1], 10);
- } catch { /* use default */ }
-
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
- }
- return null;
-}
-
-/**
- * Check if a port is listening and optionally verify it matches the expected framework.
- * Returns { listening: true, matched: true/false } or { listening: false }.
- */
-async function isPortListening(port, fingerprint = null) {
- if (!fingerprint) {
- // Simple TCP probe fallback
- const net = await import('node:net');
- return new Promise((resolve) => {
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
- sock.setTimeout(500);
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
- sock.on('error', () => resolve({ listening: false }));
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
- });
- }
-
- // HTTP probe with fingerprint matching
- try {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 2000);
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
- clearTimeout(timeout);
-
- // Check header fingerprint
- if (fingerprint.header) {
- const val = res.headers.get(fingerprint.header);
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
- return { listening: true, matched: true };
- }
- }
-
- // Check body fingerprint
- if (fingerprint.body) {
- const body = await res.text();
- if (fingerprint.body.test(body)) {
- return { listening: true, matched: true };
- }
- }
-
- // Port is listening but doesn't match the expected framework
- return { listening: true, matched: false };
- } catch {
- return { listening: false };
- }
-}
-
-export {
- SKIP_DIRS,
- SCANNABLE_EXTENSIONS,
- HTML_EXTENSIONS,
- walkDir,
- resolveImport,
- buildImportGraph,
- FRAMEWORK_CONFIGS,
- detectFrameworkConfig,
- isPortListening,
-};
@@ -1,166 +0,0 @@
-function profileNow() {
- return typeof performance !== 'undefined' && performance.now
- ? performance.now()
- : Date.now();
-}
-
-function createDetectorProfile() {
- return { events: [] };
-}
-
-function recordProfileEvent(profile, event) {
- if (!profile) return;
- const normalized = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- ms: Number.isFinite(event.ms) ? event.ms : 0,
- findings: Number.isFinite(event.findings) ? event.findings : 0,
- };
- if (event.detail) normalized.detail = event.detail;
- if (Array.isArray(event.findingIds) && event.findingIds.length) {
- normalized.findingIds = event.findingIds;
- }
- if (typeof profile === 'function') {
- profile(normalized);
- } else if (typeof profile.record === 'function') {
- profile.record(normalized);
- } else if (Array.isArray(profile.events)) {
- profile.events.push(normalized);
- } else if (Array.isArray(profile)) {
- profile.push(normalized);
- }
-}
-
-function extractFindingIds(findings) {
- if (!Array.isArray(findings) || findings.length === 0) return [];
- return [...new Set(findings.map(f => f?.id || f?.type || f?.antipattern).filter(Boolean))];
-}
-
-function profileFindings(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-function profileStep(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-async function profileFindingsAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = await callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-async function profileStepAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return await callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-function percentile(sortedValues, pct) {
- if (!sortedValues.length) return 0;
- const idx = Math.min(
- sortedValues.length - 1,
- Math.max(0, Math.ceil((pct / 100) * sortedValues.length) - 1),
- );
- return sortedValues[idx];
-}
-
-function summarizeDetectorProfile(profile) {
- const events = Array.isArray(profile)
- ? profile
- : (Array.isArray(profile?.events) ? profile.events : []);
- const groups = new Map();
- for (const event of events) {
- const key = [
- event.engine || 'unknown',
- event.phase || 'unknown',
- event.ruleId || 'unknown',
- event.target || '',
- ].join('\u0000');
- let group = groups.get(key);
- if (!group) {
- group = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- calls: 0,
- totalMs: 0,
- findings: 0,
- samples: [],
- };
- groups.set(key, group);
- }
- const ms = Number.isFinite(event.ms) ? event.ms : 0;
- group.calls += 1;
- group.totalMs += ms;
- group.findings += Number.isFinite(event.findings) ? event.findings : 0;
- group.samples.push(ms);
- }
- return [...groups.values()]
- .map(group => {
- const samples = group.samples.sort((a, b) => a - b);
- return {
- engine: group.engine,
- phase: group.phase,
- ruleId: group.ruleId,
- target: group.target,
- calls: group.calls,
- totalMs: Number(group.totalMs.toFixed(3)),
- avgMs: Number((group.totalMs / group.calls).toFixed(3)),
- p50: Number(percentile(samples, 50).toFixed(3)),
- p95: Number(percentile(samples, 95).toFixed(3)),
- findings: group.findings,
- };
- })
- .sort((a, b) => b.totalMs - a.totalMs);
-}
-
-export {
- profileNow,
- createDetectorProfile,
- recordProfileEvent,
- extractFindingIds,
- profileFindings,
- profileStep,
- profileFindingsAsync,
- profileStepAsync,
- percentile,
- summarizeDetectorProfile,
-};
@@ -1,278 +0,0 @@
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-const RULE_ENGINE_SUPPORT = {
- regex: new Set(['source', 'page-analyzer']),
- 'static-html': new Set(['element', 'page']),
- browser: new Set(['element', 'page', 'layout']),
- visual: new Set(['visual-contrast']),
-};
-
-function getAntipattern(id) {
- return ANTIPATTERNS.find(rule => rule.id === id);
-}
-
-function getRulesForCategory(category) {
- return ANTIPATTERNS.filter(rule => rule.category === category);
-}
-
-function getRuleEngineSupport(engine) {
- return RULE_ENGINE_SUPPORT[engine] || new Set();
-}
-
-export {
- ANTIPATTERNS,
- RULE_ENGINE_SUPPORT,
- getAntipattern,
- getRulesForCategory,
- getRuleEngineSupport,
-};
@@ -1,1948 +0,0 @@
-import {
- BORDER_SAFE_TAGS,
- GENERIC_FONTS,
- KNOWN_SERIF_FONTS,
- OVERUSED_FONTS,
- SAFE_TAGS,
- WCAG_LARGE_BOLD_TEXT_PX,
- WCAG_LARGE_TEXT_PX,
- isBrandFontOnOwnDomain,
-} from '../shared/constants.mjs';
-import {
- colorToHex,
- contrastRatio,
- getHue,
- hasChroma,
- isNeutralColor,
- parseGradientColors,
- parseRgb,
- relativeLuminance,
-} from '../shared/color.mjs';
-
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-export {
- checkBorders,
- isEmojiOnlyText,
- checkColors,
- isCardLikeFromProps,
- checkIconTile,
- resolveSerif,
- checkItalicSerif,
- isAccentColor,
- checkHeroEyebrow,
- checkRepeatedSectionKickers,
- checkMotion,
- checkGlow,
- checkHtmlPatterns,
- readOwnBackgroundColor,
- resolveBackground,
- resolveGradientStops,
- parseRadiusToPx,
- resolveBorderRadiusPx,
- checkElementBordersDOM,
- checkElementColorsDOM,
- checkElementIconTileDOM,
- checkElementItalicSerifDOM,
- checkElementHeroEyebrowDOM,
- buildCustomPropMap,
- resolveVarRefs,
- oklchToRgb,
- parseAnyColor,
- parseColorResolved,
- cleanInlineText,
- isRepeatedKickerCandidate,
- collectRepeatedSectionKickerCandidates,
- checkRepeatedSectionKickersDOM,
- checkElementMotionDOM,
- checkElementGlowDOM,
- checkElementAIPaletteDOM,
- resolveFontSizePx,
- resolveLengthPx,
- checkQuality,
- checkElementQualityDOM,
- checkPageQualityFromDoc,
- checkPageQualityDOM,
- checkElementQuality,
- checkElementBorders,
- checkElementColors,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementHeroEyebrow,
- checkRepeatedSectionKickersFromDoc,
- checkElementMotion,
- checkElementGlow,
- checkTypography,
- isCardLikeDOM,
- checkLayout,
- checkPageTypography,
- isCardLike,
- checkPageLayout,
-};
@@ -1,124 +0,0 @@
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-export {
- isNeutralColor,
- parseRgb,
- relativeLuminance,
- contrastRatio,
- parseGradientColors,
- hasChroma,
- getHue,
- colorToHex,
-};
@@ -1,101 +0,0 @@
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-export {
- SAFE_TAGS,
- BORDER_SAFE_TAGS,
- OVERUSED_FONTS,
- GOOGLE_DOMAINS,
- VERCEL_DOMAINS,
- GITHUB_DOMAINS,
- BRAND_FONT_DOMAINS,
- isBrandFontOnOwnDomain,
- GENERIC_FONTS,
- WCAG_LARGE_TEXT_PX,
- WCAG_LARGE_BOLD_TEXT_PX,
- KNOWN_SERIF_FONTS,
-};
@@ -1,7 +0,0 @@
-/** Check if content looks like a full page (not a component/partial) */
-function isFullPage(content) {
- const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
- return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
-}
-
-export { isFullPage };
@@ -1,110 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-export const IMPECCABLE_DIR = '.impeccable';
-export const LIVE_DIR = 'live';
-export const CRITIQUE_DIR = 'critique';
-
-export function getImpeccableDir(cwd = process.cwd()) {
- return path.join(cwd, IMPECCABLE_DIR);
-}
-
-export function getDesignSidecarPath(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), 'design.json');
-}
-
-export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {
- const candidates = [
- getDesignSidecarPath(cwd),
- path.join(cwd, 'DESIGN.json'),
- ];
- const contextLegacy = path.join(contextDir, 'DESIGN.json');
- if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
- return candidates;
-}
-
-export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
- return firstExisting(getDesignSidecarCandidates(cwd, contextDir));
-}
-
-export function getLiveDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), LIVE_DIR);
-}
-
-export function getLiveConfigPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'config.json');
-}
-
-export function getLegacyLiveConfigPath(scriptsDir) {
- return path.join(scriptsDir, 'config.json');
-}
-
-export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {
- if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
- const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
- return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
- }
- const primary = getLiveConfigPath(cwd);
- if (fs.existsSync(primary)) return primary;
- if (scriptsDir) {
- const legacy = getLegacyLiveConfigPath(scriptsDir);
- if (fs.existsSync(legacy)) return legacy;
- }
- return primary;
-}
-
-export function getLiveServerPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'server.json');
-}
-
-export function getLegacyLiveServerPath(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live.json');
-}
-
-export function readLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try {
- return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };
- } catch {
- /* try next */
- }
- }
- return null;
-}
-
-export function writeLiveServerInfo(cwd = process.cwd(), info) {
- const filePath = getLiveServerPath(cwd);
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- fs.writeFileSync(filePath, JSON.stringify(info));
- return filePath;
-}
-
-export function removeLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try { fs.unlinkSync(filePath); } catch {}
- }
-}
-
-export function getLiveSessionsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'sessions');
-}
-
-export function getLegacyLiveSessionsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'sessions');
-}
-
-export function getLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'annotations');
-}
-
-export function getCritiqueDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), CRITIQUE_DIR);
-}
-
-export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'annotations');
-}
-
-function firstExisting(paths) {
- return paths.find((filePath) => fs.existsSync(filePath)) || null;
-}
@@ -1,69 +0,0 @@
-/**
- * Decide whether a given file is "generated" (regenerated by a build step,
- * unsafe to write variants into) or "source" (safe to edit, changes persist).
- *
- * Why this matters: when the user picks an element on a page whose underlying
- * file is regenerated by a build step (e.g. `scripts/build-sub-pages.js`
- * rewriting `public/docs/*.html`), writing variants or accepted changes into
- * that file is silent data loss — the next build wipes them.
- *
- * Signals, in order of reliability:
- * 1. Git check-ignore: gitignored files are assumed generated.
- * 2. File-header markers ("GENERATED", "DO NOT EDIT", "AUTO-GENERATED")
- * within the first ~300 characters — catches non-git projects.
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-
-const HEADER_SCAN_BYTES = 300;
-const HEADER_MARKERS = [
- /@generated\b/i,
- /\bGENERATED\s+FILE\b/,
- /\bAUTO-?GENERATED\b/i,
- /\bDO\s+NOT\s+EDIT\b/i,
-];
-
-/**
- * @param {string} filePath - absolute or cwd-relative path
- * @param {object} [options]
- * @param {string} [options.cwd] - project root (defaults to process.cwd())
- */
-export function isGeneratedFile(filePath, options = {}) {
- const cwd = options.cwd || process.cwd();
- const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
-
- if (isGitIgnored(absPath, cwd)) return true;
- if (hasGeneratedHeader(absPath)) return true;
- return false;
-}
-
-function isGitIgnored(absPath, cwd) {
- try {
- execSync(`git check-ignore --quiet ${JSON.stringify(absPath)}`, {
- cwd,
- stdio: 'ignore',
- });
- return true; // exit 0 = ignored
- } catch (err) {
- // Exit code 1 = not ignored. Exit code 128 = not a git repo or other error.
- // In both cases, treat as "not known to be ignored."
- return false;
- }
-}
-
-function hasGeneratedHeader(absPath) {
- let fd;
- try {
- fd = fs.openSync(absPath, 'r');
- const buf = Buffer.alloc(HEADER_SCAN_BYTES);
- const bytesRead = fs.readSync(fd, buf, 0, HEADER_SCAN_BYTES, 0);
- const head = buf.slice(0, bytesRead).toString('utf-8');
- return HEADER_MARKERS.some((re) => re.test(head));
- } catch {
- return false;
- } finally {
- if (fd !== undefined) { try { fs.closeSync(fd); } catch {} }
- }
-}
@@ -1,595 +0,0 @@
-/**
- * CLI helper: deterministic accept/discard of variant sessions.
- *
- * Usage:
- * node live-accept.mjs --id SESSION_ID --discard
- * node live-accept.mjs --id SESSION_ID --variant N
- *
- * For discard: removes the entire variant wrapper and restores the original.
- * For accept: replaces the wrapper with the chosen variant's content. If the
- * session had a colocated <style> block, it's preserved with carbonize markers
- * for a background agent to integrate into the project's CSS.
- *
- * Output: JSON to stdout.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-export async function acceptCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-accept.mjs [options]
-
-Deterministic accept/discard for live variant sessions.
-
-Modes:
- --discard Remove variants, restore original
- --variant N Accept variant N, discard the rest
-
-Required:
- --id SESSION_ID Session ID of the variant wrapper
-
-Output (JSON):
- { handled, file, carbonize }`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const variantNum = argVal(args, '--variant');
- const paramValuesRaw = argVal(args, '--param-values');
- const isDiscard = args.includes('--discard');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }
-
- let paramValues = null;
- if (paramValuesRaw) {
- try { paramValues = JSON.parse(paramValuesRaw); }
- catch { paramValues = null; } // malformed blob: skip the comment rather than failing the accept
- }
-
- // Find the file containing this session's markers
- const found = findSessionFile(id, process.cwd());
- if (!found) {
- console.log(JSON.stringify({ handled: false, error: 'Session markers not found for id: ' + id }));
- process.exit(0);
- }
-
- const { file: targetFile, content, lines } = found;
- const relFile = path.relative(process.cwd(), targetFile);
-
- // Bail if the session lives in a generated file. The agent manually wrote
- // the wrapper there for preview, and is responsible for writing the
- // accepted variant to true source (or cleaning up on discard). See
- // "Handle fallback" in live.md.
- if (isGeneratedFile(targetFile, { cwd: process.cwd() })) {
- console.log(JSON.stringify({
- handled: false,
- mode: 'fallback',
- file: relFile,
- hint: 'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.',
- }));
- process.exit(0);
- }
-
- if (isDiscard) {
- const result = handleDiscard(id, lines, targetFile);
- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));
- } else {
- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);
- // Single-line attention-grabber when cleanup is required. The full
- // five-step checklist lives in reference/live.md (loaded once per
- // session); repeating it per-event would waste tokens.
- if (result.carbonize) {
- result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + relFile + '. See reference/live.md "Required after accept".';
- }
- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));
- }
-}
-
-// ---------------------------------------------------------------------------
-// Discard
-// ---------------------------------------------------------------------------
-
-function handleDiscard(id, lines, targetFile) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const original = extractOriginal(lines, block);
- const isJsx = detectCommentSyntax(targetFile).open === '{/*';
- const replaceRange = expandReplaceRange(block, lines, isJsx);
-
- // Restore at the line we're actually replacing FROM, not the marker line.
- // For JSX wrappers the marker comments live INSIDE the outer `<div>`, so
- // `block.start` sits 2 spaces deeper than the original element. Using that
- // as the deindent base would push the restored content 2 spaces too far
- // right on every JSX/TSX session. `replaceRange.start` is the outer wrapper
- // line, which is at the original element's indent for both HTML and JSX.
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
- const restored = deindentContent(original, indent);
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...restored,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
- return {};
-}
-
-// ---------------------------------------------------------------------------
-// Accept
-// ---------------------------------------------------------------------------
-
-function handleAccept(id, variantNum, lines, targetFile, paramValues) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const commentSyntax = detectCommentSyntax(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- // Anchor indent on the line we're replacing FROM (the outer wrapper),
- // not on `block.start` — for JSX that's the marker comment 2 spaces
- // deeper than the original element. See handleDiscard for the full
- // rationale.
- const replaceRange = expandReplaceRange(block, lines, isJsx);
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
-
- // Extract the chosen variant's inner content
- const variantContent = extractVariant(lines, block, variantNum);
- if (!variantContent) return { handled: false, error: 'Variant ' + variantNum + ' not found' };
-
- // Extract CSS block if present
- const cssContent = extractCss(lines, block, id);
-
- // Check if carbonizing is needed:
- // - CSS block exists, OR
- // - variant HTML contains helper classes/attributes that need cleanup
- const variantText = variantContent.join('\n');
- const hasHelperAttrs = variantText.includes('data-impeccable-variant');
- const needsCarbonize = !!(cssContent || hasHelperAttrs);
-
- // Build the replacement
- const restored = deindentContent(variantContent, indent);
- const replacement = [];
-
- if (cssContent) {
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
- // JSX targets need the CSS body wrapped in a template literal so that the
- // `{` and `}` in CSS rules don't get parsed as JSX expressions.
- replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
- // Re-indent CSS content to match
- for (const cssLine of cssContent) {
- replacement.push(indent + cssLine.trimStart());
- }
- replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
- if (paramValues && Object.keys(paramValues).length > 0) {
- // Preserve the user's knob positions for the carbonize-cleanup agent
- // to bake into the final CSS when it collapses scoped rules.
- replacement.push(indent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close);
- }
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close);
- }
-
- // Keep the `@scope ([data-impeccable-variant="N"])` selectors in the
- // carbonize CSS block working visually by re-wrapping the accepted content
- // in a data-impeccable-variant="N" div with `display: contents` (so layout
- // isn't affected). The carbonize agent strips this attribute + wrapper when
- // it moves the CSS to a proper stylesheet.
- //
- // Style attribute syntax has to follow the host file's flavor — JSX files
- // need the object form, otherwise React 19 throws "Failed to set indexed
- // property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
- if (cssContent) {
- const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
- replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
- replacement.push(...restored);
- replacement.push(indent + '</div>');
- } else {
- replacement.push(...restored);
- }
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...replacement,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- return { carbonize: needsCarbonize };
-}
-
-// ---------------------------------------------------------------------------
-// Parsing helpers
-// ---------------------------------------------------------------------------
-
-/**
- * Find the start/end marker lines for a session.
- * Returns { start, end } (0-indexed line numbers) or null.
- */
-function findMarkerBlock(id, lines) {
- let start = -1;
- let end = -1;
- const startPattern = 'impeccable-variants-start ' + id;
- const endPattern = 'impeccable-variants-end ' + id;
-
- for (let i = 0; i < lines.length; i++) {
- if (start === -1 && lines[i].includes(startPattern)) start = i;
- if (lines[i].includes(endPattern)) { end = i; break; }
- }
-
- return (start !== -1 && end !== -1) ? { start, end } : null;
-}
-
-/**
- * Compute the line range to REPLACE (vs. just the marker range to extract
- * from). For JSX/TSX wrappers, live-wrap places the marker comments INSIDE
- * the `<div data-impeccable-variants="ID">` outer wrapper so the picked
- * element's JSX slot keeps a single child — a Fragment `<></>` would have
- * solved the multi-sibling case but failed inside `asChild` / cloneElement
- * parents with "Invalid prop supplied to React.Fragment".
- *
- * That means the marker block is enclosed by the wrapper `<div>` opener
- * (with `data-impeccable-variants="ID"`) and its matching `</div>`. We
- * walk back to the opener and forward to the closer so accept/discard
- * remove the entire scaffold, not just the inner markers.
- *
- * Marker lines themselves stay where they were so extractOriginal /
- * extractVariant / extractCss continue to walk the same range.
- */
-function expandReplaceRange(block, lines, isJsx) {
- if (!isJsx) return { start: block.start, end: block.end };
-
- let { start, end } = block;
-
- // Walk back for the wrapper `<div data-impeccable-variants="..."` opener.
- // The attr may sit on a continuation line of a multi-line opening tag, so
- // also walk to the line that actually contains `<div`.
- for (let i = start - 1; i >= Math.max(0, start - 12); i--) {
- if (/data-impeccable-variants=/.test(lines[i])) {
- let opener = i;
- while (opener > 0 && !/<div\b/.test(lines[opener])) opener--;
- start = opener;
- break;
- }
- }
-
- // Walk forward to the matching `</div>` by div-depth tracking from the
- // wrapper opener. Operate on JOINED text instead of per-line: a
- // multi-line self-closing JSX `<div\n className="spacer"\n/>` would
- // fool per-line regex tracking (the `<div` line matches openRe but the
- // `/>` line never matches selfCloseRe since it needs `<div` on the same
- // line). That left depth permanently over-counted and the wrapper's
- // outer `</div>` orphaned after accept/discard. Single regex with
- // `[^>]*?` (which spans newlines in JS) handles either form correctly.
- const joined = lines.slice(start).join('\n');
- // Match either `<div … />` (self-close, group 1 is `/`), `<div … >`
- // (open, group 1 is empty), or `</div>`.
- const tagRe = /<div\b[^>]*?(\/?)>|<\/div\s*>/g;
- let depth = 0;
- let m;
- while ((m = tagRe.exec(joined)) !== null) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && m[1] === '/';
- if (isClose) depth--;
- else if (!isSelfClose) depth++;
- if (depth <= 0) {
- // m.index is offset within `joined`; convert back to a file line.
- const linesBefore = joined.slice(0, m.index + m[0].length).split('\n').length - 1;
- const candidateEnd = start + linesBefore;
- if (candidateEnd >= end) {
- end = candidateEnd;
- break;
- }
- }
- }
-
- return { start, end };
-}
-
-/**
- * Join wrapper lines into a single string with `<style>` elements removed so
- * marker matching and div-depth tracking aren't confused by:
- * - CSS `@scope ([data-impeccable-variant="N"])` strings that look like the
- * HTML marker we're searching for
- * - JSX self-closing `<style ... />` (no separate `</style>` to close on)
- * - Same-line `<style>…</style>` blocks
- * - Multi-line `<style>\n…\n</style>` blocks
- */
-function stripStyleAndJoin(lines, block) {
- const out = [];
- let inStyle = false;
- for (let i = block.start; i <= block.end; i++) {
- let line = lines[i];
-
- if (!inStyle) {
- // Strip any complete <style> elements on this line (self-closed or
- // same-line-closed), including their body content.
- line = line
- .replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/g, '')
- .replace(/<style\b[^>]*\/\s*>/g, '');
-
- // If a <style> opener remains (multi-line body starts here), strip from
- // the opener to end-of-line and flip into skip mode.
- const openerIdx = line.search(/<style\b/);
- if (openerIdx !== -1) {
- line = line.slice(0, openerIdx);
- inStyle = true;
- }
- out.push(line);
- } else {
- // In multi-line style body; drop everything until we see </style>.
- const closeIdx = line.search(/<\/style\s*>/);
- if (closeIdx !== -1) {
- inStyle = false;
- out.push(line.slice(closeIdx).replace(/<\/style\s*>/, ''));
- }
- // else: skip line entirely
- }
- }
- return out.join('\n');
-}
-
-/**
- * Find the inner content of `<TAG ...attrMatch...>…</TAG>` inside `text`,
- * handling nested same-tag elements via depth counting. `attrMatch` is a
- * regex source fragment that must appear inside the opener tag.
- * Returns the inner string (may be empty), or null if not found.
- */
-function extractInnerByAttr(text, attrMatch) {
- const openerRe = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*' + attrMatch + '[^>]*>');
- const openMatch = text.match(openerRe);
- if (!openMatch) return null;
-
- const tagName = openMatch[1];
- const innerStart = openMatch.index + openMatch[0].length;
-
- // Match any opener or closer of this tag name after innerStart.
- // (Does not match self-closing <TAG … />, which doesn't contribute to depth.)
- const tagRe = new RegExp('<(?:/)?' + tagName + '\\b[^>]*>', 'g');
- tagRe.lastIndex = innerStart;
-
- let depth = 1;
- let m;
- while ((m = tagRe.exec(text))) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && /\/\s*>$/.test(m[0]);
- if (isClose) {
- depth--;
- if (depth === 0) return text.slice(innerStart, m.index);
- } else if (!isSelfClose) {
- depth++;
- }
- }
- return null;
-}
-
-/**
- * Extract the original element content from within the variant wrapper.
- * Returns an array of lines.
- */
-function extractOriginal(lines, block) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="original"');
- if (inner === null) return [];
- return inner.split('\n');
-}
-
-/**
- * Extract a specific variant's inner content (stripping the wrapper div).
- * Returns an array of lines, or null if not found.
- */
-function extractVariant(lines, block, variantNum) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + variantNum + '"');
- if (inner === null) return null;
- const result = inner.split('\n');
- // Collapse a lone empty leading/trailing line (common after string splice).
- while (result.length > 1 && result[0].trim() === '') result.shift();
- while (result.length > 1 && result[result.length - 1].trim() === '') result.pop();
- return result.length > 0 ? result : null;
-}
-
-/**
- * Extract the colocated <style> block content (between the style tags).
- * Returns an array of CSS lines, or null if no style block found.
- *
- * Handles three shapes of `<style data-impeccable-css="ID" ...>`:
- * 1. Self-closing: `<style ... />` — no body; return null (nothing to carbonize).
- * 2. Same-line open+close: `<style>...</style>` — return the inner content.
- * 3. Multi-line: `<style>` on one line, `</style>` on a later line — return
- * the lines between them.
- */
-function extractCss(lines, block, id) {
- const styleAttr = 'data-impeccable-css="' + id + '"';
- let inStyle = false;
- const content = [];
-
- for (let i = block.start; i <= block.end; i++) {
- const line = lines[i];
-
- if (!inStyle && line.includes(styleAttr)) {
- // Self-closing: nothing to carbonize.
- if (/<style\b[^>]*\/\s*>/.test(line)) return null;
- // Same-line open + close: extract inner text.
- const sameLine = line.match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/);
- if (sameLine) {
- const inner = stripJsxTemplateWrap(sameLine[1]);
- return inner.length > 0 ? inner.split('\n') : null;
- }
- inStyle = true;
- continue; // skip the <style> opening tag
- }
-
- if (inStyle) {
- // Detect </style> anywhere on the line — JSX template-literal closes
- // (`}</style>`) put the close mid-line, and we don't want to absorb the
- // template-literal punctuation as CSS content.
- const closeIdx = line.indexOf('</style>');
- if (closeIdx !== -1) break;
- content.push(line);
- }
- }
-
- if (content.length === 0) return null;
- return stripJsxTemplateLines(content);
-}
-
-/**
- * Strip a JSX template-literal wrap (`{` … `}`) from CSS extracted out of a
- * `<style>` element in a JSX/TSX file. The agent may write the wrap with
- * `{` and `}` directly attached to the `<style>` tags, on their own lines,
- * or attached to the first/last CSS lines — all three are JSX-legal.
- *
- * Stripping is required because handleAccept re-wraps the CSS itself when
- * carbonizing. Without this, two consecutive accepts (or a previously-
- * accepted variants block being carbonized) would produce nested
- * `{` `{` … `}` `}`, which oxc rejects with "Expected `}` but found `@`".
- */
-function stripJsxTemplateLines(content) {
- const out = content.slice();
-
- // Drop any leading blank lines so we don't miss a `{` line buried below
- // them; same for trailing.
- while (out.length > 0 && out[0].trim() === '') out.shift();
- while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
- if (out.length === 0) return null;
-
- // Leading `{`: own line, or attached to the first CSS line.
- const firstTrim = out[0].trimStart();
- if (firstTrim === '{`') {
- out.shift();
- } else if (firstTrim.startsWith('{`')) {
- const idx = out[0].indexOf('{`');
- out[0] = out[0].slice(0, idx) + out[0].slice(idx + 2);
- if (out[0].trim() === '') out.shift();
- }
- if (out.length === 0) return null;
-
- // Trailing `` ` `` `}`: own line, or attached to the last CSS line.
- const lastIdx = out.length - 1;
- const lastTrim = out[lastIdx].trimEnd();
- if (lastTrim === '`}') {
- out.pop();
- } else if (lastTrim.endsWith('`}')) {
- const text = out[lastIdx];
- const idx = text.lastIndexOf('`}');
- out[lastIdx] = text.slice(0, idx) + text.slice(idx + 2);
- if (out[lastIdx].trim() === '') out.pop();
- }
-
- return out.length > 0 ? out : null;
-}
-
-function stripJsxTemplateWrap(text) {
- const lines = text.split('\n');
- const stripped = stripJsxTemplateLines(lines);
- return stripped ? stripped.join('\n') : '';
-}
-
-/**
- * De-indent content that was indented by live-wrap.mjs.
- * The wrap script adds `indent + ' '` (4 extra spaces) to each line.
- * We restore to just `indent` level.
- */
-function deindentContent(contentLines, baseIndent) {
- // Find the minimum indentation in the content to determine how much was added
- let minIndent = Infinity;
- for (const line of contentLines) {
- if (line.trim() === '') continue;
- const leadingSpaces = line.match(/^(\s*)/)[1].length;
- minIndent = Math.min(minIndent, leadingSpaces);
- }
- if (minIndent === Infinity) minIndent = 0;
-
- // Strip the extra indentation and re-add base indent
- return contentLines.map(line => {
- if (line.trim() === '') return '';
- return baseIndent + line.slice(minIndent);
- });
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- return { open: '<!--', close: '-->' };
-}
-
-// ---------------------------------------------------------------------------
-// File search (find the file containing session markers)
-// ---------------------------------------------------------------------------
-
-function findSessionFile(id, cwd) {
- const marker = 'impeccable-variants-start ' + id;
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, marker, seen, 0);
- if (result) {
- const content = fs.readFileSync(result, 'utf-8');
- return { file: result, content, lines: content.split('\n') };
- }
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth) {
- if (depth > 5) return null;
- let realDir;
- try { realDir = fs.realpathSync(dir); } catch { return null; }
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- if (!EXTENSIONS.includes(path.extname(entry.name).toLowerCase())) continue;
- const filePath = path.join(dir, entry.name);
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip */ }
- }
-
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
- if (result) return result;
- }
-
- return null;
-}
-
-// ---------------------------------------------------------------------------
-// Utilities
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-accept.mjs') || _running?.endsWith('live-accept.mjs/')) {
- acceptCli();
-}
-
-export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax };
@@ -1,123 +0,0 @@
-/**
- * Browser-side durable session helpers for Impeccable live mode.
- *
- * Kept separate from live-browser.js so recovery state can be tested without
- * booting the full overlay UI. Served before live-browser.js and attached to
- * window.__IMPECCABLE_LIVE_SESSION__.
- */
-(function (root) {
- 'use strict';
-
- function createLiveBrowserSessionState({ prefix, storage, idFactory }) {
- if (!prefix) throw new Error('prefix required');
- const store = storage || root.localStorage;
- const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };
- const sessionKey = prefix + '-session';
- const handledKey = sessionKey + '-handled';
- const scrollKey = sessionKey + '-scroll';
- let checkpointRevision = 0;
- const owner = makeId();
-
- function safeRead(key) {
- try { return store.getItem(key); } catch { return null; }
- }
-
- function safeWrite(key, value) {
- try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }
- }
-
- function safeRemove(key) {
- try { store.removeItem(key); } catch { /* unavailable storage */ }
- }
-
- function loadSession() {
- try {
- const raw = safeRead(sessionKey);
- if (!raw) return null;
- const parsed = JSON.parse(raw);
- if (Number.isInteger(parsed.checkpointRevision)) {
- checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);
- }
- return parsed;
- } catch { return null; }
- }
-
- function saveSession(session) {
- if (!session || !session.id) return;
- const payload = {
- ...session,
- checkpointRevision,
- };
- safeWrite(sessionKey, JSON.stringify(payload));
- }
-
- function clearSession() {
- safeRemove(sessionKey);
- }
-
- function nextCheckpointRevision() {
- checkpointRevision += 1;
- const existing = loadSession();
- if (existing?.id) saveSession(existing);
- return checkpointRevision;
- }
-
- function seedCheckpointRevision(value) {
- if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);
- return checkpointRevision;
- }
-
- function currentCheckpointRevision() {
- return checkpointRevision;
- }
-
- function markHandled(id) {
- if (!id) return;
- safeWrite(handledKey, id);
- }
-
- function isHandled(id) {
- return !!id && safeRead(handledKey) === id;
- }
-
- function clearHandled() {
- safeRemove(handledKey);
- }
-
- function writeScrollY(y) {
- safeWrite(scrollKey, String(y));
- }
-
- function readScrollY() {
- const raw = safeRead(scrollKey);
- if (raw == null) return null;
- const n = parseFloat(raw);
- return isFinite(n) ? n : null;
- }
-
- function clearScrollY() {
- safeRemove(scrollKey);
- }
-
- return {
- owner,
- sessionKey,
- handledKey,
- scrollKey,
- saveSession,
- loadSession,
- clearSession,
- nextCheckpointRevision,
- seedCheckpointRevision,
- currentCheckpointRevision,
- markHandled,
- isHandled,
- clearHandled,
- writeScrollY,
- readScrollY,
- clearScrollY,
- };
- }
-
- root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };
-})(typeof window !== 'undefined' ? window : globalThis);
@@ -1,4860 +0,0 @@
-/**
- * Impeccable Live Variant Mode — Browser Script
- *
- * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
- * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
- * before this code.
- *
- * UI: a single floating bar that morphs between three states —
- * configure (pick action + go), generating (progressive dots), and cycling
- * (prev/next + accept/discard). Feels like Spotlight, not a modal.
- */
-(function () {
- 'use strict';
- if (typeof window === 'undefined') return;
-
- // Guard against double-init. Bun's HTML loader may process the <script> tag
- // and create a bundled copy alongside the external load, or HMR may re-execute.
- // Check BEFORE reading token/port to catch all cases.
- if (window.__IMPECCABLE_LIVE_INIT__) return;
- window.__IMPECCABLE_LIVE_INIT__ = true;
-
- const TOKEN = window.__IMPECCABLE_TOKEN__;
- const PORT = window.__IMPECCABLE_PORT__;
- if (!TOKEN || !PORT) {
- window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
- return;
- }
-
- // ---------------------------------------------------------------------------
- // Design tokens
- // ---------------------------------------------------------------------------
-
- // Brand magenta is pinned to the site token (--color-accent in main.css)
- // so Accept / knobs / cycle-dots match the site's accent, not a washed
- // theme-adjusted one.
- const C = {
- brand: 'oklch(60% 0.25 350)',
- brandHov: 'oklch(52% 0.25 350)',
- brandSoft: 'oklch(60% 0.25 350 / 0.15)',
- ink: 'oklch(15% 0.01 350)',
- ash: 'oklch(55% 0 0)',
- paper: 'oklch(98% 0.005 350 / 0.92)',
- paperSolid:'oklch(98% 0.005 350)',
- mist: 'oklch(90% 0.01 350 / 0.6)',
- white: 'oklch(99% 0 0)',
- };
- const FONT = 'system-ui, -apple-system, sans-serif';
- const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
- // z-index: detect overlays use 99999, so our UI must be above them
- const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };
- const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
- const PREFIX = 'impeccable-live';
- const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
- prefix: PREFIX,
- storage: localStorage,
- idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),
- });
- if (!sessionState) {
- console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');
- window.__IMPECCABLE_LIVE_INIT__ = false;
- return;
- }
- const HIGHLIGHT_TRANSITION =
- 'top 140ms ' + EASE +
- ', left 140ms ' + EASE +
- ', width 140ms ' + EASE +
- ', height 140ms ' + EASE +
- ', opacity 150ms ease';
- const TOOLTIP_TRANSITION =
- 'top 140ms ' + EASE + ', left 140ms ' + EASE + ', opacity 150ms ease';
-
- const SKIP_TAGS = new Set([
- 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
- ]);
-
- // SVG icons stack above each chip label. All strokes use currentColor so the
- // icon recolors to C.brand when its chip is selected. 20x20 render, 24-viewBox,
- // 1.5 stroke — visually consistent with the Foundation grid on the homepage.
- const ICON_ATTRS = 'width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block"';
- const ICONS = {
- impeccable: `<svg ${ICON_ATTRS}><path d="M4 20l4-1L18 9l-3-3L5 16z"/><path d="M14 7l3 3"/></svg>`,
- bolder: `<svg ${ICON_ATTRS}><rect x="6" y="12" width="4" height="7" rx="0.5"/><rect x="14" y="5" width="4" height="14" rx="0.5"/></svg>`,
- quieter: `<svg ${ICON_ATTRS}><rect x="6" y="5" width="4" height="14" rx="0.5"/><rect x="14" y="12" width="4" height="7" rx="0.5"/></svg>`,
- distill: `<svg ${ICON_ATTRS}><path d="M4 5h16l-6 8v7l-4-2v-5z"/></svg>`,
- polish: `<svg ${ICON_ATTRS}><path d="M15 3l1 3 3 1-3 1-1 3-1-3-3-1 3-1z"/><path d="M7 13l0.6 1.8 1.8 0.6-1.8 0.6-0.6 1.8-0.6-1.8-1.8-0.6 1.8-0.6z"/></svg>`,
- typeset: `<svg ${ICON_ATTRS}><path d="M5 6h14" stroke-width="2.6"/><path d="M5 12h9" stroke-width="1.9"/><path d="M5 18h5" stroke-width="1.3"/></svg>`,
- colorize: `<svg ${ICON_ATTRS}><circle cx="9" cy="10" r="5"/><circle cx="15" cy="10" r="5"/><circle cx="12" cy="15" r="5"/></svg>`,
- layout: `<svg ${ICON_ATTRS}><rect x="3" y="4" width="8" height="16" rx="0.5"/><rect x="13" y="4" width="8" height="7" rx="0.5"/><rect x="13" y="13" width="8" height="7" rx="0.5"/></svg>`,
- adapt: `<svg ${ICON_ATTRS}><rect x="2.5" y="5" width="12" height="11" rx="1"/><line x1="2.5" y1="19" x2="14.5" y2="19"/><rect x="16.5" y="8" width="5" height="11" rx="1"/></svg>`,
- animate: `<svg ${ICON_ATTRS}><path d="M3 18c4-4 6-10 10-10"/><path d="M13 8c3 0 5 5 8 10"/><circle cx="13" cy="8" r="1.6" fill="currentColor" stroke="none"/></svg>`,
- delight: `<svg ${ICON_ATTRS}><path d="M12 3l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>`,
- overdrive: `<svg ${ICON_ATTRS}><path d="M13 3L5 13h5l-1 8 9-12h-6z"/></svg>`,
- };
-
- const ACTIONS = [
- { value: 'impeccable', label: 'Freeform' },
- { value: 'bolder', label: 'Bolder' },
- { value: 'quieter', label: 'Quieter' },
- { value: 'distill', label: 'Distill' },
- { value: 'polish', label: 'Polish' },
- { value: 'typeset', label: 'Typeset' },
- { value: 'colorize', label: 'Colorize' },
- { value: 'layout', label: 'Layout' },
- { value: 'adapt', label: 'Adapt' },
- { value: 'animate', label: 'Animate' },
- { value: 'delight', label: 'Delight' },
- { value: 'overdrive', label: 'Overdrive' },
- ];
-
- // ---------------------------------------------------------------------------
- // State
- // ---------------------------------------------------------------------------
-
- let state = 'IDLE';
- let hoveredElement = null;
- let selectedElement = null;
- let currentSessionId = null;
- let expectedVariants = 0;
- let arrivedVariants = 0;
- let visibleVariant = 0;
- let variantObserver = null;
- let hasProjectContext = false;
- let selectedAction = 'impeccable';
- let selectedCount = 3;
- const browserOwner = sessionState.owner;
- let checkpointTimer = null;
-
- // Scroll lock — holds window.scrollY at a fixed value while the session is
- // active, so HMR DOM patches and variant swaps can't drift the page. See
- // startScrollLock / stopScrollLock below.
- let scrollLockObserver = null;
- let scrollLockTargetY = null;
- let scrollLockRaf = null;
- let scrollLockAbort = null;
-
- // Dedicated key for scroll position — SEPARATE from LS_KEY so that
- // saveSession's state updates don't clobber a carefully-captured scrollY.
- // (Previously: saveSession wrote scrollY alongside state, so every call
- // during resume overwrote the pre-reload value with whatever the browser
- // had landed on, typically 0.)
- function writeScrollY(y) { sessionState.writeScrollY(y); }
- function readScrollY() { return sessionState.readScrollY(); }
- function clearScrollY() { sessionState.clearScrollY(); }
-
- // Pre-empt the browser: apply manual scroll restoration and jump to the
- // saved scrollY at script-parse time. Retries on fonts.ready and load
- // are essential: scrollTo(y) clamps to the current document.scrollHeight,
- // which is often hundreds of pixels short of the final value until
- // async-loaded fonts swap in and reflow.
- try {
- history.scrollRestoration = 'manual';
- const savedY = readScrollY();
- if (savedY != null) {
- const apply = () => {
- if (Math.abs(window.scrollY - savedY) > 0.5) {
- console.log('[impeccable.scroll] early restore', { from: window.scrollY, to: savedY });
- window.scrollTo(0, savedY);
- }
- };
- apply();
- if (document.fonts?.ready) document.fonts.ready.then(apply).catch(() => {});
- window.addEventListener('load', apply, { once: true });
- }
- } catch {}
-
- // UI refs
- let highlightEl = null;
- let tooltipEl = null;
- let barEl = null;
- let pickerEl = null;
- let toastEl = null;
- let scrollRaf = null;
-
- // ---------------------------------------------------------------------------
- // Helpers
- // ---------------------------------------------------------------------------
-
- function own(el) {
- return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
- }
-
- function pickable(el) {
- if (!el || el.nodeType !== 1) return false;
- if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
- if (own(el)) return false;
- const r = el.getBoundingClientRect();
- return r.width >= 20 && r.height >= 20;
- }
-
- function desc(el) {
- if (!el) return '';
- let s = el.tagName.toLowerCase();
- if (el.id) s += '#' + el.id;
- else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
- return s;
- }
-
- function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
-
- // Modal-aware chrome: keep our floating UI clickable inside Radix /
- // Headless UI / vaul portals.
- //
- // Two host-page behaviors break us when the picked element lives inside a
- // modal dialog:
- //
- // 1. Modal scroll-lock disables outside pointer events. Radix's
- // `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
- // while a modal is open and only restores `auto` on the layer. Our
- // chrome inherits `none` from <body> and becomes unclickable.
- // 2. The dialog's outside-interaction handler (Radix's
- // `usePointerDownOutside`) listens at document level and dismisses
- // the dialog whenever a `pointerdown` lands outside the layer node.
- // Our chrome is a sibling of <body>, so Radix classifies our clicks
- // as outside and tears the dialog down mid-task.
- //
- // We can't reliably re-parent our chrome into the dialog subtree (z-index
- // stacking, scroll containers, theming all become host-page concerns), so
- // we defang both behaviors at our root:
- //
- // - `pointer-events: auto !important` overrides the inherited `none`.
- // - Stop `pointerdown` / `mousedown` propagation so the document-level
- // dismiss listener never fires for our clicks.
- // - Stop `focusin` propagation so any focus shifts inside our chrome
- // don't read as "focus moved outside the dialog" to focus traps.
- //
- // Click events still bubble normally — only the early pointer/focus
- // signals that drive outside-interaction detection are silenced.
- function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
- if (!rootEl) return;
- if (setPointerEvents) {
- rootEl.style.setProperty('pointer-events', 'auto', 'important');
- }
- const stop = (e) => e.stopPropagation();
- rootEl.addEventListener('pointerdown', stop);
- rootEl.addEventListener('mousedown', stop);
- rootEl.addEventListener('focusin', stop);
- }
-
- // ---------------------------------------------------------------------------
- // Highlight overlay
- // ---------------------------------------------------------------------------
-
- function initHighlight() {
- highlightEl = document.createElement('div');
- highlightEl.id = PREFIX + '-highlight';
- Object.assign(highlightEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- border: '2px solid ' + C.brand, borderRadius: '3px',
- pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
- transition: HIGHLIGHT_TRANSITION,
- display: 'none', opacity: '0',
- });
- document.body.appendChild(highlightEl);
-
- tooltipEl = document.createElement('div');
- tooltipEl.id = PREFIX + '-tooltip';
- Object.assign(tooltipEl.style, {
- position: 'fixed',
- background: C.ink, color: C.white,
- fontFamily: MONO, fontSize: '10px', fontWeight: '500',
- padding: '2px 6px', borderRadius: '3px',
- zIndex: Z.highlight + 1, pointerEvents: 'none',
- whiteSpace: 'nowrap', display: 'none',
- letterSpacing: '0.02em',
- transition: TOOLTIP_TRANSITION,
- });
- document.body.appendChild(tooltipEl);
- }
-
- function showHighlight(el) {
- if (!el || !highlightEl) return;
- const r = el.getBoundingClientRect();
- const top = (r.top - 2) + 'px', left = (r.left - 2) + 'px';
- const width = (r.width + 4) + 'px', height = (r.height + 4) + 'px';
- const tipTop = r.top - 20;
- const tipY = (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px';
- const tipX = Math.max(4, r.left) + 'px';
- tooltipEl.textContent = desc(el);
-
- const hiWasHidden = highlightEl.style.display === 'none' || highlightEl.style.opacity === '0';
- if (hiWasHidden) {
- // Snap to first target without animating from (0,0), then fade in.
- highlightEl.style.transition = 'none';
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block' });
- tooltipEl.style.transition = 'none';
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block' });
- void highlightEl.offsetWidth;
- highlightEl.style.transition = HIGHLIGHT_TRANSITION;
- highlightEl.style.opacity = '1';
- tooltipEl.style.transition = TOOLTIP_TRANSITION;
- tooltipEl.style.opacity = '1';
- } else {
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block', opacity: '1' });
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block', opacity: '1' });
- }
- }
-
- function hideHighlight() {
- if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
- if (tooltipEl) { tooltipEl.style.opacity = '0'; tooltipEl.style.display = 'none'; }
- }
-
- // ---------------------------------------------------------------------------
- // Annotation overlay (comment pins + magenta strokes)
- //
- // Active while state === 'CONFIGURING'. The overlay is a fixed-positioned
- // sibling of <body> mirroring selectedElement's bounding rect. Click (no
- // drag) drops a comment pin; drag paints a magenta SVG stroke. All coords
- // are stored in element-local CSS px so they survive scroll / resize and
- // correlate directly with the captured PNG.
- // ---------------------------------------------------------------------------
-
- const DRAG_THRESHOLD = 5; // px — below this, treat pointerup as a click
- const PIN_DBL_CLICK_MS = 300; // two clicks on the same pin within this delete it
- let annotOverlayEl = null;
- let annotSvgEl = null;
- let annotPinsEl = null;
- let annotClearChipEl = null;
- let annotState = { comments: [], strokes: [] };
- let annotActive = false;
- // `annotPointer` is either:
- // { kind: 'new', x0, y0, moved, strokeEl, strokePoints } creating a stroke/pin
- // { kind: 'pin', idx, startPointer, startPin, moved } dragging an existing pin
- let annotPointer = null;
- let annotEditing = null; // { idx, input, wrapEl }
- let annotLastPinClick = { idx: -1, time: 0 }; // for click-click-to-delete
-
- function initAnnotOverlay() {
- annotOverlayEl = document.createElement('div');
- annotOverlayEl.id = PREFIX + '-annot';
- Object.assign(annotOverlayEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- pointerEvents: 'auto', zIndex: Z.highlight + 2,
- display: 'none', overflow: 'visible',
- cursor: 'crosshair', touchAction: 'none',
- });
-
- annotSvgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- annotSvgEl.id = PREFIX + '-annot-svg';
- Object.assign(annotSvgEl.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%',
- // The SVG itself doesn't absorb clicks; individual hit-paths opt-in via
- // pointer-events=stroke so gaps still fall through to the overlay.
- pointerEvents: 'none', overflow: 'visible',
- });
- annotOverlayEl.appendChild(annotSvgEl);
-
- annotPinsEl = document.createElement('div');
- annotPinsEl.id = PREFIX + '-annot-pins';
- Object.assign(annotPinsEl.style, {
- position: 'absolute', inset: '0',
- pointerEvents: 'none',
- });
- annotOverlayEl.appendChild(annotPinsEl);
-
- annotClearChipEl = document.createElement('div');
- annotClearChipEl.id = PREFIX + '-annot-clear';
- annotClearChipEl.dataset.annotClear = 'true';
- annotClearChipEl.textContent = 'Clear';
- Object.assign(annotClearChipEl.style, {
- position: 'absolute', top: '8px', right: '8px',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '10px', fontWeight: '500',
- letterSpacing: '0.08em', textTransform: 'uppercase',
- padding: '5px 12px', borderRadius: '999px',
- cursor: 'pointer', pointerEvents: 'auto',
- display: 'none', userSelect: 'none',
- boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
- });
- annotOverlayEl.appendChild(annotClearChipEl);
-
- annotOverlayEl.addEventListener('pointerdown', onAnnotDown);
- annotOverlayEl.addEventListener('pointermove', onAnnotMove);
- annotOverlayEl.addEventListener('pointerup', onAnnotUp);
- annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
- document.body.appendChild(annotOverlayEl);
- // Modal-host friendliness: pointer-events is already 'auto' on this
- // overlay; we only need to silence the host's outside-interaction
- // listeners. Don't override pointer-events here (the overlay toggles
- // visibility via display:none, which is fine).
- defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
- }
-
- function updateClearChip() {
- if (!annotClearChipEl) return;
- const hasAny = annotState.comments.length > 0 || annotState.strokes.length > 0;
- annotClearChipEl.style.display = hasAny ? 'block' : 'none';
- }
-
- function showAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- annotActive = true;
- positionAnnotOverlay(el);
- annotOverlayEl.style.display = 'block';
- }
-
- function hideAnnotOverlay() {
- annotActive = false;
- if (annotOverlayEl) annotOverlayEl.style.display = 'none';
- // Drop any in-progress edit without touching annotState — clearAnnotations
- // (if the caller is exiting configure mode) handles state reset.
- annotEditing = null;
- }
-
- function positionAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- const r = el.getBoundingClientRect();
- Object.assign(annotOverlayEl.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- annotSvgEl.setAttribute('viewBox', '0 0 ' + r.width + ' ' + r.height);
- }
-
- function clearAnnotations() {
- annotState.comments = [];
- annotState.strokes = [];
- if (annotSvgEl) while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- if (annotPinsEl) annotPinsEl.innerHTML = '';
- annotPointer = null;
- annotEditing = null;
- annotLastPinClick = { idx: -1, time: 0 };
- updateClearChip();
- }
-
- // Rebuild the SVG layer. Each stroke gets a wider invisible hit path
- // beneath the visible magenta path so clicks register on thin lines.
- function redrawStrokes() {
- while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- annotState.strokes.forEach((s, idx) => {
- const d = pointsToPath(s.points);
- const hit = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- hit.setAttribute('d', d);
- hit.setAttribute('stroke', 'transparent');
- hit.setAttribute('stroke-width', '16');
- hit.setAttribute('stroke-linecap', 'round');
- hit.setAttribute('stroke-linejoin', 'round');
- hit.setAttribute('fill', 'none');
- hit.setAttribute('pointer-events', 'stroke');
- hit.style.cursor = 'pointer';
- hit.dataset.annotStroke = String(idx);
- annotSvgEl.appendChild(hit);
- const visible = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- visible.setAttribute('d', d);
- visible.setAttribute('stroke', C.brand);
- visible.setAttribute('stroke-width', '3');
- visible.setAttribute('stroke-linecap', 'round');
- visible.setAttribute('stroke-linejoin', 'round');
- visible.setAttribute('fill', 'none');
- visible.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(visible);
- });
- updateClearChip();
- }
-
- function localCoords(e) {
- const rect = annotOverlayEl.getBoundingClientRect();
- return { x: e.clientX - rect.left, y: e.clientY - rect.top };
- }
-
- function onAnnotDown(e) {
- if (!annotActive) return;
-
- // 1) Clear chip → wipe all annotations
- if (e.target.closest?.('[data-annot-clear]')) {
- if (annotEditing) annotEditing = null;
- clearAnnotations();
- renderAllPins();
- redrawStrokes();
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 2) Stroke hit path → delete that stroke
- const strokeHit = e.target.closest?.('[data-annot-stroke]');
- if (strokeHit) {
- const idx = parseInt(strokeHit.dataset.annotStroke, 10);
- if (Number.isInteger(idx)) {
- annotState.strokes.splice(idx, 1);
- redrawStrokes();
- }
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 3) Pin → drag, edit, or delete-on-double-click
- const pinWrap = e.target.closest?.('[data-annot-pin]');
- if (pinWrap) {
- const idx = parseInt(pinWrap.dataset.annotPin, 10);
- if (!Number.isInteger(idx)) return;
- // Double-click (two pointerdowns on the same pin within window) → delete.
- const now = Date.now();
- if (annotLastPinClick.idx === idx && now - annotLastPinClick.time < PIN_DBL_CLICK_MS) {
- if (annotEditing && annotEditing.idx === idx) annotEditing = null;
- annotState.comments.splice(idx, 1);
- annotLastPinClick = { idx: -1, time: 0 };
- renderAllPins();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- annotLastPinClick = { idx, time: now };
- // If editing a different pin, commit that edit before starting here.
- if (annotEditing && annotEditing.idx !== idx) finalizeEditingPin();
- // If already editing THIS pin and the user clicked the dot, let the
- // input keep focus (don't start a drag — the click wasn't meant as one).
- if (annotEditing && annotEditing.idx === idx) return;
- const p = localCoords(e);
- const pin = annotState.comments[idx];
- annotPointer = {
- kind: 'pin', idx,
- startPointer: p,
- startPin: { x: pin.x, y: pin.y },
- moved: false,
- };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 4) Empty area → commit any open edit, then start new annotation
- if (annotEditing) {
- finalizeEditingPin();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- const p = localCoords(e);
- annotPointer = { kind: 'new', x0: p.x, y0: p.y, moved: false, strokeEl: null, strokePoints: null };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- }
-
- function onAnnotMove(e) {
- if (!annotActive || !annotPointer) return;
- const p = localCoords(e);
-
- if (annotPointer.kind === 'pin') {
- const dx = p.x - annotPointer.startPointer.x;
- const dy = p.y - annotPointer.startPointer.y;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- }
- const pin = annotState.comments[annotPointer.idx];
- if (!pin) { annotPointer = null; return; }
- pin.x = annotPointer.startPin.x + dx;
- pin.y = annotPointer.startPin.y + dy;
- renderAllPins();
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const dx = p.x - annotPointer.x0, dy = p.y - annotPointer.y0;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- const strokeEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- strokeEl.setAttribute('stroke', C.brand);
- strokeEl.setAttribute('stroke-width', '3');
- strokeEl.setAttribute('stroke-linecap', 'round');
- strokeEl.setAttribute('stroke-linejoin', 'round');
- strokeEl.setAttribute('fill', 'none');
- strokeEl.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(strokeEl);
- annotPointer.strokeEl = strokeEl;
- annotPointer.strokePoints = [[annotPointer.x0, annotPointer.y0]];
- }
- annotPointer.strokePoints.push([p.x, p.y]);
- annotPointer.strokeEl.setAttribute('d', pointsToPath(annotPointer.strokePoints));
- e.stopPropagation();
- }
-
- function onAnnotUp(e) {
- if (!annotActive || !annotPointer) return;
-
- if (annotPointer.kind === 'pin') {
- const wasDrag = annotPointer.moved;
- const idx = annotPointer.idx;
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- if (wasDrag) {
- // A drag is an intentional reposition; a follow-up click shouldn't be
- // interpreted as a double-click-to-delete.
- annotLastPinClick = { idx: -1, time: 0 };
- } else {
- beginEditPin(idx);
- }
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const wasDrag = annotPointer.moved;
- if (wasDrag) {
- annotState.strokes.push({ points: annotPointer.strokePoints });
- // Swap the temporary preview SVG path for the full render with hit paths.
- redrawStrokes();
- } else {
- const idx = annotState.comments.length;
- annotState.comments.push({ x: annotPointer.x0, y: annotPointer.y0, text: '' });
- renderAllPins();
- beginEditPin(idx);
- }
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- e.stopPropagation();
- }
-
- function pointsToPath(points) {
- if (!points || points.length === 0) return '';
- let d = 'M' + points[0][0].toFixed(1) + ' ' + points[0][1].toFixed(1);
- for (let i = 1; i < points.length; i++) {
- d += ' L' + points[i][0].toFixed(1) + ' ' + points[i][1].toFixed(1);
- }
- return d;
- }
-
- function renderAllPins() {
- annotPinsEl.innerHTML = '';
- annotState.comments.forEach((c, idx) => {
- annotPinsEl.appendChild(buildPinElement(c, idx));
- });
- updateClearChip();
- }
-
- function buildPinElement(comment, idx) {
- const interactive = idx >= 0;
- const wrap = document.createElement('div');
- if (interactive) wrap.dataset.annotPin = String(idx);
- Object.assign(wrap.style, {
- position: 'absolute',
- left: (comment.x - 7) + 'px', top: (comment.y - 7) + 'px',
- pointerEvents: interactive ? 'auto' : 'none',
- display: 'flex', alignItems: 'flex-start', gap: '6px',
- cursor: interactive ? 'grab' : 'default',
- touchAction: 'none',
- });
- const dot = document.createElement('div');
- Object.assign(dot.style, {
- width: '14px', height: '14px', borderRadius: '50%',
- background: C.brand, border: '2px solid ' + C.white,
- boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
- flexShrink: '0',
- });
- wrap.appendChild(dot);
-
- if (comment.text) {
- const bubble = document.createElement('div');
- bubble.textContent = comment.text;
- Object.assign(bubble.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- marginTop: '-2px', maxWidth: '220px',
- pointerEvents: 'none', whiteSpace: 'pre-wrap',
- wordBreak: 'break-word',
- });
- wrap.appendChild(bubble);
- }
- return wrap;
- }
-
- function beginEditPin(idx) {
- const wrapEl = annotPinsEl.querySelector('[data-annot-pin="' + idx + '"]');
- if (!wrapEl) return;
- // Strip any existing bubble (but keep the dot)
- wrapEl.querySelectorAll('div:not(:first-child)').forEach(n => n.remove());
- const input = document.createElement('input');
- input.type = 'text';
- input.placeholder = 'Note…';
- Object.assign(input.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- border: '1px solid ' + C.brand,
- outline: 'none', marginTop: '-2px',
- width: '220px', pointerEvents: 'auto',
- });
- const originalText = annotState.comments[idx].text || '';
- input.value = originalText;
- wrapEl.appendChild(input);
- annotEditing = { idx, input, wrapEl, originalText };
- input.addEventListener('keydown', onAnnotInputKey, true);
- input.addEventListener('blur', () => {
- // Fires on both focus-loss and programmatic blur; commit unless we
- // already handled it.
- if (annotEditing && annotEditing.input === input) finalizeEditingPin();
- });
- // Stop clicks/pointerdowns inside the input from bubbling to the overlay
- ['pointerdown', 'click'].forEach(ev => {
- input.addEventListener(ev, e => e.stopPropagation());
- });
- setTimeout(() => input.focus(), 0);
- }
-
- function onAnnotInputKey(e) {
- if (e.key === 'Enter') {
- e.preventDefault(); e.stopPropagation();
- finalizeEditingPin();
- } else if (e.key === 'Escape') {
- e.preventDefault(); e.stopPropagation();
- cancelEditingPin();
- } else {
- // Keep arrows / backspace from hitting global handlers
- e.stopPropagation();
- }
- }
-
- function finalizeEditingPin() {
- if (!annotEditing) return;
- const { idx, input } = annotEditing;
- const text = input.value.trim();
- annotEditing = null;
- if (text) annotState.comments[idx].text = text;
- else annotState.comments.splice(idx, 1);
- renderAllPins();
- }
-
- function cancelEditingPin() {
- if (!annotEditing) return;
- const { idx, originalText } = annotEditing;
- annotEditing = null;
- // If the pin had text before this edit, revert to it. If it was a
- // just-created empty pin, Escape removes it.
- if (originalText) {
- annotState.comments[idx].text = originalText;
- } else {
- annotState.comments.splice(idx, 1);
- }
- renderAllPins();
- }
-
- // Build a detached annotation subtree suitable for injection into the clone
- // modern-screenshot creates. Coordinates are element-local so this slots
- // straight into an element that's been made position:relative. Takes an
- // explicit snapshot so it works after annotState has been cleared.
- function buildAnnotationsForCapture(rect, snapshot) {
- const comments = snapshot ? snapshot.comments : annotState.comments;
- const strokes = snapshot ? snapshot.strokes : annotState.strokes;
- if (comments.length === 0 && strokes.length === 0) return null;
- const wrap = document.createElement('div');
- Object.assign(wrap.style, {
- position: 'absolute', top: '0', left: '0',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none', overflow: 'visible',
- });
- if (strokes.length > 0) {
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- svg.setAttribute('viewBox', '0 0 ' + rect.width + ' ' + rect.height);
- Object.assign(svg.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%', overflow: 'visible',
- });
- for (const s of strokes) {
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- path.setAttribute('stroke', C.brand);
- path.setAttribute('stroke-width', '3');
- path.setAttribute('stroke-linecap', 'round');
- path.setAttribute('stroke-linejoin', 'round');
- path.setAttribute('fill', 'none');
- path.setAttribute('d', pointsToPath(s.points));
- svg.appendChild(path);
- }
- wrap.appendChild(svg);
- }
- for (const c of comments) {
- // idx=-1 means non-interactive; pointerEvents stay off in the clone
- wrap.appendChild(buildPinElement(c, -1));
- }
- return wrap;
- }
-
- // ---------------------------------------------------------------------------
- // Element context extraction
- // ---------------------------------------------------------------------------
-
- function extractContext(el) {
- const cs = getComputedStyle(el);
- const r = el.getBoundingClientRect();
- const props = {};
- for (const sheet of document.styleSheets) {
- try {
- for (const rule of sheet.cssRules) {
- if (rule.style) for (let i = 0; i < rule.style.length; i++) {
- const p = rule.style[i];
- if (p.startsWith('--') && !props[p]) {
- const v = cs.getPropertyValue(p).trim();
- if (v) props[p] = v;
- }
- }
- }
- } catch { /* cross-origin */ }
- }
- return {
- tagName: el.tagName.toLowerCase(), id: el.id || null,
- classes: [...el.classList],
- textContent: (el.textContent || '').slice(0, 500),
- outerHTML: el.outerHTML.slice(0, 10000),
- computedStyles: {
- 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
- 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
- 'color': cs.color, 'background': cs.background,
- 'background-color': cs.backgroundColor,
- 'padding': cs.padding, 'margin': cs.margin,
- 'display': cs.display, 'position': cs.position,
- 'gap': cs.gap, 'border-radius': cs.borderRadius,
- 'box-shadow': cs.boxShadow,
- },
- cssCustomProperties: props,
- parentContext: el.parentElement
- ? '<' + el.parentElement.tagName.toLowerCase()
- + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
- + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
- + '>'
- : null,
- boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
- };
- }
-
- // ---------------------------------------------------------------------------
- // The Bar — one floating element, three modes
- // ---------------------------------------------------------------------------
-
- // Contextual-bar palette. Cached at init so every build*Row reads a
- // consistent set of colors; detectPageTheme runs once rather than on every
- // phase transition.
- let BP = null;
-
- // Bar shadow variants. The default projects down + subtle around. When
- // the Tune popover opens below the bar, a downward shadow lands on the
- // dark popover and reads as a bright ghost line. We swap to UP-only while
- // tune is open below so the popover's top edge is clean.
- const BAR_SHADOW_DEFAULT = '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_UP = '0 -4px 20px oklch(0% 0 0 / 0.08), 0 -1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_DOWN = BAR_SHADOW_DEFAULT;
-
- function initBar() {
- BP = barPaletteForTheme(detectPageTheme());
- barEl = document.createElement('div');
- barEl.id = PREFIX + '-bar';
- Object.assign(barEl.style, {
- position: 'fixed', zIndex: Z.bar,
- display: 'none', opacity: '0',
- transform: 'translateY(6px)',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- background: BP.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + BP.hairline,
- borderRadius: '10px',
- boxShadow: BAR_SHADOW_DEFAULT,
- transition: 'box-shadow 0.2s ease, opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- fontFamily: FONT, fontSize: '13px', color: BP.text,
- padding: '6px',
- maxWidth: '520px', minWidth: '320px',
- });
- document.body.appendChild(barEl);
- defangOutsideHandlers(barEl);
- }
-
- function positionBar() {
- if (!barEl || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- const barH = barEl.offsetHeight || 44;
- const barW = barEl.offsetWidth || 380;
- const GLOBAL_BAR_RESERVE = 64; // global bar height + bottom margin + breathing room
- const GAP = 8;
-
- // Prefer below the element; fall back to above; if neither fits (element
- // taller than viewport), pin to a stable viewport anchor so the bar
- // doesn't teleport between top and bottom as the user scrolls.
- let top;
- const belowTop = r.bottom + GAP;
- const aboveTop = r.top - barH - GAP;
- if (belowTop + barH + GAP <= window.innerHeight - GLOBAL_BAR_RESERVE) {
- top = belowTop;
- } else if (aboveTop >= GAP) {
- top = aboveTop;
- } else {
- top = window.innerHeight - barH - GLOBAL_BAR_RESERVE;
- }
-
- let left = r.left + (r.width - barW) / 2;
- if (left < GAP) left = GAP;
- if (left + barW > window.innerWidth - GAP) left = window.innerWidth - barW - GAP;
- Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
- }
-
- function showBar(mode) {
- barEl.innerHTML = '';
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- barEl.style.display = 'block';
- positionBar();
- requestAnimationFrame(() => {
- barEl.style.opacity = '1';
- barEl.style.transform = 'translateY(0)';
- });
- }
-
- function hideBar() {
- if (!barEl) return;
- barEl.style.opacity = '0';
- barEl.style.transform = 'translateY(6px)';
- setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
- hideActionPicker();
- closeTunePopover();
- }
-
- function updateBarContent(mode) {
- if (!barEl || barEl.style.display === 'none') return;
- barEl.innerHTML = '';
- // Reset bar styling to the theme-aware palette
- barEl.style.background = BP.surface;
- barEl.style.border = '1px solid ' + BP.hairline;
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- else if (mode === 'saving') barEl.appendChild(buildSavingRow());
- else if (mode === 'confirmed') {
- barEl.appendChild(buildConfirmedRow());
- barEl.style.background = 'oklch(95% 0.05 145)';
- barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
- }
- }
-
- // --- Configure row ---
-
- function buildConfigureRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
-
- // Action pill
- const pill = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '4px',
- padding: '5px 10px', borderRadius: '6px',
- background: BP.mark, color: BP.markText,
- fontFamily: FONT, fontSize: '12px', fontWeight: '500',
- border: 'none', cursor: 'pointer',
- transition: 'background 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap', flexShrink: '0',
- });
- pill.textContent = actionLabel() + ' \u25BE';
- pill.addEventListener('mouseenter', () => pill.style.background = BP.accent);
- pill.addEventListener('mouseleave', () => pill.style.background = BP.mark);
- pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
- pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
- pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
- row.appendChild(pill);
-
- // Freeform input. Focus state shows an accent-colored border only —
- // an earlier version tinted the background with `BP.accentSoft`, which
- // composited against the dark bar surface to a murky purple where the
- // browser's default placeholder gray was unreadable. Placeholder color
- // is set explicitly via a one-shot stylesheet keyed off this input's id
- // so it picks up the bar's `textDim` token in both themes.
- const input = document.createElement('input');
- input.id = PREFIX + '-input';
- input.type = 'text';
- input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
- Object.assign(input.style, {
- flex: '1', minWidth: '0',
- padding: '5px 8px', borderRadius: '6px',
- border: '1px solid transparent', background: 'transparent',
- fontFamily: FONT, fontSize: '12px', color: BP.text,
- outline: 'none',
- transition: 'border-color 0.15s ease',
- });
- if (!document.getElementById(PREFIX + '-input-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-input-style';
- s.textContent =
- '#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
- document.head.appendChild(s);
- }
- input.addEventListener('focus', () => {
- input.style.borderColor = BP.accent;
- });
- input.addEventListener('blur', () => {
- input.style.borderColor = 'transparent';
- });
- input.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
- if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; return; }
- // Let arrow keys pass through to the element picker when the input is empty
- if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && !input.value) return;
- e.stopPropagation();
- });
- row.appendChild(input);
-
- // Variant count toggle
- const count = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: MONO, fontSize: '11px', fontWeight: '600',
- color: BP.textDim, cursor: 'pointer',
- transition: 'color 0.12s ease, border-color 0.12s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- count.textContent = '\u00D7' + selectedCount;
- count.title = 'Variants: click to change';
- count.addEventListener('mouseenter', () => { count.style.color = BP.text; count.style.borderColor = BP.text; });
- count.addEventListener('mouseleave', () => { count.style.color = BP.textDim; count.style.borderColor = BP.hairline; });
- count.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
- count.textContent = '\u00D7' + selectedCount;
- });
- row.appendChild(count);
-
- // Go button
- const go = el('button', {
- padding: '5px 12px', borderRadius: '6px',
- border: 'none', background: BP.accent, color: BP.mark,
- fontFamily: FONT, fontSize: '12px', fontWeight: '600',
- cursor: 'pointer',
- transition: 'filter 0.12s ease, transform 0.1s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- go.textContent = 'Go \u2192';
- go.addEventListener('mouseenter', () => go.style.filter = 'brightness(1.1)');
- go.addEventListener('mouseleave', () => go.style.filter = 'none');
- go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
- go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
- go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
- row.appendChild(go);
-
- // Auto-focus input after a beat
- setTimeout(() => input.focus(), 60);
- return row;
- }
-
- // --- Generating row ---
-
- function buildGeneratingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 4px',
- });
-
- // Action label
- const label = el('span', {
- fontWeight: '600', fontSize: '12px', color: BP.text,
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- label.textContent = actionLabel();
- row.appendChild(label);
-
- // Dots
- row.appendChild(buildDots(false));
-
- // Status
- const status = el('span', {
- fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',
- marginLeft: 'auto',
- });
- // Variants currently arrive atomically in a single file edit, so a
- // per-variant counter would lie. Say what's true.
- status.textContent = arrivedVariants < expectedVariants
- ? 'Generating ' + expectedVariants + ' variants...'
- : 'Done';
- row.appendChild(status);
-
- return row;
- }
-
- // --- Cycling row ---
-
- const TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';
-
- function buildCyclingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '6px',
- padding: '1px 2px',
- });
-
- // Prev
- const prev = navBtn('\u2190');
- prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
- if (visibleVariant <= 1) prev.style.opacity = '0.3';
- row.appendChild(prev);
-
- // Dots (clickable)
- row.appendChild(buildDots(true));
-
- // Counter
- const counter = el('span', {
- fontFamily: MONO, fontSize: '11px', fontWeight: '500',
- color: BP.textDim, minWidth: '24px', textAlign: 'center',
- });
- counter.textContent = visibleVariant + '/' + arrivedVariants;
- row.appendChild(counter);
-
- // Next
- const next = navBtn('\u2192');
- next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
- if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
- row.appendChild(next);
-
- // Tune chip — only when the visible variant exposes params
- const visParams = parseVariantParams(getVisibleVariantEl());
- const hasParams = visParams.length > 0;
- if (hasParams) {
- const tune = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '6px',
- padding: '4px 10px', borderRadius: '5px',
- border: '1px solid transparent',
- background: tuneOpen ? BP.accentSoft : 'transparent',
- color: tuneOpen ? BP.accent : BP.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'color 0.12s ease, background 0.12s ease',
- whiteSpace: 'nowrap',
- });
- tune.innerHTML = TUNE_ICON_SVG;
- const tuneLabel = document.createElement('span');
- tuneLabel.textContent = 'Tune';
- tune.appendChild(tuneLabel);
- const tuneBadge = document.createElement('span');
- Object.assign(tuneBadge.style, {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- minWidth: '16px', height: '16px', padding: '0 4px',
- borderRadius: '999px',
- background: tuneOpen ? C.brand : BP.hairline,
- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',
- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',
- lineHeight: '1',
- boxSizing: 'border-box',
- });
- tuneBadge.textContent = String(visParams.length);
- tune.appendChild(tuneBadge);
- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';
- tune.addEventListener('mouseenter', () => {
- if (!tuneOpen) tune.style.background = BP.accentSoft;
- });
- tune.addEventListener('mouseleave', () => {
- if (!tuneOpen) tune.style.background = 'transparent';
- });
- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });
- tune.dataset.iceqTune = '1';
- row.appendChild(tune);
- }
-
- // Spacer
- row.appendChild(el('div', { flex: '1' }));
-
- // Accept — primary action, uses the site's saturated brand magenta
- // with paper-white text, not the theme-muted BP.accent.
- const accept = el('button', {
- padding: '5px 14px', borderRadius: '5px',
- border: 'none', background: C.brand, color: 'oklch(98% 0 0)',
- fontFamily: FONT, fontSize: '11px', fontWeight: '600',
- cursor: 'pointer', transition: 'filter 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap',
- });
- accept.textContent = '\u2713 Accept';
- accept.addEventListener('mouseenter', () => accept.style.filter = 'brightness(1.08)');
- accept.addEventListener('mouseleave', () => accept.style.filter = 'none');
- accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');
- accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');
- accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
- row.appendChild(accept);
-
- // Discard
- const discard = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: FONT, fontSize: '11px', color: BP.textDim,
- cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
- });
- discard.textContent = '\u2715';
- discard.title = 'Discard all variants';
- discard.addEventListener('mouseenter', () => { discard.style.color = BP.text; discard.style.borderColor = BP.text; });
- discard.addEventListener('mouseleave', () => { discard.style.color = BP.textDim; discard.style.borderColor = BP.hairline; });
- discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
- row.appendChild(discard);
-
- return row;
- }
-
- // --- Shared UI builders ---
-
- // --- Saving row (waiting for agent to process accept/discard) ---
-
- function buildSavingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const spinner = el('div', {
- width: '14px', height: '14px', borderRadius: '50%',
- border: '2px solid ' + BP.hairline,
- borderTopColor: BP.accent,
- animation: 'impeccable-spin 0.6s linear infinite',
- flexShrink: '0',
- });
- row.appendChild(spinner);
- const label = el('span', {
- fontSize: '12px', color: BP.textDim, fontWeight: '500',
- });
- label.textContent = 'Applying variant...';
- row.appendChild(label);
-
- // Inject the keyframes if not already present
- if (!document.getElementById(PREFIX + '-keyframes')) {
- const style = document.createElement('style');
- style.id = PREFIX + '-keyframes';
- style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
- document.head.appendChild(style);
- }
- return row;
- }
-
- // --- Confirmed row (green success, auto-dismisses) ---
-
- function buildConfirmedRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const check = el('span', {
- fontSize: '15px', lineHeight: '1', flexShrink: '0',
- color: 'oklch(45% 0.15 145)',
- });
- check.textContent = '\u2713';
- row.appendChild(check);
- const label = el('span', {
- fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
- });
- label.textContent = 'Variant applied';
- row.appendChild(label);
- return row;
- }
-
- // --- Shared UI builders ---
-
- function buildDots(clickable) {
- const container = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
- for (let i = 1; i <= expectedVariants; i++) {
- const arrived = i <= arrivedVariants;
- const active = i === visibleVariant;
- // active: solid site-brand magenta dot. arrived+inactive: muted neutral.
- // pending (not yet arrived): faint outline ring. No borders on arrived
- // dots — the previous "accent ring + ash fill" combo read as noisy
- // magenta chips, especially when all variants had arrived and every
- // dot wore an accent ring.
- const dotBg = active ? C.brand
- : arrived ? BP.textDim
- : 'transparent';
- const dotBorder = arrived ? 'none' : '1.5px solid ' + BP.hairline;
- const dot = el('div', {
- width: active ? '8px' : '6px',
- height: active ? '8px' : '6px',
- borderRadius: '50%',
- background: dotBg,
- border: dotBorder,
- boxSizing: 'border-box',
- transition: 'all 0.2s ' + EASE,
- cursor: (clickable && arrived) ? 'pointer' : 'default',
- transform: arrived ? 'scale(1)' : 'scale(0.85)',
- opacity: arrived ? (active ? '1' : '0.6') : '0.4',
- });
- if (clickable && arrived) {
- const idx = i;
- dot.addEventListener('click', (e) => {
- e.stopPropagation();
- visibleVariant = idx;
- showVariantInDOM(currentSessionId, idx);
- updateSelectedElement();
- updateBarContent('cycling');
- });
- }
- container.appendChild(dot);
- }
- return container;
- }
-
- function navBtn(text) {
- const b = el('button', {
- width: '26px', height: '26px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- color: BP.text, fontFamily: FONT, fontSize: '13px',
- cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
- transition: 'border-color 0.12s ease, background 0.12s ease',
- padding: '0', lineHeight: '1',
- });
- b.textContent = text;
- b.addEventListener('mouseenter', () => { b.style.borderColor = BP.text; });
- b.addEventListener('mouseleave', () => { b.style.borderColor = BP.hairline; });
- return b;
- }
-
- function actionLabel() {
- const a = ACTIONS.find(a => a.value === selectedAction);
- return a ? a.label : 'Freeform';
- }
-
- function el(tag, styles) {
- const e = document.createElement(tag);
- if (styles) Object.assign(e.style, styles);
- return e;
- }
-
- // ---------------------------------------------------------------------------
- // Action picker popover
- // ---------------------------------------------------------------------------
-
- function initActionPicker() {
- const P = barPaletteForTheme(detectPageTheme());
- pickerEl = document.createElement('div');
- pickerEl.id = PREFIX + '-picker';
- Object.assign(pickerEl.style, {
- position: 'fixed', zIndex: Z.picker,
- display: 'none', opacity: '0',
- transform: 'scale(0.96) translateY(4px)',
- transformOrigin: 'bottom left',
- transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
- background: P.surface,
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
- padding: '6px',
- fontFamily: FONT,
- backdropFilter: 'blur(10px)',
- WebkitBackdropFilter: 'blur(10px)',
- });
-
- // Build the chip grid
- const grid = el('div', {
- display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
- });
-
- ACTIONS.forEach(action => {
- const chip = el('button', {
- display: 'flex', flexDirection: 'column', alignItems: 'center',
- gap: '4px',
- padding: '8px 6px', borderRadius: '6px',
- border: 'none',
- background: action.value === selectedAction ? P.accentSoft : 'transparent',
- color: action.value === selectedAction ? P.accent : P.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.1s ease, color 0.1s ease',
- textAlign: 'center', whiteSpace: 'nowrap',
- });
- const iconWrap = el('span', {
- display: 'flex', alignItems: 'center', justifyContent: 'center',
- height: '20px', opacity: '0.9',
- });
- iconWrap.innerHTML = ICONS[action.value] || '';
- const labelEl = el('span', { lineHeight: '1' });
- labelEl.textContent = action.label;
- chip.appendChild(iconWrap);
- chip.appendChild(labelEl);
- chip.dataset.action = action.value;
- chip.addEventListener('mouseenter', () => {
- if (action.value !== selectedAction) chip.style.background = P.accentSoft;
- });
- chip.addEventListener('mouseleave', () => {
- chip.style.background = action.value === selectedAction ? P.accentSoft : 'transparent';
- });
- chip.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedAction = action.value;
- hideActionPicker();
- updateBarContent('configure');
- });
- grid.appendChild(chip);
- });
-
- pickerEl.appendChild(grid);
- document.body.appendChild(pickerEl);
- defangOutsideHandlers(pickerEl);
-
- // Cache the palette on the picker so toggleActionPicker's state refresh
- // uses the same theme-aware colors when it repaints chips.
- pickerEl.__iceq_palette = P;
- }
-
- function toggleActionPicker() {
- if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
- // Rebuild chips to reflect current selection
- const P = pickerEl.__iceq_palette || barPaletteForTheme(detectPageTheme());
- pickerEl.querySelectorAll('button').forEach(chip => {
- const isActive = chip.dataset.action === selectedAction;
- chip.style.background = isActive ? P.accentSoft : 'transparent';
- chip.style.color = isActive ? P.accent : P.text;
- });
- // Position above the bar
- const barRect = barEl.getBoundingClientRect();
- const pickerH = 170; // approximate; grows with icon + label rows
- let top = barRect.top - pickerH - 6;
- if (top < 8) top = barRect.bottom + 6;
- Object.assign(pickerEl.style, {
- top: top + 'px', left: barRect.left + 'px',
- display: 'block',
- });
- requestAnimationFrame(() => {
- pickerEl.style.opacity = '1';
- pickerEl.style.transform = 'scale(1) translateY(0)';
- });
- }
-
- function hideActionPicker() {
- if (!pickerEl) return;
- pickerEl.style.opacity = '0';
- pickerEl.style.transform = 'scale(0.96) translateY(4px)';
- setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
- }
-
- // ---------------------------------------------------------------------------
- // Params panel (per-variant coarse controls)
- //
- // Variants may declare a parameter manifest via a JSON attribute on the
- // variant wrapper:
- //
- // <div data-impeccable-variant="1"
- // data-impeccable-params='[{"id":"density","kind":"steps",...}]'>
- //
- // The panel docks to the right edge of the outline during CYCLING and
- // exposes 2-5 coarse knobs. Values apply to the variant wrapper so scoped
- // CSS can respond instantly without regeneration:
- //
- // range / numeric toggle → CSS var (`--p-<id>`) used via var(--p-foo, N)
- // steps / boolean toggle → data-p-<id> attribute used via :scope[data-p-foo="..."]
- //
- // On variant switch, values reset to that variant's declared defaults.
- // On accept, current values are sent in the event payload so the agent
- // can bake them into the source-file write.
- // ---------------------------------------------------------------------------
-
- let paramsPanelEl = null; // outer wrapper (overflow:hidden, clips the slide)
- let paramsPanelInner = null; // translating content (carries bg, padding, knobs)
- let paramsPanelBody = null; // grid holding the knob cells
- let paramsCurrentValues = {}; // {paramId: value} — mirror of the visible variant's live values
- let tuneOpen = false; // whether the Tune popover is open right now
-
- // Theme-aware Tune popover. Appears as a drawer that slides out from the
- // contextual bar's bar-facing edge (below if the bar sits below the
- // element, above otherwise). Same width as the bar. Auto-wraps to extra
- // rows when the knobs exceed one row. The bar's border-radius on the
- // popover side goes flat while open so the two shapes read as one.
- let paramsPanelPalette = null;
-
- function initParamsPanel() {
- paramsPanelPalette = barPaletteForTheme(detectPageTheme());
- const P = paramsPanelPalette;
-
- // Single element, always in the DOM. The slide animation is a CSS mask
- // with mask-size growing from 0% to 100% along the bar-facing axis — no
- // display toggle, no opacity toggle, no transform trickery. The mask
- // hides everything initially; as it grows, content is revealed from
- // the bar edge outward.
- paramsPanelEl = document.createElement('div');
- paramsPanelEl.id = PREFIX + '-params-panel';
- Object.assign(paramsPanelEl.style, {
- position: 'fixed', zIndex: String(Z.bar - 1),
- background: P.surfaceDeep,
- color: P.text,
- fontFamily: FONT,
- padding: '14px 18px',
- boxSizing: 'border-box',
- borderRadius: '0 0 10px 10px',
- pointerEvents: 'none',
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
-
- // clip-path is the same conceptual reveal as mask but with rock-solid
- // transition support across engines. Closed state clips from the far
- // edge; open = inset(0) shows everything.
- clipPath: 'inset(0 0 100% 0)',
- transition: 'clip-path 0.44s ' + EASE,
-
- // Park off-screen until positionParamsPanel places it. These are NOT
- // in the transition list, so they snap instantly — no fly-in from the
- // top-left when first shown.
- top: '-9999px', left: '-9999px', width: '0',
- });
-
- paramsPanelBody = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
- gap: '12px 16px',
- });
-
- paramsPanelEl.appendChild(paramsPanelBody);
- document.body.appendChild(paramsPanelEl);
- // Don't override pointer-events: the panel toggles between 'none' (closed,
- // click-through) and 'auto' (open) on its own. Just silence the host's
- // outside-interaction listeners while the panel is open.
- defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
- paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
- }
-
- function getVisibleVariantEl() {
- if (!currentSessionId) return null;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return null;
- return wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"]');
- }
-
- function parseVariantParams(variantEl) {
- if (!variantEl) return [];
- const raw = variantEl.getAttribute('data-impeccable-params');
- if (!raw) return [];
- try {
- const parsed = JSON.parse(raw);
- return Array.isArray(parsed) ? parsed : [];
- } catch (err) {
- console.warn('[impeccable] Invalid data-impeccable-params JSON:', err.message);
- return [];
- }
- }
-
- function applyParamValue(variantEl, param, value) {
- if (!variantEl) return;
- const attr = 'data-p-' + param.id;
- if (param.kind === 'range') {
- variantEl.style.setProperty('--p-' + param.id, String(value));
- } else if (param.kind === 'toggle') {
- const on = !!value;
- variantEl.style.setProperty('--p-' + param.id, on ? '1' : '0');
- if (on) variantEl.setAttribute(attr, 'on');
- else variantEl.removeAttribute(attr);
- } else if (param.kind === 'steps') {
- variantEl.setAttribute(attr, String(value));
- }
- }
-
- function applyParamDefaults(variantEl, params) {
- paramsCurrentValues = {};
- for (const p of params) {
- paramsCurrentValues[p.id] = p.default;
- applyParamValue(variantEl, p, p.default);
- }
- }
-
- function formatRangeValue(input) {
- const max = parseFloat(input.max), min = parseFloat(input.min);
- const v = parseFloat(input.value);
- if (!isFinite(v)) return input.value;
- return (max - min) <= 2 ? v.toFixed(2) : String(Math.round(v));
- }
-
- function buildParamsPanel(variantEl, params) {
- const P = paramsPanelPalette || barPaletteForTheme(detectPageTheme());
- paramsPanelBody.innerHTML = '';
- for (const p of params) {
- const row = el('div', { display: 'flex', flexDirection: 'column', gap: '6px' });
- const labelRow = el('div', {
- display: 'flex', justifyContent: 'space-between',
- alignItems: 'baseline', gap: '8px',
- });
- const lbl = el('span', {
- fontSize: '10.5px', fontWeight: '600', color: P.text,
- letterSpacing: '0.03em',
- });
- lbl.textContent = p.label || p.id;
- labelRow.appendChild(lbl);
- const readout = el('span', {
- fontSize: '10.5px', color: P.textDim,
- fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
- });
- labelRow.appendChild(readout);
- row.appendChild(labelRow);
-
- if (p.kind === 'range') {
- const input = document.createElement('input');
- input.type = 'range';
- input.min = String(p.min != null ? p.min : 0);
- input.max = String(p.max != null ? p.max : 1);
- input.step = String(p.step != null ? p.step : 0.05);
- input.value = String(p.default);
- Object.assign(input.style, {
- width: '100%', accentColor: C.brand, cursor: 'pointer',
- });
- readout.textContent = formatRangeValue(input);
- input.addEventListener('input', (e) => {
- e.stopPropagation();
- const v = parseFloat(input.value);
- paramsCurrentValues[p.id] = v;
- readout.textContent = formatRangeValue(input);
- applyParamValue(variantEl, p, v);
- queueCheckpoint('param_changed');
- });
- row.appendChild(input);
- } else if (p.kind === 'toggle') {
- const initial = !!p.default;
- readout.textContent = initial ? 'On' : 'Off';
- const track = el('button', {
- position: 'relative', width: '36px', height: '20px',
- borderRadius: '10px', border: 'none', padding: '0',
- cursor: 'pointer',
- background: initial ? C.brand : P.hairline,
- transition: 'background 0.15s ease',
- alignSelf: 'flex-start',
- });
- const knob = el('span', {
- position: 'absolute', top: '2px',
- left: initial ? '18px' : '2px',
- width: '16px', height: '16px', borderRadius: '50%',
- background: 'oklch(98% 0 0)',
- transition: 'left 0.18s ' + EASE,
- boxShadow: '0 1px 2px oklch(0% 0 0 / 0.2)',
- });
- track.appendChild(knob);
- track.addEventListener('click', (e) => {
- e.stopPropagation();
- const next = !paramsCurrentValues[p.id];
- paramsCurrentValues[p.id] = next;
- track.style.background = next ? C.brand : P.hairline;
- knob.style.left = next ? '18px' : '2px';
- readout.textContent = next ? 'On' : 'Off';
- applyParamValue(variantEl, p, next);
- queueCheckpoint('param_changed');
- });
- row.appendChild(track);
- } else if (p.kind === 'steps') {
- const opts = (p.options || []).map(o =>
- typeof o === 'string' ? { value: o, label: o } : o
- );
- const activeOpt = opts.find(o => o.value === p.default) || opts[0];
- readout.textContent = activeOpt ? activeOpt.label : String(p.default);
- const segRow = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(' + opts.length + ', 1fr)',
- gap: '1px', padding: '2px',
- background: P.hairline, borderRadius: '5px',
- });
- const segBtns = [];
- opts.forEach(o => {
- const active = o.value === p.default;
- const b = el('button', {
- padding: '5px 4px', border: 'none', borderRadius: '3px',
- background: active ? C.brand : 'transparent',
- color: active ? 'oklch(98% 0 0)' : P.text,
- fontFamily: FONT, fontSize: '10.5px', fontWeight: '500',
- cursor: 'pointer', whiteSpace: 'nowrap',
- transition: 'background 0.1s ease, color 0.1s ease',
- });
- b.textContent = o.label;
- b.addEventListener('click', (e) => {
- e.stopPropagation();
- paramsCurrentValues[p.id] = o.value;
- readout.textContent = o.label;
- segBtns.forEach(({ btn, val }) => {
- const on = val === o.value;
- btn.style.background = on ? C.brand : 'transparent';
- btn.style.color = on ? 'oklch(98% 0 0)' : P.text;
- });
- applyParamValue(variantEl, p, o.value);
- queueCheckpoint('param_changed');
- });
- segRow.appendChild(b);
- segBtns.push({ btn: b, val: o.value });
- });
- row.appendChild(segRow);
- }
-
- paramsPanelBody.appendChild(row);
- }
- }
-
- // Decide which way the popover opens: away from the picked element. If the
- // bar landed below the element, popover slides DOWN from the bar's bottom.
- // If the bar landed above, popover slides UP from the bar's top.
- function popoverDirection() {
- if (!barEl || !selectedElement) return 'below';
- const br = barEl.getBoundingClientRect();
- const er = selectedElement.getBoundingClientRect();
- return br.top >= er.bottom - 4 ? 'below' : 'above';
- }
-
- // The popover overlaps the bar by OVERLAP px on the bar-facing side. With
- // popover z-index below bar, that overlap sits behind bar (invisible) and
- // reinforces the "tucked behind" feel. Padding compensates so the real
- // content starts flush with bar's outer edge.
- const TUNE_OVERLAP = 6;
-
- // Closed clip-path depends on direction: for 'below' clip from the far
- // (bottom) edge so the reveal grows downward from the bar; for 'above'
- // clip from the top edge so the reveal grows upward from the bar.
- function closedClipPath(direction) {
- return direction === 'below' ? 'inset(0 0 100% 0)' : 'inset(100% 0 0 0)';
- }
-
- function setClipPath(value, withTransition) {
- const saved = paramsPanelEl.style.transition;
- if (!withTransition) paramsPanelEl.style.transition = 'none';
- paramsPanelEl.style.clipPath = value;
- if (!withTransition) {
- void paramsPanelEl.offsetHeight;
- paramsPanelEl.style.transition = saved;
- }
- }
-
- function positionParamsPanel() {
- if (!paramsPanelEl || !barEl || barEl.style.display === 'none') return;
- const br = barEl.getBoundingClientRect();
- const direction = popoverDirection();
- const prevDirection = paramsPanelEl.dataset.tuneDirection;
-
- // top/left/width are NOT in the transition list, so they snap instantly.
- paramsPanelEl.style.left = br.left + 'px';
- paramsPanelEl.style.width = br.width + 'px';
-
- if (direction === 'below') {
- paramsPanelEl.style.top = (br.bottom - TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '0 0 10px 10px';
- paramsPanelEl.style.paddingTop = (14 + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.paddingBottom = '14px';
- } else {
- const ih = paramsPanelEl.offsetHeight || 80;
- paramsPanelEl.style.top = (br.top - ih + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '10px 10px 0 0';
- paramsPanelEl.style.paddingTop = '14px';
- paramsPanelEl.style.paddingBottom = (14 + TUNE_OVERLAP) + 'px';
- }
- paramsPanelEl.dataset.tuneDirection = direction;
-
- // If currently closed and direction flipped (or first-time setup),
- // snap the clip-path to the new direction's closed pose without
- // transitioning (so the clip doesn't slide across the element).
- if (!tuneOpen && (!prevDirection || prevDirection !== direction)) {
- setClipPath(closedClipPath(direction), false);
- }
- }
-
- function showParamsPanel() {
- if (!paramsPanelEl) return;
- positionParamsPanel();
- paramsPanelEl.style.pointerEvents = 'auto';
- // rAF so the positioning paint commits before the transition fires.
- requestAnimationFrame(() => {
- setClipPath('inset(0 0 0 0)', true);
- });
- }
-
- function hideParamsPanel() {
- if (!paramsPanelEl) return;
- paramsPanelEl.style.pointerEvents = 'none';
- const direction = paramsPanelEl.dataset.tuneDirection || 'below';
- setClipPath(closedClipPath(direction), true);
- }
-
- // Build/rebuild the panel's contents for the current variant AND apply
- // its defaults to the variant wrapper (so scoped CSS responds even before
- // the user opens the popover). Visibility is governed by tuneOpen.
- function refreshParamsPanel() {
- if (state !== 'CYCLING') {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- if (tuneOpen) {
- // If already visible (variant cycled while open), refresh in place
- // instead of re-running the clip-path animation.
- const alreadyVisible = paramsPanelEl.style.display === 'block'
- && paramsPanelEl.style.opacity === '1';
- if (alreadyVisible) positionParamsPanel();
- else showParamsPanel();
- } else {
- hideParamsPanel();
- }
- }
-
- function toggleTunePopover() {
- if (tuneOpen) { closeTunePopover(); return; }
- openTunePopover();
- }
-
- function openTunePopover() {
- if (state !== 'CYCLING') return;
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) return;
- // Build fresh to ensure the current variant's controls are shown.
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- tuneOpen = true;
- showParamsPanel();
- // Kill the bar's shadow on the popover-facing side so the dark popover
- // doesn't pick up a bright glow line.
- if (barEl) {
- const direction = paramsPanelEl?.dataset.tuneDirection || 'below';
- barEl.style.boxShadow = direction === 'below' ? BAR_SHADOW_UP : BAR_SHADOW_DOWN;
- }
- // Re-render the bar so the Tune chip picks up the active styling.
- updateBarContent('cycling');
- }
-
- function closeTunePopover() {
- tuneOpen = false;
- hideParamsPanel();
- if (barEl) barEl.style.boxShadow = BAR_SHADOW_DEFAULT;
- if (barEl && barEl.style.display !== 'none' && state === 'CYCLING') {
- updateBarContent('cycling');
- }
- }
-
- // ---------------------------------------------------------------------------
- // Variant cycling in DOM
- // ---------------------------------------------------------------------------
-
- function showVariantInDOM(sessionId, num) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
- for (const child of wrapper.children) {
- const v = child.dataset ? child.dataset.impeccableVariant : null;
- if (!v) continue;
- child.style.display = (v === String(num)) ? '' : 'none';
- }
- // Unconditional refresh — covers first-reveal (no-op if state isn't
- // CYCLING yet, the subsequent CYCLING transition triggers its own
- // refresh) and every cycle step.
- refreshParamsPanel();
- }
-
- /**
- * No-HMR fallback: fetch the raw source file from the live server,
- * parse it, extract the variant wrapper, and inject it into the live DOM.
- * This works even when the dev server caches HTML (Bun, static servers).
- */
- function injectVariantsFromSource(filePath, sessionId) {
- const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
- fetch(url)
- .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
- .then(html => {
- // Parse the raw source HTML
- const parser = new DOMParser();
- const doc = parser.parseFromString(html, 'text/html');
- const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!srcWrapper) {
- console.error('[impeccable] Variant wrapper not found in source file.');
- return;
- }
-
- // Find the original element in the live DOM.
- // The original is inside the wrapper in the source. We find the
- // corresponding element in the live DOM by matching the first child's
- // tag + classes from the original snapshot.
- const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
- if (!origContent) return;
-
- const tag = origContent.tagName.toLowerCase();
- const cls = origContent.className;
- let liveEl = null;
- if (origContent.id) {
- liveEl = document.getElementById(origContent.id);
- } else if (cls) {
- // Find by tag + exact class match
- const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
- for (const c of candidates) {
- if (c.className === cls && !own(c)) { liveEl = c; break; }
- }
- }
-
- if (!liveEl) {
- console.error('[impeccable] Could not find original element in live DOM.');
- return;
- }
-
- const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;
-
- // Replace the live element with the full wrapper from source
- const wrapper = srcWrapper.cloneNode(true);
- liveEl.parentElement.replaceChild(wrapper, liveEl);
-
- // Update state: count variants, preserving the user's current variant
- // when a late HMR/source reinjection lands after they have cycled.
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants
- ? previousVisibleVariant
- : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);
- showVariantInDOM(sessionId, visibleVariant);
-
- // Update selectedElement to the visible variant's content
- selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;
-
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- saveSession();
- console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
- })
- .catch(err => {
- console.error('[impeccable] Failed to fetch source:', err);
- showToast('Could not load variants. Try refreshing the page.', 5000);
- });
- }
-
- function cycleVariant(dir) {
- const next = visibleVariant + dir;
- if (next < 1 || next > arrivedVariants) return;
- visibleVariant = next;
- showVariantInDOM(currentSessionId, next); // calls refreshParamsPanel itself
- updateSelectedElement();
- updateBarContent('cycling');
- saveSession();
- queueCheckpoint('variant_changed');
- }
-
- function updateSelectedElement() {
- if (!currentSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return;
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- function readVisibleVariantFromDOM(sessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return 0;
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- for (const variant of variants) {
- if (variant.style.display === 'none') continue;
- const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);
- if (idx > 0) return idx;
- }
- return 0;
- }
-
- // Resolve the element that represents the variant's visible content.
- // Contract: each variant div should contain exactly one top-level element
- // (the full replacement). In practice a model may ship loose siblings or
- // lead with <style>/<script>. Be defensive: skip non-visual elements, and
- // if the variant has multiple element children, use the variant div itself
- // (it wraps all of them and gets correct bounds).
- function pickVariantContent(wrapper, index) {
- if (!wrapper) return null;
- const variantDiv = wrapper.querySelector('[data-impeccable-variant="' + index + '"]');
- if (!variantDiv) return null;
- const NON_VISUAL = new Set(['STYLE', 'SCRIPT', 'LINK', 'META', 'TEMPLATE']);
- const visual = [];
- for (const child of variantDiv.children) {
- if (!NON_VISUAL.has(child.tagName)) visual.push(child);
- }
- if (visual.length === 1) return visual[0];
- return variantDiv;
- }
-
- // Hold window.scrollY at a fixed value across DOM mutations inside the
- // session's wrapper (HMR patches, variant inserts, cycle swaps).
- function startScrollLock(sessionId, initialTargetY) {
- stopScrollLock();
- scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)
- ? initialTargetY
- : window.scrollY;
- console.log('[impeccable.scroll] startScrollLock', { sessionId, scrollY: window.scrollY, targetY: scrollLockTargetY, initialOverride: initialTargetY });
-
- try { history.scrollRestoration = 'manual'; } catch {}
-
- const prevHtmlAnchor = document.documentElement.style.overflowAnchor;
- const prevBodyAnchor = document.body.style.overflowAnchor;
- document.documentElement.style.overflowAnchor = 'none';
- document.body.style.overflowAnchor = 'none';
-
- const correct = (why) => {
- scrollLockRaf = null;
- if (scrollLockTargetY == null) return;
- const before = window.scrollY;
- const delta = before - scrollLockTargetY;
- if (Math.abs(delta) < 0.5) {
- console.log('[impeccable.scroll] correct noop', { why, scrollY: before, targetY: scrollLockTargetY });
- return;
- }
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] corrected', { why, from: before, to: scrollLockTargetY, delta, nowAt: window.scrollY });
- };
- const schedule = (why) => {
- if (scrollLockRaf != null) return;
- scrollLockRaf = requestAnimationFrame(() => correct(why));
- };
-
- scrollLockObserver = new MutationObserver((mutations) => {
- for (const m of mutations) {
- if (m.target?.closest?.('[data-impeccable-variants="' + sessionId + '"]')) {
- const childAdds = Array.from(m.addedNodes).map(n => n.nodeType === 1 ? (n.tagName + (n.dataset?.impeccableVariant ? ('[variant=' + n.dataset.impeccableVariant + ']') : '')) : n.nodeType).join(',');
- console.log('[impeccable.scroll] mutation inside wrapper', { type: m.type, target: m.target?.tagName, adds: childAdds, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('mutation-in-wrapper');
- return;
- }
- for (const n of m.addedNodes) {
- if (n.nodeType === 1 && (n.matches?.('[data-impeccable-variants="' + sessionId + '"]') || n.querySelector?.('[data-impeccable-variants="' + sessionId + '"]'))) {
- console.log('[impeccable.scroll] wrapper node added', { tag: n.tagName, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('wrapper-added');
- return;
- }
- }
- }
- });
- scrollLockObserver.observe(document.body, { childList: true, subtree: true });
-
- scrollLockAbort = new AbortController();
- scrollLockAbort.signal.addEventListener('abort', () => {
- document.documentElement.style.overflowAnchor = prevHtmlAnchor;
- document.body.style.overflowAnchor = prevBodyAnchor;
- }, { once: true });
- const sig = { signal: scrollLockAbort.signal };
- // Track whether the most recent scroll came from a user gesture. We
- // gate user-scroll re-anchoring on this flag so programmatic smooth
- // scrolls (browser reload-restore, scrollIntoView from other scripts)
- // don't accidentally update our target.
- let userGestureAt = 0;
- const USER_GESTURE_WINDOW_MS = 250;
-
- const reanchor = (why) => {
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- const prevTarget = scrollLockTargetY;
- scrollLockTargetY = window.scrollY;
- writeScrollY(scrollLockTargetY);
- console.log('[impeccable.scroll] reanchor', { why, prevTarget, newTarget: scrollLockTargetY });
- };
- const markGesture = (why) => {
- userGestureAt = performance.now();
- reanchor(why);
- };
- window.addEventListener('wheel', () => markGesture('wheel'), { passive: true, ...sig });
- window.addEventListener('touchstart', () => markGesture('touchstart'), { passive: true, ...sig });
- window.addEventListener('touchmove', () => markGesture('touchmove'), { passive: true, ...sig });
- window.addEventListener('keydown', (e) => {
- if (['PageDown', 'PageUp', ' ', 'End', 'Home', 'ArrowDown', 'ArrowUp'].includes(e.key)) markGesture('key:' + e.key);
- }, sig);
-
- // Correct on EVERY scroll event: whether it's the browser's
- // post-reload animated restore or some other script calling
- // scrollIntoView, we want to snap back immediately. Only skip if a
- // user gesture fired in the last 250ms.
- let lastLoggedScrollY = window.scrollY;
- window.addEventListener('scroll', () => {
- const now = window.scrollY;
- if (Math.abs(now - lastLoggedScrollY) > 5) {
- console.log('[impeccable.scroll] scroll event', { from: lastLoggedScrollY, to: now, targetY: scrollLockTargetY });
- lastLoggedScrollY = now;
- }
- if (scrollLockTargetY == null) return;
- if (performance.now() - userGestureAt < USER_GESTURE_WINDOW_MS) return;
- if (Math.abs(now - scrollLockTargetY) < 0.5) return;
- console.log('[impeccable.scroll] scroll-event snap', { from: now, to: scrollLockTargetY });
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- }, { passive: true, ...sig });
-
- // Apply target synchronously, not via rAF — racing the browser's
- // restore or a smooth-scroll animation means we want to win now.
- if (Math.abs(window.scrollY - scrollLockTargetY) > 0.5) {
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] startScrollLock initial apply', { to: scrollLockTargetY });
- }
- }
-
- function stopScrollLock() {
- if (scrollLockObserver) { scrollLockObserver.disconnect(); scrollLockObserver = null; }
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }
- scrollLockTargetY = null;
- // NOTE: do NOT clear the persistent scroll key here. startScrollLock
- // calls us as a reset, and clearing the key would nuke the Go-time
- // scrollY that the next resume needs to read.
- }
-
- // ---------------------------------------------------------------------------
- // MutationObserver for progressive variant reveal
- // ---------------------------------------------------------------------------
-
- function startVariantObserver(sessionId) {
- let updating = false; // re-entrancy guard
-
- const obs = new MutationObserver((mutations) => {
- if (updating) return;
-
- // Only react to mutations that add nodes with data-impeccable-variant,
- // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
- let dominated = false;
- for (const m of mutations) {
- if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
- for (const n of m.addedNodes) {
- if (n.nodeType !== 1) continue;
- // Direct hit: the added node itself is the wrapper or a variant.
- if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
- dominated = true; break;
- }
- // Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
- // a whole subtree where the wrapper is a descendant of the added
- // node. Without this check, the observer ignores those mutations
- // and the session stays in GENERATING forever.
- if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
- dominated = true; break;
- }
- }
- if (dominated) break;
- }
- if (!dominated) return;
-
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
-
- // Re-anchor selectedElement if it was detached by live-wrap's HMR swap.
- // Without this, the shader / highlight / bar track a zero-rect phantom
- // and the overlay appears frozen.
- if (selectedElement && !document.body.contains(selectedElement)) {
- selectedElement = pickVariantContent(wrapper, 'original') || wrapper;
- }
-
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- const count = variants.length;
-
- // Nothing new
- if (count <= arrivedVariants) return;
-
- updating = true;
- arrivedVariants = count;
- if (visibleVariant === 0 && arrivedVariants > 0) {
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;
- showVariantInDOM(sessionId, visibleVariant);
- // showVariantInDOM hid the original (display:none); if we were still
- // anchored to the original's content, its boundingRect is now zero
- // and the bar snaps to (0,0). Re-point at the visible variant instead.
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- if (expected > 0) expectedVariants = expected;
-
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- } else if (state === 'GENERATING') {
- updateBarContent('generating');
- }
- saveSession();
- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');
- updating = false;
- });
-
- obs.observe(document.body, { childList: true, subtree: true });
- return obs;
- }
-
- // ---------------------------------------------------------------------------
- // Bar scroll tracking
- // ---------------------------------------------------------------------------
-
- function startScrollTracking() {
- function tick() {
- if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
- positionBar();
- showHighlight(selectedElement);
- if (tuneOpen) positionParamsPanel();
- }
- if (annotActive) positionAnnotOverlay(selectedElement);
- // Shader overlay (via debug P toggle or generation) is repositioned
- // by its own branch below; debug no longer has a separate overlay.
- if (shaderState) positionShaderOverlay();
- scrollRaf = requestAnimationFrame(tick);
- }
- scrollRaf = requestAnimationFrame(tick);
- }
-
- function stopScrollTracking() {
- if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
- }
-
- // ---------------------------------------------------------------------------
- // SSE (server→browser) + fetch POST (browser→server)
- // Zero-dependency replacement for WebSocket.
- // ---------------------------------------------------------------------------
-
- let evtSource = null;
- let sseRetries = 0;
- const SSE_MAX_RETRIES = 20; // generous: heartbeats keep the connection alive, so retries mean real trouble
-
- function connectSSE() {
- evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
-
- evtSource.onopen = () => {
- sseRetries = 0; // reset on successful (re)connect
- };
-
- evtSource.onmessage = (e) => {
- sseRetries = 0; // reset on any successful message
- let msg; try { msg = JSON.parse(e.data); } catch { return; }
- switch (msg.type) {
- case 'connected':
- hasProjectContext = !!msg.hasProjectContext;
- if (!hasProjectContext) showToast('No PRODUCT.md found. Variants will be brand-agnostic. Run /impeccable teach to generate one.', 7000);
- console.log('[impeccable] Live mode connected.');
- if (state === 'IDLE') state = 'PICKING';
- break;
- case 'done':
- // Variants already arrived via HMR → normal transition.
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- if (state === 'GENERATING') {
- state = 'CYCLING';
- updateBarContent('cycling');
- refreshParamsPanel();
- }
- break;
- }
- // Variants are in source but not in the DOM yet. Common when the
- // picked element lived inside conditional render (closed modal,
- // hidden tab, a route the user navigated away from). The variant
- // MutationObserver stays armed and auto-transitions to CYCLING
- // the moment the wrapper actually mounts. Nudge the user toward
- // that path with a toast — better than the prior force-reload
- // which reset framework state and left the session stuck.
- setTimeout(() => {
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
- if (state !== 'GENERATING') return;
- showToast(
- "Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
- 15000,
- );
- }, 2000);
- break;
- case 'error':
- console.error('[impeccable] Error:', msg.message);
- showToast('Error: ' + msg.message, 5000);
- hideBar();
- state = 'PICKING';
- break;
- }
- };
-
- evtSource.onerror = () => {
- sseRetries++;
- if (sseRetries <= SSE_MAX_RETRIES) {
- console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
- return; // EventSource auto-reconnects
- }
- // Server is gone. Clean up gracefully.
- console.log('[impeccable] Live server unreachable. Cleaning up UI.');
- evtSource.close();
- evtSource = null;
- handleServerLost();
- };
- }
-
- /** Server died or became unreachable. Reset UI to a clean state. */
- function handleServerLost() {
- const recoveryState = currentSessionId ? state : 'IDLE';
- if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
- showToast('Live server disconnected. Session ended.', 5000);
- }
- hideBar();
- hideHighlight();
- hideShaderOverlay();
- hideAnnotOverlay();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- // Preserve local session state on server loss. The durable journal is the
- // source of truth, but localStorage plus the variant wrapper lets the UI
- // resume after a helper restart or page reload instead of treating a
- // transient disconnect as an explicit discard.
- selectedElement = null;
- selectedAction = 'impeccable';
- state = recoveryState;
- if (currentSessionId) saveSession();
- }
-
- function sendEvent(msg, opts) {
- msg.token = TOKEN;
- function handleFailure(err) {
- console.error('[impeccable] Failed to send event:', err);
- if (opts && opts.throwOnError) throw err;
- return null;
- }
- return fetch('http://localhost:' + PORT + '/events', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(msg),
- }).then(res => {
- if (res.ok) return res;
- return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));
- }).catch(handleFailure);
- }
-
- function checkpointPayload(reason) {
- return {
- type: 'checkpoint',
- id: currentSessionId,
- revision: sessionState.nextCheckpointRevision(),
- owner: browserOwner,
- phase: String(state || '').toLowerCase(),
- reason,
- pageUrl: location.pathname,
- expectedVariants,
- arrivedVariants,
- visibleVariant,
- paramValues: { ...paramsCurrentValues },
- };
- }
-
- function sendCheckpoint(reason) {
- if (!currentSessionId) return Promise.resolve(null);
- return sendEvent(checkpointPayload(reason)).catch(() => null);
- }
-
- function queueCheckpoint(reason) {
- if (!currentSessionId) return;
- if (checkpointTimer) clearTimeout(checkpointTimer);
- checkpointTimer = setTimeout(() => {
- checkpointTimer = null;
- sendCheckpoint(reason);
- }, 120);
- }
-
- // ---------------------------------------------------------------------------
- // Event handlers
- // ---------------------------------------------------------------------------
-
- function handleMouseMove(e) {
- if (state !== 'PICKING' || !pickActive) return;
- const target = document.elementFromPoint(e.clientX, e.clientY);
- if (!target || !pickable(target) || target === hoveredElement) return;
- hoveredElement = target;
- showHighlight(target);
- }
-
- function handleClick(e) {
- // Close action picker on any outside click
- if (pickerEl?.style.display !== 'none' && !own(e.target)) {
- hideActionPicker();
- }
- // Close Tune popover on outside click (anything outside panel + bar)
- if (tuneOpen && paramsPanelEl && !paramsPanelEl.contains(e.target) && barEl && !barEl.contains(e.target)) {
- closeTunePopover();
- }
- // In CONFIGURING: click outside the bar and selected element returns to PICKING
- if (state === 'CONFIGURING' && !own(e.target) && selectedElement && !selectedElement.contains(e.target)) {
- hideBar();
- stopScrollTracking();
- hideAnnotOverlay();
- clearAnnotations();
- state = 'PICKING';
- hoveredElement = null;
- hideHighlight();
- return;
- }
- if (state !== 'PICKING' || !pickActive) return;
- if (own(e.target)) return;
- if (!hoveredElement || !pickable(hoveredElement)) return;
- e.preventDefault();
- e.stopPropagation();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- maybePrefetchPage();
- maybeWarnConditionalAncestor(selectedElement);
- }
-
- /**
- * Surface a brief, non-blocking heads-up when the picked element lives
- * inside a container whose visibility is gated by ephemeral state — modals,
- * collapsible panels, popovers, off-screen tab panels. If HMR remounts the
- * parent during generation (Vite Fast Refresh, SvelteKit page reload), the
- * variants land in source but stay invisible until the user re-opens the
- * container. Telling the user upfront is much friendlier than the silent
- * timeout-then-toast that they'd otherwise hit.
- *
- * Heuristic, intentionally narrow — only fires for unambiguous cases so
- * we don't cry wolf on every nested element.
- */
- function maybeWarnConditionalAncestor(el) {
- let node = el?.parentElement;
- let depth = 0;
- while (node && depth < 12) {
- // 1. Active dialog / modal
- if (node.getAttribute && node.getAttribute('role') === 'dialog'
- && node.getAttribute('aria-modal') === 'true') {
- showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 2. Common Radix / shadcn / headless-ui open-state attribute
- if (node.dataset && node.dataset.state === 'open') {
- showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 3. Tab panel — only meaningful when the page also shows ANOTHER
- // tab as selected. A single tabpanel with no tablist is just a static
- // section in disguise and isn't conditional.
- if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
- const list = document.querySelector('[role="tablist"]');
- if (list) {
- const tabs = list.querySelectorAll('[role="tab"]');
- if (tabs.length > 1) {
- showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
- return;
- }
- }
- }
- // 4. Collapsible: aria-expanded sibling. Look for the trigger button.
- if (node.id) {
- const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
- if (trigger) {
- showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
- return;
- }
- }
- node = node.parentElement;
- depth++;
- }
- }
-
- // Fire a lightweight prefetch event the first time the user selects an
- // element on a given route. The agent uses this to Read the underlying file
- // into context before Go is hit, shaving the read off the critical path.
- // Dedupe per session by pathname — clicking around on the same page doesn't
- // re-fire.
- //
- // DISABLED: quick-Go workflows pay an extra harness round trip because
- // prefetch + generate arrive as two events instead of one. Re-enable with
- // a browser-side debounce (~800–1000ms, cancelled on Go) if we want to
- // resurrect this. Server validator and skill dispatch remain in place so
- // flipping this flag is the only change needed.
- const PREFETCH_ENABLED = false;
- const prefetchedPaths = new Set();
- function maybePrefetchPage() {
- if (!PREFETCH_ENABLED) return;
- const path = location.pathname;
- if (prefetchedPaths.has(path)) return;
- prefetchedPaths.add(path);
- sendEvent({ type: 'prefetch', pageUrl: path });
- }
-
- function handleKeyDown(e) {
- // When the annotation input is focused, let it handle its own keys.
- if (annotEditing && annotEditing.input && e.target === annotEditing.input) return;
- if (e.key === 'Escape') {
- e.preventDefault();
- if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
- if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); hideAnnotOverlay(); clearAnnotations(); state = 'PICKING'; return; }
- if (state === 'CYCLING') { handleDiscard(); return; }
- if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
- if (state === 'PICKING') {
- // Use togglePick so the "Pick" button in the global bar also flips
- // off, otherwise the bar stays lit while nothing else is active.
- if (pickActive) togglePick();
- else { hideHighlight(); state = 'IDLE'; }
- return;
- }
- }
-
- // Arrow/Enter nav works in PICKING (hover) and CONFIGURING (selected, input empty)
- var navEl = (state === 'PICKING') ? hoveredElement : (state === 'CONFIGURING') ? selectedElement : null;
- if (navEl && (e.key === 'ArrowUp' || e.key === 'ArrowDown' || (e.key === 'Enter' && state === 'PICKING'))) {
- let next = null;
- if (e.key === 'ArrowDown' && !e.shiftKey) {
- next = navEl.nextElementSibling;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'ArrowUp' && !e.shiftKey) {
- next = navEl.previousElementSibling;
- while (next && !pickable(next)) next = next.previousElementSibling;
- } else if (e.key === 'ArrowUp' && e.shiftKey) {
- next = navEl.parentElement;
- if (next && !pickable(next)) next = null;
- } else if (e.key === 'ArrowDown' && e.shiftKey) {
- next = navEl.firstElementChild;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'Enter') {
- e.preventDefault();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- return;
- }
- if (next) {
- e.preventDefault();
- if (state === 'PICKING') {
- hoveredElement = next;
- } else {
- // CONFIGURING: re-select the new element and refresh the bar
- selectedElement = next;
- clearAnnotations();
- showAnnotOverlay(next);
- showBar('configure');
- startScrollTracking();
- }
- showHighlight(next);
- next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
- }
- return;
- }
-
- if (state === 'CYCLING') {
- if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
- if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
- if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
- }
- }
-
- function handleGo() {
- if (!selectedElement || state !== 'CONFIGURING') return;
- const input = document.getElementById(PREFIX + '-input');
- const prompt = input ? input.value.trim() : '';
-
- // Commit any pending pin edit BEFORE we snapshot annotations.
- if (annotEditing) finalizeEditingPin();
-
- currentSessionId = id8();
- expectedVariants = selectedCount;
- arrivedVariants = 0;
- visibleVariant = 0;
-
- // Flip to GENERATING immediately so the bar morphs without waiting on
- // capture + upload. The event is emitted from captureAndEmit() once the
- // screenshot is uploaded (or capture fails — we still emit, just without
- // screenshotPath).
- const elForCapture = selectedElement;
- const captureRect = elForCapture.getBoundingClientRect();
- const snapshot = {
- comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),
- strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),
- };
- const basePayload = {
- type: 'generate', id: currentSessionId,
- action: selectedAction,
- freeformPrompt: prompt || undefined,
- count: selectedCount,
- pageUrl: location.pathname,
- element: extractContext(elForCapture),
- };
- if (snapshot.comments.length > 0) basePayload.comments = snapshot.comments;
- if (snapshot.strokes.length > 0) basePayload.strokes = snapshot.strokes;
-
- // Hide the interactive overlay so it doesn't linger during generation.
- hideAnnotOverlay();
- clearAnnotations();
-
- state = 'GENERATING';
- showBar('generating');
- saveSession();
- sendCheckpoint('generate_started');
- writeScrollY(window.scrollY);
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
- console.log('[impeccable.scroll] Go pressed', { scrollY: window.scrollY, sessionId: currentSessionId });
- startScrollLock(currentSessionId);
-
- captureAndEmit(elForCapture, basePayload, snapshot, captureRect);
- }
-
- // ---------------------------------------------------------------------------
- // Screenshot capture + upload
- // ---------------------------------------------------------------------------
-
- let msLoadPromise = null;
- function loadModernScreenshot() {
- if (window.modernScreenshot) return Promise.resolve(window.modernScreenshot);
- if (msLoadPromise) return msLoadPromise;
- msLoadPromise = new Promise((resolve, reject) => {
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/modern-screenshot.js';
- s.onload = () => resolve(window.modernScreenshot);
- s.onerror = () => { msLoadPromise = null; reject(new Error('modern-screenshot failed to load')); };
- document.head.appendChild(s);
- });
- return msLoadPromise;
- }
-
- // Collect @font-face rules from every stylesheet on the page. Cross-origin
- // sheets (Google Fonts, Typekit, etc.) throw SecurityError on .cssRules
- // access, so modern-screenshot can't embed them on its own — the resulting
- // SVG falls back to system fonts and text re-wraps + renders with different
- // weight. We fetch the raw CSS text (CORS-permitted for these providers),
- // extract @font-face blocks, inline the referenced font files as base64
- // data URIs (SVGs rasterized via canvas can't fetch external resources,
- // so URLs inside the SVG silently fail without this), and pass the result
- // to modern-screenshot as font.cssText.
- const FONT_EXT_RE = /\.(woff2?|ttf|otf|eot)(\?.*)?$/i;
- const FONT_MIME = {
- woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', eot: 'application/vnd.ms-fontobject',
- };
- function bufferToBase64(buf) {
- const bytes = new Uint8Array(buf);
- let binary = '';
- const CHUNK = 0x8000;
- for (let i = 0; i < bytes.length; i += CHUNK) {
- binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
- }
- return btoa(binary);
- }
- async function inlineFontUrls(cssText) {
- const urlRe = /url\((['"]?)(https?:\/\/[^'")\s]+)\1\)/g;
- const urls = new Set();
- let m;
- while ((m = urlRe.exec(cssText))) {
- if (FONT_EXT_RE.test(m[2])) urls.add(m[2]);
- }
- const map = new Map();
- await Promise.all([...urls].map(async (url) => {
- try {
- const res = await fetch(url);
- if (!res.ok) return;
- const buf = await res.arrayBuffer();
- const ext = url.toLowerCase().match(FONT_EXT_RE)?.[1] || 'woff2';
- const mime = FONT_MIME[ext] || 'application/octet-stream';
- map.set(url, 'data:' + mime + ';base64,' + bufferToBase64(buf));
- } catch { /* skip; fall through to URL */ }
- }));
- return cssText.replace(urlRe, (orig, q, url) => {
- const data = map.get(url);
- return data ? 'url(' + q + data + q + ')' : orig;
- });
- }
- async function collectFontCssText() {
- const chunks = [];
- const fontFaceRe = /@font-face\s*\{[^}]*\}/g;
- for (const sheet of document.styleSheets) {
- try {
- const rules = sheet.cssRules;
- for (const rule of rules) {
- if (rule.constructor.name === 'CSSFontFaceRule' || rule.cssText?.startsWith('@font-face')) {
- chunks.push(rule.cssText);
- }
- }
- } catch {
- if (!sheet.href) continue;
- try {
- const res = await fetch(sheet.href);
- if (!res.ok) continue;
- const text = await res.text();
- let m2;
- while ((m2 = fontFaceRe.exec(text))) chunks.push(m2[0]);
- } catch { /* ignore; capture is best-effort */ }
- }
- }
- if (chunks.length === 0) return '';
- return inlineFontUrls(chunks.join('\n'));
- }
-
- // True if `s` is a computed color string that renders as nothing
- // (explicit `transparent`, or `rgba(...)` with alpha 0).
- function isTransparentColor(s) {
- if (!s) return true;
- if (s === 'transparent') return true;
- const m = /rgba?\(([^)]+)\)/.exec(s);
- if (!m) return false;
- const parts = m[1].split(',').map((p) => p.trim());
- if (parts.length === 4) return parseFloat(parts[3]) === 0;
- return false;
- }
-
- // modern-screenshot force-sets `background-color: X !important` on the
- // cloned root whenever `backgroundColor` is passed, clobbering the
- // element's own background. So we only pass it when the element is
- // genuinely transparent (no own color, no own image) — in that case
- // we resolve up the DOM to the nearest opaque ancestor so the capture
- // sits on the page's real background instead of rendering black.
- function resolveCanvasBackground(el) {
- const own = getComputedStyle(el);
- if (!isTransparentColor(own.backgroundColor)) return null;
- if (own.backgroundImage && own.backgroundImage !== 'none') return null;
- let node = el.parentElement;
- while (node) {
- const cs = getComputedStyle(node);
- if (!isTransparentColor(cs.backgroundColor)) return cs.backgroundColor;
- node = node.parentElement;
- }
- // The walk already passed through <body> and <html>; if they had been
- // opaque we would have returned. Falling through with the previous
- // `getComputedStyle(body).backgroundColor || …` chain is a trap: that
- // call returns the literal string `"rgba(0, 0, 0, 0)"` for a page that
- // never set its own bg, which is truthy and short-circuits the chain to
- // transparent-black — modern-screenshot then renders the capture on a
- // black canvas and the shader overlay flashes solid black during load.
- // The browser canvas defaults to white, so we do too.
- return '#ffffff';
- }
-
- // Capture the element (with current annotations baked in) and return a PNG
- // Blob. Shared between the Go flow (uploads it to the server) and the
- // debug toggle (displays it as an overlay for side-by-side comparison).
- async function captureElementToBlob(el, snapshot, rect) {
- try { if (document.fonts?.ready) await document.fonts.ready; } catch {}
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- let annotNode = null;
- let savedPosition = null;
- if (hasAnnotations) {
- const pos = getComputedStyle(el).position;
- if (pos === 'static') {
- savedPosition = el.style.position;
- el.style.position = 'relative';
- }
- annotNode = buildAnnotationsForCapture(rect, snapshot);
- el.appendChild(annotNode);
- }
- try {
- const ms = await loadModernScreenshot();
- const fontCssText = await collectFontCssText();
- const backgroundColor = resolveCanvasBackground(el);
- return await ms.domToBlob(el, {
- scale: Math.min(window.devicePixelRatio || 1, 2),
- font: fontCssText ? { cssText: fontCssText } : undefined,
- ...(backgroundColor ? { backgroundColor } : {}),
- });
- } finally {
- if (annotNode) annotNode.remove();
- if (savedPosition !== null) el.style.position = savedPosition;
- }
- }
-
- async function captureAndEmit(el, basePayload, snapshot, rect) {
- let screenshotPath;
- let blob;
- try {
- blob = await captureElementToBlob(el, snapshot, rect);
- } catch (err) {
- console.warn('[impeccable] capture failed, proceeding without screenshot:', err);
- }
- // Light up the shader overlay the moment capture is ready — no reason to
- // wait for the upload to complete before the user sees something alive.
- if (blob && state === 'GENERATING') {
- showShaderOverlay(el, blob, rect);
- }
- // Only upload + forward the screenshot when annotations (comments/strokes)
- // are present. Without annotations the image is pure visual anchoring —
- // it biases the model toward the current rendering and works against the
- // three-distinct-directions brief.
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- if (blob && hasAnnotations) {
- try {
- const uploadRes = await fetch(
- 'http://localhost:' + PORT + '/annotation?token=' + encodeURIComponent(TOKEN) +
- '&eventId=' + encodeURIComponent(basePayload.id),
- { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: blob },
- );
- if (uploadRes.ok) {
- const { path: p } = await uploadRes.json();
- screenshotPath = p;
- } else {
- console.warn('[impeccable] annotation upload failed:', uploadRes.status);
- }
- } catch (err) {
- console.warn('[impeccable] annotation upload failed:', err);
- }
- }
- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);
- }
-
- // ---------------------------------------------------------------------------
- // Shader overlay — renders the captured screenshot as a WebGL texture and
- // runs an editorial "ink-wash" fragment shader over it during generation.
- // A single rolling band sweeps top-to-bottom, desaturating + tinting magenta
- // and leaving a soft trail. Makes the wait feel like a letterpress scan
- // instead of a dead spinner.
- // ---------------------------------------------------------------------------
-
- const SHADER_VS = `attribute vec2 a_position;
-attribute vec2 a_uv;
-varying vec2 v_uv;
-void main() {
- v_uv = a_uv;
- gl_Position = vec4(a_position, 0.0, 1.0);
-}`;
-
- const SHADER_FS = `precision highp float;
-uniform sampler2D u_texture;
-uniform float u_time;
-uniform vec2 u_resolution;
-uniform vec3 u_accent;
-varying vec2 v_uv;
-
-// Asymmetric roller band. Product of two one-sided smoothsteps — peaks at
-// d=0 with a short sharp leading ramp and a longer soft trailing tail. Clean
-// outside the [-leadW, trailW] range (no rogue "trail=1 everywhere below"
-// failure that reversed-edge smoothstep would give).
-float bandAt(float d, float leadW, float trailW) {
- float above = smoothstep(-leadW, 0.0, d);
- float below = 1.0 - smoothstep(0.0, trailW, d);
- return above * below;
-}
-
-void main() {
- vec2 uv = v_uv;
- // Roller sweeps top-to-bottom with small overshoot so each cycle enters
- // and exits the element cleanly.
- float phase = fract(u_time / 3.4);
- float y = phase * 1.25 - 0.12;
- float band = bandAt(uv.y - y, 0.05, 0.32);
-
- // Halftone cell grid (fixed ~10 px pitch).
- float cellPx = 10.0;
- vec2 gridUv = uv * u_resolution / cellPx;
- vec2 cellId = floor(gridUv);
- vec2 cellUv = fract(gridUv) - 0.5;
- vec2 sampleCenter = (cellId + 0.5) * cellPx / u_resolution;
- vec3 cellImg = texture2D(u_texture, sampleCenter).rgb;
- float luma = dot(cellImg, vec3(0.299, 0.587, 0.114));
- // Darker cells → bigger magenta dots (classic risograph halftone curve).
- float radius = sqrt(clamp(1.0 - luma, 0.0, 1.0)) * 0.56;
- float dotMask = smoothstep(radius + 0.06, radius, length(cellUv));
- vec3 paper = vec3(0.975, 0.965, 0.955);
- vec3 dotLayer = mix(paper, u_accent, dotMask);
-
- // Blend the halftone layer in where the roller is passing; leave the
- // element pristine elsewhere.
- vec3 base = texture2D(u_texture, uv).rgb;
- gl_FragColor = vec4(mix(base, dotLayer, band), 1.0);
-}`;
-
- // Editorial Magenta converted to approximate sRGB 0-1 (matches oklch(60% 0.25 350))
- const SHADER_ACCENT = [0.82, 0.16, 0.47];
- let shaderState = null; // { canvas, gl, program, texture, rafId, startTime }
-
- function compileShader(gl, type, source) {
- const sh = gl.createShader(type);
- gl.shaderSource(sh, source);
- gl.compileShader(sh);
- if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
- const info = gl.getShaderInfoLog(sh);
- gl.deleteShader(sh);
- throw new Error('shader compile failed: ' + info);
- }
- return sh;
- }
-
- function positionShaderOverlay() {
- if (!shaderState || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- Object.assign(shaderState.canvas.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- }
-
- function hideShaderOverlay() {
- if (!shaderState) return;
- if (shaderState.rafId) cancelAnimationFrame(shaderState.rafId);
- if (shaderState.canvas) shaderState.canvas.remove();
- const lose = shaderState.gl?.getExtension?.('WEBGL_lose_context');
- try { lose?.loseContext(); } catch {}
- shaderState = null;
- }
-
- async function showShaderOverlay(el, blob, rect) {
- hideShaderOverlay();
- if (!blob || !el) return;
- const canvas = document.createElement('canvas');
- canvas.id = PREFIX + '-shader';
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
- canvas.width = Math.max(1, Math.floor(rect.width * dpr));
- canvas.height = Math.max(1, Math.floor(rect.height * dpr));
- Object.assign(canvas.style, {
- position: 'fixed',
- top: rect.top + 'px', left: rect.left + 'px',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none',
- zIndex: Z.bar - 1,
- });
- document.body.appendChild(canvas);
-
- const gl = canvas.getContext('webgl', { premultipliedAlpha: false, preserveDrawingBuffer: false })
- || canvas.getContext('experimental-webgl');
- if (!gl) {
- // WebGL unavailable — fall back to a plain <img> overlay so the user
- // still sees something meaningful during generation.
- canvas.remove();
- const img = document.createElement('img');
- img.src = URL.createObjectURL(blob);
- img.id = PREFIX + '-shader';
- // Copy positioning via cssText. Object.assign across CSSStyleDeclaration
- // throws in modern Chromium because the source's indexed properties
- // (style[0], [1], ...) are read-only and the engine forbids writing
- // them on the destination.
- img.style.cssText = canvas.style.cssText;
- img.style.outline = '2px dashed ' + C.brand;
- img.style.outlineOffset = '-2px';
- document.body.appendChild(img);
- shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
- return;
- }
-
- let program, texture;
- try {
- const vs = compileShader(gl, gl.VERTEX_SHADER, SHADER_VS);
- const fs = compileShader(gl, gl.FRAGMENT_SHADER, SHADER_FS);
- program = gl.createProgram();
- gl.attachShader(program, vs);
- gl.attachShader(program, fs);
- gl.linkProgram(program);
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- throw new Error('program link failed: ' + gl.getProgramInfoLog(program));
- }
- // Full-screen quad
- const buf = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
- -1, -1, 0, 1,
- 1, -1, 1, 1,
- -1, 1, 0, 0,
- -1, 1, 0, 0,
- 1, -1, 1, 1,
- 1, 1, 1, 0,
- ]), gl.STATIC_DRAW);
- const posLoc = gl.getAttribLocation(program, 'a_position');
- const uvLoc = gl.getAttribLocation(program, 'a_uv');
- gl.enableVertexAttribArray(posLoc);
- gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 16, 0);
- gl.enableVertexAttribArray(uvLoc);
- gl.vertexAttribPointer(uvLoc, 2, gl.FLOAT, false, 16, 8);
- } catch (err) {
- console.warn('[impeccable] shader setup failed:', err);
- canvas.remove();
- return;
- }
-
- // Upload the screenshot as a texture
- let bitmap;
- try {
- bitmap = await createImageBitmap(blob);
- } catch {
- // Safari fallback: go via a regular Image
- const imgUrl = URL.createObjectURL(blob);
- const img = new Image();
- img.src = imgUrl;
- await new Promise((r, rej) => { img.onload = r; img.onerror = rej; });
- bitmap = img;
- URL.revokeObjectURL(imgUrl);
- }
- texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
- if (bitmap.close) bitmap.close();
-
- const uTime = gl.getUniformLocation(program, 'u_time');
- const uRes = gl.getUniformLocation(program, 'u_resolution');
- const uAccent = gl.getUniformLocation(program, 'u_accent');
- const uTex = gl.getUniformLocation(program, 'u_texture');
- const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-
- shaderState = { canvas, gl, program, texture, rafId: 0, startTime: performance.now(), reduced };
- function frame() {
- if (!shaderState) return;
- const elapsed = (performance.now() - shaderState.startTime) / 1000;
- const t = shaderState.reduced ? 0.0 : elapsed;
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.useProgram(program);
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.uniform1i(uTex, 0);
- gl.uniform1f(uTime, t);
- gl.uniform2f(uRes, canvas.width, canvas.height);
- gl.uniform3f(uAccent, SHADER_ACCENT[0], SHADER_ACCENT[1], SHADER_ACCENT[2]);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- shaderState.rafId = requestAnimationFrame(frame);
- }
- frame();
- }
-
- function handleAccept() {
- if (!currentSessionId || arrivedVariants === 0) return;
- const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);
- if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;
- const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };
- if (Object.keys(paramsCurrentValues).length > 0) {
- acceptPayload.paramValues = { ...paramsCurrentValues };
- }
- // The accepted variant is already the only visible child of the wrapper
- // (all other variants are display:none). HMR from the source rewrite will
- // replace the wrapper imminently. Don't eagerly replaceChild here — React
- // reconciliation races with our mutation and throws NotFoundError in Next
- // 16 / Turbopack. Schedule a fallback that runs the manual swap only if
- // HMR hasn't cleaned up by then (keeps static-server flows working).
- const acceptedSessionId = currentSessionId;
- const acceptedVariant = visibleVariant;
-
- state = 'SAVING';
- updateBarContent('saving');
-
- sendEvent(acceptPayload, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- confirmAcceptAfterReceipt();
- })
- .catch(() => {
- state = 'CYCLING';
- updateBarContent('cycling');
- showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);
- });
-
- function confirmAcceptAfterReceipt() {
- state = 'CONFIRMED';
- updateBarContent('confirmed');
- scheduleAcceptCleanup();
- }
-
- function scheduleAcceptCleanup() {
- setTimeout(function() {
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }, 1800);
-
- // Static-server / no-HMR fallback: if the wrapper is still around 2s after
- // the cleanup above, swap it out manually. By now React has either moved
- // on or the app isn't React at all. Preserve the `data-impeccable-variant="N"`
- // div (with display:contents) so @scope rules anchored to the variant
- // attribute keep matching until reload replaces it with the carbonize block.
- setTimeout(function() {
- const wrapper = document.querySelector('[data-impeccable-variants="' + acceptedSessionId + '"]');
- if (!wrapper) return;
- const accepted = wrapper.querySelector('[data-impeccable-variant="' + acceptedVariant + '"]');
- if (accepted && accepted.firstElementChild) {
- const parent = wrapper.parentElement;
- if (!parent) return;
- accepted.style.display = 'contents';
- parent.replaceChild(accepted, wrapper);
- }
- }, 2000);
- }
- }
-
- function handleDiscard() {
- if (!currentSessionId) return;
- sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- cleanup();
- })
- .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));
- }
-
- // ---------------------------------------------------------------------------
- // Session persistence via live-browser-session.js
- // ---------------------------------------------------------------------------
- // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
-
- function saveSession() {
- if (!currentSessionId) return;
- // NOTE: scrollY is stored under a separate key (writeScrollY). Storing
- // it here would overwrite the Go-time value every time state changes.
- sessionState.saveSession({
- id: currentSessionId,
- state,
- action: selectedAction,
- count: selectedCount,
- expected: expectedVariants,
- arrived: arrivedVariants,
- visible: visibleVariant,
- });
- }
-
- function loadSession() {
- return sessionState.loadSession();
- }
-
- function clearSession() {
- sessionState.clearSession();
- }
-
- /** Mark session as handled (accepted/discarded). The agent will clean up
- * the source, but until it does the wrapper is still in the HTML. This
- * prevents resumeSession from picking it up again after reload. */
- function markSessionHandled() {
- if (!currentSessionId) return;
- sessionState.markHandled(currentSessionId);
- }
-
- function isSessionHandled(id) {
- return sessionState.isHandled(id);
- }
-
- function clearHandled() {
- sessionState.clearHandled();
- }
-
- function cleanup() {
- // Hide the wrapper immediately so variants disappear. DON'T structurally
- // mutate the DOM yet — HMR from the agent's source rewrite is on its way,
- // and a manual replaceChild under React causes NotFoundError when the
- // reconciler later tries to remove a wrapper we already removed.
- // Schedule a 2s fallback that does the manual swap only if HMR hasn't
- // replaced the wrapper by then (keeps static-server / no-HMR flows alive).
- const cleanupSessionId = currentSessionId;
- if (cleanupSessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (wrapper) wrapper.style.display = 'none';
- }
- setTimeout(function() {
- if (!cleanupSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (!wrapper) return;
- const orig = wrapper.querySelector('[data-impeccable-variant="original"]');
- if (orig) {
- const content = orig.firstElementChild;
- if (content) {
- wrapper.parentElement.replaceChild(content, wrapper);
- return;
- }
- }
- wrapper.remove();
- }, 2000);
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }
-
- // ---------------------------------------------------------------------------
- // Toast
- // ---------------------------------------------------------------------------
-
- function showToast(message, duration) {
- if (toastEl) toastEl.remove();
- // Stack the toast above the global bar (which sits at bottom:14px) so
- // the two never overlap. Read the bar's actual rect — its height varies
- // with hover-expanded labels — and fall back to a sensible default
- // when the bar isn't mounted yet.
- const barRect = globalBarEl?.getBoundingClientRect();
- const barTopFromBottom = barRect && barRect.height > 0
- ? Math.max(16, window.innerHeight - barRect.top + 12)
- : 16;
- toastEl = el('div', {
- position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
- transform: 'translateX(-50%) translateY(8px)',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px',
- padding: '8px 16px', borderRadius: '8px',
- zIndex: Z.toast, opacity: '0',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
- pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
- });
- toastEl.id = PREFIX + '-toast';
- toastEl.textContent = message;
- document.body.appendChild(toastEl);
- requestAnimationFrame(() => {
- toastEl.style.opacity = '1';
- toastEl.style.transform = 'translateX(-50%) translateY(0)';
- });
- setTimeout(() => {
- if (toastEl) {
- toastEl.style.opacity = '0';
- toastEl.style.transform = 'translateX(-50%) translateY(8px)';
- setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
- }
- }, duration);
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- // Resume an active variant session after HMR/page reload.
- // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
- // variants before HMR fired. Pick up where we left off.
- function resumeSession() {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) { clearSession(); clearHandled(); return false; }
-
- const sessionId = wrapper.dataset.impeccableVariants;
-
- // Don't resume if this session was already accepted/discarded
- if (isSessionHandled(sessionId)) return false;
-
- currentSessionId = sessionId;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
-
- // Restore state from localStorage if available
- const saved = loadSession();
- if (saved && saved.id === sessionId) {
- visibleVariant = (saved.visible > 0 && saved.visible <= arrivedVariants) ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
- if (saved.action) selectedAction = saved.action;
- if (saved.count) selectedCount = saved.count;
- } else {
- visibleVariant = arrivedVariants > 0 ? 1 : 0;
- }
-
- // Find the visible variant's content element for highlight positioning.
- // Try the visible variant first, fall back to the original's content.
- const visEl = visibleVariant > 0 ? pickVariantContent(wrapper, visibleVariant) : null;
- const origEl = pickVariantContent(wrapper, 'original');
- selectedElement = visEl || origEl || wrapper.parentElement;
-
- // Set display state BEFORE starting observer (avoid triggering it)
- if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
-
- state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
- showBar(state === 'CYCLING' ? 'cycling' : 'generating');
- startScrollTracking();
- // Build the params panel for the restored visible variant. Previously
- // this was missed on page-reload resume: showVariantInDOM above fires
- // refreshParamsPanel, but state was still IDLE at that moment so it
- // hid. Now that state is CYCLING, re-fire.
- if (state === 'CYCLING') refreshParamsPanel();
- saveSession();
- queueCheckpoint('browser_resumed');
-
- // Start observing for more variants AFTER initial setup
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
-
- // Hold the target at its saved viewport top through any subsequent
- // HMR patches, variant inserts, or cycle swaps.
- startScrollLock(currentSessionId, readScrollY());
-
- // If we reloaded mid-generation (Bun's HTML HMR destroys the shader
- // canvas), re-capture the original's content and restart the shader so
- // the wait doesn't go dead.
- if (state === 'GENERATING' && origEl) {
- (async () => {
- try {
- const rect = origEl.getBoundingClientRect();
- if (rect.width === 0 || rect.height === 0) return;
- const blob = await captureElementToBlob(origEl, null, rect);
- if (blob && state === 'GENERATING') {
- showShaderOverlay(origEl, blob, rect);
- }
- } catch (err) {
- console.warn('[impeccable] shader resume failed:', err);
- }
- })();
- }
- return true;
- }
-
- // ---------------------------------------------------------------------------
- // Global bar (always visible at bottom)
- // ---------------------------------------------------------------------------
-
- let globalBarEl = null;
- let detectActive = false;
- let pickActive = true;
- let detectCount = 0;
- let detectScriptLoaded = false;
-
- // Theme-aware color palette for the global bar. We detect the page's
- // ambient background and invert — dark bar on light pages, light bar on
- // dark pages. This keeps the bar from fighting with the host design.
- function detectPageTheme() {
- try {
- // Dev override: set localStorage 'impeccable-dev-theme' to 'light' or
- // 'dark' to preview the opposite palette without actually changing the
- // page bg. Used for screenshots and theme QA.
- const override = localStorage.getItem('impeccable-dev-theme');
- if (override === 'light' || override === 'dark') return override;
-
- // Walk body → html, taking the first opaque background. The browser's
- // default body / html background is `rgba(0, 0, 0, 0)`, which a naive
- // regex would read as black and mislabel a perfectly white page as
- // dark. Honoring alpha avoids that — and falling through to <html>
- // catches the common pattern of a bg only on <html> (or only on body).
- function readOpaque(el) {
- if (!el) return null;
- const bg = getComputedStyle(el).backgroundColor;
- const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
- if (!m) return null;
- const alpha = m[4] == null ? 1 : parseFloat(m[4]);
- if (alpha < 0.5) return null; // transparent / nearly transparent → skip
- return [+m[1], +m[2], +m[3]];
- }
-
- const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
- // Both transparent → fall back to the browser's effective canvas color.
- // White is the universal default; only one in a thousand sites swaps it
- // via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
- // us catch that case.
- if (!rgb) {
- return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
- }
- const [r, g, b] = rgb;
- // Perceptual luminance (Rec. 709)
- const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
- return L > 0.55 ? 'light' : 'dark';
- } catch { return 'light'; }
- }
-
- function barPaletteForTheme(theme) {
- if (theme === 'dark') {
- // Light bar on dark page
- return {
- surface: 'oklch(98% 0 0 / 0.92)',
- surfaceDeep: 'oklch(92% 0.005 60 / 0.96)', // slightly deeper, faint warm
- hairline: 'oklch(70% 0 0 / 0.35)',
- text: 'oklch(15% 0 0)',
- textDim: 'oklch(45% 0 0)',
- accent: 'oklch(60% 0.25 350)',
- accentSoft: 'oklch(60% 0.25 350 / 0.18)',
- mark: 'oklch(98% 0 0)', // logo mark fill
- markText: 'oklch(15% 0 0)', // logo "/" color
- exitHover: 'oklch(85% 0 0 / 0.5)',
- };
- }
- // Dark bar on light page. Bar is a warm charcoal, logo slab is much
- // deeper so the rounded-right shape reads as a clear sculpted mark.
- return {
- surface: 'oklch(26% 0 0 / 0.94)',
- surfaceDeep: 'oklch(18% 0 0 / 0.96)', // darker sand for Tune popover
- hairline: 'oklch(42% 0 0 / 0.5)',
- text: 'oklch(96% 0 0)',
- textDim: 'oklch(72% 0 0)',
- accent: 'oklch(72% 0.22 350)',
- accentSoft: 'oklch(72% 0.22 350 / 0.22)',
- mark: 'oklch(8% 0 0)',
- markText: 'oklch(96% 0 0)',
- exitHover: 'oklch(36% 0 0 / 0.6)',
- };
- }
-
- // Impeccable logo mark — matches the site-header SVG (rounded square + "/").
- function brandMarkSvg(fill, ink, size = 18) {
- return `<svg width="${size}" height="${size}" viewBox="0 0 32 32" aria-hidden="true">
- <rect width="32" height="32" rx="7" fill="${fill}"/>
- <text x="16" y="24" font-family="system-ui, -apple-system, sans-serif" font-size="22" font-weight="500" fill="${ink}" text-anchor="middle">/</text>
- </svg>`;
- }
-
- function initGlobalBar() {
- const theme = detectPageTheme();
- const P = barPaletteForTheme(theme);
-
- // Custom focus-visible for bar buttons. Browser default is a heavy
- // blue ring that looks jarring on the dark capsule. Replace with a
- // soft accent-tinted inner ring that respects the bar's palette.
- if (!document.getElementById(PREFIX + '-bar-focus-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-bar-focus-style';
- s.textContent =
- '#' + PREFIX + '-global-bar button:focus { outline: none; }' +
- '#' + PREFIX + '-global-bar button:focus-visible {' +
- ' outline: none;' +
- ' box-shadow: 0 0 0 2px ' + P.accentSoft + ', 0 0 0 3px ' + P.accent + ';' +
- '}';
- document.head.appendChild(s);
- }
-
- globalBarEl = el('div', {
- position: 'fixed', bottom: '14px', left: '50%',
- transform: 'translateX(-50%) translateY(20px)',
- zIndex: Z.bar + 5,
- display: 'flex', alignItems: 'stretch',
- gap: '2px',
- background: P.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 4px 20px oklch(0% 0 0 / 0.12), 0 1px 3px oklch(0% 0 0 / 0.08)',
- fontFamily: FONT, fontSize: '12px', lineHeight: '1',
- opacity: '0',
- overflow: 'hidden', // clip the full-bleed brand mark to the bar radius
- transition: 'opacity 0.3s ' + EASE + ', transform 0.3s ' + EASE,
- });
- globalBarEl.id = PREFIX + '-global-bar';
- globalBarEl.dataset.theme = theme;
-
- // Brand mark — fills bar height on the left. Left side inherits the bar's
- // rounded corner via overflow:hidden; right side is a clean hard edge since
- // the near-black/charcoal contrast does the shape-defining work.
- const brand = el('span', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- alignSelf: 'stretch',
- padding: '0 12px 0 14px',
- background: P.mark,
- color: P.markText,
- fontFamily: 'system-ui, -apple-system, sans-serif',
- fontWeight: '500',
- fontSize: '18px', lineHeight: '1',
- });
- brand.textContent = '/';
- brand.title = 'Impeccable';
- globalBarEl.appendChild(brand);
-
- // Inner wrapper: holds the toggles with normal bar padding.
- const inner = el('div', {
- display: 'flex', alignItems: 'center',
- padding: '4px 5px', gap: '2px',
- });
- inner.id = PREFIX + '-global-bar-inner';
- globalBarEl.appendChild(inner);
-
- // --- button factory: icon-only at rest, label slides in on hover/active ---
- function makeIconBtn({ id, svg, label, ariaLabel, labelFont, onClick }) {
- const b = el('button', {
- position: 'relative',
- display: 'inline-flex', alignItems: 'center',
- padding: '6px 8px', borderRadius: '7px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '11.5px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.15s ease, color 0.15s ease',
- whiteSpace: 'nowrap', overflow: 'hidden',
- });
- b.id = id;
- b.title = ariaLabel || label || '';
- b.setAttribute('aria-label', ariaLabel || label || '');
- b.innerHTML = svg + (label
- ? `<span class="icon-btn-label" style="display:inline-block;max-width:0;opacity:0;margin-left:0;overflow:hidden;font-family:${labelFont || FONT};transition:max-width 0.25s ${EASE}, opacity 0.2s ease, margin-left 0.25s ${EASE};">${label}</span>`
- : '');
- const labelEl = b.querySelector('.icon-btn-label');
- const expand = () => {
- if (!labelEl) return;
- labelEl.style.maxWidth = '120px'; labelEl.style.opacity = '1'; labelEl.style.marginLeft = '6px';
- };
- const collapse = () => {
- if (!labelEl || b.dataset.active === 'true') return;
- labelEl.style.maxWidth = '0'; labelEl.style.opacity = '0'; labelEl.style.marginLeft = '0';
- };
- // Per-button hover only changes color (no layout). The label expand/
- // collapse is driven by the bar-level mouseenter/mouseleave so moving
- // the mouse between adjacent buttons doesn't trigger per-button width
- // thrashing — the whole bar grows once and shrinks once.
- b.addEventListener('mouseenter', () => { if (b.dataset.active !== 'true') b.style.color = P.text; });
- b.addEventListener('mouseleave', () => { if (b.dataset.active !== 'true') b.style.color = P.textDim; });
- b.addEventListener('click', onClick);
- b._expandLabel = expand;
- b._collapseLabel = collapse;
- return b;
- }
-
- // Pick toggle — starts active (primary intent when entering live mode).
- const pickBtn = makeIconBtn({
- id: PREFIX + '-pick-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',
- label: 'Pick',
- ariaLabel: 'Pick element',
- onClick: () => togglePick(),
- });
- pickBtn.style.background = P.accentSoft;
- pickBtn.style.color = P.accent;
- pickBtn.dataset.active = 'true';
- pickBtn._expandLabel();
- inner.appendChild(pickBtn);
-
- // Detect toggle
- const detectBtn = makeIconBtn({
- id: PREFIX + '-detect-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',
- label: 'Detect',
- ariaLabel: 'Detect anti-patterns',
- onClick: () => toggleDetect(),
- });
- const detectBadge = el('span', {
- fontSize: '10px', fontWeight: '600',
- padding: '0px 5px', borderRadius: '7px', lineHeight: '16px',
- background: P.accent, color: P.surface.includes('18%') ? 'oklch(18% 0 0)' : 'oklch(98% 0 0)',
- display: 'none', fontFamily: MONO, marginLeft: '4px',
- });
- detectBadge.id = PREFIX + '-detect-badge';
- detectBtn.appendChild(detectBadge);
- inner.appendChild(detectBtn);
-
- // DESIGN.md panel toggle — quartet of color squares as the mark.
- const designBtn = makeIconBtn({
- id: PREFIX + '-design-toggle',
- svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px ${P.hairline};flex-shrink:0">
- <span style="background:oklch(60% 0.25 350)"></span>
- <span style="background:oklch(60% 0.15 45)"></span>
- <span style="background:oklch(55% 0.12 250)"></span>
- <span style="background:oklch(30% 0 0)"></span>
- </span>`,
- label: 'DESIGN.md',
- ariaLabel: 'Toggle DESIGN.md panel',
- labelFont: MONO,
- onClick: () => toggleDesignPanel(),
- });
- inner.appendChild(designBtn);
-
- // Thin divider before the exit button
- const divider = el('span', {
- width: '1px', height: '18px',
- background: P.hairline,
- margin: '0 4px 0 2px',
- });
- inner.appendChild(divider);
-
- // Exit × on the right — intentionally subtle (textDim at rest, text on
- // hover) so it sits behind the active toggles in visual hierarchy.
- //
- // Explicit padding + box-sizing here is load-bearing: a host page like
- // `button { padding: 0.5rem 1rem; }` (very common in resets) would
- // otherwise inflate this 24x24 button into 56x40 and push the SVG out
- // of the visible bar — the X stays invisible even though the styles in
- // DevTools look fine. Every other chrome button sets padding inline;
- // this one needed it too.
- const exitBtn = el('button', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- padding: '0', boxSizing: 'border-box',
- width: '24px', height: '24px', borderRadius: '6px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
- cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
- });
- exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
- exitBtn.title = 'Exit live mode';
- exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
- exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
- exitBtn.addEventListener('click', () => { sendEvent({ type: 'exit' }); teardown(); });
- inner.appendChild(exitBtn);
-
- // Bar-level hover: expand every toggle's label at once; collapse on leave.
- // Buttons with dataset.active="true" ignore collapse (their label stays).
- const toggles = [pickBtn, detectBtn, designBtn];
- globalBarEl.addEventListener('mouseenter', () => {
- toggles.forEach((t) => t._expandLabel && t._expandLabel());
- });
- globalBarEl.addEventListener('mouseleave', () => {
- toggles.forEach((t) => t._collapseLabel && t._collapseLabel());
- });
-
- document.body.appendChild(globalBarEl);
- defangOutsideHandlers(globalBarEl);
-
- requestAnimationFrame(() => {
- globalBarEl.style.opacity = '1';
- globalBarEl.style.transform = 'translateX(-50%) translateY(0)';
- });
-
- // Listen for detection results AND ready signal
- window.addEventListener('message', onDetectMessage);
- }
-
- function updateGlobalBarState() {
- const detectToggle = document.getElementById(PREFIX + '-detect-toggle');
- const detectBadge = document.getElementById(PREFIX + '-detect-badge');
- const pickToggle = document.getElementById(PREFIX + '-pick-toggle');
- const designToggle = document.getElementById(PREFIX + '-design-toggle');
- const theme = globalBarEl?.dataset.theme || 'light';
- const P = barPaletteForTheme(theme);
-
- // Sync one toggle's active state, colors, and slide-label visibility.
- function sync(btn, active) {
- if (!btn) return;
- btn.style.background = active ? P.accentSoft : 'transparent';
- btn.style.color = active ? P.accent : P.textDim;
- btn.dataset.active = active ? 'true' : 'false';
- if (active && btn._expandLabel) btn._expandLabel();
- else if (!active && btn._collapseLabel) btn._collapseLabel();
- }
- sync(pickToggle, pickActive);
- sync(detectToggle, detectActive);
- sync(designToggle, designState.open);
-
- // If the bar is currently under the cursor, keep all labels expanded —
- // otherwise clicking a toggle that deactivates (e.g. closing DESIGN.md)
- // would collapse its label while the user's mouse is still on the bar.
- if (globalBarEl && globalBarEl.matches(':hover')) {
- [pickToggle, detectToggle, designToggle].forEach((t) => t?._expandLabel?.());
- }
-
- if (detectBadge) {
- detectBadge.style.display = (detectActive && detectCount > 0) ? 'inline' : 'none';
- detectBadge.textContent = detectCount;
- }
-
- // When pick is active, make detect overlays click-through so the picker works
- document.querySelectorAll('.impeccable-overlay').forEach(o => {
- o.style.pointerEvents = pickActive ? 'none' : '';
- });
- }
-
- let detectReady = false; // true once detect script posts 'impeccable-ready'
- let detectPendingScan = false; // scan requested before script was ready
-
- function toggleDetect() {
- detectActive = !detectActive;
- updateGlobalBarState();
-
- if (detectActive) {
- if (!detectScriptLoaded) {
- detectPendingScan = true;
- loadDetectScript();
- } else if (detectReady) {
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- } else {
- detectPendingScan = true;
- }
- } else {
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- detectCount = 0;
- updateGlobalBarState();
- }
- }
-
- function togglePick() {
- pickActive = !pickActive;
- updateGlobalBarState();
-
- if (!pickActive) {
- // Disabling pick clears any in-flight selection and UI: highlight,
- // contextual bar, selectedElement. Otherwise a stale selection sits
- // on screen with no obvious way to dismiss.
- hideHighlight();
- hideBar();
- hideActionPicker();
- selectedElement = null;
- if (state === 'PICKING' || state === 'CONFIGURING') state = 'IDLE';
- } else {
- if (state === 'IDLE') state = 'PICKING';
- }
- }
-
- function loadDetectScript() {
- if (detectScriptLoaded) return;
- detectScriptLoaded = true;
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/detect.js';
- s.dataset.impeccableExtension = 'true';
- document.head.appendChild(s);
- }
-
- function onDetectMessage(e) {
- if (!e.data || typeof e.data.source !== 'string') return;
- // Detection script is loaded and ready
- if (e.data.source === 'impeccable-ready') {
- detectReady = true;
- if (detectPendingScan && detectActive) {
- detectPendingScan = false;
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- }
- }
- // Scan results arrived
- if (e.data.source === 'impeccable-results') {
- detectCount = e.data.count || 0;
- updateGlobalBarState();
- }
- }
-
- /** Full teardown: remove all UI, disconnect SSE, clean up. */
- function teardown() {
- cleanup();
- hideBar();
- if (globalBarEl) {
- globalBarEl.style.transform = 'translateY(100%)';
- setTimeout(() => { if (globalBarEl) globalBarEl.remove(); globalBarEl = null; }, 300);
- }
- if (highlightEl) { highlightEl.remove(); highlightEl = null; }
- if (tooltipEl) { tooltipEl.remove(); tooltipEl = null; }
- if (barEl) { barEl.remove(); barEl = null; }
- if (pickerEl) { pickerEl.remove(); pickerEl = null; }
- if (paramsPanelEl) { paramsPanelEl.remove(); paramsPanelEl = null; paramsPanelInner = null; paramsPanelBody = null; }
- if (evtSource) { evtSource.close(); evtSource = null; }
- document.removeEventListener('mousemove', handleMouseMove, true);
- document.removeEventListener('click', handleClick, true);
- document.removeEventListener('keydown', handleKeyDown, true);
- window.removeEventListener('message', onDetectMessage);
- // Remove detection overlays
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- state = 'IDLE';
- window.__IMPECCABLE_LIVE_INIT__ = false;
- console.log('[impeccable] Live mode exited.');
- }
-
- // ---------------------------------------------------------------------------
- // Design System Panel — visualizes the project's .impeccable/design.json sidecar
- // ---------------------------------------------------------------------------
-
- const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';
- const DESIGN_PANEL_WIDTH = 440;
-
- let designHost = null;
- let designShadow = null;
- let designState = {
- open: false,
- tab: 'visual', // 'visual' | 'raw'
- parsed: null, // parseDesignMd output (frontmatter + body sections)
- sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)
- hasMd: false,
- hasSidecar: false,
- present: null, // true/false once fetch resolves
- raw: null, // raw DESIGN.md for the raw tab
- mdNewerThanJson: false, // stale-hint flag
- loading: false,
- error: null,
- collapsed: { // narrative-section accordion state
- rules: true, dosdonts: true, overview: true,
- },
- };
-
- function loadDesignPrefs() {
- // `open` is intentionally NOT persisted — the panel always starts closed
- // so live mode doesn't auto-slide a big panel over the page on startup.
- try {
- const raw = localStorage.getItem(DESIGN_PREFS_KEY);
- if (!raw) return;
- const prefs = JSON.parse(raw);
- if (prefs.tab === 'visual' || prefs.tab === 'raw') designState.tab = prefs.tab;
- if (prefs.collapsed && typeof prefs.collapsed === 'object') {
- Object.assign(designState.collapsed, prefs.collapsed);
- }
- } catch { /* ignore */ }
- }
-
- function saveDesignPrefs() {
- try {
- localStorage.setItem(DESIGN_PREFS_KEY, JSON.stringify({
- tab: designState.tab,
- collapsed: designState.collapsed,
- }));
- } catch { /* ignore */ }
- }
-
- function initDesignPanel() {
- designHost = document.createElement('div');
- designHost.id = PREFIX + '-design-host';
- Object.assign(designHost.style, {
- position: 'fixed', top: '0', left: '0',
- width: '0', height: '0',
- zIndex: String(Z.bar + 10),
- pointerEvents: 'none',
- });
- designShadow = designHost.attachShadow({ mode: 'open' });
-
- const style = document.createElement('style');
- // Theme-match the bar: dark chrome on light pages, light chrome on dark pages.
- const theme = detectPageTheme();
- style.textContent = designPanelCss(barPaletteForTheme(theme));
- designShadow.appendChild(style);
-
- const root = document.createElement('div');
- root.className = 'root';
- designShadow.appendChild(root);
-
- document.body.appendChild(designHost);
- // The host is pointer-events: none; the panel inside the shadow DOM
- // manages its own auto/none. Events bubble through the shadow boundary,
- // so attaching here silences host-page outside-interaction handlers
- // without touching the host's click-through behavior.
- defangOutsideHandlers(designHost, { setPointerEvents: false });
-
- loadDesignPrefs();
- renderDesignChrome();
- if (designState.open) {
- fetchDesignSystem();
- }
- }
-
- // Neutral panel palette — deliberately NOT Impeccable-branded. The panel is
- // a viewer of the project's design system, not an Impeccable surface.
- const DP = {
- canvas: 'oklch(94% 0 0)', // panel background
- tile: 'oklch(98.5% 0 0)', // card-on-canvas
- tileAlt: 'oklch(96% 0 0)', // subtler tile for inner surfaces
- ink: 'oklch(15% 0 0)',
- ink2: 'oklch(35% 0 0)',
- meta: 'oklch(55% 0 0)',
- hairline: 'oklch(88% 0 0)',
- hairlineSoft: 'oklch(92% 0 0)',
- amber: 'oklch(70% 0.13 65)', // stale-hint accent
- amberBg: 'oklch(95% 0.05 80)',
- };
-
- function designPanelCss(BP) {
- // BP = bar palette (theme-aware, matches the global bar).
- // DP = internal content palette (neutral, so tiles render colors true).
- return `
- :host, .root { all: initial; }
- .root {
- font-family: ${FONT};
- color: ${DP.ink};
- pointer-events: none;
- }
- .root * { box-sizing: border-box; }
- button { font: inherit; color: inherit; }
-
- /* --- Panel shell: chrome matches the bar; body canvas stays neutral --- */
- .panel {
- position: fixed; top: 12px; bottom: 72px; right: 12px;
- width: ${DESIGN_PANEL_WIDTH}px; max-width: calc(100vw - 24px);
- background: ${BP.surface};
- border: 1px solid ${BP.hairline};
- border-radius: 14px;
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- box-shadow: 0 20px 60px oklch(0% 0 0 / 0.18), 0 4px 12px oklch(0% 0 0 / 0.08);
- display: flex; flex-direction: column;
- transform: translateX(calc(100% + 24px));
- opacity: 0;
- transition: transform 0.35s ${EASE}, opacity 0.25s ${EASE};
- pointer-events: none;
- overflow: hidden;
- }
- .panel[data-open="true"] { transform: translateX(0); opacity: 1; pointer-events: auto; }
-
- .panel-header {
- display: flex; align-items: center; gap: 10px;
- padding: 10px 10px 10px 14px;
- background: transparent;
- border-bottom: 1px solid ${BP.hairline};
- }
- .panel-title {
- flex: 1; min-width: 0;
- font-family: ${MONO};
- font-size: 11.5px; font-weight: 600;
- letter-spacing: 0.02em;
- color: ${BP.text};
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
- }
- .panel-close {
- border: none; background: transparent; color: ${BP.textDim};
- width: 26px; height: 26px; border-radius: 7px;
- display: inline-flex; align-items: center; justify-content: center;
- cursor: pointer; transition: background 0.15s ease, color 0.15s ease;
- }
- .panel-close:hover { background: ${BP.hairline}; color: ${BP.text}; }
-
- .tabs {
- display: inline-flex; padding: 2px;
- background: ${BP.hairline};
- border-radius: 7px;
- gap: 2px;
- }
- .tab {
- border: none; background: transparent;
- padding: 4px 10px; border-radius: 5px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 600; letter-spacing: 0.08em;
- text-transform: uppercase;
- color: ${BP.textDim}; cursor: pointer;
- transition: background 0.15s ease, color 0.15s ease;
- }
- .tab[data-active="true"] { background: ${BP.surface}; color: ${BP.text}; }
-
- .panel-body {
- flex: 1; overflow-y: auto;
- padding: 12px 12px 20px;
- background: ${DP.canvas};
- scrollbar-width: thin;
- scrollbar-color: ${DP.hairline} transparent;
- }
- .panel-body::-webkit-scrollbar { width: 8px; }
- .panel-body::-webkit-scrollbar-thumb { background: ${DP.hairline}; border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
-
- /* --- States --- */
- .empty, .loading, .error {
- margin: 16px 4px;
- padding: 28px 20px; text-align: center;
- background: ${DP.tile}; border-radius: 14px;
- color: ${DP.ink2}; font-size: 13px; line-height: 1.55;
- }
- .empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
- .empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
- .error { color: oklch(45% 0.15 25); }
-
- /* --- Stale hint --- */
- .stale {
- display: flex; align-items: center; gap: 8px;
- margin: 8px 4px 12px;
- padding: 8px 12px;
- background: ${DP.amberBg};
- border-radius: 10px;
- font-size: 11.5px; color: ${DP.ink2};
- }
- .stale-dot { width: 8px; height: 8px; border-radius: 50%; background: ${DP.amber}; flex-shrink: 0; }
- .stale-text { flex: 1; min-width: 0; }
- .stale-text strong { color: ${DP.ink}; font-weight: 600; }
-
- /* --- Parsed-md fallback banner --- */
- .parsed-md-cta {
- margin: 8px 4px 14px;
- padding: 14px 16px;
- background: ${DP.tile};
- border: 1px dashed ${DP.hairline};
- border-radius: 12px;
- font-size: 12px; color: ${DP.ink2}; line-height: 1.55;
- }
- .parsed-md-cta strong { color: ${DP.ink}; display: block; margin-bottom: 4px; font-size: 13px; font-weight: 600; }
- .parsed-md-cta code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; font-size: 11.5px; color: ${DP.ink}; }
-
- /* --- Tile primitives --- */
- .tile {
- position: relative;
- background: ${DP.tile};
- border-radius: 16px;
- padding: 16px;
- margin: 0 4px 10px;
- }
- .tile-row { margin: 0 4px 10px; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
- .tile-row .tile { margin: 0; }
- .tile-meta {
- display: flex; align-items: baseline; justify-content: space-between;
- gap: 10px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase;
- color: ${DP.meta};
- }
- .tile-meta .name { color: ${DP.ink}; font-weight: 600; letter-spacing: 0.05em; text-transform: none; font-family: ${FONT}; font-size: 12.5px; }
-
- /* --- Color tile --- */
- .c-tile { cursor: pointer; transition: transform 0.2s ${EASE}; }
- .c-tile:hover { transform: translateY(-1px); }
- .c-hero {
- height: 72px; border-radius: 10px; margin-top: 10px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.05);
- }
- .c-ramp {
- display: flex; gap: 0; height: 14px; border-radius: 4px; overflow: hidden;
- margin-top: 8px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.04);
- }
- .c-ramp > span { flex: 1; }
- .c-desc { margin-top: 8px; font-size: 11.5px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Type tile --- */
- .t-tile { }
- .t-specimen {
- margin: 4px 0 6px;
- color: ${DP.ink};
- line-height: 0.9;
- }
- .t-family { margin-top: 4px; font-size: 12px; font-weight: 600; color: ${DP.ink}; }
- .t-purpose { margin-top: 4px; font-size: 11px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Shadow tile --- */
- .s-tile { }
- .s-surface {
- height: 60px; margin: 8px 2px 10px;
- background: ${DP.tile};
- border-radius: 10px;
- }
- .s-value { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; word-break: break-all; line-height: 1.4; }
- .s-purpose { margin-top: 4px; font-size: 11px; color: ${DP.ink2}; line-height: 1.45; }
-
- /* --- Radii strip --- */
- .r-strip { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
- .r-item { display: flex; flex-direction: column; align-items: center; gap: 4px; flex: 1; min-width: 60px; }
- .r-sample { width: 44px; height: 44px; background: ${DP.canvas}; box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.08); }
- .r-label { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; text-transform: uppercase; }
- .r-val { font-family: ${MONO}; font-size: 10px; color: ${DP.ink}; }
-
- /* --- Component tile (hosts live primitives) --- */
- .cmp-tile { }
- .cmp-stage {
- margin: 12px -4px 0;
- padding: 18px 16px 10px;
- border-top: 1px solid ${DP.hairlineSoft};
- display: flex; flex-direction: column; align-items: center; justify-content: center;
- gap: 14px;
- min-height: 68px;
- }
- .cmp-stage + .cmp-stage { border-top: 1px dashed ${DP.hairlineSoft}; }
- .cmp-sublabel { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.06em; }
- .cmp-kind { font-family: ${MONO}; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; }
-
- /* --- Collapsible --- */
- .coll {
- margin: 0 4px 8px;
- background: ${DP.tile};
- border-radius: 12px;
- overflow: hidden;
- }
- .coll-head {
- display: flex; align-items: center; gap: 10px;
- width: 100%;
- padding: 12px 14px;
- background: transparent; border: none;
- cursor: pointer; text-align: left;
- font-family: ${FONT}; font-size: 12.5px; font-weight: 600; color: ${DP.ink};
- transition: background 0.12s ease;
- }
- .coll-head:hover { background: ${DP.tileAlt}; }
- .coll-chev {
- width: 12px; height: 12px; flex-shrink: 0;
- color: ${DP.meta};
- transition: transform 0.2s ${EASE};
- }
- .coll[data-open="true"] .coll-chev { transform: rotate(90deg); }
- .coll-count { margin-left: auto; font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; }
- .coll-body { padding: 0 14px 14px; display: none; }
- .coll[data-open="true"] .coll-body { display: block; }
-
- .rule-card {
- padding: 10px 0;
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .rule-card:first-child { border-top: none; padding-top: 2px; }
- .rule-card .name { font-size: 11.5px; font-weight: 700; color: ${DP.ink}; margin-bottom: 3px; }
- .rule-card .name .section { font-family: ${MONO}; font-size: 9px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; margin-left: 8px; }
- .rule-card .body { font-size: 11.5px; color: ${DP.ink2}; line-height: 1.5; }
-
- .coll .dos { display: grid; gap: 0; margin-top: 2px; }
- .coll .do, .coll .dont {
- position: relative;
- padding: 8px 0 8px 22px;
- font-size: 11.5px; line-height: 1.5; color: ${DP.ink2};
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .coll .do:first-child, .coll .dont:first-child,
- .coll .do:first-of-type { border-top: none; }
- .coll .do + .dont { border-top: 1px solid ${DP.hairlineSoft}; }
- .coll .do::before, .coll .dont::before {
- content: ''; position: absolute; left: 4px; top: 13px;
- width: 8px; height: 8px; border-radius: 50%;
- }
- .coll .do::before { background: oklch(62% 0.16 145); }
- .coll .dont::before { background: oklch(58% 0.22 25); }
-
- .coll .overview-body {
- font-size: 12px; line-height: 1.55; color: ${DP.ink2};
- }
- .coll .overview-body .north-star {
- display: block; font-family: ${FONT}; font-style: italic;
- font-size: 15px; line-height: 1.3; color: ${DP.ink};
- margin-bottom: 8px;
- }
- .coll .overview-body p { margin: 0 0 8px; }
- .coll .overview-body ul { margin: 6px 0 0; padding-left: 16px; font-size: 11.5px; }
- .coll .overview-body li { margin-bottom: 3px; }
-
- /* --- raw tab markdown (unchanged layout, neutralized palette) --- */
- .md { padding: 4px 10px 20px; font-size: 13px; line-height: 1.6; color: ${DP.ink}; }
- .md h1, .md h2, .md h3, .md h4 { margin: 20px 0 8px; color: ${DP.ink}; font-weight: 600; }
- .md h1 { font-size: 18px; }
- .md h2 { font-size: 15px; padding-bottom: 4px; border-bottom: 1px solid ${DP.hairlineSoft}; }
- .md h3 { font-size: 13px; }
- .md h4 { font-size: 12px; color: ${DP.meta}; }
- .md p { margin: 0 0 10px; }
- .md ul, .md ol { margin: 0 0 10px; padding-left: 20px; }
- .md li { margin-bottom: 4px; }
- .md code { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; }
- .md pre { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 10px 12px; border-radius: 8px; overflow-x: auto; margin: 0 0 10px; }
- .md pre code { background: none; padding: 0; }
- .md strong { font-weight: 700; }
- .md em { font-style: italic; }
- .md a { color: ${DP.ink}; text-decoration: underline; }
- .md hr { border: none; border-top: 1px solid ${DP.hairlineSoft}; margin: 16px 0; }
- `;
- }
-
- function renderDesignChrome() {
- const root = designShadow.querySelector('.root');
- root.innerHTML = '';
-
- // (Panel toggle lives in the global bar — no floating FAB.)
- // Panel
- const panel = document.createElement('aside');
- panel.className = 'panel';
- panel.setAttribute('data-open', designState.open ? 'true' : 'false');
- panel.appendChild(buildDesignHeader());
- const body = document.createElement('div');
- body.className = 'panel-body';
- body.id = 'panel-body';
- panel.appendChild(body);
- root.appendChild(panel);
-
- renderDesignBody();
- }
-
- function buildDesignHeader() {
- const header = document.createElement('div');
- header.className = 'panel-header';
-
- const title = document.createElement('div');
- title.className = 'panel-title';
- title.textContent = 'DESIGN.md';
- header.appendChild(title);
-
- const tabs = document.createElement('div');
- tabs.className = 'tabs';
- for (const t of [['visual', 'Visual'], ['raw', 'Raw']]) {
- const btn = document.createElement('button');
- btn.className = 'tab';
- btn.textContent = t[1];
- btn.setAttribute('data-active', designState.tab === t[0] ? 'true' : 'false');
- btn.addEventListener('click', () => {
- if (designState.tab === t[0]) return;
- designState.tab = t[0];
- saveDesignPrefs();
- renderDesignChrome();
- if (t[0] === 'raw' && designState.raw === null && !designState.loading) {
- fetchDesignSystem(); // raw is part of the same fetch pair
- }
- });
- tabs.appendChild(btn);
- }
- header.appendChild(tabs);
-
- const close = document.createElement('button');
- close.className = 'panel-close';
- close.innerHTML = '✕';
- close.setAttribute('aria-label', 'Close panel');
- close.addEventListener('click', toggleDesignPanel);
- header.appendChild(close);
-
- return header;
- }
-
- function toggleDesignPanel() {
- designState.open = !designState.open;
- renderDesignChrome();
- updateGlobalBarState();
- if (designState.open && designState.present === null && !designState.loading) {
- fetchDesignSystem();
- }
- }
-
- async function fetchDesignSystem() {
- designState.loading = true;
- designState.error = null;
- renderDesignBody();
- try {
- const [jsonRes, rawRes] = await Promise.all([
- fetch(`http://localhost:${PORT}/design-system.json?token=${TOKEN}`, { cache: 'no-store' }),
- fetch(`http://localhost:${PORT}/design-system/raw?token=${TOKEN}`, { cache: 'no-store' }),
- ]);
- const jsonData = await jsonRes.json();
- designState.present = jsonData.present === true;
- designState.parsed = jsonData.parsed || null;
- designState.sidecar = jsonData.sidecar || null;
- designState.hasMd = !!jsonData.hasMd;
- designState.hasSidecar = !!jsonData.hasSidecar;
- designState.mdNewerThanJson = !!jsonData.mdNewerThanJson;
- designState.raw = designState.present && rawRes.ok ? await rawRes.text() : null;
- designState.error = jsonData.parseError || jsonData.sidecarError || null;
- } catch (err) {
- designState.error = err?.message || 'Failed to load design system.';
- } finally {
- designState.loading = false;
- renderDesignChrome(); // refresh title from data
- }
- }
-
- function renderDesignBody() {
- const body = designShadow.querySelector('#panel-body');
- if (!body) return;
- body.innerHTML = '';
-
- if (designState.loading) {
- body.appendChild(msgDiv('loading', 'Loading design system…'));
- return;
- }
- if (designState.error) {
- body.appendChild(msgDiv('error', designState.error));
- return;
- }
- if (designState.present === false) {
- const empty = document.createElement('div');
- empty.className = 'empty';
- empty.innerHTML = `<strong>No DESIGN.md yet</strong>Create one by running <code>/impeccable document</code> in your terminal, then re-open this panel.`;
- body.appendChild(empty);
- return;
- }
-
- if (designState.tab === 'raw') {
- renderRawTab(body, designState.raw || '');
- return;
- }
-
- // Visual tab — single unified render path.
- if (designState.mdNewerThanJson) body.appendChild(renderStaleHint());
- if (designState.hasMd && !designState.hasSidecar) {
- body.appendChild(renderParsedMdCta());
- }
- renderDesignVisual(body, designState.parsed, designState.sidecar);
- }
-
- function msgDiv(cls, text) {
- const d = document.createElement('div');
- d.className = cls;
- d.textContent = text;
- return d;
- }
-
- function renderStaleHint() {
- const box = document.createElement('div');
- box.className = 'stale';
- box.innerHTML = `
- <span class="stale-dot"></span>
- <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>
- `;
- return box;
- }
-
- function renderParsedMdCta() {
- const box = document.createElement('div');
- box.className = 'parsed-md-cta';
- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;
- return box;
- }
-
- // --- Unified render: merge parsed DESIGN.md frontmatter with sidecar v2 ---
-
- function renderDesignVisual(body, parsed, sidecar) {
- const frontmatter = parsed?.frontmatter || {};
- const extensions = sidecar?.extensions || {};
- const proseColors = parsed?.colors || null;
-
- const colors = buildColorModels(frontmatter.colors, extensions.colorMeta, proseColors);
- if (colors.length) renderColorTiles(body, colors);
-
- const types = buildTypographyModels(frontmatter.typography, extensions.typographyMeta);
- if (types.length) renderTypeTiles(body, types);
-
- const radii = buildRadiiModels(frontmatter.rounded);
- if (radii.length) renderRadiiTile(body, radii);
-
- if (extensions.shadows?.length) renderShadowTiles(body, extensions.shadows);
-
- const components = sidecar?.components || [];
- if (components.length) renderComponentTiles(body, components);
-
- // Narrative: sidecar wins if present (richer, agent-curated). Otherwise
- // synthesize from prose sections.
- const narrative = sidecar?.narrative || synthesizeNarrative(parsed);
- if (narrative.rules?.length) body.appendChild(renderRulesCollapsible(narrative.rules));
- if ((narrative.dos?.length || narrative.donts?.length)) body.appendChild(renderDosDontsCollapsible(narrative));
- if (narrative.overview || narrative.northStar || narrative.keyCharacteristics?.length) {
- body.appendChild(renderOverviewCollapsible(narrative));
- }
-
- if (body.childElementCount === 0) {
- body.appendChild(msgDiv('empty', 'No design system data available.'));
- }
- }
-
- // Frontmatter primitives + sidecar colorMeta → tile-ready color models.
- // A matching prose bullet (when the slug sits in the bullet text) supplies
- // description as a last-resort fallback.
- function buildColorModels(fmColors, colorMeta, proseColors) {
- if (!fmColors) return [];
- const meta = colorMeta || {};
- return Object.entries(fmColors).map(([key, value]) => {
- const m = meta[key] || {};
- return {
- role: m.role || humanizeKey(key),
- name: m.displayName || humanizeKey(key),
- value: value,
- canonical: m.canonical || null,
- description: m.description || findProseDescription(proseColors, key, m.displayName),
- tonalRamp: m.tonalRamp || null,
- };
- });
- }
-
- function buildTypographyModels(fmTypography, typographyMeta) {
- if (!fmTypography) return [];
- const meta = typographyMeta || {};
- return Object.entries(fmTypography).map(([key, spec]) => {
- const m = meta[key] || {};
- const { family, fallback } = splitFontFamily(spec?.fontFamily);
- return {
- role: key,
- name: m.displayName || humanizeKey(key),
- family,
- fallback,
- weight: spec?.fontWeight ?? 400,
- // fontStyle isn't in Stitch's frontmatter schema; the sidecar carries
- // it when a role is rendered in italic (e.g. display italic).
- style: m.style || 'normal',
- sampleSize: spec?.fontSize || '1rem',
- lineHeight: spec?.lineHeight != null ? String(spec.lineHeight) : '',
- letterSpacing: spec?.letterSpacing,
- purpose: m.purpose,
- };
- });
- }
-
- function buildRadiiModels(fmRounded) {
- if (!fmRounded) return [];
- return Object.entries(fmRounded).map(([name, value]) => ({ name, value }));
- }
-
- function splitFontFamily(stack) {
- if (!stack || typeof stack !== 'string') return { family: '', fallback: '' };
- const parts = stack.split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, ''));
- return { family: parts[0] || '', fallback: parts.slice(1).join(', ') };
- }
-
- function humanizeKey(k) {
- return String(k || '').replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
- }
-
- function findProseDescription(proseColors, key, displayName) {
- if (!proseColors || !proseColors.groups) return null;
- const needles = [key, displayName].filter(Boolean).map((s) => s.toLowerCase());
- for (const g of proseColors.groups) {
- for (const c of g.colors || []) {
- const hay = String(c.name || '').toLowerCase();
- if (hay && needles.some((n) => hay.includes(n) || n.includes(hay))) {
- return c.description || null;
- }
- }
- }
- return null;
- }
-
- function synthesizeNarrative(parsed) {
- if (!parsed) return {};
- const md = parsed;
- return {
- northStar: md.overview?.creativeNorthStar,
- overview: (md.overview?.philosophy || []).join(' '),
- keyCharacteristics: md.overview?.keyCharacteristics || [],
- rules: [
- ...(md.colors?.rules || []).map((r) => ({ ...r, section: 'colors' })),
- ...(md.typography?.rules || []).map((r) => ({ ...r, section: 'typography' })),
- ...(md.elevation?.rules || []).map((r) => ({ ...r, section: 'elevation' })),
- ],
- dos: md.dosDonts?.dos || [],
- donts: md.dosDonts?.donts || [],
- };
- }
-
- function renderColorTiles(body, colors) {
- for (const c of colors) {
- const tile = document.createElement('div');
- tile.className = 'tile c-tile';
- tile.title = 'Click to copy';
- tile.addEventListener('click', () => copyToClipboard(c.value));
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(c.name || c.role || 'Color')}</span><span>${escapeHtml(c.value || '')}</span>`;
- tile.appendChild(meta);
-
- const hero = document.createElement('div');
- hero.className = 'c-hero';
- hero.style.background = c.value;
- tile.appendChild(hero);
-
- const ramp = synthesizeRamp(c);
- if (ramp.length) {
- const r = document.createElement('div');
- r.className = 'c-ramp';
- r.innerHTML = ramp.map((v) => `<span style="background:${cssSafe(v)}"></span>`).join('');
- tile.appendChild(r);
- }
-
- if (c.description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = c.description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function synthesizeRamp(c) {
- if (c.tonalRamp?.length) return c.tonalRamp;
- // If base value is OKLCH, synthesize an 8-step ramp across lightness.
- const m = typeof c.value === 'string' && c.value.match(/^oklch\(\s*([\d.]+)%\s+([\d.]+)\s+([\d.]+)\s*(?:\/\s*([\d.]+))?\s*\)$/i);
- if (!m) return [];
- const [, , chroma, hue] = m;
- const steps = [20, 32, 44, 56, 68, 80, 90, 96];
- return steps.map((l) => `oklch(${l}% ${chroma} ${hue})`);
- }
-
- function renderTypeTiles(body, types) {
- for (const t of types) {
- const tile = document.createElement('div');
- tile.className = 'tile t-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span>${escapeHtml(t.role || '')}</span><span>${escapeHtml(t.weight || '')} ${escapeHtml(t.style === 'italic' ? 'italic' : '')}</span>`;
- tile.appendChild(meta);
-
- const specimen = document.createElement('div');
- specimen.className = 't-specimen';
- specimen.textContent = 'Aa';
- specimen.style.fontFamily = fontStack(t);
- specimen.style.fontWeight = String(t.weight || 400);
- specimen.style.fontStyle = t.style || 'normal';
- specimen.style.fontSize = '56px'; // Fixed specimen size — compare faces, not scales.
- specimen.style.letterSpacing = 'normal';
- specimen.style.textTransform = 'none';
- tile.appendChild(specimen);
-
- // The system's actual sample size for this role, shown as small mono meta below.
- if (t.sampleSize) {
- const scale = document.createElement('div');
- scale.style.cssText = 'font-family:' + MONO + '; font-size: 10px; color:' + DP.meta + '; margin-top: 2px;';
- scale.textContent = t.sampleSize;
- tile.appendChild(scale);
- }
-
- const family = document.createElement('div');
- family.className = 't-family';
- family.textContent = t.family || t.name || '';
- tile.appendChild(family);
-
- if (t.purpose) {
- const p = document.createElement('div');
- p.className = 't-purpose';
- p.textContent = t.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function fontStack(t) {
- const fam = t.family || '';
- const fb = t.fallback || '';
- if (fam && /[,\s]/.test(fam) && !fam.includes("'") && !fam.includes('"')) {
- return `"${fam}", ${fb}`;
- }
- return fam && fb ? `"${fam}", ${fb}` : (fam || fb);
- }
-
- function renderRadiiTile(body, radii) {
- const tile = document.createElement('div');
- tile.className = 'tile';
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">Corner Radii</span><span>${radii.length}</span>`;
- tile.appendChild(meta);
-
- const strip = document.createElement('div');
- strip.className = 'r-strip';
- for (const r of radii) {
- const item = document.createElement('div');
- item.className = 'r-item';
- const s = document.createElement('div');
- s.className = 'r-sample';
- s.style.borderRadius = r.value || '0';
- item.appendChild(s);
- const lbl = document.createElement('div');
- lbl.className = 'r-label';
- lbl.textContent = r.name || '';
- item.appendChild(lbl);
- const val = document.createElement('div');
- val.className = 'r-val';
- val.textContent = r.value || '';
- item.appendChild(val);
- strip.appendChild(item);
- }
- tile.appendChild(strip);
- body.appendChild(tile);
- }
-
- function renderShadowTiles(body, shadows) {
- for (const sh of shadows) {
- const tile = document.createElement('div');
- tile.className = 'tile s-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(sh.name || 'Shadow')}</span><span>Elevation</span>`;
- tile.appendChild(meta);
-
- const surface = document.createElement('div');
- surface.className = 's-surface';
- surface.style.boxShadow = sh.value || 'none';
- tile.appendChild(surface);
-
- const val = document.createElement('div');
- val.className = 's-value';
- val.textContent = sh.value || '';
- tile.appendChild(val);
-
- if (sh.purpose) {
- const p = document.createElement('div');
- p.className = 's-purpose';
- p.textContent = sh.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function renderComponentTiles(body, components) {
- // Group consecutive components that share a kind into one tile. This avoids
- // a pile of one-component tiles (e.g., three button variants = three tiles)
- // and reads more like a proper category.
- const groups = groupByKind(components);
-
- for (const group of groups) {
- const tile = document.createElement('div');
- tile.className = 'tile cmp-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- const groupTitle = group.length === 1
- ? (group[0].name || group[0].kind || 'Component')
- : titleForKind(group[0].kind, group.length);
- meta.innerHTML = `<span class="name">${escapeHtml(groupTitle)}</span><span class="cmp-kind">${escapeHtml(group[0].kind || '')}</span>`;
- tile.appendChild(meta);
-
- for (const c of group) {
- const stage = document.createElement('div');
- stage.className = 'cmp-stage';
-
- // Render the component in its own shadow root so its CSS can't bleed.
- const host = document.createElement('div');
- const sub = host.attachShadow({ mode: 'open' });
- const style = document.createElement('style');
- style.textContent = c.css || '';
- sub.appendChild(style);
- const container = document.createElement('div');
- container.innerHTML = c.html || '';
- sub.appendChild(container);
- stage.appendChild(host);
-
- // Show component name as a sublabel only when the tile groups >1 item,
- // or when the component's display name differs from its kind.
- const showSublabel = group.length > 1;
- if (showSublabel) {
- const lbl = document.createElement('div');
- lbl.className = 'cmp-sublabel';
- lbl.textContent = c.name || '';
- stage.appendChild(lbl);
- }
- tile.appendChild(stage);
- }
-
- // Single shared description if all items carry the same one; otherwise
- // skip — per-item descriptions clutter a grouped tile.
- if (group.length === 1 && group[0].description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = group[0].description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function groupByKind(components) {
- const groups = [];
- for (const c of components) {
- const last = groups[groups.length - 1];
- if (last && last[0].kind && c.kind === last[0].kind) {
- last.push(c);
- } else {
- groups.push([c]);
- }
- }
- return groups;
- }
-
- function titleForKind(kind, count) {
- const labels = {
- button: 'Buttons',
- input: 'Inputs',
- nav: 'Navigation',
- chip: 'Chips',
- card: 'Cards',
- custom: 'Components',
- };
- return labels[kind] || (kind ? kind.charAt(0).toUpperCase() + kind.slice(1) + 's' : 'Components');
- }
-
- // --- Collapsibles ---------------------------------------------------------
-
- function buildCollapsible(key, label, count) {
- const wrap = document.createElement('div');
- wrap.className = 'coll';
- wrap.setAttribute('data-open', designState.collapsed[key] ? 'false' : 'true');
-
- const head = document.createElement('button');
- head.className = 'coll-head';
- head.innerHTML = `
- <svg class="coll-chev" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 2.5L8 6 4 9.5"/></svg>
- <span>${escapeHtml(label)}</span>
- ${count != null ? `<span class="coll-count">${escapeHtml(String(count))}</span>` : ''}
- `;
- head.addEventListener('click', () => {
- designState.collapsed[key] = !designState.collapsed[key];
- saveDesignPrefs();
- renderDesignBody();
- });
- wrap.appendChild(head);
-
- const body = document.createElement('div');
- body.className = 'coll-body';
- wrap.appendChild(body);
- return { wrap, body };
- }
-
- function renderRulesCollapsible(rules) {
- const { wrap, body } = buildCollapsible('rules', 'Named Rules', rules.length);
- for (const r of rules) {
- const card = document.createElement('div');
- card.className = 'rule-card';
- const name = document.createElement('div');
- name.className = 'name';
- name.innerHTML = `${escapeHtml(r.name)}${r.section ? `<span class="section">${escapeHtml(r.section)}</span>` : ''}`;
- card.appendChild(name);
- const b = document.createElement('div');
- b.className = 'body';
- b.textContent = r.body || '';
- card.appendChild(b);
- body.appendChild(card);
- }
- return wrap;
- }
-
- function renderDosDontsCollapsible(n) {
- const total = (n.dos?.length || 0) + (n.donts?.length || 0);
- const { wrap, body } = buildCollapsible('dosdonts', "Do's and Don'ts", total);
- const grid = document.createElement('div');
- grid.className = 'dos';
- for (const d of n.dos || []) {
- const el = document.createElement('div');
- el.className = 'do';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- for (const d of n.donts || []) {
- const el = document.createElement('div');
- el.className = 'dont';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- body.appendChild(grid);
- return wrap;
- }
-
- function renderOverviewCollapsible(n) {
- const { wrap, body } = buildCollapsible('overview', 'Overview', null);
- const ov = document.createElement('div');
- ov.className = 'overview-body';
- if (n.northStar) {
- const star = document.createElement('span');
- star.className = 'north-star';
- star.textContent = '“' + n.northStar + '”';
- ov.appendChild(star);
- }
- if (n.overview) {
- const p = document.createElement('p');
- p.innerHTML = inlineMd(n.overview);
- ov.appendChild(p);
- }
- if (n.keyCharacteristics?.length) {
- const ul = document.createElement('ul');
- ul.innerHTML = n.keyCharacteristics.map((k) => `<li>${inlineMd(k)}</li>`).join('');
- ov.appendChild(ul);
- }
- body.appendChild(ov);
- return wrap;
- }
-
- function cssSafe(v) {
- // Strip anything outside valid CSS value chars to prevent injection via
- // .impeccable/design.json values rendered into inline style strings.
- return String(v).replace(/[<>"'`\n]/g, '');
- }
-
- // --- Raw tab: minimal markdown renderer (subset) --------------------------
-
- function renderRawTab(body, md) {
- const wrap = document.createElement('div');
- wrap.className = 'md';
- wrap.innerHTML = renderMarkdown(md);
- body.appendChild(wrap);
- }
-
- function renderMarkdown(md) {
- const lines = md.split(/\r?\n/);
- const out = [];
- let i = 0;
- let inCode = false;
- let codeBuf = [];
- let paraBuf = [];
- let listBuf = []; // array of { indent, html }
- let listType = null; // 'ul' | 'ol'
-
- const flushPara = () => {
- if (paraBuf.length) {
- out.push(`<p>${inlineMd(paraBuf.join(' '))}</p>`);
- paraBuf = [];
- }
- };
- const flushList = () => {
- if (listBuf.length) {
- out.push(buildListHtml(listBuf, listType));
- listBuf = [];
- listType = null;
- }
- };
- const flushAll = () => { flushPara(); flushList(); };
-
- for (; i < lines.length; i++) {
- const line = lines[i];
-
- // Code fence
- const fence = line.match(/^```(\w*)\s*$/);
- if (fence) {
- if (!inCode) { flushAll(); inCode = true; codeBuf = []; }
- else {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- inCode = false;
- }
- continue;
- }
- if (inCode) { codeBuf.push(line); continue; }
-
- if (line.trim() === '') { flushAll(); continue; }
-
- const hr = line.match(/^\s*(?:---+|\*\*\*+)\s*$/);
- if (hr) { flushAll(); out.push('<hr />'); continue; }
-
- const heading = line.match(/^(#{1,4})\s+(.+)$/);
- if (heading) {
- flushAll();
- const lvl = heading[1].length;
- out.push(`<h${lvl}>${inlineMd(heading[2])}</h${lvl}>`);
- continue;
- }
-
- const bullet = line.match(/^(\s*)([-*])\s+(.+)$/);
- const ordered = line.match(/^(\s*)(\d+)\.\s+(.+)$/);
- if (bullet || ordered) {
- flushPara();
- const m = bullet || ordered;
- const indent = Math.floor(m[1].length / 2);
- const t = bullet ? 'ul' : 'ol';
- if (listType && listType !== t) flushList();
- listType = t;
- listBuf.push({ indent, html: inlineMd(m[3]) });
- continue;
- }
-
- paraBuf.push(line);
- }
- flushAll();
- if (inCode && codeBuf.length) {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- }
- return out.join('\n');
- }
-
- function buildListHtml(items, type) {
- // Nest by indent (one level deep is plenty for DESIGN.md).
- let html = `<${type}>`;
- let lastIndent = 0;
- for (const it of items) {
- if (it.indent > lastIndent) html += `<${type}>`;
- else if (it.indent < lastIndent) html += `</${type}>`.repeat(lastIndent - it.indent);
- html += `<li>${it.html}</li>`;
- lastIndent = it.indent;
- }
- html += `</${type}>`.repeat(lastIndent + 1);
- return html;
- }
-
- function inlineMd(text) {
- // Order matters: escape first, then re-inject tags.
- let s = escapeHtml(text);
- // Code spans
- s = s.replace(/`([^`]+)`/g, (_, code) => `<code>${code}</code>`);
- // Links [text](url)
- s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, t, u) => `<a href="${u}" target="_blank" rel="noopener noreferrer">${t}</a>`);
- // Bold
- s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
- // Italic (only single *…*, skip if inside bold already handled)
- s = s.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em>$2</em>');
- return s;
- }
-
- function highlightBold(text) {
- return inlineMd(text);
- }
-
- function escapeHtml(s) {
- return String(s)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
-
- function copyToClipboard(text) {
- if (!text) return;
- try {
- navigator.clipboard.writeText(text);
- showToast('Copied: ' + text);
- } catch { /* ignore */ }
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- function init() {
- try { history.scrollRestoration = 'manual'; } catch {}
- initHighlight();
- initAnnotOverlay();
- initBar();
- initActionPicker();
- initParamsPanel();
- initGlobalBar();
- initDesignPanel();
- document.addEventListener('mousemove', handleMouseMove, true);
- document.addEventListener('click', handleClick, true);
- document.addEventListener('keydown', handleKeyDown, true);
- connectSSE();
-
- // Check for an active session to resume (variant wrapper already in DOM after HMR)
- if (!resumeSession()) {
- console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
- // SvelteKit (and any framework that hydrates after HTML parse) may add
- // the variant wrapper AFTER init runs. Watch for it and retry resume
- // once it appears. Disconnect on first hit.
- const scout = new MutationObserver(() => {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) return;
- scout.disconnect();
- if (resumeSession()) {
- console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
- }
- });
- scout.observe(document.body, { childList: true, subtree: true });
- } else {
- console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
- }
- }
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
- } else {
- init();
- }
-})();
@@ -1,75 +0,0 @@
-#!/usr/bin/env node
-/**
- * Canonical durable completion acknowledgement for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function parseArgs(argv) {
- const out = { status: 'complete' };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';
- else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }
- else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function completeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help || !args.id) {
- console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);
- process.exit(args.help ? 0 : 1);
- }
-
- const serverInfo = readServerInfo();
- const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;
- if (serverResult?.ok) {
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const snapshot = store.getSnapshot(args.id, { includeCompleted: true });
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const event = args.status === 'discarded'
- ? { type: 'discarded', id: args.id }
- : args.status === 'agent_error'
- ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }
- : { type: 'complete', id: args.id };
- const snapshot = store.appendEvent(event);
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));
-}
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function completeThroughServer(info, args) {
- const type = args.status === 'discarded'
- ? 'discarded'
- : args.status === 'agent_error'
- ? 'error'
- : 'complete';
- try {
- const res = await fetch(`http://localhost:${info.port}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),
- });
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {
- completeCli();
-}
@@ -1,18 +0,0 @@
-export function completionTypeForAcceptResult(eventType, acceptResult) {
- if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';
- if (acceptResult?.handled === true) return 'complete';
- if (acceptResult?.mode === 'error') return 'error';
- return 'agent_done';
-}
-
-export function completionAckForAcceptResult(eventId, completionType, acceptResult) {
- const ack = { ok: true, type: completionType };
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) {
- ack.final = false;
- ack.requiresComplete = true;
- ack.nextCommand = `live-complete.mjs --id ${eventId}`;
- ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';
- }
- return ack;
-}
@@ -1,446 +0,0 @@
-/**
- * CLI helper: insert/remove the live variant mode script tag in the project's
- * main HTML entry point.
- *
- * On first live run, the agent generates `.impeccable/live/config.json`
- * with the project's insertion target (framework-specific). On
- * every subsequent run, this script handles insert/remove deterministically
- * with zero LLM involvement.
- *
- * Usage:
- * node live-inject.mjs --port PORT # Insert the live script tag
- * node live-inject.mjs --remove # Remove the live script tag
- * node live-inject.mjs --check # Check whether live config exists
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { resolveLiveConfigPath } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });
-const MARKER_OPEN_TEXT = 'impeccable-live-start';
-const MARKER_CLOSE_TEXT = 'impeccable-live-end';
-
-/**
- * Hard-excluded directory patterns. These are NEVER user-facing pages and
- * matching them would silently inject tracking scripts into third-party
- * code. The user cannot turn these off via config — they are the floor.
- */
-const HARD_EXCLUDES = [
- '**/node_modules/**',
- '**/.git/**',
-];
-
-export async function injectCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-inject.mjs [options]
-
-Insert or remove the live mode script tag in the project's HTML entry point.
-Reads configuration from .impeccable/live/config.json.
-
-Modes:
- --port PORT Insert script tag pointing at http://localhost:PORT/live.js
- --remove Remove the script tag (if present)
- --check Print whether .impeccable/live/config.json exists and its content
-
-Output (JSON):
- { ok, file, inserted|removed, config? }`);
- process.exit(0);
- }
-
- if (args.includes('--check')) {
- if (!fs.existsSync(CONFIG_PATH)) {
- console.log(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(0);
- }
- let cfg;
- try {
- cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- try {
- validateConfig(cfg);
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- console.log(JSON.stringify({ ok: true, config: cfg, path: CONFIG_PATH }));
- return;
- }
-
- // Load config
- if (!fs.existsSync(CONFIG_PATH)) {
- console.error(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(1);
- }
- const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- validateConfig(config);
-
- const resolvedFiles = resolveFiles(process.cwd(), config);
-
- if (args.includes('--remove')) {
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const detagged = removeTag(content, config.commentSyntax);
- const updated = revertCspMeta(detagged);
- if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- removed: detagged !== content,
- cspReverted: updated !== detagged,
- };
- });
- console.log(JSON.stringify({ ok: true, results }));
- return;
- }
-
- // Insert mode — need --port
- const portIdx = args.indexOf('--port');
- const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : NaN;
- if (!Number.isFinite(port)) {
- console.error(JSON.stringify({ ok: false, error: 'missing_port' }));
- process.exit(1);
- }
-
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
- const withTag = insertTag(withoutOld, config, port);
- if (withTag === withoutOld) {
- return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
- }
- const updated = patchCspMeta(withTag, port);
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- inserted: true,
- cspPatched: updated !== withTag,
- };
- });
- const anyInserted = results.some((r) => r.inserted);
- console.log(JSON.stringify({ ok: anyInserted, port, results }));
- if (!anyInserted) process.exit(1);
-}
-
-/**
- * Expand config.files (which may contain glob patterns) into a literal list
- * of existing file paths relative to rootDir. Literal entries pass through;
- * glob patterns are expanded via fs.globSync. HARD_EXCLUDES and config.exclude
- * are applied as filters. Duplicates are removed. Order is preserved by
- * first appearance.
- */
-export function resolveFiles(rootDir, config) {
- const patterns = config.files;
- const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
- const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
- const excludeRegexes = allExcludes.map(globToRegex);
-
- const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
- const isGlob = (s) => /[*?[]/.test(s);
-
- const seen = new Set();
- const out = [];
- for (const pat of patterns) {
- if (!isGlob(pat)) {
- // Literal path — include even if it doesn't exist yet; the caller
- // reports file_not_found per-entry. Exclude list doesn't apply to
- // explicit literal entries (user named it on purpose).
- if (!seen.has(pat)) {
- seen.add(pat);
- out.push(pat);
- }
- continue;
- }
- let matches;
- try {
- matches = fs.globSync(pat, { cwd: rootDir, withFileTypes: true });
- } catch {
- continue;
- }
- for (const ent of matches) {
- if (!ent.isFile || !ent.isFile()) continue;
- const abs = path.join(ent.parentPath || ent.path || rootDir, ent.name);
- const rel = path.relative(rootDir, abs).split(path.sep).join('/');
- if (isExcluded(rel)) continue;
- if (seen.has(rel)) continue;
- seen.add(rel);
- out.push(rel);
- }
- }
- return out;
-}
-
-/**
- * Convert a glob pattern to a RegExp. Supports:
- * ** → any number of path segments (including zero)
- * * → any chars except `/`
- * ? → any single char except `/`
- * Paths are normalized to forward slashes before matching.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- // ** — any number of segments, including zero. Handle the common
- // **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
- if (pattern[i + 2] === '/') {
- re += '(?:.*/)?';
- i += 3;
- } else {
- re += '.*';
- i += 2;
- }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Core operations
-// ---------------------------------------------------------------------------
-
-function validateConfig(cfg) {
- if (!cfg || typeof cfg !== 'object') throw new Error('config.json must be an object');
- if (!Array.isArray(cfg.files) || cfg.files.length === 0) {
- throw new Error('config.files (non-empty string array) required');
- }
- if (!cfg.files.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.files must contain only non-empty strings');
- }
- if (cfg.exclude !== undefined) {
- if (!Array.isArray(cfg.exclude)) {
- throw new Error('config.exclude, if present, must be a string array');
- }
- if (!cfg.exclude.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.exclude must contain only non-empty strings');
- }
- }
- if (typeof cfg.insertBefore !== 'string' && typeof cfg.insertAfter !== 'string') {
- throw new Error('config.insertBefore or config.insertAfter (string) required');
- }
- if (cfg.commentSyntax !== 'html' && cfg.commentSyntax !== 'jsx') {
- throw new Error("config.commentSyntax must be 'html' or 'jsx'");
- }
- if (cfg.cspChecked !== undefined && typeof cfg.cspChecked !== 'boolean') {
- throw new Error("config.cspChecked, if present, must be a boolean");
- }
-}
-
-function commentOpen(syntax) { return syntax === 'jsx' ? '{/*' : '<!--'; }
-function commentClose(syntax) { return syntax === 'jsx' ? '*/}' : '-->'; }
-
-function buildTagBlock(syntax, port) {
- const open = commentOpen(syntax);
- const close = commentClose(syntax);
- return (
- open + ' ' + MARKER_OPEN_TEXT + ' ' + close + '\n' +
- '<script src="http://localhost:' + port + '/live.js"></script>\n' +
- open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n'
- );
-}
-
-function insertTag(content, config, port) {
- const block = buildTagBlock(config.commentSyntax, port);
- // insertBefore: match the LAST occurrence. Anchors like `</body>` naturally
- // belong at the end, and the same literal can appear earlier in code blocks
- // within rendered documentation pages.
- if (config.insertBefore) {
- const idx = content.lastIndexOf(config.insertBefore);
- if (idx === -1) return content;
- return content.slice(0, idx) + block + content.slice(idx);
- }
- // insertAfter: match the FIRST occurrence — typical anchors like `<head>` or
- // `<body>` open near the top of the document.
- const idx = content.indexOf(config.insertAfter);
- if (idx === -1) return content;
- const after = idx + config.insertAfter.length;
- // Preserve a single trailing newline if the anchor didn't end with one
- const prefix = content[after] === '\n' ? content.slice(0, after + 1) : content.slice(0, after) + '\n';
- return prefix + block + content.slice(prefix.length);
-}
-
-/**
- * Remove the live script block. Matches either HTML or JSX comment markers
- * regardless of config (so stale tags from a wrong config can still be cleaned).
- *
- * Indent-preserving: captures any whitespace immediately preceding the opener
- * marker and re-emits it in place of the removed block. `insertTag` inserted
- * the block *after* the original line's indent and *before* the anchor (e.g.
- * `</body>`), which moved the indent onto the opener line and left the anchor
- * unindented. Replacing the whole block (plus its trailing newline) with just
- * the captured indent hands the indent back to the anchor that follows.
- */
-function removeTag(content, _syntax) {
- const patterns = [
- /([ \t]*)<!--\s*impeccable-live-start\s*-->[\s\S]*?<!--\s*impeccable-live-end\s*-->[ \t]*\n/,
- /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}[ \t]*\n/,
- ];
- for (const pat of patterns) {
- const next = content.replace(pat, '$1');
- if (next !== content) return next;
- }
- return content;
-}
-
-// ---------------------------------------------------------------------------
-// Content-Security-Policy meta-tag patcher
-//
-// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
-// the cross-origin load of /live.js (and the SSE/POST connection back to
-// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
-//
-// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
-// and stash the original `content` value in a `data-impeccable-csp-original`
-// attribute (base64) so revert is exact.
-//
-// On remove: detect the marker attribute, decode it, restore the original
-// content value verbatim, drop the marker.
-//
-// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
-// shared helpers) is NOT patched here — those need framework-specific config
-// edits and are handled via the existing detect-csp.mjs reference output.
-// Only the in-source meta-tag form gets the auto-patch.
-// ---------------------------------------------------------------------------
-
-const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
-
-function findCspMetaTags(content) {
- const out = [];
- const tagRe = /<meta\s+([^>]*?)\/?>/gis;
- let m;
- while ((m = tagRe.exec(content)) !== null) {
- const attrs = m[1];
- if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
- out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
- }
- return out;
-}
-
-function getAttr(attrs, name) {
- const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
- const m = attrs.match(re);
- return m ? { quote: m[1], value: m[2], full: m[0] } : null;
-}
-
-function appendOriginToDirective(csp, directive, origin) {
- const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
- const m = csp.match(re);
- if (m) {
- const tokens = m[4].trim().split(/\s+/);
- if (tokens.includes(origin)) return csp;
- return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
- }
- // Directive missing — add it. Use 'self' + origin so we don't inadvertently
- // narrow the policy compared to the default-src fallback (most users with
- // an explicit CSP have 'self' there).
- return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
-}
-
-export function patchCspMeta(content, port) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
- const origin = `http://localhost:${port}`;
-
- // Walk last-to-first so prior splices don't invalidate later indices.
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const attrs = tag.attrs;
- if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
- const contentAttr = getAttr(attrs, 'content');
- if (!contentAttr) continue;
-
- const original = contentAttr.value;
- let patched = original;
- patched = appendOriginToDirective(patched, 'script-src', origin);
- patched = appendOriginToDirective(patched, 'connect-src', origin);
- // The shader overlay during 'generating' creates a screenshot via
- // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
- // those. Add `blob:` so the overlay doesn't throw a CSP violation.
- patched = appendOriginToDirective(patched, 'img-src', 'blob:');
- if (patched === original) continue;
-
- const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
- const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
- // The tagRe captures any whitespace between the last attribute and the
- // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
- // a replace would land it BEFORE that trailing space, leaving a double
- // space inside attrs and clobbering the space before `/>`. Split off
- // the trailing whitespace, splice the marker into the attribute body,
- // and re-append the original trailing whitespace so a self-closing
- // `<meta … />` round-trips byte-for-byte.
- const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
- const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
- const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
- const newTag = tag.full.replace(attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-export function revertCspMeta(content) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
-
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
- if (!origAttr) continue;
- const contentAttr = getAttr(tag.attrs, 'content');
- if (!contentAttr) continue;
-
- let originalValue;
- try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
- catch { continue; }
-
- const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
- let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
- // Drop the marker attribute and any single space immediately preceding it.
- newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
- const newTag = tag.full.replace(tag.attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
- injectCli();
-}
-
-export { insertTag, removeTag, validateConfig, buildTagBlock };
-// patchCspMeta + revertCspMeta are exported above where they're defined.
@@ -1,200 +0,0 @@
-/**
- * CLI client for the live variant mode poll/reply protocol.
- *
- * Usage:
- * npx impeccable poll # Block until browser event, print JSON
- * npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
- * npx impeccable poll --reply <id> done # Reply "done" to event <id>
- * npx impeccable poll --reply <id> error "msg" # Reply with error
- */
-
-import { execFileSync } from 'node:child_process';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-// Node's built-in fetch (undici under the hood) enforces a 300s headers
-// timeout that can't be lowered per-request. We cap each request below
-// that ceiling and loop in `pollOnce` to synthesize a long poll without
-// depending on the standalone undici package.
-const PER_REQUEST_TIMEOUT_MS = 270_000;
-
-function readServerInfo() {
- const record = readLiveServerInfo(process.cwd());
- if (!record) {
- console.error('No running live server found. Start one with: npx impeccable live');
- process.exit(1);
- }
- return record.info;
-}
-
-export function buildPollReplyPayload(token, { id, type, message, file, data }) {
- return { token, id, type, message, file, data };
-}
-
-async function postReply(base, token, reply) {
- const res = await fetch(`${base}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(buildPollReplyPayload(token, reply)),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error || res.statusText);
- }
-}
-
-export async function pollCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable poll [options]
-
-Wait for a browser event from the live variant server, or reply to one.
-
-Modes:
- poll Block until a browser event arrives, print JSON
- poll --reply <id> done Reply "done" to event <id>
- poll --reply <id> error "msg" Reply with an error message
-
-Options:
- --timeout=MS Long-poll timeout in ms (default: 600000). Use the default unless the user asked to pause live; never use a short timeout to end the chat turn
- --help Show this help message`);
- process.exit(0);
- }
-
- const info = readServerInfo();
- const base = `http://localhost:${info.port}`;
-
- // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
- const replyIdx = args.indexOf('--reply');
- if (replyIdx !== -1) {
- const id = args[replyIdx + 1];
- const status = args[replyIdx + 2] || 'done';
- const fileIdx = args.indexOf('--file');
- const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
- // Message is any remaining positional arg that isn't a flag
- const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
-
- if (!id) {
- console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
- process.exit(1);
- }
-
- try {
- await postReply(base, info.token, { id, type: status, message, file: filePath });
-
- // Success — silent exit (agent doesn't need output for replies)
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Reply failed:', err.message);
- }
- process.exit(1);
- }
- return;
- }
-
- // Poll mode: block until browser event. Default 10 min. Node's built-in
- // fetch enforces a 300s headers timeout, so we loop in slices under that
- // ceiling and keep re-polling until we get a real event or the user's
- // total timeout runs out.
- const timeoutArg = args.find(a => a.startsWith('--timeout='));
- const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600000;
-
- const deadline = Date.now() + totalTimeout;
- let event;
- try {
- while (true) {
- const remaining = deadline - Date.now();
- if (remaining <= 0) {
- event = { type: 'timeout' };
- break;
- }
- const slice = Math.min(remaining, PER_REQUEST_TIMEOUT_MS);
- const res = await fetch(`${base}/poll?token=${info.token}&timeout=${slice}`);
-
- if (res.status === 401) {
- console.error('Authentication failed. The server token may have changed.');
- console.error('Try restarting: npx impeccable live stop && npx impeccable live');
- process.exit(1);
- }
-
- if (!res.ok) {
- console.error(`Poll failed: ${res.status} ${res.statusText}`);
- process.exit(1);
- }
-
- const next = await res.json();
- // Server-side timeout means no browser event arrived in this slice.
- // Loop and re-poll until we get a real event or we hit the user's
- // total deadline.
- if (next?.type === 'timeout' && Date.now() < deadline) continue;
- event = next;
- break;
- }
-
- // Auto-handle accept/discard via deterministic script
- if (event.type === 'accept' || event.type === 'discard') {
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const acceptScript = path.join(__dirname, 'live-accept.mjs');
- const scriptArgs = event.type === 'discard'
- ? ['--id', event.id, '--discard']
- : ['--id', event.id, '--variant', event.variantId];
- if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
- scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
- }
- try {
- const out = execFileSync(
- 'node',
- [acceptScript, ...scriptArgs],
- { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 }
- );
- event._acceptResult = JSON.parse(out.trim());
- } catch (err) {
- event._acceptResult = { handled: false, mode: 'error', error: err.message };
- }
-
- const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
- try {
- await postReply(base, info.token, {
- id: event.id,
- type: completionType,
- message: event._acceptResult?.error,
- file: event._acceptResult?.file,
- data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
- });
- } catch (err) {
- event._completionAck = { ok: false, error: err.message };
- }
- if (!event._completionAck) {
- event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
- }
- }
-
- // Second signal path: stderr banner in case the agent parses stdout
- // JSON but skips nested fields. One line is enough — the full checklist
- // is in reference/live.md.
- if (event._acceptResult?.carbonize === true) {
- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
- }
-
- // Print the event as JSON — the agent reads this from stdout
- console.log(JSON.stringify(event));
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Poll failed:', err.message);
- }
- process.exit(1);
- }
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
- pollCli();
-}
@@ -1,48 +0,0 @@
-#!/usr/bin/env node
-/**
- * Recover the next agent action from the durable live-session journal.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-
-function parseArgs(argv) {
- const out = { id: null };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function resumeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help) {
- console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });
- const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;
- if (!snapshot) {
- console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));
- return;
- }
-
- const pending = snapshot.pendingEvent || null;
- const nextAction = pending
- ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`
- : snapshot.phase === 'carbonize_required'
- ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`
- : snapshot.phase === 'accept_requested'
- ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`
- : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;
-
- console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {
- resumeCli();
-}
@@ -1,838 +0,0 @@
-#!/usr/bin/env node
-/**
- * Live variant mode server (self-contained, zero dependencies).
- *
- * Serves the browser script (/live.js), the detection overlay (/detect.js),
- * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
- * browser→server events. Agent communicates via HTTP long-poll (/poll).
- *
- * Usage:
- * node <scripts_path>/live-server.mjs # start
- * node <scripts_path>/live-server.mjs stop # stop + remove injected live.js tag
- * node <scripts_path>/live-server.mjs stop --keep-inject # stop only
- * node <scripts_path>/live-server.mjs --help
- */
-
-import http from 'node:http';
-import { randomUUID } from 'node:crypto';
-import { spawn, execFileSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import net from 'node:net';
-import { fileURLToPath } from 'node:url';
-import { parseDesignMd } from './design-parser.mjs';
-import { resolveContextDir } from './load-context.mjs';
-import { createLiveSessionStore } from './live-session-store.mjs';
-import {
- getDesignSidecarPath,
- getLiveAnnotationsDir,
- readLiveServerInfo,
- removeLiveServerInfo,
- resolveDesignSidecarPath,
- writeLiveServerInfo,
-} from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated
-// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
-// DESIGN.json fallback for existing projects.
-const CONTEXT_DIR = resolveContextDir(process.cwd());
-const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anyway
-const SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s
-
-// ---------------------------------------------------------------------------
-// Port detection
-// ---------------------------------------------------------------------------
-
-async function findOpenPort(start = 8400) {
- return new Promise((resolve) => {
- const srv = net.createServer();
- srv.listen(start, '127.0.0.1', () => {
- const port = srv.address().port;
- srv.close(() => resolve(port));
- });
- srv.on('error', () => resolve(findOpenPort(start + 1)));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Session state
-// ---------------------------------------------------------------------------
-
-const state = {
- token: null,
- port: null,
- sseClients: new Set(), // SSE response objects (server→browser push)
- pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
- pendingPolls: [], // agent poll callbacks waiting for browser events
- exitTimer: null,
- sessionDir: null, // per-session tmp dir for annotation screenshots
- sessionStore: null,
- leaseTimer: null,
-};
-
-// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;
-// cap at 10 MB to guard against runaway writes from a misbehaving client.
-const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
-
-function enqueueEvent(event) {
- if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;
- state.pendingEvents.push({ event, leaseUntil: 0 });
- flushPendingPolls();
-}
-
-function restorePendingEventsFromStore() {
- if (!state.sessionStore) return;
- for (const snapshot of state.sessionStore.listActiveSessions()) {
- if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);
- }
-}
-
-function findAvailablePendingEvent(now = Date.now()) {
- return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);
-}
-
-function leaseEvent(entry, leaseMs) {
- if (!entry.event?.id) {
- const idx = state.pendingEvents.indexOf(entry);
- if (idx !== -1) state.pendingEvents.splice(idx, 1);
- return entry.event;
- }
- entry.leaseUntil = Date.now() + leaseMs;
- return entry.event;
-}
-
-function acknowledgePendingEvent(id) {
- if (!id) return false;
- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);
- if (idx === -1) return false;
- state.pendingEvents.splice(idx, 1);
- scheduleLeaseFlush();
- return true;
-}
-
-function scheduleLeaseFlush() {
- if (state.leaseTimer) {
- clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- }
- if (state.pendingPolls.length === 0) return;
- const now = Date.now();
- const nextLeaseUntil = state.pendingEvents
- .map((entry) => entry.leaseUntil || 0)
- .filter((leaseUntil) => leaseUntil > now)
- .sort((a, b) => a - b)[0];
- if (!nextLeaseUntil) return;
- state.leaseTimer = setTimeout(() => {
- state.leaseTimer = null;
- flushPendingPolls();
- }, Math.max(0, nextLeaseUntil - now));
-}
-
-function flushPendingPolls() {
- while (state.pendingPolls.length > 0) {
- const entry = findAvailablePendingEvent();
- if (!entry) {
- scheduleLeaseFlush();
- return;
- }
- const poll = state.pendingPolls.shift();
- poll.resolve(leaseEvent(entry, poll.leaseMs));
- }
- scheduleLeaseFlush();
-}
-
-/** Push a message to all connected SSE clients. */
-function broadcast(msg) {
- const data = 'data: ' + JSON.stringify(msg) + '\n\n';
- for (const res of state.sseClients) {
- try { res.write(data); } catch { /* client gone */ }
- }
-}
-
-// ---------------------------------------------------------------------------
-// Load scripts
-// ---------------------------------------------------------------------------
-
-function loadBrowserScripts() {
- // Detection script: prefer the skill-bundled detector, then fall back to
- // source/npm package locations for local development and older installs.
- // This one IS cached — detect.js rarely changes during a session.
- const detectPaths = [
- path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(process.cwd(), 'node_modules', 'impeccable', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- ];
- let detectScript = '';
- for (const p of detectPaths) {
- try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
- }
-
- // live-browser.js: DO NOT cache. Return the path so the /live.js handler
- // can re-read on every request. Editing the browser script during iteration
- // should land on the next tab reload, not require a server restart.
- const sessionPath = path.join(__dirname, 'live-browser-session.js');
- const livePath = path.join(__dirname, 'live-browser.js');
- for (const p of [sessionPath, livePath]) {
- if (!fs.existsSync(p)) {
- process.stderr.write('Error: live browser script not found at ' + p + '\n');
- process.exit(1);
- }
- }
-
- return { detectScript, sessionPath, livePath };
-}
-
-function hasProjectContext() {
- // PRODUCT.md carries brand voice / anti-references — that's what determines
- // whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
- // concern, surfaced by the design panel's own empty state. Legacy
- // .impeccable.md is auto-migrated to PRODUCT.md by load-context.mjs.
- try {
- fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
- return true;
- } catch { return false; }
-}
-
-function statOrNull(filePath) {
- try { return fs.statSync(filePath); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// Validation (inline — no external import needed for self-contained script)
-// ---------------------------------------------------------------------------
-
-const VISUAL_ACTIONS = [
- 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
- 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
-];
-
-// Browser generates ids via crypto.randomUUID().slice(0, 8) (8 hex chars)
-// and variantIds via String(small integer). Restrict to those shapes so
-// any value that reaches a downstream child_process or DOM selector is
-// inert by construction.
-const ID_PATTERN = /^[0-9a-f]{8}$/;
-const VARIANT_ID_PATTERN = /^[0-9]{1,3}$/;
-
-function isValidId(v) { return typeof v === 'string' && ID_PATTERN.test(v); }
-function isValidVariantId(v) { return typeof v === 'string' && VARIANT_ID_PATTERN.test(v); }
-
-function validateEvent(msg) {
- if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
- switch (msg.type) {
- case 'generate':
- if (!isValidId(msg.id)) return 'generate: missing or malformed id';
- if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
- if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
- if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
- // Optional annotation fields (all-or-nothing: if any present, all must be well-formed).
- if (msg.screenshotPath !== undefined && typeof msg.screenshotPath !== 'string') return 'generate: screenshotPath must be string';
- if (msg.comments !== undefined && !Array.isArray(msg.comments)) return 'generate: comments must be array';
- if (msg.strokes !== undefined && !Array.isArray(msg.strokes)) return 'generate: strokes must be array';
- return null;
- case 'accept':
- if (!isValidId(msg.id)) return 'accept: missing or malformed id';
- if (!isValidVariantId(msg.variantId)) return 'accept: missing or malformed variantId';
- if (msg.paramValues !== undefined) {
- if (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues)) {
- return 'accept: paramValues must be an object';
- }
- }
- return null;
- case 'discard':
- return isValidId(msg.id) ? null : 'discard: missing or malformed id';
- case 'checkpoint':
- if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';
- if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';
- if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {
- return 'checkpoint: paramValues must be an object';
- }
- return null;
- case 'exit':
- return null;
- case 'prefetch':
- if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return 'prefetch: missing pageUrl';
- return null;
- default:
- return 'Unknown event type: ' + msg.type;
- }
-}
-
-// ---------------------------------------------------------------------------
-// HTTP request handler
-// ---------------------------------------------------------------------------
-
-function createRequestHandler({ detectScript, sessionPath, livePath }) {
- return (req, res) => {
- const url = new URL(req.url, `http://localhost:${state.port}`);
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
- if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
-
- const p = url.pathname;
-
- // --- Scripts ---
- if (p === '/live.js') {
- // Re-read from disk each request so edits to live-browser.js land on
- // the next tab reload. No-store headers prevent browser caching across
- // sessions — during iteration, a cached old script silently breaks
- // every subsequent session.
- let sessionScript;
- let liveScript;
- try {
- sessionScript = fs.readFileSync(sessionPath, 'utf-8');
- liveScript = fs.readFileSync(livePath, 'utf-8');
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'text/plain' });
- res.end('Error reading live browser scripts: ' + err.message);
- return;
- }
- const body =
- `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
- `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
- sessionScript + '\n' +
- liveScript;
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
- 'Pragma': 'no-cache',
- });
- res.end(body);
- return;
- }
- if (p === '/detect.js' || p === '/') {
- if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
- res.writeHead(200, { 'Content-Type': 'application/javascript' });
- res.end(detectScript);
- return;
- }
-
- // --- Vendored modern-screenshot (UMD build) ---
- // Lazy-loaded by live.js when the user clicks Go; exposes
- // window.modernScreenshot.domToBlob(...) for capture.
- if (p === '/modern-screenshot.js') {
- const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
- try {
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'public, max-age=31536000, immutable',
- });
- res.end(fs.readFileSync(vendorPath));
- } catch {
- res.writeHead(404); res.end('Vendor script not found');
- }
- return;
- }
-
- // --- Annotation upload (browser → server, raw PNG body) ---
- // Client generates the eventId, POSTs the PNG, then POSTs the generate
- // event with screenshotPath already set. Keeps bytes out of the SSE/poll
- // bridge and preserves the "one shot from the user's POV" UX.
- if (p === '/annotation' && req.method === 'POST') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const eventId = url.searchParams.get('eventId');
- if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid eventId' }));
- return;
- }
- if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
- res.writeHead(415, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
- return;
- }
- if (!state.sessionDir) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Session dir unavailable' }));
- return;
- }
- const chunks = [];
- let total = 0;
- let aborted = false;
- req.on('data', (c) => {
- if (aborted) return;
- total += c.length;
- if (total > MAX_ANNOTATION_BYTES) {
- aborted = true;
- res.writeHead(413, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Payload too large' }));
- req.destroy();
- return;
- }
- chunks.push(c);
- });
- req.on('end', () => {
- if (aborted) return;
- const absPath = path.join(state.sessionDir, eventId + '.png');
- try {
- fs.writeFileSync(absPath, Buffer.concat(chunks));
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Write failed: ' + err.message }));
- return;
- }
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true, path: absPath }));
- });
- req.on('error', () => {
- if (!aborted) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Upload failed' }));
- }
- });
- return;
- }
-
- // --- Health ---
- if (p === '/status') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
- const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok',
- port: state.port,
- connectedClients: state.sseClients.size,
- pendingEvents: state.pendingEvents.map((entry) => ({
- id: entry.event?.id,
- type: entry.event?.type,
- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),
- leaseUntil: entry.leaseUntil || null,
- })),
- activeSessions: sessions,
- }));
- return;
- }
-
- if (p === '/health') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok', port: state.port, mode: 'variant',
- hasProjectContext: hasProjectContext(),
- connectedClients: state.sseClients.size,
- }));
- return;
- }
-
- // --- Design system (unified v2 response) + raw ---
- // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json
- // sidecar when present. Panel merges them:
- // { present, parsed, sidecar, hasMd, hasSidecar,
- // mdNewerThanJson, parseError?, sidecarError? }
- // - parsed: output of parseDesignMd (frontmatter
- // + six canonical sections) when DESIGN.md exists.
- // - sidecar: .impeccable/design.json contents when present.
- // Expected shape: schemaVersion 2, carrying
- // extensions + components + narrative.
- // /design-system/raw returns DESIGN.md markdown verbatim
- if (p === '/design-system.json' || p === '/design-system/raw') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
-
- const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
- const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
- const mdStat = statOrNull(mdPath);
- const jsonStat = statOrNull(jsonPath);
-
- if (p === '/design-system/raw') {
- if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
- res.end(fs.readFileSync(mdPath, 'utf-8'));
- return;
- }
-
- if (!mdStat && !jsonStat) {
- res.writeHead(404, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ present: false }));
- return;
- }
-
- const response = {
- present: true,
- hasMd: !!mdStat,
- hasSidecar: !!jsonStat,
- mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
- };
-
- if (mdStat) {
- try {
- response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
- } catch (err) {
- response.parseError = err.message;
- }
- }
-
- if (jsonStat) {
- try {
- response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
- } catch (err) {
- response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;
- }
- }
-
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(response));
- return;
- }
-
- // --- Source file (no-HMR fallback) ---
- if (p === '/source') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const filePath = url.searchParams.get('path');
- if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
- const absPath = path.resolve(process.cwd(), filePath);
- if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
- let content;
- try { content = fs.readFileSync(absPath, 'utf-8'); }
- catch { res.writeHead(404); res.end('File not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
- res.end(content);
- return;
- }
-
- // --- SSE: server→browser push (replaces WebSocket) ---
- if (p === '/events' && req.method === 'GET') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- 'Connection': 'keep-alive',
- });
- res.write('data: ' + JSON.stringify({
- type: 'connected',
- hasProjectContext: hasProjectContext(),
- }) + '\n\n');
-
- state.sseClients.add(res);
- clearTimeout(state.exitTimer);
-
- // Keepalive: SSE comment every 30s prevents silent connection drops.
- const heartbeat = setInterval(() => {
- try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
- }, SSE_HEARTBEAT_INTERVAL);
-
- req.on('close', () => {
- clearInterval(heartbeat);
- state.sseClients.delete(res);
- if (state.sseClients.size === 0) {
- clearTimeout(state.exitTimer);
- state.exitTimer = setTimeout(() => {
- if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
- }, 8000);
- }
- });
- return;
- }
-
- // --- Browser→server events (replaces WebSocket messages) ---
- if (p === '/events' && req.method === 'POST') {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const error = validateEvent(msg);
- if (error) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error }));
- return;
- }
- if (state.sessionStore && msg.id) {
- try {
- state.sessionStore.appendEvent(msg);
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
- return;
- }
- }
- if (msg.type !== 'checkpoint') enqueueEvent(msg);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
- return;
- }
-
- // --- Stop ---
- if (p === '/stop') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.end('stopping');
- shutdown();
- return;
- }
-
- // --- Agent poll ---
- if (p === '/poll' && req.method === 'GET') {
- handlePollGet(req, res, url);
- return;
- }
- if (p === '/poll' && req.method === 'POST') {
- handlePollPost(req, res);
- return;
- }
-
- res.writeHead(404); res.end('Not found');
- };
-}
-
-// ---------------------------------------------------------------------------
-// Agent poll endpoints (unchanged from WS version)
-// ---------------------------------------------------------------------------
-
-function handlePollGet(req, res, url) {
- const token = url.searchParams.get('token');
- if (token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
- const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
- const available = findAvailablePendingEvent();
- if (available) {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(leaseEvent(available, leaseMs)));
- return;
- }
- const poll = { resolve, leaseMs };
- const timer = setTimeout(() => {
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ type: 'timeout' }));
- }, timeout);
- function resolve(event) {
- clearTimeout(timer);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(event));
- }
- state.pendingPolls.push(poll);
- scheduleLeaseFlush();
- req.on('close', () => {
- clearTimeout(timer);
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- });
-}
-
-function handlePollPost(req, res) {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- acknowledgePendingEvent(msg.id);
- if (state.sessionStore && msg.id) {
- try {
- const eventType = msg.type === 'discard' || msg.type === 'discarded'
- ? 'discarded'
- : msg.type === 'complete'
- ? 'complete'
- : msg.type === 'error'
- ? 'agent_error'
- : 'agent_done';
- state.sessionStore.appendEvent({
- type: eventType,
- id: msg.id,
- file: msg.file,
- message: msg.message,
- carbonize: msg.data?.carbonize === true,
- });
- } catch { /* keep reply path best-effort; browser still needs SSE */ }
- }
- flushPendingPolls();
- // Forward the reply to the browser via SSE
- broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Lifecycle
-// ---------------------------------------------------------------------------
-
-let httpServer = null;
-
-function shutdown() {
- removeLiveServerInfo(process.cwd());
- if (state.leaseTimer) clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- if (state.sessionDir) {
- try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}
- }
- for (const res of state.sseClients) { try { res.end(); } catch {} }
- state.sseClients.clear();
- for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });
- state.pendingPolls.length = 0;
- if (httpServer) httpServer.close();
- process.exit(0);
-}
-
-// ---------------------------------------------------------------------------
-// Main
-// ---------------------------------------------------------------------------
-
-const args = process.argv.slice(2);
-
-if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-server.mjs [options]
-
-Start the live variant mode server (zero dependencies).
-
-Commands:
- (default) Start the server (foreground)
- stop Stop the server and remove the injected live.js script tag
- stop --keep-inject Stop the server only (leave the script tag in the HTML entry)
-
-Options:
- --background Start detached, print connection JSON to stdout, then exit
- --port=PORT Use a specific port (default: auto-detect starting at 8400)
- --keep-inject Only with stop: skip live-inject.mjs --remove
- --help Show this help
-
-Endpoints:
- /live.js Browser script (element picker + variant cycling)
- /detect.js Detection overlay (backwards compatible)
- /modern-screenshot.js Vendored modern-screenshot UMD build (lazy-loaded by live.js)
- /annotation POST raw image/png to stage a variant screenshot
- /events SSE stream (server→browser) + POST (browser→server)
- /poll Long-poll for agent CLI
- /source Raw source file reader (no-HMR fallback)
- /status Durable recovery status (token-protected)
- /health Health check`);
- process.exit(0);
-}
-
-if (args.includes('stop')) {
- const keepInject = args.includes('--keep-inject');
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);
- if (res.ok) console.log(`Stopped live server on port ${info.port}.`);
- } catch {
- console.log('No running live server found.');
- }
- if (!keepInject) {
- const injectPath = path.join(__dirname, 'live-inject.mjs');
- try {
- const out = execFileSync(process.execPath, [injectPath, '--remove'], {
- encoding: 'utf-8',
- cwd: process.cwd(),
- });
- const line = out.trim().split('\n').filter(Boolean).pop();
- if (line) {
- try {
- const j = JSON.parse(line);
- if (j.removed === true) {
- console.log(`Removed live script tag from ${j.file}.`);
- }
- } catch {
- /* ignore non-JSON lines */
- }
- }
- } catch (err) {
- const detail = err.stderr?.toString?.().trim?.()
- || err.stdout?.toString?.().trim?.()
- || err.message
- || String(err);
- console.warn(`Note: could not remove live script tag (${detail.split('\n')[0]})`);
- }
- }
- process.exit(0);
-}
-
-// --background: spawn a detached child server, wait for it to be ready,
-// print the connection JSON, then exit. This keeps the startup command
-// simple (no shell backgrounding or chained commands).
-if (args.includes('--background')) {
- const childArgs = args.filter(a => a !== '--background');
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), ...childArgs], {
- detached: true,
- stdio: 'ignore',
- cwd: process.cwd(),
- });
- child.unref();
-
- // Poll for the PID file (the child writes it once the HTTP server is listening).
- const deadline = Date.now() + 10_000;
- while (Date.now() < deadline) {
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- if (info.pid !== process.pid) {
- // Output JSON so the agent can read port + token from stdout.
- console.log(JSON.stringify(info));
- process.exit(0);
- }
- } catch { /* not ready yet */ }
- await new Promise(r => setTimeout(r, 200));
- }
- console.error('Timed out waiting for live server to start.');
- process.exit(1);
-}
-
-// Check for existing session
-const existingRecord = readLiveServerInfo(process.cwd());
-if (existingRecord?.info) {
- const existing = existingRecord.info;
- try {
- process.kill(existing.pid, 0);
- console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
- console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');
- process.exit(1);
- } catch {
- try { fs.unlinkSync(existingRecord.path); } catch {}
- }
-}
-
-state.token = randomUUID();
-state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });
-restorePendingEventsFromStore();
-const portArg = args.find(a => a.startsWith('--port='));
-state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
-// Annotation screenshots live in the project root so the agent's Read tool
-// doesn't trip a per-file permission prompt. Sessioned by token so concurrent
-// projects (or quick restarts) don't collide.
-const annotRoot = getLiveAnnotationsDir(process.cwd());
-fs.mkdirSync(annotRoot, { recursive: true });
-state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));
-
-const { detectScript, sessionPath, livePath } = loadBrowserScripts();
-httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));
-
-httpServer.listen(state.port, '127.0.0.1', () => {
- writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });
- const url = `http://localhost:${state.port}`;
- console.log(`\nImpeccable live server running on ${url}`);
- console.log(`Token: ${state.token}\n`);
- console.log(`Inject: <script src="${url}/live.js"><\/script>`);
- console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
-});
-
-process.on('SIGINT', shutdown);
-process.on('SIGTERM', shutdown);
@@ -1,254 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';
-
-const COMPLETED_PHASES = new Set(['completed', 'discarded']);
-
-export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {
- const rootDir = getLiveSessionsDir(cwd);
- const legacyRootDir = getLegacyLiveSessionsDir(cwd);
- fs.mkdirSync(rootDir, { recursive: true });
- const snapshotCache = new Map();
-
- function loadCachedOrRebuild(id) {
- const cached = snapshotCache.get(id);
- if (cached) return cached;
- const journalPath = getReadableJournalPath(id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- return rebuilt;
- }
-
- function getReadableJournalPath(id) {
- const primary = getJournalPath(rootDir, id);
- if (fs.existsSync(primary)) return primary;
- const legacy = getJournalPath(legacyRootDir, id);
- if (fs.existsSync(legacy)) return legacy;
- return primary;
- }
-
- return {
- rootDir,
- legacyRootDir,
- appendEvent(event) {
- const normalized = normalizeEvent(event, sessionId);
- const journalPath = getJournalPath(rootDir, normalized.id);
- const snapshotPath = getSnapshotPath(rootDir, normalized.id);
- const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);
- if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {
- fs.copyFileSync(legacyJournalPath, journalPath);
- }
- const prior = loadCachedOrRebuild(normalized.id);
- const seq = prior.nextSeq;
- const entry = {
- seq,
- id: normalized.id,
- type: normalized.type,
- ts: new Date().toISOString(),
- event: normalized,
- };
- fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');
- const next = applyEvent(prior.snapshot, entry, prior.diagnostics);
- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });
- writeSnapshot(snapshotPath, next);
- return next;
- },
- getSnapshot(id = sessionId, opts = {}) {
- if (!id) throw new Error('session id required');
- const journalPath = getReadableJournalPath(id);
- const snapshotPath = getSnapshotPath(rootDir, id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- writeSnapshot(snapshotPath, rebuilt.snapshot);
- if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;
- return rebuilt.snapshot;
- },
- listActiveSessions() {
- const ids = new Set();
- for (const dir of [legacyRootDir, rootDir]) {
- if (!fs.existsSync(dir)) continue;
- for (const name of fs.readdirSync(dir)) {
- if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));
- }
- }
- return [...ids]
- .sort()
- .map((id) => this.getSnapshot(id))
- .filter(Boolean);
- },
- };
-}
-
-function normalizeEvent(event, fallbackId) {
- if (!event || typeof event !== 'object') throw new Error('event object required');
- const id = event.id || fallbackId;
- if (!id || typeof id !== 'string') throw new Error('event id required');
- if (!event.type || typeof event.type !== 'string') throw new Error('event type required');
- return { ...event, id };
-}
-
-function getJournalPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.jsonl');
-}
-
-function getSnapshotPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.snapshot.json');
-}
-
-function safeSessionId(id) {
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);
- return id;
-}
-
-function baseSnapshot(id) {
- return {
- id,
- phase: 'new',
- pageUrl: null,
- sourceFile: null,
- expectedVariants: 0,
- arrivedVariants: 0,
- visibleVariant: null,
- paramValues: {},
- pendingEventSeq: null,
- pendingEvent: null,
- deliveryLease: null,
- checkpointRevision: 0,
- activeOwner: null,
- sourceMarkers: {},
- fallbackMode: null,
- annotationArtifacts: [],
- diagnostics: [],
- updatedAt: null,
- };
-}
-
-function rebuildSnapshotFromJournal(journalPath, id) {
- let snapshot = baseSnapshot(id);
- const diagnostics = [];
- let nextSeq = 1;
- if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };
-
- const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- if (!line.trim()) continue;
- try {
- const entry = JSON.parse(line);
- if (!entry || typeof entry !== 'object') throw new Error('entry is not object');
- if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);
- snapshot = applyEvent(snapshot, entry);
- } catch (err) {
- diagnostics.push({
- error: 'journal_parse_failed',
- line: i + 1,
- message: err.message,
- });
- }
- }
- snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];
- return { snapshot, diagnostics, nextSeq };
-}
-
-function applyEvent(snapshot, entry, inheritedDiagnostics = []) {
- const event = entry.event || entry;
- const next = {
- ...snapshot,
- paramValues: { ...(snapshot.paramValues || {}) },
- sourceMarkers: { ...(snapshot.sourceMarkers || {}) },
- annotationArtifacts: [...(snapshot.annotationArtifacts || [])],
- diagnostics: [...(snapshot.diagnostics || [])],
- updatedAt: entry.ts || new Date().toISOString(),
- };
-
- if (inheritedDiagnostics.length && next.diagnostics.length === 0) {
- next.diagnostics = [...inheritedDiagnostics];
- }
-
- switch (event.type) {
- case 'generate':
- next.phase = 'generate_requested';
- next.pageUrl = event.pageUrl ?? next.pageUrl;
- next.expectedVariants = event.count ?? next.expectedVariants;
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });
- break;
- case 'variants_ready':
- case 'agent_done':
- next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';
- next.sourceFile = event.file ?? next.sourceFile;
- next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- if (event.carbonize === true) {
- next.diagnostics.push({
- error: 'carbonize_cleanup_required',
- file: event.file || null,
- message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',
- });
- }
- break;
- case 'checkpoint':
- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {
- next.phase = event.phase ?? next.phase;
- next.checkpointRevision = event.revision ?? next.checkpointRevision;
- next.activeOwner = event.owner ?? next.activeOwner;
- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;
- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- } else {
- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });
- }
- break;
- case 'accept':
- case 'accept_intent':
- next.phase = 'accept_requested';
- next.visibleVariant = Number(event.variantId ?? next.visibleVariant);
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discard':
- next.phase = 'discard_requested';
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discarded':
- next.phase = 'discarded';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'complete':
- next.phase = 'completed';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'agent_error':
- next.phase = 'agent_error';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });
- break;
- default:
- next.diagnostics.push({ error: 'unknown_event_type', type: event.type });
- break;
- }
- return next;
-}
-
-function toPendingEvent(event) {
- const pending = { ...event };
- delete pending.token;
- return pending;
-}
-
-function upsertArtifact(artifacts, artifact) {
- if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {
- artifacts.push(artifact);
- }
-}
-
-function writeSnapshot(snapshotPath, snapshot) {
- fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');
-}
@@ -1,47 +0,0 @@
-#!/usr/bin/env node
-/**
- * Print durable recovery status for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function fetchServerStatus(info) {
- if (!info) return null;
- try {
- const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-export async function statusCli() {
- const info = readServerInfo();
- const server = await fetchServerStatus(info);
- const store = createLiveSessionStore({ cwd: process.cwd() });
- const activeSessions = store.listActiveSessions();
- const payload = {
- liveServer: server ? {
- status: server.status,
- port: server.port,
- connectedClients: server.connectedClients,
- pendingEvents: server.pendingEvents,
- } : null,
- activeSessions: server?.activeSessions || activeSessions,
- recoveryHint: server
- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'
- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',
- };
- console.log(JSON.stringify(payload, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {
- statusCli();
-}
@@ -1,632 +0,0 @@
-/**
- * CLI helper: find an element in source and wrap it in a variant container.
- *
- * Usage:
- * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
- *
- * Searches project files for the element matching the query (class name, ID, or
- * text snippet), wraps it with the variant scaffolding, and prints the file path
- * + line range where the agent should insert variant HTML.
- *
- * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-export async function wrapCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable wrap [options]
-
-Find an element in source and wrap it in a variant container.
-
-Required:
- --id ID Session ID for the variant wrapper
- --count N Number of expected variants (1-8)
-
-Element identification (at least one required):
- --element-id ID HTML id attribute of the element
- --classes A,B,C Comma-separated CSS class names
- --tag TAG Tag name (div, section, etc.)
- --query TEXT Fallback: raw text to search for
-
-Optional:
- --file PATH Source file to search in (skips auto-detection)
- --text TEXT Picked element's textContent. Used to disambiguate when
- classes/tag match multiple sibling elements (e.g. a list
- of <Card>s with the same className). Pass the first ~80
- chars of event.element.textContent.
- --help Show this help message
-
-Output (JSON):
- { file, startLine, endLine, insertLine, commentSyntax }
-
-The agent should insert variant HTML at insertLine.`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const count = parseInt(argVal(args, '--count') || '3');
- const elementId = argVal(args, '--element-id');
- const classes = argVal(args, '--classes');
- const tag = argVal(args, '--tag');
- const query = argVal(args, '--query');
- const filePath = argVal(args, '--file');
- const text = argVal(args, '--text');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!elementId && !classes && !query) {
- console.error('Need at least one of: --element-id, --classes, --query');
- process.exit(1);
- }
-
- // Build search queries in priority order (most specific first)
- const queries = buildSearchQueries(elementId, classes, tag, query);
-
- const genOpts = { cwd: process.cwd() };
-
- // Find the source file. Generated files are excluded from auto-search so we
- // don't silently write variants into a file the next build will wipe.
- let targetFile = filePath;
- let matchedQuery = null;
- if (!targetFile) {
- for (const q of queries) {
- targetFile = findFileWithQuery(q, process.cwd(), genOpts);
- if (targetFile) { matchedQuery = q; break; }
- }
- if (!targetFile) {
- // Nothing in source. Did the element show up in a generated file? That
- // tells the agent "fall back to the agent-driven flow" vs "element just
- // doesn't exist in this project."
- let generatedHit = null;
- for (const q of queries) {
- generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
- if (generatedHit) break;
- }
- if (generatedHit) {
- console.error(JSON.stringify({
- error: 'element_not_in_source',
- fallback: 'agent-driven',
- generatedMatch: path.relative(process.cwd(), generatedHit),
- hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
- }));
- } else {
- console.error(JSON.stringify({
- error: 'element_not_found',
- fallback: 'agent-driven',
- hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
- }));
- }
- process.exit(1);
- }
- } else {
- if (isGeneratedFile(targetFile, genOpts)) {
- console.error(JSON.stringify({
- error: 'file_is_generated',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
- hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- matchedQuery = queries[0];
- }
-
- const content = fs.readFileSync(targetFile, 'utf-8');
- const lines = content.split('\n');
-
- // Find the element, trying each query in priority order. When `--text` is
- // supplied, collect every candidate the queries surface and disambiguate
- // by the picked element's textContent. Without `--text`, fall back to the
- // legacy first-match behavior so unmodified callers keep working.
- let match = null;
- if (text) {
- const candidates = [];
- for (const q of queries) {
- const all = findAllElements(lines, q, tag);
- for (const c of all) {
- if (!candidates.some((x) => x.startLine === c.startLine)) {
- candidates.push(c);
- }
- }
- // Once a more-specific query (ID, full className combo) yielded a unique
- // result, stop — falling through to the loose tag+single-class query
- // would readmit the siblings we just disambiguated past.
- if (candidates.length === 1) break;
- }
- if (candidates.length === 0) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- if (candidates.length === 1) {
- match = candidates[0];
- } else {
- const filtered = filterByText(candidates, lines, text);
- if (filtered.length === 1) {
- match = filtered[0];
- } else if (filtered.length === 0) {
- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the
- // browser-side textContent doesn't appear literally in source. Fall
- // back to first-match rather than refusing — this is the same
- // behavior unmodified callers see, just preserved.
- match = candidates[0];
- } else {
- // Multiple candidates ALSO match the text. Truly ambiguous — refuse
- // rather than pick wrong, and hand the agent the candidate locations
- // so it can disambiguate by reading the file.
- console.error(JSON.stringify({
- error: 'element_ambiguous',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), targetFile),
- candidates: filtered.map((c) => ({
- startLine: c.startLine + 1,
- endLine: c.endLine + 1,
- })),
- hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- }
- } else {
- for (const q of queries) {
- match = findElement(lines, q, tag);
- if (match) break;
- }
- if (!match) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- }
-
- const { startLine, endLine } = match;
- const commentSyntax = detectCommentSyntax(targetFile);
- const styleMode = detectStyleMode(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- const indent = lines[startLine].match(/^(\s*)/)[1];
-
- // Extract the original element. Reindent under the wrapper while preserving
- // the relative depth between lines — `l.trimStart()` would strip ALL leading
- // whitespace and collapse e.g. `<aside>`/` <h1>`/`</aside>` (6/8/6 spaces)
- // to a single uniform indent, so on accept/discard the round-trip restores
- // the inner element at its parent's depth instead of nested inside it.
- // Strip only the COMMON minimum leading whitespace across the picked lines;
- // `deindentContent` on the accept side already mirrors this convention.
- const originalLines = lines.slice(startLine, endLine + 1);
- const originalBaseIndent = minLeadingSpaces(originalLines);
- const reindentOriginal = (extra) => originalLines
- .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
- .join('\n');
- const originalIndented = reindentOriginal(' ');
-
- // Wrapper attributes differ by syntax. HTML allows plain string attrs;
- // JSX requires object-literal style and parses string attrs as HTML (which
- // either type-errors or renders a literal CSS string).
- const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
-
- // JSX/TSX guard: the picked element occupies a single JSX child slot
- // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
- // any other expression position). Replacing it with `comment + <div> +
- // comment` yields three adjacent siblings — invalid JSX. We can't use a
- // Fragment `<></>` either: parents that clone children (Radix `asChild`,
- // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
- // they try to pass an `id` through.
- //
- // Solution: keep the wrapper `<div>` as the single JSX-slot child and
- // tuck both marker comments INSIDE it. accept/discard then expands its
- // replacement range to include the wrapper's `<div>` open / close lines
- // so the entire scaffold gets removed cleanly.
- const wrapperLines = isJsx ? [
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- reindentOriginal(' '),
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- indent + '</div>',
- ] : [
- indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- originalIndented,
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + '</div>',
- indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- ];
-
- // Replace the original element with the wrapper
- const newLines = [
- ...lines.slice(0, startLine),
- ...wrapperLines,
- ...lines.slice(endLine + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- // Calculate insert line (the "insert below this line" comment).
- // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
- // the insert marker (HTML: start-comment + outer-div + Original-comment +
- // original-div + content + close-original-div; JSX: outer-div +
- // start-comment + Original-comment + original-div + content +
- // close-original-div). Multi-line originals push the marker by their
- // extra line count.
- const insertLine = startLine + 6 + (originalLines.length - 1);
-
- console.log(JSON.stringify({
- file: path.relative(process.cwd(), targetFile),
- startLine: startLine + 1, // 1-indexed for the agent
- // wrapperLines is an array but one element (the original-content slot)
- // is a `\n`-joined multi-line string, so the actual file-row count is
- // wrapperLines.length + (originalLines.length - 1). Without the offset,
- // endLine pointed inside the wrapper for any picked element that
- // spanned more than one source line.
- endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexed
- insertLine: insertLine + 1, // 1-indexed: where variants go
- commentSyntax: commentSyntax,
- styleMode: styleMode.mode,
- styleTag: styleMode.styleTag,
- cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
- cssAuthoring: buildCssAuthoring(styleMode, count),
- originalLineCount: originalLines.length,
- }));
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-/**
- * Build search query strings in priority order (most specific first).
- * ID is most reliable, then specific class combos, then single classes, then raw query.
- */
-function buildSearchQueries(elementId, classes, tag, query) {
- const queries = [];
-
- // 1. ID is the most specific
- if (elementId) {
- queries.push('id="' + elementId + '"');
- }
-
- // 2. Full class attribute match (for elements with distinctive multi-class combos).
- // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
- // convention the file uses will match.
- if (classes) {
- const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
- if (classList.length > 1) {
- const joined = classList.join(' ');
- const sorted = [...classList].sort((a, b) => b.length - a.length);
- queries.push('class="' + joined + '"');
- queries.push('className="' + joined + '"');
- queries.push(sorted[0]); // most distinctive single class, fallback
- } else if (classList.length === 1) {
- queries.push(classList[0]);
- }
- }
-
- // 3. Tag + class combo (e.g., <section class="hero">).
- // Same dual-emit for JSX compatibility.
- if (tag && classes) {
- const firstClass = classes.split(',')[0].trim();
- queries.push('<' + tag + ' class="' + firstClass);
- queries.push('<' + tag + ' className="' + firstClass);
- }
-
- // 4. Raw fallback query
- if (query) {
- queries.push(query);
- }
-
- return queries;
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- // HTML, Vue, Svelte, Astro all use HTML comments
- return { open: '<!--', close: '-->' };
-}
-
-function detectStyleMode(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.astro') {
- return {
- mode: 'astro-global-prefixed',
- styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',
- };
- }
- return {
- mode: 'scoped',
- styleTag: '<style data-impeccable-css="SESSION_ID">',
- };
-}
-
-function buildCssSelectorPrefixExamples(styleMode, count) {
- if (styleMode !== 'astro-global-prefixed') return [];
- return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);
-}
-
-function buildCssAuthoring(styleMode, count) {
- const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
- if (styleMode.mode === 'astro-global-prefixed') {
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'global-prefixed',
- rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',
- selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),
- requirements: [
- 'Use the styleTag exactly; the is:inline attribute is required for this file.',
- 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',
- 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
- ],
- forbidden: [
- 'Do not use @scope for this styleMode.',
- ],
- };
- }
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'scope-rule',
- rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',
- selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),
- requirements: [
- 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',
- 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
- 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
- ],
- forbidden: [
- 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',
- 'Do not add is:inline to the style tag for this styleMode.',
- ],
- };
-}
-
-/**
- * Search project files for the query string (class name, ID, etc.)
- * Returns the first matching file path, or null.
- */
-function findFileWithQuery(query, cwd, genOpts = {}) {
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, query, seen, 0, genOpts);
- if (result) return result;
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth, genOpts) {
- if (depth > 5) return null; // don't go too deep
- const realDir = fs.realpathSync(dir);
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- // Check files first
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name).toLowerCase();
- if (!EXTENSIONS.includes(ext)) continue;
-
- const filePath = path.join(dir, entry.name);
- if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip unreadable files */ }
- }
-
- // Then recurse into directories. Always skip node_modules and .git (never
- // project content). dist/build/out are left to the isGeneratedFile guard so
- // the includeGenerated second-pass can still find the element there and
- // report `generatedMatch`.
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
- if (result) return result;
- }
-
- return null;
-}
-
-/**
- * Regex that matches a tag opener on a line. Allows the tag name to be
- * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
- * openers (e.g. `<section\n className="..."\n>`) are recognised.
- */
-const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
-
-/**
- * Find the element's start and end line in the file.
- *
- * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
- * `id="..."`), or a raw text snippet. Because a query can appear on a
- * continuation line of a multi-line tag (e.g. the `className="..."` row of a
- * `<section\n className="..."\n>` JSX tag), we walk backward from the match
- * line to find the actual tag opener. When `tag` is provided, opener candidates
- * must match that tag name.
- */
-/**
- * Return the smallest leading-whitespace count across a set of lines,
- * ignoring blank lines (whose indent isn't load-bearing). Used to compute
- * the common base indent of a multi-line picked element so reindenting
- * under the wrapper preserves the relative depth between lines.
- */
-function minLeadingSpaces(lines) {
- let min = Infinity;
- for (const l of lines) {
- if (l.trim() === '') continue;
- const m = l.match(/^(\s*)/);
- if (m && m[1].length < min) min = m[1].length;
- }
- return min === Infinity ? 0 : min;
-}
-
-function findElement(lines, query, tag = null) {
- // Iterate all matches — the first substring hit isn't always the right one.
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
-
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- // Skip lines already inside a variant wrapper
- if (lines[i].includes('data-impeccable-variant')) continue;
-
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
-
- const endLine = findClosingLine(lines, openerLine);
- return { startLine: openerLine, endLine };
- }
-
- return null;
-}
-
-/**
- * Like findElement, but returns every match. Used for ambiguity detection
- * when the agent passes --text: when the same className appears on multiple
- * sibling elements (a list of cards, repeated section variants, etc.),
- * first-match silently lands on the wrong branch. Returning all matches lets
- * the caller narrow by textContent or fail with a structured ambiguity error.
- */
-function findAllElements(lines, query, tag = null) {
- const out = [];
- const seen = new Set();
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- if (lines[i].includes('data-impeccable-variant')) continue;
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
- if (seen.has(openerLine)) continue; // multiple matches inside the same element
- seen.add(openerLine);
- const endLine = findClosingLine(lines, openerLine);
- out.push({ startLine: openerLine, endLine });
- }
- return out;
-}
-
-/**
- * Narrow a candidate set to those whose source body matches a meaningful
- * prefix of the picked element's textContent. The compare strips tags and
- * JSX expressions, then checks two whitespace normalizations side-by-side:
- *
- * - single-space ("hero two second card body")
- * - no-whitespace ("herotwosecondcardbody")
- *
- * Both are needed because `el.textContent` concatenates sibling text without
- * inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
- * `"Hero TwoSecond…"`), while the source has whitespace between tags. If
- * EITHER normalization matches, the candidate keeps. A snippet shorter than
- * 8 chars after stripping is too weak to disambiguate — the caller falls
- * back to first-match.
- */
-function filterByText(candidates, lines, text) {
- const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
- // Too short to disambiguate. Return [] so the caller's `filtered.length
- // === 0` branch fires (fall back to first-match) — the previous
- // `candidates.slice()` return forced `filtered.length > 1` and surfaced
- // a spurious `element_ambiguous` error on every short-text picker event
- // with multiple candidates.
- if (trimmed.length < 8) return [];
- const targetSpaced = trimmed;
- const targetCompact = trimmed.replace(/\s+/g, '');
-
- return candidates.filter((c) => {
- const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
- const inner = body
- .replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
- .replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
- .toLowerCase();
- const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
- const sourceCompact = inner.replace(/\s+/g, '');
- return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
- });
-}
-
-/**
- * Resolve a match line to the real tag opener. If the match line itself opens
- * a tag, return it. Otherwise walk up to 10 lines backward looking for the
- * first tag opener. If `tag` is specified, the opener must match that tag
- * name; an opener with a different tag name aborts the backward walk for this
- * match (we don't jump across element boundaries).
- *
- * Returns the line index of the opener, or -1 if none can be resolved.
- */
-function findOpenerLine(lines, matchLine, tag) {
- const self = lines[matchLine].match(OPENER_RE);
- if (self) {
- if (!tag || self[1] === tag) return matchLine;
- return -1;
- }
- const MAX_BACKWALK = 10;
- for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
- const opener = lines[i].match(OPENER_RE);
- if (!opener) continue;
- if (!tag || opener[1] === tag) return i;
- // Different tag name than requested — abort; we're inside a non-target opener.
- return -1;
- }
- return -1;
-}
-
-/**
- * Starting from a line with an opening tag, find the line with the matching
- * closing tag by counting tag nesting depth.
- */
-function findClosingLine(lines, start) {
- const openMatch = lines[start].match(OPENER_RE);
- if (!openMatch) return start; // caller passed a non-opener; nothing to span
-
- const tagName = openMatch[1];
- let depth = 0;
- const openRe = new RegExp('<' + tagName + '(?=[\\s/>]|$)', 'g');
- const selfCloseRe = new RegExp('<' + tagName + '[^>]*/>', 'g');
- const closeRe = new RegExp('</' + tagName + '\\s*>', 'g');
-
- for (let i = start; i < lines.length; i++) {
- const line = lines[i];
- const opens = (line.match(openRe) || []).length;
- const selfCloses = (line.match(selfCloseRe) || []).length;
- const closes = (line.match(closeRe) || []).length;
-
- depth += opens - selfCloses - closes;
-
- if (depth <= 0) return i;
- }
-
- // If we can't find the close, return a reasonable guess
- return Math.min(start + 50, lines.length - 1);
-}
-
-// Auto-execute when run directly (node live-wrap.mjs ...)
-const _running = process.argv[1];
-if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {
- wrapCli();
-}
-
-// Test exports (used by tests/live-wrap.test.mjs)
-export { buildSearchQueries, findElement, findClosingLine, detectCommentSyntax };
@@ -1,247 +0,0 @@
-/**
- * CLI entry point: prepare everything needed to enter the live variant poll loop.
- *
- * Does (all in one command):
- * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)
- * 2. Start the live server in the background (or reuse a running one)
- * 3. Inject the browser script tag into the project's entry file
- * 4. Read PRODUCT.md / DESIGN.md for project context
- * 5. Print a single JSON blob with everything the agent needs
- *
- * After this, the agent's only remaining steps are:
- * - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll
- * - Enter the poll loop: `node live-poll.mjs`
- *
- * Usage:
- * node live.mjs # Prepare everything, print JSON, exit
- * node live.mjs --help
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { loadContext } from './load-context.mjs';
-import { resolveFiles } from './live-inject.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-async function liveCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live.mjs
-
-Prepare everything for live variant mode in a single command:
- - Checks .impeccable/live/config.json (required, created once per project)
- - Starts (or reuses) the live server in the background
- - Injects the browser script tag
- - Reads PRODUCT.md / DESIGN.md for project context
-
-On success, prints a JSON blob with:
- { ok, serverPort, serverToken, pageFile, hasContext, context }
-
-On config_missing, prints:
- { ok: false, error: "config_missing", configPath, hint }
-
-The agent should then:
- 1. If config_missing, create the config and re-run this script
- 2. Optionally open the project's dev/preview URL in the browser (see reference/live.md—not serverPort)
- 3. Enter the poll loop: node live-poll.mjs`);
- process.exit(0);
- }
-
- // 1. Check config (fail fast if missing — no point starting anything else)
- const checkOut = runScript('live-inject.mjs', ['--check']);
- const checkResult = safeParse(checkOut);
- if (!checkResult || !checkResult.ok) {
- console.log(JSON.stringify(checkResult || { ok: false, error: 'check_failed', raw: checkOut }));
- process.exit(0);
- }
-
- // 2. Start server (or reuse existing)
- const serverInfo = ensureServerRunning();
- if (!serverInfo) {
- console.log(JSON.stringify({ ok: false, error: 'server_start_failed' }));
- process.exit(1);
- }
-
- // 3. Inject the script tag at the current port
- const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)]);
- const injectResult = safeParse(injectOut);
- if (!injectResult || !injectResult.ok) {
- console.log(JSON.stringify({
- ok: false,
- error: 'inject_failed',
- detail: injectResult || injectOut,
- serverPort: serverInfo.port,
- }));
- process.exit(1);
- }
-
- // 4. Load PRODUCT.md + DESIGN.md context (auto-migrates legacy .impeccable.md)
- const ctx = loadContext(process.cwd());
-
- // 5. Compute drift-heal: compare resolved inject targets against the
- // project's HTML files. Orphans are HTML files not covered by config.
- // Warning only — the agent decides whether to act.
- const resolvedFiles = resolveFiles(process.cwd(), checkResult.config);
- const drift = scanForDrift(process.cwd(), resolvedFiles, checkResult.config);
-
- // 6. Emit everything the agent needs
- console.log(JSON.stringify({
- ok: true,
- serverPort: serverInfo.port,
- serverToken: serverInfo.token,
- pageFiles: resolvedFiles,
- configDrift: drift,
- hasProduct: ctx.hasProduct,
- product: ctx.product,
- productPath: ctx.productPath,
- hasDesign: ctx.hasDesign,
- design: ctx.design,
- designPath: ctx.designPath,
- migrated: ctx.migrated,
- }, null, 2));
-}
-
-/**
- * Drift-heal scan. Walks the project for HTML files under common
- * page-source directories (public/, src/, app/, pages/) and reports any
- * that aren't covered by the resolved inject targets. This is purely
- * advisory — the agent can ignore it, or suggest the user add the
- * orphans to config.files.
- *
- * Skipped if config.files already contains at least one glob pattern
- * covering everything in practice (signaled by the orphan count being 0).
- */
-function scanForDrift(rootDir, resolvedFiles, config) {
- const SCAN_ROOTS = ['public', 'src', 'app', 'pages'];
- const IGNORE_DIRS = new Set([
- 'node_modules', '.git', '.next', '.nuxt', '.svelte-kit', '.astro',
- '.turbo', '.vercel', '.cache', 'coverage', 'dist', 'build',
- ]);
-
- const resolvedSet = new Set(resolvedFiles.map((f) => f.split(path.sep).join('/')));
-
- // Files matching the user's `exclude` globs are intentional omissions,
- // not drift. Compile them to regexes so the orphan list stays signal.
- const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
- .map((p) => globToRegex(p));
- const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
-
- const orphans = [];
-
- const walk = (dir, relBase) => {
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
- for (const e of entries) {
- const rel = relBase ? `${relBase}/${e.name}` : e.name;
- if (e.isDirectory()) {
- if (IGNORE_DIRS.has(e.name) || e.name.startsWith('.')) continue;
- walk(path.join(dir, e.name), rel);
- } else if (e.isFile() && e.name.endsWith('.html')) {
- if (resolvedSet.has(rel)) continue;
- if (isUserExcluded(rel)) continue;
- orphans.push(rel);
- }
- }
- };
-
- for (const root of SCAN_ROOTS) {
- const abs = path.join(rootDir, root);
- if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
- walk(abs, root);
- }
- }
-
- if (orphans.length === 0) return null;
- const capped = orphans.slice(0, 20);
- return {
- orphans: capped,
- orphanCount: orphans.length,
- hint: `${orphans.length} HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like "public/**/*.html".`,
- };
-}
-
-/**
- * Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
- * to avoid a circular import (live-inject.mjs already imports nothing
- * from live.mjs). The two must stay in sync.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
- else { re += '.*'; i += 2; }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function runScript(name, args) {
- const scriptPath = path.join(__dirname, name);
- const cmd = `node "${scriptPath}" ${args.map(a => `"${a}"`).join(' ')}`;
- try {
- return execSync(cmd, { encoding: 'utf-8', cwd: process.cwd(), timeout: 15_000 });
- } catch (err) {
- // execSync throws on non-zero exit; return stdout if any
- return err.stdout || err.message || '';
- }
-}
-
-function safeParse(out) {
- try { return JSON.parse(String(out).trim()); } catch { return null; }
-}
-
-/**
- * Return { pid, port, token } for the running live server, starting one if needed.
- */
-function ensureServerRunning() {
- // Try to reuse an existing server
- try {
- const existing = readLiveServerInfo(process.cwd())?.info;
- if (existing && existing.pid) {
- try {
- process.kill(existing.pid, 0); // throws if dead
- return existing;
- } catch { /* stale PID file — the server script will clean it up */ }
- }
- } catch { /* no PID file */ }
-
- // Start a new server
- const out = runScript('live-server.mjs', ['--background']);
- return safeParse(out);
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live.mjs') || _running?.endsWith('live.mjs/')) {
- liveCli();
-}
@@ -1,141 +0,0 @@
-/**
- * Shared context loader for every impeccable command that needs to know
- * "who is this for" and "what does this look like".
- *
- * Input: project root (process.cwd()).
- *
- * Output (JSON to stdout):
- * {
- * hasProduct: boolean, // PRODUCT.md found (or auto-migrated)
- * product: string | null, // PRODUCT.md contents
- * productPath: string | null, // relative path
- * hasDesign: boolean, // DESIGN.md found
- * design: string | null, // DESIGN.md contents
- * designPath: string | null,
- * migrated: boolean, // true if we auto-renamed .impeccable.md -> PRODUCT.md
- * contextDir: string, // absolute path of the directory the files were found in
- * }
- *
- * Filename matching is case-insensitive for PRODUCT.md and DESIGN.md. The
- * Google DESIGN.md convention is uppercase at repo root; Kiro-style and
- * lowercase variants are also matched so users don't get punished for case.
- *
- * Lookup directory resolution (first match wins):
- * 1. process.env.IMPECCABLE_CONTEXT_DIR (absolute or relative to cwd)
- * 2. cwd, if PRODUCT.md / DESIGN.md / .impeccable.md is there (back-compat)
- * 3. Auto-fallback subdirectories of cwd: .agents/context/, then docs/
- * 4. cwd as a default "no context found" location
- *
- * Legacy `.impeccable.md` -> PRODUCT.md migration only fires at cwd root;
- * fallback directories are read-only as far as auto-rename is concerned.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
-const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
-const LEGACY_NAMES = ['.impeccable.md'];
-const FALLBACK_DIRS = ['.agents/context', 'docs'];
-
-/**
- * Resolve the directory that holds PRODUCT.md / DESIGN.md for
- * this project. Exported so other scripts (e.g. live-server.mjs) can read the
- * design files from the same location the loader uses.
- */
-export function resolveContextDir(cwd = process.cwd()) {
- // 1. Explicit override
- const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
- if (envDir && envDir.trim()) {
- const trimmed = envDir.trim();
- return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- }
-
- // 2. cwd wins if any canonical or legacy file is there. We check legacy too
- // so the auto-migration path in loadContext stays predictable.
- if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES, ...LEGACY_NAMES])) {
- return cwd;
- }
-
- // 3. Auto-fallback subdirs. Match if PRODUCT.md or DESIGN.md is present;
- // legacy `.impeccable.md` does not pull the lookup into a fallback dir.
- for (const rel of FALLBACK_DIRS) {
- const candidate = path.resolve(cwd, rel);
- if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
- return candidate;
- }
- }
-
- // 4. Nothing found — keep the historical "default to cwd" behaviour so the
- // caller's `hasProduct === false` branch still fires the same way.
- return cwd;
-}
-
-export function loadContext(cwd = process.cwd()) {
- let migrated = false;
- const contextDir = resolveContextDir(cwd);
-
- // 1. Look for PRODUCT.md (case-insensitive) in the resolved dir
- let productPath = firstExisting(contextDir, PRODUCT_NAMES);
-
- // 2. Legacy: if no PRODUCT.md but .impeccable.md exists at cwd root, rename
- // it in place. We only migrate at the root — fallback dirs are read-only
- // so we don't surprise users by mutating files under docs/ or .agents/.
- if (!productPath && contextDir === cwd) {
- const legacyPath = firstExisting(cwd, LEGACY_NAMES);
- if (legacyPath) {
- const newPath = path.join(cwd, 'PRODUCT.md');
- try {
- fs.renameSync(legacyPath, newPath);
- productPath = newPath;
- migrated = true;
- } catch {
- // Rename failed (permissions, etc.) — fall back to reading legacy in place
- productPath = legacyPath;
- }
- }
- }
-
- // 3. DESIGN.md (case-insensitive)
- const designPath = firstExisting(contextDir, DESIGN_NAMES);
-
- const product = productPath ? safeRead(productPath) : null;
- const design = designPath ? safeRead(designPath) : null;
-
- return {
- hasProduct: !!product,
- product,
- productPath: productPath ? path.relative(cwd, productPath) : null,
- hasDesign: !!design,
- design,
- designPath: designPath ? path.relative(cwd, designPath) : null,
- migrated,
- contextDir,
- };
-}
-
-function firstExisting(dir, names) {
- for (const name of names) {
- const abs = path.join(dir, name);
- if (fs.existsSync(abs)) return abs;
- }
- return null;
-}
-
-function safeRead(p) {
- try { return fs.readFileSync(p, 'utf-8'); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// CLI mode — print the context as JSON
-// ---------------------------------------------------------------------------
-
-function cli() {
- const result = loadContext(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('load-context.mjs') || _running?.endsWith('load-context.mjs/')) {
- cli();
-}
@@ -1,14 +0,0 @@
@@ -1,214 +0,0 @@
-#!/usr/bin/env node
-/**
- * Pin/unpin sub-commands as standalone skill shortcuts.
- *
- * Usage:
- * node <scripts_path>/pin.mjs pin <command>
- * node <scripts_path>/pin.mjs unpin <command>
- *
- * `pin audit` creates a lightweight /audit skill that redirects to /impeccable audit.
- * `unpin audit` removes that shortcut.
- *
- * The script discovers harness directories (.claude/skills, .cursor/skills, etc.)
- * in the project root and creates/removes the pin in all of them.
- */
-
-import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
-import { join, resolve, dirname } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-// All known harness directories
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Valid sub-command names
-const VALID_COMMANDS = [
- 'craft', 'teach', 'extract', 'document', 'shape',
- 'critique', 'audit',
- 'polish', 'bolder', 'quieter', 'distill', 'harden', 'onboard', 'live',
- 'animate', 'colorize', 'typeset', 'layout', 'delight', 'overdrive',
- 'clarify', 'adapt', 'optimize',
-];
-
-// Marker to identify pinned skills (so unpin doesn't delete user skills)
-const PIN_MARKER = '<!-- impeccable-pinned-skill -->';
-
-/**
- * Walk up from startDir to find a project root.
- */
-function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- while (dir !== '/') {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Find harness skill directories that have an impeccable skill installed.
- */
-function findHarnessDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const skillsDir = join(projectRoot, harness, 'skills');
- // Only pin in harness dirs that already have impeccable installed
- const impeccableDir = join(skillsDir, 'impeccable');
- if (existsSync(impeccableDir) || existsSync(join(skillsDir, 'i-impeccable'))) {
- dirs.push(skillsDir);
- }
- }
- return dirs;
-}
-
-/**
- * Load command metadata (descriptions for pinned skills).
- */
-function loadCommandMetadata() {
- const metadataPath = join(__dirname, 'command-metadata.json');
- if (existsSync(metadataPath)) {
- return JSON.parse(readFileSync(metadataPath, 'utf-8'));
- }
- return {};
-}
-
-/**
- * Generate a pinned skill's SKILL.md content.
- */
-function generatePinnedSkill(command, metadata) {
- const desc = metadata[command]?.description || `Shortcut for /impeccable ${command}.`;
- const hint = metadata[command]?.argumentHint || '[target]';
-
- return `---
-name: ${command}
-description: "${desc}"
-argument-hint: "${hint}"
-user-invocable: true
----
-
-${PIN_MARKER}
-
-This is a pinned shortcut for \`{{command_prefix}}impeccable ${command}\`.
-
-Invoke {{command_prefix}}impeccable ${command}, passing along any arguments provided here, and follow its instructions.
-`;
-}
-
-/**
- * Pin a command: create shortcut skill in all harness dirs.
- */
-function pin(command, projectRoot) {
- const metadata = loadCommandMetadata();
- const harnessDirs = findHarnessDirs(projectRoot);
-
- if (harnessDirs.length === 0) {
- console.log('No harness directories with impeccable installed found.');
- return false;
- }
-
- const content = generatePinnedSkill(command, metadata);
- let created = 0;
-
- for (const skillsDir of harnessDirs) {
- // Check if skill already exists (and isn't a pin)
- const skillDir = join(skillsDir, command);
- if (existsSync(skillDir)) {
- const existingMd = join(skillDir, 'SKILL.md');
- if (existsSync(existingMd)) {
- const existing = readFileSync(existingMd, 'utf-8');
- if (!existing.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (non-pinned skill already exists)`);
- continue;
- }
- }
- }
-
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(join(skillDir, 'SKILL.md'), content, 'utf-8');
- console.log(` + ${skillDir}`);
- created++;
- }
-
- if (created > 0) {
- console.log(`\nPinned '${command}' as a standalone shortcut in ${created} location(s).`);
- console.log(`You can now use /${command} directly.`);
- }
-
- return created > 0;
-}
-
-/**
- * Unpin a command: remove shortcut skill from all harness dirs.
- */
-function unpin(command, projectRoot) {
- const harnessDirs = findHarnessDirs(projectRoot);
- let removed = 0;
-
- for (const skillsDir of harnessDirs) {
- const skillDir = join(skillsDir, command);
- if (!existsSync(skillDir)) continue;
-
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) continue;
-
- // Safety: only remove if it's a pinned skill
- const content = readFileSync(skillMd, 'utf-8');
- if (!content.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (not a pinned skill)`);
- continue;
- }
-
- rmSync(skillDir, { recursive: true, force: true });
- console.log(` - ${skillDir}`);
- removed++;
- }
-
- if (removed > 0) {
- console.log(`\nUnpinned '${command}' from ${removed} location(s).`);
- console.log(`Use /impeccable ${command} to access it.`);
- } else {
- console.log(`No pinned '${command}' shortcut found.`);
- }
-
- return removed > 0;
-}
-
-// --- CLI ---
-const [,, action, command] = process.argv;
-
-if (!action || !command) {
- console.log('Usage: node pin.mjs <pin|unpin> <command>');
- console.log(`\nAvailable commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-if (action !== 'pin' && action !== 'unpin') {
- console.error(`Unknown action: ${action}. Use 'pin' or 'unpin'.`);
- process.exit(1);
-}
-
-if (!VALID_COMMANDS.includes(command)) {
- console.error(`Unknown command: ${command}`);
- console.error(`Available commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-const root = findProjectRoot();
-
-if (action === 'pin') {
- pin(command, root);
-} else {
- unpin(command, root);
-}
@@ -1,8 +0,0 @@
-# Global ownership — auto-request review from Paul on every PR
-* @pbakaus
-
-# Build system
-scripts/ @pbakaus
-
-# Source content (skills & commands)
-source/ @pbakaus
@@ -1,31 +0,0 @@
----
-name: Bug report
-about: Something isn't working as expected
-title: "[Bug] "
-labels: bug
-assignees: ''
----
-
-## What happened?
-
-<!-- A clear description of the bug. -->
-
-## Steps to reproduce
-
-1.
-2.
-3.
-
-## Expected behavior
-
-<!-- What did you expect to happen? -->
-
-## Provider & environment
-
-- **Provider** (Cursor / Claude Code / Gemini CLI / Codex / Copilot / Kiro / OpenCode):
-- **Provider version**:
-- **OS**:
-
-## Additional context
-
-<!-- Paste relevant command output, screenshots, or config snippets here. -->
@@ -1,31 +0,0 @@
----
-name: Feature request
-about: Suggest a new command, skill reference, or improvement
-title: "[Feature] "
-labels: enhancement
-assignees: ''
----
-
-## What problem does this solve?
-
-<!-- Describe the design/UX problem you keep running into. -->
-
-## Proposed solution
-
-<!-- What command, skill update, or anti-pattern guidance would help? -->
-
-## Provider(s) this applies to
-
-- [ ] Cursor
-- [ ] Claude Code
-- [ ] Gemini CLI
-- [ ] Codex CLI
-- [ ] VS Code Copilot
-- [ ] Kiro
-- [ ] OpenCode
-- [ ] Qoder
-- [ ] All providers
-
-## Alternatives considered
-
-<!-- Any other approaches you thought about? -->
@@ -1,21 +0,0 @@
-## Summary
-
-<!-- What does this PR change and why? -->
-
-## Type of change
-
-- [ ] New command
-- [ ] New / updated skill reference
-- [ ] New anti-pattern guidance
-- [ ] Bug fix
-- [ ] Documentation update
-- [ ] Build system / tooling
-- [ ] Other:
-
-## Checklist
-
-- [ ] Source files updated in `source/`
-- [ ] `bun run build` ran successfully
-- [ ] `bun test` passes
-- [ ] Tested with at least one provider (Cursor / Claude Code / Gemini CLI / Codex / Copilot / Kiro / OpenCode / Qoder)
-- [ ] README / DEVELOP.md updated if needed
@@ -1,167 +0,0 @@
----
-name: impeccable
-description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
-version: 3.1.1
-user-invocable: true
-argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · teach|document|extract|live] [target]"
-license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
----
-
-Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
-
-## Setup
-
-Before any design work or file edits:
-
-1. Load context (PRODUCT.md / DESIGN.md) via the loader script.
-2. Identify the register and load the matching register reference (brand.md or product.md).
-3. **If the user invoked a sub-command (e.g. `craft`, `shape`, `audit`), load its reference file too.** This is non-negotiable: `craft` without `craft.md` loaded means you'll skip the shape-and-confirm step the user expects.
-
-Skipping these produces generic output that ignores the project.
-
-### 1. Context gathering
-
-Two files, case-insensitive. The loader looks at the project root by default and falls back to `.agents/context/` and `docs/` if the root is clean. Override with `IMPECCABLE_CONTEXT_DIR=path/to/dir` (absolute or relative to cwd).
-
-- **PRODUCT.md**: required. Users, brand, tone, anti-references, strategic principles.
-- **DESIGN.md**: optional, strongly recommended. Colors, typography, elevation, components.
-
-Load both in one call:
-
-```bash
-node .github/skills/impeccable/scripts/load-context.mjs
-```
-
-Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`. The output's `contextDir` field tells you where the files were resolved from.
-
-If the output is already in this session's conversation history, don't re-run. Exceptions requiring a fresh load: you just ran `/impeccable teach` or `/impeccable document` (they rewrite the files), or the user manually edited one.
-
-`/impeccable live` already warms context via `live.mjs`. If you've run `live.mjs`, don't also run `load-context.mjs` this session.
-
-If PRODUCT.md is missing, empty, or placeholder (`[TODO]` markers, <200 chars): run `/impeccable teach`, then resume the user's original task with the fresh context. If the original task was `/impeccable craft`, resume into `/impeccable shape` before any implementation work.
-
-If DESIGN.md is missing: nudge once per session (*"Run `/impeccable document` for more on-brand output"*), then proceed.
-
-### 2. Register
-
-Every design task is **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboard, tool: design SERVES the product).
-
-Identify before designing. Priority: (1) cue in the task itself ("landing page" vs "dashboard"); (2) the surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. First match wins.
-
-If PRODUCT.md lacks the `register` field (legacy), infer it once from its "Users" and "Product Purpose" sections, then cache the inferred value for the session. Suggest the user run `/impeccable teach` to add the field explicitly.
-
-Load the matching reference: [reference/brand.md](reference/brand.md) or [reference/product.md](reference/product.md). The shared design laws below apply to both.
-
-## Shared design laws
-
-Apply to every design, both registers. Match implementation complexity to the aesthetic vision: maximalism needs elaborate code, minimalism needs precision. Interpret creatively. Vary across projects; never converge on the same choices. the model is capable of extraordinary work. Don't hold back.
-
-### Color
-
-- Use OKLCH. Reduce chroma as lightness approaches 0 or 100; high chroma at extremes looks garish.
-- Never use `#000` or `#fff`. Tint every neutral toward the brand hue (chroma 0.005–0.01 is enough).
-- Pick a **color strategy** before picking colors. Four steps on the commitment axis:
- - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism.
- - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages.
- - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz.
- - **Drenched**: the surface IS the color. Brand heroes, campaign pages.
-- The "one accent ≤10%" rule is Restrained only. Committed / Full palette / Drenched exceed it on purpose. Don't collapse every design to Restrained by reflex.
-
-### Theme
-
-Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe."
-
-Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does.
-
-"Observability dashboard" does not force an answer. "SRE glancing at incident severity on a 27-inch monitor at 2am in a dim room" does. Run the sentence, not the category.
-
-### Typography
-
-- Cap body line length at 65–75ch.
-- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales.
-
-### Layout
-
-- Vary spacing for rhythm. Same padding everywhere is monotony.
-- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
-- Don't wrap everything in a container. Most things don't need one.
-
-### Motion
-
-- Don't animate CSS layout properties.
-- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
-
-### Absolute bans
-
-Match-and-refuse. If you're about to write any of these, rewrite the element with different structure.
-
-- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing.
-- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size.
-- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing.
-- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché.
-- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly.
-- **Modal as first thought.** Modals are usually laziness. Exhaust inline / progressive alternatives first.
-
-### Copy
-
-- Every word earns its place. No restated headings, no intros that repeat the title.
-- **No em dashes.** Use commas, colons, semicolons, periods, or parentheses. Also not `--`.
-
-### The AI slop test
-
-If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference.
-
-**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses.
-
-- **First-order:** if someone could guess the theme + palette from the category alone ("observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black"), it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
-- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families.
-
-## Commands
-
-| Command | Category | Description | Reference |
-|---|---|---|---|
-| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) |
-| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) |
-| `teach` | Build | Set up PRODUCT.md and DESIGN.md context | [reference/teach.md](reference/teach.md) |
-| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) |
-| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) |
-| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) |
-| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) |
-| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) |
-| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) |
-| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) |
-| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) |
-| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) |
-| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) |
-| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) |
-| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) |
-| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) |
-| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) |
-| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) |
-| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) |
-| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) |
-| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) |
-| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
-| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
-
-### Routing rules
-
-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
-3. **First word doesn't match**: general design invocation. Apply the setup steps, shared design laws, and the loaded register reference, using the full argument as context.
-
-Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `/impeccable`.
-
-If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `teach` as a blocker, finish teach, refresh context, then resume the original command and target.
-
-## Pin / Unpin
-
-**Pin** creates a standalone shortcut so `/<command>` invokes `/impeccable <command>` directly. **Unpin** removes it. The script writes to every harness directory present in the project.
-
-```bash
-node .github/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
-```
-
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
@@ -1,190 +0,0 @@
-> **Additional context needed**: target platforms/devices and usage contexts.
-
-Adapt an existing design to a different context: another screen size, device, platform, or use case. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context.
-
-
----
-
-## Assess Adaptation Challenge
-
-Understand what needs adaptation and why:
-
-1. **Identify the source context**:
- - What was it designed for originally? (Desktop web? Mobile app?)
- - What assumptions were made? (Large screen? Mouse input? Fast connection?)
- - What works well in current context?
-
-2. **Understand target context**:
- - **Device**: Mobile, tablet, desktop, TV, watch, print?
- - **Input method**: Touch, mouse, keyboard, voice, gamepad?
- - **Screen constraints**: Size, resolution, orientation?
- - **Connection**: Fast wifi, slow 3G, offline?
- - **Usage context**: On-the-go vs desk, quick glance vs focused reading?
- - **User expectations**: What do users expect on this platform?
-
-3. **Identify adaptation challenges**:
- - What won't fit? (Content, navigation, features)
- - What won't work? (Hover states on touch, tiny touch targets)
- - What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop)
-
-**CRITICAL**: Adaptation is rethinking the experience for the new context, not scaling pixels.
-
-## Plan Adaptation Strategy
-
-Create context-appropriate strategy:
-
-### Mobile Adaptation (Desktop → Mobile)
-
-**Layout Strategy**:
-- Single column instead of multi-column
-- Vertical stacking instead of side-by-side
-- Full-width components instead of fixed widths
-- Bottom navigation instead of top/side navigation
-
-**Interaction Strategy**:
-- Touch targets 44x44px minimum (not hover-dependent)
-- Swipe gestures where appropriate (lists, carousels)
-- Bottom sheets instead of dropdowns
-- Thumbs-first design (controls within thumb reach)
-- Larger tap areas with more spacing
-
-**Content Strategy**:
-- Progressive disclosure (don't show everything at once)
-- Prioritize primary content (secondary content in tabs/accordions)
-- Shorter text (more concise)
-- Larger text (16px minimum)
-
-**Navigation Strategy**:
-- Hamburger menu or bottom navigation
-- Reduce navigation complexity
-- Sticky headers for context
-- Back button in navigation flow
-
-### Tablet Adaptation (Hybrid Approach)
-
-**Layout Strategy**:
-- Two-column layouts (not single or three-column)
-- Side panels for secondary content
-- Master-detail views (list + detail)
-- Adaptive based on orientation (portrait vs landscape)
-
-**Interaction Strategy**:
-- Support both touch and pointer
-- Touch targets 44x44px but allow denser layouts than phone
-- Side navigation drawers
-- Multi-column forms where appropriate
-
-### Desktop Adaptation (Mobile → Desktop)
-
-**Layout Strategy**:
-- Multi-column layouts (use horizontal space)
-- Side navigation always visible
-- Multiple information panels simultaneously
-- Fixed widths with max-width constraints (don't stretch to 4K)
-
-**Interaction Strategy**:
-- Hover states for additional information
-- Keyboard shortcuts
-- Right-click context menus
-- Drag and drop where helpful
-- Multi-select with Shift/Cmd
-
-**Content Strategy**:
-- Show more information upfront (less progressive disclosure)
-- Data tables with many columns
-- Richer visualizations
-- More detailed descriptions
-
-### Print Adaptation (Screen → Print)
-
-**Layout Strategy**:
-- Page breaks at logical points
-- Remove navigation, footer, interactive elements
-- Black and white (or limited color)
-- Proper margins for binding
-
-**Content Strategy**:
-- Expand shortened content (show full URLs, hidden sections)
-- Add page numbers, headers, footers
-- Include metadata (print date, page title)
-- Convert charts to print-friendly versions
-
-### Email Adaptation (Web → Email)
-
-**Layout Strategy**:
-- Narrow width (600px max)
-- Single column only
-- Inline CSS (no external stylesheets)
-- Table-based layouts (for email client compatibility)
-
-**Interaction Strategy**:
-- Large, obvious CTAs (buttons not text links)
-- No hover states (not reliable)
-- Deep links to web app for complex interactions
-
-## Implement Adaptations
-
-Apply changes systematically:
-
-### Responsive Breakpoints
-
-Choose appropriate breakpoints:
-- Mobile: 320px-767px
-- Tablet: 768px-1023px
-- Desktop: 1024px+
-- Or content-driven breakpoints (where design breaks)
-
-### Layout Adaptation Techniques
-
-- **CSS Grid/Flexbox**: Reflow layouts automatically
-- **Container Queries**: Adapt based on container, not viewport
-- **`clamp()`**: Fluid sizing between min and max
-- **Media queries**: Different styles for different contexts
-- **Display properties**: Show/hide elements per context
-
-### Touch Adaptation
-
-- Increase touch target sizes (44x44px minimum)
-- Add more spacing between interactive elements
-- Remove hover-dependent interactions
-- Add touch feedback (ripples, highlights)
-- Consider thumb zones (easier to reach bottom than top)
-
-### Content Adaptation
-
-- Use `display: none` sparingly (still downloads)
-- Progressive enhancement (core content first, enhancements on larger screens)
-- Lazy loading for off-screen content
-- Responsive images (`srcset`, `picture` element)
-
-### Navigation Adaptation
-
-- Transform complex nav to hamburger/drawer on mobile
-- Bottom nav bar for mobile apps
-- Persistent side navigation on desktop
-- Breadcrumbs on smaller screens for context
-
-**IMPORTANT**: Test on real devices. Device emulation in DevTools is helpful but not perfect.
-
-**NEVER**:
-- Hide core functionality on mobile (if it matters, make it work)
-- Assume desktop = powerful device (consider accessibility, older machines)
-- Use different information architecture across contexts (confusing)
-- Break user expectations for platform (mobile users expect mobile patterns)
-- Forget landscape orientation on mobile/tablet
-- Use generic breakpoints blindly (use content-driven breakpoints)
-- Ignore touch on desktop (many desktop devices have touch)
-
-## Verify Adaptations
-
-Test thoroughly across contexts:
-
-- **Real devices**: Test on actual phones, tablets, desktops
-- **Different orientations**: Portrait and landscape
-- **Different browsers**: Safari, Chrome, Firefox, Edge
-- **Different OS**: iOS, Android, Windows, macOS
-- **Different input methods**: Touch, mouse, keyboard
-- **Edge cases**: Very small screens (320px), very large screens (4K)
-- **Slow connections**: Test on throttled network
-
-When the adaptation feels native to each context, hand off to `/impeccable polish` for the final pass.
@@ -1,175 +0,0 @@
-> **Additional context needed**: performance constraints.
-
-Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it.
-
----
-
-## Register
-
-Brand: orchestrated page-load sequences, staggered reveals, scroll-driven animation. Motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions.
-
-Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it.
-
----
-
-## Assess Animation Opportunities
-
-Analyze where motion would improve the experience:
-
-1. **Identify static areas**:
- - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.)
- - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes)
- - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious
- - **Lack of delight**: Functional but joyless interactions
- - **Missed guidance**: Opportunities to direct attention or explain behavior
-
-2. **Understand the context**:
- - What's the personality? (Playful vs serious, energetic vs calm)
- - What's the performance budget? (Mobile-first? Complex page?)
- - Who's the audience? (Motion-sensitive users? Power users who want speed?)
- - What matters most? (One hero animation vs many micro-interactions?)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them.
-
-## Plan Animation Strategy
-
-Create a purposeful animation plan:
-
-- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?)
-- **Feedback layer**: Which interactions need acknowledgment?
-- **Transition layer**: Which state changes need smoothing?
-- **Delight layer**: Where can we surprise and delight?
-
-**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments.
-
-## Implement Animations
-
-Add motion systematically across these categories:
-
-### Entrance Animations
-- **Page load choreography**: Stagger element reveals (100-150ms delays), fade + slide combinations
-- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects)
-- **Content reveals**: Scroll-triggered animations using intersection observer
-- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management
-
-### Micro-interactions
-- **Button feedback**:
- - Hover: Subtle scale (1.02-1.05), color shift, shadow increase
- - Click: Quick scale down then up (0.95 → 1), ripple effect
- - Loading: Spinner or pulse state
-- **Form interactions**:
- - Input focus: Border color transition, slight scale or glow
- - Validation: Shake on error, check mark on success, smooth color transitions
-- **Toggle switches**: Smooth slide + color transition (200-300ms)
-- **Checkboxes/radio**: Check mark animation, ripple effect
-- **Like/favorite**: Scale + rotation, particle effects, color transition
-
-### State Transitions
-- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms)
-- **Expand/collapse**: Height transition with overflow handling, icon rotation
-- **Loading states**: Skeleton screen fades, spinner animations, progress bars
-- **Success/error**: Color transitions, icon animations, gentle scale pulse
-- **Enable/disable**: Opacity transitions, cursor changes
-
-### Navigation & Flow
-- **Page transitions**: Crossfade between routes, shared element transitions
-- **Tab switching**: Slide indicator, content fade/slide
-- **Carousel/slider**: Smooth transforms, snap points, momentum
-- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators
-
-### Feedback & Guidance
-- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights
-- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning
-- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation
-- **Focus flow**: Highlight path through form or workflow
-
-### Delight Moments
-- **Empty states**: Subtle floating animations on illustrations
-- **Completed actions**: Confetti, check mark flourish, success celebrations
-- **Easter eggs**: Hidden interactions for discovery
-- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches
-
-## Technical Implementation
-
-Use appropriate techniques for each animation:
-
-### Timing & Easing
-
-**Durations by purpose:**
-- **100-150ms**: Instant feedback (button press, toggle)
-- **200-300ms**: State changes (hover, menu open)
-- **300-500ms**: Layout changes (accordion, modal)
-- **500-800ms**: Entrance animations (page load)
-
-**Easing curves (use these, not CSS defaults):**
-```css
-/* Recommended: natural deceleration */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */
-
-/* AVOID: feel dated and tacky */
-/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */
-/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */
-```
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-### CSS Animations
-```css
-/* Prefer for simple, declarative animations */
-- transitions for state changes
-- @keyframes for complex sequences
-- transform and opacity for reliable movement
-- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth
-```
-
-### JavaScript Animation
-```javascript
-/* Use for complex, interactive animations */
-- Web Animations API for programmatic control
-- Framer Motion for React
-- GSAP for complex sequences
-```
-
-### Performance
-- **Motion materials**: Use transform/opacity for reliable movement, but use blur, filters, masks, shadows, and color shifts when they materially improve the effect
-- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- **will-change**: Add sparingly for known expensive animations
-- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate
-- **Monitor FPS**: Ensure 60fps on target devices
-
-### Accessibility
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**NEVER**:
-- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself
-- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work
-- Use durations over 500ms for feedback (it feels laggy)
-- Animate without purpose (every animation needs a reason)
-- Ignore `prefers-reduced-motion` (this is an accessibility violation)
-- Animate everything (animation fatigue makes interfaces feel exhausting)
-- Block interaction during animations unless intentional
-
-## Verify Quality
-
-Test animations thoroughly:
-
-- **Smooth at 60fps**: No jank on target devices
-- **Feels natural**: Easing curves feel organic, not robotic
-- **Appropriate timing**: Not too fast (jarring) or too slow (laggy)
-- **Reduced motion works**: Animations disabled or simplified appropriately
-- **Doesn't block**: Users can interact during/after animations
-- **Adds value**: Makes interface clearer or more delightful
-
-When the motion clarifies state instead of decorating it, hand off to `/impeccable polish` for the final pass.
@@ -1,133 +0,0 @@
-Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues; document them for other commands to address.
-
-This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation.
-
-## Diagnostic Scan
-
-Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below.
-
-### 1. Accessibility (A11y)
-
-**Check for**:
-- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA)
-- **Missing ARIA**: Interactive elements without proper roles, labels, or states
-- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps
-- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons
-- **Alt text**: Missing or poor image descriptions
-- **Form issues**: Inputs without labels, poor error messaging, missing required indicators
-
-**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA)
-
-### 2. Performance
-
-**Check for**:
-- **Layout thrashing**: Reading/writing layout properties in loops
-- **Expensive animations**: Casual layout-property animation, unbounded blur/filter/shadow effects, or effects that visibly drop frames
-- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change
-- **Bundle size**: Unnecessary imports, unused dependencies
-- **Render performance**: Unnecessary re-renders, missing memoization
-
-**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized)
-
-### 3. Theming
-
-**Check for**:
-- **Hard-coded colors**: Colors not using design tokens
-- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme
-- **Inconsistent tokens**: Using wrong tokens, mixing token types
-- **Theme switching issues**: Values that don't update on theme change
-
-**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly)
-
-### 4. Responsive Design
-
-**Check for**:
-- **Fixed widths**: Hard-coded widths that break on mobile
-- **Touch targets**: Interactive elements < 44x44px
-- **Horizontal scroll**: Content overflow on narrow viewports
-- **Text scaling**: Layouts that break when text size increases
-- **Missing breakpoints**: No mobile/tablet variants
-
-**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets)
-
-### 5. Anti-Patterns (CRITICAL)
-
-Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy).
-
-**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design)
-
-## Generate Report
-
-### Audit Health Score
-
-| # | Dimension | Score | Key Finding |
-|---|-----------|-------|-------------|
-| 1 | Accessibility | ? | [most critical a11y issue or "--"] |
-| 2 | Performance | ? | |
-| 3 | Responsive Design | ? | |
-| 4 | Theming | ? | |
-| 5 | Anti-Patterns | ? | |
-| **Total** | | **??/20** | **[Rating band]** |
-
-**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues)
-
-### Anti-Patterns Verdict
-**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest.
-
-### Executive Summary
-- Audit Health Score: **??/20** ([rating band])
-- Total issues found (count by severity: P0/P1/P2/P3)
-- Top 3-5 critical issues
-- Recommended next steps
-
-### Detailed Findings by Severity
-
-Tag every issue with **P0-P3 severity**:
-- **P0 Blocking**: Prevents task completion. Fix immediately
-- **P1 Major**: Significant difficulty or WCAG AA violation. Fix before release
-- **P2 Minor**: Annoyance, workaround exists. Fix in next pass
-- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits
-
-For each issue, document:
-- **[P?] Issue name**
-- **Location**: Component, file, line
-- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern
-- **Impact**: How it affects users
-- **WCAG/Standard**: Which standard it violates (if applicable)
-- **Recommendation**: How to fix it
-- **Suggested command**: Which command to use (prefer: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-### Patterns & Systemic Issues
-
-Identify recurring problems that indicate systemic gaps rather than one-off mistakes:
-- "Hard-coded colors appear in 15+ components, should use design tokens"
-- "Touch targets consistently too small (<44px) throughout mobile experience"
-
-### Positive Findings
-
-Note what's working well: good practices to maintain and replicate.
-
-## Recommended Actions
-
-List recommended commands in priority order (P0 first, then P1, then P2):
-
-1. **[P?] `/command-name`**: Brief description (specific context from audit findings)
-2. **[P?] `/command-name`**: Brief description (specific context)
-
-**Rules**: Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset. Map findings to the most appropriate command. End with `/impeccable polish` as the final step if any fixes were recommended.
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable audit` after fixes to see your score improve.
-
-**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters.
-
-**NEVER**:
-- Report issues without explaining impact (why does this matter?)
-- Provide generic recommendations (be specific and actionable)
-- Skip positive findings (celebrate what works)
-- Forget to prioritize (everything can't be P0)
-- Report false positives without verification
-
@@ -1,113 +0,0 @@
-When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact and personality through stronger hierarchy, committed scale, and decisive type.
-
----
-
-## Register
-
-Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
-
-Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too safe or boring:
-
-1. **Identify weakness sources**:
- - **Generic choices**: System fonts, basic colors, standard layouts
- - **Timid scale**: Everything is medium-sized with no drama
- - **Low contrast**: Everything has similar visual weight
- - **Static**: No motion, no energy, no life
- - **Predictable**: Standard patterns with no surprises
- - **Flat hierarchy**: Nothing stands out or commands attention
-
-2. **Understand the context**:
- - What's the brand personality? (How far can we push?)
- - What's the purpose? (Marketing can be bolder than financial dashboards)
- - Who's the audience? (What will resonate?)
- - What are the constraints? (Brand guidelines, accessibility, performance)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
-
-**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
-
-## Plan Amplification
-
-Create a strategy to increase impact while maintaining coherence:
-
-- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
-- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
-- **Risk budget**: How experimental can we be? Push boundaries within constraints.
-- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
-
-**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration.
-
-## Amplify the Design
-
-Systematically increase impact across these dimensions:
-
-### Typography Amplification
-- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and [typography.md](typography.md) for inspiration)
-- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
-- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
-- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
-
-### Color Intensification
-- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
-- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop
-- **Dominant color strategy**: Let one bold color own 60% of the design
-- **Sharp accents**: High-contrast accent colors that pop
-- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
-- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
-
-### Spatial Drama
-- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
-- **Break the grid**: Let hero elements escape containers and cross boundaries
-- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
-- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
-- **Overlap**: Layer elements intentionally for depth
-
-### Visual Effects
-- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
-- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
-- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop)
-- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
-- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
-
-### Motion & Animation
-- **Entrance choreography**: Staggered, dramatic page load animations with 50-100ms delays
-- **Scroll effects**: Parallax, reveal animations, scroll-triggered sequences
-- **Micro-interactions**: Satisfying hover effects, click feedback, state changes
-- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect)
-
-### Composition Boldness
-- **Hero moments**: Create clear focal points with dramatic treatment
-- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
-- **Full-bleed elements**: Use full viewport width/height for impact
-- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
-
-**NEVER**:
-- Add effects randomly without purpose (chaos ≠ bold)
-- Sacrifice readability for aesthetics (body text must be readable)
-- Make everything bold (then nothing is bold; you need contrast)
-- Ignore accessibility (bold design must still meet WCAG standards)
-- Overwhelm with motion (animation fatigue is real)
-- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
-
-## Verify Quality
-
-Ensure amplification maintains usability and coherence:
-
-- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over.
-- **Still functional**: Can users accomplish tasks without distraction?
-- **Coherent**: Does everything feel intentional and unified?
-- **Memorable**: Will users remember this experience?
-- **Performant**: Do all these effects run smoothly?
-- **Accessible**: Does it still meet accessibility standards?
-
-**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects."
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,118 +0,0 @@
-# Brand register
-
-When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made.
-
-The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look.
-
-## The brand slop test
-
-If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?"
-
-Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home.
-
-**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register.
-
-Then the inverse test: in one sentence, describe what you're about to build the way a competitor would describe theirs. If that sentence fits the modal landing page in the category, restart.
-
-## Typography
-
-### Font selection procedure
-
-Every project. Never skip.
-
-1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words.
-2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture.
-3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy."
-4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over.
-
-### Reflex-reject list
-
-Training-data defaults. Ban list. Look further:
-
-Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif
-
-### Reflex-reject aesthetic lanes
-
-Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further.
-
-- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery.
-
-(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.)
-
-The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md).
-
-### Pairing and voice
-
-Distinctive + refined is the goal. The specific shape depends on the brand:
-
-- **Editorial / long-form / luxury**: display serif + sans body (a magazine shape).
-- **Tech / dev tools / fintech**: one committed sans, usually; custom-tight tracking, strong weight contrast inside a single family.
-- **Consumer / food / travel**: warmer pairings, often a humanist sans plus a script or display serif.
-- **Creative studios / agencies**: rule-breaking welcome. Mono-only, or display-only, or custom-drawn type as voice.
-
-Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair.
-
-Vary across projects. If the last brief was a serif-display landing page, this one isn't.
-
-### Scale
-
-Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted.
-
-Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room.
-
-## Color
-
-Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register.
-
-- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige.
-- Palette IS voice. A calm brand and a restless brand should not share palette mechanics.
-- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit.
-- Don't converge across projects. If the last brand surface was restrained-on-cream, this one is not.
-- When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette.
-
-## Layout
-
-- Asymmetric compositions are one option. Break the grid intentionally for emphasis.
-- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings.
-- Alternative: a strict, visible grid as the voice (brutalist / Swiss / tech-spec aesthetics). Either asymmetric or rigorously-gridded can be "designed"; the failure mode is splitting the difference into a generic centered stack.
-- Don't default to centering everything. Left-aligned with asymmetric layouts feels more designed; a strict grid reads as confident structure. A centered-stack hero with icon-title-subtitle cards reads as template.
-- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness.
-
-## Imagery
-
-Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo.
-
-**When the brief implies imagery (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product), you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy.
-
-- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `<div>` placeholders.
-- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel".
-- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one.
-- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish".
-
-"Imagery" here is broader than stock photography: product screenshots, custom data visualizations, generated SVG, and canvas/WebGL scenes are all imagery. Text-only pages where typography alone carries the entire visual weight are the failure mode.
-
-## Motion
-
-- One well-orchestrated page-load with staggered reveals beats scattered micro-interactions, when the brand invites it. Tech-minimal brands often skip entrance motion entirely; the restraint is the voice.
-- For collapsing/expanding sections, transition `grid-template-rows` rather than `height`.
-
-## Brand bans (on top of the shared absolute bans)
-
-- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume.
-- Large rounded-corner icons above every heading. Screams template.
-- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.)
-- All-caps body copy. Reserve caps for short labels and headings.
-- Timid palettes and average layouts. Safe = invisible.
-- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs.
-- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic.
-- Repeated tiny uppercase tracked labels above every section heading. A single strong kicker can be voice; repeating it as section grammar is AI scaffolding unless it's a deliberate, named brand system.
-
-## Brand permissions
-
-Brand can afford things product can't. Take them.
-
-- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography.
-- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing.
-- Typographic risk. Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines, a single oversize word as a hero.
-- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics.
-- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment.
@@ -1,174 +0,0 @@
-> **Additional context needed**: audience technical level and users' mental state in context.
-
-Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task.
-
-
----
-
-## Assess Current Copy
-
-Identify what makes the text unclear or ineffective:
-
-1. **Find clarity problems**:
- - **Jargon**: Technical terms users won't understand
- - **Ambiguity**: Multiple interpretations possible
- - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file"
- - **Length**: Too wordy or too terse
- - **Assumptions**: Assuming user knowledge they don't have
- - **Missing context**: Users don't know what to do or why
- - **Tone mismatch**: Too formal, too casual, or inappropriate for situation
-
-2. **Understand the context**:
- - Who's the audience? (Technical? General? First-time users?)
- - What's the user's mental state? (Stressed during error? Confident during success?)
- - What's the action? (What do we want users to do?)
- - What's the constraint? (Character limits? Space limitations?)
-
-**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets.
-
-## Plan Copy Improvements
-
-Create a strategy for clearer communication:
-
-- **Primary message**: What's the ONE thing users need to know?
-- **Action needed**: What should users do next (if anything)?
-- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?)
-- **Constraints**: Length limits, brand voice, localization considerations
-
-**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words.
-
-## Improve Copy Systematically
-
-Refine text across these common areas:
-
-### Error Messages
-**Bad**: "Error 403: Forbidden"
-**Good**: "You don't have permission to view this page. Contact your admin for access."
-
-**Bad**: "Invalid input"
-**Good**: "Email addresses need an @ symbol. Try: name@example.com"
-
-**Principles**:
-- Explain what went wrong in plain language
-- Suggest how to fix it
-- Don't blame the user
-- Include examples when helpful
-- Link to help/support if applicable
-
-### Form Labels & Instructions
-**Bad**: "DOB (MM/DD/YYYY)"
-**Good**: "Date of birth" (with placeholder showing format)
-
-**Bad**: "Enter value here"
-**Good**: "Your email address" or "Company name"
-
-**Principles**:
-- Use clear, specific labels (not generic placeholders)
-- Show format expectations with examples
-- Explain why you're asking (when not obvious)
-- Put instructions before the field, not after
-- Keep required field indicators clear
-
-### Button & CTA Text
-**Bad**: "Click here" | "Submit" | "OK"
-**Good**: "Create account" | "Save changes" | "Got it, thanks"
-
-**Principles**:
-- Describe the action specifically
-- Use active voice (verb + noun)
-- Match user's mental model
-- Be specific ("Save" is better than "OK")
-
-### Help Text & Tooltips
-**Bad**: "This is the username field"
-**Good**: "Choose a username. You can change this later in Settings."
-
-**Principles**:
-- Add value (don't just repeat the label)
-- Answer the implicit question ("What is this?" or "Why do you need this?")
-- Keep it brief but complete
-- Link to detailed docs if needed
-
-### Empty States
-**Bad**: "No items"
-**Good**: "No projects yet. Create your first project to get started."
-
-**Principles**:
-- Explain why it's empty (if not obvious)
-- Show next action clearly
-- Make it welcoming, not dead-end
-
-### Success Messages
-**Bad**: "Success"
-**Good**: "Settings saved! Your changes will take effect immediately."
-
-**Principles**:
-- Confirm what happened
-- Explain what happens next (if relevant)
-- Be brief but complete
-- Match the user's emotional moment (celebrate big wins)
-
-### Loading States
-**Bad**: "Loading..." (for 30+ seconds)
-**Good**: "Analyzing your data... this usually takes 30-60 seconds"
-
-**Principles**:
-- Set expectations (how long?)
-- Explain what's happening (when it's not obvious)
-- Show progress when possible
-- Offer escape hatch if appropriate ("Cancel")
-
-### Confirmation Dialogs
-**Bad**: "Are you sure?"
-**Good**: "Delete 'Project Alpha'? This can't be undone."
-
-**Principles**:
-- State the specific action
-- Explain consequences (especially for destructive actions)
-- Use clear button labels ("Delete project" not "Yes")
-- Don't overuse confirmations (only for risky actions)
-
-### Navigation & Wayfinding
-**Bad**: Generic labels like "Items" | "Things" | "Stuff"
-**Good**: Specific labels like "Your projects" | "Team members" | "Settings"
-
-**Principles**:
-- Be specific and descriptive
-- Use language users understand (not internal jargon)
-- Make hierarchy clear
-- Consider information scent (breadcrumbs, current location)
-
-## Apply Clarity Principles
-
-Every piece of copy should follow these rules:
-
-1. **Be specific**: "Enter email" not "Enter value"
-2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity)
-3. **Be active**: "Save changes" not "Changes will be saved"
-4. **Be human**: "Oops, something went wrong" not "System error encountered"
-5. **Tell users what to do**, not just what happened
-6. **Be consistent**: Use same terms throughout (don't vary for variety)
-
-**NEVER**:
-- Use jargon without explanation
-- Blame users ("You made an error" → "This field is required")
-- Be vague ("Something went wrong" without explanation)
-- Use passive voice unnecessarily
-- Write overly long explanations (be concise)
-- Use humor for errors (be empathetic instead)
-- Assume technical knowledge
-- Vary terminology (pick one term and stick with it)
-- Repeat information (headers restating intros, redundant explanations)
-- Use placeholders as the only labels (they disappear when users type)
-
-## Verify Improvements
-
-Test that copy improvements work:
-
-- **Comprehension**: Can users understand without context?
-- **Actionability**: Do users know what to do next?
-- **Brevity**: Is it as short as possible while remaining clear?
-- **Consistency**: Does it match terminology elsewhere?
-- **Tone**: Is it appropriate for the situation?
-
-When the copy reads cleanly, hand off to `/impeccable polish` for the final pass.
@@ -1,105 +0,0 @@
-# Codex: Visual Direction & Asset Production
-
-This file is loaded by `/impeccable craft` when the harness has native image generation (currently Codex via `image_gen`). Other harnesses skip it. It covers the two craft steps that depend on real image generation: landing the visual direction, and producing the raster assets the implementation will compose.
-
-Read this *before* generating any images. The order matters, and the per-step user pauses are what keep generated imagery from drifting away from the brief.
-
-### Four stop points before code
-
-Steps A through D each end with the user. Do not advance past any of them on your own read of the situation.
-
-1. **STOP after Step A questions.** Wait for answers.
-2. **STOP after Step B palette generation.** Wait for "confirm palette."
-3. **STOP after Step C mocks.** Wait for direction approval or delegation.
-4. **Only after Step D approves a direction** do you return to craft.md Step 4 and write code.
-
-Prior shape approval does **not** satisfy any of these. Shape's "confirm or override" advances you into Step A; it is not a substitute for it.
-
-## Step A: Explore Directions with the User
-
-Before generating anything, run a brief direction conversation grounded in the shape brief.
-
-**Step A is required even when shape just produced a confirmed brief.** The shape questions and Step A questions cover different ground: shape pins purpose, content, scope; Step A pins palette, atmosphere, and named visual references for the comps you're about to generate. The only time you can skip Step A is when the user has already answered these exact palette/atmosphere/reference questions in the same session.
-
-Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions:
-
-- "Brief says 'editorial restraint, Klim-adjacent.' Are we closer to a quiet specimen page or a magazine-spread feel with hero imagery?"
-- "Palette strategy from shape was 'Committed.' Want it warm-grounded (deep oxblood + cream) or cool-grounded (slate + paper white)?"
-
-**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded.
-
-## Step B: Generate the Brand Palette First
-
-Generate **one** palette artifact before any mocks. This is a small, focused image: typography pairing on the chosen background, primary + accent color swatches, one signature ornament or motif. Single image, single pass.
-
-Why palette first: mocks generated against a vague color sense produce noise that drowns out the structural decisions. A confirmed palette is the first concrete contract for everything downstream.
-
-Show the palette to the user. Ask one question: "This is the palette I'm locking in for the mocks. Confirm, or call out what to shift?"
-
-**STOP and wait for confirmation.** Do not generate mocks against an unconfirmed palette. "Probably good enough" is the wrong call here; the palette is the contract for everything downstream.
-
-## Step C: Generate 1-3 Visual Mocks Against the Palette
-
-Once the palette is confirmed, generate **1 to 3** high-fidelity north-star comps. Each mock must use the confirmed palette and typography. Mocks differ in *structural* direction (hierarchy, topology, density, composition), not in color or motif.
-
-- Brand work: push visual identity, composition, mood, and signature motifs.
-- Product work: push hierarchy, topology, density, tone, grounded in realistic product structure.
-- Landing pages and long-form brand surfaces: show enough of the second fold to establish the system beyond the hero.
-
-Use the `image_gen` tool directly (or via the imagegen skill when available). Don't ask the user to install anything.
-
-## Step D: Approval Loop
-
-Show the comps. Ask what carries forward. Iterate until **one direction is approved** or the user explicitly delegates.
-
-**STOP and wait for the approval or the delegation.** Do not begin Step E or return to craft.md Step 4 until a single direction is named. If the user delegates, pick the strongest direction and explain it from the brief, not personal taste.
-
-Before moving to assets, summarize what to carry into code and what *not* to literalize from the mock. This is the handoff between visual exploration and semantic implementation.
-
-## Step E: Mock Fidelity Inventory
-
-Inventory the approved mock's major visible ingredients. For each, decide implementation: semantic HTML/CSS/SVG, generated raster, sourced raster, icon library, canvas/WebGL, or accepted omission.
-
-Common ingredients to inventory:
-
-- Hero silhouette and dominant composition
-- Signature motifs (planets, devices, portraits, charts, route lines, insets, badges, etc.)
-- Nav and primary CTA treatment
-- Section sequence, especially the second fold
-- Image-native content the concept depends on
-- Typography, density, color/material treatment, motion cues
-
-Treat the mock as a north star, not a screenshot to trace. Don't rasterize core UI text. But if the live result lacks the mock's major ingredients, the implementation is wrong.
-
-If a photographic, architectural, product, or place-led mock becomes generic CSS scenery, decorative diagrams, bullets, or copy, stop and fix it. That's a broken implementation, not a harmless interpretation.
-
-Don't substitute a different hero composition or visual driver post-approval without user sign-off.
-
-## Step F: Asset Slicing via the Asset Producer
-
-Raster ingredients identified in Step E need clean production assets. Use the bundled `impeccable_asset_producer` subagent rather than producing inline.
-
-Spawn it as a scoped subagent. If you do not have explicit permission to use agents, stop and ask:
-
-```text
-Asset production will work better as a scoped subagent job. Should I spawn the Impeccable asset producer subagent for this step?
-```
-
-Pass to the agent:
-
-- Approved mock path or screenshot reference
-- Crop paths or a contact sheet with crop ids
-- Output directory
-- Required dimensions, format, transparency needs
-- Avoid list
-- Notes on what should remain semantic HTML/CSS/SVG instead of raster
-
-Attach image generation capability to the spawned agent when the harness supports it. Do **not** load image-generation reference material into the parent thread.
-
-Inline asset production is allowed only if the user declines subagents, the harness cannot spawn the authorized agent, or the user explicitly asks for single-thread mode.
-
-Prefer HTML/CSS/SVG/canvas when they can credibly reproduce an ingredient; reach for real, generated, or stock imagery when the mock or subject matter calls for actual visual content.
-
-## After This File
-
-Once Steps A through F are complete, return to `craft.md` Step 5 (Build to Production Quality). The implementation builds against the confirmed palette, approved mock, and the assets the producer wrote.
@@ -1,106 +0,0 @@
-# Cognitive Load Assessment
-
-Cognitive load is the total mental effort required to use an interface. Overloaded users make mistakes, get frustrated, and leave. This reference helps identify and fix cognitive overload.
-
----
-
-## Three Types of Cognitive Load
-
-### Intrinsic Load: The Task Itself
-Complexity inherent to what the user is trying to do. You can't eliminate this, but you can structure it.
-
-**Manage it by**:
-- Breaking complex tasks into discrete steps
-- Providing scaffolding (templates, defaults, examples)
-- Progressive disclosure: show what's needed now, hide the rest
-- Grouping related decisions together
-
-### Extraneous Load: Bad Design
-Mental effort caused by poor design choices. **Eliminate this ruthlessly.** It's pure waste.
-
-**Common sources**:
-- Confusing navigation that requires mental mapping
-- Unclear labels that force users to guess meaning
-- Visual clutter competing for attention
-- Inconsistent patterns that prevent learning
-- Unnecessary steps between user intent and result
-
-### Germane Load: Learning Effort
-Mental effort spent building understanding. This is *good* cognitive load; it leads to mastery.
-
-**Support it by**:
-- Progressive disclosure that reveals complexity gradually
-- Consistent patterns that reward learning
-- Feedback that confirms correct understanding
-- Onboarding that teaches through action, not walls of text
-
----
-
-## Cognitive Load Checklist
-
-Evaluate the interface against these 8 items:
-
-- [ ] **Single focus**: Can the user complete their primary task without distraction from competing elements?
-- [ ] **Chunking**: Is information presented in digestible groups (≤4 items per group)?
-- [ ] **Grouping**: Are related items visually grouped together (proximity, borders, shared background)?
-- [ ] **Visual hierarchy**: Is it immediately clear what's most important on the screen?
-- [ ] **One thing at a time**: Can the user focus on a single decision before moving to the next?
-- [ ] **Minimal choices**: Are decisions simplified (≤4 visible options at any decision point)?
-- [ ] **Working memory**: Does the user need to remember information from a previous screen to act on the current one?
-- [ ] **Progressive disclosure**: Is complexity revealed only when the user needs it?
-
-**Scoring**: Count the failed items. 0–1 failures = low cognitive load (good). 2–3 = moderate (address soon). 4+ = high cognitive load (critical fix needed).
-
----
-
-## The Working Memory Rule
-
-**Humans can hold ≤4 items in working memory at once** (Miller's Law revised by Cowan, 2001).
-
-At any decision point, count the number of distinct options, actions, or pieces of information a user must simultaneously consider:
-- **≤4 items**: Within working memory limits, manageable
-- **5–7 items**: Pushing the boundary; consider grouping or progressive disclosure
-- **8+ items**: Overloaded; users will skip, misclick, or abandon
-
-**Practical applications**:
-- Navigation menus: ≤5 top-level items (group the rest under clear categories)
-- Form sections: ≤4 fields visible per group before a visual break
-- Action buttons: 1 primary, 1–2 secondary, group the rest in a menu
-- Dashboard widgets: ≤4 key metrics visible without scrolling
-- Pricing tiers: ≤3 options (more causes analysis paralysis)
-
----
-
-## Common Cognitive Load Violations
-
-### 1. The Wall of Options
-**Problem**: Presenting 10+ choices at once with no hierarchy.
-**Fix**: Group into categories, highlight recommended, use progressive disclosure.
-
-### 2. The Memory Bridge
-**Problem**: User must remember info from step 1 to complete step 3.
-**Fix**: Keep relevant context visible, or repeat it where it's needed.
-
-### 3. The Hidden Navigation
-**Problem**: User must build a mental map of where things are.
-**Fix**: Always show current location (breadcrumbs, active states, progress indicators).
-
-### 4. The Jargon Barrier
-**Problem**: Technical or domain language forces translation effort.
-**Fix**: Use plain language. If domain terms are unavoidable, define them inline.
-
-### 5. The Visual Noise Floor
-**Problem**: Every element has the same visual weight; nothing stands out.
-**Fix**: Establish clear hierarchy: one primary element, 2–3 secondary, everything else muted.
-
-### 6. The Inconsistent Pattern
-**Problem**: Similar actions work differently in different places.
-**Fix**: Standardize interaction patterns. Same type of action = same type of UI.
-
-### 7. The Multi-Task Demand
-**Problem**: Interface requires processing multiple simultaneous inputs (reading + deciding + navigating).
-**Fix**: Sequence the steps. Let the user do one thing at a time.
-
-### 8. The Context Switch
-**Problem**: User must jump between screens/tabs/modals to gather info for a single decision.
-**Fix**: Co-locate the information needed for each decision. Reduce back-and-forth.
@@ -1,105 +0,0 @@
-# Color & Contrast
-
-## Color Spaces: Use OKLCH
-
-**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark.
-
-The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish.
-
-The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand.
-
-## Building Functional Palettes
-
-### Tinted Neutrals
-
-**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces.
-
-The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette.
-
-**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects.
-
-### Palette Structure
-
-A complete system needs:
-
-| Role | Purpose | Example |
-|------|---------|---------|
-| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades |
-| **Neutral** | Text, backgrounds, borders | 9-11 shade scale |
-| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each |
-| **Surface** | Cards, modals, overlays | 2-3 elevation levels |
-
-**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise.
-
-### The 60-30-10 Rule (Applied Correctly)
-
-This rule is about **visual weight**, not pixel count:
-
-- **60%**: Neutral backgrounds, white space, base surfaces
-- **30%**: Secondary colors: text, borders, inactive states
-- **10%**: Accent: CTAs, highlights, focus states
-
-The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power.
-
-## Contrast & Accessibility
-
-### WCAG Requirements
-
-| Content Type | AA Minimum | AAA Target |
-|--------------|------------|------------|
-| Body text | 4.5:1 | 7:1 |
-| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 |
-| UI components, icons | 3:1 | 4.5:1 |
-| Non-essential decorations | None | None |
-
-**The gotcha**: Placeholder text still needs 4.5:1. That light gray placeholder you see everywhere? Usually fails WCAG.
-
-### Dangerous Color Combinations
-
-These commonly fail contrast or cause readability issues:
-
-- Light gray text on white (the #1 accessibility fail)
-- **Gray text on any colored background**: gray looks washed out and dead on color. Use a darker shade of the background color, or transparency
-- Red text on green background (or vice versa): 8% of men can't distinguish these
-- Blue text on red background (vibrates visually)
-- Yellow text on white (almost always fails)
-- Thin light text on images (unpredictable contrast)
-
-### Never Use Pure Gray or Pure Black
-
-Pure gray (`oklch(50% 0 0)`) and pure black (`#000`) don't exist in nature; real shadows and surfaces always have a color cast. Even a chroma of 0.005-0.01 is enough to feel natural without being obviously tinted. (See tinted neutrals example above.)
-
-### Testing
-
-Don't trust your eyes. Use tools:
-
-- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/)
-- Browser DevTools → Rendering → Emulate vision deficiencies
-- [Polypane](https://polypane.app/) for real-time testing
-
-## Theming: Light & Dark Mode
-
-### Dark Mode Is Not Inverted Light Mode
-
-You can't just swap colors. Dark mode requires different design decisions:
-
-| Light Mode | Dark Mode |
-|------------|-----------|
-| Shadows for depth | Lighter surfaces for depth (no shadows) |
-| Dark text on light | Light text on dark (reduce font weight) |
-| Vibrant accents | Desaturate accents slightly |
-| White backgrounds | Never pure black; use dark gray (oklch 12-18%) |
-
-In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light.
-
-### Token Hierarchy
-
-Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same.
-
-## Alpha Is A Design Smell
-
-Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed.
-
----
-
-**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Using pure black (#000) for large areas. Skipping color blindness testing (8% of men affected).
@@ -1,154 +0,0 @@
-> **Additional context needed**: existing brand colors.
-
-Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit.
-
----
-
-## Register
-
-Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it.
-
-Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen.
-
----
-
-## Assess Color Opportunity
-
-Analyze the current state and identify opportunities:
-
-1. **Understand current state**:
- - **Color absence**: Pure grayscale? Limited neutrals? One timid accent?
- - **Missed opportunities**: Where could color add meaning, hierarchy, or delight?
- - **Context**: What's appropriate for this domain and audience?
- - **Brand**: Are there existing brand colors we should use?
-
-2. **Identify where color adds value**:
- - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue)
- - **Hierarchy**: Drawing attention to important elements
- - **Categorization**: Different sections, types, or states
- - **Emotional tone**: Warmth, energy, trust, creativity
- - **Wayfinding**: Helping users navigate and understand structure
- - **Delight**: Moments of visual interest and personality
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose.
-
-## Plan Color Strategy
-
-Create a purposeful color introduction plan:
-
-- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals)
-- **Dominant color**: Which color owns 60% of colored elements?
-- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%)
-- **Application strategy**: Where does each color appear and why?
-
-**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more.
-
-## Introduce Color Strategically
-
-Add color systematically across these dimensions:
-
-### Semantic Color
-- **State indicators**:
- - Success: Green tones (emerald, forest, mint)
- - Error: Red/pink tones (rose, crimson, coral)
- - Warning: Orange/amber tones
- - Info: Blue tones (sky, ocean, indigo)
- - Neutral: Gray/slate for inactive states
-
-- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.)
-- **Progress indicators**: Colored bars, rings, or charts showing completion or health
-
-### Accent Color Application
-- **Primary actions**: Color the most important buttons/CTAs
-- **Links**: Add color to clickable text (maintain accessibility)
-- **Icons**: Colorize key icons for recognition and personality
-- **Headers/titles**: Add color to section headers or key labels
-- **Hover states**: Introduce color on interaction
-
-### Background & Surfaces
-- **Tinted backgrounds**: Replace pure gray (`#f5f5f5`) with warm neutrals (`oklch(97% 0.01 60)`) or cool tints (`oklch(97% 0.01 250)`)
-- **Colored sections**: Use subtle background colors to separate areas
-- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue)
-- **Cards & surfaces**: Tint cards or surfaces slightly for warmth
-
-**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
-
-### Data Visualization
-- **Charts & graphs**: Use color to encode categories or values
-- **Heatmaps**: Color intensity shows density or importance
-- **Comparison**: Color coding for different datasets or timeframes
-
-### Borders & Accents
-- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`)
-- **Underlines**: Color underlines for emphasis or active states
-- **Dividers**: Subtle colored dividers instead of gray lines
-- **Focus rings**: Colored focus indicators matching brand
-- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe
-
-**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe.
-
-### Typography Color
-- **Colored headings**: Use brand colors for section headings (maintain contrast)
-- **Highlight text**: Color for emphasis or categories
-- **Labels & tags**: Small colored labels for metadata or categories
-
-### Decorative Elements
-- **Illustrations**: Add colored illustrations or icons
-- **Shapes**: Geometric shapes in brand colors as background elements
-- **Gradients**: Colorful gradient overlays or mesh backgrounds
-- **Blobs/organic shapes**: Soft colored shapes for visual interest
-
-## Balance & Refinement
-
-Ensure color addition improves rather than overwhelms:
-
-### Maintain Hierarchy
-- **Dominant color** (60%): Primary brand color or most used accent
-- **Secondary color** (30%): Supporting color for variety
-- **Accent color** (10%): High contrast for key moments
-- **Neutrals** (remaining): Gray/black/white for structure
-
-### Accessibility
-- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components)
-- **Don't rely on color alone**: Use icons, labels, or patterns alongside color
-- **Test for color blindness**: Verify red/green combinations work for all users
-
-### Cohesion
-- **Consistent palette**: Use colors from defined palette, not arbitrary choices
-- **Systematic application**: Same color meanings throughout (green always = success)
-- **Temperature consistency**: Warm palette stays warm, cool stays cool
-
-**NEVER**:
-- Use every color in the rainbow (choose 2-4 colors beyond neutrals)
-- Apply color randomly without semantic meaning
-- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead
-- Use pure gray for neutrals. Add subtle color tint (warm or cool) for depth
-- Use pure black (`#000`) or pure white (`#fff`) for large areas
-- Violate WCAG contrast requirements
-- Use color as the only indicator (accessibility issue)
-- Make everything colorful (defeats the purpose)
-- Default to purple-blue gradients (AI slop aesthetic)
-
-## Verify Color Addition
-
-Test that colorization improves the experience:
-
-- **Better hierarchy**: Does color guide attention appropriately?
-- **Clearer meaning**: Does color help users understand states/categories?
-- **More engaging**: Does the interface feel warmer and more inviting?
-- **Still accessible**: Do all color combinations meet WCAG standards?
-- **Not overwhelming**: Is color balanced and purposeful?
-
-When the palette earns its place, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage.
-
-```json
-{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"}
-```
-
-Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract.
@@ -1,123 +0,0 @@
-# Craft Flow
-
-Build a feature with impeccable UX and UI quality: shape the design, land the visual direction, build real production code, inspect and improve in-browser until it meets a high-end studio bar.
-
-Before writing code, you need: PRODUCT.md loaded, register identified and the matching reference loaded, and a confirmed design direction for this task (either from `shape` or supplied by the user). PRODUCT.md is project context, not a task-specific brief.
-
-Treat any approved visual direction (generated mock or stated reference) as a concrete contract for composition, hierarchy, density, atmosphere, signature motifs, and distinctive visual moves. Don't let mocks replace structure, copy, accessibility, or state design. But if the live result lacks the approved direction's major ingredients, the implementation is wrong.
-
-### Gates: do not compress
-
-Craft has **multiple user gates**, not one. When the harness has native image generation (Codex via `image_gen`), the gate sequence before code is:
-
-1. **Shape brief confirmed** (Step 1)
-2. **Direction questions answered** (codex.md Step A)
-3. **Palette confirmed** (codex.md Step B)
-4. **One mock direction approved or delegated** (codex.md Step D)
-
-You must stop at every gate. **Shape confirmation alone is NOT a green light to start coding.** It is the green light to begin codex.md Step A. Compressing gates 2 through 4 because the shape brief felt complete is the dominant failure mode of this flow.
-
-When the harness lacks native image generation, gates 2-4 collapse into the brief itself, and shape confirmation does advance straight to code.
-
-## Step 0: Project Foundation
-
-Before shape, before code: figure out what kind of project you're working in.
-
-Look at the working directory. Run `ls`. Check for:
-
-- An existing framework: `astro.config.mjs/ts`, `next.config.js/ts`, `nuxt.config.ts`, `svelte.config.js`, `vite.config.js/ts`, `package.json` with framework deps, `Cargo.toml` + Leptos/Yew, `Gemfile` + Rails. **If found, use it.** Do not start a parallel build, do not introduce a second framework, do not write to `dist/` or `build/` directly. Whatever pipeline the project has, respect it.
-- An existing component library or design system: `src/components/`, `app/components/`, a `tokens.css` / `theme.ts`, an `astro.config` `integrations`. Read what's there before adding to it.
-- An existing icon set: `lucide-react`, `@phosphor-icons/react`, `@iconify/*`, hand-rolled SVG sprites in `assets/icons/`. **Use what's already in the project**; don't introduce a second set.
-
-If the directory is empty (greenfield), don't pick a framework silently. Ask the user via the AskUserQuestion tool, with sensible defaults framed by the brief:
-
-```text
-What should this be built on?
- - Astro (default for content-led brand sites, landing pages, marketing surfaces)
- - SvelteKit / Next.js / Nuxt (when the brief implies an app surface or significant interactivity)
- - Single index.html (one-shot demo, prototype, or a deliberately framework-free experiment)
-```
-
-Default: Astro for brand briefs, the project's existing framework for product briefs. Ask once; don't re-ask mid-task.
-
-## Step 1: Shape the Design
-
-Run /impeccable shape, passing along whatever feature description the user provided. Shape is **required** for craft; it is what produces a confirmed direction.
-
-Present the shape output and stop. Wait for the user to confirm, override, or course-correct before writing code.
-
-If the user already supplied a confirmed brief or ran shape separately, use it and skip this step.
-
-When the original prompt + PRODUCT.md already answer scope, content, and visual direction with no real ambiguity, the shape output can be **compact** (3-5 bullets stating what you're building and the visual lane, ending with one or two specific questions or "confirm or override"). The full 10-section structured brief is reserved for genuinely ambiguous, multi-screen, or stakeholder-heavy tasks. Don't pad a clear brief into a long one to look thorough; equally, don't skip the pause to look efficient.
-
-If the harness has native image generation (Codex), a compact shape's "confirm or override" advances to **Step 3 and the codex.md flow**, not to Step 4. Phrase the closing line accordingly: "Confirm or override; once we lock direction, I'll run a couple of palette and reference questions before generating any mocks." This stops the model from reading shape confirmation as code-green.
-
-## Step 2: Load References
-
-Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult:
-
-- [spatial-design.md](spatial-design.md) for layout and spacing
-- [typography.md](typography.md) for type hierarchy
-
-Then add references based on the brief's needs:
-- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md)
-- Animation or transitions? Consult [motion-design.md](motion-design.md)
-- Color-heavy or themed? Consult [color-and-contrast.md](color-and-contrast.md)
-- Responsive requirements? Consult [responsive-design.md](responsive-design.md)
-- Heavy on copy, labels, or errors? Consult [ux-writing.md](ux-writing.md)
-
-## Step 3: Visual Direction & Assets (Harness-Gated)
-
-If the harness has **native image generation** (currently Codex via `image_gen`), this step is mandatory. **Stop and load [codex.md](codex.md)**. It covers palette generation, mock exploration, the approval loop, mock-fidelity inventory, and asset slicing via the `impeccable_asset_producer` subagent. Follow Steps A-F in that file, then return here for Step 4.
-
-If the harness lacks native image generation, **state in one line that the visual-direction-by-generation step is being skipped because the harness lacks native image generation, then proceed**. The one-line announcement is required; it forces a conscious decision instead of letting the step quietly evaporate. The brief is your only visual reference. Implement directly from it, treating any named anchor references and the brief's "Design Direction" as the contract.
-
-Whether you generated mocks or not: don't replace required imagery with generic cards, bullets, emoji, fake metrics, decorative CSS panels, or filler copy. Image-led briefs (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product) need real or sourced imagery in the build, not CSS scenery.
-
-## Step 4: Build to Production Quality
-
-**Precondition.** If Step 3 routed you to codex.md (native image generation available), Steps A through D in that file must be complete before any code: questions answered, palette confirmed, mocks generated, one direction approved or delegated. **Do not mention implementation, file paths, or patch plans until that's done.** A confirmed shape brief is not enough; the model that compressed those gates is the model that already failed this flow.
-
-Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration.
-
-### Production bar
-
-- **Real content.** No placeholder copy, placeholder images, dead links, fake controls, or unused scaffold at presentation time.
-- **Preserve the approved mock's major ingredients.** Missing hero objects, world/product imagery, section structure, CTA/nav treatment, or distinctive motifs are blocking defects unless the user accepted the change.
-- **Semantic first.** Real headings, landmarks, labels, form associations, button/link semantics, accessible names, state announcements where needed.
-- **Deliberate spacing and alignment.** No default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment.
-- **Intentional typography.** Chosen loading strategy, clear hierarchy, readable measure, stable line breaks, no overflow at any width.
-- **Realistic state coverage.** Default, hover, focus-visible, active, disabled, loading, error, success, empty, overflow, long/short text, first-run.
-- **Finished interaction quality.** Keyboard paths, touch targets, feedback timing, scroll behavior, state transitions, no hover-only functionality.
-- **Coherent icon set.** Use the project's established set; otherwise pick one library or use accessible text. Don't mix.
-- **Respect the build pipeline.** Edit source files and run the project's build (`npm run build` or equivalent). Don't write to `build/` / `dist/` / `.next/` with `cat`, heredoc, or Bash redirects; that skips asset hashing, image optimization, code splitting, and CSS extraction, and produces output the dev server won't serve.
-- **Verify image URLs before referencing them.** Use image-search MCP or web-fetch when available; guessed photo IDs ship as broken-image placeholders. Without verification, prefer fewer images you're confident about.
-- **Optimized imagery and media.** Correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset`/`picture` for raster, no project-referenced asset left outside the workspace.
-- **Premium motion.** Use atmospheric blur, filter, mask, shadow, reveal when they improve the experience. Avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion.
-- **Maintainable.** Reusable local patterns, clear component boundaries, project conventions. No rasterized UI text or one-off hacks when a local pattern exists.
-- **Technically clean.** Production build passes, no console errors, no avoidable layout shift, no needless dependencies, no broken asset paths.
-- **Ask when uncertain.** If a discovery materially changes the brief or approved direction, stop and ask. Don't guess.
-
-## Step 5: Iterate Visually
-
-Look at what you built like a designer would. Your eyes are whatever the harness gives you: a connected browser, a screenshotting tool, Playwright, or asking the user. Use them for responsive testing (mobile, tablet, desktop minimum) and general visual validation.
-
-If your tool returns a file path, read the PNG back into the conversation. A screenshot you didn't read doesn't count.
-
-For long-form brand surfaces, inspect major sections individually. Thumbnails hide spacing, clipping, and cascade defects.
-
-After the first pass, write an honest critique against the brief, the approved mock's major ingredients (hero silhouette, motifs, imagery, nav/CTA, density), and impeccable's DON'Ts. Patch material defects and re-inspect. **Don't invent defects to demonstrate iteration.** A confident "first pass clean, shipping" beats a fake fix.
-
-Actively check: responsive behavior (composes, not shrinks), every state (empty / error / loading / edge), craft details (spacing, alignment, hierarchy, contrast, motion timing, focus), performance basics. The exit bar: defensible in a high-end studio review.
-
-Detector or QA output is defect evidence only; never proof the work is finished.
-
-## Step 6: Present
-
-Present the result to the user:
-- Show the feature in its primary state
-- Summarize the browser/viewports checked and the most important fixes made after inspection
-- Walk through the key states (empty, error, responsive)
-- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients.
-- Note any remaining limitations or follow-up risks honestly
-- Ask: "What's working? What isn't?"
@@ -1,236 +0,0 @@
-### Purpose
-
-Resolve one stable target, run two independent assessments, synthesize a design critique, persist a snapshot, and ask the user what to improve next. The chat response is the primary deliverable; the snapshot is an archive/backlog for future commands.
-
-### Hard Invariants
-
-- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
-- Assessment A must finish before detector findings enter the parent synthesis context. Detector output is deterministic, but it still anchors judgment.
-- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize.
-- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
-- Viewable targets require browser inspection when available.
-- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
-- Do not claim a user-visible overlay exists unless script injection succeeded and the detector ran in the page.
-
-### Setup
-
-1. **Resolve the target** to a concrete file path or URL. Prefer a source path over a dev-server URL when both identify the same surface; ports drift, paths do not.
- - "the homepage" -> `site/pages/index.astro` or `index.html`
- - "the settings modal" -> the primary component file
- - "this page" -> the current URL or source file
-2. **Compute the slug**:
- ```bash
- node .github/skills/impeccable/scripts/critique-storage.mjs slug "<resolved-path-or-url>"
- ```
- Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique.
-3. **Read `.impeccable/critique/ignore.md`** if it exists. Drop matching findings silently; it is the only prior-run input critique consumes.
-
-### Assessment Orchestration
-
-Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis.
-
-If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
-
-### Assessment A: Design Review
-
-Read relevant source files and visually inspect the live page when browser automation is available. Think like a design director.
-
-Evaluate:
-- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill.
-- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases.
-- **Cognitive load**: consult [cognitive-load](cognitive-load.md); report checklist failures and decision points with >4 visible options.
-- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments.
-- **Nielsen heuristics**: consult [heuristics-scoring](heuristics-scoring.md); score all 10 heuristics 0-4.
-
-Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions.
-
-### Assessment B: Detector + Browser Evidence
-
-Run the bundled detector and browser visualization evidence. Assessment B is mandatory and must remain isolated from Assessment A until both are complete.
-
-CLI scan:
-```bash
-node .github/skills/impeccable/scripts/detect.mjs --json [--fast] [target]
-```
-
-- Pass markup files/directories as `[target]`; do not pass CSS-only files.
-- For URLs, skip CLI scan and use browser visualization.
-- For 200+ scannable files, use `--fast`; for 500+, narrow scope or ask.
-- Exit code 0 = clean; 2 = findings.
-- If the detector entrypoint is missing or fails to load, report deterministic scan unavailable and continue with browser/manual review.
-
-Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
-
-1. Create a fresh tab and navigate.
-2. Preflight mutable injection by setting `document.title` and appending a `<script>` tag. Read-only evaluate APIs do not count.
-3. If mutation is unavailable, skip live server, browser presentation, and injection; report fallback signal.
-4. If mutation is available, start `node .github/skills/impeccable/scripts/live-server.mjs --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then stop the live server.
-5. For multi-view targets, inject on 3-5 representative pages.
-
-Return: CLI findings JSON/counts, browser console findings if applicable, false positives, and skipped/failed browser steps with concrete reasons.
-
-After Assessment B returns usable CLI findings, reuse them. Do not rerun `detect.mjs` in the parent unless Assessment B failed, was truncated, or omitted count, rule names, or file locations.
-
-### Generate Combined Critique Report
-
-Synthesize both assessments into a single report. Do NOT simply concatenate. Weave the findings together, noting where the LLM review and detector agree, where the detector caught issues the LLM missed, and where detector findings are false positives.
-
-The chat response is the primary user-facing deliverable. Present the full structured critique below in chat; do not replace it with a summary and a link. The persisted snapshot is only an archive/backlog for later commands.
-
-Structure your feedback as a design director would:
-
-#### Design Health Score
-> *Consult [heuristics-scoring](heuristics-scoring.md)*
-
-Present the Nielsen's 10 heuristics scores as a table:
-
-| # | Heuristic | Score | Key Issue |
-|---|-----------|-------|-----------|
-| 1 | Visibility of System Status | ? | [specific finding or "n/a" if solid] |
-| 2 | Match System / Real World | ? | |
-| 3 | User Control and Freedom | ? | |
-| 4 | Consistency and Standards | ? | |
-| 5 | Error Prevention | ? | |
-| 6 | Recognition Rather Than Recall | ? | |
-| 7 | Flexibility and Efficiency | ? | |
-| 8 | Aesthetic and Minimalist Design | ? | |
-| 9 | Error Recovery | ? | |
-| 10 | Help and Documentation | ? | |
-| **Total** | | **??/40** | **[Rating band]** |
-
-Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32.
-
-#### Anti-Patterns Verdict
-
-**Start here.** Does this look AI-generated?
-
-**LLM assessment**: Your own evaluation of AI slop tells. Cover overall aesthetic feel, layout sameness, generic composition, missed opportunities for personality.
-
-**Deterministic scan**: Summarize what the automated detector found, with counts and file locations. Note any additional issues the detector caught that you missed, and flag any false positives.
-
-**Visual overlays** (if injection succeeded): Tell the user that overlays are now visible in the **[Human]** tab in their browser, highlighting the detected issues. Summarize what the console output reported. If browser visualization was attempted but injection failed, say that no reliable user-visible overlay is available and report the fallback signal instead.
-
-#### Overall Impression
-A brief gut reaction: what works, what doesn't, and the single biggest opportunity.
-
-#### What's Working
-Highlight 2-3 things done well. Be specific about why they work.
-
-#### Priority Issues
-The 3-5 most impactful design problems, ordered by importance.
-
-For each issue, tag with **P0-P3 severity** (consult [heuristics-scoring](heuristics-scoring.md) for severity definitions):
-- **[P?] What**: Name the problem clearly
-- **Why it matters**: How this hurts users or undermines goals
-- **Fix**: What to do about it (be concrete)
-- **Suggested command**: Which command could address this (from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-#### Persona Red Flags
-> *Consult [personas](personas.md)*
-
-Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `.github/copilot-instructions.md` contains a `## Design Context` section from `impeccable teach`, also generate 1-2 project-specific personas from the audience/brand info.
-
-For each selected persona, walk through the primary user action and list specific red flags found:
-
-**Alex (Power User)**: No keyboard shortcuts detected. Form requires 8 clicks for primary action. Forced modal onboarding. High abandonment risk.
-
-**Jordan (First-Timer)**: Icon-only nav in sidebar. Technical jargon in error messages ("404 Not Found"). No visible help. Will abandon at step 2.
-
-Be specific. Name the exact elements and interactions that fail each persona. Don't write generic persona descriptions; write what broke for them.
-
-#### Minor Observations
-Quick notes on smaller issues worth addressing.
-
-#### Questions to Consider
-Provocative questions that might unlock better solutions:
-- "What if the primary action were more prominent?"
-- "Does this need to feel this complex?"
-- "What would a confident version of this look like?"
-
-**Remember**:
-- Be direct. Vague feedback wastes everyone's time.
-- Be specific. "The submit button," not "some elements."
-- Say what's wrong AND why it matters to users.
-- Give concrete suggestions. Cut "consider exploring..." entirely.
-- Prioritize ruthlessly. If everything is important, nothing is.
-- Don't soften criticism. Developers need honest feedback to ship great design.
-
-### Persist the Snapshot
-
-Once the report above is finalized, write it to `.impeccable/critique/` so the user can refer back, and so `/impeccable polish` can pick up the priority issues without a copy-paste.
-
-Skip this step if the Setup slug was null (vague or root-level target).
-
-1. **Write the body to a temp file** so you can pipe it to the helper. Use the full critique report (heuristic table, anti-patterns verdict, priority issues, persona red flags, minor observations, and questions), but stop before the "Ask the User" / "Recommended Actions" sections that come later.
-
-2. **Pass the structured metadata** through `IMPECCABLE_CRITIQUE_META` (JSON), then run the write command:
- ```bash
- IMPECCABLE_CRITIQUE_META='{"target":"<user phrasing>","total_score":<n>,"p0_count":<n>,"p1_count":<n>}' \
- node .github/skills/impeccable/scripts/critique-storage.mjs write <slug> <body-file>
- ```
- The helper prints the absolute path it wrote.
-
-3. **Delete the temp body file** after the write attempt completes, whether the write succeeded or failed. If deletion fails, mention `temp-file cleanup failed: <reason>` briefly in the final output, but do not block the critique.
-
-4. **Read the trend** for context:
- ```bash
- node .github/skills/impeccable/scripts/critique-storage.mjs trend <slug> 5
- ```
- This returns a JSON array of the last 5 frontmatter entries (including the one you just wrote).
-
-5. **Append a single line to the user-visible output**, after the report and before the questions:
-
- > **Trend for `<slug>` (last 5 runs): 24 → 28 → 32 → 29 → 32**
- > Wrote `.impeccable/critique/<filename>`.
-
- If this is the first run for the slug, the trend is just one score; say so: "First run for this target, no trend yet."
-
-This is fire-and-forget. Do not show the user the helper's JSON output; only the human-readable trend line and the written path. Failures here should not block the rest of the flow; print the error and move on.
-
-### Ask the User
-
-**After presenting findings**, use targeted questions based on what was actually found. ask the user directly to clarify what you cannot infer. These answers will shape the action plan.
-
-Ask questions along these lines (adapt to the specific findings; do NOT ask generic questions):
-
-1. **Priority direction**: Based on the issues found, ask which category matters most to the user right now. For example: "I found problems with visual hierarchy, color usage, and information overload. Which area should we tackle first?" Offer the top 2-3 issue categories as options.
-
-2. **Design intent**: If the critique found a tonal mismatch, ask whether it was intentional. For example: "The interface feels clinical and corporate. Is that the intended tone, or should it feel warmer/bolder/more playful?" Offer 2-3 tonal directions as options based on what would fix the issues found.
-
-3. **Scope**: Ask how much the user wants to take on. For example: "I found N issues. Want to address everything, or focus on the top 3?" Offer scope options like "Top 3 only", "All issues", "Critical issues only".
-
-4. **Constraints** (optional; only ask if relevant): If the findings touch many areas, ask if anything is off-limits. For example: "Should any sections stay as-is?" This prevents the plan from touching things the user considers done.
-
-**Rules for questions**:
-- Every question must reference specific findings from the report. Never ask generic "who is your audience?" questions.
-- Keep it to 2-4 questions maximum. Respect the user's time.
-- Offer concrete options, not open-ended prompts.
-- If findings are straightforward (e.g., only 1-2 clear issues), skip questions and go directly to Recommended Actions.
-
-### Recommended Actions
-
-**After receiving the user's answers**, present a prioritized action summary reflecting the user's priorities and scope from Ask the User.
-
-#### Action Summary
-
-List recommended commands in priority order, based on the user's answers:
-
-1. **`/command-name`**: Brief description of what to fix (specific context from critique findings)
-2. **`/command-name`**: Brief description (specific context)
-...
-
-**Rules for recommendations**:
-- Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset
-- Order by the user's stated priorities first, then by impact
-- Each item's description should carry enough context that the command knows what to focus on
-- Map each Priority Issue to the appropriate command
-- Skip commands that would address zero issues
-- If the user chose a limited scope, only include items within that scope
-- If the user marked areas as off-limits, exclude commands that would touch those areas
-- End with `/impeccable polish` as the final step if any fixes were recommended
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable critique` after fixes to see your score improve.
@@ -1,302 +0,0 @@
-> **Additional context needed**: what's appropriate for the domain (playful vs professional vs quirky vs elegant).
-
-Find the moments where personality and unexpected polish would turn a functional interface into one users remember and tell other people about. Add only where the moment earns it; delight everywhere reads as noise.
-
----
-
-## Register
-
-Brand: delight can be distributed across copy voice, section transitions, discovery rewards, seasonal touches, personality across the whole surface.
-
-Product: delight at specific moments, not pages. Completion, first-time actions, error recovery, milestone crossings. Reliability and consistency carry the rest of the experience; delight pushed everywhere reads as noise.
-
----
-
-## Assess Delight Opportunities
-
-Identify where delight would enhance (not distract from) the experience:
-
-1. **Find natural delight moments**:
- - **Success states**: Completed actions (save, send, publish)
- - **Empty states**: First-time experiences, onboarding
- - **Loading states**: Waiting periods that could be entertaining
- - **Achievements**: Milestones, streaks, completions
- - **Interactions**: Hover states, clicks, drags
- - **Errors**: Softening frustrating moments
- - **Easter eggs**: Hidden discoveries for curious users
-
-2. **Understand the context**:
- - What's the brand personality? (Playful? Professional? Quirky? Elegant?)
- - Who's the audience? (Tech-savvy? Creative? Corporate?)
- - What's the emotional context? (Accomplishment? Exploration? Frustration?)
- - What's appropriate? (Banking app ≠ gaming app)
-
-3. **Define delight strategy**:
- - **Subtle sophistication**: Refined micro-interactions (luxury brands)
- - **Playful personality**: Whimsical illustrations and copy (consumer apps)
- - **Helpful surprises**: Anticipating needs before users ask (productivity tools)
- - **Sensory richness**: Satisfying sounds, smooth animations (creative tools)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Delight should enhance usability, never obscure it. If users notice the delight more than accomplishing their goal, you've gone too far.
-
-## Delight Principles
-
-Follow these guidelines:
-
-### Delight Amplifies, Never Blocks
-- Delight moments should be quick (< 1 second)
-- Never delay core functionality for delight
-- Make delight skippable or subtle
-- Respect user's time and task focus
-
-### Surprise and Discovery
-- Hide delightful details for users to discover
-- Reward exploration and curiosity
-- Don't announce every delight moment
-- Let users share discoveries with others
-
-### Appropriate to Context
-- Match delight to emotional moment (celebrate success, empathize with errors)
-- Respect the user's state (don't be playful during critical errors)
-- Match brand personality and audience expectations
-- Cultural sensitivity (what's delightful varies by culture)
-
-### Compound Over Time
-- Delight should remain fresh with repeated use
-- Vary responses (not same animation every time)
-- Reveal deeper layers with continued use
-- Build anticipation through patterns
-
-## Delight Techniques
-
-Add personality and joy through these methods:
-
-### Micro-interactions & Animation
-
-**Button delight**:
-```css
-/* Satisfying button press */
-.button {
- transition: transform 0.1s, box-shadow 0.1s;
-}
-.button:active {
- transform: translateY(2px);
- box-shadow: 0 2px 4px rgba(0,0,0,0.2);
-}
-
-/* Ripple effect on click */
-/* Smooth lift on hover */
-.button:hover {
- transform: translateY(-2px);
- transition: transform 0.2s cubic-bezier(0.25, 1, 0.5, 1); /* ease-out-quart */
-}
-```
-
-**Loading delight**:
-- Playful loading animations (not just spinners)
-- Personality in loading messages (write product-specific ones, not generic AI filler)
-- Progress indication with encouraging messages
-- Skeleton screens with subtle animations
-
-**Success animations**:
-- Checkmark draw animation
-- Confetti burst for major achievements
-- Gentle scale + fade for confirmation
-- Satisfying sound effects (subtle)
-
-**Hover surprises**:
-- Icons that animate on hover
-- Color shifts or glow effects
-- Tooltip reveals with personality
-- Cursor changes (custom cursors for branded experiences)
-
-### Personality in Copy
-
-**Playful error messages**:
-```
-"Error 404"
-"This page is playing hide and seek. (And winning)"
-
-"Connection failed"
-"Looks like the internet took a coffee break. Want to retry?"
-```
-
-**Encouraging empty states**:
-```
-"No projects"
-"Your canvas awaits. Create something amazing."
-
-"No messages"
-"Inbox zero! You're crushing it today."
-```
-
-**Playful labels & tooltips**:
-```
-"Delete"
-"Send to void" (for playful brand)
-
-"Help"
-"Rescue me" (tooltip)
-```
-
-**IMPORTANT**: Match copy personality to brand. Banks shouldn't be wacky, but they can be warm.
-
-### Illustrations & Visual Personality
-
-**Custom illustrations**:
-- Empty state illustrations (not stock icons)
-- Error state illustrations (friendly monsters, quirky characters)
-- Loading state illustrations (animated characters)
-- Success state illustrations (celebrations)
-
-**Icon personality**:
-- Custom icon set matching brand personality
-- Animated icons (subtle motion on hover/click)
-- Illustrative icons (more detailed than generic)
-- Consistent style across all icons
-
-**Background effects**:
-- Subtle particle effects
-- Gradient mesh backgrounds
-- Geometric patterns
-- Parallax depth
-- Time-of-day themes (morning vs night)
-
-### Satisfying Interactions
-
-**Drag and drop delight**:
-- Lift effect on drag (shadow, scale)
-- Snap animation when dropped
-- Satisfying placement sound
-- Undo toast ("Dropped in wrong place? [Undo]")
-
-**Toggle switches**:
-- Smooth slide with spring physics
-- Color transition
-- Haptic feedback on mobile
-- Optional sound effect
-
-**Progress & achievements**:
-- Streak counters with celebratory milestones
-- Progress bars that "celebrate" at 100%
-- Badge unlocks with animation
-- Playful stats ("You're on fire! 5 days in a row")
-
-**Form interactions**:
-- Input fields that animate on focus
-- Checkboxes with a satisfying scale pulse when checked
-- Success state that celebrates valid input
-- Auto-grow textareas
-
-### Sound Design
-
-**Subtle audio cues** (when appropriate):
-- Notification sounds (distinctive but not annoying)
-- Success sounds (satisfying "ding")
-- Error sounds (empathetic, not harsh)
-- Typing sounds for chat/messaging
-- Ambient background audio (very subtle)
-
-**IMPORTANT**:
-- Respect system sound settings
-- Provide mute option
-- Keep volumes quiet (subtle cues, not alarms)
-- Don't play on every interaction (sound fatigue is real)
-
-### Easter Eggs & Hidden Delights
-
-**Discovery rewards**:
-- Konami code unlocks special theme
-- Hidden keyboard shortcuts (Cmd+K for special features)
-- Hover reveals on logos or illustrations
-- Alt text jokes on images (for screen reader users too!)
-- Console messages for developers ("Like what you see? We're hiring!")
-
-**Seasonal touches**:
-- Holiday themes (subtle, tasteful)
-- Seasonal color shifts
-- Weather-based variations
-- Time-based changes (dark at night, light during day)
-
-**Contextual personality**:
-- Different messages based on time of day
-- Responses to specific user actions
-- Randomized variations (not same every time)
-- Progressive reveals with continued use
-
-### Loading & Waiting States
-
-**Make waiting engaging**:
-- Interesting loading messages that rotate
-- Progress bars with personality
-- Mini-games during long loads
-- Fun facts or tips while waiting
-- Countdown with encouraging messages
-
-```
-Loading messages: write ones specific to your product, not generic AI filler:
-- "Crunching your latest numbers..."
-- "Syncing with your team's changes..."
-- "Preparing your dashboard..."
-- "Checking for updates since yesterday..."
-```
-
-**WARNING**: Avoid cliched loading messages like "Herding pixels", "Teaching robots to dance", "Consulting the magic 8-ball", "Counting backwards from infinity". These are AI-slop copy, instantly recognizable as machine-generated. Write messages that are specific to what your product actually does.
-
-### Celebration Moments
-
-**Success celebrations**:
-- Confetti for major milestones
-- Animated checkmarks for completions
-- Progress bar celebrations at 100%
-- "Achievement unlocked" style notifications
-- Personalized messages ("You published your 10th article!")
-
-**Milestone recognition**:
-- First-time actions get special treatment
-- Streak tracking and celebration
-- Progress toward goals
-- Anniversary celebrations
-
-## Implementation Patterns
-
-**Animation libraries**:
-- Framer Motion (React)
-- GSAP (universal)
-- Lottie (After Effects animations)
-- Canvas confetti (party effects)
-
-**Sound libraries**:
-- Howler.js (audio management)
-- Use-sound (React hook)
-
-**Physics libraries**:
-- React Spring (spring physics)
-- Popmotion (animation primitives)
-
-**IMPORTANT**: File size matters. Compress images, optimize animations, lazy load delight features.
-
-**NEVER**:
-- Delay core functionality for delight
-- Force users through delightful moments (make skippable)
-- Use delight to hide poor UX
-- Overdo it (less is more)
-- Ignore accessibility (animate responsibly, provide alternatives)
-- Make every interaction delightful (special moments should be special)
-- Sacrifice performance for delight
-- Be inappropriate for context (read the room)
-
-## Verify Delight Quality
-
-Test that delight actually delights:
-
-- **User reactions**: Do users smile? Share screenshots?
-- **Doesn't annoy**: Still pleasant after 100th time?
-- **Doesn't block**: Can users opt out or skip?
-- **Performant**: No jank, no slowdown
-- **Appropriate**: Matches brand and context
-- **Accessible**: Works with reduced motion, screen readers
-
-When the moments feel earned, hand off to `/impeccable polish` for the final pass.
@@ -1,111 +0,0 @@
-Strip a design to its essence. Remove anything that doesn't earn its place: redundant elements, repeated information, decorative noise, cosmetic complexity.
-
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel complex or cluttered:
-
-1. **Identify complexity sources**:
- - **Too many elements**: Competing buttons, redundant information, visual clutter
- - **Excessive variation**: Too many colors, fonts, sizes, styles without purpose
- - **Information overload**: Everything visible at once, no progressive disclosure
- - **Visual noise**: Unnecessary borders, shadows, backgrounds, decorations
- - **Confusing hierarchy**: Unclear what matters most
- - **Feature creep**: Too many options, actions, or paths forward
-
-2. **Find the essence**:
- - What's the primary user goal? (There should be ONE)
- - What's actually necessary vs nice-to-have?
- - What can be removed, hidden, or combined?
- - What's the 20% that delivers 80% of value?
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Simplicity is not about removing features. It's about removing obstacles between users and their goals. Every element should justify its existence.
-
-## Plan Simplification
-
-Create a ruthless editing strategy:
-
-- **Core purpose**: What's the ONE thing this should accomplish?
-- **Essential elements**: What's truly necessary to achieve that purpose?
-- **Progressive disclosure**: What can be hidden until needed?
-- **Consolidation opportunities**: What can be combined or integrated?
-
-**IMPORTANT**: Simplification is hard. It requires saying no to good ideas to make room for great execution. Be ruthless.
-
-## Simplify the Design
-
-Systematically remove complexity across these dimensions:
-
-### Information Architecture
-- **Reduce scope**: Remove secondary actions, optional features, redundant information
-- **Progressive disclosure**: Hide complexity behind clear entry points (accordions, modals, step-through flows)
-- **Combine related actions**: Merge similar buttons, consolidate forms, group related content
-- **Clear hierarchy**: ONE primary action, few secondary actions, everything else tertiary or hidden
-- **Remove redundancy**: If it's said elsewhere, don't repeat it here
-
-### Visual Simplification
-- **Reduce color palette**: Use 1-2 colors plus neutrals, not 5-7 colors
-- **Limit typography**: One font family, 3-4 sizes maximum, 2-3 weights
-- **Remove decorations**: Eliminate borders, shadows, backgrounds that don't serve hierarchy or function
-- **Flatten structure**: Reduce nesting, remove unnecessary containers; never nest cards inside cards
-- **Remove unnecessary cards**: Cards aren't needed for basic layout; use spacing and alignment instead
-- **Consistent spacing**: Use one spacing scale, remove arbitrary gaps
-
-### Layout Simplification
-- **Linear flow**: Replace complex grids with simple vertical flow where possible
-- **Remove sidebars**: Move secondary content inline or hide it
-- **Full-width**: Use available space generously instead of complex multi-column layouts
-- **Consistent alignment**: Pick left or center, stick with it
-- **Generous white space**: Let content breathe, don't pack everything tight
-
-### Interaction Simplification
-- **Reduce choices**: Fewer buttons, fewer options, clearer path forward (paradox of choice is real)
-- **Smart defaults**: Make common choices automatic, only ask when necessary
-- **Inline actions**: Replace modal flows with inline editing where possible
-- **Remove steps**: Can signup be one step instead of three? Can checkout be simplified?
-- **Clear CTAs**: ONE obvious next step, not five competing actions
-
-### Content Simplification
-- **Shorter copy**: Cut every sentence in half, then do it again
-- **Active voice**: "Save changes" not "Changes will be saved"
-- **Remove jargon**: Plain language always wins
-- **Scannable structure**: Short paragraphs, bullet points, clear headings
-- **Essential information only**: Remove marketing fluff, legalese, hedging
-- **Remove redundant copy**: No headers restating intros, no repeated explanations, say it once
-
-### Code Simplification
-- **Remove unused code**: Dead CSS, unused components, orphaned files
-- **Flatten component trees**: Reduce nesting depth
-- **Consolidate styles**: Merge similar styles, use utilities consistently
-- **Reduce variants**: Does that component need 12 variations, or can 3 cover 90% of cases?
-
-**NEVER**:
-- Remove necessary functionality (simplicity ≠ feature-less)
-- Sacrifice accessibility for simplicity (clear labels and ARIA still required)
-- Make things so simple they're unclear (mystery ≠ minimalism)
-- Remove information users need to make decisions
-- Eliminate hierarchy completely (some things should stand out)
-- Oversimplify complex domains (match complexity to actual task complexity)
-
-## Verify Simplification
-
-Ensure simplification improves usability:
-
-- **Faster task completion**: Can users accomplish goals more quickly?
-- **Reduced cognitive load**: Is it easier to understand what to do?
-- **Still complete**: Are all necessary features still accessible?
-- **Clearer hierarchy**: Is it obvious what matters most?
-- **Better performance**: Does simpler design load faster?
-
-## Document Removed Complexity
-
-If you removed features or options:
-- Document why they were removed
-- Consider if they need alternative access points
-- Note any user feedback to monitor
-
-When the cuts feel right, hand off to `/impeccable polish` for the final pass. As Antoine de Saint-Exupéry put it: "Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away."
@@ -1,427 +0,0 @@
-Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
-
-DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
-
-## The frontmatter: token schema
-
-The YAML frontmatter is the machine-readable layer. It's what Stitch's linter validates and what the live panel renders tiles from. Keep it tight; every entry should correspond to a token the project actually uses.
-
-```yaml
----
-name: <project title>
-description: <one-line tagline>
-colors:
- primary: "#b8422e"
- neutral-bg: "#faf7f2"
- # ...one entry per extracted color; key = descriptive slug
-typography:
- display:
- fontFamily: "Cormorant Garamond, Georgia, serif"
- fontSize: "clamp(2.5rem, 7vw, 4.5rem)"
- fontWeight: 300
- lineHeight: 1
- letterSpacing: "normal"
- body:
- # ...
-rounded:
- sm: "4px"
- md: "8px"
-spacing:
- sm: "8px"
- md: "16px"
-components:
- button-primary:
- backgroundColor: "{colors.primary}"
- textColor: "{colors.neutral-bg}"
- rounded: "{rounded.sm}"
- padding: "16px 48px"
- button-primary-hover:
- backgroundColor: "{colors.primary-deep}"
----
-```
-
-Rules that matter:
-
-- **Token refs** use `{path.to.token}` (e.g. `{colors.primary}`, `{rounded.md}`). Components may reference primitives; primitives may not reference each other.
-- **Stitch validates colors as hex sRGB only** (`#RGB` / `#RGBA` / `#RRGGBB` / `#RRGGBBAA`); OKLCH/HSL/P3 trigger a linter warning, not a hard error. YAML accepts the string either way and our own parser is format-agnostic. Choose based on project posture: (a) if the project has an "OKLCH-only" doctrine or uses Display-P3 values that don't round-trip through sRGB, put OKLCH directly in the frontmatter and accept the Stitch linter warning; (b) if the project wants strict Stitch compliance or plans to use their Tailwind/DTCG export pipeline, put hex in the frontmatter and keep OKLCH in prose as the canonical reference. Never split the source of truth without explicit reason.
-- **Component sub-tokens** are limited to 8 props: `backgroundColor`, `textColor`, `typography`, `rounded`, `padding`, `size`, `height`, `width`. Shadows, motion, focus rings, backdrop-filter: none of those fit. Carry them in the sidecar (Step 4b).
-- **Scale keys are open-ended.** Use whatever names the project already uses (`warm-ash-cream`, `surface-container-low`). Don't rename to Material defaults.
-- **Variants are naming convention, not schema.** `button-primary` / `button-primary-hover` / `button-primary-active` as sibling keys.
-
-## The markdown body: six sections (exact order)
-
-1. `## Overview`
-2. `## Colors`
-3. `## Typography`
-4. `## Elevation`
-5. `## Components`
-6. `## Do's and Don'ts`
-
-Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] Palette` (Stitch's own outputs do this), but the literal word in each header (Overview, Colors, Typography, Elevation, Components, Do's and Don'ts) must be present. Do NOT add extra top-level sections (Layout Principles, Responsive Behavior, Motion, Agent Prompt Guide). Fold that content into the six spec sections where it naturally belongs.
-
-## When to run
-
-- The user just ran `/impeccable teach` and needs the visual side documented.
-- The skill noticed no `DESIGN.md` exists and nudged the user to create one.
-- An existing `DESIGN.md` is stale (the design has drifted).
-- Before a large redesign, to capture the current state as a reference.
-
-If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user the existing file and ask the user directly to clarify what you cannot infer. whether to refresh, overwrite, or merge.
-
-## Two paths
-
-- **Scan mode** (default): the project has design tokens, components, or rendered output. Extract, then confirm descriptive language. Use when there's code to analyze.
-- **Seed mode**: the project is pre-implementation (fresh teach, nothing built yet). Interview for five high-level answers, write a minimal DESIGN.md marked `<!-- SEED -->`. Re-run in scan mode once there's code.
-
-Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode; don't silently switch. `/impeccable document --seed` forces seed mode regardless of code presence.
-
-## Scan mode (approach C: auto-extract, then confirm descriptive language)
-
-### Step 1: Find the design assets
-
-Search the codebase in priority order:
-
-1. **CSS custom properties**: grep for `--color-`, `--font-`, `--spacing-`, `--radius-`, `--shadow-`, `--ease-`, `--duration-` declarations in CSS files (usually `src/styles/`, `public/css/`, `app/globals.css`, etc.). Record name, value, and the file it's defined in.
-2. **Tailwind config**: if `tailwind.config.{js,ts,mjs}` exists, read the `theme.extend` block for colors, fontFamily, spacing, borderRadius, boxShadow.
-3. **CSS-in-JS theme files**: styled-components, emotion, vanilla-extract, stitches; look for `theme.ts`, `tokens.ts`, or equivalent.
-4. **Design token files**: `tokens.json`, `design-tokens.json`, Style Dictionary output, W3C token community group format.
-5. **Component library**: scan the main button, card, input, navigation, dialog components. Note their variant APIs and default styles.
-6. **Global stylesheet**: the root CSS file usually has the base typography and color assignments.
-7. **Visible rendered output**: if browser automation tools are available, load the live site and sample computed styles from key elements (body, h1, a, button, .card). This catches values that tokens miss.
-
-### Step 2: Auto-extract what can be auto-extracted
-
-Build a structured draft from the discovered tokens. For each token class:
-
-- **Colors**: Group into Primary / Secondary / Tertiary / Neutral (the Material-derived roles Stitch uses). If the project only has one accent, express it as Primary + Neutral; omit Secondary and Tertiary rather than inventing them.
-- **Typography**: Map observed sizes and weights to the Material hierarchy (display / headline / title / body / label). Note font-family stacks and the scale ratio.
-- **Elevation**: Catalogue the shadow vocabulary. If the project is flat and uses tonal layering instead, that's a valid answer; state it explicitly.
-- **Components**: For each common component (button, card, input, chip, list item, tooltip, nav), extract shape (radius), color assignment, hover/focus treatment, internal padding.
-- **Spacing + layout**: Fold into Overview or relevant Components. The spec does NOT have a Layout section.
-
-### Step 2b: Stage the frontmatter
-
-From the auto-extracted tokens, draft the YAML frontmatter now (you'll write it at the top of DESIGN.md in Step 4). This is the machine-readable layer: what the live panel and Stitch's linter consume.
-
-- **Colors**: one entry per extracted color. Key = descriptive slug (`warm-ash-cream`, `editorial-magenta`, not `blue-800`). Value = whichever format the project treats as canonical (OKLCH or hex; see the frontmatter rules above). Don't split the source of truth: one format in the frontmatter, don't redefine the same token in prose with a different value.
-- **Typography**: one entry per role (`display`, `headline`, `title`, `body`, `label`). Typography is an object; include only the props that are real for the project (`fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `fontFeature`, `fontVariation`).
-- **Rounded / Spacing**: whatever scale steps the project actually uses, keyed by whatever scale name the project uses (`sm` / `md` / `lg`, or `surface-sm`, or numeric steps).
-- **Components**: one entry per variant (`button-primary`, `button-primary-hover`, `button-ghost`). Reference primitives via `{colors.X}`, `{rounded.Y}`. If a variant needs a property Stitch's 8-prop set doesn't cover (shadow, focus ring, backdrop-filter), carry the full snippet in the sidecar instead.
-
-Skip anything the project doesn't have. Empty scale keys or fabricated tokens pollute the spec.
-
-### Step 3: Ask the user for qualitative language
-
-The following require creative input that cannot be auto-extracted. Group them into one `AskUserQuestion` interaction:
-
-- **Creative North Star**: a single named metaphor for the whole system ("The Editorial Sanctuary", "The Golden State Curator", "The Lab Notebook"). Offer 2-3 options that honor PRODUCT.md's brand personality.
-- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, anti-references (what the system should not feel like).
-- **Color character** (for auto-extracted colors): descriptive names ("Deep Muted Teal-Navy", not "blue-800"). Suggest 2-3 options per key color based on hue/saturation.
-- **Elevation philosophy**: flat/layered/lifted. If shadows exist, is their role ambient or structural?
-- **Component philosophy**: the feel of buttons, cards, inputs in one phrase ("tactile and confident" vs. "refined and restrained").
-
-Quote a line from PRODUCT.md when possible so the user sees their own strategic language carry forward.
-
-### Step 4: Write DESIGN.md
-
-The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the structure below. Headers must match character-for-character. Optional evocative subtitles (e.g. `## 2. Colors: The Coastal Palette`) are allowed.
-
-```markdown
----
-name: [Project Title]
-description: [one-line tagline]
-colors:
- # ... staged frontmatter from Step 2b
----
-
-# Design System: [Project Title]
-
-## 1. Overview
-
-**Creative North Star: "[Named metaphor in quotes]"**
-
-[2-3 paragraph holistic description: personality, density, aesthetic philosophy. Start from the North Star and work outward. State what this system explicitly rejects (pulled from PRODUCT.md's anti-references). End with a short **Key Characteristics:** bullet list.]
-
-## 2. Colors
-
-[Describe the palette character in one sentence.]
-
-### Primary
-- **[Descriptive Name]** (#HEX / oklch(...)): [Where and why this color is used. Be specific about context, not just role.]
-
-### Secondary (optional; omit if the project has only one accent)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Tertiary (optional)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Neutral
-- **[Descriptive Name]** (#HEX): [Text / background / border / divider role.]
-- [...]
-
-### Named Rules (optional, powerful)
-**The [Rule Name] Rule.** [Short, forceful prohibition or doctrine, e.g. "The One Voice Rule. The primary accent is used on ≤10% of any given screen. Its rarity is the point."]
-
-## 3. Typography
-
-**Display Font:** [Family] (with [fallback])
-**Body Font:** [Family] (with [fallback])
-**Label/Mono Font:** [Family, if distinct]
-
-**Character:** [1-2 sentence personality description of the pairing.]
-
-### Hierarchy
-- **Display** ([weight], [size/clamp], [line-height]): [Purpose; where it appears.]
-- **Headline** ([weight], [size], [line-height]): [Purpose.]
-- **Title** ([weight], [size], [line-height]): [Purpose.]
-- **Body** ([weight], [size], [line-height]): [Purpose. Include max line length like 65–75ch if relevant.]
-- **Label** ([weight], [size], [letter-spacing], [case if uppercase]): [Purpose.]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [Short doctrine about type use.]
-
-## 4. Elevation
-
-[One paragraph: does this system use shadows, tonal layering, or a hybrid? If "no shadows", say so explicitly and describe how depth is conveyed instead.]
-
-### Shadow Vocabulary (if applicable)
-- **[Role name]** (`box-shadow: [exact value]`): [When to use it.]
-- [...]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [e.g. "The Flat-By-Default Rule. Surfaces are flat at rest. Shadows appear only as a response to state (hover, elevation, focus)."]
-
-## 5. Components
-
-For each component, lead with a short character line, then specify shape, color assignment, states, and any distinctive behavior.
-
-### Buttons
-- **Shape:** [radius described, exact value in parens]
-- **Primary:** [color assignment + padding, in semantic + exact terms]
-- **Hover / Focus:** [transitions, treatments]
-- **Secondary / Ghost / Tertiary (if applicable):** [brief description]
-
-### Chips (if used)
-- **Style:** [background, text color, border treatment]
-- **State:** [selected / unselected, filter / action variants]
-
-### Cards / Containers
-- **Corner Style:** [radius]
-- **Background:** [colors used]
-- **Shadow Strategy:** [reference Elevation section]
-- **Border:** [if any]
-- **Internal Padding:** [scale]
-
-### Inputs / Fields
-- **Style:** [stroke, background, radius]
-- **Focus:** [treatment, e.g. glow, border shift, etc.]
-- **Error / Disabled:** [if applicable]
-
-### Navigation
-- **Style, typography, default/hover/active states, mobile treatment.**
-
-### [Signature Component] (optional; if the project has a distinctive custom component worth documenting)
-[Description.]
-
-## 6. Do's and Don'ts
-
-Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: include exact colors, pixel values, and named anti-patterns the user mentioned in PRODUCT.md. **Every anti-reference in PRODUCT.md should show up here as a "Don't" with the same language**, so the visual spec carries the strategic line through. Quote PRODUCT.md directly where possible: if PRODUCT.md says *"avoid dark mode with purple gradients, neon accents, glassmorphism"*, the Don'ts here should repeat that by name.
-
-### Do:
-- **Do** [specific prescription with exact values / named rule].
-- **Do** [...]
-
-### Don't:
-- **Don't** [specific prohibition, e.g. "use border-left greater than 1px as a colored stripe"].
-- **Don't** [...]
-- **Don't** [...]
-```
-
-### Step 4b: Write .impeccable/design.json sidecar (extensions only)
-
-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.
-
-Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.
-
-#### Schema
-
-```json
-{
- "schemaVersion": 2,
- "generatedAt": "ISO-8601 string",
- "title": "Design System: [Project Title]",
- "extensions": {
- "colorMeta": {
- "primary": { "role": "primary", "displayName": "Editorial Magenta", "canonical": "oklch(60% 0.25 350)", "tonalRamp": ["...", "...", "..."] },
- "warm-ash-cream": { "role": "neutral", "displayName": "Warm Ash Cream", "canonical": "oklch(96% 0.005 350)", "tonalRamp": ["...", "...", "..."] }
- },
- "typographyMeta": {
- "display": { "displayName": "Display", "purpose": "Hero headlines only." }
- },
- "shadows": [
- { "name": "ambient-low", "value": "0 4px 24px rgba(0,0,0,0.12)", "purpose": "Diffuse hover glow under accent elements." }
- ],
- "motion": [
- { "name": "ease-standard", "value": "cubic-bezier(0.4, 0, 0.2, 1)", "purpose": "Default easing for state transitions." }
- ],
- "breakpoints": [
- { "name": "sm", "value": "640px" }
- ]
- },
- "components": [
- {
- "name": "Primary Button",
- "kind": "button | input | nav | chip | card | custom",
- "refersTo": "button-primary",
- "description": "One-line what and when.",
- "html": "<button class=\"ds-btn-primary\">GET STARTED</button>",
- "css": ".ds-btn-primary { background: #191c1d; color: #fff; padding: 16px 48px; letter-spacing: 0.05em; text-transform: uppercase; font-weight: 500; border: none; border-radius: 0; transition: background 0.2s, transform 0.2s; } .ds-btn-primary:hover { background: oklch(60% 0.25 350); transform: translateY(-2px); }"
- }
- ],
- "narrative": {
- "northStar": "The Editorial Sanctuary",
- "overview": "2-3 paragraphs of the philosophy, pulled from DESIGN.md Overview section.",
- "keyCharacteristics": ["...", "..."],
- "rules": [{ "name": "The One Voice Rule", "body": "...", "section": "colors|typography|elevation" }],
- "dos": ["Do use ..."],
- "donts": ["Don't use ..."]
- }
-}
-```
-
-**What changed from schemaVersion 1.** The old sidecar carried token primitive arrays (`tokens.colors[]`, `tokens.typography[]`, etc.). Those values now live in the frontmatter. The sidecar only carries metadata that can't live in the frontmatter (tonal ramps, canonical OKLCH when the hex is an approximation, display names, role hints), keyed by the frontmatter token name (`colorMeta.<token-name>`, `typographyMeta.<token-name>`). Components still carry full HTML/CSS because Stitch's 8-prop set can't hold them.
-
-#### Component translation rules
-
-The `html` and `css` fields must be **self-contained, drop-in snippets** that render correctly when injected into a shadow DOM. The panel applies them directly: no post-processing, no framework runtime.
-
-1. **Tailwind expansion.** If the source uses Tailwind (className="bg-primary text-white rounded-lg px-6 py-3"), expand every utility to literal CSS properties in the `css` string. Do **not** reference Tailwind classes; do **not** assume a Tailwind CSS bundle is loaded. Each component is self-contained.
-2. **Token resolution.** If the project exposes tokens as CSS custom properties on `:root` (e.g. `--color-primary`, `--radius-md`), reference them via `var(--color-primary)`; they inherit through the shadow DOM and stay live-bound. If tokens live only in JS theme objects (styled-components, CSS-in-JS), resolve to literal values at generation time.
-3. **Icons.** Inline as SVG. Do not reference Lucide/Heroicons packages, icon fonts, or `<img src="...">`. A typical icon is 16-24px; copy the SVG path data directly.
-4. **States.** Include `:hover`, `:focus-visible`, and (if meaningful) `:active` rules inline. A static default-only snapshot makes the panel feel dead. Hover + focus rules in the CSS make it feel alive.
-5. **Reset bloat.** Extract only the component's *distinctive* CSS (background, color, padding, border-radius, typography, transition). Skip universal resets (`box-sizing: border-box`, `line-height: inherit`, `-webkit-font-smoothing`). The panel already has a neutral canvas; don't re-ship resets.
-6. **Scoped class names.** Prefix every class with `ds-` (e.g. `ds-btn-primary`, `ds-input-search`) so component CSS doesn't collide with other components' CSS in the same shadow DOM.
-
-#### What to include
-
-Aim for a tight set of **5-10 components** that best represent the visual system:
-
-- **Canonical primitives (always include if the project has them):** button (each variant as a separate component entry), input/text field, navigation, chip/tag, card.
-- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.
-- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.
-
-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.
-
-#### Tonal ramps
-
-For each color token, generate an 8-step `tonalRamp` array: dark to light, same hue and chroma, stepped lightness from ~15% to ~95%. The panel renders this as a strip under the swatch. If the project already defines a tonal scale (Material `surface-container-low` family, Tailwind-style `blue-50..blue-900`), use those values. Otherwise synthesize in OKLCH.
-
-#### Narrative mapping
-
-Pull directly from the DESIGN.md you just wrote:
-
-- `narrative.northStar` → the `**Creative North Star: "..."**` line from Overview
-- `narrative.overview` → the philosophy paragraphs from Overview
-- `narrative.keyCharacteristics` → the bulleted `**Key Characteristics:**` list
-- `narrative.rules` → every `**The [Name] Rule.** [body]` across all sections, tagged with `section`
-- `narrative.dos` / `narrative.donts` → the bullet lists from Do's and Don'ts verbatim
-
-Do not reword. The panel shows these as secondary collapsible context; the same voice that's in the Markdown carries through.
-
-### Step 5: Confirm, refine, and refresh session cache
-
-1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).
-2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.
-3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"
-4. **Refresh the session cache.** Run `node .github/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.
-
-## Seed mode
-
-For projects with no visual system to extract yet. Produces a minimal scaffold, not a full spec.
-
-### Step 1: Confirm seed mode
-
-Before interviewing: "There's no existing visual system to scan. I'll ask five quick questions to seed a starter DESIGN.md. You can re-run `/impeccable document` once there's code, to capture the real tokens and components. OK?"
-
-If the user prefers to skip, stop. No file.
-
-### Step 2: Five questions
-
-Group into one `AskUserQuestion` interaction. Options must be concrete.
-
-1. **Color strategy.** Pick one:
- - Restrained: tinted neutrals + one accent ≤10%
- - Committed: one saturated color carries 30–60% of the surface
- - Full palette: 3–4 named color roles, each deliberate
- - Drenched: the surface IS the color
-
- Then: one hue family or anchor reference ("deep teal", "mustard", "Klim #ff4500 orange").
-
-2. **Typography direction.** Pick one (specific fonts come later):
- - Serif display + sans body
- - Single sans (warm / technical / geometric / humanist; pick a feel)
- - Display + mono
- - Mono-forward
- - Editorial script + sans
-
-3. **Motion energy.** Pick one:
- - Restrained: state changes only
- - Responsive: feedback + transitions, no choreography
- - Choreographed: orchestrated entrances, scroll-driven sequences
-
-4. **Three named references.** Brands, products, printed objects. Not adjectives.
-
-5. **One anti-reference.** What it should NOT feel like. Also named.
-
-### Step 3: Write seed DESIGN.md
-
-Use the six-section spec from Scan mode. Populate what the interview answers; leave the rest as honest placeholders. The seed is a scaffold, not a fabricated spec.
-
-Lead the file with:
-
-```markdown
-<!-- SEED: re-run /impeccable document once there's code to capture the actual tokens and components. -->
-```
-
-Per-section guidance in seed mode:
-
-- **Overview**: Creative North Star and philosophy phrased from the answers (color strategy + motion energy + references). Reference the user's anti-reference directly.
-- **Colors**: Color strategy as a Named Rule (e.g. *"The Drenched Rule. The surface IS the color."*). Hue family or anchor reference. No hex values; mark as `[to be resolved during implementation]`.
-- **Typography**: the direction the user picked (e.g. "Serif display + sans body"). No font names yet: `[font pairing to be chosen at implementation]`.
-- **Elevation**: inferred from motion energy. Restrained/Responsive → flat by default; Choreographed → layered. One sentence.
-- **Components**: omit entirely; no components exist yet.
-- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.
-
-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.
-
-### Step 4: Confirm and refresh session cache
-
-1. Show the seed DESIGN.md. Call out that it is a seed (the marker is the literal commitment).
-2. Tell the user: "Re-run `/impeccable document` once you have some code. That pass will extract real tokens and generate the sidecar."
-3. Run `node .github/skills/impeccable/scripts/load-context.mjs` once so the seed lands in conversation for the rest of the session.
-
-## Style guidelines
-
-- **Frontmatter first, prose second.** Tokens go in the YAML frontmatter; prose contextualizes them. Don't redefine a token value in two places; the frontmatter is normative.
-- **Cite PRODUCT.md anti-references by name** in the Do's and Don'ts section. If PRODUCT.md lists "SaaS landing-page clichés" or "generic AI tool marketing" as anti-references, the DESIGN.md Don'ts should repeat those phrases verbatim so the visual spec enforces the strategic line.
-- **Match the spec, don't invent new sections.** The six section names are fixed. If you have Layout/Motion/Responsive content to document, fold it into Overview (philosophy-level rules) or Components (per-component behavior).
-- **Descriptive > technical**: "Gently curved edges (8px radius)" > "rounded-lg". Include the technical value in parens, lead with the description.
-- **Functional > decorative**: for each token, explain WHERE and WHY it's used, not just WHAT it is.
-- **Exact values in parens**: hex codes, px/rem values, font weights; always the number in parens alongside the description.
-- **Use Named Rules**: `**The [Name] Rule.** [short doctrine]`. These are memorable, citable, and much stickier for AI consumers than bullet lists. Stitch's own outputs use them heavily ("The No-Line Rule", "The Ghost Border Fallback"). Aim for 1-3 per section.
-- **Be forceful**. The voice of a design director. "Prohibited", "forbidden", "never", "always", not "consider", "might", "prefer". Match PRODUCT.md's tone.
-- **Concrete anti-pattern tests**. Stitch writes things like *"If it looks like a 2014 app, the shadow is too dark and the blur is too small."* A one-sentence audit test beats a paragraph of principle.
-- **Reference PRODUCT.md**. The anti-references section of PRODUCT.md should directly inform the Do's and Don'ts section here. Quote or paraphrase.
-- **Group colors by role**, not by hex-order or hue-order. Primary / Secondary / Tertiary / Neutral is the spec ordering.
-
-## Pitfalls
-
-- Don't paste raw CSS class names. Translate to descriptive language.
-- Don't extract every token. Stop at what's actually reused; one-offs pollute the system.
-- Don't invent components that don't exist. If the project only has buttons and cards, only document those.
-- Don't overwrite an existing DESIGN.md without asking.
-- Don't duplicate content from PRODUCT.md. DESIGN.md is strictly visual.
-- Don't add a "Layout Principles" or "Motion" or "Responsive Behavior" top-level section. The spec has six, not nine. Fold that content where it belongs.
-- Don't rename sections even slightly. "Colors" not "Color Palette & Roles". "Typography" not "Typography Rules". Tooling parsing depends on exact headers.
-- Don't duplicate token values between frontmatter and prose. If a color is in `colors.primary` as hex, the prose can name it and describe its role but should not reassert a different hex. The frontmatter is normative.
-- Don't invent frontmatter token groups outside Stitch's schema (no `motion:`, `breakpoints:`, `shadows:` at the top level). Stitch's Zod schema only accepts `colors`, `typography`, `rounded`, `spacing`, `components`. Anything else belongs in the sidecar's `extensions`.
@@ -1,69 +0,0 @@
-# Extract Flow
-
-Identify reusable patterns, components, and design tokens, then extract and consolidate them into the design system for systematic reuse.
-
-## Step 1: Discover the Design System
-
-Find the design system, component library, or shared UI directory. Understand its structure: component organization, naming conventions, design token structure, import/export conventions.
-
-**CRITICAL**: If no design system exists, ask the user directly to clarify what you cannot infer. before creating one. Understand the preferred location and structure first.
-
-## Step 2: Identify Patterns
-
-Look for extraction opportunities in the target area:
-
-- **Repeated components**: Similar UI patterns used 3+ times (buttons, cards, inputs)
-- **Hard-coded values**: Colors, spacing, typography, shadows that should be tokens
-- **Inconsistent variations**: Multiple implementations of the same concept
-- **Composition patterns**: Layout or interaction patterns that repeat (form rows, toolbar groups, empty states)
-- **Type styles**: Repeated font-size + weight + line-height combinations
-- **Animation patterns**: Repeated easing, duration, or keyframe combinations
-
-Assess value: only extract things used 3+ times with the same intent. Premature abstraction is worse than duplication.
-
-## Step 3: Plan Extraction
-
-Create a systematic plan:
-
-- **Components to extract**: Which UI elements become reusable components?
-- **Tokens to create**: Which hard-coded values become design tokens?
-- **Variants to support**: What variations does each component need?
-- **Naming conventions**: Component names, token names, prop names that match existing patterns
-- **Migration path**: How to refactor existing uses to consume the new shared versions
-
-**IMPORTANT**: Design systems grow incrementally. Extract what is clearly reusable now, not everything that might someday be reusable.
-
-## Step 4: Extract & Enrich
-
-Build improved, reusable versions:
-
-- **Components**: Clear props API with sensible defaults, proper variants for different use cases, accessibility built in (ARIA, keyboard navigation, focus management), documentation and usage examples
-- **Design tokens**: Clear naming (primitive vs semantic), proper hierarchy and organization, documentation of when to use each token
-- **Patterns**: When to use this pattern, code examples, variations and combinations
-
-## Step 5: Migrate
-
-Replace existing uses with the new shared versions:
-
-- **Find all instances**: Search for the patterns you extracted
-- **Replace systematically**: Update each use to consume the shared version
-- **Test thoroughly**: Ensure visual and functional parity
-- **Delete dead code**: Remove the old implementations
-
-## Step 6: Document
-
-Update design system documentation:
-
-- Add new components to the component library
-- Document token usage and values
-- Add examples and guidelines
-- Update any Storybook or component catalog
-
-**NEVER**:
-- Extract one-off, context-specific implementations without generalization
-- Create components so generic they are useless
-- Extract without considering existing design system conventions
-- Skip proper TypeScript types or prop documentation
-- Create tokens for every single value (tokens should have semantic meaning)
-- Extract things that differ in intent (two buttons that look similar but serve different purposes should stay separate)
-
@@ -1,347 +0,0 @@
-Designs that only work with perfect data aren't production-ready. Harden the interface against the inputs, errors, languages, and network conditions that real users will throw at it.
-
-## Assess Hardening Needs
-
-Identify weaknesses and edge cases:
-
-1. **Test with extreme inputs**:
- - Very long text (names, descriptions, titles)
- - Very short text (empty, single character)
- - Special characters (emoji, RTL text, accents)
- - Large numbers (millions, billions)
- - Many items (1000+ list items, 50+ options)
- - No data (empty states)
-
-2. **Test error scenarios**:
- - Network failures (offline, slow, timeout)
- - API errors (400, 401, 403, 404, 500)
- - Validation errors
- - Permission errors
- - Rate limiting
- - Concurrent operations
-
-3. **Test internationalization**:
- - Long translations (German is often 30% longer than English)
- - RTL languages (Arabic, Hebrew)
- - Character sets (Chinese, Japanese, Korean, emoji)
- - Date/time formats
- - Number formats (1,000 vs 1.000)
- - Currency symbols
-
-**CRITICAL**: Designs that only work with perfect data aren't production-ready. Harden against reality.
-
-## Hardening Dimensions
-
-Systematically improve resilience:
-
-### Text Overflow & Wrapping
-
-**Long text handling**:
-```css
-/* Single line with ellipsis */
-.truncate {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* Multi-line with clamp */
-.line-clamp {
- display: -webkit-box;
- -webkit-line-clamp: 3;
- -webkit-box-orient: vertical;
- overflow: hidden;
-}
-
-/* Allow wrapping */
-.wrap {
- word-wrap: break-word;
- overflow-wrap: break-word;
- hyphens: auto;
-}
-```
-
-**Flex/Grid overflow**:
-```css
-/* Prevent flex items from overflowing */
-.flex-item {
- min-width: 0; /* Allow shrinking below content size */
- overflow: hidden;
-}
-
-/* Prevent grid items from overflowing */
-.grid-item {
- min-width: 0;
- min-height: 0;
-}
-```
-
-**Responsive text sizing**:
-- Use `clamp()` for fluid typography
-- Set minimum readable sizes (14px on mobile)
-- Test text scaling (zoom to 200%)
-- Ensure containers expand with text
-
-### Internationalization (i18n)
-
-**Text expansion**:
-- Add 30-40% space budget for translations
-- Use flexbox/grid that adapts to content
-- Test with longest language (usually German)
-- Avoid fixed widths on text containers
-
-```jsx
-// ❌ Bad: Assumes short English text
-<button className="w-24">Submit</button>
-
-// ✅ Good: Adapts to content
-<button className="px-4 py-2">Submit</button>
-```
-
-**RTL (Right-to-Left) support**:
-```css
-/* Use logical properties */
-margin-inline-start: 1rem; /* Not margin-left */
-padding-inline: 1rem; /* Not padding-left/right */
-border-inline-end: 1px solid; /* Not border-right */
-
-/* Or use dir attribute */
-[dir="rtl"] .arrow { transform: scaleX(-1); }
-```
-
-**Character set support**:
-- Use UTF-8 encoding everywhere
-- Test with Chinese/Japanese/Korean (CJK) characters
-- Test with emoji (they can be 2-4 bytes)
-- Handle different scripts (Latin, Cyrillic, Arabic, etc.)
-
-**Date/Time formatting**:
-```javascript
-// ✅ Use Intl API for proper formatting
-new Intl.DateTimeFormat('en-US').format(date); // 1/15/2024
-new Intl.DateTimeFormat('de-DE').format(date); // 15.1.2024
-
-new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: 'USD'
-}).format(1234.56); // $1,234.56
-```
-
-**Pluralization**:
-```javascript
-// ❌ Bad: Assumes English pluralization
-`${count} item${count !== 1 ? 's' : ''}`
-
-// ✅ Good: Use proper i18n library
-t('items', { count }) // Handles complex plural rules
-```
-
-### Error Handling
-
-**Network errors**:
-- Show clear error messages
-- Provide retry button
-- Explain what happened
-- Offer offline mode (if applicable)
-- Handle timeout scenarios
-
-```jsx
-// Error states with recovery
-{error && (
- <ErrorMessage>
- <p>Failed to load data. {error.message}</p>
- <button onClick={retry}>Try again</button>
- </ErrorMessage>
-)}
-```
-
-**Form validation errors**:
-- Inline errors near fields
-- Clear, specific messages
-- Suggest corrections
-- Don't block submission unnecessarily
-- Preserve user input on error
-
-**API errors**:
-- Handle each status code appropriately
- - 400: Show validation errors
- - 401: Redirect to login
- - 403: Show permission error
- - 404: Show not found state
- - 429: Show rate limit message
- - 500: Show generic error, offer support
-
-**Graceful degradation**:
-- Core functionality works without JavaScript
-- Images have alt text
-- Progressive enhancement
-- Fallbacks for unsupported features
-
-### Edge Cases & Boundary Conditions
-
-**Empty states**:
-- No items in list
-- No search results
-- No notifications
-- No data to display
-- Provide clear next action
-
-**Loading states**:
-- Initial load
-- Pagination load
-- Refresh
-- Show what's loading ("Loading your projects...")
-- Time estimates for long operations
-
-**Large datasets**:
-- Pagination or virtual scrolling
-- Search/filter capabilities
-- Performance optimization
-- Don't load all 10,000 items at once
-
-**Concurrent operations**:
-- Prevent double-submission (disable button while loading)
-- Handle race conditions
-- Optimistic updates with rollback
-- Conflict resolution
-
-**Permission states**:
-- No permission to view
-- No permission to edit
-- Read-only mode
-- Clear explanation of why
-
-**Browser compatibility**:
-- Polyfills for modern features
-- Fallbacks for unsupported CSS
-- Feature detection (not browser detection)
-- Test in target browsers
-
-### Input Validation & Sanitization
-
-**Client-side validation**:
-- Required fields
-- Format validation (email, phone, URL)
-- Length limits
-- Pattern matching
-- Custom validation rules
-
-**Server-side validation** (always):
-- Never trust client-side only
-- Validate and sanitize all inputs
-- Protect against injection attacks
-- Rate limiting
-
-**Constraint handling**:
-```html
-<!-- Set clear constraints -->
-<input
- type="text"
- maxlength="100"
- pattern="[A-Za-z0-9]+"
- required
- aria-describedby="username-hint"
-/>
-<small id="username-hint">
- Letters and numbers only, up to 100 characters
-</small>
-```
-
-### Accessibility Resilience
-
-**Keyboard navigation**:
-- All functionality accessible via keyboard
-- Logical tab order
-- Focus management in modals
-- Skip links for long content
-
-**Screen reader support**:
-- Proper ARIA labels
-- Announce dynamic changes (live regions)
-- Descriptive alt text
-- Semantic HTML
-
-**Motion sensitivity**:
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**High contrast mode**:
-- Test in Windows high contrast mode
-- Don't rely only on color
-- Provide alternative visual cues
-
-### Performance Resilience
-
-**Slow connections**:
-- Progressive image loading
-- Skeleton screens
-- Optimistic UI updates
-- Offline support (service workers)
-
-**Memory leaks**:
-- Clean up event listeners
-- Cancel subscriptions
-- Clear timers/intervals
-- Abort pending requests on unmount
-
-**Throttling & Debouncing**:
-```javascript
-// Debounce search input
-const debouncedSearch = debounce(handleSearch, 300);
-
-// Throttle scroll handler
-const throttledScroll = throttle(handleScroll, 100);
-```
-
-## Testing Strategies
-
-**Manual testing**:
-- Test with extreme data (very long, very short, empty)
-- Test in different languages
-- Test offline
-- Test slow connection (throttle to 3G)
-- Test with screen reader
-- Test keyboard-only navigation
-- Test on old browsers
-
-**Automated testing**:
-- Unit tests for edge cases
-- Integration tests for error scenarios
-- E2E tests for critical paths
-- Visual regression tests
-- Accessibility tests (axe, WAVE)
-
-**IMPORTANT**: Hardening is about expecting the unexpected. Real users will do things you never imagined.
-
-**NEVER**:
-- Assume perfect input (validate everything)
-- Ignore internationalization (design for global)
-- Leave error messages generic ("Error occurred")
-- Forget offline scenarios
-- Trust client-side validation alone
-- Use fixed widths for text
-- Assume English-length text
-- Block entire interface when one component errors
-
-## Verify Hardening
-
-Test thoroughly with edge cases:
-
-- **Long text**: Try names with 100+ characters
-- **Emoji**: Use emoji in all text fields
-- **RTL**: Test with Arabic or Hebrew
-- **CJK**: Test with Chinese/Japanese/Korean
-- **Network issues**: Disable internet, throttle connection
-- **Large datasets**: Test with 1000+ items
-- **Concurrent actions**: Click submit 10 times rapidly
-- **Errors**: Force API errors, test all error states
-- **Empty**: Remove all data, test empty states
-
-When edge cases are covered, hand off to `/impeccable polish` for the final pass.
@@ -1,234 +0,0 @@
-# Heuristics Scoring Guide
-
-Score each of Nielsen's 10 Usability Heuristics on a 0–4 scale. Be honest: a 4 means genuinely excellent, not "good enough."
-
-## Nielsen's 10 Heuristics
-
-### 1. Visibility of System Status
-
-Keep users informed about what's happening through timely, appropriate feedback.
-
-**Check for**:
-- Loading indicators during async operations
-- Confirmation of user actions (save, submit, delete)
-- Progress indicators for multi-step processes
-- Current location in navigation (breadcrumbs, active states)
-- Form validation feedback (inline, not just on submit)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No feedback; user is guessing what happened |
-| 1 | Rare feedback; most actions produce no visible response |
-| 2 | Partial; some states communicated, major gaps remain |
-| 3 | Good; most operations give clear feedback, minor gaps |
-| 4 | Excellent; every action confirms, progress is always visible |
-
-### 2. Match Between System and Real World
-
-Speak the user's language. Follow real-world conventions. Information appears in natural, logical order.
-
-**Check for**:
-- Familiar terminology (no unexplained jargon)
-- Logical information order matching user expectations
-- Recognizable icons and metaphors
-- Domain-appropriate language for the target audience
-- Natural reading flow (left-to-right, top-to-bottom priority)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Pure tech jargon, alien to users |
-| 1 | Mostly confusing; requires domain expertise to navigate |
-| 2 | Mixed; some plain language, some jargon leaks through |
-| 3 | Mostly natural; occasional term needs context |
-| 4 | Speaks the user's language fluently throughout |
-
-### 3. User Control and Freedom
-
-Users need a clear "emergency exit" from unwanted states without extended dialogue.
-
-**Check for**:
-- Undo/redo functionality
-- Cancel buttons on forms and modals
-- Clear navigation back to safety (home, previous)
-- Easy way to clear filters, search, selections
-- Escape from long or multi-step processes
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Users get trapped; no way out without refreshing |
-| 1 | Difficult exits; must find obscure paths to escape |
-| 2 | Some exits; main flows have escape, edge cases don't |
-| 3 | Good control; users can exit and undo most actions |
-| 4 | Full control; undo, cancel, back, and escape everywhere |
-
-### 4. Consistency and Standards
-
-Users shouldn't wonder whether different words, situations, or actions mean the same thing.
-
-**Check for**:
-- Consistent terminology throughout the interface
-- Same actions produce same results everywhere
-- Platform conventions followed (standard UI patterns)
-- Visual consistency (colors, typography, spacing, components)
-- Consistent interaction patterns (same gesture = same behavior)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Inconsistent everywhere; feels like different products stitched together |
-| 1 | Many inconsistencies; similar things look/behave differently |
-| 2 | Partially consistent; main flows match, details diverge |
-| 3 | Mostly consistent; occasional deviation, nothing confusing |
-| 4 | Fully consistent; cohesive system, predictable behavior |
-
-### 5. Error Prevention
-
-Better than good error messages is a design that prevents problems in the first place.
-
-**Check for**:
-- Confirmation before destructive actions (delete, overwrite)
-- Constraints preventing invalid input (date pickers, dropdowns)
-- Smart defaults that reduce errors
-- Clear labels that prevent misunderstanding
-- Autosave and draft recovery
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Errors easy to make; no guardrails anywhere |
-| 1 | Few safeguards; some inputs validated, most aren't |
-| 2 | Partial prevention; common errors caught, edge cases slip |
-| 3 | Good prevention; most error paths blocked proactively |
-| 4 | Excellent; errors nearly impossible through smart constraints |
-
-### 6. Recognition Rather Than Recall
-
-Minimize memory load. Make objects, actions, and options visible or easily retrievable.
-
-**Check for**:
-- Visible options (not buried in hidden menus)
-- Contextual help when needed (tooltips, inline hints)
-- Recent items and history
-- Autocomplete and suggestions
-- Labels on icons (not icon-only navigation)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Heavy memorization; users must remember paths and commands |
-| 1 | Mostly recall; many hidden features, few visible cues |
-| 2 | Some aids; main actions visible, secondary features hidden |
-| 3 | Good recognition; most things discoverable, few memory demands |
-| 4 | Everything discoverable; users never need to memorize |
-
-### 7. Flexibility and Efficiency of Use
-
-Accelerators, invisible to novices, speed up expert interaction.
-
-**Check for**:
-- Keyboard shortcuts for common actions
-- Customizable interface elements
-- Recent items and favorites
-- Bulk/batch actions
-- Power user features that don't complicate the basics
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | One rigid path; no shortcuts or alternatives |
-| 1 | Limited flexibility; few alternatives to the main path |
-| 2 | Some shortcuts; basic keyboard support, limited bulk actions |
-| 3 | Good accelerators; keyboard nav, some customization |
-| 4 | Highly flexible; multiple paths, power features, customizable |
-
-### 8. Aesthetic and Minimalist Design
-
-Interfaces should not contain irrelevant or rarely needed information. Every element should serve a purpose.
-
-**Check for**:
-- Only necessary information visible at each step
-- Clear visual hierarchy directing attention
-- Purposeful use of color and emphasis
-- No decorative clutter competing for attention
-- Focused, uncluttered layouts
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Overwhelming; everything competes for attention equally |
-| 1 | Cluttered; too much noise, hard to find what matters |
-| 2 | Some clutter; main content clear, periphery noisy |
-| 3 | Mostly clean; focused design, minor visual noise |
-| 4 | Perfectly minimal; every element earns its pixel |
-
-### 9. Help Users Recognize, Diagnose, and Recover from Errors
-
-Error messages should use plain language, precisely indicate the problem, and constructively suggest a solution.
-
-**Check for**:
-- Plain language error messages (no error codes for users)
-- Specific problem identification ("Email is missing @" not "Invalid input")
-- Actionable recovery suggestions
-- Errors displayed near the source of the problem
-- Non-blocking error handling (don't wipe the form)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Cryptic errors; codes, jargon, or no message at all |
-| 1 | Vague errors; "Something went wrong" with no guidance |
-| 2 | Clear but unhelpful; names the problem but not the fix |
-| 3 | Clear with suggestions; identifies problem and offers next steps |
-| 4 | Perfect recovery; pinpoints issue, suggests fix, preserves user work |
-
-### 10. Help and Documentation
-
-Even if the system is usable without docs, help should be easy to find, task-focused, and concise.
-
-**Check for**:
-- Searchable help or documentation
-- Contextual help (tooltips, inline hints, guided tours)
-- Task-focused organization (not feature-organized)
-- Concise, scannable content
-- Easy access without leaving current context
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No help available anywhere |
-| 1 | Help exists but hard to find or irrelevant |
-| 2 | Basic help; FAQ or docs exist, not contextual |
-| 3 | Good documentation; searchable, mostly task-focused |
-| 4 | Excellent contextual help; right info at the right moment |
-
----
-
-## Score Summary
-
-**Total possible**: 40 points (10 heuristics × 4 max)
-
-| Score Range | Rating | What It Means |
-|-------------|--------|---------------|
-| 36–40 | Excellent | Minor polish only; ship it |
-| 28–35 | Good | Address weak areas, solid foundation |
-| 20–27 | Acceptable | Significant improvements needed before users are happy |
-| 12–19 | Poor | Major UX overhaul required; core experience broken |
-| 0–11 | Critical | Redesign needed; unusable in current state |
-
----
-
-## Issue Severity (P0–P3)
-
-Tag each individual issue found during scoring with a priority level:
-
-| Priority | Name | Description | Action |
-|----------|------|-------------|--------|
-| **P0** | Blocking | Prevents task completion entirely | Fix immediately; this is a showstopper |
-| **P1** | Major | Causes significant difficulty or confusion | Fix before release |
-| **P2** | Minor | Annoyance, but workaround exists | Fix in next pass |
-| **P3** | Polish | Nice-to-fix, no real user impact | Fix if time permits |
-
-**Tip**: If you're unsure between two levels, ask: "Would a user contact support about this?" If yes, it's at least P1.
@@ -1,195 +0,0 @@
-# Interaction Design
-
-## The Eight Interactive States
-
-Every interactive element needs these states designed:
-
-| State | When | Visual Treatment |
-|-------|------|------------------|
-| **Default** | At rest | Base styling |
-| **Hover** | Pointer over (not touch) | Subtle lift, color shift |
-| **Focus** | Keyboard/programmatic focus | Visible ring (see below) |
-| **Active** | Being pressed | Pressed in, darker |
-| **Disabled** | Not interactive | Reduced opacity, no pointer |
-| **Loading** | Processing | Spinner, skeleton |
-| **Error** | Invalid state | Red border, icon, message |
-| **Success** | Completed | Green check, confirmation |
-
-**The common miss**: Designing hover without focus, or vice versa. They're different. Keyboard users never see hover states.
-
-## Focus Rings: Do Them Right
-
-**Never `outline: none` without replacement.** It's an accessibility violation. Instead, use `:focus-visible` to show focus only for keyboard users:
-
-```css
-/* Hide focus ring for mouse/touch */
-button:focus {
- outline: none;
-}
-
-/* Show focus ring for keyboard */
-button:focus-visible {
- outline: 2px solid var(--color-accent);
- outline-offset: 2px;
-}
-```
-
-**Focus ring design**:
-- High contrast (3:1 minimum against adjacent colors)
-- 2-3px thick
-- Offset from element (not inside it)
-- Consistent across all interactive elements
-
-## Form Design: The Non-Obvious
-
-**Placeholders aren't labels.** They disappear on input. Always use visible `<label>` elements. **Validate on blur**, not on every keystroke (exception: password strength). Place errors **below** fields with `aria-describedby` connecting them.
-
-## Loading States
-
-**Optimistic updates**: Show success immediately, rollback on failure. Use for low-stakes actions (likes, follows), not payments or destructive actions. **Skeleton screens > spinners**: they preview content shape and feel faster than generic spinners.
-
-## Modals: The Inert Approach
-
-Focus trapping in modals used to require complex JavaScript. Now use the `inert` attribute:
-
-```html
-<!-- When modal is open -->
-<main inert>
- <!-- Content behind modal can't be focused or clicked -->
-</main>
-<dialog open>
- <h2>Modal Title</h2>
- <!-- Focus stays inside modal -->
-</dialog>
-```
-
-Or use the native `<dialog>` element:
-
-```javascript
-const dialog = document.querySelector('dialog');
-dialog.showModal(); // Opens with focus trap, closes on Escape
-```
-
-## The Popover API
-
-For tooltips, dropdowns, and non-modal overlays, use native popovers:
-
-```html
-<button popovertarget="menu">Open menu</button>
-<div id="menu" popover>
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-**Benefits**: Light-dismiss (click outside closes), proper stacking, no z-index wars, accessible by default.
-
-## Dropdown & Overlay Positioning
-
-Dropdowns rendered with `position: absolute` inside a container that has `overflow: hidden` or `overflow: auto` will be clipped. This is the single most common dropdown bug in generated code.
-
-### CSS Anchor Positioning
-
-The modern solution uses the CSS Anchor Positioning API to tether an overlay to its trigger without JavaScript:
-
-```css
-.trigger {
- anchor-name: --menu-trigger;
-}
-
-.dropdown {
- position: fixed;
- position-anchor: --menu-trigger;
- position-area: block-end span-inline-end;
- margin-top: 4px;
-}
-
-/* Flip above if no room below */
-@position-try --flip-above {
- position-area: block-start span-inline-end;
- margin-bottom: 4px;
-}
-```
-
-Because the dropdown uses `position: fixed`, it escapes any `overflow` clipping on ancestor elements. The `@position-try` block handles viewport edges automatically. **Browser support**: Chrome 125+, Edge 125+. Not yet in Firefox or Safari - use a fallback for those browsers.
-
-### Popover + Anchor Combo
-
-Combining the Popover API with anchor positioning gives you stacking, light-dismiss, accessibility, and correct positioning in one pattern:
-
-```html
-<button popovertarget="menu" class="trigger">Open</button>
-<div id="menu" popover class="dropdown">
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-The `popover` attribute places the element in the **top layer**, which sits above all other content regardless of z-index or overflow. No portal needed.
-
-### Portal / Teleport Pattern
-
-In component frameworks, render the dropdown at the document root and position it with JavaScript:
-
-- **React**: `createPortal(dropdown, document.body)`
-- **Vue**: `<Teleport to="body">`
-- **Svelte**: Use a portal library or mount to `document.body`
-
-Calculate position from the trigger's `getBoundingClientRect()`, then apply `position: fixed` with `top` and `left` values. Recalculate on scroll and resize.
-
-### Fixed Positioning Fallback
-
-For browsers without anchor positioning support, `position: fixed` with manual coordinates avoids overflow clipping:
-
-```css
-.dropdown {
- position: fixed;
- /* top/left set via JS from trigger's getBoundingClientRect() */
-}
-```
-
-Check viewport boundaries before rendering. If the dropdown would overflow the bottom edge, flip it above the trigger. If it would overflow the right edge, align it to the trigger's right side instead.
-
-### Anti-Patterns
-
-- **`position: absolute` inside `overflow: hidden`** - The dropdown will be clipped. Use `position: fixed` or the top layer instead.
-- **Arbitrary z-index values** like `z-index: 9999` - Use a semantic z-index scale: `dropdown (100) -> sticky (200) -> modal-backdrop (300) -> modal (400) -> toast (500) -> tooltip (600)`.
-- **Rendering dropdown markup inline** without an escape hatch from the parent's stacking context. Either use `popover` (top layer), a portal, or `position: fixed`.
-
-## Destructive Actions: Undo > Confirm
-
-**Undo is better than confirmation dialogs.** Users click through confirmations mindlessly. Remove from UI immediately, show undo toast, actually delete after toast expires. Use confirmation only for truly irreversible actions (account deletion), high-cost actions, or batch operations.
-
-## Keyboard Navigation Patterns
-
-### Roving Tabindex
-
-For component groups (tabs, menu items, radio groups), one item is tabbable; arrow keys move within:
-
-```html
-<div role="tablist">
- <button role="tab" tabindex="0">Tab 1</button>
- <button role="tab" tabindex="-1">Tab 2</button>
- <button role="tab" tabindex="-1">Tab 3</button>
-</div>
-```
-
-Arrow keys move `tabindex="0"` between items. Tab moves to the next component entirely.
-
-### Skip Links
-
-Provide skip links (`<a href="#main-content">Skip to main content</a>`) for keyboard users to jump past navigation. Hide off-screen, show on focus.
-
-## Gesture Discoverability
-
-Swipe-to-delete and similar gestures are invisible. Hint at their existence:
-
-- **Partially reveal**: Show delete button peeking from edge
-- **Onboarding**: Coach marks on first use
-- **Alternative**: Always provide a visible fallback (menu with "Delete")
-
-Don't rely on gestures as the only way to perform actions.
-
----
-
-**Avoid**: Removing focus indicators without alternatives. Using placeholder text as labels. Touch targets <44x44px. Generic error messages. Custom controls without ARIA/keyboard support.
@@ -1,141 +0,0 @@
-Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids, the centered-stack default) and fix the structure, not the surface.
-
----
-
-## Register
-
-Brand: asymmetric compositions, fluid spacing with `clamp()`, intentional grid-breaking for emphasis. Rhythm through contrast: tight groupings paired with generous separations.
-
-Product: predictable grids, consistent densities, familiar navigation patterns. Responsive behavior is structural (collapse sidebar, responsive table), not fluid typography. Consistency IS an affordance.
-
----
-
-## Assess Current Layout
-
-Analyze what's weak about the current spatial design:
-
-1. **Spacing**:
- - Is spacing consistent or arbitrary? (Random padding/margin values)
- - Is all spacing the same? (Equal padding everywhere = no rhythm)
- - Are related elements grouped tightly, with generous space between groups?
-
-2. **Visual hierarchy**:
- - Apply the squint test: blur your (metaphorical) eyes. Can you still identify the most important element, second most important, and clear groupings?
- - Is hierarchy achieved effectively? (Space and weight alone can be enough; is the current approach working?)
- - Does whitespace guide the eye to what matters?
-
-3. **Grid & structure**:
- - Is there a clear underlying structure, or does the layout feel random?
- - Are identical card grids used everywhere? (Icon + heading + text, repeated endlessly)
- - Is everything centered? (Left-aligned with asymmetric layouts feels more designed, but not a hard and fast rule)
-
-4. **Rhythm & variety**:
- - Does the layout have visual rhythm? (Alternating tight/generous spacing)
- - Is every section structured the same way? (Monotonous repetition)
- - Are there intentional moments of surprise or emphasis?
-
-5. **Density**:
- - Is the layout too cramped? (Not enough breathing room)
- - Is the layout too sparse? (Excessive whitespace without purpose)
- - Does density match the content type? (Data-dense UIs need tighter spacing; marketing pages need more air)
-
-**CRITICAL**: Layout problems are often the root cause of interfaces feeling "off" even when colors and fonts are fine. Space is a design material; use it with intention.
-
-## Plan Layout Improvements
-
-Consult the [spatial design reference](spatial-design.md) for detailed guidance on grids, rhythm, and container queries.
-
-Create a systematic plan:
-
-- **Spacing system**: Use a consistent scale (a framework's built-in scale like Tailwind's, rem-based tokens, or a custom system). The specific values matter less than consistency.
-- **Hierarchy strategy**: How will space communicate importance?
-- **Layout approach**: What structure fits the content? Flex for 1D, Grid for 2D, named areas for complex page layouts.
-- **Rhythm**: Where should spacing be tight vs generous?
-
-## Improve Layout Systematically
-
-### Establish a Spacing System
-
-- Use a consistent spacing scale (framework scales like Tailwind, rem-based tokens, or a custom scale all work). What matters is that values come from a defined set, not arbitrary numbers.
-- Name tokens semantically if using custom properties: `--space-xs` through `--space-xl`, not `--spacing-8`
-- Use `gap` for sibling spacing instead of margins; eliminates margin collapse hacks
-- Apply `clamp()` for fluid spacing that breathes on larger screens
-
-### Create Visual Rhythm
-
-- **Tight grouping** for related elements (8-12px between siblings)
-- **Generous separation** between distinct sections (48-96px)
-- **Varied spacing** within sections (not every row needs the same gap)
-- **Asymmetric compositions**: break the predictable centered-content pattern when it makes sense
-
-### Choose the Right Layout Tool
-
-- **Use Flexbox for 1D layouts**: Rows of items, nav bars, button groups, card contents, most component internals. Flex is simpler and more appropriate for the majority of layout tasks.
-- **Use Grid for 2D layouts**: Page-level structure, dashboards, data-dense interfaces, anything where rows AND columns need coordinated control.
-- **Don't default to Grid** when Flexbox with `flex-wrap` would be simpler and more flexible.
-- Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints.
-- Use named grid areas (`grid-template-areas`) for complex page layouts; redefine at breakpoints.
-
-### Break Card Grid Monotony
-
-- Don't default to card grids for everything; spacing and alignment create visual grouping naturally
-- Use cards only when content is truly distinct and actionable. Never nest cards inside cards
-- Vary card sizes, span columns, or mix cards with non-card content to break repetition
-
-### Strengthen Visual Hierarchy
-
-- Use the fewest dimensions needed for clear hierarchy. Space alone can be enough; generous whitespace around an element draws the eye. Some of the most polished designs achieve rhythm with just space and weight. Add color or size contrast only when simpler means aren't sufficient.
-- Be aware of reading flow: in LTR languages, the eye naturally scans top-left to bottom-right, but primary action placement depends on context (e.g., bottom-right in dialogs, top in navigation).
-- Create clear content groupings through proximity and separation.
-
-### Manage Depth & Elevation
-
-- Create a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip)
-- Build a consistent shadow scale (sm → md → lg → xl); shadows should be subtle
-- Use elevation to reinforce hierarchy, not as decoration
-
-### Optical Adjustments
-
-- If an icon looks visually off-center despite being geometrically centered, nudge it. But only if you're confident it actually looks wrong. Don't adjust speculatively.
-
-**NEVER**:
-- Use arbitrary spacing values outside your scale
-- Make all spacing equal (variety creates hierarchy)
-- Wrap everything in cards (not everything needs a container)
-- Nest cards inside cards (use spacing and dividers for hierarchy within)
-- Use identical card grids everywhere (icon + heading + text, repeated)
-- Center everything (left-aligned with asymmetry feels more designed)
-- Default to the hero metric layout (big number, small label, stats, gradient) as a template. If showing real user data, a prominent metric can work, but it should display actual data, not decorative numbers.
-- Default to CSS Grid when Flexbox would be simpler; use the simplest tool for the job
-- Use arbitrary z-index values (999, 9999); build a semantic scale
-
-## Verify Layout Improvements
-
-- **Squint test**: Can you identify primary, secondary, and groupings with blurred vision?
-- **Rhythm**: Does the page have a satisfying beat of tight and generous spacing?
-- **Hierarchy**: Is the most important content obvious within 2 seconds?
-- **Breathing room**: Does the layout feel comfortable, not cramped or wasteful?
-- **Consistency**: Is the spacing system applied uniformly?
-- **Responsiveness**: Does the layout adapt gracefully across screen sizes?
-
-When the rhythm and hierarchy land, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `density` param. Drive all spacing tokens in the variant's scoped CSS through `calc(var(--p-density, 1) * <base>)`: paddings, gaps, column widths. Users slide from airy to packed and see layout re-breathe with no regeneration.
-
-```json
-{"id":"density","kind":"range","min":0.6,"max":1.4,"step":0.05,"default":1,"label":"Density"}
-```
-
-For variants whose topology genuinely changes (stacked vs. side-by-side, grid vs. bento), use a `steps` param whose scoped CSS branches via `:scope[data-p-structure="X"]`. One structure param + one density param is a powerful combo; resist adding a third.
-
-```json
-{"id":"structure","kind":"steps","default":"grid","label":"Structure","options":[
- {"value":"stacked","label":"Stacked"},
- {"value":"grid","label":"Grid"},
- {"value":"bento","label":"Bento"}
-]}
-```
-
-See `reference/live.md` for the full params contract.
@@ -1,622 +0,0 @@
-Interactive live variant mode: select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via the dev server's HMR.
-
-## Prerequisites
-
-A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR a static HTML file open in the browser.
-
-## The contract (read once)
-
-Execute in order. No step skipped, no step reordered.
-
-1. `live.mjs`: boot.
-2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.
-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.
-5. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
-6. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
-7. On `exit`: run the cleanup at the bottom.
-
-Harness policy:
-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.
-- **Cursor**: run the poll in the **foreground** (blocking shell; not a background terminal, not a subagent). Cursor background terminals and subagents do not reliably resume the chat with poll stdout.
-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.
-- **Other harnesses**: foreground unless you know stdout reliably returns to this session.
-
-Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.
-
-## Start
-
-```bash
-node .github/skills/impeccable/scripts/live.mjs
-```
-
-Output JSON: `{ ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath, migrated }`. `pageFiles` is the list of HTML entries the live script was injected into. Keep PRODUCT.md and DESIGN.md in mind for variant generation; **DESIGN.md wins on visual decisions; PRODUCT.md wins on strategic/voice decisions.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt. If `migrated: true`, the loader auto-renamed legacy `.impeccable.md` to `PRODUCT.md`; mention this once and suggest `/impeccable document` for the matching DESIGN.md.
-
-`serverPort` and `serverToken` belong to the small **Impeccable live helper** HTTP server (serves `/live.js`, SSE, and `/poll`). That port is **not** your dev server and is usually not the URL you open to view the app. The browser page is whatever origin serves one of the `pageFiles` entries (Vite / Next / Bun / tunnel / LAN hostname).
-
-If output is `{ ok: false, error: "config_missing" | "config_invalid", path }`, this project hasn't been configured for live mode (or its config is stale). See **First-time setup** at the bottom.
-
-## Poll loop
-
-```
-LOOP:
- node .github/skills/impeccable/scripts/live-poll.mjs # default long timeout; no --timeout=
- Read JSON; dispatch on "type"
-
- "generate" → Handle Generate; reply done; LOOP
- "accept" → Handle Accept; complete carbonize cleanup if required; LOOP
- "discard" → Handle Discard; LOOP
- "prefetch" → Handle Prefetch; LOOP
- "timeout" → LOOP
- "exit" → break → Cleanup
-```
-
-## Recovery commands
-
-The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.
-
-Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:
-
-```bash
-node .github/skills/impeccable/scripts/live-status.mjs
-node .github/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID
-node .github/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID
-```
-
-- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.
-- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.
-- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.
-
-Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.
-
-## Handle `generate`
-
-Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.
-
-Speed matters; the user is watching a spinner. Minimize tool calls by using the `wrap` helper and writing all variants in a single edit.
-
-### 1. Read the screenshot (if present)
-
-`event.screenshotPath` is **only sent when the user placed at least one comment or stroke before Go.** When present, it's an absolute path to a PNG of the element as rendered with the annotations baked in. **Read it before planning**: annotations encode user intent not recoverable from `element.outerHTML` alone.
-
-When `screenshotPath` is absent, don't ask for one and don't go looking for the current rendering. The omission is deliberate: without annotations, a screenshot would anchor the model on the existing design and fight the three-distinct-directions brief. Work from `element.outerHTML`, the computed styles in `event.element`, and the freeform prompt if present.
-
-`event.comments` and `event.strokes` carry structured metadata alongside the visual. Treat the screenshot as primary; use the structured data for specifics worth quoting (e.g. the exact text of a comment).
-
-Reading annotations precisely:
-
-- **Comment position carries meaning.** Its `{x, y}` is element-local CSS px (same coord space as `element.boundingRect`). Find the child under that point and apply the comment text LOCALLY to that sub-element. A comment near the title is about the title, not a global description.
-- **Comments and strokes are independent annotations** unless clearly paired by overlap or tight proximity. Don't let the visual weight of a prominent stroke override the precise location of a textually-specific comment elsewhere.
-- **Strokes are gestures; read them by shape.** Closed loop = "this thing" (emphasis / focus); arrow = direction (move / point to); cross or slash = delete; free scribble = emphasis or delete depending on context. A loop around region X means "pay attention to X," not "only change pixels inside X."
-- **When a stroke's intent is ambiguous** (circle or arrow? emphasis or move?), state your reading in one sentence of rationale rather than silently guessing. If the uncertainty materially changes the brief, ask one short clarifying question before generating.
-
-### 2. Wrap the element
-
-```bash
-node .github/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"
-```
-
-Flag mapping. Keep them separate, don't collapse into `--query`:
-
-- `--element-id` ← `event.element.id`
-- `--classes` ← `event.element.classes` joined with commas
-- `--tag` ← `event.element.tagName`
-- `--text` ← first ~80 chars of `event.element.textContent` (trim, single-line). **Pass this every call.** When the picked element shares classes + tag with sibling components (a list of `<Card>`s, repeating sections), this is what disambiguates which branch in source to wrap. Without it, wrap silently lands on the first match and may rewrite the wrong element.
-
-The helper searches ID first, then classes, then tag + class combo. If `event.pageUrl` implies the file (e.g. `/` is usually `index.html`), pass `--file PATH` to skip the search. `--query` is a fallback for raw text search only; do not use it for normal element lookups.
-
-If `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.
-
-Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.
-
-`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:
-
-- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.
-- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.
-
-Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.
-
-**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:
-
-- `{ error: "file_is_generated", file, hint }`: user-supplied `--file` points at a generated file.
-- `{ error: "element_not_in_source", generatedMatch, hint }`: element exists only in a generated file (the next build would wipe any edits).
-- `{ error: "element_not_found", hint }`: element isn't in any project file; likely runtime-injected (JS component, dynamic render from data).
-
-All three carry `fallback: "agent-driven"`. Follow **Handle fallback** below.
-
-### 3. Load the action's reference
-
-If `event.action` is `impeccable` (the default freeform action), use SKILL.md's shared laws plus the loaded register reference (`brand.md` or `product.md`). Do not load a sub-command reference. **Freeform is not a pass to skip parameters:** you still follow the composition budget and the freeform bias in **§7 Parameters** below. Sub-command files list MUST-have signature knobs; freeform has no such file, so sizing knobs from surface weight and primary axes is entirely on you.
-
-Any other `event.action` (`bolder`, `quieter`, `distill`, `polish`, `typeset`, `colorize`, `layout`, `adapt`, `animate`, `delight`, `overdrive`): Read `reference/<action>.md` before planning. Each sub-command encodes a specific discipline; skipping its reference produces generic output. Those files may require specific params; layer them on top of the §7 budget, not instead of it.
-
-### 4. Plan three variants: identity first, then mode, then axes
-
-The wrong frame for live mode is "show three different design directions." Live runs on an existing surface; the brand has already been chosen. The job is variation **within identity**, not selection between identities. Failure mode: three editorial-typographic variants on a brief that wasn't editorial. Bigger failure mode: three off-brand variants the user can't accept because they don't look like their product.
-
-Four phases. Do them in order.
-
-#### Phase A: Extract the identity (non-skippable)
-
-The existing surface has an identity already. Read it before planning anything. Sources, in priority order:
-
-1. **DESIGN.md** if loaded: read the visual system fields (palette, type pairing, motion, components). This is the authoritative answer.
-2. **CSS custom properties** in the page's stylesheets (`:root { --color-...; --font-...; ... }`): these are de-facto tokens.
-3. **Computed styles** on the picked element and its parent: colors, fonts, spacing scales, corner radii.
-4. **Sibling components on the page**: what visual rhetoric do existing components use? (Asymmetric or centered? Dense or airy? Bold or quiet?)
-
-Write down what you see in **one sentence**. The sentence describes the surface that's actually on screen; it is not aspirational, not opinionated, not edited toward what the brand "should" be. Capture, in roughly this order:
-
-- The dominant surface color and accent color, by hex or token name (use the actual values, not categories like "warm" or "neutral").
-- The type pairing: the actual font names loaded, primary first.
-- The layout topology: how the dominant elements are arranged (stacked / side-by-side / grid / asymmetric / overlay).
-- The surface treatment: corners, borders, shadows, density of decoration.
-- The voice tone you read off the copy itself, not off the aesthetic feel.
-
-Be specific. "Modern" is not a color, "elegant" is not a type pairing, "clean" is not a layout. If you can't extract a real value for an axis, skip it rather than fabricate. The point is to record what is, not to describe what you wish it were.
-
-Do not include adjectives that name an aesthetic family ("editorial-leaning", "terminal-flavored", "brutalist"); those are conclusions, not data. They belong to Phase C lane selection in departure mode, not to identity description. Letting them sneak into Phase A is how the identity-lock collapses into a self-fulfilling prophecy.
-
-This sentence is the **identity lock**. Every variant must be readable as the same brand if rendered side by side. Skipping this phase is the primary cause of off-brand variants. Absence of DESIGN.md is never an excuse; extract from CSS and computed styles instead.
-
-#### Phase B: Pick mode (default vs departure)
-
-**Default mode**: the existing identity is preserved. Variants vary expression axes within it. *This is the right mode for ~90% of live sessions.* The user picked an element on a real product they're shipping; they expect variants of *their* hero, not three different brands' heroes.
-
-**Departure mode**: the existing identity is rejected. Variants propose alternatives consistent with PRODUCT.md voice. Trigger only when at least one is true:
-
-- PRODUCT.md anti-references explicitly call out the current surface ("the current `index.html` is itself an example"; "diffuse away from this"; "the page on screen is the failure"). Generic anti-references that describe what to avoid in general do **not** trigger departure mode; only ones that point at *this* surface specifically.
-- The user's freeform prompt explicitly asks for departure ("rebuild this from scratch", "what if it weren't editorial at all", "show me something completely different").
-
-If you're unsure, you're in default mode. The cost of being wrong about default is "three on-brand variants with similar feel": recoverable, the user picks none. The cost of being wrong about departure is "three off-brand variants": unrecoverable, the user is annoyed.
-
-#### Phase C: Plan three variants
-
-**Default mode.** Each variant commits to a different **primary axis** of difference, while preserving the identity sentence. The six axes:
-
-1. **Hierarchy**: which element commands the eye?
-2. **Layout topology**: stacked / side-by-side / grid / asymmetric / overlay
-3. **Typographic system**: pairing logic, scale ratio, case/weight strategy *within the available faces*
-4. **Color strategy**: which existing palette role carries the surface (Restrained / Committed / Full palette / Drenched). Use the brand's existing palette tokens, not new colors.
-5. **Density**: minimal / comfortable / dense
-6. **Structural decomposition**: merge, split, progressive disclosure
-
-Three variants → three DIFFERENT axes. The trio reads as *the same brand at three angles*. Do not introduce new fonts, new palette hues, or new aesthetic-family signals; those belong to departure mode.
-
-**While planning each variant, also name its 2–3 parameter knobs** (per the §7 budget table). Parameters are part of the design, not a decoration added afterward. If the variant explores density, expose a density knob. If it explores color commitment, expose a color-amount range. Deciding "what's tunable" during planning produces better knobs than retrofitting them onto finished HTML.
-
-**Departure mode.** Each variant anchors to a different **aesthetic direction**, derived from the brand's stated voice and register in PRODUCT.md. Do NOT pick from a fixed catalog of lane categories. The right three directions for this brand are not the same as the right three for another brand, and picking from a list is itself the training-data reflex (the model selects "Swiss-grid, Terminal, Industrial-signage" every time because those are the furthest-from-editorial items in any enumerated list).
-
-Instead, work from the brand:
-
-1. Read PRODUCT.md's Brand Personality words. What physical, spatial, or material experiences would embody those words if design were not involved? (A personality described as "specific, earned, unmistakable" evokes a hand-stamped letter, a numbered print, a watchmaker's loupe. A personality described as "restless, loud, unfiltered" evokes a concert poster, a spray-painted wall, a megaphone.)
-2. From those physical experiences, derive three visual directions that are genuinely different from each other AND from the current surface you're departing.
-3. Avoid the **reflex-reject lanes** in [brand.md](brand.md). Don't trade one monoculture for another. If you find yourself reaching for "Swiss-grid" or "Terminal" or "Industrial-signage" by reflex, you are pattern-matching a catalog in your training data, not reading the brand. Start over from the personality words.
-4. Each direction must be expressible in one concrete sentence that names a real-world referent ("a museum exhibition label system for a contemporary art gallery" not "clean and minimal"). If your sentence contains only adjectives, it's not concrete enough.
-5. **While planning each direction, also name its 2–3 parameter knobs** (per the §7 budget table). The same principle as default mode: decide "what's tunable" during planning, not after writing the HTML. A departure-mode hero with 0 parameters is not "bold creative vision," it's a missed opportunity for the user to fine-tune the direction they pick.
-
-#### Phase D: Squint test
-
-**Default mode squint.** Read each variant's identity sentence and compare to the locked identity from Phase A. If any variant has drifted to a different palette, type voice, or visual rhetoric, it has crossed into departure mode by accident; rework. Then check that each variant commits to a different primary axis. Three "tighter density" variants is failure.
-
-**Departure mode squint.** Two passes, family before sentence:
-
-1. **Family pass.** Label each variant with one design-family word of your own choosing (any concrete noun: *exhibition, storefront, cockpit, recipe-card, playbill, field-manual*). If any two variants share a label, or if the label could apply to the other variants equally well, rework. Do not use a fixed vocabulary list for the labels. *This pass is non-negotiable in departure mode and catches the monoculture failure that the sentence pass misses.*
-2. **Sentence pass.** Write three one-sentence descriptions side by side. If two of them rhyme ("both feature big type" / "both are stacks of sections" / "both center the CTA"), rework the offender.
-
-**When the primary axis is color or theme, forbid the trio from sharing theme + dominant hue.** Two dark-plus-one-dark is not distinct. Aim for three color worlds, not three shades of the same.
-
-**For action-specific invocations**, each variant must vary along the dimension the action names:
-
-- `bolder`: amplify a different dimension per variant (scale / saturation / structural change). Not three "slightly bigger" variants.
-- `quieter`: pull back a different dimension (color / ornament / spacing).
-- `distill`: remove a different class of excess (visual noise / redundant content / nested structure).
-- `polish`: target a different refinement axis (rhythm / hierarchy / micro-details like corner radii, focus states, optical kerning).
-- `typeset`: different type pairing AND different scale ratio each. Not three riffs on one pairing.
-- `colorize`: different hue family each (not shades of one hue). Vary chroma and contrast strategy.
-- `layout`: different structural arrangement (stacked / side-by-side / grid / asymmetric). Not spacing tweaks.
-- `adapt`: different target context per variant (mobile-first / tablet / desktop / print or low-data). Don't make three mobile layouts.
-- `animate`: different motion vocabulary (cascade stagger / clip wipe / scale-and-focus / morph / parallax). Not three staggered fades.
-- `delight`: different flavor of personality (unexpected micro-interaction / typographic surprise / illustrated accent / sonic-or-haptic moment / easter-egg interaction).
-- `overdrive`: different convention broken (scale / structure / motion / input model / state transitions). Skip `overdrive.md`'s "propose and ask" step; live mode is non-interactive.
-
-### 5. Apply the freeform prompt (if present)
-
-`event.freeformPrompt` is the user's ceiling on direction (all variants must honor it), but still explore meaningfully different *interpretations*. The interpretations stay within whichever mode you picked in Phase B.
-
-In **default mode**, the prompt narrows the axes you choose, not the identity. *"Make it feel more confident"* → variant 1 amplifies hierarchy (one element commands the eye), variant 2 commits the existing accent color (Committed strategy on the brand's hue), variant 3 tightens density and removes decorative slack. Three different axes, same brand.
-
-In **departure mode**, the prompt narrows the lanes you draw from, not the families. *"Make it feel like a newspaper front page"* would itself be a departure-mode prompt; honor it but pick three meaningfully different newspaper-adjacent lanes (broadsheet vs. tabloid vs. trade journal), and run the family pass to confirm they don't collapse into one.
-
-When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.
-
-### 6. Write all variants in a single edit
-
-Complete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).
-
-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).
-
-Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:
-
-```html
-<!-- Variants: insert below this line -->
-<style data-impeccable-css="SESSION_ID">
- /* rules matching cssAuthoring.rulePattern */
-</style>
-<div data-impeccable-variant="1">
- <!-- variant 1: full element replacement (single top-level element) -->
-</div>
-<div data-impeccable-variant="2" style="display: none">
- <!-- variant 2: full element replacement -->
-</div>
-<div data-impeccable-variant="3" style="display: none">
- <!-- variant 3: full element replacement -->
-</div>
-```
-
-**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.
-
-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.
-
-One edit, all variants; the browser's MutationObserver picks everything up in one pass.
-
-For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.
-
-**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:
-
-```tsx
-<style data-impeccable-css="SESSION_ID">{`
- @scope ([data-impeccable-variant="1"]) { ... }
- @scope ([data-impeccable-variant="2"]) { ... }
-`}</style>
-<div data-impeccable-variant="1">
- {/* variant 1 */}
-</div>
-<div data-impeccable-variant="2" style={{ display: 'none' }}>
- {/* variant 2 */}
-</div>
-```
-
-The wrap script already gives you a single-rooted JSX wrapper: a `<div data-impeccable-variants="…">` outer element with the marker comments tucked inside. Drop the variants block above into the "Variants: insert below this line" comment and the source stays valid TSX.
-
-### 7. Parameters (composition-sized, 0–4 per variant)
-
-Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement. The browser docks a small panel to the right of the outline with one control per parameter. The user drags/clicks and sees instant feedback: there is zero regeneration cost because the knob toggles a CSS variable or data attribute that the variant's scoped CSS is already authored against.
-
-**What “optional” does not mean.** Parameters are not nice-to-have decoration on large work. The word meant “omit controls that are redundant or cosmetic,” not “default to zero because three variants were enough work.”
-
-**When to add.** As soon as the variant’s scoped CSS has a meaningful continuous or stepped axis: density, color amount, type scale, motion intensity, column weight, and so on. If you can imagine the user muttering “a bit tighter” or “a touch more accent” **without** wanting a full regeneration, wire that axis. **Not** micro-margins or one-off nudges; those are not parameters.
-
-**Freeform (`action` is `impeccable`) bias.** You did not load a sub-command reference, so you must **choose** signature axes yourself. Match the budget table: for a hero or large composition, that means **2–3 axes per variant**, not 1. Prefer knobs that sit on the dimensions where your three variants actually differ (if density varies, expose it as a `steps` knob; if color commitment varies, expose it as a `range`). A hero that ships with **0** params is almost always a mistake, not a judgment call. A hero with exactly **1** param is underweight unless the design is genuinely a fixed-point comparison. Start from the budget table, not from zero.
-
-**Budget scales with the element's visual weight, not token budget.** Knobs need real estate to read as tunable; three sliders on a single control are noise.
-
-- **Leaf / tiny**: a single button, icon, input, bare heading, solitary paragraph: **0 params.**
-- **Small composition**: labeled input, simple card, short callout (≤ ~5 visual children): **0–1** params when one dominant axis is obvious; otherwise **0.**
-- **Medium composition**: section component, nav cluster, dense card, short feature block (6–15 visual children): **target 2**; **1** is acceptable if the block is simple; **0** only when variants are truly fixed points.
-- **Large composition**: hero section, full page region, spread layout, strong internal structure (16+ visual children or multiple sub-sections): **target 2–3**; **up to 4** when several independent axes (e.g. structure `steps` + `density` + one accent) are all authored in scoped CSS.
-
-**When in doubt, ask whether a dial exists before defaulting to zero.** The user can always request more variants, but the point of live mode is instant tuning without another Go. Crowding the panel is bad; **under-shipping** knobs on a dense composition is the more common failure for freeform. Count by **visual** children, not DOM depth; a shallow-but-wide hero is still large.
-
-**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.
-
-**How to declare.** Put a JSON manifest on the variant wrapper:
-
-```html
-<div data-impeccable-variant="1" data-impeccable-params='[
- {"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"},
- {"id":"density","kind":"steps","default":"snug","label":"Density","options":[
- {"value":"airy","label":"Airy"},
- {"value":"snug","label":"Snug"},
- {"value":"packed","label":"Packed"}
- ]},
- {"id":"serif","kind":"toggle","default":false,"label":"Serif display"}
-]'>
- ...variant content...
-</div>
-```
-
-**Three kinds:**
-
-- `range`: smooth slider. Drives a CSS custom property `--p-<id>` on the variant wrapper. Author CSS with `var(--p-color-amount, 0.5)`. Fields: `min`, `max`, `step`, `default` (number), `label`.
-- `steps`: segmented radio. Drives a data attribute `data-p-<id>` on the variant wrapper. Author CSS with `:scope[data-p-density="airy"] .grid { ... }`. Fields: `options` (array of `{value, label}`), `default` (string), `label`.
-- `toggle`: on/off switch. Drives BOTH a CSS var (`--p-<id>: 0|1`) and a data attribute (present when on, absent when off). Use whichever is more convenient. Fields: `default` (boolean), `label`.
-
-**Signature params per action.** For named sub-commands, read that action’s `reference/<action>.md` for one or two **MUST** params (e.g. `layout` → `density`). Those are non-negotiable when the design can express them. **Freeform has no file-level MUST**; the **Freeform (`impeccable`) bias** in this section is the stand-in. If the user’s action is both stylized and sub-command (e.g. `colorize`), the sub-command’s MUST list takes precedence for its axes; still respect the **Hard cap** and add no redundant duplicate knobs.
-
-**Reset on variant switch.** User dials density on v1, flips to v2, v2 starts at v2's declared defaults. Known limitation; preservation across variants may land later.
-
-**On accept**, the browser sends the user's current values in the accept event. `live-accept.mjs` writes them as a sibling comment:
-
-```html
-<!-- impeccable-param-values SESSION_ID: {"color-amount":0.7,"density":"packed"} -->
-```
-
-The carbonize cleanup step (see below) reads that comment and bakes the chosen values into the final CSS. For `steps`/`toggle` attribute selectors: keep only the branch matching the chosen value, drop the others, collapse `:scope[data-p-density="packed"] .grid` to a semantic class rule. For `range` vars: either substitute the literal or keep the var with the chosen value as its new default.
-
-### 8. Signal done
-
-```bash
-node .github/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
-```
-
-`RELATIVE_PATH` is relative to project root (`public/index.html`, `src/App.tsx`, etc.); the browser fetches source directly if the dev server lacks HMR.
-
-Then run `live-poll.mjs` again immediately.
-
-### Aborting an in-flight session
-
-If wrap or generation fails after the browser has flipped to GENERATING (e.g. wrap landed on the wrong source branch and you've already reverted it, or generation hit an unrecoverable error), tell the **browser** so its bar resets to PICKING:
-
-```bash
-node .github/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID error "Short reason"
-```
-
-Don't run `live-accept --discard` for this; that's a pure file mutator, the browser doesn't see it, and the bar gets stuck on the GENERATING dots forever (the user has to refresh). `--discard` is only correct when the **browser** initiated the discard (user clicked ✕ during CYCLING) and the agent is just running source-side cleanup the browser already triggered.
-
-## Handle fallback
-
-When wrap returns `fallback: "agent-driven"`, the deterministic flow doesn't apply. Pick up here.
-
-The goal is the same: give the user three variants to choose from AND persist the accepted one in a place the next build won't wipe. The difference is that you have to pick the right source file yourself.
-
-### Step 1: Identify where the element actually lives
-
-Use the error payload:
-
-- `element_not_in_source` with `generatedMatch: "public/docs/foo.html"`: the served HTML is generated. Find the generator (grep for writers of that path, e.g. `scripts/build-sub-pages.js`, an Astro/Next template) and locate the template or partial that emits this element.
-- `element_not_found`: the element is runtime-injected. Look for the component that renders it (React/Vue/Svelte), the JS that assembles it, or the data source that feeds it.
-- `file_is_generated` with `file: "..."`: user pointed at a generated file explicitly. Same resolution as `element_not_in_source`.
-
-Read the candidate source until you're confident where a change to the element would belong. If the change is purely visual, that source might be a shared stylesheet, not the template.
-
-### Step 2: Show three variants in the DOM for preview
-
-The browser bar is waiting for variants. Even without a wrapper in source, you still need to show something:
-
-1. Manually write the wrapper scaffold into the **served** file (the one the browser actually loaded). Use the same structure `live-wrap.mjs` produces; `<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents">…</div><!-- end -->`.
-2. Insert your three variant divs inside it, same shape as the deterministic path.
-3. Signal done with `--reply EVENT_ID done --file <served file>`. The browser's no-HMR fallback will fetch and inject.
-
-This served-file edit is **temporary**: next regen wipes it, and that's fine. The real work happens on accept.
-
-### Step 3: On accept, write to true source
-
-When the accept event arrives (`_acceptResult.handled` will usually be `false` here because accept also refuses to persist into generated files; see Handle accept for the carbonize branch), extract the accepted variant's content and write it into the source you identified in Step 1:
-
-- Structural change → edit the template / component source.
-- Visual-only change → add or update rules in the appropriate stylesheet; remove the inline `<style>` scope.
-- Dynamic from data → update the data source or the render logic.
-
-Then remove the temporary wrapper from the served file if it's still there.
-
-### Step 4: On discard, clean up the served file
-
-Remove the wrapper you inserted in Step 2. Nothing else to do.
-
-## Handle `accept`
-
-Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.
-
-- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.
-- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.
-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.
-- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.
-- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.
-
-### Required after accept (carbonize)
-
-When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.
-
-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.
-
-1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.
-2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).
-3. **Bake in parameter values while rewriting selectors.** For `@scope ([data-impeccable-variant="N"])` wrappers: retarget to real, semantic classes on the accepted HTML (`.why-visual--v2 .v2-label { … }`). For `:scope[data-p-<id>="VALUE"]` selectors: keep only the branch matching the chosen value from the param-values comment; drop the others (they're dead after accept). For `var(--p-<id>, DEFAULT)` in the CSS: either substitute the literal value, or if the param is still useful as a knob going forward, leave the var and update its initial declaration to the chosen value.
-4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; those are live-mode plumbing, not source.
-5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.
-
-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.
-
-A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.
-
-## Handle `discard`
-
-Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.
-
-## Handle `prefetch`
-
-Event: `{pageUrl}`. The browser fires this the first time the user selects an element on a given route, as a latency shortcut; it signals the user is likely about to Go on a page you haven't read yet.
-
-Resolve `pageUrl` to the underlying file:
-
-- Root `/` → the `pageFile` returned by `live.mjs` (usually `public/index.html` or equivalent).
-- Sub-routes (e.g. `/docs`, `/docs/live`) → the generated or source file for that route. Use your knowledge of the project layout (multi-page static sites often resolve `/foo` → `public/foo/index.html`; SPAs may map all routes to a single entry).
-
-Read the file into context, then poll again. No `--reply`: this is speculative pre-work; Go will come later. If you can't confidently resolve the route to a file, skip and poll again.
-
-Dedupe is the browser's job (one prefetch per unique pathname per session); trust it. If the same file shows up twice from different routes mapping to the same file, the second Read is cached anyway.
-
-## Exit
-
-The user can stop live mode by:
-- Saying "stop live mode" / "exit live" in chat
-- Closing the browser tab (SSE drops, poll returns `exit` after 8s)
-- The browser's exit button
-
-When the poll returns `exit`, proceed to cleanup. If the poll is still running as a background task, kill it first.
-
-## Cleanup
-
-```bash
-node .github/skills/impeccable/scripts/live-server.mjs stop
-```
-
-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.
-
-Then:
-- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).
-- Remove any leftover carbonize blocks (search for `impeccable-carbonize-start` markers).
-
-## First-time setup (config missing or invalid)
-
-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.
-
-Schema:
-
-```json
-{
- "files": ["<path-or-glob>", "<path-or-glob>", ...],
- "exclude": ["<optional-glob>", ...],
- "insertBefore": "</body>",
- "commentSyntax": "html",
- "cspChecked": true
-}
-```
-
-`files` is the inject target; **the HTML files the browser actually loads**, not necessarily source. Each entry is either a literal path (`"public/index.html"`) or a glob pattern (`"public/**/*.html"`). Tracked or generated doesn't matter here; wrap has its own generated-file guard and routes accepts through the fallback flow.
-
-`exclude` (optional) is a list of glob patterns matching files to skip, even if a `files` glob would have included them. Use for email templates, demo fixtures, or any HTML that isn't a live page.
-
-`cspChecked` tracks whether the CSP detection step below has already run. Absent on first setup; set to `true` after CSP is checked (whether patched, declined, or not needed).
-
-**Hard-excluded paths (cannot be overridden).** `**/node_modules/**` and `**/.git/**` are never matched regardless of what the user writes. These are vendor/metadata directories and injecting into them would silently instrument third-party code.
-
-**Glob syntax.** `**` matches any number of path segments (including zero), `*` matches any characters except `/`, `?` matches a single character except `/`. Paths are always relative to the project root with forward slashes.
-
-| Framework | `files` | `insertBefore` | `commentSyntax` |
-|-----------|---------|----------------|-----------------|
-| SPA with single shell (Vite / React / Plain HTML) | `["index.html"]` | `</body>` | `html` |
-| Next.js (App Router) | `["app/layout.tsx"]` | `</body>` | `jsx` |
-| Next.js (Pages) | `["pages/_document.tsx"]` | `</body>` | `jsx` |
-| Nuxt | `["app.vue"]` | `</body>` | `html` |
-| Svelte / SvelteKit | `["src/app.html"]` | `</body>` | `html` |
-| Astro | `[" <root layout .astro>"]` | `</body>` | `html` |
-| Multi-page (separate HTML per route) | `["public/**/*.html"]`: a glob covering the served directory | `</body>` | `html` |
-
-Pick an anchor that exists in every file (`</body>` almost always works). Use `insertAfter` if the anchor should match **after** a specific line.
-
-For multi-page sites, **prefer a glob over a literal file list**. New pages added later are picked up automatically on the next `live-inject.mjs` run; no config maintenance needed.
-
-For multi-page sites whose pages are *rebuilt* by a generator (Astro, static-site generators, custom scripts like `build-sub-pages.js`), the inject survives only until the next regeneration. Re-run `live.mjs` after each build. Accept is unaffected; it writes to true source via the fallback flow.
-
-### Drift-heal warning
-
-On every `live.mjs` boot, after inject, the project is scanned for HTML files under common page-source roots (`public/`, `src/`, `app/`, `pages/`). If any exist that aren't covered by the resolved `files` list, the output includes a `configDrift` field:
-
-```json
-{
- "ok": true,
- "serverPort": 8400,
- "pageFiles": [ "..." ],
- "configDrift": {
- "orphans": ["public/new-section/index.html", "public/docs/new-command.html"],
- "orphanCount": 2,
- "hint": "2 HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like \"public/**/*.html\"."
- }
-}
-```
-
-When `configDrift` is present, surface it to the user once per session before entering the poll loop:
-
-> Noticed N HTML file(s) in the project that aren't in `config.files`:
->
-> - `public/new-section/index.html`
-> - `public/docs/new-command.html`
->
-> Add them, or switch `files` to a glob like `["public/**/*.html"]` and let it track new pages automatically?
-
-Don't auto-update the config; let the user decide. `configDrift` is `null` when there's no drift.
-
-### CSP detection (first-time only)
-
-If `config.cspChecked === true`, skip this entire section. You already asked this user once; the answer sticks.
-
-Otherwise, run the detection helper:
-
-```bash
-node .github/skills/impeccable/scripts/detect-csp.mjs
-```
-
-Output: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.
-
-- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.
-- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:
- - Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)
- - SvelteKit `kit.csp.directives`
- - Nuxt `nuxt-security` module's `contentSecurityPolicy`
-- **`append-string`**: CSP written as a literal value string. Auto-patchable. See *append-string* below. Covers:
- - Inline `next.config.*` `headers()` with a CSP literal
- - Nuxt `routeRules` / `nitro.routeRules` headers
-- **`middleware`** or **`meta-tag`**: rarer. Detected but not auto-patched in v1. Show the user the detected files and ask them to add `http://localhost:8400` to `script-src` and `connect-src` manually, then mark `cspChecked: true` and proceed.
-
-#### Consent prompt template
-
-Use this phrasing so the experience is consistent across agents:
-
-> **CSP patch needed.** I detected a Content Security Policy in your project that blocks `http://localhost:8400`: the live picker won't load without an allowance. Here's the change I'd make:
->
-> ```diff
-> [file: <patchTarget>]
-> [exact diff, 2–5 lines]
-> ```
->
-> It's guarded by `NODE_ENV === "development"` so the extra entry only appears in dev and never reaches production. You can remove it any time by reverting this file. Apply? [y/n]
-
-On "no": skip the patch, mention live won't work until the user adds the allowance manually, still write `cspChecked: true` (the question's been asked).
-
-On "yes": apply the Shape-specific patch below, then write `cspChecked: true`.
-
-#### append-arrays
-
-CSP expressed as structured directive arrays. Patch mechanism: declare a dev-only array, spread it into the script-src and connect-src arrays.
-
-**Declare near the top of the file that holds the CSP arrays:**
-
-```ts
-// Dev-only allowance so impeccable live mode can load. Guarded by NODE_ENV.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? ["http://localhost:8400"] : [];
-```
-
-**Append `...__impeccableLiveDev` to the script-src and connect-src directive arrays.** Per-framework specifics:
-
-- **Next.js + monorepo helper**: edit the *app's* `next.config.*` (not the shared helper), appending to `additionalScriptSrc` and `additionalConnectSrc` passed into `createBaseNextConfig` (or equivalent). Keeps the shared package clean.
-- **SvelteKit**: edit `svelte.config.js`, appending to `kit.csp.directives['script-src']` and `kit.csp.directives['connect-src']`.
-- **Nuxt + nuxt-security**: edit `nuxt.config.*`, appending to `security.headers.contentSecurityPolicy['script-src']` and `['connect-src']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-turborepo/expected-after-patch.ts` (Next.js)
-- `tests/framework-fixtures/sveltekit-csp/expected-after-patch.js` (SvelteKit)
-
-Idempotency: if `__impeccableLiveDev` already exists in the file, the patch is already applied; skip asking and just mark `cspChecked: true`.
-
-#### append-string
-
-CSP built as a literal value string. Two-point patch: declare a dev-only string near the top, interpolate it into the CSP at the `script-src` and `connect-src` directives.
-
-```ts
-// Dev-only allowance so impeccable live mode can load.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? " http://localhost:8400" : "";
-```
-
-Then in the CSP value string:
-- `script-src 'self' 'unsafe-inline'` → `` `script-src 'self' 'unsafe-inline'${__impeccableLiveDev}` ``
-- `connect-src 'self'` → `` `connect-src 'self'${__impeccableLiveDev}` ``
-
-(Leading space on the dev string so it concatenates cleanly into the existing value. Convert the literal CSP directives into template strings as part of the edit if they aren't already.)
-
-Per-framework specifics:
-- **Next.js inline `headers()`**: edit `next.config.*`, splicing the variable into the CSP value.
-- **Nuxt `routeRules`**: edit `nuxt.config.*`, splicing into the CSP in `routeRules['/**'].headers['Content-Security-Policy']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-inline-csp/expected-after-patch.js` (Next.js)
-- `tests/framework-fixtures/nuxt-csp/expected-after-patch.ts` (Nuxt)
-
-### Troubleshooting
-
-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.
-
-Then re-run `live.mjs`.
@@ -1,109 +0,0 @@
-# Motion Design
-
-## Duration: The 100/300/500 Rule
-
-Timing matters more than easing. These durations feel right for most UI:
-
-| Duration | Use Case | Examples |
-|----------|----------|----------|
-| **100-150ms** | Instant feedback | Button press, toggle, color change |
-| **200-300ms** | State changes | Menu open, tooltip, hover states |
-| **300-500ms** | Layout changes | Accordion, modal, drawer |
-| **500-800ms** | Entrance animations | Page load, hero reveals |
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-## Easing: Pick the Right Curve
-
-**Don't use `ease`.** It's a compromise that's rarely optimal. Instead:
-
-| Curve | Use For | CSS |
-|-------|---------|-----|
-| **ease-out** | Elements entering | `cubic-bezier(0.16, 1, 0.3, 1)` |
-| **ease-in** | Elements leaving | `cubic-bezier(0.7, 0, 0.84, 0)` |
-| **ease-in-out** | State toggles (there → back) | `cubic-bezier(0.65, 0, 0.35, 1)` |
-
-**For micro-interactions, use exponential curves.** They feel natural because they mimic real physics (friction, deceleration):
-
-```css
-/* Quart out - smooth, refined (recommended default) */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1);
-
-/* Quint out - slightly more dramatic */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1);
-
-/* Expo out - snappy, confident */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1);
-```
-
-**Avoid bounce and elastic curves.** They were trendy in 2015 but now feel tacky and amateurish. Real objects don't bounce when they stop; they decelerate smoothly. Overshoot effects draw attention to the animation itself rather than the content.
-
-## Premium Motion Materials
-
-Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties: blur reveals, backdrop-filter panels, saturation or brightness shifts, shadow bloom, SVG filters, masks, clip paths, gradient-position movement, and variable font or shader-driven effects.
-
-Use the right material for the effect:
-
-- **Transform / opacity**: movement, press feedback, simple reveals, list choreography.
-- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances, atmospheric transitions.
-- **Clip path / masks**: wipes, reveals, editorial cropping, product-like transitions.
-- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state.
-- **Grid-template rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly.
-
-The hard rule is not "transform and opacity only." The hard rule is: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify in-browser that the result is smooth on the target viewports. If blur/filter makes the interaction feel significantly more premium and remains smooth, use it.
-
-## Staggered Animations
-
-Use CSS custom properties for cleaner stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"` on each item. **Cap total stagger time**: 10 items at 50ms = 500ms total. For many items, reduce per-item delay or cap staggered count.
-
-## Reduced Motion
-
-This is not optional. Vestibular disorders affect ~35% of adults over 40.
-
-```css
-/* Define animations normally */
-.card {
- animation: slide-up 500ms ease-out;
-}
-
-/* Provide alternative for reduced motion */
-@media (prefers-reduced-motion: reduce) {
- .card {
- animation: fade-in 200ms ease-out; /* Crossfade instead of motion */
- }
-}
-
-/* Or disable entirely */
-@media (prefers-reduced-motion: reduce) {
- *, *::before, *::after {
- animation-duration: 0.01ms !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**What to preserve**: Functional animations like progress bars, loading spinners (slowed down), and focus indicators should still work, just without spatial movement.
-
-## Perceived Performance
-
-**Nobody cares how fast your site is, just how fast it feels.** Perception can be as effective as actual performance.
-
-**The 80ms threshold**: Our brains buffer sensory input for ~80ms to synchronize perception. Anything under 80ms feels instant and simultaneous. This is your target for micro-interactions.
-
-**Active vs passive time**: Passive waiting (staring at a spinner) feels longer than active engagement. Strategies to shift the balance:
-
-- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening.
-- **Early completion**: Show content progressively, don't wait for everything. Video buffering, progressive images, streaming HTML.
-- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Instagram likes work offline; the UI updates instantly, syncs later. Use for low-stakes actions; avoid for payments or destructive operations.
-
-**Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances, but ease-in toward a task's end compresses perceived time.
-
-**Caution**: Too-fast responses can decrease perceived value. Users may distrust instant results for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
-
-## Performance
-
-Don't use `will-change` preemptively, only when animation is imminent (`:hover`, `.animating`). For scroll-triggered animations, use Intersection Observer instead of scroll events; unobserve after animating once. Create motion tokens for consistency (durations, easings, common transitions).
-
----
-
-**Avoid**: Animating everything (animation fatigue is real). Using >500ms for UI feedback. Ignoring `prefers-reduced-motion`. Using animation to hide slow loading.
@@ -1,234 +0,0 @@
-> **Additional context needed**: the "aha moment" you want users to reach, and users' experience level.
-
-Get users to first value as fast as possible. Onboarding's job is not to teach the product. Its job is to get people to the moment that proves the product is worth their time.
-
-## Assess Onboarding Needs
-
-Understand what users need to learn and why:
-
-1. **Identify the challenge**:
- - What are users trying to accomplish?
- - What's confusing or unclear about current experience?
- - Where do users get stuck or drop off?
- - What's the "aha moment" we want users to reach?
-
-2. **Understand the users**:
- - What's their experience level? (Beginners, power users, mixed?)
- - What's their motivation? (Excited and exploring? Required by work?)
- - What's their time commitment? (5 minutes? 30 minutes?)
- - What alternatives do they know? (Coming from competitor? New to category?)
-
-3. **Define success**:
- - What's the minimum users need to learn to be successful?
- - What's the key action we want them to take? (First project? First invite?)
- - How do we know onboarding worked? (Completion rate? Time to value?)
-
-**CRITICAL**: Onboarding should get users to value as quickly as possible, not teach everything possible.
-
-## Onboarding Principles
-
-Follow these core principles:
-
-### Show, Don't Tell
-- Demonstrate with working examples, not just descriptions
-- Provide real functionality in onboarding, not separate tutorial mode
-- Use progressive disclosure, teach one thing at a time
-
-### Make It Optional (When Possible)
-- Let experienced users skip onboarding
-- Don't block access to product
-- Provide "Skip" or "I'll explore on my own" options
-
-### Time to Value
-- Get users to their "aha moment" ASAP
-- Front-load most important concepts
-- Teach 20% that delivers 80% of value
-- Save advanced features for contextual discovery
-
-### Context Over Ceremony
-- Teach features when users need them, not upfront
-- Empty states are onboarding opportunities
-- Tooltips and hints at point of use
-
-### Respect User Intelligence
-- Don't patronize or over-explain
-- Be concise and clear
-- Assume users can figure out standard patterns
-
-## Design Onboarding Experiences
-
-Create appropriate onboarding for the context:
-
-### Initial Product Onboarding
-
-**Welcome Screen**:
-- Clear value proposition (what is this product?)
-- What users will learn/accomplish
-- Time estimate (honest about commitment)
-- Option to skip (for experienced users)
-
-**Account Setup**:
-- Minimal required information (collect more later)
-- Explain why you're asking for each piece of information
-- Smart defaults where possible
-- Social login when appropriate
-
-**Core Concept Introduction**:
-- Introduce 1-3 core concepts (not everything)
-- Use simple language and examples
-- Interactive when possible (do, don't just read)
-- Progress indication (step 1 of 3)
-
-**First Success**:
-- Guide users to accomplish something real
-- Pre-populated examples or templates
-- Celebrate completion (but don't overdo it)
-- Clear next steps
-
-### Feature Discovery & Adoption
-
-**Empty States**:
-Instead of blank space, show:
-- What will appear here (description + screenshot/illustration)
-- Why it's valuable
-- Clear CTA to create first item
-- Example or template option
-
-Example:
-```
-No projects yet
-Projects help you organize your work and collaborate with your team.
-[Create your first project] or [Start from template]
-```
-
-**Contextual Tooltips**:
-- Appear at relevant moment (first time user sees feature)
-- Point directly at relevant UI element
-- Brief explanation + benefit
-- Dismissable (with "Don't show again" option)
-- Optional "Learn more" link
-
-**Feature Announcements**:
-- Highlight new features when they're released
-- Show what's new and why it matters
-- Let users try immediately
-- Dismissable
-
-**Progressive Onboarding**:
-- Teach features when users encounter them
-- Badges or indicators on new/unused features
-- Unlock complexity gradually (don't show all options immediately)
-
-### Guided Tours & Walkthroughs
-
-**When to use**:
-- Complex interfaces with many features
-- Significant changes to existing product
-- Industry-specific tools needing domain knowledge
-
-**How to design**:
-- Spotlight specific UI elements (dim rest of page)
-- Keep steps short (3-7 steps max per tour)
-- Allow users to click through tour freely
-- Include "Skip tour" option
-- Make replayable (help menu)
-
-**Best practices**:
-- Interactive over passive (let users click real buttons)
-- Focus on workflow, not features ("Create a project" not "This is the project button")
-- Provide sample data so actions work
-
-### Interactive Tutorials
-
-**When to use**:
-- Users need hands-on practice
-- Concepts are complex or unfamiliar
-- High stakes (better to practice in safe environment)
-
-**How to design**:
-- Sandbox environment with sample data
-- Clear objectives ("Create a chart showing sales by region")
-- Step-by-step guidance
-- Validation (confirm they did it right)
-- Graduation moment (you're ready!)
-
-### Documentation & Help
-
-**In-product help**:
-- Contextual help links throughout interface
-- Keyboard shortcut reference
-- Search-able help center
-- Video tutorials for complex workflows
-
-**Help patterns**:
-- `?` icon near complex features
-- "Learn more" links in tooltips
-- Keyboard shortcut hints (`⌘K` shown on search box)
-
-## Empty State Design
-
-Every empty state needs:
-
-### What Will Be Here
-"Your recent projects will appear here"
-
-### Why It Matters
-"Projects help you organize your work and collaborate with your team"
-
-### How to Get Started
-[Create project] or [Import from template]
-
-### Visual Interest
-Illustration or icon (not just text on blank page)
-
-### Contextual Help
-"Need help getting started? [Watch 2-min tutorial]"
-
-**Empty state types**:
-- **First use**: Never used this feature (emphasize value, provide template)
-- **User cleared**: Intentionally deleted everything (light touch, easy to recreate)
-- **No results**: Search or filter returned nothing (suggest different query, clear filters)
-- **No permissions**: Can't access (explain why, how to get access)
-- **Error state**: Failed to load (explain what happened, retry option)
-
-## Implementation Patterns
-
-### Technical approaches:
-
-**Tooltip libraries**: Tippy.js, Popper.js
-**Tour libraries**: Intro.js, Shepherd.js, React Joyride
-**Modal patterns**: Focus trap, backdrop, ESC to close
-**Progress tracking**: LocalStorage for "seen" states
-**Analytics**: Track completion, drop-off points
-
-**Storage patterns**:
-```javascript
-// Track which onboarding steps user has seen
-localStorage.setItem('onboarding-completed', 'true');
-localStorage.setItem('feature-tooltip-seen-reports', 'true');
-```
-
-**IMPORTANT**: Don't show same onboarding twice (annoying). Track completion and respect dismissals.
-
-**NEVER**:
-- Force users through long onboarding before they can use product
-- Patronize users with obvious explanations
-- Show same tooltip repeatedly (respect dismissals)
-- Block all UI during tour (let users explore)
-- Create separate tutorial mode disconnected from real product
-- Overwhelm with information upfront (progressive disclosure!)
-- Hide "Skip" or make it hard to find
-- Forget about returning users (don't show initial onboarding again)
-
-## Verify Onboarding Quality
-
-Test with real users:
-
-- **Time to completion**: Can users complete onboarding quickly?
-- **Comprehension**: Do users understand after completing?
-- **Action**: Do users take desired next step?
-- **Skip rate**: Are too many users skipping? (Maybe it's too long or not valuable)
-- **Completion rate**: Are users completing? (If low, simplify)
-- **Time to value**: How long until users get first value?
-
-When users hit the aha moment fast and don't drop off, hand off to `/impeccable polish` for the final pass.
@@ -1,258 +0,0 @@
-Performance is a feature. Identify the actual bottleneck for THIS interface, fix it, then measure. Don't optimize what isn't slow.
-
-## Assess Performance Issues
-
-Understand current performance and identify problems:
-
-1. **Measure current state**:
- - **Core Web Vitals**: LCP, FID/INP, CLS scores
- - **Load time**: Time to interactive, first contentful paint
- - **Bundle size**: JavaScript, CSS, image sizes
- - **Runtime performance**: Frame rate, memory usage, CPU usage
- - **Network**: Request count, payload sizes, waterfall
-
-2. **Identify bottlenecks**:
- - What's slow? (Initial load? Interactions? Animations?)
- - What's causing it? (Large images? Expensive JavaScript? Layout thrashing?)
- - How bad is it? (Perceivable? Annoying? Blocking?)
- - Who's affected? (All users? Mobile only? Slow connections?)
-
-**CRITICAL**: Measure before and after. Premature optimization wastes time. Optimize what actually matters.
-
-## Optimization Strategy
-
-Create systematic improvement plan:
-
-### Loading Performance
-
-**Optimize Images**:
-- Use modern formats (WebP, AVIF)
-- Proper sizing (don't load 3000px image for 300px display)
-- Lazy loading for below-fold images
-- Responsive images (`srcset`, `picture` element)
-- Compress images (80-85% quality is usually imperceptible)
-- Use CDN for faster delivery
-
-```html
-<img
- src="hero.webp"
- srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
- sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
- loading="lazy"
- alt="Hero image"
-/>
-```
-
-**Reduce JavaScript Bundle**:
-- Code splitting (route-based, component-based)
-- Tree shaking (remove unused code)
-- Remove unused dependencies
-- Lazy load non-critical code
-- Use dynamic imports for large components
-
-```javascript
-// Lazy load heavy component
-const HeavyChart = lazy(() => import('./HeavyChart'));
-```
-
-**Optimize CSS**:
-- Remove unused CSS
-- Critical CSS inline, rest async
-- Minimize CSS files
-- Use CSS containment for independent regions
-
-**Optimize Fonts**:
-- Use `font-display: swap` or `optional`
-- Subset fonts (only characters you need)
-- Preload critical fonts
-- Use system fonts when appropriate
-- Limit font weights loaded
-
-```css
-@font-face {
- font-family: 'CustomFont';
- src: url('/fonts/custom.woff2') format('woff2');
- font-display: swap; /* Show fallback immediately */
- unicode-range: U+0020-007F; /* Basic Latin only */
-}
-```
-
-**Optimize Loading Strategy**:
-- Critical resources first (async/defer non-critical)
-- Preload critical assets
-- Prefetch likely next pages
-- Service worker for offline/caching
-- HTTP/2 or HTTP/3 for multiplexing
-
-### Rendering Performance
-
-**Avoid Layout Thrashing**:
-```javascript
-// ❌ Bad: Alternating reads and writes (causes reflows)
-elements.forEach(el => {
- const height = el.offsetHeight; // Read (forces layout)
- el.style.height = height * 2; // Write
-});
-
-// ✅ Good: Batch reads, then batch writes
-const heights = elements.map(el => el.offsetHeight); // All reads
-elements.forEach((el, i) => {
- el.style.height = heights[i] * 2; // All writes
-});
-```
-
-**Optimize Rendering**:
-- Use CSS `contain` property for independent regions
-- Minimize DOM depth (flatter is faster)
-- Reduce DOM size (fewer elements)
-- Use `content-visibility: auto` for long lists
-- Virtual scrolling for very long lists (react-window, react-virtualized)
-
-**Reduce Paint & Composite**:
-- Use `transform` and `opacity` for reliable movement, but allow blur, filters, masks, clip paths, shadows, and color shifts when they create meaningful polish
-- Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- Use `will-change` sparingly for known expensive operations
-- Bound expensive paint areas for blur/filter/shadow effects (smaller and isolated is faster)
-
-### Animation Performance
-
-**GPU Acceleration**:
-```css
-/* ✅ GPU-accelerated (fast) */
-.animated {
- transform: translateX(100px);
- opacity: 0.5;
-}
-
-/* ❌ CPU-bound (slow) */
-.animated {
- left: 100px;
- width: 300px;
-}
-```
-
-**Smooth 60fps**:
-- Target 16ms per frame (60fps)
-- Use `requestAnimationFrame` for JS animations
-- Debounce/throttle scroll handlers
-- Use CSS animations when possible
-- Avoid long-running JavaScript during animations
-
-**Intersection Observer**:
-```javascript
-// Efficiently detect when elements enter viewport
-const observer = new IntersectionObserver((entries) => {
- entries.forEach(entry => {
- if (entry.isIntersecting) {
- // Element is visible, lazy load or animate
- }
- });
-});
-```
-
-### React/Framework Optimization
-
-**React-specific**:
-- Use `memo()` for expensive components
-- `useMemo()` and `useCallback()` for expensive computations
-- Virtualize long lists
-- Code split routes
-- Avoid inline function creation in render
-- Use React DevTools Profiler
-
-**Framework-agnostic**:
-- Minimize re-renders
-- Debounce expensive operations
-- Memoize computed values
-- Lazy load routes and components
-
-### Network Optimization
-
-**Reduce Requests**:
-- Combine small files
-- Use SVG sprites for icons
-- Inline small critical assets
-- Remove unused third-party scripts
-
-**Optimize APIs**:
-- Use pagination (don't load everything)
-- GraphQL to request only needed fields
-- Response compression (gzip, brotli)
-- HTTP caching headers
-- CDN for static assets
-
-**Optimize for Slow Connections**:
-- Adaptive loading based on connection (navigator.connection)
-- Optimistic UI updates
-- Request prioritization
-- Progressive enhancement
-
-## Core Web Vitals Optimization
-
-### Largest Contentful Paint (LCP < 2.5s)
-- Optimize hero images
-- Inline critical CSS
-- Preload key resources
-- Use CDN
-- Server-side rendering
-
-### First Input Delay (FID < 100ms) / INP (< 200ms)
-- Break up long tasks
-- Defer non-critical JavaScript
-- Use web workers for heavy computation
-- Reduce JavaScript execution time
-
-### Cumulative Layout Shift (CLS < 0.1)
-- Set dimensions on images and videos
-- Don't inject content above existing content
-- Use `aspect-ratio` CSS property
-- Reserve space for ads/embeds
-- Avoid animations that cause layout shifts
-
-```css
-/* Reserve space for image */
-.image-container {
- aspect-ratio: 16 / 9;
-}
-```
-
-## Performance Monitoring
-
-**Tools to use**:
-- Chrome DevTools (Lighthouse, Performance panel)
-- WebPageTest
-- Core Web Vitals (Chrome UX Report)
-- Bundle analyzers (webpack-bundle-analyzer)
-- Performance monitoring (Sentry, DataDog, New Relic)
-
-**Key metrics**:
-- LCP, FID/INP, CLS (Core Web Vitals)
-- Time to Interactive (TTI)
-- First Contentful Paint (FCP)
-- Total Blocking Time (TBT)
-- Bundle size
-- Request count
-
-**IMPORTANT**: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.
-
-**NEVER**:
-- Optimize without measuring (premature optimization)
-- Sacrifice accessibility for performance
-- Break functionality while optimizing
-- Use `will-change` everywhere (creates new layers, uses memory)
-- Lazy load above-fold content
-- Optimize micro-optimizations while ignoring major issues (optimize the biggest bottleneck first)
-- Forget about mobile performance (often slower devices, slower connections)
-
-## Verify Improvements
-
-Test that optimizations worked:
-
-- **Before/after metrics**: Compare Lighthouse scores
-- **Real user monitoring**: Track improvements for real users
-- **Different devices**: Test on low-end Android, not just flagship iPhone
-- **Slow connections**: Throttle to 3G, test experience
-- **No regressions**: Ensure functionality still works
-- **User perception**: Does it *feel* faster?
-
-When the user-facing numbers move, hand off to `/impeccable polish` for the final pass.
@@ -1,130 +0,0 @@
-Start your response with:
-
-```
-──────────── ⚡ OVERDRIVE ─────────────
-》》》 Entering overdrive mode...
-```
-
-Push an interface past conventional limits. This isn't just about visual effects. It's about using the full power of the browser to make any part of an interface feel extraordinary: a table that handles a million rows, a dialog that morphs from its trigger, a form that validates in real-time with streaming feedback, a page transition that feels cinematic.
-
-**EXTRA IMPORTANT FOR THIS COMMAND**: Context determines what "extraordinary" means. A particle system on a creative portfolio is impressive. The same particle system on a settings page is embarrassing. But a settings page with instant optimistic saves and animated state transitions? That's extraordinary too. Understand the project's personality and goals before deciding what's appropriate.
-
-### Propose Before Building
-
-This command has the highest potential to misfire. Do NOT jump straight into implementation. You MUST:
-
-1. **Think through 2-3 different directions**: consider different techniques, levels of ambition, and aesthetic approaches. For each direction, briefly describe what the result would look and feel like.
-2. **ask the user directly to clarify what you cannot infer.** to present these directions and get the user's pick before writing any code. Explain trade-offs (browser support, performance cost, complexity).
-3. Only proceed with the direction the user confirms.
-
-Skipping this step risks building something embarrassing that needs to be thrown away.
-
-### Iterate with Browser Automation
-
-Technically ambitious effects almost never work on the first try. You MUST actively use browser automation tools to preview your work, visually verify the result, and iterate. Do not assume the effect looks right, check it. Expect multiple rounds of refinement. The gap between "technically works" and "looks extraordinary" is closed through visual iteration, not code alone.
-
----
-
-## Assess What "Extraordinary" Means Here
-
-The right kind of technical ambition depends entirely on what you're working with. Before choosing a technique, ask: **what would make a user of THIS specific interface say "wow, that's nice"?**
-
-### For visual/marketing surfaces
-Pages, hero sections, landing pages, portfolios: the "wow" is often sensory: a scroll-driven reveal, a shader background, a cinematic page transition, generative art that responds to the cursor.
-
-### For functional UI
-Tables, forms, dialogs, navigation: the "wow" is in how it FEELS: a dialog that morphs from the button that triggered it via View Transitions, a data table that renders 100k rows at 60fps via virtual scrolling, a form with streaming validation that feels instant, drag-and-drop with spring physics.
-
-### For performance-critical UI
-The "wow" is invisible but felt: a search that filters 50k items without a flicker, a complex form that never blocks the main thread, an image editor that processes in near-real-time. The interface just never hesitates.
-
-### For data-heavy interfaces
-Charts and dashboards: the "wow" is in fluidity: GPU-accelerated rendering via Canvas/WebGL for massive datasets, animated transitions between data states, force-directed graph layouts that settle naturally.
-
-**The common thread**: something about the implementation goes beyond what users expect from a web interface. The technique serves the experience, not the other way around.
-
-## The Toolkit
-
-Organized by what you're trying to achieve, not by technology name.
-
-### Make transitions feel cinematic
-- **View Transitions API** (same-document: all browsers; cross-document: no Firefox): shared element morphing between states. A list item expanding into a detail page. A button morphing into a dialog. This is the closest thing to native FLIP animations.
-- **`@starting-style`** (all browsers): animate elements from `display: none` to visible with CSS only, including entry keyframes
-- **Spring physics**: natural motion with mass, tension, and damping instead of cubic-bezier. Libraries: motion (formerly Framer Motion), GSAP, or roll your own spring solver.
-
-### Tie animation to scroll position
-- **Scroll-driven animations** (`animation-timeline: scroll()`): CSS-only, no JS. Parallax, progress bars, reveal sequences all driven by scroll position. (Chrome/Edge/Safari; Firefox: flag only; always provide a static fallback)
-
-### Render beyond CSS
-- **WebGL** (all browsers): shader effects, post-processing, particle systems. Libraries: Three.js, OGL (lightweight), regl. Use for effects CSS can't express.
-- **WebGPU** (Chrome/Edge; Safari partial; Firefox: flag only): next-gen GPU compute. More powerful than WebGL but limited browser support. Always fall back to WebGL2.
-- **Canvas 2D / OffscreenCanvas**: custom rendering, pixel manipulation, or moving heavy rendering off the main thread entirely via Web Workers + OffscreenCanvas.
-- **SVG filter chains**: displacement maps, turbulence, morphology for organic distortion effects. CSS-animatable.
-
-### Make data feel alive
-- **Virtual scrolling**: render only visible rows for tables/lists with tens of thousands of items. No library required for simple cases; TanStack Virtual for complex ones.
-- **GPU-accelerated charts**: Canvas or WebGL-rendered data visualization for datasets too large for SVG/DOM. Libraries: deck.gl, regl-based custom renderers.
-- **Animated data transitions**: morph between chart states rather than replacing. D3's `transition()` or View Transitions for DOM-based charts.
-
-### Animate complex properties
-- **`@property`** (all browsers): register custom CSS properties with types, enabling animation of gradients, colors, and complex values that CSS can't normally interpolate.
-- **Web Animations API** (all browsers): JavaScript-driven animations with the performance of CSS. Composable, cancellable, reversible. The foundation for complex choreography.
-
-### Push performance boundaries
-- **Web Workers**: move computation off the main thread. Heavy data processing, image manipulation, search indexing: anything that would cause jank.
-- **OffscreenCanvas**: render in a Worker thread. The main thread stays free while complex visuals render in the background.
-- **WASM**: near-native performance for computation-heavy features. Image processing, physics simulations, codecs.
-
-### Interact with the device
-- **Web Audio API**: spatial audio, audio-reactive visualizations, sonic feedback. Requires user gesture to start.
-- **Device APIs**: orientation, ambient light, geolocation. Use sparingly and always with user permission.
-
-**NOTE**: This command is about enhancing how an interface FEELS, not changing what a product DOES. Adding real-time collaboration, offline support, or new backend capabilities are product decisions, not UI enhancements. Focus on making existing features feel extraordinary.
-
-## Implement with Discipline
-
-### Progressive enhancement is non-negotiable
-
-Every technique must degrade gracefully. The experience without the enhancement must still be good.
-
-```css
-@supports (animation-timeline: scroll()) {
- .hero { animation-timeline: scroll(); }
-}
-```
-
-```javascript
-if ('gpu' in navigator) { /* WebGPU */ }
-else if (canvas.getContext('webgl2')) { /* WebGL2 fallback */ }
-/* CSS-only fallback must still look good */
-```
-
-### Performance rules
-
-- Target 60fps. If dropping below 50, simplify.
-- Respect `prefers-reduced-motion`, always. Provide a beautiful static alternative.
-- Lazy-initialize heavy resources (WebGL contexts, WASM modules) only when near viewport.
-- Pause off-screen rendering. Kill what you can't see.
-- Test on real mid-range devices, not just your development machine.
-
-### Polish is the difference
-
-The gap between "cool" and "extraordinary" is in the last 20% of refinement: the easing curve on a spring animation, the timing offset in a staggered reveal, the subtle secondary motion that makes a transition feel physical. Don't ship the first version that works; ship the version that feels inevitable.
-
-**NEVER**:
-- Ignore `prefers-reduced-motion`. This is an accessibility requirement, not a suggestion
-- Ship effects that cause jank on mid-range devices
-- Use bleeding-edge APIs without a functional fallback
-- Add sound without explicit user opt-in
-- Use technical ambition to mask weak design fundamentals; fix those first with other commands
-- Layer multiple competing extraordinary moments. Focus creates impact, excess creates noise
-
-## Verify the Result
-
-- **The wow test**: Show it to someone who hasn't seen it. Do they react?
-- **The removal test**: Take it away. Does the experience feel diminished, or does nobody notice?
-- **The device test**: Run it on a phone, a tablet, a Chromebook. Still smooth?
-- **The accessibility test**: Enable reduced motion. Still beautiful?
-- **The context test**: Does this make sense for THIS brand and audience?
-
-"Technically extraordinary" isn't about using the newest API. It's about making an interface do something users didn't think a website could do.
@@ -1,179 +0,0 @@
-# Persona-Based Design Testing
-
-Test the interface through the eyes of 5 distinct user archetypes. Each persona exposes different failure modes that a single "design director" perspective would miss.
-
-**How to use**: Select 2–3 personas most relevant to the interface being critiqued. Walk through the primary user action as each persona. Report specific red flags, not generic concerns.
-
----
-
-## 1. Impatient Power User: "Alex"
-
-
-**Profile**: Expert with similar products. Expects efficiency, hates hand-holding. Will find shortcuts or leave.
-
-**Behaviors**:
-- Skips all onboarding and instructions
-- Looks for keyboard shortcuts immediately
-- Tries to bulk-select, batch-edit, and automate
-- Gets frustrated by required steps that feel unnecessary
-- Abandons if anything feels slow or patronizing
-
-**Test Questions**:
-- Can Alex complete the core task in under 60 seconds?
-- Are there keyboard shortcuts for common actions?
-- Can onboarding be skipped entirely?
-- Do modals have keyboard dismiss (Esc)?
-- Is there a "power user" path (shortcuts, bulk actions)?
-
-**Red Flags** (report these specifically):
-- Forced tutorials or unskippable onboarding
-- No keyboard navigation for primary actions
-- Slow animations that can't be skipped
-- One-item-at-a-time workflows where batch would be natural
-- Redundant confirmation steps for low-risk actions
-
----
-
-## 2. Confused First-Timer: "Jordan"
-
-**Profile**: Never used this type of product. Needs guidance at every step. Will abandon rather than figure it out.
-
-**Behaviors**:
-- Reads all instructions carefully
-- Hesitates before clicking anything unfamiliar
-- Looks for help or support constantly
-- Misunderstands jargon and abbreviations
-- Takes the most literal interpretation of any label
-
-**Test Questions**:
-- Is the first action obviously clear within 5 seconds?
-- Are all icons labeled with text?
-- Is there contextual help at decision points?
-- Does terminology assume prior knowledge?
-- Is there a clear "back" or "undo" at every step?
-
-**Red Flags** (report these specifically):
-- Icon-only navigation with no labels
-- Technical jargon without explanation
-- No visible help option or guidance
-- Ambiguous next steps after completing an action
-- No confirmation that an action succeeded
-
----
-
-## 3. Accessibility-Dependent User: "Sam"
-
-**Profile**: Uses screen reader (VoiceOver/NVDA), keyboard-only navigation. May have low vision, motor impairment, or cognitive differences.
-
-**Behaviors**:
-- Tabs through the interface linearly
-- Relies on ARIA labels and heading structure
-- Cannot see hover states or visual-only indicators
-- Needs adequate color contrast (4.5:1 minimum)
-- May use browser zoom up to 200%
-
-**Test Questions**:
-- Can the entire primary flow be completed keyboard-only?
-- Are all interactive elements focusable with visible focus indicators?
-- Do images have meaningful alt text?
-- Is color contrast WCAG AA compliant (4.5:1 for text)?
-- Does the screen reader announce state changes (loading, success, errors)?
-
-**Red Flags** (report these specifically):
-- Click-only interactions with no keyboard alternative
-- Missing or invisible focus indicators
-- Meaning conveyed by color alone (red = error, green = success)
-- Unlabeled form fields or buttons
-- Time-limited actions without extension option
-- Custom components that break screen reader flow
-
----
-
-## 4. Deliberate Stress Tester: "Riley"
-
-**Profile**: Methodical user who pushes interfaces beyond the happy path. Tests edge cases, tries unexpected inputs, and probes for gaps in the experience.
-
-**Behaviors**:
-- Tests edge cases intentionally (empty states, long strings, special characters)
-- Submits forms with unexpected data (emoji, RTL text, very long values)
-- Tries to break workflows by navigating backwards, refreshing mid-flow, or opening in multiple tabs
-- Looks for inconsistencies between what the UI promises and what actually happens
-- Documents problems methodically
-
-**Test Questions**:
-- What happens at the edges (0 items, 1000 items, very long text)?
-- Do error states recover gracefully or leave the UI in a broken state?
-- What happens on refresh mid-workflow? Is state preserved?
-- Are there features that appear to work but produce broken results?
-- How does the UI handle unexpected input (emoji, special chars, paste from Excel)?
-
-**Red Flags** (report these specifically):
-- Features that appear to work but silently fail or produce wrong results
-- Error handling that exposes technical details or leaves UI in a broken state
-- Empty states that show nothing useful ("No results" with no guidance)
-- Workflows that lose user data on refresh or navigation
-- Inconsistent behavior between similar interactions in different parts of the UI
-
----
-
-## 5. Distracted Mobile User: "Casey"
-
-**Profile**: Using phone one-handed on the go. Frequently interrupted. Possibly on a slow connection.
-
-**Behaviors**:
-- Uses thumb only; prefers bottom-of-screen actions
-- Gets interrupted mid-flow and returns later
-- Switches between apps frequently
-- Has limited attention span and low patience
-- Types as little as possible, prefers taps and selections
-
-**Test Questions**:
-- Are primary actions in the thumb zone (bottom half of screen)?
-- Is state preserved if the user leaves and returns?
-- Does it work on slow connections (3G)?
-- Can forms use autocomplete and smart defaults?
-- Are touch targets at least 44×44pt?
-
-**Red Flags** (report these specifically):
-- Important actions positioned at the top of the screen (unreachable by thumb)
-- No state persistence; progress lost on tab switch or interruption
-- Large text inputs required where selection would work
-- Heavy assets loading on every page (no lazy loading)
-- Tiny tap targets or targets too close together
-
----
-
-## Selecting Personas
-
-Choose personas based on the interface type:
-
-| Interface Type | Primary Personas | Why |
-|---------------|-----------------|-----|
-| Landing page / marketing | Jordan, Riley, Casey | First impressions, trust, mobile |
-| Dashboard / admin | Alex, Sam | Power users, accessibility |
-| E-commerce / checkout | Casey, Riley, Jordan | Mobile, edge cases, clarity |
-| Onboarding flow | Jordan, Casey | Confusion, interruption |
-| Data-heavy / analytics | Alex, Sam | Efficiency, keyboard nav |
-| Form-heavy / wizard | Jordan, Sam, Casey | Clarity, accessibility, mobile |
-
----
-
-## Project-Specific Personas
-
-If `.github/copilot-instructions.md` contains a `## Design Context` section (generated by `impeccable teach`), derive 1–2 additional personas from the audience and brand information:
-
-1. Read the target audience description
-2. Identify the primary user archetype not covered by the 5 predefined personas
-3. Create a persona following this template:
-
-```
-### [Role]: "[Name]"
-
-**Profile**: [2-3 key characteristics derived from Design Context]
-
-**Behaviors**: [3-4 specific behaviors based on the described audience]
-
-**Red Flags**: [3-4 things that would alienate this specific user type]
-```
-
-Only generate project-specific personas when real Design Context data is available. Don't invent audience details; use the 5 predefined personas when no context exists.
@@ -1,242 +0,0 @@
-> **Additional context needed**: quality bar (MVP vs flagship).
-
-Perform a meticulous final pass to catch all the small details that separate good work from great work. The difference between shipped and polished.
-
-Detector and automated QA output are defect evidence only. A clean script result is never proof that the design is strong; gather browser evidence and inspect the real interaction path.
-
-## Design System Discovery
-
-Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
-
-1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
-2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
-3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category: patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
-
-If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask. Never guess at design system principles.**
-
-## Pre-Polish Assessment
-
-Understand the current state and goals before touching anything:
-
-1. **Review completeness**:
- - Is it functionally complete?
- - Are there known issues to preserve (mark with TODOs)?
- - What's the quality bar? (MVP vs flagship feature?)
- - When does it ship? (How much time for polish?)
-
-2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish; a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
-
-3. **Identify polish areas**:
- - Visual inconsistencies
- - Spacing and alignment issues
- - Interaction state gaps
- - Copy inconsistencies
- - Edge cases and error states
- - Loading and transition smoothness
- - Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
-
-4. **Pull in any prior critique** (optional signal): If `/impeccable critique` has been run on the same target, its priority issues are a useful prior for what to address first. Resolve the target to a file path or URL, then:
- ```bash
- slug=$(node .github/skills/impeccable/scripts/critique-storage.mjs slug "<resolved>")
- node .github/skills/impeccable/scripts/critique-storage.mjs latest "$slug"
- ```
- Exit 0 with body = found; fold the P0/P1 items into your polish list and mention the snapshot path so the user sees what you read. Exit 2 = no snapshot, continue without it. The critique is one input among many. Do your own pass either way.
-
-5. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent; never perfect one corner while leaving another rough.
-
-**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
-
-## Polish Systematically
-
-Work through these dimensions methodically:
-
-### Visual Alignment & Spacing
-
-- **Pixel-perfect alignment**: Everything lines up to grid
-- **Consistent spacing**: All gaps use spacing scale (no random 13px gaps)
-- **Optical alignment**: Adjust for visual weight (icons may need offset for optical centering)
-- **Responsive consistency**: Spacing and alignment work at all breakpoints
-- **Grid adherence**: Elements snap to baseline grid
-
-**Check**:
-- Enable grid overlay and verify alignment
-- Check spacing with browser inspector
-- Test at multiple viewport sizes
-- Look for elements that "feel" off
-
-### Information Architecture & Flow
-
-Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
-
-- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
-- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere: modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
-- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
-- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
-- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
-
-### Typography Refinement
-
-- **Hierarchy consistency**: Same elements use same sizes/weights throughout
-- **Line length**: 45-75 characters for body text
-- **Line height**: Appropriate for font size and context
-- **Widows & orphans**: No single words on last line
-- **Hyphenation**: Appropriate for language and column width
-- **Kerning**: Adjust letter spacing where needed (especially headlines)
-- **Font loading**: No FOUT/FOIT flashes
-
-### Color & Contrast
-
-- **Contrast ratios**: All text meets WCAG standards
-- **Consistent token usage**: No hard-coded colors, all use design tokens
-- **Theme consistency**: Works in all theme variants
-- **Color meaning**: Same colors mean same things throughout
-- **Accessible focus**: Focus indicators visible with sufficient contrast
-- **Tinted neutrals**: No pure gray or pure black; add subtle color tint (0.01 chroma)
-- **Gray on color**: Never put gray text on colored backgrounds; use a shade of that color or transparency
-
-### Interaction States
-
-Every interactive element needs all states:
-
-- **Default**: Resting state
-- **Hover**: Subtle feedback (color, scale, shadow)
-- **Focus**: Keyboard focus indicator (never remove without replacement)
-- **Active**: Click/tap feedback
-- **Disabled**: Clearly non-interactive
-- **Loading**: Async action feedback
-- **Error**: Validation or error state
-- **Success**: Successful completion
-
-**Missing states create confusion and broken experiences**.
-
-### Micro-interactions & Transitions
-
-- **Smooth transitions**: All state changes animated appropriately (150-300ms)
-- **Consistent easing**: Use ease-out-quart/quint/expo for natural deceleration. Never bounce or elastic; they feel dated.
-- **No jank**: Smooth animations; use atmospheric blur/filter/mask/shadow effects when they add polish, but bound expensive paint areas and avoid casual layout-property animation
-- **Appropriate motion**: Motion serves purpose, not decoration
-- **Reduced motion**: Respects `prefers-reduced-motion`
-
-### Content & Copy
-
-- **Consistent terminology**: Same things called same names throughout
-- **Consistent capitalization**: Title Case vs Sentence case applied consistently
-- **Grammar & spelling**: No typos
-- **Appropriate length**: Not too wordy, not too terse
-- **Punctuation consistency**: Periods on sentences, not on labels (unless all labels have them)
-
-### Icons & Images
-
-- **Consistent style**: All icons from same family or matching style
-- **Appropriate sizing**: Icons sized consistently for context
-- **Proper alignment**: Icons align with adjacent text optically
-- **Alt text**: All images have descriptive alt text
-- **Loading states**: Images don't cause layout shift, proper aspect ratios
-- **Retina support**: 2x assets for high-DPI screens
-
-### Forms & Inputs
-
-- **Label consistency**: All inputs properly labeled
-- **Required indicators**: Clear and consistent
-- **Error messages**: Helpful and consistent
-- **Tab order**: Logical keyboard navigation
-- **Auto-focus**: Appropriate (don't overuse)
-- **Validation timing**: Consistent (on blur vs on submit)
-
-### Edge Cases & Error States
-
-- **Loading states**: All async actions have loading feedback
-- **Empty states**: Helpful empty states, not just blank space
-- **Error states**: Clear error messages with recovery paths
-- **Success states**: Confirmation of successful actions
-- **Long content**: Handles very long names, descriptions, etc.
-- **No content**: Handles missing data gracefully
-- **Offline**: Appropriate offline handling (if applicable)
-
-### Responsiveness
-
-- **All breakpoints**: Test mobile, tablet, desktop
-- **Touch targets**: 44x44px minimum on touch devices
-- **Readable text**: No text smaller than 14px on mobile
-- **No horizontal scroll**: Content fits viewport
-- **Appropriate reflow**: Content adapts logically
-
-### Performance
-
-- **Fast initial load**: Optimize critical path
-- **No layout shift**: Elements don't jump after load (CLS)
-- **Smooth interactions**: No lag or jank
-- **Optimized images**: Appropriate formats and sizes
-- **Lazy loading**: Off-screen content loads lazily
-
-### Code Quality
-
-- **Remove console logs**: No debug logging in production
-- **Remove commented code**: Clean up dead code
-- **Remove unused imports**: Clean up unused dependencies
-- **Consistent naming**: Variables and functions follow conventions
-- **Type safety**: No TypeScript `any` or ignored errors
-- **Accessibility**: Proper ARIA labels and semantic HTML
-
-## Polish Checklist
-
-Go through systematically:
-
-- [ ] Aligned to the design system (drift named and resolved by root cause)
-- [ ] Information architecture and flow shape match neighboring features
-- [ ] Visual alignment perfect at all breakpoints
-- [ ] Spacing uses design tokens consistently
-- [ ] Typography hierarchy consistent
-- [ ] All interactive states implemented
-- [ ] All transitions smooth (60fps)
-- [ ] Copy is consistent and polished
-- [ ] Icons are consistent and properly sized
-- [ ] All forms properly labeled and validated
-- [ ] Error states are helpful
-- [ ] Loading states are clear
-- [ ] Empty states are welcoming
-- [ ] Touch targets are 44x44px minimum
-- [ ] Contrast ratios meet WCAG AA
-- [ ] Keyboard navigation works
-- [ ] Focus indicators visible
-- [ ] No console errors or warnings
-- [ ] No layout shift on load
-- [ ] Works in all supported browsers
-- [ ] Respects reduced motion preference
-- [ ] Code is clean (no TODOs, console.logs, commented code)
-
-**IMPORTANT**: Polish is about details. Zoom in. Squint at it. Use it yourself. The little things add up.
-
-Sweat the details. Zoom in until the alignment is right and the spacing reads as deliberate. Then ship.
-
-**NEVER**:
-- Polish before it's functionally complete
-- Polish without aligning to the design system; that's decoration on drift
-- Guess at design system principles instead of asking when something is ambiguous
-- Spend hours on polish if it ships in 30 minutes (triage)
-- Introduce bugs while polishing (test thoroughly)
-- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
-- Perfect one thing while leaving others rough (consistent quality level)
-- Create new one-off components when design system equivalents exist
-- Hard-code values that should use design tokens
-- Introduce new patterns or flows that diverge from established ones
-
-## Final Verification
-
-Before marking as done:
-
-- **Use it yourself**: Actually interact with the feature.
-- **Test on real devices**: Not just browser DevTools.
-- **Ask someone else to review**: Fresh eyes catch things.
-- **Compare to design**: Match intended design.
-- **Check all states**: Don't just test happy path.
-- **Treat automation carefully**: Run detector or QA commands when they are available and relevant, fix their defects, but never cite a clean result as proof that the work is polished.
-
-## Clean Up
-
-After polishing, ensure code quality:
-
-- **Replace custom implementations**: If the design system provides a component you reimplemented, switch to the shared version.
-- **Remove orphaned code**: Delete unused styles, components, or files made obsolete by polish.
-- **Consolidate tokens**: If you introduced new values, check whether they should be tokens.
-- **Verify DRYness**: Look for duplication introduced during polishing and consolidate.
@@ -1,62 +0,0 @@
-# Product register
-
-When design SERVES the product: app UIs, admin dashboards, settings panels, data tables, tools, authenticated surfaces, anything where the user is in a task.
-
-## The product slop test
-
-Not "would someone say AI made this." Familiarity is often a feature here. The test is: would a user fluent in the category's best tools (Linear, Figma, Notion, Raycast, Stripe come to mind) sit down and trust this interface, or pause at every subtly-off component?
-
-Product UI's failure mode isn't flatness, it's strangeness without purpose: over-decorated buttons, mismatched form controls, gratuitous motion, display fonts where labels should be, invented affordances for standard tasks. The bar is earned familiarity. The tool should disappear into the task.
-
-## Typography
-
-- **System fonts are legitimate.** `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` gives you native feel on every platform. Inter is the common cross-platform default for a reason.
-- **One family is often right.** Product UIs don't need display/body pairing. A well-tuned sans carries headings, buttons, labels, body, data.
-- **Fixed rem scale, not fluid.** Clamp-sized headings don't serve product UI. Users view at consistent DPI, and a fluid h1 that shrinks in a sidebar looks worse, not better.
-- **Tighter scale ratio.** 1.125–1.2 between steps is typical. More type elements here than on brand surfaces; exaggerated contrast creates noise.
-- **Line length still applies for prose** (65–75ch). Data and compact UI can run denser; tables at 120ch+ are fine.
-
-## Color
-
-Product defaults to Restrained. A single surface can earn Committed (a dashboard where one category color carries a report, an onboarding flow with a drenched welcome screen), but Restrained is the floor.
-
-- State-rich semantic vocabulary: hover, focus, active, disabled, selected, loading, error, warning, success, info. Standardize these.
-- Accent color used for primary actions, current selection, and state indicators only, not decoration.
-- A second neutral layer for sidebars, toolbars, and panels (slightly cooler or warmer than the content surface).
-
-## Layout
-
-- Predictable grids. Consistency IS an affordance; users navigate faster when the structure is expected.
-- Familiar patterns are features. Standard navigation (top bar, side nav), breadcrumbs, tabs, and form layouts have established user expectations. Don't reinvent for flavor.
-- Responsive behavior is structural (collapse sidebar, responsive table, breakpoint-driven columns), not fluid typography.
-
-## Components
-
-Every interactive component has: default, hover, focus, active, disabled, loading, error. Don't ship with half of these.
-
-- Skeleton states for loading, not spinners in the middle of content.
-- Empty states that teach the interface, not "nothing here."
-- Consistent affordances across the surface. Same button shape. Same form-control vocabulary. Same icon style.
-
-## Motion
-
-- 150–250 ms on most transitions. Users are in flow; don't make them wait for choreography.
-- Motion conveys state, not decoration. State change, feedback, loading, reveal: nothing else.
-- No orchestrated page-load sequences. Product loads into a task; users don't want to watch it load.
-
-## Product bans (on top of the shared absolute bans)
-
-- Decorative motion that doesn't convey state.
-- Inconsistent component vocabulary across screens. If the "save" button looks different in two places, one is wrong.
-- Display fonts in UI labels, buttons, data.
-- Reinventing standard affordances for flavor (custom scrollbars, weird form controls, non-standard modals).
-- Heavy color or full-saturation accents on inactive states.
-
-## Product permissions
-
-Product can afford things brand surfaces can't.
-
-- System fonts and familiar sans defaults (Inter, SF Pro, system-ui stacks).
-- Standard navigation patterns: top bar + side nav, breadcrumbs, tabs, command palettes.
-- Density. Tables with many rows, panels with many labels, dense information when users need it.
-- Consistency over surprise. The same visual vocabulary screen to screen is a virtue; delight is saved for moments, not pages.
@@ -1,99 +0,0 @@
-Quiet design is harder than bold design. Subtlety needs precision. Reduce visual intensity in designs that are too loud, aggressive, or overstimulating without losing personality or making the result generic.
-
----
-
-## Register
-
-Brand: "quieter" means more restrained palette, more whitespace, more typographic air. Drama is reduced, not eliminated; the POV stays intact.
-
-Product: "quieter" means reducing visual noise. Fewer background accents, flatter cards, less color, less motion. The tool should disappear more completely into the task.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too intense:
-
-1. **Identify intensity sources**:
- - **Color saturation**: Overly bright or saturated colors
- - **Contrast extremes**: Too much high-contrast juxtaposition
- - **Visual weight**: Too many bold, heavy elements competing
- - **Animation excess**: Too much motion or overly dramatic effects
- - **Complexity**: Too many visual elements, patterns, or decorations
- - **Scale**: Everything is large and loud with no hierarchy
-
-2. **Understand the context**:
- - What's the purpose? (Marketing vs tool vs reading experience)
- - Who's the audience? (Some contexts need energy)
- - What's working? (Don't throw away good ideas)
- - What's the core message? (Preserve what matters)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Quieter" doesn't mean boring or generic. It means refined and easier on the eyes. Think luxury, not laziness.
-
-## Plan Refinement
-
-Create a strategy to reduce intensity while maintaining impact:
-
-- **Color approach**: Desaturate or shift to more restrained tones?
-- **Hierarchy approach**: Which elements should stay bold (very few), which should recede?
-- **Simplification approach**: What can be removed entirely?
-- **Sophistication approach**: How can we signal quality through restraint?
-
-**IMPORTANT**: Subtlety requires precision. Quiet without intent collapses to generic.
-
-## Refine the Design
-
-Systematically reduce intensity across these dimensions:
-
-### Color Refinement
-- **Reduce saturation**: Shift from fully saturated to 70-85% saturation
-- **Soften palette**: Replace bright colors with muted tones
-- **Reduce color variety**: Use fewer colors more thoughtfully
-- **Neutral dominance**: Let neutrals do more work, use color as accent (10% rule)
-- **Gentler contrasts**: High contrast only where it matters most
-- **Tinted grays**: Use warm or cool tinted grays instead of pure gray. Adds depth without loudness
-- **Never gray on color**: If you have gray text on a colored background, use a darker shade of that color or transparency instead
-
-### Visual Weight Reduction
-- **Typography**: Reduce font weights (900 → 600, 700 → 500), decrease sizes where appropriate
-- **Hierarchy through subtlety**: Use weight, size, and space instead of color and boldness
-- **White space**: Increase breathing room, reduce density
-- **Borders & lines**: Reduce thickness, decrease opacity, or remove entirely
-
-### Simplification
-- **Remove decorative elements**: Gradients, shadows, patterns, textures that don't serve purpose
-- **Simplify shapes**: Reduce border radius extremes, simplify custom shapes
-- **Reduce layering**: Flatten visual hierarchy where possible
-- **Clean up effects**: Reduce or remove blur effects, glows, multiple shadows
-
-### Motion Reduction
-- **Reduce animation intensity**: Shorter distances (10-20px instead of 40px), gentler easing
-- **Remove decorative animations**: Keep functional motion, remove flourishes
-- **Subtle micro-interactions**: Replace dramatic effects with gentle feedback
-- **Refined easing**: Use ease-out-quart for smooth, understated motion. Never bounce or elastic
-- **Remove animations entirely** if they're not serving a clear purpose
-
-### Composition Refinement
-- **Reduce scale jumps**: Smaller contrast between sizes creates calmer feeling
-- **Align to grid**: Bring rogue elements back into systematic alignment
-- **Even out spacing**: Replace extreme spacing variations with consistent rhythm
-
-**NEVER**:
-- Make everything the same size/weight (hierarchy still matters)
-- Remove all color (quiet ≠ grayscale)
-- Eliminate all personality (maintain character through refinement)
-- Sacrifice usability for aesthetics (functional elements still need clear affordances)
-- Make everything small and light (some anchors needed)
-
-## Verify Quality
-
-Ensure refinement maintains quality:
-
-- **Still functional**: Can users still accomplish tasks easily?
-- **Still distinctive**: Does it have character, or is it generic now?
-- **Better reading**: Is text easier to read for extended periods?
-- **Restrained, not absent**: Does the POV survive the cuts?
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,114 +0,0 @@
-# Responsive Design
-
-## Mobile-First: Write It Right
-
-Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
-
-## Breakpoints: Content-Driven
-
-Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
-
-## Detect Input Method, Not Just Screen Size
-
-**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
-
-```css
-/* Fine pointer (mouse, trackpad) */
-@media (pointer: fine) {
- .button { padding: 8px 16px; }
-}
-
-/* Coarse pointer (touch, stylus) */
-@media (pointer: coarse) {
- .button { padding: 12px 20px; } /* Larger touch target */
-}
-
-/* Device supports hover */
-@media (hover: hover) {
- .card:hover { transform: translateY(-2px); }
-}
-
-/* Device doesn't support hover (touch) */
-@media (hover: none) {
- .card { /* No hover state - use active instead */ }
-}
-```
-
-**Critical**: Don't rely on hover for functionality. Touch users can't hover.
-
-## Safe Areas: Handle the Notch
-
-Modern phones have notches, rounded corners, and home indicators. Use `env()`:
-
-```css
-body {
- padding-top: env(safe-area-inset-top);
- padding-bottom: env(safe-area-inset-bottom);
- padding-left: env(safe-area-inset-left);
- padding-right: env(safe-area-inset-right);
-}
-
-/* With fallback */
-.footer {
- padding-bottom: max(1rem, env(safe-area-inset-bottom));
-}
-```
-
-**Enable viewport-fit** in your meta tag:
-```html
-<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
-```
-
-## Responsive Images: Get It Right
-
-### srcset with Width Descriptors
-
-```html
-<img
- src="hero-800.jpg"
- srcset="
- hero-400.jpg 400w,
- hero-800.jpg 800w,
- hero-1200.jpg 1200w
- "
- sizes="(max-width: 768px) 100vw, 50vw"
- alt="Hero image"
->
-```
-
-**How it works**:
-- `srcset` lists available images with their actual widths (`w` descriptors)
-- `sizes` tells the browser how wide the image will display
-- Browser picks the best file based on viewport width AND device pixel ratio
-
-### Picture Element for Art Direction
-
-When you need different crops/compositions (not just resolutions):
-
-```html
-<picture>
- <source media="(min-width: 768px)" srcset="wide.jpg">
- <source media="(max-width: 767px)" srcset="tall.jpg">
- <img src="fallback.jpg" alt="...">
-</picture>
-```
-
-## Layout Adaptation Patterns
-
-**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
-
-## Testing: Don't Trust DevTools Alone
-
-DevTools device emulation is useful for layout but misses:
-
-- Actual touch interactions
-- Real CPU/memory constraints
-- Network latency patterns
-- Font rendering differences
-- Browser chrome/keyboard appearances
-
-**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
-
----
-
-**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
@@ -1,165 +0,0 @@
-Shape the UX and UI for a feature before any code is written. This command produces a **design brief**: a structured artifact that guides implementation through discovery, not guesswork.
-
-**Scope**: Design planning only. This command does NOT write code. It produces the thinking that makes code good.
-
-**Output**: A design brief that can be handed off to /impeccable craft, or directly to /impeccable for freeform implementation. When visual direction probes are used, the images are supporting artifacts, not the primary output.
-
-## Philosophy
-
-Most AI-generated UIs fail not because of bad code, but because of skipped thinking. They jump to "here's a card grid" without asking "what is the user trying to accomplish?" This command inverts that: understand deeply first, so implementation is precise.
-
-## Phase 1: Discovery Interview
-
-**Do NOT write any code or make any design decisions during this phase.** Your only job is to understand the feature deeply enough to make excellent design decisions later.
-
-This is a required interaction, not optional guidance. Ask these questions in conversation, adapting based on answers. Don't dump them all at once; have a natural dialogue. ask the user directly to clarify what you cannot infer.
-
-### Interview cadence
-
-Discovery includes at least one user-answer round unless PRODUCT.md, DESIGN.md, or an already-confirmed brief directly answers the needed inputs. With a sparse prompt, do **not** synthesize a complete brief for confirmation on the first response.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Treat PRODUCT.md and DESIGN.md as anchors; they reduce repeated questions but do **not** replace shape for craft. Shape is task-specific.
-- One round is the default. Add a second only if the first answers leave material gaps. Don't run a second round just to feel thorough.
-- Round 1 should clarify purpose, audience/context, content/scope, and (for brand) visual direction.
-- Round 2, when needed, fills in whatever's still genuinely missing.
-
-**Assert-then-confirm, not menu-with-escape.** When PRODUCT.md and the user's prompt make one option obvious, name it and ask the user to confirm or override. Don't enumerate "Restrained / Committed / Or something else?" as a real choice; "This reads as Restrained, confirm?" beats a four-option menu when the answer is already clear.
-
-### Purpose & Context
-- What is this feature for? What problem does it solve?
-- Who specifically will use it? (Not "users"; be specific: role, context, frequency)
-- What does success look like? How will you know this feature is working?
-- What's the user's state of mind when they reach this feature? (Rushed? Exploring? Anxious? Focused?)
-
-### Content & Data
-- What content or data does this feature display or collect?
-- What are the realistic ranges? (Minimum, typical, maximum, e.g., 0 items, 5 items, 500 items)
-- What are the edge cases? (Empty state, error state, first-time use, power user)
-- Is any content dynamic? What changes and how often?
-- What visual assets are real content here? Note required images, product shots, illustrations, maps, textures, diagrams, generated objects, or existing project assets.
-
-### Design Direction
-
-Force a visual decision on three fronts. Skip anything PRODUCT.md or DESIGN.md already answers; ask only what's missing.
-
-- **Color strategy for this surface.** Pick one: Restrained / Committed / Full palette / Drenched. Can override the project default if the surface earns it (e.g. a drenched hero inside an otherwise Restrained product).
-- **Theme via scene sentence.** Write one sentence of physical context for this surface: who uses it, where, under what ambient light, in what mood. The sentence forces dark vs light. If it doesn't, add detail until it does.
-- **Two or three named anchor references.** Specific products, brands, objects. Not adjectives like "modern" or "clean."
-
-### Scope
-
-Always ask. Sketch quality and shipped quality are different outputs; don't guess between them.
-
-- **Fidelity.** Sketch / mid-fi / high-fi / production-ready?
-- **Breadth.** One screen / a flow / a whole surface?
-- **Interactivity.** Static visual / interactive prototype / shipped-quality component?
-- **Time intent.** Quick exploration, or polish until it ships?
-
-Scope answers are task-scoped. Don't write them to PRODUCT.md or DESIGN.md; carry them through the design brief only.
-
-### Constraints
-- Are there technical constraints? (Framework, performance budget, browser support)
-- Are there content constraints? (Localization, dynamic text length, user-generated content)
-- Mobile/responsive requirements?
-- Accessibility requirements beyond WCAG AA?
-
-### Anti-Goals
-- What should this NOT be? What would be a wrong direction?
-- What's the biggest risk of getting this wrong?
-
-## Phase 1.5: Visual Direction Probe (Capability-Gated)
-
-After the discovery interview, generate a small set of visual direction probes **before** writing the final brief when all of these are true:
-
-- The work is **net-new** or directionally ambiguous enough that visual exploration will clarify the brief.
-- The requested fidelity is **mid-fi, high-fi, or production-ready**. Skip for sketch-only planning.
-- The current harness gives you native image generation (Codex's `image_gen`, an equivalent MCP tool, or similar). Don't ask the user to install APIs or tooling.
-
-When those conditions are met, this step is mandatory. If image generation isn't natively available, do not ask the user to install APIs or tooling. State in one line that the image step is skipped because the harness lacks native image generation, then proceed. The one-line announcement is required, not optional; it forces a conscious decision instead of letting the step quietly evaporate.
-
-Use probes to explore visual lanes, not to replace the brief.
-
-Do not skip probes because the final UI will be semantic, editable, code-native, responsive, or accessible. Those are implementation requirements, not reasons to avoid visual exploration.
-
-### What to generate
-
-Generate **2 to 4** distinct direction probes based on the discovery answers, especially:
-
-- Color strategy
-- Theme scene sentence
-- Named anchor references
-- Scope and fidelity
-
-The probes should differ in primary visual direction (hierarchy, topology, density, typographic voice, or color strategy), not just palette tweaks.
-
-### How to use the probes
-
-- Treat them as **direction tests**, not final designs.
-- Use them to pressure-test whether the brief is pointing at the right lane.
-- Ask the user which direction feels closest, what feels off, and what should carry forward.
-- If the probes reveal a mismatch, revise the brief inputs before finalizing the brief.
-
-### Important limits
-
-- Do **not** skip discovery because image generation is available.
-- Do **not** treat generated imagery as final UX specification, final copy, or final accessibility behavior.
-- Do **not** use this step for minor refinements of existing work. It's for shaping a new surface or clarifying a big directional choice.
-
-If image generation isn't natively available, announce the skip in one line and proceed to the design brief.
-
-## Phase 2: Design Brief
-
-After the interview and any required probes, present a brief and **end your response**. The user must confirm before any implementation runs. Do not present a brief and then continue to code in the same response, even if the brief feels obvious to you. The user's confirmation is the gate.
-
-**Choose the brief shape based on how clear the answers are:**
-
-- **Compact form (3-5 bullets)** when discovery was crisp and the original prompt + PRODUCT.md already pinned scope, content, and direction. State what you're building, the visual lane, and end with one or two specific questions or a clear "confirm or override?" prompt. This is the default for typical craft requests with a clear prompt.
-- **Full structured form (sections below)** when the task is genuinely ambiguous, multi-screen, or when the user asked for shape as a standalone step. Use this when the discipline of structure earns its weight.
-
-Don't pad a clear brief into a long one to look thorough. A 70-line brief restating answers the user just gave is noise, not rigor. Equally, don't skip the confirmation pause to look efficient: the pause is the point.
-
-Present the brief, then **stop and wait for explicit confirmation**. You are not the judge of whether the user already approved. Even when the brief feels obviously right, ask once and wait. The pause is what separates shape from premature implementation.
-
-### Brief Structure
-
-**1. Feature Summary** (2-3 sentences)
-What this is, who it's for, what it needs to accomplish.
-
-**2. Primary User Action**
-The single most important thing a user should do or understand here.
-
-**3. Design Direction**
-Color strategy (Restrained / Committed / Full palette / Drenched) + the theme scene sentence + 2–3 named anchor references. Reference PRODUCT.md and DESIGN.md where they already answer, and note any per-surface overrides.
-
-If you ran the Visual Direction Probe step, name which probe direction won and what changed in the brief because of it.
-
-**4. Scope**
-Fidelity, breadth, interactivity, and time intent from the Scope section of the interview. Task-scoped; these don't persist beyond the brief.
-
-**5. Layout Strategy**
-High-level spatial approach: what gets emphasis, what's secondary, how information flows. Describe the visual hierarchy and rhythm, not specific CSS.
-
-**6. Key States**
-List every state the feature needs: default, empty, loading, error, success, edge cases. For each, note what the user needs to see and feel.
-
-**7. Interaction Model**
-How users interact with this feature. What happens on click, hover, scroll? What feedback do they get? What's the flow from entry to completion?
-
-**8. Content Requirements**
-What copy, labels, empty state messages, error messages, and microcopy are needed. Note any dynamic content and its realistic ranges. For image-led surfaces, also list the required image/media roles and their likely source (project asset, generated raster, semantic SVG/CSS, canvas/WebGL, icon library, or accepted omission).
-
-**9. Recommended References**
-Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., spatial-design.md for complex layouts, motion-design.md for animated features, interaction-design.md for form-heavy features).
-
-**10. Open Questions**
-Anything genuinely unresolved. Don't list "open questions" you've already recommended a default for; assert the default and move on. If you'd write `Recommend: X` next to a question, just decide X.
-
----
-
-ask the user directly to clarify what you cannot infer. Ask for explicit confirmation of the brief before finishing.
-
-If the user disagrees with any part, revisit the relevant discovery questions. A shape run is incomplete until the user confirms direction.
-
-Once confirmed, the brief is complete. The user can now hand it to /impeccable, or use it to guide any other implementation approach. (If the user wants the full discovery-then-build flow in one step, they should use /impeccable craft instead, which runs this command internally.)
@@ -1,100 +0,0 @@
-# Spatial Design
-
-## Spacing Systems
-
-### Use 4pt Base, Not 8pt
-
-8pt systems are too coarse; you'll frequently need 12px (between 8 and 16). Use 4pt for granularity: 4, 8, 12, 16, 24, 32, 48, 64, 96px.
-
-### Name Tokens Semantically
-
-Name by relationship (`--space-sm`, `--space-lg`), not value (`--spacing-8`). Use `gap` instead of margins for sibling spacing; it eliminates margin collapse and cleanup hacks.
-
-## Grid Systems
-
-### The Self-Adjusting Grid
-
-Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Columns are at least 280px, as many as fit per row, leftovers stretch. For complex layouts, use named grid areas (`grid-template-areas`) and redefine them at breakpoints.
-
-## Visual Hierarchy
-
-### The Squint Test
-
-Blur your eyes (or screenshot and blur). Can you still identify:
-- The most important element?
-- The second most important?
-- Clear groupings?
-
-If everything looks the same weight blurred, you have a hierarchy problem.
-
-### Hierarchy Through Multiple Dimensions
-
-Don't rely on size alone. Combine:
-
-| Tool | Strong Hierarchy | Weak Hierarchy |
-|------|------------------|----------------|
-| **Size** | 3:1 ratio or more | <2:1 ratio |
-| **Weight** | Bold vs Regular | Medium vs Regular |
-| **Color** | High contrast | Similar tones |
-| **Position** | Top/left (primary) | Bottom/right |
-| **Space** | Surrounded by white space | Crowded |
-
-**The best hierarchy uses 2-3 dimensions at once**: A heading that's larger, bolder, AND has more space above it.
-
-### Cards Are Not Required
-
-Cards are overused. Spacing and alignment create visual grouping naturally. Use cards only when content is truly distinct and actionable, items need visual comparison in a grid, or content needs clear interaction boundaries. **Never nest cards inside cards.** Use spacing, typography, and subtle dividers for hierarchy within a card.
-
-## Container Queries
-
-Viewport queries are for page layouts. **Container queries are for components**:
-
-```css
-.card-container {
- container-type: inline-size;
-}
-
-.card {
- display: grid;
- gap: var(--space-md);
-}
-
-/* Card layout changes based on its container, not viewport */
-@container (min-width: 400px) {
- .card {
- grid-template-columns: 120px 1fr;
- }
-}
-```
-
-**Why this matters**: A card in a narrow sidebar stays compact, while the same card in a main content area expands automatically, without viewport hacks.
-
-## Optical Adjustments
-
-Text at `margin-left: 0` looks indented due to letterform whitespace; use negative margin (`-0.05em`) to optically align. Geometrically centered icons often look off-center; play icons need to shift right, arrows shift toward their direction.
-
-### Touch Targets vs Visual Size
-
-Buttons can look small but need large touch targets (44px minimum). Use padding or pseudo-elements:
-
-```css
-.icon-button {
- width: 24px; /* Visual size */
- height: 24px;
- position: relative;
-}
-
-.icon-button::before {
- content: '';
- position: absolute;
- inset: -10px; /* Expand tap target to 44px */
-}
-```
-
-## Depth & Elevation
-
-Create semantic z-index scales (dropdown → sticky → modal-backdrop → modal → toast → tooltip) instead of arbitrary numbers. For shadows, create a consistent elevation scale (sm → md → lg → xl). **Key insight**: Shadows should be subtle. If you can clearly see it, it's probably too strong.
-
----
-
-**Avoid**: Arbitrary spacing values outside your scale. Making all spacing equal (variety creates hierarchy). Creating hierarchy through size alone - combine size, weight, color, and space.
@@ -1,156 +0,0 @@
-# Teach Flow
-
-Gathers design context for a project and writes two complementary files at the project root:
-
-- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
-- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
-
-Every other impeccable command reads these files before doing any work.
-
-## Step 1: Load current state
-
-Run the shared loader first so you know what already exists:
-
-```bash
-node .github/skills/impeccable/scripts/load-context.mjs
-```
-
-The output tells you whether PRODUCT.md and/or DESIGN.md already exist. If `migrated: true`, legacy `.impeccable.md` was auto-renamed to `PRODUCT.md`. Mention this once to the user.
-
-Decision tree:
-- **Neither file exists (empty project or no context yet)**: do Steps 2-4 (write PRODUCT.md), then decide on DESIGN.md based on whether there's code to analyze.
-- **PRODUCT.md exists, DESIGN.md missing**: skip to Step 5 and offer to run `/impeccable document` for DESIGN.md.
-- **PRODUCT.md exists but has no `## Register` section (legacy)**: add it. Infer a hypothesis from the codebase (see Step 2), confirm with the user, write the field.
-- **Both exist**: ask the user directly to clarify what you cannot infer. Ask which file to refresh. Skip the one the user doesn't want changed.
-- **Just DESIGN.md exists (unusual)**: do Steps 2-4 to produce PRODUCT.md.
-
-Never silently overwrite an existing file. Always confirm first.
-
-If teach was invoked as a setup blocker by another command, such as `/impeccable craft landing page`, pause that command here. Complete teach, re-run the loader, then resume the original command with the freshly loaded context. For craft, resume into shape next; teach creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
-
-## Step 2: Explore the codebase
-
-Before asking questions, thoroughly scan the project to discover what you can:
-
-- **README and docs**: Project purpose, target audience, any stated goals
-- **Package.json / config files**: Tech stack, dependencies, existing design libraries
-- **Existing components**: Current design patterns, spacing, typography in use
-- **Brand assets**: Logos, favicons, color values already defined
-- **Design tokens / CSS variables**: Existing color palettes, font stacks, spacing scales
-- **Any style guides or brand documentation**
-
-Also form a **register hypothesis** from what you find:
-
-- Brand signals: `/`, `/about`, `/pricing`, `/blog/*`, `/docs/*`, hero sections, big typography, scroll-driven sections, landing-page-shaped content.
-- Product signals: `/app/*`, `/dashboard`, `/settings`, `/(auth)`, forms, data tables, side/top nav, app-shell components.
-
-Register is a hypothesis at this point, not a decision; Step 3 confirms it.
-
-Note what you've learned and what remains unclear. This exploration feeds both PRODUCT.md and DESIGN.md.
-
-## Step 3: Ask strategic questions (for PRODUCT.md)
-
-ask the user directly to clarify what you cannot infer. Ask only about what you couldn't infer from the codebase.
-
-### Interview mode, not confirmation mode
-
-If the repo is empty or the user's brief is sparse, run a short interview before proposing PRODUCT.md. Do **not** turn a one-sentence request into a complete inferred PRODUCT.md and ask for blanket confirmation.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Use inferred answers as hypotheses or options, not as finished facts.
-- Complete at least one real user-answer round before drafting PRODUCT.md, unless every required answer is directly discoverable from repo docs.
-- Round 1 should establish register, users/purpose, and desired outcome.
-- Round 2 should establish brand personality or references, anti-references, and accessibility needs.
-
-### Minimum viable interview
-
-Ask enough to complete PRODUCT.md. At minimum, cover register confirmation, users and purpose, brand personality, anti-references, and accessibility needs unless each answer is directly discoverable from repo context. After at least one interview round, you may propose inferred answers, but the user must confirm them before you write PRODUCT.md. Never synthesize PRODUCT.md from the original task prompt alone.
-
-### Register (ask first; it shapes everything below)
-
-Every design task is either **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboards, tools: design SERVES the product).
-
-If Step 2 produced a clear hypothesis, lead with it: *"From the codebase, this looks like a [brand / product] surface. Does that match your intent, or should we treat it differently?"*
-
-If the signal is genuinely split (e.g. a product with a big marketing landing), ask the user directly to clarify what you cannot infer. Ask which register describes the **primary** surface. The register can be overridden per task later, but PRODUCT.md carries one default.
-
-### Users & Purpose
-- Who uses this? What's their context when using it?
-- What job are they trying to get done?
-- For brand: what emotions should the interface evoke? (confidence, delight, calm, urgency)
-- For product: what workflow are they in? What's the primary task on any given screen?
-
-### Brand & Personality
-- How would you describe the brand personality in 3 words?
-- Reference sites or apps that capture the right feel? What specifically about them?
- - For brand, push for real-world references in the right lane (tech-minimal, editorial-magazine, consumer-warm, brutalist-grid, etc.), not generic "modern" adjectives.
- - For product, push for category best-tool references (Linear, Figma, Notion, Raycast, Stripe).
-- What should this explicitly NOT look like? Any anti-references?
-
-### Accessibility & Inclusion
-- Specific accessibility requirements? (WCAG level, known user needs)
-- Considerations for reduced motion, color blindness, or other accommodations?
-
-Skip questions where the answer is already clear. **Do NOT ask about colors, fonts, radii, or visual styling here.** Those belong in DESIGN.md, not PRODUCT.md.
-
-## Step 4: Write PRODUCT.md
-
-Write PRODUCT.md only after the user has confirmed the strategic answers from Step 3. If an inferred answer is uncertain or unconfirmed, ask before writing.
-
-Synthesize into a strategic document:
-
-```markdown
-# Product
-
-## Register
-
-product
-
-## Users
-[Who they are, their context, the job to be done]
-
-## Product Purpose
-[What this product does, why it exists, what success looks like]
-
-## Brand Personality
-[Voice, tone, 3-word personality, emotional goals]
-
-## Anti-references
-[What this should NOT look like. Specific bad-example sites or patterns to avoid.]
-
-## Design Principles
-[3-5 strategic principles derived from the conversation. Principles like "practice what you preach", "show, don't tell", "expert confidence". NOT visual rules like "use OKLCH" or "magenta accent".]
-
-## Accessibility & Inclusion
-[WCAG level, known user needs, considerations]
-```
-
-Register is either `brand` or `product` as a bare value. No prose, no commentary.
-
-Write to `PROJECT_ROOT/PRODUCT.md`. If `.impeccable.md` existed, the loader already renamed it; merge into that content rather than starting from scratch.
-
-## Step 5: Decide on DESIGN.md
-
-Offer `/impeccable document` either way. Two paths:
-
-- **Code exists** (CSS tokens, components, a running site): "I can generate a DESIGN.md that captures your visual system (colors, typography, components) so variants stay on-brand. Want to do that now?"
-- **Pre-implementation** (empty project): "I can seed a starter DESIGN.md from five quick questions about color strategy, type direction, motion energy, and references. You can re-run once there's code, to capture the real tokens. Want to do that now?"
-
-If the user agrees, delegate to `/impeccable document` (it auto-detects scan vs seed). Load its reference and follow that flow.
-
-If the user prefers to skip, mention they can run `/impeccable document` any time later.
-
-## Step 6: Confirm and wrap up
-
-Summarize:
-- Register captured (brand / product)
-- What was written (PRODUCT.md, DESIGN.md, or both)
-- The 3-5 strategic principles from PRODUCT.md that will guide future work
-- If DESIGN.md is pending, remind the user how to generate it later
-
-**Critical: re-run the loader to refresh session context.** After writing PRODUCT.md, run `node .github/skills/impeccable/scripts/load-context.mjs` one final time and let its full JSON output land in conversation. This ensures subsequent commands in this session use the freshly-written PRODUCT.md, not a stale earlier version.
-
-If teach was invoked as a blocker by another impeccable command (e.g. the user ran `/impeccable polish` with no PRODUCT.md), resume that original task now with the fresh context.
-
-Optionally ask the user directly to clarify what you cannot infer. Ask whether they'd like a brief summary of PRODUCT.md appended to .github/copilot-instructions.md for easier agent reference. If yes, append a short **Design Context** pointer section there.
@@ -1,124 +0,0 @@
-Typography carries most of the information on the page. Replace generic defaults (Inter, Roboto, system fallback at flat scale) with type that reflects the brand and scales with intentional contrast.
-
----
-
-## Register
-
-Brand: run the font selection procedure in [brand.md](brand.md). Pairing follows the brand's lane (display serif + sans body for editorial/luxury, one committed sans for tech, etc.). Fluid `clamp()` scale, ≥1.25 ratio between steps.
-
-Product: system fonts and familiar sans stacks are legitimate here. One well-tuned family typically carries the whole UI. Fixed `rem` scale, 1.125–1.2 ratio between more closely-spaced steps.
-
----
-
-## Assess Current Typography
-
-Analyze what's weak or generic about the current type:
-
-1. **Font choices**:
- - Are we using invisible defaults? (Inter, Roboto, Arial, Open Sans, system defaults)
- - Does the font match the brand personality? (A playful brand shouldn't use a corporate typeface)
- - Are there too many font families? (More than 2-3 is almost always a mess)
-
-2. **Hierarchy**:
- - Can you tell headings from body from captions at a glance?
- - Are font sizes too close together? (14px, 15px, 16px = muddy hierarchy)
- - Are weight contrasts strong enough? (Medium vs Regular is barely visible)
-
-3. **Sizing & scale**:
- - Is there a consistent type scale, or are sizes arbitrary?
- - Does body text meet minimum readability? (16px+)
- - Is the sizing strategy appropriate for the context? (Fixed `rem` scales for app UIs; fluid `clamp()` for marketing/content page headings)
-
-4. **Readability**:
- - Are line lengths comfortable? (45-75 characters ideal)
- - Is line-height appropriate for the font and context?
- - Is there enough contrast between text and background?
-
-5. **Consistency**:
- - Are the same elements styled the same way throughout?
- - Are font weights used consistently? (Not bold in one section, semibold in another for the same role)
- - Is letter-spacing intentional or default everywhere?
-
-**CRITICAL**: The goal isn't to make text "fancier." It's to make it clearer, more readable, and more intentional. Good typography is invisible; bad typography is distracting.
-
-## Plan Typography Improvements
-
-Consult the [typography reference](typography.md) for detailed guidance on scales, pairing, and loading strategies.
-
-Create a systematic plan:
-
-- **Font selection**: Do fonts need replacing? What fits the brand/context?
-- **Type scale**: Establish a modular scale (e.g., 1.25 ratio) with clear hierarchy
-- **Weight strategy**: Which weights serve which roles? (Regular for body, Semibold for labels, Bold for headings, or whatever fits)
-- **Spacing**: Line-heights, letter-spacing, and margins between typographic elements
-
-## Improve Typography Systematically
-
-### Font Selection
-
-If fonts need replacing:
-- Choose fonts that reflect the brand personality
-- Pair with genuine contrast (serif + sans, geometric + humanist), or use a single family in multiple weights
-- Ensure web font loading doesn't cause layout shift (`font-display: swap`, metric-matched fallbacks)
-
-### Establish Hierarchy
-
-Build a clear type scale:
-- **5 sizes cover most needs**: caption, secondary, body, subheading, heading
-- **Use a consistent ratio** between levels (1.25, 1.333, or 1.5)
-- **Combine dimensions**: Size + weight + color + space for strong hierarchy. Don't rely on size alone
-- **App UIs**: Use a fixed `rem`-based type scale, optionally adjusted at 1-2 breakpoints. Fluid sizing undermines the spatial predictability that dense, container-based layouts need
-- **Marketing / content pages**: Use fluid sizing via `clamp(min, preferred, max)` for headings and display text. Keep body text fixed
-
-### Fix Readability
-
-- Set `max-width` on text containers using `ch` units (`max-width: 65ch`)
-- Adjust line-height per context: tighter for headings (1.1-1.2), looser for body (1.5-1.7)
-- Increase line-height slightly for light-on-dark text
-- Ensure body text is at least 16px / 1rem
-
-### Refine Details
-
-- Use `tabular-nums` for data tables and numbers that should align
-- Apply proper `letter-spacing`: slightly open for small caps and uppercase, default or tight for large display text
-- Use semantic token names (`--text-body`, `--text-heading`), not value names (`--font-16`)
-- Set `font-kerning: normal` and consider OpenType features where appropriate
-
-### Weight Consistency
-
-- Define clear roles for each weight and stick to them
-- Don't use more than 3-4 weights (Regular, Medium, Semibold, Bold is plenty)
-- Load only the weights you actually use (each weight adds to page load)
-
-**NEVER**:
-- Use more than 2-3 font families
-- Pick sizes arbitrarily; commit to a scale
-- Set body text below 16px
-- Use decorative/display fonts for body text
-- Disable browser zoom (`user-scalable=no`)
-- Use `px` for font sizes; use `rem` to respect user settings
-- Default to Inter/Roboto/Open Sans when personality matters
-- Pair fonts that are similar but not identical (two geometric sans-serifs)
-
-## Verify Typography Improvements
-
-- **Hierarchy**: Can you identify heading vs body vs caption instantly?
-- **Readability**: Is body text comfortable to read in long passages?
-- **Consistency**: Are same-role elements styled identically throughout?
-- **Personality**: Does the typography reflect the brand?
-- **Performance**: Are web fonts loading efficiently without layout shift?
-- **Accessibility**: Does text meet WCAG contrast ratios? Is it zoomable to 200%?
-
-When the type carries the hierarchy on its own, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `scale` param controlling the hierarchy ratio. Express all font sizes in the variant's scoped CSS through `calc(var(--p-scale, 1) * <base>)` or, better, scale the type ramp via `clamp(min, calc(var(--p-scale, 1) * Npx), max)`. Users slide from subdued to commanding.
-
-```json
-{"id":"scale","kind":"range","min":0.85,"max":1.3,"step":0.05,"default":1,"label":"Scale"}
-```
-
-Where the variant riffs on a specific pairing, expose the pairing choice as a `steps` param (e.g. "serif display + sans body" vs. "mono display + sans body" vs. "all-sans"). Each branch routes through `:scope[data-p-pairing="X"]` selectors in scoped CSS.
-
-See `reference/live.md` for the full params contract.
@@ -1,159 +0,0 @@
-# Typography
-
-## Classic Typography Principles
-
-### Vertical Rhythm
-
-Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
-
-### Modular Scale & Hierarchy
-
-The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
-
-**Use fewer sizes with more contrast.** A 5-size system covers most needs:
-
-| Role | Typical Ratio | Use Case |
-|------|---------------|----------|
-| xs | 0.75rem | Captions, legal |
-| sm | 0.875rem | Secondary UI, metadata |
-| base | 1rem | Body text |
-| lg | 1.25-1.5rem | Subheadings, lead text |
-| xl+ | 2-4rem | Headlines, hero text |
-
-Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
-
-### Readability & Measure
-
-Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
-
-**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
-
-**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
-
-## Font Selection & Pairing
-
-The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
-
-### Anti-reflexes worth defending against
-
-- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
-- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
-- A children's product does NOT need a rounded display font. Kids' books use real type.
-- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
-
-**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
-
-### Pairing Principles
-
-**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
-
-When pairing, contrast on multiple axes:
-- Serif + Sans (structure contrast)
-- Geometric + Humanist (personality contrast)
-- Condensed display + Wide body (proportion contrast)
-
-**Never pair fonts that are similar but not identical** (e.g., two geometric sans-serifs). They create visual tension without clear hierarchy.
-
-### Web Font Loading
-
-The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
-
-```css
-/* 1. Use font-display: swap for visibility */
-@font-face {
- font-family: 'CustomFont';
- src: url('font.woff2') format('woff2');
- font-display: swap;
-}
-
-/* 2. Match fallback metrics to minimize shift */
-@font-face {
- font-family: 'CustomFont-Fallback';
- src: local('Arial');
- size-adjust: 105%; /* Scale to match x-height */
- ascent-override: 90%; /* Match ascender height */
- descent-override: 20%; /* Match descender depth */
- line-gap-override: 10%; /* Match line spacing */
-}
-
-body {
- font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
-}
-```
-
-Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
-
-**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
-
-**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
-
-**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
-
-## Modern Web Typography
-
-### Fluid Type
-
-Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
-
-**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
-
-**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
-
-**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
-
-**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
-
-### OpenType Features
-
-Most developers don't know these exist. Use them for polish:
-
-```css
-/* Tabular numbers for data alignment */
-.data-table { font-variant-numeric: tabular-nums; }
-
-/* Proper fractions */
-.recipe-amount { font-variant-numeric: diagonal-fractions; }
-
-/* Small caps for abbreviations */
-abbr { font-variant-caps: all-small-caps; }
-
-/* Disable ligatures in code */
-code { font-variant-ligatures: none; }
-
-/* Enable kerning (usually on by default, but be explicit) */
-body { font-kerning: normal; }
-```
-
-Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
-
-### Rendering polish
-
-```css
-/* Even out heading line lengths (browser picks better break points) */
-h1, h2, h3 { text-wrap: balance; }
-
-/* Reduce orphans and ragged endings in long prose */
-article p { text-wrap: pretty; }
-
-/* Variable fonts: pick the right optical-size master automatically */
-body { font-optical-sizing: auto; }
-```
-
-**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
-
-## Typography System Architecture
-
-Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
-
-## Accessibility Considerations
-
-Beyond contrast ratios (which are well-documented), consider:
-
-- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
-- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
-- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
-- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
-
----
-
-**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
@@ -1,107 +0,0 @@
-# UX Writing
-
-## The Button Label Problem
-
-**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
-
-| Bad | Good | Why |
-|-----|------|-----|
-| OK | Save changes | Says what will happen |
-| Submit | Create account | Outcome-focused |
-| Yes | Delete message | Confirms the action |
-| Cancel | Keep editing | Clarifies what "cancel" means |
-| Click here | Download PDF | Describes the destination |
-
-**For destructive actions**, name the destruction:
-- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
-- "Delete 5 items" not "Delete selected" (show the count)
-
-## Error Messages: The Formula
-
-Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
-
-### Error Message Templates
-
-| Situation | Template |
-|-----------|----------|
-| **Format error** | "[Field] needs to be [format]. Example: [example]" |
-| **Missing required** | "Please enter [what's missing]" |
-| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
-| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
-| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
-
-### Don't Blame the User
-
-Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
-
-## Empty States Are Opportunities
-
-Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
-
-## Voice vs Tone
-
-**Voice** is your brand's personality, consistent everywhere.
-**Tone** adapts to the moment.
-
-| Moment | Tone Shift |
-|--------|------------|
-| Success | Celebratory, brief: "Done! Your changes are live." |
-| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
-| Loading | Reassuring: "Saving your work..." |
-| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
-
-**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
-
-## Writing for Accessibility
-
-**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
-
-## Writing for Translation
-
-### Plan for Expansion
-
-German text is ~30% longer than English. Allocate space:
-
-| Language | Expansion |
-|----------|-----------|
-| German | +30% |
-| French | +20% |
-| Finnish | +30-40% |
-| Chinese | -30% (fewer chars, but same width) |
-
-### Translation-Friendly Patterns
-
-Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
-
-## Consistency: The Terminology Problem
-
-Pick one term and stick with it:
-
-| Inconsistent | Consistent |
-|--------------|------------|
-| Delete / Remove / Trash | Delete |
-| Settings / Preferences / Options | Settings |
-| Sign in / Log in / Enter | Sign in |
-| Create / Add / New | Create |
-
-Build a terminology glossary and enforce it. Variety creates confusion.
-
-## Avoid Redundant Copy
-
-If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
-
-## Loading States
-
-Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
-
-## Confirmation Dialogs: Use Sparingly
-
-Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
-
-## Form Instructions
-
-Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
-
----
-
-**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
@@ -1,284 +0,0 @@
-#!/usr/bin/env node
-/**
- * Cleans up deprecated Impeccable skill files, symlinks, and
- * skills-lock.json entries left over from previous versions.
- *
- * Safe to run repeatedly -- it is a no-op when nothing needs cleaning.
- *
- * Usage (from the project root):
- * node {{scripts_path}}/cleanup-deprecated.mjs
- *
- * What it does:
- * 1. Finds every harness-specific skills directory (.claude/skills,
- * .cursor/skills, .agents/skills, etc.).
- * 2. For each deprecated skill name (with and without i- prefix),
- * checks if the directory exists and its SKILL.md mentions
- * "impeccable" (to avoid deleting unrelated user skills).
- * 3. Deletes confirmed matches (files, directories, or symlinks).
- * 4. Removes the corresponding entries from skills-lock.json.
- */
-
-import { existsSync, readFileSync, writeFileSync, rmSync, readdirSync, statSync, lstatSync, unlinkSync } from 'node:fs';
-import { join, resolve } from 'node:path';
-
-// Skills that were renamed, merged, or folded in v2.0, v2.1, and v3.0.
-const DEPRECATED_NAMES = [
- // v2.0 renames
- 'frontend-design', // renamed to impeccable
- 'teach-impeccable', // folded into /impeccable teach
- // v2.1 merges
- 'arrange', // renamed to layout
- 'normalize', // merged into polish
- 'onboard', // merged into harden
- 'extract', // merged into /impeccable extract
- // v3.0 consolidation: all standalone skills -> /impeccable sub-commands
- 'adapt',
- 'animate',
- 'audit',
- 'bolder',
- 'clarify',
- 'colorize',
- 'critique',
- 'delight',
- 'distill',
- 'harden',
- 'layout',
- 'optimize',
- 'overdrive',
- 'polish',
- 'quieter',
- 'shape',
- 'typeset',
-];
-
-// All known harness directories that may contain a skills/ subfolder.
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Per-skill fingerprints for SKILL.md bodies that never mentioned
-// "impeccable" in their v2.x source. Used as a last-resort match
-// when no skills-lock.json exists and the word heuristic fails.
-// The strings are lifted verbatim from the v2.x frontmatter
-// descriptions, so collisions with hand-written user skills are
-// vanishingly unlikely.
-const SKILL_FINGERPRINTS = {
- harden: 'Make interfaces production-ready: error handling, empty states',
- optimize: 'Diagnoses and fixes UI performance across loading speed',
-};
-
-/**
- * Walk up from startDir until we find a directory that looks like a
- * project root (has package.json, .git, or skills-lock.json).
- */
-export function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- const { root } = { root: '/' };
- while (dir !== root) {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Load skills-lock.json from the project root, or null if missing/unreadable.
- */
-export function loadLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return null;
- try {
- return JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return null;
- }
-}
-
-/**
- * Check whether a skill directory belongs to Impeccable. Three layered
- * signals, in order of reliability:
- * 1. Lock source equals "pbakaus/impeccable" (authoritative).
- * 2. SKILL.md body contains the word "impeccable".
- * 3. SKILL.md body contains a per-skill fingerprint (for harden and
- * optimize, whose v2.x SKILL.md never mentioned the pack name).
- */
-export function isImpeccableSkill(skillDir, { skillName, lock } = {}) {
- // 1. Authoritative: the lock file claims this skill is ours.
- if (skillName && lock?.skills?.[skillName]?.source === 'pbakaus/impeccable') {
- return true;
- }
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) return false;
- let content;
- try {
- content = readFileSync(skillMd, 'utf-8');
- } catch {
- return false;
- }
- // 2. Word-level content heuristic.
- if (/impeccable/i.test(content)) return true;
- // 3. Per-skill fingerprint for old skills that never mentioned the pack.
- // Strip the i- prefix so both `harden` and `i-harden` resolve to the
- // same fingerprint entry.
- const unprefixed = skillName?.startsWith('i-') ? skillName.slice(2) : skillName;
- const fingerprint = unprefixed && SKILL_FINGERPRINTS[unprefixed];
- if (fingerprint && content.includes(fingerprint)) return true;
- return false;
-}
-
-/**
- * Build the full list of names to check: each deprecated name, plus
- * its i-prefixed variant.
- */
-export function buildTargetNames() {
- const names = [];
- for (const name of DEPRECATED_NAMES) {
- names.push(name);
- names.push(`i-${name}`);
- }
- return names;
-}
-
-/**
- * Find every skills directory across all harness dirs in the project.
- * Returns absolute paths that exist on disk.
- */
-export function findSkillsDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const candidate = join(projectRoot, harness, 'skills');
- if (existsSync(candidate)) {
- dirs.push(candidate);
- }
- }
- return dirs;
-}
-
-/**
- * Remove deprecated skill directories/symlinks from all harness dirs.
- * Reads skills-lock.json so the authoritative "source" field can
- * drive deletion even when SKILL.md never mentions impeccable.
- * Returns an array of paths that were deleted.
- */
-export function removeDeprecatedSkills(projectRoot, lock) {
- if (lock === undefined) lock = loadLock(projectRoot);
- const targets = buildTargetNames();
- const skillsDirs = findSkillsDirs(projectRoot);
- const deleted = [];
-
- for (const skillsDir of skillsDirs) {
- for (const name of targets) {
- const skillPath = join(skillsDir, name);
-
- // Use lstat to detect symlinks (existsSync follows symlinks and
- // returns false for dangling ones).
- let stat;
- try {
- stat = lstatSync(skillPath);
- } catch {
- continue; // does not exist at all
- }
-
- if (stat.isSymbolicLink()) {
- // Symlink: check the target if it's alive, otherwise treat
- // dangling symlinks to deprecated names as safe to remove.
- const targetAlive = existsSync(skillPath);
- const isMatch = targetAlive
- ? isImpeccableSkill(skillPath, { skillName: name, lock })
- : true;
- if (isMatch) {
- unlinkSync(skillPath);
- deleted.push(skillPath);
- }
- continue;
- }
-
- // Regular directory -- verify it belongs to impeccable
- if (isImpeccableSkill(skillPath, { skillName: name, lock })) {
- rmSync(skillPath, { recursive: true, force: true });
- deleted.push(skillPath);
- }
- }
- }
-
- return deleted;
-}
-
-/**
- * Remove deprecated entries from skills-lock.json.
- * Only removes entries whose source is "pbakaus/impeccable".
- * Returns the list of removed skill names.
- */
-export function cleanSkillsLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return [];
-
- let lock;
- try {
- lock = JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return [];
- }
-
- if (!lock.skills || typeof lock.skills !== 'object') return [];
-
- const targets = buildTargetNames();
- const removed = [];
-
- for (const name of targets) {
- const entry = lock.skills[name];
- if (!entry) continue;
- // Only remove if it belongs to impeccable
- if (entry.source === 'pbakaus/impeccable') {
- delete lock.skills[name];
- removed.push(name);
- }
- }
-
- if (removed.length > 0) {
- writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\n', 'utf-8');
- }
-
- return removed;
-}
-
-/**
- * Run the full cleanup. Returns a summary object.
- *
- * Order matters: read the lock and delete directories first, then
- * strip lock entries. Otherwise the authoritative signal is gone by
- * the time directory deletion runs.
- */
-export function cleanup(projectRoot) {
- const root = projectRoot || findProjectRoot();
- const lock = loadLock(root);
- const deletedPaths = removeDeprecatedSkills(root, lock);
- const removedLockEntries = cleanSkillsLock(root);
- return { deletedPaths, removedLockEntries, projectRoot: root };
-}
-
-// CLI entry point
-if (process.argv[1] && resolve(process.argv[1]) === resolve(new URL(import.meta.url).pathname)) {
- const result = cleanup();
- if (result.deletedPaths.length === 0 && result.removedLockEntries.length === 0) {
- console.log('No deprecated Impeccable skills found. Nothing to clean up.');
- } else {
- if (result.deletedPaths.length > 0) {
- console.log(`Removed ${result.deletedPaths.length} deprecated skill(s):`);
- for (const p of result.deletedPaths) console.log(` - ${p}`);
- }
- if (result.removedLockEntries.length > 0) {
- console.log(`Cleaned ${result.removedLockEntries.length} entry/entries from skills-lock.json:`);
- for (const name of result.removedLockEntries) console.log(` - ${name}`);
- }
- }
-}
@@ -1,94 +0,0 @@
-{
- "craft": {
- "description": "Full confirmed-brief-then-build flow. Runs multi-round shape discovery first, resolves visual probe and north-star mock gates when available, then builds and visually iterates. Use when building a new feature end-to-end.",
- "argumentHint": "[feature description]"
- },
- "teach": {
- "description": "Gathers design context for a project. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles) and, when code exists to analyze, DESIGN.md (visual: colors, typography, components). Every other command reads these files before doing work. Use once per project.",
- "argumentHint": ""
- },
- "document": {
- "description": "Generate a DESIGN.md file that captures the current visual design system. Auto-extracts colors, typography, spacing, radii, and component patterns from the codebase, then asks the user to confirm descriptive language for atmosphere and color character. Follows the Google Stitch DESIGN.md format so the file is tool-compatible. Use when you need a visual design spec an AI agent can follow to stay on-brand.",
- "argumentHint": ""
- },
- "extract": {
- "description": "Pull reusable patterns, components, and design tokens into the design system. Identifies repeated patterns and consolidates them. Use when you have drift across the codebase and want to bring things back to a consistent system.",
- "argumentHint": "[target]"
- },
- "live": {
- "description": "Interactive live variant mode. Select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via HMR. Requires a running dev server. Use when you want to visually experiment with design alternatives in real time.",
- "argumentHint": ""
- },
- "adapt": {
- "description": "Adapt designs to work across different screen sizes, devices, contexts, or platforms. Implements breakpoints, fluid layouts, and touch targets. Use when the user mentions responsive design, mobile layouts, breakpoints, viewport adaptation, or cross-device compatibility.",
- "argumentHint": "[target] [context (mobile, tablet, print...)]"
- },
- "animate": {
- "description": "Review a feature and enhance it with purposeful animations, micro-interactions, and motion effects that improve usability and delight. Use when the user mentions adding animation, transitions, micro-interactions, motion design, hover effects, or making the UI feel more alive.",
- "argumentHint": "[target]"
- },
- "audit": {
- "description": "Run technical quality checks across accessibility, performance, theming, responsive design, and anti-patterns. Generates a scored report with P0-P3 severity ratings and actionable plan. Use when the user wants an accessibility check, performance audit, or technical quality review.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "bolder": {
- "description": "Amplify safe or boring designs to make them more visually interesting and stimulating. Increases impact while maintaining usability. Use when the user says the design looks bland, generic, too safe, lacks personality, or wants more visual impact and character.",
- "argumentHint": "[target]"
- },
- "clarify": {
- "description": "Improve unclear UX copy, error messages, microcopy, labels, and instructions to make interfaces easier to understand. Use when the user mentions confusing text, unclear labels, bad error messages, hard-to-follow instructions, or wanting better UX writing.",
- "argumentHint": "[target]"
- },
- "colorize": {
- "description": "Add strategic color to features that are too monochromatic or lack visual interest, making interfaces more engaging and expressive. Use when the user mentions the design looking gray, dull, lacking warmth, needing more color, or wanting a more vibrant or expressive palette.",
- "argumentHint": "[target]"
- },
- "critique": {
- "description": "Evaluate design from a UX perspective, assessing visual hierarchy, information architecture, emotional resonance, cognitive load, and overall quality with quantitative scoring, persona-based testing, automated anti-pattern detection, and actionable feedback. Use when the user asks to review, critique, evaluate, or give feedback on a design or component.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "delight": {
- "description": "Add moments of joy, personality, and unexpected touches that make interfaces memorable and enjoyable to use. Elevates functional to delightful. Use when the user asks to add polish, personality, animations, micro-interactions, delight, or make an interface feel fun or memorable.",
- "argumentHint": "[target]"
- },
- "distill": {
- "description": "Strip designs to their essence by removing unnecessary complexity. Great design is simple, powerful, and clean. Use when the user asks to simplify, declutter, reduce noise, remove elements, or make a UI cleaner and more focused.",
- "argumentHint": "[target]"
- },
- "harden": {
- "description": "Make interfaces production-ready: error handling, i18n, text overflow, edge case management, and resilience under real-world data. Use when the user asks to harden, make production-ready, handle edge cases, add error states, or fix overflow and i18n issues.",
- "argumentHint": "[target]"
- },
- "onboard": {
- "description": "Design onboarding flows, first-run experiences, and empty states that guide new users to value. Covers welcome screens, account setup, progressive disclosure, contextual tooltips, feature announcements, and activation moments. Use when the user mentions onboarding, first-time users, empty states, activation, getting started, new user flows, or the aha moment.",
- "argumentHint": "[target]"
- },
- "layout": {
- "description": "Improve layout, spacing, and visual rhythm. Fixes monotonous grids, inconsistent spacing, and weak visual hierarchy. Use when the user mentions layout feeling off, spacing issues, visual hierarchy, crowded UI, alignment problems, or wanting better composition.",
- "argumentHint": "[target]"
- },
- "optimize": {
- "description": "Diagnoses and fixes UI performance across loading speed, rendering, animations, images, and bundle size. Use when the user mentions slow, laggy, janky, performance, bundle size, load time, or wants a faster, smoother experience.",
- "argumentHint": "[target]"
- },
- "overdrive": {
- "description": "Pushes interfaces past conventional limits with technically ambitious implementations — shaders, spring physics, scroll-driven reveals, 60fps animations. Use when the user wants to wow, impress, go all-out, or make something that feels extraordinary.",
- "argumentHint": "[target]"
- },
- "polish": {
- "description": "Performs a final quality pass fixing alignment, spacing, consistency, and micro-detail issues before shipping. Use when the user mentions polish, finishing touches, pre-launch review, something looks off, or wants to go from good to great.",
- "argumentHint": "[target]"
- },
- "quieter": {
- "description": "Tones down visually aggressive or overstimulating designs, reducing intensity while preserving quality. Use when the user mentions too bold, too loud, overwhelming, aggressive, garish, or wants a calmer, more refined aesthetic.",
- "argumentHint": "[target]"
- },
- "shape": {
- "description": "Plan UX and UI before code. Runs a required multi-round discovery interview, uses visual probes when available, and produces a user-confirmed design brief for implementation.",
- "argumentHint": "[feature to shape]"
- },
- "typeset": {
- "description": "Improves typography by fixing font choices, hierarchy, sizing, weight, and readability so text feels intentional. Use when the user mentions fonts, type, readability, text hierarchy, sizing looks off, or wants more polished, intentional typography.",
- "argumentHint": "[target]"
- }
-}
@@ -1,242 +0,0 @@
-#!/usr/bin/env node
-/**
- * Critique persistence helper.
- *
- * Each run of /impeccable critique writes a per-target snapshot to
- * .impeccable/critique/<timestamp>__<slug>.md
- * with a small YAML frontmatter carrying the score + P0/P1 counts.
- *
- * /impeccable polish reads the latest matching snapshot at start as its
- * fix backlog. No other skill auto-reads critique output.
- *
- * The slug is derived mechanically from the *resolved* primary artifact
- * (file path or URL), never from the user's natural-language phrasing.
- * Slug stability across runs is what lets the trend display work.
- *
- * CLI entry points (called from skill instructions):
- * node critique-storage.mjs slug <resolved-target>
- * node critique-storage.mjs write <slug> <snapshot-body-file>
- * node critique-storage.mjs latest <slug>
- * node critique-storage.mjs trend <slug> [limit]
- *
- * Note: there is intentionally no `ignore` subcommand. ignore.md is a plain
- * markdown file; the model reads it directly with its file-read tool. This
- * helper only exists for operations the model can't trivially do inline
- * (normalizing paths, generating filenames, globbing + parsing frontmatter).
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath, pathToFileURL } from 'node:url';
-import { getCritiqueDir } from './impeccable-paths.mjs';
-
-const SLUG_MAX = 50;
-
-/**
- * Mechanically derive a slug from a resolved target. Returns null if the
- * input doesn't look like a stable identifier (empty, project root, etc).
- *
- * Accepts file paths and URLs. The model resolves "the homepage" to a
- * concrete artifact before calling this — we never slug a natural-language
- * phrase.
- */
-export function slugFromTarget(resolved, { cwd = process.cwd() } = {}) {
- if (!resolved || typeof resolved !== 'string') return null;
- const trimmed = resolved.trim();
- if (!trimmed) return null;
-
- // URL
- if (/^https?:\/\//i.test(trimmed)) {
- let url;
- try { url = new URL(trimmed); } catch { return null; }
- const hostPath = `${url.hostname}${url.pathname}`;
- return kebab(hostPath);
- }
-
- // File path. Make it project-relative so two devs critiquing the same
- // checkout get the same slug regardless of where their repo is cloned.
- const abs = path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- let rel = path.relative(cwd, abs);
- // If the target is outside cwd, fall back to the basename so we still
- // produce a stable slug (vs the absolute path, which would include
- // home dirs / usernames).
- if (rel.startsWith('..') || path.isAbsolute(rel)) {
- rel = path.basename(abs);
- }
- if (!rel || rel === '.' || rel === '') return null;
- return kebab(rel);
-}
-
-function kebab(s) {
- const slug = s
- .toLowerCase()
- .replace(/[/\\.]+/g, '-')
- .replace(/[^a-z0-9-]+/g, '-')
- .replace(/-+/g, '-')
- .replace(/^-|-$/g, '');
- if (!slug) return null;
- // Cap from the tail — the tail (filename) is more identifying than the
- // top-level directory.
- return slug.length <= SLUG_MAX ? slug : slug.slice(slug.length - SLUG_MAX).replace(/^-/, '');
-}
-
-/**
- * Filename-safe UTC ISO timestamp: hyphens for separators, trailing Z.
- * Plain colons aren't allowed on Windows filesystems.
- */
-export function nowFilenameStamp(date = new Date()) {
- const iso = date.toISOString(); // 2026-05-12T18:30:00.123Z
- return iso.replace(/[:.]/g, '-').replace(/-\d+Z$/, 'Z');
-}
-
-/**
- * Write a snapshot for `slug`. `meta` carries the small structured frontmatter
- * keys read back by readTrend(). `body` is the human-readable critique
- * report (everything below the frontmatter).
- *
- * Returns the absolute path written.
- */
-export function writeSnapshot({ slug, meta, body, cwd = process.cwd(), now = new Date() }) {
- if (!slug) throw new Error('writeSnapshot requires a slug');
- const dir = getCritiqueDir(cwd);
- fs.mkdirSync(dir, { recursive: true });
- const timestamp = nowFilenameStamp(now);
- const filePath = path.join(dir, `${timestamp}__${slug}.md`);
- // Spread `meta` first so internally computed `timestamp` and `slug`
- // always win. Otherwise a caller-supplied meta blob (parsed from the
- // IMPECCABLE_CRITIQUE_META env var) could clobber them, leaving the
- // filename in disagreement with its frontmatter and corrupting trends.
- const front = serializeFrontmatter({ ...meta, timestamp, slug });
- fs.writeFileSync(filePath, `${front}\n${body.trim()}\n`, 'utf-8');
- return filePath;
-}
-
-function serializeFrontmatter(obj) {
- const lines = ['---'];
- for (const [key, value] of Object.entries(obj)) {
- if (value === undefined || value === null) continue;
- const str = typeof value === 'string' ? value : String(value);
- // Quote strings that contain : or # to keep parsing simple.
- const needsQuotes = typeof value === 'string' && /[:#]/.test(str);
- lines.push(`${key}: ${needsQuotes ? JSON.stringify(str) : str}`);
- }
- lines.push('---');
- return lines.join('\n');
-}
-
-function parseFrontmatter(text) {
- const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
- if (!match) return {};
- const out = {};
- for (const line of match[1].split(/\r?\n/)) {
- const colon = line.indexOf(':');
- if (colon < 0) continue;
- const key = line.slice(0, colon).trim();
- let value = line.slice(colon + 1).trim();
- if (/^".*"$/.test(value)) {
- try { value = JSON.parse(value); } catch { /* leave as-is */ }
- } else if (/^-?\d+$/.test(value)) {
- value = Number(value);
- }
- out[key] = value;
- }
- return out;
-}
-
-/**
- * Return all snapshot files for `slug`, sorted oldest → newest.
- */
-function listSnapshotsForSlug(slug, cwd) {
- const dir = getCritiqueDir(cwd);
- if (!fs.existsSync(dir)) return [];
- const suffix = `__${slug}.md`;
- return fs.readdirSync(dir)
- .filter((f) => f.endsWith(suffix))
- .sort()
- .map((f) => path.join(dir, f));
-}
-
-/**
- * Return the most recent snapshot for `slug`, or null. Polish reads this
- * to find its fix backlog when the slug matches.
- */
-export function readLatestSnapshot(slug, { cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- if (!all.length) return null;
- const latest = all[all.length - 1];
- const body = fs.readFileSync(latest, 'utf-8');
- return { path: latest, body, meta: parseFrontmatter(body) };
-}
-
-/**
- * Return the last `limit` snapshots' frontmatter, oldest → newest.
- * Critique appends a one-line trend to its output using this.
- */
-export function readTrend(slug, { limit = 5, cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- const slice = all.slice(-limit);
- return slice.map((file) => parseFrontmatter(fs.readFileSync(file, 'utf-8')));
-}
-
-// ---- CLI ---------------------------------------------------------------
-
-function main(argv) {
- const [cmd, ...args] = argv;
- switch (cmd) {
- case 'slug': {
- const slug = slugFromTarget(args[0]);
- if (!slug) { process.stderr.write('no stable slug for input\n'); process.exit(1); }
- process.stdout.write(`${slug}\n`);
- return;
- }
- case 'write': {
- const [slug, bodyFile] = args;
- if (!slug || !bodyFile) { process.stderr.write('usage: write <slug> <body-file>\n'); process.exit(1); }
- const raw = fs.readFileSync(bodyFile, 'utf-8');
- // The body file may be a full report. The caller passes the meta as
- // a JSON object on stdin if it wants structured frontmatter; otherwise
- // we write with minimal metadata.
- let meta = {};
- const metaArg = process.env.IMPECCABLE_CRITIQUE_META;
- if (metaArg) {
- try { meta = JSON.parse(metaArg); } catch { /* ignore */ }
- }
- const out = writeSnapshot({ slug, meta, body: raw });
- process.stdout.write(`${out}\n`);
- return;
- }
- case 'latest': {
- const latest = readLatestSnapshot(args[0]);
- if (!latest) { process.exit(2); }
- process.stdout.write(latest.body);
- return;
- }
- case 'trend': {
- const rows = readTrend(args[0], { limit: args[1] ? Number(args[1]) : 5 });
- process.stdout.write(JSON.stringify(rows, null, 2) + '\n');
- return;
- }
- default:
- process.stderr.write('usage: critique-storage.mjs <slug|write|latest|trend> [args]\n');
- process.exit(1);
- }
-}
-
-function isMainModule() {
- if (!process.argv[1]) return false;
- try {
- return fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1]);
- } catch {
- // pathToFileURL normalizes Windows paths; keep it as a fallback for any
- // environment where realpath is unavailable.
- return import.meta.url === pathToFileURL(process.argv[1]).href;
- }
-}
-
-// Why the realpath check: generated skills are often reached through symlinked
-// harness directories (for example a demo repo's `.agents` -> source `.agents`).
-// Node resolves import.meta.url to the real file, while process.argv[1] keeps
-// the symlink path. Comparing canonical paths prevents a silent exit-0 no-op.
-if (isMainModule()) {
- main(process.argv.slice(2));
-}
@@ -1,820 +0,0 @@
-// Parse a DESIGN.md (Stitch-spec format) into a structured JSON model that
-// the live-mode design-system panel can render. Deterministic, dependency-free.
-//
-// Two-layer: YAML frontmatter (machine-readable tokens) + markdown body
-// (prose with six canonical H2 sections). When frontmatter is present, it's
-// exposed on `model.frontmatter` alongside the prose-scraped sections;
-// consumers can prefer frontmatter values and fall back to prose.
-
-const CANONICAL_SECTIONS = [
- 'Overview',
- 'Colors',
- 'Typography',
- 'Elevation',
- 'Components',
- "Do's and Don'ts",
-];
-
-// ---------- Frontmatter (Stitch YAML subset) ----------
-
-function parseFrontmatter(md) {
- const lines = md.split(/\r?\n/);
- if (lines[0]?.trim() !== '---') return { frontmatter: null, body: md };
-
- let end = -1;
- for (let i = 1; i < lines.length; i++) {
- if (lines[i].trim() === '---') { end = i; break; }
- }
- if (end === -1) return { frontmatter: null, body: md };
-
- const yaml = lines.slice(1, end).join('\n');
- const body = lines.slice(end + 1).join('\n');
- try {
- return { frontmatter: parseYamlSubset(yaml), body };
- } catch {
- return { frontmatter: null, body: md };
- }
-}
-
-// Minimal YAML reader for the Stitch frontmatter subset: scalar maps with
-// one level of nested objects (typography roles, components). Indent-based,
-// 2-space convention. No arrays, no anchors, no multi-line scalars — Stitch's
-// schema doesn't need them and accepting them would require a real YAML
-// dependency we don't want to vendor.
-function parseYamlSubset(yaml) {
- const lines = yaml.split(/\r?\n/);
- const root = {};
- const stack = [{ indent: -1, obj: root }];
-
- for (const raw of lines) {
- // Skip blanks and line-only comments. Don't strip inline comments:
- // unquoted hex values start with `#` and can't be safely distinguished
- // from a comment after whitespace.
- if (!raw.trim() || /^\s*#/.test(raw)) continue;
-
- const indent = raw.match(/^\s*/)[0].length;
- const content = raw.slice(indent);
-
- const colonIdx = findTopLevelColon(content);
- if (colonIdx === -1) continue;
-
- while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
- stack.pop();
- }
-
- const key = content.slice(0, colonIdx).trim();
- const rest = content.slice(colonIdx + 1).trim();
- const parent = stack[stack.length - 1].obj;
-
- if (rest === '') {
- const obj = {};
- parent[key] = obj;
- stack.push({ indent, obj });
- } else {
- parent[key] = parseScalar(rest);
- }
- }
-
- return root;
-}
-
-function findTopLevelColon(s) {
- let inQuote = null;
- for (let i = 0; i < s.length; i++) {
- const ch = s[i];
- if (inQuote) {
- if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
- } else if (ch === '"' || ch === "'") {
- inQuote = ch;
- } else if (ch === ':') {
- return i;
- }
- }
- return -1;
-}
-
-function parseScalar(raw) {
- const s = raw.trim();
- if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
- return s.slice(1, -1);
- }
- if (s === 'true') return true;
- if (s === 'false') return false;
- if (s === 'null' || s === '~') return null;
- if (/^-?\d+$/.test(s)) return Number(s);
- if (/^-?\d*\.\d+$/.test(s)) return Number(s);
- return s;
-}
-
-const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
-const OKLCH_RE = /oklch\([^)]+\)/gi;
-const RGBA_RE = /rgba?\([^)]+\)/gi;
-const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
-const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
-
-// ---------- Section splitting ----------
-
-function splitSections(md) {
- const lines = md.split(/\r?\n/);
- let title = null;
- const sections = {};
- let current = null;
-
- for (const raw of lines) {
- const line = raw.trimEnd();
-
- if (!title && line.startsWith('# ') && !line.startsWith('## ')) {
- title = line.replace(/^#\s+/, '').trim();
- continue;
- }
-
- const h2 = line.match(/^##\s+(?:\d+\.\s*)?([^:\n]+?)(?::\s*(.+))?$/);
- if (h2) {
- const rawName = normalizeApostrophes(h2[1].trim());
- const subtitle = h2[2] ? h2[2].trim() : null;
- const canonical = matchCanonicalSection(rawName);
- if (canonical) {
- current = { name: canonical, subtitle, lines: [] };
- sections[canonical] = current;
- continue;
- }
- // non-canonical H2 — ignore but stop feeding into current
- current = null;
- continue;
- }
-
- if (current) current.lines.push(raw);
- }
-
- return { title, sections };
-}
-
-function normalizeApostrophes(s) {
- return s.replace(/[\u2018\u2019]/g, "'");
-}
-
-function matchCanonicalSection(name) {
- const normalized = normalizeApostrophes(name).toLowerCase();
- // Exact match first
- for (const c of CANONICAL_SECTIONS) {
- if (normalizeApostrophes(c).toLowerCase() === normalized) return c;
- }
- // Keyword-contained match: "Overview & Creative North Star" -> "Overview",
- // "Elevation & Depth" -> "Elevation", etc.
- for (const c of CANONICAL_SECTIONS) {
- const key = normalizeApostrophes(c).toLowerCase();
- const pattern = new RegExp(`\\b${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
- if (pattern.test(normalized)) return c;
- }
- return null;
-}
-
-// ---------- Subsection splitting (inside a canonical section) ----------
-
-function splitSubsections(lines) {
- const subs = [];
- let current = { name: null, lines: [] };
- subs.push(current);
-
- for (const raw of lines) {
- const h3 = raw.match(/^###\s+(.+?)\s*$/);
- if (h3) {
- current = { name: h3[1].trim(), lines: [] };
- subs.push(current);
- continue;
- }
- current.lines.push(raw);
- }
-
- return subs;
-}
-
-// ---------- Generic helpers ----------
-
-function collectParagraphs(lines) {
- const paragraphs = [];
- let buf = [];
- const flush = () => {
- if (buf.length) {
- paragraphs.push(buf.join(' ').trim());
- buf = [];
- }
- };
- for (const raw of lines) {
- const trimmed = raw.trim();
- if (trimmed === '') { flush(); continue; }
- // Horizontal rules (---, ***) and headings/bullets end a paragraph.
- if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { flush(); continue; }
- if (raw.startsWith('#') || raw.match(/^[-*]\s/)) { flush(); continue; }
- buf.push(trimmed);
- }
- flush();
- return paragraphs.filter(Boolean);
-}
-
-function collectBullets(lines) {
- const bullets = [];
- let current = null;
- for (const raw of lines) {
- const m = raw.match(/^\s*[-*]\s+(.+)$/);
- if (m) {
- if (current) bullets.push(current);
- current = m[1];
- continue;
- }
- // continuation of a bullet (indented line)
- if (current && raw.match(/^\s{2,}\S/)) {
- current += ' ' + raw.trim();
- continue;
- }
- // blank line ends a bullet
- if (raw.trim() === '' && current) {
- bullets.push(current);
- current = null;
- }
- }
- if (current) bullets.push(current);
- return bullets;
-}
-
-function stripBold(s) {
- return s.replace(/\*\*(.+?)\*\*/g, '$1');
-}
-
-function extractNamedRules(lines) {
- const rules = [];
- const seen = new Set();
-
- // Style A (Impeccable): "**The X Rule.** body body body" — can span lines.
- const joined = lines.join('\n');
- const inlineStart = /\*\*(The [^*]+?Rule)\.\*\*/g;
- const inlineMatches = [];
- let m;
- while ((m = inlineStart.exec(joined)) !== null) {
- inlineMatches.push({ name: m[1], start: m.index, end: inlineStart.lastIndex });
- }
- for (let i = 0; i < inlineMatches.length; i++) {
- const mm = inlineMatches[i];
- const bodyEnd = i + 1 < inlineMatches.length ? inlineMatches[i + 1].start : joined.length;
- const body = joined
- .slice(mm.end, bodyEnd)
- .replace(/\n##[^\n]*$/s, '')
- .replace(/\n###[^\n]*$/s, '')
- .trim();
- const name = stripBold(mm.name).trim();
- seen.add(name.toLowerCase());
- rules.push({ name, body: stripBold(body) });
- }
-
- // Style B (Stitch): `### The "X" Rule` or `### The X Fallback`, body is the
- // bullets/paragraphs until the next heading. Accept Rule / Fallback / Principle.
- for (let i = 0; i < lines.length; i++) {
- const h3 = lines[i].match(/^###\s+(.+?)\s*$/);
- if (!h3) continue;
- const headerName = stripBold(h3[1]).replace(/["“”]/g, '').trim();
- if (!/^The\b.*\b(Rule|Fallback|Principle)\b/i.test(headerName)) continue;
- if (seen.has(headerName.toLowerCase())) continue;
-
- const bodyLines = [];
- for (let j = i + 1; j < lines.length; j++) {
- if (/^##\s|^###\s/.test(lines[j])) break;
- bodyLines.push(lines[j]);
- }
- const body = stripBold(bodyLines.join('\n').replace(/\n+/g, ' ')).trim();
- if (body) {
- seen.add(headerName.toLowerCase());
- rules.push({ name: headerName, body });
- }
- }
-
- // Style C (Stitch bullet form): "* **The Layering Principle:** body"
- // Colon/period lives inside the bold, so match "**...**" then inspect.
- for (const b of collectBullets(lines)) {
- const mm = b.match(/^\*\*([^*]+?)\*\*\s*(.+)$/);
- if (!mm) continue;
- const nameRaw = mm[1].replace(/[.:]\s*$/, '').replace(/["“”]/g, '').trim();
- if (!/^The\b.+\b(Rule|Fallback|Principle)$/i.test(nameRaw)) continue;
- if (seen.has(nameRaw.toLowerCase())) continue;
- seen.add(nameRaw.toLowerCase());
- rules.push({ name: nameRaw, body: stripBold(mm[2]).trim() });
- }
-
- return rules;
-}
-
-// ---------- Per-section extractors ----------
-
-function extractOverview(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
- const northStar = text.match(/\*\*Creative North Star:\s*"([^"]+)"\*\*/);
- const keyChars = [];
- const keyCharMatch = text.match(/\*\*Key Characteristics:\*\*\s*\n([\s\S]+?)(?:\n##|\n###|$)/);
- if (keyCharMatch) {
- for (const line of keyCharMatch[1].split('\n')) {
- const m = line.match(/^\s*[-*]\s+(.+)$/);
- if (m) keyChars.push(stripBold(m[1].trim()));
- }
- }
-
- // Philosophy paragraphs: everything that isn't a rule header or key-char block
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) =>
- !p.startsWith('**Creative North Star') &&
- !p.startsWith('**Key Characteristics')
- );
-
- return {
- subtitle: section.subtitle,
- creativeNorthStar: northStar ? northStar[1] : null,
- philosophy: paragraphs,
- keyCharacteristics: keyChars,
- };
-}
-
-function extractColors(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ');
- const groups = [];
- const ROLE_KEYWORDS = /^(primary|secondary|tertiary|neutral|accent)\b/i;
-
- for (const sub of subs.slice(1)) {
- if (!sub.name || /Named Rules?/i.test(sub.name) || /^The\s/i.test(sub.name)) continue;
-
- const bullets = collectBullets(sub.lines);
- const parsed = bullets.map((b) => parseColorBullet(b)).filter(Boolean);
- if (parsed.length === 0) continue;
-
- // If every bullet starts with a role keyword (Primary/Secondary/...), promote
- // each bullet to its own group. Otherwise keep the subsection as the group.
- const allRoleBullets =
- parsed.length > 0 && parsed.every((p) => p.name && ROLE_KEYWORDS.test(p.name));
-
- if (allRoleBullets) {
- for (const p of parsed) {
- groups.push({ role: p.name, colors: [p] });
- }
- } else {
- groups.push({ role: sub.name, colors: parsed });
- }
- }
-
- // If the Colors section has no subsections at all (unlikely), fall back to
- // scanning the whole section as a flat bullet list.
- if (groups.length === 0) {
- const flat = collectBullets(section.lines)
- .map((b) => parseColorBullet(b))
- .filter(Boolean);
- if (flat.length) {
- for (const p of flat) {
- if (p.name && ROLE_KEYWORDS.test(p.name)) {
- groups.push({ role: p.name, colors: [p] });
- } else {
- const fallback = groups.find((g) => g.role === 'Palette');
- if (fallback) fallback.colors.push(p);
- else groups.push({ role: 'Palette', colors: [p] });
- }
- }
- }
- }
-
- return {
- subtitle: section.subtitle,
- description: description || null,
- groups,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function parseColorBullet(bullet) {
- const text = bullet.trim();
-
- // Case 1 (Impeccable): **Name** (value-with-maybe-nested-parens): description
- const bold = text.match(/^\*\*(.+?)\*\*\s*(.*)$/);
- if (bold && bold[2].startsWith('(')) {
- const value = extractParenGroup(bold[2]);
- if (value !== null) {
- const after = bold[2].slice(value.length + 2).trimStart();
- if (after.startsWith(':')) {
- return buildColor(bold[1], value, after.slice(1).trim());
- }
- }
- }
-
- // Case 2 (Stitch): **Name (values):** description — value embedded in bold.
- const stitch = text.match(/^\*\*([^*]+?)\s*\(([^)]+)\):\*\*\s*(.*)$/);
- if (stitch) {
- return buildColor(stitch[1].trim(), stitch[2], stitch[3]);
- }
-
- // Case 3: bullet without bold, just hex/oklch inside.
- const values = collectColorValues(text);
- if (values.length) {
- return buildColor(null, values.join(' to '), text);
- }
- return null;
-}
-
-function extractParenGroup(s) {
- if (s[0] !== '(') return null;
- let depth = 0;
- for (let i = 0; i < s.length; i++) {
- if (s[i] === '(') depth++;
- else if (s[i] === ')') {
- depth--;
- if (depth === 0) return s.slice(1, i);
- }
- }
- return null;
-}
-
-function buildColor(name, rawValue, description) {
- const values = collectColorValues(rawValue);
- const primary = values[0] ?? rawValue.trim();
- return {
- name: name ? stripBold(name).trim() : null,
- value: primary,
- valueRange: values.length > 1 ? values : null,
- format: detectFormat(primary),
- description: stripBold(description || '').trim() || null,
- };
-}
-
-function collectColorValues(s) {
- const out = [];
- s.replace(HEX_RE, (v) => {
- out.push(v);
- return v;
- });
- s.replace(OKLCH_RE, (v) => {
- out.push(v);
- return v;
- });
- return out;
-}
-
-function detectFormat(v) {
- if (!v) return 'unknown';
- if (v.startsWith('#')) return 'hex';
- if (/^oklch/i.test(v)) return 'oklch';
- if (/^rgb/i.test(v)) return 'rgb';
- return 'unknown';
-}
-
-function scanInlineColors(lines) {
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '');
- const color = parseColorBullet(trimmed);
- if (color) out.push(color);
- }
- return out;
-}
-
-function parseStitchInlineGroups(lines) {
- // Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
- // Each bullet IS its own role. Group them under the spoken role name.
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
- const m = trimmed.match(
- /^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
- );
- if (m) {
- const role = m[1];
- const color = buildColor(role, m[2], m[3]);
- out.push({ role, colors: [color] });
- }
- }
- return out;
-}
-
-function extractTypography(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
-
- const fonts = {};
- // Pattern A: **Display Font:** Family (with fallback)
- const fontLineRe = /\*\*([\w\s/]+?)Font:\*\*\s*([^\n(]+?)(?:\s*\(with\s+([^)]+)\))?\s*$/gm;
- let fm;
- while ((fm = fontLineRe.exec(text)) !== null) {
- const rawRole = fm[1].trim().toLowerCase().replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || 'display';
- fonts[role] = {
- family: fm[2].trim(),
- fallback: fm[3] ? fm[3].trim() : null,
- };
- }
-
- // Pattern B (Stitch): * **Display & Headlines (Noto Serif):** description
- if (Object.keys(fonts).length === 0) {
- const stitchRe = /\*\*([\w\s&/]+?)\s*\(([^)]+)\):\*\*\s*(.+)/g;
- let sm;
- while ((sm = stitchRe.exec(text)) !== null) {
- const rawRole = sm[1]
- .trim()
- .toLowerCase()
- .replace(/\s*&\s*/g, '-')
- .replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || rawRole;
- fonts[role] = { family: sm[2].trim(), fallback: null, purpose: sm[3].trim() };
- }
- }
-
- // Character paragraph — either a **Character:** label, or fall back to the
- // first free paragraph under the section header (Stitch style).
- const characterMatch = text.match(/\*\*Character:\*\*\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\n|\n###|\n##|$)/);
- let character = characterMatch ? characterMatch[1].replace(/\n/g, ' ').trim() : null;
- if (!character) {
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) => !/^\*\*[\w\s/&]+Font/i.test(p) && !/^\*\*[\w\s/&]+\([^)]+\)/.test(p)
- );
- if (paragraphs.length) character = paragraphs[0];
- }
-
- // Hierarchy bullets under ### Hierarchy
- const subs = splitSubsections(section.lines);
- let hierarchy = [];
- const hierSub = subs.find((s) => s.name && /hierarch/i.test(s.name));
- if (hierSub) {
- const bullets = collectBullets(hierSub.lines);
- hierarchy = bullets.map(parseTypeBullet).filter(Boolean);
- }
-
- return {
- subtitle: section.subtitle,
- fonts,
- character,
- hierarchy,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function normalizeFontRole(raw) {
- // Canonical roles the panel cares about: display, body, label, mono.
- // Stitch often writes compound roles like "display-&-headlines" or "ui-&-body"
- // — collapse them to the first canonical role present.
- const tokens = raw.split(/[-/&\s]+/).filter(Boolean);
- const priority = ['display', 'headline', 'body', 'ui', 'label', 'mono'];
- const canonical = { headline: 'display', ui: 'body' };
- for (const p of priority) {
- if (tokens.includes(p)) return canonical[p] || p;
- }
- return null;
-}
-
-function parseTypeBullet(bullet) {
- // - **Display** (family, weight 300, italic, clamp(...), line-height 1): purpose
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(([^)]+)\):\s*(.*)$/);
- if (!m) return null;
- const name = m[1].trim();
- const specs = m[2].split(',').map((s) => s.trim());
- return {
- name,
- specs,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractElevation(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ') || null;
-
- const shadows = [];
- const seen = new Set();
- const dedupe = (entry) => {
- const key = (entry.name || '') + '::' + entry.value;
- if (seen.has(key)) return;
- seen.add(key);
- shadows.push(entry);
- };
-
- for (const b of collectBullets(section.lines)) {
- const parsed = parseShadowBullet(b);
- if (parsed) dedupe(parsed);
- }
-
- // Fallback: extract shadows written inline in prose. Stitch style is
- // "...use an extra-diffused shadow: `box-shadow: 0 12px 40px rgba(...)`."
- for (const p of collectParagraphs(section.lines)) {
- for (const inline of extractInlineShadows(p)) dedupe(inline);
- }
- for (const b of collectBullets(section.lines)) {
- for (const inline of extractInlineShadows(b)) dedupe(inline);
- }
-
- return {
- subtitle: section.subtitle,
- description,
- shadows,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function extractInlineShadows(text) {
- // Find `box-shadow: ...` anywhere in prose and capture the value. Work on the
- // raw string so it handles both backtick-fenced and unfenced variants.
- const out = [];
- const re = /box-shadow\s*:\s*([^`;\n]+)/gi;
- let m;
- while ((m = re.exec(text)) !== null) {
- const value = m[1].replace(/[`.)]+$/, '').trim();
- if (!value) continue;
- // Name heuristic: the noun immediately before the shadow phrase.
- // e.g. "an extra-diffused shadow: ..." -> "extra-diffused shadow"
- const before = text.slice(0, m.index);
- const nameMatch = before.match(/\b([A-Za-z][A-Za-z\- ]{2,40})\s+shadow\b[^A-Za-z0-9]*$/i);
- let name = null;
- if (nameMatch) {
- const stripped = nameMatch[1]
- .replace(/^(?:use|using|apply|applying|is|are|looks? like)\s+/i, '')
- .replace(/^(?:a|an|the)\s+/i, '')
- .trim();
- if (stripped) {
- name =
- stripped.charAt(0).toUpperCase() + stripped.slice(1) + ' shadow';
- }
- }
- out.push({
- name,
- value,
- purpose: null,
- });
- }
- return out;
-}
-
-function parseShadowBullet(bullet) {
- // - **Name** (`box-shadow: value`): purpose
- // - **Name** (`value`): purpose
- // Only accept if the paren content looks like a shadow value (contains px,
- // rem, rgba, or box-shadow). This filters out `**Rule Name:**` bullets.
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(`?([^`]+?)`?\):\s*(.*)$/);
- if (!m) return null;
- const rawValue = m[2].replace(/^box-shadow:\s*/i, '').trim();
- const looksLikeShadow =
- /box-shadow|rgba?\(|\bpx\b|\brem\b|^-?\d+\s/i.test(rawValue) &&
- /\d/.test(rawValue);
- if (!looksLikeShadow) return null;
- const name = stripBold(m[1]).trim();
- return {
- name,
- value: rawValue,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractComponents(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const components = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
-
- const bullets = collectBullets(sub.lines);
- const paragraphs = collectParagraphs(sub.lines);
-
- const variants = [];
- const properties = {};
-
- for (const b of bullets) {
- // - **Key:** value
- const m = b.match(/^\*\*(.+?):?\*\*:?\s*(.+)$/);
- if (m) {
- const key = stripBold(m[1]).trim();
- const value = stripBold(m[2]).trim();
- // Heuristic: "Primary", "Secondary", "Hover", "Focus" etc are variants;
- // "Shape", "Background", "Padding" are properties.
- if (/^(primary|secondary|tertiary|ghost|hover|focus|active|disabled|default|error|selected|unselected|state)$/i.test(key.split(/[\s/]/)[0])) {
- variants.push({ name: key, description: value });
- } else {
- properties[key.toLowerCase()] = value;
- }
- }
- }
-
- components.push({
- name: sub.name,
- description: paragraphs.join(' ') || null,
- properties,
- variants,
- });
- }
-
- return {
- subtitle: section.subtitle,
- components,
- };
-}
-
-function extractDosDonts(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const dos = [];
- const donts = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
- const subName = normalizeApostrophes(sub.name);
- const bullets = collectBullets(sub.lines).map((b) => stripBold(b).trim());
- if (/^do'?t?:?$/i.test(subName) || /^do:?$/i.test(subName)) {
- dos.push(...bullets);
- } else if (/^don'?t:?$/i.test(subName)) {
- donts.push(...bullets);
- }
- }
-
- // Classify by bullet prefix as a backup (catches loose bullets outside H3 wrappers)
- for (const b of collectBullets(section.lines)) {
- const stripped = normalizeApostrophes(stripBold(b).trim());
- if (/^don'?t\b/i.test(stripped)) {
- if (!donts.some((d) => normalizeApostrophes(d) === stripped)) donts.push(stripped);
- } else if (/^do\b/i.test(stripped)) {
- if (!dos.some((d) => normalizeApostrophes(d) === stripped)) dos.push(stripped);
- }
- }
-
- return { dos, donts };
-}
-
-// ---------- Coverage assessment ----------
-
-function assessCoverage(model) {
- const report = {};
-
- report.overview = model.overview
- ? {
- northStar: Boolean(model.overview.creativeNorthStar),
- philosophy: model.overview.philosophy.length > 0,
- keyCharacteristics: model.overview.keyCharacteristics.length,
- }
- : 'missing';
-
- report.colors = model.colors
- ? {
- groups: model.colors.groups.length,
- totalColors: model.colors.groups.reduce((n, g) => n + g.colors.length, 0),
- rules: model.colors.rules.length,
- }
- : 'missing';
-
- report.typography = model.typography
- ? {
- fonts: Object.keys(model.typography.fonts).length,
- hierarchyEntries: model.typography.hierarchy.length,
- character: Boolean(model.typography.character),
- rules: model.typography.rules.length,
- }
- : 'missing';
-
- report.elevation = model.elevation
- ? {
- shadows: model.elevation.shadows.length,
- rules: model.elevation.rules.length,
- description: Boolean(model.elevation.description),
- }
- : 'missing';
-
- report.components = model.components
- ? {
- count: model.components.components.length,
- variantTotal: model.components.components.reduce((n, c) => n + c.variants.length, 0),
- }
- : 'missing';
-
- report.dosDonts = model.dosDonts
- ? {
- dos: model.dosDonts.dos.length,
- donts: model.dosDonts.donts.length,
- }
- : 'missing';
-
- return report;
-}
-
-// ---------- Main ----------
-
-export function parseDesignMd(md) {
- const { frontmatter, body } = parseFrontmatter(md);
- const { title, sections } = splitSections(body);
- return {
- schemaVersion: 2,
- title,
- frontmatter,
- overview: extractOverview(sections['Overview']),
- colors: extractColors(sections['Colors']),
- typography: extractTypography(sections['Typography']),
- elevation: extractElevation(sections['Elevation']),
- components: extractComponents(sections['Components']),
- dosDonts: extractDosDonts(sections["Do's and Don'ts"]),
- };
-}
-
-export { assessCoverage };
@@ -1,198 +0,0 @@
-/**
- * Scan a project tree for Content-Security-Policy signals and classify the
- * shape so the agent knows which patch template to propose.
- *
- * Used at first-time `live.mjs` setup. Mechanical (grep-based) — no network,
- * no dev server, no JS evaluation. The classification drives a user-facing
- * consent prompt; the agent does the actual patch writing.
- *
- * Shapes are named by patch mechanism, not framework origin:
- * - "append-arrays": CSP defined as structured directive arrays. Patch
- * appends a dev-only localhost entry. Covers:
- * - Monorepo helpers with additional*Src options
- * (e.g. createBaseNextConfig for Next)
- * - SvelteKit kit.csp.directives
- * - nuxt-security module's contentSecurityPolicy
- * - "append-string": CSP built as a literal value string. Patch splices
- * a dev-only token into script-src and connect-src.
- * Covers:
- * - Inline Next.js headers() with CSP string
- * - Nuxt routeRules / nitro.routeRules CSP headers
- * - "middleware": CSP set dynamically in middleware.{ts,js}.
- * Detected but not auto-patched in v1.
- * - "meta-tag": <meta http-equiv="Content-Security-Policy"> in
- * layout files. Detected but not auto-patched in v1.
- * - null: no CSP signals found; no patch needed.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const SKIP_DIRS = new Set([
- 'node_modules',
- '.git',
- '.next',
- '.turbo',
- '.svelte-kit',
- '.nuxt',
- '.astro',
- 'dist',
- 'build',
- 'out',
- '.vercel',
-]);
-
-const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.tsx', '.jsx']);
-const LAYOUT_EXTS = new Set(['.tsx', '.jsx', '.astro', '.vue', '.svelte', '.html']);
-const MAX_DEPTH = 6;
-const MAX_READ_BYTES = 64 * 1024;
-
-// append-arrays signals: CSP expressed as structured directive arrays
-const MONOREPO_HELPER_SIGNALS = [
- /\bbuildCSPConfig\b/,
- /\bbuildSecurityHeaders\b/,
- /\badditionalScriptSrc\b/,
- /\badditionalConnectSrc\b/,
- /\bcreateBaseNextConfig\b/,
-];
-const SVELTEKIT_CSP_SIGNALS = [
- /\bkit\s*:/,
- /\bcsp\s*:/,
- /\bdirectives\s*:/,
-];
-const NUXT_SECURITY_SIGNALS = [
- /['"]nuxt-security['"]/,
- /\bcontentSecurityPolicy\b/,
-];
-
-// append-string signals: CSP written as a literal value string
-const INLINE_HEADER_SIGNALS = [
- /["']Content-Security-Policy["']/i,
- /\bscript-src\b/,
- /\bconnect-src\b/,
-];
-const NUXT_ROUTE_RULES_SIGNALS = [
- /\brouteRules\b/,
- /Content-Security-Policy/i,
- /\bscript-src\b/,
-];
-
-const MIDDLEWARE_HINT = /headers\.set\(\s*["']Content-Security-Policy["']/i;
-const META_TAG_HINT = /http-equiv\s*=\s*["']Content-Security-Policy["']/i;
-
-/**
- * @param {string} cwd Project root.
- * @returns {{ shape: string|null, signals: string[] }}
- */
-export function detectCsp(cwd = process.cwd()) {
- const hits = { appendArrays: [], appendString: [], middleware: [], metaTag: [] };
-
- walk(cwd, cwd, 0, (absPath, relPath, body) => {
- const ext = path.extname(absPath);
- const base = path.basename(absPath).toLowerCase();
- const isConfig = (name) =>
- new RegExp('(^|/)' + name + '\\.config\\.').test(relPath);
-
- // === append-arrays candidates ===
-
- // Monorepo CSP helper: packages/*/src/.../(config|security)/*
- if (SCAN_EXTS.has(ext) &&
- /packages\/[^/]+\/src\/.*(config|next-config|security)/.test(relPath) &&
- MONOREPO_HELPER_SIGNALS.some((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // SvelteKit kit.csp.directives
- if (SCAN_EXTS.has(ext) && isConfig('svelte') &&
- SVELTEKIT_CSP_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // Nuxt nuxt-security module
- if (SCAN_EXTS.has(ext) && isConfig('nuxt') &&
- NUXT_SECURITY_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // === append-string candidates ===
-
- // Inline headers in Next/Nuxt/SvelteKit/Astro/Vite config
- if (SCAN_EXTS.has(ext) &&
- /(^|\/)(next|nuxt|vite|astro|svelte)\.config\./.test(relPath) &&
- INLINE_HEADER_SIGNALS.every((re) => re.test(body))) {
- // Nuxt routeRules is a sub-shape of append-string; we already covered
- // nuxt-security above via return, so any remaining Nuxt CSP match here
- // is a route-rules / inline-headers case. Either way, same patch
- // mechanism.
- hits.appendString.push(relPath);
- return;
- }
-
- // === detect-only shapes ===
-
- if ((base === 'middleware.ts' || base === 'middleware.js' || base === 'middleware.mjs') &&
- MIDDLEWARE_HINT.test(body)) {
- hits.middleware.push(relPath);
- }
-
- if (LAYOUT_EXTS.has(ext) && META_TAG_HINT.test(body)) {
- hits.metaTag.push(relPath);
- }
- });
-
- // Priority: append-arrays > append-string > middleware > meta-tag.
- // Structured patches are safer than string splices; runtime and HTML
- // injection patches are less reliable and v1 doesn't auto-apply them.
- if (hits.appendArrays.length > 0) {
- return { shape: 'append-arrays', signals: hits.appendArrays };
- }
- if (hits.appendString.length > 0) {
- return { shape: 'append-string', signals: hits.appendString };
- }
- if (hits.middleware.length > 0) {
- return { shape: 'middleware', signals: hits.middleware };
- }
- if (hits.metaTag.length > 0) {
- return { shape: 'meta-tag', signals: hits.metaTag };
- }
- return { shape: null, signals: [] };
-}
-
-function walk(root, dir, depth, visit) {
- if (depth > MAX_DEPTH) return;
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
-
- for (const entry of entries) {
- const abs = path.join(dir, entry.name);
- if (entry.isDirectory()) {
- if (SKIP_DIRS.has(entry.name)) continue;
- walk(root, abs, depth + 1, visit);
- continue;
- }
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name);
- if (!SCAN_EXTS.has(ext) && !LAYOUT_EXTS.has(ext)) continue;
- let body;
- try {
- const fd = fs.openSync(abs, 'r');
- try {
- const buf = Buffer.alloc(MAX_READ_BYTES);
- const n = fs.readSync(fd, buf, 0, MAX_READ_BYTES, 0);
- body = buf.slice(0, n).toString('utf-8');
- } finally { fs.closeSync(fd); }
- } catch { continue; }
- visit(abs, path.relative(root, abs), body);
- }
-}
-
-// CLI mode
-const _running = process.argv[1];
-if (_running?.endsWith('detect-csp.mjs') || _running?.endsWith('detect-csp.mjs/')) {
- const result = detectCsp(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
@@ -1,21 +0,0 @@
-#!/usr/bin/env node
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { pathToFileURL, fileURLToPath } from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const candidates = [
- path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
-];
-const detectorPath = candidates.find(p => fs.existsSync(p));
-
-if (!detectorPath) {
- process.stderr.write('Error: bundled detector not found.\n');
- process.exit(1);
-}
-
-const { detectCli } = await import(pathToFileURL(detectorPath));
-
-await detectCli();
@@ -1,1688 +0,0 @@
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
@@ -1,232 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
-import { detectHtml } from '../engines/static-html/detect-html.mjs';
-import { detectText } from '../engines/regex/detect-text.mjs';
-import {
- HTML_EXTENSIONS,
- buildImportGraph,
- detectFrameworkConfig,
- isPortListening,
- walkDir,
-} from '../node/file-system.mjs';
-
-// ---------------------------------------------------------------------------
-// Output formatting
-// ---------------------------------------------------------------------------
-
-function formatFindings(findings, jsonMode) {
- if (jsonMode) return JSON.stringify(findings, null, 2);
-
- const grouped = {};
- for (const f of findings) {
- if (!grouped[f.file]) grouped[f.file] = [];
- grouped[f.file].push(f);
- }
- const out = [];
- for (const [file, items] of Object.entries(grouped)) {
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
- out.push(`\n${file}${importNote}`);
- for (const item of items) {
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
- out.push(` → ${item.description}`);
- }
- }
- out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
- return out.join('\n');
-}
-
-// ---------------------------------------------------------------------------
-// Stdin handling
-// ---------------------------------------------------------------------------
-
-async function handleStdin() {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- const input = Buffer.concat(chunks).toString('utf-8');
- try {
- const parsed = JSON.parse(input);
- const fp = parsed?.tool_input?.file_path;
- if (fp && fs.existsSync(fp)) {
- return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
- ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
- }
- } catch { /* not JSON */ }
- return detectText(input, '<stdin>');
-}
-
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-async function confirm(question) {
- const rl = (await import('node:readline')).default.createInterface({
- input: process.stdin, output: process.stderr,
- });
- return new Promise((resolve) => {
- rl.question(`${question} [Y/n] `, (answer) => {
- rl.close();
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
- });
- });
-}
-
-function printUsage() {
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
-
-Scan files or URLs for UI anti-patterns and design quality issues.
-
-Options:
- --fast Regex-only mode (skip static HTML/CSS analysis, faster but misses linked stylesheets)
- --json Output results as JSON
- --help Show this help message
-
-Detection modes:
- HTML files Static HTML/CSS analysis (default, catches linked CSS)
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
- URLs Puppeteer full browser rendering (auto-detected)
- --fast Forces regex for all files
-
-Examples:
- impeccable detect src/
- impeccable detect index.html
- impeccable detect https://example.com
- impeccable detect --fast --json .`);
-}
-
-async function detectCli() {
- let args = process.argv.slice(2).map(arg => {
- if (arg === '-json') return '--json';
- if (arg === '-fast') return '--fast';
- return arg;
- });
- if (args[0] === 'detect') args = args.slice(1);
- const jsonMode = args.includes('--json');
- const helpMode = args.includes('--help');
- const fastMode = args.includes('--fast');
- const targets = args.filter(a => !a.startsWith('--'));
-
- if (helpMode) { printUsage(); process.exit(0); }
-
- let allFindings = [];
-
- if (!process.stdin.isTTY && targets.length === 0) {
- allFindings = await handleStdin();
- } else {
- const paths = targets.length > 0 ? targets : [process.cwd()];
- const urlTargetCount = paths.filter(target => /^https?:\/\//i.test(target)).length;
- const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
-
- try {
- for (const target of paths) {
- if (/^https?:\/\//i.test(target)) {
- try {
- const scanner = browserDetector
- ? (url) => browserDetector.detectUrl(url)
- : (url) => detectUrl(url);
- allFindings.push(...await scanner(target));
- } catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
- continue;
- }
-
- const resolved = path.resolve(target);
- let stat;
- try { stat = fs.statSync(resolved); }
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
-
- if (stat.isDirectory()) {
- // Check for framework dev server config (skip in JSON mode to avoid polluting output)
- if (!jsonMode) {
- const fwConfig = detectFrameworkConfig(resolved);
- if (fwConfig) {
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
- if (probe.listening && probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
- `For more accurate results, scan the running site:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- } else if (probe.listening && !probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
- );
- } else {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Start the dev server and scan via URL for best results:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- }
- }
- }
-
- const files = walkDir(resolved);
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
-
- // Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
- if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
- process.stderr.write(
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
- `Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
- `Use --fast to skip static HTML/CSS analysis, or target a specific subdirectory.\n`
- );
- const ok = await confirm('Continue?');
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
- }
-
- // Build import graph for multi-file awareness
- const graph = buildImportGraph(files);
- // Build reverse map: file -> set of files that import it
- const importedByMap = new Map();
- for (const [importer, imports] of graph) {
- for (const imported of imports) {
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
- importedByMap.get(imported).add(importer);
- }
- }
-
- for (const file of files) {
- const ext = path.extname(file).toLowerCase();
- let fileFindings;
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- fileFindings = await detectHtml(file);
- } else {
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
- }
- // Annotate findings with import context
- const importers = importedByMap.get(file);
- if (importers && importers.size > 0) {
- const importerNames = [...importers].map(f => path.basename(f));
- for (const f of fileFindings) {
- f.importedBy = importerNames;
- }
- }
- allFindings.push(...fileFindings);
- }
- } else if (stat.isFile()) {
- const ext = path.extname(resolved).toLowerCase();
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- allFindings.push(...await detectHtml(resolved));
- } else {
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
- }
- }
- }
- } finally {
- if (browserDetector) await browserDetector.close();
- }
- }
-
- if (allFindings.length > 0) {
- if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
- else process.stderr.write(formatFindings(allFindings, false) + '\n');
- process.exit(2);
- }
- if (jsonMode) process.stdout.write('[]\n');
- process.exit(0);
-}
-
-export { formatFindings, handleStdin, confirm, printUsage, detectCli };
@@ -1,4030 +0,0 @@
-/**
- * Anti-Pattern Browser Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * GENERATED -- do not edit. Source: cli/engine/browser/injected/index.mjs
- * Rebuild: node scripts/build-browser-detector.js
- *
- * Usage: <script src="detect-antipatterns-browser.js"></script>
- * Re-scan: window.impeccableScan()
- */
-(function () {
-if (typeof window === 'undefined') return;
-// --- cli/engine/shared/constants.mjs ---
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-// --- cli/engine/registry/antipatterns.mjs ---
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-// --- cli/engine/shared/color.mjs ---
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-// --- cli/engine/rules/checks.mjs ---
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-// --- cli/engine/browser/injected/index.mjs ---
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
-
-})();
@@ -1,43 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Anti-Pattern Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * Public API facade. Runtime engines live under cli/engine/engines/.
- */
-
-import { detectCli } from './cli/main.mjs';
-
-export { ANTIPATTERNS, RULE_ENGINE_SUPPORT, getAntipattern, getRulesForCategory, getRuleEngineSupport } from './registry/antipatterns.mjs';
-export { SAFE_TAGS, BORDER_SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS, KNOWN_SERIF_FONTS } from './shared/constants.mjs';
-export { isNeutralColor, parseRgb, relativeLuminance, contrastRatio, parseGradientColors, hasChroma, getHue, colorToHex } from './shared/color.mjs';
-export { isFullPage } from './shared/page.mjs';
-export {
- checkElementBorders,
- checkElementMotion,
- checkElementGlow,
- checkPageTypography,
- checkPageLayout,
- checkHtmlPatterns,
-} from './rules/checks.mjs';
-export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
-export { detectHtml } from './engines/static-html/detect-html.mjs';
-export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
-export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
-export {
- walkDir,
- SCANNABLE_EXTENSIONS,
- SKIP_DIRS,
- buildImportGraph,
- resolveImport,
- detectFrameworkConfig,
- isPortListening,
- FRAMEWORK_CONFIGS,
-} from './node/file-system.mjs';
-export { formatFindings, detectCli } from './cli/main.mjs';
-
-const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
-if (isMainModule) detectCli();
@@ -1,251 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { finding } from '../../findings.mjs';
-import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
-
-async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
- if (options?.visualContrast === false) return [];
- const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : 12;
- const scrollOffscreen = options?.visualContrastScrollOffscreen !== false;
- const existingLowContrastSelectors = new Set(
- serializedGroups
- .filter(group => group.findings?.some(f => f.type === 'low-contrast'))
- .map(group => group.selector)
- .filter(Boolean)
- );
-
- let browserAnalyses = [];
- const findings = [];
- if (options?.visualContrastBrowser !== false) {
- const browserFindings = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'browser-fallback',
- target,
- }, async () => {
- browserAnalyses = await page.evaluate(async ({ maxCandidates, scrollOffscreen }) => {
- if (typeof window.impeccableAnalyzeVisualContrast !== 'function') return [];
- return window.impeccableAnalyzeVisualContrast({ maxCandidates, scrollOffscreen });
- }, { maxCandidates, scrollOffscreen });
- return browserAnalyses
- .filter(result => result.finding && !existingLowContrastSelectors.has(result.selector))
- .map(result => result.finding);
- });
- findings.push(...browserFindings);
- }
-
- let candidates = browserAnalyses.length > 0 ? browserAnalyses : [];
- if (candidates.length === 0) {
- candidates = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'collect-candidates',
- target,
- }, () => page.evaluate(({ maxCandidates }) => {
- if (typeof window.impeccableCollectVisualContrastCandidates !== 'function') return [];
- return window.impeccableCollectVisualContrastCandidates({ maxCandidates });
- }, { maxCandidates }));
- }
-
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const browserResolvedSelectors = new Set(
- browserAnalyses
- .filter(result => result.status === 'fail' || result.status === 'pass')
- .map(result => result.selector)
- .filter(Boolean)
- );
- const filtered = candidates.filter(candidate =>
- !existingLowContrastSelectors.has(candidate.selector) &&
- !browserResolvedSelectors.has(candidate.selector)
- );
- if (options?.visualContrastPixel === false) return findings;
- for (const candidate of filtered) {
- const result = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'pixel-diff',
- target,
- }, async () => {
- const finding = await captureVisualContrastCandidate(page, candidate, viewport);
- return finding ? [finding] : [];
- });
- findings.push(...result);
- }
- return findings;
-}
-
-// ---------------------------------------------------------------------------
-// Puppeteer detection (for URLs)
-// ---------------------------------------------------------------------------
-
-async function detectUrl(url, options = {}) {
- const profile = options?.profile;
- const waitUntil = options?.waitUntil || 'networkidle0';
- const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const externalBrowser = options?.browser || null;
- let puppeteer;
- if (!externalBrowser) {
- try {
- puppeteer = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'import-puppeteer',
- target: url,
- }, () => import('puppeteer'));
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- }
-
- // Read the browser detection script — reuse it instead of reimplementing
- const browserScriptPath = path.resolve(
- path.dirname(fileURLToPath(import.meta.url)),
- '..',
- '..',
- 'detect-antipatterns-browser.js'
- );
- let browserScript;
- try {
- browserScript = profileStep(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'read-browser-script',
- target: url,
- }, () => fs.readFileSync(browserScriptPath, 'utf-8'));
- } catch {
- throw new Error(`Browser script not found at ${browserScriptPath}`);
- }
-
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
- // running in CI; local users keep the default hardened launch.
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
- const browser = externalBrowser || await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'launch-browser',
- target: url,
- }, () => puppeteer.default.launch({ headless: true, args: launchArgs }));
- const page = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'new-page',
- target: url,
- }, () => browser.newPage());
- let results = [];
- try {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'set-viewport',
- target: url,
- }, () => page.setViewport(viewport));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: `goto:${waitUntil}`,
- target: url,
- }, () => page.goto(url, { waitUntil, timeout: 30000 }));
- if (settleMs > 0) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'settle',
- target: url,
- }, () => new Promise(resolve => setTimeout(resolve, settleMs)));
- }
-
- // Inject the browser detection script and collect results
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'configure-pure-detect',
- target: url,
- }, () => page.evaluate(() => {
- window.__IMPECCABLE_CONFIG__ = {
- ...(window.__IMPECCABLE_CONFIG__ || {}),
- autoScan: false,
- };
- }));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'inject-browser-script',
- target: url,
- }, () => page.evaluate(browserScript));
- let serializedGroups = [];
- results = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'browser-scan',
- target: url,
- }, async () => {
- serializedGroups = await page.evaluate(() => {
- if (!window.impeccableDetect) return [];
- return window.impeccableDetect({ decorate: false, serialize: true });
- });
- return serializedGroups.flatMap(({ findings }) =>
- findings.map(f => ({ id: f.type, snippet: f.detail }))
- );
- });
- const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
- results.push(...visualFindings);
- } finally {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-page',
- target: url,
- }, () => page.close().catch(() => {}));
- if (!externalBrowser) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-browser',
- target: url,
- }, () => browser.close());
- }
- }
- return results.map(f => finding(f.id, url, f.snippet));
-}
-
-async function createBrowserDetector(options = {}) {
- let puppeteer;
- try {
- puppeteer = await import('puppeteer');
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- const launchArgs = options.launchArgs || (process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : []);
- const browser = options.browser || await puppeteer.default.launch({
- headless: options.headless ?? true,
- args: launchArgs,
- });
- const ownsBrowser = !options.browser;
- const defaults = {
- waitUntil: options.waitUntil || 'load',
- settleMs: Number.isFinite(options.settleMs) ? options.settleMs : 100,
- viewport: options.viewport || { width: 1280, height: 800 },
- };
- return {
- browser,
- async detectUrl(url, scanOptions = {}) {
- return detectUrl(url, {
- ...defaults,
- ...scanOptions,
- browser,
- });
- },
- async close() {
- if (ownsBrowser) await browser.close().catch(() => {});
- },
- };
-}
-
-export { runVisualContrastFallback, detectUrl, createBrowserDetector };
@@ -1,420 +0,0 @@
-import { GENERIC_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep } from '../../profile/profiler.mjs';
-
-// ---------------------------------------------------------------------------
-// Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
-// ---------------------------------------------------------------------------
-
-const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
-const hasBorderRadius = (line) => /border-radius/i.test(line);
-const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
-
-function isNeutralBorderColor(str) {
- const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
- if (!m) return false;
- const c = m[1].toLowerCase();
- if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
- const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
- if (hex) {
- const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
- if (shex) {
- const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- return false;
-}
-
-const REGEX_MATCHERS = [
- // --- Side-tab ---
- { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
- test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
- test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
- fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
- { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
- test: (m) => +m[1] >= 3,
- fmt: (m) => m[0] },
- // --- Border accent on rounded ---
- { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
- test: (m, line) => hasRounded(line) && +m[1] >= 1,
- fmt: (m) => m[0] },
- { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
- fmt: (m) => m[0] },
- // --- Overused font ---
- { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
- test: () => true,
- fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
- // --- Pure black background ---
- { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Gradient text ---
- { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
- test: (m, line) => /gradient/i.test(line),
- fmt: () => 'background-clip: text + gradient' },
- // --- Gradient text (Tailwind) ---
- { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
- test: (m, line) => /\bbg-gradient-to-/i.test(line),
- fmt: () => 'bg-clip-text + bg-gradient' },
- // --- Tailwind pure black background ---
- { id: 'pure-black-white', regex: /\bbg-black\b/g,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Tailwind gray on colored bg ---
- { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
- test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
- fmt: (m, line) => { const bg = line.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/); return `${m[0]} on ${bg?.[0] || '?'}`; } },
- // --- Tailwind AI palette ---
- { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
- fmt: (m) => `${m[0]} on heading` },
- { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
- fmt: (m) => `${m[0]} gradient` },
- // --- Bounce/elastic easing ---
- { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
- test: () => true,
- fmt: () => 'animate-bounce (Tailwind)' },
- { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
- test: (m) => {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
- },
- fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
- // --- Layout property transition ---
- { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition: ${found ? found.join(', ') : m[1].trim()}`;
- } },
- { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
- } },
-];
-
-const REGEX_ANALYZERS = [
- // Single font
- (content, filePath) => {
- const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
- const fonts = new Set();
- let m;
- while ((m = fontFamilyRe.exec(content)) !== null) {
- for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
- }
- }
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- while ((m = gfRe.exec(content)) !== null) {
- for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
- }
- if (fonts.size !== 1 || content.split('\n').length < 20) return [];
- const name = [...fonts][0];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
- return [finding('single-font', filePath, `only font used is ${name}`, line)];
- },
- // Flat type hierarchy
- (content, filePath) => {
- const sizes = new Set();
- const REM = 16;
- let m;
- const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
- while ((m = sizeRe.exec(content)) !== null) {
- const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
- if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
- }
- const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
- while ((m = clampRe.exec(content)) !== null) {
- sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
- sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
- }
- const TW = { 'text-xs': 12, 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24, 'text-3xl': 30, 'text-4xl': 36, 'text-5xl': 48, 'text-6xl': 60, 'text-7xl': 72, 'text-8xl': 96, 'text-9xl': 128 };
- for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
- if (sizes.size < 3) return [];
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio >= 2.0) return [];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (/font-size/i.test(lines[i]) || /\btext-(?:xs|sm|base|lg|xl|\d)/i.test(lines[i])) { line = i + 1; break; } }
- return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
- },
- // Monotonous spacing (regex)
- (content, filePath) => {
- const vals = [];
- let m;
- const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
- const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
- const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
- const rounded = vals.map(v => Math.round(v / 4) * 4);
- if (rounded.length < 10) return [];
- const counts = {};
- for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const pct = maxCount / rounded.length;
- const unique = [...new Set(rounded)].filter(v => v > 0);
- if (pct <= 0.6 || unique.length > 3) return [];
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
- },
- // Everything centered (regex)
- (content, filePath) => {
- const lines = content.split('\n');
- let centered = 0, total = 0;
- for (const line of lines) {
- if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
- total++;
- if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
- }
- }
- if (total < 5 || centered / total <= 0.7) return [];
- return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
- },
- // Dark glow (page-level: dark bg + colored box-shadow with blur)
- (content, filePath) => {
- // Check if page has a dark background
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
- if (!hasDarkBg) return [];
-
- // Check for colored box-shadow with blur > 4px
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let m;
- while ((m = shadowRe.exec(content)) !== null) {
- const val = m[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
- // Check blur: look for pattern like "0 0 20px" (third number > 4)
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- const lines = content.substring(0, m.index).split('\n');
- return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
- }
- }
- return [];
- },
-];
-
-// ---------------------------------------------------------------------------
-// Style block extraction (Vue/Svelte <style> blocks)
-// ---------------------------------------------------------------------------
-
-function extractStyleBlocks(content, ext) {
- ext = ext.toLowerCase();
- if (ext !== '.vue' && ext !== '.svelte') return [];
- const blocks = [];
- const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length + 1;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-// ---------------------------------------------------------------------------
-// CSS-in-JS extraction (styled-components, emotion)
-// ---------------------------------------------------------------------------
-
-const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
-
-function extractCSSinJS(content, ext) {
- ext = ext.toLowerCase();
- if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
- const blocks = [];
- const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null, options = {}) {
- const { profile, phase = 'regex-matchers' } = options || {};
- const findings = [];
- if (!profile) {
- for (const matcher of REGEX_MATCHERS) {
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- }
- return findings;
- }
-
- for (const matcher of REGEX_MATCHERS) {
- const matcherFindings = profileFindings(profile, {
- engine: 'regex',
- phase,
- ruleId: matcher.id,
- target: filePath,
- }, () => {
- const matches = [];
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- matches.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- return matches;
- });
- findings.push(...matcherFindings);
- }
- return findings;
-}
-
-function detectText(content, filePath, options = {}) {
- const profile = options?.profile;
- const findings = [];
- const lines = content.split('\n');
- const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
-
- // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
- // Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
- findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
- profile,
- phase: 'source',
- }));
-
- // Extract and scan <style> blocks from Vue/Svelte SFCs
- const styleBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'style-blocks',
- target: filePath,
- }, () => extractStyleBlocks(content, ext))
- : extractStyleBlocks(content, ext);
- for (const block of styleBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'style-block',
- }));
- }
-
- // Extract and scan CSS-in-JS template literals
- const cssJsBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'css-in-js',
- target: filePath,
- }, () => extractCSSinJS(content, ext))
- : extractCSSinJS(content, ext);
- for (const block of cssJsBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'css-in-js',
- }));
- }
-
- // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
- const deduped = [];
- for (const f of findings) {
- const isDupe = deduped.some(d =>
- d.antipattern === f.antipattern &&
- d.snippet === f.snippet &&
- Math.abs(d.line - f.line) <= 2
- );
- if (!isDupe) deduped.push(f);
- }
-
- // Page-level analyzers only run on full pages
- if (isFullPage(content)) {
- const analyzerIds = [
- 'single-font',
- 'flat-type-hierarchy',
- 'monotonous-spacing',
- 'everything-centered',
- 'dark-glow',
- ];
- for (let i = 0; i < REGEX_ANALYZERS.length; i++) {
- const analyzer = REGEX_ANALYZERS[i];
- deduped.push(...profileFindings(profile, {
- engine: 'regex',
- phase: 'page-analyzer',
- ruleId: analyzerIds[i] || `analyzer-${i + 1}`,
- target: filePath,
- }, () => analyzer(content, filePath)));
- }
- }
-
- return deduped;
-}
-
-export {
- REGEX_MATCHERS,
- REGEX_ANALYZERS,
- extractStyleBlocks,
- extractCSSinJS,
- runRegexMatchers,
- detectText,
-};
@@ -1,954 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { profileStep, recordProfileEvent } from '../../profile/profiler.mjs';
-import { parseAnyColor, resolveLengthPx, resolveVarRefs } from '../../rules/checks.mjs';
-
-// ---------------------------------------------------------------------------
-// jsdom CSS-variable border override map
-// ---------------------------------------------------------------------------
-//
-// jsdom's CSSOM silently drops any border shorthand that contains a var()
-// reference — the computed style for the element then shows empty width,
-// empty style, and a default black color. That's enough to hide the most
-// common real-world side-tab pattern in AI-generated pages:
-//
-// :root { --brand: #87a8ff; }
-// .card { border-left: 5px solid var(--brand); border-radius: 4px; }
-//
-// Real browsers (and therefore the browser detector path) resolve var()
-// natively, so this only affects the Node jsdom path.
-//
-// This pre-pass walks the stylesheets, finds any rule whose per-side or
-// all-sides border property contains var(), resolves the var() against
-// :root-level custom properties (read from the documentElement's computed
-// style, which jsdom DOES handle correctly), and attaches the resolved
-// width+color to every element that matches the rule's selector. The
-// Node-side `checkElementBorders` adapter consumes that map as a fallback
-// whenever jsdom's computed style came back empty.
-//
-// Limitations (intentional, to keep the pass simple):
-// * Only :root-level custom properties are resolved. Scoped overrides on
-// descendants are not tracked — uncommon in practice and would require
-// a per-element cascade walk.
-// * @media / @supports wrapped rules are ignored (jsdom often mishandles
-// these anyway).
-// * The fallback only fills sides that jsdom left empty, so any rule
-// whose border parses normally still wins via the computed style.
-
-const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
-
-// isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
-// CSS variables typically hold hex or named colors, so normalize those to
-// rgb() before handing the value off to the shared check. Anything we don't
-// recognise is passed through unchanged — isNeutralColor then treats it as
-// non-neutral, which is the safer default (matches the oklch-era bugfix).
-const NAMED_COLORS = {
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
-};
-
-function normalizeColorForCheck(value) {
- if (!value) return value;
- const v = value.trim();
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
- if (hex6) {
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
- if (hex3) {
- const [r, g, b] = [
- parseInt(hex3[1] + hex3[1], 16),
- parseInt(hex3[2] + hex3[2], 16),
- parseInt(hex3[3] + hex3[3], 16),
- ];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const named = NAMED_COLORS[v.toLowerCase()];
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
- return v;
-}
-
-function buildBorderOverrideMap(document, window) {
- const map = new Map();
- const rootStyle = window.getComputedStyle(document.documentElement);
-
- function resolveVar(value, depth = 0) {
- if (!value || depth > 10 || !value.includes('var(')) return value;
- return value.replace(
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
- (_, name, fallback) => {
- const v = rootStyle.getPropertyValue(name).trim();
- if (v) return resolveVar(v, depth + 1);
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
- return '';
- }
- );
- }
-
- function parseShorthand(text) {
- const m = text.trim().match(BORDER_SHORTHAND_RE);
- if (!m) return null;
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
- }
-
- // Read from the per-property accessors on rule.style. jsdom preserves
- // each border-* shorthand it parsed, even when the overall cssText has
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
- // `border-left: ...` loses the first declaration but keeps the second).
- const SIDE_PROPS = [
- ['borderLeft', 'Left'],
- ['borderRight', 'Right'],
- ['borderTop', 'Top'],
- ['borderBottom', 'Bottom'],
- ['borderInlineStart', 'Left'],
- ['borderInlineEnd', 'Right'],
- ];
-
- for (const sheet of document.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || []; } catch { continue; }
- for (const rule of rules) {
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
-
- const perSide = {};
-
- for (const [prop, side] of SIDE_PROPS) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const parsed = parseShorthand(resolveVar(val));
- if (parsed && parsed.color) perSide[side] = parsed;
- }
-
- // Uniform `border: <w> <style> var(...)` applies to every side the
- // per-side map didn't already claim.
- const borderAll = rule.style.border;
- if (borderAll && borderAll.includes('var(')) {
- const parsed = parseShorthand(resolveVar(borderAll));
- if (parsed && parsed.color) {
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
- if (!perSide[s]) perSide[s] = parsed;
- }
- }
- }
-
- // Longhand `border-*-color: var(...)` with width/style in separate
- // declarations. Rare in AI-generated pages, but cheap to cover.
- for (const [prop, side] of [
- ['borderLeftColor', 'Left'],
- ['borderRightColor', 'Right'],
- ['borderTopColor', 'Top'],
- ['borderBottomColor', 'Bottom'],
- ]) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const resolved = resolveVar(val).trim();
- if (!resolved) continue;
- // Width may or may not come from this rule — that's fine; the
- // adapter only substitutes the color when jsdom left it as a
- // literal var() string.
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
- }
-
- if (Object.keys(perSide).length === 0) continue;
-
- let matched;
- try { matched = document.querySelectorAll(rule.selectorText); }
- catch { continue; }
-
- for (const el of matched) {
- const existing = map.get(el);
- if (existing) {
- // Later rules overwrite earlier ones — approximates source-order
- // cascade for equal-specificity rules and is good enough for the
- // uncontested var()-dropped sides we're trying to recover.
- Object.assign(existing, perSide);
- } else {
- map.set(el, { ...perSide });
- }
- }
- }
- }
-
- return map;
-}
-
-// Strip `@layer NAME { … }` wrappers from a CSS / HTML source, leaving
-// the inner rules as flat CSS. jsdom doesn't implement CSS @layer, so
-// any rule inside a layer block becomes invisible to getComputedStyle.
-// Tailwind v4 makes this ubiquitous: every utility class lives in
-// `@layer utilities`, and Preflight lives in `@layer base`. Without
-// unwrapping, every Tailwind-styled element returns empty computed
-// styles. We walk the source character-by-character, balancing braces
-// so we correctly handle nested style rules inside the layer block.
-function unwrapCssAtLayer(source) {
- if (!source || !source.includes('@layer')) return source;
- // Find `@layer <name>? {` openers. The match starts at the @, and
- // we then balance braces from the opening { onward.
- const re = /@layer\b[^{;]*\{/g;
- let out = '';
- let lastIdx = 0;
- let m;
- while ((m = re.exec(source)) !== null) {
- const openStart = m.index;
- const openEnd = m.index + m[0].length; // position right after `{`
- let depth = 1;
- let i = openEnd;
- while (i < source.length && depth > 0) {
- const c = source.charCodeAt(i);
- if (c === 0x7b /* { */) depth++;
- else if (c === 0x7d /* } */) depth--;
- i++;
- }
- if (depth !== 0) {
- // Unbalanced — bail and return source unchanged.
- return source;
- }
- // Emit everything before the @layer, then the inner contents
- // (between the opening { and the matched closing }), then advance.
- out += source.slice(lastIdx, openStart);
- out += source.slice(openEnd, i - 1); // i-1 = position of the closing }
- lastIdx = i;
- re.lastIndex = i;
- }
- out += source.slice(lastIdx);
- return out;
-}
-
-// ---------------------------------------------------------------------------
-// Static HTML/CSS detection (default for local HTML files)
-// ---------------------------------------------------------------------------
-
-const STATIC_INHERITED_PROPS = new Set([
- 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight',
- 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'hyphens',
- 'webkitHyphens',
-]);
-
-const STATIC_DEFAULT_STYLE = {
- color: 'rgb(0, 0, 0)',
- backgroundColor: 'rgba(0, 0, 0, 0)',
- backgroundImage: 'none',
- borderTopWidth: '0px',
- borderRightWidth: '0px',
- borderBottomWidth: '0px',
- borderLeftWidth: '0px',
- borderTopColor: 'rgb(0, 0, 0)',
- borderRightColor: 'rgb(0, 0, 0)',
- borderBottomColor: 'rgb(0, 0, 0)',
- borderLeftColor: 'rgb(0, 0, 0)',
- borderRadius: '0px',
- boxShadow: 'none',
- fontFamily: '',
- fontSize: '16px',
- fontStyle: 'normal',
- fontWeight: '400',
- lineHeight: 'normal',
- letterSpacing: 'normal',
- textTransform: 'none',
- textAlign: 'start',
- hyphens: 'manual',
- webkitHyphens: 'manual',
- transitionProperty: '',
- transitionTimingFunction: '',
- animationName: '',
- animationTimingFunction: '',
- webkitBackgroundClip: '',
- backgroundClip: '',
- width: '',
- height: '',
- paddingTop: '0px',
- paddingRight: '0px',
- paddingBottom: '0px',
- paddingLeft: '0px',
- position: 'static',
- display: '',
-};
-
-const STATIC_PROP_MAP = {
- 'background-color': 'backgroundColor',
- 'background-image': 'backgroundImage',
- 'background-clip': 'backgroundClip',
- '-webkit-background-clip': 'webkitBackgroundClip',
- 'border-radius': 'borderRadius',
- 'border-top-width': 'borderTopWidth',
- 'border-right-width': 'borderRightWidth',
- 'border-bottom-width': 'borderBottomWidth',
- 'border-left-width': 'borderLeftWidth',
- 'border-top-color': 'borderTopColor',
- 'border-right-color': 'borderRightColor',
- 'border-bottom-color': 'borderBottomColor',
- 'border-left-color': 'borderLeftColor',
- 'box-shadow': 'boxShadow',
- 'font-family': 'fontFamily',
- 'font-size': 'fontSize',
- 'font-style': 'fontStyle',
- 'font-weight': 'fontWeight',
- 'line-height': 'lineHeight',
- 'letter-spacing': 'letterSpacing',
- 'text-transform': 'textTransform',
- 'text-align': 'textAlign',
- 'hyphens': 'hyphens',
- '-webkit-hyphens': 'webkitHyphens',
- 'transition-property': 'transitionProperty',
- 'transition-timing-function': 'transitionTimingFunction',
- 'animation-name': 'animationName',
- 'animation-timing-function': 'animationTimingFunction',
- 'width': 'width',
- 'height': 'height',
- 'padding-top': 'paddingTop',
- 'padding-right': 'paddingRight',
- 'padding-bottom': 'paddingBottom',
- 'padding-left': 'paddingLeft',
- 'position': 'position',
- 'display': 'display',
-};
-
-const STATIC_NAMED_COLORS = {
- black: { r: 0, g: 0, b: 0, a: 1 },
- white: { r: 255, g: 255, b: 255, a: 1 },
- transparent: { r: 0, g: 0, b: 0, a: 0 },
- gray: { r: 128, g: 128, b: 128, a: 1 },
- grey: { r: 128, g: 128, b: 128, a: 1 },
- silver: { r: 192, g: 192, b: 192, a: 1 },
- red: { r: 255, g: 0, b: 0, a: 1 },
- green: { r: 0, g: 128, b: 0, a: 1 },
- blue: { r: 0, g: 0, b: 255, a: 1 },
-};
-
-function splitCssList(value) {
- const parts = [];
- let depth = 0, quote = '', start = 0;
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; continue; }
- if (ch === '(' || ch === '[') depth++;
- else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);
- else if (ch === ',' && depth === 0) {
- parts.push(value.slice(start, i).trim());
- start = i + 1;
- }
- }
- const tail = value.slice(start).trim();
- if (tail) parts.push(tail);
- return parts;
-}
-
-function splitCssTokens(value) {
- const tokens = [];
- let depth = 0, quote = '', current = '';
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- current += ch;
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
- if (ch === '(') { depth++; current += ch; continue; }
- if (ch === ')') { depth = Math.max(0, depth - 1); current += ch; continue; }
- if (/\s/.test(ch) && depth === 0) {
- if (current) { tokens.push(current); current = ''; }
- continue;
- }
- current += ch;
- }
- if (current) tokens.push(current);
- return tokens;
-}
-
-function cssPropToCamel(prop) {
- if (!prop) return prop;
- const mapped = STATIC_PROP_MAP[prop];
- if (mapped) return mapped;
- return prop.replace(/-([a-z])/g, (_m, ch) => ch.toUpperCase());
-}
-
-function staticColorToCss(c) {
- if (!c) return '';
- if (c.a != null && c.a < 1) return `rgba(${c.r}, ${c.g}, ${c.b}, ${Number(c.a.toFixed(3))})`;
- return `rgb(${c.r}, ${c.g}, ${c.b})`;
-}
-
-function parseStaticColor(value) {
- const parsed = parseAnyColor(value);
- if (parsed) return parsed;
- const named = STATIC_NAMED_COLORS[String(value || '').trim().toLowerCase()];
- return named ? { ...named } : null;
-}
-
-function extractStaticColor(value) {
- if (!value) return '';
- const raw = String(value).trim();
- if (/^var\(/i.test(raw)) return raw;
- const colorLike = raw.match(/(?:rgba?\([^)]+\)|oklch\([^)]+\)|oklab\([^)]+\)|lch\([^)]+\)|lab\([^)]+\)|hsla?\([^)]+\)|hwb\([^)]+\)|#[0-9a-f]{3,8}\b|\b(?:black|white|gray|grey|silver|red|green|blue|transparent)\b)/i);
- if (!colorLike) return '';
- return colorLike[0];
-}
-
-function normalizeStaticCssValue(prop, value, customProps, parentStyle, currentStyle = null) {
- let resolved = resolveVarRefs(String(value || '').trim(), customProps);
- if (resolved === 'inherit') return parentStyle?.[prop] || STATIC_DEFAULT_STYLE[prop] || '';
- const isModernBorderColor = /^border[A-Z][a-z]+Color$/.test(prop) && /^(?:oklch|oklab|lch|lab|hsl|hwb)\(/i.test(resolved);
- if (!isModernBorderColor && (/color$/i.test(prop) || prop === 'color' || prop === 'backgroundColor')) {
- const parsed = parseStaticColor(resolved);
- if (parsed) resolved = staticColorToCss(parsed);
- }
- if (prop === 'fontSize') {
- const base = parseFloat(parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'letterSpacing') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'lineHeight' && resolved !== 'normal') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- return resolved;
-}
-
-function expandStaticBoxValues(tokens) {
- if (tokens.length === 0) return ['0px', '0px', '0px', '0px'];
- if (tokens.length === 1) return [tokens[0], tokens[0], tokens[0], tokens[0]];
- if (tokens.length === 2) return [tokens[0], tokens[1], tokens[0], tokens[1]];
- if (tokens.length === 3) return [tokens[0], tokens[1], tokens[2], tokens[1]];
- return [tokens[0], tokens[1], tokens[2], tokens[3]];
-}
-
-function parseStaticBorder(value) {
- const tokens = splitCssTokens(value);
- let width = '', color = '';
- for (const token of tokens) {
- if (!width && /^-?[\d.]+(?:px|rem|em|%)$/.test(token)) width = token;
- if (!color) color = extractStaticColor(token);
- }
- return { width, color };
-}
-
-function parseStaticFont(value) {
- const out = [];
- const slashParts = value.match(/(?:^|\s)([\d.]+(?:px|rem|em|%))(?:\/([^\s]+))?/);
- if (/\bitalic\b/i.test(value)) out.push(['fontStyle', 'italic']);
- const weight = value.match(/\b([1-9]00|bold|normal|lighter|bolder)\b/i);
- if (weight) out.push(['fontWeight', weight[1]]);
- if (slashParts) {
- out.push(['fontSize', slashParts[1]]);
- if (slashParts[2]) out.push(['lineHeight', slashParts[2]]);
- const familyStart = value.indexOf(slashParts[0]) + slashParts[0].length;
- const family = value.slice(familyStart).trim();
- if (family) out.push(['fontFamily', family]);
- }
- return out;
-}
-
-function parseStaticTransition(value) {
- const props = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const prop = tokens.find(token => /^[a-z-]+$/i.test(token) && !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none)$/.test(token) && !/s$/.test(token));
- if (prop) props.push(prop);
- }
- return {
- property: props.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function parseStaticAnimation(value) {
- const names = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const name = tokens.find(token =>
- /^[a-z_-][\w-]*$/i.test(token) &&
- !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none|running|paused)$/.test(token)
- );
- if (name) names.push(name);
- }
- return {
- name: names.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function expandStaticDeclaration(prop, value) {
- const p = prop.toLowerCase();
- const v = String(value || '').trim();
- if (!v) return [];
- if (p.startsWith('--')) return [[p, v]];
- if (p === 'background') {
- const out = [];
- const hasImage = /gradient|url\(/i.test(v);
- if (hasImage) out.push(['backgroundImage', v]);
- const beforeImage = hasImage ? v.split(/(?:repeating-)?(?:linear|radial|conic)-gradient\(|url\(/i)[0] : v;
- const color = extractStaticColor(hasImage ? beforeImage : v);
- if (color) out.push(['backgroundColor', color]);
- return out;
- }
- if (p === 'border') {
- const parsed = parseStaticBorder(v);
- const out = [];
- for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
- if (parsed.width) out.push([`border${side}Width`, parsed.width]);
- if (parsed.color) out.push([`border${side}Color`, parsed.color]);
- }
- return out;
- }
- const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
- if (sideMatch) {
- const parsed = parseStaticBorder(v);
- const side = sideMatch[1][0].toUpperCase() + sideMatch[1].slice(1);
- return [
- ...(parsed.width ? [[`border${side}Width`, parsed.width]] : []),
- ...(parsed.color ? [[`border${side}Color`, parsed.color]] : []),
- ];
- }
- if (p === 'border-width') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopWidth', vals[0]],
- ['borderRightWidth', vals[1]],
- ['borderBottomWidth', vals[2]],
- ['borderLeftWidth', vals[3]],
- ];
- }
- if (p === 'border-color') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopColor', vals[0]],
- ['borderRightColor', vals[1]],
- ['borderBottomColor', vals[2]],
- ['borderLeftColor', vals[3]],
- ];
- }
- if (p === 'padding') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['paddingTop', vals[0]],
- ['paddingRight', vals[1]],
- ['paddingBottom', vals[2]],
- ['paddingLeft', vals[3]],
- ];
- }
- if (p === 'font') return parseStaticFont(v);
- if (p === 'transition') {
- const parsed = parseStaticTransition(v);
- return [
- ...(parsed.property ? [['transitionProperty', parsed.property]] : []),
- ...(parsed.timing ? [['transitionTimingFunction', parsed.timing]] : []),
- ];
- }
- if (p === 'animation') {
- const parsed = parseStaticAnimation(v);
- return [
- ...(parsed.name ? [['animationName', parsed.name]] : []),
- ...(parsed.timing ? [['animationTimingFunction', parsed.timing]] : []),
- ];
- }
- const mapped = cssPropToCamel(p);
- if (STATIC_DEFAULT_STYLE[mapped] != null || STATIC_INHERITED_PROPS.has(mapped)) {
- return [[mapped, v]];
- }
- return [];
-}
-
-function compareStaticPriority(a, b) {
- if (!a) return true;
- if (!!b.important !== !!a.important) return !!b.important;
- if (!!b.inline !== !!a.inline) return !!b.inline;
- for (let i = 0; i < 3; i++) {
- if ((b.specificity[i] || 0) !== (a.specificity[i] || 0)) {
- return (b.specificity[i] || 0) > (a.specificity[i] || 0);
- }
- }
- return b.order >= a.order;
-}
-
-function staticSpecificity(selector) {
- const noWhere = selector.replace(/:where\([^)]*\)/g, '');
- const ids = (noWhere.match(/#[\w-]+/g) || []).length;
- const classes = (noWhere.match(/\.[\w-]+|\[[^\]]+\]|:(?!:)[\w-]+(?:\([^)]*\))?/g) || []).length;
- const stripped = noWhere
- .replace(/#[\w-]+/g, ' ')
- .replace(/\.[\w-]+|\[[^\]]+\]|:{1,2}[\w-]+(?:\([^)]*\))?/g, ' ')
- .replace(/[*>+~(),]/g, ' ');
- const types = (stripped.match(/\b[a-zA-Z][\w-]*\b/g) || []).length;
- return [ids, classes, types];
-}
-
-function applyStaticDeclaration(specified, node, prop, value, meta) {
- let map = specified.get(node);
- if (!map) { map = new Map(); specified.set(node, map); }
- for (const [expandedProp, expandedValue] of expandStaticDeclaration(prop, value)) {
- const existing = map.get(expandedProp);
- const next = { ...meta, prop: expandedProp, value: expandedValue };
- if (compareStaticPriority(existing, next)) map.set(expandedProp, next);
- }
-}
-
-function parseStaticStyleAttribute(styleText, orderBase = 0) {
- const decls = [];
- for (const part of String(styleText || '').split(';')) {
- const idx = part.indexOf(':');
- if (idx <= 0) continue;
- const prop = part.slice(0, idx).trim();
- let value = part.slice(idx + 1).trim();
- const important = /!important\s*$/i.test(value);
- value = value.replace(/\s*!important\s*$/i, '').trim();
- decls.push({ prop, value, important, order: orderBase + decls.length });
- }
- return decls;
-}
-
-function collectStaticCssRules(cssText, csstree) {
- const rules = [];
- let ast;
- try {
- ast = csstree.parse(cssText, { positions: false, parseValue: true, parseCustomProperty: false });
- } catch {
- return rules;
- }
- let order = 0;
- const walkList = (list, atRuleStack = []) => {
- list?.forEach?.(node => {
- if (node.type === 'Rule' && node.block) {
- if (atRuleStack.some(name => /keyframes$/i.test(name))) return;
- const selectorText = csstree.generate(node.prelude).trim();
- const declarations = [];
- node.block.children?.forEach?.(child => {
- if (child.type !== 'Declaration') return;
- declarations.push({
- prop: child.property,
- value: csstree.generate(child.value).trim(),
- important: !!child.important,
- });
- });
- for (const selector of splitCssList(selectorText)) {
- if (selector) rules.push({ selector, declarations, specificity: staticSpecificity(selector), order: order++ });
- }
- return;
- }
- if (node.type === 'Atrule' && node.block) {
- const name = String(node.name || '').toLowerCase();
- if (name === 'media' || name === 'supports' || name === 'layer') {
- walkList(node.block.children, [...atRuleStack, name]);
- }
- }
- });
- };
- walkList(ast.children);
- return rules;
-}
-
-class StaticElement {
- constructor(node, doc) {
- this.node = node;
- this._doc = doc;
- this.nodeType = 1;
- this.tagName = String(node.name || '').toUpperCase();
- this.nodeName = this.tagName;
- }
- get parentElement() {
- let cur = this.node.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- return cur ? this._doc.wrap(cur) : null;
- }
- get previousElementSibling() {
- let cur = this.node.prev;
- while (cur && cur.type !== 'tag') cur = cur.prev;
- return cur ? this._doc.wrap(cur) : null;
- }
- get children() {
- return (this.node.children || []).filter(child => child.type === 'tag').map(child => this._doc.wrap(child));
- }
- get childNodes() {
- return (this.node.children || []).map(child => {
- if (child.type === 'text') return { nodeType: 3, textContent: child.data || '' };
- if (child.type === 'tag') return this._doc.wrap(child);
- return { nodeType: 8, textContent: child.data || '' };
- });
- }
- get textContent() {
- return this._doc.domutils.textContent(this.node);
- }
- get className() {
- return this.getAttribute('class') || '';
- }
- get id() {
- return this.getAttribute('id') || '';
- }
- getAttribute(name) {
- return this.node.attribs?.[name] ?? null;
- }
- querySelector(selector) {
- try {
- const found = this._doc.selectOne(selector, this.node.children || []);
- return found ? this._doc.wrap(found) : null;
- } catch {
- return null;
- }
- }
- querySelectorAll(selector) {
- try {
- return this._doc.selectAll(selector, this.node.children || []).map(node => this._doc.wrap(node));
- } catch {
- return [];
- }
- }
- closest(selector) {
- let cur = this.node;
- while (cur && cur.type === 'tag') {
- try {
- if (this._doc.is(cur, selector)) return this._doc.wrap(cur);
- } catch {
- return null;
- }
- cur = cur.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- }
- return null;
- }
- contains(other) {
- let cur = other?.node || null;
- while (cur) {
- if (cur === this.node) return true;
- cur = cur.parent;
- }
- return false;
- }
-}
-
-class StaticDocument {
- constructor(root, modules) {
- this.root = root;
- this.selectAll = modules.selectAll;
- this.selectOne = modules.selectOne;
- this.is = modules.is;
- this.domutils = modules.domutils;
- this._wrappers = new WeakMap();
- this._styleMap = new WeakMap();
- }
- wrap(node) {
- let wrapped = this._wrappers.get(node);
- if (!wrapped) {
- wrapped = new StaticElement(node, this);
- this._wrappers.set(node, wrapped);
- }
- return wrapped;
- }
- querySelectorAll(selector) {
- try {
- return this.selectAll(selector, this.root.children || []).map(node => this.wrap(node));
- } catch {
- return [];
- }
- }
- querySelector(selector) {
- try {
- const found = this.selectOne(selector, this.root.children || []);
- return found ? this.wrap(found) : null;
- } catch {
- return null;
- }
- }
- get documentElement() {
- return this.querySelector('html');
- }
- get body() {
- return this.querySelector('body');
- }
- setStyle(node, style) {
- this._styleMap.set(node, style);
- }
- getStyle(el) {
- return this._styleMap.get(el.node) || makeStaticStyle();
- }
-}
-
-function makeStaticStyle(values = {}) {
- const style = { ...STATIC_DEFAULT_STYLE, ...values };
- style.getPropertyValue = (prop) => {
- const key = cssPropToCamel(prop);
- return style[key] || style[prop] || '';
- };
- return style;
-}
-
-function buildStaticWindow(staticDoc) {
- return {
- document: staticDoc,
- getComputedStyle: (el) => staticDoc.getStyle(el),
- };
-}
-
-function collectStaticCssText(root, fileDir, profile, filePath, modules) {
- const styleTexts = [];
- for (const styleEl of modules.selectAll('style', root.children || [])) {
- styleTexts.push(modules.domutils.textContent(styleEl));
- }
- const links = modules.selectAll('link', root.children || []);
- for (const link of links) {
- const rel = link.attribs?.rel || '';
- const href = link.attribs?.href || '';
- if (!/\bstylesheet\b/i.test(rel) || !href || /^(https?:)?\/\//i.test(href)) continue;
- const cssPath = path.resolve(fileDir, href);
- try {
- const css = profileStep(profile, {
- engine: 'static-html',
- phase: 'preprocess',
- ruleId: 'inline-linked-stylesheet',
- target: filePath,
- detail: href,
- }, () => fs.readFileSync(cssPath, 'utf-8'));
- styleTexts.push(css);
- } catch { /* skip unreadable */ }
- }
- return styleTexts.join('\n');
-}
-
-function buildStaticStyleMap(root, staticDoc, cssText, modules, profile, filePath) {
- const specified = new Map();
- const allNodes = modules.selectAll('*', root.children || []);
- const rules = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-css',
- ruleId: 'css-rules',
- target: filePath,
- }, () => collectStaticCssRules(cssText, modules.csstree));
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'css-selectors',
- target: filePath,
- }, () => {
- for (const rule of rules) {
- let matched;
- try {
- matched = modules.selectAll(rule.selector, root.children || []);
- } catch {
- recordProfileEvent(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'unsupported-selector',
- target: filePath,
- ms: 0,
- findings: 0,
- detail: rule.selector,
- });
- continue;
- }
- for (const node of matched) {
- for (const decl of rule.declarations) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: rule.specificity,
- order: rule.order,
- inline: false,
- });
- }
- }
- }
-
- let inlineOrder = rules.length + 1;
- for (const node of allNodes) {
- const styleText = node.attribs?.style;
- if (!styleText) continue;
- for (const decl of parseStaticStyleAttribute(styleText, inlineOrder)) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: [1, 0, 0],
- order: decl.order,
- inline: true,
- });
- }
- inlineOrder += 1000;
- }
- });
-
- const computeNode = (node, parentStyle = null, parentCustom = new Map()) => {
- const specifiedMap = specified.get(node) || new Map();
- const customProps = new Map(parentCustom);
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) customProps.set(prop, resolveVarRefs(decl.value, customProps));
- }
- const values = {};
- for (const prop of Object.keys(STATIC_DEFAULT_STYLE)) {
- if (STATIC_INHERITED_PROPS.has(prop) && parentStyle?.[prop] != null) values[prop] = parentStyle[prop];
- else values[prop] = STATIC_DEFAULT_STYLE[prop];
- }
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) continue;
- values[prop] = normalizeStaticCssValue(prop, decl.value, customProps, parentStyle, values);
- }
- const style = makeStaticStyle(values);
- staticDoc.setStyle(node, style);
- for (const child of node.children || []) {
- if (child.type === 'tag') computeNode(child, style, customProps);
- }
- };
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'cascade',
- ruleId: 'compute-styles',
- target: filePath,
- }, () => {
- for (const child of root.children || []) {
- if (child.type === 'tag') computeNode(child);
- }
- });
-}
-
-export {
- BORDER_SHORTHAND_RE,
- NAMED_COLORS,
- normalizeColorForCheck,
- buildBorderOverrideMap,
- unwrapCssAtLayer,
- STATIC_INHERITED_PROPS,
- STATIC_DEFAULT_STYLE,
- STATIC_PROP_MAP,
- STATIC_NAMED_COLORS,
- splitCssList,
- splitCssTokens,
- cssPropToCamel,
- staticColorToCss,
- parseStaticColor,
- extractStaticColor,
- normalizeStaticCssValue,
- expandStaticBoxValues,
- parseStaticBorder,
- parseStaticFont,
- parseStaticTransition,
- parseStaticAnimation,
- expandStaticDeclaration,
- compareStaticPriority,
- staticSpecificity,
- applyStaticDeclaration,
- parseStaticStyleAttribute,
- collectStaticCssRules,
- StaticElement,
- StaticDocument,
- makeStaticStyle,
- buildStaticWindow,
- collectStaticCssText,
- buildStaticStyleMap,
-};
@@ -1,174 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import {
- checkElementBorders,
- checkElementColors,
- checkElementGlow,
- checkElementHeroEyebrow,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementMotion,
- checkElementQuality,
- checkHtmlPatterns,
- checkPageLayout,
- checkPageQualityFromDoc,
- checkRepeatedSectionKickersFromDoc,
- resolveBackground,
- resolveBorderRadiusPx,
-} from '../../rules/checks.mjs';
-import { detectText } from '../regex/detect-text.mjs';
-import {
- StaticDocument,
- buildStaticStyleMap,
- buildStaticWindow,
- collectStaticCssText,
-} from './css-cascade.mjs';
-
-function checkStaticPageTypography(document, window) {
- const findings = [];
- const fonts = new Set();
- const overusedFound = new Set();
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span, div')) {
- const hasText = el.childNodes.some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const ff = window.getComputedStyle(el).fontFamily || '';
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
- if (fonts.size === 1 && document.querySelectorAll('*').length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div')) {
- const fontSize = parseFloat(window.getComputedStyle(el).fontSize);
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
- return findings;
-}
-
-const STATIC_ELEMENT_RULES = [
- { id: 'border-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementBorders(tag, style, null, resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window)) },
- { id: 'color-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementColors(el, style, tag, window, customPropMap, false) },
- { id: 'dark-glow', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window, customPropMap)) },
- { id: 'motion-rules', selector: '*', run: (el, tag, style) => checkElementMotion(tag, style) },
- { id: 'icon-tile-stack', selector: 'h1,h2,h3,h4,h5,h6', run: (el, tag, _style, window) => checkElementIconTile(el, tag, window) },
- { id: 'italic-serif-display', selector: 'h1,h2', run: (el, tag, style) => checkElementItalicSerif(el, style, tag) },
- { id: 'hero-eyebrow-chip', selector: 'h1', run: (el, tag, style, window, customPropMap) => checkElementHeroEyebrow(el, style, tag, window, customPropMap) },
- { id: 'quality-rules', selector: '*', run: (el, tag, style, window) => checkElementQuality(el, style, tag, window) },
-];
-
-async function detectHtml(filePath, options = {}) {
- const profile = options?.profile;
- const html = profileStep(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'read-html',
- target: filePath,
- }, () => fs.readFileSync(filePath, 'utf-8'));
-
- let modules;
- try {
- modules = await profileStepAsync(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'import-static-parser',
- target: filePath,
- }, async () => {
- const [htmlparser2, cssSelect, csstree, domutils] = await Promise.all([
- import('htmlparser2'),
- import('css-select'),
- import('css-tree'),
- import('domutils'),
- ]);
- return {
- parseDocument: htmlparser2.parseDocument,
- selectAll: cssSelect.selectAll,
- selectOne: cssSelect.selectOne,
- is: cssSelect.is,
- csstree,
- domutils,
- };
- });
- } catch {
- return detectText(html, filePath, options);
- }
-
- const resolvedPath = path.resolve(filePath);
- const fileDir = path.dirname(resolvedPath);
- const root = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-html',
- ruleId: 'parse-document',
- target: filePath,
- }, () => modules.parseDocument(html, { lowerCaseAttributeNames: false, lowerCaseTags: true }));
-
- const cssText = collectStaticCssText(root, fileDir, profile, filePath, modules);
- const document = new StaticDocument(root, modules);
- buildStaticStyleMap(root, document, cssText, modules, profile, filePath);
- const window = buildStaticWindow(document);
-
- const customPropMap = null;
-
- const findings = [];
- const runElementCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'element', ruleId, target: filePath }, callback)
- : callback();
-
- const visitedByRule = new Map();
- for (const rule of STATIC_ELEMENT_RULES) {
- const elements = document.querySelectorAll(rule.selector);
- visitedByRule.set(rule.id, elements.length);
- for (const el of elements) {
- const tag = el.tagName.toLowerCase();
- const style = window.getComputedStyle(el);
- for (const f of runElementCheck(rule.id, () => rule.run(el, tag, style, window, customPropMap))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
- }
-
- if (isFullPage(html)) {
- const runPageCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
- : callback();
- for (const f of runPageCheck('typography-rules', () => checkStaticPageTypography(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('repeated-section-kickers', () => checkRepeatedSectionKickersFromDoc(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('layout-rules', () => checkPageLayout(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('skipped-heading', () => checkPageQualityFromDoc(document))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('html-patterns', () => checkHtmlPatterns(html).filter(item =>
- item.id !== 'bounce-easing' && item.id !== 'layout-transition'
- ))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
-
- return findings;
-}
-
-export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -1,189 +0,0 @@
-function sanitizeScreenshotClip(clip, viewport) {
- if (!clip) return null;
- const x = Math.max(0, Math.floor(clip.x || 0));
- const y = Math.max(0, Math.floor(clip.y || 0));
- const width = Math.min(
- Math.max(1, Math.ceil(clip.width || 0)),
- Math.max(1, viewport?.width || 1600),
- );
- const height = Math.min(
- Math.max(1, Math.ceil(clip.height || 0)),
- 320,
- );
- if (width < 1 || height < 1) return null;
- return { x, y, width, height };
-}
-
-async function compareScreenshotContrast(page, beforeBase64, afterBase64, candidate) {
- return page.evaluate(async ({ beforeBase64, afterBase64, candidate }) => {
- const loadImage = (base64) => new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = () => reject(new Error('Could not decode contrast screenshot'));
- img.src = `data:image/png;base64,${base64}`;
- });
- const [before, after] = await Promise.all([loadImage(beforeBase64), loadImage(afterBase64)]);
- const width = Math.min(before.width, after.width);
- const height = Math.min(before.height, after.height);
- if (width < 1 || height < 1) return null;
-
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return null;
-
- ctx.drawImage(before, 0, 0, width, height);
- const beforePixels = ctx.getImageData(0, 0, width, height).data;
- ctx.clearRect(0, 0, width, height);
- ctx.drawImage(after, 0, 0, width, height);
- const afterPixels = ctx.getImageData(0, 0, width, height).data;
-
- const luminance = ({ r, g, b }) => {
- const convert = c => {
- const v = c / 255;
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
- };
- return 0.2126 * convert(r) + 0.7152 * convert(g) + 0.0722 * convert(b);
- };
- const ratio = (a, b) => {
- const l1 = luminance(a);
- const l2 = luminance(b);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
- };
-
- const cssTextColor = candidate.textColor && !candidate.preferRenderedForeground
- ? {
- r: candidate.textColor.r,
- g: candidate.textColor.g,
- b: candidate.textColor.b,
- }
- : null;
- const ratios = [];
- let glyphPixels = 0;
- let strongestDelta = 0;
- for (let i = 0; i < beforePixels.length; i += 4) {
- const delta = Math.abs(beforePixels[i] - afterPixels[i])
- + Math.abs(beforePixels[i + 1] - afterPixels[i + 1])
- + Math.abs(beforePixels[i + 2] - afterPixels[i + 2])
- + Math.abs(beforePixels[i + 3] - afterPixels[i + 3]);
- strongestDelta = Math.max(strongestDelta, delta);
- if (delta < 10) continue;
- glyphPixels++;
- const fg = cssTextColor || {
- r: beforePixels[i],
- g: beforePixels[i + 1],
- b: beforePixels[i + 2],
- };
- const bg = {
- r: afterPixels[i],
- g: afterPixels[i + 1],
- b: afterPixels[i + 2],
- };
- ratios.push(ratio(fg, bg));
- }
-
- if (ratios.length < 8) {
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: null,
- p10Ratio: null,
- medianRatio: null,
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: ratios[0],
- p10Ratio: pick(10),
- medianRatio: pick(50),
- };
- }, { beforeBase64, afterBase64, candidate });
-}
-
-async function captureVisualContrastCandidate(page, candidate, viewport) {
- const clip = sanitizeScreenshotClip(candidate.clip, viewport);
- if (!clip) return null;
-
- const beforeBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- const token = `impeccable-contrast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- const applied = await page.evaluate(({ selector, token, backgroundClipText }) => {
- let el;
- try {
- el = document.querySelector(selector);
- } catch {
- return false;
- }
- if (!el) return false;
- let style = document.getElementById('impeccable-visual-contrast-hide-style');
- if (!style) {
- style = document.createElement('style');
- style.id = 'impeccable-visual-contrast-hide-style';
- style.textContent = [
- '[data-impeccable-visual-contrast-target] {',
- ' color: transparent !important;',
- ' -webkit-text-fill-color: transparent !important;',
- ' text-shadow: none !important;',
- '}',
- '[data-impeccable-visual-contrast-target][data-impeccable-bgclip-text="true"] {',
- ' background-image: none !important;',
- '}',
- ].join('\n');
- document.head.appendChild(style);
- }
- el.setAttribute('data-impeccable-visual-contrast-target', token);
- if (backgroundClipText) el.setAttribute('data-impeccable-bgclip-text', 'true');
- return true;
- }, {
- selector: candidate.selector,
- token,
- backgroundClipText: candidate.backgroundClipText,
- });
- if (!applied) return null;
-
- let afterBase64;
- try {
- afterBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- } finally {
- await page.evaluate(({ selector }) => {
- try {
- const el = document.querySelector(selector);
- if (el) {
- el.removeAttribute('data-impeccable-visual-contrast-target');
- el.removeAttribute('data-impeccable-bgclip-text');
- }
- } catch {
- // Ignore invalid or stale selectors during cleanup.
- }
- }, { selector: candidate.selector }).catch(() => {});
- }
-
- const metrics = await compareScreenshotContrast(page, beforeBase64, afterBase64, candidate);
- if (!metrics || !Number.isFinite(metrics.p10Ratio) || metrics.glyphPixels < 8) return null;
- const measuredRatio = metrics.p10Ratio;
- if (measuredRatio >= candidate.threshold) return null;
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const reasonLabel = (candidate.reasons || []).slice(0, 3).join(', ') || 'visual background';
- return {
- id: 'low-contrast',
- snippet: `pixel contrast ${measuredRatio.toFixed(1)}:1 median ${metrics.medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) on ${reasonLabel}${textLabel}`,
- };
-}
-
-export {
- sanitizeScreenshotClip,
- compareScreenshotContrast,
- captureVisualContrastCandidate,
-};
@@ -1,12 +0,0 @@
-import { getAntipattern } from './registry/antipatterns.mjs';
-
-function getAP(id) {
- return getAntipattern(id);
-}
-
-function finding(id, filePath, snippet, line = 0) {
- const ap = getAP(id);
- return { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', file: filePath, line, snippet };
-}
-
-export { getAP, finding };
@@ -1,198 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-// ---------------------------------------------------------------------------
-// File walker
-// ---------------------------------------------------------------------------
-
-const SKIP_DIRS = new Set([
- 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
- '.svelte-kit', '__pycache__', '.turbo', '.vercel',
-]);
-
-const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
- '.jsx', '.tsx', '.js', '.ts',
- '.vue', '.svelte', '.astro',
-]);
-
-const HTML_EXTENSIONS = new Set(['.html', '.htm']);
-
-function walkDir(dir) {
- const files = [];
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
- for (const entry of entries) {
- if (SKIP_DIRS.has(entry.name)) continue;
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) files.push(...walkDir(full));
- else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
- }
- return files;
-}
-
-
-// ---------------------------------------------------------------------------
-// Import graph (multi-file awareness)
-// ---------------------------------------------------------------------------
-
-function resolveImport(specifier, fromDir, fileSet) {
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
- const base = path.resolve(fromDir, specifier);
- if (fileSet.has(base)) return base;
- for (const ext of SCANNABLE_EXTENSIONS) {
- const withExt = base + ext;
- if (fileSet.has(withExt)) return withExt;
- }
- // index file convention
- for (const ext of SCANNABLE_EXTENSIONS) {
- const indexFile = path.join(base, 'index' + ext);
- if (fileSet.has(indexFile)) return indexFile;
- }
- return null;
-}
-
-function buildImportGraph(files) {
- const fileSet = new Set(files);
- const graph = new Map();
-
- for (const file of files) {
- const content = fs.readFileSync(file, 'utf-8');
- const dir = path.dirname(file);
- const imports = new Set();
-
- // ES imports: import ... from '...' and import '...'
- const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
- let m;
- while ((m = esRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // CSS @import
- const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
- while ((m = cssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // SCSS @use / @forward
- const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
- while ((m = scssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- graph.set(file, imports);
- }
- return graph;
-}
-
-// ---------------------------------------------------------------------------
-// Framework dev server detection
-// ---------------------------------------------------------------------------
-
-const FRAMEWORK_CONFIGS = [
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /next/i } },
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-sveltekit-page', value: null } },
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /@vite\/client/ } },
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /astro/i } },
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
- portRe: /"port"\s*:\s*(\d+)/,
- fingerprint: { body: /ng-version/i } },
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
-];
-
-function detectFrameworkConfig(dir) {
- let entries;
- try { entries = fs.readdirSync(dir); } catch { return null; }
- const entrySet = new Set(entries);
-
- for (const cfg of FRAMEWORK_CONFIGS) {
- const match = cfg.files.find(f => entrySet.has(f));
- if (!match) continue;
-
- const configPath = path.join(dir, match);
- let port = cfg.defaultPort;
- try {
- const content = fs.readFileSync(configPath, 'utf-8');
- const portMatch = content.match(cfg.portRe);
- if (portMatch) port = parseInt(portMatch[1], 10);
- } catch { /* use default */ }
-
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
- }
- return null;
-}
-
-/**
- * Check if a port is listening and optionally verify it matches the expected framework.
- * Returns { listening: true, matched: true/false } or { listening: false }.
- */
-async function isPortListening(port, fingerprint = null) {
- if (!fingerprint) {
- // Simple TCP probe fallback
- const net = await import('node:net');
- return new Promise((resolve) => {
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
- sock.setTimeout(500);
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
- sock.on('error', () => resolve({ listening: false }));
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
- });
- }
-
- // HTTP probe with fingerprint matching
- try {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 2000);
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
- clearTimeout(timeout);
-
- // Check header fingerprint
- if (fingerprint.header) {
- const val = res.headers.get(fingerprint.header);
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
- return { listening: true, matched: true };
- }
- }
-
- // Check body fingerprint
- if (fingerprint.body) {
- const body = await res.text();
- if (fingerprint.body.test(body)) {
- return { listening: true, matched: true };
- }
- }
-
- // Port is listening but doesn't match the expected framework
- return { listening: true, matched: false };
- } catch {
- return { listening: false };
- }
-}
-
-export {
- SKIP_DIRS,
- SCANNABLE_EXTENSIONS,
- HTML_EXTENSIONS,
- walkDir,
- resolveImport,
- buildImportGraph,
- FRAMEWORK_CONFIGS,
- detectFrameworkConfig,
- isPortListening,
-};
@@ -1,166 +0,0 @@
-function profileNow() {
- return typeof performance !== 'undefined' && performance.now
- ? performance.now()
- : Date.now();
-}
-
-function createDetectorProfile() {
- return { events: [] };
-}
-
-function recordProfileEvent(profile, event) {
- if (!profile) return;
- const normalized = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- ms: Number.isFinite(event.ms) ? event.ms : 0,
- findings: Number.isFinite(event.findings) ? event.findings : 0,
- };
- if (event.detail) normalized.detail = event.detail;
- if (Array.isArray(event.findingIds) && event.findingIds.length) {
- normalized.findingIds = event.findingIds;
- }
- if (typeof profile === 'function') {
- profile(normalized);
- } else if (typeof profile.record === 'function') {
- profile.record(normalized);
- } else if (Array.isArray(profile.events)) {
- profile.events.push(normalized);
- } else if (Array.isArray(profile)) {
- profile.push(normalized);
- }
-}
-
-function extractFindingIds(findings) {
- if (!Array.isArray(findings) || findings.length === 0) return [];
- return [...new Set(findings.map(f => f?.id || f?.type || f?.antipattern).filter(Boolean))];
-}
-
-function profileFindings(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-function profileStep(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-async function profileFindingsAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = await callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-async function profileStepAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return await callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-function percentile(sortedValues, pct) {
- if (!sortedValues.length) return 0;
- const idx = Math.min(
- sortedValues.length - 1,
- Math.max(0, Math.ceil((pct / 100) * sortedValues.length) - 1),
- );
- return sortedValues[idx];
-}
-
-function summarizeDetectorProfile(profile) {
- const events = Array.isArray(profile)
- ? profile
- : (Array.isArray(profile?.events) ? profile.events : []);
- const groups = new Map();
- for (const event of events) {
- const key = [
- event.engine || 'unknown',
- event.phase || 'unknown',
- event.ruleId || 'unknown',
- event.target || '',
- ].join('\u0000');
- let group = groups.get(key);
- if (!group) {
- group = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- calls: 0,
- totalMs: 0,
- findings: 0,
- samples: [],
- };
- groups.set(key, group);
- }
- const ms = Number.isFinite(event.ms) ? event.ms : 0;
- group.calls += 1;
- group.totalMs += ms;
- group.findings += Number.isFinite(event.findings) ? event.findings : 0;
- group.samples.push(ms);
- }
- return [...groups.values()]
- .map(group => {
- const samples = group.samples.sort((a, b) => a - b);
- return {
- engine: group.engine,
- phase: group.phase,
- ruleId: group.ruleId,
- target: group.target,
- calls: group.calls,
- totalMs: Number(group.totalMs.toFixed(3)),
- avgMs: Number((group.totalMs / group.calls).toFixed(3)),
- p50: Number(percentile(samples, 50).toFixed(3)),
- p95: Number(percentile(samples, 95).toFixed(3)),
- findings: group.findings,
- };
- })
- .sort((a, b) => b.totalMs - a.totalMs);
-}
-
-export {
- profileNow,
- createDetectorProfile,
- recordProfileEvent,
- extractFindingIds,
- profileFindings,
- profileStep,
- profileFindingsAsync,
- profileStepAsync,
- percentile,
- summarizeDetectorProfile,
-};
@@ -1,278 +0,0 @@
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-const RULE_ENGINE_SUPPORT = {
- regex: new Set(['source', 'page-analyzer']),
- 'static-html': new Set(['element', 'page']),
- browser: new Set(['element', 'page', 'layout']),
- visual: new Set(['visual-contrast']),
-};
-
-function getAntipattern(id) {
- return ANTIPATTERNS.find(rule => rule.id === id);
-}
-
-function getRulesForCategory(category) {
- return ANTIPATTERNS.filter(rule => rule.category === category);
-}
-
-function getRuleEngineSupport(engine) {
- return RULE_ENGINE_SUPPORT[engine] || new Set();
-}
-
-export {
- ANTIPATTERNS,
- RULE_ENGINE_SUPPORT,
- getAntipattern,
- getRulesForCategory,
- getRuleEngineSupport,
-};
@@ -1,1948 +0,0 @@
-import {
- BORDER_SAFE_TAGS,
- GENERIC_FONTS,
- KNOWN_SERIF_FONTS,
- OVERUSED_FONTS,
- SAFE_TAGS,
- WCAG_LARGE_BOLD_TEXT_PX,
- WCAG_LARGE_TEXT_PX,
- isBrandFontOnOwnDomain,
-} from '../shared/constants.mjs';
-import {
- colorToHex,
- contrastRatio,
- getHue,
- hasChroma,
- isNeutralColor,
- parseGradientColors,
- parseRgb,
- relativeLuminance,
-} from '../shared/color.mjs';
-
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-export {
- checkBorders,
- isEmojiOnlyText,
- checkColors,
- isCardLikeFromProps,
- checkIconTile,
- resolveSerif,
- checkItalicSerif,
- isAccentColor,
- checkHeroEyebrow,
- checkRepeatedSectionKickers,
- checkMotion,
- checkGlow,
- checkHtmlPatterns,
- readOwnBackgroundColor,
- resolveBackground,
- resolveGradientStops,
- parseRadiusToPx,
- resolveBorderRadiusPx,
- checkElementBordersDOM,
- checkElementColorsDOM,
- checkElementIconTileDOM,
- checkElementItalicSerifDOM,
- checkElementHeroEyebrowDOM,
- buildCustomPropMap,
- resolveVarRefs,
- oklchToRgb,
- parseAnyColor,
- parseColorResolved,
- cleanInlineText,
- isRepeatedKickerCandidate,
- collectRepeatedSectionKickerCandidates,
- checkRepeatedSectionKickersDOM,
- checkElementMotionDOM,
- checkElementGlowDOM,
- checkElementAIPaletteDOM,
- resolveFontSizePx,
- resolveLengthPx,
- checkQuality,
- checkElementQualityDOM,
- checkPageQualityFromDoc,
- checkPageQualityDOM,
- checkElementQuality,
- checkElementBorders,
- checkElementColors,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementHeroEyebrow,
- checkRepeatedSectionKickersFromDoc,
- checkElementMotion,
- checkElementGlow,
- checkTypography,
- isCardLikeDOM,
- checkLayout,
- checkPageTypography,
- isCardLike,
- checkPageLayout,
-};
@@ -1,124 +0,0 @@
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-export {
- isNeutralColor,
- parseRgb,
- relativeLuminance,
- contrastRatio,
- parseGradientColors,
- hasChroma,
- getHue,
- colorToHex,
-};
@@ -1,101 +0,0 @@
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-export {
- SAFE_TAGS,
- BORDER_SAFE_TAGS,
- OVERUSED_FONTS,
- GOOGLE_DOMAINS,
- VERCEL_DOMAINS,
- GITHUB_DOMAINS,
- BRAND_FONT_DOMAINS,
- isBrandFontOnOwnDomain,
- GENERIC_FONTS,
- WCAG_LARGE_TEXT_PX,
- WCAG_LARGE_BOLD_TEXT_PX,
- KNOWN_SERIF_FONTS,
-};
@@ -1,7 +0,0 @@
-/** Check if content looks like a full page (not a component/partial) */
-function isFullPage(content) {
- const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
- return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
-}
-
-export { isFullPage };
@@ -1,110 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-export const IMPECCABLE_DIR = '.impeccable';
-export const LIVE_DIR = 'live';
-export const CRITIQUE_DIR = 'critique';
-
-export function getImpeccableDir(cwd = process.cwd()) {
- return path.join(cwd, IMPECCABLE_DIR);
-}
-
-export function getDesignSidecarPath(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), 'design.json');
-}
-
-export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {
- const candidates = [
- getDesignSidecarPath(cwd),
- path.join(cwd, 'DESIGN.json'),
- ];
- const contextLegacy = path.join(contextDir, 'DESIGN.json');
- if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
- return candidates;
-}
-
-export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
- return firstExisting(getDesignSidecarCandidates(cwd, contextDir));
-}
-
-export function getLiveDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), LIVE_DIR);
-}
-
-export function getLiveConfigPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'config.json');
-}
-
-export function getLegacyLiveConfigPath(scriptsDir) {
- return path.join(scriptsDir, 'config.json');
-}
-
-export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {
- if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
- const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
- return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
- }
- const primary = getLiveConfigPath(cwd);
- if (fs.existsSync(primary)) return primary;
- if (scriptsDir) {
- const legacy = getLegacyLiveConfigPath(scriptsDir);
- if (fs.existsSync(legacy)) return legacy;
- }
- return primary;
-}
-
-export function getLiveServerPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'server.json');
-}
-
-export function getLegacyLiveServerPath(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live.json');
-}
-
-export function readLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try {
- return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };
- } catch {
- /* try next */
- }
- }
- return null;
-}
-
-export function writeLiveServerInfo(cwd = process.cwd(), info) {
- const filePath = getLiveServerPath(cwd);
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- fs.writeFileSync(filePath, JSON.stringify(info));
- return filePath;
-}
-
-export function removeLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try { fs.unlinkSync(filePath); } catch {}
- }
-}
-
-export function getLiveSessionsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'sessions');
-}
-
-export function getLegacyLiveSessionsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'sessions');
-}
-
-export function getLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'annotations');
-}
-
-export function getCritiqueDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), CRITIQUE_DIR);
-}
-
-export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'annotations');
-}
-
-function firstExisting(paths) {
- return paths.find((filePath) => fs.existsSync(filePath)) || null;
-}
@@ -1,69 +0,0 @@
-/**
- * Decide whether a given file is "generated" (regenerated by a build step,
- * unsafe to write variants into) or "source" (safe to edit, changes persist).
- *
- * Why this matters: when the user picks an element on a page whose underlying
- * file is regenerated by a build step (e.g. `scripts/build-sub-pages.js`
- * rewriting `public/docs/*.html`), writing variants or accepted changes into
- * that file is silent data loss — the next build wipes them.
- *
- * Signals, in order of reliability:
- * 1. Git check-ignore: gitignored files are assumed generated.
- * 2. File-header markers ("GENERATED", "DO NOT EDIT", "AUTO-GENERATED")
- * within the first ~300 characters — catches non-git projects.
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-
-const HEADER_SCAN_BYTES = 300;
-const HEADER_MARKERS = [
- /@generated\b/i,
- /\bGENERATED\s+FILE\b/,
- /\bAUTO-?GENERATED\b/i,
- /\bDO\s+NOT\s+EDIT\b/i,
-];
-
-/**
- * @param {string} filePath - absolute or cwd-relative path
- * @param {object} [options]
- * @param {string} [options.cwd] - project root (defaults to process.cwd())
- */
-export function isGeneratedFile(filePath, options = {}) {
- const cwd = options.cwd || process.cwd();
- const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
-
- if (isGitIgnored(absPath, cwd)) return true;
- if (hasGeneratedHeader(absPath)) return true;
- return false;
-}
-
-function isGitIgnored(absPath, cwd) {
- try {
- execSync(`git check-ignore --quiet ${JSON.stringify(absPath)}`, {
- cwd,
- stdio: 'ignore',
- });
- return true; // exit 0 = ignored
- } catch (err) {
- // Exit code 1 = not ignored. Exit code 128 = not a git repo or other error.
- // In both cases, treat as "not known to be ignored."
- return false;
- }
-}
-
-function hasGeneratedHeader(absPath) {
- let fd;
- try {
- fd = fs.openSync(absPath, 'r');
- const buf = Buffer.alloc(HEADER_SCAN_BYTES);
- const bytesRead = fs.readSync(fd, buf, 0, HEADER_SCAN_BYTES, 0);
- const head = buf.slice(0, bytesRead).toString('utf-8');
- return HEADER_MARKERS.some((re) => re.test(head));
- } catch {
- return false;
- } finally {
- if (fd !== undefined) { try { fs.closeSync(fd); } catch {} }
- }
-}
@@ -1,595 +0,0 @@
-/**
- * CLI helper: deterministic accept/discard of variant sessions.
- *
- * Usage:
- * node live-accept.mjs --id SESSION_ID --discard
- * node live-accept.mjs --id SESSION_ID --variant N
- *
- * For discard: removes the entire variant wrapper and restores the original.
- * For accept: replaces the wrapper with the chosen variant's content. If the
- * session had a colocated <style> block, it's preserved with carbonize markers
- * for a background agent to integrate into the project's CSS.
- *
- * Output: JSON to stdout.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-export async function acceptCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-accept.mjs [options]
-
-Deterministic accept/discard for live variant sessions.
-
-Modes:
- --discard Remove variants, restore original
- --variant N Accept variant N, discard the rest
-
-Required:
- --id SESSION_ID Session ID of the variant wrapper
-
-Output (JSON):
- { handled, file, carbonize }`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const variantNum = argVal(args, '--variant');
- const paramValuesRaw = argVal(args, '--param-values');
- const isDiscard = args.includes('--discard');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }
-
- let paramValues = null;
- if (paramValuesRaw) {
- try { paramValues = JSON.parse(paramValuesRaw); }
- catch { paramValues = null; } // malformed blob: skip the comment rather than failing the accept
- }
-
- // Find the file containing this session's markers
- const found = findSessionFile(id, process.cwd());
- if (!found) {
- console.log(JSON.stringify({ handled: false, error: 'Session markers not found for id: ' + id }));
- process.exit(0);
- }
-
- const { file: targetFile, content, lines } = found;
- const relFile = path.relative(process.cwd(), targetFile);
-
- // Bail if the session lives in a generated file. The agent manually wrote
- // the wrapper there for preview, and is responsible for writing the
- // accepted variant to true source (or cleaning up on discard). See
- // "Handle fallback" in live.md.
- if (isGeneratedFile(targetFile, { cwd: process.cwd() })) {
- console.log(JSON.stringify({
- handled: false,
- mode: 'fallback',
- file: relFile,
- hint: 'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.',
- }));
- process.exit(0);
- }
-
- if (isDiscard) {
- const result = handleDiscard(id, lines, targetFile);
- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));
- } else {
- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);
- // Single-line attention-grabber when cleanup is required. The full
- // five-step checklist lives in reference/live.md (loaded once per
- // session); repeating it per-event would waste tokens.
- if (result.carbonize) {
- result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + relFile + '. See reference/live.md "Required after accept".';
- }
- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));
- }
-}
-
-// ---------------------------------------------------------------------------
-// Discard
-// ---------------------------------------------------------------------------
-
-function handleDiscard(id, lines, targetFile) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const original = extractOriginal(lines, block);
- const isJsx = detectCommentSyntax(targetFile).open === '{/*';
- const replaceRange = expandReplaceRange(block, lines, isJsx);
-
- // Restore at the line we're actually replacing FROM, not the marker line.
- // For JSX wrappers the marker comments live INSIDE the outer `<div>`, so
- // `block.start` sits 2 spaces deeper than the original element. Using that
- // as the deindent base would push the restored content 2 spaces too far
- // right on every JSX/TSX session. `replaceRange.start` is the outer wrapper
- // line, which is at the original element's indent for both HTML and JSX.
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
- const restored = deindentContent(original, indent);
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...restored,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
- return {};
-}
-
-// ---------------------------------------------------------------------------
-// Accept
-// ---------------------------------------------------------------------------
-
-function handleAccept(id, variantNum, lines, targetFile, paramValues) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const commentSyntax = detectCommentSyntax(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- // Anchor indent on the line we're replacing FROM (the outer wrapper),
- // not on `block.start` — for JSX that's the marker comment 2 spaces
- // deeper than the original element. See handleDiscard for the full
- // rationale.
- const replaceRange = expandReplaceRange(block, lines, isJsx);
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
-
- // Extract the chosen variant's inner content
- const variantContent = extractVariant(lines, block, variantNum);
- if (!variantContent) return { handled: false, error: 'Variant ' + variantNum + ' not found' };
-
- // Extract CSS block if present
- const cssContent = extractCss(lines, block, id);
-
- // Check if carbonizing is needed:
- // - CSS block exists, OR
- // - variant HTML contains helper classes/attributes that need cleanup
- const variantText = variantContent.join('\n');
- const hasHelperAttrs = variantText.includes('data-impeccable-variant');
- const needsCarbonize = !!(cssContent || hasHelperAttrs);
-
- // Build the replacement
- const restored = deindentContent(variantContent, indent);
- const replacement = [];
-
- if (cssContent) {
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
- // JSX targets need the CSS body wrapped in a template literal so that the
- // `{` and `}` in CSS rules don't get parsed as JSX expressions.
- replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
- // Re-indent CSS content to match
- for (const cssLine of cssContent) {
- replacement.push(indent + cssLine.trimStart());
- }
- replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
- if (paramValues && Object.keys(paramValues).length > 0) {
- // Preserve the user's knob positions for the carbonize-cleanup agent
- // to bake into the final CSS when it collapses scoped rules.
- replacement.push(indent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close);
- }
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close);
- }
-
- // Keep the `@scope ([data-impeccable-variant="N"])` selectors in the
- // carbonize CSS block working visually by re-wrapping the accepted content
- // in a data-impeccable-variant="N" div with `display: contents` (so layout
- // isn't affected). The carbonize agent strips this attribute + wrapper when
- // it moves the CSS to a proper stylesheet.
- //
- // Style attribute syntax has to follow the host file's flavor — JSX files
- // need the object form, otherwise React 19 throws "Failed to set indexed
- // property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
- if (cssContent) {
- const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
- replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
- replacement.push(...restored);
- replacement.push(indent + '</div>');
- } else {
- replacement.push(...restored);
- }
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...replacement,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- return { carbonize: needsCarbonize };
-}
-
-// ---------------------------------------------------------------------------
-// Parsing helpers
-// ---------------------------------------------------------------------------
-
-/**
- * Find the start/end marker lines for a session.
- * Returns { start, end } (0-indexed line numbers) or null.
- */
-function findMarkerBlock(id, lines) {
- let start = -1;
- let end = -1;
- const startPattern = 'impeccable-variants-start ' + id;
- const endPattern = 'impeccable-variants-end ' + id;
-
- for (let i = 0; i < lines.length; i++) {
- if (start === -1 && lines[i].includes(startPattern)) start = i;
- if (lines[i].includes(endPattern)) { end = i; break; }
- }
-
- return (start !== -1 && end !== -1) ? { start, end } : null;
-}
-
-/**
- * Compute the line range to REPLACE (vs. just the marker range to extract
- * from). For JSX/TSX wrappers, live-wrap places the marker comments INSIDE
- * the `<div data-impeccable-variants="ID">` outer wrapper so the picked
- * element's JSX slot keeps a single child — a Fragment `<></>` would have
- * solved the multi-sibling case but failed inside `asChild` / cloneElement
- * parents with "Invalid prop supplied to React.Fragment".
- *
- * That means the marker block is enclosed by the wrapper `<div>` opener
- * (with `data-impeccable-variants="ID"`) and its matching `</div>`. We
- * walk back to the opener and forward to the closer so accept/discard
- * remove the entire scaffold, not just the inner markers.
- *
- * Marker lines themselves stay where they were so extractOriginal /
- * extractVariant / extractCss continue to walk the same range.
- */
-function expandReplaceRange(block, lines, isJsx) {
- if (!isJsx) return { start: block.start, end: block.end };
-
- let { start, end } = block;
-
- // Walk back for the wrapper `<div data-impeccable-variants="..."` opener.
- // The attr may sit on a continuation line of a multi-line opening tag, so
- // also walk to the line that actually contains `<div`.
- for (let i = start - 1; i >= Math.max(0, start - 12); i--) {
- if (/data-impeccable-variants=/.test(lines[i])) {
- let opener = i;
- while (opener > 0 && !/<div\b/.test(lines[opener])) opener--;
- start = opener;
- break;
- }
- }
-
- // Walk forward to the matching `</div>` by div-depth tracking from the
- // wrapper opener. Operate on JOINED text instead of per-line: a
- // multi-line self-closing JSX `<div\n className="spacer"\n/>` would
- // fool per-line regex tracking (the `<div` line matches openRe but the
- // `/>` line never matches selfCloseRe since it needs `<div` on the same
- // line). That left depth permanently over-counted and the wrapper's
- // outer `</div>` orphaned after accept/discard. Single regex with
- // `[^>]*?` (which spans newlines in JS) handles either form correctly.
- const joined = lines.slice(start).join('\n');
- // Match either `<div … />` (self-close, group 1 is `/`), `<div … >`
- // (open, group 1 is empty), or `</div>`.
- const tagRe = /<div\b[^>]*?(\/?)>|<\/div\s*>/g;
- let depth = 0;
- let m;
- while ((m = tagRe.exec(joined)) !== null) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && m[1] === '/';
- if (isClose) depth--;
- else if (!isSelfClose) depth++;
- if (depth <= 0) {
- // m.index is offset within `joined`; convert back to a file line.
- const linesBefore = joined.slice(0, m.index + m[0].length).split('\n').length - 1;
- const candidateEnd = start + linesBefore;
- if (candidateEnd >= end) {
- end = candidateEnd;
- break;
- }
- }
- }
-
- return { start, end };
-}
-
-/**
- * Join wrapper lines into a single string with `<style>` elements removed so
- * marker matching and div-depth tracking aren't confused by:
- * - CSS `@scope ([data-impeccable-variant="N"])` strings that look like the
- * HTML marker we're searching for
- * - JSX self-closing `<style ... />` (no separate `</style>` to close on)
- * - Same-line `<style>…</style>` blocks
- * - Multi-line `<style>\n…\n</style>` blocks
- */
-function stripStyleAndJoin(lines, block) {
- const out = [];
- let inStyle = false;
- for (let i = block.start; i <= block.end; i++) {
- let line = lines[i];
-
- if (!inStyle) {
- // Strip any complete <style> elements on this line (self-closed or
- // same-line-closed), including their body content.
- line = line
- .replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/g, '')
- .replace(/<style\b[^>]*\/\s*>/g, '');
-
- // If a <style> opener remains (multi-line body starts here), strip from
- // the opener to end-of-line and flip into skip mode.
- const openerIdx = line.search(/<style\b/);
- if (openerIdx !== -1) {
- line = line.slice(0, openerIdx);
- inStyle = true;
- }
- out.push(line);
- } else {
- // In multi-line style body; drop everything until we see </style>.
- const closeIdx = line.search(/<\/style\s*>/);
- if (closeIdx !== -1) {
- inStyle = false;
- out.push(line.slice(closeIdx).replace(/<\/style\s*>/, ''));
- }
- // else: skip line entirely
- }
- }
- return out.join('\n');
-}
-
-/**
- * Find the inner content of `<TAG ...attrMatch...>…</TAG>` inside `text`,
- * handling nested same-tag elements via depth counting. `attrMatch` is a
- * regex source fragment that must appear inside the opener tag.
- * Returns the inner string (may be empty), or null if not found.
- */
-function extractInnerByAttr(text, attrMatch) {
- const openerRe = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*' + attrMatch + '[^>]*>');
- const openMatch = text.match(openerRe);
- if (!openMatch) return null;
-
- const tagName = openMatch[1];
- const innerStart = openMatch.index + openMatch[0].length;
-
- // Match any opener or closer of this tag name after innerStart.
- // (Does not match self-closing <TAG … />, which doesn't contribute to depth.)
- const tagRe = new RegExp('<(?:/)?' + tagName + '\\b[^>]*>', 'g');
- tagRe.lastIndex = innerStart;
-
- let depth = 1;
- let m;
- while ((m = tagRe.exec(text))) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && /\/\s*>$/.test(m[0]);
- if (isClose) {
- depth--;
- if (depth === 0) return text.slice(innerStart, m.index);
- } else if (!isSelfClose) {
- depth++;
- }
- }
- return null;
-}
-
-/**
- * Extract the original element content from within the variant wrapper.
- * Returns an array of lines.
- */
-function extractOriginal(lines, block) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="original"');
- if (inner === null) return [];
- return inner.split('\n');
-}
-
-/**
- * Extract a specific variant's inner content (stripping the wrapper div).
- * Returns an array of lines, or null if not found.
- */
-function extractVariant(lines, block, variantNum) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + variantNum + '"');
- if (inner === null) return null;
- const result = inner.split('\n');
- // Collapse a lone empty leading/trailing line (common after string splice).
- while (result.length > 1 && result[0].trim() === '') result.shift();
- while (result.length > 1 && result[result.length - 1].trim() === '') result.pop();
- return result.length > 0 ? result : null;
-}
-
-/**
- * Extract the colocated <style> block content (between the style tags).
- * Returns an array of CSS lines, or null if no style block found.
- *
- * Handles three shapes of `<style data-impeccable-css="ID" ...>`:
- * 1. Self-closing: `<style ... />` — no body; return null (nothing to carbonize).
- * 2. Same-line open+close: `<style>...</style>` — return the inner content.
- * 3. Multi-line: `<style>` on one line, `</style>` on a later line — return
- * the lines between them.
- */
-function extractCss(lines, block, id) {
- const styleAttr = 'data-impeccable-css="' + id + '"';
- let inStyle = false;
- const content = [];
-
- for (let i = block.start; i <= block.end; i++) {
- const line = lines[i];
-
- if (!inStyle && line.includes(styleAttr)) {
- // Self-closing: nothing to carbonize.
- if (/<style\b[^>]*\/\s*>/.test(line)) return null;
- // Same-line open + close: extract inner text.
- const sameLine = line.match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/);
- if (sameLine) {
- const inner = stripJsxTemplateWrap(sameLine[1]);
- return inner.length > 0 ? inner.split('\n') : null;
- }
- inStyle = true;
- continue; // skip the <style> opening tag
- }
-
- if (inStyle) {
- // Detect </style> anywhere on the line — JSX template-literal closes
- // (`}</style>`) put the close mid-line, and we don't want to absorb the
- // template-literal punctuation as CSS content.
- const closeIdx = line.indexOf('</style>');
- if (closeIdx !== -1) break;
- content.push(line);
- }
- }
-
- if (content.length === 0) return null;
- return stripJsxTemplateLines(content);
-}
-
-/**
- * Strip a JSX template-literal wrap (`{` … `}`) from CSS extracted out of a
- * `<style>` element in a JSX/TSX file. The agent may write the wrap with
- * `{` and `}` directly attached to the `<style>` tags, on their own lines,
- * or attached to the first/last CSS lines — all three are JSX-legal.
- *
- * Stripping is required because handleAccept re-wraps the CSS itself when
- * carbonizing. Without this, two consecutive accepts (or a previously-
- * accepted variants block being carbonized) would produce nested
- * `{` `{` … `}` `}`, which oxc rejects with "Expected `}` but found `@`".
- */
-function stripJsxTemplateLines(content) {
- const out = content.slice();
-
- // Drop any leading blank lines so we don't miss a `{` line buried below
- // them; same for trailing.
- while (out.length > 0 && out[0].trim() === '') out.shift();
- while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
- if (out.length === 0) return null;
-
- // Leading `{`: own line, or attached to the first CSS line.
- const firstTrim = out[0].trimStart();
- if (firstTrim === '{`') {
- out.shift();
- } else if (firstTrim.startsWith('{`')) {
- const idx = out[0].indexOf('{`');
- out[0] = out[0].slice(0, idx) + out[0].slice(idx + 2);
- if (out[0].trim() === '') out.shift();
- }
- if (out.length === 0) return null;
-
- // Trailing `` ` `` `}`: own line, or attached to the last CSS line.
- const lastIdx = out.length - 1;
- const lastTrim = out[lastIdx].trimEnd();
- if (lastTrim === '`}') {
- out.pop();
- } else if (lastTrim.endsWith('`}')) {
- const text = out[lastIdx];
- const idx = text.lastIndexOf('`}');
- out[lastIdx] = text.slice(0, idx) + text.slice(idx + 2);
- if (out[lastIdx].trim() === '') out.pop();
- }
-
- return out.length > 0 ? out : null;
-}
-
-function stripJsxTemplateWrap(text) {
- const lines = text.split('\n');
- const stripped = stripJsxTemplateLines(lines);
- return stripped ? stripped.join('\n') : '';
-}
-
-/**
- * De-indent content that was indented by live-wrap.mjs.
- * The wrap script adds `indent + ' '` (4 extra spaces) to each line.
- * We restore to just `indent` level.
- */
-function deindentContent(contentLines, baseIndent) {
- // Find the minimum indentation in the content to determine how much was added
- let minIndent = Infinity;
- for (const line of contentLines) {
- if (line.trim() === '') continue;
- const leadingSpaces = line.match(/^(\s*)/)[1].length;
- minIndent = Math.min(minIndent, leadingSpaces);
- }
- if (minIndent === Infinity) minIndent = 0;
-
- // Strip the extra indentation and re-add base indent
- return contentLines.map(line => {
- if (line.trim() === '') return '';
- return baseIndent + line.slice(minIndent);
- });
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- return { open: '<!--', close: '-->' };
-}
-
-// ---------------------------------------------------------------------------
-// File search (find the file containing session markers)
-// ---------------------------------------------------------------------------
-
-function findSessionFile(id, cwd) {
- const marker = 'impeccable-variants-start ' + id;
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, marker, seen, 0);
- if (result) {
- const content = fs.readFileSync(result, 'utf-8');
- return { file: result, content, lines: content.split('\n') };
- }
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth) {
- if (depth > 5) return null;
- let realDir;
- try { realDir = fs.realpathSync(dir); } catch { return null; }
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- if (!EXTENSIONS.includes(path.extname(entry.name).toLowerCase())) continue;
- const filePath = path.join(dir, entry.name);
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip */ }
- }
-
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
- if (result) return result;
- }
-
- return null;
-}
-
-// ---------------------------------------------------------------------------
-// Utilities
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-accept.mjs') || _running?.endsWith('live-accept.mjs/')) {
- acceptCli();
-}
-
-export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax };
@@ -1,123 +0,0 @@
-/**
- * Browser-side durable session helpers for Impeccable live mode.
- *
- * Kept separate from live-browser.js so recovery state can be tested without
- * booting the full overlay UI. Served before live-browser.js and attached to
- * window.__IMPECCABLE_LIVE_SESSION__.
- */
-(function (root) {
- 'use strict';
-
- function createLiveBrowserSessionState({ prefix, storage, idFactory }) {
- if (!prefix) throw new Error('prefix required');
- const store = storage || root.localStorage;
- const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };
- const sessionKey = prefix + '-session';
- const handledKey = sessionKey + '-handled';
- const scrollKey = sessionKey + '-scroll';
- let checkpointRevision = 0;
- const owner = makeId();
-
- function safeRead(key) {
- try { return store.getItem(key); } catch { return null; }
- }
-
- function safeWrite(key, value) {
- try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }
- }
-
- function safeRemove(key) {
- try { store.removeItem(key); } catch { /* unavailable storage */ }
- }
-
- function loadSession() {
- try {
- const raw = safeRead(sessionKey);
- if (!raw) return null;
- const parsed = JSON.parse(raw);
- if (Number.isInteger(parsed.checkpointRevision)) {
- checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);
- }
- return parsed;
- } catch { return null; }
- }
-
- function saveSession(session) {
- if (!session || !session.id) return;
- const payload = {
- ...session,
- checkpointRevision,
- };
- safeWrite(sessionKey, JSON.stringify(payload));
- }
-
- function clearSession() {
- safeRemove(sessionKey);
- }
-
- function nextCheckpointRevision() {
- checkpointRevision += 1;
- const existing = loadSession();
- if (existing?.id) saveSession(existing);
- return checkpointRevision;
- }
-
- function seedCheckpointRevision(value) {
- if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);
- return checkpointRevision;
- }
-
- function currentCheckpointRevision() {
- return checkpointRevision;
- }
-
- function markHandled(id) {
- if (!id) return;
- safeWrite(handledKey, id);
- }
-
- function isHandled(id) {
- return !!id && safeRead(handledKey) === id;
- }
-
- function clearHandled() {
- safeRemove(handledKey);
- }
-
- function writeScrollY(y) {
- safeWrite(scrollKey, String(y));
- }
-
- function readScrollY() {
- const raw = safeRead(scrollKey);
- if (raw == null) return null;
- const n = parseFloat(raw);
- return isFinite(n) ? n : null;
- }
-
- function clearScrollY() {
- safeRemove(scrollKey);
- }
-
- return {
- owner,
- sessionKey,
- handledKey,
- scrollKey,
- saveSession,
- loadSession,
- clearSession,
- nextCheckpointRevision,
- seedCheckpointRevision,
- currentCheckpointRevision,
- markHandled,
- isHandled,
- clearHandled,
- writeScrollY,
- readScrollY,
- clearScrollY,
- };
- }
-
- root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };
-})(typeof window !== 'undefined' ? window : globalThis);
@@ -1,4860 +0,0 @@
-/**
- * Impeccable Live Variant Mode — Browser Script
- *
- * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
- * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
- * before this code.
- *
- * UI: a single floating bar that morphs between three states —
- * configure (pick action + go), generating (progressive dots), and cycling
- * (prev/next + accept/discard). Feels like Spotlight, not a modal.
- */
-(function () {
- 'use strict';
- if (typeof window === 'undefined') return;
-
- // Guard against double-init. Bun's HTML loader may process the <script> tag
- // and create a bundled copy alongside the external load, or HMR may re-execute.
- // Check BEFORE reading token/port to catch all cases.
- if (window.__IMPECCABLE_LIVE_INIT__) return;
- window.__IMPECCABLE_LIVE_INIT__ = true;
-
- const TOKEN = window.__IMPECCABLE_TOKEN__;
- const PORT = window.__IMPECCABLE_PORT__;
- if (!TOKEN || !PORT) {
- window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
- return;
- }
-
- // ---------------------------------------------------------------------------
- // Design tokens
- // ---------------------------------------------------------------------------
-
- // Brand magenta is pinned to the site token (--color-accent in main.css)
- // so Accept / knobs / cycle-dots match the site's accent, not a washed
- // theme-adjusted one.
- const C = {
- brand: 'oklch(60% 0.25 350)',
- brandHov: 'oklch(52% 0.25 350)',
- brandSoft: 'oklch(60% 0.25 350 / 0.15)',
- ink: 'oklch(15% 0.01 350)',
- ash: 'oklch(55% 0 0)',
- paper: 'oklch(98% 0.005 350 / 0.92)',
- paperSolid:'oklch(98% 0.005 350)',
- mist: 'oklch(90% 0.01 350 / 0.6)',
- white: 'oklch(99% 0 0)',
- };
- const FONT = 'system-ui, -apple-system, sans-serif';
- const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
- // z-index: detect overlays use 99999, so our UI must be above them
- const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };
- const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
- const PREFIX = 'impeccable-live';
- const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
- prefix: PREFIX,
- storage: localStorage,
- idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),
- });
- if (!sessionState) {
- console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');
- window.__IMPECCABLE_LIVE_INIT__ = false;
- return;
- }
- const HIGHLIGHT_TRANSITION =
- 'top 140ms ' + EASE +
- ', left 140ms ' + EASE +
- ', width 140ms ' + EASE +
- ', height 140ms ' + EASE +
- ', opacity 150ms ease';
- const TOOLTIP_TRANSITION =
- 'top 140ms ' + EASE + ', left 140ms ' + EASE + ', opacity 150ms ease';
-
- const SKIP_TAGS = new Set([
- 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
- ]);
-
- // SVG icons stack above each chip label. All strokes use currentColor so the
- // icon recolors to C.brand when its chip is selected. 20x20 render, 24-viewBox,
- // 1.5 stroke — visually consistent with the Foundation grid on the homepage.
- const ICON_ATTRS = 'width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block"';
- const ICONS = {
- impeccable: `<svg ${ICON_ATTRS}><path d="M4 20l4-1L18 9l-3-3L5 16z"/><path d="M14 7l3 3"/></svg>`,
- bolder: `<svg ${ICON_ATTRS}><rect x="6" y="12" width="4" height="7" rx="0.5"/><rect x="14" y="5" width="4" height="14" rx="0.5"/></svg>`,
- quieter: `<svg ${ICON_ATTRS}><rect x="6" y="5" width="4" height="14" rx="0.5"/><rect x="14" y="12" width="4" height="7" rx="0.5"/></svg>`,
- distill: `<svg ${ICON_ATTRS}><path d="M4 5h16l-6 8v7l-4-2v-5z"/></svg>`,
- polish: `<svg ${ICON_ATTRS}><path d="M15 3l1 3 3 1-3 1-1 3-1-3-3-1 3-1z"/><path d="M7 13l0.6 1.8 1.8 0.6-1.8 0.6-0.6 1.8-0.6-1.8-1.8-0.6 1.8-0.6z"/></svg>`,
- typeset: `<svg ${ICON_ATTRS}><path d="M5 6h14" stroke-width="2.6"/><path d="M5 12h9" stroke-width="1.9"/><path d="M5 18h5" stroke-width="1.3"/></svg>`,
- colorize: `<svg ${ICON_ATTRS}><circle cx="9" cy="10" r="5"/><circle cx="15" cy="10" r="5"/><circle cx="12" cy="15" r="5"/></svg>`,
- layout: `<svg ${ICON_ATTRS}><rect x="3" y="4" width="8" height="16" rx="0.5"/><rect x="13" y="4" width="8" height="7" rx="0.5"/><rect x="13" y="13" width="8" height="7" rx="0.5"/></svg>`,
- adapt: `<svg ${ICON_ATTRS}><rect x="2.5" y="5" width="12" height="11" rx="1"/><line x1="2.5" y1="19" x2="14.5" y2="19"/><rect x="16.5" y="8" width="5" height="11" rx="1"/></svg>`,
- animate: `<svg ${ICON_ATTRS}><path d="M3 18c4-4 6-10 10-10"/><path d="M13 8c3 0 5 5 8 10"/><circle cx="13" cy="8" r="1.6" fill="currentColor" stroke="none"/></svg>`,
- delight: `<svg ${ICON_ATTRS}><path d="M12 3l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>`,
- overdrive: `<svg ${ICON_ATTRS}><path d="M13 3L5 13h5l-1 8 9-12h-6z"/></svg>`,
- };
-
- const ACTIONS = [
- { value: 'impeccable', label: 'Freeform' },
- { value: 'bolder', label: 'Bolder' },
- { value: 'quieter', label: 'Quieter' },
- { value: 'distill', label: 'Distill' },
- { value: 'polish', label: 'Polish' },
- { value: 'typeset', label: 'Typeset' },
- { value: 'colorize', label: 'Colorize' },
- { value: 'layout', label: 'Layout' },
- { value: 'adapt', label: 'Adapt' },
- { value: 'animate', label: 'Animate' },
- { value: 'delight', label: 'Delight' },
- { value: 'overdrive', label: 'Overdrive' },
- ];
-
- // ---------------------------------------------------------------------------
- // State
- // ---------------------------------------------------------------------------
-
- let state = 'IDLE';
- let hoveredElement = null;
- let selectedElement = null;
- let currentSessionId = null;
- let expectedVariants = 0;
- let arrivedVariants = 0;
- let visibleVariant = 0;
- let variantObserver = null;
- let hasProjectContext = false;
- let selectedAction = 'impeccable';
- let selectedCount = 3;
- const browserOwner = sessionState.owner;
- let checkpointTimer = null;
-
- // Scroll lock — holds window.scrollY at a fixed value while the session is
- // active, so HMR DOM patches and variant swaps can't drift the page. See
- // startScrollLock / stopScrollLock below.
- let scrollLockObserver = null;
- let scrollLockTargetY = null;
- let scrollLockRaf = null;
- let scrollLockAbort = null;
-
- // Dedicated key for scroll position — SEPARATE from LS_KEY so that
- // saveSession's state updates don't clobber a carefully-captured scrollY.
- // (Previously: saveSession wrote scrollY alongside state, so every call
- // during resume overwrote the pre-reload value with whatever the browser
- // had landed on, typically 0.)
- function writeScrollY(y) { sessionState.writeScrollY(y); }
- function readScrollY() { return sessionState.readScrollY(); }
- function clearScrollY() { sessionState.clearScrollY(); }
-
- // Pre-empt the browser: apply manual scroll restoration and jump to the
- // saved scrollY at script-parse time. Retries on fonts.ready and load
- // are essential: scrollTo(y) clamps to the current document.scrollHeight,
- // which is often hundreds of pixels short of the final value until
- // async-loaded fonts swap in and reflow.
- try {
- history.scrollRestoration = 'manual';
- const savedY = readScrollY();
- if (savedY != null) {
- const apply = () => {
- if (Math.abs(window.scrollY - savedY) > 0.5) {
- console.log('[impeccable.scroll] early restore', { from: window.scrollY, to: savedY });
- window.scrollTo(0, savedY);
- }
- };
- apply();
- if (document.fonts?.ready) document.fonts.ready.then(apply).catch(() => {});
- window.addEventListener('load', apply, { once: true });
- }
- } catch {}
-
- // UI refs
- let highlightEl = null;
- let tooltipEl = null;
- let barEl = null;
- let pickerEl = null;
- let toastEl = null;
- let scrollRaf = null;
-
- // ---------------------------------------------------------------------------
- // Helpers
- // ---------------------------------------------------------------------------
-
- function own(el) {
- return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
- }
-
- function pickable(el) {
- if (!el || el.nodeType !== 1) return false;
- if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
- if (own(el)) return false;
- const r = el.getBoundingClientRect();
- return r.width >= 20 && r.height >= 20;
- }
-
- function desc(el) {
- if (!el) return '';
- let s = el.tagName.toLowerCase();
- if (el.id) s += '#' + el.id;
- else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
- return s;
- }
-
- function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
-
- // Modal-aware chrome: keep our floating UI clickable inside Radix /
- // Headless UI / vaul portals.
- //
- // Two host-page behaviors break us when the picked element lives inside a
- // modal dialog:
- //
- // 1. Modal scroll-lock disables outside pointer events. Radix's
- // `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
- // while a modal is open and only restores `auto` on the layer. Our
- // chrome inherits `none` from <body> and becomes unclickable.
- // 2. The dialog's outside-interaction handler (Radix's
- // `usePointerDownOutside`) listens at document level and dismisses
- // the dialog whenever a `pointerdown` lands outside the layer node.
- // Our chrome is a sibling of <body>, so Radix classifies our clicks
- // as outside and tears the dialog down mid-task.
- //
- // We can't reliably re-parent our chrome into the dialog subtree (z-index
- // stacking, scroll containers, theming all become host-page concerns), so
- // we defang both behaviors at our root:
- //
- // - `pointer-events: auto !important` overrides the inherited `none`.
- // - Stop `pointerdown` / `mousedown` propagation so the document-level
- // dismiss listener never fires for our clicks.
- // - Stop `focusin` propagation so any focus shifts inside our chrome
- // don't read as "focus moved outside the dialog" to focus traps.
- //
- // Click events still bubble normally — only the early pointer/focus
- // signals that drive outside-interaction detection are silenced.
- function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
- if (!rootEl) return;
- if (setPointerEvents) {
- rootEl.style.setProperty('pointer-events', 'auto', 'important');
- }
- const stop = (e) => e.stopPropagation();
- rootEl.addEventListener('pointerdown', stop);
- rootEl.addEventListener('mousedown', stop);
- rootEl.addEventListener('focusin', stop);
- }
-
- // ---------------------------------------------------------------------------
- // Highlight overlay
- // ---------------------------------------------------------------------------
-
- function initHighlight() {
- highlightEl = document.createElement('div');
- highlightEl.id = PREFIX + '-highlight';
- Object.assign(highlightEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- border: '2px solid ' + C.brand, borderRadius: '3px',
- pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
- transition: HIGHLIGHT_TRANSITION,
- display: 'none', opacity: '0',
- });
- document.body.appendChild(highlightEl);
-
- tooltipEl = document.createElement('div');
- tooltipEl.id = PREFIX + '-tooltip';
- Object.assign(tooltipEl.style, {
- position: 'fixed',
- background: C.ink, color: C.white,
- fontFamily: MONO, fontSize: '10px', fontWeight: '500',
- padding: '2px 6px', borderRadius: '3px',
- zIndex: Z.highlight + 1, pointerEvents: 'none',
- whiteSpace: 'nowrap', display: 'none',
- letterSpacing: '0.02em',
- transition: TOOLTIP_TRANSITION,
- });
- document.body.appendChild(tooltipEl);
- }
-
- function showHighlight(el) {
- if (!el || !highlightEl) return;
- const r = el.getBoundingClientRect();
- const top = (r.top - 2) + 'px', left = (r.left - 2) + 'px';
- const width = (r.width + 4) + 'px', height = (r.height + 4) + 'px';
- const tipTop = r.top - 20;
- const tipY = (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px';
- const tipX = Math.max(4, r.left) + 'px';
- tooltipEl.textContent = desc(el);
-
- const hiWasHidden = highlightEl.style.display === 'none' || highlightEl.style.opacity === '0';
- if (hiWasHidden) {
- // Snap to first target without animating from (0,0), then fade in.
- highlightEl.style.transition = 'none';
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block' });
- tooltipEl.style.transition = 'none';
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block' });
- void highlightEl.offsetWidth;
- highlightEl.style.transition = HIGHLIGHT_TRANSITION;
- highlightEl.style.opacity = '1';
- tooltipEl.style.transition = TOOLTIP_TRANSITION;
- tooltipEl.style.opacity = '1';
- } else {
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block', opacity: '1' });
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block', opacity: '1' });
- }
- }
-
- function hideHighlight() {
- if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
- if (tooltipEl) { tooltipEl.style.opacity = '0'; tooltipEl.style.display = 'none'; }
- }
-
- // ---------------------------------------------------------------------------
- // Annotation overlay (comment pins + magenta strokes)
- //
- // Active while state === 'CONFIGURING'. The overlay is a fixed-positioned
- // sibling of <body> mirroring selectedElement's bounding rect. Click (no
- // drag) drops a comment pin; drag paints a magenta SVG stroke. All coords
- // are stored in element-local CSS px so they survive scroll / resize and
- // correlate directly with the captured PNG.
- // ---------------------------------------------------------------------------
-
- const DRAG_THRESHOLD = 5; // px — below this, treat pointerup as a click
- const PIN_DBL_CLICK_MS = 300; // two clicks on the same pin within this delete it
- let annotOverlayEl = null;
- let annotSvgEl = null;
- let annotPinsEl = null;
- let annotClearChipEl = null;
- let annotState = { comments: [], strokes: [] };
- let annotActive = false;
- // `annotPointer` is either:
- // { kind: 'new', x0, y0, moved, strokeEl, strokePoints } creating a stroke/pin
- // { kind: 'pin', idx, startPointer, startPin, moved } dragging an existing pin
- let annotPointer = null;
- let annotEditing = null; // { idx, input, wrapEl }
- let annotLastPinClick = { idx: -1, time: 0 }; // for click-click-to-delete
-
- function initAnnotOverlay() {
- annotOverlayEl = document.createElement('div');
- annotOverlayEl.id = PREFIX + '-annot';
- Object.assign(annotOverlayEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- pointerEvents: 'auto', zIndex: Z.highlight + 2,
- display: 'none', overflow: 'visible',
- cursor: 'crosshair', touchAction: 'none',
- });
-
- annotSvgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- annotSvgEl.id = PREFIX + '-annot-svg';
- Object.assign(annotSvgEl.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%',
- // The SVG itself doesn't absorb clicks; individual hit-paths opt-in via
- // pointer-events=stroke so gaps still fall through to the overlay.
- pointerEvents: 'none', overflow: 'visible',
- });
- annotOverlayEl.appendChild(annotSvgEl);
-
- annotPinsEl = document.createElement('div');
- annotPinsEl.id = PREFIX + '-annot-pins';
- Object.assign(annotPinsEl.style, {
- position: 'absolute', inset: '0',
- pointerEvents: 'none',
- });
- annotOverlayEl.appendChild(annotPinsEl);
-
- annotClearChipEl = document.createElement('div');
- annotClearChipEl.id = PREFIX + '-annot-clear';
- annotClearChipEl.dataset.annotClear = 'true';
- annotClearChipEl.textContent = 'Clear';
- Object.assign(annotClearChipEl.style, {
- position: 'absolute', top: '8px', right: '8px',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '10px', fontWeight: '500',
- letterSpacing: '0.08em', textTransform: 'uppercase',
- padding: '5px 12px', borderRadius: '999px',
- cursor: 'pointer', pointerEvents: 'auto',
- display: 'none', userSelect: 'none',
- boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
- });
- annotOverlayEl.appendChild(annotClearChipEl);
-
- annotOverlayEl.addEventListener('pointerdown', onAnnotDown);
- annotOverlayEl.addEventListener('pointermove', onAnnotMove);
- annotOverlayEl.addEventListener('pointerup', onAnnotUp);
- annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
- document.body.appendChild(annotOverlayEl);
- // Modal-host friendliness: pointer-events is already 'auto' on this
- // overlay; we only need to silence the host's outside-interaction
- // listeners. Don't override pointer-events here (the overlay toggles
- // visibility via display:none, which is fine).
- defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
- }
-
- function updateClearChip() {
- if (!annotClearChipEl) return;
- const hasAny = annotState.comments.length > 0 || annotState.strokes.length > 0;
- annotClearChipEl.style.display = hasAny ? 'block' : 'none';
- }
-
- function showAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- annotActive = true;
- positionAnnotOverlay(el);
- annotOverlayEl.style.display = 'block';
- }
-
- function hideAnnotOverlay() {
- annotActive = false;
- if (annotOverlayEl) annotOverlayEl.style.display = 'none';
- // Drop any in-progress edit without touching annotState — clearAnnotations
- // (if the caller is exiting configure mode) handles state reset.
- annotEditing = null;
- }
-
- function positionAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- const r = el.getBoundingClientRect();
- Object.assign(annotOverlayEl.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- annotSvgEl.setAttribute('viewBox', '0 0 ' + r.width + ' ' + r.height);
- }
-
- function clearAnnotations() {
- annotState.comments = [];
- annotState.strokes = [];
- if (annotSvgEl) while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- if (annotPinsEl) annotPinsEl.innerHTML = '';
- annotPointer = null;
- annotEditing = null;
- annotLastPinClick = { idx: -1, time: 0 };
- updateClearChip();
- }
-
- // Rebuild the SVG layer. Each stroke gets a wider invisible hit path
- // beneath the visible magenta path so clicks register on thin lines.
- function redrawStrokes() {
- while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- annotState.strokes.forEach((s, idx) => {
- const d = pointsToPath(s.points);
- const hit = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- hit.setAttribute('d', d);
- hit.setAttribute('stroke', 'transparent');
- hit.setAttribute('stroke-width', '16');
- hit.setAttribute('stroke-linecap', 'round');
- hit.setAttribute('stroke-linejoin', 'round');
- hit.setAttribute('fill', 'none');
- hit.setAttribute('pointer-events', 'stroke');
- hit.style.cursor = 'pointer';
- hit.dataset.annotStroke = String(idx);
- annotSvgEl.appendChild(hit);
- const visible = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- visible.setAttribute('d', d);
- visible.setAttribute('stroke', C.brand);
- visible.setAttribute('stroke-width', '3');
- visible.setAttribute('stroke-linecap', 'round');
- visible.setAttribute('stroke-linejoin', 'round');
- visible.setAttribute('fill', 'none');
- visible.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(visible);
- });
- updateClearChip();
- }
-
- function localCoords(e) {
- const rect = annotOverlayEl.getBoundingClientRect();
- return { x: e.clientX - rect.left, y: e.clientY - rect.top };
- }
-
- function onAnnotDown(e) {
- if (!annotActive) return;
-
- // 1) Clear chip → wipe all annotations
- if (e.target.closest?.('[data-annot-clear]')) {
- if (annotEditing) annotEditing = null;
- clearAnnotations();
- renderAllPins();
- redrawStrokes();
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 2) Stroke hit path → delete that stroke
- const strokeHit = e.target.closest?.('[data-annot-stroke]');
- if (strokeHit) {
- const idx = parseInt(strokeHit.dataset.annotStroke, 10);
- if (Number.isInteger(idx)) {
- annotState.strokes.splice(idx, 1);
- redrawStrokes();
- }
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 3) Pin → drag, edit, or delete-on-double-click
- const pinWrap = e.target.closest?.('[data-annot-pin]');
- if (pinWrap) {
- const idx = parseInt(pinWrap.dataset.annotPin, 10);
- if (!Number.isInteger(idx)) return;
- // Double-click (two pointerdowns on the same pin within window) → delete.
- const now = Date.now();
- if (annotLastPinClick.idx === idx && now - annotLastPinClick.time < PIN_DBL_CLICK_MS) {
- if (annotEditing && annotEditing.idx === idx) annotEditing = null;
- annotState.comments.splice(idx, 1);
- annotLastPinClick = { idx: -1, time: 0 };
- renderAllPins();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- annotLastPinClick = { idx, time: now };
- // If editing a different pin, commit that edit before starting here.
- if (annotEditing && annotEditing.idx !== idx) finalizeEditingPin();
- // If already editing THIS pin and the user clicked the dot, let the
- // input keep focus (don't start a drag — the click wasn't meant as one).
- if (annotEditing && annotEditing.idx === idx) return;
- const p = localCoords(e);
- const pin = annotState.comments[idx];
- annotPointer = {
- kind: 'pin', idx,
- startPointer: p,
- startPin: { x: pin.x, y: pin.y },
- moved: false,
- };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 4) Empty area → commit any open edit, then start new annotation
- if (annotEditing) {
- finalizeEditingPin();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- const p = localCoords(e);
- annotPointer = { kind: 'new', x0: p.x, y0: p.y, moved: false, strokeEl: null, strokePoints: null };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- }
-
- function onAnnotMove(e) {
- if (!annotActive || !annotPointer) return;
- const p = localCoords(e);
-
- if (annotPointer.kind === 'pin') {
- const dx = p.x - annotPointer.startPointer.x;
- const dy = p.y - annotPointer.startPointer.y;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- }
- const pin = annotState.comments[annotPointer.idx];
- if (!pin) { annotPointer = null; return; }
- pin.x = annotPointer.startPin.x + dx;
- pin.y = annotPointer.startPin.y + dy;
- renderAllPins();
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const dx = p.x - annotPointer.x0, dy = p.y - annotPointer.y0;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- const strokeEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- strokeEl.setAttribute('stroke', C.brand);
- strokeEl.setAttribute('stroke-width', '3');
- strokeEl.setAttribute('stroke-linecap', 'round');
- strokeEl.setAttribute('stroke-linejoin', 'round');
- strokeEl.setAttribute('fill', 'none');
- strokeEl.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(strokeEl);
- annotPointer.strokeEl = strokeEl;
- annotPointer.strokePoints = [[annotPointer.x0, annotPointer.y0]];
- }
- annotPointer.strokePoints.push([p.x, p.y]);
- annotPointer.strokeEl.setAttribute('d', pointsToPath(annotPointer.strokePoints));
- e.stopPropagation();
- }
-
- function onAnnotUp(e) {
- if (!annotActive || !annotPointer) return;
-
- if (annotPointer.kind === 'pin') {
- const wasDrag = annotPointer.moved;
- const idx = annotPointer.idx;
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- if (wasDrag) {
- // A drag is an intentional reposition; a follow-up click shouldn't be
- // interpreted as a double-click-to-delete.
- annotLastPinClick = { idx: -1, time: 0 };
- } else {
- beginEditPin(idx);
- }
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const wasDrag = annotPointer.moved;
- if (wasDrag) {
- annotState.strokes.push({ points: annotPointer.strokePoints });
- // Swap the temporary preview SVG path for the full render with hit paths.
- redrawStrokes();
- } else {
- const idx = annotState.comments.length;
- annotState.comments.push({ x: annotPointer.x0, y: annotPointer.y0, text: '' });
- renderAllPins();
- beginEditPin(idx);
- }
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- e.stopPropagation();
- }
-
- function pointsToPath(points) {
- if (!points || points.length === 0) return '';
- let d = 'M' + points[0][0].toFixed(1) + ' ' + points[0][1].toFixed(1);
- for (let i = 1; i < points.length; i++) {
- d += ' L' + points[i][0].toFixed(1) + ' ' + points[i][1].toFixed(1);
- }
- return d;
- }
-
- function renderAllPins() {
- annotPinsEl.innerHTML = '';
- annotState.comments.forEach((c, idx) => {
- annotPinsEl.appendChild(buildPinElement(c, idx));
- });
- updateClearChip();
- }
-
- function buildPinElement(comment, idx) {
- const interactive = idx >= 0;
- const wrap = document.createElement('div');
- if (interactive) wrap.dataset.annotPin = String(idx);
- Object.assign(wrap.style, {
- position: 'absolute',
- left: (comment.x - 7) + 'px', top: (comment.y - 7) + 'px',
- pointerEvents: interactive ? 'auto' : 'none',
- display: 'flex', alignItems: 'flex-start', gap: '6px',
- cursor: interactive ? 'grab' : 'default',
- touchAction: 'none',
- });
- const dot = document.createElement('div');
- Object.assign(dot.style, {
- width: '14px', height: '14px', borderRadius: '50%',
- background: C.brand, border: '2px solid ' + C.white,
- boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
- flexShrink: '0',
- });
- wrap.appendChild(dot);
-
- if (comment.text) {
- const bubble = document.createElement('div');
- bubble.textContent = comment.text;
- Object.assign(bubble.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- marginTop: '-2px', maxWidth: '220px',
- pointerEvents: 'none', whiteSpace: 'pre-wrap',
- wordBreak: 'break-word',
- });
- wrap.appendChild(bubble);
- }
- return wrap;
- }
-
- function beginEditPin(idx) {
- const wrapEl = annotPinsEl.querySelector('[data-annot-pin="' + idx + '"]');
- if (!wrapEl) return;
- // Strip any existing bubble (but keep the dot)
- wrapEl.querySelectorAll('div:not(:first-child)').forEach(n => n.remove());
- const input = document.createElement('input');
- input.type = 'text';
- input.placeholder = 'Note…';
- Object.assign(input.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- border: '1px solid ' + C.brand,
- outline: 'none', marginTop: '-2px',
- width: '220px', pointerEvents: 'auto',
- });
- const originalText = annotState.comments[idx].text || '';
- input.value = originalText;
- wrapEl.appendChild(input);
- annotEditing = { idx, input, wrapEl, originalText };
- input.addEventListener('keydown', onAnnotInputKey, true);
- input.addEventListener('blur', () => {
- // Fires on both focus-loss and programmatic blur; commit unless we
- // already handled it.
- if (annotEditing && annotEditing.input === input) finalizeEditingPin();
- });
- // Stop clicks/pointerdowns inside the input from bubbling to the overlay
- ['pointerdown', 'click'].forEach(ev => {
- input.addEventListener(ev, e => e.stopPropagation());
- });
- setTimeout(() => input.focus(), 0);
- }
-
- function onAnnotInputKey(e) {
- if (e.key === 'Enter') {
- e.preventDefault(); e.stopPropagation();
- finalizeEditingPin();
- } else if (e.key === 'Escape') {
- e.preventDefault(); e.stopPropagation();
- cancelEditingPin();
- } else {
- // Keep arrows / backspace from hitting global handlers
- e.stopPropagation();
- }
- }
-
- function finalizeEditingPin() {
- if (!annotEditing) return;
- const { idx, input } = annotEditing;
- const text = input.value.trim();
- annotEditing = null;
- if (text) annotState.comments[idx].text = text;
- else annotState.comments.splice(idx, 1);
- renderAllPins();
- }
-
- function cancelEditingPin() {
- if (!annotEditing) return;
- const { idx, originalText } = annotEditing;
- annotEditing = null;
- // If the pin had text before this edit, revert to it. If it was a
- // just-created empty pin, Escape removes it.
- if (originalText) {
- annotState.comments[idx].text = originalText;
- } else {
- annotState.comments.splice(idx, 1);
- }
- renderAllPins();
- }
-
- // Build a detached annotation subtree suitable for injection into the clone
- // modern-screenshot creates. Coordinates are element-local so this slots
- // straight into an element that's been made position:relative. Takes an
- // explicit snapshot so it works after annotState has been cleared.
- function buildAnnotationsForCapture(rect, snapshot) {
- const comments = snapshot ? snapshot.comments : annotState.comments;
- const strokes = snapshot ? snapshot.strokes : annotState.strokes;
- if (comments.length === 0 && strokes.length === 0) return null;
- const wrap = document.createElement('div');
- Object.assign(wrap.style, {
- position: 'absolute', top: '0', left: '0',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none', overflow: 'visible',
- });
- if (strokes.length > 0) {
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- svg.setAttribute('viewBox', '0 0 ' + rect.width + ' ' + rect.height);
- Object.assign(svg.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%', overflow: 'visible',
- });
- for (const s of strokes) {
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- path.setAttribute('stroke', C.brand);
- path.setAttribute('stroke-width', '3');
- path.setAttribute('stroke-linecap', 'round');
- path.setAttribute('stroke-linejoin', 'round');
- path.setAttribute('fill', 'none');
- path.setAttribute('d', pointsToPath(s.points));
- svg.appendChild(path);
- }
- wrap.appendChild(svg);
- }
- for (const c of comments) {
- // idx=-1 means non-interactive; pointerEvents stay off in the clone
- wrap.appendChild(buildPinElement(c, -1));
- }
- return wrap;
- }
-
- // ---------------------------------------------------------------------------
- // Element context extraction
- // ---------------------------------------------------------------------------
-
- function extractContext(el) {
- const cs = getComputedStyle(el);
- const r = el.getBoundingClientRect();
- const props = {};
- for (const sheet of document.styleSheets) {
- try {
- for (const rule of sheet.cssRules) {
- if (rule.style) for (let i = 0; i < rule.style.length; i++) {
- const p = rule.style[i];
- if (p.startsWith('--') && !props[p]) {
- const v = cs.getPropertyValue(p).trim();
- if (v) props[p] = v;
- }
- }
- }
- } catch { /* cross-origin */ }
- }
- return {
- tagName: el.tagName.toLowerCase(), id: el.id || null,
- classes: [...el.classList],
- textContent: (el.textContent || '').slice(0, 500),
- outerHTML: el.outerHTML.slice(0, 10000),
- computedStyles: {
- 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
- 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
- 'color': cs.color, 'background': cs.background,
- 'background-color': cs.backgroundColor,
- 'padding': cs.padding, 'margin': cs.margin,
- 'display': cs.display, 'position': cs.position,
- 'gap': cs.gap, 'border-radius': cs.borderRadius,
- 'box-shadow': cs.boxShadow,
- },
- cssCustomProperties: props,
- parentContext: el.parentElement
- ? '<' + el.parentElement.tagName.toLowerCase()
- + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
- + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
- + '>'
- : null,
- boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
- };
- }
-
- // ---------------------------------------------------------------------------
- // The Bar — one floating element, three modes
- // ---------------------------------------------------------------------------
-
- // Contextual-bar palette. Cached at init so every build*Row reads a
- // consistent set of colors; detectPageTheme runs once rather than on every
- // phase transition.
- let BP = null;
-
- // Bar shadow variants. The default projects down + subtle around. When
- // the Tune popover opens below the bar, a downward shadow lands on the
- // dark popover and reads as a bright ghost line. We swap to UP-only while
- // tune is open below so the popover's top edge is clean.
- const BAR_SHADOW_DEFAULT = '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_UP = '0 -4px 20px oklch(0% 0 0 / 0.08), 0 -1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_DOWN = BAR_SHADOW_DEFAULT;
-
- function initBar() {
- BP = barPaletteForTheme(detectPageTheme());
- barEl = document.createElement('div');
- barEl.id = PREFIX + '-bar';
- Object.assign(barEl.style, {
- position: 'fixed', zIndex: Z.bar,
- display: 'none', opacity: '0',
- transform: 'translateY(6px)',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- background: BP.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + BP.hairline,
- borderRadius: '10px',
- boxShadow: BAR_SHADOW_DEFAULT,
- transition: 'box-shadow 0.2s ease, opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- fontFamily: FONT, fontSize: '13px', color: BP.text,
- padding: '6px',
- maxWidth: '520px', minWidth: '320px',
- });
- document.body.appendChild(barEl);
- defangOutsideHandlers(barEl);
- }
-
- function positionBar() {
- if (!barEl || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- const barH = barEl.offsetHeight || 44;
- const barW = barEl.offsetWidth || 380;
- const GLOBAL_BAR_RESERVE = 64; // global bar height + bottom margin + breathing room
- const GAP = 8;
-
- // Prefer below the element; fall back to above; if neither fits (element
- // taller than viewport), pin to a stable viewport anchor so the bar
- // doesn't teleport between top and bottom as the user scrolls.
- let top;
- const belowTop = r.bottom + GAP;
- const aboveTop = r.top - barH - GAP;
- if (belowTop + barH + GAP <= window.innerHeight - GLOBAL_BAR_RESERVE) {
- top = belowTop;
- } else if (aboveTop >= GAP) {
- top = aboveTop;
- } else {
- top = window.innerHeight - barH - GLOBAL_BAR_RESERVE;
- }
-
- let left = r.left + (r.width - barW) / 2;
- if (left < GAP) left = GAP;
- if (left + barW > window.innerWidth - GAP) left = window.innerWidth - barW - GAP;
- Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
- }
-
- function showBar(mode) {
- barEl.innerHTML = '';
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- barEl.style.display = 'block';
- positionBar();
- requestAnimationFrame(() => {
- barEl.style.opacity = '1';
- barEl.style.transform = 'translateY(0)';
- });
- }
-
- function hideBar() {
- if (!barEl) return;
- barEl.style.opacity = '0';
- barEl.style.transform = 'translateY(6px)';
- setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
- hideActionPicker();
- closeTunePopover();
- }
-
- function updateBarContent(mode) {
- if (!barEl || barEl.style.display === 'none') return;
- barEl.innerHTML = '';
- // Reset bar styling to the theme-aware palette
- barEl.style.background = BP.surface;
- barEl.style.border = '1px solid ' + BP.hairline;
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- else if (mode === 'saving') barEl.appendChild(buildSavingRow());
- else if (mode === 'confirmed') {
- barEl.appendChild(buildConfirmedRow());
- barEl.style.background = 'oklch(95% 0.05 145)';
- barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
- }
- }
-
- // --- Configure row ---
-
- function buildConfigureRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
-
- // Action pill
- const pill = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '4px',
- padding: '5px 10px', borderRadius: '6px',
- background: BP.mark, color: BP.markText,
- fontFamily: FONT, fontSize: '12px', fontWeight: '500',
- border: 'none', cursor: 'pointer',
- transition: 'background 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap', flexShrink: '0',
- });
- pill.textContent = actionLabel() + ' \u25BE';
- pill.addEventListener('mouseenter', () => pill.style.background = BP.accent);
- pill.addEventListener('mouseleave', () => pill.style.background = BP.mark);
- pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
- pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
- pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
- row.appendChild(pill);
-
- // Freeform input. Focus state shows an accent-colored border only —
- // an earlier version tinted the background with `BP.accentSoft`, which
- // composited against the dark bar surface to a murky purple where the
- // browser's default placeholder gray was unreadable. Placeholder color
- // is set explicitly via a one-shot stylesheet keyed off this input's id
- // so it picks up the bar's `textDim` token in both themes.
- const input = document.createElement('input');
- input.id = PREFIX + '-input';
- input.type = 'text';
- input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
- Object.assign(input.style, {
- flex: '1', minWidth: '0',
- padding: '5px 8px', borderRadius: '6px',
- border: '1px solid transparent', background: 'transparent',
- fontFamily: FONT, fontSize: '12px', color: BP.text,
- outline: 'none',
- transition: 'border-color 0.15s ease',
- });
- if (!document.getElementById(PREFIX + '-input-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-input-style';
- s.textContent =
- '#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
- document.head.appendChild(s);
- }
- input.addEventListener('focus', () => {
- input.style.borderColor = BP.accent;
- });
- input.addEventListener('blur', () => {
- input.style.borderColor = 'transparent';
- });
- input.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
- if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; return; }
- // Let arrow keys pass through to the element picker when the input is empty
- if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && !input.value) return;
- e.stopPropagation();
- });
- row.appendChild(input);
-
- // Variant count toggle
- const count = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: MONO, fontSize: '11px', fontWeight: '600',
- color: BP.textDim, cursor: 'pointer',
- transition: 'color 0.12s ease, border-color 0.12s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- count.textContent = '\u00D7' + selectedCount;
- count.title = 'Variants: click to change';
- count.addEventListener('mouseenter', () => { count.style.color = BP.text; count.style.borderColor = BP.text; });
- count.addEventListener('mouseleave', () => { count.style.color = BP.textDim; count.style.borderColor = BP.hairline; });
- count.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
- count.textContent = '\u00D7' + selectedCount;
- });
- row.appendChild(count);
-
- // Go button
- const go = el('button', {
- padding: '5px 12px', borderRadius: '6px',
- border: 'none', background: BP.accent, color: BP.mark,
- fontFamily: FONT, fontSize: '12px', fontWeight: '600',
- cursor: 'pointer',
- transition: 'filter 0.12s ease, transform 0.1s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- go.textContent = 'Go \u2192';
- go.addEventListener('mouseenter', () => go.style.filter = 'brightness(1.1)');
- go.addEventListener('mouseleave', () => go.style.filter = 'none');
- go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
- go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
- go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
- row.appendChild(go);
-
- // Auto-focus input after a beat
- setTimeout(() => input.focus(), 60);
- return row;
- }
-
- // --- Generating row ---
-
- function buildGeneratingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 4px',
- });
-
- // Action label
- const label = el('span', {
- fontWeight: '600', fontSize: '12px', color: BP.text,
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- label.textContent = actionLabel();
- row.appendChild(label);
-
- // Dots
- row.appendChild(buildDots(false));
-
- // Status
- const status = el('span', {
- fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',
- marginLeft: 'auto',
- });
- // Variants currently arrive atomically in a single file edit, so a
- // per-variant counter would lie. Say what's true.
- status.textContent = arrivedVariants < expectedVariants
- ? 'Generating ' + expectedVariants + ' variants...'
- : 'Done';
- row.appendChild(status);
-
- return row;
- }
-
- // --- Cycling row ---
-
- const TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';
-
- function buildCyclingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '6px',
- padding: '1px 2px',
- });
-
- // Prev
- const prev = navBtn('\u2190');
- prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
- if (visibleVariant <= 1) prev.style.opacity = '0.3';
- row.appendChild(prev);
-
- // Dots (clickable)
- row.appendChild(buildDots(true));
-
- // Counter
- const counter = el('span', {
- fontFamily: MONO, fontSize: '11px', fontWeight: '500',
- color: BP.textDim, minWidth: '24px', textAlign: 'center',
- });
- counter.textContent = visibleVariant + '/' + arrivedVariants;
- row.appendChild(counter);
-
- // Next
- const next = navBtn('\u2192');
- next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
- if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
- row.appendChild(next);
-
- // Tune chip — only when the visible variant exposes params
- const visParams = parseVariantParams(getVisibleVariantEl());
- const hasParams = visParams.length > 0;
- if (hasParams) {
- const tune = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '6px',
- padding: '4px 10px', borderRadius: '5px',
- border: '1px solid transparent',
- background: tuneOpen ? BP.accentSoft : 'transparent',
- color: tuneOpen ? BP.accent : BP.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'color 0.12s ease, background 0.12s ease',
- whiteSpace: 'nowrap',
- });
- tune.innerHTML = TUNE_ICON_SVG;
- const tuneLabel = document.createElement('span');
- tuneLabel.textContent = 'Tune';
- tune.appendChild(tuneLabel);
- const tuneBadge = document.createElement('span');
- Object.assign(tuneBadge.style, {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- minWidth: '16px', height: '16px', padding: '0 4px',
- borderRadius: '999px',
- background: tuneOpen ? C.brand : BP.hairline,
- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',
- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',
- lineHeight: '1',
- boxSizing: 'border-box',
- });
- tuneBadge.textContent = String(visParams.length);
- tune.appendChild(tuneBadge);
- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';
- tune.addEventListener('mouseenter', () => {
- if (!tuneOpen) tune.style.background = BP.accentSoft;
- });
- tune.addEventListener('mouseleave', () => {
- if (!tuneOpen) tune.style.background = 'transparent';
- });
- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });
- tune.dataset.iceqTune = '1';
- row.appendChild(tune);
- }
-
- // Spacer
- row.appendChild(el('div', { flex: '1' }));
-
- // Accept — primary action, uses the site's saturated brand magenta
- // with paper-white text, not the theme-muted BP.accent.
- const accept = el('button', {
- padding: '5px 14px', borderRadius: '5px',
- border: 'none', background: C.brand, color: 'oklch(98% 0 0)',
- fontFamily: FONT, fontSize: '11px', fontWeight: '600',
- cursor: 'pointer', transition: 'filter 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap',
- });
- accept.textContent = '\u2713 Accept';
- accept.addEventListener('mouseenter', () => accept.style.filter = 'brightness(1.08)');
- accept.addEventListener('mouseleave', () => accept.style.filter = 'none');
- accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');
- accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');
- accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
- row.appendChild(accept);
-
- // Discard
- const discard = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: FONT, fontSize: '11px', color: BP.textDim,
- cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
- });
- discard.textContent = '\u2715';
- discard.title = 'Discard all variants';
- discard.addEventListener('mouseenter', () => { discard.style.color = BP.text; discard.style.borderColor = BP.text; });
- discard.addEventListener('mouseleave', () => { discard.style.color = BP.textDim; discard.style.borderColor = BP.hairline; });
- discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
- row.appendChild(discard);
-
- return row;
- }
-
- // --- Shared UI builders ---
-
- // --- Saving row (waiting for agent to process accept/discard) ---
-
- function buildSavingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const spinner = el('div', {
- width: '14px', height: '14px', borderRadius: '50%',
- border: '2px solid ' + BP.hairline,
- borderTopColor: BP.accent,
- animation: 'impeccable-spin 0.6s linear infinite',
- flexShrink: '0',
- });
- row.appendChild(spinner);
- const label = el('span', {
- fontSize: '12px', color: BP.textDim, fontWeight: '500',
- });
- label.textContent = 'Applying variant...';
- row.appendChild(label);
-
- // Inject the keyframes if not already present
- if (!document.getElementById(PREFIX + '-keyframes')) {
- const style = document.createElement('style');
- style.id = PREFIX + '-keyframes';
- style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
- document.head.appendChild(style);
- }
- return row;
- }
-
- // --- Confirmed row (green success, auto-dismisses) ---
-
- function buildConfirmedRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const check = el('span', {
- fontSize: '15px', lineHeight: '1', flexShrink: '0',
- color: 'oklch(45% 0.15 145)',
- });
- check.textContent = '\u2713';
- row.appendChild(check);
- const label = el('span', {
- fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
- });
- label.textContent = 'Variant applied';
- row.appendChild(label);
- return row;
- }
-
- // --- Shared UI builders ---
-
- function buildDots(clickable) {
- const container = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
- for (let i = 1; i <= expectedVariants; i++) {
- const arrived = i <= arrivedVariants;
- const active = i === visibleVariant;
- // active: solid site-brand magenta dot. arrived+inactive: muted neutral.
- // pending (not yet arrived): faint outline ring. No borders on arrived
- // dots — the previous "accent ring + ash fill" combo read as noisy
- // magenta chips, especially when all variants had arrived and every
- // dot wore an accent ring.
- const dotBg = active ? C.brand
- : arrived ? BP.textDim
- : 'transparent';
- const dotBorder = arrived ? 'none' : '1.5px solid ' + BP.hairline;
- const dot = el('div', {
- width: active ? '8px' : '6px',
- height: active ? '8px' : '6px',
- borderRadius: '50%',
- background: dotBg,
- border: dotBorder,
- boxSizing: 'border-box',
- transition: 'all 0.2s ' + EASE,
- cursor: (clickable && arrived) ? 'pointer' : 'default',
- transform: arrived ? 'scale(1)' : 'scale(0.85)',
- opacity: arrived ? (active ? '1' : '0.6') : '0.4',
- });
- if (clickable && arrived) {
- const idx = i;
- dot.addEventListener('click', (e) => {
- e.stopPropagation();
- visibleVariant = idx;
- showVariantInDOM(currentSessionId, idx);
- updateSelectedElement();
- updateBarContent('cycling');
- });
- }
- container.appendChild(dot);
- }
- return container;
- }
-
- function navBtn(text) {
- const b = el('button', {
- width: '26px', height: '26px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- color: BP.text, fontFamily: FONT, fontSize: '13px',
- cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
- transition: 'border-color 0.12s ease, background 0.12s ease',
- padding: '0', lineHeight: '1',
- });
- b.textContent = text;
- b.addEventListener('mouseenter', () => { b.style.borderColor = BP.text; });
- b.addEventListener('mouseleave', () => { b.style.borderColor = BP.hairline; });
- return b;
- }
-
- function actionLabel() {
- const a = ACTIONS.find(a => a.value === selectedAction);
- return a ? a.label : 'Freeform';
- }
-
- function el(tag, styles) {
- const e = document.createElement(tag);
- if (styles) Object.assign(e.style, styles);
- return e;
- }
-
- // ---------------------------------------------------------------------------
- // Action picker popover
- // ---------------------------------------------------------------------------
-
- function initActionPicker() {
- const P = barPaletteForTheme(detectPageTheme());
- pickerEl = document.createElement('div');
- pickerEl.id = PREFIX + '-picker';
- Object.assign(pickerEl.style, {
- position: 'fixed', zIndex: Z.picker,
- display: 'none', opacity: '0',
- transform: 'scale(0.96) translateY(4px)',
- transformOrigin: 'bottom left',
- transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
- background: P.surface,
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
- padding: '6px',
- fontFamily: FONT,
- backdropFilter: 'blur(10px)',
- WebkitBackdropFilter: 'blur(10px)',
- });
-
- // Build the chip grid
- const grid = el('div', {
- display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
- });
-
- ACTIONS.forEach(action => {
- const chip = el('button', {
- display: 'flex', flexDirection: 'column', alignItems: 'center',
- gap: '4px',
- padding: '8px 6px', borderRadius: '6px',
- border: 'none',
- background: action.value === selectedAction ? P.accentSoft : 'transparent',
- color: action.value === selectedAction ? P.accent : P.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.1s ease, color 0.1s ease',
- textAlign: 'center', whiteSpace: 'nowrap',
- });
- const iconWrap = el('span', {
- display: 'flex', alignItems: 'center', justifyContent: 'center',
- height: '20px', opacity: '0.9',
- });
- iconWrap.innerHTML = ICONS[action.value] || '';
- const labelEl = el('span', { lineHeight: '1' });
- labelEl.textContent = action.label;
- chip.appendChild(iconWrap);
- chip.appendChild(labelEl);
- chip.dataset.action = action.value;
- chip.addEventListener('mouseenter', () => {
- if (action.value !== selectedAction) chip.style.background = P.accentSoft;
- });
- chip.addEventListener('mouseleave', () => {
- chip.style.background = action.value === selectedAction ? P.accentSoft : 'transparent';
- });
- chip.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedAction = action.value;
- hideActionPicker();
- updateBarContent('configure');
- });
- grid.appendChild(chip);
- });
-
- pickerEl.appendChild(grid);
- document.body.appendChild(pickerEl);
- defangOutsideHandlers(pickerEl);
-
- // Cache the palette on the picker so toggleActionPicker's state refresh
- // uses the same theme-aware colors when it repaints chips.
- pickerEl.__iceq_palette = P;
- }
-
- function toggleActionPicker() {
- if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
- // Rebuild chips to reflect current selection
- const P = pickerEl.__iceq_palette || barPaletteForTheme(detectPageTheme());
- pickerEl.querySelectorAll('button').forEach(chip => {
- const isActive = chip.dataset.action === selectedAction;
- chip.style.background = isActive ? P.accentSoft : 'transparent';
- chip.style.color = isActive ? P.accent : P.text;
- });
- // Position above the bar
- const barRect = barEl.getBoundingClientRect();
- const pickerH = 170; // approximate; grows with icon + label rows
- let top = barRect.top - pickerH - 6;
- if (top < 8) top = barRect.bottom + 6;
- Object.assign(pickerEl.style, {
- top: top + 'px', left: barRect.left + 'px',
- display: 'block',
- });
- requestAnimationFrame(() => {
- pickerEl.style.opacity = '1';
- pickerEl.style.transform = 'scale(1) translateY(0)';
- });
- }
-
- function hideActionPicker() {
- if (!pickerEl) return;
- pickerEl.style.opacity = '0';
- pickerEl.style.transform = 'scale(0.96) translateY(4px)';
- setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
- }
-
- // ---------------------------------------------------------------------------
- // Params panel (per-variant coarse controls)
- //
- // Variants may declare a parameter manifest via a JSON attribute on the
- // variant wrapper:
- //
- // <div data-impeccable-variant="1"
- // data-impeccable-params='[{"id":"density","kind":"steps",...}]'>
- //
- // The panel docks to the right edge of the outline during CYCLING and
- // exposes 2-5 coarse knobs. Values apply to the variant wrapper so scoped
- // CSS can respond instantly without regeneration:
- //
- // range / numeric toggle → CSS var (`--p-<id>`) used via var(--p-foo, N)
- // steps / boolean toggle → data-p-<id> attribute used via :scope[data-p-foo="..."]
- //
- // On variant switch, values reset to that variant's declared defaults.
- // On accept, current values are sent in the event payload so the agent
- // can bake them into the source-file write.
- // ---------------------------------------------------------------------------
-
- let paramsPanelEl = null; // outer wrapper (overflow:hidden, clips the slide)
- let paramsPanelInner = null; // translating content (carries bg, padding, knobs)
- let paramsPanelBody = null; // grid holding the knob cells
- let paramsCurrentValues = {}; // {paramId: value} — mirror of the visible variant's live values
- let tuneOpen = false; // whether the Tune popover is open right now
-
- // Theme-aware Tune popover. Appears as a drawer that slides out from the
- // contextual bar's bar-facing edge (below if the bar sits below the
- // element, above otherwise). Same width as the bar. Auto-wraps to extra
- // rows when the knobs exceed one row. The bar's border-radius on the
- // popover side goes flat while open so the two shapes read as one.
- let paramsPanelPalette = null;
-
- function initParamsPanel() {
- paramsPanelPalette = barPaletteForTheme(detectPageTheme());
- const P = paramsPanelPalette;
-
- // Single element, always in the DOM. The slide animation is a CSS mask
- // with mask-size growing from 0% to 100% along the bar-facing axis — no
- // display toggle, no opacity toggle, no transform trickery. The mask
- // hides everything initially; as it grows, content is revealed from
- // the bar edge outward.
- paramsPanelEl = document.createElement('div');
- paramsPanelEl.id = PREFIX + '-params-panel';
- Object.assign(paramsPanelEl.style, {
- position: 'fixed', zIndex: String(Z.bar - 1),
- background: P.surfaceDeep,
- color: P.text,
- fontFamily: FONT,
- padding: '14px 18px',
- boxSizing: 'border-box',
- borderRadius: '0 0 10px 10px',
- pointerEvents: 'none',
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
-
- // clip-path is the same conceptual reveal as mask but with rock-solid
- // transition support across engines. Closed state clips from the far
- // edge; open = inset(0) shows everything.
- clipPath: 'inset(0 0 100% 0)',
- transition: 'clip-path 0.44s ' + EASE,
-
- // Park off-screen until positionParamsPanel places it. These are NOT
- // in the transition list, so they snap instantly — no fly-in from the
- // top-left when first shown.
- top: '-9999px', left: '-9999px', width: '0',
- });
-
- paramsPanelBody = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
- gap: '12px 16px',
- });
-
- paramsPanelEl.appendChild(paramsPanelBody);
- document.body.appendChild(paramsPanelEl);
- // Don't override pointer-events: the panel toggles between 'none' (closed,
- // click-through) and 'auto' (open) on its own. Just silence the host's
- // outside-interaction listeners while the panel is open.
- defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
- paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
- }
-
- function getVisibleVariantEl() {
- if (!currentSessionId) return null;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return null;
- return wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"]');
- }
-
- function parseVariantParams(variantEl) {
- if (!variantEl) return [];
- const raw = variantEl.getAttribute('data-impeccable-params');
- if (!raw) return [];
- try {
- const parsed = JSON.parse(raw);
- return Array.isArray(parsed) ? parsed : [];
- } catch (err) {
- console.warn('[impeccable] Invalid data-impeccable-params JSON:', err.message);
- return [];
- }
- }
-
- function applyParamValue(variantEl, param, value) {
- if (!variantEl) return;
- const attr = 'data-p-' + param.id;
- if (param.kind === 'range') {
- variantEl.style.setProperty('--p-' + param.id, String(value));
- } else if (param.kind === 'toggle') {
- const on = !!value;
- variantEl.style.setProperty('--p-' + param.id, on ? '1' : '0');
- if (on) variantEl.setAttribute(attr, 'on');
- else variantEl.removeAttribute(attr);
- } else if (param.kind === 'steps') {
- variantEl.setAttribute(attr, String(value));
- }
- }
-
- function applyParamDefaults(variantEl, params) {
- paramsCurrentValues = {};
- for (const p of params) {
- paramsCurrentValues[p.id] = p.default;
- applyParamValue(variantEl, p, p.default);
- }
- }
-
- function formatRangeValue(input) {
- const max = parseFloat(input.max), min = parseFloat(input.min);
- const v = parseFloat(input.value);
- if (!isFinite(v)) return input.value;
- return (max - min) <= 2 ? v.toFixed(2) : String(Math.round(v));
- }
-
- function buildParamsPanel(variantEl, params) {
- const P = paramsPanelPalette || barPaletteForTheme(detectPageTheme());
- paramsPanelBody.innerHTML = '';
- for (const p of params) {
- const row = el('div', { display: 'flex', flexDirection: 'column', gap: '6px' });
- const labelRow = el('div', {
- display: 'flex', justifyContent: 'space-between',
- alignItems: 'baseline', gap: '8px',
- });
- const lbl = el('span', {
- fontSize: '10.5px', fontWeight: '600', color: P.text,
- letterSpacing: '0.03em',
- });
- lbl.textContent = p.label || p.id;
- labelRow.appendChild(lbl);
- const readout = el('span', {
- fontSize: '10.5px', color: P.textDim,
- fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
- });
- labelRow.appendChild(readout);
- row.appendChild(labelRow);
-
- if (p.kind === 'range') {
- const input = document.createElement('input');
- input.type = 'range';
- input.min = String(p.min != null ? p.min : 0);
- input.max = String(p.max != null ? p.max : 1);
- input.step = String(p.step != null ? p.step : 0.05);
- input.value = String(p.default);
- Object.assign(input.style, {
- width: '100%', accentColor: C.brand, cursor: 'pointer',
- });
- readout.textContent = formatRangeValue(input);
- input.addEventListener('input', (e) => {
- e.stopPropagation();
- const v = parseFloat(input.value);
- paramsCurrentValues[p.id] = v;
- readout.textContent = formatRangeValue(input);
- applyParamValue(variantEl, p, v);
- queueCheckpoint('param_changed');
- });
- row.appendChild(input);
- } else if (p.kind === 'toggle') {
- const initial = !!p.default;
- readout.textContent = initial ? 'On' : 'Off';
- const track = el('button', {
- position: 'relative', width: '36px', height: '20px',
- borderRadius: '10px', border: 'none', padding: '0',
- cursor: 'pointer',
- background: initial ? C.brand : P.hairline,
- transition: 'background 0.15s ease',
- alignSelf: 'flex-start',
- });
- const knob = el('span', {
- position: 'absolute', top: '2px',
- left: initial ? '18px' : '2px',
- width: '16px', height: '16px', borderRadius: '50%',
- background: 'oklch(98% 0 0)',
- transition: 'left 0.18s ' + EASE,
- boxShadow: '0 1px 2px oklch(0% 0 0 / 0.2)',
- });
- track.appendChild(knob);
- track.addEventListener('click', (e) => {
- e.stopPropagation();
- const next = !paramsCurrentValues[p.id];
- paramsCurrentValues[p.id] = next;
- track.style.background = next ? C.brand : P.hairline;
- knob.style.left = next ? '18px' : '2px';
- readout.textContent = next ? 'On' : 'Off';
- applyParamValue(variantEl, p, next);
- queueCheckpoint('param_changed');
- });
- row.appendChild(track);
- } else if (p.kind === 'steps') {
- const opts = (p.options || []).map(o =>
- typeof o === 'string' ? { value: o, label: o } : o
- );
- const activeOpt = opts.find(o => o.value === p.default) || opts[0];
- readout.textContent = activeOpt ? activeOpt.label : String(p.default);
- const segRow = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(' + opts.length + ', 1fr)',
- gap: '1px', padding: '2px',
- background: P.hairline, borderRadius: '5px',
- });
- const segBtns = [];
- opts.forEach(o => {
- const active = o.value === p.default;
- const b = el('button', {
- padding: '5px 4px', border: 'none', borderRadius: '3px',
- background: active ? C.brand : 'transparent',
- color: active ? 'oklch(98% 0 0)' : P.text,
- fontFamily: FONT, fontSize: '10.5px', fontWeight: '500',
- cursor: 'pointer', whiteSpace: 'nowrap',
- transition: 'background 0.1s ease, color 0.1s ease',
- });
- b.textContent = o.label;
- b.addEventListener('click', (e) => {
- e.stopPropagation();
- paramsCurrentValues[p.id] = o.value;
- readout.textContent = o.label;
- segBtns.forEach(({ btn, val }) => {
- const on = val === o.value;
- btn.style.background = on ? C.brand : 'transparent';
- btn.style.color = on ? 'oklch(98% 0 0)' : P.text;
- });
- applyParamValue(variantEl, p, o.value);
- queueCheckpoint('param_changed');
- });
- segRow.appendChild(b);
- segBtns.push({ btn: b, val: o.value });
- });
- row.appendChild(segRow);
- }
-
- paramsPanelBody.appendChild(row);
- }
- }
-
- // Decide which way the popover opens: away from the picked element. If the
- // bar landed below the element, popover slides DOWN from the bar's bottom.
- // If the bar landed above, popover slides UP from the bar's top.
- function popoverDirection() {
- if (!barEl || !selectedElement) return 'below';
- const br = barEl.getBoundingClientRect();
- const er = selectedElement.getBoundingClientRect();
- return br.top >= er.bottom - 4 ? 'below' : 'above';
- }
-
- // The popover overlaps the bar by OVERLAP px on the bar-facing side. With
- // popover z-index below bar, that overlap sits behind bar (invisible) and
- // reinforces the "tucked behind" feel. Padding compensates so the real
- // content starts flush with bar's outer edge.
- const TUNE_OVERLAP = 6;
-
- // Closed clip-path depends on direction: for 'below' clip from the far
- // (bottom) edge so the reveal grows downward from the bar; for 'above'
- // clip from the top edge so the reveal grows upward from the bar.
- function closedClipPath(direction) {
- return direction === 'below' ? 'inset(0 0 100% 0)' : 'inset(100% 0 0 0)';
- }
-
- function setClipPath(value, withTransition) {
- const saved = paramsPanelEl.style.transition;
- if (!withTransition) paramsPanelEl.style.transition = 'none';
- paramsPanelEl.style.clipPath = value;
- if (!withTransition) {
- void paramsPanelEl.offsetHeight;
- paramsPanelEl.style.transition = saved;
- }
- }
-
- function positionParamsPanel() {
- if (!paramsPanelEl || !barEl || barEl.style.display === 'none') return;
- const br = barEl.getBoundingClientRect();
- const direction = popoverDirection();
- const prevDirection = paramsPanelEl.dataset.tuneDirection;
-
- // top/left/width are NOT in the transition list, so they snap instantly.
- paramsPanelEl.style.left = br.left + 'px';
- paramsPanelEl.style.width = br.width + 'px';
-
- if (direction === 'below') {
- paramsPanelEl.style.top = (br.bottom - TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '0 0 10px 10px';
- paramsPanelEl.style.paddingTop = (14 + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.paddingBottom = '14px';
- } else {
- const ih = paramsPanelEl.offsetHeight || 80;
- paramsPanelEl.style.top = (br.top - ih + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '10px 10px 0 0';
- paramsPanelEl.style.paddingTop = '14px';
- paramsPanelEl.style.paddingBottom = (14 + TUNE_OVERLAP) + 'px';
- }
- paramsPanelEl.dataset.tuneDirection = direction;
-
- // If currently closed and direction flipped (or first-time setup),
- // snap the clip-path to the new direction's closed pose without
- // transitioning (so the clip doesn't slide across the element).
- if (!tuneOpen && (!prevDirection || prevDirection !== direction)) {
- setClipPath(closedClipPath(direction), false);
- }
- }
-
- function showParamsPanel() {
- if (!paramsPanelEl) return;
- positionParamsPanel();
- paramsPanelEl.style.pointerEvents = 'auto';
- // rAF so the positioning paint commits before the transition fires.
- requestAnimationFrame(() => {
- setClipPath('inset(0 0 0 0)', true);
- });
- }
-
- function hideParamsPanel() {
- if (!paramsPanelEl) return;
- paramsPanelEl.style.pointerEvents = 'none';
- const direction = paramsPanelEl.dataset.tuneDirection || 'below';
- setClipPath(closedClipPath(direction), true);
- }
-
- // Build/rebuild the panel's contents for the current variant AND apply
- // its defaults to the variant wrapper (so scoped CSS responds even before
- // the user opens the popover). Visibility is governed by tuneOpen.
- function refreshParamsPanel() {
- if (state !== 'CYCLING') {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- if (tuneOpen) {
- // If already visible (variant cycled while open), refresh in place
- // instead of re-running the clip-path animation.
- const alreadyVisible = paramsPanelEl.style.display === 'block'
- && paramsPanelEl.style.opacity === '1';
- if (alreadyVisible) positionParamsPanel();
- else showParamsPanel();
- } else {
- hideParamsPanel();
- }
- }
-
- function toggleTunePopover() {
- if (tuneOpen) { closeTunePopover(); return; }
- openTunePopover();
- }
-
- function openTunePopover() {
- if (state !== 'CYCLING') return;
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) return;
- // Build fresh to ensure the current variant's controls are shown.
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- tuneOpen = true;
- showParamsPanel();
- // Kill the bar's shadow on the popover-facing side so the dark popover
- // doesn't pick up a bright glow line.
- if (barEl) {
- const direction = paramsPanelEl?.dataset.tuneDirection || 'below';
- barEl.style.boxShadow = direction === 'below' ? BAR_SHADOW_UP : BAR_SHADOW_DOWN;
- }
- // Re-render the bar so the Tune chip picks up the active styling.
- updateBarContent('cycling');
- }
-
- function closeTunePopover() {
- tuneOpen = false;
- hideParamsPanel();
- if (barEl) barEl.style.boxShadow = BAR_SHADOW_DEFAULT;
- if (barEl && barEl.style.display !== 'none' && state === 'CYCLING') {
- updateBarContent('cycling');
- }
- }
-
- // ---------------------------------------------------------------------------
- // Variant cycling in DOM
- // ---------------------------------------------------------------------------
-
- function showVariantInDOM(sessionId, num) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
- for (const child of wrapper.children) {
- const v = child.dataset ? child.dataset.impeccableVariant : null;
- if (!v) continue;
- child.style.display = (v === String(num)) ? '' : 'none';
- }
- // Unconditional refresh — covers first-reveal (no-op if state isn't
- // CYCLING yet, the subsequent CYCLING transition triggers its own
- // refresh) and every cycle step.
- refreshParamsPanel();
- }
-
- /**
- * No-HMR fallback: fetch the raw source file from the live server,
- * parse it, extract the variant wrapper, and inject it into the live DOM.
- * This works even when the dev server caches HTML (Bun, static servers).
- */
- function injectVariantsFromSource(filePath, sessionId) {
- const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
- fetch(url)
- .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
- .then(html => {
- // Parse the raw source HTML
- const parser = new DOMParser();
- const doc = parser.parseFromString(html, 'text/html');
- const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!srcWrapper) {
- console.error('[impeccable] Variant wrapper not found in source file.');
- return;
- }
-
- // Find the original element in the live DOM.
- // The original is inside the wrapper in the source. We find the
- // corresponding element in the live DOM by matching the first child's
- // tag + classes from the original snapshot.
- const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
- if (!origContent) return;
-
- const tag = origContent.tagName.toLowerCase();
- const cls = origContent.className;
- let liveEl = null;
- if (origContent.id) {
- liveEl = document.getElementById(origContent.id);
- } else if (cls) {
- // Find by tag + exact class match
- const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
- for (const c of candidates) {
- if (c.className === cls && !own(c)) { liveEl = c; break; }
- }
- }
-
- if (!liveEl) {
- console.error('[impeccable] Could not find original element in live DOM.');
- return;
- }
-
- const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;
-
- // Replace the live element with the full wrapper from source
- const wrapper = srcWrapper.cloneNode(true);
- liveEl.parentElement.replaceChild(wrapper, liveEl);
-
- // Update state: count variants, preserving the user's current variant
- // when a late HMR/source reinjection lands after they have cycled.
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants
- ? previousVisibleVariant
- : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);
- showVariantInDOM(sessionId, visibleVariant);
-
- // Update selectedElement to the visible variant's content
- selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;
-
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- saveSession();
- console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
- })
- .catch(err => {
- console.error('[impeccable] Failed to fetch source:', err);
- showToast('Could not load variants. Try refreshing the page.', 5000);
- });
- }
-
- function cycleVariant(dir) {
- const next = visibleVariant + dir;
- if (next < 1 || next > arrivedVariants) return;
- visibleVariant = next;
- showVariantInDOM(currentSessionId, next); // calls refreshParamsPanel itself
- updateSelectedElement();
- updateBarContent('cycling');
- saveSession();
- queueCheckpoint('variant_changed');
- }
-
- function updateSelectedElement() {
- if (!currentSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return;
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- function readVisibleVariantFromDOM(sessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return 0;
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- for (const variant of variants) {
- if (variant.style.display === 'none') continue;
- const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);
- if (idx > 0) return idx;
- }
- return 0;
- }
-
- // Resolve the element that represents the variant's visible content.
- // Contract: each variant div should contain exactly one top-level element
- // (the full replacement). In practice a model may ship loose siblings or
- // lead with <style>/<script>. Be defensive: skip non-visual elements, and
- // if the variant has multiple element children, use the variant div itself
- // (it wraps all of them and gets correct bounds).
- function pickVariantContent(wrapper, index) {
- if (!wrapper) return null;
- const variantDiv = wrapper.querySelector('[data-impeccable-variant="' + index + '"]');
- if (!variantDiv) return null;
- const NON_VISUAL = new Set(['STYLE', 'SCRIPT', 'LINK', 'META', 'TEMPLATE']);
- const visual = [];
- for (const child of variantDiv.children) {
- if (!NON_VISUAL.has(child.tagName)) visual.push(child);
- }
- if (visual.length === 1) return visual[0];
- return variantDiv;
- }
-
- // Hold window.scrollY at a fixed value across DOM mutations inside the
- // session's wrapper (HMR patches, variant inserts, cycle swaps).
- function startScrollLock(sessionId, initialTargetY) {
- stopScrollLock();
- scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)
- ? initialTargetY
- : window.scrollY;
- console.log('[impeccable.scroll] startScrollLock', { sessionId, scrollY: window.scrollY, targetY: scrollLockTargetY, initialOverride: initialTargetY });
-
- try { history.scrollRestoration = 'manual'; } catch {}
-
- const prevHtmlAnchor = document.documentElement.style.overflowAnchor;
- const prevBodyAnchor = document.body.style.overflowAnchor;
- document.documentElement.style.overflowAnchor = 'none';
- document.body.style.overflowAnchor = 'none';
-
- const correct = (why) => {
- scrollLockRaf = null;
- if (scrollLockTargetY == null) return;
- const before = window.scrollY;
- const delta = before - scrollLockTargetY;
- if (Math.abs(delta) < 0.5) {
- console.log('[impeccable.scroll] correct noop', { why, scrollY: before, targetY: scrollLockTargetY });
- return;
- }
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] corrected', { why, from: before, to: scrollLockTargetY, delta, nowAt: window.scrollY });
- };
- const schedule = (why) => {
- if (scrollLockRaf != null) return;
- scrollLockRaf = requestAnimationFrame(() => correct(why));
- };
-
- scrollLockObserver = new MutationObserver((mutations) => {
- for (const m of mutations) {
- if (m.target?.closest?.('[data-impeccable-variants="' + sessionId + '"]')) {
- const childAdds = Array.from(m.addedNodes).map(n => n.nodeType === 1 ? (n.tagName + (n.dataset?.impeccableVariant ? ('[variant=' + n.dataset.impeccableVariant + ']') : '')) : n.nodeType).join(',');
- console.log('[impeccable.scroll] mutation inside wrapper', { type: m.type, target: m.target?.tagName, adds: childAdds, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('mutation-in-wrapper');
- return;
- }
- for (const n of m.addedNodes) {
- if (n.nodeType === 1 && (n.matches?.('[data-impeccable-variants="' + sessionId + '"]') || n.querySelector?.('[data-impeccable-variants="' + sessionId + '"]'))) {
- console.log('[impeccable.scroll] wrapper node added', { tag: n.tagName, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('wrapper-added');
- return;
- }
- }
- }
- });
- scrollLockObserver.observe(document.body, { childList: true, subtree: true });
-
- scrollLockAbort = new AbortController();
- scrollLockAbort.signal.addEventListener('abort', () => {
- document.documentElement.style.overflowAnchor = prevHtmlAnchor;
- document.body.style.overflowAnchor = prevBodyAnchor;
- }, { once: true });
- const sig = { signal: scrollLockAbort.signal };
- // Track whether the most recent scroll came from a user gesture. We
- // gate user-scroll re-anchoring on this flag so programmatic smooth
- // scrolls (browser reload-restore, scrollIntoView from other scripts)
- // don't accidentally update our target.
- let userGestureAt = 0;
- const USER_GESTURE_WINDOW_MS = 250;
-
- const reanchor = (why) => {
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- const prevTarget = scrollLockTargetY;
- scrollLockTargetY = window.scrollY;
- writeScrollY(scrollLockTargetY);
- console.log('[impeccable.scroll] reanchor', { why, prevTarget, newTarget: scrollLockTargetY });
- };
- const markGesture = (why) => {
- userGestureAt = performance.now();
- reanchor(why);
- };
- window.addEventListener('wheel', () => markGesture('wheel'), { passive: true, ...sig });
- window.addEventListener('touchstart', () => markGesture('touchstart'), { passive: true, ...sig });
- window.addEventListener('touchmove', () => markGesture('touchmove'), { passive: true, ...sig });
- window.addEventListener('keydown', (e) => {
- if (['PageDown', 'PageUp', ' ', 'End', 'Home', 'ArrowDown', 'ArrowUp'].includes(e.key)) markGesture('key:' + e.key);
- }, sig);
-
- // Correct on EVERY scroll event: whether it's the browser's
- // post-reload animated restore or some other script calling
- // scrollIntoView, we want to snap back immediately. Only skip if a
- // user gesture fired in the last 250ms.
- let lastLoggedScrollY = window.scrollY;
- window.addEventListener('scroll', () => {
- const now = window.scrollY;
- if (Math.abs(now - lastLoggedScrollY) > 5) {
- console.log('[impeccable.scroll] scroll event', { from: lastLoggedScrollY, to: now, targetY: scrollLockTargetY });
- lastLoggedScrollY = now;
- }
- if (scrollLockTargetY == null) return;
- if (performance.now() - userGestureAt < USER_GESTURE_WINDOW_MS) return;
- if (Math.abs(now - scrollLockTargetY) < 0.5) return;
- console.log('[impeccable.scroll] scroll-event snap', { from: now, to: scrollLockTargetY });
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- }, { passive: true, ...sig });
-
- // Apply target synchronously, not via rAF — racing the browser's
- // restore or a smooth-scroll animation means we want to win now.
- if (Math.abs(window.scrollY - scrollLockTargetY) > 0.5) {
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] startScrollLock initial apply', { to: scrollLockTargetY });
- }
- }
-
- function stopScrollLock() {
- if (scrollLockObserver) { scrollLockObserver.disconnect(); scrollLockObserver = null; }
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }
- scrollLockTargetY = null;
- // NOTE: do NOT clear the persistent scroll key here. startScrollLock
- // calls us as a reset, and clearing the key would nuke the Go-time
- // scrollY that the next resume needs to read.
- }
-
- // ---------------------------------------------------------------------------
- // MutationObserver for progressive variant reveal
- // ---------------------------------------------------------------------------
-
- function startVariantObserver(sessionId) {
- let updating = false; // re-entrancy guard
-
- const obs = new MutationObserver((mutations) => {
- if (updating) return;
-
- // Only react to mutations that add nodes with data-impeccable-variant,
- // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
- let dominated = false;
- for (const m of mutations) {
- if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
- for (const n of m.addedNodes) {
- if (n.nodeType !== 1) continue;
- // Direct hit: the added node itself is the wrapper or a variant.
- if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
- dominated = true; break;
- }
- // Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
- // a whole subtree where the wrapper is a descendant of the added
- // node. Without this check, the observer ignores those mutations
- // and the session stays in GENERATING forever.
- if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
- dominated = true; break;
- }
- }
- if (dominated) break;
- }
- if (!dominated) return;
-
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
-
- // Re-anchor selectedElement if it was detached by live-wrap's HMR swap.
- // Without this, the shader / highlight / bar track a zero-rect phantom
- // and the overlay appears frozen.
- if (selectedElement && !document.body.contains(selectedElement)) {
- selectedElement = pickVariantContent(wrapper, 'original') || wrapper;
- }
-
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- const count = variants.length;
-
- // Nothing new
- if (count <= arrivedVariants) return;
-
- updating = true;
- arrivedVariants = count;
- if (visibleVariant === 0 && arrivedVariants > 0) {
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;
- showVariantInDOM(sessionId, visibleVariant);
- // showVariantInDOM hid the original (display:none); if we were still
- // anchored to the original's content, its boundingRect is now zero
- // and the bar snaps to (0,0). Re-point at the visible variant instead.
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- if (expected > 0) expectedVariants = expected;
-
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- } else if (state === 'GENERATING') {
- updateBarContent('generating');
- }
- saveSession();
- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');
- updating = false;
- });
-
- obs.observe(document.body, { childList: true, subtree: true });
- return obs;
- }
-
- // ---------------------------------------------------------------------------
- // Bar scroll tracking
- // ---------------------------------------------------------------------------
-
- function startScrollTracking() {
- function tick() {
- if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
- positionBar();
- showHighlight(selectedElement);
- if (tuneOpen) positionParamsPanel();
- }
- if (annotActive) positionAnnotOverlay(selectedElement);
- // Shader overlay (via debug P toggle or generation) is repositioned
- // by its own branch below; debug no longer has a separate overlay.
- if (shaderState) positionShaderOverlay();
- scrollRaf = requestAnimationFrame(tick);
- }
- scrollRaf = requestAnimationFrame(tick);
- }
-
- function stopScrollTracking() {
- if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
- }
-
- // ---------------------------------------------------------------------------
- // SSE (server→browser) + fetch POST (browser→server)
- // Zero-dependency replacement for WebSocket.
- // ---------------------------------------------------------------------------
-
- let evtSource = null;
- let sseRetries = 0;
- const SSE_MAX_RETRIES = 20; // generous: heartbeats keep the connection alive, so retries mean real trouble
-
- function connectSSE() {
- evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
-
- evtSource.onopen = () => {
- sseRetries = 0; // reset on successful (re)connect
- };
-
- evtSource.onmessage = (e) => {
- sseRetries = 0; // reset on any successful message
- let msg; try { msg = JSON.parse(e.data); } catch { return; }
- switch (msg.type) {
- case 'connected':
- hasProjectContext = !!msg.hasProjectContext;
- if (!hasProjectContext) showToast('No PRODUCT.md found. Variants will be brand-agnostic. Run /impeccable teach to generate one.', 7000);
- console.log('[impeccable] Live mode connected.');
- if (state === 'IDLE') state = 'PICKING';
- break;
- case 'done':
- // Variants already arrived via HMR → normal transition.
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- if (state === 'GENERATING') {
- state = 'CYCLING';
- updateBarContent('cycling');
- refreshParamsPanel();
- }
- break;
- }
- // Variants are in source but not in the DOM yet. Common when the
- // picked element lived inside conditional render (closed modal,
- // hidden tab, a route the user navigated away from). The variant
- // MutationObserver stays armed and auto-transitions to CYCLING
- // the moment the wrapper actually mounts. Nudge the user toward
- // that path with a toast — better than the prior force-reload
- // which reset framework state and left the session stuck.
- setTimeout(() => {
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
- if (state !== 'GENERATING') return;
- showToast(
- "Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
- 15000,
- );
- }, 2000);
- break;
- case 'error':
- console.error('[impeccable] Error:', msg.message);
- showToast('Error: ' + msg.message, 5000);
- hideBar();
- state = 'PICKING';
- break;
- }
- };
-
- evtSource.onerror = () => {
- sseRetries++;
- if (sseRetries <= SSE_MAX_RETRIES) {
- console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
- return; // EventSource auto-reconnects
- }
- // Server is gone. Clean up gracefully.
- console.log('[impeccable] Live server unreachable. Cleaning up UI.');
- evtSource.close();
- evtSource = null;
- handleServerLost();
- };
- }
-
- /** Server died or became unreachable. Reset UI to a clean state. */
- function handleServerLost() {
- const recoveryState = currentSessionId ? state : 'IDLE';
- if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
- showToast('Live server disconnected. Session ended.', 5000);
- }
- hideBar();
- hideHighlight();
- hideShaderOverlay();
- hideAnnotOverlay();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- // Preserve local session state on server loss. The durable journal is the
- // source of truth, but localStorage plus the variant wrapper lets the UI
- // resume after a helper restart or page reload instead of treating a
- // transient disconnect as an explicit discard.
- selectedElement = null;
- selectedAction = 'impeccable';
- state = recoveryState;
- if (currentSessionId) saveSession();
- }
-
- function sendEvent(msg, opts) {
- msg.token = TOKEN;
- function handleFailure(err) {
- console.error('[impeccable] Failed to send event:', err);
- if (opts && opts.throwOnError) throw err;
- return null;
- }
- return fetch('http://localhost:' + PORT + '/events', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(msg),
- }).then(res => {
- if (res.ok) return res;
- return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));
- }).catch(handleFailure);
- }
-
- function checkpointPayload(reason) {
- return {
- type: 'checkpoint',
- id: currentSessionId,
- revision: sessionState.nextCheckpointRevision(),
- owner: browserOwner,
- phase: String(state || '').toLowerCase(),
- reason,
- pageUrl: location.pathname,
- expectedVariants,
- arrivedVariants,
- visibleVariant,
- paramValues: { ...paramsCurrentValues },
- };
- }
-
- function sendCheckpoint(reason) {
- if (!currentSessionId) return Promise.resolve(null);
- return sendEvent(checkpointPayload(reason)).catch(() => null);
- }
-
- function queueCheckpoint(reason) {
- if (!currentSessionId) return;
- if (checkpointTimer) clearTimeout(checkpointTimer);
- checkpointTimer = setTimeout(() => {
- checkpointTimer = null;
- sendCheckpoint(reason);
- }, 120);
- }
-
- // ---------------------------------------------------------------------------
- // Event handlers
- // ---------------------------------------------------------------------------
-
- function handleMouseMove(e) {
- if (state !== 'PICKING' || !pickActive) return;
- const target = document.elementFromPoint(e.clientX, e.clientY);
- if (!target || !pickable(target) || target === hoveredElement) return;
- hoveredElement = target;
- showHighlight(target);
- }
-
- function handleClick(e) {
- // Close action picker on any outside click
- if (pickerEl?.style.display !== 'none' && !own(e.target)) {
- hideActionPicker();
- }
- // Close Tune popover on outside click (anything outside panel + bar)
- if (tuneOpen && paramsPanelEl && !paramsPanelEl.contains(e.target) && barEl && !barEl.contains(e.target)) {
- closeTunePopover();
- }
- // In CONFIGURING: click outside the bar and selected element returns to PICKING
- if (state === 'CONFIGURING' && !own(e.target) && selectedElement && !selectedElement.contains(e.target)) {
- hideBar();
- stopScrollTracking();
- hideAnnotOverlay();
- clearAnnotations();
- state = 'PICKING';
- hoveredElement = null;
- hideHighlight();
- return;
- }
- if (state !== 'PICKING' || !pickActive) return;
- if (own(e.target)) return;
- if (!hoveredElement || !pickable(hoveredElement)) return;
- e.preventDefault();
- e.stopPropagation();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- maybePrefetchPage();
- maybeWarnConditionalAncestor(selectedElement);
- }
-
- /**
- * Surface a brief, non-blocking heads-up when the picked element lives
- * inside a container whose visibility is gated by ephemeral state — modals,
- * collapsible panels, popovers, off-screen tab panels. If HMR remounts the
- * parent during generation (Vite Fast Refresh, SvelteKit page reload), the
- * variants land in source but stay invisible until the user re-opens the
- * container. Telling the user upfront is much friendlier than the silent
- * timeout-then-toast that they'd otherwise hit.
- *
- * Heuristic, intentionally narrow — only fires for unambiguous cases so
- * we don't cry wolf on every nested element.
- */
- function maybeWarnConditionalAncestor(el) {
- let node = el?.parentElement;
- let depth = 0;
- while (node && depth < 12) {
- // 1. Active dialog / modal
- if (node.getAttribute && node.getAttribute('role') === 'dialog'
- && node.getAttribute('aria-modal') === 'true') {
- showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 2. Common Radix / shadcn / headless-ui open-state attribute
- if (node.dataset && node.dataset.state === 'open') {
- showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 3. Tab panel — only meaningful when the page also shows ANOTHER
- // tab as selected. A single tabpanel with no tablist is just a static
- // section in disguise and isn't conditional.
- if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
- const list = document.querySelector('[role="tablist"]');
- if (list) {
- const tabs = list.querySelectorAll('[role="tab"]');
- if (tabs.length > 1) {
- showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
- return;
- }
- }
- }
- // 4. Collapsible: aria-expanded sibling. Look for the trigger button.
- if (node.id) {
- const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
- if (trigger) {
- showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
- return;
- }
- }
- node = node.parentElement;
- depth++;
- }
- }
-
- // Fire a lightweight prefetch event the first time the user selects an
- // element on a given route. The agent uses this to Read the underlying file
- // into context before Go is hit, shaving the read off the critical path.
- // Dedupe per session by pathname — clicking around on the same page doesn't
- // re-fire.
- //
- // DISABLED: quick-Go workflows pay an extra harness round trip because
- // prefetch + generate arrive as two events instead of one. Re-enable with
- // a browser-side debounce (~800–1000ms, cancelled on Go) if we want to
- // resurrect this. Server validator and skill dispatch remain in place so
- // flipping this flag is the only change needed.
- const PREFETCH_ENABLED = false;
- const prefetchedPaths = new Set();
- function maybePrefetchPage() {
- if (!PREFETCH_ENABLED) return;
- const path = location.pathname;
- if (prefetchedPaths.has(path)) return;
- prefetchedPaths.add(path);
- sendEvent({ type: 'prefetch', pageUrl: path });
- }
-
- function handleKeyDown(e) {
- // When the annotation input is focused, let it handle its own keys.
- if (annotEditing && annotEditing.input && e.target === annotEditing.input) return;
- if (e.key === 'Escape') {
- e.preventDefault();
- if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
- if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); hideAnnotOverlay(); clearAnnotations(); state = 'PICKING'; return; }
- if (state === 'CYCLING') { handleDiscard(); return; }
- if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
- if (state === 'PICKING') {
- // Use togglePick so the "Pick" button in the global bar also flips
- // off, otherwise the bar stays lit while nothing else is active.
- if (pickActive) togglePick();
- else { hideHighlight(); state = 'IDLE'; }
- return;
- }
- }
-
- // Arrow/Enter nav works in PICKING (hover) and CONFIGURING (selected, input empty)
- var navEl = (state === 'PICKING') ? hoveredElement : (state === 'CONFIGURING') ? selectedElement : null;
- if (navEl && (e.key === 'ArrowUp' || e.key === 'ArrowDown' || (e.key === 'Enter' && state === 'PICKING'))) {
- let next = null;
- if (e.key === 'ArrowDown' && !e.shiftKey) {
- next = navEl.nextElementSibling;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'ArrowUp' && !e.shiftKey) {
- next = navEl.previousElementSibling;
- while (next && !pickable(next)) next = next.previousElementSibling;
- } else if (e.key === 'ArrowUp' && e.shiftKey) {
- next = navEl.parentElement;
- if (next && !pickable(next)) next = null;
- } else if (e.key === 'ArrowDown' && e.shiftKey) {
- next = navEl.firstElementChild;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'Enter') {
- e.preventDefault();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- return;
- }
- if (next) {
- e.preventDefault();
- if (state === 'PICKING') {
- hoveredElement = next;
- } else {
- // CONFIGURING: re-select the new element and refresh the bar
- selectedElement = next;
- clearAnnotations();
- showAnnotOverlay(next);
- showBar('configure');
- startScrollTracking();
- }
- showHighlight(next);
- next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
- }
- return;
- }
-
- if (state === 'CYCLING') {
- if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
- if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
- if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
- }
- }
-
- function handleGo() {
- if (!selectedElement || state !== 'CONFIGURING') return;
- const input = document.getElementById(PREFIX + '-input');
- const prompt = input ? input.value.trim() : '';
-
- // Commit any pending pin edit BEFORE we snapshot annotations.
- if (annotEditing) finalizeEditingPin();
-
- currentSessionId = id8();
- expectedVariants = selectedCount;
- arrivedVariants = 0;
- visibleVariant = 0;
-
- // Flip to GENERATING immediately so the bar morphs without waiting on
- // capture + upload. The event is emitted from captureAndEmit() once the
- // screenshot is uploaded (or capture fails — we still emit, just without
- // screenshotPath).
- const elForCapture = selectedElement;
- const captureRect = elForCapture.getBoundingClientRect();
- const snapshot = {
- comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),
- strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),
- };
- const basePayload = {
- type: 'generate', id: currentSessionId,
- action: selectedAction,
- freeformPrompt: prompt || undefined,
- count: selectedCount,
- pageUrl: location.pathname,
- element: extractContext(elForCapture),
- };
- if (snapshot.comments.length > 0) basePayload.comments = snapshot.comments;
- if (snapshot.strokes.length > 0) basePayload.strokes = snapshot.strokes;
-
- // Hide the interactive overlay so it doesn't linger during generation.
- hideAnnotOverlay();
- clearAnnotations();
-
- state = 'GENERATING';
- showBar('generating');
- saveSession();
- sendCheckpoint('generate_started');
- writeScrollY(window.scrollY);
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
- console.log('[impeccable.scroll] Go pressed', { scrollY: window.scrollY, sessionId: currentSessionId });
- startScrollLock(currentSessionId);
-
- captureAndEmit(elForCapture, basePayload, snapshot, captureRect);
- }
-
- // ---------------------------------------------------------------------------
- // Screenshot capture + upload
- // ---------------------------------------------------------------------------
-
- let msLoadPromise = null;
- function loadModernScreenshot() {
- if (window.modernScreenshot) return Promise.resolve(window.modernScreenshot);
- if (msLoadPromise) return msLoadPromise;
- msLoadPromise = new Promise((resolve, reject) => {
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/modern-screenshot.js';
- s.onload = () => resolve(window.modernScreenshot);
- s.onerror = () => { msLoadPromise = null; reject(new Error('modern-screenshot failed to load')); };
- document.head.appendChild(s);
- });
- return msLoadPromise;
- }
-
- // Collect @font-face rules from every stylesheet on the page. Cross-origin
- // sheets (Google Fonts, Typekit, etc.) throw SecurityError on .cssRules
- // access, so modern-screenshot can't embed them on its own — the resulting
- // SVG falls back to system fonts and text re-wraps + renders with different
- // weight. We fetch the raw CSS text (CORS-permitted for these providers),
- // extract @font-face blocks, inline the referenced font files as base64
- // data URIs (SVGs rasterized via canvas can't fetch external resources,
- // so URLs inside the SVG silently fail without this), and pass the result
- // to modern-screenshot as font.cssText.
- const FONT_EXT_RE = /\.(woff2?|ttf|otf|eot)(\?.*)?$/i;
- const FONT_MIME = {
- woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', eot: 'application/vnd.ms-fontobject',
- };
- function bufferToBase64(buf) {
- const bytes = new Uint8Array(buf);
- let binary = '';
- const CHUNK = 0x8000;
- for (let i = 0; i < bytes.length; i += CHUNK) {
- binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
- }
- return btoa(binary);
- }
- async function inlineFontUrls(cssText) {
- const urlRe = /url\((['"]?)(https?:\/\/[^'")\s]+)\1\)/g;
- const urls = new Set();
- let m;
- while ((m = urlRe.exec(cssText))) {
- if (FONT_EXT_RE.test(m[2])) urls.add(m[2]);
- }
- const map = new Map();
- await Promise.all([...urls].map(async (url) => {
- try {
- const res = await fetch(url);
- if (!res.ok) return;
- const buf = await res.arrayBuffer();
- const ext = url.toLowerCase().match(FONT_EXT_RE)?.[1] || 'woff2';
- const mime = FONT_MIME[ext] || 'application/octet-stream';
- map.set(url, 'data:' + mime + ';base64,' + bufferToBase64(buf));
- } catch { /* skip; fall through to URL */ }
- }));
- return cssText.replace(urlRe, (orig, q, url) => {
- const data = map.get(url);
- return data ? 'url(' + q + data + q + ')' : orig;
- });
- }
- async function collectFontCssText() {
- const chunks = [];
- const fontFaceRe = /@font-face\s*\{[^}]*\}/g;
- for (const sheet of document.styleSheets) {
- try {
- const rules = sheet.cssRules;
- for (const rule of rules) {
- if (rule.constructor.name === 'CSSFontFaceRule' || rule.cssText?.startsWith('@font-face')) {
- chunks.push(rule.cssText);
- }
- }
- } catch {
- if (!sheet.href) continue;
- try {
- const res = await fetch(sheet.href);
- if (!res.ok) continue;
- const text = await res.text();
- let m2;
- while ((m2 = fontFaceRe.exec(text))) chunks.push(m2[0]);
- } catch { /* ignore; capture is best-effort */ }
- }
- }
- if (chunks.length === 0) return '';
- return inlineFontUrls(chunks.join('\n'));
- }
-
- // True if `s` is a computed color string that renders as nothing
- // (explicit `transparent`, or `rgba(...)` with alpha 0).
- function isTransparentColor(s) {
- if (!s) return true;
- if (s === 'transparent') return true;
- const m = /rgba?\(([^)]+)\)/.exec(s);
- if (!m) return false;
- const parts = m[1].split(',').map((p) => p.trim());
- if (parts.length === 4) return parseFloat(parts[3]) === 0;
- return false;
- }
-
- // modern-screenshot force-sets `background-color: X !important` on the
- // cloned root whenever `backgroundColor` is passed, clobbering the
- // element's own background. So we only pass it when the element is
- // genuinely transparent (no own color, no own image) — in that case
- // we resolve up the DOM to the nearest opaque ancestor so the capture
- // sits on the page's real background instead of rendering black.
- function resolveCanvasBackground(el) {
- const own = getComputedStyle(el);
- if (!isTransparentColor(own.backgroundColor)) return null;
- if (own.backgroundImage && own.backgroundImage !== 'none') return null;
- let node = el.parentElement;
- while (node) {
- const cs = getComputedStyle(node);
- if (!isTransparentColor(cs.backgroundColor)) return cs.backgroundColor;
- node = node.parentElement;
- }
- // The walk already passed through <body> and <html>; if they had been
- // opaque we would have returned. Falling through with the previous
- // `getComputedStyle(body).backgroundColor || …` chain is a trap: that
- // call returns the literal string `"rgba(0, 0, 0, 0)"` for a page that
- // never set its own bg, which is truthy and short-circuits the chain to
- // transparent-black — modern-screenshot then renders the capture on a
- // black canvas and the shader overlay flashes solid black during load.
- // The browser canvas defaults to white, so we do too.
- return '#ffffff';
- }
-
- // Capture the element (with current annotations baked in) and return a PNG
- // Blob. Shared between the Go flow (uploads it to the server) and the
- // debug toggle (displays it as an overlay for side-by-side comparison).
- async function captureElementToBlob(el, snapshot, rect) {
- try { if (document.fonts?.ready) await document.fonts.ready; } catch {}
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- let annotNode = null;
- let savedPosition = null;
- if (hasAnnotations) {
- const pos = getComputedStyle(el).position;
- if (pos === 'static') {
- savedPosition = el.style.position;
- el.style.position = 'relative';
- }
- annotNode = buildAnnotationsForCapture(rect, snapshot);
- el.appendChild(annotNode);
- }
- try {
- const ms = await loadModernScreenshot();
- const fontCssText = await collectFontCssText();
- const backgroundColor = resolveCanvasBackground(el);
- return await ms.domToBlob(el, {
- scale: Math.min(window.devicePixelRatio || 1, 2),
- font: fontCssText ? { cssText: fontCssText } : undefined,
- ...(backgroundColor ? { backgroundColor } : {}),
- });
- } finally {
- if (annotNode) annotNode.remove();
- if (savedPosition !== null) el.style.position = savedPosition;
- }
- }
-
- async function captureAndEmit(el, basePayload, snapshot, rect) {
- let screenshotPath;
- let blob;
- try {
- blob = await captureElementToBlob(el, snapshot, rect);
- } catch (err) {
- console.warn('[impeccable] capture failed, proceeding without screenshot:', err);
- }
- // Light up the shader overlay the moment capture is ready — no reason to
- // wait for the upload to complete before the user sees something alive.
- if (blob && state === 'GENERATING') {
- showShaderOverlay(el, blob, rect);
- }
- // Only upload + forward the screenshot when annotations (comments/strokes)
- // are present. Without annotations the image is pure visual anchoring —
- // it biases the model toward the current rendering and works against the
- // three-distinct-directions brief.
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- if (blob && hasAnnotations) {
- try {
- const uploadRes = await fetch(
- 'http://localhost:' + PORT + '/annotation?token=' + encodeURIComponent(TOKEN) +
- '&eventId=' + encodeURIComponent(basePayload.id),
- { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: blob },
- );
- if (uploadRes.ok) {
- const { path: p } = await uploadRes.json();
- screenshotPath = p;
- } else {
- console.warn('[impeccable] annotation upload failed:', uploadRes.status);
- }
- } catch (err) {
- console.warn('[impeccable] annotation upload failed:', err);
- }
- }
- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);
- }
-
- // ---------------------------------------------------------------------------
- // Shader overlay — renders the captured screenshot as a WebGL texture and
- // runs an editorial "ink-wash" fragment shader over it during generation.
- // A single rolling band sweeps top-to-bottom, desaturating + tinting magenta
- // and leaving a soft trail. Makes the wait feel like a letterpress scan
- // instead of a dead spinner.
- // ---------------------------------------------------------------------------
-
- const SHADER_VS = `attribute vec2 a_position;
-attribute vec2 a_uv;
-varying vec2 v_uv;
-void main() {
- v_uv = a_uv;
- gl_Position = vec4(a_position, 0.0, 1.0);
-}`;
-
- const SHADER_FS = `precision highp float;
-uniform sampler2D u_texture;
-uniform float u_time;
-uniform vec2 u_resolution;
-uniform vec3 u_accent;
-varying vec2 v_uv;
-
-// Asymmetric roller band. Product of two one-sided smoothsteps — peaks at
-// d=0 with a short sharp leading ramp and a longer soft trailing tail. Clean
-// outside the [-leadW, trailW] range (no rogue "trail=1 everywhere below"
-// failure that reversed-edge smoothstep would give).
-float bandAt(float d, float leadW, float trailW) {
- float above = smoothstep(-leadW, 0.0, d);
- float below = 1.0 - smoothstep(0.0, trailW, d);
- return above * below;
-}
-
-void main() {
- vec2 uv = v_uv;
- // Roller sweeps top-to-bottom with small overshoot so each cycle enters
- // and exits the element cleanly.
- float phase = fract(u_time / 3.4);
- float y = phase * 1.25 - 0.12;
- float band = bandAt(uv.y - y, 0.05, 0.32);
-
- // Halftone cell grid (fixed ~10 px pitch).
- float cellPx = 10.0;
- vec2 gridUv = uv * u_resolution / cellPx;
- vec2 cellId = floor(gridUv);
- vec2 cellUv = fract(gridUv) - 0.5;
- vec2 sampleCenter = (cellId + 0.5) * cellPx / u_resolution;
- vec3 cellImg = texture2D(u_texture, sampleCenter).rgb;
- float luma = dot(cellImg, vec3(0.299, 0.587, 0.114));
- // Darker cells → bigger magenta dots (classic risograph halftone curve).
- float radius = sqrt(clamp(1.0 - luma, 0.0, 1.0)) * 0.56;
- float dotMask = smoothstep(radius + 0.06, radius, length(cellUv));
- vec3 paper = vec3(0.975, 0.965, 0.955);
- vec3 dotLayer = mix(paper, u_accent, dotMask);
-
- // Blend the halftone layer in where the roller is passing; leave the
- // element pristine elsewhere.
- vec3 base = texture2D(u_texture, uv).rgb;
- gl_FragColor = vec4(mix(base, dotLayer, band), 1.0);
-}`;
-
- // Editorial Magenta converted to approximate sRGB 0-1 (matches oklch(60% 0.25 350))
- const SHADER_ACCENT = [0.82, 0.16, 0.47];
- let shaderState = null; // { canvas, gl, program, texture, rafId, startTime }
-
- function compileShader(gl, type, source) {
- const sh = gl.createShader(type);
- gl.shaderSource(sh, source);
- gl.compileShader(sh);
- if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
- const info = gl.getShaderInfoLog(sh);
- gl.deleteShader(sh);
- throw new Error('shader compile failed: ' + info);
- }
- return sh;
- }
-
- function positionShaderOverlay() {
- if (!shaderState || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- Object.assign(shaderState.canvas.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- }
-
- function hideShaderOverlay() {
- if (!shaderState) return;
- if (shaderState.rafId) cancelAnimationFrame(shaderState.rafId);
- if (shaderState.canvas) shaderState.canvas.remove();
- const lose = shaderState.gl?.getExtension?.('WEBGL_lose_context');
- try { lose?.loseContext(); } catch {}
- shaderState = null;
- }
-
- async function showShaderOverlay(el, blob, rect) {
- hideShaderOverlay();
- if (!blob || !el) return;
- const canvas = document.createElement('canvas');
- canvas.id = PREFIX + '-shader';
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
- canvas.width = Math.max(1, Math.floor(rect.width * dpr));
- canvas.height = Math.max(1, Math.floor(rect.height * dpr));
- Object.assign(canvas.style, {
- position: 'fixed',
- top: rect.top + 'px', left: rect.left + 'px',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none',
- zIndex: Z.bar - 1,
- });
- document.body.appendChild(canvas);
-
- const gl = canvas.getContext('webgl', { premultipliedAlpha: false, preserveDrawingBuffer: false })
- || canvas.getContext('experimental-webgl');
- if (!gl) {
- // WebGL unavailable — fall back to a plain <img> overlay so the user
- // still sees something meaningful during generation.
- canvas.remove();
- const img = document.createElement('img');
- img.src = URL.createObjectURL(blob);
- img.id = PREFIX + '-shader';
- // Copy positioning via cssText. Object.assign across CSSStyleDeclaration
- // throws in modern Chromium because the source's indexed properties
- // (style[0], [1], ...) are read-only and the engine forbids writing
- // them on the destination.
- img.style.cssText = canvas.style.cssText;
- img.style.outline = '2px dashed ' + C.brand;
- img.style.outlineOffset = '-2px';
- document.body.appendChild(img);
- shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
- return;
- }
-
- let program, texture;
- try {
- const vs = compileShader(gl, gl.VERTEX_SHADER, SHADER_VS);
- const fs = compileShader(gl, gl.FRAGMENT_SHADER, SHADER_FS);
- program = gl.createProgram();
- gl.attachShader(program, vs);
- gl.attachShader(program, fs);
- gl.linkProgram(program);
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- throw new Error('program link failed: ' + gl.getProgramInfoLog(program));
- }
- // Full-screen quad
- const buf = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
- -1, -1, 0, 1,
- 1, -1, 1, 1,
- -1, 1, 0, 0,
- -1, 1, 0, 0,
- 1, -1, 1, 1,
- 1, 1, 1, 0,
- ]), gl.STATIC_DRAW);
- const posLoc = gl.getAttribLocation(program, 'a_position');
- const uvLoc = gl.getAttribLocation(program, 'a_uv');
- gl.enableVertexAttribArray(posLoc);
- gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 16, 0);
- gl.enableVertexAttribArray(uvLoc);
- gl.vertexAttribPointer(uvLoc, 2, gl.FLOAT, false, 16, 8);
- } catch (err) {
- console.warn('[impeccable] shader setup failed:', err);
- canvas.remove();
- return;
- }
-
- // Upload the screenshot as a texture
- let bitmap;
- try {
- bitmap = await createImageBitmap(blob);
- } catch {
- // Safari fallback: go via a regular Image
- const imgUrl = URL.createObjectURL(blob);
- const img = new Image();
- img.src = imgUrl;
- await new Promise((r, rej) => { img.onload = r; img.onerror = rej; });
- bitmap = img;
- URL.revokeObjectURL(imgUrl);
- }
- texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
- if (bitmap.close) bitmap.close();
-
- const uTime = gl.getUniformLocation(program, 'u_time');
- const uRes = gl.getUniformLocation(program, 'u_resolution');
- const uAccent = gl.getUniformLocation(program, 'u_accent');
- const uTex = gl.getUniformLocation(program, 'u_texture');
- const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-
- shaderState = { canvas, gl, program, texture, rafId: 0, startTime: performance.now(), reduced };
- function frame() {
- if (!shaderState) return;
- const elapsed = (performance.now() - shaderState.startTime) / 1000;
- const t = shaderState.reduced ? 0.0 : elapsed;
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.useProgram(program);
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.uniform1i(uTex, 0);
- gl.uniform1f(uTime, t);
- gl.uniform2f(uRes, canvas.width, canvas.height);
- gl.uniform3f(uAccent, SHADER_ACCENT[0], SHADER_ACCENT[1], SHADER_ACCENT[2]);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- shaderState.rafId = requestAnimationFrame(frame);
- }
- frame();
- }
-
- function handleAccept() {
- if (!currentSessionId || arrivedVariants === 0) return;
- const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);
- if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;
- const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };
- if (Object.keys(paramsCurrentValues).length > 0) {
- acceptPayload.paramValues = { ...paramsCurrentValues };
- }
- // The accepted variant is already the only visible child of the wrapper
- // (all other variants are display:none). HMR from the source rewrite will
- // replace the wrapper imminently. Don't eagerly replaceChild here — React
- // reconciliation races with our mutation and throws NotFoundError in Next
- // 16 / Turbopack. Schedule a fallback that runs the manual swap only if
- // HMR hasn't cleaned up by then (keeps static-server flows working).
- const acceptedSessionId = currentSessionId;
- const acceptedVariant = visibleVariant;
-
- state = 'SAVING';
- updateBarContent('saving');
-
- sendEvent(acceptPayload, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- confirmAcceptAfterReceipt();
- })
- .catch(() => {
- state = 'CYCLING';
- updateBarContent('cycling');
- showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);
- });
-
- function confirmAcceptAfterReceipt() {
- state = 'CONFIRMED';
- updateBarContent('confirmed');
- scheduleAcceptCleanup();
- }
-
- function scheduleAcceptCleanup() {
- setTimeout(function() {
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }, 1800);
-
- // Static-server / no-HMR fallback: if the wrapper is still around 2s after
- // the cleanup above, swap it out manually. By now React has either moved
- // on or the app isn't React at all. Preserve the `data-impeccable-variant="N"`
- // div (with display:contents) so @scope rules anchored to the variant
- // attribute keep matching until reload replaces it with the carbonize block.
- setTimeout(function() {
- const wrapper = document.querySelector('[data-impeccable-variants="' + acceptedSessionId + '"]');
- if (!wrapper) return;
- const accepted = wrapper.querySelector('[data-impeccable-variant="' + acceptedVariant + '"]');
- if (accepted && accepted.firstElementChild) {
- const parent = wrapper.parentElement;
- if (!parent) return;
- accepted.style.display = 'contents';
- parent.replaceChild(accepted, wrapper);
- }
- }, 2000);
- }
- }
-
- function handleDiscard() {
- if (!currentSessionId) return;
- sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- cleanup();
- })
- .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));
- }
-
- // ---------------------------------------------------------------------------
- // Session persistence via live-browser-session.js
- // ---------------------------------------------------------------------------
- // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
-
- function saveSession() {
- if (!currentSessionId) return;
- // NOTE: scrollY is stored under a separate key (writeScrollY). Storing
- // it here would overwrite the Go-time value every time state changes.
- sessionState.saveSession({
- id: currentSessionId,
- state,
- action: selectedAction,
- count: selectedCount,
- expected: expectedVariants,
- arrived: arrivedVariants,
- visible: visibleVariant,
- });
- }
-
- function loadSession() {
- return sessionState.loadSession();
- }
-
- function clearSession() {
- sessionState.clearSession();
- }
-
- /** Mark session as handled (accepted/discarded). The agent will clean up
- * the source, but until it does the wrapper is still in the HTML. This
- * prevents resumeSession from picking it up again after reload. */
- function markSessionHandled() {
- if (!currentSessionId) return;
- sessionState.markHandled(currentSessionId);
- }
-
- function isSessionHandled(id) {
- return sessionState.isHandled(id);
- }
-
- function clearHandled() {
- sessionState.clearHandled();
- }
-
- function cleanup() {
- // Hide the wrapper immediately so variants disappear. DON'T structurally
- // mutate the DOM yet — HMR from the agent's source rewrite is on its way,
- // and a manual replaceChild under React causes NotFoundError when the
- // reconciler later tries to remove a wrapper we already removed.
- // Schedule a 2s fallback that does the manual swap only if HMR hasn't
- // replaced the wrapper by then (keeps static-server / no-HMR flows alive).
- const cleanupSessionId = currentSessionId;
- if (cleanupSessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (wrapper) wrapper.style.display = 'none';
- }
- setTimeout(function() {
- if (!cleanupSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (!wrapper) return;
- const orig = wrapper.querySelector('[data-impeccable-variant="original"]');
- if (orig) {
- const content = orig.firstElementChild;
- if (content) {
- wrapper.parentElement.replaceChild(content, wrapper);
- return;
- }
- }
- wrapper.remove();
- }, 2000);
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }
-
- // ---------------------------------------------------------------------------
- // Toast
- // ---------------------------------------------------------------------------
-
- function showToast(message, duration) {
- if (toastEl) toastEl.remove();
- // Stack the toast above the global bar (which sits at bottom:14px) so
- // the two never overlap. Read the bar's actual rect — its height varies
- // with hover-expanded labels — and fall back to a sensible default
- // when the bar isn't mounted yet.
- const barRect = globalBarEl?.getBoundingClientRect();
- const barTopFromBottom = barRect && barRect.height > 0
- ? Math.max(16, window.innerHeight - barRect.top + 12)
- : 16;
- toastEl = el('div', {
- position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
- transform: 'translateX(-50%) translateY(8px)',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px',
- padding: '8px 16px', borderRadius: '8px',
- zIndex: Z.toast, opacity: '0',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
- pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
- });
- toastEl.id = PREFIX + '-toast';
- toastEl.textContent = message;
- document.body.appendChild(toastEl);
- requestAnimationFrame(() => {
- toastEl.style.opacity = '1';
- toastEl.style.transform = 'translateX(-50%) translateY(0)';
- });
- setTimeout(() => {
- if (toastEl) {
- toastEl.style.opacity = '0';
- toastEl.style.transform = 'translateX(-50%) translateY(8px)';
- setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
- }
- }, duration);
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- // Resume an active variant session after HMR/page reload.
- // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
- // variants before HMR fired. Pick up where we left off.
- function resumeSession() {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) { clearSession(); clearHandled(); return false; }
-
- const sessionId = wrapper.dataset.impeccableVariants;
-
- // Don't resume if this session was already accepted/discarded
- if (isSessionHandled(sessionId)) return false;
-
- currentSessionId = sessionId;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
-
- // Restore state from localStorage if available
- const saved = loadSession();
- if (saved && saved.id === sessionId) {
- visibleVariant = (saved.visible > 0 && saved.visible <= arrivedVariants) ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
- if (saved.action) selectedAction = saved.action;
- if (saved.count) selectedCount = saved.count;
- } else {
- visibleVariant = arrivedVariants > 0 ? 1 : 0;
- }
-
- // Find the visible variant's content element for highlight positioning.
- // Try the visible variant first, fall back to the original's content.
- const visEl = visibleVariant > 0 ? pickVariantContent(wrapper, visibleVariant) : null;
- const origEl = pickVariantContent(wrapper, 'original');
- selectedElement = visEl || origEl || wrapper.parentElement;
-
- // Set display state BEFORE starting observer (avoid triggering it)
- if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
-
- state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
- showBar(state === 'CYCLING' ? 'cycling' : 'generating');
- startScrollTracking();
- // Build the params panel for the restored visible variant. Previously
- // this was missed on page-reload resume: showVariantInDOM above fires
- // refreshParamsPanel, but state was still IDLE at that moment so it
- // hid. Now that state is CYCLING, re-fire.
- if (state === 'CYCLING') refreshParamsPanel();
- saveSession();
- queueCheckpoint('browser_resumed');
-
- // Start observing for more variants AFTER initial setup
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
-
- // Hold the target at its saved viewport top through any subsequent
- // HMR patches, variant inserts, or cycle swaps.
- startScrollLock(currentSessionId, readScrollY());
-
- // If we reloaded mid-generation (Bun's HTML HMR destroys the shader
- // canvas), re-capture the original's content and restart the shader so
- // the wait doesn't go dead.
- if (state === 'GENERATING' && origEl) {
- (async () => {
- try {
- const rect = origEl.getBoundingClientRect();
- if (rect.width === 0 || rect.height === 0) return;
- const blob = await captureElementToBlob(origEl, null, rect);
- if (blob && state === 'GENERATING') {
- showShaderOverlay(origEl, blob, rect);
- }
- } catch (err) {
- console.warn('[impeccable] shader resume failed:', err);
- }
- })();
- }
- return true;
- }
-
- // ---------------------------------------------------------------------------
- // Global bar (always visible at bottom)
- // ---------------------------------------------------------------------------
-
- let globalBarEl = null;
- let detectActive = false;
- let pickActive = true;
- let detectCount = 0;
- let detectScriptLoaded = false;
-
- // Theme-aware color palette for the global bar. We detect the page's
- // ambient background and invert — dark bar on light pages, light bar on
- // dark pages. This keeps the bar from fighting with the host design.
- function detectPageTheme() {
- try {
- // Dev override: set localStorage 'impeccable-dev-theme' to 'light' or
- // 'dark' to preview the opposite palette without actually changing the
- // page bg. Used for screenshots and theme QA.
- const override = localStorage.getItem('impeccable-dev-theme');
- if (override === 'light' || override === 'dark') return override;
-
- // Walk body → html, taking the first opaque background. The browser's
- // default body / html background is `rgba(0, 0, 0, 0)`, which a naive
- // regex would read as black and mislabel a perfectly white page as
- // dark. Honoring alpha avoids that — and falling through to <html>
- // catches the common pattern of a bg only on <html> (or only on body).
- function readOpaque(el) {
- if (!el) return null;
- const bg = getComputedStyle(el).backgroundColor;
- const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
- if (!m) return null;
- const alpha = m[4] == null ? 1 : parseFloat(m[4]);
- if (alpha < 0.5) return null; // transparent / nearly transparent → skip
- return [+m[1], +m[2], +m[3]];
- }
-
- const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
- // Both transparent → fall back to the browser's effective canvas color.
- // White is the universal default; only one in a thousand sites swaps it
- // via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
- // us catch that case.
- if (!rgb) {
- return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
- }
- const [r, g, b] = rgb;
- // Perceptual luminance (Rec. 709)
- const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
- return L > 0.55 ? 'light' : 'dark';
- } catch { return 'light'; }
- }
-
- function barPaletteForTheme(theme) {
- if (theme === 'dark') {
- // Light bar on dark page
- return {
- surface: 'oklch(98% 0 0 / 0.92)',
- surfaceDeep: 'oklch(92% 0.005 60 / 0.96)', // slightly deeper, faint warm
- hairline: 'oklch(70% 0 0 / 0.35)',
- text: 'oklch(15% 0 0)',
- textDim: 'oklch(45% 0 0)',
- accent: 'oklch(60% 0.25 350)',
- accentSoft: 'oklch(60% 0.25 350 / 0.18)',
- mark: 'oklch(98% 0 0)', // logo mark fill
- markText: 'oklch(15% 0 0)', // logo "/" color
- exitHover: 'oklch(85% 0 0 / 0.5)',
- };
- }
- // Dark bar on light page. Bar is a warm charcoal, logo slab is much
- // deeper so the rounded-right shape reads as a clear sculpted mark.
- return {
- surface: 'oklch(26% 0 0 / 0.94)',
- surfaceDeep: 'oklch(18% 0 0 / 0.96)', // darker sand for Tune popover
- hairline: 'oklch(42% 0 0 / 0.5)',
- text: 'oklch(96% 0 0)',
- textDim: 'oklch(72% 0 0)',
- accent: 'oklch(72% 0.22 350)',
- accentSoft: 'oklch(72% 0.22 350 / 0.22)',
- mark: 'oklch(8% 0 0)',
- markText: 'oklch(96% 0 0)',
- exitHover: 'oklch(36% 0 0 / 0.6)',
- };
- }
-
- // Impeccable logo mark — matches the site-header SVG (rounded square + "/").
- function brandMarkSvg(fill, ink, size = 18) {
- return `<svg width="${size}" height="${size}" viewBox="0 0 32 32" aria-hidden="true">
- <rect width="32" height="32" rx="7" fill="${fill}"/>
- <text x="16" y="24" font-family="system-ui, -apple-system, sans-serif" font-size="22" font-weight="500" fill="${ink}" text-anchor="middle">/</text>
- </svg>`;
- }
-
- function initGlobalBar() {
- const theme = detectPageTheme();
- const P = barPaletteForTheme(theme);
-
- // Custom focus-visible for bar buttons. Browser default is a heavy
- // blue ring that looks jarring on the dark capsule. Replace with a
- // soft accent-tinted inner ring that respects the bar's palette.
- if (!document.getElementById(PREFIX + '-bar-focus-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-bar-focus-style';
- s.textContent =
- '#' + PREFIX + '-global-bar button:focus { outline: none; }' +
- '#' + PREFIX + '-global-bar button:focus-visible {' +
- ' outline: none;' +
- ' box-shadow: 0 0 0 2px ' + P.accentSoft + ', 0 0 0 3px ' + P.accent + ';' +
- '}';
- document.head.appendChild(s);
- }
-
- globalBarEl = el('div', {
- position: 'fixed', bottom: '14px', left: '50%',
- transform: 'translateX(-50%) translateY(20px)',
- zIndex: Z.bar + 5,
- display: 'flex', alignItems: 'stretch',
- gap: '2px',
- background: P.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 4px 20px oklch(0% 0 0 / 0.12), 0 1px 3px oklch(0% 0 0 / 0.08)',
- fontFamily: FONT, fontSize: '12px', lineHeight: '1',
- opacity: '0',
- overflow: 'hidden', // clip the full-bleed brand mark to the bar radius
- transition: 'opacity 0.3s ' + EASE + ', transform 0.3s ' + EASE,
- });
- globalBarEl.id = PREFIX + '-global-bar';
- globalBarEl.dataset.theme = theme;
-
- // Brand mark — fills bar height on the left. Left side inherits the bar's
- // rounded corner via overflow:hidden; right side is a clean hard edge since
- // the near-black/charcoal contrast does the shape-defining work.
- const brand = el('span', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- alignSelf: 'stretch',
- padding: '0 12px 0 14px',
- background: P.mark,
- color: P.markText,
- fontFamily: 'system-ui, -apple-system, sans-serif',
- fontWeight: '500',
- fontSize: '18px', lineHeight: '1',
- });
- brand.textContent = '/';
- brand.title = 'Impeccable';
- globalBarEl.appendChild(brand);
-
- // Inner wrapper: holds the toggles with normal bar padding.
- const inner = el('div', {
- display: 'flex', alignItems: 'center',
- padding: '4px 5px', gap: '2px',
- });
- inner.id = PREFIX + '-global-bar-inner';
- globalBarEl.appendChild(inner);
-
- // --- button factory: icon-only at rest, label slides in on hover/active ---
- function makeIconBtn({ id, svg, label, ariaLabel, labelFont, onClick }) {
- const b = el('button', {
- position: 'relative',
- display: 'inline-flex', alignItems: 'center',
- padding: '6px 8px', borderRadius: '7px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '11.5px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.15s ease, color 0.15s ease',
- whiteSpace: 'nowrap', overflow: 'hidden',
- });
- b.id = id;
- b.title = ariaLabel || label || '';
- b.setAttribute('aria-label', ariaLabel || label || '');
- b.innerHTML = svg + (label
- ? `<span class="icon-btn-label" style="display:inline-block;max-width:0;opacity:0;margin-left:0;overflow:hidden;font-family:${labelFont || FONT};transition:max-width 0.25s ${EASE}, opacity 0.2s ease, margin-left 0.25s ${EASE};">${label}</span>`
- : '');
- const labelEl = b.querySelector('.icon-btn-label');
- const expand = () => {
- if (!labelEl) return;
- labelEl.style.maxWidth = '120px'; labelEl.style.opacity = '1'; labelEl.style.marginLeft = '6px';
- };
- const collapse = () => {
- if (!labelEl || b.dataset.active === 'true') return;
- labelEl.style.maxWidth = '0'; labelEl.style.opacity = '0'; labelEl.style.marginLeft = '0';
- };
- // Per-button hover only changes color (no layout). The label expand/
- // collapse is driven by the bar-level mouseenter/mouseleave so moving
- // the mouse between adjacent buttons doesn't trigger per-button width
- // thrashing — the whole bar grows once and shrinks once.
- b.addEventListener('mouseenter', () => { if (b.dataset.active !== 'true') b.style.color = P.text; });
- b.addEventListener('mouseleave', () => { if (b.dataset.active !== 'true') b.style.color = P.textDim; });
- b.addEventListener('click', onClick);
- b._expandLabel = expand;
- b._collapseLabel = collapse;
- return b;
- }
-
- // Pick toggle — starts active (primary intent when entering live mode).
- const pickBtn = makeIconBtn({
- id: PREFIX + '-pick-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',
- label: 'Pick',
- ariaLabel: 'Pick element',
- onClick: () => togglePick(),
- });
- pickBtn.style.background = P.accentSoft;
- pickBtn.style.color = P.accent;
- pickBtn.dataset.active = 'true';
- pickBtn._expandLabel();
- inner.appendChild(pickBtn);
-
- // Detect toggle
- const detectBtn = makeIconBtn({
- id: PREFIX + '-detect-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',
- label: 'Detect',
- ariaLabel: 'Detect anti-patterns',
- onClick: () => toggleDetect(),
- });
- const detectBadge = el('span', {
- fontSize: '10px', fontWeight: '600',
- padding: '0px 5px', borderRadius: '7px', lineHeight: '16px',
- background: P.accent, color: P.surface.includes('18%') ? 'oklch(18% 0 0)' : 'oklch(98% 0 0)',
- display: 'none', fontFamily: MONO, marginLeft: '4px',
- });
- detectBadge.id = PREFIX + '-detect-badge';
- detectBtn.appendChild(detectBadge);
- inner.appendChild(detectBtn);
-
- // DESIGN.md panel toggle — quartet of color squares as the mark.
- const designBtn = makeIconBtn({
- id: PREFIX + '-design-toggle',
- svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px ${P.hairline};flex-shrink:0">
- <span style="background:oklch(60% 0.25 350)"></span>
- <span style="background:oklch(60% 0.15 45)"></span>
- <span style="background:oklch(55% 0.12 250)"></span>
- <span style="background:oklch(30% 0 0)"></span>
- </span>`,
- label: 'DESIGN.md',
- ariaLabel: 'Toggle DESIGN.md panel',
- labelFont: MONO,
- onClick: () => toggleDesignPanel(),
- });
- inner.appendChild(designBtn);
-
- // Thin divider before the exit button
- const divider = el('span', {
- width: '1px', height: '18px',
- background: P.hairline,
- margin: '0 4px 0 2px',
- });
- inner.appendChild(divider);
-
- // Exit × on the right — intentionally subtle (textDim at rest, text on
- // hover) so it sits behind the active toggles in visual hierarchy.
- //
- // Explicit padding + box-sizing here is load-bearing: a host page like
- // `button { padding: 0.5rem 1rem; }` (very common in resets) would
- // otherwise inflate this 24x24 button into 56x40 and push the SVG out
- // of the visible bar — the X stays invisible even though the styles in
- // DevTools look fine. Every other chrome button sets padding inline;
- // this one needed it too.
- const exitBtn = el('button', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- padding: '0', boxSizing: 'border-box',
- width: '24px', height: '24px', borderRadius: '6px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
- cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
- });
- exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
- exitBtn.title = 'Exit live mode';
- exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
- exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
- exitBtn.addEventListener('click', () => { sendEvent({ type: 'exit' }); teardown(); });
- inner.appendChild(exitBtn);
-
- // Bar-level hover: expand every toggle's label at once; collapse on leave.
- // Buttons with dataset.active="true" ignore collapse (their label stays).
- const toggles = [pickBtn, detectBtn, designBtn];
- globalBarEl.addEventListener('mouseenter', () => {
- toggles.forEach((t) => t._expandLabel && t._expandLabel());
- });
- globalBarEl.addEventListener('mouseleave', () => {
- toggles.forEach((t) => t._collapseLabel && t._collapseLabel());
- });
-
- document.body.appendChild(globalBarEl);
- defangOutsideHandlers(globalBarEl);
-
- requestAnimationFrame(() => {
- globalBarEl.style.opacity = '1';
- globalBarEl.style.transform = 'translateX(-50%) translateY(0)';
- });
-
- // Listen for detection results AND ready signal
- window.addEventListener('message', onDetectMessage);
- }
-
- function updateGlobalBarState() {
- const detectToggle = document.getElementById(PREFIX + '-detect-toggle');
- const detectBadge = document.getElementById(PREFIX + '-detect-badge');
- const pickToggle = document.getElementById(PREFIX + '-pick-toggle');
- const designToggle = document.getElementById(PREFIX + '-design-toggle');
- const theme = globalBarEl?.dataset.theme || 'light';
- const P = barPaletteForTheme(theme);
-
- // Sync one toggle's active state, colors, and slide-label visibility.
- function sync(btn, active) {
- if (!btn) return;
- btn.style.background = active ? P.accentSoft : 'transparent';
- btn.style.color = active ? P.accent : P.textDim;
- btn.dataset.active = active ? 'true' : 'false';
- if (active && btn._expandLabel) btn._expandLabel();
- else if (!active && btn._collapseLabel) btn._collapseLabel();
- }
- sync(pickToggle, pickActive);
- sync(detectToggle, detectActive);
- sync(designToggle, designState.open);
-
- // If the bar is currently under the cursor, keep all labels expanded —
- // otherwise clicking a toggle that deactivates (e.g. closing DESIGN.md)
- // would collapse its label while the user's mouse is still on the bar.
- if (globalBarEl && globalBarEl.matches(':hover')) {
- [pickToggle, detectToggle, designToggle].forEach((t) => t?._expandLabel?.());
- }
-
- if (detectBadge) {
- detectBadge.style.display = (detectActive && detectCount > 0) ? 'inline' : 'none';
- detectBadge.textContent = detectCount;
- }
-
- // When pick is active, make detect overlays click-through so the picker works
- document.querySelectorAll('.impeccable-overlay').forEach(o => {
- o.style.pointerEvents = pickActive ? 'none' : '';
- });
- }
-
- let detectReady = false; // true once detect script posts 'impeccable-ready'
- let detectPendingScan = false; // scan requested before script was ready
-
- function toggleDetect() {
- detectActive = !detectActive;
- updateGlobalBarState();
-
- if (detectActive) {
- if (!detectScriptLoaded) {
- detectPendingScan = true;
- loadDetectScript();
- } else if (detectReady) {
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- } else {
- detectPendingScan = true;
- }
- } else {
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- detectCount = 0;
- updateGlobalBarState();
- }
- }
-
- function togglePick() {
- pickActive = !pickActive;
- updateGlobalBarState();
-
- if (!pickActive) {
- // Disabling pick clears any in-flight selection and UI: highlight,
- // contextual bar, selectedElement. Otherwise a stale selection sits
- // on screen with no obvious way to dismiss.
- hideHighlight();
- hideBar();
- hideActionPicker();
- selectedElement = null;
- if (state === 'PICKING' || state === 'CONFIGURING') state = 'IDLE';
- } else {
- if (state === 'IDLE') state = 'PICKING';
- }
- }
-
- function loadDetectScript() {
- if (detectScriptLoaded) return;
- detectScriptLoaded = true;
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/detect.js';
- s.dataset.impeccableExtension = 'true';
- document.head.appendChild(s);
- }
-
- function onDetectMessage(e) {
- if (!e.data || typeof e.data.source !== 'string') return;
- // Detection script is loaded and ready
- if (e.data.source === 'impeccable-ready') {
- detectReady = true;
- if (detectPendingScan && detectActive) {
- detectPendingScan = false;
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- }
- }
- // Scan results arrived
- if (e.data.source === 'impeccable-results') {
- detectCount = e.data.count || 0;
- updateGlobalBarState();
- }
- }
-
- /** Full teardown: remove all UI, disconnect SSE, clean up. */
- function teardown() {
- cleanup();
- hideBar();
- if (globalBarEl) {
- globalBarEl.style.transform = 'translateY(100%)';
- setTimeout(() => { if (globalBarEl) globalBarEl.remove(); globalBarEl = null; }, 300);
- }
- if (highlightEl) { highlightEl.remove(); highlightEl = null; }
- if (tooltipEl) { tooltipEl.remove(); tooltipEl = null; }
- if (barEl) { barEl.remove(); barEl = null; }
- if (pickerEl) { pickerEl.remove(); pickerEl = null; }
- if (paramsPanelEl) { paramsPanelEl.remove(); paramsPanelEl = null; paramsPanelInner = null; paramsPanelBody = null; }
- if (evtSource) { evtSource.close(); evtSource = null; }
- document.removeEventListener('mousemove', handleMouseMove, true);
- document.removeEventListener('click', handleClick, true);
- document.removeEventListener('keydown', handleKeyDown, true);
- window.removeEventListener('message', onDetectMessage);
- // Remove detection overlays
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- state = 'IDLE';
- window.__IMPECCABLE_LIVE_INIT__ = false;
- console.log('[impeccable] Live mode exited.');
- }
-
- // ---------------------------------------------------------------------------
- // Design System Panel — visualizes the project's .impeccable/design.json sidecar
- // ---------------------------------------------------------------------------
-
- const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';
- const DESIGN_PANEL_WIDTH = 440;
-
- let designHost = null;
- let designShadow = null;
- let designState = {
- open: false,
- tab: 'visual', // 'visual' | 'raw'
- parsed: null, // parseDesignMd output (frontmatter + body sections)
- sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)
- hasMd: false,
- hasSidecar: false,
- present: null, // true/false once fetch resolves
- raw: null, // raw DESIGN.md for the raw tab
- mdNewerThanJson: false, // stale-hint flag
- loading: false,
- error: null,
- collapsed: { // narrative-section accordion state
- rules: true, dosdonts: true, overview: true,
- },
- };
-
- function loadDesignPrefs() {
- // `open` is intentionally NOT persisted — the panel always starts closed
- // so live mode doesn't auto-slide a big panel over the page on startup.
- try {
- const raw = localStorage.getItem(DESIGN_PREFS_KEY);
- if (!raw) return;
- const prefs = JSON.parse(raw);
- if (prefs.tab === 'visual' || prefs.tab === 'raw') designState.tab = prefs.tab;
- if (prefs.collapsed && typeof prefs.collapsed === 'object') {
- Object.assign(designState.collapsed, prefs.collapsed);
- }
- } catch { /* ignore */ }
- }
-
- function saveDesignPrefs() {
- try {
- localStorage.setItem(DESIGN_PREFS_KEY, JSON.stringify({
- tab: designState.tab,
- collapsed: designState.collapsed,
- }));
- } catch { /* ignore */ }
- }
-
- function initDesignPanel() {
- designHost = document.createElement('div');
- designHost.id = PREFIX + '-design-host';
- Object.assign(designHost.style, {
- position: 'fixed', top: '0', left: '0',
- width: '0', height: '0',
- zIndex: String(Z.bar + 10),
- pointerEvents: 'none',
- });
- designShadow = designHost.attachShadow({ mode: 'open' });
-
- const style = document.createElement('style');
- // Theme-match the bar: dark chrome on light pages, light chrome on dark pages.
- const theme = detectPageTheme();
- style.textContent = designPanelCss(barPaletteForTheme(theme));
- designShadow.appendChild(style);
-
- const root = document.createElement('div');
- root.className = 'root';
- designShadow.appendChild(root);
-
- document.body.appendChild(designHost);
- // The host is pointer-events: none; the panel inside the shadow DOM
- // manages its own auto/none. Events bubble through the shadow boundary,
- // so attaching here silences host-page outside-interaction handlers
- // without touching the host's click-through behavior.
- defangOutsideHandlers(designHost, { setPointerEvents: false });
-
- loadDesignPrefs();
- renderDesignChrome();
- if (designState.open) {
- fetchDesignSystem();
- }
- }
-
- // Neutral panel palette — deliberately NOT Impeccable-branded. The panel is
- // a viewer of the project's design system, not an Impeccable surface.
- const DP = {
- canvas: 'oklch(94% 0 0)', // panel background
- tile: 'oklch(98.5% 0 0)', // card-on-canvas
- tileAlt: 'oklch(96% 0 0)', // subtler tile for inner surfaces
- ink: 'oklch(15% 0 0)',
- ink2: 'oklch(35% 0 0)',
- meta: 'oklch(55% 0 0)',
- hairline: 'oklch(88% 0 0)',
- hairlineSoft: 'oklch(92% 0 0)',
- amber: 'oklch(70% 0.13 65)', // stale-hint accent
- amberBg: 'oklch(95% 0.05 80)',
- };
-
- function designPanelCss(BP) {
- // BP = bar palette (theme-aware, matches the global bar).
- // DP = internal content palette (neutral, so tiles render colors true).
- return `
- :host, .root { all: initial; }
- .root {
- font-family: ${FONT};
- color: ${DP.ink};
- pointer-events: none;
- }
- .root * { box-sizing: border-box; }
- button { font: inherit; color: inherit; }
-
- /* --- Panel shell: chrome matches the bar; body canvas stays neutral --- */
- .panel {
- position: fixed; top: 12px; bottom: 72px; right: 12px;
- width: ${DESIGN_PANEL_WIDTH}px; max-width: calc(100vw - 24px);
- background: ${BP.surface};
- border: 1px solid ${BP.hairline};
- border-radius: 14px;
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- box-shadow: 0 20px 60px oklch(0% 0 0 / 0.18), 0 4px 12px oklch(0% 0 0 / 0.08);
- display: flex; flex-direction: column;
- transform: translateX(calc(100% + 24px));
- opacity: 0;
- transition: transform 0.35s ${EASE}, opacity 0.25s ${EASE};
- pointer-events: none;
- overflow: hidden;
- }
- .panel[data-open="true"] { transform: translateX(0); opacity: 1; pointer-events: auto; }
-
- .panel-header {
- display: flex; align-items: center; gap: 10px;
- padding: 10px 10px 10px 14px;
- background: transparent;
- border-bottom: 1px solid ${BP.hairline};
- }
- .panel-title {
- flex: 1; min-width: 0;
- font-family: ${MONO};
- font-size: 11.5px; font-weight: 600;
- letter-spacing: 0.02em;
- color: ${BP.text};
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
- }
- .panel-close {
- border: none; background: transparent; color: ${BP.textDim};
- width: 26px; height: 26px; border-radius: 7px;
- display: inline-flex; align-items: center; justify-content: center;
- cursor: pointer; transition: background 0.15s ease, color 0.15s ease;
- }
- .panel-close:hover { background: ${BP.hairline}; color: ${BP.text}; }
-
- .tabs {
- display: inline-flex; padding: 2px;
- background: ${BP.hairline};
- border-radius: 7px;
- gap: 2px;
- }
- .tab {
- border: none; background: transparent;
- padding: 4px 10px; border-radius: 5px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 600; letter-spacing: 0.08em;
- text-transform: uppercase;
- color: ${BP.textDim}; cursor: pointer;
- transition: background 0.15s ease, color 0.15s ease;
- }
- .tab[data-active="true"] { background: ${BP.surface}; color: ${BP.text}; }
-
- .panel-body {
- flex: 1; overflow-y: auto;
- padding: 12px 12px 20px;
- background: ${DP.canvas};
- scrollbar-width: thin;
- scrollbar-color: ${DP.hairline} transparent;
- }
- .panel-body::-webkit-scrollbar { width: 8px; }
- .panel-body::-webkit-scrollbar-thumb { background: ${DP.hairline}; border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
-
- /* --- States --- */
- .empty, .loading, .error {
- margin: 16px 4px;
- padding: 28px 20px; text-align: center;
- background: ${DP.tile}; border-radius: 14px;
- color: ${DP.ink2}; font-size: 13px; line-height: 1.55;
- }
- .empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
- .empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
- .error { color: oklch(45% 0.15 25); }
-
- /* --- Stale hint --- */
- .stale {
- display: flex; align-items: center; gap: 8px;
- margin: 8px 4px 12px;
- padding: 8px 12px;
- background: ${DP.amberBg};
- border-radius: 10px;
- font-size: 11.5px; color: ${DP.ink2};
- }
- .stale-dot { width: 8px; height: 8px; border-radius: 50%; background: ${DP.amber}; flex-shrink: 0; }
- .stale-text { flex: 1; min-width: 0; }
- .stale-text strong { color: ${DP.ink}; font-weight: 600; }
-
- /* --- Parsed-md fallback banner --- */
- .parsed-md-cta {
- margin: 8px 4px 14px;
- padding: 14px 16px;
- background: ${DP.tile};
- border: 1px dashed ${DP.hairline};
- border-radius: 12px;
- font-size: 12px; color: ${DP.ink2}; line-height: 1.55;
- }
- .parsed-md-cta strong { color: ${DP.ink}; display: block; margin-bottom: 4px; font-size: 13px; font-weight: 600; }
- .parsed-md-cta code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; font-size: 11.5px; color: ${DP.ink}; }
-
- /* --- Tile primitives --- */
- .tile {
- position: relative;
- background: ${DP.tile};
- border-radius: 16px;
- padding: 16px;
- margin: 0 4px 10px;
- }
- .tile-row { margin: 0 4px 10px; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
- .tile-row .tile { margin: 0; }
- .tile-meta {
- display: flex; align-items: baseline; justify-content: space-between;
- gap: 10px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase;
- color: ${DP.meta};
- }
- .tile-meta .name { color: ${DP.ink}; font-weight: 600; letter-spacing: 0.05em; text-transform: none; font-family: ${FONT}; font-size: 12.5px; }
-
- /* --- Color tile --- */
- .c-tile { cursor: pointer; transition: transform 0.2s ${EASE}; }
- .c-tile:hover { transform: translateY(-1px); }
- .c-hero {
- height: 72px; border-radius: 10px; margin-top: 10px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.05);
- }
- .c-ramp {
- display: flex; gap: 0; height: 14px; border-radius: 4px; overflow: hidden;
- margin-top: 8px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.04);
- }
- .c-ramp > span { flex: 1; }
- .c-desc { margin-top: 8px; font-size: 11.5px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Type tile --- */
- .t-tile { }
- .t-specimen {
- margin: 4px 0 6px;
- color: ${DP.ink};
- line-height: 0.9;
- }
- .t-family { margin-top: 4px; font-size: 12px; font-weight: 600; color: ${DP.ink}; }
- .t-purpose { margin-top: 4px; font-size: 11px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Shadow tile --- */
- .s-tile { }
- .s-surface {
- height: 60px; margin: 8px 2px 10px;
- background: ${DP.tile};
- border-radius: 10px;
- }
- .s-value { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; word-break: break-all; line-height: 1.4; }
- .s-purpose { margin-top: 4px; font-size: 11px; color: ${DP.ink2}; line-height: 1.45; }
-
- /* --- Radii strip --- */
- .r-strip { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
- .r-item { display: flex; flex-direction: column; align-items: center; gap: 4px; flex: 1; min-width: 60px; }
- .r-sample { width: 44px; height: 44px; background: ${DP.canvas}; box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.08); }
- .r-label { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; text-transform: uppercase; }
- .r-val { font-family: ${MONO}; font-size: 10px; color: ${DP.ink}; }
-
- /* --- Component tile (hosts live primitives) --- */
- .cmp-tile { }
- .cmp-stage {
- margin: 12px -4px 0;
- padding: 18px 16px 10px;
- border-top: 1px solid ${DP.hairlineSoft};
- display: flex; flex-direction: column; align-items: center; justify-content: center;
- gap: 14px;
- min-height: 68px;
- }
- .cmp-stage + .cmp-stage { border-top: 1px dashed ${DP.hairlineSoft}; }
- .cmp-sublabel { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.06em; }
- .cmp-kind { font-family: ${MONO}; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; }
-
- /* --- Collapsible --- */
- .coll {
- margin: 0 4px 8px;
- background: ${DP.tile};
- border-radius: 12px;
- overflow: hidden;
- }
- .coll-head {
- display: flex; align-items: center; gap: 10px;
- width: 100%;
- padding: 12px 14px;
- background: transparent; border: none;
- cursor: pointer; text-align: left;
- font-family: ${FONT}; font-size: 12.5px; font-weight: 600; color: ${DP.ink};
- transition: background 0.12s ease;
- }
- .coll-head:hover { background: ${DP.tileAlt}; }
- .coll-chev {
- width: 12px; height: 12px; flex-shrink: 0;
- color: ${DP.meta};
- transition: transform 0.2s ${EASE};
- }
- .coll[data-open="true"] .coll-chev { transform: rotate(90deg); }
- .coll-count { margin-left: auto; font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; }
- .coll-body { padding: 0 14px 14px; display: none; }
- .coll[data-open="true"] .coll-body { display: block; }
-
- .rule-card {
- padding: 10px 0;
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .rule-card:first-child { border-top: none; padding-top: 2px; }
- .rule-card .name { font-size: 11.5px; font-weight: 700; color: ${DP.ink}; margin-bottom: 3px; }
- .rule-card .name .section { font-family: ${MONO}; font-size: 9px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; margin-left: 8px; }
- .rule-card .body { font-size: 11.5px; color: ${DP.ink2}; line-height: 1.5; }
-
- .coll .dos { display: grid; gap: 0; margin-top: 2px; }
- .coll .do, .coll .dont {
- position: relative;
- padding: 8px 0 8px 22px;
- font-size: 11.5px; line-height: 1.5; color: ${DP.ink2};
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .coll .do:first-child, .coll .dont:first-child,
- .coll .do:first-of-type { border-top: none; }
- .coll .do + .dont { border-top: 1px solid ${DP.hairlineSoft}; }
- .coll .do::before, .coll .dont::before {
- content: ''; position: absolute; left: 4px; top: 13px;
- width: 8px; height: 8px; border-radius: 50%;
- }
- .coll .do::before { background: oklch(62% 0.16 145); }
- .coll .dont::before { background: oklch(58% 0.22 25); }
-
- .coll .overview-body {
- font-size: 12px; line-height: 1.55; color: ${DP.ink2};
- }
- .coll .overview-body .north-star {
- display: block; font-family: ${FONT}; font-style: italic;
- font-size: 15px; line-height: 1.3; color: ${DP.ink};
- margin-bottom: 8px;
- }
- .coll .overview-body p { margin: 0 0 8px; }
- .coll .overview-body ul { margin: 6px 0 0; padding-left: 16px; font-size: 11.5px; }
- .coll .overview-body li { margin-bottom: 3px; }
-
- /* --- raw tab markdown (unchanged layout, neutralized palette) --- */
- .md { padding: 4px 10px 20px; font-size: 13px; line-height: 1.6; color: ${DP.ink}; }
- .md h1, .md h2, .md h3, .md h4 { margin: 20px 0 8px; color: ${DP.ink}; font-weight: 600; }
- .md h1 { font-size: 18px; }
- .md h2 { font-size: 15px; padding-bottom: 4px; border-bottom: 1px solid ${DP.hairlineSoft}; }
- .md h3 { font-size: 13px; }
- .md h4 { font-size: 12px; color: ${DP.meta}; }
- .md p { margin: 0 0 10px; }
- .md ul, .md ol { margin: 0 0 10px; padding-left: 20px; }
- .md li { margin-bottom: 4px; }
- .md code { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; }
- .md pre { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 10px 12px; border-radius: 8px; overflow-x: auto; margin: 0 0 10px; }
- .md pre code { background: none; padding: 0; }
- .md strong { font-weight: 700; }
- .md em { font-style: italic; }
- .md a { color: ${DP.ink}; text-decoration: underline; }
- .md hr { border: none; border-top: 1px solid ${DP.hairlineSoft}; margin: 16px 0; }
- `;
- }
-
- function renderDesignChrome() {
- const root = designShadow.querySelector('.root');
- root.innerHTML = '';
-
- // (Panel toggle lives in the global bar — no floating FAB.)
- // Panel
- const panel = document.createElement('aside');
- panel.className = 'panel';
- panel.setAttribute('data-open', designState.open ? 'true' : 'false');
- panel.appendChild(buildDesignHeader());
- const body = document.createElement('div');
- body.className = 'panel-body';
- body.id = 'panel-body';
- panel.appendChild(body);
- root.appendChild(panel);
-
- renderDesignBody();
- }
-
- function buildDesignHeader() {
- const header = document.createElement('div');
- header.className = 'panel-header';
-
- const title = document.createElement('div');
- title.className = 'panel-title';
- title.textContent = 'DESIGN.md';
- header.appendChild(title);
-
- const tabs = document.createElement('div');
- tabs.className = 'tabs';
- for (const t of [['visual', 'Visual'], ['raw', 'Raw']]) {
- const btn = document.createElement('button');
- btn.className = 'tab';
- btn.textContent = t[1];
- btn.setAttribute('data-active', designState.tab === t[0] ? 'true' : 'false');
- btn.addEventListener('click', () => {
- if (designState.tab === t[0]) return;
- designState.tab = t[0];
- saveDesignPrefs();
- renderDesignChrome();
- if (t[0] === 'raw' && designState.raw === null && !designState.loading) {
- fetchDesignSystem(); // raw is part of the same fetch pair
- }
- });
- tabs.appendChild(btn);
- }
- header.appendChild(tabs);
-
- const close = document.createElement('button');
- close.className = 'panel-close';
- close.innerHTML = '✕';
- close.setAttribute('aria-label', 'Close panel');
- close.addEventListener('click', toggleDesignPanel);
- header.appendChild(close);
-
- return header;
- }
-
- function toggleDesignPanel() {
- designState.open = !designState.open;
- renderDesignChrome();
- updateGlobalBarState();
- if (designState.open && designState.present === null && !designState.loading) {
- fetchDesignSystem();
- }
- }
-
- async function fetchDesignSystem() {
- designState.loading = true;
- designState.error = null;
- renderDesignBody();
- try {
- const [jsonRes, rawRes] = await Promise.all([
- fetch(`http://localhost:${PORT}/design-system.json?token=${TOKEN}`, { cache: 'no-store' }),
- fetch(`http://localhost:${PORT}/design-system/raw?token=${TOKEN}`, { cache: 'no-store' }),
- ]);
- const jsonData = await jsonRes.json();
- designState.present = jsonData.present === true;
- designState.parsed = jsonData.parsed || null;
- designState.sidecar = jsonData.sidecar || null;
- designState.hasMd = !!jsonData.hasMd;
- designState.hasSidecar = !!jsonData.hasSidecar;
- designState.mdNewerThanJson = !!jsonData.mdNewerThanJson;
- designState.raw = designState.present && rawRes.ok ? await rawRes.text() : null;
- designState.error = jsonData.parseError || jsonData.sidecarError || null;
- } catch (err) {
- designState.error = err?.message || 'Failed to load design system.';
- } finally {
- designState.loading = false;
- renderDesignChrome(); // refresh title from data
- }
- }
-
- function renderDesignBody() {
- const body = designShadow.querySelector('#panel-body');
- if (!body) return;
- body.innerHTML = '';
-
- if (designState.loading) {
- body.appendChild(msgDiv('loading', 'Loading design system…'));
- return;
- }
- if (designState.error) {
- body.appendChild(msgDiv('error', designState.error));
- return;
- }
- if (designState.present === false) {
- const empty = document.createElement('div');
- empty.className = 'empty';
- empty.innerHTML = `<strong>No DESIGN.md yet</strong>Create one by running <code>/impeccable document</code> in your terminal, then re-open this panel.`;
- body.appendChild(empty);
- return;
- }
-
- if (designState.tab === 'raw') {
- renderRawTab(body, designState.raw || '');
- return;
- }
-
- // Visual tab — single unified render path.
- if (designState.mdNewerThanJson) body.appendChild(renderStaleHint());
- if (designState.hasMd && !designState.hasSidecar) {
- body.appendChild(renderParsedMdCta());
- }
- renderDesignVisual(body, designState.parsed, designState.sidecar);
- }
-
- function msgDiv(cls, text) {
- const d = document.createElement('div');
- d.className = cls;
- d.textContent = text;
- return d;
- }
-
- function renderStaleHint() {
- const box = document.createElement('div');
- box.className = 'stale';
- box.innerHTML = `
- <span class="stale-dot"></span>
- <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>
- `;
- return box;
- }
-
- function renderParsedMdCta() {
- const box = document.createElement('div');
- box.className = 'parsed-md-cta';
- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;
- return box;
- }
-
- // --- Unified render: merge parsed DESIGN.md frontmatter with sidecar v2 ---
-
- function renderDesignVisual(body, parsed, sidecar) {
- const frontmatter = parsed?.frontmatter || {};
- const extensions = sidecar?.extensions || {};
- const proseColors = parsed?.colors || null;
-
- const colors = buildColorModels(frontmatter.colors, extensions.colorMeta, proseColors);
- if (colors.length) renderColorTiles(body, colors);
-
- const types = buildTypographyModels(frontmatter.typography, extensions.typographyMeta);
- if (types.length) renderTypeTiles(body, types);
-
- const radii = buildRadiiModels(frontmatter.rounded);
- if (radii.length) renderRadiiTile(body, radii);
-
- if (extensions.shadows?.length) renderShadowTiles(body, extensions.shadows);
-
- const components = sidecar?.components || [];
- if (components.length) renderComponentTiles(body, components);
-
- // Narrative: sidecar wins if present (richer, agent-curated). Otherwise
- // synthesize from prose sections.
- const narrative = sidecar?.narrative || synthesizeNarrative(parsed);
- if (narrative.rules?.length) body.appendChild(renderRulesCollapsible(narrative.rules));
- if ((narrative.dos?.length || narrative.donts?.length)) body.appendChild(renderDosDontsCollapsible(narrative));
- if (narrative.overview || narrative.northStar || narrative.keyCharacteristics?.length) {
- body.appendChild(renderOverviewCollapsible(narrative));
- }
-
- if (body.childElementCount === 0) {
- body.appendChild(msgDiv('empty', 'No design system data available.'));
- }
- }
-
- // Frontmatter primitives + sidecar colorMeta → tile-ready color models.
- // A matching prose bullet (when the slug sits in the bullet text) supplies
- // description as a last-resort fallback.
- function buildColorModels(fmColors, colorMeta, proseColors) {
- if (!fmColors) return [];
- const meta = colorMeta || {};
- return Object.entries(fmColors).map(([key, value]) => {
- const m = meta[key] || {};
- return {
- role: m.role || humanizeKey(key),
- name: m.displayName || humanizeKey(key),
- value: value,
- canonical: m.canonical || null,
- description: m.description || findProseDescription(proseColors, key, m.displayName),
- tonalRamp: m.tonalRamp || null,
- };
- });
- }
-
- function buildTypographyModels(fmTypography, typographyMeta) {
- if (!fmTypography) return [];
- const meta = typographyMeta || {};
- return Object.entries(fmTypography).map(([key, spec]) => {
- const m = meta[key] || {};
- const { family, fallback } = splitFontFamily(spec?.fontFamily);
- return {
- role: key,
- name: m.displayName || humanizeKey(key),
- family,
- fallback,
- weight: spec?.fontWeight ?? 400,
- // fontStyle isn't in Stitch's frontmatter schema; the sidecar carries
- // it when a role is rendered in italic (e.g. display italic).
- style: m.style || 'normal',
- sampleSize: spec?.fontSize || '1rem',
- lineHeight: spec?.lineHeight != null ? String(spec.lineHeight) : '',
- letterSpacing: spec?.letterSpacing,
- purpose: m.purpose,
- };
- });
- }
-
- function buildRadiiModels(fmRounded) {
- if (!fmRounded) return [];
- return Object.entries(fmRounded).map(([name, value]) => ({ name, value }));
- }
-
- function splitFontFamily(stack) {
- if (!stack || typeof stack !== 'string') return { family: '', fallback: '' };
- const parts = stack.split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, ''));
- return { family: parts[0] || '', fallback: parts.slice(1).join(', ') };
- }
-
- function humanizeKey(k) {
- return String(k || '').replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
- }
-
- function findProseDescription(proseColors, key, displayName) {
- if (!proseColors || !proseColors.groups) return null;
- const needles = [key, displayName].filter(Boolean).map((s) => s.toLowerCase());
- for (const g of proseColors.groups) {
- for (const c of g.colors || []) {
- const hay = String(c.name || '').toLowerCase();
- if (hay && needles.some((n) => hay.includes(n) || n.includes(hay))) {
- return c.description || null;
- }
- }
- }
- return null;
- }
-
- function synthesizeNarrative(parsed) {
- if (!parsed) return {};
- const md = parsed;
- return {
- northStar: md.overview?.creativeNorthStar,
- overview: (md.overview?.philosophy || []).join(' '),
- keyCharacteristics: md.overview?.keyCharacteristics || [],
- rules: [
- ...(md.colors?.rules || []).map((r) => ({ ...r, section: 'colors' })),
- ...(md.typography?.rules || []).map((r) => ({ ...r, section: 'typography' })),
- ...(md.elevation?.rules || []).map((r) => ({ ...r, section: 'elevation' })),
- ],
- dos: md.dosDonts?.dos || [],
- donts: md.dosDonts?.donts || [],
- };
- }
-
- function renderColorTiles(body, colors) {
- for (const c of colors) {
- const tile = document.createElement('div');
- tile.className = 'tile c-tile';
- tile.title = 'Click to copy';
- tile.addEventListener('click', () => copyToClipboard(c.value));
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(c.name || c.role || 'Color')}</span><span>${escapeHtml(c.value || '')}</span>`;
- tile.appendChild(meta);
-
- const hero = document.createElement('div');
- hero.className = 'c-hero';
- hero.style.background = c.value;
- tile.appendChild(hero);
-
- const ramp = synthesizeRamp(c);
- if (ramp.length) {
- const r = document.createElement('div');
- r.className = 'c-ramp';
- r.innerHTML = ramp.map((v) => `<span style="background:${cssSafe(v)}"></span>`).join('');
- tile.appendChild(r);
- }
-
- if (c.description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = c.description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function synthesizeRamp(c) {
- if (c.tonalRamp?.length) return c.tonalRamp;
- // If base value is OKLCH, synthesize an 8-step ramp across lightness.
- const m = typeof c.value === 'string' && c.value.match(/^oklch\(\s*([\d.]+)%\s+([\d.]+)\s+([\d.]+)\s*(?:\/\s*([\d.]+))?\s*\)$/i);
- if (!m) return [];
- const [, , chroma, hue] = m;
- const steps = [20, 32, 44, 56, 68, 80, 90, 96];
- return steps.map((l) => `oklch(${l}% ${chroma} ${hue})`);
- }
-
- function renderTypeTiles(body, types) {
- for (const t of types) {
- const tile = document.createElement('div');
- tile.className = 'tile t-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span>${escapeHtml(t.role || '')}</span><span>${escapeHtml(t.weight || '')} ${escapeHtml(t.style === 'italic' ? 'italic' : '')}</span>`;
- tile.appendChild(meta);
-
- const specimen = document.createElement('div');
- specimen.className = 't-specimen';
- specimen.textContent = 'Aa';
- specimen.style.fontFamily = fontStack(t);
- specimen.style.fontWeight = String(t.weight || 400);
- specimen.style.fontStyle = t.style || 'normal';
- specimen.style.fontSize = '56px'; // Fixed specimen size — compare faces, not scales.
- specimen.style.letterSpacing = 'normal';
- specimen.style.textTransform = 'none';
- tile.appendChild(specimen);
-
- // The system's actual sample size for this role, shown as small mono meta below.
- if (t.sampleSize) {
- const scale = document.createElement('div');
- scale.style.cssText = 'font-family:' + MONO + '; font-size: 10px; color:' + DP.meta + '; margin-top: 2px;';
- scale.textContent = t.sampleSize;
- tile.appendChild(scale);
- }
-
- const family = document.createElement('div');
- family.className = 't-family';
- family.textContent = t.family || t.name || '';
- tile.appendChild(family);
-
- if (t.purpose) {
- const p = document.createElement('div');
- p.className = 't-purpose';
- p.textContent = t.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function fontStack(t) {
- const fam = t.family || '';
- const fb = t.fallback || '';
- if (fam && /[,\s]/.test(fam) && !fam.includes("'") && !fam.includes('"')) {
- return `"${fam}", ${fb}`;
- }
- return fam && fb ? `"${fam}", ${fb}` : (fam || fb);
- }
-
- function renderRadiiTile(body, radii) {
- const tile = document.createElement('div');
- tile.className = 'tile';
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">Corner Radii</span><span>${radii.length}</span>`;
- tile.appendChild(meta);
-
- const strip = document.createElement('div');
- strip.className = 'r-strip';
- for (const r of radii) {
- const item = document.createElement('div');
- item.className = 'r-item';
- const s = document.createElement('div');
- s.className = 'r-sample';
- s.style.borderRadius = r.value || '0';
- item.appendChild(s);
- const lbl = document.createElement('div');
- lbl.className = 'r-label';
- lbl.textContent = r.name || '';
- item.appendChild(lbl);
- const val = document.createElement('div');
- val.className = 'r-val';
- val.textContent = r.value || '';
- item.appendChild(val);
- strip.appendChild(item);
- }
- tile.appendChild(strip);
- body.appendChild(tile);
- }
-
- function renderShadowTiles(body, shadows) {
- for (const sh of shadows) {
- const tile = document.createElement('div');
- tile.className = 'tile s-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(sh.name || 'Shadow')}</span><span>Elevation</span>`;
- tile.appendChild(meta);
-
- const surface = document.createElement('div');
- surface.className = 's-surface';
- surface.style.boxShadow = sh.value || 'none';
- tile.appendChild(surface);
-
- const val = document.createElement('div');
- val.className = 's-value';
- val.textContent = sh.value || '';
- tile.appendChild(val);
-
- if (sh.purpose) {
- const p = document.createElement('div');
- p.className = 's-purpose';
- p.textContent = sh.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function renderComponentTiles(body, components) {
- // Group consecutive components that share a kind into one tile. This avoids
- // a pile of one-component tiles (e.g., three button variants = three tiles)
- // and reads more like a proper category.
- const groups = groupByKind(components);
-
- for (const group of groups) {
- const tile = document.createElement('div');
- tile.className = 'tile cmp-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- const groupTitle = group.length === 1
- ? (group[0].name || group[0].kind || 'Component')
- : titleForKind(group[0].kind, group.length);
- meta.innerHTML = `<span class="name">${escapeHtml(groupTitle)}</span><span class="cmp-kind">${escapeHtml(group[0].kind || '')}</span>`;
- tile.appendChild(meta);
-
- for (const c of group) {
- const stage = document.createElement('div');
- stage.className = 'cmp-stage';
-
- // Render the component in its own shadow root so its CSS can't bleed.
- const host = document.createElement('div');
- const sub = host.attachShadow({ mode: 'open' });
- const style = document.createElement('style');
- style.textContent = c.css || '';
- sub.appendChild(style);
- const container = document.createElement('div');
- container.innerHTML = c.html || '';
- sub.appendChild(container);
- stage.appendChild(host);
-
- // Show component name as a sublabel only when the tile groups >1 item,
- // or when the component's display name differs from its kind.
- const showSublabel = group.length > 1;
- if (showSublabel) {
- const lbl = document.createElement('div');
- lbl.className = 'cmp-sublabel';
- lbl.textContent = c.name || '';
- stage.appendChild(lbl);
- }
- tile.appendChild(stage);
- }
-
- // Single shared description if all items carry the same one; otherwise
- // skip — per-item descriptions clutter a grouped tile.
- if (group.length === 1 && group[0].description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = group[0].description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function groupByKind(components) {
- const groups = [];
- for (const c of components) {
- const last = groups[groups.length - 1];
- if (last && last[0].kind && c.kind === last[0].kind) {
- last.push(c);
- } else {
- groups.push([c]);
- }
- }
- return groups;
- }
-
- function titleForKind(kind, count) {
- const labels = {
- button: 'Buttons',
- input: 'Inputs',
- nav: 'Navigation',
- chip: 'Chips',
- card: 'Cards',
- custom: 'Components',
- };
- return labels[kind] || (kind ? kind.charAt(0).toUpperCase() + kind.slice(1) + 's' : 'Components');
- }
-
- // --- Collapsibles ---------------------------------------------------------
-
- function buildCollapsible(key, label, count) {
- const wrap = document.createElement('div');
- wrap.className = 'coll';
- wrap.setAttribute('data-open', designState.collapsed[key] ? 'false' : 'true');
-
- const head = document.createElement('button');
- head.className = 'coll-head';
- head.innerHTML = `
- <svg class="coll-chev" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 2.5L8 6 4 9.5"/></svg>
- <span>${escapeHtml(label)}</span>
- ${count != null ? `<span class="coll-count">${escapeHtml(String(count))}</span>` : ''}
- `;
- head.addEventListener('click', () => {
- designState.collapsed[key] = !designState.collapsed[key];
- saveDesignPrefs();
- renderDesignBody();
- });
- wrap.appendChild(head);
-
- const body = document.createElement('div');
- body.className = 'coll-body';
- wrap.appendChild(body);
- return { wrap, body };
- }
-
- function renderRulesCollapsible(rules) {
- const { wrap, body } = buildCollapsible('rules', 'Named Rules', rules.length);
- for (const r of rules) {
- const card = document.createElement('div');
- card.className = 'rule-card';
- const name = document.createElement('div');
- name.className = 'name';
- name.innerHTML = `${escapeHtml(r.name)}${r.section ? `<span class="section">${escapeHtml(r.section)}</span>` : ''}`;
- card.appendChild(name);
- const b = document.createElement('div');
- b.className = 'body';
- b.textContent = r.body || '';
- card.appendChild(b);
- body.appendChild(card);
- }
- return wrap;
- }
-
- function renderDosDontsCollapsible(n) {
- const total = (n.dos?.length || 0) + (n.donts?.length || 0);
- const { wrap, body } = buildCollapsible('dosdonts', "Do's and Don'ts", total);
- const grid = document.createElement('div');
- grid.className = 'dos';
- for (const d of n.dos || []) {
- const el = document.createElement('div');
- el.className = 'do';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- for (const d of n.donts || []) {
- const el = document.createElement('div');
- el.className = 'dont';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- body.appendChild(grid);
- return wrap;
- }
-
- function renderOverviewCollapsible(n) {
- const { wrap, body } = buildCollapsible('overview', 'Overview', null);
- const ov = document.createElement('div');
- ov.className = 'overview-body';
- if (n.northStar) {
- const star = document.createElement('span');
- star.className = 'north-star';
- star.textContent = '“' + n.northStar + '”';
- ov.appendChild(star);
- }
- if (n.overview) {
- const p = document.createElement('p');
- p.innerHTML = inlineMd(n.overview);
- ov.appendChild(p);
- }
- if (n.keyCharacteristics?.length) {
- const ul = document.createElement('ul');
- ul.innerHTML = n.keyCharacteristics.map((k) => `<li>${inlineMd(k)}</li>`).join('');
- ov.appendChild(ul);
- }
- body.appendChild(ov);
- return wrap;
- }
-
- function cssSafe(v) {
- // Strip anything outside valid CSS value chars to prevent injection via
- // .impeccable/design.json values rendered into inline style strings.
- return String(v).replace(/[<>"'`\n]/g, '');
- }
-
- // --- Raw tab: minimal markdown renderer (subset) --------------------------
-
- function renderRawTab(body, md) {
- const wrap = document.createElement('div');
- wrap.className = 'md';
- wrap.innerHTML = renderMarkdown(md);
- body.appendChild(wrap);
- }
-
- function renderMarkdown(md) {
- const lines = md.split(/\r?\n/);
- const out = [];
- let i = 0;
- let inCode = false;
- let codeBuf = [];
- let paraBuf = [];
- let listBuf = []; // array of { indent, html }
- let listType = null; // 'ul' | 'ol'
-
- const flushPara = () => {
- if (paraBuf.length) {
- out.push(`<p>${inlineMd(paraBuf.join(' '))}</p>`);
- paraBuf = [];
- }
- };
- const flushList = () => {
- if (listBuf.length) {
- out.push(buildListHtml(listBuf, listType));
- listBuf = [];
- listType = null;
- }
- };
- const flushAll = () => { flushPara(); flushList(); };
-
- for (; i < lines.length; i++) {
- const line = lines[i];
-
- // Code fence
- const fence = line.match(/^```(\w*)\s*$/);
- if (fence) {
- if (!inCode) { flushAll(); inCode = true; codeBuf = []; }
- else {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- inCode = false;
- }
- continue;
- }
- if (inCode) { codeBuf.push(line); continue; }
-
- if (line.trim() === '') { flushAll(); continue; }
-
- const hr = line.match(/^\s*(?:---+|\*\*\*+)\s*$/);
- if (hr) { flushAll(); out.push('<hr />'); continue; }
-
- const heading = line.match(/^(#{1,4})\s+(.+)$/);
- if (heading) {
- flushAll();
- const lvl = heading[1].length;
- out.push(`<h${lvl}>${inlineMd(heading[2])}</h${lvl}>`);
- continue;
- }
-
- const bullet = line.match(/^(\s*)([-*])\s+(.+)$/);
- const ordered = line.match(/^(\s*)(\d+)\.\s+(.+)$/);
- if (bullet || ordered) {
- flushPara();
- const m = bullet || ordered;
- const indent = Math.floor(m[1].length / 2);
- const t = bullet ? 'ul' : 'ol';
- if (listType && listType !== t) flushList();
- listType = t;
- listBuf.push({ indent, html: inlineMd(m[3]) });
- continue;
- }
-
- paraBuf.push(line);
- }
- flushAll();
- if (inCode && codeBuf.length) {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- }
- return out.join('\n');
- }
-
- function buildListHtml(items, type) {
- // Nest by indent (one level deep is plenty for DESIGN.md).
- let html = `<${type}>`;
- let lastIndent = 0;
- for (const it of items) {
- if (it.indent > lastIndent) html += `<${type}>`;
- else if (it.indent < lastIndent) html += `</${type}>`.repeat(lastIndent - it.indent);
- html += `<li>${it.html}</li>`;
- lastIndent = it.indent;
- }
- html += `</${type}>`.repeat(lastIndent + 1);
- return html;
- }
-
- function inlineMd(text) {
- // Order matters: escape first, then re-inject tags.
- let s = escapeHtml(text);
- // Code spans
- s = s.replace(/`([^`]+)`/g, (_, code) => `<code>${code}</code>`);
- // Links [text](url)
- s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, t, u) => `<a href="${u}" target="_blank" rel="noopener noreferrer">${t}</a>`);
- // Bold
- s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
- // Italic (only single *…*, skip if inside bold already handled)
- s = s.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em>$2</em>');
- return s;
- }
-
- function highlightBold(text) {
- return inlineMd(text);
- }
-
- function escapeHtml(s) {
- return String(s)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
-
- function copyToClipboard(text) {
- if (!text) return;
- try {
- navigator.clipboard.writeText(text);
- showToast('Copied: ' + text);
- } catch { /* ignore */ }
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- function init() {
- try { history.scrollRestoration = 'manual'; } catch {}
- initHighlight();
- initAnnotOverlay();
- initBar();
- initActionPicker();
- initParamsPanel();
- initGlobalBar();
- initDesignPanel();
- document.addEventListener('mousemove', handleMouseMove, true);
- document.addEventListener('click', handleClick, true);
- document.addEventListener('keydown', handleKeyDown, true);
- connectSSE();
-
- // Check for an active session to resume (variant wrapper already in DOM after HMR)
- if (!resumeSession()) {
- console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
- // SvelteKit (and any framework that hydrates after HTML parse) may add
- // the variant wrapper AFTER init runs. Watch for it and retry resume
- // once it appears. Disconnect on first hit.
- const scout = new MutationObserver(() => {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) return;
- scout.disconnect();
- if (resumeSession()) {
- console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
- }
- });
- scout.observe(document.body, { childList: true, subtree: true });
- } else {
- console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
- }
- }
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
- } else {
- init();
- }
-})();
@@ -1,75 +0,0 @@
-#!/usr/bin/env node
-/**
- * Canonical durable completion acknowledgement for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function parseArgs(argv) {
- const out = { status: 'complete' };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';
- else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }
- else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function completeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help || !args.id) {
- console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);
- process.exit(args.help ? 0 : 1);
- }
-
- const serverInfo = readServerInfo();
- const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;
- if (serverResult?.ok) {
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const snapshot = store.getSnapshot(args.id, { includeCompleted: true });
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const event = args.status === 'discarded'
- ? { type: 'discarded', id: args.id }
- : args.status === 'agent_error'
- ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }
- : { type: 'complete', id: args.id };
- const snapshot = store.appendEvent(event);
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));
-}
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function completeThroughServer(info, args) {
- const type = args.status === 'discarded'
- ? 'discarded'
- : args.status === 'agent_error'
- ? 'error'
- : 'complete';
- try {
- const res = await fetch(`http://localhost:${info.port}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),
- });
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {
- completeCli();
-}
@@ -1,18 +0,0 @@
-export function completionTypeForAcceptResult(eventType, acceptResult) {
- if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';
- if (acceptResult?.handled === true) return 'complete';
- if (acceptResult?.mode === 'error') return 'error';
- return 'agent_done';
-}
-
-export function completionAckForAcceptResult(eventId, completionType, acceptResult) {
- const ack = { ok: true, type: completionType };
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) {
- ack.final = false;
- ack.requiresComplete = true;
- ack.nextCommand = `live-complete.mjs --id ${eventId}`;
- ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';
- }
- return ack;
-}
@@ -1,446 +0,0 @@
-/**
- * CLI helper: insert/remove the live variant mode script tag in the project's
- * main HTML entry point.
- *
- * On first live run, the agent generates `.impeccable/live/config.json`
- * with the project's insertion target (framework-specific). On
- * every subsequent run, this script handles insert/remove deterministically
- * with zero LLM involvement.
- *
- * Usage:
- * node live-inject.mjs --port PORT # Insert the live script tag
- * node live-inject.mjs --remove # Remove the live script tag
- * node live-inject.mjs --check # Check whether live config exists
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { resolveLiveConfigPath } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });
-const MARKER_OPEN_TEXT = 'impeccable-live-start';
-const MARKER_CLOSE_TEXT = 'impeccable-live-end';
-
-/**
- * Hard-excluded directory patterns. These are NEVER user-facing pages and
- * matching them would silently inject tracking scripts into third-party
- * code. The user cannot turn these off via config — they are the floor.
- */
-const HARD_EXCLUDES = [
- '**/node_modules/**',
- '**/.git/**',
-];
-
-export async function injectCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-inject.mjs [options]
-
-Insert or remove the live mode script tag in the project's HTML entry point.
-Reads configuration from .impeccable/live/config.json.
-
-Modes:
- --port PORT Insert script tag pointing at http://localhost:PORT/live.js
- --remove Remove the script tag (if present)
- --check Print whether .impeccable/live/config.json exists and its content
-
-Output (JSON):
- { ok, file, inserted|removed, config? }`);
- process.exit(0);
- }
-
- if (args.includes('--check')) {
- if (!fs.existsSync(CONFIG_PATH)) {
- console.log(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(0);
- }
- let cfg;
- try {
- cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- try {
- validateConfig(cfg);
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- console.log(JSON.stringify({ ok: true, config: cfg, path: CONFIG_PATH }));
- return;
- }
-
- // Load config
- if (!fs.existsSync(CONFIG_PATH)) {
- console.error(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(1);
- }
- const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- validateConfig(config);
-
- const resolvedFiles = resolveFiles(process.cwd(), config);
-
- if (args.includes('--remove')) {
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const detagged = removeTag(content, config.commentSyntax);
- const updated = revertCspMeta(detagged);
- if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- removed: detagged !== content,
- cspReverted: updated !== detagged,
- };
- });
- console.log(JSON.stringify({ ok: true, results }));
- return;
- }
-
- // Insert mode — need --port
- const portIdx = args.indexOf('--port');
- const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : NaN;
- if (!Number.isFinite(port)) {
- console.error(JSON.stringify({ ok: false, error: 'missing_port' }));
- process.exit(1);
- }
-
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
- const withTag = insertTag(withoutOld, config, port);
- if (withTag === withoutOld) {
- return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
- }
- const updated = patchCspMeta(withTag, port);
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- inserted: true,
- cspPatched: updated !== withTag,
- };
- });
- const anyInserted = results.some((r) => r.inserted);
- console.log(JSON.stringify({ ok: anyInserted, port, results }));
- if (!anyInserted) process.exit(1);
-}
-
-/**
- * Expand config.files (which may contain glob patterns) into a literal list
- * of existing file paths relative to rootDir. Literal entries pass through;
- * glob patterns are expanded via fs.globSync. HARD_EXCLUDES and config.exclude
- * are applied as filters. Duplicates are removed. Order is preserved by
- * first appearance.
- */
-export function resolveFiles(rootDir, config) {
- const patterns = config.files;
- const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
- const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
- const excludeRegexes = allExcludes.map(globToRegex);
-
- const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
- const isGlob = (s) => /[*?[]/.test(s);
-
- const seen = new Set();
- const out = [];
- for (const pat of patterns) {
- if (!isGlob(pat)) {
- // Literal path — include even if it doesn't exist yet; the caller
- // reports file_not_found per-entry. Exclude list doesn't apply to
- // explicit literal entries (user named it on purpose).
- if (!seen.has(pat)) {
- seen.add(pat);
- out.push(pat);
- }
- continue;
- }
- let matches;
- try {
- matches = fs.globSync(pat, { cwd: rootDir, withFileTypes: true });
- } catch {
- continue;
- }
- for (const ent of matches) {
- if (!ent.isFile || !ent.isFile()) continue;
- const abs = path.join(ent.parentPath || ent.path || rootDir, ent.name);
- const rel = path.relative(rootDir, abs).split(path.sep).join('/');
- if (isExcluded(rel)) continue;
- if (seen.has(rel)) continue;
- seen.add(rel);
- out.push(rel);
- }
- }
- return out;
-}
-
-/**
- * Convert a glob pattern to a RegExp. Supports:
- * ** → any number of path segments (including zero)
- * * → any chars except `/`
- * ? → any single char except `/`
- * Paths are normalized to forward slashes before matching.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- // ** — any number of segments, including zero. Handle the common
- // **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
- if (pattern[i + 2] === '/') {
- re += '(?:.*/)?';
- i += 3;
- } else {
- re += '.*';
- i += 2;
- }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Core operations
-// ---------------------------------------------------------------------------
-
-function validateConfig(cfg) {
- if (!cfg || typeof cfg !== 'object') throw new Error('config.json must be an object');
- if (!Array.isArray(cfg.files) || cfg.files.length === 0) {
- throw new Error('config.files (non-empty string array) required');
- }
- if (!cfg.files.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.files must contain only non-empty strings');
- }
- if (cfg.exclude !== undefined) {
- if (!Array.isArray(cfg.exclude)) {
- throw new Error('config.exclude, if present, must be a string array');
- }
- if (!cfg.exclude.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.exclude must contain only non-empty strings');
- }
- }
- if (typeof cfg.insertBefore !== 'string' && typeof cfg.insertAfter !== 'string') {
- throw new Error('config.insertBefore or config.insertAfter (string) required');
- }
- if (cfg.commentSyntax !== 'html' && cfg.commentSyntax !== 'jsx') {
- throw new Error("config.commentSyntax must be 'html' or 'jsx'");
- }
- if (cfg.cspChecked !== undefined && typeof cfg.cspChecked !== 'boolean') {
- throw new Error("config.cspChecked, if present, must be a boolean");
- }
-}
-
-function commentOpen(syntax) { return syntax === 'jsx' ? '{/*' : '<!--'; }
-function commentClose(syntax) { return syntax === 'jsx' ? '*/}' : '-->'; }
-
-function buildTagBlock(syntax, port) {
- const open = commentOpen(syntax);
- const close = commentClose(syntax);
- return (
- open + ' ' + MARKER_OPEN_TEXT + ' ' + close + '\n' +
- '<script src="http://localhost:' + port + '/live.js"></script>\n' +
- open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n'
- );
-}
-
-function insertTag(content, config, port) {
- const block = buildTagBlock(config.commentSyntax, port);
- // insertBefore: match the LAST occurrence. Anchors like `</body>` naturally
- // belong at the end, and the same literal can appear earlier in code blocks
- // within rendered documentation pages.
- if (config.insertBefore) {
- const idx = content.lastIndexOf(config.insertBefore);
- if (idx === -1) return content;
- return content.slice(0, idx) + block + content.slice(idx);
- }
- // insertAfter: match the FIRST occurrence — typical anchors like `<head>` or
- // `<body>` open near the top of the document.
- const idx = content.indexOf(config.insertAfter);
- if (idx === -1) return content;
- const after = idx + config.insertAfter.length;
- // Preserve a single trailing newline if the anchor didn't end with one
- const prefix = content[after] === '\n' ? content.slice(0, after + 1) : content.slice(0, after) + '\n';
- return prefix + block + content.slice(prefix.length);
-}
-
-/**
- * Remove the live script block. Matches either HTML or JSX comment markers
- * regardless of config (so stale tags from a wrong config can still be cleaned).
- *
- * Indent-preserving: captures any whitespace immediately preceding the opener
- * marker and re-emits it in place of the removed block. `insertTag` inserted
- * the block *after* the original line's indent and *before* the anchor (e.g.
- * `</body>`), which moved the indent onto the opener line and left the anchor
- * unindented. Replacing the whole block (plus its trailing newline) with just
- * the captured indent hands the indent back to the anchor that follows.
- */
-function removeTag(content, _syntax) {
- const patterns = [
- /([ \t]*)<!--\s*impeccable-live-start\s*-->[\s\S]*?<!--\s*impeccable-live-end\s*-->[ \t]*\n/,
- /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}[ \t]*\n/,
- ];
- for (const pat of patterns) {
- const next = content.replace(pat, '$1');
- if (next !== content) return next;
- }
- return content;
-}
-
-// ---------------------------------------------------------------------------
-// Content-Security-Policy meta-tag patcher
-//
-// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
-// the cross-origin load of /live.js (and the SSE/POST connection back to
-// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
-//
-// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
-// and stash the original `content` value in a `data-impeccable-csp-original`
-// attribute (base64) so revert is exact.
-//
-// On remove: detect the marker attribute, decode it, restore the original
-// content value verbatim, drop the marker.
-//
-// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
-// shared helpers) is NOT patched here — those need framework-specific config
-// edits and are handled via the existing detect-csp.mjs reference output.
-// Only the in-source meta-tag form gets the auto-patch.
-// ---------------------------------------------------------------------------
-
-const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
-
-function findCspMetaTags(content) {
- const out = [];
- const tagRe = /<meta\s+([^>]*?)\/?>/gis;
- let m;
- while ((m = tagRe.exec(content)) !== null) {
- const attrs = m[1];
- if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
- out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
- }
- return out;
-}
-
-function getAttr(attrs, name) {
- const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
- const m = attrs.match(re);
- return m ? { quote: m[1], value: m[2], full: m[0] } : null;
-}
-
-function appendOriginToDirective(csp, directive, origin) {
- const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
- const m = csp.match(re);
- if (m) {
- const tokens = m[4].trim().split(/\s+/);
- if (tokens.includes(origin)) return csp;
- return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
- }
- // Directive missing — add it. Use 'self' + origin so we don't inadvertently
- // narrow the policy compared to the default-src fallback (most users with
- // an explicit CSP have 'self' there).
- return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
-}
-
-export function patchCspMeta(content, port) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
- const origin = `http://localhost:${port}`;
-
- // Walk last-to-first so prior splices don't invalidate later indices.
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const attrs = tag.attrs;
- if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
- const contentAttr = getAttr(attrs, 'content');
- if (!contentAttr) continue;
-
- const original = contentAttr.value;
- let patched = original;
- patched = appendOriginToDirective(patched, 'script-src', origin);
- patched = appendOriginToDirective(patched, 'connect-src', origin);
- // The shader overlay during 'generating' creates a screenshot via
- // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
- // those. Add `blob:` so the overlay doesn't throw a CSP violation.
- patched = appendOriginToDirective(patched, 'img-src', 'blob:');
- if (patched === original) continue;
-
- const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
- const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
- // The tagRe captures any whitespace between the last attribute and the
- // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
- // a replace would land it BEFORE that trailing space, leaving a double
- // space inside attrs and clobbering the space before `/>`. Split off
- // the trailing whitespace, splice the marker into the attribute body,
- // and re-append the original trailing whitespace so a self-closing
- // `<meta … />` round-trips byte-for-byte.
- const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
- const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
- const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
- const newTag = tag.full.replace(attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-export function revertCspMeta(content) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
-
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
- if (!origAttr) continue;
- const contentAttr = getAttr(tag.attrs, 'content');
- if (!contentAttr) continue;
-
- let originalValue;
- try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
- catch { continue; }
-
- const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
- let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
- // Drop the marker attribute and any single space immediately preceding it.
- newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
- const newTag = tag.full.replace(tag.attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
- injectCli();
-}
-
-export { insertTag, removeTag, validateConfig, buildTagBlock };
-// patchCspMeta + revertCspMeta are exported above where they're defined.
@@ -1,200 +0,0 @@
-/**
- * CLI client for the live variant mode poll/reply protocol.
- *
- * Usage:
- * npx impeccable poll # Block until browser event, print JSON
- * npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
- * npx impeccable poll --reply <id> done # Reply "done" to event <id>
- * npx impeccable poll --reply <id> error "msg" # Reply with error
- */
-
-import { execFileSync } from 'node:child_process';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-// Node's built-in fetch (undici under the hood) enforces a 300s headers
-// timeout that can't be lowered per-request. We cap each request below
-// that ceiling and loop in `pollOnce` to synthesize a long poll without
-// depending on the standalone undici package.
-const PER_REQUEST_TIMEOUT_MS = 270_000;
-
-function readServerInfo() {
- const record = readLiveServerInfo(process.cwd());
- if (!record) {
- console.error('No running live server found. Start one with: npx impeccable live');
- process.exit(1);
- }
- return record.info;
-}
-
-export function buildPollReplyPayload(token, { id, type, message, file, data }) {
- return { token, id, type, message, file, data };
-}
-
-async function postReply(base, token, reply) {
- const res = await fetch(`${base}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(buildPollReplyPayload(token, reply)),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error || res.statusText);
- }
-}
-
-export async function pollCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable poll [options]
-
-Wait for a browser event from the live variant server, or reply to one.
-
-Modes:
- poll Block until a browser event arrives, print JSON
- poll --reply <id> done Reply "done" to event <id>
- poll --reply <id> error "msg" Reply with an error message
-
-Options:
- --timeout=MS Long-poll timeout in ms (default: 600000). Use the default unless the user asked to pause live; never use a short timeout to end the chat turn
- --help Show this help message`);
- process.exit(0);
- }
-
- const info = readServerInfo();
- const base = `http://localhost:${info.port}`;
-
- // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
- const replyIdx = args.indexOf('--reply');
- if (replyIdx !== -1) {
- const id = args[replyIdx + 1];
- const status = args[replyIdx + 2] || 'done';
- const fileIdx = args.indexOf('--file');
- const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
- // Message is any remaining positional arg that isn't a flag
- const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
-
- if (!id) {
- console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
- process.exit(1);
- }
-
- try {
- await postReply(base, info.token, { id, type: status, message, file: filePath });
-
- // Success — silent exit (agent doesn't need output for replies)
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Reply failed:', err.message);
- }
- process.exit(1);
- }
- return;
- }
-
- // Poll mode: block until browser event. Default 10 min. Node's built-in
- // fetch enforces a 300s headers timeout, so we loop in slices under that
- // ceiling and keep re-polling until we get a real event or the user's
- // total timeout runs out.
- const timeoutArg = args.find(a => a.startsWith('--timeout='));
- const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600000;
-
- const deadline = Date.now() + totalTimeout;
- let event;
- try {
- while (true) {
- const remaining = deadline - Date.now();
- if (remaining <= 0) {
- event = { type: 'timeout' };
- break;
- }
- const slice = Math.min(remaining, PER_REQUEST_TIMEOUT_MS);
- const res = await fetch(`${base}/poll?token=${info.token}&timeout=${slice}`);
-
- if (res.status === 401) {
- console.error('Authentication failed. The server token may have changed.');
- console.error('Try restarting: npx impeccable live stop && npx impeccable live');
- process.exit(1);
- }
-
- if (!res.ok) {
- console.error(`Poll failed: ${res.status} ${res.statusText}`);
- process.exit(1);
- }
-
- const next = await res.json();
- // Server-side timeout means no browser event arrived in this slice.
- // Loop and re-poll until we get a real event or we hit the user's
- // total deadline.
- if (next?.type === 'timeout' && Date.now() < deadline) continue;
- event = next;
- break;
- }
-
- // Auto-handle accept/discard via deterministic script
- if (event.type === 'accept' || event.type === 'discard') {
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const acceptScript = path.join(__dirname, 'live-accept.mjs');
- const scriptArgs = event.type === 'discard'
- ? ['--id', event.id, '--discard']
- : ['--id', event.id, '--variant', event.variantId];
- if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
- scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
- }
- try {
- const out = execFileSync(
- 'node',
- [acceptScript, ...scriptArgs],
- { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 }
- );
- event._acceptResult = JSON.parse(out.trim());
- } catch (err) {
- event._acceptResult = { handled: false, mode: 'error', error: err.message };
- }
-
- const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
- try {
- await postReply(base, info.token, {
- id: event.id,
- type: completionType,
- message: event._acceptResult?.error,
- file: event._acceptResult?.file,
- data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
- });
- } catch (err) {
- event._completionAck = { ok: false, error: err.message };
- }
- if (!event._completionAck) {
- event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
- }
- }
-
- // Second signal path: stderr banner in case the agent parses stdout
- // JSON but skips nested fields. One line is enough — the full checklist
- // is in reference/live.md.
- if (event._acceptResult?.carbonize === true) {
- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
- }
-
- // Print the event as JSON — the agent reads this from stdout
- console.log(JSON.stringify(event));
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Poll failed:', err.message);
- }
- process.exit(1);
- }
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
- pollCli();
-}
@@ -1,48 +0,0 @@
-#!/usr/bin/env node
-/**
- * Recover the next agent action from the durable live-session journal.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-
-function parseArgs(argv) {
- const out = { id: null };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function resumeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help) {
- console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });
- const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;
- if (!snapshot) {
- console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));
- return;
- }
-
- const pending = snapshot.pendingEvent || null;
- const nextAction = pending
- ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`
- : snapshot.phase === 'carbonize_required'
- ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`
- : snapshot.phase === 'accept_requested'
- ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`
- : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;
-
- console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {
- resumeCli();
-}
@@ -1,838 +0,0 @@
-#!/usr/bin/env node
-/**
- * Live variant mode server (self-contained, zero dependencies).
- *
- * Serves the browser script (/live.js), the detection overlay (/detect.js),
- * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
- * browser→server events. Agent communicates via HTTP long-poll (/poll).
- *
- * Usage:
- * node <scripts_path>/live-server.mjs # start
- * node <scripts_path>/live-server.mjs stop # stop + remove injected live.js tag
- * node <scripts_path>/live-server.mjs stop --keep-inject # stop only
- * node <scripts_path>/live-server.mjs --help
- */
-
-import http from 'node:http';
-import { randomUUID } from 'node:crypto';
-import { spawn, execFileSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import net from 'node:net';
-import { fileURLToPath } from 'node:url';
-import { parseDesignMd } from './design-parser.mjs';
-import { resolveContextDir } from './load-context.mjs';
-import { createLiveSessionStore } from './live-session-store.mjs';
-import {
- getDesignSidecarPath,
- getLiveAnnotationsDir,
- readLiveServerInfo,
- removeLiveServerInfo,
- resolveDesignSidecarPath,
- writeLiveServerInfo,
-} from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated
-// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
-// DESIGN.json fallback for existing projects.
-const CONTEXT_DIR = resolveContextDir(process.cwd());
-const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anyway
-const SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s
-
-// ---------------------------------------------------------------------------
-// Port detection
-// ---------------------------------------------------------------------------
-
-async function findOpenPort(start = 8400) {
- return new Promise((resolve) => {
- const srv = net.createServer();
- srv.listen(start, '127.0.0.1', () => {
- const port = srv.address().port;
- srv.close(() => resolve(port));
- });
- srv.on('error', () => resolve(findOpenPort(start + 1)));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Session state
-// ---------------------------------------------------------------------------
-
-const state = {
- token: null,
- port: null,
- sseClients: new Set(), // SSE response objects (server→browser push)
- pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
- pendingPolls: [], // agent poll callbacks waiting for browser events
- exitTimer: null,
- sessionDir: null, // per-session tmp dir for annotation screenshots
- sessionStore: null,
- leaseTimer: null,
-};
-
-// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;
-// cap at 10 MB to guard against runaway writes from a misbehaving client.
-const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
-
-function enqueueEvent(event) {
- if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;
- state.pendingEvents.push({ event, leaseUntil: 0 });
- flushPendingPolls();
-}
-
-function restorePendingEventsFromStore() {
- if (!state.sessionStore) return;
- for (const snapshot of state.sessionStore.listActiveSessions()) {
- if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);
- }
-}
-
-function findAvailablePendingEvent(now = Date.now()) {
- return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);
-}
-
-function leaseEvent(entry, leaseMs) {
- if (!entry.event?.id) {
- const idx = state.pendingEvents.indexOf(entry);
- if (idx !== -1) state.pendingEvents.splice(idx, 1);
- return entry.event;
- }
- entry.leaseUntil = Date.now() + leaseMs;
- return entry.event;
-}
-
-function acknowledgePendingEvent(id) {
- if (!id) return false;
- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);
- if (idx === -1) return false;
- state.pendingEvents.splice(idx, 1);
- scheduleLeaseFlush();
- return true;
-}
-
-function scheduleLeaseFlush() {
- if (state.leaseTimer) {
- clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- }
- if (state.pendingPolls.length === 0) return;
- const now = Date.now();
- const nextLeaseUntil = state.pendingEvents
- .map((entry) => entry.leaseUntil || 0)
- .filter((leaseUntil) => leaseUntil > now)
- .sort((a, b) => a - b)[0];
- if (!nextLeaseUntil) return;
- state.leaseTimer = setTimeout(() => {
- state.leaseTimer = null;
- flushPendingPolls();
- }, Math.max(0, nextLeaseUntil - now));
-}
-
-function flushPendingPolls() {
- while (state.pendingPolls.length > 0) {
- const entry = findAvailablePendingEvent();
- if (!entry) {
- scheduleLeaseFlush();
- return;
- }
- const poll = state.pendingPolls.shift();
- poll.resolve(leaseEvent(entry, poll.leaseMs));
- }
- scheduleLeaseFlush();
-}
-
-/** Push a message to all connected SSE clients. */
-function broadcast(msg) {
- const data = 'data: ' + JSON.stringify(msg) + '\n\n';
- for (const res of state.sseClients) {
- try { res.write(data); } catch { /* client gone */ }
- }
-}
-
-// ---------------------------------------------------------------------------
-// Load scripts
-// ---------------------------------------------------------------------------
-
-function loadBrowserScripts() {
- // Detection script: prefer the skill-bundled detector, then fall back to
- // source/npm package locations for local development and older installs.
- // This one IS cached — detect.js rarely changes during a session.
- const detectPaths = [
- path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(process.cwd(), 'node_modules', 'impeccable', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- ];
- let detectScript = '';
- for (const p of detectPaths) {
- try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
- }
-
- // live-browser.js: DO NOT cache. Return the path so the /live.js handler
- // can re-read on every request. Editing the browser script during iteration
- // should land on the next tab reload, not require a server restart.
- const sessionPath = path.join(__dirname, 'live-browser-session.js');
- const livePath = path.join(__dirname, 'live-browser.js');
- for (const p of [sessionPath, livePath]) {
- if (!fs.existsSync(p)) {
- process.stderr.write('Error: live browser script not found at ' + p + '\n');
- process.exit(1);
- }
- }
-
- return { detectScript, sessionPath, livePath };
-}
-
-function hasProjectContext() {
- // PRODUCT.md carries brand voice / anti-references — that's what determines
- // whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
- // concern, surfaced by the design panel's own empty state. Legacy
- // .impeccable.md is auto-migrated to PRODUCT.md by load-context.mjs.
- try {
- fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
- return true;
- } catch { return false; }
-}
-
-function statOrNull(filePath) {
- try { return fs.statSync(filePath); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// Validation (inline — no external import needed for self-contained script)
-// ---------------------------------------------------------------------------
-
-const VISUAL_ACTIONS = [
- 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
- 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
-];
-
-// Browser generates ids via crypto.randomUUID().slice(0, 8) (8 hex chars)
-// and variantIds via String(small integer). Restrict to those shapes so
-// any value that reaches a downstream child_process or DOM selector is
-// inert by construction.
-const ID_PATTERN = /^[0-9a-f]{8}$/;
-const VARIANT_ID_PATTERN = /^[0-9]{1,3}$/;
-
-function isValidId(v) { return typeof v === 'string' && ID_PATTERN.test(v); }
-function isValidVariantId(v) { return typeof v === 'string' && VARIANT_ID_PATTERN.test(v); }
-
-function validateEvent(msg) {
- if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
- switch (msg.type) {
- case 'generate':
- if (!isValidId(msg.id)) return 'generate: missing or malformed id';
- if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
- if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
- if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
- // Optional annotation fields (all-or-nothing: if any present, all must be well-formed).
- if (msg.screenshotPath !== undefined && typeof msg.screenshotPath !== 'string') return 'generate: screenshotPath must be string';
- if (msg.comments !== undefined && !Array.isArray(msg.comments)) return 'generate: comments must be array';
- if (msg.strokes !== undefined && !Array.isArray(msg.strokes)) return 'generate: strokes must be array';
- return null;
- case 'accept':
- if (!isValidId(msg.id)) return 'accept: missing or malformed id';
- if (!isValidVariantId(msg.variantId)) return 'accept: missing or malformed variantId';
- if (msg.paramValues !== undefined) {
- if (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues)) {
- return 'accept: paramValues must be an object';
- }
- }
- return null;
- case 'discard':
- return isValidId(msg.id) ? null : 'discard: missing or malformed id';
- case 'checkpoint':
- if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';
- if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';
- if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {
- return 'checkpoint: paramValues must be an object';
- }
- return null;
- case 'exit':
- return null;
- case 'prefetch':
- if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return 'prefetch: missing pageUrl';
- return null;
- default:
- return 'Unknown event type: ' + msg.type;
- }
-}
-
-// ---------------------------------------------------------------------------
-// HTTP request handler
-// ---------------------------------------------------------------------------
-
-function createRequestHandler({ detectScript, sessionPath, livePath }) {
- return (req, res) => {
- const url = new URL(req.url, `http://localhost:${state.port}`);
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
- if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
-
- const p = url.pathname;
-
- // --- Scripts ---
- if (p === '/live.js') {
- // Re-read from disk each request so edits to live-browser.js land on
- // the next tab reload. No-store headers prevent browser caching across
- // sessions — during iteration, a cached old script silently breaks
- // every subsequent session.
- let sessionScript;
- let liveScript;
- try {
- sessionScript = fs.readFileSync(sessionPath, 'utf-8');
- liveScript = fs.readFileSync(livePath, 'utf-8');
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'text/plain' });
- res.end('Error reading live browser scripts: ' + err.message);
- return;
- }
- const body =
- `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
- `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
- sessionScript + '\n' +
- liveScript;
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
- 'Pragma': 'no-cache',
- });
- res.end(body);
- return;
- }
- if (p === '/detect.js' || p === '/') {
- if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
- res.writeHead(200, { 'Content-Type': 'application/javascript' });
- res.end(detectScript);
- return;
- }
-
- // --- Vendored modern-screenshot (UMD build) ---
- // Lazy-loaded by live.js when the user clicks Go; exposes
- // window.modernScreenshot.domToBlob(...) for capture.
- if (p === '/modern-screenshot.js') {
- const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
- try {
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'public, max-age=31536000, immutable',
- });
- res.end(fs.readFileSync(vendorPath));
- } catch {
- res.writeHead(404); res.end('Vendor script not found');
- }
- return;
- }
-
- // --- Annotation upload (browser → server, raw PNG body) ---
- // Client generates the eventId, POSTs the PNG, then POSTs the generate
- // event with screenshotPath already set. Keeps bytes out of the SSE/poll
- // bridge and preserves the "one shot from the user's POV" UX.
- if (p === '/annotation' && req.method === 'POST') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const eventId = url.searchParams.get('eventId');
- if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid eventId' }));
- return;
- }
- if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
- res.writeHead(415, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
- return;
- }
- if (!state.sessionDir) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Session dir unavailable' }));
- return;
- }
- const chunks = [];
- let total = 0;
- let aborted = false;
- req.on('data', (c) => {
- if (aborted) return;
- total += c.length;
- if (total > MAX_ANNOTATION_BYTES) {
- aborted = true;
- res.writeHead(413, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Payload too large' }));
- req.destroy();
- return;
- }
- chunks.push(c);
- });
- req.on('end', () => {
- if (aborted) return;
- const absPath = path.join(state.sessionDir, eventId + '.png');
- try {
- fs.writeFileSync(absPath, Buffer.concat(chunks));
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Write failed: ' + err.message }));
- return;
- }
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true, path: absPath }));
- });
- req.on('error', () => {
- if (!aborted) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Upload failed' }));
- }
- });
- return;
- }
-
- // --- Health ---
- if (p === '/status') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
- const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok',
- port: state.port,
- connectedClients: state.sseClients.size,
- pendingEvents: state.pendingEvents.map((entry) => ({
- id: entry.event?.id,
- type: entry.event?.type,
- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),
- leaseUntil: entry.leaseUntil || null,
- })),
- activeSessions: sessions,
- }));
- return;
- }
-
- if (p === '/health') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok', port: state.port, mode: 'variant',
- hasProjectContext: hasProjectContext(),
- connectedClients: state.sseClients.size,
- }));
- return;
- }
-
- // --- Design system (unified v2 response) + raw ---
- // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json
- // sidecar when present. Panel merges them:
- // { present, parsed, sidecar, hasMd, hasSidecar,
- // mdNewerThanJson, parseError?, sidecarError? }
- // - parsed: output of parseDesignMd (frontmatter
- // + six canonical sections) when DESIGN.md exists.
- // - sidecar: .impeccable/design.json contents when present.
- // Expected shape: schemaVersion 2, carrying
- // extensions + components + narrative.
- // /design-system/raw returns DESIGN.md markdown verbatim
- if (p === '/design-system.json' || p === '/design-system/raw') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
-
- const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
- const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
- const mdStat = statOrNull(mdPath);
- const jsonStat = statOrNull(jsonPath);
-
- if (p === '/design-system/raw') {
- if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
- res.end(fs.readFileSync(mdPath, 'utf-8'));
- return;
- }
-
- if (!mdStat && !jsonStat) {
- res.writeHead(404, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ present: false }));
- return;
- }
-
- const response = {
- present: true,
- hasMd: !!mdStat,
- hasSidecar: !!jsonStat,
- mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
- };
-
- if (mdStat) {
- try {
- response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
- } catch (err) {
- response.parseError = err.message;
- }
- }
-
- if (jsonStat) {
- try {
- response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
- } catch (err) {
- response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;
- }
- }
-
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(response));
- return;
- }
-
- // --- Source file (no-HMR fallback) ---
- if (p === '/source') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const filePath = url.searchParams.get('path');
- if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
- const absPath = path.resolve(process.cwd(), filePath);
- if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
- let content;
- try { content = fs.readFileSync(absPath, 'utf-8'); }
- catch { res.writeHead(404); res.end('File not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
- res.end(content);
- return;
- }
-
- // --- SSE: server→browser push (replaces WebSocket) ---
- if (p === '/events' && req.method === 'GET') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- 'Connection': 'keep-alive',
- });
- res.write('data: ' + JSON.stringify({
- type: 'connected',
- hasProjectContext: hasProjectContext(),
- }) + '\n\n');
-
- state.sseClients.add(res);
- clearTimeout(state.exitTimer);
-
- // Keepalive: SSE comment every 30s prevents silent connection drops.
- const heartbeat = setInterval(() => {
- try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
- }, SSE_HEARTBEAT_INTERVAL);
-
- req.on('close', () => {
- clearInterval(heartbeat);
- state.sseClients.delete(res);
- if (state.sseClients.size === 0) {
- clearTimeout(state.exitTimer);
- state.exitTimer = setTimeout(() => {
- if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
- }, 8000);
- }
- });
- return;
- }
-
- // --- Browser→server events (replaces WebSocket messages) ---
- if (p === '/events' && req.method === 'POST') {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const error = validateEvent(msg);
- if (error) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error }));
- return;
- }
- if (state.sessionStore && msg.id) {
- try {
- state.sessionStore.appendEvent(msg);
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
- return;
- }
- }
- if (msg.type !== 'checkpoint') enqueueEvent(msg);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
- return;
- }
-
- // --- Stop ---
- if (p === '/stop') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.end('stopping');
- shutdown();
- return;
- }
-
- // --- Agent poll ---
- if (p === '/poll' && req.method === 'GET') {
- handlePollGet(req, res, url);
- return;
- }
- if (p === '/poll' && req.method === 'POST') {
- handlePollPost(req, res);
- return;
- }
-
- res.writeHead(404); res.end('Not found');
- };
-}
-
-// ---------------------------------------------------------------------------
-// Agent poll endpoints (unchanged from WS version)
-// ---------------------------------------------------------------------------
-
-function handlePollGet(req, res, url) {
- const token = url.searchParams.get('token');
- if (token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
- const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
- const available = findAvailablePendingEvent();
- if (available) {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(leaseEvent(available, leaseMs)));
- return;
- }
- const poll = { resolve, leaseMs };
- const timer = setTimeout(() => {
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ type: 'timeout' }));
- }, timeout);
- function resolve(event) {
- clearTimeout(timer);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(event));
- }
- state.pendingPolls.push(poll);
- scheduleLeaseFlush();
- req.on('close', () => {
- clearTimeout(timer);
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- });
-}
-
-function handlePollPost(req, res) {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- acknowledgePendingEvent(msg.id);
- if (state.sessionStore && msg.id) {
- try {
- const eventType = msg.type === 'discard' || msg.type === 'discarded'
- ? 'discarded'
- : msg.type === 'complete'
- ? 'complete'
- : msg.type === 'error'
- ? 'agent_error'
- : 'agent_done';
- state.sessionStore.appendEvent({
- type: eventType,
- id: msg.id,
- file: msg.file,
- message: msg.message,
- carbonize: msg.data?.carbonize === true,
- });
- } catch { /* keep reply path best-effort; browser still needs SSE */ }
- }
- flushPendingPolls();
- // Forward the reply to the browser via SSE
- broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Lifecycle
-// ---------------------------------------------------------------------------
-
-let httpServer = null;
-
-function shutdown() {
- removeLiveServerInfo(process.cwd());
- if (state.leaseTimer) clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- if (state.sessionDir) {
- try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}
- }
- for (const res of state.sseClients) { try { res.end(); } catch {} }
- state.sseClients.clear();
- for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });
- state.pendingPolls.length = 0;
- if (httpServer) httpServer.close();
- process.exit(0);
-}
-
-// ---------------------------------------------------------------------------
-// Main
-// ---------------------------------------------------------------------------
-
-const args = process.argv.slice(2);
-
-if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-server.mjs [options]
-
-Start the live variant mode server (zero dependencies).
-
-Commands:
- (default) Start the server (foreground)
- stop Stop the server and remove the injected live.js script tag
- stop --keep-inject Stop the server only (leave the script tag in the HTML entry)
-
-Options:
- --background Start detached, print connection JSON to stdout, then exit
- --port=PORT Use a specific port (default: auto-detect starting at 8400)
- --keep-inject Only with stop: skip live-inject.mjs --remove
- --help Show this help
-
-Endpoints:
- /live.js Browser script (element picker + variant cycling)
- /detect.js Detection overlay (backwards compatible)
- /modern-screenshot.js Vendored modern-screenshot UMD build (lazy-loaded by live.js)
- /annotation POST raw image/png to stage a variant screenshot
- /events SSE stream (server→browser) + POST (browser→server)
- /poll Long-poll for agent CLI
- /source Raw source file reader (no-HMR fallback)
- /status Durable recovery status (token-protected)
- /health Health check`);
- process.exit(0);
-}
-
-if (args.includes('stop')) {
- const keepInject = args.includes('--keep-inject');
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);
- if (res.ok) console.log(`Stopped live server on port ${info.port}.`);
- } catch {
- console.log('No running live server found.');
- }
- if (!keepInject) {
- const injectPath = path.join(__dirname, 'live-inject.mjs');
- try {
- const out = execFileSync(process.execPath, [injectPath, '--remove'], {
- encoding: 'utf-8',
- cwd: process.cwd(),
- });
- const line = out.trim().split('\n').filter(Boolean).pop();
- if (line) {
- try {
- const j = JSON.parse(line);
- if (j.removed === true) {
- console.log(`Removed live script tag from ${j.file}.`);
- }
- } catch {
- /* ignore non-JSON lines */
- }
- }
- } catch (err) {
- const detail = err.stderr?.toString?.().trim?.()
- || err.stdout?.toString?.().trim?.()
- || err.message
- || String(err);
- console.warn(`Note: could not remove live script tag (${detail.split('\n')[0]})`);
- }
- }
- process.exit(0);
-}
-
-// --background: spawn a detached child server, wait for it to be ready,
-// print the connection JSON, then exit. This keeps the startup command
-// simple (no shell backgrounding or chained commands).
-if (args.includes('--background')) {
- const childArgs = args.filter(a => a !== '--background');
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), ...childArgs], {
- detached: true,
- stdio: 'ignore',
- cwd: process.cwd(),
- });
- child.unref();
-
- // Poll for the PID file (the child writes it once the HTTP server is listening).
- const deadline = Date.now() + 10_000;
- while (Date.now() < deadline) {
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- if (info.pid !== process.pid) {
- // Output JSON so the agent can read port + token from stdout.
- console.log(JSON.stringify(info));
- process.exit(0);
- }
- } catch { /* not ready yet */ }
- await new Promise(r => setTimeout(r, 200));
- }
- console.error('Timed out waiting for live server to start.');
- process.exit(1);
-}
-
-// Check for existing session
-const existingRecord = readLiveServerInfo(process.cwd());
-if (existingRecord?.info) {
- const existing = existingRecord.info;
- try {
- process.kill(existing.pid, 0);
- console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
- console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');
- process.exit(1);
- } catch {
- try { fs.unlinkSync(existingRecord.path); } catch {}
- }
-}
-
-state.token = randomUUID();
-state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });
-restorePendingEventsFromStore();
-const portArg = args.find(a => a.startsWith('--port='));
-state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
-// Annotation screenshots live in the project root so the agent's Read tool
-// doesn't trip a per-file permission prompt. Sessioned by token so concurrent
-// projects (or quick restarts) don't collide.
-const annotRoot = getLiveAnnotationsDir(process.cwd());
-fs.mkdirSync(annotRoot, { recursive: true });
-state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));
-
-const { detectScript, sessionPath, livePath } = loadBrowserScripts();
-httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));
-
-httpServer.listen(state.port, '127.0.0.1', () => {
- writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });
- const url = `http://localhost:${state.port}`;
- console.log(`\nImpeccable live server running on ${url}`);
- console.log(`Token: ${state.token}\n`);
- console.log(`Inject: <script src="${url}/live.js"><\/script>`);
- console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
-});
-
-process.on('SIGINT', shutdown);
-process.on('SIGTERM', shutdown);
@@ -1,254 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';
-
-const COMPLETED_PHASES = new Set(['completed', 'discarded']);
-
-export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {
- const rootDir = getLiveSessionsDir(cwd);
- const legacyRootDir = getLegacyLiveSessionsDir(cwd);
- fs.mkdirSync(rootDir, { recursive: true });
- const snapshotCache = new Map();
-
- function loadCachedOrRebuild(id) {
- const cached = snapshotCache.get(id);
- if (cached) return cached;
- const journalPath = getReadableJournalPath(id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- return rebuilt;
- }
-
- function getReadableJournalPath(id) {
- const primary = getJournalPath(rootDir, id);
- if (fs.existsSync(primary)) return primary;
- const legacy = getJournalPath(legacyRootDir, id);
- if (fs.existsSync(legacy)) return legacy;
- return primary;
- }
-
- return {
- rootDir,
- legacyRootDir,
- appendEvent(event) {
- const normalized = normalizeEvent(event, sessionId);
- const journalPath = getJournalPath(rootDir, normalized.id);
- const snapshotPath = getSnapshotPath(rootDir, normalized.id);
- const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);
- if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {
- fs.copyFileSync(legacyJournalPath, journalPath);
- }
- const prior = loadCachedOrRebuild(normalized.id);
- const seq = prior.nextSeq;
- const entry = {
- seq,
- id: normalized.id,
- type: normalized.type,
- ts: new Date().toISOString(),
- event: normalized,
- };
- fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');
- const next = applyEvent(prior.snapshot, entry, prior.diagnostics);
- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });
- writeSnapshot(snapshotPath, next);
- return next;
- },
- getSnapshot(id = sessionId, opts = {}) {
- if (!id) throw new Error('session id required');
- const journalPath = getReadableJournalPath(id);
- const snapshotPath = getSnapshotPath(rootDir, id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- writeSnapshot(snapshotPath, rebuilt.snapshot);
- if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;
- return rebuilt.snapshot;
- },
- listActiveSessions() {
- const ids = new Set();
- for (const dir of [legacyRootDir, rootDir]) {
- if (!fs.existsSync(dir)) continue;
- for (const name of fs.readdirSync(dir)) {
- if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));
- }
- }
- return [...ids]
- .sort()
- .map((id) => this.getSnapshot(id))
- .filter(Boolean);
- },
- };
-}
-
-function normalizeEvent(event, fallbackId) {
- if (!event || typeof event !== 'object') throw new Error('event object required');
- const id = event.id || fallbackId;
- if (!id || typeof id !== 'string') throw new Error('event id required');
- if (!event.type || typeof event.type !== 'string') throw new Error('event type required');
- return { ...event, id };
-}
-
-function getJournalPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.jsonl');
-}
-
-function getSnapshotPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.snapshot.json');
-}
-
-function safeSessionId(id) {
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);
- return id;
-}
-
-function baseSnapshot(id) {
- return {
- id,
- phase: 'new',
- pageUrl: null,
- sourceFile: null,
- expectedVariants: 0,
- arrivedVariants: 0,
- visibleVariant: null,
- paramValues: {},
- pendingEventSeq: null,
- pendingEvent: null,
- deliveryLease: null,
- checkpointRevision: 0,
- activeOwner: null,
- sourceMarkers: {},
- fallbackMode: null,
- annotationArtifacts: [],
- diagnostics: [],
- updatedAt: null,
- };
-}
-
-function rebuildSnapshotFromJournal(journalPath, id) {
- let snapshot = baseSnapshot(id);
- const diagnostics = [];
- let nextSeq = 1;
- if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };
-
- const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- if (!line.trim()) continue;
- try {
- const entry = JSON.parse(line);
- if (!entry || typeof entry !== 'object') throw new Error('entry is not object');
- if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);
- snapshot = applyEvent(snapshot, entry);
- } catch (err) {
- diagnostics.push({
- error: 'journal_parse_failed',
- line: i + 1,
- message: err.message,
- });
- }
- }
- snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];
- return { snapshot, diagnostics, nextSeq };
-}
-
-function applyEvent(snapshot, entry, inheritedDiagnostics = []) {
- const event = entry.event || entry;
- const next = {
- ...snapshot,
- paramValues: { ...(snapshot.paramValues || {}) },
- sourceMarkers: { ...(snapshot.sourceMarkers || {}) },
- annotationArtifacts: [...(snapshot.annotationArtifacts || [])],
- diagnostics: [...(snapshot.diagnostics || [])],
- updatedAt: entry.ts || new Date().toISOString(),
- };
-
- if (inheritedDiagnostics.length && next.diagnostics.length === 0) {
- next.diagnostics = [...inheritedDiagnostics];
- }
-
- switch (event.type) {
- case 'generate':
- next.phase = 'generate_requested';
- next.pageUrl = event.pageUrl ?? next.pageUrl;
- next.expectedVariants = event.count ?? next.expectedVariants;
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });
- break;
- case 'variants_ready':
- case 'agent_done':
- next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';
- next.sourceFile = event.file ?? next.sourceFile;
- next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- if (event.carbonize === true) {
- next.diagnostics.push({
- error: 'carbonize_cleanup_required',
- file: event.file || null,
- message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',
- });
- }
- break;
- case 'checkpoint':
- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {
- next.phase = event.phase ?? next.phase;
- next.checkpointRevision = event.revision ?? next.checkpointRevision;
- next.activeOwner = event.owner ?? next.activeOwner;
- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;
- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- } else {
- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });
- }
- break;
- case 'accept':
- case 'accept_intent':
- next.phase = 'accept_requested';
- next.visibleVariant = Number(event.variantId ?? next.visibleVariant);
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discard':
- next.phase = 'discard_requested';
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discarded':
- next.phase = 'discarded';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'complete':
- next.phase = 'completed';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'agent_error':
- next.phase = 'agent_error';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });
- break;
- default:
- next.diagnostics.push({ error: 'unknown_event_type', type: event.type });
- break;
- }
- return next;
-}
-
-function toPendingEvent(event) {
- const pending = { ...event };
- delete pending.token;
- return pending;
-}
-
-function upsertArtifact(artifacts, artifact) {
- if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {
- artifacts.push(artifact);
- }
-}
-
-function writeSnapshot(snapshotPath, snapshot) {
- fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');
-}
@@ -1,47 +0,0 @@
-#!/usr/bin/env node
-/**
- * Print durable recovery status for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function fetchServerStatus(info) {
- if (!info) return null;
- try {
- const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-export async function statusCli() {
- const info = readServerInfo();
- const server = await fetchServerStatus(info);
- const store = createLiveSessionStore({ cwd: process.cwd() });
- const activeSessions = store.listActiveSessions();
- const payload = {
- liveServer: server ? {
- status: server.status,
- port: server.port,
- connectedClients: server.connectedClients,
- pendingEvents: server.pendingEvents,
- } : null,
- activeSessions: server?.activeSessions || activeSessions,
- recoveryHint: server
- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'
- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',
- };
- console.log(JSON.stringify(payload, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {
- statusCli();
-}
@@ -1,632 +0,0 @@
-/**
- * CLI helper: find an element in source and wrap it in a variant container.
- *
- * Usage:
- * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
- *
- * Searches project files for the element matching the query (class name, ID, or
- * text snippet), wraps it with the variant scaffolding, and prints the file path
- * + line range where the agent should insert variant HTML.
- *
- * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-export async function wrapCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable wrap [options]
-
-Find an element in source and wrap it in a variant container.
-
-Required:
- --id ID Session ID for the variant wrapper
- --count N Number of expected variants (1-8)
-
-Element identification (at least one required):
- --element-id ID HTML id attribute of the element
- --classes A,B,C Comma-separated CSS class names
- --tag TAG Tag name (div, section, etc.)
- --query TEXT Fallback: raw text to search for
-
-Optional:
- --file PATH Source file to search in (skips auto-detection)
- --text TEXT Picked element's textContent. Used to disambiguate when
- classes/tag match multiple sibling elements (e.g. a list
- of <Card>s with the same className). Pass the first ~80
- chars of event.element.textContent.
- --help Show this help message
-
-Output (JSON):
- { file, startLine, endLine, insertLine, commentSyntax }
-
-The agent should insert variant HTML at insertLine.`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const count = parseInt(argVal(args, '--count') || '3');
- const elementId = argVal(args, '--element-id');
- const classes = argVal(args, '--classes');
- const tag = argVal(args, '--tag');
- const query = argVal(args, '--query');
- const filePath = argVal(args, '--file');
- const text = argVal(args, '--text');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!elementId && !classes && !query) {
- console.error('Need at least one of: --element-id, --classes, --query');
- process.exit(1);
- }
-
- // Build search queries in priority order (most specific first)
- const queries = buildSearchQueries(elementId, classes, tag, query);
-
- const genOpts = { cwd: process.cwd() };
-
- // Find the source file. Generated files are excluded from auto-search so we
- // don't silently write variants into a file the next build will wipe.
- let targetFile = filePath;
- let matchedQuery = null;
- if (!targetFile) {
- for (const q of queries) {
- targetFile = findFileWithQuery(q, process.cwd(), genOpts);
- if (targetFile) { matchedQuery = q; break; }
- }
- if (!targetFile) {
- // Nothing in source. Did the element show up in a generated file? That
- // tells the agent "fall back to the agent-driven flow" vs "element just
- // doesn't exist in this project."
- let generatedHit = null;
- for (const q of queries) {
- generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
- if (generatedHit) break;
- }
- if (generatedHit) {
- console.error(JSON.stringify({
- error: 'element_not_in_source',
- fallback: 'agent-driven',
- generatedMatch: path.relative(process.cwd(), generatedHit),
- hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
- }));
- } else {
- console.error(JSON.stringify({
- error: 'element_not_found',
- fallback: 'agent-driven',
- hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
- }));
- }
- process.exit(1);
- }
- } else {
- if (isGeneratedFile(targetFile, genOpts)) {
- console.error(JSON.stringify({
- error: 'file_is_generated',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
- hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- matchedQuery = queries[0];
- }
-
- const content = fs.readFileSync(targetFile, 'utf-8');
- const lines = content.split('\n');
-
- // Find the element, trying each query in priority order. When `--text` is
- // supplied, collect every candidate the queries surface and disambiguate
- // by the picked element's textContent. Without `--text`, fall back to the
- // legacy first-match behavior so unmodified callers keep working.
- let match = null;
- if (text) {
- const candidates = [];
- for (const q of queries) {
- const all = findAllElements(lines, q, tag);
- for (const c of all) {
- if (!candidates.some((x) => x.startLine === c.startLine)) {
- candidates.push(c);
- }
- }
- // Once a more-specific query (ID, full className combo) yielded a unique
- // result, stop — falling through to the loose tag+single-class query
- // would readmit the siblings we just disambiguated past.
- if (candidates.length === 1) break;
- }
- if (candidates.length === 0) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- if (candidates.length === 1) {
- match = candidates[0];
- } else {
- const filtered = filterByText(candidates, lines, text);
- if (filtered.length === 1) {
- match = filtered[0];
- } else if (filtered.length === 0) {
- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the
- // browser-side textContent doesn't appear literally in source. Fall
- // back to first-match rather than refusing — this is the same
- // behavior unmodified callers see, just preserved.
- match = candidates[0];
- } else {
- // Multiple candidates ALSO match the text. Truly ambiguous — refuse
- // rather than pick wrong, and hand the agent the candidate locations
- // so it can disambiguate by reading the file.
- console.error(JSON.stringify({
- error: 'element_ambiguous',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), targetFile),
- candidates: filtered.map((c) => ({
- startLine: c.startLine + 1,
- endLine: c.endLine + 1,
- })),
- hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- }
- } else {
- for (const q of queries) {
- match = findElement(lines, q, tag);
- if (match) break;
- }
- if (!match) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- }
-
- const { startLine, endLine } = match;
- const commentSyntax = detectCommentSyntax(targetFile);
- const styleMode = detectStyleMode(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- const indent = lines[startLine].match(/^(\s*)/)[1];
-
- // Extract the original element. Reindent under the wrapper while preserving
- // the relative depth between lines — `l.trimStart()` would strip ALL leading
- // whitespace and collapse e.g. `<aside>`/` <h1>`/`</aside>` (6/8/6 spaces)
- // to a single uniform indent, so on accept/discard the round-trip restores
- // the inner element at its parent's depth instead of nested inside it.
- // Strip only the COMMON minimum leading whitespace across the picked lines;
- // `deindentContent` on the accept side already mirrors this convention.
- const originalLines = lines.slice(startLine, endLine + 1);
- const originalBaseIndent = minLeadingSpaces(originalLines);
- const reindentOriginal = (extra) => originalLines
- .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
- .join('\n');
- const originalIndented = reindentOriginal(' ');
-
- // Wrapper attributes differ by syntax. HTML allows plain string attrs;
- // JSX requires object-literal style and parses string attrs as HTML (which
- // either type-errors or renders a literal CSS string).
- const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
-
- // JSX/TSX guard: the picked element occupies a single JSX child slot
- // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
- // any other expression position). Replacing it with `comment + <div> +
- // comment` yields three adjacent siblings — invalid JSX. We can't use a
- // Fragment `<></>` either: parents that clone children (Radix `asChild`,
- // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
- // they try to pass an `id` through.
- //
- // Solution: keep the wrapper `<div>` as the single JSX-slot child and
- // tuck both marker comments INSIDE it. accept/discard then expands its
- // replacement range to include the wrapper's `<div>` open / close lines
- // so the entire scaffold gets removed cleanly.
- const wrapperLines = isJsx ? [
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- reindentOriginal(' '),
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- indent + '</div>',
- ] : [
- indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- originalIndented,
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + '</div>',
- indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- ];
-
- // Replace the original element with the wrapper
- const newLines = [
- ...lines.slice(0, startLine),
- ...wrapperLines,
- ...lines.slice(endLine + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- // Calculate insert line (the "insert below this line" comment).
- // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
- // the insert marker (HTML: start-comment + outer-div + Original-comment +
- // original-div + content + close-original-div; JSX: outer-div +
- // start-comment + Original-comment + original-div + content +
- // close-original-div). Multi-line originals push the marker by their
- // extra line count.
- const insertLine = startLine + 6 + (originalLines.length - 1);
-
- console.log(JSON.stringify({
- file: path.relative(process.cwd(), targetFile),
- startLine: startLine + 1, // 1-indexed for the agent
- // wrapperLines is an array but one element (the original-content slot)
- // is a `\n`-joined multi-line string, so the actual file-row count is
- // wrapperLines.length + (originalLines.length - 1). Without the offset,
- // endLine pointed inside the wrapper for any picked element that
- // spanned more than one source line.
- endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexed
- insertLine: insertLine + 1, // 1-indexed: where variants go
- commentSyntax: commentSyntax,
- styleMode: styleMode.mode,
- styleTag: styleMode.styleTag,
- cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
- cssAuthoring: buildCssAuthoring(styleMode, count),
- originalLineCount: originalLines.length,
- }));
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-/**
- * Build search query strings in priority order (most specific first).
- * ID is most reliable, then specific class combos, then single classes, then raw query.
- */
-function buildSearchQueries(elementId, classes, tag, query) {
- const queries = [];
-
- // 1. ID is the most specific
- if (elementId) {
- queries.push('id="' + elementId + '"');
- }
-
- // 2. Full class attribute match (for elements with distinctive multi-class combos).
- // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
- // convention the file uses will match.
- if (classes) {
- const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
- if (classList.length > 1) {
- const joined = classList.join(' ');
- const sorted = [...classList].sort((a, b) => b.length - a.length);
- queries.push('class="' + joined + '"');
- queries.push('className="' + joined + '"');
- queries.push(sorted[0]); // most distinctive single class, fallback
- } else if (classList.length === 1) {
- queries.push(classList[0]);
- }
- }
-
- // 3. Tag + class combo (e.g., <section class="hero">).
- // Same dual-emit for JSX compatibility.
- if (tag && classes) {
- const firstClass = classes.split(',')[0].trim();
- queries.push('<' + tag + ' class="' + firstClass);
- queries.push('<' + tag + ' className="' + firstClass);
- }
-
- // 4. Raw fallback query
- if (query) {
- queries.push(query);
- }
-
- return queries;
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- // HTML, Vue, Svelte, Astro all use HTML comments
- return { open: '<!--', close: '-->' };
-}
-
-function detectStyleMode(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.astro') {
- return {
- mode: 'astro-global-prefixed',
- styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',
- };
- }
- return {
- mode: 'scoped',
- styleTag: '<style data-impeccable-css="SESSION_ID">',
- };
-}
-
-function buildCssSelectorPrefixExamples(styleMode, count) {
- if (styleMode !== 'astro-global-prefixed') return [];
- return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);
-}
-
-function buildCssAuthoring(styleMode, count) {
- const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
- if (styleMode.mode === 'astro-global-prefixed') {
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'global-prefixed',
- rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',
- selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),
- requirements: [
- 'Use the styleTag exactly; the is:inline attribute is required for this file.',
- 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',
- 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
- ],
- forbidden: [
- 'Do not use @scope for this styleMode.',
- ],
- };
- }
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'scope-rule',
- rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',
- selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),
- requirements: [
- 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',
- 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
- 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
- ],
- forbidden: [
- 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',
- 'Do not add is:inline to the style tag for this styleMode.',
- ],
- };
-}
-
-/**
- * Search project files for the query string (class name, ID, etc.)
- * Returns the first matching file path, or null.
- */
-function findFileWithQuery(query, cwd, genOpts = {}) {
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, query, seen, 0, genOpts);
- if (result) return result;
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth, genOpts) {
- if (depth > 5) return null; // don't go too deep
- const realDir = fs.realpathSync(dir);
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- // Check files first
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name).toLowerCase();
- if (!EXTENSIONS.includes(ext)) continue;
-
- const filePath = path.join(dir, entry.name);
- if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip unreadable files */ }
- }
-
- // Then recurse into directories. Always skip node_modules and .git (never
- // project content). dist/build/out are left to the isGeneratedFile guard so
- // the includeGenerated second-pass can still find the element there and
- // report `generatedMatch`.
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
- if (result) return result;
- }
-
- return null;
-}
-
-/**
- * Regex that matches a tag opener on a line. Allows the tag name to be
- * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
- * openers (e.g. `<section\n className="..."\n>`) are recognised.
- */
-const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
-
-/**
- * Find the element's start and end line in the file.
- *
- * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
- * `id="..."`), or a raw text snippet. Because a query can appear on a
- * continuation line of a multi-line tag (e.g. the `className="..."` row of a
- * `<section\n className="..."\n>` JSX tag), we walk backward from the match
- * line to find the actual tag opener. When `tag` is provided, opener candidates
- * must match that tag name.
- */
-/**
- * Return the smallest leading-whitespace count across a set of lines,
- * ignoring blank lines (whose indent isn't load-bearing). Used to compute
- * the common base indent of a multi-line picked element so reindenting
- * under the wrapper preserves the relative depth between lines.
- */
-function minLeadingSpaces(lines) {
- let min = Infinity;
- for (const l of lines) {
- if (l.trim() === '') continue;
- const m = l.match(/^(\s*)/);
- if (m && m[1].length < min) min = m[1].length;
- }
- return min === Infinity ? 0 : min;
-}
-
-function findElement(lines, query, tag = null) {
- // Iterate all matches — the first substring hit isn't always the right one.
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
-
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- // Skip lines already inside a variant wrapper
- if (lines[i].includes('data-impeccable-variant')) continue;
-
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
-
- const endLine = findClosingLine(lines, openerLine);
- return { startLine: openerLine, endLine };
- }
-
- return null;
-}
-
-/**
- * Like findElement, but returns every match. Used for ambiguity detection
- * when the agent passes --text: when the same className appears on multiple
- * sibling elements (a list of cards, repeated section variants, etc.),
- * first-match silently lands on the wrong branch. Returning all matches lets
- * the caller narrow by textContent or fail with a structured ambiguity error.
- */
-function findAllElements(lines, query, tag = null) {
- const out = [];
- const seen = new Set();
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- if (lines[i].includes('data-impeccable-variant')) continue;
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
- if (seen.has(openerLine)) continue; // multiple matches inside the same element
- seen.add(openerLine);
- const endLine = findClosingLine(lines, openerLine);
- out.push({ startLine: openerLine, endLine });
- }
- return out;
-}
-
-/**
- * Narrow a candidate set to those whose source body matches a meaningful
- * prefix of the picked element's textContent. The compare strips tags and
- * JSX expressions, then checks two whitespace normalizations side-by-side:
- *
- * - single-space ("hero two second card body")
- * - no-whitespace ("herotwosecondcardbody")
- *
- * Both are needed because `el.textContent` concatenates sibling text without
- * inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
- * `"Hero TwoSecond…"`), while the source has whitespace between tags. If
- * EITHER normalization matches, the candidate keeps. A snippet shorter than
- * 8 chars after stripping is too weak to disambiguate — the caller falls
- * back to first-match.
- */
-function filterByText(candidates, lines, text) {
- const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
- // Too short to disambiguate. Return [] so the caller's `filtered.length
- // === 0` branch fires (fall back to first-match) — the previous
- // `candidates.slice()` return forced `filtered.length > 1` and surfaced
- // a spurious `element_ambiguous` error on every short-text picker event
- // with multiple candidates.
- if (trimmed.length < 8) return [];
- const targetSpaced = trimmed;
- const targetCompact = trimmed.replace(/\s+/g, '');
-
- return candidates.filter((c) => {
- const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
- const inner = body
- .replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
- .replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
- .toLowerCase();
- const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
- const sourceCompact = inner.replace(/\s+/g, '');
- return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
- });
-}
-
-/**
- * Resolve a match line to the real tag opener. If the match line itself opens
- * a tag, return it. Otherwise walk up to 10 lines backward looking for the
- * first tag opener. If `tag` is specified, the opener must match that tag
- * name; an opener with a different tag name aborts the backward walk for this
- * match (we don't jump across element boundaries).
- *
- * Returns the line index of the opener, or -1 if none can be resolved.
- */
-function findOpenerLine(lines, matchLine, tag) {
- const self = lines[matchLine].match(OPENER_RE);
- if (self) {
- if (!tag || self[1] === tag) return matchLine;
- return -1;
- }
- const MAX_BACKWALK = 10;
- for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
- const opener = lines[i].match(OPENER_RE);
- if (!opener) continue;
- if (!tag || opener[1] === tag) return i;
- // Different tag name than requested — abort; we're inside a non-target opener.
- return -1;
- }
- return -1;
-}
-
-/**
- * Starting from a line with an opening tag, find the line with the matching
- * closing tag by counting tag nesting depth.
- */
-function findClosingLine(lines, start) {
- const openMatch = lines[start].match(OPENER_RE);
- if (!openMatch) return start; // caller passed a non-opener; nothing to span
-
- const tagName = openMatch[1];
- let depth = 0;
- const openRe = new RegExp('<' + tagName + '(?=[\\s/>]|$)', 'g');
- const selfCloseRe = new RegExp('<' + tagName + '[^>]*/>', 'g');
- const closeRe = new RegExp('</' + tagName + '\\s*>', 'g');
-
- for (let i = start; i < lines.length; i++) {
- const line = lines[i];
- const opens = (line.match(openRe) || []).length;
- const selfCloses = (line.match(selfCloseRe) || []).length;
- const closes = (line.match(closeRe) || []).length;
-
- depth += opens - selfCloses - closes;
-
- if (depth <= 0) return i;
- }
-
- // If we can't find the close, return a reasonable guess
- return Math.min(start + 50, lines.length - 1);
-}
-
-// Auto-execute when run directly (node live-wrap.mjs ...)
-const _running = process.argv[1];
-if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {
- wrapCli();
-}
-
-// Test exports (used by tests/live-wrap.test.mjs)
-export { buildSearchQueries, findElement, findClosingLine, detectCommentSyntax };
@@ -1,247 +0,0 @@
-/**
- * CLI entry point: prepare everything needed to enter the live variant poll loop.
- *
- * Does (all in one command):
- * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)
- * 2. Start the live server in the background (or reuse a running one)
- * 3. Inject the browser script tag into the project's entry file
- * 4. Read PRODUCT.md / DESIGN.md for project context
- * 5. Print a single JSON blob with everything the agent needs
- *
- * After this, the agent's only remaining steps are:
- * - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll
- * - Enter the poll loop: `node live-poll.mjs`
- *
- * Usage:
- * node live.mjs # Prepare everything, print JSON, exit
- * node live.mjs --help
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { loadContext } from './load-context.mjs';
-import { resolveFiles } from './live-inject.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-async function liveCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live.mjs
-
-Prepare everything for live variant mode in a single command:
- - Checks .impeccable/live/config.json (required, created once per project)
- - Starts (or reuses) the live server in the background
- - Injects the browser script tag
- - Reads PRODUCT.md / DESIGN.md for project context
-
-On success, prints a JSON blob with:
- { ok, serverPort, serverToken, pageFile, hasContext, context }
-
-On config_missing, prints:
- { ok: false, error: "config_missing", configPath, hint }
-
-The agent should then:
- 1. If config_missing, create the config and re-run this script
- 2. Optionally open the project's dev/preview URL in the browser (see reference/live.md—not serverPort)
- 3. Enter the poll loop: node live-poll.mjs`);
- process.exit(0);
- }
-
- // 1. Check config (fail fast if missing — no point starting anything else)
- const checkOut = runScript('live-inject.mjs', ['--check']);
- const checkResult = safeParse(checkOut);
- if (!checkResult || !checkResult.ok) {
- console.log(JSON.stringify(checkResult || { ok: false, error: 'check_failed', raw: checkOut }));
- process.exit(0);
- }
-
- // 2. Start server (or reuse existing)
- const serverInfo = ensureServerRunning();
- if (!serverInfo) {
- console.log(JSON.stringify({ ok: false, error: 'server_start_failed' }));
- process.exit(1);
- }
-
- // 3. Inject the script tag at the current port
- const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)]);
- const injectResult = safeParse(injectOut);
- if (!injectResult || !injectResult.ok) {
- console.log(JSON.stringify({
- ok: false,
- error: 'inject_failed',
- detail: injectResult || injectOut,
- serverPort: serverInfo.port,
- }));
- process.exit(1);
- }
-
- // 4. Load PRODUCT.md + DESIGN.md context (auto-migrates legacy .impeccable.md)
- const ctx = loadContext(process.cwd());
-
- // 5. Compute drift-heal: compare resolved inject targets against the
- // project's HTML files. Orphans are HTML files not covered by config.
- // Warning only — the agent decides whether to act.
- const resolvedFiles = resolveFiles(process.cwd(), checkResult.config);
- const drift = scanForDrift(process.cwd(), resolvedFiles, checkResult.config);
-
- // 6. Emit everything the agent needs
- console.log(JSON.stringify({
- ok: true,
- serverPort: serverInfo.port,
- serverToken: serverInfo.token,
- pageFiles: resolvedFiles,
- configDrift: drift,
- hasProduct: ctx.hasProduct,
- product: ctx.product,
- productPath: ctx.productPath,
- hasDesign: ctx.hasDesign,
- design: ctx.design,
- designPath: ctx.designPath,
- migrated: ctx.migrated,
- }, null, 2));
-}
-
-/**
- * Drift-heal scan. Walks the project for HTML files under common
- * page-source directories (public/, src/, app/, pages/) and reports any
- * that aren't covered by the resolved inject targets. This is purely
- * advisory — the agent can ignore it, or suggest the user add the
- * orphans to config.files.
- *
- * Skipped if config.files already contains at least one glob pattern
- * covering everything in practice (signaled by the orphan count being 0).
- */
-function scanForDrift(rootDir, resolvedFiles, config) {
- const SCAN_ROOTS = ['public', 'src', 'app', 'pages'];
- const IGNORE_DIRS = new Set([
- 'node_modules', '.git', '.next', '.nuxt', '.svelte-kit', '.astro',
- '.turbo', '.vercel', '.cache', 'coverage', 'dist', 'build',
- ]);
-
- const resolvedSet = new Set(resolvedFiles.map((f) => f.split(path.sep).join('/')));
-
- // Files matching the user's `exclude` globs are intentional omissions,
- // not drift. Compile them to regexes so the orphan list stays signal.
- const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
- .map((p) => globToRegex(p));
- const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
-
- const orphans = [];
-
- const walk = (dir, relBase) => {
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
- for (const e of entries) {
- const rel = relBase ? `${relBase}/${e.name}` : e.name;
- if (e.isDirectory()) {
- if (IGNORE_DIRS.has(e.name) || e.name.startsWith('.')) continue;
- walk(path.join(dir, e.name), rel);
- } else if (e.isFile() && e.name.endsWith('.html')) {
- if (resolvedSet.has(rel)) continue;
- if (isUserExcluded(rel)) continue;
- orphans.push(rel);
- }
- }
- };
-
- for (const root of SCAN_ROOTS) {
- const abs = path.join(rootDir, root);
- if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
- walk(abs, root);
- }
- }
-
- if (orphans.length === 0) return null;
- const capped = orphans.slice(0, 20);
- return {
- orphans: capped,
- orphanCount: orphans.length,
- hint: `${orphans.length} HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like "public/**/*.html".`,
- };
-}
-
-/**
- * Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
- * to avoid a circular import (live-inject.mjs already imports nothing
- * from live.mjs). The two must stay in sync.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
- else { re += '.*'; i += 2; }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function runScript(name, args) {
- const scriptPath = path.join(__dirname, name);
- const cmd = `node "${scriptPath}" ${args.map(a => `"${a}"`).join(' ')}`;
- try {
- return execSync(cmd, { encoding: 'utf-8', cwd: process.cwd(), timeout: 15_000 });
- } catch (err) {
- // execSync throws on non-zero exit; return stdout if any
- return err.stdout || err.message || '';
- }
-}
-
-function safeParse(out) {
- try { return JSON.parse(String(out).trim()); } catch { return null; }
-}
-
-/**
- * Return { pid, port, token } for the running live server, starting one if needed.
- */
-function ensureServerRunning() {
- // Try to reuse an existing server
- try {
- const existing = readLiveServerInfo(process.cwd())?.info;
- if (existing && existing.pid) {
- try {
- process.kill(existing.pid, 0); // throws if dead
- return existing;
- } catch { /* stale PID file — the server script will clean it up */ }
- }
- } catch { /* no PID file */ }
-
- // Start a new server
- const out = runScript('live-server.mjs', ['--background']);
- return safeParse(out);
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live.mjs') || _running?.endsWith('live.mjs/')) {
- liveCli();
-}
@@ -1,141 +0,0 @@
-/**
- * Shared context loader for every impeccable command that needs to know
- * "who is this for" and "what does this look like".
- *
- * Input: project root (process.cwd()).
- *
- * Output (JSON to stdout):
- * {
- * hasProduct: boolean, // PRODUCT.md found (or auto-migrated)
- * product: string | null, // PRODUCT.md contents
- * productPath: string | null, // relative path
- * hasDesign: boolean, // DESIGN.md found
- * design: string | null, // DESIGN.md contents
- * designPath: string | null,
- * migrated: boolean, // true if we auto-renamed .impeccable.md -> PRODUCT.md
- * contextDir: string, // absolute path of the directory the files were found in
- * }
- *
- * Filename matching is case-insensitive for PRODUCT.md and DESIGN.md. The
- * Google DESIGN.md convention is uppercase at repo root; Kiro-style and
- * lowercase variants are also matched so users don't get punished for case.
- *
- * Lookup directory resolution (first match wins):
- * 1. process.env.IMPECCABLE_CONTEXT_DIR (absolute or relative to cwd)
- * 2. cwd, if PRODUCT.md / DESIGN.md / .impeccable.md is there (back-compat)
- * 3. Auto-fallback subdirectories of cwd: .agents/context/, then docs/
- * 4. cwd as a default "no context found" location
- *
- * Legacy `.impeccable.md` -> PRODUCT.md migration only fires at cwd root;
- * fallback directories are read-only as far as auto-rename is concerned.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
-const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
-const LEGACY_NAMES = ['.impeccable.md'];
-const FALLBACK_DIRS = ['.agents/context', 'docs'];
-
-/**
- * Resolve the directory that holds PRODUCT.md / DESIGN.md for
- * this project. Exported so other scripts (e.g. live-server.mjs) can read the
- * design files from the same location the loader uses.
- */
-export function resolveContextDir(cwd = process.cwd()) {
- // 1. Explicit override
- const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
- if (envDir && envDir.trim()) {
- const trimmed = envDir.trim();
- return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- }
-
- // 2. cwd wins if any canonical or legacy file is there. We check legacy too
- // so the auto-migration path in loadContext stays predictable.
- if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES, ...LEGACY_NAMES])) {
- return cwd;
- }
-
- // 3. Auto-fallback subdirs. Match if PRODUCT.md or DESIGN.md is present;
- // legacy `.impeccable.md` does not pull the lookup into a fallback dir.
- for (const rel of FALLBACK_DIRS) {
- const candidate = path.resolve(cwd, rel);
- if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
- return candidate;
- }
- }
-
- // 4. Nothing found — keep the historical "default to cwd" behaviour so the
- // caller's `hasProduct === false` branch still fires the same way.
- return cwd;
-}
-
-export function loadContext(cwd = process.cwd()) {
- let migrated = false;
- const contextDir = resolveContextDir(cwd);
-
- // 1. Look for PRODUCT.md (case-insensitive) in the resolved dir
- let productPath = firstExisting(contextDir, PRODUCT_NAMES);
-
- // 2. Legacy: if no PRODUCT.md but .impeccable.md exists at cwd root, rename
- // it in place. We only migrate at the root — fallback dirs are read-only
- // so we don't surprise users by mutating files under docs/ or .agents/.
- if (!productPath && contextDir === cwd) {
- const legacyPath = firstExisting(cwd, LEGACY_NAMES);
- if (legacyPath) {
- const newPath = path.join(cwd, 'PRODUCT.md');
- try {
- fs.renameSync(legacyPath, newPath);
- productPath = newPath;
- migrated = true;
- } catch {
- // Rename failed (permissions, etc.) — fall back to reading legacy in place
- productPath = legacyPath;
- }
- }
- }
-
- // 3. DESIGN.md (case-insensitive)
- const designPath = firstExisting(contextDir, DESIGN_NAMES);
-
- const product = productPath ? safeRead(productPath) : null;
- const design = designPath ? safeRead(designPath) : null;
-
- return {
- hasProduct: !!product,
- product,
- productPath: productPath ? path.relative(cwd, productPath) : null,
- hasDesign: !!design,
- design,
- designPath: designPath ? path.relative(cwd, designPath) : null,
- migrated,
- contextDir,
- };
-}
-
-function firstExisting(dir, names) {
- for (const name of names) {
- const abs = path.join(dir, name);
- if (fs.existsSync(abs)) return abs;
- }
- return null;
-}
-
-function safeRead(p) {
- try { return fs.readFileSync(p, 'utf-8'); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// CLI mode — print the context as JSON
-// ---------------------------------------------------------------------------
-
-function cli() {
- const result = loadContext(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('load-context.mjs') || _running?.endsWith('load-context.mjs/')) {
- cli();
-}
@@ -1,14 +0,0 @@
@@ -1,214 +0,0 @@
-#!/usr/bin/env node
-/**
- * Pin/unpin sub-commands as standalone skill shortcuts.
- *
- * Usage:
- * node <scripts_path>/pin.mjs pin <command>
- * node <scripts_path>/pin.mjs unpin <command>
- *
- * `pin audit` creates a lightweight /audit skill that redirects to /impeccable audit.
- * `unpin audit` removes that shortcut.
- *
- * The script discovers harness directories (.claude/skills, .cursor/skills, etc.)
- * in the project root and creates/removes the pin in all of them.
- */
-
-import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
-import { join, resolve, dirname } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-// All known harness directories
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Valid sub-command names
-const VALID_COMMANDS = [
- 'craft', 'teach', 'extract', 'document', 'shape',
- 'critique', 'audit',
- 'polish', 'bolder', 'quieter', 'distill', 'harden', 'onboard', 'live',
- 'animate', 'colorize', 'typeset', 'layout', 'delight', 'overdrive',
- 'clarify', 'adapt', 'optimize',
-];
-
-// Marker to identify pinned skills (so unpin doesn't delete user skills)
-const PIN_MARKER = '<!-- impeccable-pinned-skill -->';
-
-/**
- * Walk up from startDir to find a project root.
- */
-function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- while (dir !== '/') {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Find harness skill directories that have an impeccable skill installed.
- */
-function findHarnessDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const skillsDir = join(projectRoot, harness, 'skills');
- // Only pin in harness dirs that already have impeccable installed
- const impeccableDir = join(skillsDir, 'impeccable');
- if (existsSync(impeccableDir) || existsSync(join(skillsDir, 'i-impeccable'))) {
- dirs.push(skillsDir);
- }
- }
- return dirs;
-}
-
-/**
- * Load command metadata (descriptions for pinned skills).
- */
-function loadCommandMetadata() {
- const metadataPath = join(__dirname, 'command-metadata.json');
- if (existsSync(metadataPath)) {
- return JSON.parse(readFileSync(metadataPath, 'utf-8'));
- }
- return {};
-}
-
-/**
- * Generate a pinned skill's SKILL.md content.
- */
-function generatePinnedSkill(command, metadata) {
- const desc = metadata[command]?.description || `Shortcut for /impeccable ${command}.`;
- const hint = metadata[command]?.argumentHint || '[target]';
-
- return `---
-name: ${command}
-description: "${desc}"
-argument-hint: "${hint}"
-user-invocable: true
----
-
-${PIN_MARKER}
-
-This is a pinned shortcut for \`{{command_prefix}}impeccable ${command}\`.
-
-Invoke {{command_prefix}}impeccable ${command}, passing along any arguments provided here, and follow its instructions.
-`;
-}
-
-/**
- * Pin a command: create shortcut skill in all harness dirs.
- */
-function pin(command, projectRoot) {
- const metadata = loadCommandMetadata();
- const harnessDirs = findHarnessDirs(projectRoot);
-
- if (harnessDirs.length === 0) {
- console.log('No harness directories with impeccable installed found.');
- return false;
- }
-
- const content = generatePinnedSkill(command, metadata);
- let created = 0;
-
- for (const skillsDir of harnessDirs) {
- // Check if skill already exists (and isn't a pin)
- const skillDir = join(skillsDir, command);
- if (existsSync(skillDir)) {
- const existingMd = join(skillDir, 'SKILL.md');
- if (existsSync(existingMd)) {
- const existing = readFileSync(existingMd, 'utf-8');
- if (!existing.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (non-pinned skill already exists)`);
- continue;
- }
- }
- }
-
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(join(skillDir, 'SKILL.md'), content, 'utf-8');
- console.log(` + ${skillDir}`);
- created++;
- }
-
- if (created > 0) {
- console.log(`\nPinned '${command}' as a standalone shortcut in ${created} location(s).`);
- console.log(`You can now use /${command} directly.`);
- }
-
- return created > 0;
-}
-
-/**
- * Unpin a command: remove shortcut skill from all harness dirs.
- */
-function unpin(command, projectRoot) {
- const harnessDirs = findHarnessDirs(projectRoot);
- let removed = 0;
-
- for (const skillsDir of harnessDirs) {
- const skillDir = join(skillsDir, command);
- if (!existsSync(skillDir)) continue;
-
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) continue;
-
- // Safety: only remove if it's a pinned skill
- const content = readFileSync(skillMd, 'utf-8');
- if (!content.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (not a pinned skill)`);
- continue;
- }
-
- rmSync(skillDir, { recursive: true, force: true });
- console.log(` - ${skillDir}`);
- removed++;
- }
-
- if (removed > 0) {
- console.log(`\nUnpinned '${command}' from ${removed} location(s).`);
- console.log(`Use /impeccable ${command} to access it.`);
- } else {
- console.log(`No pinned '${command}' shortcut found.`);
- }
-
- return removed > 0;
-}
-
-// --- CLI ---
-const [,, action, command] = process.argv;
-
-if (!action || !command) {
- console.log('Usage: node pin.mjs <pin|unpin> <command>');
- console.log(`\nAvailable commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-if (action !== 'pin' && action !== 'unpin') {
- console.error(`Unknown action: ${action}. Use 'pin' or 'unpin'.`);
- process.exit(1);
-}
-
-if (!VALID_COMMANDS.includes(command)) {
- console.error(`Unknown command: ${command}`);
- console.error(`Available commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-const root = findProjectRoot();
-
-if (action === 'pin') {
- pin(command, root);
-} else {
- unpin(command, root);
-}
@@ -1,41 +0,0 @@
-name: CI
-
-on:
- push:
- branches: [main]
- pull_request:
- branches: [main]
-
-jobs:
- test:
- runs-on: ubuntu-latest
-
- steps:
- - name: Checkout repository
- uses: actions/checkout@v4
-
- - name: Setup Node
- uses: actions/setup-node@v4
- with:
- node-version: 22
-
- - name: Setup Bun
- uses: oven-sh/setup-bun@v2
- with:
- bun-version: latest
-
- - name: Install dependencies
- run: bun install
-
- - name: Run tests
- run: bun run test
-
- - name: Build
- run: bun run build
-
- - name: Upload build artifacts
- uses: actions/upload-artifact@v4
- with:
- name: impeccable-dist
- path: dist/
- retention-days: 7
@@ -1,105 +0,0 @@
-# Dependencies
-node_modules/
-
-# npm lockfile (project uses bun.lock; npm may regenerate this as a side
-# effect of npm subprocesses, but it should not be tracked)
-package-lock.json
-
-# Generated files
-dist/
-build/
-
-# Test fixtures simulate "generated dist" trees; keep them tracked so tests
-# can copy them into tmp git repos and assert is-generated behavior.
-!tests/framework-fixtures/**/dist/
-!tests/framework-fixtures/**/dist/**
-
-# Build artifacts
-*.log
-
-# OS files
-.DS_Store
-Thumbs.db
-
-# IDE
-.vscode/
-.idea/
-
-# Claude Code local state
-.claude/projects/
-.claude/scheduled_tasks.lock
-.claude/settings.local.json
-
-# Environment
-.env
-.env.local
-
-# Cloudflare
-.wrangler/
-
-# Impeccable-owned project files are split: generated sidecars/config may be
-# tracked, but runtime recovery state and local assets should stay local.
-.impeccable/live/server.json
-.impeccable/live/sessions/
-.impeccable/live/annotations/
-.impeccable/live/cache/
-.impeccable/history/
-# Per-run critique snapshots are local artifacts. ignore.md (also under
-# this dir) carries deferrals the user may want to share, so it's
-# explicitly re-included below.
-.impeccable/critique/
-!.impeccable/critique/ignore.md
-
-# Legacy live mode session file + annotation screenshots
-.impeccable-live.json
-.impeccable-live/
-
-# Legacy per-project live mode injection config. New installs use
-# .impeccable/live/config.json in the project root instead.
-**/skills/impeccable/scripts/config.json
-
-# Extension build artifacts
-extension/detector/
-
-# Legacy design context (pre-v3.1, auto-migrated to PRODUCT.md by load-context.mjs)
-.impeccable.md
-# Note: PRODUCT.md and DESIGN.md are INTENTIONALLY tracked in this repo —
-# they serve as reference implementations for users installing impeccable.
-# Users of impeccable in their own projects can choose whether to track them.
-
-# Evals (private, commercial)
-evals/
-tests/evals-v2/
-
-# Video backlog & scripts (local working files, not for distribution)
-videos/
-
-# Talk decks & speaker materials (local working files, not for distribution)
-talks/
-
-# Generated sub-pages (legacy, now replaced by Astro content collections)
-site/public/docs/
-site/public/anti-patterns/
-site/public/tutorials/
-site/public/visual-mode/
-site/public/slop/
-
-# Build artifacts written to site/public/ so Astro copies them to build/
-site/public/_data/
-site/public/_headers
-site/public/_redirects
-site/public/_routes.json
-site/public/js/detect-antipatterns-browser.js
-site/public/js/generated/
-
-# Note: harness skill directories (.claude/skills/, .cursor/skills/, etc.)
-# are intentionally tracked. npx skills reads them from this repo at install
-# time, and they enable clean submodule use. Run `bun run build` to refresh
-# them after editing skill/.
-#
-# Codex CLI consumes `.agents/skills/`; native custom agents live under
-# `.codex/agents/`. Keep only those agent definitions tracked.
-.codex/*
-!.codex/agents/
-!.codex/agents/**
-.astro/
@@ -1,281 +0,0 @@
-{
- "schemaVersion": 2,
- "generatedAt": "2026-04-23T00:00:00Z",
- "title": "Design System: Impeccable",
- "extensions": {
- "colorMeta": {
- "editorial-magenta": {
- "role": "primary",
- "displayName": "Editorial Magenta",
- "description": "The one vibrant voice. Primary CTAs, active navigation, live-state indicators. Rarity is the design choice.",
- "tonalRamp": [
- "oklch(22% 0.12 350)",
- "oklch(32% 0.18 350)",
- "oklch(42% 0.22 350)",
- "oklch(52% 0.25 350)",
- "oklch(60% 0.25 350)",
- "oklch(72% 0.18 350)",
- "oklch(84% 0.10 350)",
- "oklch(94% 0.04 350)"
- ]
- },
- "editorial-magenta-deep": {
- "role": "accent",
- "displayName": "Editorial Magenta Deep",
- "description": "Hover/active state for Editorial Magenta. Small darkening, confirms interaction without shouting."
- },
- "warm-ash-cream": {
- "role": "neutral",
- "displayName": "Warm Ash Cream",
- "description": "Primary page background. Almost-imperceptible magenta tint that creates subconscious cohesion with the accent.",
- "tonalRamp": [
- "oklch(15% 0.005 350)",
- "oklch(25% 0.005 350)",
- "oklch(40% 0.005 350)",
- "oklch(55% 0.005 350)",
- "oklch(70% 0.005 350)",
- "oklch(82% 0.005 350)",
- "oklch(92% 0.005 350)",
- "oklch(96% 0.005 350)"
- ]
- },
- "crisp-paper-white": {
- "role": "neutral",
- "displayName": "Crisp Paper White",
- "description": "Pure background for inverted text moments (white-on-dark CTAs) and maximum-contrast surfaces."
- },
- "deep-graphite": {
- "role": "neutral",
- "displayName": "Deep Graphite",
- "description": "Primary text and primary-CTA background. Softer than pure black, reads as confident-but-not-aggressive on warm paper.",
- "tonalRamp": [
- "oklch(10% 0 0)",
- "oklch(25% 0 0)",
- "oklch(40% 0 0)",
- "oklch(55% 0 0)",
- "oklch(70% 0 0)",
- "oklch(85% 0 0)",
- "oklch(92% 0 0)",
- "oklch(98% 0 0)"
- ]
- },
- "soft-charcoal": {
- "role": "neutral",
- "displayName": "Soft Charcoal",
- "description": "Secondary text — taglines, hook paragraphs, supporting copy."
- },
- "mid-ash": {
- "role": "neutral",
- "displayName": "Mid Ash",
- "description": "Tertiary text — micro-labels, captions, meta lines. Reads as intentionally recessed metadata."
- },
- "paper-mist": {
- "role": "neutral",
- "displayName": "Paper Mist",
- "description": "Hairline borders, section dividers, barely-visible structural seams."
- },
- "magenta-whisper": {
- "role": "accent",
- "displayName": "Magenta Whisper",
- "description": "Diffuse glow backdrop under accent elements on hover; subtle selection highlights."
- },
- "magenta-veil": {
- "role": "accent",
- "displayName": "Magenta Veil",
- "description": "Stronger translucent tint for focus rings and emphasis shells."
- }
- },
- "typographyMeta": {
- "display": {
- "displayName": "Display",
- "purpose": "Hero title only. Light italic for an author-signature feel.",
- "style": "italic"
- },
- "headline": {
- "displayName": "Headline",
- "purpose": "Section headings. Larger editorial moments."
- },
- "title": {
- "displayName": "Title",
- "purpose": "Hero tagline / section leads. A quieter second display voice.",
- "style": "italic"
- },
- "body": {
- "displayName": "Body",
- "purpose": "Paragraph copy. Capped at 65–75ch for readability."
- },
- "body-lead": {
- "displayName": "Body Lead",
- "purpose": "The one or two lead paragraphs on each page. Slightly relaxed leading."
- },
- "supporting": {
- "displayName": "Supporting",
- "purpose": "Captions, footnotes, supporting context."
- },
- "label": {
- "displayName": "Label",
- "purpose": "CTA labels. Short, declarative. Uppercase, letter-tracked."
- },
- "micro-label": {
- "displayName": "Micro-Label",
- "purpose": "\"Works with\", \"What's included\", \"v3.0 Changelog\"."
- },
- "mono": {
- "displayName": "Monospace Meta",
- "purpose": "Command names in inline prose, periodic-table tile labels."
- }
- },
- "shadows": [
- {
- "name": "Soft Hover Lift",
- "value": "0 4px 24px -4px rgba(0,0,0,0.12), 0 1px 3px rgba(0,0,0,0.06)",
- "purpose": "Default hover response on cards and interactive surfaces."
- },
- {
- "name": "Lifted Card",
- "value": "0 20px 40px rgba(0,0,0,0.08)",
- "purpose": "Deliberately elevated content (featured cards, install blocks)."
- },
- {
- "name": "Accent Glow",
- "value": "0 20px 60px oklch(60% 0.25 350 / 0.15)",
- "purpose": "Magenta-tinted ambient shadow under the rare magnetic moment. Used sparingly."
- }
- ],
- "motion": [
- {
- "name": "ease-out",
- "value": "cubic-bezier(0.16, 1, 0.3, 1)",
- "purpose": "Primary curve. Expo-out feel — objects decelerate smoothly."
- },
- {
- "name": "ease-out-quint",
- "value": "cubic-bezier(0.22, 1, 0.36, 1)",
- "purpose": "Slightly sharper alternative. Use for transforms on compact elements."
- },
- {
- "name": "duration-fast",
- "value": "0.15s",
- "purpose": "State transitions (color, opacity)."
- },
- {
- "name": "duration-base",
- "value": "0.3s",
- "purpose": "Default for transforms and non-color changes."
- },
- {
- "name": "duration-slow",
- "value": "0.6s",
- "purpose": "Orchestrated entrances."
- }
- ],
- "breakpoints": []
- },
- "components": [
- {
- "name": "Primary CTA",
- "kind": "button",
- "refersTo": "button-primary",
- "description": "Sharp, squared, uppercase. The editorial signature.",
- "html": "<button class=\"ds-btn-primary\">GET STARTED</button>",
- "css": ".ds-btn-primary { display: inline-block; padding: 16px 48px; font-family: 'Instrument Sans', system-ui, sans-serif; font-size: 0.9rem; font-weight: 500; letter-spacing: 0.05em; text-transform: uppercase; color: oklch(98% 0 0); background: oklch(10% 0 0); border: none; border-radius: 0; cursor: pointer; transition: transform 0.2s ease, background 0.2s ease; } .ds-btn-primary:hover { transform: translateY(-2px); background: oklch(60% 0.25 350); }"
- },
- {
- "name": "Inline Text Link",
- "kind": "button",
- "description": "Secondary action. No boxed secondary button exists in the system.",
- "html": "<a href=\"#\" class=\"ds-link\">Read the docs</a>",
- "css": ".ds-link { color: oklch(10% 0 0); font-family: 'Instrument Sans', system-ui, sans-serif; font-weight: 500; text-decoration: underline; text-underline-offset: 3px; text-decoration-thickness: 1px; transition: color 0.2s ease; } .ds-link:hover { color: oklch(60% 0.25 350); }"
- },
- {
- "name": "Email Input",
- "kind": "input",
- "refersTo": "input-text",
- "description": "Hairline border, transparent background, magenta focus glow.",
- "html": "<input type=\"email\" class=\"ds-input-email\" placeholder=\"you@example.com\">",
- "css": ".ds-input-email { width: 100%; padding: 10px 14px; font-family: 'Instrument Sans', system-ui, sans-serif; font-size: 0.9rem; color: oklch(10% 0 0); background: transparent; border: 1px solid oklch(92% 0 0); border-radius: 6px; outline: none; transition: border-color 0.15s ease, box-shadow 0.15s ease; } .ds-input-email::placeholder { color: oklch(55% 0 0); } .ds-input-email:focus { border-color: oklch(60% 0.25 350); box-shadow: 0 0 0 3px oklch(60% 0.25 350 / 0.15); }"
- },
- {
- "name": "Micro-Label",
- "kind": "chip",
- "description": "'What's included' style. Uppercase mono, wide tracking.",
- "html": "<span class=\"ds-microlabel\">What's included</span>",
- "css": ".ds-microlabel { display: inline-block; font-family: 'Space Grotesk', ui-monospace, monospace; font-size: 0.6875rem; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: oklch(55% 0 0); }"
- },
- {
- "name": "Site Navigation",
- "kind": "nav",
- "refersTo": "nav-link",
- "description": "62px compact bar. No underline at rest; accent underline on active.",
- "html": "<nav class=\"ds-nav\"><span class=\"ds-nav-brand\">/ Impeccable</span><div class=\"ds-nav-links\"><a href=\"#\" class=\"ds-nav-link ds-nav-active\">Home</a><a href=\"#\" class=\"ds-nav-link\">Docs</a><a href=\"#\" class=\"ds-nav-link\">Anti-patterns</a></div></nav>",
- "css": ".ds-nav { display: flex; align-items: center; justify-content: space-between; gap: 24px; padding: 12px 20px; background: oklch(96% 0.005 350); font-family: 'Instrument Sans', system-ui, sans-serif; } .ds-nav-brand { font-family: 'Cormorant Garamond', Georgia, serif; font-style: italic; font-size: 1.05rem; color: oklch(10% 0 0); } .ds-nav-links { display: flex; gap: 16px; } .ds-nav-link { font-size: 0.85rem; font-weight: 500; color: oklch(10% 0 0); text-decoration: none; padding-bottom: 3px; border-bottom: 1px solid transparent; transition: color 0.2s ease, border-color 0.2s ease; } .ds-nav-link:hover { color: oklch(60% 0.25 350); } .ds-nav-active { border-bottom-color: oklch(60% 0.25 350); }"
- },
- {
- "name": "Feature Card",
- "kind": "card",
- "refersTo": "card-feature",
- "description": "Standard card: 12px radius, hairline border, hover lift with soft shadow.",
- "html": "<article class=\"ds-card\"><h3 class=\"ds-card-title\">/impeccable polish</h3><p class=\"ds-card-body\">Sweep a site for AI-tool tells and refine typography, spacing, color in one pass.</p></article>",
- "css": ".ds-card { padding: 20px 22px; background: oklch(98% 0 0); border: 1px solid oklch(92% 0 0); border-radius: 12px; transition: transform 0.2s ease, box-shadow 0.2s ease; font-family: 'Instrument Sans', system-ui, sans-serif; } .ds-card:hover { transform: translateY(-2px); box-shadow: 0 4px 24px -4px rgba(0,0,0,0.12), 0 1px 3px rgba(0,0,0,0.06); } .ds-card-title { font-family: 'Space Grotesk', ui-monospace, monospace; font-size: 0.85rem; font-weight: 500; color: oklch(10% 0 0); margin: 0 0 6px; } .ds-card-body { font-size: 0.85rem; line-height: 1.55; color: oklch(25% 0 0); margin: 0; }"
- },
- {
- "name": "Command Category Tile",
- "kind": "custom",
- "description": "Signature component: periodic-table tile used in the commands visualization.",
- "html": "<div class=\"ds-tile\"><span class=\"ds-tile-num\">07</span><span class=\"ds-tile-sym\">Po</span><span class=\"ds-tile-lbl\">polish</span></div>",
- "css": ".ds-tile { display: grid; grid-template-rows: auto 1fr auto; align-items: center; justify-items: center; width: 56px; height: 64px; padding: 4px; background: #fdf2f8; border: 1px solid #ec4899; border-radius: 6px; color: #be185d; cursor: pointer; transition: transform 0.2s ease, box-shadow 0.2s ease; } .ds-tile:hover { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(236, 72, 153, 0.18); } .ds-tile-num { font-family: 'Space Grotesk', ui-monospace, monospace; font-size: 7px; font-weight: 500; letter-spacing: 0.05em; justify-self: start; } .ds-tile-sym { font-family: 'Cormorant Garamond', Georgia, serif; font-style: italic; font-size: 20px; font-weight: 500; line-height: 1; } .ds-tile-lbl { font-family: 'Space Grotesk', ui-monospace, monospace; font-size: 7px; font-weight: 500; letter-spacing: 0.05em; text-transform: lowercase; }"
- }
- ],
- "narrative": {
- "northStar": "The Editorial Sanctuary",
- "overview": "The Impeccable site reads more like a printed design publication than a SaaS landing page. Committed typography, generous breathing room, a single decisive accent. The aesthetic philosophy is restraint in service of craft. Every element earns its place.",
- "keyCharacteristics": [
- "Warm off-white paper tones with an almost-imperceptible magenta tint.",
- "A single decisive magenta accent used on ≤10% of any screen.",
- "Italic serif for display type; clean neutral sans for body at 1.6 line-height.",
- "Sharp, uppercase, letter-tracked primary CTAs.",
- "Flat surfaces at rest. Shadows appear only on state change.",
- "Magazine-scale spacing (8 / 16 / 24 / 32 / 48 / 80 / 120px)."
- ],
- "rules": [
- { "name": "The One Voice Rule", "section": "colors", "body": "Editorial Magenta is the only vibrant color. No supporting accent, ever. If a second emphasis point is needed, use scale or weight, never a second hue." },
- { "name": "The Paper-Not-White Rule", "section": "colors", "body": "Page background is Warm Ash Cream, never Crisp Paper White. Warmth is load-bearing." },
- { "name": "The OKLCH-Only Rule", "section": "colors", "body": "All new colors declared in OKLCH. Hex is reserved for the fenced Command Category Tints." },
- { "name": "The Italic-Is-Voice Rule", "section": "typography", "body": "Italic is a voice choice for display type, not emphasis inside body copy. Body emphasis is carried by weight." },
- { "name": "The 1.6 Leading Rule", "section": "typography", "body": "Body line-height is 1.6 everywhere. Not 1.5, not 1.7. This is the load-bearing readability decision." },
- { "name": "The Fluid-Headlines-Only Rule", "section": "typography", "body": "Headings use clamp() fluid sizing. Body copy uses fixed rem values." },
- { "name": "The Flat-By-Default Rule", "section": "elevation", "body": "Surfaces are flat at rest. Reach for shadows only on hover or deliberate elevation." },
- { "name": "The Low-Alpha Rule", "section": "elevation", "body": "Every shadow uses ≤0.15 alpha on its strongest blur. Higher alphas read as 2014 Material drop shadows." },
- { "name": "The Tinted-Shadow-Only-For-Accent Rule", "section": "elevation", "body": "Neutral shadows for structure. Magenta-tinted shadows only for deliberate accent-glow moments." }
- ],
- "dos": [
- "Do treat Warm Ash Cream as the default page background.",
- "Do use Editorial Magenta on ≤10% of any given screen.",
- "Do set all new colors in OKLCH.",
- "Do use italic display type as a voice, not as emphasis inside paragraphs.",
- "Do use clamp() fluid sizing for headings; use fixed rem for body.",
- "Do keep the primary CTA sharp and squared. border-radius: 0, uppercase, letter-tracked.",
- "Do use --ease-out (cubic-bezier(0.16, 1, 0.3, 1)) or --ease-out-quint on transitions.",
- "Do leave surfaces flat at rest. Reach for shadows only on hover or deliberate elevation.",
- "Do respect prefers-reduced-motion on every animation.",
- "Do cap body line length at 65–75ch via max-width."
- ],
- "donts": [
- "Don't use pure black (#000) or pure white (#fff).",
- "Don't use border-left or border-right greater than 1px as a colored stripe. The AI-dashboard tell.",
- "Don't use background-clip: text with a gradient. Gradient text is banned.",
- "Don't default to dark mode.",
- "Don't use glassmorphism.",
- "Don't add a second accent color.",
- "Don't use rounded rectangles with generic drop shadows.",
- "Don't use bounce or elastic easing.",
- "Don't animate layout properties (width, height, padding, margin). Use transform and opacity.",
- "Don't nest cards inside cards.",
- "Don't use identical card grids.",
- "Don't use the hero-metric layout template.",
- "Don't extend the Command Category Tints vocabulary.",
- "Don't hedge in UI copy.",
- "Don't introduce a new spacing token outside the 8/16/24/32/48/80/120 scale."
- ]
- }
-}
@@ -1,6 +0,0 @@
-{
- "files": ["site/layouts/Base.astro"],
- "insertBefore": "</body>",
- "commentSyntax": "html",
- "cspChecked": true
-}
@@ -1,165 +0,0 @@
----
-name: impeccable
-description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
-version: 3.1.1
-license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
----
-
-Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
-
-## Setup
-
-Before any design work or file edits:
-
-1. Load context (PRODUCT.md / DESIGN.md) via the loader script.
-2. Identify the register and load the matching register reference (brand.md or product.md).
-3. **If the user invoked a sub-command (e.g. `craft`, `shape`, `audit`), load its reference file too.** This is non-negotiable: `craft` without `craft.md` loaded means you'll skip the shape-and-confirm step the user expects.
-
-Skipping these produces generic output that ignores the project.
-
-### 1. Context gathering
-
-Two files, case-insensitive. The loader looks at the project root by default and falls back to `.agents/context/` and `docs/` if the root is clean. Override with `IMPECCABLE_CONTEXT_DIR=path/to/dir` (absolute or relative to cwd).
-
-- **PRODUCT.md**: required. Users, brand, tone, anti-references, strategic principles.
-- **DESIGN.md**: optional, strongly recommended. Colors, typography, elevation, components.
-
-Load both in one call:
-
-```bash
-node .kiro/skills/impeccable/scripts/load-context.mjs
-```
-
-Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`. The output's `contextDir` field tells you where the files were resolved from.
-
-If the output is already in this session's conversation history, don't re-run. Exceptions requiring a fresh load: you just ran `/impeccable teach` or `/impeccable document` (they rewrite the files), or the user manually edited one.
-
-`/impeccable live` already warms context via `live.mjs`. If you've run `live.mjs`, don't also run `load-context.mjs` this session.
-
-If PRODUCT.md is missing, empty, or placeholder (`[TODO]` markers, <200 chars): run `/impeccable teach`, then resume the user's original task with the fresh context. If the original task was `/impeccable craft`, resume into `/impeccable shape` before any implementation work.
-
-If DESIGN.md is missing: nudge once per session (*"Run `/impeccable document` for more on-brand output"*), then proceed.
-
-### 2. Register
-
-Every design task is **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboard, tool: design SERVES the product).
-
-Identify before designing. Priority: (1) cue in the task itself ("landing page" vs "dashboard"); (2) the surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. First match wins.
-
-If PRODUCT.md lacks the `register` field (legacy), infer it once from its "Users" and "Product Purpose" sections, then cache the inferred value for the session. Suggest the user run `/impeccable teach` to add the field explicitly.
-
-Load the matching reference: [reference/brand.md](reference/brand.md) or [reference/product.md](reference/product.md). The shared design laws below apply to both.
-
-## Shared design laws
-
-Apply to every design, both registers. Match implementation complexity to the aesthetic vision: maximalism needs elaborate code, minimalism needs precision. Interpret creatively. Vary across projects; never converge on the same choices. Claude is capable of extraordinary work. Don't hold back.
-
-### Color
-
-- Use OKLCH. Reduce chroma as lightness approaches 0 or 100; high chroma at extremes looks garish.
-- Never use `#000` or `#fff`. Tint every neutral toward the brand hue (chroma 0.005–0.01 is enough).
-- Pick a **color strategy** before picking colors. Four steps on the commitment axis:
- - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism.
- - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages.
- - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz.
- - **Drenched**: the surface IS the color. Brand heroes, campaign pages.
-- The "one accent ≤10%" rule is Restrained only. Committed / Full palette / Drenched exceed it on purpose. Don't collapse every design to Restrained by reflex.
-
-### Theme
-
-Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe."
-
-Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does.
-
-"Observability dashboard" does not force an answer. "SRE glancing at incident severity on a 27-inch monitor at 2am in a dim room" does. Run the sentence, not the category.
-
-### Typography
-
-- Cap body line length at 65–75ch.
-- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales.
-
-### Layout
-
-- Vary spacing for rhythm. Same padding everywhere is monotony.
-- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
-- Don't wrap everything in a container. Most things don't need one.
-
-### Motion
-
-- Don't animate CSS layout properties.
-- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
-
-### Absolute bans
-
-Match-and-refuse. If you're about to write any of these, rewrite the element with different structure.
-
-- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing.
-- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size.
-- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing.
-- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché.
-- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly.
-- **Modal as first thought.** Modals are usually laziness. Exhaust inline / progressive alternatives first.
-
-### Copy
-
-- Every word earns its place. No restated headings, no intros that repeat the title.
-- **No em dashes.** Use commas, colons, semicolons, periods, or parentheses. Also not `--`.
-
-### The AI slop test
-
-If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference.
-
-**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses.
-
-- **First-order:** if someone could guess the theme + palette from the category alone ("observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black"), it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
-- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families.
-
-## Commands
-
-| Command | Category | Description | Reference |
-|---|---|---|---|
-| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) |
-| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) |
-| `teach` | Build | Set up PRODUCT.md and DESIGN.md context | [reference/teach.md](reference/teach.md) |
-| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) |
-| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) |
-| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) |
-| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) |
-| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) |
-| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) |
-| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) |
-| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) |
-| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) |
-| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) |
-| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) |
-| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) |
-| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) |
-| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) |
-| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) |
-| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) |
-| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) |
-| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) |
-| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
-| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
-
-### Routing rules
-
-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
-3. **First word doesn't match**: general design invocation. Apply the setup steps, shared design laws, and the loaded register reference, using the full argument as context.
-
-Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `/impeccable`.
-
-If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `teach` as a blocker, finish teach, refresh context, then resume the original command and target.
-
-## Pin / Unpin
-
-**Pin** creates a standalone shortcut so `/<command>` invokes `/impeccable <command>` directly. **Unpin** removes it. The script writes to every harness directory present in the project.
-
-```bash
-node .kiro/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
-```
-
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
@@ -1,190 +0,0 @@
-> **Additional context needed**: target platforms/devices and usage contexts.
-
-Adapt an existing design to a different context: another screen size, device, platform, or use case. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context.
-
-
----
-
-## Assess Adaptation Challenge
-
-Understand what needs adaptation and why:
-
-1. **Identify the source context**:
- - What was it designed for originally? (Desktop web? Mobile app?)
- - What assumptions were made? (Large screen? Mouse input? Fast connection?)
- - What works well in current context?
-
-2. **Understand target context**:
- - **Device**: Mobile, tablet, desktop, TV, watch, print?
- - **Input method**: Touch, mouse, keyboard, voice, gamepad?
- - **Screen constraints**: Size, resolution, orientation?
- - **Connection**: Fast wifi, slow 3G, offline?
- - **Usage context**: On-the-go vs desk, quick glance vs focused reading?
- - **User expectations**: What do users expect on this platform?
-
-3. **Identify adaptation challenges**:
- - What won't fit? (Content, navigation, features)
- - What won't work? (Hover states on touch, tiny touch targets)
- - What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop)
-
-**CRITICAL**: Adaptation is rethinking the experience for the new context, not scaling pixels.
-
-## Plan Adaptation Strategy
-
-Create context-appropriate strategy:
-
-### Mobile Adaptation (Desktop → Mobile)
-
-**Layout Strategy**:
-- Single column instead of multi-column
-- Vertical stacking instead of side-by-side
-- Full-width components instead of fixed widths
-- Bottom navigation instead of top/side navigation
-
-**Interaction Strategy**:
-- Touch targets 44x44px minimum (not hover-dependent)
-- Swipe gestures where appropriate (lists, carousels)
-- Bottom sheets instead of dropdowns
-- Thumbs-first design (controls within thumb reach)
-- Larger tap areas with more spacing
-
-**Content Strategy**:
-- Progressive disclosure (don't show everything at once)
-- Prioritize primary content (secondary content in tabs/accordions)
-- Shorter text (more concise)
-- Larger text (16px minimum)
-
-**Navigation Strategy**:
-- Hamburger menu or bottom navigation
-- Reduce navigation complexity
-- Sticky headers for context
-- Back button in navigation flow
-
-### Tablet Adaptation (Hybrid Approach)
-
-**Layout Strategy**:
-- Two-column layouts (not single or three-column)
-- Side panels for secondary content
-- Master-detail views (list + detail)
-- Adaptive based on orientation (portrait vs landscape)
-
-**Interaction Strategy**:
-- Support both touch and pointer
-- Touch targets 44x44px but allow denser layouts than phone
-- Side navigation drawers
-- Multi-column forms where appropriate
-
-### Desktop Adaptation (Mobile → Desktop)
-
-**Layout Strategy**:
-- Multi-column layouts (use horizontal space)
-- Side navigation always visible
-- Multiple information panels simultaneously
-- Fixed widths with max-width constraints (don't stretch to 4K)
-
-**Interaction Strategy**:
-- Hover states for additional information
-- Keyboard shortcuts
-- Right-click context menus
-- Drag and drop where helpful
-- Multi-select with Shift/Cmd
-
-**Content Strategy**:
-- Show more information upfront (less progressive disclosure)
-- Data tables with many columns
-- Richer visualizations
-- More detailed descriptions
-
-### Print Adaptation (Screen → Print)
-
-**Layout Strategy**:
-- Page breaks at logical points
-- Remove navigation, footer, interactive elements
-- Black and white (or limited color)
-- Proper margins for binding
-
-**Content Strategy**:
-- Expand shortened content (show full URLs, hidden sections)
-- Add page numbers, headers, footers
-- Include metadata (print date, page title)
-- Convert charts to print-friendly versions
-
-### Email Adaptation (Web → Email)
-
-**Layout Strategy**:
-- Narrow width (600px max)
-- Single column only
-- Inline CSS (no external stylesheets)
-- Table-based layouts (for email client compatibility)
-
-**Interaction Strategy**:
-- Large, obvious CTAs (buttons not text links)
-- No hover states (not reliable)
-- Deep links to web app for complex interactions
-
-## Implement Adaptations
-
-Apply changes systematically:
-
-### Responsive Breakpoints
-
-Choose appropriate breakpoints:
-- Mobile: 320px-767px
-- Tablet: 768px-1023px
-- Desktop: 1024px+
-- Or content-driven breakpoints (where design breaks)
-
-### Layout Adaptation Techniques
-
-- **CSS Grid/Flexbox**: Reflow layouts automatically
-- **Container Queries**: Adapt based on container, not viewport
-- **`clamp()`**: Fluid sizing between min and max
-- **Media queries**: Different styles for different contexts
-- **Display properties**: Show/hide elements per context
-
-### Touch Adaptation
-
-- Increase touch target sizes (44x44px minimum)
-- Add more spacing between interactive elements
-- Remove hover-dependent interactions
-- Add touch feedback (ripples, highlights)
-- Consider thumb zones (easier to reach bottom than top)
-
-### Content Adaptation
-
-- Use `display: none` sparingly (still downloads)
-- Progressive enhancement (core content first, enhancements on larger screens)
-- Lazy loading for off-screen content
-- Responsive images (`srcset`, `picture` element)
-
-### Navigation Adaptation
-
-- Transform complex nav to hamburger/drawer on mobile
-- Bottom nav bar for mobile apps
-- Persistent side navigation on desktop
-- Breadcrumbs on smaller screens for context
-
-**IMPORTANT**: Test on real devices. Device emulation in DevTools is helpful but not perfect.
-
-**NEVER**:
-- Hide core functionality on mobile (if it matters, make it work)
-- Assume desktop = powerful device (consider accessibility, older machines)
-- Use different information architecture across contexts (confusing)
-- Break user expectations for platform (mobile users expect mobile patterns)
-- Forget landscape orientation on mobile/tablet
-- Use generic breakpoints blindly (use content-driven breakpoints)
-- Ignore touch on desktop (many desktop devices have touch)
-
-## Verify Adaptations
-
-Test thoroughly across contexts:
-
-- **Real devices**: Test on actual phones, tablets, desktops
-- **Different orientations**: Portrait and landscape
-- **Different browsers**: Safari, Chrome, Firefox, Edge
-- **Different OS**: iOS, Android, Windows, macOS
-- **Different input methods**: Touch, mouse, keyboard
-- **Edge cases**: Very small screens (320px), very large screens (4K)
-- **Slow connections**: Test on throttled network
-
-When the adaptation feels native to each context, hand off to `/impeccable polish` for the final pass.
@@ -1,175 +0,0 @@
-> **Additional context needed**: performance constraints.
-
-Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it.
-
----
-
-## Register
-
-Brand: orchestrated page-load sequences, staggered reveals, scroll-driven animation. Motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions.
-
-Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it.
-
----
-
-## Assess Animation Opportunities
-
-Analyze where motion would improve the experience:
-
-1. **Identify static areas**:
- - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.)
- - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes)
- - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious
- - **Lack of delight**: Functional but joyless interactions
- - **Missed guidance**: Opportunities to direct attention or explain behavior
-
-2. **Understand the context**:
- - What's the personality? (Playful vs serious, energetic vs calm)
- - What's the performance budget? (Mobile-first? Complex page?)
- - Who's the audience? (Motion-sensitive users? Power users who want speed?)
- - What matters most? (One hero animation vs many micro-interactions?)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them.
-
-## Plan Animation Strategy
-
-Create a purposeful animation plan:
-
-- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?)
-- **Feedback layer**: Which interactions need acknowledgment?
-- **Transition layer**: Which state changes need smoothing?
-- **Delight layer**: Where can we surprise and delight?
-
-**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments.
-
-## Implement Animations
-
-Add motion systematically across these categories:
-
-### Entrance Animations
-- **Page load choreography**: Stagger element reveals (100-150ms delays), fade + slide combinations
-- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects)
-- **Content reveals**: Scroll-triggered animations using intersection observer
-- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management
-
-### Micro-interactions
-- **Button feedback**:
- - Hover: Subtle scale (1.02-1.05), color shift, shadow increase
- - Click: Quick scale down then up (0.95 → 1), ripple effect
- - Loading: Spinner or pulse state
-- **Form interactions**:
- - Input focus: Border color transition, slight scale or glow
- - Validation: Shake on error, check mark on success, smooth color transitions
-- **Toggle switches**: Smooth slide + color transition (200-300ms)
-- **Checkboxes/radio**: Check mark animation, ripple effect
-- **Like/favorite**: Scale + rotation, particle effects, color transition
-
-### State Transitions
-- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms)
-- **Expand/collapse**: Height transition with overflow handling, icon rotation
-- **Loading states**: Skeleton screen fades, spinner animations, progress bars
-- **Success/error**: Color transitions, icon animations, gentle scale pulse
-- **Enable/disable**: Opacity transitions, cursor changes
-
-### Navigation & Flow
-- **Page transitions**: Crossfade between routes, shared element transitions
-- **Tab switching**: Slide indicator, content fade/slide
-- **Carousel/slider**: Smooth transforms, snap points, momentum
-- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators
-
-### Feedback & Guidance
-- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights
-- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning
-- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation
-- **Focus flow**: Highlight path through form or workflow
-
-### Delight Moments
-- **Empty states**: Subtle floating animations on illustrations
-- **Completed actions**: Confetti, check mark flourish, success celebrations
-- **Easter eggs**: Hidden interactions for discovery
-- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches
-
-## Technical Implementation
-
-Use appropriate techniques for each animation:
-
-### Timing & Easing
-
-**Durations by purpose:**
-- **100-150ms**: Instant feedback (button press, toggle)
-- **200-300ms**: State changes (hover, menu open)
-- **300-500ms**: Layout changes (accordion, modal)
-- **500-800ms**: Entrance animations (page load)
-
-**Easing curves (use these, not CSS defaults):**
-```css
-/* Recommended: natural deceleration */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */
-
-/* AVOID: feel dated and tacky */
-/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */
-/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */
-```
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-### CSS Animations
-```css
-/* Prefer for simple, declarative animations */
-- transitions for state changes
-- @keyframes for complex sequences
-- transform and opacity for reliable movement
-- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth
-```
-
-### JavaScript Animation
-```javascript
-/* Use for complex, interactive animations */
-- Web Animations API for programmatic control
-- Framer Motion for React
-- GSAP for complex sequences
-```
-
-### Performance
-- **Motion materials**: Use transform/opacity for reliable movement, but use blur, filters, masks, shadows, and color shifts when they materially improve the effect
-- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- **will-change**: Add sparingly for known expensive animations
-- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate
-- **Monitor FPS**: Ensure 60fps on target devices
-
-### Accessibility
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**NEVER**:
-- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself
-- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work
-- Use durations over 500ms for feedback (it feels laggy)
-- Animate without purpose (every animation needs a reason)
-- Ignore `prefers-reduced-motion` (this is an accessibility violation)
-- Animate everything (animation fatigue makes interfaces feel exhausting)
-- Block interaction during animations unless intentional
-
-## Verify Quality
-
-Test animations thoroughly:
-
-- **Smooth at 60fps**: No jank on target devices
-- **Feels natural**: Easing curves feel organic, not robotic
-- **Appropriate timing**: Not too fast (jarring) or too slow (laggy)
-- **Reduced motion works**: Animations disabled or simplified appropriately
-- **Doesn't block**: Users can interact during/after animations
-- **Adds value**: Makes interface clearer or more delightful
-
-When the motion clarifies state instead of decorating it, hand off to `/impeccable polish` for the final pass.
@@ -1,133 +0,0 @@
-Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues; document them for other commands to address.
-
-This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation.
-
-## Diagnostic Scan
-
-Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below.
-
-### 1. Accessibility (A11y)
-
-**Check for**:
-- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA)
-- **Missing ARIA**: Interactive elements without proper roles, labels, or states
-- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps
-- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons
-- **Alt text**: Missing or poor image descriptions
-- **Form issues**: Inputs without labels, poor error messaging, missing required indicators
-
-**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA)
-
-### 2. Performance
-
-**Check for**:
-- **Layout thrashing**: Reading/writing layout properties in loops
-- **Expensive animations**: Casual layout-property animation, unbounded blur/filter/shadow effects, or effects that visibly drop frames
-- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change
-- **Bundle size**: Unnecessary imports, unused dependencies
-- **Render performance**: Unnecessary re-renders, missing memoization
-
-**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized)
-
-### 3. Theming
-
-**Check for**:
-- **Hard-coded colors**: Colors not using design tokens
-- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme
-- **Inconsistent tokens**: Using wrong tokens, mixing token types
-- **Theme switching issues**: Values that don't update on theme change
-
-**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly)
-
-### 4. Responsive Design
-
-**Check for**:
-- **Fixed widths**: Hard-coded widths that break on mobile
-- **Touch targets**: Interactive elements < 44x44px
-- **Horizontal scroll**: Content overflow on narrow viewports
-- **Text scaling**: Layouts that break when text size increases
-- **Missing breakpoints**: No mobile/tablet variants
-
-**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets)
-
-### 5. Anti-Patterns (CRITICAL)
-
-Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy).
-
-**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design)
-
-## Generate Report
-
-### Audit Health Score
-
-| # | Dimension | Score | Key Finding |
-|---|-----------|-------|-------------|
-| 1 | Accessibility | ? | [most critical a11y issue or "--"] |
-| 2 | Performance | ? | |
-| 3 | Responsive Design | ? | |
-| 4 | Theming | ? | |
-| 5 | Anti-Patterns | ? | |
-| **Total** | | **??/20** | **[Rating band]** |
-
-**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues)
-
-### Anti-Patterns Verdict
-**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest.
-
-### Executive Summary
-- Audit Health Score: **??/20** ([rating band])
-- Total issues found (count by severity: P0/P1/P2/P3)
-- Top 3-5 critical issues
-- Recommended next steps
-
-### Detailed Findings by Severity
-
-Tag every issue with **P0-P3 severity**:
-- **P0 Blocking**: Prevents task completion. Fix immediately
-- **P1 Major**: Significant difficulty or WCAG AA violation. Fix before release
-- **P2 Minor**: Annoyance, workaround exists. Fix in next pass
-- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits
-
-For each issue, document:
-- **[P?] Issue name**
-- **Location**: Component, file, line
-- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern
-- **Impact**: How it affects users
-- **WCAG/Standard**: Which standard it violates (if applicable)
-- **Recommendation**: How to fix it
-- **Suggested command**: Which command to use (prefer: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-### Patterns & Systemic Issues
-
-Identify recurring problems that indicate systemic gaps rather than one-off mistakes:
-- "Hard-coded colors appear in 15+ components, should use design tokens"
-- "Touch targets consistently too small (<44px) throughout mobile experience"
-
-### Positive Findings
-
-Note what's working well: good practices to maintain and replicate.
-
-## Recommended Actions
-
-List recommended commands in priority order (P0 first, then P1, then P2):
-
-1. **[P?] `/command-name`**: Brief description (specific context from audit findings)
-2. **[P?] `/command-name`**: Brief description (specific context)
-
-**Rules**: Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset. Map findings to the most appropriate command. End with `/impeccable polish` as the final step if any fixes were recommended.
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable audit` after fixes to see your score improve.
-
-**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters.
-
-**NEVER**:
-- Report issues without explaining impact (why does this matter?)
-- Provide generic recommendations (be specific and actionable)
-- Skip positive findings (celebrate what works)
-- Forget to prioritize (everything can't be P0)
-- Report false positives without verification
-
@@ -1,113 +0,0 @@
-When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact and personality through stronger hierarchy, committed scale, and decisive type.
-
----
-
-## Register
-
-Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
-
-Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too safe or boring:
-
-1. **Identify weakness sources**:
- - **Generic choices**: System fonts, basic colors, standard layouts
- - **Timid scale**: Everything is medium-sized with no drama
- - **Low contrast**: Everything has similar visual weight
- - **Static**: No motion, no energy, no life
- - **Predictable**: Standard patterns with no surprises
- - **Flat hierarchy**: Nothing stands out or commands attention
-
-2. **Understand the context**:
- - What's the brand personality? (How far can we push?)
- - What's the purpose? (Marketing can be bolder than financial dashboards)
- - Who's the audience? (What will resonate?)
- - What are the constraints? (Brand guidelines, accessibility, performance)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
-
-**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
-
-## Plan Amplification
-
-Create a strategy to increase impact while maintaining coherence:
-
-- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
-- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
-- **Risk budget**: How experimental can we be? Push boundaries within constraints.
-- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
-
-**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration.
-
-## Amplify the Design
-
-Systematically increase impact across these dimensions:
-
-### Typography Amplification
-- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and [typography.md](typography.md) for inspiration)
-- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
-- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
-- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
-
-### Color Intensification
-- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
-- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop
-- **Dominant color strategy**: Let one bold color own 60% of the design
-- **Sharp accents**: High-contrast accent colors that pop
-- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
-- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
-
-### Spatial Drama
-- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
-- **Break the grid**: Let hero elements escape containers and cross boundaries
-- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
-- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
-- **Overlap**: Layer elements intentionally for depth
-
-### Visual Effects
-- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
-- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
-- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop)
-- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
-- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
-
-### Motion & Animation
-- **Entrance choreography**: Staggered, dramatic page load animations with 50-100ms delays
-- **Scroll effects**: Parallax, reveal animations, scroll-triggered sequences
-- **Micro-interactions**: Satisfying hover effects, click feedback, state changes
-- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect)
-
-### Composition Boldness
-- **Hero moments**: Create clear focal points with dramatic treatment
-- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
-- **Full-bleed elements**: Use full viewport width/height for impact
-- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
-
-**NEVER**:
-- Add effects randomly without purpose (chaos ≠ bold)
-- Sacrifice readability for aesthetics (body text must be readable)
-- Make everything bold (then nothing is bold; you need contrast)
-- Ignore accessibility (bold design must still meet WCAG standards)
-- Overwhelm with motion (animation fatigue is real)
-- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
-
-## Verify Quality
-
-Ensure amplification maintains usability and coherence:
-
-- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over.
-- **Still functional**: Can users accomplish tasks without distraction?
-- **Coherent**: Does everything feel intentional and unified?
-- **Memorable**: Will users remember this experience?
-- **Performant**: Do all these effects run smoothly?
-- **Accessible**: Does it still meet accessibility standards?
-
-**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects."
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,118 +0,0 @@
-# Brand register
-
-When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made.
-
-The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look.
-
-## The brand slop test
-
-If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?"
-
-Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home.
-
-**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register.
-
-Then the inverse test: in one sentence, describe what you're about to build the way a competitor would describe theirs. If that sentence fits the modal landing page in the category, restart.
-
-## Typography
-
-### Font selection procedure
-
-Every project. Never skip.
-
-1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words.
-2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture.
-3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy."
-4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over.
-
-### Reflex-reject list
-
-Training-data defaults. Ban list. Look further:
-
-Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif
-
-### Reflex-reject aesthetic lanes
-
-Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further.
-
-- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery.
-
-(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.)
-
-The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md).
-
-### Pairing and voice
-
-Distinctive + refined is the goal. The specific shape depends on the brand:
-
-- **Editorial / long-form / luxury**: display serif + sans body (a magazine shape).
-- **Tech / dev tools / fintech**: one committed sans, usually; custom-tight tracking, strong weight contrast inside a single family.
-- **Consumer / food / travel**: warmer pairings, often a humanist sans plus a script or display serif.
-- **Creative studios / agencies**: rule-breaking welcome. Mono-only, or display-only, or custom-drawn type as voice.
-
-Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair.
-
-Vary across projects. If the last brief was a serif-display landing page, this one isn't.
-
-### Scale
-
-Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted.
-
-Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room.
-
-## Color
-
-Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register.
-
-- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige.
-- Palette IS voice. A calm brand and a restless brand should not share palette mechanics.
-- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit.
-- Don't converge across projects. If the last brand surface was restrained-on-cream, this one is not.
-- When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette.
-
-## Layout
-
-- Asymmetric compositions are one option. Break the grid intentionally for emphasis.
-- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings.
-- Alternative: a strict, visible grid as the voice (brutalist / Swiss / tech-spec aesthetics). Either asymmetric or rigorously-gridded can be "designed"; the failure mode is splitting the difference into a generic centered stack.
-- Don't default to centering everything. Left-aligned with asymmetric layouts feels more designed; a strict grid reads as confident structure. A centered-stack hero with icon-title-subtitle cards reads as template.
-- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness.
-
-## Imagery
-
-Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo.
-
-**When the brief implies imagery (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product), you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy.
-
-- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `<div>` placeholders.
-- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel".
-- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one.
-- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish".
-
-"Imagery" here is broader than stock photography: product screenshots, custom data visualizations, generated SVG, and canvas/WebGL scenes are all imagery. Text-only pages where typography alone carries the entire visual weight are the failure mode.
-
-## Motion
-
-- One well-orchestrated page-load with staggered reveals beats scattered micro-interactions, when the brand invites it. Tech-minimal brands often skip entrance motion entirely; the restraint is the voice.
-- For collapsing/expanding sections, transition `grid-template-rows` rather than `height`.
-
-## Brand bans (on top of the shared absolute bans)
-
-- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume.
-- Large rounded-corner icons above every heading. Screams template.
-- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.)
-- All-caps body copy. Reserve caps for short labels and headings.
-- Timid palettes and average layouts. Safe = invisible.
-- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs.
-- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic.
-- Repeated tiny uppercase tracked labels above every section heading. A single strong kicker can be voice; repeating it as section grammar is AI scaffolding unless it's a deliberate, named brand system.
-
-## Brand permissions
-
-Brand can afford things product can't. Take them.
-
-- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography.
-- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing.
-- Typographic risk. Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines, a single oversize word as a hero.
-- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics.
-- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment.
@@ -1,174 +0,0 @@
-> **Additional context needed**: audience technical level and users' mental state in context.
-
-Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task.
-
-
----
-
-## Assess Current Copy
-
-Identify what makes the text unclear or ineffective:
-
-1. **Find clarity problems**:
- - **Jargon**: Technical terms users won't understand
- - **Ambiguity**: Multiple interpretations possible
- - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file"
- - **Length**: Too wordy or too terse
- - **Assumptions**: Assuming user knowledge they don't have
- - **Missing context**: Users don't know what to do or why
- - **Tone mismatch**: Too formal, too casual, or inappropriate for situation
-
-2. **Understand the context**:
- - Who's the audience? (Technical? General? First-time users?)
- - What's the user's mental state? (Stressed during error? Confident during success?)
- - What's the action? (What do we want users to do?)
- - What's the constraint? (Character limits? Space limitations?)
-
-**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets.
-
-## Plan Copy Improvements
-
-Create a strategy for clearer communication:
-
-- **Primary message**: What's the ONE thing users need to know?
-- **Action needed**: What should users do next (if anything)?
-- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?)
-- **Constraints**: Length limits, brand voice, localization considerations
-
-**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words.
-
-## Improve Copy Systematically
-
-Refine text across these common areas:
-
-### Error Messages
-**Bad**: "Error 403: Forbidden"
-**Good**: "You don't have permission to view this page. Contact your admin for access."
-
-**Bad**: "Invalid input"
-**Good**: "Email addresses need an @ symbol. Try: name@example.com"
-
-**Principles**:
-- Explain what went wrong in plain language
-- Suggest how to fix it
-- Don't blame the user
-- Include examples when helpful
-- Link to help/support if applicable
-
-### Form Labels & Instructions
-**Bad**: "DOB (MM/DD/YYYY)"
-**Good**: "Date of birth" (with placeholder showing format)
-
-**Bad**: "Enter value here"
-**Good**: "Your email address" or "Company name"
-
-**Principles**:
-- Use clear, specific labels (not generic placeholders)
-- Show format expectations with examples
-- Explain why you're asking (when not obvious)
-- Put instructions before the field, not after
-- Keep required field indicators clear
-
-### Button & CTA Text
-**Bad**: "Click here" | "Submit" | "OK"
-**Good**: "Create account" | "Save changes" | "Got it, thanks"
-
-**Principles**:
-- Describe the action specifically
-- Use active voice (verb + noun)
-- Match user's mental model
-- Be specific ("Save" is better than "OK")
-
-### Help Text & Tooltips
-**Bad**: "This is the username field"
-**Good**: "Choose a username. You can change this later in Settings."
-
-**Principles**:
-- Add value (don't just repeat the label)
-- Answer the implicit question ("What is this?" or "Why do you need this?")
-- Keep it brief but complete
-- Link to detailed docs if needed
-
-### Empty States
-**Bad**: "No items"
-**Good**: "No projects yet. Create your first project to get started."
-
-**Principles**:
-- Explain why it's empty (if not obvious)
-- Show next action clearly
-- Make it welcoming, not dead-end
-
-### Success Messages
-**Bad**: "Success"
-**Good**: "Settings saved! Your changes will take effect immediately."
-
-**Principles**:
-- Confirm what happened
-- Explain what happens next (if relevant)
-- Be brief but complete
-- Match the user's emotional moment (celebrate big wins)
-
-### Loading States
-**Bad**: "Loading..." (for 30+ seconds)
-**Good**: "Analyzing your data... this usually takes 30-60 seconds"
-
-**Principles**:
-- Set expectations (how long?)
-- Explain what's happening (when it's not obvious)
-- Show progress when possible
-- Offer escape hatch if appropriate ("Cancel")
-
-### Confirmation Dialogs
-**Bad**: "Are you sure?"
-**Good**: "Delete 'Project Alpha'? This can't be undone."
-
-**Principles**:
-- State the specific action
-- Explain consequences (especially for destructive actions)
-- Use clear button labels ("Delete project" not "Yes")
-- Don't overuse confirmations (only for risky actions)
-
-### Navigation & Wayfinding
-**Bad**: Generic labels like "Items" | "Things" | "Stuff"
-**Good**: Specific labels like "Your projects" | "Team members" | "Settings"
-
-**Principles**:
-- Be specific and descriptive
-- Use language users understand (not internal jargon)
-- Make hierarchy clear
-- Consider information scent (breadcrumbs, current location)
-
-## Apply Clarity Principles
-
-Every piece of copy should follow these rules:
-
-1. **Be specific**: "Enter email" not "Enter value"
-2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity)
-3. **Be active**: "Save changes" not "Changes will be saved"
-4. **Be human**: "Oops, something went wrong" not "System error encountered"
-5. **Tell users what to do**, not just what happened
-6. **Be consistent**: Use same terms throughout (don't vary for variety)
-
-**NEVER**:
-- Use jargon without explanation
-- Blame users ("You made an error" → "This field is required")
-- Be vague ("Something went wrong" without explanation)
-- Use passive voice unnecessarily
-- Write overly long explanations (be concise)
-- Use humor for errors (be empathetic instead)
-- Assume technical knowledge
-- Vary terminology (pick one term and stick with it)
-- Repeat information (headers restating intros, redundant explanations)
-- Use placeholders as the only labels (they disappear when users type)
-
-## Verify Improvements
-
-Test that copy improvements work:
-
-- **Comprehension**: Can users understand without context?
-- **Actionability**: Do users know what to do next?
-- **Brevity**: Is it as short as possible while remaining clear?
-- **Consistency**: Does it match terminology elsewhere?
-- **Tone**: Is it appropriate for the situation?
-
-When the copy reads cleanly, hand off to `/impeccable polish` for the final pass.
@@ -1,105 +0,0 @@
-# Codex: Visual Direction & Asset Production
-
-This file is loaded by `/impeccable craft` when the harness has native image generation (currently Codex via `image_gen`). Other harnesses skip it. It covers the two craft steps that depend on real image generation: landing the visual direction, and producing the raster assets the implementation will compose.
-
-Read this *before* generating any images. The order matters, and the per-step user pauses are what keep generated imagery from drifting away from the brief.
-
-### Four stop points before code
-
-Steps A through D each end with the user. Do not advance past any of them on your own read of the situation.
-
-1. **STOP after Step A questions.** Wait for answers.
-2. **STOP after Step B palette generation.** Wait for "confirm palette."
-3. **STOP after Step C mocks.** Wait for direction approval or delegation.
-4. **Only after Step D approves a direction** do you return to craft.md Step 4 and write code.
-
-Prior shape approval does **not** satisfy any of these. Shape's "confirm or override" advances you into Step A; it is not a substitute for it.
-
-## Step A: Explore Directions with the User
-
-Before generating anything, run a brief direction conversation grounded in the shape brief.
-
-**Step A is required even when shape just produced a confirmed brief.** The shape questions and Step A questions cover different ground: shape pins purpose, content, scope; Step A pins palette, atmosphere, and named visual references for the comps you're about to generate. The only time you can skip Step A is when the user has already answered these exact palette/atmosphere/reference questions in the same session.
-
-Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions:
-
-- "Brief says 'editorial restraint, Klim-adjacent.' Are we closer to a quiet specimen page or a magazine-spread feel with hero imagery?"
-- "Palette strategy from shape was 'Committed.' Want it warm-grounded (deep oxblood + cream) or cool-grounded (slate + paper white)?"
-
-**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded.
-
-## Step B: Generate the Brand Palette First
-
-Generate **one** palette artifact before any mocks. This is a small, focused image: typography pairing on the chosen background, primary + accent color swatches, one signature ornament or motif. Single image, single pass.
-
-Why palette first: mocks generated against a vague color sense produce noise that drowns out the structural decisions. A confirmed palette is the first concrete contract for everything downstream.
-
-Show the palette to the user. Ask one question: "This is the palette I'm locking in for the mocks. Confirm, or call out what to shift?"
-
-**STOP and wait for confirmation.** Do not generate mocks against an unconfirmed palette. "Probably good enough" is the wrong call here; the palette is the contract for everything downstream.
-
-## Step C: Generate 1-3 Visual Mocks Against the Palette
-
-Once the palette is confirmed, generate **1 to 3** high-fidelity north-star comps. Each mock must use the confirmed palette and typography. Mocks differ in *structural* direction (hierarchy, topology, density, composition), not in color or motif.
-
-- Brand work: push visual identity, composition, mood, and signature motifs.
-- Product work: push hierarchy, topology, density, tone, grounded in realistic product structure.
-- Landing pages and long-form brand surfaces: show enough of the second fold to establish the system beyond the hero.
-
-Use the `image_gen` tool directly (or via the imagegen skill when available). Don't ask the user to install anything.
-
-## Step D: Approval Loop
-
-Show the comps. Ask what carries forward. Iterate until **one direction is approved** or the user explicitly delegates.
-
-**STOP and wait for the approval or the delegation.** Do not begin Step E or return to craft.md Step 4 until a single direction is named. If the user delegates, pick the strongest direction and explain it from the brief, not personal taste.
-
-Before moving to assets, summarize what to carry into code and what *not* to literalize from the mock. This is the handoff between visual exploration and semantic implementation.
-
-## Step E: Mock Fidelity Inventory
-
-Inventory the approved mock's major visible ingredients. For each, decide implementation: semantic HTML/CSS/SVG, generated raster, sourced raster, icon library, canvas/WebGL, or accepted omission.
-
-Common ingredients to inventory:
-
-- Hero silhouette and dominant composition
-- Signature motifs (planets, devices, portraits, charts, route lines, insets, badges, etc.)
-- Nav and primary CTA treatment
-- Section sequence, especially the second fold
-- Image-native content the concept depends on
-- Typography, density, color/material treatment, motion cues
-
-Treat the mock as a north star, not a screenshot to trace. Don't rasterize core UI text. But if the live result lacks the mock's major ingredients, the implementation is wrong.
-
-If a photographic, architectural, product, or place-led mock becomes generic CSS scenery, decorative diagrams, bullets, or copy, stop and fix it. That's a broken implementation, not a harmless interpretation.
-
-Don't substitute a different hero composition or visual driver post-approval without user sign-off.
-
-## Step F: Asset Slicing via the Asset Producer
-
-Raster ingredients identified in Step E need clean production assets. Use the bundled `impeccable_asset_producer` subagent rather than producing inline.
-
-Spawn it as a scoped subagent. If you do not have explicit permission to use agents, stop and ask:
-
-```text
-Asset production will work better as a scoped subagent job. Should I spawn the Impeccable asset producer subagent for this step?
-```
-
-Pass to the agent:
-
-- Approved mock path or screenshot reference
-- Crop paths or a contact sheet with crop ids
-- Output directory
-- Required dimensions, format, transparency needs
-- Avoid list
-- Notes on what should remain semantic HTML/CSS/SVG instead of raster
-
-Attach image generation capability to the spawned agent when the harness supports it. Do **not** load image-generation reference material into the parent thread.
-
-Inline asset production is allowed only if the user declines subagents, the harness cannot spawn the authorized agent, or the user explicitly asks for single-thread mode.
-
-Prefer HTML/CSS/SVG/canvas when they can credibly reproduce an ingredient; reach for real, generated, or stock imagery when the mock or subject matter calls for actual visual content.
-
-## After This File
-
-Once Steps A through F are complete, return to `craft.md` Step 5 (Build to Production Quality). The implementation builds against the confirmed palette, approved mock, and the assets the producer wrote.
@@ -1,106 +0,0 @@
-# Cognitive Load Assessment
-
-Cognitive load is the total mental effort required to use an interface. Overloaded users make mistakes, get frustrated, and leave. This reference helps identify and fix cognitive overload.
-
----
-
-## Three Types of Cognitive Load
-
-### Intrinsic Load: The Task Itself
-Complexity inherent to what the user is trying to do. You can't eliminate this, but you can structure it.
-
-**Manage it by**:
-- Breaking complex tasks into discrete steps
-- Providing scaffolding (templates, defaults, examples)
-- Progressive disclosure: show what's needed now, hide the rest
-- Grouping related decisions together
-
-### Extraneous Load: Bad Design
-Mental effort caused by poor design choices. **Eliminate this ruthlessly.** It's pure waste.
-
-**Common sources**:
-- Confusing navigation that requires mental mapping
-- Unclear labels that force users to guess meaning
-- Visual clutter competing for attention
-- Inconsistent patterns that prevent learning
-- Unnecessary steps between user intent and result
-
-### Germane Load: Learning Effort
-Mental effort spent building understanding. This is *good* cognitive load; it leads to mastery.
-
-**Support it by**:
-- Progressive disclosure that reveals complexity gradually
-- Consistent patterns that reward learning
-- Feedback that confirms correct understanding
-- Onboarding that teaches through action, not walls of text
-
----
-
-## Cognitive Load Checklist
-
-Evaluate the interface against these 8 items:
-
-- [ ] **Single focus**: Can the user complete their primary task without distraction from competing elements?
-- [ ] **Chunking**: Is information presented in digestible groups (≤4 items per group)?
-- [ ] **Grouping**: Are related items visually grouped together (proximity, borders, shared background)?
-- [ ] **Visual hierarchy**: Is it immediately clear what's most important on the screen?
-- [ ] **One thing at a time**: Can the user focus on a single decision before moving to the next?
-- [ ] **Minimal choices**: Are decisions simplified (≤4 visible options at any decision point)?
-- [ ] **Working memory**: Does the user need to remember information from a previous screen to act on the current one?
-- [ ] **Progressive disclosure**: Is complexity revealed only when the user needs it?
-
-**Scoring**: Count the failed items. 0–1 failures = low cognitive load (good). 2–3 = moderate (address soon). 4+ = high cognitive load (critical fix needed).
-
----
-
-## The Working Memory Rule
-
-**Humans can hold ≤4 items in working memory at once** (Miller's Law revised by Cowan, 2001).
-
-At any decision point, count the number of distinct options, actions, or pieces of information a user must simultaneously consider:
-- **≤4 items**: Within working memory limits, manageable
-- **5–7 items**: Pushing the boundary; consider grouping or progressive disclosure
-- **8+ items**: Overloaded; users will skip, misclick, or abandon
-
-**Practical applications**:
-- Navigation menus: ≤5 top-level items (group the rest under clear categories)
-- Form sections: ≤4 fields visible per group before a visual break
-- Action buttons: 1 primary, 1–2 secondary, group the rest in a menu
-- Dashboard widgets: ≤4 key metrics visible without scrolling
-- Pricing tiers: ≤3 options (more causes analysis paralysis)
-
----
-
-## Common Cognitive Load Violations
-
-### 1. The Wall of Options
-**Problem**: Presenting 10+ choices at once with no hierarchy.
-**Fix**: Group into categories, highlight recommended, use progressive disclosure.
-
-### 2. The Memory Bridge
-**Problem**: User must remember info from step 1 to complete step 3.
-**Fix**: Keep relevant context visible, or repeat it where it's needed.
-
-### 3. The Hidden Navigation
-**Problem**: User must build a mental map of where things are.
-**Fix**: Always show current location (breadcrumbs, active states, progress indicators).
-
-### 4. The Jargon Barrier
-**Problem**: Technical or domain language forces translation effort.
-**Fix**: Use plain language. If domain terms are unavoidable, define them inline.
-
-### 5. The Visual Noise Floor
-**Problem**: Every element has the same visual weight; nothing stands out.
-**Fix**: Establish clear hierarchy: one primary element, 2–3 secondary, everything else muted.
-
-### 6. The Inconsistent Pattern
-**Problem**: Similar actions work differently in different places.
-**Fix**: Standardize interaction patterns. Same type of action = same type of UI.
-
-### 7. The Multi-Task Demand
-**Problem**: Interface requires processing multiple simultaneous inputs (reading + deciding + navigating).
-**Fix**: Sequence the steps. Let the user do one thing at a time.
-
-### 8. The Context Switch
-**Problem**: User must jump between screens/tabs/modals to gather info for a single decision.
-**Fix**: Co-locate the information needed for each decision. Reduce back-and-forth.
@@ -1,105 +0,0 @@
-# Color & Contrast
-
-## Color Spaces: Use OKLCH
-
-**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark.
-
-The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish.
-
-The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand.
-
-## Building Functional Palettes
-
-### Tinted Neutrals
-
-**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces.
-
-The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette.
-
-**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects.
-
-### Palette Structure
-
-A complete system needs:
-
-| Role | Purpose | Example |
-|------|---------|---------|
-| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades |
-| **Neutral** | Text, backgrounds, borders | 9-11 shade scale |
-| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each |
-| **Surface** | Cards, modals, overlays | 2-3 elevation levels |
-
-**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise.
-
-### The 60-30-10 Rule (Applied Correctly)
-
-This rule is about **visual weight**, not pixel count:
-
-- **60%**: Neutral backgrounds, white space, base surfaces
-- **30%**: Secondary colors: text, borders, inactive states
-- **10%**: Accent: CTAs, highlights, focus states
-
-The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power.
-
-## Contrast & Accessibility
-
-### WCAG Requirements
-
-| Content Type | AA Minimum | AAA Target |
-|--------------|------------|------------|
-| Body text | 4.5:1 | 7:1 |
-| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 |
-| UI components, icons | 3:1 | 4.5:1 |
-| Non-essential decorations | None | None |
-
-**The gotcha**: Placeholder text still needs 4.5:1. That light gray placeholder you see everywhere? Usually fails WCAG.
-
-### Dangerous Color Combinations
-
-These commonly fail contrast or cause readability issues:
-
-- Light gray text on white (the #1 accessibility fail)
-- **Gray text on any colored background**: gray looks washed out and dead on color. Use a darker shade of the background color, or transparency
-- Red text on green background (or vice versa): 8% of men can't distinguish these
-- Blue text on red background (vibrates visually)
-- Yellow text on white (almost always fails)
-- Thin light text on images (unpredictable contrast)
-
-### Never Use Pure Gray or Pure Black
-
-Pure gray (`oklch(50% 0 0)`) and pure black (`#000`) don't exist in nature; real shadows and surfaces always have a color cast. Even a chroma of 0.005-0.01 is enough to feel natural without being obviously tinted. (See tinted neutrals example above.)
-
-### Testing
-
-Don't trust your eyes. Use tools:
-
-- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/)
-- Browser DevTools → Rendering → Emulate vision deficiencies
-- [Polypane](https://polypane.app/) for real-time testing
-
-## Theming: Light & Dark Mode
-
-### Dark Mode Is Not Inverted Light Mode
-
-You can't just swap colors. Dark mode requires different design decisions:
-
-| Light Mode | Dark Mode |
-|------------|-----------|
-| Shadows for depth | Lighter surfaces for depth (no shadows) |
-| Dark text on light | Light text on dark (reduce font weight) |
-| Vibrant accents | Desaturate accents slightly |
-| White backgrounds | Never pure black; use dark gray (oklch 12-18%) |
-
-In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light.
-
-### Token Hierarchy
-
-Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same.
-
-## Alpha Is A Design Smell
-
-Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed.
-
----
-
-**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Using pure black (#000) for large areas. Skipping color blindness testing (8% of men affected).
@@ -1,154 +0,0 @@
-> **Additional context needed**: existing brand colors.
-
-Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit.
-
----
-
-## Register
-
-Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it.
-
-Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen.
-
----
-
-## Assess Color Opportunity
-
-Analyze the current state and identify opportunities:
-
-1. **Understand current state**:
- - **Color absence**: Pure grayscale? Limited neutrals? One timid accent?
- - **Missed opportunities**: Where could color add meaning, hierarchy, or delight?
- - **Context**: What's appropriate for this domain and audience?
- - **Brand**: Are there existing brand colors we should use?
-
-2. **Identify where color adds value**:
- - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue)
- - **Hierarchy**: Drawing attention to important elements
- - **Categorization**: Different sections, types, or states
- - **Emotional tone**: Warmth, energy, trust, creativity
- - **Wayfinding**: Helping users navigate and understand structure
- - **Delight**: Moments of visual interest and personality
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose.
-
-## Plan Color Strategy
-
-Create a purposeful color introduction plan:
-
-- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals)
-- **Dominant color**: Which color owns 60% of colored elements?
-- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%)
-- **Application strategy**: Where does each color appear and why?
-
-**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more.
-
-## Introduce Color Strategically
-
-Add color systematically across these dimensions:
-
-### Semantic Color
-- **State indicators**:
- - Success: Green tones (emerald, forest, mint)
- - Error: Red/pink tones (rose, crimson, coral)
- - Warning: Orange/amber tones
- - Info: Blue tones (sky, ocean, indigo)
- - Neutral: Gray/slate for inactive states
-
-- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.)
-- **Progress indicators**: Colored bars, rings, or charts showing completion or health
-
-### Accent Color Application
-- **Primary actions**: Color the most important buttons/CTAs
-- **Links**: Add color to clickable text (maintain accessibility)
-- **Icons**: Colorize key icons for recognition and personality
-- **Headers/titles**: Add color to section headers or key labels
-- **Hover states**: Introduce color on interaction
-
-### Background & Surfaces
-- **Tinted backgrounds**: Replace pure gray (`#f5f5f5`) with warm neutrals (`oklch(97% 0.01 60)`) or cool tints (`oklch(97% 0.01 250)`)
-- **Colored sections**: Use subtle background colors to separate areas
-- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue)
-- **Cards & surfaces**: Tint cards or surfaces slightly for warmth
-
-**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
-
-### Data Visualization
-- **Charts & graphs**: Use color to encode categories or values
-- **Heatmaps**: Color intensity shows density or importance
-- **Comparison**: Color coding for different datasets or timeframes
-
-### Borders & Accents
-- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`)
-- **Underlines**: Color underlines for emphasis or active states
-- **Dividers**: Subtle colored dividers instead of gray lines
-- **Focus rings**: Colored focus indicators matching brand
-- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe
-
-**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe.
-
-### Typography Color
-- **Colored headings**: Use brand colors for section headings (maintain contrast)
-- **Highlight text**: Color for emphasis or categories
-- **Labels & tags**: Small colored labels for metadata or categories
-
-### Decorative Elements
-- **Illustrations**: Add colored illustrations or icons
-- **Shapes**: Geometric shapes in brand colors as background elements
-- **Gradients**: Colorful gradient overlays or mesh backgrounds
-- **Blobs/organic shapes**: Soft colored shapes for visual interest
-
-## Balance & Refinement
-
-Ensure color addition improves rather than overwhelms:
-
-### Maintain Hierarchy
-- **Dominant color** (60%): Primary brand color or most used accent
-- **Secondary color** (30%): Supporting color for variety
-- **Accent color** (10%): High contrast for key moments
-- **Neutrals** (remaining): Gray/black/white for structure
-
-### Accessibility
-- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components)
-- **Don't rely on color alone**: Use icons, labels, or patterns alongside color
-- **Test for color blindness**: Verify red/green combinations work for all users
-
-### Cohesion
-- **Consistent palette**: Use colors from defined palette, not arbitrary choices
-- **Systematic application**: Same color meanings throughout (green always = success)
-- **Temperature consistency**: Warm palette stays warm, cool stays cool
-
-**NEVER**:
-- Use every color in the rainbow (choose 2-4 colors beyond neutrals)
-- Apply color randomly without semantic meaning
-- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead
-- Use pure gray for neutrals. Add subtle color tint (warm or cool) for depth
-- Use pure black (`#000`) or pure white (`#fff`) for large areas
-- Violate WCAG contrast requirements
-- Use color as the only indicator (accessibility issue)
-- Make everything colorful (defeats the purpose)
-- Default to purple-blue gradients (AI slop aesthetic)
-
-## Verify Color Addition
-
-Test that colorization improves the experience:
-
-- **Better hierarchy**: Does color guide attention appropriately?
-- **Clearer meaning**: Does color help users understand states/categories?
-- **More engaging**: Does the interface feel warmer and more inviting?
-- **Still accessible**: Do all color combinations meet WCAG standards?
-- **Not overwhelming**: Is color balanced and purposeful?
-
-When the palette earns its place, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage.
-
-```json
-{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"}
-```
-
-Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract.
@@ -1,123 +0,0 @@
-# Craft Flow
-
-Build a feature with impeccable UX and UI quality: shape the design, land the visual direction, build real production code, inspect and improve in-browser until it meets a high-end studio bar.
-
-Before writing code, you need: PRODUCT.md loaded, register identified and the matching reference loaded, and a confirmed design direction for this task (either from `shape` or supplied by the user). PRODUCT.md is project context, not a task-specific brief.
-
-Treat any approved visual direction (generated mock or stated reference) as a concrete contract for composition, hierarchy, density, atmosphere, signature motifs, and distinctive visual moves. Don't let mocks replace structure, copy, accessibility, or state design. But if the live result lacks the approved direction's major ingredients, the implementation is wrong.
-
-### Gates: do not compress
-
-Craft has **multiple user gates**, not one. When the harness has native image generation (Codex via `image_gen`), the gate sequence before code is:
-
-1. **Shape brief confirmed** (Step 1)
-2. **Direction questions answered** (codex.md Step A)
-3. **Palette confirmed** (codex.md Step B)
-4. **One mock direction approved or delegated** (codex.md Step D)
-
-You must stop at every gate. **Shape confirmation alone is NOT a green light to start coding.** It is the green light to begin codex.md Step A. Compressing gates 2 through 4 because the shape brief felt complete is the dominant failure mode of this flow.
-
-When the harness lacks native image generation, gates 2-4 collapse into the brief itself, and shape confirmation does advance straight to code.
-
-## Step 0: Project Foundation
-
-Before shape, before code: figure out what kind of project you're working in.
-
-Look at the working directory. Run `ls`. Check for:
-
-- An existing framework: `astro.config.mjs/ts`, `next.config.js/ts`, `nuxt.config.ts`, `svelte.config.js`, `vite.config.js/ts`, `package.json` with framework deps, `Cargo.toml` + Leptos/Yew, `Gemfile` + Rails. **If found, use it.** Do not start a parallel build, do not introduce a second framework, do not write to `dist/` or `build/` directly. Whatever pipeline the project has, respect it.
-- An existing component library or design system: `src/components/`, `app/components/`, a `tokens.css` / `theme.ts`, an `astro.config` `integrations`. Read what's there before adding to it.
-- An existing icon set: `lucide-react`, `@phosphor-icons/react`, `@iconify/*`, hand-rolled SVG sprites in `assets/icons/`. **Use what's already in the project**; don't introduce a second set.
-
-If the directory is empty (greenfield), don't pick a framework silently. Ask the user via the AskUserQuestion tool, with sensible defaults framed by the brief:
-
-```text
-What should this be built on?
- - Astro (default for content-led brand sites, landing pages, marketing surfaces)
- - SvelteKit / Next.js / Nuxt (when the brief implies an app surface or significant interactivity)
- - Single index.html (one-shot demo, prototype, or a deliberately framework-free experiment)
-```
-
-Default: Astro for brand briefs, the project's existing framework for product briefs. Ask once; don't re-ask mid-task.
-
-## Step 1: Shape the Design
-
-Run /impeccable shape, passing along whatever feature description the user provided. Shape is **required** for craft; it is what produces a confirmed direction.
-
-Present the shape output and stop. Wait for the user to confirm, override, or course-correct before writing code.
-
-If the user already supplied a confirmed brief or ran shape separately, use it and skip this step.
-
-When the original prompt + PRODUCT.md already answer scope, content, and visual direction with no real ambiguity, the shape output can be **compact** (3-5 bullets stating what you're building and the visual lane, ending with one or two specific questions or "confirm or override"). The full 10-section structured brief is reserved for genuinely ambiguous, multi-screen, or stakeholder-heavy tasks. Don't pad a clear brief into a long one to look thorough; equally, don't skip the pause to look efficient.
-
-If the harness has native image generation (Codex), a compact shape's "confirm or override" advances to **Step 3 and the codex.md flow**, not to Step 4. Phrase the closing line accordingly: "Confirm or override; once we lock direction, I'll run a couple of palette and reference questions before generating any mocks." This stops the model from reading shape confirmation as code-green.
-
-## Step 2: Load References
-
-Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult:
-
-- [spatial-design.md](spatial-design.md) for layout and spacing
-- [typography.md](typography.md) for type hierarchy
-
-Then add references based on the brief's needs:
-- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md)
-- Animation or transitions? Consult [motion-design.md](motion-design.md)
-- Color-heavy or themed? Consult [color-and-contrast.md](color-and-contrast.md)
-- Responsive requirements? Consult [responsive-design.md](responsive-design.md)
-- Heavy on copy, labels, or errors? Consult [ux-writing.md](ux-writing.md)
-
-## Step 3: Visual Direction & Assets (Harness-Gated)
-
-If the harness has **native image generation** (currently Codex via `image_gen`), this step is mandatory. **Stop and load [codex.md](codex.md)**. It covers palette generation, mock exploration, the approval loop, mock-fidelity inventory, and asset slicing via the `impeccable_asset_producer` subagent. Follow Steps A-F in that file, then return here for Step 4.
-
-If the harness lacks native image generation, **state in one line that the visual-direction-by-generation step is being skipped because the harness lacks native image generation, then proceed**. The one-line announcement is required; it forces a conscious decision instead of letting the step quietly evaporate. The brief is your only visual reference. Implement directly from it, treating any named anchor references and the brief's "Design Direction" as the contract.
-
-Whether you generated mocks or not: don't replace required imagery with generic cards, bullets, emoji, fake metrics, decorative CSS panels, or filler copy. Image-led briefs (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product) need real or sourced imagery in the build, not CSS scenery.
-
-## Step 4: Build to Production Quality
-
-**Precondition.** If Step 3 routed you to codex.md (native image generation available), Steps A through D in that file must be complete before any code: questions answered, palette confirmed, mocks generated, one direction approved or delegated. **Do not mention implementation, file paths, or patch plans until that's done.** A confirmed shape brief is not enough; the model that compressed those gates is the model that already failed this flow.
-
-Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration.
-
-### Production bar
-
-- **Real content.** No placeholder copy, placeholder images, dead links, fake controls, or unused scaffold at presentation time.
-- **Preserve the approved mock's major ingredients.** Missing hero objects, world/product imagery, section structure, CTA/nav treatment, or distinctive motifs are blocking defects unless the user accepted the change.
-- **Semantic first.** Real headings, landmarks, labels, form associations, button/link semantics, accessible names, state announcements where needed.
-- **Deliberate spacing and alignment.** No default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment.
-- **Intentional typography.** Chosen loading strategy, clear hierarchy, readable measure, stable line breaks, no overflow at any width.
-- **Realistic state coverage.** Default, hover, focus-visible, active, disabled, loading, error, success, empty, overflow, long/short text, first-run.
-- **Finished interaction quality.** Keyboard paths, touch targets, feedback timing, scroll behavior, state transitions, no hover-only functionality.
-- **Coherent icon set.** Use the project's established set; otherwise pick one library or use accessible text. Don't mix.
-- **Respect the build pipeline.** Edit source files and run the project's build (`npm run build` or equivalent). Don't write to `build/` / `dist/` / `.next/` with `cat`, heredoc, or Bash redirects; that skips asset hashing, image optimization, code splitting, and CSS extraction, and produces output the dev server won't serve.
-- **Verify image URLs before referencing them.** Use image-search MCP or web-fetch when available; guessed photo IDs ship as broken-image placeholders. Without verification, prefer fewer images you're confident about.
-- **Optimized imagery and media.** Correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset`/`picture` for raster, no project-referenced asset left outside the workspace.
-- **Premium motion.** Use atmospheric blur, filter, mask, shadow, reveal when they improve the experience. Avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion.
-- **Maintainable.** Reusable local patterns, clear component boundaries, project conventions. No rasterized UI text or one-off hacks when a local pattern exists.
-- **Technically clean.** Production build passes, no console errors, no avoidable layout shift, no needless dependencies, no broken asset paths.
-- **Ask when uncertain.** If a discovery materially changes the brief or approved direction, stop and ask. Don't guess.
-
-## Step 5: Iterate Visually
-
-Look at what you built like a designer would. Your eyes are whatever the harness gives you: a connected browser, a screenshotting tool, Playwright, or asking the user. Use them for responsive testing (mobile, tablet, desktop minimum) and general visual validation.
-
-If your tool returns a file path, read the PNG back into the conversation. A screenshot you didn't read doesn't count.
-
-For long-form brand surfaces, inspect major sections individually. Thumbnails hide spacing, clipping, and cascade defects.
-
-After the first pass, write an honest critique against the brief, the approved mock's major ingredients (hero silhouette, motifs, imagery, nav/CTA, density), and impeccable's DON'Ts. Patch material defects and re-inspect. **Don't invent defects to demonstrate iteration.** A confident "first pass clean, shipping" beats a fake fix.
-
-Actively check: responsive behavior (composes, not shrinks), every state (empty / error / loading / edge), craft details (spacing, alignment, hierarchy, contrast, motion timing, focus), performance basics. The exit bar: defensible in a high-end studio review.
-
-Detector or QA output is defect evidence only; never proof the work is finished.
-
-## Step 6: Present
-
-Present the result to the user:
-- Show the feature in its primary state
-- Summarize the browser/viewports checked and the most important fixes made after inspection
-- Walk through the key states (empty, error, responsive)
-- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients.
-- Note any remaining limitations or follow-up risks honestly
-- Ask: "What's working? What isn't?"
@@ -1,236 +0,0 @@
-### Purpose
-
-Resolve one stable target, run two independent assessments, synthesize a design critique, persist a snapshot, and ask the user what to improve next. The chat response is the primary deliverable; the snapshot is an archive/backlog for future commands.
-
-### Hard Invariants
-
-- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
-- Assessment A must finish before detector findings enter the parent synthesis context. Detector output is deterministic, but it still anchors judgment.
-- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize.
-- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
-- Viewable targets require browser inspection when available.
-- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
-- Do not claim a user-visible overlay exists unless script injection succeeded and the detector ran in the page.
-
-### Setup
-
-1. **Resolve the target** to a concrete file path or URL. Prefer a source path over a dev-server URL when both identify the same surface; ports drift, paths do not.
- - "the homepage" -> `site/pages/index.astro` or `index.html`
- - "the settings modal" -> the primary component file
- - "this page" -> the current URL or source file
-2. **Compute the slug**:
- ```bash
- node .kiro/skills/impeccable/scripts/critique-storage.mjs slug "<resolved-path-or-url>"
- ```
- Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique.
-3. **Read `.impeccable/critique/ignore.md`** if it exists. Drop matching findings silently; it is the only prior-run input critique consumes.
-
-### Assessment Orchestration
-
-Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis.
-
-If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
-
-### Assessment A: Design Review
-
-Read relevant source files and visually inspect the live page when browser automation is available. Think like a design director.
-
-Evaluate:
-- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill.
-- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases.
-- **Cognitive load**: consult [cognitive-load](cognitive-load.md); report checklist failures and decision points with >4 visible options.
-- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments.
-- **Nielsen heuristics**: consult [heuristics-scoring](heuristics-scoring.md); score all 10 heuristics 0-4.
-
-Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions.
-
-### Assessment B: Detector + Browser Evidence
-
-Run the bundled detector and browser visualization evidence. Assessment B is mandatory and must remain isolated from Assessment A until both are complete.
-
-CLI scan:
-```bash
-node .kiro/skills/impeccable/scripts/detect.mjs --json [--fast] [target]
-```
-
-- Pass markup files/directories as `[target]`; do not pass CSS-only files.
-- For URLs, skip CLI scan and use browser visualization.
-- For 200+ scannable files, use `--fast`; for 500+, narrow scope or ask.
-- Exit code 0 = clean; 2 = findings.
-- If the detector entrypoint is missing or fails to load, report deterministic scan unavailable and continue with browser/manual review.
-
-Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
-
-1. Create a fresh tab and navigate.
-2. Preflight mutable injection by setting `document.title` and appending a `<script>` tag. Read-only evaluate APIs do not count.
-3. If mutation is unavailable, skip live server, browser presentation, and injection; report fallback signal.
-4. If mutation is available, start `node .kiro/skills/impeccable/scripts/live-server.mjs --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then stop the live server.
-5. For multi-view targets, inject on 3-5 representative pages.
-
-Return: CLI findings JSON/counts, browser console findings if applicable, false positives, and skipped/failed browser steps with concrete reasons.
-
-After Assessment B returns usable CLI findings, reuse them. Do not rerun `detect.mjs` in the parent unless Assessment B failed, was truncated, or omitted count, rule names, or file locations.
-
-### Generate Combined Critique Report
-
-Synthesize both assessments into a single report. Do NOT simply concatenate. Weave the findings together, noting where the LLM review and detector agree, where the detector caught issues the LLM missed, and where detector findings are false positives.
-
-The chat response is the primary user-facing deliverable. Present the full structured critique below in chat; do not replace it with a summary and a link. The persisted snapshot is only an archive/backlog for later commands.
-
-Structure your feedback as a design director would:
-
-#### Design Health Score
-> *Consult [heuristics-scoring](heuristics-scoring.md)*
-
-Present the Nielsen's 10 heuristics scores as a table:
-
-| # | Heuristic | Score | Key Issue |
-|---|-----------|-------|-----------|
-| 1 | Visibility of System Status | ? | [specific finding or "n/a" if solid] |
-| 2 | Match System / Real World | ? | |
-| 3 | User Control and Freedom | ? | |
-| 4 | Consistency and Standards | ? | |
-| 5 | Error Prevention | ? | |
-| 6 | Recognition Rather Than Recall | ? | |
-| 7 | Flexibility and Efficiency | ? | |
-| 8 | Aesthetic and Minimalist Design | ? | |
-| 9 | Error Recovery | ? | |
-| 10 | Help and Documentation | ? | |
-| **Total** | | **??/40** | **[Rating band]** |
-
-Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32.
-
-#### Anti-Patterns Verdict
-
-**Start here.** Does this look AI-generated?
-
-**LLM assessment**: Your own evaluation of AI slop tells. Cover overall aesthetic feel, layout sameness, generic composition, missed opportunities for personality.
-
-**Deterministic scan**: Summarize what the automated detector found, with counts and file locations. Note any additional issues the detector caught that you missed, and flag any false positives.
-
-**Visual overlays** (if injection succeeded): Tell the user that overlays are now visible in the **[Human]** tab in their browser, highlighting the detected issues. Summarize what the console output reported. If browser visualization was attempted but injection failed, say that no reliable user-visible overlay is available and report the fallback signal instead.
-
-#### Overall Impression
-A brief gut reaction: what works, what doesn't, and the single biggest opportunity.
-
-#### What's Working
-Highlight 2-3 things done well. Be specific about why they work.
-
-#### Priority Issues
-The 3-5 most impactful design problems, ordered by importance.
-
-For each issue, tag with **P0-P3 severity** (consult [heuristics-scoring](heuristics-scoring.md) for severity definitions):
-- **[P?] What**: Name the problem clearly
-- **Why it matters**: How this hurts users or undermines goals
-- **Fix**: What to do about it (be concrete)
-- **Suggested command**: Which command could address this (from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-#### Persona Red Flags
-> *Consult [personas](personas.md)*
-
-Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `.kiro/settings.json` contains a `## Design Context` section from `impeccable teach`, also generate 1-2 project-specific personas from the audience/brand info.
-
-For each selected persona, walk through the primary user action and list specific red flags found:
-
-**Alex (Power User)**: No keyboard shortcuts detected. Form requires 8 clicks for primary action. Forced modal onboarding. High abandonment risk.
-
-**Jordan (First-Timer)**: Icon-only nav in sidebar. Technical jargon in error messages ("404 Not Found"). No visible help. Will abandon at step 2.
-
-Be specific. Name the exact elements and interactions that fail each persona. Don't write generic persona descriptions; write what broke for them.
-
-#### Minor Observations
-Quick notes on smaller issues worth addressing.
-
-#### Questions to Consider
-Provocative questions that might unlock better solutions:
-- "What if the primary action were more prominent?"
-- "Does this need to feel this complex?"
-- "What would a confident version of this look like?"
-
-**Remember**:
-- Be direct. Vague feedback wastes everyone's time.
-- Be specific. "The submit button," not "some elements."
-- Say what's wrong AND why it matters to users.
-- Give concrete suggestions. Cut "consider exploring..." entirely.
-- Prioritize ruthlessly. If everything is important, nothing is.
-- Don't soften criticism. Developers need honest feedback to ship great design.
-
-### Persist the Snapshot
-
-Once the report above is finalized, write it to `.impeccable/critique/` so the user can refer back, and so `/impeccable polish` can pick up the priority issues without a copy-paste.
-
-Skip this step if the Setup slug was null (vague or root-level target).
-
-1. **Write the body to a temp file** so you can pipe it to the helper. Use the full critique report (heuristic table, anti-patterns verdict, priority issues, persona red flags, minor observations, and questions), but stop before the "Ask the User" / "Recommended Actions" sections that come later.
-
-2. **Pass the structured metadata** through `IMPECCABLE_CRITIQUE_META` (JSON), then run the write command:
- ```bash
- IMPECCABLE_CRITIQUE_META='{"target":"<user phrasing>","total_score":<n>,"p0_count":<n>,"p1_count":<n>}' \
- node .kiro/skills/impeccable/scripts/critique-storage.mjs write <slug> <body-file>
- ```
- The helper prints the absolute path it wrote.
-
-3. **Delete the temp body file** after the write attempt completes, whether the write succeeded or failed. If deletion fails, mention `temp-file cleanup failed: <reason>` briefly in the final output, but do not block the critique.
-
-4. **Read the trend** for context:
- ```bash
- node .kiro/skills/impeccable/scripts/critique-storage.mjs trend <slug> 5
- ```
- This returns a JSON array of the last 5 frontmatter entries (including the one you just wrote).
-
-5. **Append a single line to the user-visible output**, after the report and before the questions:
-
- > **Trend for `<slug>` (last 5 runs): 24 → 28 → 32 → 29 → 32**
- > Wrote `.impeccable/critique/<filename>`.
-
- If this is the first run for the slug, the trend is just one score; say so: "First run for this target, no trend yet."
-
-This is fire-and-forget. Do not show the user the helper's JSON output; only the human-readable trend line and the written path. Failures here should not block the rest of the flow; print the error and move on.
-
-### Ask the User
-
-**After presenting findings**, use targeted questions based on what was actually found. ask the user directly to clarify what you cannot infer. These answers will shape the action plan.
-
-Ask questions along these lines (adapt to the specific findings; do NOT ask generic questions):
-
-1. **Priority direction**: Based on the issues found, ask which category matters most to the user right now. For example: "I found problems with visual hierarchy, color usage, and information overload. Which area should we tackle first?" Offer the top 2-3 issue categories as options.
-
-2. **Design intent**: If the critique found a tonal mismatch, ask whether it was intentional. For example: "The interface feels clinical and corporate. Is that the intended tone, or should it feel warmer/bolder/more playful?" Offer 2-3 tonal directions as options based on what would fix the issues found.
-
-3. **Scope**: Ask how much the user wants to take on. For example: "I found N issues. Want to address everything, or focus on the top 3?" Offer scope options like "Top 3 only", "All issues", "Critical issues only".
-
-4. **Constraints** (optional; only ask if relevant): If the findings touch many areas, ask if anything is off-limits. For example: "Should any sections stay as-is?" This prevents the plan from touching things the user considers done.
-
-**Rules for questions**:
-- Every question must reference specific findings from the report. Never ask generic "who is your audience?" questions.
-- Keep it to 2-4 questions maximum. Respect the user's time.
-- Offer concrete options, not open-ended prompts.
-- If findings are straightforward (e.g., only 1-2 clear issues), skip questions and go directly to Recommended Actions.
-
-### Recommended Actions
-
-**After receiving the user's answers**, present a prioritized action summary reflecting the user's priorities and scope from Ask the User.
-
-#### Action Summary
-
-List recommended commands in priority order, based on the user's answers:
-
-1. **`/command-name`**: Brief description of what to fix (specific context from critique findings)
-2. **`/command-name`**: Brief description (specific context)
-...
-
-**Rules for recommendations**:
-- Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset
-- Order by the user's stated priorities first, then by impact
-- Each item's description should carry enough context that the command knows what to focus on
-- Map each Priority Issue to the appropriate command
-- Skip commands that would address zero issues
-- If the user chose a limited scope, only include items within that scope
-- If the user marked areas as off-limits, exclude commands that would touch those areas
-- End with `/impeccable polish` as the final step if any fixes were recommended
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable critique` after fixes to see your score improve.
@@ -1,302 +0,0 @@
-> **Additional context needed**: what's appropriate for the domain (playful vs professional vs quirky vs elegant).
-
-Find the moments where personality and unexpected polish would turn a functional interface into one users remember and tell other people about. Add only where the moment earns it; delight everywhere reads as noise.
-
----
-
-## Register
-
-Brand: delight can be distributed across copy voice, section transitions, discovery rewards, seasonal touches, personality across the whole surface.
-
-Product: delight at specific moments, not pages. Completion, first-time actions, error recovery, milestone crossings. Reliability and consistency carry the rest of the experience; delight pushed everywhere reads as noise.
-
----
-
-## Assess Delight Opportunities
-
-Identify where delight would enhance (not distract from) the experience:
-
-1. **Find natural delight moments**:
- - **Success states**: Completed actions (save, send, publish)
- - **Empty states**: First-time experiences, onboarding
- - **Loading states**: Waiting periods that could be entertaining
- - **Achievements**: Milestones, streaks, completions
- - **Interactions**: Hover states, clicks, drags
- - **Errors**: Softening frustrating moments
- - **Easter eggs**: Hidden discoveries for curious users
-
-2. **Understand the context**:
- - What's the brand personality? (Playful? Professional? Quirky? Elegant?)
- - Who's the audience? (Tech-savvy? Creative? Corporate?)
- - What's the emotional context? (Accomplishment? Exploration? Frustration?)
- - What's appropriate? (Banking app ≠ gaming app)
-
-3. **Define delight strategy**:
- - **Subtle sophistication**: Refined micro-interactions (luxury brands)
- - **Playful personality**: Whimsical illustrations and copy (consumer apps)
- - **Helpful surprises**: Anticipating needs before users ask (productivity tools)
- - **Sensory richness**: Satisfying sounds, smooth animations (creative tools)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Delight should enhance usability, never obscure it. If users notice the delight more than accomplishing their goal, you've gone too far.
-
-## Delight Principles
-
-Follow these guidelines:
-
-### Delight Amplifies, Never Blocks
-- Delight moments should be quick (< 1 second)
-- Never delay core functionality for delight
-- Make delight skippable or subtle
-- Respect user's time and task focus
-
-### Surprise and Discovery
-- Hide delightful details for users to discover
-- Reward exploration and curiosity
-- Don't announce every delight moment
-- Let users share discoveries with others
-
-### Appropriate to Context
-- Match delight to emotional moment (celebrate success, empathize with errors)
-- Respect the user's state (don't be playful during critical errors)
-- Match brand personality and audience expectations
-- Cultural sensitivity (what's delightful varies by culture)
-
-### Compound Over Time
-- Delight should remain fresh with repeated use
-- Vary responses (not same animation every time)
-- Reveal deeper layers with continued use
-- Build anticipation through patterns
-
-## Delight Techniques
-
-Add personality and joy through these methods:
-
-### Micro-interactions & Animation
-
-**Button delight**:
-```css
-/* Satisfying button press */
-.button {
- transition: transform 0.1s, box-shadow 0.1s;
-}
-.button:active {
- transform: translateY(2px);
- box-shadow: 0 2px 4px rgba(0,0,0,0.2);
-}
-
-/* Ripple effect on click */
-/* Smooth lift on hover */
-.button:hover {
- transform: translateY(-2px);
- transition: transform 0.2s cubic-bezier(0.25, 1, 0.5, 1); /* ease-out-quart */
-}
-```
-
-**Loading delight**:
-- Playful loading animations (not just spinners)
-- Personality in loading messages (write product-specific ones, not generic AI filler)
-- Progress indication with encouraging messages
-- Skeleton screens with subtle animations
-
-**Success animations**:
-- Checkmark draw animation
-- Confetti burst for major achievements
-- Gentle scale + fade for confirmation
-- Satisfying sound effects (subtle)
-
-**Hover surprises**:
-- Icons that animate on hover
-- Color shifts or glow effects
-- Tooltip reveals with personality
-- Cursor changes (custom cursors for branded experiences)
-
-### Personality in Copy
-
-**Playful error messages**:
-```
-"Error 404"
-"This page is playing hide and seek. (And winning)"
-
-"Connection failed"
-"Looks like the internet took a coffee break. Want to retry?"
-```
-
-**Encouraging empty states**:
-```
-"No projects"
-"Your canvas awaits. Create something amazing."
-
-"No messages"
-"Inbox zero! You're crushing it today."
-```
-
-**Playful labels & tooltips**:
-```
-"Delete"
-"Send to void" (for playful brand)
-
-"Help"
-"Rescue me" (tooltip)
-```
-
-**IMPORTANT**: Match copy personality to brand. Banks shouldn't be wacky, but they can be warm.
-
-### Illustrations & Visual Personality
-
-**Custom illustrations**:
-- Empty state illustrations (not stock icons)
-- Error state illustrations (friendly monsters, quirky characters)
-- Loading state illustrations (animated characters)
-- Success state illustrations (celebrations)
-
-**Icon personality**:
-- Custom icon set matching brand personality
-- Animated icons (subtle motion on hover/click)
-- Illustrative icons (more detailed than generic)
-- Consistent style across all icons
-
-**Background effects**:
-- Subtle particle effects
-- Gradient mesh backgrounds
-- Geometric patterns
-- Parallax depth
-- Time-of-day themes (morning vs night)
-
-### Satisfying Interactions
-
-**Drag and drop delight**:
-- Lift effect on drag (shadow, scale)
-- Snap animation when dropped
-- Satisfying placement sound
-- Undo toast ("Dropped in wrong place? [Undo]")
-
-**Toggle switches**:
-- Smooth slide with spring physics
-- Color transition
-- Haptic feedback on mobile
-- Optional sound effect
-
-**Progress & achievements**:
-- Streak counters with celebratory milestones
-- Progress bars that "celebrate" at 100%
-- Badge unlocks with animation
-- Playful stats ("You're on fire! 5 days in a row")
-
-**Form interactions**:
-- Input fields that animate on focus
-- Checkboxes with a satisfying scale pulse when checked
-- Success state that celebrates valid input
-- Auto-grow textareas
-
-### Sound Design
-
-**Subtle audio cues** (when appropriate):
-- Notification sounds (distinctive but not annoying)
-- Success sounds (satisfying "ding")
-- Error sounds (empathetic, not harsh)
-- Typing sounds for chat/messaging
-- Ambient background audio (very subtle)
-
-**IMPORTANT**:
-- Respect system sound settings
-- Provide mute option
-- Keep volumes quiet (subtle cues, not alarms)
-- Don't play on every interaction (sound fatigue is real)
-
-### Easter Eggs & Hidden Delights
-
-**Discovery rewards**:
-- Konami code unlocks special theme
-- Hidden keyboard shortcuts (Cmd+K for special features)
-- Hover reveals on logos or illustrations
-- Alt text jokes on images (for screen reader users too!)
-- Console messages for developers ("Like what you see? We're hiring!")
-
-**Seasonal touches**:
-- Holiday themes (subtle, tasteful)
-- Seasonal color shifts
-- Weather-based variations
-- Time-based changes (dark at night, light during day)
-
-**Contextual personality**:
-- Different messages based on time of day
-- Responses to specific user actions
-- Randomized variations (not same every time)
-- Progressive reveals with continued use
-
-### Loading & Waiting States
-
-**Make waiting engaging**:
-- Interesting loading messages that rotate
-- Progress bars with personality
-- Mini-games during long loads
-- Fun facts or tips while waiting
-- Countdown with encouraging messages
-
-```
-Loading messages: write ones specific to your product, not generic AI filler:
-- "Crunching your latest numbers..."
-- "Syncing with your team's changes..."
-- "Preparing your dashboard..."
-- "Checking for updates since yesterday..."
-```
-
-**WARNING**: Avoid cliched loading messages like "Herding pixels", "Teaching robots to dance", "Consulting the magic 8-ball", "Counting backwards from infinity". These are AI-slop copy, instantly recognizable as machine-generated. Write messages that are specific to what your product actually does.
-
-### Celebration Moments
-
-**Success celebrations**:
-- Confetti for major milestones
-- Animated checkmarks for completions
-- Progress bar celebrations at 100%
-- "Achievement unlocked" style notifications
-- Personalized messages ("You published your 10th article!")
-
-**Milestone recognition**:
-- First-time actions get special treatment
-- Streak tracking and celebration
-- Progress toward goals
-- Anniversary celebrations
-
-## Implementation Patterns
-
-**Animation libraries**:
-- Framer Motion (React)
-- GSAP (universal)
-- Lottie (After Effects animations)
-- Canvas confetti (party effects)
-
-**Sound libraries**:
-- Howler.js (audio management)
-- Use-sound (React hook)
-
-**Physics libraries**:
-- React Spring (spring physics)
-- Popmotion (animation primitives)
-
-**IMPORTANT**: File size matters. Compress images, optimize animations, lazy load delight features.
-
-**NEVER**:
-- Delay core functionality for delight
-- Force users through delightful moments (make skippable)
-- Use delight to hide poor UX
-- Overdo it (less is more)
-- Ignore accessibility (animate responsibly, provide alternatives)
-- Make every interaction delightful (special moments should be special)
-- Sacrifice performance for delight
-- Be inappropriate for context (read the room)
-
-## Verify Delight Quality
-
-Test that delight actually delights:
-
-- **User reactions**: Do users smile? Share screenshots?
-- **Doesn't annoy**: Still pleasant after 100th time?
-- **Doesn't block**: Can users opt out or skip?
-- **Performant**: No jank, no slowdown
-- **Appropriate**: Matches brand and context
-- **Accessible**: Works with reduced motion, screen readers
-
-When the moments feel earned, hand off to `/impeccable polish` for the final pass.
@@ -1,111 +0,0 @@
-Strip a design to its essence. Remove anything that doesn't earn its place: redundant elements, repeated information, decorative noise, cosmetic complexity.
-
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel complex or cluttered:
-
-1. **Identify complexity sources**:
- - **Too many elements**: Competing buttons, redundant information, visual clutter
- - **Excessive variation**: Too many colors, fonts, sizes, styles without purpose
- - **Information overload**: Everything visible at once, no progressive disclosure
- - **Visual noise**: Unnecessary borders, shadows, backgrounds, decorations
- - **Confusing hierarchy**: Unclear what matters most
- - **Feature creep**: Too many options, actions, or paths forward
-
-2. **Find the essence**:
- - What's the primary user goal? (There should be ONE)
- - What's actually necessary vs nice-to-have?
- - What can be removed, hidden, or combined?
- - What's the 20% that delivers 80% of value?
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Simplicity is not about removing features. It's about removing obstacles between users and their goals. Every element should justify its existence.
-
-## Plan Simplification
-
-Create a ruthless editing strategy:
-
-- **Core purpose**: What's the ONE thing this should accomplish?
-- **Essential elements**: What's truly necessary to achieve that purpose?
-- **Progressive disclosure**: What can be hidden until needed?
-- **Consolidation opportunities**: What can be combined or integrated?
-
-**IMPORTANT**: Simplification is hard. It requires saying no to good ideas to make room for great execution. Be ruthless.
-
-## Simplify the Design
-
-Systematically remove complexity across these dimensions:
-
-### Information Architecture
-- **Reduce scope**: Remove secondary actions, optional features, redundant information
-- **Progressive disclosure**: Hide complexity behind clear entry points (accordions, modals, step-through flows)
-- **Combine related actions**: Merge similar buttons, consolidate forms, group related content
-- **Clear hierarchy**: ONE primary action, few secondary actions, everything else tertiary or hidden
-- **Remove redundancy**: If it's said elsewhere, don't repeat it here
-
-### Visual Simplification
-- **Reduce color palette**: Use 1-2 colors plus neutrals, not 5-7 colors
-- **Limit typography**: One font family, 3-4 sizes maximum, 2-3 weights
-- **Remove decorations**: Eliminate borders, shadows, backgrounds that don't serve hierarchy or function
-- **Flatten structure**: Reduce nesting, remove unnecessary containers; never nest cards inside cards
-- **Remove unnecessary cards**: Cards aren't needed for basic layout; use spacing and alignment instead
-- **Consistent spacing**: Use one spacing scale, remove arbitrary gaps
-
-### Layout Simplification
-- **Linear flow**: Replace complex grids with simple vertical flow where possible
-- **Remove sidebars**: Move secondary content inline or hide it
-- **Full-width**: Use available space generously instead of complex multi-column layouts
-- **Consistent alignment**: Pick left or center, stick with it
-- **Generous white space**: Let content breathe, don't pack everything tight
-
-### Interaction Simplification
-- **Reduce choices**: Fewer buttons, fewer options, clearer path forward (paradox of choice is real)
-- **Smart defaults**: Make common choices automatic, only ask when necessary
-- **Inline actions**: Replace modal flows with inline editing where possible
-- **Remove steps**: Can signup be one step instead of three? Can checkout be simplified?
-- **Clear CTAs**: ONE obvious next step, not five competing actions
-
-### Content Simplification
-- **Shorter copy**: Cut every sentence in half, then do it again
-- **Active voice**: "Save changes" not "Changes will be saved"
-- **Remove jargon**: Plain language always wins
-- **Scannable structure**: Short paragraphs, bullet points, clear headings
-- **Essential information only**: Remove marketing fluff, legalese, hedging
-- **Remove redundant copy**: No headers restating intros, no repeated explanations, say it once
-
-### Code Simplification
-- **Remove unused code**: Dead CSS, unused components, orphaned files
-- **Flatten component trees**: Reduce nesting depth
-- **Consolidate styles**: Merge similar styles, use utilities consistently
-- **Reduce variants**: Does that component need 12 variations, or can 3 cover 90% of cases?
-
-**NEVER**:
-- Remove necessary functionality (simplicity ≠ feature-less)
-- Sacrifice accessibility for simplicity (clear labels and ARIA still required)
-- Make things so simple they're unclear (mystery ≠ minimalism)
-- Remove information users need to make decisions
-- Eliminate hierarchy completely (some things should stand out)
-- Oversimplify complex domains (match complexity to actual task complexity)
-
-## Verify Simplification
-
-Ensure simplification improves usability:
-
-- **Faster task completion**: Can users accomplish goals more quickly?
-- **Reduced cognitive load**: Is it easier to understand what to do?
-- **Still complete**: Are all necessary features still accessible?
-- **Clearer hierarchy**: Is it obvious what matters most?
-- **Better performance**: Does simpler design load faster?
-
-## Document Removed Complexity
-
-If you removed features or options:
-- Document why they were removed
-- Consider if they need alternative access points
-- Note any user feedback to monitor
-
-When the cuts feel right, hand off to `/impeccable polish` for the final pass. As Antoine de Saint-Exupéry put it: "Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away."
@@ -1,427 +0,0 @@
-Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
-
-DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
-
-## The frontmatter: token schema
-
-The YAML frontmatter is the machine-readable layer. It's what Stitch's linter validates and what the live panel renders tiles from. Keep it tight; every entry should correspond to a token the project actually uses.
-
-```yaml
----
-name: <project title>
-description: <one-line tagline>
-colors:
- primary: "#b8422e"
- neutral-bg: "#faf7f2"
- # ...one entry per extracted color; key = descriptive slug
-typography:
- display:
- fontFamily: "Cormorant Garamond, Georgia, serif"
- fontSize: "clamp(2.5rem, 7vw, 4.5rem)"
- fontWeight: 300
- lineHeight: 1
- letterSpacing: "normal"
- body:
- # ...
-rounded:
- sm: "4px"
- md: "8px"
-spacing:
- sm: "8px"
- md: "16px"
-components:
- button-primary:
- backgroundColor: "{colors.primary}"
- textColor: "{colors.neutral-bg}"
- rounded: "{rounded.sm}"
- padding: "16px 48px"
- button-primary-hover:
- backgroundColor: "{colors.primary-deep}"
----
-```
-
-Rules that matter:
-
-- **Token refs** use `{path.to.token}` (e.g. `{colors.primary}`, `{rounded.md}`). Components may reference primitives; primitives may not reference each other.
-- **Stitch validates colors as hex sRGB only** (`#RGB` / `#RGBA` / `#RRGGBB` / `#RRGGBBAA`); OKLCH/HSL/P3 trigger a linter warning, not a hard error. YAML accepts the string either way and our own parser is format-agnostic. Choose based on project posture: (a) if the project has an "OKLCH-only" doctrine or uses Display-P3 values that don't round-trip through sRGB, put OKLCH directly in the frontmatter and accept the Stitch linter warning; (b) if the project wants strict Stitch compliance or plans to use their Tailwind/DTCG export pipeline, put hex in the frontmatter and keep OKLCH in prose as the canonical reference. Never split the source of truth without explicit reason.
-- **Component sub-tokens** are limited to 8 props: `backgroundColor`, `textColor`, `typography`, `rounded`, `padding`, `size`, `height`, `width`. Shadows, motion, focus rings, backdrop-filter: none of those fit. Carry them in the sidecar (Step 4b).
-- **Scale keys are open-ended.** Use whatever names the project already uses (`warm-ash-cream`, `surface-container-low`). Don't rename to Material defaults.
-- **Variants are naming convention, not schema.** `button-primary` / `button-primary-hover` / `button-primary-active` as sibling keys.
-
-## The markdown body: six sections (exact order)
-
-1. `## Overview`
-2. `## Colors`
-3. `## Typography`
-4. `## Elevation`
-5. `## Components`
-6. `## Do's and Don'ts`
-
-Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] Palette` (Stitch's own outputs do this), but the literal word in each header (Overview, Colors, Typography, Elevation, Components, Do's and Don'ts) must be present. Do NOT add extra top-level sections (Layout Principles, Responsive Behavior, Motion, Agent Prompt Guide). Fold that content into the six spec sections where it naturally belongs.
-
-## When to run
-
-- The user just ran `/impeccable teach` and needs the visual side documented.
-- The skill noticed no `DESIGN.md` exists and nudged the user to create one.
-- An existing `DESIGN.md` is stale (the design has drifted).
-- Before a large redesign, to capture the current state as a reference.
-
-If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user the existing file and ask the user directly to clarify what you cannot infer. whether to refresh, overwrite, or merge.
-
-## Two paths
-
-- **Scan mode** (default): the project has design tokens, components, or rendered output. Extract, then confirm descriptive language. Use when there's code to analyze.
-- **Seed mode**: the project is pre-implementation (fresh teach, nothing built yet). Interview for five high-level answers, write a minimal DESIGN.md marked `<!-- SEED -->`. Re-run in scan mode once there's code.
-
-Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode; don't silently switch. `/impeccable document --seed` forces seed mode regardless of code presence.
-
-## Scan mode (approach C: auto-extract, then confirm descriptive language)
-
-### Step 1: Find the design assets
-
-Search the codebase in priority order:
-
-1. **CSS custom properties**: grep for `--color-`, `--font-`, `--spacing-`, `--radius-`, `--shadow-`, `--ease-`, `--duration-` declarations in CSS files (usually `src/styles/`, `public/css/`, `app/globals.css`, etc.). Record name, value, and the file it's defined in.
-2. **Tailwind config**: if `tailwind.config.{js,ts,mjs}` exists, read the `theme.extend` block for colors, fontFamily, spacing, borderRadius, boxShadow.
-3. **CSS-in-JS theme files**: styled-components, emotion, vanilla-extract, stitches; look for `theme.ts`, `tokens.ts`, or equivalent.
-4. **Design token files**: `tokens.json`, `design-tokens.json`, Style Dictionary output, W3C token community group format.
-5. **Component library**: scan the main button, card, input, navigation, dialog components. Note their variant APIs and default styles.
-6. **Global stylesheet**: the root CSS file usually has the base typography and color assignments.
-7. **Visible rendered output**: if browser automation tools are available, load the live site and sample computed styles from key elements (body, h1, a, button, .card). This catches values that tokens miss.
-
-### Step 2: Auto-extract what can be auto-extracted
-
-Build a structured draft from the discovered tokens. For each token class:
-
-- **Colors**: Group into Primary / Secondary / Tertiary / Neutral (the Material-derived roles Stitch uses). If the project only has one accent, express it as Primary + Neutral; omit Secondary and Tertiary rather than inventing them.
-- **Typography**: Map observed sizes and weights to the Material hierarchy (display / headline / title / body / label). Note font-family stacks and the scale ratio.
-- **Elevation**: Catalogue the shadow vocabulary. If the project is flat and uses tonal layering instead, that's a valid answer; state it explicitly.
-- **Components**: For each common component (button, card, input, chip, list item, tooltip, nav), extract shape (radius), color assignment, hover/focus treatment, internal padding.
-- **Spacing + layout**: Fold into Overview or relevant Components. The spec does NOT have a Layout section.
-
-### Step 2b: Stage the frontmatter
-
-From the auto-extracted tokens, draft the YAML frontmatter now (you'll write it at the top of DESIGN.md in Step 4). This is the machine-readable layer: what the live panel and Stitch's linter consume.
-
-- **Colors**: one entry per extracted color. Key = descriptive slug (`warm-ash-cream`, `editorial-magenta`, not `blue-800`). Value = whichever format the project treats as canonical (OKLCH or hex; see the frontmatter rules above). Don't split the source of truth: one format in the frontmatter, don't redefine the same token in prose with a different value.
-- **Typography**: one entry per role (`display`, `headline`, `title`, `body`, `label`). Typography is an object; include only the props that are real for the project (`fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `fontFeature`, `fontVariation`).
-- **Rounded / Spacing**: whatever scale steps the project actually uses, keyed by whatever scale name the project uses (`sm` / `md` / `lg`, or `surface-sm`, or numeric steps).
-- **Components**: one entry per variant (`button-primary`, `button-primary-hover`, `button-ghost`). Reference primitives via `{colors.X}`, `{rounded.Y}`. If a variant needs a property Stitch's 8-prop set doesn't cover (shadow, focus ring, backdrop-filter), carry the full snippet in the sidecar instead.
-
-Skip anything the project doesn't have. Empty scale keys or fabricated tokens pollute the spec.
-
-### Step 3: Ask the user for qualitative language
-
-The following require creative input that cannot be auto-extracted. Group them into one `AskUserQuestion` interaction:
-
-- **Creative North Star**: a single named metaphor for the whole system ("The Editorial Sanctuary", "The Golden State Curator", "The Lab Notebook"). Offer 2-3 options that honor PRODUCT.md's brand personality.
-- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, anti-references (what the system should not feel like).
-- **Color character** (for auto-extracted colors): descriptive names ("Deep Muted Teal-Navy", not "blue-800"). Suggest 2-3 options per key color based on hue/saturation.
-- **Elevation philosophy**: flat/layered/lifted. If shadows exist, is their role ambient or structural?
-- **Component philosophy**: the feel of buttons, cards, inputs in one phrase ("tactile and confident" vs. "refined and restrained").
-
-Quote a line from PRODUCT.md when possible so the user sees their own strategic language carry forward.
-
-### Step 4: Write DESIGN.md
-
-The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the structure below. Headers must match character-for-character. Optional evocative subtitles (e.g. `## 2. Colors: The Coastal Palette`) are allowed.
-
-```markdown
----
-name: [Project Title]
-description: [one-line tagline]
-colors:
- # ... staged frontmatter from Step 2b
----
-
-# Design System: [Project Title]
-
-## 1. Overview
-
-**Creative North Star: "[Named metaphor in quotes]"**
-
-[2-3 paragraph holistic description: personality, density, aesthetic philosophy. Start from the North Star and work outward. State what this system explicitly rejects (pulled from PRODUCT.md's anti-references). End with a short **Key Characteristics:** bullet list.]
-
-## 2. Colors
-
-[Describe the palette character in one sentence.]
-
-### Primary
-- **[Descriptive Name]** (#HEX / oklch(...)): [Where and why this color is used. Be specific about context, not just role.]
-
-### Secondary (optional; omit if the project has only one accent)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Tertiary (optional)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Neutral
-- **[Descriptive Name]** (#HEX): [Text / background / border / divider role.]
-- [...]
-
-### Named Rules (optional, powerful)
-**The [Rule Name] Rule.** [Short, forceful prohibition or doctrine, e.g. "The One Voice Rule. The primary accent is used on ≤10% of any given screen. Its rarity is the point."]
-
-## 3. Typography
-
-**Display Font:** [Family] (with [fallback])
-**Body Font:** [Family] (with [fallback])
-**Label/Mono Font:** [Family, if distinct]
-
-**Character:** [1-2 sentence personality description of the pairing.]
-
-### Hierarchy
-- **Display** ([weight], [size/clamp], [line-height]): [Purpose; where it appears.]
-- **Headline** ([weight], [size], [line-height]): [Purpose.]
-- **Title** ([weight], [size], [line-height]): [Purpose.]
-- **Body** ([weight], [size], [line-height]): [Purpose. Include max line length like 65–75ch if relevant.]
-- **Label** ([weight], [size], [letter-spacing], [case if uppercase]): [Purpose.]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [Short doctrine about type use.]
-
-## 4. Elevation
-
-[One paragraph: does this system use shadows, tonal layering, or a hybrid? If "no shadows", say so explicitly and describe how depth is conveyed instead.]
-
-### Shadow Vocabulary (if applicable)
-- **[Role name]** (`box-shadow: [exact value]`): [When to use it.]
-- [...]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [e.g. "The Flat-By-Default Rule. Surfaces are flat at rest. Shadows appear only as a response to state (hover, elevation, focus)."]
-
-## 5. Components
-
-For each component, lead with a short character line, then specify shape, color assignment, states, and any distinctive behavior.
-
-### Buttons
-- **Shape:** [radius described, exact value in parens]
-- **Primary:** [color assignment + padding, in semantic + exact terms]
-- **Hover / Focus:** [transitions, treatments]
-- **Secondary / Ghost / Tertiary (if applicable):** [brief description]
-
-### Chips (if used)
-- **Style:** [background, text color, border treatment]
-- **State:** [selected / unselected, filter / action variants]
-
-### Cards / Containers
-- **Corner Style:** [radius]
-- **Background:** [colors used]
-- **Shadow Strategy:** [reference Elevation section]
-- **Border:** [if any]
-- **Internal Padding:** [scale]
-
-### Inputs / Fields
-- **Style:** [stroke, background, radius]
-- **Focus:** [treatment, e.g. glow, border shift, etc.]
-- **Error / Disabled:** [if applicable]
-
-### Navigation
-- **Style, typography, default/hover/active states, mobile treatment.**
-
-### [Signature Component] (optional; if the project has a distinctive custom component worth documenting)
-[Description.]
-
-## 6. Do's and Don'ts
-
-Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: include exact colors, pixel values, and named anti-patterns the user mentioned in PRODUCT.md. **Every anti-reference in PRODUCT.md should show up here as a "Don't" with the same language**, so the visual spec carries the strategic line through. Quote PRODUCT.md directly where possible: if PRODUCT.md says *"avoid dark mode with purple gradients, neon accents, glassmorphism"*, the Don'ts here should repeat that by name.
-
-### Do:
-- **Do** [specific prescription with exact values / named rule].
-- **Do** [...]
-
-### Don't:
-- **Don't** [specific prohibition, e.g. "use border-left greater than 1px as a colored stripe"].
-- **Don't** [...]
-- **Don't** [...]
-```
-
-### Step 4b: Write .impeccable/design.json sidecar (extensions only)
-
-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.
-
-Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.
-
-#### Schema
-
-```json
-{
- "schemaVersion": 2,
- "generatedAt": "ISO-8601 string",
- "title": "Design System: [Project Title]",
- "extensions": {
- "colorMeta": {
- "primary": { "role": "primary", "displayName": "Editorial Magenta", "canonical": "oklch(60% 0.25 350)", "tonalRamp": ["...", "...", "..."] },
- "warm-ash-cream": { "role": "neutral", "displayName": "Warm Ash Cream", "canonical": "oklch(96% 0.005 350)", "tonalRamp": ["...", "...", "..."] }
- },
- "typographyMeta": {
- "display": { "displayName": "Display", "purpose": "Hero headlines only." }
- },
- "shadows": [
- { "name": "ambient-low", "value": "0 4px 24px rgba(0,0,0,0.12)", "purpose": "Diffuse hover glow under accent elements." }
- ],
- "motion": [
- { "name": "ease-standard", "value": "cubic-bezier(0.4, 0, 0.2, 1)", "purpose": "Default easing for state transitions." }
- ],
- "breakpoints": [
- { "name": "sm", "value": "640px" }
- ]
- },
- "components": [
- {
- "name": "Primary Button",
- "kind": "button | input | nav | chip | card | custom",
- "refersTo": "button-primary",
- "description": "One-line what and when.",
- "html": "<button class=\"ds-btn-primary\">GET STARTED</button>",
- "css": ".ds-btn-primary { background: #191c1d; color: #fff; padding: 16px 48px; letter-spacing: 0.05em; text-transform: uppercase; font-weight: 500; border: none; border-radius: 0; transition: background 0.2s, transform 0.2s; } .ds-btn-primary:hover { background: oklch(60% 0.25 350); transform: translateY(-2px); }"
- }
- ],
- "narrative": {
- "northStar": "The Editorial Sanctuary",
- "overview": "2-3 paragraphs of the philosophy, pulled from DESIGN.md Overview section.",
- "keyCharacteristics": ["...", "..."],
- "rules": [{ "name": "The One Voice Rule", "body": "...", "section": "colors|typography|elevation" }],
- "dos": ["Do use ..."],
- "donts": ["Don't use ..."]
- }
-}
-```
-
-**What changed from schemaVersion 1.** The old sidecar carried token primitive arrays (`tokens.colors[]`, `tokens.typography[]`, etc.). Those values now live in the frontmatter. The sidecar only carries metadata that can't live in the frontmatter (tonal ramps, canonical OKLCH when the hex is an approximation, display names, role hints), keyed by the frontmatter token name (`colorMeta.<token-name>`, `typographyMeta.<token-name>`). Components still carry full HTML/CSS because Stitch's 8-prop set can't hold them.
-
-#### Component translation rules
-
-The `html` and `css` fields must be **self-contained, drop-in snippets** that render correctly when injected into a shadow DOM. The panel applies them directly: no post-processing, no framework runtime.
-
-1. **Tailwind expansion.** If the source uses Tailwind (className="bg-primary text-white rounded-lg px-6 py-3"), expand every utility to literal CSS properties in the `css` string. Do **not** reference Tailwind classes; do **not** assume a Tailwind CSS bundle is loaded. Each component is self-contained.
-2. **Token resolution.** If the project exposes tokens as CSS custom properties on `:root` (e.g. `--color-primary`, `--radius-md`), reference them via `var(--color-primary)`; they inherit through the shadow DOM and stay live-bound. If tokens live only in JS theme objects (styled-components, CSS-in-JS), resolve to literal values at generation time.
-3. **Icons.** Inline as SVG. Do not reference Lucide/Heroicons packages, icon fonts, or `<img src="...">`. A typical icon is 16-24px; copy the SVG path data directly.
-4. **States.** Include `:hover`, `:focus-visible`, and (if meaningful) `:active` rules inline. A static default-only snapshot makes the panel feel dead. Hover + focus rules in the CSS make it feel alive.
-5. **Reset bloat.** Extract only the component's *distinctive* CSS (background, color, padding, border-radius, typography, transition). Skip universal resets (`box-sizing: border-box`, `line-height: inherit`, `-webkit-font-smoothing`). The panel already has a neutral canvas; don't re-ship resets.
-6. **Scoped class names.** Prefix every class with `ds-` (e.g. `ds-btn-primary`, `ds-input-search`) so component CSS doesn't collide with other components' CSS in the same shadow DOM.
-
-#### What to include
-
-Aim for a tight set of **5-10 components** that best represent the visual system:
-
-- **Canonical primitives (always include if the project has them):** button (each variant as a separate component entry), input/text field, navigation, chip/tag, card.
-- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.
-- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.
-
-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.
-
-#### Tonal ramps
-
-For each color token, generate an 8-step `tonalRamp` array: dark to light, same hue and chroma, stepped lightness from ~15% to ~95%. The panel renders this as a strip under the swatch. If the project already defines a tonal scale (Material `surface-container-low` family, Tailwind-style `blue-50..blue-900`), use those values. Otherwise synthesize in OKLCH.
-
-#### Narrative mapping
-
-Pull directly from the DESIGN.md you just wrote:
-
-- `narrative.northStar` → the `**Creative North Star: "..."**` line from Overview
-- `narrative.overview` → the philosophy paragraphs from Overview
-- `narrative.keyCharacteristics` → the bulleted `**Key Characteristics:**` list
-- `narrative.rules` → every `**The [Name] Rule.** [body]` across all sections, tagged with `section`
-- `narrative.dos` / `narrative.donts` → the bullet lists from Do's and Don'ts verbatim
-
-Do not reword. The panel shows these as secondary collapsible context; the same voice that's in the Markdown carries through.
-
-### Step 5: Confirm, refine, and refresh session cache
-
-1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).
-2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.
-3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"
-4. **Refresh the session cache.** Run `node .kiro/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.
-
-## Seed mode
-
-For projects with no visual system to extract yet. Produces a minimal scaffold, not a full spec.
-
-### Step 1: Confirm seed mode
-
-Before interviewing: "There's no existing visual system to scan. I'll ask five quick questions to seed a starter DESIGN.md. You can re-run `/impeccable document` once there's code, to capture the real tokens and components. OK?"
-
-If the user prefers to skip, stop. No file.
-
-### Step 2: Five questions
-
-Group into one `AskUserQuestion` interaction. Options must be concrete.
-
-1. **Color strategy.** Pick one:
- - Restrained: tinted neutrals + one accent ≤10%
- - Committed: one saturated color carries 30–60% of the surface
- - Full palette: 3–4 named color roles, each deliberate
- - Drenched: the surface IS the color
-
- Then: one hue family or anchor reference ("deep teal", "mustard", "Klim #ff4500 orange").
-
-2. **Typography direction.** Pick one (specific fonts come later):
- - Serif display + sans body
- - Single sans (warm / technical / geometric / humanist; pick a feel)
- - Display + mono
- - Mono-forward
- - Editorial script + sans
-
-3. **Motion energy.** Pick one:
- - Restrained: state changes only
- - Responsive: feedback + transitions, no choreography
- - Choreographed: orchestrated entrances, scroll-driven sequences
-
-4. **Three named references.** Brands, products, printed objects. Not adjectives.
-
-5. **One anti-reference.** What it should NOT feel like. Also named.
-
-### Step 3: Write seed DESIGN.md
-
-Use the six-section spec from Scan mode. Populate what the interview answers; leave the rest as honest placeholders. The seed is a scaffold, not a fabricated spec.
-
-Lead the file with:
-
-```markdown
-<!-- SEED: re-run /impeccable document once there's code to capture the actual tokens and components. -->
-```
-
-Per-section guidance in seed mode:
-
-- **Overview**: Creative North Star and philosophy phrased from the answers (color strategy + motion energy + references). Reference the user's anti-reference directly.
-- **Colors**: Color strategy as a Named Rule (e.g. *"The Drenched Rule. The surface IS the color."*). Hue family or anchor reference. No hex values; mark as `[to be resolved during implementation]`.
-- **Typography**: the direction the user picked (e.g. "Serif display + sans body"). No font names yet: `[font pairing to be chosen at implementation]`.
-- **Elevation**: inferred from motion energy. Restrained/Responsive → flat by default; Choreographed → layered. One sentence.
-- **Components**: omit entirely; no components exist yet.
-- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.
-
-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.
-
-### Step 4: Confirm and refresh session cache
-
-1. Show the seed DESIGN.md. Call out that it is a seed (the marker is the literal commitment).
-2. Tell the user: "Re-run `/impeccable document` once you have some code. That pass will extract real tokens and generate the sidecar."
-3. Run `node .kiro/skills/impeccable/scripts/load-context.mjs` once so the seed lands in conversation for the rest of the session.
-
-## Style guidelines
-
-- **Frontmatter first, prose second.** Tokens go in the YAML frontmatter; prose contextualizes them. Don't redefine a token value in two places; the frontmatter is normative.
-- **Cite PRODUCT.md anti-references by name** in the Do's and Don'ts section. If PRODUCT.md lists "SaaS landing-page clichés" or "generic AI tool marketing" as anti-references, the DESIGN.md Don'ts should repeat those phrases verbatim so the visual spec enforces the strategic line.
-- **Match the spec, don't invent new sections.** The six section names are fixed. If you have Layout/Motion/Responsive content to document, fold it into Overview (philosophy-level rules) or Components (per-component behavior).
-- **Descriptive > technical**: "Gently curved edges (8px radius)" > "rounded-lg". Include the technical value in parens, lead with the description.
-- **Functional > decorative**: for each token, explain WHERE and WHY it's used, not just WHAT it is.
-- **Exact values in parens**: hex codes, px/rem values, font weights; always the number in parens alongside the description.
-- **Use Named Rules**: `**The [Name] Rule.** [short doctrine]`. These are memorable, citable, and much stickier for AI consumers than bullet lists. Stitch's own outputs use them heavily ("The No-Line Rule", "The Ghost Border Fallback"). Aim for 1-3 per section.
-- **Be forceful**. The voice of a design director. "Prohibited", "forbidden", "never", "always", not "consider", "might", "prefer". Match PRODUCT.md's tone.
-- **Concrete anti-pattern tests**. Stitch writes things like *"If it looks like a 2014 app, the shadow is too dark and the blur is too small."* A one-sentence audit test beats a paragraph of principle.
-- **Reference PRODUCT.md**. The anti-references section of PRODUCT.md should directly inform the Do's and Don'ts section here. Quote or paraphrase.
-- **Group colors by role**, not by hex-order or hue-order. Primary / Secondary / Tertiary / Neutral is the spec ordering.
-
-## Pitfalls
-
-- Don't paste raw CSS class names. Translate to descriptive language.
-- Don't extract every token. Stop at what's actually reused; one-offs pollute the system.
-- Don't invent components that don't exist. If the project only has buttons and cards, only document those.
-- Don't overwrite an existing DESIGN.md without asking.
-- Don't duplicate content from PRODUCT.md. DESIGN.md is strictly visual.
-- Don't add a "Layout Principles" or "Motion" or "Responsive Behavior" top-level section. The spec has six, not nine. Fold that content where it belongs.
-- Don't rename sections even slightly. "Colors" not "Color Palette & Roles". "Typography" not "Typography Rules". Tooling parsing depends on exact headers.
-- Don't duplicate token values between frontmatter and prose. If a color is in `colors.primary` as hex, the prose can name it and describe its role but should not reassert a different hex. The frontmatter is normative.
-- Don't invent frontmatter token groups outside Stitch's schema (no `motion:`, `breakpoints:`, `shadows:` at the top level). Stitch's Zod schema only accepts `colors`, `typography`, `rounded`, `spacing`, `components`. Anything else belongs in the sidecar's `extensions`.
@@ -1,69 +0,0 @@
-# Extract Flow
-
-Identify reusable patterns, components, and design tokens, then extract and consolidate them into the design system for systematic reuse.
-
-## Step 1: Discover the Design System
-
-Find the design system, component library, or shared UI directory. Understand its structure: component organization, naming conventions, design token structure, import/export conventions.
-
-**CRITICAL**: If no design system exists, ask the user directly to clarify what you cannot infer. before creating one. Understand the preferred location and structure first.
-
-## Step 2: Identify Patterns
-
-Look for extraction opportunities in the target area:
-
-- **Repeated components**: Similar UI patterns used 3+ times (buttons, cards, inputs)
-- **Hard-coded values**: Colors, spacing, typography, shadows that should be tokens
-- **Inconsistent variations**: Multiple implementations of the same concept
-- **Composition patterns**: Layout or interaction patterns that repeat (form rows, toolbar groups, empty states)
-- **Type styles**: Repeated font-size + weight + line-height combinations
-- **Animation patterns**: Repeated easing, duration, or keyframe combinations
-
-Assess value: only extract things used 3+ times with the same intent. Premature abstraction is worse than duplication.
-
-## Step 3: Plan Extraction
-
-Create a systematic plan:
-
-- **Components to extract**: Which UI elements become reusable components?
-- **Tokens to create**: Which hard-coded values become design tokens?
-- **Variants to support**: What variations does each component need?
-- **Naming conventions**: Component names, token names, prop names that match existing patterns
-- **Migration path**: How to refactor existing uses to consume the new shared versions
-
-**IMPORTANT**: Design systems grow incrementally. Extract what is clearly reusable now, not everything that might someday be reusable.
-
-## Step 4: Extract & Enrich
-
-Build improved, reusable versions:
-
-- **Components**: Clear props API with sensible defaults, proper variants for different use cases, accessibility built in (ARIA, keyboard navigation, focus management), documentation and usage examples
-- **Design tokens**: Clear naming (primitive vs semantic), proper hierarchy and organization, documentation of when to use each token
-- **Patterns**: When to use this pattern, code examples, variations and combinations
-
-## Step 5: Migrate
-
-Replace existing uses with the new shared versions:
-
-- **Find all instances**: Search for the patterns you extracted
-- **Replace systematically**: Update each use to consume the shared version
-- **Test thoroughly**: Ensure visual and functional parity
-- **Delete dead code**: Remove the old implementations
-
-## Step 6: Document
-
-Update design system documentation:
-
-- Add new components to the component library
-- Document token usage and values
-- Add examples and guidelines
-- Update any Storybook or component catalog
-
-**NEVER**:
-- Extract one-off, context-specific implementations without generalization
-- Create components so generic they are useless
-- Extract without considering existing design system conventions
-- Skip proper TypeScript types or prop documentation
-- Create tokens for every single value (tokens should have semantic meaning)
-- Extract things that differ in intent (two buttons that look similar but serve different purposes should stay separate)
-
@@ -1,347 +0,0 @@
-Designs that only work with perfect data aren't production-ready. Harden the interface against the inputs, errors, languages, and network conditions that real users will throw at it.
-
-## Assess Hardening Needs
-
-Identify weaknesses and edge cases:
-
-1. **Test with extreme inputs**:
- - Very long text (names, descriptions, titles)
- - Very short text (empty, single character)
- - Special characters (emoji, RTL text, accents)
- - Large numbers (millions, billions)
- - Many items (1000+ list items, 50+ options)
- - No data (empty states)
-
-2. **Test error scenarios**:
- - Network failures (offline, slow, timeout)
- - API errors (400, 401, 403, 404, 500)
- - Validation errors
- - Permission errors
- - Rate limiting
- - Concurrent operations
-
-3. **Test internationalization**:
- - Long translations (German is often 30% longer than English)
- - RTL languages (Arabic, Hebrew)
- - Character sets (Chinese, Japanese, Korean, emoji)
- - Date/time formats
- - Number formats (1,000 vs 1.000)
- - Currency symbols
-
-**CRITICAL**: Designs that only work with perfect data aren't production-ready. Harden against reality.
-
-## Hardening Dimensions
-
-Systematically improve resilience:
-
-### Text Overflow & Wrapping
-
-**Long text handling**:
-```css
-/* Single line with ellipsis */
-.truncate {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* Multi-line with clamp */
-.line-clamp {
- display: -webkit-box;
- -webkit-line-clamp: 3;
- -webkit-box-orient: vertical;
- overflow: hidden;
-}
-
-/* Allow wrapping */
-.wrap {
- word-wrap: break-word;
- overflow-wrap: break-word;
- hyphens: auto;
-}
-```
-
-**Flex/Grid overflow**:
-```css
-/* Prevent flex items from overflowing */
-.flex-item {
- min-width: 0; /* Allow shrinking below content size */
- overflow: hidden;
-}
-
-/* Prevent grid items from overflowing */
-.grid-item {
- min-width: 0;
- min-height: 0;
-}
-```
-
-**Responsive text sizing**:
-- Use `clamp()` for fluid typography
-- Set minimum readable sizes (14px on mobile)
-- Test text scaling (zoom to 200%)
-- Ensure containers expand with text
-
-### Internationalization (i18n)
-
-**Text expansion**:
-- Add 30-40% space budget for translations
-- Use flexbox/grid that adapts to content
-- Test with longest language (usually German)
-- Avoid fixed widths on text containers
-
-```jsx
-// ❌ Bad: Assumes short English text
-<button className="w-24">Submit</button>
-
-// ✅ Good: Adapts to content
-<button className="px-4 py-2">Submit</button>
-```
-
-**RTL (Right-to-Left) support**:
-```css
-/* Use logical properties */
-margin-inline-start: 1rem; /* Not margin-left */
-padding-inline: 1rem; /* Not padding-left/right */
-border-inline-end: 1px solid; /* Not border-right */
-
-/* Or use dir attribute */
-[dir="rtl"] .arrow { transform: scaleX(-1); }
-```
-
-**Character set support**:
-- Use UTF-8 encoding everywhere
-- Test with Chinese/Japanese/Korean (CJK) characters
-- Test with emoji (they can be 2-4 bytes)
-- Handle different scripts (Latin, Cyrillic, Arabic, etc.)
-
-**Date/Time formatting**:
-```javascript
-// ✅ Use Intl API for proper formatting
-new Intl.DateTimeFormat('en-US').format(date); // 1/15/2024
-new Intl.DateTimeFormat('de-DE').format(date); // 15.1.2024
-
-new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: 'USD'
-}).format(1234.56); // $1,234.56
-```
-
-**Pluralization**:
-```javascript
-// ❌ Bad: Assumes English pluralization
-`${count} item${count !== 1 ? 's' : ''}`
-
-// ✅ Good: Use proper i18n library
-t('items', { count }) // Handles complex plural rules
-```
-
-### Error Handling
-
-**Network errors**:
-- Show clear error messages
-- Provide retry button
-- Explain what happened
-- Offer offline mode (if applicable)
-- Handle timeout scenarios
-
-```jsx
-// Error states with recovery
-{error && (
- <ErrorMessage>
- <p>Failed to load data. {error.message}</p>
- <button onClick={retry}>Try again</button>
- </ErrorMessage>
-)}
-```
-
-**Form validation errors**:
-- Inline errors near fields
-- Clear, specific messages
-- Suggest corrections
-- Don't block submission unnecessarily
-- Preserve user input on error
-
-**API errors**:
-- Handle each status code appropriately
- - 400: Show validation errors
- - 401: Redirect to login
- - 403: Show permission error
- - 404: Show not found state
- - 429: Show rate limit message
- - 500: Show generic error, offer support
-
-**Graceful degradation**:
-- Core functionality works without JavaScript
-- Images have alt text
-- Progressive enhancement
-- Fallbacks for unsupported features
-
-### Edge Cases & Boundary Conditions
-
-**Empty states**:
-- No items in list
-- No search results
-- No notifications
-- No data to display
-- Provide clear next action
-
-**Loading states**:
-- Initial load
-- Pagination load
-- Refresh
-- Show what's loading ("Loading your projects...")
-- Time estimates for long operations
-
-**Large datasets**:
-- Pagination or virtual scrolling
-- Search/filter capabilities
-- Performance optimization
-- Don't load all 10,000 items at once
-
-**Concurrent operations**:
-- Prevent double-submission (disable button while loading)
-- Handle race conditions
-- Optimistic updates with rollback
-- Conflict resolution
-
-**Permission states**:
-- No permission to view
-- No permission to edit
-- Read-only mode
-- Clear explanation of why
-
-**Browser compatibility**:
-- Polyfills for modern features
-- Fallbacks for unsupported CSS
-- Feature detection (not browser detection)
-- Test in target browsers
-
-### Input Validation & Sanitization
-
-**Client-side validation**:
-- Required fields
-- Format validation (email, phone, URL)
-- Length limits
-- Pattern matching
-- Custom validation rules
-
-**Server-side validation** (always):
-- Never trust client-side only
-- Validate and sanitize all inputs
-- Protect against injection attacks
-- Rate limiting
-
-**Constraint handling**:
-```html
-<!-- Set clear constraints -->
-<input
- type="text"
- maxlength="100"
- pattern="[A-Za-z0-9]+"
- required
- aria-describedby="username-hint"
-/>
-<small id="username-hint">
- Letters and numbers only, up to 100 characters
-</small>
-```
-
-### Accessibility Resilience
-
-**Keyboard navigation**:
-- All functionality accessible via keyboard
-- Logical tab order
-- Focus management in modals
-- Skip links for long content
-
-**Screen reader support**:
-- Proper ARIA labels
-- Announce dynamic changes (live regions)
-- Descriptive alt text
-- Semantic HTML
-
-**Motion sensitivity**:
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**High contrast mode**:
-- Test in Windows high contrast mode
-- Don't rely only on color
-- Provide alternative visual cues
-
-### Performance Resilience
-
-**Slow connections**:
-- Progressive image loading
-- Skeleton screens
-- Optimistic UI updates
-- Offline support (service workers)
-
-**Memory leaks**:
-- Clean up event listeners
-- Cancel subscriptions
-- Clear timers/intervals
-- Abort pending requests on unmount
-
-**Throttling & Debouncing**:
-```javascript
-// Debounce search input
-const debouncedSearch = debounce(handleSearch, 300);
-
-// Throttle scroll handler
-const throttledScroll = throttle(handleScroll, 100);
-```
-
-## Testing Strategies
-
-**Manual testing**:
-- Test with extreme data (very long, very short, empty)
-- Test in different languages
-- Test offline
-- Test slow connection (throttle to 3G)
-- Test with screen reader
-- Test keyboard-only navigation
-- Test on old browsers
-
-**Automated testing**:
-- Unit tests for edge cases
-- Integration tests for error scenarios
-- E2E tests for critical paths
-- Visual regression tests
-- Accessibility tests (axe, WAVE)
-
-**IMPORTANT**: Hardening is about expecting the unexpected. Real users will do things you never imagined.
-
-**NEVER**:
-- Assume perfect input (validate everything)
-- Ignore internationalization (design for global)
-- Leave error messages generic ("Error occurred")
-- Forget offline scenarios
-- Trust client-side validation alone
-- Use fixed widths for text
-- Assume English-length text
-- Block entire interface when one component errors
-
-## Verify Hardening
-
-Test thoroughly with edge cases:
-
-- **Long text**: Try names with 100+ characters
-- **Emoji**: Use emoji in all text fields
-- **RTL**: Test with Arabic or Hebrew
-- **CJK**: Test with Chinese/Japanese/Korean
-- **Network issues**: Disable internet, throttle connection
-- **Large datasets**: Test with 1000+ items
-- **Concurrent actions**: Click submit 10 times rapidly
-- **Errors**: Force API errors, test all error states
-- **Empty**: Remove all data, test empty states
-
-When edge cases are covered, hand off to `/impeccable polish` for the final pass.
@@ -1,234 +0,0 @@
-# Heuristics Scoring Guide
-
-Score each of Nielsen's 10 Usability Heuristics on a 0–4 scale. Be honest: a 4 means genuinely excellent, not "good enough."
-
-## Nielsen's 10 Heuristics
-
-### 1. Visibility of System Status
-
-Keep users informed about what's happening through timely, appropriate feedback.
-
-**Check for**:
-- Loading indicators during async operations
-- Confirmation of user actions (save, submit, delete)
-- Progress indicators for multi-step processes
-- Current location in navigation (breadcrumbs, active states)
-- Form validation feedback (inline, not just on submit)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No feedback; user is guessing what happened |
-| 1 | Rare feedback; most actions produce no visible response |
-| 2 | Partial; some states communicated, major gaps remain |
-| 3 | Good; most operations give clear feedback, minor gaps |
-| 4 | Excellent; every action confirms, progress is always visible |
-
-### 2. Match Between System and Real World
-
-Speak the user's language. Follow real-world conventions. Information appears in natural, logical order.
-
-**Check for**:
-- Familiar terminology (no unexplained jargon)
-- Logical information order matching user expectations
-- Recognizable icons and metaphors
-- Domain-appropriate language for the target audience
-- Natural reading flow (left-to-right, top-to-bottom priority)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Pure tech jargon, alien to users |
-| 1 | Mostly confusing; requires domain expertise to navigate |
-| 2 | Mixed; some plain language, some jargon leaks through |
-| 3 | Mostly natural; occasional term needs context |
-| 4 | Speaks the user's language fluently throughout |
-
-### 3. User Control and Freedom
-
-Users need a clear "emergency exit" from unwanted states without extended dialogue.
-
-**Check for**:
-- Undo/redo functionality
-- Cancel buttons on forms and modals
-- Clear navigation back to safety (home, previous)
-- Easy way to clear filters, search, selections
-- Escape from long or multi-step processes
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Users get trapped; no way out without refreshing |
-| 1 | Difficult exits; must find obscure paths to escape |
-| 2 | Some exits; main flows have escape, edge cases don't |
-| 3 | Good control; users can exit and undo most actions |
-| 4 | Full control; undo, cancel, back, and escape everywhere |
-
-### 4. Consistency and Standards
-
-Users shouldn't wonder whether different words, situations, or actions mean the same thing.
-
-**Check for**:
-- Consistent terminology throughout the interface
-- Same actions produce same results everywhere
-- Platform conventions followed (standard UI patterns)
-- Visual consistency (colors, typography, spacing, components)
-- Consistent interaction patterns (same gesture = same behavior)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Inconsistent everywhere; feels like different products stitched together |
-| 1 | Many inconsistencies; similar things look/behave differently |
-| 2 | Partially consistent; main flows match, details diverge |
-| 3 | Mostly consistent; occasional deviation, nothing confusing |
-| 4 | Fully consistent; cohesive system, predictable behavior |
-
-### 5. Error Prevention
-
-Better than good error messages is a design that prevents problems in the first place.
-
-**Check for**:
-- Confirmation before destructive actions (delete, overwrite)
-- Constraints preventing invalid input (date pickers, dropdowns)
-- Smart defaults that reduce errors
-- Clear labels that prevent misunderstanding
-- Autosave and draft recovery
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Errors easy to make; no guardrails anywhere |
-| 1 | Few safeguards; some inputs validated, most aren't |
-| 2 | Partial prevention; common errors caught, edge cases slip |
-| 3 | Good prevention; most error paths blocked proactively |
-| 4 | Excellent; errors nearly impossible through smart constraints |
-
-### 6. Recognition Rather Than Recall
-
-Minimize memory load. Make objects, actions, and options visible or easily retrievable.
-
-**Check for**:
-- Visible options (not buried in hidden menus)
-- Contextual help when needed (tooltips, inline hints)
-- Recent items and history
-- Autocomplete and suggestions
-- Labels on icons (not icon-only navigation)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Heavy memorization; users must remember paths and commands |
-| 1 | Mostly recall; many hidden features, few visible cues |
-| 2 | Some aids; main actions visible, secondary features hidden |
-| 3 | Good recognition; most things discoverable, few memory demands |
-| 4 | Everything discoverable; users never need to memorize |
-
-### 7. Flexibility and Efficiency of Use
-
-Accelerators, invisible to novices, speed up expert interaction.
-
-**Check for**:
-- Keyboard shortcuts for common actions
-- Customizable interface elements
-- Recent items and favorites
-- Bulk/batch actions
-- Power user features that don't complicate the basics
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | One rigid path; no shortcuts or alternatives |
-| 1 | Limited flexibility; few alternatives to the main path |
-| 2 | Some shortcuts; basic keyboard support, limited bulk actions |
-| 3 | Good accelerators; keyboard nav, some customization |
-| 4 | Highly flexible; multiple paths, power features, customizable |
-
-### 8. Aesthetic and Minimalist Design
-
-Interfaces should not contain irrelevant or rarely needed information. Every element should serve a purpose.
-
-**Check for**:
-- Only necessary information visible at each step
-- Clear visual hierarchy directing attention
-- Purposeful use of color and emphasis
-- No decorative clutter competing for attention
-- Focused, uncluttered layouts
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Overwhelming; everything competes for attention equally |
-| 1 | Cluttered; too much noise, hard to find what matters |
-| 2 | Some clutter; main content clear, periphery noisy |
-| 3 | Mostly clean; focused design, minor visual noise |
-| 4 | Perfectly minimal; every element earns its pixel |
-
-### 9. Help Users Recognize, Diagnose, and Recover from Errors
-
-Error messages should use plain language, precisely indicate the problem, and constructively suggest a solution.
-
-**Check for**:
-- Plain language error messages (no error codes for users)
-- Specific problem identification ("Email is missing @" not "Invalid input")
-- Actionable recovery suggestions
-- Errors displayed near the source of the problem
-- Non-blocking error handling (don't wipe the form)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Cryptic errors; codes, jargon, or no message at all |
-| 1 | Vague errors; "Something went wrong" with no guidance |
-| 2 | Clear but unhelpful; names the problem but not the fix |
-| 3 | Clear with suggestions; identifies problem and offers next steps |
-| 4 | Perfect recovery; pinpoints issue, suggests fix, preserves user work |
-
-### 10. Help and Documentation
-
-Even if the system is usable without docs, help should be easy to find, task-focused, and concise.
-
-**Check for**:
-- Searchable help or documentation
-- Contextual help (tooltips, inline hints, guided tours)
-- Task-focused organization (not feature-organized)
-- Concise, scannable content
-- Easy access without leaving current context
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No help available anywhere |
-| 1 | Help exists but hard to find or irrelevant |
-| 2 | Basic help; FAQ or docs exist, not contextual |
-| 3 | Good documentation; searchable, mostly task-focused |
-| 4 | Excellent contextual help; right info at the right moment |
-
----
-
-## Score Summary
-
-**Total possible**: 40 points (10 heuristics × 4 max)
-
-| Score Range | Rating | What It Means |
-|-------------|--------|---------------|
-| 36–40 | Excellent | Minor polish only; ship it |
-| 28–35 | Good | Address weak areas, solid foundation |
-| 20–27 | Acceptable | Significant improvements needed before users are happy |
-| 12–19 | Poor | Major UX overhaul required; core experience broken |
-| 0–11 | Critical | Redesign needed; unusable in current state |
-
----
-
-## Issue Severity (P0–P3)
-
-Tag each individual issue found during scoring with a priority level:
-
-| Priority | Name | Description | Action |
-|----------|------|-------------|--------|
-| **P0** | Blocking | Prevents task completion entirely | Fix immediately; this is a showstopper |
-| **P1** | Major | Causes significant difficulty or confusion | Fix before release |
-| **P2** | Minor | Annoyance, but workaround exists | Fix in next pass |
-| **P3** | Polish | Nice-to-fix, no real user impact | Fix if time permits |
-
-**Tip**: If you're unsure between two levels, ask: "Would a user contact support about this?" If yes, it's at least P1.
@@ -1,195 +0,0 @@
-# Interaction Design
-
-## The Eight Interactive States
-
-Every interactive element needs these states designed:
-
-| State | When | Visual Treatment |
-|-------|------|------------------|
-| **Default** | At rest | Base styling |
-| **Hover** | Pointer over (not touch) | Subtle lift, color shift |
-| **Focus** | Keyboard/programmatic focus | Visible ring (see below) |
-| **Active** | Being pressed | Pressed in, darker |
-| **Disabled** | Not interactive | Reduced opacity, no pointer |
-| **Loading** | Processing | Spinner, skeleton |
-| **Error** | Invalid state | Red border, icon, message |
-| **Success** | Completed | Green check, confirmation |
-
-**The common miss**: Designing hover without focus, or vice versa. They're different. Keyboard users never see hover states.
-
-## Focus Rings: Do Them Right
-
-**Never `outline: none` without replacement.** It's an accessibility violation. Instead, use `:focus-visible` to show focus only for keyboard users:
-
-```css
-/* Hide focus ring for mouse/touch */
-button:focus {
- outline: none;
-}
-
-/* Show focus ring for keyboard */
-button:focus-visible {
- outline: 2px solid var(--color-accent);
- outline-offset: 2px;
-}
-```
-
-**Focus ring design**:
-- High contrast (3:1 minimum against adjacent colors)
-- 2-3px thick
-- Offset from element (not inside it)
-- Consistent across all interactive elements
-
-## Form Design: The Non-Obvious
-
-**Placeholders aren't labels.** They disappear on input. Always use visible `<label>` elements. **Validate on blur**, not on every keystroke (exception: password strength). Place errors **below** fields with `aria-describedby` connecting them.
-
-## Loading States
-
-**Optimistic updates**: Show success immediately, rollback on failure. Use for low-stakes actions (likes, follows), not payments or destructive actions. **Skeleton screens > spinners**: they preview content shape and feel faster than generic spinners.
-
-## Modals: The Inert Approach
-
-Focus trapping in modals used to require complex JavaScript. Now use the `inert` attribute:
-
-```html
-<!-- When modal is open -->
-<main inert>
- <!-- Content behind modal can't be focused or clicked -->
-</main>
-<dialog open>
- <h2>Modal Title</h2>
- <!-- Focus stays inside modal -->
-</dialog>
-```
-
-Or use the native `<dialog>` element:
-
-```javascript
-const dialog = document.querySelector('dialog');
-dialog.showModal(); // Opens with focus trap, closes on Escape
-```
-
-## The Popover API
-
-For tooltips, dropdowns, and non-modal overlays, use native popovers:
-
-```html
-<button popovertarget="menu">Open menu</button>
-<div id="menu" popover>
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-**Benefits**: Light-dismiss (click outside closes), proper stacking, no z-index wars, accessible by default.
-
-## Dropdown & Overlay Positioning
-
-Dropdowns rendered with `position: absolute` inside a container that has `overflow: hidden` or `overflow: auto` will be clipped. This is the single most common dropdown bug in generated code.
-
-### CSS Anchor Positioning
-
-The modern solution uses the CSS Anchor Positioning API to tether an overlay to its trigger without JavaScript:
-
-```css
-.trigger {
- anchor-name: --menu-trigger;
-}
-
-.dropdown {
- position: fixed;
- position-anchor: --menu-trigger;
- position-area: block-end span-inline-end;
- margin-top: 4px;
-}
-
-/* Flip above if no room below */
-@position-try --flip-above {
- position-area: block-start span-inline-end;
- margin-bottom: 4px;
-}
-```
-
-Because the dropdown uses `position: fixed`, it escapes any `overflow` clipping on ancestor elements. The `@position-try` block handles viewport edges automatically. **Browser support**: Chrome 125+, Edge 125+. Not yet in Firefox or Safari - use a fallback for those browsers.
-
-### Popover + Anchor Combo
-
-Combining the Popover API with anchor positioning gives you stacking, light-dismiss, accessibility, and correct positioning in one pattern:
-
-```html
-<button popovertarget="menu" class="trigger">Open</button>
-<div id="menu" popover class="dropdown">
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-The `popover` attribute places the element in the **top layer**, which sits above all other content regardless of z-index or overflow. No portal needed.
-
-### Portal / Teleport Pattern
-
-In component frameworks, render the dropdown at the document root and position it with JavaScript:
-
-- **React**: `createPortal(dropdown, document.body)`
-- **Vue**: `<Teleport to="body">`
-- **Svelte**: Use a portal library or mount to `document.body`
-
-Calculate position from the trigger's `getBoundingClientRect()`, then apply `position: fixed` with `top` and `left` values. Recalculate on scroll and resize.
-
-### Fixed Positioning Fallback
-
-For browsers without anchor positioning support, `position: fixed` with manual coordinates avoids overflow clipping:
-
-```css
-.dropdown {
- position: fixed;
- /* top/left set via JS from trigger's getBoundingClientRect() */
-}
-```
-
-Check viewport boundaries before rendering. If the dropdown would overflow the bottom edge, flip it above the trigger. If it would overflow the right edge, align it to the trigger's right side instead.
-
-### Anti-Patterns
-
-- **`position: absolute` inside `overflow: hidden`** - The dropdown will be clipped. Use `position: fixed` or the top layer instead.
-- **Arbitrary z-index values** like `z-index: 9999` - Use a semantic z-index scale: `dropdown (100) -> sticky (200) -> modal-backdrop (300) -> modal (400) -> toast (500) -> tooltip (600)`.
-- **Rendering dropdown markup inline** without an escape hatch from the parent's stacking context. Either use `popover` (top layer), a portal, or `position: fixed`.
-
-## Destructive Actions: Undo > Confirm
-
-**Undo is better than confirmation dialogs.** Users click through confirmations mindlessly. Remove from UI immediately, show undo toast, actually delete after toast expires. Use confirmation only for truly irreversible actions (account deletion), high-cost actions, or batch operations.
-
-## Keyboard Navigation Patterns
-
-### Roving Tabindex
-
-For component groups (tabs, menu items, radio groups), one item is tabbable; arrow keys move within:
-
-```html
-<div role="tablist">
- <button role="tab" tabindex="0">Tab 1</button>
- <button role="tab" tabindex="-1">Tab 2</button>
- <button role="tab" tabindex="-1">Tab 3</button>
-</div>
-```
-
-Arrow keys move `tabindex="0"` between items. Tab moves to the next component entirely.
-
-### Skip Links
-
-Provide skip links (`<a href="#main-content">Skip to main content</a>`) for keyboard users to jump past navigation. Hide off-screen, show on focus.
-
-## Gesture Discoverability
-
-Swipe-to-delete and similar gestures are invisible. Hint at their existence:
-
-- **Partially reveal**: Show delete button peeking from edge
-- **Onboarding**: Coach marks on first use
-- **Alternative**: Always provide a visible fallback (menu with "Delete")
-
-Don't rely on gestures as the only way to perform actions.
-
----
-
-**Avoid**: Removing focus indicators without alternatives. Using placeholder text as labels. Touch targets <44x44px. Generic error messages. Custom controls without ARIA/keyboard support.
@@ -1,141 +0,0 @@
-Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids, the centered-stack default) and fix the structure, not the surface.
-
----
-
-## Register
-
-Brand: asymmetric compositions, fluid spacing with `clamp()`, intentional grid-breaking for emphasis. Rhythm through contrast: tight groupings paired with generous separations.
-
-Product: predictable grids, consistent densities, familiar navigation patterns. Responsive behavior is structural (collapse sidebar, responsive table), not fluid typography. Consistency IS an affordance.
-
----
-
-## Assess Current Layout
-
-Analyze what's weak about the current spatial design:
-
-1. **Spacing**:
- - Is spacing consistent or arbitrary? (Random padding/margin values)
- - Is all spacing the same? (Equal padding everywhere = no rhythm)
- - Are related elements grouped tightly, with generous space between groups?
-
-2. **Visual hierarchy**:
- - Apply the squint test: blur your (metaphorical) eyes. Can you still identify the most important element, second most important, and clear groupings?
- - Is hierarchy achieved effectively? (Space and weight alone can be enough; is the current approach working?)
- - Does whitespace guide the eye to what matters?
-
-3. **Grid & structure**:
- - Is there a clear underlying structure, or does the layout feel random?
- - Are identical card grids used everywhere? (Icon + heading + text, repeated endlessly)
- - Is everything centered? (Left-aligned with asymmetric layouts feels more designed, but not a hard and fast rule)
-
-4. **Rhythm & variety**:
- - Does the layout have visual rhythm? (Alternating tight/generous spacing)
- - Is every section structured the same way? (Monotonous repetition)
- - Are there intentional moments of surprise or emphasis?
-
-5. **Density**:
- - Is the layout too cramped? (Not enough breathing room)
- - Is the layout too sparse? (Excessive whitespace without purpose)
- - Does density match the content type? (Data-dense UIs need tighter spacing; marketing pages need more air)
-
-**CRITICAL**: Layout problems are often the root cause of interfaces feeling "off" even when colors and fonts are fine. Space is a design material; use it with intention.
-
-## Plan Layout Improvements
-
-Consult the [spatial design reference](spatial-design.md) for detailed guidance on grids, rhythm, and container queries.
-
-Create a systematic plan:
-
-- **Spacing system**: Use a consistent scale (a framework's built-in scale like Tailwind's, rem-based tokens, or a custom system). The specific values matter less than consistency.
-- **Hierarchy strategy**: How will space communicate importance?
-- **Layout approach**: What structure fits the content? Flex for 1D, Grid for 2D, named areas for complex page layouts.
-- **Rhythm**: Where should spacing be tight vs generous?
-
-## Improve Layout Systematically
-
-### Establish a Spacing System
-
-- Use a consistent spacing scale (framework scales like Tailwind, rem-based tokens, or a custom scale all work). What matters is that values come from a defined set, not arbitrary numbers.
-- Name tokens semantically if using custom properties: `--space-xs` through `--space-xl`, not `--spacing-8`
-- Use `gap` for sibling spacing instead of margins; eliminates margin collapse hacks
-- Apply `clamp()` for fluid spacing that breathes on larger screens
-
-### Create Visual Rhythm
-
-- **Tight grouping** for related elements (8-12px between siblings)
-- **Generous separation** between distinct sections (48-96px)
-- **Varied spacing** within sections (not every row needs the same gap)
-- **Asymmetric compositions**: break the predictable centered-content pattern when it makes sense
-
-### Choose the Right Layout Tool
-
-- **Use Flexbox for 1D layouts**: Rows of items, nav bars, button groups, card contents, most component internals. Flex is simpler and more appropriate for the majority of layout tasks.
-- **Use Grid for 2D layouts**: Page-level structure, dashboards, data-dense interfaces, anything where rows AND columns need coordinated control.
-- **Don't default to Grid** when Flexbox with `flex-wrap` would be simpler and more flexible.
-- Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints.
-- Use named grid areas (`grid-template-areas`) for complex page layouts; redefine at breakpoints.
-
-### Break Card Grid Monotony
-
-- Don't default to card grids for everything; spacing and alignment create visual grouping naturally
-- Use cards only when content is truly distinct and actionable. Never nest cards inside cards
-- Vary card sizes, span columns, or mix cards with non-card content to break repetition
-
-### Strengthen Visual Hierarchy
-
-- Use the fewest dimensions needed for clear hierarchy. Space alone can be enough; generous whitespace around an element draws the eye. Some of the most polished designs achieve rhythm with just space and weight. Add color or size contrast only when simpler means aren't sufficient.
-- Be aware of reading flow: in LTR languages, the eye naturally scans top-left to bottom-right, but primary action placement depends on context (e.g., bottom-right in dialogs, top in navigation).
-- Create clear content groupings through proximity and separation.
-
-### Manage Depth & Elevation
-
-- Create a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip)
-- Build a consistent shadow scale (sm → md → lg → xl); shadows should be subtle
-- Use elevation to reinforce hierarchy, not as decoration
-
-### Optical Adjustments
-
-- If an icon looks visually off-center despite being geometrically centered, nudge it. But only if you're confident it actually looks wrong. Don't adjust speculatively.
-
-**NEVER**:
-- Use arbitrary spacing values outside your scale
-- Make all spacing equal (variety creates hierarchy)
-- Wrap everything in cards (not everything needs a container)
-- Nest cards inside cards (use spacing and dividers for hierarchy within)
-- Use identical card grids everywhere (icon + heading + text, repeated)
-- Center everything (left-aligned with asymmetry feels more designed)
-- Default to the hero metric layout (big number, small label, stats, gradient) as a template. If showing real user data, a prominent metric can work, but it should display actual data, not decorative numbers.
-- Default to CSS Grid when Flexbox would be simpler; use the simplest tool for the job
-- Use arbitrary z-index values (999, 9999); build a semantic scale
-
-## Verify Layout Improvements
-
-- **Squint test**: Can you identify primary, secondary, and groupings with blurred vision?
-- **Rhythm**: Does the page have a satisfying beat of tight and generous spacing?
-- **Hierarchy**: Is the most important content obvious within 2 seconds?
-- **Breathing room**: Does the layout feel comfortable, not cramped or wasteful?
-- **Consistency**: Is the spacing system applied uniformly?
-- **Responsiveness**: Does the layout adapt gracefully across screen sizes?
-
-When the rhythm and hierarchy land, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `density` param. Drive all spacing tokens in the variant's scoped CSS through `calc(var(--p-density, 1) * <base>)`: paddings, gaps, column widths. Users slide from airy to packed and see layout re-breathe with no regeneration.
-
-```json
-{"id":"density","kind":"range","min":0.6,"max":1.4,"step":0.05,"default":1,"label":"Density"}
-```
-
-For variants whose topology genuinely changes (stacked vs. side-by-side, grid vs. bento), use a `steps` param whose scoped CSS branches via `:scope[data-p-structure="X"]`. One structure param + one density param is a powerful combo; resist adding a third.
-
-```json
-{"id":"structure","kind":"steps","default":"grid","label":"Structure","options":[
- {"value":"stacked","label":"Stacked"},
- {"value":"grid","label":"Grid"},
- {"value":"bento","label":"Bento"}
-]}
-```
-
-See `reference/live.md` for the full params contract.
@@ -1,622 +0,0 @@
-Interactive live variant mode: select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via the dev server's HMR.
-
-## Prerequisites
-
-A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR a static HTML file open in the browser.
-
-## The contract (read once)
-
-Execute in order. No step skipped, no step reordered.
-
-1. `live.mjs`: boot.
-2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.
-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.
-5. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
-6. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
-7. On `exit`: run the cleanup at the bottom.
-
-Harness policy:
-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.
-- **Cursor**: run the poll in the **foreground** (blocking shell; not a background terminal, not a subagent). Cursor background terminals and subagents do not reliably resume the chat with poll stdout.
-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.
-- **Other harnesses**: foreground unless you know stdout reliably returns to this session.
-
-Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.
-
-## Start
-
-```bash
-node .kiro/skills/impeccable/scripts/live.mjs
-```
-
-Output JSON: `{ ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath, migrated }`. `pageFiles` is the list of HTML entries the live script was injected into. Keep PRODUCT.md and DESIGN.md in mind for variant generation; **DESIGN.md wins on visual decisions; PRODUCT.md wins on strategic/voice decisions.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt. If `migrated: true`, the loader auto-renamed legacy `.impeccable.md` to `PRODUCT.md`; mention this once and suggest `/impeccable document` for the matching DESIGN.md.
-
-`serverPort` and `serverToken` belong to the small **Impeccable live helper** HTTP server (serves `/live.js`, SSE, and `/poll`). That port is **not** your dev server and is usually not the URL you open to view the app. The browser page is whatever origin serves one of the `pageFiles` entries (Vite / Next / Bun / tunnel / LAN hostname).
-
-If output is `{ ok: false, error: "config_missing" | "config_invalid", path }`, this project hasn't been configured for live mode (or its config is stale). See **First-time setup** at the bottom.
-
-## Poll loop
-
-```
-LOOP:
- node .kiro/skills/impeccable/scripts/live-poll.mjs # default long timeout; no --timeout=
- Read JSON; dispatch on "type"
-
- "generate" → Handle Generate; reply done; LOOP
- "accept" → Handle Accept; complete carbonize cleanup if required; LOOP
- "discard" → Handle Discard; LOOP
- "prefetch" → Handle Prefetch; LOOP
- "timeout" → LOOP
- "exit" → break → Cleanup
-```
-
-## Recovery commands
-
-The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.
-
-Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:
-
-```bash
-node .kiro/skills/impeccable/scripts/live-status.mjs
-node .kiro/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID
-node .kiro/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID
-```
-
-- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.
-- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.
-- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.
-
-Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.
-
-## Handle `generate`
-
-Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.
-
-Speed matters; the user is watching a spinner. Minimize tool calls by using the `wrap` helper and writing all variants in a single edit.
-
-### 1. Read the screenshot (if present)
-
-`event.screenshotPath` is **only sent when the user placed at least one comment or stroke before Go.** When present, it's an absolute path to a PNG of the element as rendered with the annotations baked in. **Read it before planning**: annotations encode user intent not recoverable from `element.outerHTML` alone.
-
-When `screenshotPath` is absent, don't ask for one and don't go looking for the current rendering. The omission is deliberate: without annotations, a screenshot would anchor the model on the existing design and fight the three-distinct-directions brief. Work from `element.outerHTML`, the computed styles in `event.element`, and the freeform prompt if present.
-
-`event.comments` and `event.strokes` carry structured metadata alongside the visual. Treat the screenshot as primary; use the structured data for specifics worth quoting (e.g. the exact text of a comment).
-
-Reading annotations precisely:
-
-- **Comment position carries meaning.** Its `{x, y}` is element-local CSS px (same coord space as `element.boundingRect`). Find the child under that point and apply the comment text LOCALLY to that sub-element. A comment near the title is about the title, not a global description.
-- **Comments and strokes are independent annotations** unless clearly paired by overlap or tight proximity. Don't let the visual weight of a prominent stroke override the precise location of a textually-specific comment elsewhere.
-- **Strokes are gestures; read them by shape.** Closed loop = "this thing" (emphasis / focus); arrow = direction (move / point to); cross or slash = delete; free scribble = emphasis or delete depending on context. A loop around region X means "pay attention to X," not "only change pixels inside X."
-- **When a stroke's intent is ambiguous** (circle or arrow? emphasis or move?), state your reading in one sentence of rationale rather than silently guessing. If the uncertainty materially changes the brief, ask one short clarifying question before generating.
-
-### 2. Wrap the element
-
-```bash
-node .kiro/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"
-```
-
-Flag mapping. Keep them separate, don't collapse into `--query`:
-
-- `--element-id` ← `event.element.id`
-- `--classes` ← `event.element.classes` joined with commas
-- `--tag` ← `event.element.tagName`
-- `--text` ← first ~80 chars of `event.element.textContent` (trim, single-line). **Pass this every call.** When the picked element shares classes + tag with sibling components (a list of `<Card>`s, repeating sections), this is what disambiguates which branch in source to wrap. Without it, wrap silently lands on the first match and may rewrite the wrong element.
-
-The helper searches ID first, then classes, then tag + class combo. If `event.pageUrl` implies the file (e.g. `/` is usually `index.html`), pass `--file PATH` to skip the search. `--query` is a fallback for raw text search only; do not use it for normal element lookups.
-
-If `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.
-
-Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.
-
-`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:
-
-- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.
-- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.
-
-Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.
-
-**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:
-
-- `{ error: "file_is_generated", file, hint }`: user-supplied `--file` points at a generated file.
-- `{ error: "element_not_in_source", generatedMatch, hint }`: element exists only in a generated file (the next build would wipe any edits).
-- `{ error: "element_not_found", hint }`: element isn't in any project file; likely runtime-injected (JS component, dynamic render from data).
-
-All three carry `fallback: "agent-driven"`. Follow **Handle fallback** below.
-
-### 3. Load the action's reference
-
-If `event.action` is `impeccable` (the default freeform action), use SKILL.md's shared laws plus the loaded register reference (`brand.md` or `product.md`). Do not load a sub-command reference. **Freeform is not a pass to skip parameters:** you still follow the composition budget and the freeform bias in **§7 Parameters** below. Sub-command files list MUST-have signature knobs; freeform has no such file, so sizing knobs from surface weight and primary axes is entirely on you.
-
-Any other `event.action` (`bolder`, `quieter`, `distill`, `polish`, `typeset`, `colorize`, `layout`, `adapt`, `animate`, `delight`, `overdrive`): Read `reference/<action>.md` before planning. Each sub-command encodes a specific discipline; skipping its reference produces generic output. Those files may require specific params; layer them on top of the §7 budget, not instead of it.
-
-### 4. Plan three variants: identity first, then mode, then axes
-
-The wrong frame for live mode is "show three different design directions." Live runs on an existing surface; the brand has already been chosen. The job is variation **within identity**, not selection between identities. Failure mode: three editorial-typographic variants on a brief that wasn't editorial. Bigger failure mode: three off-brand variants the user can't accept because they don't look like their product.
-
-Four phases. Do them in order.
-
-#### Phase A: Extract the identity (non-skippable)
-
-The existing surface has an identity already. Read it before planning anything. Sources, in priority order:
-
-1. **DESIGN.md** if loaded: read the visual system fields (palette, type pairing, motion, components). This is the authoritative answer.
-2. **CSS custom properties** in the page's stylesheets (`:root { --color-...; --font-...; ... }`): these are de-facto tokens.
-3. **Computed styles** on the picked element and its parent: colors, fonts, spacing scales, corner radii.
-4. **Sibling components on the page**: what visual rhetoric do existing components use? (Asymmetric or centered? Dense or airy? Bold or quiet?)
-
-Write down what you see in **one sentence**. The sentence describes the surface that's actually on screen; it is not aspirational, not opinionated, not edited toward what the brand "should" be. Capture, in roughly this order:
-
-- The dominant surface color and accent color, by hex or token name (use the actual values, not categories like "warm" or "neutral").
-- The type pairing: the actual font names loaded, primary first.
-- The layout topology: how the dominant elements are arranged (stacked / side-by-side / grid / asymmetric / overlay).
-- The surface treatment: corners, borders, shadows, density of decoration.
-- The voice tone you read off the copy itself, not off the aesthetic feel.
-
-Be specific. "Modern" is not a color, "elegant" is not a type pairing, "clean" is not a layout. If you can't extract a real value for an axis, skip it rather than fabricate. The point is to record what is, not to describe what you wish it were.
-
-Do not include adjectives that name an aesthetic family ("editorial-leaning", "terminal-flavored", "brutalist"); those are conclusions, not data. They belong to Phase C lane selection in departure mode, not to identity description. Letting them sneak into Phase A is how the identity-lock collapses into a self-fulfilling prophecy.
-
-This sentence is the **identity lock**. Every variant must be readable as the same brand if rendered side by side. Skipping this phase is the primary cause of off-brand variants. Absence of DESIGN.md is never an excuse; extract from CSS and computed styles instead.
-
-#### Phase B: Pick mode (default vs departure)
-
-**Default mode**: the existing identity is preserved. Variants vary expression axes within it. *This is the right mode for ~90% of live sessions.* The user picked an element on a real product they're shipping; they expect variants of *their* hero, not three different brands' heroes.
-
-**Departure mode**: the existing identity is rejected. Variants propose alternatives consistent with PRODUCT.md voice. Trigger only when at least one is true:
-
-- PRODUCT.md anti-references explicitly call out the current surface ("the current `index.html` is itself an example"; "diffuse away from this"; "the page on screen is the failure"). Generic anti-references that describe what to avoid in general do **not** trigger departure mode; only ones that point at *this* surface specifically.
-- The user's freeform prompt explicitly asks for departure ("rebuild this from scratch", "what if it weren't editorial at all", "show me something completely different").
-
-If you're unsure, you're in default mode. The cost of being wrong about default is "three on-brand variants with similar feel": recoverable, the user picks none. The cost of being wrong about departure is "three off-brand variants": unrecoverable, the user is annoyed.
-
-#### Phase C: Plan three variants
-
-**Default mode.** Each variant commits to a different **primary axis** of difference, while preserving the identity sentence. The six axes:
-
-1. **Hierarchy**: which element commands the eye?
-2. **Layout topology**: stacked / side-by-side / grid / asymmetric / overlay
-3. **Typographic system**: pairing logic, scale ratio, case/weight strategy *within the available faces*
-4. **Color strategy**: which existing palette role carries the surface (Restrained / Committed / Full palette / Drenched). Use the brand's existing palette tokens, not new colors.
-5. **Density**: minimal / comfortable / dense
-6. **Structural decomposition**: merge, split, progressive disclosure
-
-Three variants → three DIFFERENT axes. The trio reads as *the same brand at three angles*. Do not introduce new fonts, new palette hues, or new aesthetic-family signals; those belong to departure mode.
-
-**While planning each variant, also name its 2–3 parameter knobs** (per the §7 budget table). Parameters are part of the design, not a decoration added afterward. If the variant explores density, expose a density knob. If it explores color commitment, expose a color-amount range. Deciding "what's tunable" during planning produces better knobs than retrofitting them onto finished HTML.
-
-**Departure mode.** Each variant anchors to a different **aesthetic direction**, derived from the brand's stated voice and register in PRODUCT.md. Do NOT pick from a fixed catalog of lane categories. The right three directions for this brand are not the same as the right three for another brand, and picking from a list is itself the training-data reflex (the model selects "Swiss-grid, Terminal, Industrial-signage" every time because those are the furthest-from-editorial items in any enumerated list).
-
-Instead, work from the brand:
-
-1. Read PRODUCT.md's Brand Personality words. What physical, spatial, or material experiences would embody those words if design were not involved? (A personality described as "specific, earned, unmistakable" evokes a hand-stamped letter, a numbered print, a watchmaker's loupe. A personality described as "restless, loud, unfiltered" evokes a concert poster, a spray-painted wall, a megaphone.)
-2. From those physical experiences, derive three visual directions that are genuinely different from each other AND from the current surface you're departing.
-3. Avoid the **reflex-reject lanes** in [brand.md](brand.md). Don't trade one monoculture for another. If you find yourself reaching for "Swiss-grid" or "Terminal" or "Industrial-signage" by reflex, you are pattern-matching a catalog in your training data, not reading the brand. Start over from the personality words.
-4. Each direction must be expressible in one concrete sentence that names a real-world referent ("a museum exhibition label system for a contemporary art gallery" not "clean and minimal"). If your sentence contains only adjectives, it's not concrete enough.
-5. **While planning each direction, also name its 2–3 parameter knobs** (per the §7 budget table). The same principle as default mode: decide "what's tunable" during planning, not after writing the HTML. A departure-mode hero with 0 parameters is not "bold creative vision," it's a missed opportunity for the user to fine-tune the direction they pick.
-
-#### Phase D: Squint test
-
-**Default mode squint.** Read each variant's identity sentence and compare to the locked identity from Phase A. If any variant has drifted to a different palette, type voice, or visual rhetoric, it has crossed into departure mode by accident; rework. Then check that each variant commits to a different primary axis. Three "tighter density" variants is failure.
-
-**Departure mode squint.** Two passes, family before sentence:
-
-1. **Family pass.** Label each variant with one design-family word of your own choosing (any concrete noun: *exhibition, storefront, cockpit, recipe-card, playbill, field-manual*). If any two variants share a label, or if the label could apply to the other variants equally well, rework. Do not use a fixed vocabulary list for the labels. *This pass is non-negotiable in departure mode and catches the monoculture failure that the sentence pass misses.*
-2. **Sentence pass.** Write three one-sentence descriptions side by side. If two of them rhyme ("both feature big type" / "both are stacks of sections" / "both center the CTA"), rework the offender.
-
-**When the primary axis is color or theme, forbid the trio from sharing theme + dominant hue.** Two dark-plus-one-dark is not distinct. Aim for three color worlds, not three shades of the same.
-
-**For action-specific invocations**, each variant must vary along the dimension the action names:
-
-- `bolder`: amplify a different dimension per variant (scale / saturation / structural change). Not three "slightly bigger" variants.
-- `quieter`: pull back a different dimension (color / ornament / spacing).
-- `distill`: remove a different class of excess (visual noise / redundant content / nested structure).
-- `polish`: target a different refinement axis (rhythm / hierarchy / micro-details like corner radii, focus states, optical kerning).
-- `typeset`: different type pairing AND different scale ratio each. Not three riffs on one pairing.
-- `colorize`: different hue family each (not shades of one hue). Vary chroma and contrast strategy.
-- `layout`: different structural arrangement (stacked / side-by-side / grid / asymmetric). Not spacing tweaks.
-- `adapt`: different target context per variant (mobile-first / tablet / desktop / print or low-data). Don't make three mobile layouts.
-- `animate`: different motion vocabulary (cascade stagger / clip wipe / scale-and-focus / morph / parallax). Not three staggered fades.
-- `delight`: different flavor of personality (unexpected micro-interaction / typographic surprise / illustrated accent / sonic-or-haptic moment / easter-egg interaction).
-- `overdrive`: different convention broken (scale / structure / motion / input model / state transitions). Skip `overdrive.md`'s "propose and ask" step; live mode is non-interactive.
-
-### 5. Apply the freeform prompt (if present)
-
-`event.freeformPrompt` is the user's ceiling on direction (all variants must honor it), but still explore meaningfully different *interpretations*. The interpretations stay within whichever mode you picked in Phase B.
-
-In **default mode**, the prompt narrows the axes you choose, not the identity. *"Make it feel more confident"* → variant 1 amplifies hierarchy (one element commands the eye), variant 2 commits the existing accent color (Committed strategy on the brand's hue), variant 3 tightens density and removes decorative slack. Three different axes, same brand.
-
-In **departure mode**, the prompt narrows the lanes you draw from, not the families. *"Make it feel like a newspaper front page"* would itself be a departure-mode prompt; honor it but pick three meaningfully different newspaper-adjacent lanes (broadsheet vs. tabloid vs. trade journal), and run the family pass to confirm they don't collapse into one.
-
-When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.
-
-### 6. Write all variants in a single edit
-
-Complete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).
-
-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).
-
-Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:
-
-```html
-<!-- Variants: insert below this line -->
-<style data-impeccable-css="SESSION_ID">
- /* rules matching cssAuthoring.rulePattern */
-</style>
-<div data-impeccable-variant="1">
- <!-- variant 1: full element replacement (single top-level element) -->
-</div>
-<div data-impeccable-variant="2" style="display: none">
- <!-- variant 2: full element replacement -->
-</div>
-<div data-impeccable-variant="3" style="display: none">
- <!-- variant 3: full element replacement -->
-</div>
-```
-
-**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.
-
-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.
-
-One edit, all variants; the browser's MutationObserver picks everything up in one pass.
-
-For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.
-
-**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:
-
-```tsx
-<style data-impeccable-css="SESSION_ID">{`
- @scope ([data-impeccable-variant="1"]) { ... }
- @scope ([data-impeccable-variant="2"]) { ... }
-`}</style>
-<div data-impeccable-variant="1">
- {/* variant 1 */}
-</div>
-<div data-impeccable-variant="2" style={{ display: 'none' }}>
- {/* variant 2 */}
-</div>
-```
-
-The wrap script already gives you a single-rooted JSX wrapper: a `<div data-impeccable-variants="…">` outer element with the marker comments tucked inside. Drop the variants block above into the "Variants: insert below this line" comment and the source stays valid TSX.
-
-### 7. Parameters (composition-sized, 0–4 per variant)
-
-Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement. The browser docks a small panel to the right of the outline with one control per parameter. The user drags/clicks and sees instant feedback: there is zero regeneration cost because the knob toggles a CSS variable or data attribute that the variant's scoped CSS is already authored against.
-
-**What “optional” does not mean.** Parameters are not nice-to-have decoration on large work. The word meant “omit controls that are redundant or cosmetic,” not “default to zero because three variants were enough work.”
-
-**When to add.** As soon as the variant’s scoped CSS has a meaningful continuous or stepped axis: density, color amount, type scale, motion intensity, column weight, and so on. If you can imagine the user muttering “a bit tighter” or “a touch more accent” **without** wanting a full regeneration, wire that axis. **Not** micro-margins or one-off nudges; those are not parameters.
-
-**Freeform (`action` is `impeccable`) bias.** You did not load a sub-command reference, so you must **choose** signature axes yourself. Match the budget table: for a hero or large composition, that means **2–3 axes per variant**, not 1. Prefer knobs that sit on the dimensions where your three variants actually differ (if density varies, expose it as a `steps` knob; if color commitment varies, expose it as a `range`). A hero that ships with **0** params is almost always a mistake, not a judgment call. A hero with exactly **1** param is underweight unless the design is genuinely a fixed-point comparison. Start from the budget table, not from zero.
-
-**Budget scales with the element's visual weight, not token budget.** Knobs need real estate to read as tunable; three sliders on a single control are noise.
-
-- **Leaf / tiny**: a single button, icon, input, bare heading, solitary paragraph: **0 params.**
-- **Small composition**: labeled input, simple card, short callout (≤ ~5 visual children): **0–1** params when one dominant axis is obvious; otherwise **0.**
-- **Medium composition**: section component, nav cluster, dense card, short feature block (6–15 visual children): **target 2**; **1** is acceptable if the block is simple; **0** only when variants are truly fixed points.
-- **Large composition**: hero section, full page region, spread layout, strong internal structure (16+ visual children or multiple sub-sections): **target 2–3**; **up to 4** when several independent axes (e.g. structure `steps` + `density` + one accent) are all authored in scoped CSS.
-
-**When in doubt, ask whether a dial exists before defaulting to zero.** The user can always request more variants, but the point of live mode is instant tuning without another Go. Crowding the panel is bad; **under-shipping** knobs on a dense composition is the more common failure for freeform. Count by **visual** children, not DOM depth; a shallow-but-wide hero is still large.
-
-**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.
-
-**How to declare.** Put a JSON manifest on the variant wrapper:
-
-```html
-<div data-impeccable-variant="1" data-impeccable-params='[
- {"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"},
- {"id":"density","kind":"steps","default":"snug","label":"Density","options":[
- {"value":"airy","label":"Airy"},
- {"value":"snug","label":"Snug"},
- {"value":"packed","label":"Packed"}
- ]},
- {"id":"serif","kind":"toggle","default":false,"label":"Serif display"}
-]'>
- ...variant content...
-</div>
-```
-
-**Three kinds:**
-
-- `range`: smooth slider. Drives a CSS custom property `--p-<id>` on the variant wrapper. Author CSS with `var(--p-color-amount, 0.5)`. Fields: `min`, `max`, `step`, `default` (number), `label`.
-- `steps`: segmented radio. Drives a data attribute `data-p-<id>` on the variant wrapper. Author CSS with `:scope[data-p-density="airy"] .grid { ... }`. Fields: `options` (array of `{value, label}`), `default` (string), `label`.
-- `toggle`: on/off switch. Drives BOTH a CSS var (`--p-<id>: 0|1`) and a data attribute (present when on, absent when off). Use whichever is more convenient. Fields: `default` (boolean), `label`.
-
-**Signature params per action.** For named sub-commands, read that action’s `reference/<action>.md` for one or two **MUST** params (e.g. `layout` → `density`). Those are non-negotiable when the design can express them. **Freeform has no file-level MUST**; the **Freeform (`impeccable`) bias** in this section is the stand-in. If the user’s action is both stylized and sub-command (e.g. `colorize`), the sub-command’s MUST list takes precedence for its axes; still respect the **Hard cap** and add no redundant duplicate knobs.
-
-**Reset on variant switch.** User dials density on v1, flips to v2, v2 starts at v2's declared defaults. Known limitation; preservation across variants may land later.
-
-**On accept**, the browser sends the user's current values in the accept event. `live-accept.mjs` writes them as a sibling comment:
-
-```html
-<!-- impeccable-param-values SESSION_ID: {"color-amount":0.7,"density":"packed"} -->
-```
-
-The carbonize cleanup step (see below) reads that comment and bakes the chosen values into the final CSS. For `steps`/`toggle` attribute selectors: keep only the branch matching the chosen value, drop the others, collapse `:scope[data-p-density="packed"] .grid` to a semantic class rule. For `range` vars: either substitute the literal or keep the var with the chosen value as its new default.
-
-### 8. Signal done
-
-```bash
-node .kiro/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
-```
-
-`RELATIVE_PATH` is relative to project root (`public/index.html`, `src/App.tsx`, etc.); the browser fetches source directly if the dev server lacks HMR.
-
-Then run `live-poll.mjs` again immediately.
-
-### Aborting an in-flight session
-
-If wrap or generation fails after the browser has flipped to GENERATING (e.g. wrap landed on the wrong source branch and you've already reverted it, or generation hit an unrecoverable error), tell the **browser** so its bar resets to PICKING:
-
-```bash
-node .kiro/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID error "Short reason"
-```
-
-Don't run `live-accept --discard` for this; that's a pure file mutator, the browser doesn't see it, and the bar gets stuck on the GENERATING dots forever (the user has to refresh). `--discard` is only correct when the **browser** initiated the discard (user clicked ✕ during CYCLING) and the agent is just running source-side cleanup the browser already triggered.
-
-## Handle fallback
-
-When wrap returns `fallback: "agent-driven"`, the deterministic flow doesn't apply. Pick up here.
-
-The goal is the same: give the user three variants to choose from AND persist the accepted one in a place the next build won't wipe. The difference is that you have to pick the right source file yourself.
-
-### Step 1: Identify where the element actually lives
-
-Use the error payload:
-
-- `element_not_in_source` with `generatedMatch: "public/docs/foo.html"`: the served HTML is generated. Find the generator (grep for writers of that path, e.g. `scripts/build-sub-pages.js`, an Astro/Next template) and locate the template or partial that emits this element.
-- `element_not_found`: the element is runtime-injected. Look for the component that renders it (React/Vue/Svelte), the JS that assembles it, or the data source that feeds it.
-- `file_is_generated` with `file: "..."`: user pointed at a generated file explicitly. Same resolution as `element_not_in_source`.
-
-Read the candidate source until you're confident where a change to the element would belong. If the change is purely visual, that source might be a shared stylesheet, not the template.
-
-### Step 2: Show three variants in the DOM for preview
-
-The browser bar is waiting for variants. Even without a wrapper in source, you still need to show something:
-
-1. Manually write the wrapper scaffold into the **served** file (the one the browser actually loaded). Use the same structure `live-wrap.mjs` produces; `<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents">…</div><!-- end -->`.
-2. Insert your three variant divs inside it, same shape as the deterministic path.
-3. Signal done with `--reply EVENT_ID done --file <served file>`. The browser's no-HMR fallback will fetch and inject.
-
-This served-file edit is **temporary**: next regen wipes it, and that's fine. The real work happens on accept.
-
-### Step 3: On accept, write to true source
-
-When the accept event arrives (`_acceptResult.handled` will usually be `false` here because accept also refuses to persist into generated files; see Handle accept for the carbonize branch), extract the accepted variant's content and write it into the source you identified in Step 1:
-
-- Structural change → edit the template / component source.
-- Visual-only change → add or update rules in the appropriate stylesheet; remove the inline `<style>` scope.
-- Dynamic from data → update the data source or the render logic.
-
-Then remove the temporary wrapper from the served file if it's still there.
-
-### Step 4: On discard, clean up the served file
-
-Remove the wrapper you inserted in Step 2. Nothing else to do.
-
-## Handle `accept`
-
-Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.
-
-- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.
-- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.
-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.
-- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.
-- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.
-
-### Required after accept (carbonize)
-
-When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.
-
-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.
-
-1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.
-2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).
-3. **Bake in parameter values while rewriting selectors.** For `@scope ([data-impeccable-variant="N"])` wrappers: retarget to real, semantic classes on the accepted HTML (`.why-visual--v2 .v2-label { … }`). For `:scope[data-p-<id>="VALUE"]` selectors: keep only the branch matching the chosen value from the param-values comment; drop the others (they're dead after accept). For `var(--p-<id>, DEFAULT)` in the CSS: either substitute the literal value, or if the param is still useful as a knob going forward, leave the var and update its initial declaration to the chosen value.
-4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; those are live-mode plumbing, not source.
-5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.
-
-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.
-
-A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.
-
-## Handle `discard`
-
-Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.
-
-## Handle `prefetch`
-
-Event: `{pageUrl}`. The browser fires this the first time the user selects an element on a given route, as a latency shortcut; it signals the user is likely about to Go on a page you haven't read yet.
-
-Resolve `pageUrl` to the underlying file:
-
-- Root `/` → the `pageFile` returned by `live.mjs` (usually `public/index.html` or equivalent).
-- Sub-routes (e.g. `/docs`, `/docs/live`) → the generated or source file for that route. Use your knowledge of the project layout (multi-page static sites often resolve `/foo` → `public/foo/index.html`; SPAs may map all routes to a single entry).
-
-Read the file into context, then poll again. No `--reply`: this is speculative pre-work; Go will come later. If you can't confidently resolve the route to a file, skip and poll again.
-
-Dedupe is the browser's job (one prefetch per unique pathname per session); trust it. If the same file shows up twice from different routes mapping to the same file, the second Read is cached anyway.
-
-## Exit
-
-The user can stop live mode by:
-- Saying "stop live mode" / "exit live" in chat
-- Closing the browser tab (SSE drops, poll returns `exit` after 8s)
-- The browser's exit button
-
-When the poll returns `exit`, proceed to cleanup. If the poll is still running as a background task, kill it first.
-
-## Cleanup
-
-```bash
-node .kiro/skills/impeccable/scripts/live-server.mjs stop
-```
-
-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.
-
-Then:
-- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).
-- Remove any leftover carbonize blocks (search for `impeccable-carbonize-start` markers).
-
-## First-time setup (config missing or invalid)
-
-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.
-
-Schema:
-
-```json
-{
- "files": ["<path-or-glob>", "<path-or-glob>", ...],
- "exclude": ["<optional-glob>", ...],
- "insertBefore": "</body>",
- "commentSyntax": "html",
- "cspChecked": true
-}
-```
-
-`files` is the inject target; **the HTML files the browser actually loads**, not necessarily source. Each entry is either a literal path (`"public/index.html"`) or a glob pattern (`"public/**/*.html"`). Tracked or generated doesn't matter here; wrap has its own generated-file guard and routes accepts through the fallback flow.
-
-`exclude` (optional) is a list of glob patterns matching files to skip, even if a `files` glob would have included them. Use for email templates, demo fixtures, or any HTML that isn't a live page.
-
-`cspChecked` tracks whether the CSP detection step below has already run. Absent on first setup; set to `true` after CSP is checked (whether patched, declined, or not needed).
-
-**Hard-excluded paths (cannot be overridden).** `**/node_modules/**` and `**/.git/**` are never matched regardless of what the user writes. These are vendor/metadata directories and injecting into them would silently instrument third-party code.
-
-**Glob syntax.** `**` matches any number of path segments (including zero), `*` matches any characters except `/`, `?` matches a single character except `/`. Paths are always relative to the project root with forward slashes.
-
-| Framework | `files` | `insertBefore` | `commentSyntax` |
-|-----------|---------|----------------|-----------------|
-| SPA with single shell (Vite / React / Plain HTML) | `["index.html"]` | `</body>` | `html` |
-| Next.js (App Router) | `["app/layout.tsx"]` | `</body>` | `jsx` |
-| Next.js (Pages) | `["pages/_document.tsx"]` | `</body>` | `jsx` |
-| Nuxt | `["app.vue"]` | `</body>` | `html` |
-| Svelte / SvelteKit | `["src/app.html"]` | `</body>` | `html` |
-| Astro | `[" <root layout .astro>"]` | `</body>` | `html` |
-| Multi-page (separate HTML per route) | `["public/**/*.html"]`: a glob covering the served directory | `</body>` | `html` |
-
-Pick an anchor that exists in every file (`</body>` almost always works). Use `insertAfter` if the anchor should match **after** a specific line.
-
-For multi-page sites, **prefer a glob over a literal file list**. New pages added later are picked up automatically on the next `live-inject.mjs` run; no config maintenance needed.
-
-For multi-page sites whose pages are *rebuilt* by a generator (Astro, static-site generators, custom scripts like `build-sub-pages.js`), the inject survives only until the next regeneration. Re-run `live.mjs` after each build. Accept is unaffected; it writes to true source via the fallback flow.
-
-### Drift-heal warning
-
-On every `live.mjs` boot, after inject, the project is scanned for HTML files under common page-source roots (`public/`, `src/`, `app/`, `pages/`). If any exist that aren't covered by the resolved `files` list, the output includes a `configDrift` field:
-
-```json
-{
- "ok": true,
- "serverPort": 8400,
- "pageFiles": [ "..." ],
- "configDrift": {
- "orphans": ["public/new-section/index.html", "public/docs/new-command.html"],
- "orphanCount": 2,
- "hint": "2 HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like \"public/**/*.html\"."
- }
-}
-```
-
-When `configDrift` is present, surface it to the user once per session before entering the poll loop:
-
-> Noticed N HTML file(s) in the project that aren't in `config.files`:
->
-> - `public/new-section/index.html`
-> - `public/docs/new-command.html`
->
-> Add them, or switch `files` to a glob like `["public/**/*.html"]` and let it track new pages automatically?
-
-Don't auto-update the config; let the user decide. `configDrift` is `null` when there's no drift.
-
-### CSP detection (first-time only)
-
-If `config.cspChecked === true`, skip this entire section. You already asked this user once; the answer sticks.
-
-Otherwise, run the detection helper:
-
-```bash
-node .kiro/skills/impeccable/scripts/detect-csp.mjs
-```
-
-Output: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.
-
-- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.
-- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:
- - Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)
- - SvelteKit `kit.csp.directives`
- - Nuxt `nuxt-security` module's `contentSecurityPolicy`
-- **`append-string`**: CSP written as a literal value string. Auto-patchable. See *append-string* below. Covers:
- - Inline `next.config.*` `headers()` with a CSP literal
- - Nuxt `routeRules` / `nitro.routeRules` headers
-- **`middleware`** or **`meta-tag`**: rarer. Detected but not auto-patched in v1. Show the user the detected files and ask them to add `http://localhost:8400` to `script-src` and `connect-src` manually, then mark `cspChecked: true` and proceed.
-
-#### Consent prompt template
-
-Use this phrasing so the experience is consistent across agents:
-
-> **CSP patch needed.** I detected a Content Security Policy in your project that blocks `http://localhost:8400`: the live picker won't load without an allowance. Here's the change I'd make:
->
-> ```diff
-> [file: <patchTarget>]
-> [exact diff, 2–5 lines]
-> ```
->
-> It's guarded by `NODE_ENV === "development"` so the extra entry only appears in dev and never reaches production. You can remove it any time by reverting this file. Apply? [y/n]
-
-On "no": skip the patch, mention live won't work until the user adds the allowance manually, still write `cspChecked: true` (the question's been asked).
-
-On "yes": apply the Shape-specific patch below, then write `cspChecked: true`.
-
-#### append-arrays
-
-CSP expressed as structured directive arrays. Patch mechanism: declare a dev-only array, spread it into the script-src and connect-src arrays.
-
-**Declare near the top of the file that holds the CSP arrays:**
-
-```ts
-// Dev-only allowance so impeccable live mode can load. Guarded by NODE_ENV.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? ["http://localhost:8400"] : [];
-```
-
-**Append `...__impeccableLiveDev` to the script-src and connect-src directive arrays.** Per-framework specifics:
-
-- **Next.js + monorepo helper**: edit the *app's* `next.config.*` (not the shared helper), appending to `additionalScriptSrc` and `additionalConnectSrc` passed into `createBaseNextConfig` (or equivalent). Keeps the shared package clean.
-- **SvelteKit**: edit `svelte.config.js`, appending to `kit.csp.directives['script-src']` and `kit.csp.directives['connect-src']`.
-- **Nuxt + nuxt-security**: edit `nuxt.config.*`, appending to `security.headers.contentSecurityPolicy['script-src']` and `['connect-src']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-turborepo/expected-after-patch.ts` (Next.js)
-- `tests/framework-fixtures/sveltekit-csp/expected-after-patch.js` (SvelteKit)
-
-Idempotency: if `__impeccableLiveDev` already exists in the file, the patch is already applied; skip asking and just mark `cspChecked: true`.
-
-#### append-string
-
-CSP built as a literal value string. Two-point patch: declare a dev-only string near the top, interpolate it into the CSP at the `script-src` and `connect-src` directives.
-
-```ts
-// Dev-only allowance so impeccable live mode can load.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? " http://localhost:8400" : "";
-```
-
-Then in the CSP value string:
-- `script-src 'self' 'unsafe-inline'` → `` `script-src 'self' 'unsafe-inline'${__impeccableLiveDev}` ``
-- `connect-src 'self'` → `` `connect-src 'self'${__impeccableLiveDev}` ``
-
-(Leading space on the dev string so it concatenates cleanly into the existing value. Convert the literal CSP directives into template strings as part of the edit if they aren't already.)
-
-Per-framework specifics:
-- **Next.js inline `headers()`**: edit `next.config.*`, splicing the variable into the CSP value.
-- **Nuxt `routeRules`**: edit `nuxt.config.*`, splicing into the CSP in `routeRules['/**'].headers['Content-Security-Policy']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-inline-csp/expected-after-patch.js` (Next.js)
-- `tests/framework-fixtures/nuxt-csp/expected-after-patch.ts` (Nuxt)
-
-### Troubleshooting
-
-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.
-
-Then re-run `live.mjs`.
@@ -1,109 +0,0 @@
-# Motion Design
-
-## Duration: The 100/300/500 Rule
-
-Timing matters more than easing. These durations feel right for most UI:
-
-| Duration | Use Case | Examples |
-|----------|----------|----------|
-| **100-150ms** | Instant feedback | Button press, toggle, color change |
-| **200-300ms** | State changes | Menu open, tooltip, hover states |
-| **300-500ms** | Layout changes | Accordion, modal, drawer |
-| **500-800ms** | Entrance animations | Page load, hero reveals |
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-## Easing: Pick the Right Curve
-
-**Don't use `ease`.** It's a compromise that's rarely optimal. Instead:
-
-| Curve | Use For | CSS |
-|-------|---------|-----|
-| **ease-out** | Elements entering | `cubic-bezier(0.16, 1, 0.3, 1)` |
-| **ease-in** | Elements leaving | `cubic-bezier(0.7, 0, 0.84, 0)` |
-| **ease-in-out** | State toggles (there → back) | `cubic-bezier(0.65, 0, 0.35, 1)` |
-
-**For micro-interactions, use exponential curves.** They feel natural because they mimic real physics (friction, deceleration):
-
-```css
-/* Quart out - smooth, refined (recommended default) */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1);
-
-/* Quint out - slightly more dramatic */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1);
-
-/* Expo out - snappy, confident */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1);
-```
-
-**Avoid bounce and elastic curves.** They were trendy in 2015 but now feel tacky and amateurish. Real objects don't bounce when they stop; they decelerate smoothly. Overshoot effects draw attention to the animation itself rather than the content.
-
-## Premium Motion Materials
-
-Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties: blur reveals, backdrop-filter panels, saturation or brightness shifts, shadow bloom, SVG filters, masks, clip paths, gradient-position movement, and variable font or shader-driven effects.
-
-Use the right material for the effect:
-
-- **Transform / opacity**: movement, press feedback, simple reveals, list choreography.
-- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances, atmospheric transitions.
-- **Clip path / masks**: wipes, reveals, editorial cropping, product-like transitions.
-- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state.
-- **Grid-template rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly.
-
-The hard rule is not "transform and opacity only." The hard rule is: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify in-browser that the result is smooth on the target viewports. If blur/filter makes the interaction feel significantly more premium and remains smooth, use it.
-
-## Staggered Animations
-
-Use CSS custom properties for cleaner stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"` on each item. **Cap total stagger time**: 10 items at 50ms = 500ms total. For many items, reduce per-item delay or cap staggered count.
-
-## Reduced Motion
-
-This is not optional. Vestibular disorders affect ~35% of adults over 40.
-
-```css
-/* Define animations normally */
-.card {
- animation: slide-up 500ms ease-out;
-}
-
-/* Provide alternative for reduced motion */
-@media (prefers-reduced-motion: reduce) {
- .card {
- animation: fade-in 200ms ease-out; /* Crossfade instead of motion */
- }
-}
-
-/* Or disable entirely */
-@media (prefers-reduced-motion: reduce) {
- *, *::before, *::after {
- animation-duration: 0.01ms !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**What to preserve**: Functional animations like progress bars, loading spinners (slowed down), and focus indicators should still work, just without spatial movement.
-
-## Perceived Performance
-
-**Nobody cares how fast your site is, just how fast it feels.** Perception can be as effective as actual performance.
-
-**The 80ms threshold**: Our brains buffer sensory input for ~80ms to synchronize perception. Anything under 80ms feels instant and simultaneous. This is your target for micro-interactions.
-
-**Active vs passive time**: Passive waiting (staring at a spinner) feels longer than active engagement. Strategies to shift the balance:
-
-- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening.
-- **Early completion**: Show content progressively, don't wait for everything. Video buffering, progressive images, streaming HTML.
-- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Instagram likes work offline; the UI updates instantly, syncs later. Use for low-stakes actions; avoid for payments or destructive operations.
-
-**Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances, but ease-in toward a task's end compresses perceived time.
-
-**Caution**: Too-fast responses can decrease perceived value. Users may distrust instant results for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
-
-## Performance
-
-Don't use `will-change` preemptively, only when animation is imminent (`:hover`, `.animating`). For scroll-triggered animations, use Intersection Observer instead of scroll events; unobserve after animating once. Create motion tokens for consistency (durations, easings, common transitions).
-
----
-
-**Avoid**: Animating everything (animation fatigue is real). Using >500ms for UI feedback. Ignoring `prefers-reduced-motion`. Using animation to hide slow loading.
@@ -1,234 +0,0 @@
-> **Additional context needed**: the "aha moment" you want users to reach, and users' experience level.
-
-Get users to first value as fast as possible. Onboarding's job is not to teach the product. Its job is to get people to the moment that proves the product is worth their time.
-
-## Assess Onboarding Needs
-
-Understand what users need to learn and why:
-
-1. **Identify the challenge**:
- - What are users trying to accomplish?
- - What's confusing or unclear about current experience?
- - Where do users get stuck or drop off?
- - What's the "aha moment" we want users to reach?
-
-2. **Understand the users**:
- - What's their experience level? (Beginners, power users, mixed?)
- - What's their motivation? (Excited and exploring? Required by work?)
- - What's their time commitment? (5 minutes? 30 minutes?)
- - What alternatives do they know? (Coming from competitor? New to category?)
-
-3. **Define success**:
- - What's the minimum users need to learn to be successful?
- - What's the key action we want them to take? (First project? First invite?)
- - How do we know onboarding worked? (Completion rate? Time to value?)
-
-**CRITICAL**: Onboarding should get users to value as quickly as possible, not teach everything possible.
-
-## Onboarding Principles
-
-Follow these core principles:
-
-### Show, Don't Tell
-- Demonstrate with working examples, not just descriptions
-- Provide real functionality in onboarding, not separate tutorial mode
-- Use progressive disclosure, teach one thing at a time
-
-### Make It Optional (When Possible)
-- Let experienced users skip onboarding
-- Don't block access to product
-- Provide "Skip" or "I'll explore on my own" options
-
-### Time to Value
-- Get users to their "aha moment" ASAP
-- Front-load most important concepts
-- Teach 20% that delivers 80% of value
-- Save advanced features for contextual discovery
-
-### Context Over Ceremony
-- Teach features when users need them, not upfront
-- Empty states are onboarding opportunities
-- Tooltips and hints at point of use
-
-### Respect User Intelligence
-- Don't patronize or over-explain
-- Be concise and clear
-- Assume users can figure out standard patterns
-
-## Design Onboarding Experiences
-
-Create appropriate onboarding for the context:
-
-### Initial Product Onboarding
-
-**Welcome Screen**:
-- Clear value proposition (what is this product?)
-- What users will learn/accomplish
-- Time estimate (honest about commitment)
-- Option to skip (for experienced users)
-
-**Account Setup**:
-- Minimal required information (collect more later)
-- Explain why you're asking for each piece of information
-- Smart defaults where possible
-- Social login when appropriate
-
-**Core Concept Introduction**:
-- Introduce 1-3 core concepts (not everything)
-- Use simple language and examples
-- Interactive when possible (do, don't just read)
-- Progress indication (step 1 of 3)
-
-**First Success**:
-- Guide users to accomplish something real
-- Pre-populated examples or templates
-- Celebrate completion (but don't overdo it)
-- Clear next steps
-
-### Feature Discovery & Adoption
-
-**Empty States**:
-Instead of blank space, show:
-- What will appear here (description + screenshot/illustration)
-- Why it's valuable
-- Clear CTA to create first item
-- Example or template option
-
-Example:
-```
-No projects yet
-Projects help you organize your work and collaborate with your team.
-[Create your first project] or [Start from template]
-```
-
-**Contextual Tooltips**:
-- Appear at relevant moment (first time user sees feature)
-- Point directly at relevant UI element
-- Brief explanation + benefit
-- Dismissable (with "Don't show again" option)
-- Optional "Learn more" link
-
-**Feature Announcements**:
-- Highlight new features when they're released
-- Show what's new and why it matters
-- Let users try immediately
-- Dismissable
-
-**Progressive Onboarding**:
-- Teach features when users encounter them
-- Badges or indicators on new/unused features
-- Unlock complexity gradually (don't show all options immediately)
-
-### Guided Tours & Walkthroughs
-
-**When to use**:
-- Complex interfaces with many features
-- Significant changes to existing product
-- Industry-specific tools needing domain knowledge
-
-**How to design**:
-- Spotlight specific UI elements (dim rest of page)
-- Keep steps short (3-7 steps max per tour)
-- Allow users to click through tour freely
-- Include "Skip tour" option
-- Make replayable (help menu)
-
-**Best practices**:
-- Interactive over passive (let users click real buttons)
-- Focus on workflow, not features ("Create a project" not "This is the project button")
-- Provide sample data so actions work
-
-### Interactive Tutorials
-
-**When to use**:
-- Users need hands-on practice
-- Concepts are complex or unfamiliar
-- High stakes (better to practice in safe environment)
-
-**How to design**:
-- Sandbox environment with sample data
-- Clear objectives ("Create a chart showing sales by region")
-- Step-by-step guidance
-- Validation (confirm they did it right)
-- Graduation moment (you're ready!)
-
-### Documentation & Help
-
-**In-product help**:
-- Contextual help links throughout interface
-- Keyboard shortcut reference
-- Search-able help center
-- Video tutorials for complex workflows
-
-**Help patterns**:
-- `?` icon near complex features
-- "Learn more" links in tooltips
-- Keyboard shortcut hints (`⌘K` shown on search box)
-
-## Empty State Design
-
-Every empty state needs:
-
-### What Will Be Here
-"Your recent projects will appear here"
-
-### Why It Matters
-"Projects help you organize your work and collaborate with your team"
-
-### How to Get Started
-[Create project] or [Import from template]
-
-### Visual Interest
-Illustration or icon (not just text on blank page)
-
-### Contextual Help
-"Need help getting started? [Watch 2-min tutorial]"
-
-**Empty state types**:
-- **First use**: Never used this feature (emphasize value, provide template)
-- **User cleared**: Intentionally deleted everything (light touch, easy to recreate)
-- **No results**: Search or filter returned nothing (suggest different query, clear filters)
-- **No permissions**: Can't access (explain why, how to get access)
-- **Error state**: Failed to load (explain what happened, retry option)
-
-## Implementation Patterns
-
-### Technical approaches:
-
-**Tooltip libraries**: Tippy.js, Popper.js
-**Tour libraries**: Intro.js, Shepherd.js, React Joyride
-**Modal patterns**: Focus trap, backdrop, ESC to close
-**Progress tracking**: LocalStorage for "seen" states
-**Analytics**: Track completion, drop-off points
-
-**Storage patterns**:
-```javascript
-// Track which onboarding steps user has seen
-localStorage.setItem('onboarding-completed', 'true');
-localStorage.setItem('feature-tooltip-seen-reports', 'true');
-```
-
-**IMPORTANT**: Don't show same onboarding twice (annoying). Track completion and respect dismissals.
-
-**NEVER**:
-- Force users through long onboarding before they can use product
-- Patronize users with obvious explanations
-- Show same tooltip repeatedly (respect dismissals)
-- Block all UI during tour (let users explore)
-- Create separate tutorial mode disconnected from real product
-- Overwhelm with information upfront (progressive disclosure!)
-- Hide "Skip" or make it hard to find
-- Forget about returning users (don't show initial onboarding again)
-
-## Verify Onboarding Quality
-
-Test with real users:
-
-- **Time to completion**: Can users complete onboarding quickly?
-- **Comprehension**: Do users understand after completing?
-- **Action**: Do users take desired next step?
-- **Skip rate**: Are too many users skipping? (Maybe it's too long or not valuable)
-- **Completion rate**: Are users completing? (If low, simplify)
-- **Time to value**: How long until users get first value?
-
-When users hit the aha moment fast and don't drop off, hand off to `/impeccable polish` for the final pass.
@@ -1,258 +0,0 @@
-Performance is a feature. Identify the actual bottleneck for THIS interface, fix it, then measure. Don't optimize what isn't slow.
-
-## Assess Performance Issues
-
-Understand current performance and identify problems:
-
-1. **Measure current state**:
- - **Core Web Vitals**: LCP, FID/INP, CLS scores
- - **Load time**: Time to interactive, first contentful paint
- - **Bundle size**: JavaScript, CSS, image sizes
- - **Runtime performance**: Frame rate, memory usage, CPU usage
- - **Network**: Request count, payload sizes, waterfall
-
-2. **Identify bottlenecks**:
- - What's slow? (Initial load? Interactions? Animations?)
- - What's causing it? (Large images? Expensive JavaScript? Layout thrashing?)
- - How bad is it? (Perceivable? Annoying? Blocking?)
- - Who's affected? (All users? Mobile only? Slow connections?)
-
-**CRITICAL**: Measure before and after. Premature optimization wastes time. Optimize what actually matters.
-
-## Optimization Strategy
-
-Create systematic improvement plan:
-
-### Loading Performance
-
-**Optimize Images**:
-- Use modern formats (WebP, AVIF)
-- Proper sizing (don't load 3000px image for 300px display)
-- Lazy loading for below-fold images
-- Responsive images (`srcset`, `picture` element)
-- Compress images (80-85% quality is usually imperceptible)
-- Use CDN for faster delivery
-
-```html
-<img
- src="hero.webp"
- srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
- sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
- loading="lazy"
- alt="Hero image"
-/>
-```
-
-**Reduce JavaScript Bundle**:
-- Code splitting (route-based, component-based)
-- Tree shaking (remove unused code)
-- Remove unused dependencies
-- Lazy load non-critical code
-- Use dynamic imports for large components
-
-```javascript
-// Lazy load heavy component
-const HeavyChart = lazy(() => import('./HeavyChart'));
-```
-
-**Optimize CSS**:
-- Remove unused CSS
-- Critical CSS inline, rest async
-- Minimize CSS files
-- Use CSS containment for independent regions
-
-**Optimize Fonts**:
-- Use `font-display: swap` or `optional`
-- Subset fonts (only characters you need)
-- Preload critical fonts
-- Use system fonts when appropriate
-- Limit font weights loaded
-
-```css
-@font-face {
- font-family: 'CustomFont';
- src: url('/fonts/custom.woff2') format('woff2');
- font-display: swap; /* Show fallback immediately */
- unicode-range: U+0020-007F; /* Basic Latin only */
-}
-```
-
-**Optimize Loading Strategy**:
-- Critical resources first (async/defer non-critical)
-- Preload critical assets
-- Prefetch likely next pages
-- Service worker for offline/caching
-- HTTP/2 or HTTP/3 for multiplexing
-
-### Rendering Performance
-
-**Avoid Layout Thrashing**:
-```javascript
-// ❌ Bad: Alternating reads and writes (causes reflows)
-elements.forEach(el => {
- const height = el.offsetHeight; // Read (forces layout)
- el.style.height = height * 2; // Write
-});
-
-// ✅ Good: Batch reads, then batch writes
-const heights = elements.map(el => el.offsetHeight); // All reads
-elements.forEach((el, i) => {
- el.style.height = heights[i] * 2; // All writes
-});
-```
-
-**Optimize Rendering**:
-- Use CSS `contain` property for independent regions
-- Minimize DOM depth (flatter is faster)
-- Reduce DOM size (fewer elements)
-- Use `content-visibility: auto` for long lists
-- Virtual scrolling for very long lists (react-window, react-virtualized)
-
-**Reduce Paint & Composite**:
-- Use `transform` and `opacity` for reliable movement, but allow blur, filters, masks, clip paths, shadows, and color shifts when they create meaningful polish
-- Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- Use `will-change` sparingly for known expensive operations
-- Bound expensive paint areas for blur/filter/shadow effects (smaller and isolated is faster)
-
-### Animation Performance
-
-**GPU Acceleration**:
-```css
-/* ✅ GPU-accelerated (fast) */
-.animated {
- transform: translateX(100px);
- opacity: 0.5;
-}
-
-/* ❌ CPU-bound (slow) */
-.animated {
- left: 100px;
- width: 300px;
-}
-```
-
-**Smooth 60fps**:
-- Target 16ms per frame (60fps)
-- Use `requestAnimationFrame` for JS animations
-- Debounce/throttle scroll handlers
-- Use CSS animations when possible
-- Avoid long-running JavaScript during animations
-
-**Intersection Observer**:
-```javascript
-// Efficiently detect when elements enter viewport
-const observer = new IntersectionObserver((entries) => {
- entries.forEach(entry => {
- if (entry.isIntersecting) {
- // Element is visible, lazy load or animate
- }
- });
-});
-```
-
-### React/Framework Optimization
-
-**React-specific**:
-- Use `memo()` for expensive components
-- `useMemo()` and `useCallback()` for expensive computations
-- Virtualize long lists
-- Code split routes
-- Avoid inline function creation in render
-- Use React DevTools Profiler
-
-**Framework-agnostic**:
-- Minimize re-renders
-- Debounce expensive operations
-- Memoize computed values
-- Lazy load routes and components
-
-### Network Optimization
-
-**Reduce Requests**:
-- Combine small files
-- Use SVG sprites for icons
-- Inline small critical assets
-- Remove unused third-party scripts
-
-**Optimize APIs**:
-- Use pagination (don't load everything)
-- GraphQL to request only needed fields
-- Response compression (gzip, brotli)
-- HTTP caching headers
-- CDN for static assets
-
-**Optimize for Slow Connections**:
-- Adaptive loading based on connection (navigator.connection)
-- Optimistic UI updates
-- Request prioritization
-- Progressive enhancement
-
-## Core Web Vitals Optimization
-
-### Largest Contentful Paint (LCP < 2.5s)
-- Optimize hero images
-- Inline critical CSS
-- Preload key resources
-- Use CDN
-- Server-side rendering
-
-### First Input Delay (FID < 100ms) / INP (< 200ms)
-- Break up long tasks
-- Defer non-critical JavaScript
-- Use web workers for heavy computation
-- Reduce JavaScript execution time
-
-### Cumulative Layout Shift (CLS < 0.1)
-- Set dimensions on images and videos
-- Don't inject content above existing content
-- Use `aspect-ratio` CSS property
-- Reserve space for ads/embeds
-- Avoid animations that cause layout shifts
-
-```css
-/* Reserve space for image */
-.image-container {
- aspect-ratio: 16 / 9;
-}
-```
-
-## Performance Monitoring
-
-**Tools to use**:
-- Chrome DevTools (Lighthouse, Performance panel)
-- WebPageTest
-- Core Web Vitals (Chrome UX Report)
-- Bundle analyzers (webpack-bundle-analyzer)
-- Performance monitoring (Sentry, DataDog, New Relic)
-
-**Key metrics**:
-- LCP, FID/INP, CLS (Core Web Vitals)
-- Time to Interactive (TTI)
-- First Contentful Paint (FCP)
-- Total Blocking Time (TBT)
-- Bundle size
-- Request count
-
-**IMPORTANT**: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.
-
-**NEVER**:
-- Optimize without measuring (premature optimization)
-- Sacrifice accessibility for performance
-- Break functionality while optimizing
-- Use `will-change` everywhere (creates new layers, uses memory)
-- Lazy load above-fold content
-- Optimize micro-optimizations while ignoring major issues (optimize the biggest bottleneck first)
-- Forget about mobile performance (often slower devices, slower connections)
-
-## Verify Improvements
-
-Test that optimizations worked:
-
-- **Before/after metrics**: Compare Lighthouse scores
-- **Real user monitoring**: Track improvements for real users
-- **Different devices**: Test on low-end Android, not just flagship iPhone
-- **Slow connections**: Throttle to 3G, test experience
-- **No regressions**: Ensure functionality still works
-- **User perception**: Does it *feel* faster?
-
-When the user-facing numbers move, hand off to `/impeccable polish` for the final pass.
@@ -1,130 +0,0 @@
-Start your response with:
-
-```
-──────────── ⚡ OVERDRIVE ─────────────
-》》》 Entering overdrive mode...
-```
-
-Push an interface past conventional limits. This isn't just about visual effects. It's about using the full power of the browser to make any part of an interface feel extraordinary: a table that handles a million rows, a dialog that morphs from its trigger, a form that validates in real-time with streaming feedback, a page transition that feels cinematic.
-
-**EXTRA IMPORTANT FOR THIS COMMAND**: Context determines what "extraordinary" means. A particle system on a creative portfolio is impressive. The same particle system on a settings page is embarrassing. But a settings page with instant optimistic saves and animated state transitions? That's extraordinary too. Understand the project's personality and goals before deciding what's appropriate.
-
-### Propose Before Building
-
-This command has the highest potential to misfire. Do NOT jump straight into implementation. You MUST:
-
-1. **Think through 2-3 different directions**: consider different techniques, levels of ambition, and aesthetic approaches. For each direction, briefly describe what the result would look and feel like.
-2. **ask the user directly to clarify what you cannot infer.** to present these directions and get the user's pick before writing any code. Explain trade-offs (browser support, performance cost, complexity).
-3. Only proceed with the direction the user confirms.
-
-Skipping this step risks building something embarrassing that needs to be thrown away.
-
-### Iterate with Browser Automation
-
-Technically ambitious effects almost never work on the first try. You MUST actively use browser automation tools to preview your work, visually verify the result, and iterate. Do not assume the effect looks right, check it. Expect multiple rounds of refinement. The gap between "technically works" and "looks extraordinary" is closed through visual iteration, not code alone.
-
----
-
-## Assess What "Extraordinary" Means Here
-
-The right kind of technical ambition depends entirely on what you're working with. Before choosing a technique, ask: **what would make a user of THIS specific interface say "wow, that's nice"?**
-
-### For visual/marketing surfaces
-Pages, hero sections, landing pages, portfolios: the "wow" is often sensory: a scroll-driven reveal, a shader background, a cinematic page transition, generative art that responds to the cursor.
-
-### For functional UI
-Tables, forms, dialogs, navigation: the "wow" is in how it FEELS: a dialog that morphs from the button that triggered it via View Transitions, a data table that renders 100k rows at 60fps via virtual scrolling, a form with streaming validation that feels instant, drag-and-drop with spring physics.
-
-### For performance-critical UI
-The "wow" is invisible but felt: a search that filters 50k items without a flicker, a complex form that never blocks the main thread, an image editor that processes in near-real-time. The interface just never hesitates.
-
-### For data-heavy interfaces
-Charts and dashboards: the "wow" is in fluidity: GPU-accelerated rendering via Canvas/WebGL for massive datasets, animated transitions between data states, force-directed graph layouts that settle naturally.
-
-**The common thread**: something about the implementation goes beyond what users expect from a web interface. The technique serves the experience, not the other way around.
-
-## The Toolkit
-
-Organized by what you're trying to achieve, not by technology name.
-
-### Make transitions feel cinematic
-- **View Transitions API** (same-document: all browsers; cross-document: no Firefox): shared element morphing between states. A list item expanding into a detail page. A button morphing into a dialog. This is the closest thing to native FLIP animations.
-- **`@starting-style`** (all browsers): animate elements from `display: none` to visible with CSS only, including entry keyframes
-- **Spring physics**: natural motion with mass, tension, and damping instead of cubic-bezier. Libraries: motion (formerly Framer Motion), GSAP, or roll your own spring solver.
-
-### Tie animation to scroll position
-- **Scroll-driven animations** (`animation-timeline: scroll()`): CSS-only, no JS. Parallax, progress bars, reveal sequences all driven by scroll position. (Chrome/Edge/Safari; Firefox: flag only; always provide a static fallback)
-
-### Render beyond CSS
-- **WebGL** (all browsers): shader effects, post-processing, particle systems. Libraries: Three.js, OGL (lightweight), regl. Use for effects CSS can't express.
-- **WebGPU** (Chrome/Edge; Safari partial; Firefox: flag only): next-gen GPU compute. More powerful than WebGL but limited browser support. Always fall back to WebGL2.
-- **Canvas 2D / OffscreenCanvas**: custom rendering, pixel manipulation, or moving heavy rendering off the main thread entirely via Web Workers + OffscreenCanvas.
-- **SVG filter chains**: displacement maps, turbulence, morphology for organic distortion effects. CSS-animatable.
-
-### Make data feel alive
-- **Virtual scrolling**: render only visible rows for tables/lists with tens of thousands of items. No library required for simple cases; TanStack Virtual for complex ones.
-- **GPU-accelerated charts**: Canvas or WebGL-rendered data visualization for datasets too large for SVG/DOM. Libraries: deck.gl, regl-based custom renderers.
-- **Animated data transitions**: morph between chart states rather than replacing. D3's `transition()` or View Transitions for DOM-based charts.
-
-### Animate complex properties
-- **`@property`** (all browsers): register custom CSS properties with types, enabling animation of gradients, colors, and complex values that CSS can't normally interpolate.
-- **Web Animations API** (all browsers): JavaScript-driven animations with the performance of CSS. Composable, cancellable, reversible. The foundation for complex choreography.
-
-### Push performance boundaries
-- **Web Workers**: move computation off the main thread. Heavy data processing, image manipulation, search indexing: anything that would cause jank.
-- **OffscreenCanvas**: render in a Worker thread. The main thread stays free while complex visuals render in the background.
-- **WASM**: near-native performance for computation-heavy features. Image processing, physics simulations, codecs.
-
-### Interact with the device
-- **Web Audio API**: spatial audio, audio-reactive visualizations, sonic feedback. Requires user gesture to start.
-- **Device APIs**: orientation, ambient light, geolocation. Use sparingly and always with user permission.
-
-**NOTE**: This command is about enhancing how an interface FEELS, not changing what a product DOES. Adding real-time collaboration, offline support, or new backend capabilities are product decisions, not UI enhancements. Focus on making existing features feel extraordinary.
-
-## Implement with Discipline
-
-### Progressive enhancement is non-negotiable
-
-Every technique must degrade gracefully. The experience without the enhancement must still be good.
-
-```css
-@supports (animation-timeline: scroll()) {
- .hero { animation-timeline: scroll(); }
-}
-```
-
-```javascript
-if ('gpu' in navigator) { /* WebGPU */ }
-else if (canvas.getContext('webgl2')) { /* WebGL2 fallback */ }
-/* CSS-only fallback must still look good */
-```
-
-### Performance rules
-
-- Target 60fps. If dropping below 50, simplify.
-- Respect `prefers-reduced-motion`, always. Provide a beautiful static alternative.
-- Lazy-initialize heavy resources (WebGL contexts, WASM modules) only when near viewport.
-- Pause off-screen rendering. Kill what you can't see.
-- Test on real mid-range devices, not just your development machine.
-
-### Polish is the difference
-
-The gap between "cool" and "extraordinary" is in the last 20% of refinement: the easing curve on a spring animation, the timing offset in a staggered reveal, the subtle secondary motion that makes a transition feel physical. Don't ship the first version that works; ship the version that feels inevitable.
-
-**NEVER**:
-- Ignore `prefers-reduced-motion`. This is an accessibility requirement, not a suggestion
-- Ship effects that cause jank on mid-range devices
-- Use bleeding-edge APIs without a functional fallback
-- Add sound without explicit user opt-in
-- Use technical ambition to mask weak design fundamentals; fix those first with other commands
-- Layer multiple competing extraordinary moments. Focus creates impact, excess creates noise
-
-## Verify the Result
-
-- **The wow test**: Show it to someone who hasn't seen it. Do they react?
-- **The removal test**: Take it away. Does the experience feel diminished, or does nobody notice?
-- **The device test**: Run it on a phone, a tablet, a Chromebook. Still smooth?
-- **The accessibility test**: Enable reduced motion. Still beautiful?
-- **The context test**: Does this make sense for THIS brand and audience?
-
-"Technically extraordinary" isn't about using the newest API. It's about making an interface do something users didn't think a website could do.
@@ -1,179 +0,0 @@
-# Persona-Based Design Testing
-
-Test the interface through the eyes of 5 distinct user archetypes. Each persona exposes different failure modes that a single "design director" perspective would miss.
-
-**How to use**: Select 2–3 personas most relevant to the interface being critiqued. Walk through the primary user action as each persona. Report specific red flags, not generic concerns.
-
----
-
-## 1. Impatient Power User: "Alex"
-
-
-**Profile**: Expert with similar products. Expects efficiency, hates hand-holding. Will find shortcuts or leave.
-
-**Behaviors**:
-- Skips all onboarding and instructions
-- Looks for keyboard shortcuts immediately
-- Tries to bulk-select, batch-edit, and automate
-- Gets frustrated by required steps that feel unnecessary
-- Abandons if anything feels slow or patronizing
-
-**Test Questions**:
-- Can Alex complete the core task in under 60 seconds?
-- Are there keyboard shortcuts for common actions?
-- Can onboarding be skipped entirely?
-- Do modals have keyboard dismiss (Esc)?
-- Is there a "power user" path (shortcuts, bulk actions)?
-
-**Red Flags** (report these specifically):
-- Forced tutorials or unskippable onboarding
-- No keyboard navigation for primary actions
-- Slow animations that can't be skipped
-- One-item-at-a-time workflows where batch would be natural
-- Redundant confirmation steps for low-risk actions
-
----
-
-## 2. Confused First-Timer: "Jordan"
-
-**Profile**: Never used this type of product. Needs guidance at every step. Will abandon rather than figure it out.
-
-**Behaviors**:
-- Reads all instructions carefully
-- Hesitates before clicking anything unfamiliar
-- Looks for help or support constantly
-- Misunderstands jargon and abbreviations
-- Takes the most literal interpretation of any label
-
-**Test Questions**:
-- Is the first action obviously clear within 5 seconds?
-- Are all icons labeled with text?
-- Is there contextual help at decision points?
-- Does terminology assume prior knowledge?
-- Is there a clear "back" or "undo" at every step?
-
-**Red Flags** (report these specifically):
-- Icon-only navigation with no labels
-- Technical jargon without explanation
-- No visible help option or guidance
-- Ambiguous next steps after completing an action
-- No confirmation that an action succeeded
-
----
-
-## 3. Accessibility-Dependent User: "Sam"
-
-**Profile**: Uses screen reader (VoiceOver/NVDA), keyboard-only navigation. May have low vision, motor impairment, or cognitive differences.
-
-**Behaviors**:
-- Tabs through the interface linearly
-- Relies on ARIA labels and heading structure
-- Cannot see hover states or visual-only indicators
-- Needs adequate color contrast (4.5:1 minimum)
-- May use browser zoom up to 200%
-
-**Test Questions**:
-- Can the entire primary flow be completed keyboard-only?
-- Are all interactive elements focusable with visible focus indicators?
-- Do images have meaningful alt text?
-- Is color contrast WCAG AA compliant (4.5:1 for text)?
-- Does the screen reader announce state changes (loading, success, errors)?
-
-**Red Flags** (report these specifically):
-- Click-only interactions with no keyboard alternative
-- Missing or invisible focus indicators
-- Meaning conveyed by color alone (red = error, green = success)
-- Unlabeled form fields or buttons
-- Time-limited actions without extension option
-- Custom components that break screen reader flow
-
----
-
-## 4. Deliberate Stress Tester: "Riley"
-
-**Profile**: Methodical user who pushes interfaces beyond the happy path. Tests edge cases, tries unexpected inputs, and probes for gaps in the experience.
-
-**Behaviors**:
-- Tests edge cases intentionally (empty states, long strings, special characters)
-- Submits forms with unexpected data (emoji, RTL text, very long values)
-- Tries to break workflows by navigating backwards, refreshing mid-flow, or opening in multiple tabs
-- Looks for inconsistencies between what the UI promises and what actually happens
-- Documents problems methodically
-
-**Test Questions**:
-- What happens at the edges (0 items, 1000 items, very long text)?
-- Do error states recover gracefully or leave the UI in a broken state?
-- What happens on refresh mid-workflow? Is state preserved?
-- Are there features that appear to work but produce broken results?
-- How does the UI handle unexpected input (emoji, special chars, paste from Excel)?
-
-**Red Flags** (report these specifically):
-- Features that appear to work but silently fail or produce wrong results
-- Error handling that exposes technical details or leaves UI in a broken state
-- Empty states that show nothing useful ("No results" with no guidance)
-- Workflows that lose user data on refresh or navigation
-- Inconsistent behavior between similar interactions in different parts of the UI
-
----
-
-## 5. Distracted Mobile User: "Casey"
-
-**Profile**: Using phone one-handed on the go. Frequently interrupted. Possibly on a slow connection.
-
-**Behaviors**:
-- Uses thumb only; prefers bottom-of-screen actions
-- Gets interrupted mid-flow and returns later
-- Switches between apps frequently
-- Has limited attention span and low patience
-- Types as little as possible, prefers taps and selections
-
-**Test Questions**:
-- Are primary actions in the thumb zone (bottom half of screen)?
-- Is state preserved if the user leaves and returns?
-- Does it work on slow connections (3G)?
-- Can forms use autocomplete and smart defaults?
-- Are touch targets at least 44×44pt?
-
-**Red Flags** (report these specifically):
-- Important actions positioned at the top of the screen (unreachable by thumb)
-- No state persistence; progress lost on tab switch or interruption
-- Large text inputs required where selection would work
-- Heavy assets loading on every page (no lazy loading)
-- Tiny tap targets or targets too close together
-
----
-
-## Selecting Personas
-
-Choose personas based on the interface type:
-
-| Interface Type | Primary Personas | Why |
-|---------------|-----------------|-----|
-| Landing page / marketing | Jordan, Riley, Casey | First impressions, trust, mobile |
-| Dashboard / admin | Alex, Sam | Power users, accessibility |
-| E-commerce / checkout | Casey, Riley, Jordan | Mobile, edge cases, clarity |
-| Onboarding flow | Jordan, Casey | Confusion, interruption |
-| Data-heavy / analytics | Alex, Sam | Efficiency, keyboard nav |
-| Form-heavy / wizard | Jordan, Sam, Casey | Clarity, accessibility, mobile |
-
----
-
-## Project-Specific Personas
-
-If `.kiro/settings.json` contains a `## Design Context` section (generated by `impeccable teach`), derive 1–2 additional personas from the audience and brand information:
-
-1. Read the target audience description
-2. Identify the primary user archetype not covered by the 5 predefined personas
-3. Create a persona following this template:
-
-```
-### [Role]: "[Name]"
-
-**Profile**: [2-3 key characteristics derived from Design Context]
-
-**Behaviors**: [3-4 specific behaviors based on the described audience]
-
-**Red Flags**: [3-4 things that would alienate this specific user type]
-```
-
-Only generate project-specific personas when real Design Context data is available. Don't invent audience details; use the 5 predefined personas when no context exists.
@@ -1,242 +0,0 @@
-> **Additional context needed**: quality bar (MVP vs flagship).
-
-Perform a meticulous final pass to catch all the small details that separate good work from great work. The difference between shipped and polished.
-
-Detector and automated QA output are defect evidence only. A clean script result is never proof that the design is strong; gather browser evidence and inspect the real interaction path.
-
-## Design System Discovery
-
-Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
-
-1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
-2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
-3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category: patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
-
-If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask. Never guess at design system principles.**
-
-## Pre-Polish Assessment
-
-Understand the current state and goals before touching anything:
-
-1. **Review completeness**:
- - Is it functionally complete?
- - Are there known issues to preserve (mark with TODOs)?
- - What's the quality bar? (MVP vs flagship feature?)
- - When does it ship? (How much time for polish?)
-
-2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish; a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
-
-3. **Identify polish areas**:
- - Visual inconsistencies
- - Spacing and alignment issues
- - Interaction state gaps
- - Copy inconsistencies
- - Edge cases and error states
- - Loading and transition smoothness
- - Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
-
-4. **Pull in any prior critique** (optional signal): If `/impeccable critique` has been run on the same target, its priority issues are a useful prior for what to address first. Resolve the target to a file path or URL, then:
- ```bash
- slug=$(node .kiro/skills/impeccable/scripts/critique-storage.mjs slug "<resolved>")
- node .kiro/skills/impeccable/scripts/critique-storage.mjs latest "$slug"
- ```
- Exit 0 with body = found; fold the P0/P1 items into your polish list and mention the snapshot path so the user sees what you read. Exit 2 = no snapshot, continue without it. The critique is one input among many. Do your own pass either way.
-
-5. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent; never perfect one corner while leaving another rough.
-
-**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
-
-## Polish Systematically
-
-Work through these dimensions methodically:
-
-### Visual Alignment & Spacing
-
-- **Pixel-perfect alignment**: Everything lines up to grid
-- **Consistent spacing**: All gaps use spacing scale (no random 13px gaps)
-- **Optical alignment**: Adjust for visual weight (icons may need offset for optical centering)
-- **Responsive consistency**: Spacing and alignment work at all breakpoints
-- **Grid adherence**: Elements snap to baseline grid
-
-**Check**:
-- Enable grid overlay and verify alignment
-- Check spacing with browser inspector
-- Test at multiple viewport sizes
-- Look for elements that "feel" off
-
-### Information Architecture & Flow
-
-Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
-
-- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
-- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere: modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
-- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
-- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
-- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
-
-### Typography Refinement
-
-- **Hierarchy consistency**: Same elements use same sizes/weights throughout
-- **Line length**: 45-75 characters for body text
-- **Line height**: Appropriate for font size and context
-- **Widows & orphans**: No single words on last line
-- **Hyphenation**: Appropriate for language and column width
-- **Kerning**: Adjust letter spacing where needed (especially headlines)
-- **Font loading**: No FOUT/FOIT flashes
-
-### Color & Contrast
-
-- **Contrast ratios**: All text meets WCAG standards
-- **Consistent token usage**: No hard-coded colors, all use design tokens
-- **Theme consistency**: Works in all theme variants
-- **Color meaning**: Same colors mean same things throughout
-- **Accessible focus**: Focus indicators visible with sufficient contrast
-- **Tinted neutrals**: No pure gray or pure black; add subtle color tint (0.01 chroma)
-- **Gray on color**: Never put gray text on colored backgrounds; use a shade of that color or transparency
-
-### Interaction States
-
-Every interactive element needs all states:
-
-- **Default**: Resting state
-- **Hover**: Subtle feedback (color, scale, shadow)
-- **Focus**: Keyboard focus indicator (never remove without replacement)
-- **Active**: Click/tap feedback
-- **Disabled**: Clearly non-interactive
-- **Loading**: Async action feedback
-- **Error**: Validation or error state
-- **Success**: Successful completion
-
-**Missing states create confusion and broken experiences**.
-
-### Micro-interactions & Transitions
-
-- **Smooth transitions**: All state changes animated appropriately (150-300ms)
-- **Consistent easing**: Use ease-out-quart/quint/expo for natural deceleration. Never bounce or elastic; they feel dated.
-- **No jank**: Smooth animations; use atmospheric blur/filter/mask/shadow effects when they add polish, but bound expensive paint areas and avoid casual layout-property animation
-- **Appropriate motion**: Motion serves purpose, not decoration
-- **Reduced motion**: Respects `prefers-reduced-motion`
-
-### Content & Copy
-
-- **Consistent terminology**: Same things called same names throughout
-- **Consistent capitalization**: Title Case vs Sentence case applied consistently
-- **Grammar & spelling**: No typos
-- **Appropriate length**: Not too wordy, not too terse
-- **Punctuation consistency**: Periods on sentences, not on labels (unless all labels have them)
-
-### Icons & Images
-
-- **Consistent style**: All icons from same family or matching style
-- **Appropriate sizing**: Icons sized consistently for context
-- **Proper alignment**: Icons align with adjacent text optically
-- **Alt text**: All images have descriptive alt text
-- **Loading states**: Images don't cause layout shift, proper aspect ratios
-- **Retina support**: 2x assets for high-DPI screens
-
-### Forms & Inputs
-
-- **Label consistency**: All inputs properly labeled
-- **Required indicators**: Clear and consistent
-- **Error messages**: Helpful and consistent
-- **Tab order**: Logical keyboard navigation
-- **Auto-focus**: Appropriate (don't overuse)
-- **Validation timing**: Consistent (on blur vs on submit)
-
-### Edge Cases & Error States
-
-- **Loading states**: All async actions have loading feedback
-- **Empty states**: Helpful empty states, not just blank space
-- **Error states**: Clear error messages with recovery paths
-- **Success states**: Confirmation of successful actions
-- **Long content**: Handles very long names, descriptions, etc.
-- **No content**: Handles missing data gracefully
-- **Offline**: Appropriate offline handling (if applicable)
-
-### Responsiveness
-
-- **All breakpoints**: Test mobile, tablet, desktop
-- **Touch targets**: 44x44px minimum on touch devices
-- **Readable text**: No text smaller than 14px on mobile
-- **No horizontal scroll**: Content fits viewport
-- **Appropriate reflow**: Content adapts logically
-
-### Performance
-
-- **Fast initial load**: Optimize critical path
-- **No layout shift**: Elements don't jump after load (CLS)
-- **Smooth interactions**: No lag or jank
-- **Optimized images**: Appropriate formats and sizes
-- **Lazy loading**: Off-screen content loads lazily
-
-### Code Quality
-
-- **Remove console logs**: No debug logging in production
-- **Remove commented code**: Clean up dead code
-- **Remove unused imports**: Clean up unused dependencies
-- **Consistent naming**: Variables and functions follow conventions
-- **Type safety**: No TypeScript `any` or ignored errors
-- **Accessibility**: Proper ARIA labels and semantic HTML
-
-## Polish Checklist
-
-Go through systematically:
-
-- [ ] Aligned to the design system (drift named and resolved by root cause)
-- [ ] Information architecture and flow shape match neighboring features
-- [ ] Visual alignment perfect at all breakpoints
-- [ ] Spacing uses design tokens consistently
-- [ ] Typography hierarchy consistent
-- [ ] All interactive states implemented
-- [ ] All transitions smooth (60fps)
-- [ ] Copy is consistent and polished
-- [ ] Icons are consistent and properly sized
-- [ ] All forms properly labeled and validated
-- [ ] Error states are helpful
-- [ ] Loading states are clear
-- [ ] Empty states are welcoming
-- [ ] Touch targets are 44x44px minimum
-- [ ] Contrast ratios meet WCAG AA
-- [ ] Keyboard navigation works
-- [ ] Focus indicators visible
-- [ ] No console errors or warnings
-- [ ] No layout shift on load
-- [ ] Works in all supported browsers
-- [ ] Respects reduced motion preference
-- [ ] Code is clean (no TODOs, console.logs, commented code)
-
-**IMPORTANT**: Polish is about details. Zoom in. Squint at it. Use it yourself. The little things add up.
-
-Sweat the details. Zoom in until the alignment is right and the spacing reads as deliberate. Then ship.
-
-**NEVER**:
-- Polish before it's functionally complete
-- Polish without aligning to the design system; that's decoration on drift
-- Guess at design system principles instead of asking when something is ambiguous
-- Spend hours on polish if it ships in 30 minutes (triage)
-- Introduce bugs while polishing (test thoroughly)
-- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
-- Perfect one thing while leaving others rough (consistent quality level)
-- Create new one-off components when design system equivalents exist
-- Hard-code values that should use design tokens
-- Introduce new patterns or flows that diverge from established ones
-
-## Final Verification
-
-Before marking as done:
-
-- **Use it yourself**: Actually interact with the feature.
-- **Test on real devices**: Not just browser DevTools.
-- **Ask someone else to review**: Fresh eyes catch things.
-- **Compare to design**: Match intended design.
-- **Check all states**: Don't just test happy path.
-- **Treat automation carefully**: Run detector or QA commands when they are available and relevant, fix their defects, but never cite a clean result as proof that the work is polished.
-
-## Clean Up
-
-After polishing, ensure code quality:
-
-- **Replace custom implementations**: If the design system provides a component you reimplemented, switch to the shared version.
-- **Remove orphaned code**: Delete unused styles, components, or files made obsolete by polish.
-- **Consolidate tokens**: If you introduced new values, check whether they should be tokens.
-- **Verify DRYness**: Look for duplication introduced during polishing and consolidate.
@@ -1,62 +0,0 @@
-# Product register
-
-When design SERVES the product: app UIs, admin dashboards, settings panels, data tables, tools, authenticated surfaces, anything where the user is in a task.
-
-## The product slop test
-
-Not "would someone say AI made this." Familiarity is often a feature here. The test is: would a user fluent in the category's best tools (Linear, Figma, Notion, Raycast, Stripe come to mind) sit down and trust this interface, or pause at every subtly-off component?
-
-Product UI's failure mode isn't flatness, it's strangeness without purpose: over-decorated buttons, mismatched form controls, gratuitous motion, display fonts where labels should be, invented affordances for standard tasks. The bar is earned familiarity. The tool should disappear into the task.
-
-## Typography
-
-- **System fonts are legitimate.** `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` gives you native feel on every platform. Inter is the common cross-platform default for a reason.
-- **One family is often right.** Product UIs don't need display/body pairing. A well-tuned sans carries headings, buttons, labels, body, data.
-- **Fixed rem scale, not fluid.** Clamp-sized headings don't serve product UI. Users view at consistent DPI, and a fluid h1 that shrinks in a sidebar looks worse, not better.
-- **Tighter scale ratio.** 1.125–1.2 between steps is typical. More type elements here than on brand surfaces; exaggerated contrast creates noise.
-- **Line length still applies for prose** (65–75ch). Data and compact UI can run denser; tables at 120ch+ are fine.
-
-## Color
-
-Product defaults to Restrained. A single surface can earn Committed (a dashboard where one category color carries a report, an onboarding flow with a drenched welcome screen), but Restrained is the floor.
-
-- State-rich semantic vocabulary: hover, focus, active, disabled, selected, loading, error, warning, success, info. Standardize these.
-- Accent color used for primary actions, current selection, and state indicators only, not decoration.
-- A second neutral layer for sidebars, toolbars, and panels (slightly cooler or warmer than the content surface).
-
-## Layout
-
-- Predictable grids. Consistency IS an affordance; users navigate faster when the structure is expected.
-- Familiar patterns are features. Standard navigation (top bar, side nav), breadcrumbs, tabs, and form layouts have established user expectations. Don't reinvent for flavor.
-- Responsive behavior is structural (collapse sidebar, responsive table, breakpoint-driven columns), not fluid typography.
-
-## Components
-
-Every interactive component has: default, hover, focus, active, disabled, loading, error. Don't ship with half of these.
-
-- Skeleton states for loading, not spinners in the middle of content.
-- Empty states that teach the interface, not "nothing here."
-- Consistent affordances across the surface. Same button shape. Same form-control vocabulary. Same icon style.
-
-## Motion
-
-- 150–250 ms on most transitions. Users are in flow; don't make them wait for choreography.
-- Motion conveys state, not decoration. State change, feedback, loading, reveal: nothing else.
-- No orchestrated page-load sequences. Product loads into a task; users don't want to watch it load.
-
-## Product bans (on top of the shared absolute bans)
-
-- Decorative motion that doesn't convey state.
-- Inconsistent component vocabulary across screens. If the "save" button looks different in two places, one is wrong.
-- Display fonts in UI labels, buttons, data.
-- Reinventing standard affordances for flavor (custom scrollbars, weird form controls, non-standard modals).
-- Heavy color or full-saturation accents on inactive states.
-
-## Product permissions
-
-Product can afford things brand surfaces can't.
-
-- System fonts and familiar sans defaults (Inter, SF Pro, system-ui stacks).
-- Standard navigation patterns: top bar + side nav, breadcrumbs, tabs, command palettes.
-- Density. Tables with many rows, panels with many labels, dense information when users need it.
-- Consistency over surprise. The same visual vocabulary screen to screen is a virtue; delight is saved for moments, not pages.
@@ -1,99 +0,0 @@
-Quiet design is harder than bold design. Subtlety needs precision. Reduce visual intensity in designs that are too loud, aggressive, or overstimulating without losing personality or making the result generic.
-
----
-
-## Register
-
-Brand: "quieter" means more restrained palette, more whitespace, more typographic air. Drama is reduced, not eliminated; the POV stays intact.
-
-Product: "quieter" means reducing visual noise. Fewer background accents, flatter cards, less color, less motion. The tool should disappear more completely into the task.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too intense:
-
-1. **Identify intensity sources**:
- - **Color saturation**: Overly bright or saturated colors
- - **Contrast extremes**: Too much high-contrast juxtaposition
- - **Visual weight**: Too many bold, heavy elements competing
- - **Animation excess**: Too much motion or overly dramatic effects
- - **Complexity**: Too many visual elements, patterns, or decorations
- - **Scale**: Everything is large and loud with no hierarchy
-
-2. **Understand the context**:
- - What's the purpose? (Marketing vs tool vs reading experience)
- - Who's the audience? (Some contexts need energy)
- - What's working? (Don't throw away good ideas)
- - What's the core message? (Preserve what matters)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Quieter" doesn't mean boring or generic. It means refined and easier on the eyes. Think luxury, not laziness.
-
-## Plan Refinement
-
-Create a strategy to reduce intensity while maintaining impact:
-
-- **Color approach**: Desaturate or shift to more restrained tones?
-- **Hierarchy approach**: Which elements should stay bold (very few), which should recede?
-- **Simplification approach**: What can be removed entirely?
-- **Sophistication approach**: How can we signal quality through restraint?
-
-**IMPORTANT**: Subtlety requires precision. Quiet without intent collapses to generic.
-
-## Refine the Design
-
-Systematically reduce intensity across these dimensions:
-
-### Color Refinement
-- **Reduce saturation**: Shift from fully saturated to 70-85% saturation
-- **Soften palette**: Replace bright colors with muted tones
-- **Reduce color variety**: Use fewer colors more thoughtfully
-- **Neutral dominance**: Let neutrals do more work, use color as accent (10% rule)
-- **Gentler contrasts**: High contrast only where it matters most
-- **Tinted grays**: Use warm or cool tinted grays instead of pure gray. Adds depth without loudness
-- **Never gray on color**: If you have gray text on a colored background, use a darker shade of that color or transparency instead
-
-### Visual Weight Reduction
-- **Typography**: Reduce font weights (900 → 600, 700 → 500), decrease sizes where appropriate
-- **Hierarchy through subtlety**: Use weight, size, and space instead of color and boldness
-- **White space**: Increase breathing room, reduce density
-- **Borders & lines**: Reduce thickness, decrease opacity, or remove entirely
-
-### Simplification
-- **Remove decorative elements**: Gradients, shadows, patterns, textures that don't serve purpose
-- **Simplify shapes**: Reduce border radius extremes, simplify custom shapes
-- **Reduce layering**: Flatten visual hierarchy where possible
-- **Clean up effects**: Reduce or remove blur effects, glows, multiple shadows
-
-### Motion Reduction
-- **Reduce animation intensity**: Shorter distances (10-20px instead of 40px), gentler easing
-- **Remove decorative animations**: Keep functional motion, remove flourishes
-- **Subtle micro-interactions**: Replace dramatic effects with gentle feedback
-- **Refined easing**: Use ease-out-quart for smooth, understated motion. Never bounce or elastic
-- **Remove animations entirely** if they're not serving a clear purpose
-
-### Composition Refinement
-- **Reduce scale jumps**: Smaller contrast between sizes creates calmer feeling
-- **Align to grid**: Bring rogue elements back into systematic alignment
-- **Even out spacing**: Replace extreme spacing variations with consistent rhythm
-
-**NEVER**:
-- Make everything the same size/weight (hierarchy still matters)
-- Remove all color (quiet ≠ grayscale)
-- Eliminate all personality (maintain character through refinement)
-- Sacrifice usability for aesthetics (functional elements still need clear affordances)
-- Make everything small and light (some anchors needed)
-
-## Verify Quality
-
-Ensure refinement maintains quality:
-
-- **Still functional**: Can users still accomplish tasks easily?
-- **Still distinctive**: Does it have character, or is it generic now?
-- **Better reading**: Is text easier to read for extended periods?
-- **Restrained, not absent**: Does the POV survive the cuts?
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,114 +0,0 @@
-# Responsive Design
-
-## Mobile-First: Write It Right
-
-Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
-
-## Breakpoints: Content-Driven
-
-Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
-
-## Detect Input Method, Not Just Screen Size
-
-**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
-
-```css
-/* Fine pointer (mouse, trackpad) */
-@media (pointer: fine) {
- .button { padding: 8px 16px; }
-}
-
-/* Coarse pointer (touch, stylus) */
-@media (pointer: coarse) {
- .button { padding: 12px 20px; } /* Larger touch target */
-}
-
-/* Device supports hover */
-@media (hover: hover) {
- .card:hover { transform: translateY(-2px); }
-}
-
-/* Device doesn't support hover (touch) */
-@media (hover: none) {
- .card { /* No hover state - use active instead */ }
-}
-```
-
-**Critical**: Don't rely on hover for functionality. Touch users can't hover.
-
-## Safe Areas: Handle the Notch
-
-Modern phones have notches, rounded corners, and home indicators. Use `env()`:
-
-```css
-body {
- padding-top: env(safe-area-inset-top);
- padding-bottom: env(safe-area-inset-bottom);
- padding-left: env(safe-area-inset-left);
- padding-right: env(safe-area-inset-right);
-}
-
-/* With fallback */
-.footer {
- padding-bottom: max(1rem, env(safe-area-inset-bottom));
-}
-```
-
-**Enable viewport-fit** in your meta tag:
-```html
-<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
-```
-
-## Responsive Images: Get It Right
-
-### srcset with Width Descriptors
-
-```html
-<img
- src="hero-800.jpg"
- srcset="
- hero-400.jpg 400w,
- hero-800.jpg 800w,
- hero-1200.jpg 1200w
- "
- sizes="(max-width: 768px) 100vw, 50vw"
- alt="Hero image"
->
-```
-
-**How it works**:
-- `srcset` lists available images with their actual widths (`w` descriptors)
-- `sizes` tells the browser how wide the image will display
-- Browser picks the best file based on viewport width AND device pixel ratio
-
-### Picture Element for Art Direction
-
-When you need different crops/compositions (not just resolutions):
-
-```html
-<picture>
- <source media="(min-width: 768px)" srcset="wide.jpg">
- <source media="(max-width: 767px)" srcset="tall.jpg">
- <img src="fallback.jpg" alt="...">
-</picture>
-```
-
-## Layout Adaptation Patterns
-
-**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
-
-## Testing: Don't Trust DevTools Alone
-
-DevTools device emulation is useful for layout but misses:
-
-- Actual touch interactions
-- Real CPU/memory constraints
-- Network latency patterns
-- Font rendering differences
-- Browser chrome/keyboard appearances
-
-**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
-
----
-
-**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
@@ -1,165 +0,0 @@
-Shape the UX and UI for a feature before any code is written. This command produces a **design brief**: a structured artifact that guides implementation through discovery, not guesswork.
-
-**Scope**: Design planning only. This command does NOT write code. It produces the thinking that makes code good.
-
-**Output**: A design brief that can be handed off to /impeccable craft, or directly to /impeccable for freeform implementation. When visual direction probes are used, the images are supporting artifacts, not the primary output.
-
-## Philosophy
-
-Most AI-generated UIs fail not because of bad code, but because of skipped thinking. They jump to "here's a card grid" without asking "what is the user trying to accomplish?" This command inverts that: understand deeply first, so implementation is precise.
-
-## Phase 1: Discovery Interview
-
-**Do NOT write any code or make any design decisions during this phase.** Your only job is to understand the feature deeply enough to make excellent design decisions later.
-
-This is a required interaction, not optional guidance. Ask these questions in conversation, adapting based on answers. Don't dump them all at once; have a natural dialogue. ask the user directly to clarify what you cannot infer.
-
-### Interview cadence
-
-Discovery includes at least one user-answer round unless PRODUCT.md, DESIGN.md, or an already-confirmed brief directly answers the needed inputs. With a sparse prompt, do **not** synthesize a complete brief for confirmation on the first response.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Treat PRODUCT.md and DESIGN.md as anchors; they reduce repeated questions but do **not** replace shape for craft. Shape is task-specific.
-- One round is the default. Add a second only if the first answers leave material gaps. Don't run a second round just to feel thorough.
-- Round 1 should clarify purpose, audience/context, content/scope, and (for brand) visual direction.
-- Round 2, when needed, fills in whatever's still genuinely missing.
-
-**Assert-then-confirm, not menu-with-escape.** When PRODUCT.md and the user's prompt make one option obvious, name it and ask the user to confirm or override. Don't enumerate "Restrained / Committed / Or something else?" as a real choice; "This reads as Restrained, confirm?" beats a four-option menu when the answer is already clear.
-
-### Purpose & Context
-- What is this feature for? What problem does it solve?
-- Who specifically will use it? (Not "users"; be specific: role, context, frequency)
-- What does success look like? How will you know this feature is working?
-- What's the user's state of mind when they reach this feature? (Rushed? Exploring? Anxious? Focused?)
-
-### Content & Data
-- What content or data does this feature display or collect?
-- What are the realistic ranges? (Minimum, typical, maximum, e.g., 0 items, 5 items, 500 items)
-- What are the edge cases? (Empty state, error state, first-time use, power user)
-- Is any content dynamic? What changes and how often?
-- What visual assets are real content here? Note required images, product shots, illustrations, maps, textures, diagrams, generated objects, or existing project assets.
-
-### Design Direction
-
-Force a visual decision on three fronts. Skip anything PRODUCT.md or DESIGN.md already answers; ask only what's missing.
-
-- **Color strategy for this surface.** Pick one: Restrained / Committed / Full palette / Drenched. Can override the project default if the surface earns it (e.g. a drenched hero inside an otherwise Restrained product).
-- **Theme via scene sentence.** Write one sentence of physical context for this surface: who uses it, where, under what ambient light, in what mood. The sentence forces dark vs light. If it doesn't, add detail until it does.
-- **Two or three named anchor references.** Specific products, brands, objects. Not adjectives like "modern" or "clean."
-
-### Scope
-
-Always ask. Sketch quality and shipped quality are different outputs; don't guess between them.
-
-- **Fidelity.** Sketch / mid-fi / high-fi / production-ready?
-- **Breadth.** One screen / a flow / a whole surface?
-- **Interactivity.** Static visual / interactive prototype / shipped-quality component?
-- **Time intent.** Quick exploration, or polish until it ships?
-
-Scope answers are task-scoped. Don't write them to PRODUCT.md or DESIGN.md; carry them through the design brief only.
-
-### Constraints
-- Are there technical constraints? (Framework, performance budget, browser support)
-- Are there content constraints? (Localization, dynamic text length, user-generated content)
-- Mobile/responsive requirements?
-- Accessibility requirements beyond WCAG AA?
-
-### Anti-Goals
-- What should this NOT be? What would be a wrong direction?
-- What's the biggest risk of getting this wrong?
-
-## Phase 1.5: Visual Direction Probe (Capability-Gated)
-
-After the discovery interview, generate a small set of visual direction probes **before** writing the final brief when all of these are true:
-
-- The work is **net-new** or directionally ambiguous enough that visual exploration will clarify the brief.
-- The requested fidelity is **mid-fi, high-fi, or production-ready**. Skip for sketch-only planning.
-- The current harness gives you native image generation (Codex's `image_gen`, an equivalent MCP tool, or similar). Don't ask the user to install APIs or tooling.
-
-When those conditions are met, this step is mandatory. If image generation isn't natively available, do not ask the user to install APIs or tooling. State in one line that the image step is skipped because the harness lacks native image generation, then proceed. The one-line announcement is required, not optional; it forces a conscious decision instead of letting the step quietly evaporate.
-
-Use probes to explore visual lanes, not to replace the brief.
-
-Do not skip probes because the final UI will be semantic, editable, code-native, responsive, or accessible. Those are implementation requirements, not reasons to avoid visual exploration.
-
-### What to generate
-
-Generate **2 to 4** distinct direction probes based on the discovery answers, especially:
-
-- Color strategy
-- Theme scene sentence
-- Named anchor references
-- Scope and fidelity
-
-The probes should differ in primary visual direction (hierarchy, topology, density, typographic voice, or color strategy), not just palette tweaks.
-
-### How to use the probes
-
-- Treat them as **direction tests**, not final designs.
-- Use them to pressure-test whether the brief is pointing at the right lane.
-- Ask the user which direction feels closest, what feels off, and what should carry forward.
-- If the probes reveal a mismatch, revise the brief inputs before finalizing the brief.
-
-### Important limits
-
-- Do **not** skip discovery because image generation is available.
-- Do **not** treat generated imagery as final UX specification, final copy, or final accessibility behavior.
-- Do **not** use this step for minor refinements of existing work. It's for shaping a new surface or clarifying a big directional choice.
-
-If image generation isn't natively available, announce the skip in one line and proceed to the design brief.
-
-## Phase 2: Design Brief
-
-After the interview and any required probes, present a brief and **end your response**. The user must confirm before any implementation runs. Do not present a brief and then continue to code in the same response, even if the brief feels obvious to you. The user's confirmation is the gate.
-
-**Choose the brief shape based on how clear the answers are:**
-
-- **Compact form (3-5 bullets)** when discovery was crisp and the original prompt + PRODUCT.md already pinned scope, content, and direction. State what you're building, the visual lane, and end with one or two specific questions or a clear "confirm or override?" prompt. This is the default for typical craft requests with a clear prompt.
-- **Full structured form (sections below)** when the task is genuinely ambiguous, multi-screen, or when the user asked for shape as a standalone step. Use this when the discipline of structure earns its weight.
-
-Don't pad a clear brief into a long one to look thorough. A 70-line brief restating answers the user just gave is noise, not rigor. Equally, don't skip the confirmation pause to look efficient: the pause is the point.
-
-Present the brief, then **stop and wait for explicit confirmation**. You are not the judge of whether the user already approved. Even when the brief feels obviously right, ask once and wait. The pause is what separates shape from premature implementation.
-
-### Brief Structure
-
-**1. Feature Summary** (2-3 sentences)
-What this is, who it's for, what it needs to accomplish.
-
-**2. Primary User Action**
-The single most important thing a user should do or understand here.
-
-**3. Design Direction**
-Color strategy (Restrained / Committed / Full palette / Drenched) + the theme scene sentence + 2–3 named anchor references. Reference PRODUCT.md and DESIGN.md where they already answer, and note any per-surface overrides.
-
-If you ran the Visual Direction Probe step, name which probe direction won and what changed in the brief because of it.
-
-**4. Scope**
-Fidelity, breadth, interactivity, and time intent from the Scope section of the interview. Task-scoped; these don't persist beyond the brief.
-
-**5. Layout Strategy**
-High-level spatial approach: what gets emphasis, what's secondary, how information flows. Describe the visual hierarchy and rhythm, not specific CSS.
-
-**6. Key States**
-List every state the feature needs: default, empty, loading, error, success, edge cases. For each, note what the user needs to see and feel.
-
-**7. Interaction Model**
-How users interact with this feature. What happens on click, hover, scroll? What feedback do they get? What's the flow from entry to completion?
-
-**8. Content Requirements**
-What copy, labels, empty state messages, error messages, and microcopy are needed. Note any dynamic content and its realistic ranges. For image-led surfaces, also list the required image/media roles and their likely source (project asset, generated raster, semantic SVG/CSS, canvas/WebGL, icon library, or accepted omission).
-
-**9. Recommended References**
-Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., spatial-design.md for complex layouts, motion-design.md for animated features, interaction-design.md for form-heavy features).
-
-**10. Open Questions**
-Anything genuinely unresolved. Don't list "open questions" you've already recommended a default for; assert the default and move on. If you'd write `Recommend: X` next to a question, just decide X.
-
----
-
-ask the user directly to clarify what you cannot infer. Ask for explicit confirmation of the brief before finishing.
-
-If the user disagrees with any part, revisit the relevant discovery questions. A shape run is incomplete until the user confirms direction.
-
-Once confirmed, the brief is complete. The user can now hand it to /impeccable, or use it to guide any other implementation approach. (If the user wants the full discovery-then-build flow in one step, they should use /impeccable craft instead, which runs this command internally.)
@@ -1,100 +0,0 @@
-# Spatial Design
-
-## Spacing Systems
-
-### Use 4pt Base, Not 8pt
-
-8pt systems are too coarse; you'll frequently need 12px (between 8 and 16). Use 4pt for granularity: 4, 8, 12, 16, 24, 32, 48, 64, 96px.
-
-### Name Tokens Semantically
-
-Name by relationship (`--space-sm`, `--space-lg`), not value (`--spacing-8`). Use `gap` instead of margins for sibling spacing; it eliminates margin collapse and cleanup hacks.
-
-## Grid Systems
-
-### The Self-Adjusting Grid
-
-Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Columns are at least 280px, as many as fit per row, leftovers stretch. For complex layouts, use named grid areas (`grid-template-areas`) and redefine them at breakpoints.
-
-## Visual Hierarchy
-
-### The Squint Test
-
-Blur your eyes (or screenshot and blur). Can you still identify:
-- The most important element?
-- The second most important?
-- Clear groupings?
-
-If everything looks the same weight blurred, you have a hierarchy problem.
-
-### Hierarchy Through Multiple Dimensions
-
-Don't rely on size alone. Combine:
-
-| Tool | Strong Hierarchy | Weak Hierarchy |
-|------|------------------|----------------|
-| **Size** | 3:1 ratio or more | <2:1 ratio |
-| **Weight** | Bold vs Regular | Medium vs Regular |
-| **Color** | High contrast | Similar tones |
-| **Position** | Top/left (primary) | Bottom/right |
-| **Space** | Surrounded by white space | Crowded |
-
-**The best hierarchy uses 2-3 dimensions at once**: A heading that's larger, bolder, AND has more space above it.
-
-### Cards Are Not Required
-
-Cards are overused. Spacing and alignment create visual grouping naturally. Use cards only when content is truly distinct and actionable, items need visual comparison in a grid, or content needs clear interaction boundaries. **Never nest cards inside cards.** Use spacing, typography, and subtle dividers for hierarchy within a card.
-
-## Container Queries
-
-Viewport queries are for page layouts. **Container queries are for components**:
-
-```css
-.card-container {
- container-type: inline-size;
-}
-
-.card {
- display: grid;
- gap: var(--space-md);
-}
-
-/* Card layout changes based on its container, not viewport */
-@container (min-width: 400px) {
- .card {
- grid-template-columns: 120px 1fr;
- }
-}
-```
-
-**Why this matters**: A card in a narrow sidebar stays compact, while the same card in a main content area expands automatically, without viewport hacks.
-
-## Optical Adjustments
-
-Text at `margin-left: 0` looks indented due to letterform whitespace; use negative margin (`-0.05em`) to optically align. Geometrically centered icons often look off-center; play icons need to shift right, arrows shift toward their direction.
-
-### Touch Targets vs Visual Size
-
-Buttons can look small but need large touch targets (44px minimum). Use padding or pseudo-elements:
-
-```css
-.icon-button {
- width: 24px; /* Visual size */
- height: 24px;
- position: relative;
-}
-
-.icon-button::before {
- content: '';
- position: absolute;
- inset: -10px; /* Expand tap target to 44px */
-}
-```
-
-## Depth & Elevation
-
-Create semantic z-index scales (dropdown → sticky → modal-backdrop → modal → toast → tooltip) instead of arbitrary numbers. For shadows, create a consistent elevation scale (sm → md → lg → xl). **Key insight**: Shadows should be subtle. If you can clearly see it, it's probably too strong.
-
----
-
-**Avoid**: Arbitrary spacing values outside your scale. Making all spacing equal (variety creates hierarchy). Creating hierarchy through size alone - combine size, weight, color, and space.
@@ -1,156 +0,0 @@
-# Teach Flow
-
-Gathers design context for a project and writes two complementary files at the project root:
-
-- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
-- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
-
-Every other impeccable command reads these files before doing any work.
-
-## Step 1: Load current state
-
-Run the shared loader first so you know what already exists:
-
-```bash
-node .kiro/skills/impeccable/scripts/load-context.mjs
-```
-
-The output tells you whether PRODUCT.md and/or DESIGN.md already exist. If `migrated: true`, legacy `.impeccable.md` was auto-renamed to `PRODUCT.md`. Mention this once to the user.
-
-Decision tree:
-- **Neither file exists (empty project or no context yet)**: do Steps 2-4 (write PRODUCT.md), then decide on DESIGN.md based on whether there's code to analyze.
-- **PRODUCT.md exists, DESIGN.md missing**: skip to Step 5 and offer to run `/impeccable document` for DESIGN.md.
-- **PRODUCT.md exists but has no `## Register` section (legacy)**: add it. Infer a hypothesis from the codebase (see Step 2), confirm with the user, write the field.
-- **Both exist**: ask the user directly to clarify what you cannot infer. Ask which file to refresh. Skip the one the user doesn't want changed.
-- **Just DESIGN.md exists (unusual)**: do Steps 2-4 to produce PRODUCT.md.
-
-Never silently overwrite an existing file. Always confirm first.
-
-If teach was invoked as a setup blocker by another command, such as `/impeccable craft landing page`, pause that command here. Complete teach, re-run the loader, then resume the original command with the freshly loaded context. For craft, resume into shape next; teach creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
-
-## Step 2: Explore the codebase
-
-Before asking questions, thoroughly scan the project to discover what you can:
-
-- **README and docs**: Project purpose, target audience, any stated goals
-- **Package.json / config files**: Tech stack, dependencies, existing design libraries
-- **Existing components**: Current design patterns, spacing, typography in use
-- **Brand assets**: Logos, favicons, color values already defined
-- **Design tokens / CSS variables**: Existing color palettes, font stacks, spacing scales
-- **Any style guides or brand documentation**
-
-Also form a **register hypothesis** from what you find:
-
-- Brand signals: `/`, `/about`, `/pricing`, `/blog/*`, `/docs/*`, hero sections, big typography, scroll-driven sections, landing-page-shaped content.
-- Product signals: `/app/*`, `/dashboard`, `/settings`, `/(auth)`, forms, data tables, side/top nav, app-shell components.
-
-Register is a hypothesis at this point, not a decision; Step 3 confirms it.
-
-Note what you've learned and what remains unclear. This exploration feeds both PRODUCT.md and DESIGN.md.
-
-## Step 3: Ask strategic questions (for PRODUCT.md)
-
-ask the user directly to clarify what you cannot infer. Ask only about what you couldn't infer from the codebase.
-
-### Interview mode, not confirmation mode
-
-If the repo is empty or the user's brief is sparse, run a short interview before proposing PRODUCT.md. Do **not** turn a one-sentence request into a complete inferred PRODUCT.md and ask for blanket confirmation.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Use inferred answers as hypotheses or options, not as finished facts.
-- Complete at least one real user-answer round before drafting PRODUCT.md, unless every required answer is directly discoverable from repo docs.
-- Round 1 should establish register, users/purpose, and desired outcome.
-- Round 2 should establish brand personality or references, anti-references, and accessibility needs.
-
-### Minimum viable interview
-
-Ask enough to complete PRODUCT.md. At minimum, cover register confirmation, users and purpose, brand personality, anti-references, and accessibility needs unless each answer is directly discoverable from repo context. After at least one interview round, you may propose inferred answers, but the user must confirm them before you write PRODUCT.md. Never synthesize PRODUCT.md from the original task prompt alone.
-
-### Register (ask first; it shapes everything below)
-
-Every design task is either **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboards, tools: design SERVES the product).
-
-If Step 2 produced a clear hypothesis, lead with it: *"From the codebase, this looks like a [brand / product] surface. Does that match your intent, or should we treat it differently?"*
-
-If the signal is genuinely split (e.g. a product with a big marketing landing), ask the user directly to clarify what you cannot infer. Ask which register describes the **primary** surface. The register can be overridden per task later, but PRODUCT.md carries one default.
-
-### Users & Purpose
-- Who uses this? What's their context when using it?
-- What job are they trying to get done?
-- For brand: what emotions should the interface evoke? (confidence, delight, calm, urgency)
-- For product: what workflow are they in? What's the primary task on any given screen?
-
-### Brand & Personality
-- How would you describe the brand personality in 3 words?
-- Reference sites or apps that capture the right feel? What specifically about them?
- - For brand, push for real-world references in the right lane (tech-minimal, editorial-magazine, consumer-warm, brutalist-grid, etc.), not generic "modern" adjectives.
- - For product, push for category best-tool references (Linear, Figma, Notion, Raycast, Stripe).
-- What should this explicitly NOT look like? Any anti-references?
-
-### Accessibility & Inclusion
-- Specific accessibility requirements? (WCAG level, known user needs)
-- Considerations for reduced motion, color blindness, or other accommodations?
-
-Skip questions where the answer is already clear. **Do NOT ask about colors, fonts, radii, or visual styling here.** Those belong in DESIGN.md, not PRODUCT.md.
-
-## Step 4: Write PRODUCT.md
-
-Write PRODUCT.md only after the user has confirmed the strategic answers from Step 3. If an inferred answer is uncertain or unconfirmed, ask before writing.
-
-Synthesize into a strategic document:
-
-```markdown
-# Product
-
-## Register
-
-product
-
-## Users
-[Who they are, their context, the job to be done]
-
-## Product Purpose
-[What this product does, why it exists, what success looks like]
-
-## Brand Personality
-[Voice, tone, 3-word personality, emotional goals]
-
-## Anti-references
-[What this should NOT look like. Specific bad-example sites or patterns to avoid.]
-
-## Design Principles
-[3-5 strategic principles derived from the conversation. Principles like "practice what you preach", "show, don't tell", "expert confidence". NOT visual rules like "use OKLCH" or "magenta accent".]
-
-## Accessibility & Inclusion
-[WCAG level, known user needs, considerations]
-```
-
-Register is either `brand` or `product` as a bare value. No prose, no commentary.
-
-Write to `PROJECT_ROOT/PRODUCT.md`. If `.impeccable.md` existed, the loader already renamed it; merge into that content rather than starting from scratch.
-
-## Step 5: Decide on DESIGN.md
-
-Offer `/impeccable document` either way. Two paths:
-
-- **Code exists** (CSS tokens, components, a running site): "I can generate a DESIGN.md that captures your visual system (colors, typography, components) so variants stay on-brand. Want to do that now?"
-- **Pre-implementation** (empty project): "I can seed a starter DESIGN.md from five quick questions about color strategy, type direction, motion energy, and references. You can re-run once there's code, to capture the real tokens. Want to do that now?"
-
-If the user agrees, delegate to `/impeccable document` (it auto-detects scan vs seed). Load its reference and follow that flow.
-
-If the user prefers to skip, mention they can run `/impeccable document` any time later.
-
-## Step 6: Confirm and wrap up
-
-Summarize:
-- Register captured (brand / product)
-- What was written (PRODUCT.md, DESIGN.md, or both)
-- The 3-5 strategic principles from PRODUCT.md that will guide future work
-- If DESIGN.md is pending, remind the user how to generate it later
-
-**Critical: re-run the loader to refresh session context.** After writing PRODUCT.md, run `node .kiro/skills/impeccable/scripts/load-context.mjs` one final time and let its full JSON output land in conversation. This ensures subsequent commands in this session use the freshly-written PRODUCT.md, not a stale earlier version.
-
-If teach was invoked as a blocker by another impeccable command (e.g. the user ran `/impeccable polish` with no PRODUCT.md), resume that original task now with the fresh context.
-
-Optionally ask the user directly to clarify what you cannot infer. Ask whether they'd like a brief summary of PRODUCT.md appended to .kiro/settings.json for easier agent reference. If yes, append a short **Design Context** pointer section there.
@@ -1,124 +0,0 @@
-Typography carries most of the information on the page. Replace generic defaults (Inter, Roboto, system fallback at flat scale) with type that reflects the brand and scales with intentional contrast.
-
----
-
-## Register
-
-Brand: run the font selection procedure in [brand.md](brand.md). Pairing follows the brand's lane (display serif + sans body for editorial/luxury, one committed sans for tech, etc.). Fluid `clamp()` scale, ≥1.25 ratio between steps.
-
-Product: system fonts and familiar sans stacks are legitimate here. One well-tuned family typically carries the whole UI. Fixed `rem` scale, 1.125–1.2 ratio between more closely-spaced steps.
-
----
-
-## Assess Current Typography
-
-Analyze what's weak or generic about the current type:
-
-1. **Font choices**:
- - Are we using invisible defaults? (Inter, Roboto, Arial, Open Sans, system defaults)
- - Does the font match the brand personality? (A playful brand shouldn't use a corporate typeface)
- - Are there too many font families? (More than 2-3 is almost always a mess)
-
-2. **Hierarchy**:
- - Can you tell headings from body from captions at a glance?
- - Are font sizes too close together? (14px, 15px, 16px = muddy hierarchy)
- - Are weight contrasts strong enough? (Medium vs Regular is barely visible)
-
-3. **Sizing & scale**:
- - Is there a consistent type scale, or are sizes arbitrary?
- - Does body text meet minimum readability? (16px+)
- - Is the sizing strategy appropriate for the context? (Fixed `rem` scales for app UIs; fluid `clamp()` for marketing/content page headings)
-
-4. **Readability**:
- - Are line lengths comfortable? (45-75 characters ideal)
- - Is line-height appropriate for the font and context?
- - Is there enough contrast between text and background?
-
-5. **Consistency**:
- - Are the same elements styled the same way throughout?
- - Are font weights used consistently? (Not bold in one section, semibold in another for the same role)
- - Is letter-spacing intentional or default everywhere?
-
-**CRITICAL**: The goal isn't to make text "fancier." It's to make it clearer, more readable, and more intentional. Good typography is invisible; bad typography is distracting.
-
-## Plan Typography Improvements
-
-Consult the [typography reference](typography.md) for detailed guidance on scales, pairing, and loading strategies.
-
-Create a systematic plan:
-
-- **Font selection**: Do fonts need replacing? What fits the brand/context?
-- **Type scale**: Establish a modular scale (e.g., 1.25 ratio) with clear hierarchy
-- **Weight strategy**: Which weights serve which roles? (Regular for body, Semibold for labels, Bold for headings, or whatever fits)
-- **Spacing**: Line-heights, letter-spacing, and margins between typographic elements
-
-## Improve Typography Systematically
-
-### Font Selection
-
-If fonts need replacing:
-- Choose fonts that reflect the brand personality
-- Pair with genuine contrast (serif + sans, geometric + humanist), or use a single family in multiple weights
-- Ensure web font loading doesn't cause layout shift (`font-display: swap`, metric-matched fallbacks)
-
-### Establish Hierarchy
-
-Build a clear type scale:
-- **5 sizes cover most needs**: caption, secondary, body, subheading, heading
-- **Use a consistent ratio** between levels (1.25, 1.333, or 1.5)
-- **Combine dimensions**: Size + weight + color + space for strong hierarchy. Don't rely on size alone
-- **App UIs**: Use a fixed `rem`-based type scale, optionally adjusted at 1-2 breakpoints. Fluid sizing undermines the spatial predictability that dense, container-based layouts need
-- **Marketing / content pages**: Use fluid sizing via `clamp(min, preferred, max)` for headings and display text. Keep body text fixed
-
-### Fix Readability
-
-- Set `max-width` on text containers using `ch` units (`max-width: 65ch`)
-- Adjust line-height per context: tighter for headings (1.1-1.2), looser for body (1.5-1.7)
-- Increase line-height slightly for light-on-dark text
-- Ensure body text is at least 16px / 1rem
-
-### Refine Details
-
-- Use `tabular-nums` for data tables and numbers that should align
-- Apply proper `letter-spacing`: slightly open for small caps and uppercase, default or tight for large display text
-- Use semantic token names (`--text-body`, `--text-heading`), not value names (`--font-16`)
-- Set `font-kerning: normal` and consider OpenType features where appropriate
-
-### Weight Consistency
-
-- Define clear roles for each weight and stick to them
-- Don't use more than 3-4 weights (Regular, Medium, Semibold, Bold is plenty)
-- Load only the weights you actually use (each weight adds to page load)
-
-**NEVER**:
-- Use more than 2-3 font families
-- Pick sizes arbitrarily; commit to a scale
-- Set body text below 16px
-- Use decorative/display fonts for body text
-- Disable browser zoom (`user-scalable=no`)
-- Use `px` for font sizes; use `rem` to respect user settings
-- Default to Inter/Roboto/Open Sans when personality matters
-- Pair fonts that are similar but not identical (two geometric sans-serifs)
-
-## Verify Typography Improvements
-
-- **Hierarchy**: Can you identify heading vs body vs caption instantly?
-- **Readability**: Is body text comfortable to read in long passages?
-- **Consistency**: Are same-role elements styled identically throughout?
-- **Personality**: Does the typography reflect the brand?
-- **Performance**: Are web fonts loading efficiently without layout shift?
-- **Accessibility**: Does text meet WCAG contrast ratios? Is it zoomable to 200%?
-
-When the type carries the hierarchy on its own, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `scale` param controlling the hierarchy ratio. Express all font sizes in the variant's scoped CSS through `calc(var(--p-scale, 1) * <base>)` or, better, scale the type ramp via `clamp(min, calc(var(--p-scale, 1) * Npx), max)`. Users slide from subdued to commanding.
-
-```json
-{"id":"scale","kind":"range","min":0.85,"max":1.3,"step":0.05,"default":1,"label":"Scale"}
-```
-
-Where the variant riffs on a specific pairing, expose the pairing choice as a `steps` param (e.g. "serif display + sans body" vs. "mono display + sans body" vs. "all-sans"). Each branch routes through `:scope[data-p-pairing="X"]` selectors in scoped CSS.
-
-See `reference/live.md` for the full params contract.
@@ -1,159 +0,0 @@
-# Typography
-
-## Classic Typography Principles
-
-### Vertical Rhythm
-
-Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
-
-### Modular Scale & Hierarchy
-
-The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
-
-**Use fewer sizes with more contrast.** A 5-size system covers most needs:
-
-| Role | Typical Ratio | Use Case |
-|------|---------------|----------|
-| xs | 0.75rem | Captions, legal |
-| sm | 0.875rem | Secondary UI, metadata |
-| base | 1rem | Body text |
-| lg | 1.25-1.5rem | Subheadings, lead text |
-| xl+ | 2-4rem | Headlines, hero text |
-
-Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
-
-### Readability & Measure
-
-Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
-
-**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
-
-**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
-
-## Font Selection & Pairing
-
-The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
-
-### Anti-reflexes worth defending against
-
-- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
-- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
-- A children's product does NOT need a rounded display font. Kids' books use real type.
-- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
-
-**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
-
-### Pairing Principles
-
-**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
-
-When pairing, contrast on multiple axes:
-- Serif + Sans (structure contrast)
-- Geometric + Humanist (personality contrast)
-- Condensed display + Wide body (proportion contrast)
-
-**Never pair fonts that are similar but not identical** (e.g., two geometric sans-serifs). They create visual tension without clear hierarchy.
-
-### Web Font Loading
-
-The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
-
-```css
-/* 1. Use font-display: swap for visibility */
-@font-face {
- font-family: 'CustomFont';
- src: url('font.woff2') format('woff2');
- font-display: swap;
-}
-
-/* 2. Match fallback metrics to minimize shift */
-@font-face {
- font-family: 'CustomFont-Fallback';
- src: local('Arial');
- size-adjust: 105%; /* Scale to match x-height */
- ascent-override: 90%; /* Match ascender height */
- descent-override: 20%; /* Match descender depth */
- line-gap-override: 10%; /* Match line spacing */
-}
-
-body {
- font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
-}
-```
-
-Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
-
-**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
-
-**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
-
-**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
-
-## Modern Web Typography
-
-### Fluid Type
-
-Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
-
-**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
-
-**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
-
-**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
-
-**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
-
-### OpenType Features
-
-Most developers don't know these exist. Use them for polish:
-
-```css
-/* Tabular numbers for data alignment */
-.data-table { font-variant-numeric: tabular-nums; }
-
-/* Proper fractions */
-.recipe-amount { font-variant-numeric: diagonal-fractions; }
-
-/* Small caps for abbreviations */
-abbr { font-variant-caps: all-small-caps; }
-
-/* Disable ligatures in code */
-code { font-variant-ligatures: none; }
-
-/* Enable kerning (usually on by default, but be explicit) */
-body { font-kerning: normal; }
-```
-
-Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
-
-### Rendering polish
-
-```css
-/* Even out heading line lengths (browser picks better break points) */
-h1, h2, h3 { text-wrap: balance; }
-
-/* Reduce orphans and ragged endings in long prose */
-article p { text-wrap: pretty; }
-
-/* Variable fonts: pick the right optical-size master automatically */
-body { font-optical-sizing: auto; }
-```
-
-**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
-
-## Typography System Architecture
-
-Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
-
-## Accessibility Considerations
-
-Beyond contrast ratios (which are well-documented), consider:
-
-- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
-- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
-- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
-- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
-
----
-
-**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
@@ -1,107 +0,0 @@
-# UX Writing
-
-## The Button Label Problem
-
-**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
-
-| Bad | Good | Why |
-|-----|------|-----|
-| OK | Save changes | Says what will happen |
-| Submit | Create account | Outcome-focused |
-| Yes | Delete message | Confirms the action |
-| Cancel | Keep editing | Clarifies what "cancel" means |
-| Click here | Download PDF | Describes the destination |
-
-**For destructive actions**, name the destruction:
-- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
-- "Delete 5 items" not "Delete selected" (show the count)
-
-## Error Messages: The Formula
-
-Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
-
-### Error Message Templates
-
-| Situation | Template |
-|-----------|----------|
-| **Format error** | "[Field] needs to be [format]. Example: [example]" |
-| **Missing required** | "Please enter [what's missing]" |
-| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
-| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
-| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
-
-### Don't Blame the User
-
-Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
-
-## Empty States Are Opportunities
-
-Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
-
-## Voice vs Tone
-
-**Voice** is your brand's personality, consistent everywhere.
-**Tone** adapts to the moment.
-
-| Moment | Tone Shift |
-|--------|------------|
-| Success | Celebratory, brief: "Done! Your changes are live." |
-| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
-| Loading | Reassuring: "Saving your work..." |
-| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
-
-**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
-
-## Writing for Accessibility
-
-**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
-
-## Writing for Translation
-
-### Plan for Expansion
-
-German text is ~30% longer than English. Allocate space:
-
-| Language | Expansion |
-|----------|-----------|
-| German | +30% |
-| French | +20% |
-| Finnish | +30-40% |
-| Chinese | -30% (fewer chars, but same width) |
-
-### Translation-Friendly Patterns
-
-Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
-
-## Consistency: The Terminology Problem
-
-Pick one term and stick with it:
-
-| Inconsistent | Consistent |
-|--------------|------------|
-| Delete / Remove / Trash | Delete |
-| Settings / Preferences / Options | Settings |
-| Sign in / Log in / Enter | Sign in |
-| Create / Add / New | Create |
-
-Build a terminology glossary and enforce it. Variety creates confusion.
-
-## Avoid Redundant Copy
-
-If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
-
-## Loading States
-
-Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
-
-## Confirmation Dialogs: Use Sparingly
-
-Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
-
-## Form Instructions
-
-Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
-
----
-
-**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
@@ -1,284 +0,0 @@
-#!/usr/bin/env node
-/**
- * Cleans up deprecated Impeccable skill files, symlinks, and
- * skills-lock.json entries left over from previous versions.
- *
- * Safe to run repeatedly -- it is a no-op when nothing needs cleaning.
- *
- * Usage (from the project root):
- * node {{scripts_path}}/cleanup-deprecated.mjs
- *
- * What it does:
- * 1. Finds every harness-specific skills directory (.claude/skills,
- * .cursor/skills, .agents/skills, etc.).
- * 2. For each deprecated skill name (with and without i- prefix),
- * checks if the directory exists and its SKILL.md mentions
- * "impeccable" (to avoid deleting unrelated user skills).
- * 3. Deletes confirmed matches (files, directories, or symlinks).
- * 4. Removes the corresponding entries from skills-lock.json.
- */
-
-import { existsSync, readFileSync, writeFileSync, rmSync, readdirSync, statSync, lstatSync, unlinkSync } from 'node:fs';
-import { join, resolve } from 'node:path';
-
-// Skills that were renamed, merged, or folded in v2.0, v2.1, and v3.0.
-const DEPRECATED_NAMES = [
- // v2.0 renames
- 'frontend-design', // renamed to impeccable
- 'teach-impeccable', // folded into /impeccable teach
- // v2.1 merges
- 'arrange', // renamed to layout
- 'normalize', // merged into polish
- 'onboard', // merged into harden
- 'extract', // merged into /impeccable extract
- // v3.0 consolidation: all standalone skills -> /impeccable sub-commands
- 'adapt',
- 'animate',
- 'audit',
- 'bolder',
- 'clarify',
- 'colorize',
- 'critique',
- 'delight',
- 'distill',
- 'harden',
- 'layout',
- 'optimize',
- 'overdrive',
- 'polish',
- 'quieter',
- 'shape',
- 'typeset',
-];
-
-// All known harness directories that may contain a skills/ subfolder.
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Per-skill fingerprints for SKILL.md bodies that never mentioned
-// "impeccable" in their v2.x source. Used as a last-resort match
-// when no skills-lock.json exists and the word heuristic fails.
-// The strings are lifted verbatim from the v2.x frontmatter
-// descriptions, so collisions with hand-written user skills are
-// vanishingly unlikely.
-const SKILL_FINGERPRINTS = {
- harden: 'Make interfaces production-ready: error handling, empty states',
- optimize: 'Diagnoses and fixes UI performance across loading speed',
-};
-
-/**
- * Walk up from startDir until we find a directory that looks like a
- * project root (has package.json, .git, or skills-lock.json).
- */
-export function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- const { root } = { root: '/' };
- while (dir !== root) {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Load skills-lock.json from the project root, or null if missing/unreadable.
- */
-export function loadLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return null;
- try {
- return JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return null;
- }
-}
-
-/**
- * Check whether a skill directory belongs to Impeccable. Three layered
- * signals, in order of reliability:
- * 1. Lock source equals "pbakaus/impeccable" (authoritative).
- * 2. SKILL.md body contains the word "impeccable".
- * 3. SKILL.md body contains a per-skill fingerprint (for harden and
- * optimize, whose v2.x SKILL.md never mentioned the pack name).
- */
-export function isImpeccableSkill(skillDir, { skillName, lock } = {}) {
- // 1. Authoritative: the lock file claims this skill is ours.
- if (skillName && lock?.skills?.[skillName]?.source === 'pbakaus/impeccable') {
- return true;
- }
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) return false;
- let content;
- try {
- content = readFileSync(skillMd, 'utf-8');
- } catch {
- return false;
- }
- // 2. Word-level content heuristic.
- if (/impeccable/i.test(content)) return true;
- // 3. Per-skill fingerprint for old skills that never mentioned the pack.
- // Strip the i- prefix so both `harden` and `i-harden` resolve to the
- // same fingerprint entry.
- const unprefixed = skillName?.startsWith('i-') ? skillName.slice(2) : skillName;
- const fingerprint = unprefixed && SKILL_FINGERPRINTS[unprefixed];
- if (fingerprint && content.includes(fingerprint)) return true;
- return false;
-}
-
-/**
- * Build the full list of names to check: each deprecated name, plus
- * its i-prefixed variant.
- */
-export function buildTargetNames() {
- const names = [];
- for (const name of DEPRECATED_NAMES) {
- names.push(name);
- names.push(`i-${name}`);
- }
- return names;
-}
-
-/**
- * Find every skills directory across all harness dirs in the project.
- * Returns absolute paths that exist on disk.
- */
-export function findSkillsDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const candidate = join(projectRoot, harness, 'skills');
- if (existsSync(candidate)) {
- dirs.push(candidate);
- }
- }
- return dirs;
-}
-
-/**
- * Remove deprecated skill directories/symlinks from all harness dirs.
- * Reads skills-lock.json so the authoritative "source" field can
- * drive deletion even when SKILL.md never mentions impeccable.
- * Returns an array of paths that were deleted.
- */
-export function removeDeprecatedSkills(projectRoot, lock) {
- if (lock === undefined) lock = loadLock(projectRoot);
- const targets = buildTargetNames();
- const skillsDirs = findSkillsDirs(projectRoot);
- const deleted = [];
-
- for (const skillsDir of skillsDirs) {
- for (const name of targets) {
- const skillPath = join(skillsDir, name);
-
- // Use lstat to detect symlinks (existsSync follows symlinks and
- // returns false for dangling ones).
- let stat;
- try {
- stat = lstatSync(skillPath);
- } catch {
- continue; // does not exist at all
- }
-
- if (stat.isSymbolicLink()) {
- // Symlink: check the target if it's alive, otherwise treat
- // dangling symlinks to deprecated names as safe to remove.
- const targetAlive = existsSync(skillPath);
- const isMatch = targetAlive
- ? isImpeccableSkill(skillPath, { skillName: name, lock })
- : true;
- if (isMatch) {
- unlinkSync(skillPath);
- deleted.push(skillPath);
- }
- continue;
- }
-
- // Regular directory -- verify it belongs to impeccable
- if (isImpeccableSkill(skillPath, { skillName: name, lock })) {
- rmSync(skillPath, { recursive: true, force: true });
- deleted.push(skillPath);
- }
- }
- }
-
- return deleted;
-}
-
-/**
- * Remove deprecated entries from skills-lock.json.
- * Only removes entries whose source is "pbakaus/impeccable".
- * Returns the list of removed skill names.
- */
-export function cleanSkillsLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return [];
-
- let lock;
- try {
- lock = JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return [];
- }
-
- if (!lock.skills || typeof lock.skills !== 'object') return [];
-
- const targets = buildTargetNames();
- const removed = [];
-
- for (const name of targets) {
- const entry = lock.skills[name];
- if (!entry) continue;
- // Only remove if it belongs to impeccable
- if (entry.source === 'pbakaus/impeccable') {
- delete lock.skills[name];
- removed.push(name);
- }
- }
-
- if (removed.length > 0) {
- writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\n', 'utf-8');
- }
-
- return removed;
-}
-
-/**
- * Run the full cleanup. Returns a summary object.
- *
- * Order matters: read the lock and delete directories first, then
- * strip lock entries. Otherwise the authoritative signal is gone by
- * the time directory deletion runs.
- */
-export function cleanup(projectRoot) {
- const root = projectRoot || findProjectRoot();
- const lock = loadLock(root);
- const deletedPaths = removeDeprecatedSkills(root, lock);
- const removedLockEntries = cleanSkillsLock(root);
- return { deletedPaths, removedLockEntries, projectRoot: root };
-}
-
-// CLI entry point
-if (process.argv[1] && resolve(process.argv[1]) === resolve(new URL(import.meta.url).pathname)) {
- const result = cleanup();
- if (result.deletedPaths.length === 0 && result.removedLockEntries.length === 0) {
- console.log('No deprecated Impeccable skills found. Nothing to clean up.');
- } else {
- if (result.deletedPaths.length > 0) {
- console.log(`Removed ${result.deletedPaths.length} deprecated skill(s):`);
- for (const p of result.deletedPaths) console.log(` - ${p}`);
- }
- if (result.removedLockEntries.length > 0) {
- console.log(`Cleaned ${result.removedLockEntries.length} entry/entries from skills-lock.json:`);
- for (const name of result.removedLockEntries) console.log(` - ${name}`);
- }
- }
-}
@@ -1,94 +0,0 @@
-{
- "craft": {
- "description": "Full confirmed-brief-then-build flow. Runs multi-round shape discovery first, resolves visual probe and north-star mock gates when available, then builds and visually iterates. Use when building a new feature end-to-end.",
- "argumentHint": "[feature description]"
- },
- "teach": {
- "description": "Gathers design context for a project. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles) and, when code exists to analyze, DESIGN.md (visual: colors, typography, components). Every other command reads these files before doing work. Use once per project.",
- "argumentHint": ""
- },
- "document": {
- "description": "Generate a DESIGN.md file that captures the current visual design system. Auto-extracts colors, typography, spacing, radii, and component patterns from the codebase, then asks the user to confirm descriptive language for atmosphere and color character. Follows the Google Stitch DESIGN.md format so the file is tool-compatible. Use when you need a visual design spec an AI agent can follow to stay on-brand.",
- "argumentHint": ""
- },
- "extract": {
- "description": "Pull reusable patterns, components, and design tokens into the design system. Identifies repeated patterns and consolidates them. Use when you have drift across the codebase and want to bring things back to a consistent system.",
- "argumentHint": "[target]"
- },
- "live": {
- "description": "Interactive live variant mode. Select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via HMR. Requires a running dev server. Use when you want to visually experiment with design alternatives in real time.",
- "argumentHint": ""
- },
- "adapt": {
- "description": "Adapt designs to work across different screen sizes, devices, contexts, or platforms. Implements breakpoints, fluid layouts, and touch targets. Use when the user mentions responsive design, mobile layouts, breakpoints, viewport adaptation, or cross-device compatibility.",
- "argumentHint": "[target] [context (mobile, tablet, print...)]"
- },
- "animate": {
- "description": "Review a feature and enhance it with purposeful animations, micro-interactions, and motion effects that improve usability and delight. Use when the user mentions adding animation, transitions, micro-interactions, motion design, hover effects, or making the UI feel more alive.",
- "argumentHint": "[target]"
- },
- "audit": {
- "description": "Run technical quality checks across accessibility, performance, theming, responsive design, and anti-patterns. Generates a scored report with P0-P3 severity ratings and actionable plan. Use when the user wants an accessibility check, performance audit, or technical quality review.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "bolder": {
- "description": "Amplify safe or boring designs to make them more visually interesting and stimulating. Increases impact while maintaining usability. Use when the user says the design looks bland, generic, too safe, lacks personality, or wants more visual impact and character.",
- "argumentHint": "[target]"
- },
- "clarify": {
- "description": "Improve unclear UX copy, error messages, microcopy, labels, and instructions to make interfaces easier to understand. Use when the user mentions confusing text, unclear labels, bad error messages, hard-to-follow instructions, or wanting better UX writing.",
- "argumentHint": "[target]"
- },
- "colorize": {
- "description": "Add strategic color to features that are too monochromatic or lack visual interest, making interfaces more engaging and expressive. Use when the user mentions the design looking gray, dull, lacking warmth, needing more color, or wanting a more vibrant or expressive palette.",
- "argumentHint": "[target]"
- },
- "critique": {
- "description": "Evaluate design from a UX perspective, assessing visual hierarchy, information architecture, emotional resonance, cognitive load, and overall quality with quantitative scoring, persona-based testing, automated anti-pattern detection, and actionable feedback. Use when the user asks to review, critique, evaluate, or give feedback on a design or component.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "delight": {
- "description": "Add moments of joy, personality, and unexpected touches that make interfaces memorable and enjoyable to use. Elevates functional to delightful. Use when the user asks to add polish, personality, animations, micro-interactions, delight, or make an interface feel fun or memorable.",
- "argumentHint": "[target]"
- },
- "distill": {
- "description": "Strip designs to their essence by removing unnecessary complexity. Great design is simple, powerful, and clean. Use when the user asks to simplify, declutter, reduce noise, remove elements, or make a UI cleaner and more focused.",
- "argumentHint": "[target]"
- },
- "harden": {
- "description": "Make interfaces production-ready: error handling, i18n, text overflow, edge case management, and resilience under real-world data. Use when the user asks to harden, make production-ready, handle edge cases, add error states, or fix overflow and i18n issues.",
- "argumentHint": "[target]"
- },
- "onboard": {
- "description": "Design onboarding flows, first-run experiences, and empty states that guide new users to value. Covers welcome screens, account setup, progressive disclosure, contextual tooltips, feature announcements, and activation moments. Use when the user mentions onboarding, first-time users, empty states, activation, getting started, new user flows, or the aha moment.",
- "argumentHint": "[target]"
- },
- "layout": {
- "description": "Improve layout, spacing, and visual rhythm. Fixes monotonous grids, inconsistent spacing, and weak visual hierarchy. Use when the user mentions layout feeling off, spacing issues, visual hierarchy, crowded UI, alignment problems, or wanting better composition.",
- "argumentHint": "[target]"
- },
- "optimize": {
- "description": "Diagnoses and fixes UI performance across loading speed, rendering, animations, images, and bundle size. Use when the user mentions slow, laggy, janky, performance, bundle size, load time, or wants a faster, smoother experience.",
- "argumentHint": "[target]"
- },
- "overdrive": {
- "description": "Pushes interfaces past conventional limits with technically ambitious implementations — shaders, spring physics, scroll-driven reveals, 60fps animations. Use when the user wants to wow, impress, go all-out, or make something that feels extraordinary.",
- "argumentHint": "[target]"
- },
- "polish": {
- "description": "Performs a final quality pass fixing alignment, spacing, consistency, and micro-detail issues before shipping. Use when the user mentions polish, finishing touches, pre-launch review, something looks off, or wants to go from good to great.",
- "argumentHint": "[target]"
- },
- "quieter": {
- "description": "Tones down visually aggressive or overstimulating designs, reducing intensity while preserving quality. Use when the user mentions too bold, too loud, overwhelming, aggressive, garish, or wants a calmer, more refined aesthetic.",
- "argumentHint": "[target]"
- },
- "shape": {
- "description": "Plan UX and UI before code. Runs a required multi-round discovery interview, uses visual probes when available, and produces a user-confirmed design brief for implementation.",
- "argumentHint": "[feature to shape]"
- },
- "typeset": {
- "description": "Improves typography by fixing font choices, hierarchy, sizing, weight, and readability so text feels intentional. Use when the user mentions fonts, type, readability, text hierarchy, sizing looks off, or wants more polished, intentional typography.",
- "argumentHint": "[target]"
- }
-}
@@ -1,242 +0,0 @@
-#!/usr/bin/env node
-/**
- * Critique persistence helper.
- *
- * Each run of /impeccable critique writes a per-target snapshot to
- * .impeccable/critique/<timestamp>__<slug>.md
- * with a small YAML frontmatter carrying the score + P0/P1 counts.
- *
- * /impeccable polish reads the latest matching snapshot at start as its
- * fix backlog. No other skill auto-reads critique output.
- *
- * The slug is derived mechanically from the *resolved* primary artifact
- * (file path or URL), never from the user's natural-language phrasing.
- * Slug stability across runs is what lets the trend display work.
- *
- * CLI entry points (called from skill instructions):
- * node critique-storage.mjs slug <resolved-target>
- * node critique-storage.mjs write <slug> <snapshot-body-file>
- * node critique-storage.mjs latest <slug>
- * node critique-storage.mjs trend <slug> [limit]
- *
- * Note: there is intentionally no `ignore` subcommand. ignore.md is a plain
- * markdown file; the model reads it directly with its file-read tool. This
- * helper only exists for operations the model can't trivially do inline
- * (normalizing paths, generating filenames, globbing + parsing frontmatter).
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath, pathToFileURL } from 'node:url';
-import { getCritiqueDir } from './impeccable-paths.mjs';
-
-const SLUG_MAX = 50;
-
-/**
- * Mechanically derive a slug from a resolved target. Returns null if the
- * input doesn't look like a stable identifier (empty, project root, etc).
- *
- * Accepts file paths and URLs. The model resolves "the homepage" to a
- * concrete artifact before calling this — we never slug a natural-language
- * phrase.
- */
-export function slugFromTarget(resolved, { cwd = process.cwd() } = {}) {
- if (!resolved || typeof resolved !== 'string') return null;
- const trimmed = resolved.trim();
- if (!trimmed) return null;
-
- // URL
- if (/^https?:\/\//i.test(trimmed)) {
- let url;
- try { url = new URL(trimmed); } catch { return null; }
- const hostPath = `${url.hostname}${url.pathname}`;
- return kebab(hostPath);
- }
-
- // File path. Make it project-relative so two devs critiquing the same
- // checkout get the same slug regardless of where their repo is cloned.
- const abs = path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- let rel = path.relative(cwd, abs);
- // If the target is outside cwd, fall back to the basename so we still
- // produce a stable slug (vs the absolute path, which would include
- // home dirs / usernames).
- if (rel.startsWith('..') || path.isAbsolute(rel)) {
- rel = path.basename(abs);
- }
- if (!rel || rel === '.' || rel === '') return null;
- return kebab(rel);
-}
-
-function kebab(s) {
- const slug = s
- .toLowerCase()
- .replace(/[/\\.]+/g, '-')
- .replace(/[^a-z0-9-]+/g, '-')
- .replace(/-+/g, '-')
- .replace(/^-|-$/g, '');
- if (!slug) return null;
- // Cap from the tail — the tail (filename) is more identifying than the
- // top-level directory.
- return slug.length <= SLUG_MAX ? slug : slug.slice(slug.length - SLUG_MAX).replace(/^-/, '');
-}
-
-/**
- * Filename-safe UTC ISO timestamp: hyphens for separators, trailing Z.
- * Plain colons aren't allowed on Windows filesystems.
- */
-export function nowFilenameStamp(date = new Date()) {
- const iso = date.toISOString(); // 2026-05-12T18:30:00.123Z
- return iso.replace(/[:.]/g, '-').replace(/-\d+Z$/, 'Z');
-}
-
-/**
- * Write a snapshot for `slug`. `meta` carries the small structured frontmatter
- * keys read back by readTrend(). `body` is the human-readable critique
- * report (everything below the frontmatter).
- *
- * Returns the absolute path written.
- */
-export function writeSnapshot({ slug, meta, body, cwd = process.cwd(), now = new Date() }) {
- if (!slug) throw new Error('writeSnapshot requires a slug');
- const dir = getCritiqueDir(cwd);
- fs.mkdirSync(dir, { recursive: true });
- const timestamp = nowFilenameStamp(now);
- const filePath = path.join(dir, `${timestamp}__${slug}.md`);
- // Spread `meta` first so internally computed `timestamp` and `slug`
- // always win. Otherwise a caller-supplied meta blob (parsed from the
- // IMPECCABLE_CRITIQUE_META env var) could clobber them, leaving the
- // filename in disagreement with its frontmatter and corrupting trends.
- const front = serializeFrontmatter({ ...meta, timestamp, slug });
- fs.writeFileSync(filePath, `${front}\n${body.trim()}\n`, 'utf-8');
- return filePath;
-}
-
-function serializeFrontmatter(obj) {
- const lines = ['---'];
- for (const [key, value] of Object.entries(obj)) {
- if (value === undefined || value === null) continue;
- const str = typeof value === 'string' ? value : String(value);
- // Quote strings that contain : or # to keep parsing simple.
- const needsQuotes = typeof value === 'string' && /[:#]/.test(str);
- lines.push(`${key}: ${needsQuotes ? JSON.stringify(str) : str}`);
- }
- lines.push('---');
- return lines.join('\n');
-}
-
-function parseFrontmatter(text) {
- const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
- if (!match) return {};
- const out = {};
- for (const line of match[1].split(/\r?\n/)) {
- const colon = line.indexOf(':');
- if (colon < 0) continue;
- const key = line.slice(0, colon).trim();
- let value = line.slice(colon + 1).trim();
- if (/^".*"$/.test(value)) {
- try { value = JSON.parse(value); } catch { /* leave as-is */ }
- } else if (/^-?\d+$/.test(value)) {
- value = Number(value);
- }
- out[key] = value;
- }
- return out;
-}
-
-/**
- * Return all snapshot files for `slug`, sorted oldest → newest.
- */
-function listSnapshotsForSlug(slug, cwd) {
- const dir = getCritiqueDir(cwd);
- if (!fs.existsSync(dir)) return [];
- const suffix = `__${slug}.md`;
- return fs.readdirSync(dir)
- .filter((f) => f.endsWith(suffix))
- .sort()
- .map((f) => path.join(dir, f));
-}
-
-/**
- * Return the most recent snapshot for `slug`, or null. Polish reads this
- * to find its fix backlog when the slug matches.
- */
-export function readLatestSnapshot(slug, { cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- if (!all.length) return null;
- const latest = all[all.length - 1];
- const body = fs.readFileSync(latest, 'utf-8');
- return { path: latest, body, meta: parseFrontmatter(body) };
-}
-
-/**
- * Return the last `limit` snapshots' frontmatter, oldest → newest.
- * Critique appends a one-line trend to its output using this.
- */
-export function readTrend(slug, { limit = 5, cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- const slice = all.slice(-limit);
- return slice.map((file) => parseFrontmatter(fs.readFileSync(file, 'utf-8')));
-}
-
-// ---- CLI ---------------------------------------------------------------
-
-function main(argv) {
- const [cmd, ...args] = argv;
- switch (cmd) {
- case 'slug': {
- const slug = slugFromTarget(args[0]);
- if (!slug) { process.stderr.write('no stable slug for input\n'); process.exit(1); }
- process.stdout.write(`${slug}\n`);
- return;
- }
- case 'write': {
- const [slug, bodyFile] = args;
- if (!slug || !bodyFile) { process.stderr.write('usage: write <slug> <body-file>\n'); process.exit(1); }
- const raw = fs.readFileSync(bodyFile, 'utf-8');
- // The body file may be a full report. The caller passes the meta as
- // a JSON object on stdin if it wants structured frontmatter; otherwise
- // we write with minimal metadata.
- let meta = {};
- const metaArg = process.env.IMPECCABLE_CRITIQUE_META;
- if (metaArg) {
- try { meta = JSON.parse(metaArg); } catch { /* ignore */ }
- }
- const out = writeSnapshot({ slug, meta, body: raw });
- process.stdout.write(`${out}\n`);
- return;
- }
- case 'latest': {
- const latest = readLatestSnapshot(args[0]);
- if (!latest) { process.exit(2); }
- process.stdout.write(latest.body);
- return;
- }
- case 'trend': {
- const rows = readTrend(args[0], { limit: args[1] ? Number(args[1]) : 5 });
- process.stdout.write(JSON.stringify(rows, null, 2) + '\n');
- return;
- }
- default:
- process.stderr.write('usage: critique-storage.mjs <slug|write|latest|trend> [args]\n');
- process.exit(1);
- }
-}
-
-function isMainModule() {
- if (!process.argv[1]) return false;
- try {
- return fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1]);
- } catch {
- // pathToFileURL normalizes Windows paths; keep it as a fallback for any
- // environment where realpath is unavailable.
- return import.meta.url === pathToFileURL(process.argv[1]).href;
- }
-}
-
-// Why the realpath check: generated skills are often reached through symlinked
-// harness directories (for example a demo repo's `.agents` -> source `.agents`).
-// Node resolves import.meta.url to the real file, while process.argv[1] keeps
-// the symlink path. Comparing canonical paths prevents a silent exit-0 no-op.
-if (isMainModule()) {
- main(process.argv.slice(2));
-}
@@ -1,820 +0,0 @@
-// Parse a DESIGN.md (Stitch-spec format) into a structured JSON model that
-// the live-mode design-system panel can render. Deterministic, dependency-free.
-//
-// Two-layer: YAML frontmatter (machine-readable tokens) + markdown body
-// (prose with six canonical H2 sections). When frontmatter is present, it's
-// exposed on `model.frontmatter` alongside the prose-scraped sections;
-// consumers can prefer frontmatter values and fall back to prose.
-
-const CANONICAL_SECTIONS = [
- 'Overview',
- 'Colors',
- 'Typography',
- 'Elevation',
- 'Components',
- "Do's and Don'ts",
-];
-
-// ---------- Frontmatter (Stitch YAML subset) ----------
-
-function parseFrontmatter(md) {
- const lines = md.split(/\r?\n/);
- if (lines[0]?.trim() !== '---') return { frontmatter: null, body: md };
-
- let end = -1;
- for (let i = 1; i < lines.length; i++) {
- if (lines[i].trim() === '---') { end = i; break; }
- }
- if (end === -1) return { frontmatter: null, body: md };
-
- const yaml = lines.slice(1, end).join('\n');
- const body = lines.slice(end + 1).join('\n');
- try {
- return { frontmatter: parseYamlSubset(yaml), body };
- } catch {
- return { frontmatter: null, body: md };
- }
-}
-
-// Minimal YAML reader for the Stitch frontmatter subset: scalar maps with
-// one level of nested objects (typography roles, components). Indent-based,
-// 2-space convention. No arrays, no anchors, no multi-line scalars — Stitch's
-// schema doesn't need them and accepting them would require a real YAML
-// dependency we don't want to vendor.
-function parseYamlSubset(yaml) {
- const lines = yaml.split(/\r?\n/);
- const root = {};
- const stack = [{ indent: -1, obj: root }];
-
- for (const raw of lines) {
- // Skip blanks and line-only comments. Don't strip inline comments:
- // unquoted hex values start with `#` and can't be safely distinguished
- // from a comment after whitespace.
- if (!raw.trim() || /^\s*#/.test(raw)) continue;
-
- const indent = raw.match(/^\s*/)[0].length;
- const content = raw.slice(indent);
-
- const colonIdx = findTopLevelColon(content);
- if (colonIdx === -1) continue;
-
- while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
- stack.pop();
- }
-
- const key = content.slice(0, colonIdx).trim();
- const rest = content.slice(colonIdx + 1).trim();
- const parent = stack[stack.length - 1].obj;
-
- if (rest === '') {
- const obj = {};
- parent[key] = obj;
- stack.push({ indent, obj });
- } else {
- parent[key] = parseScalar(rest);
- }
- }
-
- return root;
-}
-
-function findTopLevelColon(s) {
- let inQuote = null;
- for (let i = 0; i < s.length; i++) {
- const ch = s[i];
- if (inQuote) {
- if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
- } else if (ch === '"' || ch === "'") {
- inQuote = ch;
- } else if (ch === ':') {
- return i;
- }
- }
- return -1;
-}
-
-function parseScalar(raw) {
- const s = raw.trim();
- if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
- return s.slice(1, -1);
- }
- if (s === 'true') return true;
- if (s === 'false') return false;
- if (s === 'null' || s === '~') return null;
- if (/^-?\d+$/.test(s)) return Number(s);
- if (/^-?\d*\.\d+$/.test(s)) return Number(s);
- return s;
-}
-
-const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
-const OKLCH_RE = /oklch\([^)]+\)/gi;
-const RGBA_RE = /rgba?\([^)]+\)/gi;
-const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
-const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
-
-// ---------- Section splitting ----------
-
-function splitSections(md) {
- const lines = md.split(/\r?\n/);
- let title = null;
- const sections = {};
- let current = null;
-
- for (const raw of lines) {
- const line = raw.trimEnd();
-
- if (!title && line.startsWith('# ') && !line.startsWith('## ')) {
- title = line.replace(/^#\s+/, '').trim();
- continue;
- }
-
- const h2 = line.match(/^##\s+(?:\d+\.\s*)?([^:\n]+?)(?::\s*(.+))?$/);
- if (h2) {
- const rawName = normalizeApostrophes(h2[1].trim());
- const subtitle = h2[2] ? h2[2].trim() : null;
- const canonical = matchCanonicalSection(rawName);
- if (canonical) {
- current = { name: canonical, subtitle, lines: [] };
- sections[canonical] = current;
- continue;
- }
- // non-canonical H2 — ignore but stop feeding into current
- current = null;
- continue;
- }
-
- if (current) current.lines.push(raw);
- }
-
- return { title, sections };
-}
-
-function normalizeApostrophes(s) {
- return s.replace(/[\u2018\u2019]/g, "'");
-}
-
-function matchCanonicalSection(name) {
- const normalized = normalizeApostrophes(name).toLowerCase();
- // Exact match first
- for (const c of CANONICAL_SECTIONS) {
- if (normalizeApostrophes(c).toLowerCase() === normalized) return c;
- }
- // Keyword-contained match: "Overview & Creative North Star" -> "Overview",
- // "Elevation & Depth" -> "Elevation", etc.
- for (const c of CANONICAL_SECTIONS) {
- const key = normalizeApostrophes(c).toLowerCase();
- const pattern = new RegExp(`\\b${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
- if (pattern.test(normalized)) return c;
- }
- return null;
-}
-
-// ---------- Subsection splitting (inside a canonical section) ----------
-
-function splitSubsections(lines) {
- const subs = [];
- let current = { name: null, lines: [] };
- subs.push(current);
-
- for (const raw of lines) {
- const h3 = raw.match(/^###\s+(.+?)\s*$/);
- if (h3) {
- current = { name: h3[1].trim(), lines: [] };
- subs.push(current);
- continue;
- }
- current.lines.push(raw);
- }
-
- return subs;
-}
-
-// ---------- Generic helpers ----------
-
-function collectParagraphs(lines) {
- const paragraphs = [];
- let buf = [];
- const flush = () => {
- if (buf.length) {
- paragraphs.push(buf.join(' ').trim());
- buf = [];
- }
- };
- for (const raw of lines) {
- const trimmed = raw.trim();
- if (trimmed === '') { flush(); continue; }
- // Horizontal rules (---, ***) and headings/bullets end a paragraph.
- if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { flush(); continue; }
- if (raw.startsWith('#') || raw.match(/^[-*]\s/)) { flush(); continue; }
- buf.push(trimmed);
- }
- flush();
- return paragraphs.filter(Boolean);
-}
-
-function collectBullets(lines) {
- const bullets = [];
- let current = null;
- for (const raw of lines) {
- const m = raw.match(/^\s*[-*]\s+(.+)$/);
- if (m) {
- if (current) bullets.push(current);
- current = m[1];
- continue;
- }
- // continuation of a bullet (indented line)
- if (current && raw.match(/^\s{2,}\S/)) {
- current += ' ' + raw.trim();
- continue;
- }
- // blank line ends a bullet
- if (raw.trim() === '' && current) {
- bullets.push(current);
- current = null;
- }
- }
- if (current) bullets.push(current);
- return bullets;
-}
-
-function stripBold(s) {
- return s.replace(/\*\*(.+?)\*\*/g, '$1');
-}
-
-function extractNamedRules(lines) {
- const rules = [];
- const seen = new Set();
-
- // Style A (Impeccable): "**The X Rule.** body body body" — can span lines.
- const joined = lines.join('\n');
- const inlineStart = /\*\*(The [^*]+?Rule)\.\*\*/g;
- const inlineMatches = [];
- let m;
- while ((m = inlineStart.exec(joined)) !== null) {
- inlineMatches.push({ name: m[1], start: m.index, end: inlineStart.lastIndex });
- }
- for (let i = 0; i < inlineMatches.length; i++) {
- const mm = inlineMatches[i];
- const bodyEnd = i + 1 < inlineMatches.length ? inlineMatches[i + 1].start : joined.length;
- const body = joined
- .slice(mm.end, bodyEnd)
- .replace(/\n##[^\n]*$/s, '')
- .replace(/\n###[^\n]*$/s, '')
- .trim();
- const name = stripBold(mm.name).trim();
- seen.add(name.toLowerCase());
- rules.push({ name, body: stripBold(body) });
- }
-
- // Style B (Stitch): `### The "X" Rule` or `### The X Fallback`, body is the
- // bullets/paragraphs until the next heading. Accept Rule / Fallback / Principle.
- for (let i = 0; i < lines.length; i++) {
- const h3 = lines[i].match(/^###\s+(.+?)\s*$/);
- if (!h3) continue;
- const headerName = stripBold(h3[1]).replace(/["“”]/g, '').trim();
- if (!/^The\b.*\b(Rule|Fallback|Principle)\b/i.test(headerName)) continue;
- if (seen.has(headerName.toLowerCase())) continue;
-
- const bodyLines = [];
- for (let j = i + 1; j < lines.length; j++) {
- if (/^##\s|^###\s/.test(lines[j])) break;
- bodyLines.push(lines[j]);
- }
- const body = stripBold(bodyLines.join('\n').replace(/\n+/g, ' ')).trim();
- if (body) {
- seen.add(headerName.toLowerCase());
- rules.push({ name: headerName, body });
- }
- }
-
- // Style C (Stitch bullet form): "* **The Layering Principle:** body"
- // Colon/period lives inside the bold, so match "**...**" then inspect.
- for (const b of collectBullets(lines)) {
- const mm = b.match(/^\*\*([^*]+?)\*\*\s*(.+)$/);
- if (!mm) continue;
- const nameRaw = mm[1].replace(/[.:]\s*$/, '').replace(/["“”]/g, '').trim();
- if (!/^The\b.+\b(Rule|Fallback|Principle)$/i.test(nameRaw)) continue;
- if (seen.has(nameRaw.toLowerCase())) continue;
- seen.add(nameRaw.toLowerCase());
- rules.push({ name: nameRaw, body: stripBold(mm[2]).trim() });
- }
-
- return rules;
-}
-
-// ---------- Per-section extractors ----------
-
-function extractOverview(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
- const northStar = text.match(/\*\*Creative North Star:\s*"([^"]+)"\*\*/);
- const keyChars = [];
- const keyCharMatch = text.match(/\*\*Key Characteristics:\*\*\s*\n([\s\S]+?)(?:\n##|\n###|$)/);
- if (keyCharMatch) {
- for (const line of keyCharMatch[1].split('\n')) {
- const m = line.match(/^\s*[-*]\s+(.+)$/);
- if (m) keyChars.push(stripBold(m[1].trim()));
- }
- }
-
- // Philosophy paragraphs: everything that isn't a rule header or key-char block
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) =>
- !p.startsWith('**Creative North Star') &&
- !p.startsWith('**Key Characteristics')
- );
-
- return {
- subtitle: section.subtitle,
- creativeNorthStar: northStar ? northStar[1] : null,
- philosophy: paragraphs,
- keyCharacteristics: keyChars,
- };
-}
-
-function extractColors(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ');
- const groups = [];
- const ROLE_KEYWORDS = /^(primary|secondary|tertiary|neutral|accent)\b/i;
-
- for (const sub of subs.slice(1)) {
- if (!sub.name || /Named Rules?/i.test(sub.name) || /^The\s/i.test(sub.name)) continue;
-
- const bullets = collectBullets(sub.lines);
- const parsed = bullets.map((b) => parseColorBullet(b)).filter(Boolean);
- if (parsed.length === 0) continue;
-
- // If every bullet starts with a role keyword (Primary/Secondary/...), promote
- // each bullet to its own group. Otherwise keep the subsection as the group.
- const allRoleBullets =
- parsed.length > 0 && parsed.every((p) => p.name && ROLE_KEYWORDS.test(p.name));
-
- if (allRoleBullets) {
- for (const p of parsed) {
- groups.push({ role: p.name, colors: [p] });
- }
- } else {
- groups.push({ role: sub.name, colors: parsed });
- }
- }
-
- // If the Colors section has no subsections at all (unlikely), fall back to
- // scanning the whole section as a flat bullet list.
- if (groups.length === 0) {
- const flat = collectBullets(section.lines)
- .map((b) => parseColorBullet(b))
- .filter(Boolean);
- if (flat.length) {
- for (const p of flat) {
- if (p.name && ROLE_KEYWORDS.test(p.name)) {
- groups.push({ role: p.name, colors: [p] });
- } else {
- const fallback = groups.find((g) => g.role === 'Palette');
- if (fallback) fallback.colors.push(p);
- else groups.push({ role: 'Palette', colors: [p] });
- }
- }
- }
- }
-
- return {
- subtitle: section.subtitle,
- description: description || null,
- groups,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function parseColorBullet(bullet) {
- const text = bullet.trim();
-
- // Case 1 (Impeccable): **Name** (value-with-maybe-nested-parens): description
- const bold = text.match(/^\*\*(.+?)\*\*\s*(.*)$/);
- if (bold && bold[2].startsWith('(')) {
- const value = extractParenGroup(bold[2]);
- if (value !== null) {
- const after = bold[2].slice(value.length + 2).trimStart();
- if (after.startsWith(':')) {
- return buildColor(bold[1], value, after.slice(1).trim());
- }
- }
- }
-
- // Case 2 (Stitch): **Name (values):** description — value embedded in bold.
- const stitch = text.match(/^\*\*([^*]+?)\s*\(([^)]+)\):\*\*\s*(.*)$/);
- if (stitch) {
- return buildColor(stitch[1].trim(), stitch[2], stitch[3]);
- }
-
- // Case 3: bullet without bold, just hex/oklch inside.
- const values = collectColorValues(text);
- if (values.length) {
- return buildColor(null, values.join(' to '), text);
- }
- return null;
-}
-
-function extractParenGroup(s) {
- if (s[0] !== '(') return null;
- let depth = 0;
- for (let i = 0; i < s.length; i++) {
- if (s[i] === '(') depth++;
- else if (s[i] === ')') {
- depth--;
- if (depth === 0) return s.slice(1, i);
- }
- }
- return null;
-}
-
-function buildColor(name, rawValue, description) {
- const values = collectColorValues(rawValue);
- const primary = values[0] ?? rawValue.trim();
- return {
- name: name ? stripBold(name).trim() : null,
- value: primary,
- valueRange: values.length > 1 ? values : null,
- format: detectFormat(primary),
- description: stripBold(description || '').trim() || null,
- };
-}
-
-function collectColorValues(s) {
- const out = [];
- s.replace(HEX_RE, (v) => {
- out.push(v);
- return v;
- });
- s.replace(OKLCH_RE, (v) => {
- out.push(v);
- return v;
- });
- return out;
-}
-
-function detectFormat(v) {
- if (!v) return 'unknown';
- if (v.startsWith('#')) return 'hex';
- if (/^oklch/i.test(v)) return 'oklch';
- if (/^rgb/i.test(v)) return 'rgb';
- return 'unknown';
-}
-
-function scanInlineColors(lines) {
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '');
- const color = parseColorBullet(trimmed);
- if (color) out.push(color);
- }
- return out;
-}
-
-function parseStitchInlineGroups(lines) {
- // Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
- // Each bullet IS its own role. Group them under the spoken role name.
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
- const m = trimmed.match(
- /^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
- );
- if (m) {
- const role = m[1];
- const color = buildColor(role, m[2], m[3]);
- out.push({ role, colors: [color] });
- }
- }
- return out;
-}
-
-function extractTypography(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
-
- const fonts = {};
- // Pattern A: **Display Font:** Family (with fallback)
- const fontLineRe = /\*\*([\w\s/]+?)Font:\*\*\s*([^\n(]+?)(?:\s*\(with\s+([^)]+)\))?\s*$/gm;
- let fm;
- while ((fm = fontLineRe.exec(text)) !== null) {
- const rawRole = fm[1].trim().toLowerCase().replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || 'display';
- fonts[role] = {
- family: fm[2].trim(),
- fallback: fm[3] ? fm[3].trim() : null,
- };
- }
-
- // Pattern B (Stitch): * **Display & Headlines (Noto Serif):** description
- if (Object.keys(fonts).length === 0) {
- const stitchRe = /\*\*([\w\s&/]+?)\s*\(([^)]+)\):\*\*\s*(.+)/g;
- let sm;
- while ((sm = stitchRe.exec(text)) !== null) {
- const rawRole = sm[1]
- .trim()
- .toLowerCase()
- .replace(/\s*&\s*/g, '-')
- .replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || rawRole;
- fonts[role] = { family: sm[2].trim(), fallback: null, purpose: sm[3].trim() };
- }
- }
-
- // Character paragraph — either a **Character:** label, or fall back to the
- // first free paragraph under the section header (Stitch style).
- const characterMatch = text.match(/\*\*Character:\*\*\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\n|\n###|\n##|$)/);
- let character = characterMatch ? characterMatch[1].replace(/\n/g, ' ').trim() : null;
- if (!character) {
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) => !/^\*\*[\w\s/&]+Font/i.test(p) && !/^\*\*[\w\s/&]+\([^)]+\)/.test(p)
- );
- if (paragraphs.length) character = paragraphs[0];
- }
-
- // Hierarchy bullets under ### Hierarchy
- const subs = splitSubsections(section.lines);
- let hierarchy = [];
- const hierSub = subs.find((s) => s.name && /hierarch/i.test(s.name));
- if (hierSub) {
- const bullets = collectBullets(hierSub.lines);
- hierarchy = bullets.map(parseTypeBullet).filter(Boolean);
- }
-
- return {
- subtitle: section.subtitle,
- fonts,
- character,
- hierarchy,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function normalizeFontRole(raw) {
- // Canonical roles the panel cares about: display, body, label, mono.
- // Stitch often writes compound roles like "display-&-headlines" or "ui-&-body"
- // — collapse them to the first canonical role present.
- const tokens = raw.split(/[-/&\s]+/).filter(Boolean);
- const priority = ['display', 'headline', 'body', 'ui', 'label', 'mono'];
- const canonical = { headline: 'display', ui: 'body' };
- for (const p of priority) {
- if (tokens.includes(p)) return canonical[p] || p;
- }
- return null;
-}
-
-function parseTypeBullet(bullet) {
- // - **Display** (family, weight 300, italic, clamp(...), line-height 1): purpose
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(([^)]+)\):\s*(.*)$/);
- if (!m) return null;
- const name = m[1].trim();
- const specs = m[2].split(',').map((s) => s.trim());
- return {
- name,
- specs,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractElevation(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ') || null;
-
- const shadows = [];
- const seen = new Set();
- const dedupe = (entry) => {
- const key = (entry.name || '') + '::' + entry.value;
- if (seen.has(key)) return;
- seen.add(key);
- shadows.push(entry);
- };
-
- for (const b of collectBullets(section.lines)) {
- const parsed = parseShadowBullet(b);
- if (parsed) dedupe(parsed);
- }
-
- // Fallback: extract shadows written inline in prose. Stitch style is
- // "...use an extra-diffused shadow: `box-shadow: 0 12px 40px rgba(...)`."
- for (const p of collectParagraphs(section.lines)) {
- for (const inline of extractInlineShadows(p)) dedupe(inline);
- }
- for (const b of collectBullets(section.lines)) {
- for (const inline of extractInlineShadows(b)) dedupe(inline);
- }
-
- return {
- subtitle: section.subtitle,
- description,
- shadows,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function extractInlineShadows(text) {
- // Find `box-shadow: ...` anywhere in prose and capture the value. Work on the
- // raw string so it handles both backtick-fenced and unfenced variants.
- const out = [];
- const re = /box-shadow\s*:\s*([^`;\n]+)/gi;
- let m;
- while ((m = re.exec(text)) !== null) {
- const value = m[1].replace(/[`.)]+$/, '').trim();
- if (!value) continue;
- // Name heuristic: the noun immediately before the shadow phrase.
- // e.g. "an extra-diffused shadow: ..." -> "extra-diffused shadow"
- const before = text.slice(0, m.index);
- const nameMatch = before.match(/\b([A-Za-z][A-Za-z\- ]{2,40})\s+shadow\b[^A-Za-z0-9]*$/i);
- let name = null;
- if (nameMatch) {
- const stripped = nameMatch[1]
- .replace(/^(?:use|using|apply|applying|is|are|looks? like)\s+/i, '')
- .replace(/^(?:a|an|the)\s+/i, '')
- .trim();
- if (stripped) {
- name =
- stripped.charAt(0).toUpperCase() + stripped.slice(1) + ' shadow';
- }
- }
- out.push({
- name,
- value,
- purpose: null,
- });
- }
- return out;
-}
-
-function parseShadowBullet(bullet) {
- // - **Name** (`box-shadow: value`): purpose
- // - **Name** (`value`): purpose
- // Only accept if the paren content looks like a shadow value (contains px,
- // rem, rgba, or box-shadow). This filters out `**Rule Name:**` bullets.
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(`?([^`]+?)`?\):\s*(.*)$/);
- if (!m) return null;
- const rawValue = m[2].replace(/^box-shadow:\s*/i, '').trim();
- const looksLikeShadow =
- /box-shadow|rgba?\(|\bpx\b|\brem\b|^-?\d+\s/i.test(rawValue) &&
- /\d/.test(rawValue);
- if (!looksLikeShadow) return null;
- const name = stripBold(m[1]).trim();
- return {
- name,
- value: rawValue,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractComponents(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const components = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
-
- const bullets = collectBullets(sub.lines);
- const paragraphs = collectParagraphs(sub.lines);
-
- const variants = [];
- const properties = {};
-
- for (const b of bullets) {
- // - **Key:** value
- const m = b.match(/^\*\*(.+?):?\*\*:?\s*(.+)$/);
- if (m) {
- const key = stripBold(m[1]).trim();
- const value = stripBold(m[2]).trim();
- // Heuristic: "Primary", "Secondary", "Hover", "Focus" etc are variants;
- // "Shape", "Background", "Padding" are properties.
- if (/^(primary|secondary|tertiary|ghost|hover|focus|active|disabled|default|error|selected|unselected|state)$/i.test(key.split(/[\s/]/)[0])) {
- variants.push({ name: key, description: value });
- } else {
- properties[key.toLowerCase()] = value;
- }
- }
- }
-
- components.push({
- name: sub.name,
- description: paragraphs.join(' ') || null,
- properties,
- variants,
- });
- }
-
- return {
- subtitle: section.subtitle,
- components,
- };
-}
-
-function extractDosDonts(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const dos = [];
- const donts = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
- const subName = normalizeApostrophes(sub.name);
- const bullets = collectBullets(sub.lines).map((b) => stripBold(b).trim());
- if (/^do'?t?:?$/i.test(subName) || /^do:?$/i.test(subName)) {
- dos.push(...bullets);
- } else if (/^don'?t:?$/i.test(subName)) {
- donts.push(...bullets);
- }
- }
-
- // Classify by bullet prefix as a backup (catches loose bullets outside H3 wrappers)
- for (const b of collectBullets(section.lines)) {
- const stripped = normalizeApostrophes(stripBold(b).trim());
- if (/^don'?t\b/i.test(stripped)) {
- if (!donts.some((d) => normalizeApostrophes(d) === stripped)) donts.push(stripped);
- } else if (/^do\b/i.test(stripped)) {
- if (!dos.some((d) => normalizeApostrophes(d) === stripped)) dos.push(stripped);
- }
- }
-
- return { dos, donts };
-}
-
-// ---------- Coverage assessment ----------
-
-function assessCoverage(model) {
- const report = {};
-
- report.overview = model.overview
- ? {
- northStar: Boolean(model.overview.creativeNorthStar),
- philosophy: model.overview.philosophy.length > 0,
- keyCharacteristics: model.overview.keyCharacteristics.length,
- }
- : 'missing';
-
- report.colors = model.colors
- ? {
- groups: model.colors.groups.length,
- totalColors: model.colors.groups.reduce((n, g) => n + g.colors.length, 0),
- rules: model.colors.rules.length,
- }
- : 'missing';
-
- report.typography = model.typography
- ? {
- fonts: Object.keys(model.typography.fonts).length,
- hierarchyEntries: model.typography.hierarchy.length,
- character: Boolean(model.typography.character),
- rules: model.typography.rules.length,
- }
- : 'missing';
-
- report.elevation = model.elevation
- ? {
- shadows: model.elevation.shadows.length,
- rules: model.elevation.rules.length,
- description: Boolean(model.elevation.description),
- }
- : 'missing';
-
- report.components = model.components
- ? {
- count: model.components.components.length,
- variantTotal: model.components.components.reduce((n, c) => n + c.variants.length, 0),
- }
- : 'missing';
-
- report.dosDonts = model.dosDonts
- ? {
- dos: model.dosDonts.dos.length,
- donts: model.dosDonts.donts.length,
- }
- : 'missing';
-
- return report;
-}
-
-// ---------- Main ----------
-
-export function parseDesignMd(md) {
- const { frontmatter, body } = parseFrontmatter(md);
- const { title, sections } = splitSections(body);
- return {
- schemaVersion: 2,
- title,
- frontmatter,
- overview: extractOverview(sections['Overview']),
- colors: extractColors(sections['Colors']),
- typography: extractTypography(sections['Typography']),
- elevation: extractElevation(sections['Elevation']),
- components: extractComponents(sections['Components']),
- dosDonts: extractDosDonts(sections["Do's and Don'ts"]),
- };
-}
-
-export { assessCoverage };
@@ -1,198 +0,0 @@
-/**
- * Scan a project tree for Content-Security-Policy signals and classify the
- * shape so the agent knows which patch template to propose.
- *
- * Used at first-time `live.mjs` setup. Mechanical (grep-based) — no network,
- * no dev server, no JS evaluation. The classification drives a user-facing
- * consent prompt; the agent does the actual patch writing.
- *
- * Shapes are named by patch mechanism, not framework origin:
- * - "append-arrays": CSP defined as structured directive arrays. Patch
- * appends a dev-only localhost entry. Covers:
- * - Monorepo helpers with additional*Src options
- * (e.g. createBaseNextConfig for Next)
- * - SvelteKit kit.csp.directives
- * - nuxt-security module's contentSecurityPolicy
- * - "append-string": CSP built as a literal value string. Patch splices
- * a dev-only token into script-src and connect-src.
- * Covers:
- * - Inline Next.js headers() with CSP string
- * - Nuxt routeRules / nitro.routeRules CSP headers
- * - "middleware": CSP set dynamically in middleware.{ts,js}.
- * Detected but not auto-patched in v1.
- * - "meta-tag": <meta http-equiv="Content-Security-Policy"> in
- * layout files. Detected but not auto-patched in v1.
- * - null: no CSP signals found; no patch needed.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const SKIP_DIRS = new Set([
- 'node_modules',
- '.git',
- '.next',
- '.turbo',
- '.svelte-kit',
- '.nuxt',
- '.astro',
- 'dist',
- 'build',
- 'out',
- '.vercel',
-]);
-
-const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.tsx', '.jsx']);
-const LAYOUT_EXTS = new Set(['.tsx', '.jsx', '.astro', '.vue', '.svelte', '.html']);
-const MAX_DEPTH = 6;
-const MAX_READ_BYTES = 64 * 1024;
-
-// append-arrays signals: CSP expressed as structured directive arrays
-const MONOREPO_HELPER_SIGNALS = [
- /\bbuildCSPConfig\b/,
- /\bbuildSecurityHeaders\b/,
- /\badditionalScriptSrc\b/,
- /\badditionalConnectSrc\b/,
- /\bcreateBaseNextConfig\b/,
-];
-const SVELTEKIT_CSP_SIGNALS = [
- /\bkit\s*:/,
- /\bcsp\s*:/,
- /\bdirectives\s*:/,
-];
-const NUXT_SECURITY_SIGNALS = [
- /['"]nuxt-security['"]/,
- /\bcontentSecurityPolicy\b/,
-];
-
-// append-string signals: CSP written as a literal value string
-const INLINE_HEADER_SIGNALS = [
- /["']Content-Security-Policy["']/i,
- /\bscript-src\b/,
- /\bconnect-src\b/,
-];
-const NUXT_ROUTE_RULES_SIGNALS = [
- /\brouteRules\b/,
- /Content-Security-Policy/i,
- /\bscript-src\b/,
-];
-
-const MIDDLEWARE_HINT = /headers\.set\(\s*["']Content-Security-Policy["']/i;
-const META_TAG_HINT = /http-equiv\s*=\s*["']Content-Security-Policy["']/i;
-
-/**
- * @param {string} cwd Project root.
- * @returns {{ shape: string|null, signals: string[] }}
- */
-export function detectCsp(cwd = process.cwd()) {
- const hits = { appendArrays: [], appendString: [], middleware: [], metaTag: [] };
-
- walk(cwd, cwd, 0, (absPath, relPath, body) => {
- const ext = path.extname(absPath);
- const base = path.basename(absPath).toLowerCase();
- const isConfig = (name) =>
- new RegExp('(^|/)' + name + '\\.config\\.').test(relPath);
-
- // === append-arrays candidates ===
-
- // Monorepo CSP helper: packages/*/src/.../(config|security)/*
- if (SCAN_EXTS.has(ext) &&
- /packages\/[^/]+\/src\/.*(config|next-config|security)/.test(relPath) &&
- MONOREPO_HELPER_SIGNALS.some((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // SvelteKit kit.csp.directives
- if (SCAN_EXTS.has(ext) && isConfig('svelte') &&
- SVELTEKIT_CSP_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // Nuxt nuxt-security module
- if (SCAN_EXTS.has(ext) && isConfig('nuxt') &&
- NUXT_SECURITY_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // === append-string candidates ===
-
- // Inline headers in Next/Nuxt/SvelteKit/Astro/Vite config
- if (SCAN_EXTS.has(ext) &&
- /(^|\/)(next|nuxt|vite|astro|svelte)\.config\./.test(relPath) &&
- INLINE_HEADER_SIGNALS.every((re) => re.test(body))) {
- // Nuxt routeRules is a sub-shape of append-string; we already covered
- // nuxt-security above via return, so any remaining Nuxt CSP match here
- // is a route-rules / inline-headers case. Either way, same patch
- // mechanism.
- hits.appendString.push(relPath);
- return;
- }
-
- // === detect-only shapes ===
-
- if ((base === 'middleware.ts' || base === 'middleware.js' || base === 'middleware.mjs') &&
- MIDDLEWARE_HINT.test(body)) {
- hits.middleware.push(relPath);
- }
-
- if (LAYOUT_EXTS.has(ext) && META_TAG_HINT.test(body)) {
- hits.metaTag.push(relPath);
- }
- });
-
- // Priority: append-arrays > append-string > middleware > meta-tag.
- // Structured patches are safer than string splices; runtime and HTML
- // injection patches are less reliable and v1 doesn't auto-apply them.
- if (hits.appendArrays.length > 0) {
- return { shape: 'append-arrays', signals: hits.appendArrays };
- }
- if (hits.appendString.length > 0) {
- return { shape: 'append-string', signals: hits.appendString };
- }
- if (hits.middleware.length > 0) {
- return { shape: 'middleware', signals: hits.middleware };
- }
- if (hits.metaTag.length > 0) {
- return { shape: 'meta-tag', signals: hits.metaTag };
- }
- return { shape: null, signals: [] };
-}
-
-function walk(root, dir, depth, visit) {
- if (depth > MAX_DEPTH) return;
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
-
- for (const entry of entries) {
- const abs = path.join(dir, entry.name);
- if (entry.isDirectory()) {
- if (SKIP_DIRS.has(entry.name)) continue;
- walk(root, abs, depth + 1, visit);
- continue;
- }
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name);
- if (!SCAN_EXTS.has(ext) && !LAYOUT_EXTS.has(ext)) continue;
- let body;
- try {
- const fd = fs.openSync(abs, 'r');
- try {
- const buf = Buffer.alloc(MAX_READ_BYTES);
- const n = fs.readSync(fd, buf, 0, MAX_READ_BYTES, 0);
- body = buf.slice(0, n).toString('utf-8');
- } finally { fs.closeSync(fd); }
- } catch { continue; }
- visit(abs, path.relative(root, abs), body);
- }
-}
-
-// CLI mode
-const _running = process.argv[1];
-if (_running?.endsWith('detect-csp.mjs') || _running?.endsWith('detect-csp.mjs/')) {
- const result = detectCsp(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
@@ -1,21 +0,0 @@
-#!/usr/bin/env node
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { pathToFileURL, fileURLToPath } from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const candidates = [
- path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
-];
-const detectorPath = candidates.find(p => fs.existsSync(p));
-
-if (!detectorPath) {
- process.stderr.write('Error: bundled detector not found.\n');
- process.exit(1);
-}
-
-const { detectCli } = await import(pathToFileURL(detectorPath));
-
-await detectCli();
@@ -1,1688 +0,0 @@
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
@@ -1,232 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
-import { detectHtml } from '../engines/static-html/detect-html.mjs';
-import { detectText } from '../engines/regex/detect-text.mjs';
-import {
- HTML_EXTENSIONS,
- buildImportGraph,
- detectFrameworkConfig,
- isPortListening,
- walkDir,
-} from '../node/file-system.mjs';
-
-// ---------------------------------------------------------------------------
-// Output formatting
-// ---------------------------------------------------------------------------
-
-function formatFindings(findings, jsonMode) {
- if (jsonMode) return JSON.stringify(findings, null, 2);
-
- const grouped = {};
- for (const f of findings) {
- if (!grouped[f.file]) grouped[f.file] = [];
- grouped[f.file].push(f);
- }
- const out = [];
- for (const [file, items] of Object.entries(grouped)) {
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
- out.push(`\n${file}${importNote}`);
- for (const item of items) {
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
- out.push(` → ${item.description}`);
- }
- }
- out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
- return out.join('\n');
-}
-
-// ---------------------------------------------------------------------------
-// Stdin handling
-// ---------------------------------------------------------------------------
-
-async function handleStdin() {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- const input = Buffer.concat(chunks).toString('utf-8');
- try {
- const parsed = JSON.parse(input);
- const fp = parsed?.tool_input?.file_path;
- if (fp && fs.existsSync(fp)) {
- return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
- ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
- }
- } catch { /* not JSON */ }
- return detectText(input, '<stdin>');
-}
-
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-async function confirm(question) {
- const rl = (await import('node:readline')).default.createInterface({
- input: process.stdin, output: process.stderr,
- });
- return new Promise((resolve) => {
- rl.question(`${question} [Y/n] `, (answer) => {
- rl.close();
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
- });
- });
-}
-
-function printUsage() {
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
-
-Scan files or URLs for UI anti-patterns and design quality issues.
-
-Options:
- --fast Regex-only mode (skip static HTML/CSS analysis, faster but misses linked stylesheets)
- --json Output results as JSON
- --help Show this help message
-
-Detection modes:
- HTML files Static HTML/CSS analysis (default, catches linked CSS)
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
- URLs Puppeteer full browser rendering (auto-detected)
- --fast Forces regex for all files
-
-Examples:
- impeccable detect src/
- impeccable detect index.html
- impeccable detect https://example.com
- impeccable detect --fast --json .`);
-}
-
-async function detectCli() {
- let args = process.argv.slice(2).map(arg => {
- if (arg === '-json') return '--json';
- if (arg === '-fast') return '--fast';
- return arg;
- });
- if (args[0] === 'detect') args = args.slice(1);
- const jsonMode = args.includes('--json');
- const helpMode = args.includes('--help');
- const fastMode = args.includes('--fast');
- const targets = args.filter(a => !a.startsWith('--'));
-
- if (helpMode) { printUsage(); process.exit(0); }
-
- let allFindings = [];
-
- if (!process.stdin.isTTY && targets.length === 0) {
- allFindings = await handleStdin();
- } else {
- const paths = targets.length > 0 ? targets : [process.cwd()];
- const urlTargetCount = paths.filter(target => /^https?:\/\//i.test(target)).length;
- const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
-
- try {
- for (const target of paths) {
- if (/^https?:\/\//i.test(target)) {
- try {
- const scanner = browserDetector
- ? (url) => browserDetector.detectUrl(url)
- : (url) => detectUrl(url);
- allFindings.push(...await scanner(target));
- } catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
- continue;
- }
-
- const resolved = path.resolve(target);
- let stat;
- try { stat = fs.statSync(resolved); }
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
-
- if (stat.isDirectory()) {
- // Check for framework dev server config (skip in JSON mode to avoid polluting output)
- if (!jsonMode) {
- const fwConfig = detectFrameworkConfig(resolved);
- if (fwConfig) {
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
- if (probe.listening && probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
- `For more accurate results, scan the running site:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- } else if (probe.listening && !probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
- );
- } else {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Start the dev server and scan via URL for best results:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- }
- }
- }
-
- const files = walkDir(resolved);
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
-
- // Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
- if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
- process.stderr.write(
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
- `Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
- `Use --fast to skip static HTML/CSS analysis, or target a specific subdirectory.\n`
- );
- const ok = await confirm('Continue?');
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
- }
-
- // Build import graph for multi-file awareness
- const graph = buildImportGraph(files);
- // Build reverse map: file -> set of files that import it
- const importedByMap = new Map();
- for (const [importer, imports] of graph) {
- for (const imported of imports) {
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
- importedByMap.get(imported).add(importer);
- }
- }
-
- for (const file of files) {
- const ext = path.extname(file).toLowerCase();
- let fileFindings;
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- fileFindings = await detectHtml(file);
- } else {
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
- }
- // Annotate findings with import context
- const importers = importedByMap.get(file);
- if (importers && importers.size > 0) {
- const importerNames = [...importers].map(f => path.basename(f));
- for (const f of fileFindings) {
- f.importedBy = importerNames;
- }
- }
- allFindings.push(...fileFindings);
- }
- } else if (stat.isFile()) {
- const ext = path.extname(resolved).toLowerCase();
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- allFindings.push(...await detectHtml(resolved));
- } else {
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
- }
- }
- }
- } finally {
- if (browserDetector) await browserDetector.close();
- }
- }
-
- if (allFindings.length > 0) {
- if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
- else process.stderr.write(formatFindings(allFindings, false) + '\n');
- process.exit(2);
- }
- if (jsonMode) process.stdout.write('[]\n');
- process.exit(0);
-}
-
-export { formatFindings, handleStdin, confirm, printUsage, detectCli };
@@ -1,4030 +0,0 @@
-/**
- * Anti-Pattern Browser Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * GENERATED -- do not edit. Source: cli/engine/browser/injected/index.mjs
- * Rebuild: node scripts/build-browser-detector.js
- *
- * Usage: <script src="detect-antipatterns-browser.js"></script>
- * Re-scan: window.impeccableScan()
- */
-(function () {
-if (typeof window === 'undefined') return;
-// --- cli/engine/shared/constants.mjs ---
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-// --- cli/engine/registry/antipatterns.mjs ---
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-// --- cli/engine/shared/color.mjs ---
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-// --- cli/engine/rules/checks.mjs ---
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-// --- cli/engine/browser/injected/index.mjs ---
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
-
-})();
@@ -1,43 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Anti-Pattern Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * Public API facade. Runtime engines live under cli/engine/engines/.
- */
-
-import { detectCli } from './cli/main.mjs';
-
-export { ANTIPATTERNS, RULE_ENGINE_SUPPORT, getAntipattern, getRulesForCategory, getRuleEngineSupport } from './registry/antipatterns.mjs';
-export { SAFE_TAGS, BORDER_SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS, KNOWN_SERIF_FONTS } from './shared/constants.mjs';
-export { isNeutralColor, parseRgb, relativeLuminance, contrastRatio, parseGradientColors, hasChroma, getHue, colorToHex } from './shared/color.mjs';
-export { isFullPage } from './shared/page.mjs';
-export {
- checkElementBorders,
- checkElementMotion,
- checkElementGlow,
- checkPageTypography,
- checkPageLayout,
- checkHtmlPatterns,
-} from './rules/checks.mjs';
-export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
-export { detectHtml } from './engines/static-html/detect-html.mjs';
-export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
-export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
-export {
- walkDir,
- SCANNABLE_EXTENSIONS,
- SKIP_DIRS,
- buildImportGraph,
- resolveImport,
- detectFrameworkConfig,
- isPortListening,
- FRAMEWORK_CONFIGS,
-} from './node/file-system.mjs';
-export { formatFindings, detectCli } from './cli/main.mjs';
-
-const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
-if (isMainModule) detectCli();
@@ -1,251 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { finding } from '../../findings.mjs';
-import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
-
-async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
- if (options?.visualContrast === false) return [];
- const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : 12;
- const scrollOffscreen = options?.visualContrastScrollOffscreen !== false;
- const existingLowContrastSelectors = new Set(
- serializedGroups
- .filter(group => group.findings?.some(f => f.type === 'low-contrast'))
- .map(group => group.selector)
- .filter(Boolean)
- );
-
- let browserAnalyses = [];
- const findings = [];
- if (options?.visualContrastBrowser !== false) {
- const browserFindings = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'browser-fallback',
- target,
- }, async () => {
- browserAnalyses = await page.evaluate(async ({ maxCandidates, scrollOffscreen }) => {
- if (typeof window.impeccableAnalyzeVisualContrast !== 'function') return [];
- return window.impeccableAnalyzeVisualContrast({ maxCandidates, scrollOffscreen });
- }, { maxCandidates, scrollOffscreen });
- return browserAnalyses
- .filter(result => result.finding && !existingLowContrastSelectors.has(result.selector))
- .map(result => result.finding);
- });
- findings.push(...browserFindings);
- }
-
- let candidates = browserAnalyses.length > 0 ? browserAnalyses : [];
- if (candidates.length === 0) {
- candidates = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'collect-candidates',
- target,
- }, () => page.evaluate(({ maxCandidates }) => {
- if (typeof window.impeccableCollectVisualContrastCandidates !== 'function') return [];
- return window.impeccableCollectVisualContrastCandidates({ maxCandidates });
- }, { maxCandidates }));
- }
-
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const browserResolvedSelectors = new Set(
- browserAnalyses
- .filter(result => result.status === 'fail' || result.status === 'pass')
- .map(result => result.selector)
- .filter(Boolean)
- );
- const filtered = candidates.filter(candidate =>
- !existingLowContrastSelectors.has(candidate.selector) &&
- !browserResolvedSelectors.has(candidate.selector)
- );
- if (options?.visualContrastPixel === false) return findings;
- for (const candidate of filtered) {
- const result = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'pixel-diff',
- target,
- }, async () => {
- const finding = await captureVisualContrastCandidate(page, candidate, viewport);
- return finding ? [finding] : [];
- });
- findings.push(...result);
- }
- return findings;
-}
-
-// ---------------------------------------------------------------------------
-// Puppeteer detection (for URLs)
-// ---------------------------------------------------------------------------
-
-async function detectUrl(url, options = {}) {
- const profile = options?.profile;
- const waitUntil = options?.waitUntil || 'networkidle0';
- const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const externalBrowser = options?.browser || null;
- let puppeteer;
- if (!externalBrowser) {
- try {
- puppeteer = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'import-puppeteer',
- target: url,
- }, () => import('puppeteer'));
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- }
-
- // Read the browser detection script — reuse it instead of reimplementing
- const browserScriptPath = path.resolve(
- path.dirname(fileURLToPath(import.meta.url)),
- '..',
- '..',
- 'detect-antipatterns-browser.js'
- );
- let browserScript;
- try {
- browserScript = profileStep(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'read-browser-script',
- target: url,
- }, () => fs.readFileSync(browserScriptPath, 'utf-8'));
- } catch {
- throw new Error(`Browser script not found at ${browserScriptPath}`);
- }
-
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
- // running in CI; local users keep the default hardened launch.
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
- const browser = externalBrowser || await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'launch-browser',
- target: url,
- }, () => puppeteer.default.launch({ headless: true, args: launchArgs }));
- const page = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'new-page',
- target: url,
- }, () => browser.newPage());
- let results = [];
- try {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'set-viewport',
- target: url,
- }, () => page.setViewport(viewport));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: `goto:${waitUntil}`,
- target: url,
- }, () => page.goto(url, { waitUntil, timeout: 30000 }));
- if (settleMs > 0) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'settle',
- target: url,
- }, () => new Promise(resolve => setTimeout(resolve, settleMs)));
- }
-
- // Inject the browser detection script and collect results
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'configure-pure-detect',
- target: url,
- }, () => page.evaluate(() => {
- window.__IMPECCABLE_CONFIG__ = {
- ...(window.__IMPECCABLE_CONFIG__ || {}),
- autoScan: false,
- };
- }));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'inject-browser-script',
- target: url,
- }, () => page.evaluate(browserScript));
- let serializedGroups = [];
- results = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'browser-scan',
- target: url,
- }, async () => {
- serializedGroups = await page.evaluate(() => {
- if (!window.impeccableDetect) return [];
- return window.impeccableDetect({ decorate: false, serialize: true });
- });
- return serializedGroups.flatMap(({ findings }) =>
- findings.map(f => ({ id: f.type, snippet: f.detail }))
- );
- });
- const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
- results.push(...visualFindings);
- } finally {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-page',
- target: url,
- }, () => page.close().catch(() => {}));
- if (!externalBrowser) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-browser',
- target: url,
- }, () => browser.close());
- }
- }
- return results.map(f => finding(f.id, url, f.snippet));
-}
-
-async function createBrowserDetector(options = {}) {
- let puppeteer;
- try {
- puppeteer = await import('puppeteer');
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- const launchArgs = options.launchArgs || (process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : []);
- const browser = options.browser || await puppeteer.default.launch({
- headless: options.headless ?? true,
- args: launchArgs,
- });
- const ownsBrowser = !options.browser;
- const defaults = {
- waitUntil: options.waitUntil || 'load',
- settleMs: Number.isFinite(options.settleMs) ? options.settleMs : 100,
- viewport: options.viewport || { width: 1280, height: 800 },
- };
- return {
- browser,
- async detectUrl(url, scanOptions = {}) {
- return detectUrl(url, {
- ...defaults,
- ...scanOptions,
- browser,
- });
- },
- async close() {
- if (ownsBrowser) await browser.close().catch(() => {});
- },
- };
-}
-
-export { runVisualContrastFallback, detectUrl, createBrowserDetector };
@@ -1,420 +0,0 @@
-import { GENERIC_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep } from '../../profile/profiler.mjs';
-
-// ---------------------------------------------------------------------------
-// Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
-// ---------------------------------------------------------------------------
-
-const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
-const hasBorderRadius = (line) => /border-radius/i.test(line);
-const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
-
-function isNeutralBorderColor(str) {
- const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
- if (!m) return false;
- const c = m[1].toLowerCase();
- if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
- const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
- if (hex) {
- const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
- if (shex) {
- const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- return false;
-}
-
-const REGEX_MATCHERS = [
- // --- Side-tab ---
- { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
- test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
- test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
- fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
- { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
- test: (m) => +m[1] >= 3,
- fmt: (m) => m[0] },
- // --- Border accent on rounded ---
- { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
- test: (m, line) => hasRounded(line) && +m[1] >= 1,
- fmt: (m) => m[0] },
- { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
- fmt: (m) => m[0] },
- // --- Overused font ---
- { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
- test: () => true,
- fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
- // --- Pure black background ---
- { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Gradient text ---
- { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
- test: (m, line) => /gradient/i.test(line),
- fmt: () => 'background-clip: text + gradient' },
- // --- Gradient text (Tailwind) ---
- { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
- test: (m, line) => /\bbg-gradient-to-/i.test(line),
- fmt: () => 'bg-clip-text + bg-gradient' },
- // --- Tailwind pure black background ---
- { id: 'pure-black-white', regex: /\bbg-black\b/g,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Tailwind gray on colored bg ---
- { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
- test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
- fmt: (m, line) => { const bg = line.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/); return `${m[0]} on ${bg?.[0] || '?'}`; } },
- // --- Tailwind AI palette ---
- { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
- fmt: (m) => `${m[0]} on heading` },
- { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
- fmt: (m) => `${m[0]} gradient` },
- // --- Bounce/elastic easing ---
- { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
- test: () => true,
- fmt: () => 'animate-bounce (Tailwind)' },
- { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
- test: (m) => {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
- },
- fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
- // --- Layout property transition ---
- { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition: ${found ? found.join(', ') : m[1].trim()}`;
- } },
- { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
- } },
-];
-
-const REGEX_ANALYZERS = [
- // Single font
- (content, filePath) => {
- const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
- const fonts = new Set();
- let m;
- while ((m = fontFamilyRe.exec(content)) !== null) {
- for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
- }
- }
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- while ((m = gfRe.exec(content)) !== null) {
- for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
- }
- if (fonts.size !== 1 || content.split('\n').length < 20) return [];
- const name = [...fonts][0];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
- return [finding('single-font', filePath, `only font used is ${name}`, line)];
- },
- // Flat type hierarchy
- (content, filePath) => {
- const sizes = new Set();
- const REM = 16;
- let m;
- const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
- while ((m = sizeRe.exec(content)) !== null) {
- const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
- if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
- }
- const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
- while ((m = clampRe.exec(content)) !== null) {
- sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
- sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
- }
- const TW = { 'text-xs': 12, 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24, 'text-3xl': 30, 'text-4xl': 36, 'text-5xl': 48, 'text-6xl': 60, 'text-7xl': 72, 'text-8xl': 96, 'text-9xl': 128 };
- for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
- if (sizes.size < 3) return [];
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio >= 2.0) return [];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (/font-size/i.test(lines[i]) || /\btext-(?:xs|sm|base|lg|xl|\d)/i.test(lines[i])) { line = i + 1; break; } }
- return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
- },
- // Monotonous spacing (regex)
- (content, filePath) => {
- const vals = [];
- let m;
- const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
- const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
- const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
- const rounded = vals.map(v => Math.round(v / 4) * 4);
- if (rounded.length < 10) return [];
- const counts = {};
- for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const pct = maxCount / rounded.length;
- const unique = [...new Set(rounded)].filter(v => v > 0);
- if (pct <= 0.6 || unique.length > 3) return [];
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
- },
- // Everything centered (regex)
- (content, filePath) => {
- const lines = content.split('\n');
- let centered = 0, total = 0;
- for (const line of lines) {
- if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
- total++;
- if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
- }
- }
- if (total < 5 || centered / total <= 0.7) return [];
- return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
- },
- // Dark glow (page-level: dark bg + colored box-shadow with blur)
- (content, filePath) => {
- // Check if page has a dark background
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
- if (!hasDarkBg) return [];
-
- // Check for colored box-shadow with blur > 4px
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let m;
- while ((m = shadowRe.exec(content)) !== null) {
- const val = m[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
- // Check blur: look for pattern like "0 0 20px" (third number > 4)
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- const lines = content.substring(0, m.index).split('\n');
- return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
- }
- }
- return [];
- },
-];
-
-// ---------------------------------------------------------------------------
-// Style block extraction (Vue/Svelte <style> blocks)
-// ---------------------------------------------------------------------------
-
-function extractStyleBlocks(content, ext) {
- ext = ext.toLowerCase();
- if (ext !== '.vue' && ext !== '.svelte') return [];
- const blocks = [];
- const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length + 1;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-// ---------------------------------------------------------------------------
-// CSS-in-JS extraction (styled-components, emotion)
-// ---------------------------------------------------------------------------
-
-const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
-
-function extractCSSinJS(content, ext) {
- ext = ext.toLowerCase();
- if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
- const blocks = [];
- const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null, options = {}) {
- const { profile, phase = 'regex-matchers' } = options || {};
- const findings = [];
- if (!profile) {
- for (const matcher of REGEX_MATCHERS) {
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- }
- return findings;
- }
-
- for (const matcher of REGEX_MATCHERS) {
- const matcherFindings = profileFindings(profile, {
- engine: 'regex',
- phase,
- ruleId: matcher.id,
- target: filePath,
- }, () => {
- const matches = [];
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- matches.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- return matches;
- });
- findings.push(...matcherFindings);
- }
- return findings;
-}
-
-function detectText(content, filePath, options = {}) {
- const profile = options?.profile;
- const findings = [];
- const lines = content.split('\n');
- const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
-
- // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
- // Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
- findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
- profile,
- phase: 'source',
- }));
-
- // Extract and scan <style> blocks from Vue/Svelte SFCs
- const styleBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'style-blocks',
- target: filePath,
- }, () => extractStyleBlocks(content, ext))
- : extractStyleBlocks(content, ext);
- for (const block of styleBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'style-block',
- }));
- }
-
- // Extract and scan CSS-in-JS template literals
- const cssJsBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'css-in-js',
- target: filePath,
- }, () => extractCSSinJS(content, ext))
- : extractCSSinJS(content, ext);
- for (const block of cssJsBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'css-in-js',
- }));
- }
-
- // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
- const deduped = [];
- for (const f of findings) {
- const isDupe = deduped.some(d =>
- d.antipattern === f.antipattern &&
- d.snippet === f.snippet &&
- Math.abs(d.line - f.line) <= 2
- );
- if (!isDupe) deduped.push(f);
- }
-
- // Page-level analyzers only run on full pages
- if (isFullPage(content)) {
- const analyzerIds = [
- 'single-font',
- 'flat-type-hierarchy',
- 'monotonous-spacing',
- 'everything-centered',
- 'dark-glow',
- ];
- for (let i = 0; i < REGEX_ANALYZERS.length; i++) {
- const analyzer = REGEX_ANALYZERS[i];
- deduped.push(...profileFindings(profile, {
- engine: 'regex',
- phase: 'page-analyzer',
- ruleId: analyzerIds[i] || `analyzer-${i + 1}`,
- target: filePath,
- }, () => analyzer(content, filePath)));
- }
- }
-
- return deduped;
-}
-
-export {
- REGEX_MATCHERS,
- REGEX_ANALYZERS,
- extractStyleBlocks,
- extractCSSinJS,
- runRegexMatchers,
- detectText,
-};
@@ -1,954 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { profileStep, recordProfileEvent } from '../../profile/profiler.mjs';
-import { parseAnyColor, resolveLengthPx, resolveVarRefs } from '../../rules/checks.mjs';
-
-// ---------------------------------------------------------------------------
-// jsdom CSS-variable border override map
-// ---------------------------------------------------------------------------
-//
-// jsdom's CSSOM silently drops any border shorthand that contains a var()
-// reference — the computed style for the element then shows empty width,
-// empty style, and a default black color. That's enough to hide the most
-// common real-world side-tab pattern in AI-generated pages:
-//
-// :root { --brand: #87a8ff; }
-// .card { border-left: 5px solid var(--brand); border-radius: 4px; }
-//
-// Real browsers (and therefore the browser detector path) resolve var()
-// natively, so this only affects the Node jsdom path.
-//
-// This pre-pass walks the stylesheets, finds any rule whose per-side or
-// all-sides border property contains var(), resolves the var() against
-// :root-level custom properties (read from the documentElement's computed
-// style, which jsdom DOES handle correctly), and attaches the resolved
-// width+color to every element that matches the rule's selector. The
-// Node-side `checkElementBorders` adapter consumes that map as a fallback
-// whenever jsdom's computed style came back empty.
-//
-// Limitations (intentional, to keep the pass simple):
-// * Only :root-level custom properties are resolved. Scoped overrides on
-// descendants are not tracked — uncommon in practice and would require
-// a per-element cascade walk.
-// * @media / @supports wrapped rules are ignored (jsdom often mishandles
-// these anyway).
-// * The fallback only fills sides that jsdom left empty, so any rule
-// whose border parses normally still wins via the computed style.
-
-const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
-
-// isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
-// CSS variables typically hold hex or named colors, so normalize those to
-// rgb() before handing the value off to the shared check. Anything we don't
-// recognise is passed through unchanged — isNeutralColor then treats it as
-// non-neutral, which is the safer default (matches the oklch-era bugfix).
-const NAMED_COLORS = {
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
-};
-
-function normalizeColorForCheck(value) {
- if (!value) return value;
- const v = value.trim();
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
- if (hex6) {
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
- if (hex3) {
- const [r, g, b] = [
- parseInt(hex3[1] + hex3[1], 16),
- parseInt(hex3[2] + hex3[2], 16),
- parseInt(hex3[3] + hex3[3], 16),
- ];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const named = NAMED_COLORS[v.toLowerCase()];
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
- return v;
-}
-
-function buildBorderOverrideMap(document, window) {
- const map = new Map();
- const rootStyle = window.getComputedStyle(document.documentElement);
-
- function resolveVar(value, depth = 0) {
- if (!value || depth > 10 || !value.includes('var(')) return value;
- return value.replace(
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
- (_, name, fallback) => {
- const v = rootStyle.getPropertyValue(name).trim();
- if (v) return resolveVar(v, depth + 1);
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
- return '';
- }
- );
- }
-
- function parseShorthand(text) {
- const m = text.trim().match(BORDER_SHORTHAND_RE);
- if (!m) return null;
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
- }
-
- // Read from the per-property accessors on rule.style. jsdom preserves
- // each border-* shorthand it parsed, even when the overall cssText has
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
- // `border-left: ...` loses the first declaration but keeps the second).
- const SIDE_PROPS = [
- ['borderLeft', 'Left'],
- ['borderRight', 'Right'],
- ['borderTop', 'Top'],
- ['borderBottom', 'Bottom'],
- ['borderInlineStart', 'Left'],
- ['borderInlineEnd', 'Right'],
- ];
-
- for (const sheet of document.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || []; } catch { continue; }
- for (const rule of rules) {
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
-
- const perSide = {};
-
- for (const [prop, side] of SIDE_PROPS) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const parsed = parseShorthand(resolveVar(val));
- if (parsed && parsed.color) perSide[side] = parsed;
- }
-
- // Uniform `border: <w> <style> var(...)` applies to every side the
- // per-side map didn't already claim.
- const borderAll = rule.style.border;
- if (borderAll && borderAll.includes('var(')) {
- const parsed = parseShorthand(resolveVar(borderAll));
- if (parsed && parsed.color) {
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
- if (!perSide[s]) perSide[s] = parsed;
- }
- }
- }
-
- // Longhand `border-*-color: var(...)` with width/style in separate
- // declarations. Rare in AI-generated pages, but cheap to cover.
- for (const [prop, side] of [
- ['borderLeftColor', 'Left'],
- ['borderRightColor', 'Right'],
- ['borderTopColor', 'Top'],
- ['borderBottomColor', 'Bottom'],
- ]) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const resolved = resolveVar(val).trim();
- if (!resolved) continue;
- // Width may or may not come from this rule — that's fine; the
- // adapter only substitutes the color when jsdom left it as a
- // literal var() string.
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
- }
-
- if (Object.keys(perSide).length === 0) continue;
-
- let matched;
- try { matched = document.querySelectorAll(rule.selectorText); }
- catch { continue; }
-
- for (const el of matched) {
- const existing = map.get(el);
- if (existing) {
- // Later rules overwrite earlier ones — approximates source-order
- // cascade for equal-specificity rules and is good enough for the
- // uncontested var()-dropped sides we're trying to recover.
- Object.assign(existing, perSide);
- } else {
- map.set(el, { ...perSide });
- }
- }
- }
- }
-
- return map;
-}
-
-// Strip `@layer NAME { … }` wrappers from a CSS / HTML source, leaving
-// the inner rules as flat CSS. jsdom doesn't implement CSS @layer, so
-// any rule inside a layer block becomes invisible to getComputedStyle.
-// Tailwind v4 makes this ubiquitous: every utility class lives in
-// `@layer utilities`, and Preflight lives in `@layer base`. Without
-// unwrapping, every Tailwind-styled element returns empty computed
-// styles. We walk the source character-by-character, balancing braces
-// so we correctly handle nested style rules inside the layer block.
-function unwrapCssAtLayer(source) {
- if (!source || !source.includes('@layer')) return source;
- // Find `@layer <name>? {` openers. The match starts at the @, and
- // we then balance braces from the opening { onward.
- const re = /@layer\b[^{;]*\{/g;
- let out = '';
- let lastIdx = 0;
- let m;
- while ((m = re.exec(source)) !== null) {
- const openStart = m.index;
- const openEnd = m.index + m[0].length; // position right after `{`
- let depth = 1;
- let i = openEnd;
- while (i < source.length && depth > 0) {
- const c = source.charCodeAt(i);
- if (c === 0x7b /* { */) depth++;
- else if (c === 0x7d /* } */) depth--;
- i++;
- }
- if (depth !== 0) {
- // Unbalanced — bail and return source unchanged.
- return source;
- }
- // Emit everything before the @layer, then the inner contents
- // (between the opening { and the matched closing }), then advance.
- out += source.slice(lastIdx, openStart);
- out += source.slice(openEnd, i - 1); // i-1 = position of the closing }
- lastIdx = i;
- re.lastIndex = i;
- }
- out += source.slice(lastIdx);
- return out;
-}
-
-// ---------------------------------------------------------------------------
-// Static HTML/CSS detection (default for local HTML files)
-// ---------------------------------------------------------------------------
-
-const STATIC_INHERITED_PROPS = new Set([
- 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight',
- 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'hyphens',
- 'webkitHyphens',
-]);
-
-const STATIC_DEFAULT_STYLE = {
- color: 'rgb(0, 0, 0)',
- backgroundColor: 'rgba(0, 0, 0, 0)',
- backgroundImage: 'none',
- borderTopWidth: '0px',
- borderRightWidth: '0px',
- borderBottomWidth: '0px',
- borderLeftWidth: '0px',
- borderTopColor: 'rgb(0, 0, 0)',
- borderRightColor: 'rgb(0, 0, 0)',
- borderBottomColor: 'rgb(0, 0, 0)',
- borderLeftColor: 'rgb(0, 0, 0)',
- borderRadius: '0px',
- boxShadow: 'none',
- fontFamily: '',
- fontSize: '16px',
- fontStyle: 'normal',
- fontWeight: '400',
- lineHeight: 'normal',
- letterSpacing: 'normal',
- textTransform: 'none',
- textAlign: 'start',
- hyphens: 'manual',
- webkitHyphens: 'manual',
- transitionProperty: '',
- transitionTimingFunction: '',
- animationName: '',
- animationTimingFunction: '',
- webkitBackgroundClip: '',
- backgroundClip: '',
- width: '',
- height: '',
- paddingTop: '0px',
- paddingRight: '0px',
- paddingBottom: '0px',
- paddingLeft: '0px',
- position: 'static',
- display: '',
-};
-
-const STATIC_PROP_MAP = {
- 'background-color': 'backgroundColor',
- 'background-image': 'backgroundImage',
- 'background-clip': 'backgroundClip',
- '-webkit-background-clip': 'webkitBackgroundClip',
- 'border-radius': 'borderRadius',
- 'border-top-width': 'borderTopWidth',
- 'border-right-width': 'borderRightWidth',
- 'border-bottom-width': 'borderBottomWidth',
- 'border-left-width': 'borderLeftWidth',
- 'border-top-color': 'borderTopColor',
- 'border-right-color': 'borderRightColor',
- 'border-bottom-color': 'borderBottomColor',
- 'border-left-color': 'borderLeftColor',
- 'box-shadow': 'boxShadow',
- 'font-family': 'fontFamily',
- 'font-size': 'fontSize',
- 'font-style': 'fontStyle',
- 'font-weight': 'fontWeight',
- 'line-height': 'lineHeight',
- 'letter-spacing': 'letterSpacing',
- 'text-transform': 'textTransform',
- 'text-align': 'textAlign',
- 'hyphens': 'hyphens',
- '-webkit-hyphens': 'webkitHyphens',
- 'transition-property': 'transitionProperty',
- 'transition-timing-function': 'transitionTimingFunction',
- 'animation-name': 'animationName',
- 'animation-timing-function': 'animationTimingFunction',
- 'width': 'width',
- 'height': 'height',
- 'padding-top': 'paddingTop',
- 'padding-right': 'paddingRight',
- 'padding-bottom': 'paddingBottom',
- 'padding-left': 'paddingLeft',
- 'position': 'position',
- 'display': 'display',
-};
-
-const STATIC_NAMED_COLORS = {
- black: { r: 0, g: 0, b: 0, a: 1 },
- white: { r: 255, g: 255, b: 255, a: 1 },
- transparent: { r: 0, g: 0, b: 0, a: 0 },
- gray: { r: 128, g: 128, b: 128, a: 1 },
- grey: { r: 128, g: 128, b: 128, a: 1 },
- silver: { r: 192, g: 192, b: 192, a: 1 },
- red: { r: 255, g: 0, b: 0, a: 1 },
- green: { r: 0, g: 128, b: 0, a: 1 },
- blue: { r: 0, g: 0, b: 255, a: 1 },
-};
-
-function splitCssList(value) {
- const parts = [];
- let depth = 0, quote = '', start = 0;
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; continue; }
- if (ch === '(' || ch === '[') depth++;
- else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);
- else if (ch === ',' && depth === 0) {
- parts.push(value.slice(start, i).trim());
- start = i + 1;
- }
- }
- const tail = value.slice(start).trim();
- if (tail) parts.push(tail);
- return parts;
-}
-
-function splitCssTokens(value) {
- const tokens = [];
- let depth = 0, quote = '', current = '';
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- current += ch;
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
- if (ch === '(') { depth++; current += ch; continue; }
- if (ch === ')') { depth = Math.max(0, depth - 1); current += ch; continue; }
- if (/\s/.test(ch) && depth === 0) {
- if (current) { tokens.push(current); current = ''; }
- continue;
- }
- current += ch;
- }
- if (current) tokens.push(current);
- return tokens;
-}
-
-function cssPropToCamel(prop) {
- if (!prop) return prop;
- const mapped = STATIC_PROP_MAP[prop];
- if (mapped) return mapped;
- return prop.replace(/-([a-z])/g, (_m, ch) => ch.toUpperCase());
-}
-
-function staticColorToCss(c) {
- if (!c) return '';
- if (c.a != null && c.a < 1) return `rgba(${c.r}, ${c.g}, ${c.b}, ${Number(c.a.toFixed(3))})`;
- return `rgb(${c.r}, ${c.g}, ${c.b})`;
-}
-
-function parseStaticColor(value) {
- const parsed = parseAnyColor(value);
- if (parsed) return parsed;
- const named = STATIC_NAMED_COLORS[String(value || '').trim().toLowerCase()];
- return named ? { ...named } : null;
-}
-
-function extractStaticColor(value) {
- if (!value) return '';
- const raw = String(value).trim();
- if (/^var\(/i.test(raw)) return raw;
- const colorLike = raw.match(/(?:rgba?\([^)]+\)|oklch\([^)]+\)|oklab\([^)]+\)|lch\([^)]+\)|lab\([^)]+\)|hsla?\([^)]+\)|hwb\([^)]+\)|#[0-9a-f]{3,8}\b|\b(?:black|white|gray|grey|silver|red|green|blue|transparent)\b)/i);
- if (!colorLike) return '';
- return colorLike[0];
-}
-
-function normalizeStaticCssValue(prop, value, customProps, parentStyle, currentStyle = null) {
- let resolved = resolveVarRefs(String(value || '').trim(), customProps);
- if (resolved === 'inherit') return parentStyle?.[prop] || STATIC_DEFAULT_STYLE[prop] || '';
- const isModernBorderColor = /^border[A-Z][a-z]+Color$/.test(prop) && /^(?:oklch|oklab|lch|lab|hsl|hwb)\(/i.test(resolved);
- if (!isModernBorderColor && (/color$/i.test(prop) || prop === 'color' || prop === 'backgroundColor')) {
- const parsed = parseStaticColor(resolved);
- if (parsed) resolved = staticColorToCss(parsed);
- }
- if (prop === 'fontSize') {
- const base = parseFloat(parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'letterSpacing') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'lineHeight' && resolved !== 'normal') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- return resolved;
-}
-
-function expandStaticBoxValues(tokens) {
- if (tokens.length === 0) return ['0px', '0px', '0px', '0px'];
- if (tokens.length === 1) return [tokens[0], tokens[0], tokens[0], tokens[0]];
- if (tokens.length === 2) return [tokens[0], tokens[1], tokens[0], tokens[1]];
- if (tokens.length === 3) return [tokens[0], tokens[1], tokens[2], tokens[1]];
- return [tokens[0], tokens[1], tokens[2], tokens[3]];
-}
-
-function parseStaticBorder(value) {
- const tokens = splitCssTokens(value);
- let width = '', color = '';
- for (const token of tokens) {
- if (!width && /^-?[\d.]+(?:px|rem|em|%)$/.test(token)) width = token;
- if (!color) color = extractStaticColor(token);
- }
- return { width, color };
-}
-
-function parseStaticFont(value) {
- const out = [];
- const slashParts = value.match(/(?:^|\s)([\d.]+(?:px|rem|em|%))(?:\/([^\s]+))?/);
- if (/\bitalic\b/i.test(value)) out.push(['fontStyle', 'italic']);
- const weight = value.match(/\b([1-9]00|bold|normal|lighter|bolder)\b/i);
- if (weight) out.push(['fontWeight', weight[1]]);
- if (slashParts) {
- out.push(['fontSize', slashParts[1]]);
- if (slashParts[2]) out.push(['lineHeight', slashParts[2]]);
- const familyStart = value.indexOf(slashParts[0]) + slashParts[0].length;
- const family = value.slice(familyStart).trim();
- if (family) out.push(['fontFamily', family]);
- }
- return out;
-}
-
-function parseStaticTransition(value) {
- const props = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const prop = tokens.find(token => /^[a-z-]+$/i.test(token) && !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none)$/.test(token) && !/s$/.test(token));
- if (prop) props.push(prop);
- }
- return {
- property: props.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function parseStaticAnimation(value) {
- const names = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const name = tokens.find(token =>
- /^[a-z_-][\w-]*$/i.test(token) &&
- !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none|running|paused)$/.test(token)
- );
- if (name) names.push(name);
- }
- return {
- name: names.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function expandStaticDeclaration(prop, value) {
- const p = prop.toLowerCase();
- const v = String(value || '').trim();
- if (!v) return [];
- if (p.startsWith('--')) return [[p, v]];
- if (p === 'background') {
- const out = [];
- const hasImage = /gradient|url\(/i.test(v);
- if (hasImage) out.push(['backgroundImage', v]);
- const beforeImage = hasImage ? v.split(/(?:repeating-)?(?:linear|radial|conic)-gradient\(|url\(/i)[0] : v;
- const color = extractStaticColor(hasImage ? beforeImage : v);
- if (color) out.push(['backgroundColor', color]);
- return out;
- }
- if (p === 'border') {
- const parsed = parseStaticBorder(v);
- const out = [];
- for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
- if (parsed.width) out.push([`border${side}Width`, parsed.width]);
- if (parsed.color) out.push([`border${side}Color`, parsed.color]);
- }
- return out;
- }
- const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
- if (sideMatch) {
- const parsed = parseStaticBorder(v);
- const side = sideMatch[1][0].toUpperCase() + sideMatch[1].slice(1);
- return [
- ...(parsed.width ? [[`border${side}Width`, parsed.width]] : []),
- ...(parsed.color ? [[`border${side}Color`, parsed.color]] : []),
- ];
- }
- if (p === 'border-width') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopWidth', vals[0]],
- ['borderRightWidth', vals[1]],
- ['borderBottomWidth', vals[2]],
- ['borderLeftWidth', vals[3]],
- ];
- }
- if (p === 'border-color') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopColor', vals[0]],
- ['borderRightColor', vals[1]],
- ['borderBottomColor', vals[2]],
- ['borderLeftColor', vals[3]],
- ];
- }
- if (p === 'padding') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['paddingTop', vals[0]],
- ['paddingRight', vals[1]],
- ['paddingBottom', vals[2]],
- ['paddingLeft', vals[3]],
- ];
- }
- if (p === 'font') return parseStaticFont(v);
- if (p === 'transition') {
- const parsed = parseStaticTransition(v);
- return [
- ...(parsed.property ? [['transitionProperty', parsed.property]] : []),
- ...(parsed.timing ? [['transitionTimingFunction', parsed.timing]] : []),
- ];
- }
- if (p === 'animation') {
- const parsed = parseStaticAnimation(v);
- return [
- ...(parsed.name ? [['animationName', parsed.name]] : []),
- ...(parsed.timing ? [['animationTimingFunction', parsed.timing]] : []),
- ];
- }
- const mapped = cssPropToCamel(p);
- if (STATIC_DEFAULT_STYLE[mapped] != null || STATIC_INHERITED_PROPS.has(mapped)) {
- return [[mapped, v]];
- }
- return [];
-}
-
-function compareStaticPriority(a, b) {
- if (!a) return true;
- if (!!b.important !== !!a.important) return !!b.important;
- if (!!b.inline !== !!a.inline) return !!b.inline;
- for (let i = 0; i < 3; i++) {
- if ((b.specificity[i] || 0) !== (a.specificity[i] || 0)) {
- return (b.specificity[i] || 0) > (a.specificity[i] || 0);
- }
- }
- return b.order >= a.order;
-}
-
-function staticSpecificity(selector) {
- const noWhere = selector.replace(/:where\([^)]*\)/g, '');
- const ids = (noWhere.match(/#[\w-]+/g) || []).length;
- const classes = (noWhere.match(/\.[\w-]+|\[[^\]]+\]|:(?!:)[\w-]+(?:\([^)]*\))?/g) || []).length;
- const stripped = noWhere
- .replace(/#[\w-]+/g, ' ')
- .replace(/\.[\w-]+|\[[^\]]+\]|:{1,2}[\w-]+(?:\([^)]*\))?/g, ' ')
- .replace(/[*>+~(),]/g, ' ');
- const types = (stripped.match(/\b[a-zA-Z][\w-]*\b/g) || []).length;
- return [ids, classes, types];
-}
-
-function applyStaticDeclaration(specified, node, prop, value, meta) {
- let map = specified.get(node);
- if (!map) { map = new Map(); specified.set(node, map); }
- for (const [expandedProp, expandedValue] of expandStaticDeclaration(prop, value)) {
- const existing = map.get(expandedProp);
- const next = { ...meta, prop: expandedProp, value: expandedValue };
- if (compareStaticPriority(existing, next)) map.set(expandedProp, next);
- }
-}
-
-function parseStaticStyleAttribute(styleText, orderBase = 0) {
- const decls = [];
- for (const part of String(styleText || '').split(';')) {
- const idx = part.indexOf(':');
- if (idx <= 0) continue;
- const prop = part.slice(0, idx).trim();
- let value = part.slice(idx + 1).trim();
- const important = /!important\s*$/i.test(value);
- value = value.replace(/\s*!important\s*$/i, '').trim();
- decls.push({ prop, value, important, order: orderBase + decls.length });
- }
- return decls;
-}
-
-function collectStaticCssRules(cssText, csstree) {
- const rules = [];
- let ast;
- try {
- ast = csstree.parse(cssText, { positions: false, parseValue: true, parseCustomProperty: false });
- } catch {
- return rules;
- }
- let order = 0;
- const walkList = (list, atRuleStack = []) => {
- list?.forEach?.(node => {
- if (node.type === 'Rule' && node.block) {
- if (atRuleStack.some(name => /keyframes$/i.test(name))) return;
- const selectorText = csstree.generate(node.prelude).trim();
- const declarations = [];
- node.block.children?.forEach?.(child => {
- if (child.type !== 'Declaration') return;
- declarations.push({
- prop: child.property,
- value: csstree.generate(child.value).trim(),
- important: !!child.important,
- });
- });
- for (const selector of splitCssList(selectorText)) {
- if (selector) rules.push({ selector, declarations, specificity: staticSpecificity(selector), order: order++ });
- }
- return;
- }
- if (node.type === 'Atrule' && node.block) {
- const name = String(node.name || '').toLowerCase();
- if (name === 'media' || name === 'supports' || name === 'layer') {
- walkList(node.block.children, [...atRuleStack, name]);
- }
- }
- });
- };
- walkList(ast.children);
- return rules;
-}
-
-class StaticElement {
- constructor(node, doc) {
- this.node = node;
- this._doc = doc;
- this.nodeType = 1;
- this.tagName = String(node.name || '').toUpperCase();
- this.nodeName = this.tagName;
- }
- get parentElement() {
- let cur = this.node.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- return cur ? this._doc.wrap(cur) : null;
- }
- get previousElementSibling() {
- let cur = this.node.prev;
- while (cur && cur.type !== 'tag') cur = cur.prev;
- return cur ? this._doc.wrap(cur) : null;
- }
- get children() {
- return (this.node.children || []).filter(child => child.type === 'tag').map(child => this._doc.wrap(child));
- }
- get childNodes() {
- return (this.node.children || []).map(child => {
- if (child.type === 'text') return { nodeType: 3, textContent: child.data || '' };
- if (child.type === 'tag') return this._doc.wrap(child);
- return { nodeType: 8, textContent: child.data || '' };
- });
- }
- get textContent() {
- return this._doc.domutils.textContent(this.node);
- }
- get className() {
- return this.getAttribute('class') || '';
- }
- get id() {
- return this.getAttribute('id') || '';
- }
- getAttribute(name) {
- return this.node.attribs?.[name] ?? null;
- }
- querySelector(selector) {
- try {
- const found = this._doc.selectOne(selector, this.node.children || []);
- return found ? this._doc.wrap(found) : null;
- } catch {
- return null;
- }
- }
- querySelectorAll(selector) {
- try {
- return this._doc.selectAll(selector, this.node.children || []).map(node => this._doc.wrap(node));
- } catch {
- return [];
- }
- }
- closest(selector) {
- let cur = this.node;
- while (cur && cur.type === 'tag') {
- try {
- if (this._doc.is(cur, selector)) return this._doc.wrap(cur);
- } catch {
- return null;
- }
- cur = cur.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- }
- return null;
- }
- contains(other) {
- let cur = other?.node || null;
- while (cur) {
- if (cur === this.node) return true;
- cur = cur.parent;
- }
- return false;
- }
-}
-
-class StaticDocument {
- constructor(root, modules) {
- this.root = root;
- this.selectAll = modules.selectAll;
- this.selectOne = modules.selectOne;
- this.is = modules.is;
- this.domutils = modules.domutils;
- this._wrappers = new WeakMap();
- this._styleMap = new WeakMap();
- }
- wrap(node) {
- let wrapped = this._wrappers.get(node);
- if (!wrapped) {
- wrapped = new StaticElement(node, this);
- this._wrappers.set(node, wrapped);
- }
- return wrapped;
- }
- querySelectorAll(selector) {
- try {
- return this.selectAll(selector, this.root.children || []).map(node => this.wrap(node));
- } catch {
- return [];
- }
- }
- querySelector(selector) {
- try {
- const found = this.selectOne(selector, this.root.children || []);
- return found ? this.wrap(found) : null;
- } catch {
- return null;
- }
- }
- get documentElement() {
- return this.querySelector('html');
- }
- get body() {
- return this.querySelector('body');
- }
- setStyle(node, style) {
- this._styleMap.set(node, style);
- }
- getStyle(el) {
- return this._styleMap.get(el.node) || makeStaticStyle();
- }
-}
-
-function makeStaticStyle(values = {}) {
- const style = { ...STATIC_DEFAULT_STYLE, ...values };
- style.getPropertyValue = (prop) => {
- const key = cssPropToCamel(prop);
- return style[key] || style[prop] || '';
- };
- return style;
-}
-
-function buildStaticWindow(staticDoc) {
- return {
- document: staticDoc,
- getComputedStyle: (el) => staticDoc.getStyle(el),
- };
-}
-
-function collectStaticCssText(root, fileDir, profile, filePath, modules) {
- const styleTexts = [];
- for (const styleEl of modules.selectAll('style', root.children || [])) {
- styleTexts.push(modules.domutils.textContent(styleEl));
- }
- const links = modules.selectAll('link', root.children || []);
- for (const link of links) {
- const rel = link.attribs?.rel || '';
- const href = link.attribs?.href || '';
- if (!/\bstylesheet\b/i.test(rel) || !href || /^(https?:)?\/\//i.test(href)) continue;
- const cssPath = path.resolve(fileDir, href);
- try {
- const css = profileStep(profile, {
- engine: 'static-html',
- phase: 'preprocess',
- ruleId: 'inline-linked-stylesheet',
- target: filePath,
- detail: href,
- }, () => fs.readFileSync(cssPath, 'utf-8'));
- styleTexts.push(css);
- } catch { /* skip unreadable */ }
- }
- return styleTexts.join('\n');
-}
-
-function buildStaticStyleMap(root, staticDoc, cssText, modules, profile, filePath) {
- const specified = new Map();
- const allNodes = modules.selectAll('*', root.children || []);
- const rules = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-css',
- ruleId: 'css-rules',
- target: filePath,
- }, () => collectStaticCssRules(cssText, modules.csstree));
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'css-selectors',
- target: filePath,
- }, () => {
- for (const rule of rules) {
- let matched;
- try {
- matched = modules.selectAll(rule.selector, root.children || []);
- } catch {
- recordProfileEvent(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'unsupported-selector',
- target: filePath,
- ms: 0,
- findings: 0,
- detail: rule.selector,
- });
- continue;
- }
- for (const node of matched) {
- for (const decl of rule.declarations) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: rule.specificity,
- order: rule.order,
- inline: false,
- });
- }
- }
- }
-
- let inlineOrder = rules.length + 1;
- for (const node of allNodes) {
- const styleText = node.attribs?.style;
- if (!styleText) continue;
- for (const decl of parseStaticStyleAttribute(styleText, inlineOrder)) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: [1, 0, 0],
- order: decl.order,
- inline: true,
- });
- }
- inlineOrder += 1000;
- }
- });
-
- const computeNode = (node, parentStyle = null, parentCustom = new Map()) => {
- const specifiedMap = specified.get(node) || new Map();
- const customProps = new Map(parentCustom);
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) customProps.set(prop, resolveVarRefs(decl.value, customProps));
- }
- const values = {};
- for (const prop of Object.keys(STATIC_DEFAULT_STYLE)) {
- if (STATIC_INHERITED_PROPS.has(prop) && parentStyle?.[prop] != null) values[prop] = parentStyle[prop];
- else values[prop] = STATIC_DEFAULT_STYLE[prop];
- }
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) continue;
- values[prop] = normalizeStaticCssValue(prop, decl.value, customProps, parentStyle, values);
- }
- const style = makeStaticStyle(values);
- staticDoc.setStyle(node, style);
- for (const child of node.children || []) {
- if (child.type === 'tag') computeNode(child, style, customProps);
- }
- };
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'cascade',
- ruleId: 'compute-styles',
- target: filePath,
- }, () => {
- for (const child of root.children || []) {
- if (child.type === 'tag') computeNode(child);
- }
- });
-}
-
-export {
- BORDER_SHORTHAND_RE,
- NAMED_COLORS,
- normalizeColorForCheck,
- buildBorderOverrideMap,
- unwrapCssAtLayer,
- STATIC_INHERITED_PROPS,
- STATIC_DEFAULT_STYLE,
- STATIC_PROP_MAP,
- STATIC_NAMED_COLORS,
- splitCssList,
- splitCssTokens,
- cssPropToCamel,
- staticColorToCss,
- parseStaticColor,
- extractStaticColor,
- normalizeStaticCssValue,
- expandStaticBoxValues,
- parseStaticBorder,
- parseStaticFont,
- parseStaticTransition,
- parseStaticAnimation,
- expandStaticDeclaration,
- compareStaticPriority,
- staticSpecificity,
- applyStaticDeclaration,
- parseStaticStyleAttribute,
- collectStaticCssRules,
- StaticElement,
- StaticDocument,
- makeStaticStyle,
- buildStaticWindow,
- collectStaticCssText,
- buildStaticStyleMap,
-};
@@ -1,174 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import {
- checkElementBorders,
- checkElementColors,
- checkElementGlow,
- checkElementHeroEyebrow,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementMotion,
- checkElementQuality,
- checkHtmlPatterns,
- checkPageLayout,
- checkPageQualityFromDoc,
- checkRepeatedSectionKickersFromDoc,
- resolveBackground,
- resolveBorderRadiusPx,
-} from '../../rules/checks.mjs';
-import { detectText } from '../regex/detect-text.mjs';
-import {
- StaticDocument,
- buildStaticStyleMap,
- buildStaticWindow,
- collectStaticCssText,
-} from './css-cascade.mjs';
-
-function checkStaticPageTypography(document, window) {
- const findings = [];
- const fonts = new Set();
- const overusedFound = new Set();
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span, div')) {
- const hasText = el.childNodes.some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const ff = window.getComputedStyle(el).fontFamily || '';
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
- if (fonts.size === 1 && document.querySelectorAll('*').length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div')) {
- const fontSize = parseFloat(window.getComputedStyle(el).fontSize);
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
- return findings;
-}
-
-const STATIC_ELEMENT_RULES = [
- { id: 'border-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementBorders(tag, style, null, resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window)) },
- { id: 'color-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementColors(el, style, tag, window, customPropMap, false) },
- { id: 'dark-glow', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window, customPropMap)) },
- { id: 'motion-rules', selector: '*', run: (el, tag, style) => checkElementMotion(tag, style) },
- { id: 'icon-tile-stack', selector: 'h1,h2,h3,h4,h5,h6', run: (el, tag, _style, window) => checkElementIconTile(el, tag, window) },
- { id: 'italic-serif-display', selector: 'h1,h2', run: (el, tag, style) => checkElementItalicSerif(el, style, tag) },
- { id: 'hero-eyebrow-chip', selector: 'h1', run: (el, tag, style, window, customPropMap) => checkElementHeroEyebrow(el, style, tag, window, customPropMap) },
- { id: 'quality-rules', selector: '*', run: (el, tag, style, window) => checkElementQuality(el, style, tag, window) },
-];
-
-async function detectHtml(filePath, options = {}) {
- const profile = options?.profile;
- const html = profileStep(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'read-html',
- target: filePath,
- }, () => fs.readFileSync(filePath, 'utf-8'));
-
- let modules;
- try {
- modules = await profileStepAsync(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'import-static-parser',
- target: filePath,
- }, async () => {
- const [htmlparser2, cssSelect, csstree, domutils] = await Promise.all([
- import('htmlparser2'),
- import('css-select'),
- import('css-tree'),
- import('domutils'),
- ]);
- return {
- parseDocument: htmlparser2.parseDocument,
- selectAll: cssSelect.selectAll,
- selectOne: cssSelect.selectOne,
- is: cssSelect.is,
- csstree,
- domutils,
- };
- });
- } catch {
- return detectText(html, filePath, options);
- }
-
- const resolvedPath = path.resolve(filePath);
- const fileDir = path.dirname(resolvedPath);
- const root = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-html',
- ruleId: 'parse-document',
- target: filePath,
- }, () => modules.parseDocument(html, { lowerCaseAttributeNames: false, lowerCaseTags: true }));
-
- const cssText = collectStaticCssText(root, fileDir, profile, filePath, modules);
- const document = new StaticDocument(root, modules);
- buildStaticStyleMap(root, document, cssText, modules, profile, filePath);
- const window = buildStaticWindow(document);
-
- const customPropMap = null;
-
- const findings = [];
- const runElementCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'element', ruleId, target: filePath }, callback)
- : callback();
-
- const visitedByRule = new Map();
- for (const rule of STATIC_ELEMENT_RULES) {
- const elements = document.querySelectorAll(rule.selector);
- visitedByRule.set(rule.id, elements.length);
- for (const el of elements) {
- const tag = el.tagName.toLowerCase();
- const style = window.getComputedStyle(el);
- for (const f of runElementCheck(rule.id, () => rule.run(el, tag, style, window, customPropMap))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
- }
-
- if (isFullPage(html)) {
- const runPageCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
- : callback();
- for (const f of runPageCheck('typography-rules', () => checkStaticPageTypography(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('repeated-section-kickers', () => checkRepeatedSectionKickersFromDoc(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('layout-rules', () => checkPageLayout(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('skipped-heading', () => checkPageQualityFromDoc(document))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('html-patterns', () => checkHtmlPatterns(html).filter(item =>
- item.id !== 'bounce-easing' && item.id !== 'layout-transition'
- ))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
-
- return findings;
-}
-
-export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -1,189 +0,0 @@
-function sanitizeScreenshotClip(clip, viewport) {
- if (!clip) return null;
- const x = Math.max(0, Math.floor(clip.x || 0));
- const y = Math.max(0, Math.floor(clip.y || 0));
- const width = Math.min(
- Math.max(1, Math.ceil(clip.width || 0)),
- Math.max(1, viewport?.width || 1600),
- );
- const height = Math.min(
- Math.max(1, Math.ceil(clip.height || 0)),
- 320,
- );
- if (width < 1 || height < 1) return null;
- return { x, y, width, height };
-}
-
-async function compareScreenshotContrast(page, beforeBase64, afterBase64, candidate) {
- return page.evaluate(async ({ beforeBase64, afterBase64, candidate }) => {
- const loadImage = (base64) => new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = () => reject(new Error('Could not decode contrast screenshot'));
- img.src = `data:image/png;base64,${base64}`;
- });
- const [before, after] = await Promise.all([loadImage(beforeBase64), loadImage(afterBase64)]);
- const width = Math.min(before.width, after.width);
- const height = Math.min(before.height, after.height);
- if (width < 1 || height < 1) return null;
-
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return null;
-
- ctx.drawImage(before, 0, 0, width, height);
- const beforePixels = ctx.getImageData(0, 0, width, height).data;
- ctx.clearRect(0, 0, width, height);
- ctx.drawImage(after, 0, 0, width, height);
- const afterPixels = ctx.getImageData(0, 0, width, height).data;
-
- const luminance = ({ r, g, b }) => {
- const convert = c => {
- const v = c / 255;
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
- };
- return 0.2126 * convert(r) + 0.7152 * convert(g) + 0.0722 * convert(b);
- };
- const ratio = (a, b) => {
- const l1 = luminance(a);
- const l2 = luminance(b);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
- };
-
- const cssTextColor = candidate.textColor && !candidate.preferRenderedForeground
- ? {
- r: candidate.textColor.r,
- g: candidate.textColor.g,
- b: candidate.textColor.b,
- }
- : null;
- const ratios = [];
- let glyphPixels = 0;
- let strongestDelta = 0;
- for (let i = 0; i < beforePixels.length; i += 4) {
- const delta = Math.abs(beforePixels[i] - afterPixels[i])
- + Math.abs(beforePixels[i + 1] - afterPixels[i + 1])
- + Math.abs(beforePixels[i + 2] - afterPixels[i + 2])
- + Math.abs(beforePixels[i + 3] - afterPixels[i + 3]);
- strongestDelta = Math.max(strongestDelta, delta);
- if (delta < 10) continue;
- glyphPixels++;
- const fg = cssTextColor || {
- r: beforePixels[i],
- g: beforePixels[i + 1],
- b: beforePixels[i + 2],
- };
- const bg = {
- r: afterPixels[i],
- g: afterPixels[i + 1],
- b: afterPixels[i + 2],
- };
- ratios.push(ratio(fg, bg));
- }
-
- if (ratios.length < 8) {
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: null,
- p10Ratio: null,
- medianRatio: null,
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: ratios[0],
- p10Ratio: pick(10),
- medianRatio: pick(50),
- };
- }, { beforeBase64, afterBase64, candidate });
-}
-
-async function captureVisualContrastCandidate(page, candidate, viewport) {
- const clip = sanitizeScreenshotClip(candidate.clip, viewport);
- if (!clip) return null;
-
- const beforeBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- const token = `impeccable-contrast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- const applied = await page.evaluate(({ selector, token, backgroundClipText }) => {
- let el;
- try {
- el = document.querySelector(selector);
- } catch {
- return false;
- }
- if (!el) return false;
- let style = document.getElementById('impeccable-visual-contrast-hide-style');
- if (!style) {
- style = document.createElement('style');
- style.id = 'impeccable-visual-contrast-hide-style';
- style.textContent = [
- '[data-impeccable-visual-contrast-target] {',
- ' color: transparent !important;',
- ' -webkit-text-fill-color: transparent !important;',
- ' text-shadow: none !important;',
- '}',
- '[data-impeccable-visual-contrast-target][data-impeccable-bgclip-text="true"] {',
- ' background-image: none !important;',
- '}',
- ].join('\n');
- document.head.appendChild(style);
- }
- el.setAttribute('data-impeccable-visual-contrast-target', token);
- if (backgroundClipText) el.setAttribute('data-impeccable-bgclip-text', 'true');
- return true;
- }, {
- selector: candidate.selector,
- token,
- backgroundClipText: candidate.backgroundClipText,
- });
- if (!applied) return null;
-
- let afterBase64;
- try {
- afterBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- } finally {
- await page.evaluate(({ selector }) => {
- try {
- const el = document.querySelector(selector);
- if (el) {
- el.removeAttribute('data-impeccable-visual-contrast-target');
- el.removeAttribute('data-impeccable-bgclip-text');
- }
- } catch {
- // Ignore invalid or stale selectors during cleanup.
- }
- }, { selector: candidate.selector }).catch(() => {});
- }
-
- const metrics = await compareScreenshotContrast(page, beforeBase64, afterBase64, candidate);
- if (!metrics || !Number.isFinite(metrics.p10Ratio) || metrics.glyphPixels < 8) return null;
- const measuredRatio = metrics.p10Ratio;
- if (measuredRatio >= candidate.threshold) return null;
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const reasonLabel = (candidate.reasons || []).slice(0, 3).join(', ') || 'visual background';
- return {
- id: 'low-contrast',
- snippet: `pixel contrast ${measuredRatio.toFixed(1)}:1 median ${metrics.medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) on ${reasonLabel}${textLabel}`,
- };
-}
-
-export {
- sanitizeScreenshotClip,
- compareScreenshotContrast,
- captureVisualContrastCandidate,
-};
@@ -1,12 +0,0 @@
-import { getAntipattern } from './registry/antipatterns.mjs';
-
-function getAP(id) {
- return getAntipattern(id);
-}
-
-function finding(id, filePath, snippet, line = 0) {
- const ap = getAP(id);
- return { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', file: filePath, line, snippet };
-}
-
-export { getAP, finding };
@@ -1,198 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-// ---------------------------------------------------------------------------
-// File walker
-// ---------------------------------------------------------------------------
-
-const SKIP_DIRS = new Set([
- 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
- '.svelte-kit', '__pycache__', '.turbo', '.vercel',
-]);
-
-const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
- '.jsx', '.tsx', '.js', '.ts',
- '.vue', '.svelte', '.astro',
-]);
-
-const HTML_EXTENSIONS = new Set(['.html', '.htm']);
-
-function walkDir(dir) {
- const files = [];
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
- for (const entry of entries) {
- if (SKIP_DIRS.has(entry.name)) continue;
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) files.push(...walkDir(full));
- else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
- }
- return files;
-}
-
-
-// ---------------------------------------------------------------------------
-// Import graph (multi-file awareness)
-// ---------------------------------------------------------------------------
-
-function resolveImport(specifier, fromDir, fileSet) {
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
- const base = path.resolve(fromDir, specifier);
- if (fileSet.has(base)) return base;
- for (const ext of SCANNABLE_EXTENSIONS) {
- const withExt = base + ext;
- if (fileSet.has(withExt)) return withExt;
- }
- // index file convention
- for (const ext of SCANNABLE_EXTENSIONS) {
- const indexFile = path.join(base, 'index' + ext);
- if (fileSet.has(indexFile)) return indexFile;
- }
- return null;
-}
-
-function buildImportGraph(files) {
- const fileSet = new Set(files);
- const graph = new Map();
-
- for (const file of files) {
- const content = fs.readFileSync(file, 'utf-8');
- const dir = path.dirname(file);
- const imports = new Set();
-
- // ES imports: import ... from '...' and import '...'
- const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
- let m;
- while ((m = esRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // CSS @import
- const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
- while ((m = cssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // SCSS @use / @forward
- const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
- while ((m = scssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- graph.set(file, imports);
- }
- return graph;
-}
-
-// ---------------------------------------------------------------------------
-// Framework dev server detection
-// ---------------------------------------------------------------------------
-
-const FRAMEWORK_CONFIGS = [
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /next/i } },
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-sveltekit-page', value: null } },
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /@vite\/client/ } },
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /astro/i } },
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
- portRe: /"port"\s*:\s*(\d+)/,
- fingerprint: { body: /ng-version/i } },
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
-];
-
-function detectFrameworkConfig(dir) {
- let entries;
- try { entries = fs.readdirSync(dir); } catch { return null; }
- const entrySet = new Set(entries);
-
- for (const cfg of FRAMEWORK_CONFIGS) {
- const match = cfg.files.find(f => entrySet.has(f));
- if (!match) continue;
-
- const configPath = path.join(dir, match);
- let port = cfg.defaultPort;
- try {
- const content = fs.readFileSync(configPath, 'utf-8');
- const portMatch = content.match(cfg.portRe);
- if (portMatch) port = parseInt(portMatch[1], 10);
- } catch { /* use default */ }
-
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
- }
- return null;
-}
-
-/**
- * Check if a port is listening and optionally verify it matches the expected framework.
- * Returns { listening: true, matched: true/false } or { listening: false }.
- */
-async function isPortListening(port, fingerprint = null) {
- if (!fingerprint) {
- // Simple TCP probe fallback
- const net = await import('node:net');
- return new Promise((resolve) => {
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
- sock.setTimeout(500);
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
- sock.on('error', () => resolve({ listening: false }));
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
- });
- }
-
- // HTTP probe with fingerprint matching
- try {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 2000);
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
- clearTimeout(timeout);
-
- // Check header fingerprint
- if (fingerprint.header) {
- const val = res.headers.get(fingerprint.header);
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
- return { listening: true, matched: true };
- }
- }
-
- // Check body fingerprint
- if (fingerprint.body) {
- const body = await res.text();
- if (fingerprint.body.test(body)) {
- return { listening: true, matched: true };
- }
- }
-
- // Port is listening but doesn't match the expected framework
- return { listening: true, matched: false };
- } catch {
- return { listening: false };
- }
-}
-
-export {
- SKIP_DIRS,
- SCANNABLE_EXTENSIONS,
- HTML_EXTENSIONS,
- walkDir,
- resolveImport,
- buildImportGraph,
- FRAMEWORK_CONFIGS,
- detectFrameworkConfig,
- isPortListening,
-};
@@ -1,166 +0,0 @@
-function profileNow() {
- return typeof performance !== 'undefined' && performance.now
- ? performance.now()
- : Date.now();
-}
-
-function createDetectorProfile() {
- return { events: [] };
-}
-
-function recordProfileEvent(profile, event) {
- if (!profile) return;
- const normalized = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- ms: Number.isFinite(event.ms) ? event.ms : 0,
- findings: Number.isFinite(event.findings) ? event.findings : 0,
- };
- if (event.detail) normalized.detail = event.detail;
- if (Array.isArray(event.findingIds) && event.findingIds.length) {
- normalized.findingIds = event.findingIds;
- }
- if (typeof profile === 'function') {
- profile(normalized);
- } else if (typeof profile.record === 'function') {
- profile.record(normalized);
- } else if (Array.isArray(profile.events)) {
- profile.events.push(normalized);
- } else if (Array.isArray(profile)) {
- profile.push(normalized);
- }
-}
-
-function extractFindingIds(findings) {
- if (!Array.isArray(findings) || findings.length === 0) return [];
- return [...new Set(findings.map(f => f?.id || f?.type || f?.antipattern).filter(Boolean))];
-}
-
-function profileFindings(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-function profileStep(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-async function profileFindingsAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = await callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-async function profileStepAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return await callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-function percentile(sortedValues, pct) {
- if (!sortedValues.length) return 0;
- const idx = Math.min(
- sortedValues.length - 1,
- Math.max(0, Math.ceil((pct / 100) * sortedValues.length) - 1),
- );
- return sortedValues[idx];
-}
-
-function summarizeDetectorProfile(profile) {
- const events = Array.isArray(profile)
- ? profile
- : (Array.isArray(profile?.events) ? profile.events : []);
- const groups = new Map();
- for (const event of events) {
- const key = [
- event.engine || 'unknown',
- event.phase || 'unknown',
- event.ruleId || 'unknown',
- event.target || '',
- ].join('\u0000');
- let group = groups.get(key);
- if (!group) {
- group = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- calls: 0,
- totalMs: 0,
- findings: 0,
- samples: [],
- };
- groups.set(key, group);
- }
- const ms = Number.isFinite(event.ms) ? event.ms : 0;
- group.calls += 1;
- group.totalMs += ms;
- group.findings += Number.isFinite(event.findings) ? event.findings : 0;
- group.samples.push(ms);
- }
- return [...groups.values()]
- .map(group => {
- const samples = group.samples.sort((a, b) => a - b);
- return {
- engine: group.engine,
- phase: group.phase,
- ruleId: group.ruleId,
- target: group.target,
- calls: group.calls,
- totalMs: Number(group.totalMs.toFixed(3)),
- avgMs: Number((group.totalMs / group.calls).toFixed(3)),
- p50: Number(percentile(samples, 50).toFixed(3)),
- p95: Number(percentile(samples, 95).toFixed(3)),
- findings: group.findings,
- };
- })
- .sort((a, b) => b.totalMs - a.totalMs);
-}
-
-export {
- profileNow,
- createDetectorProfile,
- recordProfileEvent,
- extractFindingIds,
- profileFindings,
- profileStep,
- profileFindingsAsync,
- profileStepAsync,
- percentile,
- summarizeDetectorProfile,
-};
@@ -1,278 +0,0 @@
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-const RULE_ENGINE_SUPPORT = {
- regex: new Set(['source', 'page-analyzer']),
- 'static-html': new Set(['element', 'page']),
- browser: new Set(['element', 'page', 'layout']),
- visual: new Set(['visual-contrast']),
-};
-
-function getAntipattern(id) {
- return ANTIPATTERNS.find(rule => rule.id === id);
-}
-
-function getRulesForCategory(category) {
- return ANTIPATTERNS.filter(rule => rule.category === category);
-}
-
-function getRuleEngineSupport(engine) {
- return RULE_ENGINE_SUPPORT[engine] || new Set();
-}
-
-export {
- ANTIPATTERNS,
- RULE_ENGINE_SUPPORT,
- getAntipattern,
- getRulesForCategory,
- getRuleEngineSupport,
-};
@@ -1,1948 +0,0 @@
-import {
- BORDER_SAFE_TAGS,
- GENERIC_FONTS,
- KNOWN_SERIF_FONTS,
- OVERUSED_FONTS,
- SAFE_TAGS,
- WCAG_LARGE_BOLD_TEXT_PX,
- WCAG_LARGE_TEXT_PX,
- isBrandFontOnOwnDomain,
-} from '../shared/constants.mjs';
-import {
- colorToHex,
- contrastRatio,
- getHue,
- hasChroma,
- isNeutralColor,
- parseGradientColors,
- parseRgb,
- relativeLuminance,
-} from '../shared/color.mjs';
-
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-export {
- checkBorders,
- isEmojiOnlyText,
- checkColors,
- isCardLikeFromProps,
- checkIconTile,
- resolveSerif,
- checkItalicSerif,
- isAccentColor,
- checkHeroEyebrow,
- checkRepeatedSectionKickers,
- checkMotion,
- checkGlow,
- checkHtmlPatterns,
- readOwnBackgroundColor,
- resolveBackground,
- resolveGradientStops,
- parseRadiusToPx,
- resolveBorderRadiusPx,
- checkElementBordersDOM,
- checkElementColorsDOM,
- checkElementIconTileDOM,
- checkElementItalicSerifDOM,
- checkElementHeroEyebrowDOM,
- buildCustomPropMap,
- resolveVarRefs,
- oklchToRgb,
- parseAnyColor,
- parseColorResolved,
- cleanInlineText,
- isRepeatedKickerCandidate,
- collectRepeatedSectionKickerCandidates,
- checkRepeatedSectionKickersDOM,
- checkElementMotionDOM,
- checkElementGlowDOM,
- checkElementAIPaletteDOM,
- resolveFontSizePx,
- resolveLengthPx,
- checkQuality,
- checkElementQualityDOM,
- checkPageQualityFromDoc,
- checkPageQualityDOM,
- checkElementQuality,
- checkElementBorders,
- checkElementColors,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementHeroEyebrow,
- checkRepeatedSectionKickersFromDoc,
- checkElementMotion,
- checkElementGlow,
- checkTypography,
- isCardLikeDOM,
- checkLayout,
- checkPageTypography,
- isCardLike,
- checkPageLayout,
-};
@@ -1,124 +0,0 @@
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-export {
- isNeutralColor,
- parseRgb,
- relativeLuminance,
- contrastRatio,
- parseGradientColors,
- hasChroma,
- getHue,
- colorToHex,
-};
@@ -1,101 +0,0 @@
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-export {
- SAFE_TAGS,
- BORDER_SAFE_TAGS,
- OVERUSED_FONTS,
- GOOGLE_DOMAINS,
- VERCEL_DOMAINS,
- GITHUB_DOMAINS,
- BRAND_FONT_DOMAINS,
- isBrandFontOnOwnDomain,
- GENERIC_FONTS,
- WCAG_LARGE_TEXT_PX,
- WCAG_LARGE_BOLD_TEXT_PX,
- KNOWN_SERIF_FONTS,
-};
@@ -1,7 +0,0 @@
-/** Check if content looks like a full page (not a component/partial) */
-function isFullPage(content) {
- const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
- return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
-}
-
-export { isFullPage };
@@ -1,110 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-export const IMPECCABLE_DIR = '.impeccable';
-export const LIVE_DIR = 'live';
-export const CRITIQUE_DIR = 'critique';
-
-export function getImpeccableDir(cwd = process.cwd()) {
- return path.join(cwd, IMPECCABLE_DIR);
-}
-
-export function getDesignSidecarPath(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), 'design.json');
-}
-
-export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {
- const candidates = [
- getDesignSidecarPath(cwd),
- path.join(cwd, 'DESIGN.json'),
- ];
- const contextLegacy = path.join(contextDir, 'DESIGN.json');
- if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
- return candidates;
-}
-
-export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
- return firstExisting(getDesignSidecarCandidates(cwd, contextDir));
-}
-
-export function getLiveDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), LIVE_DIR);
-}
-
-export function getLiveConfigPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'config.json');
-}
-
-export function getLegacyLiveConfigPath(scriptsDir) {
- return path.join(scriptsDir, 'config.json');
-}
-
-export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {
- if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
- const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
- return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
- }
- const primary = getLiveConfigPath(cwd);
- if (fs.existsSync(primary)) return primary;
- if (scriptsDir) {
- const legacy = getLegacyLiveConfigPath(scriptsDir);
- if (fs.existsSync(legacy)) return legacy;
- }
- return primary;
-}
-
-export function getLiveServerPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'server.json');
-}
-
-export function getLegacyLiveServerPath(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live.json');
-}
-
-export function readLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try {
- return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };
- } catch {
- /* try next */
- }
- }
- return null;
-}
-
-export function writeLiveServerInfo(cwd = process.cwd(), info) {
- const filePath = getLiveServerPath(cwd);
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- fs.writeFileSync(filePath, JSON.stringify(info));
- return filePath;
-}
-
-export function removeLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try { fs.unlinkSync(filePath); } catch {}
- }
-}
-
-export function getLiveSessionsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'sessions');
-}
-
-export function getLegacyLiveSessionsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'sessions');
-}
-
-export function getLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'annotations');
-}
-
-export function getCritiqueDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), CRITIQUE_DIR);
-}
-
-export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'annotations');
-}
-
-function firstExisting(paths) {
- return paths.find((filePath) => fs.existsSync(filePath)) || null;
-}
@@ -1,69 +0,0 @@
-/**
- * Decide whether a given file is "generated" (regenerated by a build step,
- * unsafe to write variants into) or "source" (safe to edit, changes persist).
- *
- * Why this matters: when the user picks an element on a page whose underlying
- * file is regenerated by a build step (e.g. `scripts/build-sub-pages.js`
- * rewriting `public/docs/*.html`), writing variants or accepted changes into
- * that file is silent data loss — the next build wipes them.
- *
- * Signals, in order of reliability:
- * 1. Git check-ignore: gitignored files are assumed generated.
- * 2. File-header markers ("GENERATED", "DO NOT EDIT", "AUTO-GENERATED")
- * within the first ~300 characters — catches non-git projects.
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-
-const HEADER_SCAN_BYTES = 300;
-const HEADER_MARKERS = [
- /@generated\b/i,
- /\bGENERATED\s+FILE\b/,
- /\bAUTO-?GENERATED\b/i,
- /\bDO\s+NOT\s+EDIT\b/i,
-];
-
-/**
- * @param {string} filePath - absolute or cwd-relative path
- * @param {object} [options]
- * @param {string} [options.cwd] - project root (defaults to process.cwd())
- */
-export function isGeneratedFile(filePath, options = {}) {
- const cwd = options.cwd || process.cwd();
- const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
-
- if (isGitIgnored(absPath, cwd)) return true;
- if (hasGeneratedHeader(absPath)) return true;
- return false;
-}
-
-function isGitIgnored(absPath, cwd) {
- try {
- execSync(`git check-ignore --quiet ${JSON.stringify(absPath)}`, {
- cwd,
- stdio: 'ignore',
- });
- return true; // exit 0 = ignored
- } catch (err) {
- // Exit code 1 = not ignored. Exit code 128 = not a git repo or other error.
- // In both cases, treat as "not known to be ignored."
- return false;
- }
-}
-
-function hasGeneratedHeader(absPath) {
- let fd;
- try {
- fd = fs.openSync(absPath, 'r');
- const buf = Buffer.alloc(HEADER_SCAN_BYTES);
- const bytesRead = fs.readSync(fd, buf, 0, HEADER_SCAN_BYTES, 0);
- const head = buf.slice(0, bytesRead).toString('utf-8');
- return HEADER_MARKERS.some((re) => re.test(head));
- } catch {
- return false;
- } finally {
- if (fd !== undefined) { try { fs.closeSync(fd); } catch {} }
- }
-}
@@ -1,595 +0,0 @@
-/**
- * CLI helper: deterministic accept/discard of variant sessions.
- *
- * Usage:
- * node live-accept.mjs --id SESSION_ID --discard
- * node live-accept.mjs --id SESSION_ID --variant N
- *
- * For discard: removes the entire variant wrapper and restores the original.
- * For accept: replaces the wrapper with the chosen variant's content. If the
- * session had a colocated <style> block, it's preserved with carbonize markers
- * for a background agent to integrate into the project's CSS.
- *
- * Output: JSON to stdout.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-export async function acceptCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-accept.mjs [options]
-
-Deterministic accept/discard for live variant sessions.
-
-Modes:
- --discard Remove variants, restore original
- --variant N Accept variant N, discard the rest
-
-Required:
- --id SESSION_ID Session ID of the variant wrapper
-
-Output (JSON):
- { handled, file, carbonize }`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const variantNum = argVal(args, '--variant');
- const paramValuesRaw = argVal(args, '--param-values');
- const isDiscard = args.includes('--discard');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }
-
- let paramValues = null;
- if (paramValuesRaw) {
- try { paramValues = JSON.parse(paramValuesRaw); }
- catch { paramValues = null; } // malformed blob: skip the comment rather than failing the accept
- }
-
- // Find the file containing this session's markers
- const found = findSessionFile(id, process.cwd());
- if (!found) {
- console.log(JSON.stringify({ handled: false, error: 'Session markers not found for id: ' + id }));
- process.exit(0);
- }
-
- const { file: targetFile, content, lines } = found;
- const relFile = path.relative(process.cwd(), targetFile);
-
- // Bail if the session lives in a generated file. The agent manually wrote
- // the wrapper there for preview, and is responsible for writing the
- // accepted variant to true source (or cleaning up on discard). See
- // "Handle fallback" in live.md.
- if (isGeneratedFile(targetFile, { cwd: process.cwd() })) {
- console.log(JSON.stringify({
- handled: false,
- mode: 'fallback',
- file: relFile,
- hint: 'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.',
- }));
- process.exit(0);
- }
-
- if (isDiscard) {
- const result = handleDiscard(id, lines, targetFile);
- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));
- } else {
- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);
- // Single-line attention-grabber when cleanup is required. The full
- // five-step checklist lives in reference/live.md (loaded once per
- // session); repeating it per-event would waste tokens.
- if (result.carbonize) {
- result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + relFile + '. See reference/live.md "Required after accept".';
- }
- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));
- }
-}
-
-// ---------------------------------------------------------------------------
-// Discard
-// ---------------------------------------------------------------------------
-
-function handleDiscard(id, lines, targetFile) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const original = extractOriginal(lines, block);
- const isJsx = detectCommentSyntax(targetFile).open === '{/*';
- const replaceRange = expandReplaceRange(block, lines, isJsx);
-
- // Restore at the line we're actually replacing FROM, not the marker line.
- // For JSX wrappers the marker comments live INSIDE the outer `<div>`, so
- // `block.start` sits 2 spaces deeper than the original element. Using that
- // as the deindent base would push the restored content 2 spaces too far
- // right on every JSX/TSX session. `replaceRange.start` is the outer wrapper
- // line, which is at the original element's indent for both HTML and JSX.
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
- const restored = deindentContent(original, indent);
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...restored,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
- return {};
-}
-
-// ---------------------------------------------------------------------------
-// Accept
-// ---------------------------------------------------------------------------
-
-function handleAccept(id, variantNum, lines, targetFile, paramValues) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const commentSyntax = detectCommentSyntax(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- // Anchor indent on the line we're replacing FROM (the outer wrapper),
- // not on `block.start` — for JSX that's the marker comment 2 spaces
- // deeper than the original element. See handleDiscard for the full
- // rationale.
- const replaceRange = expandReplaceRange(block, lines, isJsx);
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
-
- // Extract the chosen variant's inner content
- const variantContent = extractVariant(lines, block, variantNum);
- if (!variantContent) return { handled: false, error: 'Variant ' + variantNum + ' not found' };
-
- // Extract CSS block if present
- const cssContent = extractCss(lines, block, id);
-
- // Check if carbonizing is needed:
- // - CSS block exists, OR
- // - variant HTML contains helper classes/attributes that need cleanup
- const variantText = variantContent.join('\n');
- const hasHelperAttrs = variantText.includes('data-impeccable-variant');
- const needsCarbonize = !!(cssContent || hasHelperAttrs);
-
- // Build the replacement
- const restored = deindentContent(variantContent, indent);
- const replacement = [];
-
- if (cssContent) {
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
- // JSX targets need the CSS body wrapped in a template literal so that the
- // `{` and `}` in CSS rules don't get parsed as JSX expressions.
- replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
- // Re-indent CSS content to match
- for (const cssLine of cssContent) {
- replacement.push(indent + cssLine.trimStart());
- }
- replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
- if (paramValues && Object.keys(paramValues).length > 0) {
- // Preserve the user's knob positions for the carbonize-cleanup agent
- // to bake into the final CSS when it collapses scoped rules.
- replacement.push(indent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close);
- }
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close);
- }
-
- // Keep the `@scope ([data-impeccable-variant="N"])` selectors in the
- // carbonize CSS block working visually by re-wrapping the accepted content
- // in a data-impeccable-variant="N" div with `display: contents` (so layout
- // isn't affected). The carbonize agent strips this attribute + wrapper when
- // it moves the CSS to a proper stylesheet.
- //
- // Style attribute syntax has to follow the host file's flavor — JSX files
- // need the object form, otherwise React 19 throws "Failed to set indexed
- // property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
- if (cssContent) {
- const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
- replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
- replacement.push(...restored);
- replacement.push(indent + '</div>');
- } else {
- replacement.push(...restored);
- }
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...replacement,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- return { carbonize: needsCarbonize };
-}
-
-// ---------------------------------------------------------------------------
-// Parsing helpers
-// ---------------------------------------------------------------------------
-
-/**
- * Find the start/end marker lines for a session.
- * Returns { start, end } (0-indexed line numbers) or null.
- */
-function findMarkerBlock(id, lines) {
- let start = -1;
- let end = -1;
- const startPattern = 'impeccable-variants-start ' + id;
- const endPattern = 'impeccable-variants-end ' + id;
-
- for (let i = 0; i < lines.length; i++) {
- if (start === -1 && lines[i].includes(startPattern)) start = i;
- if (lines[i].includes(endPattern)) { end = i; break; }
- }
-
- return (start !== -1 && end !== -1) ? { start, end } : null;
-}
-
-/**
- * Compute the line range to REPLACE (vs. just the marker range to extract
- * from). For JSX/TSX wrappers, live-wrap places the marker comments INSIDE
- * the `<div data-impeccable-variants="ID">` outer wrapper so the picked
- * element's JSX slot keeps a single child — a Fragment `<></>` would have
- * solved the multi-sibling case but failed inside `asChild` / cloneElement
- * parents with "Invalid prop supplied to React.Fragment".
- *
- * That means the marker block is enclosed by the wrapper `<div>` opener
- * (with `data-impeccable-variants="ID"`) and its matching `</div>`. We
- * walk back to the opener and forward to the closer so accept/discard
- * remove the entire scaffold, not just the inner markers.
- *
- * Marker lines themselves stay where they were so extractOriginal /
- * extractVariant / extractCss continue to walk the same range.
- */
-function expandReplaceRange(block, lines, isJsx) {
- if (!isJsx) return { start: block.start, end: block.end };
-
- let { start, end } = block;
-
- // Walk back for the wrapper `<div data-impeccable-variants="..."` opener.
- // The attr may sit on a continuation line of a multi-line opening tag, so
- // also walk to the line that actually contains `<div`.
- for (let i = start - 1; i >= Math.max(0, start - 12); i--) {
- if (/data-impeccable-variants=/.test(lines[i])) {
- let opener = i;
- while (opener > 0 && !/<div\b/.test(lines[opener])) opener--;
- start = opener;
- break;
- }
- }
-
- // Walk forward to the matching `</div>` by div-depth tracking from the
- // wrapper opener. Operate on JOINED text instead of per-line: a
- // multi-line self-closing JSX `<div\n className="spacer"\n/>` would
- // fool per-line regex tracking (the `<div` line matches openRe but the
- // `/>` line never matches selfCloseRe since it needs `<div` on the same
- // line). That left depth permanently over-counted and the wrapper's
- // outer `</div>` orphaned after accept/discard. Single regex with
- // `[^>]*?` (which spans newlines in JS) handles either form correctly.
- const joined = lines.slice(start).join('\n');
- // Match either `<div … />` (self-close, group 1 is `/`), `<div … >`
- // (open, group 1 is empty), or `</div>`.
- const tagRe = /<div\b[^>]*?(\/?)>|<\/div\s*>/g;
- let depth = 0;
- let m;
- while ((m = tagRe.exec(joined)) !== null) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && m[1] === '/';
- if (isClose) depth--;
- else if (!isSelfClose) depth++;
- if (depth <= 0) {
- // m.index is offset within `joined`; convert back to a file line.
- const linesBefore = joined.slice(0, m.index + m[0].length).split('\n').length - 1;
- const candidateEnd = start + linesBefore;
- if (candidateEnd >= end) {
- end = candidateEnd;
- break;
- }
- }
- }
-
- return { start, end };
-}
-
-/**
- * Join wrapper lines into a single string with `<style>` elements removed so
- * marker matching and div-depth tracking aren't confused by:
- * - CSS `@scope ([data-impeccable-variant="N"])` strings that look like the
- * HTML marker we're searching for
- * - JSX self-closing `<style ... />` (no separate `</style>` to close on)
- * - Same-line `<style>…</style>` blocks
- * - Multi-line `<style>\n…\n</style>` blocks
- */
-function stripStyleAndJoin(lines, block) {
- const out = [];
- let inStyle = false;
- for (let i = block.start; i <= block.end; i++) {
- let line = lines[i];
-
- if (!inStyle) {
- // Strip any complete <style> elements on this line (self-closed or
- // same-line-closed), including their body content.
- line = line
- .replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/g, '')
- .replace(/<style\b[^>]*\/\s*>/g, '');
-
- // If a <style> opener remains (multi-line body starts here), strip from
- // the opener to end-of-line and flip into skip mode.
- const openerIdx = line.search(/<style\b/);
- if (openerIdx !== -1) {
- line = line.slice(0, openerIdx);
- inStyle = true;
- }
- out.push(line);
- } else {
- // In multi-line style body; drop everything until we see </style>.
- const closeIdx = line.search(/<\/style\s*>/);
- if (closeIdx !== -1) {
- inStyle = false;
- out.push(line.slice(closeIdx).replace(/<\/style\s*>/, ''));
- }
- // else: skip line entirely
- }
- }
- return out.join('\n');
-}
-
-/**
- * Find the inner content of `<TAG ...attrMatch...>…</TAG>` inside `text`,
- * handling nested same-tag elements via depth counting. `attrMatch` is a
- * regex source fragment that must appear inside the opener tag.
- * Returns the inner string (may be empty), or null if not found.
- */
-function extractInnerByAttr(text, attrMatch) {
- const openerRe = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*' + attrMatch + '[^>]*>');
- const openMatch = text.match(openerRe);
- if (!openMatch) return null;
-
- const tagName = openMatch[1];
- const innerStart = openMatch.index + openMatch[0].length;
-
- // Match any opener or closer of this tag name after innerStart.
- // (Does not match self-closing <TAG … />, which doesn't contribute to depth.)
- const tagRe = new RegExp('<(?:/)?' + tagName + '\\b[^>]*>', 'g');
- tagRe.lastIndex = innerStart;
-
- let depth = 1;
- let m;
- while ((m = tagRe.exec(text))) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && /\/\s*>$/.test(m[0]);
- if (isClose) {
- depth--;
- if (depth === 0) return text.slice(innerStart, m.index);
- } else if (!isSelfClose) {
- depth++;
- }
- }
- return null;
-}
-
-/**
- * Extract the original element content from within the variant wrapper.
- * Returns an array of lines.
- */
-function extractOriginal(lines, block) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="original"');
- if (inner === null) return [];
- return inner.split('\n');
-}
-
-/**
- * Extract a specific variant's inner content (stripping the wrapper div).
- * Returns an array of lines, or null if not found.
- */
-function extractVariant(lines, block, variantNum) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + variantNum + '"');
- if (inner === null) return null;
- const result = inner.split('\n');
- // Collapse a lone empty leading/trailing line (common after string splice).
- while (result.length > 1 && result[0].trim() === '') result.shift();
- while (result.length > 1 && result[result.length - 1].trim() === '') result.pop();
- return result.length > 0 ? result : null;
-}
-
-/**
- * Extract the colocated <style> block content (between the style tags).
- * Returns an array of CSS lines, or null if no style block found.
- *
- * Handles three shapes of `<style data-impeccable-css="ID" ...>`:
- * 1. Self-closing: `<style ... />` — no body; return null (nothing to carbonize).
- * 2. Same-line open+close: `<style>...</style>` — return the inner content.
- * 3. Multi-line: `<style>` on one line, `</style>` on a later line — return
- * the lines between them.
- */
-function extractCss(lines, block, id) {
- const styleAttr = 'data-impeccable-css="' + id + '"';
- let inStyle = false;
- const content = [];
-
- for (let i = block.start; i <= block.end; i++) {
- const line = lines[i];
-
- if (!inStyle && line.includes(styleAttr)) {
- // Self-closing: nothing to carbonize.
- if (/<style\b[^>]*\/\s*>/.test(line)) return null;
- // Same-line open + close: extract inner text.
- const sameLine = line.match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/);
- if (sameLine) {
- const inner = stripJsxTemplateWrap(sameLine[1]);
- return inner.length > 0 ? inner.split('\n') : null;
- }
- inStyle = true;
- continue; // skip the <style> opening tag
- }
-
- if (inStyle) {
- // Detect </style> anywhere on the line — JSX template-literal closes
- // (`}</style>`) put the close mid-line, and we don't want to absorb the
- // template-literal punctuation as CSS content.
- const closeIdx = line.indexOf('</style>');
- if (closeIdx !== -1) break;
- content.push(line);
- }
- }
-
- if (content.length === 0) return null;
- return stripJsxTemplateLines(content);
-}
-
-/**
- * Strip a JSX template-literal wrap (`{` … `}`) from CSS extracted out of a
- * `<style>` element in a JSX/TSX file. The agent may write the wrap with
- * `{` and `}` directly attached to the `<style>` tags, on their own lines,
- * or attached to the first/last CSS lines — all three are JSX-legal.
- *
- * Stripping is required because handleAccept re-wraps the CSS itself when
- * carbonizing. Without this, two consecutive accepts (or a previously-
- * accepted variants block being carbonized) would produce nested
- * `{` `{` … `}` `}`, which oxc rejects with "Expected `}` but found `@`".
- */
-function stripJsxTemplateLines(content) {
- const out = content.slice();
-
- // Drop any leading blank lines so we don't miss a `{` line buried below
- // them; same for trailing.
- while (out.length > 0 && out[0].trim() === '') out.shift();
- while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
- if (out.length === 0) return null;
-
- // Leading `{`: own line, or attached to the first CSS line.
- const firstTrim = out[0].trimStart();
- if (firstTrim === '{`') {
- out.shift();
- } else if (firstTrim.startsWith('{`')) {
- const idx = out[0].indexOf('{`');
- out[0] = out[0].slice(0, idx) + out[0].slice(idx + 2);
- if (out[0].trim() === '') out.shift();
- }
- if (out.length === 0) return null;
-
- // Trailing `` ` `` `}`: own line, or attached to the last CSS line.
- const lastIdx = out.length - 1;
- const lastTrim = out[lastIdx].trimEnd();
- if (lastTrim === '`}') {
- out.pop();
- } else if (lastTrim.endsWith('`}')) {
- const text = out[lastIdx];
- const idx = text.lastIndexOf('`}');
- out[lastIdx] = text.slice(0, idx) + text.slice(idx + 2);
- if (out[lastIdx].trim() === '') out.pop();
- }
-
- return out.length > 0 ? out : null;
-}
-
-function stripJsxTemplateWrap(text) {
- const lines = text.split('\n');
- const stripped = stripJsxTemplateLines(lines);
- return stripped ? stripped.join('\n') : '';
-}
-
-/**
- * De-indent content that was indented by live-wrap.mjs.
- * The wrap script adds `indent + ' '` (4 extra spaces) to each line.
- * We restore to just `indent` level.
- */
-function deindentContent(contentLines, baseIndent) {
- // Find the minimum indentation in the content to determine how much was added
- let minIndent = Infinity;
- for (const line of contentLines) {
- if (line.trim() === '') continue;
- const leadingSpaces = line.match(/^(\s*)/)[1].length;
- minIndent = Math.min(minIndent, leadingSpaces);
- }
- if (minIndent === Infinity) minIndent = 0;
-
- // Strip the extra indentation and re-add base indent
- return contentLines.map(line => {
- if (line.trim() === '') return '';
- return baseIndent + line.slice(minIndent);
- });
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- return { open: '<!--', close: '-->' };
-}
-
-// ---------------------------------------------------------------------------
-// File search (find the file containing session markers)
-// ---------------------------------------------------------------------------
-
-function findSessionFile(id, cwd) {
- const marker = 'impeccable-variants-start ' + id;
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, marker, seen, 0);
- if (result) {
- const content = fs.readFileSync(result, 'utf-8');
- return { file: result, content, lines: content.split('\n') };
- }
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth) {
- if (depth > 5) return null;
- let realDir;
- try { realDir = fs.realpathSync(dir); } catch { return null; }
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- if (!EXTENSIONS.includes(path.extname(entry.name).toLowerCase())) continue;
- const filePath = path.join(dir, entry.name);
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip */ }
- }
-
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
- if (result) return result;
- }
-
- return null;
-}
-
-// ---------------------------------------------------------------------------
-// Utilities
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-accept.mjs') || _running?.endsWith('live-accept.mjs/')) {
- acceptCli();
-}
-
-export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax };
@@ -1,123 +0,0 @@
-/**
- * Browser-side durable session helpers for Impeccable live mode.
- *
- * Kept separate from live-browser.js so recovery state can be tested without
- * booting the full overlay UI. Served before live-browser.js and attached to
- * window.__IMPECCABLE_LIVE_SESSION__.
- */
-(function (root) {
- 'use strict';
-
- function createLiveBrowserSessionState({ prefix, storage, idFactory }) {
- if (!prefix) throw new Error('prefix required');
- const store = storage || root.localStorage;
- const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };
- const sessionKey = prefix + '-session';
- const handledKey = sessionKey + '-handled';
- const scrollKey = sessionKey + '-scroll';
- let checkpointRevision = 0;
- const owner = makeId();
-
- function safeRead(key) {
- try { return store.getItem(key); } catch { return null; }
- }
-
- function safeWrite(key, value) {
- try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }
- }
-
- function safeRemove(key) {
- try { store.removeItem(key); } catch { /* unavailable storage */ }
- }
-
- function loadSession() {
- try {
- const raw = safeRead(sessionKey);
- if (!raw) return null;
- const parsed = JSON.parse(raw);
- if (Number.isInteger(parsed.checkpointRevision)) {
- checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);
- }
- return parsed;
- } catch { return null; }
- }
-
- function saveSession(session) {
- if (!session || !session.id) return;
- const payload = {
- ...session,
- checkpointRevision,
- };
- safeWrite(sessionKey, JSON.stringify(payload));
- }
-
- function clearSession() {
- safeRemove(sessionKey);
- }
-
- function nextCheckpointRevision() {
- checkpointRevision += 1;
- const existing = loadSession();
- if (existing?.id) saveSession(existing);
- return checkpointRevision;
- }
-
- function seedCheckpointRevision(value) {
- if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);
- return checkpointRevision;
- }
-
- function currentCheckpointRevision() {
- return checkpointRevision;
- }
-
- function markHandled(id) {
- if (!id) return;
- safeWrite(handledKey, id);
- }
-
- function isHandled(id) {
- return !!id && safeRead(handledKey) === id;
- }
-
- function clearHandled() {
- safeRemove(handledKey);
- }
-
- function writeScrollY(y) {
- safeWrite(scrollKey, String(y));
- }
-
- function readScrollY() {
- const raw = safeRead(scrollKey);
- if (raw == null) return null;
- const n = parseFloat(raw);
- return isFinite(n) ? n : null;
- }
-
- function clearScrollY() {
- safeRemove(scrollKey);
- }
-
- return {
- owner,
- sessionKey,
- handledKey,
- scrollKey,
- saveSession,
- loadSession,
- clearSession,
- nextCheckpointRevision,
- seedCheckpointRevision,
- currentCheckpointRevision,
- markHandled,
- isHandled,
- clearHandled,
- writeScrollY,
- readScrollY,
- clearScrollY,
- };
- }
-
- root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };
-})(typeof window !== 'undefined' ? window : globalThis);
@@ -1,4860 +0,0 @@
-/**
- * Impeccable Live Variant Mode — Browser Script
- *
- * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
- * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
- * before this code.
- *
- * UI: a single floating bar that morphs between three states —
- * configure (pick action + go), generating (progressive dots), and cycling
- * (prev/next + accept/discard). Feels like Spotlight, not a modal.
- */
-(function () {
- 'use strict';
- if (typeof window === 'undefined') return;
-
- // Guard against double-init. Bun's HTML loader may process the <script> tag
- // and create a bundled copy alongside the external load, or HMR may re-execute.
- // Check BEFORE reading token/port to catch all cases.
- if (window.__IMPECCABLE_LIVE_INIT__) return;
- window.__IMPECCABLE_LIVE_INIT__ = true;
-
- const TOKEN = window.__IMPECCABLE_TOKEN__;
- const PORT = window.__IMPECCABLE_PORT__;
- if (!TOKEN || !PORT) {
- window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
- return;
- }
-
- // ---------------------------------------------------------------------------
- // Design tokens
- // ---------------------------------------------------------------------------
-
- // Brand magenta is pinned to the site token (--color-accent in main.css)
- // so Accept / knobs / cycle-dots match the site's accent, not a washed
- // theme-adjusted one.
- const C = {
- brand: 'oklch(60% 0.25 350)',
- brandHov: 'oklch(52% 0.25 350)',
- brandSoft: 'oklch(60% 0.25 350 / 0.15)',
- ink: 'oklch(15% 0.01 350)',
- ash: 'oklch(55% 0 0)',
- paper: 'oklch(98% 0.005 350 / 0.92)',
- paperSolid:'oklch(98% 0.005 350)',
- mist: 'oklch(90% 0.01 350 / 0.6)',
- white: 'oklch(99% 0 0)',
- };
- const FONT = 'system-ui, -apple-system, sans-serif';
- const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
- // z-index: detect overlays use 99999, so our UI must be above them
- const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };
- const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
- const PREFIX = 'impeccable-live';
- const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
- prefix: PREFIX,
- storage: localStorage,
- idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),
- });
- if (!sessionState) {
- console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');
- window.__IMPECCABLE_LIVE_INIT__ = false;
- return;
- }
- const HIGHLIGHT_TRANSITION =
- 'top 140ms ' + EASE +
- ', left 140ms ' + EASE +
- ', width 140ms ' + EASE +
- ', height 140ms ' + EASE +
- ', opacity 150ms ease';
- const TOOLTIP_TRANSITION =
- 'top 140ms ' + EASE + ', left 140ms ' + EASE + ', opacity 150ms ease';
-
- const SKIP_TAGS = new Set([
- 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
- ]);
-
- // SVG icons stack above each chip label. All strokes use currentColor so the
- // icon recolors to C.brand when its chip is selected. 20x20 render, 24-viewBox,
- // 1.5 stroke — visually consistent with the Foundation grid on the homepage.
- const ICON_ATTRS = 'width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block"';
- const ICONS = {
- impeccable: `<svg ${ICON_ATTRS}><path d="M4 20l4-1L18 9l-3-3L5 16z"/><path d="M14 7l3 3"/></svg>`,
- bolder: `<svg ${ICON_ATTRS}><rect x="6" y="12" width="4" height="7" rx="0.5"/><rect x="14" y="5" width="4" height="14" rx="0.5"/></svg>`,
- quieter: `<svg ${ICON_ATTRS}><rect x="6" y="5" width="4" height="14" rx="0.5"/><rect x="14" y="12" width="4" height="7" rx="0.5"/></svg>`,
- distill: `<svg ${ICON_ATTRS}><path d="M4 5h16l-6 8v7l-4-2v-5z"/></svg>`,
- polish: `<svg ${ICON_ATTRS}><path d="M15 3l1 3 3 1-3 1-1 3-1-3-3-1 3-1z"/><path d="M7 13l0.6 1.8 1.8 0.6-1.8 0.6-0.6 1.8-0.6-1.8-1.8-0.6 1.8-0.6z"/></svg>`,
- typeset: `<svg ${ICON_ATTRS}><path d="M5 6h14" stroke-width="2.6"/><path d="M5 12h9" stroke-width="1.9"/><path d="M5 18h5" stroke-width="1.3"/></svg>`,
- colorize: `<svg ${ICON_ATTRS}><circle cx="9" cy="10" r="5"/><circle cx="15" cy="10" r="5"/><circle cx="12" cy="15" r="5"/></svg>`,
- layout: `<svg ${ICON_ATTRS}><rect x="3" y="4" width="8" height="16" rx="0.5"/><rect x="13" y="4" width="8" height="7" rx="0.5"/><rect x="13" y="13" width="8" height="7" rx="0.5"/></svg>`,
- adapt: `<svg ${ICON_ATTRS}><rect x="2.5" y="5" width="12" height="11" rx="1"/><line x1="2.5" y1="19" x2="14.5" y2="19"/><rect x="16.5" y="8" width="5" height="11" rx="1"/></svg>`,
- animate: `<svg ${ICON_ATTRS}><path d="M3 18c4-4 6-10 10-10"/><path d="M13 8c3 0 5 5 8 10"/><circle cx="13" cy="8" r="1.6" fill="currentColor" stroke="none"/></svg>`,
- delight: `<svg ${ICON_ATTRS}><path d="M12 3l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>`,
- overdrive: `<svg ${ICON_ATTRS}><path d="M13 3L5 13h5l-1 8 9-12h-6z"/></svg>`,
- };
-
- const ACTIONS = [
- { value: 'impeccable', label: 'Freeform' },
- { value: 'bolder', label: 'Bolder' },
- { value: 'quieter', label: 'Quieter' },
- { value: 'distill', label: 'Distill' },
- { value: 'polish', label: 'Polish' },
- { value: 'typeset', label: 'Typeset' },
- { value: 'colorize', label: 'Colorize' },
- { value: 'layout', label: 'Layout' },
- { value: 'adapt', label: 'Adapt' },
- { value: 'animate', label: 'Animate' },
- { value: 'delight', label: 'Delight' },
- { value: 'overdrive', label: 'Overdrive' },
- ];
-
- // ---------------------------------------------------------------------------
- // State
- // ---------------------------------------------------------------------------
-
- let state = 'IDLE';
- let hoveredElement = null;
- let selectedElement = null;
- let currentSessionId = null;
- let expectedVariants = 0;
- let arrivedVariants = 0;
- let visibleVariant = 0;
- let variantObserver = null;
- let hasProjectContext = false;
- let selectedAction = 'impeccable';
- let selectedCount = 3;
- const browserOwner = sessionState.owner;
- let checkpointTimer = null;
-
- // Scroll lock — holds window.scrollY at a fixed value while the session is
- // active, so HMR DOM patches and variant swaps can't drift the page. See
- // startScrollLock / stopScrollLock below.
- let scrollLockObserver = null;
- let scrollLockTargetY = null;
- let scrollLockRaf = null;
- let scrollLockAbort = null;
-
- // Dedicated key for scroll position — SEPARATE from LS_KEY so that
- // saveSession's state updates don't clobber a carefully-captured scrollY.
- // (Previously: saveSession wrote scrollY alongside state, so every call
- // during resume overwrote the pre-reload value with whatever the browser
- // had landed on, typically 0.)
- function writeScrollY(y) { sessionState.writeScrollY(y); }
- function readScrollY() { return sessionState.readScrollY(); }
- function clearScrollY() { sessionState.clearScrollY(); }
-
- // Pre-empt the browser: apply manual scroll restoration and jump to the
- // saved scrollY at script-parse time. Retries on fonts.ready and load
- // are essential: scrollTo(y) clamps to the current document.scrollHeight,
- // which is often hundreds of pixels short of the final value until
- // async-loaded fonts swap in and reflow.
- try {
- history.scrollRestoration = 'manual';
- const savedY = readScrollY();
- if (savedY != null) {
- const apply = () => {
- if (Math.abs(window.scrollY - savedY) > 0.5) {
- console.log('[impeccable.scroll] early restore', { from: window.scrollY, to: savedY });
- window.scrollTo(0, savedY);
- }
- };
- apply();
- if (document.fonts?.ready) document.fonts.ready.then(apply).catch(() => {});
- window.addEventListener('load', apply, { once: true });
- }
- } catch {}
-
- // UI refs
- let highlightEl = null;
- let tooltipEl = null;
- let barEl = null;
- let pickerEl = null;
- let toastEl = null;
- let scrollRaf = null;
-
- // ---------------------------------------------------------------------------
- // Helpers
- // ---------------------------------------------------------------------------
-
- function own(el) {
- return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
- }
-
- function pickable(el) {
- if (!el || el.nodeType !== 1) return false;
- if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
- if (own(el)) return false;
- const r = el.getBoundingClientRect();
- return r.width >= 20 && r.height >= 20;
- }
-
- function desc(el) {
- if (!el) return '';
- let s = el.tagName.toLowerCase();
- if (el.id) s += '#' + el.id;
- else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
- return s;
- }
-
- function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
-
- // Modal-aware chrome: keep our floating UI clickable inside Radix /
- // Headless UI / vaul portals.
- //
- // Two host-page behaviors break us when the picked element lives inside a
- // modal dialog:
- //
- // 1. Modal scroll-lock disables outside pointer events. Radix's
- // `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
- // while a modal is open and only restores `auto` on the layer. Our
- // chrome inherits `none` from <body> and becomes unclickable.
- // 2. The dialog's outside-interaction handler (Radix's
- // `usePointerDownOutside`) listens at document level and dismisses
- // the dialog whenever a `pointerdown` lands outside the layer node.
- // Our chrome is a sibling of <body>, so Radix classifies our clicks
- // as outside and tears the dialog down mid-task.
- //
- // We can't reliably re-parent our chrome into the dialog subtree (z-index
- // stacking, scroll containers, theming all become host-page concerns), so
- // we defang both behaviors at our root:
- //
- // - `pointer-events: auto !important` overrides the inherited `none`.
- // - Stop `pointerdown` / `mousedown` propagation so the document-level
- // dismiss listener never fires for our clicks.
- // - Stop `focusin` propagation so any focus shifts inside our chrome
- // don't read as "focus moved outside the dialog" to focus traps.
- //
- // Click events still bubble normally — only the early pointer/focus
- // signals that drive outside-interaction detection are silenced.
- function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
- if (!rootEl) return;
- if (setPointerEvents) {
- rootEl.style.setProperty('pointer-events', 'auto', 'important');
- }
- const stop = (e) => e.stopPropagation();
- rootEl.addEventListener('pointerdown', stop);
- rootEl.addEventListener('mousedown', stop);
- rootEl.addEventListener('focusin', stop);
- }
-
- // ---------------------------------------------------------------------------
- // Highlight overlay
- // ---------------------------------------------------------------------------
-
- function initHighlight() {
- highlightEl = document.createElement('div');
- highlightEl.id = PREFIX + '-highlight';
- Object.assign(highlightEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- border: '2px solid ' + C.brand, borderRadius: '3px',
- pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
- transition: HIGHLIGHT_TRANSITION,
- display: 'none', opacity: '0',
- });
- document.body.appendChild(highlightEl);
-
- tooltipEl = document.createElement('div');
- tooltipEl.id = PREFIX + '-tooltip';
- Object.assign(tooltipEl.style, {
- position: 'fixed',
- background: C.ink, color: C.white,
- fontFamily: MONO, fontSize: '10px', fontWeight: '500',
- padding: '2px 6px', borderRadius: '3px',
- zIndex: Z.highlight + 1, pointerEvents: 'none',
- whiteSpace: 'nowrap', display: 'none',
- letterSpacing: '0.02em',
- transition: TOOLTIP_TRANSITION,
- });
- document.body.appendChild(tooltipEl);
- }
-
- function showHighlight(el) {
- if (!el || !highlightEl) return;
- const r = el.getBoundingClientRect();
- const top = (r.top - 2) + 'px', left = (r.left - 2) + 'px';
- const width = (r.width + 4) + 'px', height = (r.height + 4) + 'px';
- const tipTop = r.top - 20;
- const tipY = (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px';
- const tipX = Math.max(4, r.left) + 'px';
- tooltipEl.textContent = desc(el);
-
- const hiWasHidden = highlightEl.style.display === 'none' || highlightEl.style.opacity === '0';
- if (hiWasHidden) {
- // Snap to first target without animating from (0,0), then fade in.
- highlightEl.style.transition = 'none';
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block' });
- tooltipEl.style.transition = 'none';
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block' });
- void highlightEl.offsetWidth;
- highlightEl.style.transition = HIGHLIGHT_TRANSITION;
- highlightEl.style.opacity = '1';
- tooltipEl.style.transition = TOOLTIP_TRANSITION;
- tooltipEl.style.opacity = '1';
- } else {
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block', opacity: '1' });
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block', opacity: '1' });
- }
- }
-
- function hideHighlight() {
- if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
- if (tooltipEl) { tooltipEl.style.opacity = '0'; tooltipEl.style.display = 'none'; }
- }
-
- // ---------------------------------------------------------------------------
- // Annotation overlay (comment pins + magenta strokes)
- //
- // Active while state === 'CONFIGURING'. The overlay is a fixed-positioned
- // sibling of <body> mirroring selectedElement's bounding rect. Click (no
- // drag) drops a comment pin; drag paints a magenta SVG stroke. All coords
- // are stored in element-local CSS px so they survive scroll / resize and
- // correlate directly with the captured PNG.
- // ---------------------------------------------------------------------------
-
- const DRAG_THRESHOLD = 5; // px — below this, treat pointerup as a click
- const PIN_DBL_CLICK_MS = 300; // two clicks on the same pin within this delete it
- let annotOverlayEl = null;
- let annotSvgEl = null;
- let annotPinsEl = null;
- let annotClearChipEl = null;
- let annotState = { comments: [], strokes: [] };
- let annotActive = false;
- // `annotPointer` is either:
- // { kind: 'new', x0, y0, moved, strokeEl, strokePoints } creating a stroke/pin
- // { kind: 'pin', idx, startPointer, startPin, moved } dragging an existing pin
- let annotPointer = null;
- let annotEditing = null; // { idx, input, wrapEl }
- let annotLastPinClick = { idx: -1, time: 0 }; // for click-click-to-delete
-
- function initAnnotOverlay() {
- annotOverlayEl = document.createElement('div');
- annotOverlayEl.id = PREFIX + '-annot';
- Object.assign(annotOverlayEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- pointerEvents: 'auto', zIndex: Z.highlight + 2,
- display: 'none', overflow: 'visible',
- cursor: 'crosshair', touchAction: 'none',
- });
-
- annotSvgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- annotSvgEl.id = PREFIX + '-annot-svg';
- Object.assign(annotSvgEl.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%',
- // The SVG itself doesn't absorb clicks; individual hit-paths opt-in via
- // pointer-events=stroke so gaps still fall through to the overlay.
- pointerEvents: 'none', overflow: 'visible',
- });
- annotOverlayEl.appendChild(annotSvgEl);
-
- annotPinsEl = document.createElement('div');
- annotPinsEl.id = PREFIX + '-annot-pins';
- Object.assign(annotPinsEl.style, {
- position: 'absolute', inset: '0',
- pointerEvents: 'none',
- });
- annotOverlayEl.appendChild(annotPinsEl);
-
- annotClearChipEl = document.createElement('div');
- annotClearChipEl.id = PREFIX + '-annot-clear';
- annotClearChipEl.dataset.annotClear = 'true';
- annotClearChipEl.textContent = 'Clear';
- Object.assign(annotClearChipEl.style, {
- position: 'absolute', top: '8px', right: '8px',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '10px', fontWeight: '500',
- letterSpacing: '0.08em', textTransform: 'uppercase',
- padding: '5px 12px', borderRadius: '999px',
- cursor: 'pointer', pointerEvents: 'auto',
- display: 'none', userSelect: 'none',
- boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
- });
- annotOverlayEl.appendChild(annotClearChipEl);
-
- annotOverlayEl.addEventListener('pointerdown', onAnnotDown);
- annotOverlayEl.addEventListener('pointermove', onAnnotMove);
- annotOverlayEl.addEventListener('pointerup', onAnnotUp);
- annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
- document.body.appendChild(annotOverlayEl);
- // Modal-host friendliness: pointer-events is already 'auto' on this
- // overlay; we only need to silence the host's outside-interaction
- // listeners. Don't override pointer-events here (the overlay toggles
- // visibility via display:none, which is fine).
- defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
- }
-
- function updateClearChip() {
- if (!annotClearChipEl) return;
- const hasAny = annotState.comments.length > 0 || annotState.strokes.length > 0;
- annotClearChipEl.style.display = hasAny ? 'block' : 'none';
- }
-
- function showAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- annotActive = true;
- positionAnnotOverlay(el);
- annotOverlayEl.style.display = 'block';
- }
-
- function hideAnnotOverlay() {
- annotActive = false;
- if (annotOverlayEl) annotOverlayEl.style.display = 'none';
- // Drop any in-progress edit without touching annotState — clearAnnotations
- // (if the caller is exiting configure mode) handles state reset.
- annotEditing = null;
- }
-
- function positionAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- const r = el.getBoundingClientRect();
- Object.assign(annotOverlayEl.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- annotSvgEl.setAttribute('viewBox', '0 0 ' + r.width + ' ' + r.height);
- }
-
- function clearAnnotations() {
- annotState.comments = [];
- annotState.strokes = [];
- if (annotSvgEl) while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- if (annotPinsEl) annotPinsEl.innerHTML = '';
- annotPointer = null;
- annotEditing = null;
- annotLastPinClick = { idx: -1, time: 0 };
- updateClearChip();
- }
-
- // Rebuild the SVG layer. Each stroke gets a wider invisible hit path
- // beneath the visible magenta path so clicks register on thin lines.
- function redrawStrokes() {
- while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- annotState.strokes.forEach((s, idx) => {
- const d = pointsToPath(s.points);
- const hit = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- hit.setAttribute('d', d);
- hit.setAttribute('stroke', 'transparent');
- hit.setAttribute('stroke-width', '16');
- hit.setAttribute('stroke-linecap', 'round');
- hit.setAttribute('stroke-linejoin', 'round');
- hit.setAttribute('fill', 'none');
- hit.setAttribute('pointer-events', 'stroke');
- hit.style.cursor = 'pointer';
- hit.dataset.annotStroke = String(idx);
- annotSvgEl.appendChild(hit);
- const visible = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- visible.setAttribute('d', d);
- visible.setAttribute('stroke', C.brand);
- visible.setAttribute('stroke-width', '3');
- visible.setAttribute('stroke-linecap', 'round');
- visible.setAttribute('stroke-linejoin', 'round');
- visible.setAttribute('fill', 'none');
- visible.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(visible);
- });
- updateClearChip();
- }
-
- function localCoords(e) {
- const rect = annotOverlayEl.getBoundingClientRect();
- return { x: e.clientX - rect.left, y: e.clientY - rect.top };
- }
-
- function onAnnotDown(e) {
- if (!annotActive) return;
-
- // 1) Clear chip → wipe all annotations
- if (e.target.closest?.('[data-annot-clear]')) {
- if (annotEditing) annotEditing = null;
- clearAnnotations();
- renderAllPins();
- redrawStrokes();
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 2) Stroke hit path → delete that stroke
- const strokeHit = e.target.closest?.('[data-annot-stroke]');
- if (strokeHit) {
- const idx = parseInt(strokeHit.dataset.annotStroke, 10);
- if (Number.isInteger(idx)) {
- annotState.strokes.splice(idx, 1);
- redrawStrokes();
- }
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 3) Pin → drag, edit, or delete-on-double-click
- const pinWrap = e.target.closest?.('[data-annot-pin]');
- if (pinWrap) {
- const idx = parseInt(pinWrap.dataset.annotPin, 10);
- if (!Number.isInteger(idx)) return;
- // Double-click (two pointerdowns on the same pin within window) → delete.
- const now = Date.now();
- if (annotLastPinClick.idx === idx && now - annotLastPinClick.time < PIN_DBL_CLICK_MS) {
- if (annotEditing && annotEditing.idx === idx) annotEditing = null;
- annotState.comments.splice(idx, 1);
- annotLastPinClick = { idx: -1, time: 0 };
- renderAllPins();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- annotLastPinClick = { idx, time: now };
- // If editing a different pin, commit that edit before starting here.
- if (annotEditing && annotEditing.idx !== idx) finalizeEditingPin();
- // If already editing THIS pin and the user clicked the dot, let the
- // input keep focus (don't start a drag — the click wasn't meant as one).
- if (annotEditing && annotEditing.idx === idx) return;
- const p = localCoords(e);
- const pin = annotState.comments[idx];
- annotPointer = {
- kind: 'pin', idx,
- startPointer: p,
- startPin: { x: pin.x, y: pin.y },
- moved: false,
- };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 4) Empty area → commit any open edit, then start new annotation
- if (annotEditing) {
- finalizeEditingPin();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- const p = localCoords(e);
- annotPointer = { kind: 'new', x0: p.x, y0: p.y, moved: false, strokeEl: null, strokePoints: null };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- }
-
- function onAnnotMove(e) {
- if (!annotActive || !annotPointer) return;
- const p = localCoords(e);
-
- if (annotPointer.kind === 'pin') {
- const dx = p.x - annotPointer.startPointer.x;
- const dy = p.y - annotPointer.startPointer.y;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- }
- const pin = annotState.comments[annotPointer.idx];
- if (!pin) { annotPointer = null; return; }
- pin.x = annotPointer.startPin.x + dx;
- pin.y = annotPointer.startPin.y + dy;
- renderAllPins();
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const dx = p.x - annotPointer.x0, dy = p.y - annotPointer.y0;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- const strokeEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- strokeEl.setAttribute('stroke', C.brand);
- strokeEl.setAttribute('stroke-width', '3');
- strokeEl.setAttribute('stroke-linecap', 'round');
- strokeEl.setAttribute('stroke-linejoin', 'round');
- strokeEl.setAttribute('fill', 'none');
- strokeEl.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(strokeEl);
- annotPointer.strokeEl = strokeEl;
- annotPointer.strokePoints = [[annotPointer.x0, annotPointer.y0]];
- }
- annotPointer.strokePoints.push([p.x, p.y]);
- annotPointer.strokeEl.setAttribute('d', pointsToPath(annotPointer.strokePoints));
- e.stopPropagation();
- }
-
- function onAnnotUp(e) {
- if (!annotActive || !annotPointer) return;
-
- if (annotPointer.kind === 'pin') {
- const wasDrag = annotPointer.moved;
- const idx = annotPointer.idx;
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- if (wasDrag) {
- // A drag is an intentional reposition; a follow-up click shouldn't be
- // interpreted as a double-click-to-delete.
- annotLastPinClick = { idx: -1, time: 0 };
- } else {
- beginEditPin(idx);
- }
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const wasDrag = annotPointer.moved;
- if (wasDrag) {
- annotState.strokes.push({ points: annotPointer.strokePoints });
- // Swap the temporary preview SVG path for the full render with hit paths.
- redrawStrokes();
- } else {
- const idx = annotState.comments.length;
- annotState.comments.push({ x: annotPointer.x0, y: annotPointer.y0, text: '' });
- renderAllPins();
- beginEditPin(idx);
- }
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- e.stopPropagation();
- }
-
- function pointsToPath(points) {
- if (!points || points.length === 0) return '';
- let d = 'M' + points[0][0].toFixed(1) + ' ' + points[0][1].toFixed(1);
- for (let i = 1; i < points.length; i++) {
- d += ' L' + points[i][0].toFixed(1) + ' ' + points[i][1].toFixed(1);
- }
- return d;
- }
-
- function renderAllPins() {
- annotPinsEl.innerHTML = '';
- annotState.comments.forEach((c, idx) => {
- annotPinsEl.appendChild(buildPinElement(c, idx));
- });
- updateClearChip();
- }
-
- function buildPinElement(comment, idx) {
- const interactive = idx >= 0;
- const wrap = document.createElement('div');
- if (interactive) wrap.dataset.annotPin = String(idx);
- Object.assign(wrap.style, {
- position: 'absolute',
- left: (comment.x - 7) + 'px', top: (comment.y - 7) + 'px',
- pointerEvents: interactive ? 'auto' : 'none',
- display: 'flex', alignItems: 'flex-start', gap: '6px',
- cursor: interactive ? 'grab' : 'default',
- touchAction: 'none',
- });
- const dot = document.createElement('div');
- Object.assign(dot.style, {
- width: '14px', height: '14px', borderRadius: '50%',
- background: C.brand, border: '2px solid ' + C.white,
- boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
- flexShrink: '0',
- });
- wrap.appendChild(dot);
-
- if (comment.text) {
- const bubble = document.createElement('div');
- bubble.textContent = comment.text;
- Object.assign(bubble.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- marginTop: '-2px', maxWidth: '220px',
- pointerEvents: 'none', whiteSpace: 'pre-wrap',
- wordBreak: 'break-word',
- });
- wrap.appendChild(bubble);
- }
- return wrap;
- }
-
- function beginEditPin(idx) {
- const wrapEl = annotPinsEl.querySelector('[data-annot-pin="' + idx + '"]');
- if (!wrapEl) return;
- // Strip any existing bubble (but keep the dot)
- wrapEl.querySelectorAll('div:not(:first-child)').forEach(n => n.remove());
- const input = document.createElement('input');
- input.type = 'text';
- input.placeholder = 'Note…';
- Object.assign(input.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- border: '1px solid ' + C.brand,
- outline: 'none', marginTop: '-2px',
- width: '220px', pointerEvents: 'auto',
- });
- const originalText = annotState.comments[idx].text || '';
- input.value = originalText;
- wrapEl.appendChild(input);
- annotEditing = { idx, input, wrapEl, originalText };
- input.addEventListener('keydown', onAnnotInputKey, true);
- input.addEventListener('blur', () => {
- // Fires on both focus-loss and programmatic blur; commit unless we
- // already handled it.
- if (annotEditing && annotEditing.input === input) finalizeEditingPin();
- });
- // Stop clicks/pointerdowns inside the input from bubbling to the overlay
- ['pointerdown', 'click'].forEach(ev => {
- input.addEventListener(ev, e => e.stopPropagation());
- });
- setTimeout(() => input.focus(), 0);
- }
-
- function onAnnotInputKey(e) {
- if (e.key === 'Enter') {
- e.preventDefault(); e.stopPropagation();
- finalizeEditingPin();
- } else if (e.key === 'Escape') {
- e.preventDefault(); e.stopPropagation();
- cancelEditingPin();
- } else {
- // Keep arrows / backspace from hitting global handlers
- e.stopPropagation();
- }
- }
-
- function finalizeEditingPin() {
- if (!annotEditing) return;
- const { idx, input } = annotEditing;
- const text = input.value.trim();
- annotEditing = null;
- if (text) annotState.comments[idx].text = text;
- else annotState.comments.splice(idx, 1);
- renderAllPins();
- }
-
- function cancelEditingPin() {
- if (!annotEditing) return;
- const { idx, originalText } = annotEditing;
- annotEditing = null;
- // If the pin had text before this edit, revert to it. If it was a
- // just-created empty pin, Escape removes it.
- if (originalText) {
- annotState.comments[idx].text = originalText;
- } else {
- annotState.comments.splice(idx, 1);
- }
- renderAllPins();
- }
-
- // Build a detached annotation subtree suitable for injection into the clone
- // modern-screenshot creates. Coordinates are element-local so this slots
- // straight into an element that's been made position:relative. Takes an
- // explicit snapshot so it works after annotState has been cleared.
- function buildAnnotationsForCapture(rect, snapshot) {
- const comments = snapshot ? snapshot.comments : annotState.comments;
- const strokes = snapshot ? snapshot.strokes : annotState.strokes;
- if (comments.length === 0 && strokes.length === 0) return null;
- const wrap = document.createElement('div');
- Object.assign(wrap.style, {
- position: 'absolute', top: '0', left: '0',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none', overflow: 'visible',
- });
- if (strokes.length > 0) {
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- svg.setAttribute('viewBox', '0 0 ' + rect.width + ' ' + rect.height);
- Object.assign(svg.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%', overflow: 'visible',
- });
- for (const s of strokes) {
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- path.setAttribute('stroke', C.brand);
- path.setAttribute('stroke-width', '3');
- path.setAttribute('stroke-linecap', 'round');
- path.setAttribute('stroke-linejoin', 'round');
- path.setAttribute('fill', 'none');
- path.setAttribute('d', pointsToPath(s.points));
- svg.appendChild(path);
- }
- wrap.appendChild(svg);
- }
- for (const c of comments) {
- // idx=-1 means non-interactive; pointerEvents stay off in the clone
- wrap.appendChild(buildPinElement(c, -1));
- }
- return wrap;
- }
-
- // ---------------------------------------------------------------------------
- // Element context extraction
- // ---------------------------------------------------------------------------
-
- function extractContext(el) {
- const cs = getComputedStyle(el);
- const r = el.getBoundingClientRect();
- const props = {};
- for (const sheet of document.styleSheets) {
- try {
- for (const rule of sheet.cssRules) {
- if (rule.style) for (let i = 0; i < rule.style.length; i++) {
- const p = rule.style[i];
- if (p.startsWith('--') && !props[p]) {
- const v = cs.getPropertyValue(p).trim();
- if (v) props[p] = v;
- }
- }
- }
- } catch { /* cross-origin */ }
- }
- return {
- tagName: el.tagName.toLowerCase(), id: el.id || null,
- classes: [...el.classList],
- textContent: (el.textContent || '').slice(0, 500),
- outerHTML: el.outerHTML.slice(0, 10000),
- computedStyles: {
- 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
- 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
- 'color': cs.color, 'background': cs.background,
- 'background-color': cs.backgroundColor,
- 'padding': cs.padding, 'margin': cs.margin,
- 'display': cs.display, 'position': cs.position,
- 'gap': cs.gap, 'border-radius': cs.borderRadius,
- 'box-shadow': cs.boxShadow,
- },
- cssCustomProperties: props,
- parentContext: el.parentElement
- ? '<' + el.parentElement.tagName.toLowerCase()
- + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
- + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
- + '>'
- : null,
- boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
- };
- }
-
- // ---------------------------------------------------------------------------
- // The Bar — one floating element, three modes
- // ---------------------------------------------------------------------------
-
- // Contextual-bar palette. Cached at init so every build*Row reads a
- // consistent set of colors; detectPageTheme runs once rather than on every
- // phase transition.
- let BP = null;
-
- // Bar shadow variants. The default projects down + subtle around. When
- // the Tune popover opens below the bar, a downward shadow lands on the
- // dark popover and reads as a bright ghost line. We swap to UP-only while
- // tune is open below so the popover's top edge is clean.
- const BAR_SHADOW_DEFAULT = '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_UP = '0 -4px 20px oklch(0% 0 0 / 0.08), 0 -1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_DOWN = BAR_SHADOW_DEFAULT;
-
- function initBar() {
- BP = barPaletteForTheme(detectPageTheme());
- barEl = document.createElement('div');
- barEl.id = PREFIX + '-bar';
- Object.assign(barEl.style, {
- position: 'fixed', zIndex: Z.bar,
- display: 'none', opacity: '0',
- transform: 'translateY(6px)',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- background: BP.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + BP.hairline,
- borderRadius: '10px',
- boxShadow: BAR_SHADOW_DEFAULT,
- transition: 'box-shadow 0.2s ease, opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- fontFamily: FONT, fontSize: '13px', color: BP.text,
- padding: '6px',
- maxWidth: '520px', minWidth: '320px',
- });
- document.body.appendChild(barEl);
- defangOutsideHandlers(barEl);
- }
-
- function positionBar() {
- if (!barEl || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- const barH = barEl.offsetHeight || 44;
- const barW = barEl.offsetWidth || 380;
- const GLOBAL_BAR_RESERVE = 64; // global bar height + bottom margin + breathing room
- const GAP = 8;
-
- // Prefer below the element; fall back to above; if neither fits (element
- // taller than viewport), pin to a stable viewport anchor so the bar
- // doesn't teleport between top and bottom as the user scrolls.
- let top;
- const belowTop = r.bottom + GAP;
- const aboveTop = r.top - barH - GAP;
- if (belowTop + barH + GAP <= window.innerHeight - GLOBAL_BAR_RESERVE) {
- top = belowTop;
- } else if (aboveTop >= GAP) {
- top = aboveTop;
- } else {
- top = window.innerHeight - barH - GLOBAL_BAR_RESERVE;
- }
-
- let left = r.left + (r.width - barW) / 2;
- if (left < GAP) left = GAP;
- if (left + barW > window.innerWidth - GAP) left = window.innerWidth - barW - GAP;
- Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
- }
-
- function showBar(mode) {
- barEl.innerHTML = '';
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- barEl.style.display = 'block';
- positionBar();
- requestAnimationFrame(() => {
- barEl.style.opacity = '1';
- barEl.style.transform = 'translateY(0)';
- });
- }
-
- function hideBar() {
- if (!barEl) return;
- barEl.style.opacity = '0';
- barEl.style.transform = 'translateY(6px)';
- setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
- hideActionPicker();
- closeTunePopover();
- }
-
- function updateBarContent(mode) {
- if (!barEl || barEl.style.display === 'none') return;
- barEl.innerHTML = '';
- // Reset bar styling to the theme-aware palette
- barEl.style.background = BP.surface;
- barEl.style.border = '1px solid ' + BP.hairline;
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- else if (mode === 'saving') barEl.appendChild(buildSavingRow());
- else if (mode === 'confirmed') {
- barEl.appendChild(buildConfirmedRow());
- barEl.style.background = 'oklch(95% 0.05 145)';
- barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
- }
- }
-
- // --- Configure row ---
-
- function buildConfigureRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
-
- // Action pill
- const pill = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '4px',
- padding: '5px 10px', borderRadius: '6px',
- background: BP.mark, color: BP.markText,
- fontFamily: FONT, fontSize: '12px', fontWeight: '500',
- border: 'none', cursor: 'pointer',
- transition: 'background 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap', flexShrink: '0',
- });
- pill.textContent = actionLabel() + ' \u25BE';
- pill.addEventListener('mouseenter', () => pill.style.background = BP.accent);
- pill.addEventListener('mouseleave', () => pill.style.background = BP.mark);
- pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
- pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
- pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
- row.appendChild(pill);
-
- // Freeform input. Focus state shows an accent-colored border only —
- // an earlier version tinted the background with `BP.accentSoft`, which
- // composited against the dark bar surface to a murky purple where the
- // browser's default placeholder gray was unreadable. Placeholder color
- // is set explicitly via a one-shot stylesheet keyed off this input's id
- // so it picks up the bar's `textDim` token in both themes.
- const input = document.createElement('input');
- input.id = PREFIX + '-input';
- input.type = 'text';
- input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
- Object.assign(input.style, {
- flex: '1', minWidth: '0',
- padding: '5px 8px', borderRadius: '6px',
- border: '1px solid transparent', background: 'transparent',
- fontFamily: FONT, fontSize: '12px', color: BP.text,
- outline: 'none',
- transition: 'border-color 0.15s ease',
- });
- if (!document.getElementById(PREFIX + '-input-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-input-style';
- s.textContent =
- '#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
- document.head.appendChild(s);
- }
- input.addEventListener('focus', () => {
- input.style.borderColor = BP.accent;
- });
- input.addEventListener('blur', () => {
- input.style.borderColor = 'transparent';
- });
- input.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
- if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; return; }
- // Let arrow keys pass through to the element picker when the input is empty
- if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && !input.value) return;
- e.stopPropagation();
- });
- row.appendChild(input);
-
- // Variant count toggle
- const count = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: MONO, fontSize: '11px', fontWeight: '600',
- color: BP.textDim, cursor: 'pointer',
- transition: 'color 0.12s ease, border-color 0.12s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- count.textContent = '\u00D7' + selectedCount;
- count.title = 'Variants: click to change';
- count.addEventListener('mouseenter', () => { count.style.color = BP.text; count.style.borderColor = BP.text; });
- count.addEventListener('mouseleave', () => { count.style.color = BP.textDim; count.style.borderColor = BP.hairline; });
- count.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
- count.textContent = '\u00D7' + selectedCount;
- });
- row.appendChild(count);
-
- // Go button
- const go = el('button', {
- padding: '5px 12px', borderRadius: '6px',
- border: 'none', background: BP.accent, color: BP.mark,
- fontFamily: FONT, fontSize: '12px', fontWeight: '600',
- cursor: 'pointer',
- transition: 'filter 0.12s ease, transform 0.1s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- go.textContent = 'Go \u2192';
- go.addEventListener('mouseenter', () => go.style.filter = 'brightness(1.1)');
- go.addEventListener('mouseleave', () => go.style.filter = 'none');
- go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
- go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
- go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
- row.appendChild(go);
-
- // Auto-focus input after a beat
- setTimeout(() => input.focus(), 60);
- return row;
- }
-
- // --- Generating row ---
-
- function buildGeneratingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 4px',
- });
-
- // Action label
- const label = el('span', {
- fontWeight: '600', fontSize: '12px', color: BP.text,
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- label.textContent = actionLabel();
- row.appendChild(label);
-
- // Dots
- row.appendChild(buildDots(false));
-
- // Status
- const status = el('span', {
- fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',
- marginLeft: 'auto',
- });
- // Variants currently arrive atomically in a single file edit, so a
- // per-variant counter would lie. Say what's true.
- status.textContent = arrivedVariants < expectedVariants
- ? 'Generating ' + expectedVariants + ' variants...'
- : 'Done';
- row.appendChild(status);
-
- return row;
- }
-
- // --- Cycling row ---
-
- const TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';
-
- function buildCyclingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '6px',
- padding: '1px 2px',
- });
-
- // Prev
- const prev = navBtn('\u2190');
- prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
- if (visibleVariant <= 1) prev.style.opacity = '0.3';
- row.appendChild(prev);
-
- // Dots (clickable)
- row.appendChild(buildDots(true));
-
- // Counter
- const counter = el('span', {
- fontFamily: MONO, fontSize: '11px', fontWeight: '500',
- color: BP.textDim, minWidth: '24px', textAlign: 'center',
- });
- counter.textContent = visibleVariant + '/' + arrivedVariants;
- row.appendChild(counter);
-
- // Next
- const next = navBtn('\u2192');
- next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
- if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
- row.appendChild(next);
-
- // Tune chip — only when the visible variant exposes params
- const visParams = parseVariantParams(getVisibleVariantEl());
- const hasParams = visParams.length > 0;
- if (hasParams) {
- const tune = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '6px',
- padding: '4px 10px', borderRadius: '5px',
- border: '1px solid transparent',
- background: tuneOpen ? BP.accentSoft : 'transparent',
- color: tuneOpen ? BP.accent : BP.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'color 0.12s ease, background 0.12s ease',
- whiteSpace: 'nowrap',
- });
- tune.innerHTML = TUNE_ICON_SVG;
- const tuneLabel = document.createElement('span');
- tuneLabel.textContent = 'Tune';
- tune.appendChild(tuneLabel);
- const tuneBadge = document.createElement('span');
- Object.assign(tuneBadge.style, {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- minWidth: '16px', height: '16px', padding: '0 4px',
- borderRadius: '999px',
- background: tuneOpen ? C.brand : BP.hairline,
- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',
- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',
- lineHeight: '1',
- boxSizing: 'border-box',
- });
- tuneBadge.textContent = String(visParams.length);
- tune.appendChild(tuneBadge);
- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';
- tune.addEventListener('mouseenter', () => {
- if (!tuneOpen) tune.style.background = BP.accentSoft;
- });
- tune.addEventListener('mouseleave', () => {
- if (!tuneOpen) tune.style.background = 'transparent';
- });
- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });
- tune.dataset.iceqTune = '1';
- row.appendChild(tune);
- }
-
- // Spacer
- row.appendChild(el('div', { flex: '1' }));
-
- // Accept — primary action, uses the site's saturated brand magenta
- // with paper-white text, not the theme-muted BP.accent.
- const accept = el('button', {
- padding: '5px 14px', borderRadius: '5px',
- border: 'none', background: C.brand, color: 'oklch(98% 0 0)',
- fontFamily: FONT, fontSize: '11px', fontWeight: '600',
- cursor: 'pointer', transition: 'filter 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap',
- });
- accept.textContent = '\u2713 Accept';
- accept.addEventListener('mouseenter', () => accept.style.filter = 'brightness(1.08)');
- accept.addEventListener('mouseleave', () => accept.style.filter = 'none');
- accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');
- accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');
- accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
- row.appendChild(accept);
-
- // Discard
- const discard = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: FONT, fontSize: '11px', color: BP.textDim,
- cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
- });
- discard.textContent = '\u2715';
- discard.title = 'Discard all variants';
- discard.addEventListener('mouseenter', () => { discard.style.color = BP.text; discard.style.borderColor = BP.text; });
- discard.addEventListener('mouseleave', () => { discard.style.color = BP.textDim; discard.style.borderColor = BP.hairline; });
- discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
- row.appendChild(discard);
-
- return row;
- }
-
- // --- Shared UI builders ---
-
- // --- Saving row (waiting for agent to process accept/discard) ---
-
- function buildSavingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const spinner = el('div', {
- width: '14px', height: '14px', borderRadius: '50%',
- border: '2px solid ' + BP.hairline,
- borderTopColor: BP.accent,
- animation: 'impeccable-spin 0.6s linear infinite',
- flexShrink: '0',
- });
- row.appendChild(spinner);
- const label = el('span', {
- fontSize: '12px', color: BP.textDim, fontWeight: '500',
- });
- label.textContent = 'Applying variant...';
- row.appendChild(label);
-
- // Inject the keyframes if not already present
- if (!document.getElementById(PREFIX + '-keyframes')) {
- const style = document.createElement('style');
- style.id = PREFIX + '-keyframes';
- style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
- document.head.appendChild(style);
- }
- return row;
- }
-
- // --- Confirmed row (green success, auto-dismisses) ---
-
- function buildConfirmedRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const check = el('span', {
- fontSize: '15px', lineHeight: '1', flexShrink: '0',
- color: 'oklch(45% 0.15 145)',
- });
- check.textContent = '\u2713';
- row.appendChild(check);
- const label = el('span', {
- fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
- });
- label.textContent = 'Variant applied';
- row.appendChild(label);
- return row;
- }
-
- // --- Shared UI builders ---
-
- function buildDots(clickable) {
- const container = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
- for (let i = 1; i <= expectedVariants; i++) {
- const arrived = i <= arrivedVariants;
- const active = i === visibleVariant;
- // active: solid site-brand magenta dot. arrived+inactive: muted neutral.
- // pending (not yet arrived): faint outline ring. No borders on arrived
- // dots — the previous "accent ring + ash fill" combo read as noisy
- // magenta chips, especially when all variants had arrived and every
- // dot wore an accent ring.
- const dotBg = active ? C.brand
- : arrived ? BP.textDim
- : 'transparent';
- const dotBorder = arrived ? 'none' : '1.5px solid ' + BP.hairline;
- const dot = el('div', {
- width: active ? '8px' : '6px',
- height: active ? '8px' : '6px',
- borderRadius: '50%',
- background: dotBg,
- border: dotBorder,
- boxSizing: 'border-box',
- transition: 'all 0.2s ' + EASE,
- cursor: (clickable && arrived) ? 'pointer' : 'default',
- transform: arrived ? 'scale(1)' : 'scale(0.85)',
- opacity: arrived ? (active ? '1' : '0.6') : '0.4',
- });
- if (clickable && arrived) {
- const idx = i;
- dot.addEventListener('click', (e) => {
- e.stopPropagation();
- visibleVariant = idx;
- showVariantInDOM(currentSessionId, idx);
- updateSelectedElement();
- updateBarContent('cycling');
- });
- }
- container.appendChild(dot);
- }
- return container;
- }
-
- function navBtn(text) {
- const b = el('button', {
- width: '26px', height: '26px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- color: BP.text, fontFamily: FONT, fontSize: '13px',
- cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
- transition: 'border-color 0.12s ease, background 0.12s ease',
- padding: '0', lineHeight: '1',
- });
- b.textContent = text;
- b.addEventListener('mouseenter', () => { b.style.borderColor = BP.text; });
- b.addEventListener('mouseleave', () => { b.style.borderColor = BP.hairline; });
- return b;
- }
-
- function actionLabel() {
- const a = ACTIONS.find(a => a.value === selectedAction);
- return a ? a.label : 'Freeform';
- }
-
- function el(tag, styles) {
- const e = document.createElement(tag);
- if (styles) Object.assign(e.style, styles);
- return e;
- }
-
- // ---------------------------------------------------------------------------
- // Action picker popover
- // ---------------------------------------------------------------------------
-
- function initActionPicker() {
- const P = barPaletteForTheme(detectPageTheme());
- pickerEl = document.createElement('div');
- pickerEl.id = PREFIX + '-picker';
- Object.assign(pickerEl.style, {
- position: 'fixed', zIndex: Z.picker,
- display: 'none', opacity: '0',
- transform: 'scale(0.96) translateY(4px)',
- transformOrigin: 'bottom left',
- transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
- background: P.surface,
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
- padding: '6px',
- fontFamily: FONT,
- backdropFilter: 'blur(10px)',
- WebkitBackdropFilter: 'blur(10px)',
- });
-
- // Build the chip grid
- const grid = el('div', {
- display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
- });
-
- ACTIONS.forEach(action => {
- const chip = el('button', {
- display: 'flex', flexDirection: 'column', alignItems: 'center',
- gap: '4px',
- padding: '8px 6px', borderRadius: '6px',
- border: 'none',
- background: action.value === selectedAction ? P.accentSoft : 'transparent',
- color: action.value === selectedAction ? P.accent : P.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.1s ease, color 0.1s ease',
- textAlign: 'center', whiteSpace: 'nowrap',
- });
- const iconWrap = el('span', {
- display: 'flex', alignItems: 'center', justifyContent: 'center',
- height: '20px', opacity: '0.9',
- });
- iconWrap.innerHTML = ICONS[action.value] || '';
- const labelEl = el('span', { lineHeight: '1' });
- labelEl.textContent = action.label;
- chip.appendChild(iconWrap);
- chip.appendChild(labelEl);
- chip.dataset.action = action.value;
- chip.addEventListener('mouseenter', () => {
- if (action.value !== selectedAction) chip.style.background = P.accentSoft;
- });
- chip.addEventListener('mouseleave', () => {
- chip.style.background = action.value === selectedAction ? P.accentSoft : 'transparent';
- });
- chip.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedAction = action.value;
- hideActionPicker();
- updateBarContent('configure');
- });
- grid.appendChild(chip);
- });
-
- pickerEl.appendChild(grid);
- document.body.appendChild(pickerEl);
- defangOutsideHandlers(pickerEl);
-
- // Cache the palette on the picker so toggleActionPicker's state refresh
- // uses the same theme-aware colors when it repaints chips.
- pickerEl.__iceq_palette = P;
- }
-
- function toggleActionPicker() {
- if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
- // Rebuild chips to reflect current selection
- const P = pickerEl.__iceq_palette || barPaletteForTheme(detectPageTheme());
- pickerEl.querySelectorAll('button').forEach(chip => {
- const isActive = chip.dataset.action === selectedAction;
- chip.style.background = isActive ? P.accentSoft : 'transparent';
- chip.style.color = isActive ? P.accent : P.text;
- });
- // Position above the bar
- const barRect = barEl.getBoundingClientRect();
- const pickerH = 170; // approximate; grows with icon + label rows
- let top = barRect.top - pickerH - 6;
- if (top < 8) top = barRect.bottom + 6;
- Object.assign(pickerEl.style, {
- top: top + 'px', left: barRect.left + 'px',
- display: 'block',
- });
- requestAnimationFrame(() => {
- pickerEl.style.opacity = '1';
- pickerEl.style.transform = 'scale(1) translateY(0)';
- });
- }
-
- function hideActionPicker() {
- if (!pickerEl) return;
- pickerEl.style.opacity = '0';
- pickerEl.style.transform = 'scale(0.96) translateY(4px)';
- setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
- }
-
- // ---------------------------------------------------------------------------
- // Params panel (per-variant coarse controls)
- //
- // Variants may declare a parameter manifest via a JSON attribute on the
- // variant wrapper:
- //
- // <div data-impeccable-variant="1"
- // data-impeccable-params='[{"id":"density","kind":"steps",...}]'>
- //
- // The panel docks to the right edge of the outline during CYCLING and
- // exposes 2-5 coarse knobs. Values apply to the variant wrapper so scoped
- // CSS can respond instantly without regeneration:
- //
- // range / numeric toggle → CSS var (`--p-<id>`) used via var(--p-foo, N)
- // steps / boolean toggle → data-p-<id> attribute used via :scope[data-p-foo="..."]
- //
- // On variant switch, values reset to that variant's declared defaults.
- // On accept, current values are sent in the event payload so the agent
- // can bake them into the source-file write.
- // ---------------------------------------------------------------------------
-
- let paramsPanelEl = null; // outer wrapper (overflow:hidden, clips the slide)
- let paramsPanelInner = null; // translating content (carries bg, padding, knobs)
- let paramsPanelBody = null; // grid holding the knob cells
- let paramsCurrentValues = {}; // {paramId: value} — mirror of the visible variant's live values
- let tuneOpen = false; // whether the Tune popover is open right now
-
- // Theme-aware Tune popover. Appears as a drawer that slides out from the
- // contextual bar's bar-facing edge (below if the bar sits below the
- // element, above otherwise). Same width as the bar. Auto-wraps to extra
- // rows when the knobs exceed one row. The bar's border-radius on the
- // popover side goes flat while open so the two shapes read as one.
- let paramsPanelPalette = null;
-
- function initParamsPanel() {
- paramsPanelPalette = barPaletteForTheme(detectPageTheme());
- const P = paramsPanelPalette;
-
- // Single element, always in the DOM. The slide animation is a CSS mask
- // with mask-size growing from 0% to 100% along the bar-facing axis — no
- // display toggle, no opacity toggle, no transform trickery. The mask
- // hides everything initially; as it grows, content is revealed from
- // the bar edge outward.
- paramsPanelEl = document.createElement('div');
- paramsPanelEl.id = PREFIX + '-params-panel';
- Object.assign(paramsPanelEl.style, {
- position: 'fixed', zIndex: String(Z.bar - 1),
- background: P.surfaceDeep,
- color: P.text,
- fontFamily: FONT,
- padding: '14px 18px',
- boxSizing: 'border-box',
- borderRadius: '0 0 10px 10px',
- pointerEvents: 'none',
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
-
- // clip-path is the same conceptual reveal as mask but with rock-solid
- // transition support across engines. Closed state clips from the far
- // edge; open = inset(0) shows everything.
- clipPath: 'inset(0 0 100% 0)',
- transition: 'clip-path 0.44s ' + EASE,
-
- // Park off-screen until positionParamsPanel places it. These are NOT
- // in the transition list, so they snap instantly — no fly-in from the
- // top-left when first shown.
- top: '-9999px', left: '-9999px', width: '0',
- });
-
- paramsPanelBody = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
- gap: '12px 16px',
- });
-
- paramsPanelEl.appendChild(paramsPanelBody);
- document.body.appendChild(paramsPanelEl);
- // Don't override pointer-events: the panel toggles between 'none' (closed,
- // click-through) and 'auto' (open) on its own. Just silence the host's
- // outside-interaction listeners while the panel is open.
- defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
- paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
- }
-
- function getVisibleVariantEl() {
- if (!currentSessionId) return null;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return null;
- return wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"]');
- }
-
- function parseVariantParams(variantEl) {
- if (!variantEl) return [];
- const raw = variantEl.getAttribute('data-impeccable-params');
- if (!raw) return [];
- try {
- const parsed = JSON.parse(raw);
- return Array.isArray(parsed) ? parsed : [];
- } catch (err) {
- console.warn('[impeccable] Invalid data-impeccable-params JSON:', err.message);
- return [];
- }
- }
-
- function applyParamValue(variantEl, param, value) {
- if (!variantEl) return;
- const attr = 'data-p-' + param.id;
- if (param.kind === 'range') {
- variantEl.style.setProperty('--p-' + param.id, String(value));
- } else if (param.kind === 'toggle') {
- const on = !!value;
- variantEl.style.setProperty('--p-' + param.id, on ? '1' : '0');
- if (on) variantEl.setAttribute(attr, 'on');
- else variantEl.removeAttribute(attr);
- } else if (param.kind === 'steps') {
- variantEl.setAttribute(attr, String(value));
- }
- }
-
- function applyParamDefaults(variantEl, params) {
- paramsCurrentValues = {};
- for (const p of params) {
- paramsCurrentValues[p.id] = p.default;
- applyParamValue(variantEl, p, p.default);
- }
- }
-
- function formatRangeValue(input) {
- const max = parseFloat(input.max), min = parseFloat(input.min);
- const v = parseFloat(input.value);
- if (!isFinite(v)) return input.value;
- return (max - min) <= 2 ? v.toFixed(2) : String(Math.round(v));
- }
-
- function buildParamsPanel(variantEl, params) {
- const P = paramsPanelPalette || barPaletteForTheme(detectPageTheme());
- paramsPanelBody.innerHTML = '';
- for (const p of params) {
- const row = el('div', { display: 'flex', flexDirection: 'column', gap: '6px' });
- const labelRow = el('div', {
- display: 'flex', justifyContent: 'space-between',
- alignItems: 'baseline', gap: '8px',
- });
- const lbl = el('span', {
- fontSize: '10.5px', fontWeight: '600', color: P.text,
- letterSpacing: '0.03em',
- });
- lbl.textContent = p.label || p.id;
- labelRow.appendChild(lbl);
- const readout = el('span', {
- fontSize: '10.5px', color: P.textDim,
- fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
- });
- labelRow.appendChild(readout);
- row.appendChild(labelRow);
-
- if (p.kind === 'range') {
- const input = document.createElement('input');
- input.type = 'range';
- input.min = String(p.min != null ? p.min : 0);
- input.max = String(p.max != null ? p.max : 1);
- input.step = String(p.step != null ? p.step : 0.05);
- input.value = String(p.default);
- Object.assign(input.style, {
- width: '100%', accentColor: C.brand, cursor: 'pointer',
- });
- readout.textContent = formatRangeValue(input);
- input.addEventListener('input', (e) => {
- e.stopPropagation();
- const v = parseFloat(input.value);
- paramsCurrentValues[p.id] = v;
- readout.textContent = formatRangeValue(input);
- applyParamValue(variantEl, p, v);
- queueCheckpoint('param_changed');
- });
- row.appendChild(input);
- } else if (p.kind === 'toggle') {
- const initial = !!p.default;
- readout.textContent = initial ? 'On' : 'Off';
- const track = el('button', {
- position: 'relative', width: '36px', height: '20px',
- borderRadius: '10px', border: 'none', padding: '0',
- cursor: 'pointer',
- background: initial ? C.brand : P.hairline,
- transition: 'background 0.15s ease',
- alignSelf: 'flex-start',
- });
- const knob = el('span', {
- position: 'absolute', top: '2px',
- left: initial ? '18px' : '2px',
- width: '16px', height: '16px', borderRadius: '50%',
- background: 'oklch(98% 0 0)',
- transition: 'left 0.18s ' + EASE,
- boxShadow: '0 1px 2px oklch(0% 0 0 / 0.2)',
- });
- track.appendChild(knob);
- track.addEventListener('click', (e) => {
- e.stopPropagation();
- const next = !paramsCurrentValues[p.id];
- paramsCurrentValues[p.id] = next;
- track.style.background = next ? C.brand : P.hairline;
- knob.style.left = next ? '18px' : '2px';
- readout.textContent = next ? 'On' : 'Off';
- applyParamValue(variantEl, p, next);
- queueCheckpoint('param_changed');
- });
- row.appendChild(track);
- } else if (p.kind === 'steps') {
- const opts = (p.options || []).map(o =>
- typeof o === 'string' ? { value: o, label: o } : o
- );
- const activeOpt = opts.find(o => o.value === p.default) || opts[0];
- readout.textContent = activeOpt ? activeOpt.label : String(p.default);
- const segRow = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(' + opts.length + ', 1fr)',
- gap: '1px', padding: '2px',
- background: P.hairline, borderRadius: '5px',
- });
- const segBtns = [];
- opts.forEach(o => {
- const active = o.value === p.default;
- const b = el('button', {
- padding: '5px 4px', border: 'none', borderRadius: '3px',
- background: active ? C.brand : 'transparent',
- color: active ? 'oklch(98% 0 0)' : P.text,
- fontFamily: FONT, fontSize: '10.5px', fontWeight: '500',
- cursor: 'pointer', whiteSpace: 'nowrap',
- transition: 'background 0.1s ease, color 0.1s ease',
- });
- b.textContent = o.label;
- b.addEventListener('click', (e) => {
- e.stopPropagation();
- paramsCurrentValues[p.id] = o.value;
- readout.textContent = o.label;
- segBtns.forEach(({ btn, val }) => {
- const on = val === o.value;
- btn.style.background = on ? C.brand : 'transparent';
- btn.style.color = on ? 'oklch(98% 0 0)' : P.text;
- });
- applyParamValue(variantEl, p, o.value);
- queueCheckpoint('param_changed');
- });
- segRow.appendChild(b);
- segBtns.push({ btn: b, val: o.value });
- });
- row.appendChild(segRow);
- }
-
- paramsPanelBody.appendChild(row);
- }
- }
-
- // Decide which way the popover opens: away from the picked element. If the
- // bar landed below the element, popover slides DOWN from the bar's bottom.
- // If the bar landed above, popover slides UP from the bar's top.
- function popoverDirection() {
- if (!barEl || !selectedElement) return 'below';
- const br = barEl.getBoundingClientRect();
- const er = selectedElement.getBoundingClientRect();
- return br.top >= er.bottom - 4 ? 'below' : 'above';
- }
-
- // The popover overlaps the bar by OVERLAP px on the bar-facing side. With
- // popover z-index below bar, that overlap sits behind bar (invisible) and
- // reinforces the "tucked behind" feel. Padding compensates so the real
- // content starts flush with bar's outer edge.
- const TUNE_OVERLAP = 6;
-
- // Closed clip-path depends on direction: for 'below' clip from the far
- // (bottom) edge so the reveal grows downward from the bar; for 'above'
- // clip from the top edge so the reveal grows upward from the bar.
- function closedClipPath(direction) {
- return direction === 'below' ? 'inset(0 0 100% 0)' : 'inset(100% 0 0 0)';
- }
-
- function setClipPath(value, withTransition) {
- const saved = paramsPanelEl.style.transition;
- if (!withTransition) paramsPanelEl.style.transition = 'none';
- paramsPanelEl.style.clipPath = value;
- if (!withTransition) {
- void paramsPanelEl.offsetHeight;
- paramsPanelEl.style.transition = saved;
- }
- }
-
- function positionParamsPanel() {
- if (!paramsPanelEl || !barEl || barEl.style.display === 'none') return;
- const br = barEl.getBoundingClientRect();
- const direction = popoverDirection();
- const prevDirection = paramsPanelEl.dataset.tuneDirection;
-
- // top/left/width are NOT in the transition list, so they snap instantly.
- paramsPanelEl.style.left = br.left + 'px';
- paramsPanelEl.style.width = br.width + 'px';
-
- if (direction === 'below') {
- paramsPanelEl.style.top = (br.bottom - TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '0 0 10px 10px';
- paramsPanelEl.style.paddingTop = (14 + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.paddingBottom = '14px';
- } else {
- const ih = paramsPanelEl.offsetHeight || 80;
- paramsPanelEl.style.top = (br.top - ih + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '10px 10px 0 0';
- paramsPanelEl.style.paddingTop = '14px';
- paramsPanelEl.style.paddingBottom = (14 + TUNE_OVERLAP) + 'px';
- }
- paramsPanelEl.dataset.tuneDirection = direction;
-
- // If currently closed and direction flipped (or first-time setup),
- // snap the clip-path to the new direction's closed pose without
- // transitioning (so the clip doesn't slide across the element).
- if (!tuneOpen && (!prevDirection || prevDirection !== direction)) {
- setClipPath(closedClipPath(direction), false);
- }
- }
-
- function showParamsPanel() {
- if (!paramsPanelEl) return;
- positionParamsPanel();
- paramsPanelEl.style.pointerEvents = 'auto';
- // rAF so the positioning paint commits before the transition fires.
- requestAnimationFrame(() => {
- setClipPath('inset(0 0 0 0)', true);
- });
- }
-
- function hideParamsPanel() {
- if (!paramsPanelEl) return;
- paramsPanelEl.style.pointerEvents = 'none';
- const direction = paramsPanelEl.dataset.tuneDirection || 'below';
- setClipPath(closedClipPath(direction), true);
- }
-
- // Build/rebuild the panel's contents for the current variant AND apply
- // its defaults to the variant wrapper (so scoped CSS responds even before
- // the user opens the popover). Visibility is governed by tuneOpen.
- function refreshParamsPanel() {
- if (state !== 'CYCLING') {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- if (tuneOpen) {
- // If already visible (variant cycled while open), refresh in place
- // instead of re-running the clip-path animation.
- const alreadyVisible = paramsPanelEl.style.display === 'block'
- && paramsPanelEl.style.opacity === '1';
- if (alreadyVisible) positionParamsPanel();
- else showParamsPanel();
- } else {
- hideParamsPanel();
- }
- }
-
- function toggleTunePopover() {
- if (tuneOpen) { closeTunePopover(); return; }
- openTunePopover();
- }
-
- function openTunePopover() {
- if (state !== 'CYCLING') return;
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) return;
- // Build fresh to ensure the current variant's controls are shown.
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- tuneOpen = true;
- showParamsPanel();
- // Kill the bar's shadow on the popover-facing side so the dark popover
- // doesn't pick up a bright glow line.
- if (barEl) {
- const direction = paramsPanelEl?.dataset.tuneDirection || 'below';
- barEl.style.boxShadow = direction === 'below' ? BAR_SHADOW_UP : BAR_SHADOW_DOWN;
- }
- // Re-render the bar so the Tune chip picks up the active styling.
- updateBarContent('cycling');
- }
-
- function closeTunePopover() {
- tuneOpen = false;
- hideParamsPanel();
- if (barEl) barEl.style.boxShadow = BAR_SHADOW_DEFAULT;
- if (barEl && barEl.style.display !== 'none' && state === 'CYCLING') {
- updateBarContent('cycling');
- }
- }
-
- // ---------------------------------------------------------------------------
- // Variant cycling in DOM
- // ---------------------------------------------------------------------------
-
- function showVariantInDOM(sessionId, num) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
- for (const child of wrapper.children) {
- const v = child.dataset ? child.dataset.impeccableVariant : null;
- if (!v) continue;
- child.style.display = (v === String(num)) ? '' : 'none';
- }
- // Unconditional refresh — covers first-reveal (no-op if state isn't
- // CYCLING yet, the subsequent CYCLING transition triggers its own
- // refresh) and every cycle step.
- refreshParamsPanel();
- }
-
- /**
- * No-HMR fallback: fetch the raw source file from the live server,
- * parse it, extract the variant wrapper, and inject it into the live DOM.
- * This works even when the dev server caches HTML (Bun, static servers).
- */
- function injectVariantsFromSource(filePath, sessionId) {
- const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
- fetch(url)
- .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
- .then(html => {
- // Parse the raw source HTML
- const parser = new DOMParser();
- const doc = parser.parseFromString(html, 'text/html');
- const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!srcWrapper) {
- console.error('[impeccable] Variant wrapper not found in source file.');
- return;
- }
-
- // Find the original element in the live DOM.
- // The original is inside the wrapper in the source. We find the
- // corresponding element in the live DOM by matching the first child's
- // tag + classes from the original snapshot.
- const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
- if (!origContent) return;
-
- const tag = origContent.tagName.toLowerCase();
- const cls = origContent.className;
- let liveEl = null;
- if (origContent.id) {
- liveEl = document.getElementById(origContent.id);
- } else if (cls) {
- // Find by tag + exact class match
- const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
- for (const c of candidates) {
- if (c.className === cls && !own(c)) { liveEl = c; break; }
- }
- }
-
- if (!liveEl) {
- console.error('[impeccable] Could not find original element in live DOM.');
- return;
- }
-
- const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;
-
- // Replace the live element with the full wrapper from source
- const wrapper = srcWrapper.cloneNode(true);
- liveEl.parentElement.replaceChild(wrapper, liveEl);
-
- // Update state: count variants, preserving the user's current variant
- // when a late HMR/source reinjection lands after they have cycled.
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants
- ? previousVisibleVariant
- : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);
- showVariantInDOM(sessionId, visibleVariant);
-
- // Update selectedElement to the visible variant's content
- selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;
-
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- saveSession();
- console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
- })
- .catch(err => {
- console.error('[impeccable] Failed to fetch source:', err);
- showToast('Could not load variants. Try refreshing the page.', 5000);
- });
- }
-
- function cycleVariant(dir) {
- const next = visibleVariant + dir;
- if (next < 1 || next > arrivedVariants) return;
- visibleVariant = next;
- showVariantInDOM(currentSessionId, next); // calls refreshParamsPanel itself
- updateSelectedElement();
- updateBarContent('cycling');
- saveSession();
- queueCheckpoint('variant_changed');
- }
-
- function updateSelectedElement() {
- if (!currentSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return;
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- function readVisibleVariantFromDOM(sessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return 0;
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- for (const variant of variants) {
- if (variant.style.display === 'none') continue;
- const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);
- if (idx > 0) return idx;
- }
- return 0;
- }
-
- // Resolve the element that represents the variant's visible content.
- // Contract: each variant div should contain exactly one top-level element
- // (the full replacement). In practice a model may ship loose siblings or
- // lead with <style>/<script>. Be defensive: skip non-visual elements, and
- // if the variant has multiple element children, use the variant div itself
- // (it wraps all of them and gets correct bounds).
- function pickVariantContent(wrapper, index) {
- if (!wrapper) return null;
- const variantDiv = wrapper.querySelector('[data-impeccable-variant="' + index + '"]');
- if (!variantDiv) return null;
- const NON_VISUAL = new Set(['STYLE', 'SCRIPT', 'LINK', 'META', 'TEMPLATE']);
- const visual = [];
- for (const child of variantDiv.children) {
- if (!NON_VISUAL.has(child.tagName)) visual.push(child);
- }
- if (visual.length === 1) return visual[0];
- return variantDiv;
- }
-
- // Hold window.scrollY at a fixed value across DOM mutations inside the
- // session's wrapper (HMR patches, variant inserts, cycle swaps).
- function startScrollLock(sessionId, initialTargetY) {
- stopScrollLock();
- scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)
- ? initialTargetY
- : window.scrollY;
- console.log('[impeccable.scroll] startScrollLock', { sessionId, scrollY: window.scrollY, targetY: scrollLockTargetY, initialOverride: initialTargetY });
-
- try { history.scrollRestoration = 'manual'; } catch {}
-
- const prevHtmlAnchor = document.documentElement.style.overflowAnchor;
- const prevBodyAnchor = document.body.style.overflowAnchor;
- document.documentElement.style.overflowAnchor = 'none';
- document.body.style.overflowAnchor = 'none';
-
- const correct = (why) => {
- scrollLockRaf = null;
- if (scrollLockTargetY == null) return;
- const before = window.scrollY;
- const delta = before - scrollLockTargetY;
- if (Math.abs(delta) < 0.5) {
- console.log('[impeccable.scroll] correct noop', { why, scrollY: before, targetY: scrollLockTargetY });
- return;
- }
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] corrected', { why, from: before, to: scrollLockTargetY, delta, nowAt: window.scrollY });
- };
- const schedule = (why) => {
- if (scrollLockRaf != null) return;
- scrollLockRaf = requestAnimationFrame(() => correct(why));
- };
-
- scrollLockObserver = new MutationObserver((mutations) => {
- for (const m of mutations) {
- if (m.target?.closest?.('[data-impeccable-variants="' + sessionId + '"]')) {
- const childAdds = Array.from(m.addedNodes).map(n => n.nodeType === 1 ? (n.tagName + (n.dataset?.impeccableVariant ? ('[variant=' + n.dataset.impeccableVariant + ']') : '')) : n.nodeType).join(',');
- console.log('[impeccable.scroll] mutation inside wrapper', { type: m.type, target: m.target?.tagName, adds: childAdds, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('mutation-in-wrapper');
- return;
- }
- for (const n of m.addedNodes) {
- if (n.nodeType === 1 && (n.matches?.('[data-impeccable-variants="' + sessionId + '"]') || n.querySelector?.('[data-impeccable-variants="' + sessionId + '"]'))) {
- console.log('[impeccable.scroll] wrapper node added', { tag: n.tagName, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('wrapper-added');
- return;
- }
- }
- }
- });
- scrollLockObserver.observe(document.body, { childList: true, subtree: true });
-
- scrollLockAbort = new AbortController();
- scrollLockAbort.signal.addEventListener('abort', () => {
- document.documentElement.style.overflowAnchor = prevHtmlAnchor;
- document.body.style.overflowAnchor = prevBodyAnchor;
- }, { once: true });
- const sig = { signal: scrollLockAbort.signal };
- // Track whether the most recent scroll came from a user gesture. We
- // gate user-scroll re-anchoring on this flag so programmatic smooth
- // scrolls (browser reload-restore, scrollIntoView from other scripts)
- // don't accidentally update our target.
- let userGestureAt = 0;
- const USER_GESTURE_WINDOW_MS = 250;
-
- const reanchor = (why) => {
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- const prevTarget = scrollLockTargetY;
- scrollLockTargetY = window.scrollY;
- writeScrollY(scrollLockTargetY);
- console.log('[impeccable.scroll] reanchor', { why, prevTarget, newTarget: scrollLockTargetY });
- };
- const markGesture = (why) => {
- userGestureAt = performance.now();
- reanchor(why);
- };
- window.addEventListener('wheel', () => markGesture('wheel'), { passive: true, ...sig });
- window.addEventListener('touchstart', () => markGesture('touchstart'), { passive: true, ...sig });
- window.addEventListener('touchmove', () => markGesture('touchmove'), { passive: true, ...sig });
- window.addEventListener('keydown', (e) => {
- if (['PageDown', 'PageUp', ' ', 'End', 'Home', 'ArrowDown', 'ArrowUp'].includes(e.key)) markGesture('key:' + e.key);
- }, sig);
-
- // Correct on EVERY scroll event: whether it's the browser's
- // post-reload animated restore or some other script calling
- // scrollIntoView, we want to snap back immediately. Only skip if a
- // user gesture fired in the last 250ms.
- let lastLoggedScrollY = window.scrollY;
- window.addEventListener('scroll', () => {
- const now = window.scrollY;
- if (Math.abs(now - lastLoggedScrollY) > 5) {
- console.log('[impeccable.scroll] scroll event', { from: lastLoggedScrollY, to: now, targetY: scrollLockTargetY });
- lastLoggedScrollY = now;
- }
- if (scrollLockTargetY == null) return;
- if (performance.now() - userGestureAt < USER_GESTURE_WINDOW_MS) return;
- if (Math.abs(now - scrollLockTargetY) < 0.5) return;
- console.log('[impeccable.scroll] scroll-event snap', { from: now, to: scrollLockTargetY });
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- }, { passive: true, ...sig });
-
- // Apply target synchronously, not via rAF — racing the browser's
- // restore or a smooth-scroll animation means we want to win now.
- if (Math.abs(window.scrollY - scrollLockTargetY) > 0.5) {
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] startScrollLock initial apply', { to: scrollLockTargetY });
- }
- }
-
- function stopScrollLock() {
- if (scrollLockObserver) { scrollLockObserver.disconnect(); scrollLockObserver = null; }
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }
- scrollLockTargetY = null;
- // NOTE: do NOT clear the persistent scroll key here. startScrollLock
- // calls us as a reset, and clearing the key would nuke the Go-time
- // scrollY that the next resume needs to read.
- }
-
- // ---------------------------------------------------------------------------
- // MutationObserver for progressive variant reveal
- // ---------------------------------------------------------------------------
-
- function startVariantObserver(sessionId) {
- let updating = false; // re-entrancy guard
-
- const obs = new MutationObserver((mutations) => {
- if (updating) return;
-
- // Only react to mutations that add nodes with data-impeccable-variant,
- // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
- let dominated = false;
- for (const m of mutations) {
- if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
- for (const n of m.addedNodes) {
- if (n.nodeType !== 1) continue;
- // Direct hit: the added node itself is the wrapper or a variant.
- if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
- dominated = true; break;
- }
- // Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
- // a whole subtree where the wrapper is a descendant of the added
- // node. Without this check, the observer ignores those mutations
- // and the session stays in GENERATING forever.
- if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
- dominated = true; break;
- }
- }
- if (dominated) break;
- }
- if (!dominated) return;
-
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
-
- // Re-anchor selectedElement if it was detached by live-wrap's HMR swap.
- // Without this, the shader / highlight / bar track a zero-rect phantom
- // and the overlay appears frozen.
- if (selectedElement && !document.body.contains(selectedElement)) {
- selectedElement = pickVariantContent(wrapper, 'original') || wrapper;
- }
-
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- const count = variants.length;
-
- // Nothing new
- if (count <= arrivedVariants) return;
-
- updating = true;
- arrivedVariants = count;
- if (visibleVariant === 0 && arrivedVariants > 0) {
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;
- showVariantInDOM(sessionId, visibleVariant);
- // showVariantInDOM hid the original (display:none); if we were still
- // anchored to the original's content, its boundingRect is now zero
- // and the bar snaps to (0,0). Re-point at the visible variant instead.
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- if (expected > 0) expectedVariants = expected;
-
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- } else if (state === 'GENERATING') {
- updateBarContent('generating');
- }
- saveSession();
- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');
- updating = false;
- });
-
- obs.observe(document.body, { childList: true, subtree: true });
- return obs;
- }
-
- // ---------------------------------------------------------------------------
- // Bar scroll tracking
- // ---------------------------------------------------------------------------
-
- function startScrollTracking() {
- function tick() {
- if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
- positionBar();
- showHighlight(selectedElement);
- if (tuneOpen) positionParamsPanel();
- }
- if (annotActive) positionAnnotOverlay(selectedElement);
- // Shader overlay (via debug P toggle or generation) is repositioned
- // by its own branch below; debug no longer has a separate overlay.
- if (shaderState) positionShaderOverlay();
- scrollRaf = requestAnimationFrame(tick);
- }
- scrollRaf = requestAnimationFrame(tick);
- }
-
- function stopScrollTracking() {
- if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
- }
-
- // ---------------------------------------------------------------------------
- // SSE (server→browser) + fetch POST (browser→server)
- // Zero-dependency replacement for WebSocket.
- // ---------------------------------------------------------------------------
-
- let evtSource = null;
- let sseRetries = 0;
- const SSE_MAX_RETRIES = 20; // generous: heartbeats keep the connection alive, so retries mean real trouble
-
- function connectSSE() {
- evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
-
- evtSource.onopen = () => {
- sseRetries = 0; // reset on successful (re)connect
- };
-
- evtSource.onmessage = (e) => {
- sseRetries = 0; // reset on any successful message
- let msg; try { msg = JSON.parse(e.data); } catch { return; }
- switch (msg.type) {
- case 'connected':
- hasProjectContext = !!msg.hasProjectContext;
- if (!hasProjectContext) showToast('No PRODUCT.md found. Variants will be brand-agnostic. Run /impeccable teach to generate one.', 7000);
- console.log('[impeccable] Live mode connected.');
- if (state === 'IDLE') state = 'PICKING';
- break;
- case 'done':
- // Variants already arrived via HMR → normal transition.
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- if (state === 'GENERATING') {
- state = 'CYCLING';
- updateBarContent('cycling');
- refreshParamsPanel();
- }
- break;
- }
- // Variants are in source but not in the DOM yet. Common when the
- // picked element lived inside conditional render (closed modal,
- // hidden tab, a route the user navigated away from). The variant
- // MutationObserver stays armed and auto-transitions to CYCLING
- // the moment the wrapper actually mounts. Nudge the user toward
- // that path with a toast — better than the prior force-reload
- // which reset framework state and left the session stuck.
- setTimeout(() => {
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
- if (state !== 'GENERATING') return;
- showToast(
- "Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
- 15000,
- );
- }, 2000);
- break;
- case 'error':
- console.error('[impeccable] Error:', msg.message);
- showToast('Error: ' + msg.message, 5000);
- hideBar();
- state = 'PICKING';
- break;
- }
- };
-
- evtSource.onerror = () => {
- sseRetries++;
- if (sseRetries <= SSE_MAX_RETRIES) {
- console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
- return; // EventSource auto-reconnects
- }
- // Server is gone. Clean up gracefully.
- console.log('[impeccable] Live server unreachable. Cleaning up UI.');
- evtSource.close();
- evtSource = null;
- handleServerLost();
- };
- }
-
- /** Server died or became unreachable. Reset UI to a clean state. */
- function handleServerLost() {
- const recoveryState = currentSessionId ? state : 'IDLE';
- if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
- showToast('Live server disconnected. Session ended.', 5000);
- }
- hideBar();
- hideHighlight();
- hideShaderOverlay();
- hideAnnotOverlay();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- // Preserve local session state on server loss. The durable journal is the
- // source of truth, but localStorage plus the variant wrapper lets the UI
- // resume after a helper restart or page reload instead of treating a
- // transient disconnect as an explicit discard.
- selectedElement = null;
- selectedAction = 'impeccable';
- state = recoveryState;
- if (currentSessionId) saveSession();
- }
-
- function sendEvent(msg, opts) {
- msg.token = TOKEN;
- function handleFailure(err) {
- console.error('[impeccable] Failed to send event:', err);
- if (opts && opts.throwOnError) throw err;
- return null;
- }
- return fetch('http://localhost:' + PORT + '/events', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(msg),
- }).then(res => {
- if (res.ok) return res;
- return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));
- }).catch(handleFailure);
- }
-
- function checkpointPayload(reason) {
- return {
- type: 'checkpoint',
- id: currentSessionId,
- revision: sessionState.nextCheckpointRevision(),
- owner: browserOwner,
- phase: String(state || '').toLowerCase(),
- reason,
- pageUrl: location.pathname,
- expectedVariants,
- arrivedVariants,
- visibleVariant,
- paramValues: { ...paramsCurrentValues },
- };
- }
-
- function sendCheckpoint(reason) {
- if (!currentSessionId) return Promise.resolve(null);
- return sendEvent(checkpointPayload(reason)).catch(() => null);
- }
-
- function queueCheckpoint(reason) {
- if (!currentSessionId) return;
- if (checkpointTimer) clearTimeout(checkpointTimer);
- checkpointTimer = setTimeout(() => {
- checkpointTimer = null;
- sendCheckpoint(reason);
- }, 120);
- }
-
- // ---------------------------------------------------------------------------
- // Event handlers
- // ---------------------------------------------------------------------------
-
- function handleMouseMove(e) {
- if (state !== 'PICKING' || !pickActive) return;
- const target = document.elementFromPoint(e.clientX, e.clientY);
- if (!target || !pickable(target) || target === hoveredElement) return;
- hoveredElement = target;
- showHighlight(target);
- }
-
- function handleClick(e) {
- // Close action picker on any outside click
- if (pickerEl?.style.display !== 'none' && !own(e.target)) {
- hideActionPicker();
- }
- // Close Tune popover on outside click (anything outside panel + bar)
- if (tuneOpen && paramsPanelEl && !paramsPanelEl.contains(e.target) && barEl && !barEl.contains(e.target)) {
- closeTunePopover();
- }
- // In CONFIGURING: click outside the bar and selected element returns to PICKING
- if (state === 'CONFIGURING' && !own(e.target) && selectedElement && !selectedElement.contains(e.target)) {
- hideBar();
- stopScrollTracking();
- hideAnnotOverlay();
- clearAnnotations();
- state = 'PICKING';
- hoveredElement = null;
- hideHighlight();
- return;
- }
- if (state !== 'PICKING' || !pickActive) return;
- if (own(e.target)) return;
- if (!hoveredElement || !pickable(hoveredElement)) return;
- e.preventDefault();
- e.stopPropagation();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- maybePrefetchPage();
- maybeWarnConditionalAncestor(selectedElement);
- }
-
- /**
- * Surface a brief, non-blocking heads-up when the picked element lives
- * inside a container whose visibility is gated by ephemeral state — modals,
- * collapsible panels, popovers, off-screen tab panels. If HMR remounts the
- * parent during generation (Vite Fast Refresh, SvelteKit page reload), the
- * variants land in source but stay invisible until the user re-opens the
- * container. Telling the user upfront is much friendlier than the silent
- * timeout-then-toast that they'd otherwise hit.
- *
- * Heuristic, intentionally narrow — only fires for unambiguous cases so
- * we don't cry wolf on every nested element.
- */
- function maybeWarnConditionalAncestor(el) {
- let node = el?.parentElement;
- let depth = 0;
- while (node && depth < 12) {
- // 1. Active dialog / modal
- if (node.getAttribute && node.getAttribute('role') === 'dialog'
- && node.getAttribute('aria-modal') === 'true') {
- showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 2. Common Radix / shadcn / headless-ui open-state attribute
- if (node.dataset && node.dataset.state === 'open') {
- showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 3. Tab panel — only meaningful when the page also shows ANOTHER
- // tab as selected. A single tabpanel with no tablist is just a static
- // section in disguise and isn't conditional.
- if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
- const list = document.querySelector('[role="tablist"]');
- if (list) {
- const tabs = list.querySelectorAll('[role="tab"]');
- if (tabs.length > 1) {
- showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
- return;
- }
- }
- }
- // 4. Collapsible: aria-expanded sibling. Look for the trigger button.
- if (node.id) {
- const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
- if (trigger) {
- showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
- return;
- }
- }
- node = node.parentElement;
- depth++;
- }
- }
-
- // Fire a lightweight prefetch event the first time the user selects an
- // element on a given route. The agent uses this to Read the underlying file
- // into context before Go is hit, shaving the read off the critical path.
- // Dedupe per session by pathname — clicking around on the same page doesn't
- // re-fire.
- //
- // DISABLED: quick-Go workflows pay an extra harness round trip because
- // prefetch + generate arrive as two events instead of one. Re-enable with
- // a browser-side debounce (~800–1000ms, cancelled on Go) if we want to
- // resurrect this. Server validator and skill dispatch remain in place so
- // flipping this flag is the only change needed.
- const PREFETCH_ENABLED = false;
- const prefetchedPaths = new Set();
- function maybePrefetchPage() {
- if (!PREFETCH_ENABLED) return;
- const path = location.pathname;
- if (prefetchedPaths.has(path)) return;
- prefetchedPaths.add(path);
- sendEvent({ type: 'prefetch', pageUrl: path });
- }
-
- function handleKeyDown(e) {
- // When the annotation input is focused, let it handle its own keys.
- if (annotEditing && annotEditing.input && e.target === annotEditing.input) return;
- if (e.key === 'Escape') {
- e.preventDefault();
- if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
- if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); hideAnnotOverlay(); clearAnnotations(); state = 'PICKING'; return; }
- if (state === 'CYCLING') { handleDiscard(); return; }
- if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
- if (state === 'PICKING') {
- // Use togglePick so the "Pick" button in the global bar also flips
- // off, otherwise the bar stays lit while nothing else is active.
- if (pickActive) togglePick();
- else { hideHighlight(); state = 'IDLE'; }
- return;
- }
- }
-
- // Arrow/Enter nav works in PICKING (hover) and CONFIGURING (selected, input empty)
- var navEl = (state === 'PICKING') ? hoveredElement : (state === 'CONFIGURING') ? selectedElement : null;
- if (navEl && (e.key === 'ArrowUp' || e.key === 'ArrowDown' || (e.key === 'Enter' && state === 'PICKING'))) {
- let next = null;
- if (e.key === 'ArrowDown' && !e.shiftKey) {
- next = navEl.nextElementSibling;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'ArrowUp' && !e.shiftKey) {
- next = navEl.previousElementSibling;
- while (next && !pickable(next)) next = next.previousElementSibling;
- } else if (e.key === 'ArrowUp' && e.shiftKey) {
- next = navEl.parentElement;
- if (next && !pickable(next)) next = null;
- } else if (e.key === 'ArrowDown' && e.shiftKey) {
- next = navEl.firstElementChild;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'Enter') {
- e.preventDefault();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- return;
- }
- if (next) {
- e.preventDefault();
- if (state === 'PICKING') {
- hoveredElement = next;
- } else {
- // CONFIGURING: re-select the new element and refresh the bar
- selectedElement = next;
- clearAnnotations();
- showAnnotOverlay(next);
- showBar('configure');
- startScrollTracking();
- }
- showHighlight(next);
- next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
- }
- return;
- }
-
- if (state === 'CYCLING') {
- if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
- if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
- if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
- }
- }
-
- function handleGo() {
- if (!selectedElement || state !== 'CONFIGURING') return;
- const input = document.getElementById(PREFIX + '-input');
- const prompt = input ? input.value.trim() : '';
-
- // Commit any pending pin edit BEFORE we snapshot annotations.
- if (annotEditing) finalizeEditingPin();
-
- currentSessionId = id8();
- expectedVariants = selectedCount;
- arrivedVariants = 0;
- visibleVariant = 0;
-
- // Flip to GENERATING immediately so the bar morphs without waiting on
- // capture + upload. The event is emitted from captureAndEmit() once the
- // screenshot is uploaded (or capture fails — we still emit, just without
- // screenshotPath).
- const elForCapture = selectedElement;
- const captureRect = elForCapture.getBoundingClientRect();
- const snapshot = {
- comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),
- strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),
- };
- const basePayload = {
- type: 'generate', id: currentSessionId,
- action: selectedAction,
- freeformPrompt: prompt || undefined,
- count: selectedCount,
- pageUrl: location.pathname,
- element: extractContext(elForCapture),
- };
- if (snapshot.comments.length > 0) basePayload.comments = snapshot.comments;
- if (snapshot.strokes.length > 0) basePayload.strokes = snapshot.strokes;
-
- // Hide the interactive overlay so it doesn't linger during generation.
- hideAnnotOverlay();
- clearAnnotations();
-
- state = 'GENERATING';
- showBar('generating');
- saveSession();
- sendCheckpoint('generate_started');
- writeScrollY(window.scrollY);
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
- console.log('[impeccable.scroll] Go pressed', { scrollY: window.scrollY, sessionId: currentSessionId });
- startScrollLock(currentSessionId);
-
- captureAndEmit(elForCapture, basePayload, snapshot, captureRect);
- }
-
- // ---------------------------------------------------------------------------
- // Screenshot capture + upload
- // ---------------------------------------------------------------------------
-
- let msLoadPromise = null;
- function loadModernScreenshot() {
- if (window.modernScreenshot) return Promise.resolve(window.modernScreenshot);
- if (msLoadPromise) return msLoadPromise;
- msLoadPromise = new Promise((resolve, reject) => {
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/modern-screenshot.js';
- s.onload = () => resolve(window.modernScreenshot);
- s.onerror = () => { msLoadPromise = null; reject(new Error('modern-screenshot failed to load')); };
- document.head.appendChild(s);
- });
- return msLoadPromise;
- }
-
- // Collect @font-face rules from every stylesheet on the page. Cross-origin
- // sheets (Google Fonts, Typekit, etc.) throw SecurityError on .cssRules
- // access, so modern-screenshot can't embed them on its own — the resulting
- // SVG falls back to system fonts and text re-wraps + renders with different
- // weight. We fetch the raw CSS text (CORS-permitted for these providers),
- // extract @font-face blocks, inline the referenced font files as base64
- // data URIs (SVGs rasterized via canvas can't fetch external resources,
- // so URLs inside the SVG silently fail without this), and pass the result
- // to modern-screenshot as font.cssText.
- const FONT_EXT_RE = /\.(woff2?|ttf|otf|eot)(\?.*)?$/i;
- const FONT_MIME = {
- woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', eot: 'application/vnd.ms-fontobject',
- };
- function bufferToBase64(buf) {
- const bytes = new Uint8Array(buf);
- let binary = '';
- const CHUNK = 0x8000;
- for (let i = 0; i < bytes.length; i += CHUNK) {
- binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
- }
- return btoa(binary);
- }
- async function inlineFontUrls(cssText) {
- const urlRe = /url\((['"]?)(https?:\/\/[^'")\s]+)\1\)/g;
- const urls = new Set();
- let m;
- while ((m = urlRe.exec(cssText))) {
- if (FONT_EXT_RE.test(m[2])) urls.add(m[2]);
- }
- const map = new Map();
- await Promise.all([...urls].map(async (url) => {
- try {
- const res = await fetch(url);
- if (!res.ok) return;
- const buf = await res.arrayBuffer();
- const ext = url.toLowerCase().match(FONT_EXT_RE)?.[1] || 'woff2';
- const mime = FONT_MIME[ext] || 'application/octet-stream';
- map.set(url, 'data:' + mime + ';base64,' + bufferToBase64(buf));
- } catch { /* skip; fall through to URL */ }
- }));
- return cssText.replace(urlRe, (orig, q, url) => {
- const data = map.get(url);
- return data ? 'url(' + q + data + q + ')' : orig;
- });
- }
- async function collectFontCssText() {
- const chunks = [];
- const fontFaceRe = /@font-face\s*\{[^}]*\}/g;
- for (const sheet of document.styleSheets) {
- try {
- const rules = sheet.cssRules;
- for (const rule of rules) {
- if (rule.constructor.name === 'CSSFontFaceRule' || rule.cssText?.startsWith('@font-face')) {
- chunks.push(rule.cssText);
- }
- }
- } catch {
- if (!sheet.href) continue;
- try {
- const res = await fetch(sheet.href);
- if (!res.ok) continue;
- const text = await res.text();
- let m2;
- while ((m2 = fontFaceRe.exec(text))) chunks.push(m2[0]);
- } catch { /* ignore; capture is best-effort */ }
- }
- }
- if (chunks.length === 0) return '';
- return inlineFontUrls(chunks.join('\n'));
- }
-
- // True if `s` is a computed color string that renders as nothing
- // (explicit `transparent`, or `rgba(...)` with alpha 0).
- function isTransparentColor(s) {
- if (!s) return true;
- if (s === 'transparent') return true;
- const m = /rgba?\(([^)]+)\)/.exec(s);
- if (!m) return false;
- const parts = m[1].split(',').map((p) => p.trim());
- if (parts.length === 4) return parseFloat(parts[3]) === 0;
- return false;
- }
-
- // modern-screenshot force-sets `background-color: X !important` on the
- // cloned root whenever `backgroundColor` is passed, clobbering the
- // element's own background. So we only pass it when the element is
- // genuinely transparent (no own color, no own image) — in that case
- // we resolve up the DOM to the nearest opaque ancestor so the capture
- // sits on the page's real background instead of rendering black.
- function resolveCanvasBackground(el) {
- const own = getComputedStyle(el);
- if (!isTransparentColor(own.backgroundColor)) return null;
- if (own.backgroundImage && own.backgroundImage !== 'none') return null;
- let node = el.parentElement;
- while (node) {
- const cs = getComputedStyle(node);
- if (!isTransparentColor(cs.backgroundColor)) return cs.backgroundColor;
- node = node.parentElement;
- }
- // The walk already passed through <body> and <html>; if they had been
- // opaque we would have returned. Falling through with the previous
- // `getComputedStyle(body).backgroundColor || …` chain is a trap: that
- // call returns the literal string `"rgba(0, 0, 0, 0)"` for a page that
- // never set its own bg, which is truthy and short-circuits the chain to
- // transparent-black — modern-screenshot then renders the capture on a
- // black canvas and the shader overlay flashes solid black during load.
- // The browser canvas defaults to white, so we do too.
- return '#ffffff';
- }
-
- // Capture the element (with current annotations baked in) and return a PNG
- // Blob. Shared between the Go flow (uploads it to the server) and the
- // debug toggle (displays it as an overlay for side-by-side comparison).
- async function captureElementToBlob(el, snapshot, rect) {
- try { if (document.fonts?.ready) await document.fonts.ready; } catch {}
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- let annotNode = null;
- let savedPosition = null;
- if (hasAnnotations) {
- const pos = getComputedStyle(el).position;
- if (pos === 'static') {
- savedPosition = el.style.position;
- el.style.position = 'relative';
- }
- annotNode = buildAnnotationsForCapture(rect, snapshot);
- el.appendChild(annotNode);
- }
- try {
- const ms = await loadModernScreenshot();
- const fontCssText = await collectFontCssText();
- const backgroundColor = resolveCanvasBackground(el);
- return await ms.domToBlob(el, {
- scale: Math.min(window.devicePixelRatio || 1, 2),
- font: fontCssText ? { cssText: fontCssText } : undefined,
- ...(backgroundColor ? { backgroundColor } : {}),
- });
- } finally {
- if (annotNode) annotNode.remove();
- if (savedPosition !== null) el.style.position = savedPosition;
- }
- }
-
- async function captureAndEmit(el, basePayload, snapshot, rect) {
- let screenshotPath;
- let blob;
- try {
- blob = await captureElementToBlob(el, snapshot, rect);
- } catch (err) {
- console.warn('[impeccable] capture failed, proceeding without screenshot:', err);
- }
- // Light up the shader overlay the moment capture is ready — no reason to
- // wait for the upload to complete before the user sees something alive.
- if (blob && state === 'GENERATING') {
- showShaderOverlay(el, blob, rect);
- }
- // Only upload + forward the screenshot when annotations (comments/strokes)
- // are present. Without annotations the image is pure visual anchoring —
- // it biases the model toward the current rendering and works against the
- // three-distinct-directions brief.
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- if (blob && hasAnnotations) {
- try {
- const uploadRes = await fetch(
- 'http://localhost:' + PORT + '/annotation?token=' + encodeURIComponent(TOKEN) +
- '&eventId=' + encodeURIComponent(basePayload.id),
- { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: blob },
- );
- if (uploadRes.ok) {
- const { path: p } = await uploadRes.json();
- screenshotPath = p;
- } else {
- console.warn('[impeccable] annotation upload failed:', uploadRes.status);
- }
- } catch (err) {
- console.warn('[impeccable] annotation upload failed:', err);
- }
- }
- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);
- }
-
- // ---------------------------------------------------------------------------
- // Shader overlay — renders the captured screenshot as a WebGL texture and
- // runs an editorial "ink-wash" fragment shader over it during generation.
- // A single rolling band sweeps top-to-bottom, desaturating + tinting magenta
- // and leaving a soft trail. Makes the wait feel like a letterpress scan
- // instead of a dead spinner.
- // ---------------------------------------------------------------------------
-
- const SHADER_VS = `attribute vec2 a_position;
-attribute vec2 a_uv;
-varying vec2 v_uv;
-void main() {
- v_uv = a_uv;
- gl_Position = vec4(a_position, 0.0, 1.0);
-}`;
-
- const SHADER_FS = `precision highp float;
-uniform sampler2D u_texture;
-uniform float u_time;
-uniform vec2 u_resolution;
-uniform vec3 u_accent;
-varying vec2 v_uv;
-
-// Asymmetric roller band. Product of two one-sided smoothsteps — peaks at
-// d=0 with a short sharp leading ramp and a longer soft trailing tail. Clean
-// outside the [-leadW, trailW] range (no rogue "trail=1 everywhere below"
-// failure that reversed-edge smoothstep would give).
-float bandAt(float d, float leadW, float trailW) {
- float above = smoothstep(-leadW, 0.0, d);
- float below = 1.0 - smoothstep(0.0, trailW, d);
- return above * below;
-}
-
-void main() {
- vec2 uv = v_uv;
- // Roller sweeps top-to-bottom with small overshoot so each cycle enters
- // and exits the element cleanly.
- float phase = fract(u_time / 3.4);
- float y = phase * 1.25 - 0.12;
- float band = bandAt(uv.y - y, 0.05, 0.32);
-
- // Halftone cell grid (fixed ~10 px pitch).
- float cellPx = 10.0;
- vec2 gridUv = uv * u_resolution / cellPx;
- vec2 cellId = floor(gridUv);
- vec2 cellUv = fract(gridUv) - 0.5;
- vec2 sampleCenter = (cellId + 0.5) * cellPx / u_resolution;
- vec3 cellImg = texture2D(u_texture, sampleCenter).rgb;
- float luma = dot(cellImg, vec3(0.299, 0.587, 0.114));
- // Darker cells → bigger magenta dots (classic risograph halftone curve).
- float radius = sqrt(clamp(1.0 - luma, 0.0, 1.0)) * 0.56;
- float dotMask = smoothstep(radius + 0.06, radius, length(cellUv));
- vec3 paper = vec3(0.975, 0.965, 0.955);
- vec3 dotLayer = mix(paper, u_accent, dotMask);
-
- // Blend the halftone layer in where the roller is passing; leave the
- // element pristine elsewhere.
- vec3 base = texture2D(u_texture, uv).rgb;
- gl_FragColor = vec4(mix(base, dotLayer, band), 1.0);
-}`;
-
- // Editorial Magenta converted to approximate sRGB 0-1 (matches oklch(60% 0.25 350))
- const SHADER_ACCENT = [0.82, 0.16, 0.47];
- let shaderState = null; // { canvas, gl, program, texture, rafId, startTime }
-
- function compileShader(gl, type, source) {
- const sh = gl.createShader(type);
- gl.shaderSource(sh, source);
- gl.compileShader(sh);
- if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
- const info = gl.getShaderInfoLog(sh);
- gl.deleteShader(sh);
- throw new Error('shader compile failed: ' + info);
- }
- return sh;
- }
-
- function positionShaderOverlay() {
- if (!shaderState || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- Object.assign(shaderState.canvas.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- }
-
- function hideShaderOverlay() {
- if (!shaderState) return;
- if (shaderState.rafId) cancelAnimationFrame(shaderState.rafId);
- if (shaderState.canvas) shaderState.canvas.remove();
- const lose = shaderState.gl?.getExtension?.('WEBGL_lose_context');
- try { lose?.loseContext(); } catch {}
- shaderState = null;
- }
-
- async function showShaderOverlay(el, blob, rect) {
- hideShaderOverlay();
- if (!blob || !el) return;
- const canvas = document.createElement('canvas');
- canvas.id = PREFIX + '-shader';
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
- canvas.width = Math.max(1, Math.floor(rect.width * dpr));
- canvas.height = Math.max(1, Math.floor(rect.height * dpr));
- Object.assign(canvas.style, {
- position: 'fixed',
- top: rect.top + 'px', left: rect.left + 'px',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none',
- zIndex: Z.bar - 1,
- });
- document.body.appendChild(canvas);
-
- const gl = canvas.getContext('webgl', { premultipliedAlpha: false, preserveDrawingBuffer: false })
- || canvas.getContext('experimental-webgl');
- if (!gl) {
- // WebGL unavailable — fall back to a plain <img> overlay so the user
- // still sees something meaningful during generation.
- canvas.remove();
- const img = document.createElement('img');
- img.src = URL.createObjectURL(blob);
- img.id = PREFIX + '-shader';
- // Copy positioning via cssText. Object.assign across CSSStyleDeclaration
- // throws in modern Chromium because the source's indexed properties
- // (style[0], [1], ...) are read-only and the engine forbids writing
- // them on the destination.
- img.style.cssText = canvas.style.cssText;
- img.style.outline = '2px dashed ' + C.brand;
- img.style.outlineOffset = '-2px';
- document.body.appendChild(img);
- shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
- return;
- }
-
- let program, texture;
- try {
- const vs = compileShader(gl, gl.VERTEX_SHADER, SHADER_VS);
- const fs = compileShader(gl, gl.FRAGMENT_SHADER, SHADER_FS);
- program = gl.createProgram();
- gl.attachShader(program, vs);
- gl.attachShader(program, fs);
- gl.linkProgram(program);
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- throw new Error('program link failed: ' + gl.getProgramInfoLog(program));
- }
- // Full-screen quad
- const buf = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
- -1, -1, 0, 1,
- 1, -1, 1, 1,
- -1, 1, 0, 0,
- -1, 1, 0, 0,
- 1, -1, 1, 1,
- 1, 1, 1, 0,
- ]), gl.STATIC_DRAW);
- const posLoc = gl.getAttribLocation(program, 'a_position');
- const uvLoc = gl.getAttribLocation(program, 'a_uv');
- gl.enableVertexAttribArray(posLoc);
- gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 16, 0);
- gl.enableVertexAttribArray(uvLoc);
- gl.vertexAttribPointer(uvLoc, 2, gl.FLOAT, false, 16, 8);
- } catch (err) {
- console.warn('[impeccable] shader setup failed:', err);
- canvas.remove();
- return;
- }
-
- // Upload the screenshot as a texture
- let bitmap;
- try {
- bitmap = await createImageBitmap(blob);
- } catch {
- // Safari fallback: go via a regular Image
- const imgUrl = URL.createObjectURL(blob);
- const img = new Image();
- img.src = imgUrl;
- await new Promise((r, rej) => { img.onload = r; img.onerror = rej; });
- bitmap = img;
- URL.revokeObjectURL(imgUrl);
- }
- texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
- if (bitmap.close) bitmap.close();
-
- const uTime = gl.getUniformLocation(program, 'u_time');
- const uRes = gl.getUniformLocation(program, 'u_resolution');
- const uAccent = gl.getUniformLocation(program, 'u_accent');
- const uTex = gl.getUniformLocation(program, 'u_texture');
- const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-
- shaderState = { canvas, gl, program, texture, rafId: 0, startTime: performance.now(), reduced };
- function frame() {
- if (!shaderState) return;
- const elapsed = (performance.now() - shaderState.startTime) / 1000;
- const t = shaderState.reduced ? 0.0 : elapsed;
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.useProgram(program);
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.uniform1i(uTex, 0);
- gl.uniform1f(uTime, t);
- gl.uniform2f(uRes, canvas.width, canvas.height);
- gl.uniform3f(uAccent, SHADER_ACCENT[0], SHADER_ACCENT[1], SHADER_ACCENT[2]);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- shaderState.rafId = requestAnimationFrame(frame);
- }
- frame();
- }
-
- function handleAccept() {
- if (!currentSessionId || arrivedVariants === 0) return;
- const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);
- if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;
- const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };
- if (Object.keys(paramsCurrentValues).length > 0) {
- acceptPayload.paramValues = { ...paramsCurrentValues };
- }
- // The accepted variant is already the only visible child of the wrapper
- // (all other variants are display:none). HMR from the source rewrite will
- // replace the wrapper imminently. Don't eagerly replaceChild here — React
- // reconciliation races with our mutation and throws NotFoundError in Next
- // 16 / Turbopack. Schedule a fallback that runs the manual swap only if
- // HMR hasn't cleaned up by then (keeps static-server flows working).
- const acceptedSessionId = currentSessionId;
- const acceptedVariant = visibleVariant;
-
- state = 'SAVING';
- updateBarContent('saving');
-
- sendEvent(acceptPayload, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- confirmAcceptAfterReceipt();
- })
- .catch(() => {
- state = 'CYCLING';
- updateBarContent('cycling');
- showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);
- });
-
- function confirmAcceptAfterReceipt() {
- state = 'CONFIRMED';
- updateBarContent('confirmed');
- scheduleAcceptCleanup();
- }
-
- function scheduleAcceptCleanup() {
- setTimeout(function() {
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }, 1800);
-
- // Static-server / no-HMR fallback: if the wrapper is still around 2s after
- // the cleanup above, swap it out manually. By now React has either moved
- // on or the app isn't React at all. Preserve the `data-impeccable-variant="N"`
- // div (with display:contents) so @scope rules anchored to the variant
- // attribute keep matching until reload replaces it with the carbonize block.
- setTimeout(function() {
- const wrapper = document.querySelector('[data-impeccable-variants="' + acceptedSessionId + '"]');
- if (!wrapper) return;
- const accepted = wrapper.querySelector('[data-impeccable-variant="' + acceptedVariant + '"]');
- if (accepted && accepted.firstElementChild) {
- const parent = wrapper.parentElement;
- if (!parent) return;
- accepted.style.display = 'contents';
- parent.replaceChild(accepted, wrapper);
- }
- }, 2000);
- }
- }
-
- function handleDiscard() {
- if (!currentSessionId) return;
- sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- cleanup();
- })
- .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));
- }
-
- // ---------------------------------------------------------------------------
- // Session persistence via live-browser-session.js
- // ---------------------------------------------------------------------------
- // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
-
- function saveSession() {
- if (!currentSessionId) return;
- // NOTE: scrollY is stored under a separate key (writeScrollY). Storing
- // it here would overwrite the Go-time value every time state changes.
- sessionState.saveSession({
- id: currentSessionId,
- state,
- action: selectedAction,
- count: selectedCount,
- expected: expectedVariants,
- arrived: arrivedVariants,
- visible: visibleVariant,
- });
- }
-
- function loadSession() {
- return sessionState.loadSession();
- }
-
- function clearSession() {
- sessionState.clearSession();
- }
-
- /** Mark session as handled (accepted/discarded). The agent will clean up
- * the source, but until it does the wrapper is still in the HTML. This
- * prevents resumeSession from picking it up again after reload. */
- function markSessionHandled() {
- if (!currentSessionId) return;
- sessionState.markHandled(currentSessionId);
- }
-
- function isSessionHandled(id) {
- return sessionState.isHandled(id);
- }
-
- function clearHandled() {
- sessionState.clearHandled();
- }
-
- function cleanup() {
- // Hide the wrapper immediately so variants disappear. DON'T structurally
- // mutate the DOM yet — HMR from the agent's source rewrite is on its way,
- // and a manual replaceChild under React causes NotFoundError when the
- // reconciler later tries to remove a wrapper we already removed.
- // Schedule a 2s fallback that does the manual swap only if HMR hasn't
- // replaced the wrapper by then (keeps static-server / no-HMR flows alive).
- const cleanupSessionId = currentSessionId;
- if (cleanupSessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (wrapper) wrapper.style.display = 'none';
- }
- setTimeout(function() {
- if (!cleanupSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (!wrapper) return;
- const orig = wrapper.querySelector('[data-impeccable-variant="original"]');
- if (orig) {
- const content = orig.firstElementChild;
- if (content) {
- wrapper.parentElement.replaceChild(content, wrapper);
- return;
- }
- }
- wrapper.remove();
- }, 2000);
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }
-
- // ---------------------------------------------------------------------------
- // Toast
- // ---------------------------------------------------------------------------
-
- function showToast(message, duration) {
- if (toastEl) toastEl.remove();
- // Stack the toast above the global bar (which sits at bottom:14px) so
- // the two never overlap. Read the bar's actual rect — its height varies
- // with hover-expanded labels — and fall back to a sensible default
- // when the bar isn't mounted yet.
- const barRect = globalBarEl?.getBoundingClientRect();
- const barTopFromBottom = barRect && barRect.height > 0
- ? Math.max(16, window.innerHeight - barRect.top + 12)
- : 16;
- toastEl = el('div', {
- position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
- transform: 'translateX(-50%) translateY(8px)',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px',
- padding: '8px 16px', borderRadius: '8px',
- zIndex: Z.toast, opacity: '0',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
- pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
- });
- toastEl.id = PREFIX + '-toast';
- toastEl.textContent = message;
- document.body.appendChild(toastEl);
- requestAnimationFrame(() => {
- toastEl.style.opacity = '1';
- toastEl.style.transform = 'translateX(-50%) translateY(0)';
- });
- setTimeout(() => {
- if (toastEl) {
- toastEl.style.opacity = '0';
- toastEl.style.transform = 'translateX(-50%) translateY(8px)';
- setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
- }
- }, duration);
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- // Resume an active variant session after HMR/page reload.
- // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
- // variants before HMR fired. Pick up where we left off.
- function resumeSession() {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) { clearSession(); clearHandled(); return false; }
-
- const sessionId = wrapper.dataset.impeccableVariants;
-
- // Don't resume if this session was already accepted/discarded
- if (isSessionHandled(sessionId)) return false;
-
- currentSessionId = sessionId;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
-
- // Restore state from localStorage if available
- const saved = loadSession();
- if (saved && saved.id === sessionId) {
- visibleVariant = (saved.visible > 0 && saved.visible <= arrivedVariants) ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
- if (saved.action) selectedAction = saved.action;
- if (saved.count) selectedCount = saved.count;
- } else {
- visibleVariant = arrivedVariants > 0 ? 1 : 0;
- }
-
- // Find the visible variant's content element for highlight positioning.
- // Try the visible variant first, fall back to the original's content.
- const visEl = visibleVariant > 0 ? pickVariantContent(wrapper, visibleVariant) : null;
- const origEl = pickVariantContent(wrapper, 'original');
- selectedElement = visEl || origEl || wrapper.parentElement;
-
- // Set display state BEFORE starting observer (avoid triggering it)
- if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
-
- state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
- showBar(state === 'CYCLING' ? 'cycling' : 'generating');
- startScrollTracking();
- // Build the params panel for the restored visible variant. Previously
- // this was missed on page-reload resume: showVariantInDOM above fires
- // refreshParamsPanel, but state was still IDLE at that moment so it
- // hid. Now that state is CYCLING, re-fire.
- if (state === 'CYCLING') refreshParamsPanel();
- saveSession();
- queueCheckpoint('browser_resumed');
-
- // Start observing for more variants AFTER initial setup
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
-
- // Hold the target at its saved viewport top through any subsequent
- // HMR patches, variant inserts, or cycle swaps.
- startScrollLock(currentSessionId, readScrollY());
-
- // If we reloaded mid-generation (Bun's HTML HMR destroys the shader
- // canvas), re-capture the original's content and restart the shader so
- // the wait doesn't go dead.
- if (state === 'GENERATING' && origEl) {
- (async () => {
- try {
- const rect = origEl.getBoundingClientRect();
- if (rect.width === 0 || rect.height === 0) return;
- const blob = await captureElementToBlob(origEl, null, rect);
- if (blob && state === 'GENERATING') {
- showShaderOverlay(origEl, blob, rect);
- }
- } catch (err) {
- console.warn('[impeccable] shader resume failed:', err);
- }
- })();
- }
- return true;
- }
-
- // ---------------------------------------------------------------------------
- // Global bar (always visible at bottom)
- // ---------------------------------------------------------------------------
-
- let globalBarEl = null;
- let detectActive = false;
- let pickActive = true;
- let detectCount = 0;
- let detectScriptLoaded = false;
-
- // Theme-aware color palette for the global bar. We detect the page's
- // ambient background and invert — dark bar on light pages, light bar on
- // dark pages. This keeps the bar from fighting with the host design.
- function detectPageTheme() {
- try {
- // Dev override: set localStorage 'impeccable-dev-theme' to 'light' or
- // 'dark' to preview the opposite palette without actually changing the
- // page bg. Used for screenshots and theme QA.
- const override = localStorage.getItem('impeccable-dev-theme');
- if (override === 'light' || override === 'dark') return override;
-
- // Walk body → html, taking the first opaque background. The browser's
- // default body / html background is `rgba(0, 0, 0, 0)`, which a naive
- // regex would read as black and mislabel a perfectly white page as
- // dark. Honoring alpha avoids that — and falling through to <html>
- // catches the common pattern of a bg only on <html> (or only on body).
- function readOpaque(el) {
- if (!el) return null;
- const bg = getComputedStyle(el).backgroundColor;
- const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
- if (!m) return null;
- const alpha = m[4] == null ? 1 : parseFloat(m[4]);
- if (alpha < 0.5) return null; // transparent / nearly transparent → skip
- return [+m[1], +m[2], +m[3]];
- }
-
- const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
- // Both transparent → fall back to the browser's effective canvas color.
- // White is the universal default; only one in a thousand sites swaps it
- // via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
- // us catch that case.
- if (!rgb) {
- return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
- }
- const [r, g, b] = rgb;
- // Perceptual luminance (Rec. 709)
- const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
- return L > 0.55 ? 'light' : 'dark';
- } catch { return 'light'; }
- }
-
- function barPaletteForTheme(theme) {
- if (theme === 'dark') {
- // Light bar on dark page
- return {
- surface: 'oklch(98% 0 0 / 0.92)',
- surfaceDeep: 'oklch(92% 0.005 60 / 0.96)', // slightly deeper, faint warm
- hairline: 'oklch(70% 0 0 / 0.35)',
- text: 'oklch(15% 0 0)',
- textDim: 'oklch(45% 0 0)',
- accent: 'oklch(60% 0.25 350)',
- accentSoft: 'oklch(60% 0.25 350 / 0.18)',
- mark: 'oklch(98% 0 0)', // logo mark fill
- markText: 'oklch(15% 0 0)', // logo "/" color
- exitHover: 'oklch(85% 0 0 / 0.5)',
- };
- }
- // Dark bar on light page. Bar is a warm charcoal, logo slab is much
- // deeper so the rounded-right shape reads as a clear sculpted mark.
- return {
- surface: 'oklch(26% 0 0 / 0.94)',
- surfaceDeep: 'oklch(18% 0 0 / 0.96)', // darker sand for Tune popover
- hairline: 'oklch(42% 0 0 / 0.5)',
- text: 'oklch(96% 0 0)',
- textDim: 'oklch(72% 0 0)',
- accent: 'oklch(72% 0.22 350)',
- accentSoft: 'oklch(72% 0.22 350 / 0.22)',
- mark: 'oklch(8% 0 0)',
- markText: 'oklch(96% 0 0)',
- exitHover: 'oklch(36% 0 0 / 0.6)',
- };
- }
-
- // Impeccable logo mark — matches the site-header SVG (rounded square + "/").
- function brandMarkSvg(fill, ink, size = 18) {
- return `<svg width="${size}" height="${size}" viewBox="0 0 32 32" aria-hidden="true">
- <rect width="32" height="32" rx="7" fill="${fill}"/>
- <text x="16" y="24" font-family="system-ui, -apple-system, sans-serif" font-size="22" font-weight="500" fill="${ink}" text-anchor="middle">/</text>
- </svg>`;
- }
-
- function initGlobalBar() {
- const theme = detectPageTheme();
- const P = barPaletteForTheme(theme);
-
- // Custom focus-visible for bar buttons. Browser default is a heavy
- // blue ring that looks jarring on the dark capsule. Replace with a
- // soft accent-tinted inner ring that respects the bar's palette.
- if (!document.getElementById(PREFIX + '-bar-focus-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-bar-focus-style';
- s.textContent =
- '#' + PREFIX + '-global-bar button:focus { outline: none; }' +
- '#' + PREFIX + '-global-bar button:focus-visible {' +
- ' outline: none;' +
- ' box-shadow: 0 0 0 2px ' + P.accentSoft + ', 0 0 0 3px ' + P.accent + ';' +
- '}';
- document.head.appendChild(s);
- }
-
- globalBarEl = el('div', {
- position: 'fixed', bottom: '14px', left: '50%',
- transform: 'translateX(-50%) translateY(20px)',
- zIndex: Z.bar + 5,
- display: 'flex', alignItems: 'stretch',
- gap: '2px',
- background: P.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 4px 20px oklch(0% 0 0 / 0.12), 0 1px 3px oklch(0% 0 0 / 0.08)',
- fontFamily: FONT, fontSize: '12px', lineHeight: '1',
- opacity: '0',
- overflow: 'hidden', // clip the full-bleed brand mark to the bar radius
- transition: 'opacity 0.3s ' + EASE + ', transform 0.3s ' + EASE,
- });
- globalBarEl.id = PREFIX + '-global-bar';
- globalBarEl.dataset.theme = theme;
-
- // Brand mark — fills bar height on the left. Left side inherits the bar's
- // rounded corner via overflow:hidden; right side is a clean hard edge since
- // the near-black/charcoal contrast does the shape-defining work.
- const brand = el('span', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- alignSelf: 'stretch',
- padding: '0 12px 0 14px',
- background: P.mark,
- color: P.markText,
- fontFamily: 'system-ui, -apple-system, sans-serif',
- fontWeight: '500',
- fontSize: '18px', lineHeight: '1',
- });
- brand.textContent = '/';
- brand.title = 'Impeccable';
- globalBarEl.appendChild(brand);
-
- // Inner wrapper: holds the toggles with normal bar padding.
- const inner = el('div', {
- display: 'flex', alignItems: 'center',
- padding: '4px 5px', gap: '2px',
- });
- inner.id = PREFIX + '-global-bar-inner';
- globalBarEl.appendChild(inner);
-
- // --- button factory: icon-only at rest, label slides in on hover/active ---
- function makeIconBtn({ id, svg, label, ariaLabel, labelFont, onClick }) {
- const b = el('button', {
- position: 'relative',
- display: 'inline-flex', alignItems: 'center',
- padding: '6px 8px', borderRadius: '7px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '11.5px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.15s ease, color 0.15s ease',
- whiteSpace: 'nowrap', overflow: 'hidden',
- });
- b.id = id;
- b.title = ariaLabel || label || '';
- b.setAttribute('aria-label', ariaLabel || label || '');
- b.innerHTML = svg + (label
- ? `<span class="icon-btn-label" style="display:inline-block;max-width:0;opacity:0;margin-left:0;overflow:hidden;font-family:${labelFont || FONT};transition:max-width 0.25s ${EASE}, opacity 0.2s ease, margin-left 0.25s ${EASE};">${label}</span>`
- : '');
- const labelEl = b.querySelector('.icon-btn-label');
- const expand = () => {
- if (!labelEl) return;
- labelEl.style.maxWidth = '120px'; labelEl.style.opacity = '1'; labelEl.style.marginLeft = '6px';
- };
- const collapse = () => {
- if (!labelEl || b.dataset.active === 'true') return;
- labelEl.style.maxWidth = '0'; labelEl.style.opacity = '0'; labelEl.style.marginLeft = '0';
- };
- // Per-button hover only changes color (no layout). The label expand/
- // collapse is driven by the bar-level mouseenter/mouseleave so moving
- // the mouse between adjacent buttons doesn't trigger per-button width
- // thrashing — the whole bar grows once and shrinks once.
- b.addEventListener('mouseenter', () => { if (b.dataset.active !== 'true') b.style.color = P.text; });
- b.addEventListener('mouseleave', () => { if (b.dataset.active !== 'true') b.style.color = P.textDim; });
- b.addEventListener('click', onClick);
- b._expandLabel = expand;
- b._collapseLabel = collapse;
- return b;
- }
-
- // Pick toggle — starts active (primary intent when entering live mode).
- const pickBtn = makeIconBtn({
- id: PREFIX + '-pick-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',
- label: 'Pick',
- ariaLabel: 'Pick element',
- onClick: () => togglePick(),
- });
- pickBtn.style.background = P.accentSoft;
- pickBtn.style.color = P.accent;
- pickBtn.dataset.active = 'true';
- pickBtn._expandLabel();
- inner.appendChild(pickBtn);
-
- // Detect toggle
- const detectBtn = makeIconBtn({
- id: PREFIX + '-detect-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',
- label: 'Detect',
- ariaLabel: 'Detect anti-patterns',
- onClick: () => toggleDetect(),
- });
- const detectBadge = el('span', {
- fontSize: '10px', fontWeight: '600',
- padding: '0px 5px', borderRadius: '7px', lineHeight: '16px',
- background: P.accent, color: P.surface.includes('18%') ? 'oklch(18% 0 0)' : 'oklch(98% 0 0)',
- display: 'none', fontFamily: MONO, marginLeft: '4px',
- });
- detectBadge.id = PREFIX + '-detect-badge';
- detectBtn.appendChild(detectBadge);
- inner.appendChild(detectBtn);
-
- // DESIGN.md panel toggle — quartet of color squares as the mark.
- const designBtn = makeIconBtn({
- id: PREFIX + '-design-toggle',
- svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px ${P.hairline};flex-shrink:0">
- <span style="background:oklch(60% 0.25 350)"></span>
- <span style="background:oklch(60% 0.15 45)"></span>
- <span style="background:oklch(55% 0.12 250)"></span>
- <span style="background:oklch(30% 0 0)"></span>
- </span>`,
- label: 'DESIGN.md',
- ariaLabel: 'Toggle DESIGN.md panel',
- labelFont: MONO,
- onClick: () => toggleDesignPanel(),
- });
- inner.appendChild(designBtn);
-
- // Thin divider before the exit button
- const divider = el('span', {
- width: '1px', height: '18px',
- background: P.hairline,
- margin: '0 4px 0 2px',
- });
- inner.appendChild(divider);
-
- // Exit × on the right — intentionally subtle (textDim at rest, text on
- // hover) so it sits behind the active toggles in visual hierarchy.
- //
- // Explicit padding + box-sizing here is load-bearing: a host page like
- // `button { padding: 0.5rem 1rem; }` (very common in resets) would
- // otherwise inflate this 24x24 button into 56x40 and push the SVG out
- // of the visible bar — the X stays invisible even though the styles in
- // DevTools look fine. Every other chrome button sets padding inline;
- // this one needed it too.
- const exitBtn = el('button', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- padding: '0', boxSizing: 'border-box',
- width: '24px', height: '24px', borderRadius: '6px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
- cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
- });
- exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
- exitBtn.title = 'Exit live mode';
- exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
- exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
- exitBtn.addEventListener('click', () => { sendEvent({ type: 'exit' }); teardown(); });
- inner.appendChild(exitBtn);
-
- // Bar-level hover: expand every toggle's label at once; collapse on leave.
- // Buttons with dataset.active="true" ignore collapse (their label stays).
- const toggles = [pickBtn, detectBtn, designBtn];
- globalBarEl.addEventListener('mouseenter', () => {
- toggles.forEach((t) => t._expandLabel && t._expandLabel());
- });
- globalBarEl.addEventListener('mouseleave', () => {
- toggles.forEach((t) => t._collapseLabel && t._collapseLabel());
- });
-
- document.body.appendChild(globalBarEl);
- defangOutsideHandlers(globalBarEl);
-
- requestAnimationFrame(() => {
- globalBarEl.style.opacity = '1';
- globalBarEl.style.transform = 'translateX(-50%) translateY(0)';
- });
-
- // Listen for detection results AND ready signal
- window.addEventListener('message', onDetectMessage);
- }
-
- function updateGlobalBarState() {
- const detectToggle = document.getElementById(PREFIX + '-detect-toggle');
- const detectBadge = document.getElementById(PREFIX + '-detect-badge');
- const pickToggle = document.getElementById(PREFIX + '-pick-toggle');
- const designToggle = document.getElementById(PREFIX + '-design-toggle');
- const theme = globalBarEl?.dataset.theme || 'light';
- const P = barPaletteForTheme(theme);
-
- // Sync one toggle's active state, colors, and slide-label visibility.
- function sync(btn, active) {
- if (!btn) return;
- btn.style.background = active ? P.accentSoft : 'transparent';
- btn.style.color = active ? P.accent : P.textDim;
- btn.dataset.active = active ? 'true' : 'false';
- if (active && btn._expandLabel) btn._expandLabel();
- else if (!active && btn._collapseLabel) btn._collapseLabel();
- }
- sync(pickToggle, pickActive);
- sync(detectToggle, detectActive);
- sync(designToggle, designState.open);
-
- // If the bar is currently under the cursor, keep all labels expanded —
- // otherwise clicking a toggle that deactivates (e.g. closing DESIGN.md)
- // would collapse its label while the user's mouse is still on the bar.
- if (globalBarEl && globalBarEl.matches(':hover')) {
- [pickToggle, detectToggle, designToggle].forEach((t) => t?._expandLabel?.());
- }
-
- if (detectBadge) {
- detectBadge.style.display = (detectActive && detectCount > 0) ? 'inline' : 'none';
- detectBadge.textContent = detectCount;
- }
-
- // When pick is active, make detect overlays click-through so the picker works
- document.querySelectorAll('.impeccable-overlay').forEach(o => {
- o.style.pointerEvents = pickActive ? 'none' : '';
- });
- }
-
- let detectReady = false; // true once detect script posts 'impeccable-ready'
- let detectPendingScan = false; // scan requested before script was ready
-
- function toggleDetect() {
- detectActive = !detectActive;
- updateGlobalBarState();
-
- if (detectActive) {
- if (!detectScriptLoaded) {
- detectPendingScan = true;
- loadDetectScript();
- } else if (detectReady) {
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- } else {
- detectPendingScan = true;
- }
- } else {
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- detectCount = 0;
- updateGlobalBarState();
- }
- }
-
- function togglePick() {
- pickActive = !pickActive;
- updateGlobalBarState();
-
- if (!pickActive) {
- // Disabling pick clears any in-flight selection and UI: highlight,
- // contextual bar, selectedElement. Otherwise a stale selection sits
- // on screen with no obvious way to dismiss.
- hideHighlight();
- hideBar();
- hideActionPicker();
- selectedElement = null;
- if (state === 'PICKING' || state === 'CONFIGURING') state = 'IDLE';
- } else {
- if (state === 'IDLE') state = 'PICKING';
- }
- }
-
- function loadDetectScript() {
- if (detectScriptLoaded) return;
- detectScriptLoaded = true;
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/detect.js';
- s.dataset.impeccableExtension = 'true';
- document.head.appendChild(s);
- }
-
- function onDetectMessage(e) {
- if (!e.data || typeof e.data.source !== 'string') return;
- // Detection script is loaded and ready
- if (e.data.source === 'impeccable-ready') {
- detectReady = true;
- if (detectPendingScan && detectActive) {
- detectPendingScan = false;
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- }
- }
- // Scan results arrived
- if (e.data.source === 'impeccable-results') {
- detectCount = e.data.count || 0;
- updateGlobalBarState();
- }
- }
-
- /** Full teardown: remove all UI, disconnect SSE, clean up. */
- function teardown() {
- cleanup();
- hideBar();
- if (globalBarEl) {
- globalBarEl.style.transform = 'translateY(100%)';
- setTimeout(() => { if (globalBarEl) globalBarEl.remove(); globalBarEl = null; }, 300);
- }
- if (highlightEl) { highlightEl.remove(); highlightEl = null; }
- if (tooltipEl) { tooltipEl.remove(); tooltipEl = null; }
- if (barEl) { barEl.remove(); barEl = null; }
- if (pickerEl) { pickerEl.remove(); pickerEl = null; }
- if (paramsPanelEl) { paramsPanelEl.remove(); paramsPanelEl = null; paramsPanelInner = null; paramsPanelBody = null; }
- if (evtSource) { evtSource.close(); evtSource = null; }
- document.removeEventListener('mousemove', handleMouseMove, true);
- document.removeEventListener('click', handleClick, true);
- document.removeEventListener('keydown', handleKeyDown, true);
- window.removeEventListener('message', onDetectMessage);
- // Remove detection overlays
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- state = 'IDLE';
- window.__IMPECCABLE_LIVE_INIT__ = false;
- console.log('[impeccable] Live mode exited.');
- }
-
- // ---------------------------------------------------------------------------
- // Design System Panel — visualizes the project's .impeccable/design.json sidecar
- // ---------------------------------------------------------------------------
-
- const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';
- const DESIGN_PANEL_WIDTH = 440;
-
- let designHost = null;
- let designShadow = null;
- let designState = {
- open: false,
- tab: 'visual', // 'visual' | 'raw'
- parsed: null, // parseDesignMd output (frontmatter + body sections)
- sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)
- hasMd: false,
- hasSidecar: false,
- present: null, // true/false once fetch resolves
- raw: null, // raw DESIGN.md for the raw tab
- mdNewerThanJson: false, // stale-hint flag
- loading: false,
- error: null,
- collapsed: { // narrative-section accordion state
- rules: true, dosdonts: true, overview: true,
- },
- };
-
- function loadDesignPrefs() {
- // `open` is intentionally NOT persisted — the panel always starts closed
- // so live mode doesn't auto-slide a big panel over the page on startup.
- try {
- const raw = localStorage.getItem(DESIGN_PREFS_KEY);
- if (!raw) return;
- const prefs = JSON.parse(raw);
- if (prefs.tab === 'visual' || prefs.tab === 'raw') designState.tab = prefs.tab;
- if (prefs.collapsed && typeof prefs.collapsed === 'object') {
- Object.assign(designState.collapsed, prefs.collapsed);
- }
- } catch { /* ignore */ }
- }
-
- function saveDesignPrefs() {
- try {
- localStorage.setItem(DESIGN_PREFS_KEY, JSON.stringify({
- tab: designState.tab,
- collapsed: designState.collapsed,
- }));
- } catch { /* ignore */ }
- }
-
- function initDesignPanel() {
- designHost = document.createElement('div');
- designHost.id = PREFIX + '-design-host';
- Object.assign(designHost.style, {
- position: 'fixed', top: '0', left: '0',
- width: '0', height: '0',
- zIndex: String(Z.bar + 10),
- pointerEvents: 'none',
- });
- designShadow = designHost.attachShadow({ mode: 'open' });
-
- const style = document.createElement('style');
- // Theme-match the bar: dark chrome on light pages, light chrome on dark pages.
- const theme = detectPageTheme();
- style.textContent = designPanelCss(barPaletteForTheme(theme));
- designShadow.appendChild(style);
-
- const root = document.createElement('div');
- root.className = 'root';
- designShadow.appendChild(root);
-
- document.body.appendChild(designHost);
- // The host is pointer-events: none; the panel inside the shadow DOM
- // manages its own auto/none. Events bubble through the shadow boundary,
- // so attaching here silences host-page outside-interaction handlers
- // without touching the host's click-through behavior.
- defangOutsideHandlers(designHost, { setPointerEvents: false });
-
- loadDesignPrefs();
- renderDesignChrome();
- if (designState.open) {
- fetchDesignSystem();
- }
- }
-
- // Neutral panel palette — deliberately NOT Impeccable-branded. The panel is
- // a viewer of the project's design system, not an Impeccable surface.
- const DP = {
- canvas: 'oklch(94% 0 0)', // panel background
- tile: 'oklch(98.5% 0 0)', // card-on-canvas
- tileAlt: 'oklch(96% 0 0)', // subtler tile for inner surfaces
- ink: 'oklch(15% 0 0)',
- ink2: 'oklch(35% 0 0)',
- meta: 'oklch(55% 0 0)',
- hairline: 'oklch(88% 0 0)',
- hairlineSoft: 'oklch(92% 0 0)',
- amber: 'oklch(70% 0.13 65)', // stale-hint accent
- amberBg: 'oklch(95% 0.05 80)',
- };
-
- function designPanelCss(BP) {
- // BP = bar palette (theme-aware, matches the global bar).
- // DP = internal content palette (neutral, so tiles render colors true).
- return `
- :host, .root { all: initial; }
- .root {
- font-family: ${FONT};
- color: ${DP.ink};
- pointer-events: none;
- }
- .root * { box-sizing: border-box; }
- button { font: inherit; color: inherit; }
-
- /* --- Panel shell: chrome matches the bar; body canvas stays neutral --- */
- .panel {
- position: fixed; top: 12px; bottom: 72px; right: 12px;
- width: ${DESIGN_PANEL_WIDTH}px; max-width: calc(100vw - 24px);
- background: ${BP.surface};
- border: 1px solid ${BP.hairline};
- border-radius: 14px;
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- box-shadow: 0 20px 60px oklch(0% 0 0 / 0.18), 0 4px 12px oklch(0% 0 0 / 0.08);
- display: flex; flex-direction: column;
- transform: translateX(calc(100% + 24px));
- opacity: 0;
- transition: transform 0.35s ${EASE}, opacity 0.25s ${EASE};
- pointer-events: none;
- overflow: hidden;
- }
- .panel[data-open="true"] { transform: translateX(0); opacity: 1; pointer-events: auto; }
-
- .panel-header {
- display: flex; align-items: center; gap: 10px;
- padding: 10px 10px 10px 14px;
- background: transparent;
- border-bottom: 1px solid ${BP.hairline};
- }
- .panel-title {
- flex: 1; min-width: 0;
- font-family: ${MONO};
- font-size: 11.5px; font-weight: 600;
- letter-spacing: 0.02em;
- color: ${BP.text};
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
- }
- .panel-close {
- border: none; background: transparent; color: ${BP.textDim};
- width: 26px; height: 26px; border-radius: 7px;
- display: inline-flex; align-items: center; justify-content: center;
- cursor: pointer; transition: background 0.15s ease, color 0.15s ease;
- }
- .panel-close:hover { background: ${BP.hairline}; color: ${BP.text}; }
-
- .tabs {
- display: inline-flex; padding: 2px;
- background: ${BP.hairline};
- border-radius: 7px;
- gap: 2px;
- }
- .tab {
- border: none; background: transparent;
- padding: 4px 10px; border-radius: 5px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 600; letter-spacing: 0.08em;
- text-transform: uppercase;
- color: ${BP.textDim}; cursor: pointer;
- transition: background 0.15s ease, color 0.15s ease;
- }
- .tab[data-active="true"] { background: ${BP.surface}; color: ${BP.text}; }
-
- .panel-body {
- flex: 1; overflow-y: auto;
- padding: 12px 12px 20px;
- background: ${DP.canvas};
- scrollbar-width: thin;
- scrollbar-color: ${DP.hairline} transparent;
- }
- .panel-body::-webkit-scrollbar { width: 8px; }
- .panel-body::-webkit-scrollbar-thumb { background: ${DP.hairline}; border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
-
- /* --- States --- */
- .empty, .loading, .error {
- margin: 16px 4px;
- padding: 28px 20px; text-align: center;
- background: ${DP.tile}; border-radius: 14px;
- color: ${DP.ink2}; font-size: 13px; line-height: 1.55;
- }
- .empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
- .empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
- .error { color: oklch(45% 0.15 25); }
-
- /* --- Stale hint --- */
- .stale {
- display: flex; align-items: center; gap: 8px;
- margin: 8px 4px 12px;
- padding: 8px 12px;
- background: ${DP.amberBg};
- border-radius: 10px;
- font-size: 11.5px; color: ${DP.ink2};
- }
- .stale-dot { width: 8px; height: 8px; border-radius: 50%; background: ${DP.amber}; flex-shrink: 0; }
- .stale-text { flex: 1; min-width: 0; }
- .stale-text strong { color: ${DP.ink}; font-weight: 600; }
-
- /* --- Parsed-md fallback banner --- */
- .parsed-md-cta {
- margin: 8px 4px 14px;
- padding: 14px 16px;
- background: ${DP.tile};
- border: 1px dashed ${DP.hairline};
- border-radius: 12px;
- font-size: 12px; color: ${DP.ink2}; line-height: 1.55;
- }
- .parsed-md-cta strong { color: ${DP.ink}; display: block; margin-bottom: 4px; font-size: 13px; font-weight: 600; }
- .parsed-md-cta code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; font-size: 11.5px; color: ${DP.ink}; }
-
- /* --- Tile primitives --- */
- .tile {
- position: relative;
- background: ${DP.tile};
- border-radius: 16px;
- padding: 16px;
- margin: 0 4px 10px;
- }
- .tile-row { margin: 0 4px 10px; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
- .tile-row .tile { margin: 0; }
- .tile-meta {
- display: flex; align-items: baseline; justify-content: space-between;
- gap: 10px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase;
- color: ${DP.meta};
- }
- .tile-meta .name { color: ${DP.ink}; font-weight: 600; letter-spacing: 0.05em; text-transform: none; font-family: ${FONT}; font-size: 12.5px; }
-
- /* --- Color tile --- */
- .c-tile { cursor: pointer; transition: transform 0.2s ${EASE}; }
- .c-tile:hover { transform: translateY(-1px); }
- .c-hero {
- height: 72px; border-radius: 10px; margin-top: 10px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.05);
- }
- .c-ramp {
- display: flex; gap: 0; height: 14px; border-radius: 4px; overflow: hidden;
- margin-top: 8px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.04);
- }
- .c-ramp > span { flex: 1; }
- .c-desc { margin-top: 8px; font-size: 11.5px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Type tile --- */
- .t-tile { }
- .t-specimen {
- margin: 4px 0 6px;
- color: ${DP.ink};
- line-height: 0.9;
- }
- .t-family { margin-top: 4px; font-size: 12px; font-weight: 600; color: ${DP.ink}; }
- .t-purpose { margin-top: 4px; font-size: 11px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Shadow tile --- */
- .s-tile { }
- .s-surface {
- height: 60px; margin: 8px 2px 10px;
- background: ${DP.tile};
- border-radius: 10px;
- }
- .s-value { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; word-break: break-all; line-height: 1.4; }
- .s-purpose { margin-top: 4px; font-size: 11px; color: ${DP.ink2}; line-height: 1.45; }
-
- /* --- Radii strip --- */
- .r-strip { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
- .r-item { display: flex; flex-direction: column; align-items: center; gap: 4px; flex: 1; min-width: 60px; }
- .r-sample { width: 44px; height: 44px; background: ${DP.canvas}; box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.08); }
- .r-label { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; text-transform: uppercase; }
- .r-val { font-family: ${MONO}; font-size: 10px; color: ${DP.ink}; }
-
- /* --- Component tile (hosts live primitives) --- */
- .cmp-tile { }
- .cmp-stage {
- margin: 12px -4px 0;
- padding: 18px 16px 10px;
- border-top: 1px solid ${DP.hairlineSoft};
- display: flex; flex-direction: column; align-items: center; justify-content: center;
- gap: 14px;
- min-height: 68px;
- }
- .cmp-stage + .cmp-stage { border-top: 1px dashed ${DP.hairlineSoft}; }
- .cmp-sublabel { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.06em; }
- .cmp-kind { font-family: ${MONO}; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; }
-
- /* --- Collapsible --- */
- .coll {
- margin: 0 4px 8px;
- background: ${DP.tile};
- border-radius: 12px;
- overflow: hidden;
- }
- .coll-head {
- display: flex; align-items: center; gap: 10px;
- width: 100%;
- padding: 12px 14px;
- background: transparent; border: none;
- cursor: pointer; text-align: left;
- font-family: ${FONT}; font-size: 12.5px; font-weight: 600; color: ${DP.ink};
- transition: background 0.12s ease;
- }
- .coll-head:hover { background: ${DP.tileAlt}; }
- .coll-chev {
- width: 12px; height: 12px; flex-shrink: 0;
- color: ${DP.meta};
- transition: transform 0.2s ${EASE};
- }
- .coll[data-open="true"] .coll-chev { transform: rotate(90deg); }
- .coll-count { margin-left: auto; font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; }
- .coll-body { padding: 0 14px 14px; display: none; }
- .coll[data-open="true"] .coll-body { display: block; }
-
- .rule-card {
- padding: 10px 0;
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .rule-card:first-child { border-top: none; padding-top: 2px; }
- .rule-card .name { font-size: 11.5px; font-weight: 700; color: ${DP.ink}; margin-bottom: 3px; }
- .rule-card .name .section { font-family: ${MONO}; font-size: 9px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; margin-left: 8px; }
- .rule-card .body { font-size: 11.5px; color: ${DP.ink2}; line-height: 1.5; }
-
- .coll .dos { display: grid; gap: 0; margin-top: 2px; }
- .coll .do, .coll .dont {
- position: relative;
- padding: 8px 0 8px 22px;
- font-size: 11.5px; line-height: 1.5; color: ${DP.ink2};
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .coll .do:first-child, .coll .dont:first-child,
- .coll .do:first-of-type { border-top: none; }
- .coll .do + .dont { border-top: 1px solid ${DP.hairlineSoft}; }
- .coll .do::before, .coll .dont::before {
- content: ''; position: absolute; left: 4px; top: 13px;
- width: 8px; height: 8px; border-radius: 50%;
- }
- .coll .do::before { background: oklch(62% 0.16 145); }
- .coll .dont::before { background: oklch(58% 0.22 25); }
-
- .coll .overview-body {
- font-size: 12px; line-height: 1.55; color: ${DP.ink2};
- }
- .coll .overview-body .north-star {
- display: block; font-family: ${FONT}; font-style: italic;
- font-size: 15px; line-height: 1.3; color: ${DP.ink};
- margin-bottom: 8px;
- }
- .coll .overview-body p { margin: 0 0 8px; }
- .coll .overview-body ul { margin: 6px 0 0; padding-left: 16px; font-size: 11.5px; }
- .coll .overview-body li { margin-bottom: 3px; }
-
- /* --- raw tab markdown (unchanged layout, neutralized palette) --- */
- .md { padding: 4px 10px 20px; font-size: 13px; line-height: 1.6; color: ${DP.ink}; }
- .md h1, .md h2, .md h3, .md h4 { margin: 20px 0 8px; color: ${DP.ink}; font-weight: 600; }
- .md h1 { font-size: 18px; }
- .md h2 { font-size: 15px; padding-bottom: 4px; border-bottom: 1px solid ${DP.hairlineSoft}; }
- .md h3 { font-size: 13px; }
- .md h4 { font-size: 12px; color: ${DP.meta}; }
- .md p { margin: 0 0 10px; }
- .md ul, .md ol { margin: 0 0 10px; padding-left: 20px; }
- .md li { margin-bottom: 4px; }
- .md code { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; }
- .md pre { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 10px 12px; border-radius: 8px; overflow-x: auto; margin: 0 0 10px; }
- .md pre code { background: none; padding: 0; }
- .md strong { font-weight: 700; }
- .md em { font-style: italic; }
- .md a { color: ${DP.ink}; text-decoration: underline; }
- .md hr { border: none; border-top: 1px solid ${DP.hairlineSoft}; margin: 16px 0; }
- `;
- }
-
- function renderDesignChrome() {
- const root = designShadow.querySelector('.root');
- root.innerHTML = '';
-
- // (Panel toggle lives in the global bar — no floating FAB.)
- // Panel
- const panel = document.createElement('aside');
- panel.className = 'panel';
- panel.setAttribute('data-open', designState.open ? 'true' : 'false');
- panel.appendChild(buildDesignHeader());
- const body = document.createElement('div');
- body.className = 'panel-body';
- body.id = 'panel-body';
- panel.appendChild(body);
- root.appendChild(panel);
-
- renderDesignBody();
- }
-
- function buildDesignHeader() {
- const header = document.createElement('div');
- header.className = 'panel-header';
-
- const title = document.createElement('div');
- title.className = 'panel-title';
- title.textContent = 'DESIGN.md';
- header.appendChild(title);
-
- const tabs = document.createElement('div');
- tabs.className = 'tabs';
- for (const t of [['visual', 'Visual'], ['raw', 'Raw']]) {
- const btn = document.createElement('button');
- btn.className = 'tab';
- btn.textContent = t[1];
- btn.setAttribute('data-active', designState.tab === t[0] ? 'true' : 'false');
- btn.addEventListener('click', () => {
- if (designState.tab === t[0]) return;
- designState.tab = t[0];
- saveDesignPrefs();
- renderDesignChrome();
- if (t[0] === 'raw' && designState.raw === null && !designState.loading) {
- fetchDesignSystem(); // raw is part of the same fetch pair
- }
- });
- tabs.appendChild(btn);
- }
- header.appendChild(tabs);
-
- const close = document.createElement('button');
- close.className = 'panel-close';
- close.innerHTML = '✕';
- close.setAttribute('aria-label', 'Close panel');
- close.addEventListener('click', toggleDesignPanel);
- header.appendChild(close);
-
- return header;
- }
-
- function toggleDesignPanel() {
- designState.open = !designState.open;
- renderDesignChrome();
- updateGlobalBarState();
- if (designState.open && designState.present === null && !designState.loading) {
- fetchDesignSystem();
- }
- }
-
- async function fetchDesignSystem() {
- designState.loading = true;
- designState.error = null;
- renderDesignBody();
- try {
- const [jsonRes, rawRes] = await Promise.all([
- fetch(`http://localhost:${PORT}/design-system.json?token=${TOKEN}`, { cache: 'no-store' }),
- fetch(`http://localhost:${PORT}/design-system/raw?token=${TOKEN}`, { cache: 'no-store' }),
- ]);
- const jsonData = await jsonRes.json();
- designState.present = jsonData.present === true;
- designState.parsed = jsonData.parsed || null;
- designState.sidecar = jsonData.sidecar || null;
- designState.hasMd = !!jsonData.hasMd;
- designState.hasSidecar = !!jsonData.hasSidecar;
- designState.mdNewerThanJson = !!jsonData.mdNewerThanJson;
- designState.raw = designState.present && rawRes.ok ? await rawRes.text() : null;
- designState.error = jsonData.parseError || jsonData.sidecarError || null;
- } catch (err) {
- designState.error = err?.message || 'Failed to load design system.';
- } finally {
- designState.loading = false;
- renderDesignChrome(); // refresh title from data
- }
- }
-
- function renderDesignBody() {
- const body = designShadow.querySelector('#panel-body');
- if (!body) return;
- body.innerHTML = '';
-
- if (designState.loading) {
- body.appendChild(msgDiv('loading', 'Loading design system…'));
- return;
- }
- if (designState.error) {
- body.appendChild(msgDiv('error', designState.error));
- return;
- }
- if (designState.present === false) {
- const empty = document.createElement('div');
- empty.className = 'empty';
- empty.innerHTML = `<strong>No DESIGN.md yet</strong>Create one by running <code>/impeccable document</code> in your terminal, then re-open this panel.`;
- body.appendChild(empty);
- return;
- }
-
- if (designState.tab === 'raw') {
- renderRawTab(body, designState.raw || '');
- return;
- }
-
- // Visual tab — single unified render path.
- if (designState.mdNewerThanJson) body.appendChild(renderStaleHint());
- if (designState.hasMd && !designState.hasSidecar) {
- body.appendChild(renderParsedMdCta());
- }
- renderDesignVisual(body, designState.parsed, designState.sidecar);
- }
-
- function msgDiv(cls, text) {
- const d = document.createElement('div');
- d.className = cls;
- d.textContent = text;
- return d;
- }
-
- function renderStaleHint() {
- const box = document.createElement('div');
- box.className = 'stale';
- box.innerHTML = `
- <span class="stale-dot"></span>
- <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>
- `;
- return box;
- }
-
- function renderParsedMdCta() {
- const box = document.createElement('div');
- box.className = 'parsed-md-cta';
- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;
- return box;
- }
-
- // --- Unified render: merge parsed DESIGN.md frontmatter with sidecar v2 ---
-
- function renderDesignVisual(body, parsed, sidecar) {
- const frontmatter = parsed?.frontmatter || {};
- const extensions = sidecar?.extensions || {};
- const proseColors = parsed?.colors || null;
-
- const colors = buildColorModels(frontmatter.colors, extensions.colorMeta, proseColors);
- if (colors.length) renderColorTiles(body, colors);
-
- const types = buildTypographyModels(frontmatter.typography, extensions.typographyMeta);
- if (types.length) renderTypeTiles(body, types);
-
- const radii = buildRadiiModels(frontmatter.rounded);
- if (radii.length) renderRadiiTile(body, radii);
-
- if (extensions.shadows?.length) renderShadowTiles(body, extensions.shadows);
-
- const components = sidecar?.components || [];
- if (components.length) renderComponentTiles(body, components);
-
- // Narrative: sidecar wins if present (richer, agent-curated). Otherwise
- // synthesize from prose sections.
- const narrative = sidecar?.narrative || synthesizeNarrative(parsed);
- if (narrative.rules?.length) body.appendChild(renderRulesCollapsible(narrative.rules));
- if ((narrative.dos?.length || narrative.donts?.length)) body.appendChild(renderDosDontsCollapsible(narrative));
- if (narrative.overview || narrative.northStar || narrative.keyCharacteristics?.length) {
- body.appendChild(renderOverviewCollapsible(narrative));
- }
-
- if (body.childElementCount === 0) {
- body.appendChild(msgDiv('empty', 'No design system data available.'));
- }
- }
-
- // Frontmatter primitives + sidecar colorMeta → tile-ready color models.
- // A matching prose bullet (when the slug sits in the bullet text) supplies
- // description as a last-resort fallback.
- function buildColorModels(fmColors, colorMeta, proseColors) {
- if (!fmColors) return [];
- const meta = colorMeta || {};
- return Object.entries(fmColors).map(([key, value]) => {
- const m = meta[key] || {};
- return {
- role: m.role || humanizeKey(key),
- name: m.displayName || humanizeKey(key),
- value: value,
- canonical: m.canonical || null,
- description: m.description || findProseDescription(proseColors, key, m.displayName),
- tonalRamp: m.tonalRamp || null,
- };
- });
- }
-
- function buildTypographyModels(fmTypography, typographyMeta) {
- if (!fmTypography) return [];
- const meta = typographyMeta || {};
- return Object.entries(fmTypography).map(([key, spec]) => {
- const m = meta[key] || {};
- const { family, fallback } = splitFontFamily(spec?.fontFamily);
- return {
- role: key,
- name: m.displayName || humanizeKey(key),
- family,
- fallback,
- weight: spec?.fontWeight ?? 400,
- // fontStyle isn't in Stitch's frontmatter schema; the sidecar carries
- // it when a role is rendered in italic (e.g. display italic).
- style: m.style || 'normal',
- sampleSize: spec?.fontSize || '1rem',
- lineHeight: spec?.lineHeight != null ? String(spec.lineHeight) : '',
- letterSpacing: spec?.letterSpacing,
- purpose: m.purpose,
- };
- });
- }
-
- function buildRadiiModels(fmRounded) {
- if (!fmRounded) return [];
- return Object.entries(fmRounded).map(([name, value]) => ({ name, value }));
- }
-
- function splitFontFamily(stack) {
- if (!stack || typeof stack !== 'string') return { family: '', fallback: '' };
- const parts = stack.split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, ''));
- return { family: parts[0] || '', fallback: parts.slice(1).join(', ') };
- }
-
- function humanizeKey(k) {
- return String(k || '').replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
- }
-
- function findProseDescription(proseColors, key, displayName) {
- if (!proseColors || !proseColors.groups) return null;
- const needles = [key, displayName].filter(Boolean).map((s) => s.toLowerCase());
- for (const g of proseColors.groups) {
- for (const c of g.colors || []) {
- const hay = String(c.name || '').toLowerCase();
- if (hay && needles.some((n) => hay.includes(n) || n.includes(hay))) {
- return c.description || null;
- }
- }
- }
- return null;
- }
-
- function synthesizeNarrative(parsed) {
- if (!parsed) return {};
- const md = parsed;
- return {
- northStar: md.overview?.creativeNorthStar,
- overview: (md.overview?.philosophy || []).join(' '),
- keyCharacteristics: md.overview?.keyCharacteristics || [],
- rules: [
- ...(md.colors?.rules || []).map((r) => ({ ...r, section: 'colors' })),
- ...(md.typography?.rules || []).map((r) => ({ ...r, section: 'typography' })),
- ...(md.elevation?.rules || []).map((r) => ({ ...r, section: 'elevation' })),
- ],
- dos: md.dosDonts?.dos || [],
- donts: md.dosDonts?.donts || [],
- };
- }
-
- function renderColorTiles(body, colors) {
- for (const c of colors) {
- const tile = document.createElement('div');
- tile.className = 'tile c-tile';
- tile.title = 'Click to copy';
- tile.addEventListener('click', () => copyToClipboard(c.value));
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(c.name || c.role || 'Color')}</span><span>${escapeHtml(c.value || '')}</span>`;
- tile.appendChild(meta);
-
- const hero = document.createElement('div');
- hero.className = 'c-hero';
- hero.style.background = c.value;
- tile.appendChild(hero);
-
- const ramp = synthesizeRamp(c);
- if (ramp.length) {
- const r = document.createElement('div');
- r.className = 'c-ramp';
- r.innerHTML = ramp.map((v) => `<span style="background:${cssSafe(v)}"></span>`).join('');
- tile.appendChild(r);
- }
-
- if (c.description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = c.description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function synthesizeRamp(c) {
- if (c.tonalRamp?.length) return c.tonalRamp;
- // If base value is OKLCH, synthesize an 8-step ramp across lightness.
- const m = typeof c.value === 'string' && c.value.match(/^oklch\(\s*([\d.]+)%\s+([\d.]+)\s+([\d.]+)\s*(?:\/\s*([\d.]+))?\s*\)$/i);
- if (!m) return [];
- const [, , chroma, hue] = m;
- const steps = [20, 32, 44, 56, 68, 80, 90, 96];
- return steps.map((l) => `oklch(${l}% ${chroma} ${hue})`);
- }
-
- function renderTypeTiles(body, types) {
- for (const t of types) {
- const tile = document.createElement('div');
- tile.className = 'tile t-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span>${escapeHtml(t.role || '')}</span><span>${escapeHtml(t.weight || '')} ${escapeHtml(t.style === 'italic' ? 'italic' : '')}</span>`;
- tile.appendChild(meta);
-
- const specimen = document.createElement('div');
- specimen.className = 't-specimen';
- specimen.textContent = 'Aa';
- specimen.style.fontFamily = fontStack(t);
- specimen.style.fontWeight = String(t.weight || 400);
- specimen.style.fontStyle = t.style || 'normal';
- specimen.style.fontSize = '56px'; // Fixed specimen size — compare faces, not scales.
- specimen.style.letterSpacing = 'normal';
- specimen.style.textTransform = 'none';
- tile.appendChild(specimen);
-
- // The system's actual sample size for this role, shown as small mono meta below.
- if (t.sampleSize) {
- const scale = document.createElement('div');
- scale.style.cssText = 'font-family:' + MONO + '; font-size: 10px; color:' + DP.meta + '; margin-top: 2px;';
- scale.textContent = t.sampleSize;
- tile.appendChild(scale);
- }
-
- const family = document.createElement('div');
- family.className = 't-family';
- family.textContent = t.family || t.name || '';
- tile.appendChild(family);
-
- if (t.purpose) {
- const p = document.createElement('div');
- p.className = 't-purpose';
- p.textContent = t.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function fontStack(t) {
- const fam = t.family || '';
- const fb = t.fallback || '';
- if (fam && /[,\s]/.test(fam) && !fam.includes("'") && !fam.includes('"')) {
- return `"${fam}", ${fb}`;
- }
- return fam && fb ? `"${fam}", ${fb}` : (fam || fb);
- }
-
- function renderRadiiTile(body, radii) {
- const tile = document.createElement('div');
- tile.className = 'tile';
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">Corner Radii</span><span>${radii.length}</span>`;
- tile.appendChild(meta);
-
- const strip = document.createElement('div');
- strip.className = 'r-strip';
- for (const r of radii) {
- const item = document.createElement('div');
- item.className = 'r-item';
- const s = document.createElement('div');
- s.className = 'r-sample';
- s.style.borderRadius = r.value || '0';
- item.appendChild(s);
- const lbl = document.createElement('div');
- lbl.className = 'r-label';
- lbl.textContent = r.name || '';
- item.appendChild(lbl);
- const val = document.createElement('div');
- val.className = 'r-val';
- val.textContent = r.value || '';
- item.appendChild(val);
- strip.appendChild(item);
- }
- tile.appendChild(strip);
- body.appendChild(tile);
- }
-
- function renderShadowTiles(body, shadows) {
- for (const sh of shadows) {
- const tile = document.createElement('div');
- tile.className = 'tile s-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(sh.name || 'Shadow')}</span><span>Elevation</span>`;
- tile.appendChild(meta);
-
- const surface = document.createElement('div');
- surface.className = 's-surface';
- surface.style.boxShadow = sh.value || 'none';
- tile.appendChild(surface);
-
- const val = document.createElement('div');
- val.className = 's-value';
- val.textContent = sh.value || '';
- tile.appendChild(val);
-
- if (sh.purpose) {
- const p = document.createElement('div');
- p.className = 's-purpose';
- p.textContent = sh.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function renderComponentTiles(body, components) {
- // Group consecutive components that share a kind into one tile. This avoids
- // a pile of one-component tiles (e.g., three button variants = three tiles)
- // and reads more like a proper category.
- const groups = groupByKind(components);
-
- for (const group of groups) {
- const tile = document.createElement('div');
- tile.className = 'tile cmp-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- const groupTitle = group.length === 1
- ? (group[0].name || group[0].kind || 'Component')
- : titleForKind(group[0].kind, group.length);
- meta.innerHTML = `<span class="name">${escapeHtml(groupTitle)}</span><span class="cmp-kind">${escapeHtml(group[0].kind || '')}</span>`;
- tile.appendChild(meta);
-
- for (const c of group) {
- const stage = document.createElement('div');
- stage.className = 'cmp-stage';
-
- // Render the component in its own shadow root so its CSS can't bleed.
- const host = document.createElement('div');
- const sub = host.attachShadow({ mode: 'open' });
- const style = document.createElement('style');
- style.textContent = c.css || '';
- sub.appendChild(style);
- const container = document.createElement('div');
- container.innerHTML = c.html || '';
- sub.appendChild(container);
- stage.appendChild(host);
-
- // Show component name as a sublabel only when the tile groups >1 item,
- // or when the component's display name differs from its kind.
- const showSublabel = group.length > 1;
- if (showSublabel) {
- const lbl = document.createElement('div');
- lbl.className = 'cmp-sublabel';
- lbl.textContent = c.name || '';
- stage.appendChild(lbl);
- }
- tile.appendChild(stage);
- }
-
- // Single shared description if all items carry the same one; otherwise
- // skip — per-item descriptions clutter a grouped tile.
- if (group.length === 1 && group[0].description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = group[0].description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function groupByKind(components) {
- const groups = [];
- for (const c of components) {
- const last = groups[groups.length - 1];
- if (last && last[0].kind && c.kind === last[0].kind) {
- last.push(c);
- } else {
- groups.push([c]);
- }
- }
- return groups;
- }
-
- function titleForKind(kind, count) {
- const labels = {
- button: 'Buttons',
- input: 'Inputs',
- nav: 'Navigation',
- chip: 'Chips',
- card: 'Cards',
- custom: 'Components',
- };
- return labels[kind] || (kind ? kind.charAt(0).toUpperCase() + kind.slice(1) + 's' : 'Components');
- }
-
- // --- Collapsibles ---------------------------------------------------------
-
- function buildCollapsible(key, label, count) {
- const wrap = document.createElement('div');
- wrap.className = 'coll';
- wrap.setAttribute('data-open', designState.collapsed[key] ? 'false' : 'true');
-
- const head = document.createElement('button');
- head.className = 'coll-head';
- head.innerHTML = `
- <svg class="coll-chev" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 2.5L8 6 4 9.5"/></svg>
- <span>${escapeHtml(label)}</span>
- ${count != null ? `<span class="coll-count">${escapeHtml(String(count))}</span>` : ''}
- `;
- head.addEventListener('click', () => {
- designState.collapsed[key] = !designState.collapsed[key];
- saveDesignPrefs();
- renderDesignBody();
- });
- wrap.appendChild(head);
-
- const body = document.createElement('div');
- body.className = 'coll-body';
- wrap.appendChild(body);
- return { wrap, body };
- }
-
- function renderRulesCollapsible(rules) {
- const { wrap, body } = buildCollapsible('rules', 'Named Rules', rules.length);
- for (const r of rules) {
- const card = document.createElement('div');
- card.className = 'rule-card';
- const name = document.createElement('div');
- name.className = 'name';
- name.innerHTML = `${escapeHtml(r.name)}${r.section ? `<span class="section">${escapeHtml(r.section)}</span>` : ''}`;
- card.appendChild(name);
- const b = document.createElement('div');
- b.className = 'body';
- b.textContent = r.body || '';
- card.appendChild(b);
- body.appendChild(card);
- }
- return wrap;
- }
-
- function renderDosDontsCollapsible(n) {
- const total = (n.dos?.length || 0) + (n.donts?.length || 0);
- const { wrap, body } = buildCollapsible('dosdonts', "Do's and Don'ts", total);
- const grid = document.createElement('div');
- grid.className = 'dos';
- for (const d of n.dos || []) {
- const el = document.createElement('div');
- el.className = 'do';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- for (const d of n.donts || []) {
- const el = document.createElement('div');
- el.className = 'dont';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- body.appendChild(grid);
- return wrap;
- }
-
- function renderOverviewCollapsible(n) {
- const { wrap, body } = buildCollapsible('overview', 'Overview', null);
- const ov = document.createElement('div');
- ov.className = 'overview-body';
- if (n.northStar) {
- const star = document.createElement('span');
- star.className = 'north-star';
- star.textContent = '“' + n.northStar + '”';
- ov.appendChild(star);
- }
- if (n.overview) {
- const p = document.createElement('p');
- p.innerHTML = inlineMd(n.overview);
- ov.appendChild(p);
- }
- if (n.keyCharacteristics?.length) {
- const ul = document.createElement('ul');
- ul.innerHTML = n.keyCharacteristics.map((k) => `<li>${inlineMd(k)}</li>`).join('');
- ov.appendChild(ul);
- }
- body.appendChild(ov);
- return wrap;
- }
-
- function cssSafe(v) {
- // Strip anything outside valid CSS value chars to prevent injection via
- // .impeccable/design.json values rendered into inline style strings.
- return String(v).replace(/[<>"'`\n]/g, '');
- }
-
- // --- Raw tab: minimal markdown renderer (subset) --------------------------
-
- function renderRawTab(body, md) {
- const wrap = document.createElement('div');
- wrap.className = 'md';
- wrap.innerHTML = renderMarkdown(md);
- body.appendChild(wrap);
- }
-
- function renderMarkdown(md) {
- const lines = md.split(/\r?\n/);
- const out = [];
- let i = 0;
- let inCode = false;
- let codeBuf = [];
- let paraBuf = [];
- let listBuf = []; // array of { indent, html }
- let listType = null; // 'ul' | 'ol'
-
- const flushPara = () => {
- if (paraBuf.length) {
- out.push(`<p>${inlineMd(paraBuf.join(' '))}</p>`);
- paraBuf = [];
- }
- };
- const flushList = () => {
- if (listBuf.length) {
- out.push(buildListHtml(listBuf, listType));
- listBuf = [];
- listType = null;
- }
- };
- const flushAll = () => { flushPara(); flushList(); };
-
- for (; i < lines.length; i++) {
- const line = lines[i];
-
- // Code fence
- const fence = line.match(/^```(\w*)\s*$/);
- if (fence) {
- if (!inCode) { flushAll(); inCode = true; codeBuf = []; }
- else {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- inCode = false;
- }
- continue;
- }
- if (inCode) { codeBuf.push(line); continue; }
-
- if (line.trim() === '') { flushAll(); continue; }
-
- const hr = line.match(/^\s*(?:---+|\*\*\*+)\s*$/);
- if (hr) { flushAll(); out.push('<hr />'); continue; }
-
- const heading = line.match(/^(#{1,4})\s+(.+)$/);
- if (heading) {
- flushAll();
- const lvl = heading[1].length;
- out.push(`<h${lvl}>${inlineMd(heading[2])}</h${lvl}>`);
- continue;
- }
-
- const bullet = line.match(/^(\s*)([-*])\s+(.+)$/);
- const ordered = line.match(/^(\s*)(\d+)\.\s+(.+)$/);
- if (bullet || ordered) {
- flushPara();
- const m = bullet || ordered;
- const indent = Math.floor(m[1].length / 2);
- const t = bullet ? 'ul' : 'ol';
- if (listType && listType !== t) flushList();
- listType = t;
- listBuf.push({ indent, html: inlineMd(m[3]) });
- continue;
- }
-
- paraBuf.push(line);
- }
- flushAll();
- if (inCode && codeBuf.length) {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- }
- return out.join('\n');
- }
-
- function buildListHtml(items, type) {
- // Nest by indent (one level deep is plenty for DESIGN.md).
- let html = `<${type}>`;
- let lastIndent = 0;
- for (const it of items) {
- if (it.indent > lastIndent) html += `<${type}>`;
- else if (it.indent < lastIndent) html += `</${type}>`.repeat(lastIndent - it.indent);
- html += `<li>${it.html}</li>`;
- lastIndent = it.indent;
- }
- html += `</${type}>`.repeat(lastIndent + 1);
- return html;
- }
-
- function inlineMd(text) {
- // Order matters: escape first, then re-inject tags.
- let s = escapeHtml(text);
- // Code spans
- s = s.replace(/`([^`]+)`/g, (_, code) => `<code>${code}</code>`);
- // Links [text](url)
- s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, t, u) => `<a href="${u}" target="_blank" rel="noopener noreferrer">${t}</a>`);
- // Bold
- s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
- // Italic (only single *…*, skip if inside bold already handled)
- s = s.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em>$2</em>');
- return s;
- }
-
- function highlightBold(text) {
- return inlineMd(text);
- }
-
- function escapeHtml(s) {
- return String(s)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
-
- function copyToClipboard(text) {
- if (!text) return;
- try {
- navigator.clipboard.writeText(text);
- showToast('Copied: ' + text);
- } catch { /* ignore */ }
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- function init() {
- try { history.scrollRestoration = 'manual'; } catch {}
- initHighlight();
- initAnnotOverlay();
- initBar();
- initActionPicker();
- initParamsPanel();
- initGlobalBar();
- initDesignPanel();
- document.addEventListener('mousemove', handleMouseMove, true);
- document.addEventListener('click', handleClick, true);
- document.addEventListener('keydown', handleKeyDown, true);
- connectSSE();
-
- // Check for an active session to resume (variant wrapper already in DOM after HMR)
- if (!resumeSession()) {
- console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
- // SvelteKit (and any framework that hydrates after HTML parse) may add
- // the variant wrapper AFTER init runs. Watch for it and retry resume
- // once it appears. Disconnect on first hit.
- const scout = new MutationObserver(() => {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) return;
- scout.disconnect();
- if (resumeSession()) {
- console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
- }
- });
- scout.observe(document.body, { childList: true, subtree: true });
- } else {
- console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
- }
- }
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
- } else {
- init();
- }
-})();
@@ -1,75 +0,0 @@
-#!/usr/bin/env node
-/**
- * Canonical durable completion acknowledgement for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function parseArgs(argv) {
- const out = { status: 'complete' };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';
- else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }
- else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function completeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help || !args.id) {
- console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);
- process.exit(args.help ? 0 : 1);
- }
-
- const serverInfo = readServerInfo();
- const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;
- if (serverResult?.ok) {
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const snapshot = store.getSnapshot(args.id, { includeCompleted: true });
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const event = args.status === 'discarded'
- ? { type: 'discarded', id: args.id }
- : args.status === 'agent_error'
- ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }
- : { type: 'complete', id: args.id };
- const snapshot = store.appendEvent(event);
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));
-}
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function completeThroughServer(info, args) {
- const type = args.status === 'discarded'
- ? 'discarded'
- : args.status === 'agent_error'
- ? 'error'
- : 'complete';
- try {
- const res = await fetch(`http://localhost:${info.port}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),
- });
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {
- completeCli();
-}
@@ -1,18 +0,0 @@
-export function completionTypeForAcceptResult(eventType, acceptResult) {
- if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';
- if (acceptResult?.handled === true) return 'complete';
- if (acceptResult?.mode === 'error') return 'error';
- return 'agent_done';
-}
-
-export function completionAckForAcceptResult(eventId, completionType, acceptResult) {
- const ack = { ok: true, type: completionType };
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) {
- ack.final = false;
- ack.requiresComplete = true;
- ack.nextCommand = `live-complete.mjs --id ${eventId}`;
- ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';
- }
- return ack;
-}
@@ -1,446 +0,0 @@
-/**
- * CLI helper: insert/remove the live variant mode script tag in the project's
- * main HTML entry point.
- *
- * On first live run, the agent generates `.impeccable/live/config.json`
- * with the project's insertion target (framework-specific). On
- * every subsequent run, this script handles insert/remove deterministically
- * with zero LLM involvement.
- *
- * Usage:
- * node live-inject.mjs --port PORT # Insert the live script tag
- * node live-inject.mjs --remove # Remove the live script tag
- * node live-inject.mjs --check # Check whether live config exists
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { resolveLiveConfigPath } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });
-const MARKER_OPEN_TEXT = 'impeccable-live-start';
-const MARKER_CLOSE_TEXT = 'impeccable-live-end';
-
-/**
- * Hard-excluded directory patterns. These are NEVER user-facing pages and
- * matching them would silently inject tracking scripts into third-party
- * code. The user cannot turn these off via config — they are the floor.
- */
-const HARD_EXCLUDES = [
- '**/node_modules/**',
- '**/.git/**',
-];
-
-export async function injectCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-inject.mjs [options]
-
-Insert or remove the live mode script tag in the project's HTML entry point.
-Reads configuration from .impeccable/live/config.json.
-
-Modes:
- --port PORT Insert script tag pointing at http://localhost:PORT/live.js
- --remove Remove the script tag (if present)
- --check Print whether .impeccable/live/config.json exists and its content
-
-Output (JSON):
- { ok, file, inserted|removed, config? }`);
- process.exit(0);
- }
-
- if (args.includes('--check')) {
- if (!fs.existsSync(CONFIG_PATH)) {
- console.log(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(0);
- }
- let cfg;
- try {
- cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- try {
- validateConfig(cfg);
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- console.log(JSON.stringify({ ok: true, config: cfg, path: CONFIG_PATH }));
- return;
- }
-
- // Load config
- if (!fs.existsSync(CONFIG_PATH)) {
- console.error(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(1);
- }
- const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- validateConfig(config);
-
- const resolvedFiles = resolveFiles(process.cwd(), config);
-
- if (args.includes('--remove')) {
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const detagged = removeTag(content, config.commentSyntax);
- const updated = revertCspMeta(detagged);
- if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- removed: detagged !== content,
- cspReverted: updated !== detagged,
- };
- });
- console.log(JSON.stringify({ ok: true, results }));
- return;
- }
-
- // Insert mode — need --port
- const portIdx = args.indexOf('--port');
- const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : NaN;
- if (!Number.isFinite(port)) {
- console.error(JSON.stringify({ ok: false, error: 'missing_port' }));
- process.exit(1);
- }
-
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
- const withTag = insertTag(withoutOld, config, port);
- if (withTag === withoutOld) {
- return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
- }
- const updated = patchCspMeta(withTag, port);
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- inserted: true,
- cspPatched: updated !== withTag,
- };
- });
- const anyInserted = results.some((r) => r.inserted);
- console.log(JSON.stringify({ ok: anyInserted, port, results }));
- if (!anyInserted) process.exit(1);
-}
-
-/**
- * Expand config.files (which may contain glob patterns) into a literal list
- * of existing file paths relative to rootDir. Literal entries pass through;
- * glob patterns are expanded via fs.globSync. HARD_EXCLUDES and config.exclude
- * are applied as filters. Duplicates are removed. Order is preserved by
- * first appearance.
- */
-export function resolveFiles(rootDir, config) {
- const patterns = config.files;
- const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
- const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
- const excludeRegexes = allExcludes.map(globToRegex);
-
- const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
- const isGlob = (s) => /[*?[]/.test(s);
-
- const seen = new Set();
- const out = [];
- for (const pat of patterns) {
- if (!isGlob(pat)) {
- // Literal path — include even if it doesn't exist yet; the caller
- // reports file_not_found per-entry. Exclude list doesn't apply to
- // explicit literal entries (user named it on purpose).
- if (!seen.has(pat)) {
- seen.add(pat);
- out.push(pat);
- }
- continue;
- }
- let matches;
- try {
- matches = fs.globSync(pat, { cwd: rootDir, withFileTypes: true });
- } catch {
- continue;
- }
- for (const ent of matches) {
- if (!ent.isFile || !ent.isFile()) continue;
- const abs = path.join(ent.parentPath || ent.path || rootDir, ent.name);
- const rel = path.relative(rootDir, abs).split(path.sep).join('/');
- if (isExcluded(rel)) continue;
- if (seen.has(rel)) continue;
- seen.add(rel);
- out.push(rel);
- }
- }
- return out;
-}
-
-/**
- * Convert a glob pattern to a RegExp. Supports:
- * ** → any number of path segments (including zero)
- * * → any chars except `/`
- * ? → any single char except `/`
- * Paths are normalized to forward slashes before matching.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- // ** — any number of segments, including zero. Handle the common
- // **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
- if (pattern[i + 2] === '/') {
- re += '(?:.*/)?';
- i += 3;
- } else {
- re += '.*';
- i += 2;
- }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Core operations
-// ---------------------------------------------------------------------------
-
-function validateConfig(cfg) {
- if (!cfg || typeof cfg !== 'object') throw new Error('config.json must be an object');
- if (!Array.isArray(cfg.files) || cfg.files.length === 0) {
- throw new Error('config.files (non-empty string array) required');
- }
- if (!cfg.files.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.files must contain only non-empty strings');
- }
- if (cfg.exclude !== undefined) {
- if (!Array.isArray(cfg.exclude)) {
- throw new Error('config.exclude, if present, must be a string array');
- }
- if (!cfg.exclude.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.exclude must contain only non-empty strings');
- }
- }
- if (typeof cfg.insertBefore !== 'string' && typeof cfg.insertAfter !== 'string') {
- throw new Error('config.insertBefore or config.insertAfter (string) required');
- }
- if (cfg.commentSyntax !== 'html' && cfg.commentSyntax !== 'jsx') {
- throw new Error("config.commentSyntax must be 'html' or 'jsx'");
- }
- if (cfg.cspChecked !== undefined && typeof cfg.cspChecked !== 'boolean') {
- throw new Error("config.cspChecked, if present, must be a boolean");
- }
-}
-
-function commentOpen(syntax) { return syntax === 'jsx' ? '{/*' : '<!--'; }
-function commentClose(syntax) { return syntax === 'jsx' ? '*/}' : '-->'; }
-
-function buildTagBlock(syntax, port) {
- const open = commentOpen(syntax);
- const close = commentClose(syntax);
- return (
- open + ' ' + MARKER_OPEN_TEXT + ' ' + close + '\n' +
- '<script src="http://localhost:' + port + '/live.js"></script>\n' +
- open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n'
- );
-}
-
-function insertTag(content, config, port) {
- const block = buildTagBlock(config.commentSyntax, port);
- // insertBefore: match the LAST occurrence. Anchors like `</body>` naturally
- // belong at the end, and the same literal can appear earlier in code blocks
- // within rendered documentation pages.
- if (config.insertBefore) {
- const idx = content.lastIndexOf(config.insertBefore);
- if (idx === -1) return content;
- return content.slice(0, idx) + block + content.slice(idx);
- }
- // insertAfter: match the FIRST occurrence — typical anchors like `<head>` or
- // `<body>` open near the top of the document.
- const idx = content.indexOf(config.insertAfter);
- if (idx === -1) return content;
- const after = idx + config.insertAfter.length;
- // Preserve a single trailing newline if the anchor didn't end with one
- const prefix = content[after] === '\n' ? content.slice(0, after + 1) : content.slice(0, after) + '\n';
- return prefix + block + content.slice(prefix.length);
-}
-
-/**
- * Remove the live script block. Matches either HTML or JSX comment markers
- * regardless of config (so stale tags from a wrong config can still be cleaned).
- *
- * Indent-preserving: captures any whitespace immediately preceding the opener
- * marker and re-emits it in place of the removed block. `insertTag` inserted
- * the block *after* the original line's indent and *before* the anchor (e.g.
- * `</body>`), which moved the indent onto the opener line and left the anchor
- * unindented. Replacing the whole block (plus its trailing newline) with just
- * the captured indent hands the indent back to the anchor that follows.
- */
-function removeTag(content, _syntax) {
- const patterns = [
- /([ \t]*)<!--\s*impeccable-live-start\s*-->[\s\S]*?<!--\s*impeccable-live-end\s*-->[ \t]*\n/,
- /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}[ \t]*\n/,
- ];
- for (const pat of patterns) {
- const next = content.replace(pat, '$1');
- if (next !== content) return next;
- }
- return content;
-}
-
-// ---------------------------------------------------------------------------
-// Content-Security-Policy meta-tag patcher
-//
-// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
-// the cross-origin load of /live.js (and the SSE/POST connection back to
-// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
-//
-// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
-// and stash the original `content` value in a `data-impeccable-csp-original`
-// attribute (base64) so revert is exact.
-//
-// On remove: detect the marker attribute, decode it, restore the original
-// content value verbatim, drop the marker.
-//
-// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
-// shared helpers) is NOT patched here — those need framework-specific config
-// edits and are handled via the existing detect-csp.mjs reference output.
-// Only the in-source meta-tag form gets the auto-patch.
-// ---------------------------------------------------------------------------
-
-const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
-
-function findCspMetaTags(content) {
- const out = [];
- const tagRe = /<meta\s+([^>]*?)\/?>/gis;
- let m;
- while ((m = tagRe.exec(content)) !== null) {
- const attrs = m[1];
- if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
- out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
- }
- return out;
-}
-
-function getAttr(attrs, name) {
- const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
- const m = attrs.match(re);
- return m ? { quote: m[1], value: m[2], full: m[0] } : null;
-}
-
-function appendOriginToDirective(csp, directive, origin) {
- const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
- const m = csp.match(re);
- if (m) {
- const tokens = m[4].trim().split(/\s+/);
- if (tokens.includes(origin)) return csp;
- return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
- }
- // Directive missing — add it. Use 'self' + origin so we don't inadvertently
- // narrow the policy compared to the default-src fallback (most users with
- // an explicit CSP have 'self' there).
- return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
-}
-
-export function patchCspMeta(content, port) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
- const origin = `http://localhost:${port}`;
-
- // Walk last-to-first so prior splices don't invalidate later indices.
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const attrs = tag.attrs;
- if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
- const contentAttr = getAttr(attrs, 'content');
- if (!contentAttr) continue;
-
- const original = contentAttr.value;
- let patched = original;
- patched = appendOriginToDirective(patched, 'script-src', origin);
- patched = appendOriginToDirective(patched, 'connect-src', origin);
- // The shader overlay during 'generating' creates a screenshot via
- // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
- // those. Add `blob:` so the overlay doesn't throw a CSP violation.
- patched = appendOriginToDirective(patched, 'img-src', 'blob:');
- if (patched === original) continue;
-
- const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
- const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
- // The tagRe captures any whitespace between the last attribute and the
- // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
- // a replace would land it BEFORE that trailing space, leaving a double
- // space inside attrs and clobbering the space before `/>`. Split off
- // the trailing whitespace, splice the marker into the attribute body,
- // and re-append the original trailing whitespace so a self-closing
- // `<meta … />` round-trips byte-for-byte.
- const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
- const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
- const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
- const newTag = tag.full.replace(attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-export function revertCspMeta(content) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
-
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
- if (!origAttr) continue;
- const contentAttr = getAttr(tag.attrs, 'content');
- if (!contentAttr) continue;
-
- let originalValue;
- try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
- catch { continue; }
-
- const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
- let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
- // Drop the marker attribute and any single space immediately preceding it.
- newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
- const newTag = tag.full.replace(tag.attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
- injectCli();
-}
-
-export { insertTag, removeTag, validateConfig, buildTagBlock };
-// patchCspMeta + revertCspMeta are exported above where they're defined.
@@ -1,200 +0,0 @@
-/**
- * CLI client for the live variant mode poll/reply protocol.
- *
- * Usage:
- * npx impeccable poll # Block until browser event, print JSON
- * npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
- * npx impeccable poll --reply <id> done # Reply "done" to event <id>
- * npx impeccable poll --reply <id> error "msg" # Reply with error
- */
-
-import { execFileSync } from 'node:child_process';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-// Node's built-in fetch (undici under the hood) enforces a 300s headers
-// timeout that can't be lowered per-request. We cap each request below
-// that ceiling and loop in `pollOnce` to synthesize a long poll without
-// depending on the standalone undici package.
-const PER_REQUEST_TIMEOUT_MS = 270_000;
-
-function readServerInfo() {
- const record = readLiveServerInfo(process.cwd());
- if (!record) {
- console.error('No running live server found. Start one with: npx impeccable live');
- process.exit(1);
- }
- return record.info;
-}
-
-export function buildPollReplyPayload(token, { id, type, message, file, data }) {
- return { token, id, type, message, file, data };
-}
-
-async function postReply(base, token, reply) {
- const res = await fetch(`${base}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(buildPollReplyPayload(token, reply)),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error || res.statusText);
- }
-}
-
-export async function pollCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable poll [options]
-
-Wait for a browser event from the live variant server, or reply to one.
-
-Modes:
- poll Block until a browser event arrives, print JSON
- poll --reply <id> done Reply "done" to event <id>
- poll --reply <id> error "msg" Reply with an error message
-
-Options:
- --timeout=MS Long-poll timeout in ms (default: 600000). Use the default unless the user asked to pause live; never use a short timeout to end the chat turn
- --help Show this help message`);
- process.exit(0);
- }
-
- const info = readServerInfo();
- const base = `http://localhost:${info.port}`;
-
- // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
- const replyIdx = args.indexOf('--reply');
- if (replyIdx !== -1) {
- const id = args[replyIdx + 1];
- const status = args[replyIdx + 2] || 'done';
- const fileIdx = args.indexOf('--file');
- const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
- // Message is any remaining positional arg that isn't a flag
- const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
-
- if (!id) {
- console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
- process.exit(1);
- }
-
- try {
- await postReply(base, info.token, { id, type: status, message, file: filePath });
-
- // Success — silent exit (agent doesn't need output for replies)
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Reply failed:', err.message);
- }
- process.exit(1);
- }
- return;
- }
-
- // Poll mode: block until browser event. Default 10 min. Node's built-in
- // fetch enforces a 300s headers timeout, so we loop in slices under that
- // ceiling and keep re-polling until we get a real event or the user's
- // total timeout runs out.
- const timeoutArg = args.find(a => a.startsWith('--timeout='));
- const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600000;
-
- const deadline = Date.now() + totalTimeout;
- let event;
- try {
- while (true) {
- const remaining = deadline - Date.now();
- if (remaining <= 0) {
- event = { type: 'timeout' };
- break;
- }
- const slice = Math.min(remaining, PER_REQUEST_TIMEOUT_MS);
- const res = await fetch(`${base}/poll?token=${info.token}&timeout=${slice}`);
-
- if (res.status === 401) {
- console.error('Authentication failed. The server token may have changed.');
- console.error('Try restarting: npx impeccable live stop && npx impeccable live');
- process.exit(1);
- }
-
- if (!res.ok) {
- console.error(`Poll failed: ${res.status} ${res.statusText}`);
- process.exit(1);
- }
-
- const next = await res.json();
- // Server-side timeout means no browser event arrived in this slice.
- // Loop and re-poll until we get a real event or we hit the user's
- // total deadline.
- if (next?.type === 'timeout' && Date.now() < deadline) continue;
- event = next;
- break;
- }
-
- // Auto-handle accept/discard via deterministic script
- if (event.type === 'accept' || event.type === 'discard') {
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const acceptScript = path.join(__dirname, 'live-accept.mjs');
- const scriptArgs = event.type === 'discard'
- ? ['--id', event.id, '--discard']
- : ['--id', event.id, '--variant', event.variantId];
- if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
- scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
- }
- try {
- const out = execFileSync(
- 'node',
- [acceptScript, ...scriptArgs],
- { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 }
- );
- event._acceptResult = JSON.parse(out.trim());
- } catch (err) {
- event._acceptResult = { handled: false, mode: 'error', error: err.message };
- }
-
- const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
- try {
- await postReply(base, info.token, {
- id: event.id,
- type: completionType,
- message: event._acceptResult?.error,
- file: event._acceptResult?.file,
- data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
- });
- } catch (err) {
- event._completionAck = { ok: false, error: err.message };
- }
- if (!event._completionAck) {
- event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
- }
- }
-
- // Second signal path: stderr banner in case the agent parses stdout
- // JSON but skips nested fields. One line is enough — the full checklist
- // is in reference/live.md.
- if (event._acceptResult?.carbonize === true) {
- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
- }
-
- // Print the event as JSON — the agent reads this from stdout
- console.log(JSON.stringify(event));
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Poll failed:', err.message);
- }
- process.exit(1);
- }
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
- pollCli();
-}
@@ -1,48 +0,0 @@
-#!/usr/bin/env node
-/**
- * Recover the next agent action from the durable live-session journal.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-
-function parseArgs(argv) {
- const out = { id: null };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function resumeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help) {
- console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });
- const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;
- if (!snapshot) {
- console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));
- return;
- }
-
- const pending = snapshot.pendingEvent || null;
- const nextAction = pending
- ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`
- : snapshot.phase === 'carbonize_required'
- ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`
- : snapshot.phase === 'accept_requested'
- ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`
- : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;
-
- console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {
- resumeCli();
-}
@@ -1,838 +0,0 @@
-#!/usr/bin/env node
-/**
- * Live variant mode server (self-contained, zero dependencies).
- *
- * Serves the browser script (/live.js), the detection overlay (/detect.js),
- * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
- * browser→server events. Agent communicates via HTTP long-poll (/poll).
- *
- * Usage:
- * node <scripts_path>/live-server.mjs # start
- * node <scripts_path>/live-server.mjs stop # stop + remove injected live.js tag
- * node <scripts_path>/live-server.mjs stop --keep-inject # stop only
- * node <scripts_path>/live-server.mjs --help
- */
-
-import http from 'node:http';
-import { randomUUID } from 'node:crypto';
-import { spawn, execFileSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import net from 'node:net';
-import { fileURLToPath } from 'node:url';
-import { parseDesignMd } from './design-parser.mjs';
-import { resolveContextDir } from './load-context.mjs';
-import { createLiveSessionStore } from './live-session-store.mjs';
-import {
- getDesignSidecarPath,
- getLiveAnnotationsDir,
- readLiveServerInfo,
- removeLiveServerInfo,
- resolveDesignSidecarPath,
- writeLiveServerInfo,
-} from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated
-// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
-// DESIGN.json fallback for existing projects.
-const CONTEXT_DIR = resolveContextDir(process.cwd());
-const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anyway
-const SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s
-
-// ---------------------------------------------------------------------------
-// Port detection
-// ---------------------------------------------------------------------------
-
-async function findOpenPort(start = 8400) {
- return new Promise((resolve) => {
- const srv = net.createServer();
- srv.listen(start, '127.0.0.1', () => {
- const port = srv.address().port;
- srv.close(() => resolve(port));
- });
- srv.on('error', () => resolve(findOpenPort(start + 1)));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Session state
-// ---------------------------------------------------------------------------
-
-const state = {
- token: null,
- port: null,
- sseClients: new Set(), // SSE response objects (server→browser push)
- pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
- pendingPolls: [], // agent poll callbacks waiting for browser events
- exitTimer: null,
- sessionDir: null, // per-session tmp dir for annotation screenshots
- sessionStore: null,
- leaseTimer: null,
-};
-
-// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;
-// cap at 10 MB to guard against runaway writes from a misbehaving client.
-const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
-
-function enqueueEvent(event) {
- if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;
- state.pendingEvents.push({ event, leaseUntil: 0 });
- flushPendingPolls();
-}
-
-function restorePendingEventsFromStore() {
- if (!state.sessionStore) return;
- for (const snapshot of state.sessionStore.listActiveSessions()) {
- if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);
- }
-}
-
-function findAvailablePendingEvent(now = Date.now()) {
- return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);
-}
-
-function leaseEvent(entry, leaseMs) {
- if (!entry.event?.id) {
- const idx = state.pendingEvents.indexOf(entry);
- if (idx !== -1) state.pendingEvents.splice(idx, 1);
- return entry.event;
- }
- entry.leaseUntil = Date.now() + leaseMs;
- return entry.event;
-}
-
-function acknowledgePendingEvent(id) {
- if (!id) return false;
- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);
- if (idx === -1) return false;
- state.pendingEvents.splice(idx, 1);
- scheduleLeaseFlush();
- return true;
-}
-
-function scheduleLeaseFlush() {
- if (state.leaseTimer) {
- clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- }
- if (state.pendingPolls.length === 0) return;
- const now = Date.now();
- const nextLeaseUntil = state.pendingEvents
- .map((entry) => entry.leaseUntil || 0)
- .filter((leaseUntil) => leaseUntil > now)
- .sort((a, b) => a - b)[0];
- if (!nextLeaseUntil) return;
- state.leaseTimer = setTimeout(() => {
- state.leaseTimer = null;
- flushPendingPolls();
- }, Math.max(0, nextLeaseUntil - now));
-}
-
-function flushPendingPolls() {
- while (state.pendingPolls.length > 0) {
- const entry = findAvailablePendingEvent();
- if (!entry) {
- scheduleLeaseFlush();
- return;
- }
- const poll = state.pendingPolls.shift();
- poll.resolve(leaseEvent(entry, poll.leaseMs));
- }
- scheduleLeaseFlush();
-}
-
-/** Push a message to all connected SSE clients. */
-function broadcast(msg) {
- const data = 'data: ' + JSON.stringify(msg) + '\n\n';
- for (const res of state.sseClients) {
- try { res.write(data); } catch { /* client gone */ }
- }
-}
-
-// ---------------------------------------------------------------------------
-// Load scripts
-// ---------------------------------------------------------------------------
-
-function loadBrowserScripts() {
- // Detection script: prefer the skill-bundled detector, then fall back to
- // source/npm package locations for local development and older installs.
- // This one IS cached — detect.js rarely changes during a session.
- const detectPaths = [
- path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(process.cwd(), 'node_modules', 'impeccable', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- ];
- let detectScript = '';
- for (const p of detectPaths) {
- try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
- }
-
- // live-browser.js: DO NOT cache. Return the path so the /live.js handler
- // can re-read on every request. Editing the browser script during iteration
- // should land on the next tab reload, not require a server restart.
- const sessionPath = path.join(__dirname, 'live-browser-session.js');
- const livePath = path.join(__dirname, 'live-browser.js');
- for (const p of [sessionPath, livePath]) {
- if (!fs.existsSync(p)) {
- process.stderr.write('Error: live browser script not found at ' + p + '\n');
- process.exit(1);
- }
- }
-
- return { detectScript, sessionPath, livePath };
-}
-
-function hasProjectContext() {
- // PRODUCT.md carries brand voice / anti-references — that's what determines
- // whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
- // concern, surfaced by the design panel's own empty state. Legacy
- // .impeccable.md is auto-migrated to PRODUCT.md by load-context.mjs.
- try {
- fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
- return true;
- } catch { return false; }
-}
-
-function statOrNull(filePath) {
- try { return fs.statSync(filePath); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// Validation (inline — no external import needed for self-contained script)
-// ---------------------------------------------------------------------------
-
-const VISUAL_ACTIONS = [
- 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
- 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
-];
-
-// Browser generates ids via crypto.randomUUID().slice(0, 8) (8 hex chars)
-// and variantIds via String(small integer). Restrict to those shapes so
-// any value that reaches a downstream child_process or DOM selector is
-// inert by construction.
-const ID_PATTERN = /^[0-9a-f]{8}$/;
-const VARIANT_ID_PATTERN = /^[0-9]{1,3}$/;
-
-function isValidId(v) { return typeof v === 'string' && ID_PATTERN.test(v); }
-function isValidVariantId(v) { return typeof v === 'string' && VARIANT_ID_PATTERN.test(v); }
-
-function validateEvent(msg) {
- if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
- switch (msg.type) {
- case 'generate':
- if (!isValidId(msg.id)) return 'generate: missing or malformed id';
- if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
- if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
- if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
- // Optional annotation fields (all-or-nothing: if any present, all must be well-formed).
- if (msg.screenshotPath !== undefined && typeof msg.screenshotPath !== 'string') return 'generate: screenshotPath must be string';
- if (msg.comments !== undefined && !Array.isArray(msg.comments)) return 'generate: comments must be array';
- if (msg.strokes !== undefined && !Array.isArray(msg.strokes)) return 'generate: strokes must be array';
- return null;
- case 'accept':
- if (!isValidId(msg.id)) return 'accept: missing or malformed id';
- if (!isValidVariantId(msg.variantId)) return 'accept: missing or malformed variantId';
- if (msg.paramValues !== undefined) {
- if (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues)) {
- return 'accept: paramValues must be an object';
- }
- }
- return null;
- case 'discard':
- return isValidId(msg.id) ? null : 'discard: missing or malformed id';
- case 'checkpoint':
- if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';
- if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';
- if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {
- return 'checkpoint: paramValues must be an object';
- }
- return null;
- case 'exit':
- return null;
- case 'prefetch':
- if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return 'prefetch: missing pageUrl';
- return null;
- default:
- return 'Unknown event type: ' + msg.type;
- }
-}
-
-// ---------------------------------------------------------------------------
-// HTTP request handler
-// ---------------------------------------------------------------------------
-
-function createRequestHandler({ detectScript, sessionPath, livePath }) {
- return (req, res) => {
- const url = new URL(req.url, `http://localhost:${state.port}`);
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
- if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
-
- const p = url.pathname;
-
- // --- Scripts ---
- if (p === '/live.js') {
- // Re-read from disk each request so edits to live-browser.js land on
- // the next tab reload. No-store headers prevent browser caching across
- // sessions — during iteration, a cached old script silently breaks
- // every subsequent session.
- let sessionScript;
- let liveScript;
- try {
- sessionScript = fs.readFileSync(sessionPath, 'utf-8');
- liveScript = fs.readFileSync(livePath, 'utf-8');
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'text/plain' });
- res.end('Error reading live browser scripts: ' + err.message);
- return;
- }
- const body =
- `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
- `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
- sessionScript + '\n' +
- liveScript;
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
- 'Pragma': 'no-cache',
- });
- res.end(body);
- return;
- }
- if (p === '/detect.js' || p === '/') {
- if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
- res.writeHead(200, { 'Content-Type': 'application/javascript' });
- res.end(detectScript);
- return;
- }
-
- // --- Vendored modern-screenshot (UMD build) ---
- // Lazy-loaded by live.js when the user clicks Go; exposes
- // window.modernScreenshot.domToBlob(...) for capture.
- if (p === '/modern-screenshot.js') {
- const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
- try {
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'public, max-age=31536000, immutable',
- });
- res.end(fs.readFileSync(vendorPath));
- } catch {
- res.writeHead(404); res.end('Vendor script not found');
- }
- return;
- }
-
- // --- Annotation upload (browser → server, raw PNG body) ---
- // Client generates the eventId, POSTs the PNG, then POSTs the generate
- // event with screenshotPath already set. Keeps bytes out of the SSE/poll
- // bridge and preserves the "one shot from the user's POV" UX.
- if (p === '/annotation' && req.method === 'POST') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const eventId = url.searchParams.get('eventId');
- if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid eventId' }));
- return;
- }
- if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
- res.writeHead(415, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
- return;
- }
- if (!state.sessionDir) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Session dir unavailable' }));
- return;
- }
- const chunks = [];
- let total = 0;
- let aborted = false;
- req.on('data', (c) => {
- if (aborted) return;
- total += c.length;
- if (total > MAX_ANNOTATION_BYTES) {
- aborted = true;
- res.writeHead(413, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Payload too large' }));
- req.destroy();
- return;
- }
- chunks.push(c);
- });
- req.on('end', () => {
- if (aborted) return;
- const absPath = path.join(state.sessionDir, eventId + '.png');
- try {
- fs.writeFileSync(absPath, Buffer.concat(chunks));
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Write failed: ' + err.message }));
- return;
- }
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true, path: absPath }));
- });
- req.on('error', () => {
- if (!aborted) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Upload failed' }));
- }
- });
- return;
- }
-
- // --- Health ---
- if (p === '/status') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
- const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok',
- port: state.port,
- connectedClients: state.sseClients.size,
- pendingEvents: state.pendingEvents.map((entry) => ({
- id: entry.event?.id,
- type: entry.event?.type,
- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),
- leaseUntil: entry.leaseUntil || null,
- })),
- activeSessions: sessions,
- }));
- return;
- }
-
- if (p === '/health') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok', port: state.port, mode: 'variant',
- hasProjectContext: hasProjectContext(),
- connectedClients: state.sseClients.size,
- }));
- return;
- }
-
- // --- Design system (unified v2 response) + raw ---
- // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json
- // sidecar when present. Panel merges them:
- // { present, parsed, sidecar, hasMd, hasSidecar,
- // mdNewerThanJson, parseError?, sidecarError? }
- // - parsed: output of parseDesignMd (frontmatter
- // + six canonical sections) when DESIGN.md exists.
- // - sidecar: .impeccable/design.json contents when present.
- // Expected shape: schemaVersion 2, carrying
- // extensions + components + narrative.
- // /design-system/raw returns DESIGN.md markdown verbatim
- if (p === '/design-system.json' || p === '/design-system/raw') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
-
- const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
- const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
- const mdStat = statOrNull(mdPath);
- const jsonStat = statOrNull(jsonPath);
-
- if (p === '/design-system/raw') {
- if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
- res.end(fs.readFileSync(mdPath, 'utf-8'));
- return;
- }
-
- if (!mdStat && !jsonStat) {
- res.writeHead(404, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ present: false }));
- return;
- }
-
- const response = {
- present: true,
- hasMd: !!mdStat,
- hasSidecar: !!jsonStat,
- mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
- };
-
- if (mdStat) {
- try {
- response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
- } catch (err) {
- response.parseError = err.message;
- }
- }
-
- if (jsonStat) {
- try {
- response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
- } catch (err) {
- response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;
- }
- }
-
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(response));
- return;
- }
-
- // --- Source file (no-HMR fallback) ---
- if (p === '/source') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const filePath = url.searchParams.get('path');
- if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
- const absPath = path.resolve(process.cwd(), filePath);
- if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
- let content;
- try { content = fs.readFileSync(absPath, 'utf-8'); }
- catch { res.writeHead(404); res.end('File not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
- res.end(content);
- return;
- }
-
- // --- SSE: server→browser push (replaces WebSocket) ---
- if (p === '/events' && req.method === 'GET') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- 'Connection': 'keep-alive',
- });
- res.write('data: ' + JSON.stringify({
- type: 'connected',
- hasProjectContext: hasProjectContext(),
- }) + '\n\n');
-
- state.sseClients.add(res);
- clearTimeout(state.exitTimer);
-
- // Keepalive: SSE comment every 30s prevents silent connection drops.
- const heartbeat = setInterval(() => {
- try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
- }, SSE_HEARTBEAT_INTERVAL);
-
- req.on('close', () => {
- clearInterval(heartbeat);
- state.sseClients.delete(res);
- if (state.sseClients.size === 0) {
- clearTimeout(state.exitTimer);
- state.exitTimer = setTimeout(() => {
- if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
- }, 8000);
- }
- });
- return;
- }
-
- // --- Browser→server events (replaces WebSocket messages) ---
- if (p === '/events' && req.method === 'POST') {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const error = validateEvent(msg);
- if (error) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error }));
- return;
- }
- if (state.sessionStore && msg.id) {
- try {
- state.sessionStore.appendEvent(msg);
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
- return;
- }
- }
- if (msg.type !== 'checkpoint') enqueueEvent(msg);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
- return;
- }
-
- // --- Stop ---
- if (p === '/stop') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.end('stopping');
- shutdown();
- return;
- }
-
- // --- Agent poll ---
- if (p === '/poll' && req.method === 'GET') {
- handlePollGet(req, res, url);
- return;
- }
- if (p === '/poll' && req.method === 'POST') {
- handlePollPost(req, res);
- return;
- }
-
- res.writeHead(404); res.end('Not found');
- };
-}
-
-// ---------------------------------------------------------------------------
-// Agent poll endpoints (unchanged from WS version)
-// ---------------------------------------------------------------------------
-
-function handlePollGet(req, res, url) {
- const token = url.searchParams.get('token');
- if (token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
- const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
- const available = findAvailablePendingEvent();
- if (available) {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(leaseEvent(available, leaseMs)));
- return;
- }
- const poll = { resolve, leaseMs };
- const timer = setTimeout(() => {
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ type: 'timeout' }));
- }, timeout);
- function resolve(event) {
- clearTimeout(timer);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(event));
- }
- state.pendingPolls.push(poll);
- scheduleLeaseFlush();
- req.on('close', () => {
- clearTimeout(timer);
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- });
-}
-
-function handlePollPost(req, res) {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- acknowledgePendingEvent(msg.id);
- if (state.sessionStore && msg.id) {
- try {
- const eventType = msg.type === 'discard' || msg.type === 'discarded'
- ? 'discarded'
- : msg.type === 'complete'
- ? 'complete'
- : msg.type === 'error'
- ? 'agent_error'
- : 'agent_done';
- state.sessionStore.appendEvent({
- type: eventType,
- id: msg.id,
- file: msg.file,
- message: msg.message,
- carbonize: msg.data?.carbonize === true,
- });
- } catch { /* keep reply path best-effort; browser still needs SSE */ }
- }
- flushPendingPolls();
- // Forward the reply to the browser via SSE
- broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Lifecycle
-// ---------------------------------------------------------------------------
-
-let httpServer = null;
-
-function shutdown() {
- removeLiveServerInfo(process.cwd());
- if (state.leaseTimer) clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- if (state.sessionDir) {
- try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}
- }
- for (const res of state.sseClients) { try { res.end(); } catch {} }
- state.sseClients.clear();
- for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });
- state.pendingPolls.length = 0;
- if (httpServer) httpServer.close();
- process.exit(0);
-}
-
-// ---------------------------------------------------------------------------
-// Main
-// ---------------------------------------------------------------------------
-
-const args = process.argv.slice(2);
-
-if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-server.mjs [options]
-
-Start the live variant mode server (zero dependencies).
-
-Commands:
- (default) Start the server (foreground)
- stop Stop the server and remove the injected live.js script tag
- stop --keep-inject Stop the server only (leave the script tag in the HTML entry)
-
-Options:
- --background Start detached, print connection JSON to stdout, then exit
- --port=PORT Use a specific port (default: auto-detect starting at 8400)
- --keep-inject Only with stop: skip live-inject.mjs --remove
- --help Show this help
-
-Endpoints:
- /live.js Browser script (element picker + variant cycling)
- /detect.js Detection overlay (backwards compatible)
- /modern-screenshot.js Vendored modern-screenshot UMD build (lazy-loaded by live.js)
- /annotation POST raw image/png to stage a variant screenshot
- /events SSE stream (server→browser) + POST (browser→server)
- /poll Long-poll for agent CLI
- /source Raw source file reader (no-HMR fallback)
- /status Durable recovery status (token-protected)
- /health Health check`);
- process.exit(0);
-}
-
-if (args.includes('stop')) {
- const keepInject = args.includes('--keep-inject');
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);
- if (res.ok) console.log(`Stopped live server on port ${info.port}.`);
- } catch {
- console.log('No running live server found.');
- }
- if (!keepInject) {
- const injectPath = path.join(__dirname, 'live-inject.mjs');
- try {
- const out = execFileSync(process.execPath, [injectPath, '--remove'], {
- encoding: 'utf-8',
- cwd: process.cwd(),
- });
- const line = out.trim().split('\n').filter(Boolean).pop();
- if (line) {
- try {
- const j = JSON.parse(line);
- if (j.removed === true) {
- console.log(`Removed live script tag from ${j.file}.`);
- }
- } catch {
- /* ignore non-JSON lines */
- }
- }
- } catch (err) {
- const detail = err.stderr?.toString?.().trim?.()
- || err.stdout?.toString?.().trim?.()
- || err.message
- || String(err);
- console.warn(`Note: could not remove live script tag (${detail.split('\n')[0]})`);
- }
- }
- process.exit(0);
-}
-
-// --background: spawn a detached child server, wait for it to be ready,
-// print the connection JSON, then exit. This keeps the startup command
-// simple (no shell backgrounding or chained commands).
-if (args.includes('--background')) {
- const childArgs = args.filter(a => a !== '--background');
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), ...childArgs], {
- detached: true,
- stdio: 'ignore',
- cwd: process.cwd(),
- });
- child.unref();
-
- // Poll for the PID file (the child writes it once the HTTP server is listening).
- const deadline = Date.now() + 10_000;
- while (Date.now() < deadline) {
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- if (info.pid !== process.pid) {
- // Output JSON so the agent can read port + token from stdout.
- console.log(JSON.stringify(info));
- process.exit(0);
- }
- } catch { /* not ready yet */ }
- await new Promise(r => setTimeout(r, 200));
- }
- console.error('Timed out waiting for live server to start.');
- process.exit(1);
-}
-
-// Check for existing session
-const existingRecord = readLiveServerInfo(process.cwd());
-if (existingRecord?.info) {
- const existing = existingRecord.info;
- try {
- process.kill(existing.pid, 0);
- console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
- console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');
- process.exit(1);
- } catch {
- try { fs.unlinkSync(existingRecord.path); } catch {}
- }
-}
-
-state.token = randomUUID();
-state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });
-restorePendingEventsFromStore();
-const portArg = args.find(a => a.startsWith('--port='));
-state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
-// Annotation screenshots live in the project root so the agent's Read tool
-// doesn't trip a per-file permission prompt. Sessioned by token so concurrent
-// projects (or quick restarts) don't collide.
-const annotRoot = getLiveAnnotationsDir(process.cwd());
-fs.mkdirSync(annotRoot, { recursive: true });
-state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));
-
-const { detectScript, sessionPath, livePath } = loadBrowserScripts();
-httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));
-
-httpServer.listen(state.port, '127.0.0.1', () => {
- writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });
- const url = `http://localhost:${state.port}`;
- console.log(`\nImpeccable live server running on ${url}`);
- console.log(`Token: ${state.token}\n`);
- console.log(`Inject: <script src="${url}/live.js"><\/script>`);
- console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
-});
-
-process.on('SIGINT', shutdown);
-process.on('SIGTERM', shutdown);
@@ -1,254 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';
-
-const COMPLETED_PHASES = new Set(['completed', 'discarded']);
-
-export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {
- const rootDir = getLiveSessionsDir(cwd);
- const legacyRootDir = getLegacyLiveSessionsDir(cwd);
- fs.mkdirSync(rootDir, { recursive: true });
- const snapshotCache = new Map();
-
- function loadCachedOrRebuild(id) {
- const cached = snapshotCache.get(id);
- if (cached) return cached;
- const journalPath = getReadableJournalPath(id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- return rebuilt;
- }
-
- function getReadableJournalPath(id) {
- const primary = getJournalPath(rootDir, id);
- if (fs.existsSync(primary)) return primary;
- const legacy = getJournalPath(legacyRootDir, id);
- if (fs.existsSync(legacy)) return legacy;
- return primary;
- }
-
- return {
- rootDir,
- legacyRootDir,
- appendEvent(event) {
- const normalized = normalizeEvent(event, sessionId);
- const journalPath = getJournalPath(rootDir, normalized.id);
- const snapshotPath = getSnapshotPath(rootDir, normalized.id);
- const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);
- if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {
- fs.copyFileSync(legacyJournalPath, journalPath);
- }
- const prior = loadCachedOrRebuild(normalized.id);
- const seq = prior.nextSeq;
- const entry = {
- seq,
- id: normalized.id,
- type: normalized.type,
- ts: new Date().toISOString(),
- event: normalized,
- };
- fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');
- const next = applyEvent(prior.snapshot, entry, prior.diagnostics);
- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });
- writeSnapshot(snapshotPath, next);
- return next;
- },
- getSnapshot(id = sessionId, opts = {}) {
- if (!id) throw new Error('session id required');
- const journalPath = getReadableJournalPath(id);
- const snapshotPath = getSnapshotPath(rootDir, id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- writeSnapshot(snapshotPath, rebuilt.snapshot);
- if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;
- return rebuilt.snapshot;
- },
- listActiveSessions() {
- const ids = new Set();
- for (const dir of [legacyRootDir, rootDir]) {
- if (!fs.existsSync(dir)) continue;
- for (const name of fs.readdirSync(dir)) {
- if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));
- }
- }
- return [...ids]
- .sort()
- .map((id) => this.getSnapshot(id))
- .filter(Boolean);
- },
- };
-}
-
-function normalizeEvent(event, fallbackId) {
- if (!event || typeof event !== 'object') throw new Error('event object required');
- const id = event.id || fallbackId;
- if (!id || typeof id !== 'string') throw new Error('event id required');
- if (!event.type || typeof event.type !== 'string') throw new Error('event type required');
- return { ...event, id };
-}
-
-function getJournalPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.jsonl');
-}
-
-function getSnapshotPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.snapshot.json');
-}
-
-function safeSessionId(id) {
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);
- return id;
-}
-
-function baseSnapshot(id) {
- return {
- id,
- phase: 'new',
- pageUrl: null,
- sourceFile: null,
- expectedVariants: 0,
- arrivedVariants: 0,
- visibleVariant: null,
- paramValues: {},
- pendingEventSeq: null,
- pendingEvent: null,
- deliveryLease: null,
- checkpointRevision: 0,
- activeOwner: null,
- sourceMarkers: {},
- fallbackMode: null,
- annotationArtifacts: [],
- diagnostics: [],
- updatedAt: null,
- };
-}
-
-function rebuildSnapshotFromJournal(journalPath, id) {
- let snapshot = baseSnapshot(id);
- const diagnostics = [];
- let nextSeq = 1;
- if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };
-
- const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- if (!line.trim()) continue;
- try {
- const entry = JSON.parse(line);
- if (!entry || typeof entry !== 'object') throw new Error('entry is not object');
- if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);
- snapshot = applyEvent(snapshot, entry);
- } catch (err) {
- diagnostics.push({
- error: 'journal_parse_failed',
- line: i + 1,
- message: err.message,
- });
- }
- }
- snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];
- return { snapshot, diagnostics, nextSeq };
-}
-
-function applyEvent(snapshot, entry, inheritedDiagnostics = []) {
- const event = entry.event || entry;
- const next = {
- ...snapshot,
- paramValues: { ...(snapshot.paramValues || {}) },
- sourceMarkers: { ...(snapshot.sourceMarkers || {}) },
- annotationArtifacts: [...(snapshot.annotationArtifacts || [])],
- diagnostics: [...(snapshot.diagnostics || [])],
- updatedAt: entry.ts || new Date().toISOString(),
- };
-
- if (inheritedDiagnostics.length && next.diagnostics.length === 0) {
- next.diagnostics = [...inheritedDiagnostics];
- }
-
- switch (event.type) {
- case 'generate':
- next.phase = 'generate_requested';
- next.pageUrl = event.pageUrl ?? next.pageUrl;
- next.expectedVariants = event.count ?? next.expectedVariants;
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });
- break;
- case 'variants_ready':
- case 'agent_done':
- next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';
- next.sourceFile = event.file ?? next.sourceFile;
- next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- if (event.carbonize === true) {
- next.diagnostics.push({
- error: 'carbonize_cleanup_required',
- file: event.file || null,
- message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',
- });
- }
- break;
- case 'checkpoint':
- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {
- next.phase = event.phase ?? next.phase;
- next.checkpointRevision = event.revision ?? next.checkpointRevision;
- next.activeOwner = event.owner ?? next.activeOwner;
- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;
- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- } else {
- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });
- }
- break;
- case 'accept':
- case 'accept_intent':
- next.phase = 'accept_requested';
- next.visibleVariant = Number(event.variantId ?? next.visibleVariant);
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discard':
- next.phase = 'discard_requested';
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discarded':
- next.phase = 'discarded';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'complete':
- next.phase = 'completed';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'agent_error':
- next.phase = 'agent_error';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });
- break;
- default:
- next.diagnostics.push({ error: 'unknown_event_type', type: event.type });
- break;
- }
- return next;
-}
-
-function toPendingEvent(event) {
- const pending = { ...event };
- delete pending.token;
- return pending;
-}
-
-function upsertArtifact(artifacts, artifact) {
- if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {
- artifacts.push(artifact);
- }
-}
-
-function writeSnapshot(snapshotPath, snapshot) {
- fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');
-}
@@ -1,47 +0,0 @@
-#!/usr/bin/env node
-/**
- * Print durable recovery status for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function fetchServerStatus(info) {
- if (!info) return null;
- try {
- const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-export async function statusCli() {
- const info = readServerInfo();
- const server = await fetchServerStatus(info);
- const store = createLiveSessionStore({ cwd: process.cwd() });
- const activeSessions = store.listActiveSessions();
- const payload = {
- liveServer: server ? {
- status: server.status,
- port: server.port,
- connectedClients: server.connectedClients,
- pendingEvents: server.pendingEvents,
- } : null,
- activeSessions: server?.activeSessions || activeSessions,
- recoveryHint: server
- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'
- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',
- };
- console.log(JSON.stringify(payload, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {
- statusCli();
-}
@@ -1,632 +0,0 @@
-/**
- * CLI helper: find an element in source and wrap it in a variant container.
- *
- * Usage:
- * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
- *
- * Searches project files for the element matching the query (class name, ID, or
- * text snippet), wraps it with the variant scaffolding, and prints the file path
- * + line range where the agent should insert variant HTML.
- *
- * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-export async function wrapCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable wrap [options]
-
-Find an element in source and wrap it in a variant container.
-
-Required:
- --id ID Session ID for the variant wrapper
- --count N Number of expected variants (1-8)
-
-Element identification (at least one required):
- --element-id ID HTML id attribute of the element
- --classes A,B,C Comma-separated CSS class names
- --tag TAG Tag name (div, section, etc.)
- --query TEXT Fallback: raw text to search for
-
-Optional:
- --file PATH Source file to search in (skips auto-detection)
- --text TEXT Picked element's textContent. Used to disambiguate when
- classes/tag match multiple sibling elements (e.g. a list
- of <Card>s with the same className). Pass the first ~80
- chars of event.element.textContent.
- --help Show this help message
-
-Output (JSON):
- { file, startLine, endLine, insertLine, commentSyntax }
-
-The agent should insert variant HTML at insertLine.`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const count = parseInt(argVal(args, '--count') || '3');
- const elementId = argVal(args, '--element-id');
- const classes = argVal(args, '--classes');
- const tag = argVal(args, '--tag');
- const query = argVal(args, '--query');
- const filePath = argVal(args, '--file');
- const text = argVal(args, '--text');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!elementId && !classes && !query) {
- console.error('Need at least one of: --element-id, --classes, --query');
- process.exit(1);
- }
-
- // Build search queries in priority order (most specific first)
- const queries = buildSearchQueries(elementId, classes, tag, query);
-
- const genOpts = { cwd: process.cwd() };
-
- // Find the source file. Generated files are excluded from auto-search so we
- // don't silently write variants into a file the next build will wipe.
- let targetFile = filePath;
- let matchedQuery = null;
- if (!targetFile) {
- for (const q of queries) {
- targetFile = findFileWithQuery(q, process.cwd(), genOpts);
- if (targetFile) { matchedQuery = q; break; }
- }
- if (!targetFile) {
- // Nothing in source. Did the element show up in a generated file? That
- // tells the agent "fall back to the agent-driven flow" vs "element just
- // doesn't exist in this project."
- let generatedHit = null;
- for (const q of queries) {
- generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
- if (generatedHit) break;
- }
- if (generatedHit) {
- console.error(JSON.stringify({
- error: 'element_not_in_source',
- fallback: 'agent-driven',
- generatedMatch: path.relative(process.cwd(), generatedHit),
- hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
- }));
- } else {
- console.error(JSON.stringify({
- error: 'element_not_found',
- fallback: 'agent-driven',
- hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
- }));
- }
- process.exit(1);
- }
- } else {
- if (isGeneratedFile(targetFile, genOpts)) {
- console.error(JSON.stringify({
- error: 'file_is_generated',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
- hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- matchedQuery = queries[0];
- }
-
- const content = fs.readFileSync(targetFile, 'utf-8');
- const lines = content.split('\n');
-
- // Find the element, trying each query in priority order. When `--text` is
- // supplied, collect every candidate the queries surface and disambiguate
- // by the picked element's textContent. Without `--text`, fall back to the
- // legacy first-match behavior so unmodified callers keep working.
- let match = null;
- if (text) {
- const candidates = [];
- for (const q of queries) {
- const all = findAllElements(lines, q, tag);
- for (const c of all) {
- if (!candidates.some((x) => x.startLine === c.startLine)) {
- candidates.push(c);
- }
- }
- // Once a more-specific query (ID, full className combo) yielded a unique
- // result, stop — falling through to the loose tag+single-class query
- // would readmit the siblings we just disambiguated past.
- if (candidates.length === 1) break;
- }
- if (candidates.length === 0) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- if (candidates.length === 1) {
- match = candidates[0];
- } else {
- const filtered = filterByText(candidates, lines, text);
- if (filtered.length === 1) {
- match = filtered[0];
- } else if (filtered.length === 0) {
- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the
- // browser-side textContent doesn't appear literally in source. Fall
- // back to first-match rather than refusing — this is the same
- // behavior unmodified callers see, just preserved.
- match = candidates[0];
- } else {
- // Multiple candidates ALSO match the text. Truly ambiguous — refuse
- // rather than pick wrong, and hand the agent the candidate locations
- // so it can disambiguate by reading the file.
- console.error(JSON.stringify({
- error: 'element_ambiguous',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), targetFile),
- candidates: filtered.map((c) => ({
- startLine: c.startLine + 1,
- endLine: c.endLine + 1,
- })),
- hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- }
- } else {
- for (const q of queries) {
- match = findElement(lines, q, tag);
- if (match) break;
- }
- if (!match) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- }
-
- const { startLine, endLine } = match;
- const commentSyntax = detectCommentSyntax(targetFile);
- const styleMode = detectStyleMode(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- const indent = lines[startLine].match(/^(\s*)/)[1];
-
- // Extract the original element. Reindent under the wrapper while preserving
- // the relative depth between lines — `l.trimStart()` would strip ALL leading
- // whitespace and collapse e.g. `<aside>`/` <h1>`/`</aside>` (6/8/6 spaces)
- // to a single uniform indent, so on accept/discard the round-trip restores
- // the inner element at its parent's depth instead of nested inside it.
- // Strip only the COMMON minimum leading whitespace across the picked lines;
- // `deindentContent` on the accept side already mirrors this convention.
- const originalLines = lines.slice(startLine, endLine + 1);
- const originalBaseIndent = minLeadingSpaces(originalLines);
- const reindentOriginal = (extra) => originalLines
- .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
- .join('\n');
- const originalIndented = reindentOriginal(' ');
-
- // Wrapper attributes differ by syntax. HTML allows plain string attrs;
- // JSX requires object-literal style and parses string attrs as HTML (which
- // either type-errors or renders a literal CSS string).
- const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
-
- // JSX/TSX guard: the picked element occupies a single JSX child slot
- // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
- // any other expression position). Replacing it with `comment + <div> +
- // comment` yields three adjacent siblings — invalid JSX. We can't use a
- // Fragment `<></>` either: parents that clone children (Radix `asChild`,
- // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
- // they try to pass an `id` through.
- //
- // Solution: keep the wrapper `<div>` as the single JSX-slot child and
- // tuck both marker comments INSIDE it. accept/discard then expands its
- // replacement range to include the wrapper's `<div>` open / close lines
- // so the entire scaffold gets removed cleanly.
- const wrapperLines = isJsx ? [
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- reindentOriginal(' '),
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- indent + '</div>',
- ] : [
- indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- originalIndented,
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + '</div>',
- indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- ];
-
- // Replace the original element with the wrapper
- const newLines = [
- ...lines.slice(0, startLine),
- ...wrapperLines,
- ...lines.slice(endLine + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- // Calculate insert line (the "insert below this line" comment).
- // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
- // the insert marker (HTML: start-comment + outer-div + Original-comment +
- // original-div + content + close-original-div; JSX: outer-div +
- // start-comment + Original-comment + original-div + content +
- // close-original-div). Multi-line originals push the marker by their
- // extra line count.
- const insertLine = startLine + 6 + (originalLines.length - 1);
-
- console.log(JSON.stringify({
- file: path.relative(process.cwd(), targetFile),
- startLine: startLine + 1, // 1-indexed for the agent
- // wrapperLines is an array but one element (the original-content slot)
- // is a `\n`-joined multi-line string, so the actual file-row count is
- // wrapperLines.length + (originalLines.length - 1). Without the offset,
- // endLine pointed inside the wrapper for any picked element that
- // spanned more than one source line.
- endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexed
- insertLine: insertLine + 1, // 1-indexed: where variants go
- commentSyntax: commentSyntax,
- styleMode: styleMode.mode,
- styleTag: styleMode.styleTag,
- cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
- cssAuthoring: buildCssAuthoring(styleMode, count),
- originalLineCount: originalLines.length,
- }));
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-/**
- * Build search query strings in priority order (most specific first).
- * ID is most reliable, then specific class combos, then single classes, then raw query.
- */
-function buildSearchQueries(elementId, classes, tag, query) {
- const queries = [];
-
- // 1. ID is the most specific
- if (elementId) {
- queries.push('id="' + elementId + '"');
- }
-
- // 2. Full class attribute match (for elements with distinctive multi-class combos).
- // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
- // convention the file uses will match.
- if (classes) {
- const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
- if (classList.length > 1) {
- const joined = classList.join(' ');
- const sorted = [...classList].sort((a, b) => b.length - a.length);
- queries.push('class="' + joined + '"');
- queries.push('className="' + joined + '"');
- queries.push(sorted[0]); // most distinctive single class, fallback
- } else if (classList.length === 1) {
- queries.push(classList[0]);
- }
- }
-
- // 3. Tag + class combo (e.g., <section class="hero">).
- // Same dual-emit for JSX compatibility.
- if (tag && classes) {
- const firstClass = classes.split(',')[0].trim();
- queries.push('<' + tag + ' class="' + firstClass);
- queries.push('<' + tag + ' className="' + firstClass);
- }
-
- // 4. Raw fallback query
- if (query) {
- queries.push(query);
- }
-
- return queries;
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- // HTML, Vue, Svelte, Astro all use HTML comments
- return { open: '<!--', close: '-->' };
-}
-
-function detectStyleMode(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.astro') {
- return {
- mode: 'astro-global-prefixed',
- styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',
- };
- }
- return {
- mode: 'scoped',
- styleTag: '<style data-impeccable-css="SESSION_ID">',
- };
-}
-
-function buildCssSelectorPrefixExamples(styleMode, count) {
- if (styleMode !== 'astro-global-prefixed') return [];
- return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);
-}
-
-function buildCssAuthoring(styleMode, count) {
- const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
- if (styleMode.mode === 'astro-global-prefixed') {
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'global-prefixed',
- rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',
- selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),
- requirements: [
- 'Use the styleTag exactly; the is:inline attribute is required for this file.',
- 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',
- 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
- ],
- forbidden: [
- 'Do not use @scope for this styleMode.',
- ],
- };
- }
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'scope-rule',
- rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',
- selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),
- requirements: [
- 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',
- 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
- 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
- ],
- forbidden: [
- 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',
- 'Do not add is:inline to the style tag for this styleMode.',
- ],
- };
-}
-
-/**
- * Search project files for the query string (class name, ID, etc.)
- * Returns the first matching file path, or null.
- */
-function findFileWithQuery(query, cwd, genOpts = {}) {
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, query, seen, 0, genOpts);
- if (result) return result;
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth, genOpts) {
- if (depth > 5) return null; // don't go too deep
- const realDir = fs.realpathSync(dir);
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- // Check files first
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name).toLowerCase();
- if (!EXTENSIONS.includes(ext)) continue;
-
- const filePath = path.join(dir, entry.name);
- if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip unreadable files */ }
- }
-
- // Then recurse into directories. Always skip node_modules and .git (never
- // project content). dist/build/out are left to the isGeneratedFile guard so
- // the includeGenerated second-pass can still find the element there and
- // report `generatedMatch`.
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
- if (result) return result;
- }
-
- return null;
-}
-
-/**
- * Regex that matches a tag opener on a line. Allows the tag name to be
- * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
- * openers (e.g. `<section\n className="..."\n>`) are recognised.
- */
-const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
-
-/**
- * Find the element's start and end line in the file.
- *
- * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
- * `id="..."`), or a raw text snippet. Because a query can appear on a
- * continuation line of a multi-line tag (e.g. the `className="..."` row of a
- * `<section\n className="..."\n>` JSX tag), we walk backward from the match
- * line to find the actual tag opener. When `tag` is provided, opener candidates
- * must match that tag name.
- */
-/**
- * Return the smallest leading-whitespace count across a set of lines,
- * ignoring blank lines (whose indent isn't load-bearing). Used to compute
- * the common base indent of a multi-line picked element so reindenting
- * under the wrapper preserves the relative depth between lines.
- */
-function minLeadingSpaces(lines) {
- let min = Infinity;
- for (const l of lines) {
- if (l.trim() === '') continue;
- const m = l.match(/^(\s*)/);
- if (m && m[1].length < min) min = m[1].length;
- }
- return min === Infinity ? 0 : min;
-}
-
-function findElement(lines, query, tag = null) {
- // Iterate all matches — the first substring hit isn't always the right one.
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
-
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- // Skip lines already inside a variant wrapper
- if (lines[i].includes('data-impeccable-variant')) continue;
-
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
-
- const endLine = findClosingLine(lines, openerLine);
- return { startLine: openerLine, endLine };
- }
-
- return null;
-}
-
-/**
- * Like findElement, but returns every match. Used for ambiguity detection
- * when the agent passes --text: when the same className appears on multiple
- * sibling elements (a list of cards, repeated section variants, etc.),
- * first-match silently lands on the wrong branch. Returning all matches lets
- * the caller narrow by textContent or fail with a structured ambiguity error.
- */
-function findAllElements(lines, query, tag = null) {
- const out = [];
- const seen = new Set();
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- if (lines[i].includes('data-impeccable-variant')) continue;
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
- if (seen.has(openerLine)) continue; // multiple matches inside the same element
- seen.add(openerLine);
- const endLine = findClosingLine(lines, openerLine);
- out.push({ startLine: openerLine, endLine });
- }
- return out;
-}
-
-/**
- * Narrow a candidate set to those whose source body matches a meaningful
- * prefix of the picked element's textContent. The compare strips tags and
- * JSX expressions, then checks two whitespace normalizations side-by-side:
- *
- * - single-space ("hero two second card body")
- * - no-whitespace ("herotwosecondcardbody")
- *
- * Both are needed because `el.textContent` concatenates sibling text without
- * inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
- * `"Hero TwoSecond…"`), while the source has whitespace between tags. If
- * EITHER normalization matches, the candidate keeps. A snippet shorter than
- * 8 chars after stripping is too weak to disambiguate — the caller falls
- * back to first-match.
- */
-function filterByText(candidates, lines, text) {
- const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
- // Too short to disambiguate. Return [] so the caller's `filtered.length
- // === 0` branch fires (fall back to first-match) — the previous
- // `candidates.slice()` return forced `filtered.length > 1` and surfaced
- // a spurious `element_ambiguous` error on every short-text picker event
- // with multiple candidates.
- if (trimmed.length < 8) return [];
- const targetSpaced = trimmed;
- const targetCompact = trimmed.replace(/\s+/g, '');
-
- return candidates.filter((c) => {
- const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
- const inner = body
- .replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
- .replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
- .toLowerCase();
- const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
- const sourceCompact = inner.replace(/\s+/g, '');
- return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
- });
-}
-
-/**
- * Resolve a match line to the real tag opener. If the match line itself opens
- * a tag, return it. Otherwise walk up to 10 lines backward looking for the
- * first tag opener. If `tag` is specified, the opener must match that tag
- * name; an opener with a different tag name aborts the backward walk for this
- * match (we don't jump across element boundaries).
- *
- * Returns the line index of the opener, or -1 if none can be resolved.
- */
-function findOpenerLine(lines, matchLine, tag) {
- const self = lines[matchLine].match(OPENER_RE);
- if (self) {
- if (!tag || self[1] === tag) return matchLine;
- return -1;
- }
- const MAX_BACKWALK = 10;
- for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
- const opener = lines[i].match(OPENER_RE);
- if (!opener) continue;
- if (!tag || opener[1] === tag) return i;
- // Different tag name than requested — abort; we're inside a non-target opener.
- return -1;
- }
- return -1;
-}
-
-/**
- * Starting from a line with an opening tag, find the line with the matching
- * closing tag by counting tag nesting depth.
- */
-function findClosingLine(lines, start) {
- const openMatch = lines[start].match(OPENER_RE);
- if (!openMatch) return start; // caller passed a non-opener; nothing to span
-
- const tagName = openMatch[1];
- let depth = 0;
- const openRe = new RegExp('<' + tagName + '(?=[\\s/>]|$)', 'g');
- const selfCloseRe = new RegExp('<' + tagName + '[^>]*/>', 'g');
- const closeRe = new RegExp('</' + tagName + '\\s*>', 'g');
-
- for (let i = start; i < lines.length; i++) {
- const line = lines[i];
- const opens = (line.match(openRe) || []).length;
- const selfCloses = (line.match(selfCloseRe) || []).length;
- const closes = (line.match(closeRe) || []).length;
-
- depth += opens - selfCloses - closes;
-
- if (depth <= 0) return i;
- }
-
- // If we can't find the close, return a reasonable guess
- return Math.min(start + 50, lines.length - 1);
-}
-
-// Auto-execute when run directly (node live-wrap.mjs ...)
-const _running = process.argv[1];
-if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {
- wrapCli();
-}
-
-// Test exports (used by tests/live-wrap.test.mjs)
-export { buildSearchQueries, findElement, findClosingLine, detectCommentSyntax };
@@ -1,247 +0,0 @@
-/**
- * CLI entry point: prepare everything needed to enter the live variant poll loop.
- *
- * Does (all in one command):
- * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)
- * 2. Start the live server in the background (or reuse a running one)
- * 3. Inject the browser script tag into the project's entry file
- * 4. Read PRODUCT.md / DESIGN.md for project context
- * 5. Print a single JSON blob with everything the agent needs
- *
- * After this, the agent's only remaining steps are:
- * - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll
- * - Enter the poll loop: `node live-poll.mjs`
- *
- * Usage:
- * node live.mjs # Prepare everything, print JSON, exit
- * node live.mjs --help
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { loadContext } from './load-context.mjs';
-import { resolveFiles } from './live-inject.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-async function liveCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live.mjs
-
-Prepare everything for live variant mode in a single command:
- - Checks .impeccable/live/config.json (required, created once per project)
- - Starts (or reuses) the live server in the background
- - Injects the browser script tag
- - Reads PRODUCT.md / DESIGN.md for project context
-
-On success, prints a JSON blob with:
- { ok, serverPort, serverToken, pageFile, hasContext, context }
-
-On config_missing, prints:
- { ok: false, error: "config_missing", configPath, hint }
-
-The agent should then:
- 1. If config_missing, create the config and re-run this script
- 2. Optionally open the project's dev/preview URL in the browser (see reference/live.md—not serverPort)
- 3. Enter the poll loop: node live-poll.mjs`);
- process.exit(0);
- }
-
- // 1. Check config (fail fast if missing — no point starting anything else)
- const checkOut = runScript('live-inject.mjs', ['--check']);
- const checkResult = safeParse(checkOut);
- if (!checkResult || !checkResult.ok) {
- console.log(JSON.stringify(checkResult || { ok: false, error: 'check_failed', raw: checkOut }));
- process.exit(0);
- }
-
- // 2. Start server (or reuse existing)
- const serverInfo = ensureServerRunning();
- if (!serverInfo) {
- console.log(JSON.stringify({ ok: false, error: 'server_start_failed' }));
- process.exit(1);
- }
-
- // 3. Inject the script tag at the current port
- const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)]);
- const injectResult = safeParse(injectOut);
- if (!injectResult || !injectResult.ok) {
- console.log(JSON.stringify({
- ok: false,
- error: 'inject_failed',
- detail: injectResult || injectOut,
- serverPort: serverInfo.port,
- }));
- process.exit(1);
- }
-
- // 4. Load PRODUCT.md + DESIGN.md context (auto-migrates legacy .impeccable.md)
- const ctx = loadContext(process.cwd());
-
- // 5. Compute drift-heal: compare resolved inject targets against the
- // project's HTML files. Orphans are HTML files not covered by config.
- // Warning only — the agent decides whether to act.
- const resolvedFiles = resolveFiles(process.cwd(), checkResult.config);
- const drift = scanForDrift(process.cwd(), resolvedFiles, checkResult.config);
-
- // 6. Emit everything the agent needs
- console.log(JSON.stringify({
- ok: true,
- serverPort: serverInfo.port,
- serverToken: serverInfo.token,
- pageFiles: resolvedFiles,
- configDrift: drift,
- hasProduct: ctx.hasProduct,
- product: ctx.product,
- productPath: ctx.productPath,
- hasDesign: ctx.hasDesign,
- design: ctx.design,
- designPath: ctx.designPath,
- migrated: ctx.migrated,
- }, null, 2));
-}
-
-/**
- * Drift-heal scan. Walks the project for HTML files under common
- * page-source directories (public/, src/, app/, pages/) and reports any
- * that aren't covered by the resolved inject targets. This is purely
- * advisory — the agent can ignore it, or suggest the user add the
- * orphans to config.files.
- *
- * Skipped if config.files already contains at least one glob pattern
- * covering everything in practice (signaled by the orphan count being 0).
- */
-function scanForDrift(rootDir, resolvedFiles, config) {
- const SCAN_ROOTS = ['public', 'src', 'app', 'pages'];
- const IGNORE_DIRS = new Set([
- 'node_modules', '.git', '.next', '.nuxt', '.svelte-kit', '.astro',
- '.turbo', '.vercel', '.cache', 'coverage', 'dist', 'build',
- ]);
-
- const resolvedSet = new Set(resolvedFiles.map((f) => f.split(path.sep).join('/')));
-
- // Files matching the user's `exclude` globs are intentional omissions,
- // not drift. Compile them to regexes so the orphan list stays signal.
- const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
- .map((p) => globToRegex(p));
- const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
-
- const orphans = [];
-
- const walk = (dir, relBase) => {
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
- for (const e of entries) {
- const rel = relBase ? `${relBase}/${e.name}` : e.name;
- if (e.isDirectory()) {
- if (IGNORE_DIRS.has(e.name) || e.name.startsWith('.')) continue;
- walk(path.join(dir, e.name), rel);
- } else if (e.isFile() && e.name.endsWith('.html')) {
- if (resolvedSet.has(rel)) continue;
- if (isUserExcluded(rel)) continue;
- orphans.push(rel);
- }
- }
- };
-
- for (const root of SCAN_ROOTS) {
- const abs = path.join(rootDir, root);
- if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
- walk(abs, root);
- }
- }
-
- if (orphans.length === 0) return null;
- const capped = orphans.slice(0, 20);
- return {
- orphans: capped,
- orphanCount: orphans.length,
- hint: `${orphans.length} HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like "public/**/*.html".`,
- };
-}
-
-/**
- * Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
- * to avoid a circular import (live-inject.mjs already imports nothing
- * from live.mjs). The two must stay in sync.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
- else { re += '.*'; i += 2; }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function runScript(name, args) {
- const scriptPath = path.join(__dirname, name);
- const cmd = `node "${scriptPath}" ${args.map(a => `"${a}"`).join(' ')}`;
- try {
- return execSync(cmd, { encoding: 'utf-8', cwd: process.cwd(), timeout: 15_000 });
- } catch (err) {
- // execSync throws on non-zero exit; return stdout if any
- return err.stdout || err.message || '';
- }
-}
-
-function safeParse(out) {
- try { return JSON.parse(String(out).trim()); } catch { return null; }
-}
-
-/**
- * Return { pid, port, token } for the running live server, starting one if needed.
- */
-function ensureServerRunning() {
- // Try to reuse an existing server
- try {
- const existing = readLiveServerInfo(process.cwd())?.info;
- if (existing && existing.pid) {
- try {
- process.kill(existing.pid, 0); // throws if dead
- return existing;
- } catch { /* stale PID file — the server script will clean it up */ }
- }
- } catch { /* no PID file */ }
-
- // Start a new server
- const out = runScript('live-server.mjs', ['--background']);
- return safeParse(out);
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live.mjs') || _running?.endsWith('live.mjs/')) {
- liveCli();
-}
@@ -1,141 +0,0 @@
-/**
- * Shared context loader for every impeccable command that needs to know
- * "who is this for" and "what does this look like".
- *
- * Input: project root (process.cwd()).
- *
- * Output (JSON to stdout):
- * {
- * hasProduct: boolean, // PRODUCT.md found (or auto-migrated)
- * product: string | null, // PRODUCT.md contents
- * productPath: string | null, // relative path
- * hasDesign: boolean, // DESIGN.md found
- * design: string | null, // DESIGN.md contents
- * designPath: string | null,
- * migrated: boolean, // true if we auto-renamed .impeccable.md -> PRODUCT.md
- * contextDir: string, // absolute path of the directory the files were found in
- * }
- *
- * Filename matching is case-insensitive for PRODUCT.md and DESIGN.md. The
- * Google DESIGN.md convention is uppercase at repo root; Kiro-style and
- * lowercase variants are also matched so users don't get punished for case.
- *
- * Lookup directory resolution (first match wins):
- * 1. process.env.IMPECCABLE_CONTEXT_DIR (absolute or relative to cwd)
- * 2. cwd, if PRODUCT.md / DESIGN.md / .impeccable.md is there (back-compat)
- * 3. Auto-fallback subdirectories of cwd: .agents/context/, then docs/
- * 4. cwd as a default "no context found" location
- *
- * Legacy `.impeccable.md` -> PRODUCT.md migration only fires at cwd root;
- * fallback directories are read-only as far as auto-rename is concerned.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
-const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
-const LEGACY_NAMES = ['.impeccable.md'];
-const FALLBACK_DIRS = ['.agents/context', 'docs'];
-
-/**
- * Resolve the directory that holds PRODUCT.md / DESIGN.md for
- * this project. Exported so other scripts (e.g. live-server.mjs) can read the
- * design files from the same location the loader uses.
- */
-export function resolveContextDir(cwd = process.cwd()) {
- // 1. Explicit override
- const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
- if (envDir && envDir.trim()) {
- const trimmed = envDir.trim();
- return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- }
-
- // 2. cwd wins if any canonical or legacy file is there. We check legacy too
- // so the auto-migration path in loadContext stays predictable.
- if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES, ...LEGACY_NAMES])) {
- return cwd;
- }
-
- // 3. Auto-fallback subdirs. Match if PRODUCT.md or DESIGN.md is present;
- // legacy `.impeccable.md` does not pull the lookup into a fallback dir.
- for (const rel of FALLBACK_DIRS) {
- const candidate = path.resolve(cwd, rel);
- if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
- return candidate;
- }
- }
-
- // 4. Nothing found — keep the historical "default to cwd" behaviour so the
- // caller's `hasProduct === false` branch still fires the same way.
- return cwd;
-}
-
-export function loadContext(cwd = process.cwd()) {
- let migrated = false;
- const contextDir = resolveContextDir(cwd);
-
- // 1. Look for PRODUCT.md (case-insensitive) in the resolved dir
- let productPath = firstExisting(contextDir, PRODUCT_NAMES);
-
- // 2. Legacy: if no PRODUCT.md but .impeccable.md exists at cwd root, rename
- // it in place. We only migrate at the root — fallback dirs are read-only
- // so we don't surprise users by mutating files under docs/ or .agents/.
- if (!productPath && contextDir === cwd) {
- const legacyPath = firstExisting(cwd, LEGACY_NAMES);
- if (legacyPath) {
- const newPath = path.join(cwd, 'PRODUCT.md');
- try {
- fs.renameSync(legacyPath, newPath);
- productPath = newPath;
- migrated = true;
- } catch {
- // Rename failed (permissions, etc.) — fall back to reading legacy in place
- productPath = legacyPath;
- }
- }
- }
-
- // 3. DESIGN.md (case-insensitive)
- const designPath = firstExisting(contextDir, DESIGN_NAMES);
-
- const product = productPath ? safeRead(productPath) : null;
- const design = designPath ? safeRead(designPath) : null;
-
- return {
- hasProduct: !!product,
- product,
- productPath: productPath ? path.relative(cwd, productPath) : null,
- hasDesign: !!design,
- design,
- designPath: designPath ? path.relative(cwd, designPath) : null,
- migrated,
- contextDir,
- };
-}
-
-function firstExisting(dir, names) {
- for (const name of names) {
- const abs = path.join(dir, name);
- if (fs.existsSync(abs)) return abs;
- }
- return null;
-}
-
-function safeRead(p) {
- try { return fs.readFileSync(p, 'utf-8'); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// CLI mode — print the context as JSON
-// ---------------------------------------------------------------------------
-
-function cli() {
- const result = loadContext(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('load-context.mjs') || _running?.endsWith('load-context.mjs/')) {
- cli();
-}
@@ -1,14 +0,0 @@
@@ -1,214 +0,0 @@
-#!/usr/bin/env node
-/**
- * Pin/unpin sub-commands as standalone skill shortcuts.
- *
- * Usage:
- * node <scripts_path>/pin.mjs pin <command>
- * node <scripts_path>/pin.mjs unpin <command>
- *
- * `pin audit` creates a lightweight /audit skill that redirects to /impeccable audit.
- * `unpin audit` removes that shortcut.
- *
- * The script discovers harness directories (.claude/skills, .cursor/skills, etc.)
- * in the project root and creates/removes the pin in all of them.
- */
-
-import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
-import { join, resolve, dirname } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-// All known harness directories
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Valid sub-command names
-const VALID_COMMANDS = [
- 'craft', 'teach', 'extract', 'document', 'shape',
- 'critique', 'audit',
- 'polish', 'bolder', 'quieter', 'distill', 'harden', 'onboard', 'live',
- 'animate', 'colorize', 'typeset', 'layout', 'delight', 'overdrive',
- 'clarify', 'adapt', 'optimize',
-];
-
-// Marker to identify pinned skills (so unpin doesn't delete user skills)
-const PIN_MARKER = '<!-- impeccable-pinned-skill -->';
-
-/**
- * Walk up from startDir to find a project root.
- */
-function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- while (dir !== '/') {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Find harness skill directories that have an impeccable skill installed.
- */
-function findHarnessDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const skillsDir = join(projectRoot, harness, 'skills');
- // Only pin in harness dirs that already have impeccable installed
- const impeccableDir = join(skillsDir, 'impeccable');
- if (existsSync(impeccableDir) || existsSync(join(skillsDir, 'i-impeccable'))) {
- dirs.push(skillsDir);
- }
- }
- return dirs;
-}
-
-/**
- * Load command metadata (descriptions for pinned skills).
- */
-function loadCommandMetadata() {
- const metadataPath = join(__dirname, 'command-metadata.json');
- if (existsSync(metadataPath)) {
- return JSON.parse(readFileSync(metadataPath, 'utf-8'));
- }
- return {};
-}
-
-/**
- * Generate a pinned skill's SKILL.md content.
- */
-function generatePinnedSkill(command, metadata) {
- const desc = metadata[command]?.description || `Shortcut for /impeccable ${command}.`;
- const hint = metadata[command]?.argumentHint || '[target]';
-
- return `---
-name: ${command}
-description: "${desc}"
-argument-hint: "${hint}"
-user-invocable: true
----
-
-${PIN_MARKER}
-
-This is a pinned shortcut for \`{{command_prefix}}impeccable ${command}\`.
-
-Invoke {{command_prefix}}impeccable ${command}, passing along any arguments provided here, and follow its instructions.
-`;
-}
-
-/**
- * Pin a command: create shortcut skill in all harness dirs.
- */
-function pin(command, projectRoot) {
- const metadata = loadCommandMetadata();
- const harnessDirs = findHarnessDirs(projectRoot);
-
- if (harnessDirs.length === 0) {
- console.log('No harness directories with impeccable installed found.');
- return false;
- }
-
- const content = generatePinnedSkill(command, metadata);
- let created = 0;
-
- for (const skillsDir of harnessDirs) {
- // Check if skill already exists (and isn't a pin)
- const skillDir = join(skillsDir, command);
- if (existsSync(skillDir)) {
- const existingMd = join(skillDir, 'SKILL.md');
- if (existsSync(existingMd)) {
- const existing = readFileSync(existingMd, 'utf-8');
- if (!existing.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (non-pinned skill already exists)`);
- continue;
- }
- }
- }
-
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(join(skillDir, 'SKILL.md'), content, 'utf-8');
- console.log(` + ${skillDir}`);
- created++;
- }
-
- if (created > 0) {
- console.log(`\nPinned '${command}' as a standalone shortcut in ${created} location(s).`);
- console.log(`You can now use /${command} directly.`);
- }
-
- return created > 0;
-}
-
-/**
- * Unpin a command: remove shortcut skill from all harness dirs.
- */
-function unpin(command, projectRoot) {
- const harnessDirs = findHarnessDirs(projectRoot);
- let removed = 0;
-
- for (const skillsDir of harnessDirs) {
- const skillDir = join(skillsDir, command);
- if (!existsSync(skillDir)) continue;
-
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) continue;
-
- // Safety: only remove if it's a pinned skill
- const content = readFileSync(skillMd, 'utf-8');
- if (!content.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (not a pinned skill)`);
- continue;
- }
-
- rmSync(skillDir, { recursive: true, force: true });
- console.log(` - ${skillDir}`);
- removed++;
- }
-
- if (removed > 0) {
- console.log(`\nUnpinned '${command}' from ${removed} location(s).`);
- console.log(`Use /impeccable ${command} to access it.`);
- } else {
- console.log(`No pinned '${command}' shortcut found.`);
- }
-
- return removed > 0;
-}
-
-// --- CLI ---
-const [,, action, command] = process.argv;
-
-if (!action || !command) {
- console.log('Usage: node pin.mjs <pin|unpin> <command>');
- console.log(`\nAvailable commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-if (action !== 'pin' && action !== 'unpin') {
- console.error(`Unknown action: ${action}. Use 'pin' or 'unpin'.`);
- process.exit(1);
-}
-
-if (!VALID_COMMANDS.includes(command)) {
- console.error(`Unknown command: ${command}`);
- console.error(`Available commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-const root = findProjectRoot();
-
-if (action === 'pin') {
- pin(command, root);
-} else {
- unpin(command, root);
-}
@@ -1,169 +0,0 @@
----
-name: impeccable
-description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
-version: 3.1.1
-user-invocable: true
-argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · teach|document|extract|live] [target]"
-license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
-allowed-tools:
- - Bash(npx impeccable *)
----
-
-Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
-
-## Setup
-
-Before any design work or file edits:
-
-1. Load context (PRODUCT.md / DESIGN.md) via the loader script.
-2. Identify the register and load the matching register reference (brand.md or product.md).
-3. **If the user invoked a sub-command (e.g. `craft`, `shape`, `audit`), load its reference file too.** This is non-negotiable: `craft` without `craft.md` loaded means you'll skip the shape-and-confirm step the user expects.
-
-Skipping these produces generic output that ignores the project.
-
-### 1. Context gathering
-
-Two files, case-insensitive. The loader looks at the project root by default and falls back to `.agents/context/` and `docs/` if the root is clean. Override with `IMPECCABLE_CONTEXT_DIR=path/to/dir` (absolute or relative to cwd).
-
-- **PRODUCT.md**: required. Users, brand, tone, anti-references, strategic principles.
-- **DESIGN.md**: optional, strongly recommended. Colors, typography, elevation, components.
-
-Load both in one call:
-
-```bash
-node .opencode/skills/impeccable/scripts/load-context.mjs
-```
-
-Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`. The output's `contextDir` field tells you where the files were resolved from.
-
-If the output is already in this session's conversation history, don't re-run. Exceptions requiring a fresh load: you just ran `/impeccable teach` or `/impeccable document` (they rewrite the files), or the user manually edited one.
-
-`/impeccable live` already warms context via `live.mjs`. If you've run `live.mjs`, don't also run `load-context.mjs` this session.
-
-If PRODUCT.md is missing, empty, or placeholder (`[TODO]` markers, <200 chars): run `/impeccable teach`, then resume the user's original task with the fresh context. If the original task was `/impeccable craft`, resume into `/impeccable shape` before any implementation work.
-
-If DESIGN.md is missing: nudge once per session (*"Run `/impeccable document` for more on-brand output"*), then proceed.
-
-### 2. Register
-
-Every design task is **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboard, tool: design SERVES the product).
-
-Identify before designing. Priority: (1) cue in the task itself ("landing page" vs "dashboard"); (2) the surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. First match wins.
-
-If PRODUCT.md lacks the `register` field (legacy), infer it once from its "Users" and "Product Purpose" sections, then cache the inferred value for the session. Suggest the user run `/impeccable teach` to add the field explicitly.
-
-Load the matching reference: [reference/brand.md](reference/brand.md) or [reference/product.md](reference/product.md). The shared design laws below apply to both.
-
-## Shared design laws
-
-Apply to every design, both registers. Match implementation complexity to the aesthetic vision: maximalism needs elaborate code, minimalism needs precision. Interpret creatively. Vary across projects; never converge on the same choices. Claude is capable of extraordinary work. Don't hold back.
-
-### Color
-
-- Use OKLCH. Reduce chroma as lightness approaches 0 or 100; high chroma at extremes looks garish.
-- Never use `#000` or `#fff`. Tint every neutral toward the brand hue (chroma 0.005–0.01 is enough).
-- Pick a **color strategy** before picking colors. Four steps on the commitment axis:
- - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism.
- - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages.
- - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz.
- - **Drenched**: the surface IS the color. Brand heroes, campaign pages.
-- The "one accent ≤10%" rule is Restrained only. Committed / Full palette / Drenched exceed it on purpose. Don't collapse every design to Restrained by reflex.
-
-### Theme
-
-Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe."
-
-Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does.
-
-"Observability dashboard" does not force an answer. "SRE glancing at incident severity on a 27-inch monitor at 2am in a dim room" does. Run the sentence, not the category.
-
-### Typography
-
-- Cap body line length at 65–75ch.
-- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales.
-
-### Layout
-
-- Vary spacing for rhythm. Same padding everywhere is monotony.
-- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
-- Don't wrap everything in a container. Most things don't need one.
-
-### Motion
-
-- Don't animate CSS layout properties.
-- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
-
-### Absolute bans
-
-Match-and-refuse. If you're about to write any of these, rewrite the element with different structure.
-
-- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing.
-- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size.
-- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing.
-- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché.
-- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly.
-- **Modal as first thought.** Modals are usually laziness. Exhaust inline / progressive alternatives first.
-
-### Copy
-
-- Every word earns its place. No restated headings, no intros that repeat the title.
-- **No em dashes.** Use commas, colons, semicolons, periods, or parentheses. Also not `--`.
-
-### The AI slop test
-
-If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference.
-
-**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses.
-
-- **First-order:** if someone could guess the theme + palette from the category alone ("observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black"), it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
-- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families.
-
-## Commands
-
-| Command | Category | Description | Reference |
-|---|---|---|---|
-| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) |
-| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) |
-| `teach` | Build | Set up PRODUCT.md and DESIGN.md context | [reference/teach.md](reference/teach.md) |
-| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) |
-| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) |
-| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) |
-| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) |
-| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) |
-| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) |
-| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) |
-| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) |
-| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) |
-| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) |
-| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) |
-| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) |
-| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) |
-| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) |
-| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) |
-| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) |
-| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) |
-| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) |
-| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
-| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
-
-### Routing rules
-
-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
-3. **First word doesn't match**: general design invocation. Apply the setup steps, shared design laws, and the loaded register reference, using the full argument as context.
-
-Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `/impeccable`.
-
-If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `teach` as a blocker, finish teach, refresh context, then resume the original command and target.
-
-## Pin / Unpin
-
-**Pin** creates a standalone shortcut so `/<command>` invokes `/impeccable <command>` directly. **Unpin** removes it. The script writes to every harness directory present in the project.
-
-```bash
-node .opencode/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
-```
-
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
@@ -1,190 +0,0 @@
-> **Additional context needed**: target platforms/devices and usage contexts.
-
-Adapt an existing design to a different context: another screen size, device, platform, or use case. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context.
-
-
----
-
-## Assess Adaptation Challenge
-
-Understand what needs adaptation and why:
-
-1. **Identify the source context**:
- - What was it designed for originally? (Desktop web? Mobile app?)
- - What assumptions were made? (Large screen? Mouse input? Fast connection?)
- - What works well in current context?
-
-2. **Understand target context**:
- - **Device**: Mobile, tablet, desktop, TV, watch, print?
- - **Input method**: Touch, mouse, keyboard, voice, gamepad?
- - **Screen constraints**: Size, resolution, orientation?
- - **Connection**: Fast wifi, slow 3G, offline?
- - **Usage context**: On-the-go vs desk, quick glance vs focused reading?
- - **User expectations**: What do users expect on this platform?
-
-3. **Identify adaptation challenges**:
- - What won't fit? (Content, navigation, features)
- - What won't work? (Hover states on touch, tiny touch targets)
- - What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop)
-
-**CRITICAL**: Adaptation is rethinking the experience for the new context, not scaling pixels.
-
-## Plan Adaptation Strategy
-
-Create context-appropriate strategy:
-
-### Mobile Adaptation (Desktop → Mobile)
-
-**Layout Strategy**:
-- Single column instead of multi-column
-- Vertical stacking instead of side-by-side
-- Full-width components instead of fixed widths
-- Bottom navigation instead of top/side navigation
-
-**Interaction Strategy**:
-- Touch targets 44x44px minimum (not hover-dependent)
-- Swipe gestures where appropriate (lists, carousels)
-- Bottom sheets instead of dropdowns
-- Thumbs-first design (controls within thumb reach)
-- Larger tap areas with more spacing
-
-**Content Strategy**:
-- Progressive disclosure (don't show everything at once)
-- Prioritize primary content (secondary content in tabs/accordions)
-- Shorter text (more concise)
-- Larger text (16px minimum)
-
-**Navigation Strategy**:
-- Hamburger menu or bottom navigation
-- Reduce navigation complexity
-- Sticky headers for context
-- Back button in navigation flow
-
-### Tablet Adaptation (Hybrid Approach)
-
-**Layout Strategy**:
-- Two-column layouts (not single or three-column)
-- Side panels for secondary content
-- Master-detail views (list + detail)
-- Adaptive based on orientation (portrait vs landscape)
-
-**Interaction Strategy**:
-- Support both touch and pointer
-- Touch targets 44x44px but allow denser layouts than phone
-- Side navigation drawers
-- Multi-column forms where appropriate
-
-### Desktop Adaptation (Mobile → Desktop)
-
-**Layout Strategy**:
-- Multi-column layouts (use horizontal space)
-- Side navigation always visible
-- Multiple information panels simultaneously
-- Fixed widths with max-width constraints (don't stretch to 4K)
-
-**Interaction Strategy**:
-- Hover states for additional information
-- Keyboard shortcuts
-- Right-click context menus
-- Drag and drop where helpful
-- Multi-select with Shift/Cmd
-
-**Content Strategy**:
-- Show more information upfront (less progressive disclosure)
-- Data tables with many columns
-- Richer visualizations
-- More detailed descriptions
-
-### Print Adaptation (Screen → Print)
-
-**Layout Strategy**:
-- Page breaks at logical points
-- Remove navigation, footer, interactive elements
-- Black and white (or limited color)
-- Proper margins for binding
-
-**Content Strategy**:
-- Expand shortened content (show full URLs, hidden sections)
-- Add page numbers, headers, footers
-- Include metadata (print date, page title)
-- Convert charts to print-friendly versions
-
-### Email Adaptation (Web → Email)
-
-**Layout Strategy**:
-- Narrow width (600px max)
-- Single column only
-- Inline CSS (no external stylesheets)
-- Table-based layouts (for email client compatibility)
-
-**Interaction Strategy**:
-- Large, obvious CTAs (buttons not text links)
-- No hover states (not reliable)
-- Deep links to web app for complex interactions
-
-## Implement Adaptations
-
-Apply changes systematically:
-
-### Responsive Breakpoints
-
-Choose appropriate breakpoints:
-- Mobile: 320px-767px
-- Tablet: 768px-1023px
-- Desktop: 1024px+
-- Or content-driven breakpoints (where design breaks)
-
-### Layout Adaptation Techniques
-
-- **CSS Grid/Flexbox**: Reflow layouts automatically
-- **Container Queries**: Adapt based on container, not viewport
-- **`clamp()`**: Fluid sizing between min and max
-- **Media queries**: Different styles for different contexts
-- **Display properties**: Show/hide elements per context
-
-### Touch Adaptation
-
-- Increase touch target sizes (44x44px minimum)
-- Add more spacing between interactive elements
-- Remove hover-dependent interactions
-- Add touch feedback (ripples, highlights)
-- Consider thumb zones (easier to reach bottom than top)
-
-### Content Adaptation
-
-- Use `display: none` sparingly (still downloads)
-- Progressive enhancement (core content first, enhancements on larger screens)
-- Lazy loading for off-screen content
-- Responsive images (`srcset`, `picture` element)
-
-### Navigation Adaptation
-
-- Transform complex nav to hamburger/drawer on mobile
-- Bottom nav bar for mobile apps
-- Persistent side navigation on desktop
-- Breadcrumbs on smaller screens for context
-
-**IMPORTANT**: Test on real devices. Device emulation in DevTools is helpful but not perfect.
-
-**NEVER**:
-- Hide core functionality on mobile (if it matters, make it work)
-- Assume desktop = powerful device (consider accessibility, older machines)
-- Use different information architecture across contexts (confusing)
-- Break user expectations for platform (mobile users expect mobile patterns)
-- Forget landscape orientation on mobile/tablet
-- Use generic breakpoints blindly (use content-driven breakpoints)
-- Ignore touch on desktop (many desktop devices have touch)
-
-## Verify Adaptations
-
-Test thoroughly across contexts:
-
-- **Real devices**: Test on actual phones, tablets, desktops
-- **Different orientations**: Portrait and landscape
-- **Different browsers**: Safari, Chrome, Firefox, Edge
-- **Different OS**: iOS, Android, Windows, macOS
-- **Different input methods**: Touch, mouse, keyboard
-- **Edge cases**: Very small screens (320px), very large screens (4K)
-- **Slow connections**: Test on throttled network
-
-When the adaptation feels native to each context, hand off to `/impeccable polish` for the final pass.
@@ -1,175 +0,0 @@
-> **Additional context needed**: performance constraints.
-
-Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it.
-
----
-
-## Register
-
-Brand: orchestrated page-load sequences, staggered reveals, scroll-driven animation. Motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions.
-
-Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it.
-
----
-
-## Assess Animation Opportunities
-
-Analyze where motion would improve the experience:
-
-1. **Identify static areas**:
- - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.)
- - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes)
- - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious
- - **Lack of delight**: Functional but joyless interactions
- - **Missed guidance**: Opportunities to direct attention or explain behavior
-
-2. **Understand the context**:
- - What's the personality? (Playful vs serious, energetic vs calm)
- - What's the performance budget? (Mobile-first? Complex page?)
- - Who's the audience? (Motion-sensitive users? Power users who want speed?)
- - What matters most? (One hero animation vs many micro-interactions?)
-
-If any of these are unclear from the codebase, STOP and call the `question` tool to clarify.
-
-**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them.
-
-## Plan Animation Strategy
-
-Create a purposeful animation plan:
-
-- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?)
-- **Feedback layer**: Which interactions need acknowledgment?
-- **Transition layer**: Which state changes need smoothing?
-- **Delight layer**: Where can we surprise and delight?
-
-**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments.
-
-## Implement Animations
-
-Add motion systematically across these categories:
-
-### Entrance Animations
-- **Page load choreography**: Stagger element reveals (100-150ms delays), fade + slide combinations
-- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects)
-- **Content reveals**: Scroll-triggered animations using intersection observer
-- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management
-
-### Micro-interactions
-- **Button feedback**:
- - Hover: Subtle scale (1.02-1.05), color shift, shadow increase
- - Click: Quick scale down then up (0.95 → 1), ripple effect
- - Loading: Spinner or pulse state
-- **Form interactions**:
- - Input focus: Border color transition, slight scale or glow
- - Validation: Shake on error, check mark on success, smooth color transitions
-- **Toggle switches**: Smooth slide + color transition (200-300ms)
-- **Checkboxes/radio**: Check mark animation, ripple effect
-- **Like/favorite**: Scale + rotation, particle effects, color transition
-
-### State Transitions
-- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms)
-- **Expand/collapse**: Height transition with overflow handling, icon rotation
-- **Loading states**: Skeleton screen fades, spinner animations, progress bars
-- **Success/error**: Color transitions, icon animations, gentle scale pulse
-- **Enable/disable**: Opacity transitions, cursor changes
-
-### Navigation & Flow
-- **Page transitions**: Crossfade between routes, shared element transitions
-- **Tab switching**: Slide indicator, content fade/slide
-- **Carousel/slider**: Smooth transforms, snap points, momentum
-- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators
-
-### Feedback & Guidance
-- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights
-- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning
-- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation
-- **Focus flow**: Highlight path through form or workflow
-
-### Delight Moments
-- **Empty states**: Subtle floating animations on illustrations
-- **Completed actions**: Confetti, check mark flourish, success celebrations
-- **Easter eggs**: Hidden interactions for discovery
-- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches
-
-## Technical Implementation
-
-Use appropriate techniques for each animation:
-
-### Timing & Easing
-
-**Durations by purpose:**
-- **100-150ms**: Instant feedback (button press, toggle)
-- **200-300ms**: State changes (hover, menu open)
-- **300-500ms**: Layout changes (accordion, modal)
-- **500-800ms**: Entrance animations (page load)
-
-**Easing curves (use these, not CSS defaults):**
-```css
-/* Recommended: natural deceleration */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */
-
-/* AVOID: feel dated and tacky */
-/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */
-/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */
-```
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-### CSS Animations
-```css
-/* Prefer for simple, declarative animations */
-- transitions for state changes
-- @keyframes for complex sequences
-- transform and opacity for reliable movement
-- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth
-```
-
-### JavaScript Animation
-```javascript
-/* Use for complex, interactive animations */
-- Web Animations API for programmatic control
-- Framer Motion for React
-- GSAP for complex sequences
-```
-
-### Performance
-- **Motion materials**: Use transform/opacity for reliable movement, but use blur, filters, masks, shadows, and color shifts when they materially improve the effect
-- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- **will-change**: Add sparingly for known expensive animations
-- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate
-- **Monitor FPS**: Ensure 60fps on target devices
-
-### Accessibility
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**NEVER**:
-- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself
-- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work
-- Use durations over 500ms for feedback (it feels laggy)
-- Animate without purpose (every animation needs a reason)
-- Ignore `prefers-reduced-motion` (this is an accessibility violation)
-- Animate everything (animation fatigue makes interfaces feel exhausting)
-- Block interaction during animations unless intentional
-
-## Verify Quality
-
-Test animations thoroughly:
-
-- **Smooth at 60fps**: No jank on target devices
-- **Feels natural**: Easing curves feel organic, not robotic
-- **Appropriate timing**: Not too fast (jarring) or too slow (laggy)
-- **Reduced motion works**: Animations disabled or simplified appropriately
-- **Doesn't block**: Users can interact during/after animations
-- **Adds value**: Makes interface clearer or more delightful
-
-When the motion clarifies state instead of decorating it, hand off to `/impeccable polish` for the final pass.
@@ -1,133 +0,0 @@
-Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues; document them for other commands to address.
-
-This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation.
-
-## Diagnostic Scan
-
-Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below.
-
-### 1. Accessibility (A11y)
-
-**Check for**:
-- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA)
-- **Missing ARIA**: Interactive elements without proper roles, labels, or states
-- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps
-- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons
-- **Alt text**: Missing or poor image descriptions
-- **Form issues**: Inputs without labels, poor error messaging, missing required indicators
-
-**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA)
-
-### 2. Performance
-
-**Check for**:
-- **Layout thrashing**: Reading/writing layout properties in loops
-- **Expensive animations**: Casual layout-property animation, unbounded blur/filter/shadow effects, or effects that visibly drop frames
-- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change
-- **Bundle size**: Unnecessary imports, unused dependencies
-- **Render performance**: Unnecessary re-renders, missing memoization
-
-**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized)
-
-### 3. Theming
-
-**Check for**:
-- **Hard-coded colors**: Colors not using design tokens
-- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme
-- **Inconsistent tokens**: Using wrong tokens, mixing token types
-- **Theme switching issues**: Values that don't update on theme change
-
-**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly)
-
-### 4. Responsive Design
-
-**Check for**:
-- **Fixed widths**: Hard-coded widths that break on mobile
-- **Touch targets**: Interactive elements < 44x44px
-- **Horizontal scroll**: Content overflow on narrow viewports
-- **Text scaling**: Layouts that break when text size increases
-- **Missing breakpoints**: No mobile/tablet variants
-
-**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets)
-
-### 5. Anti-Patterns (CRITICAL)
-
-Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy).
-
-**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design)
-
-## Generate Report
-
-### Audit Health Score
-
-| # | Dimension | Score | Key Finding |
-|---|-----------|-------|-------------|
-| 1 | Accessibility | ? | [most critical a11y issue or "--"] |
-| 2 | Performance | ? | |
-| 3 | Responsive Design | ? | |
-| 4 | Theming | ? | |
-| 5 | Anti-Patterns | ? | |
-| **Total** | | **??/20** | **[Rating band]** |
-
-**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues)
-
-### Anti-Patterns Verdict
-**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest.
-
-### Executive Summary
-- Audit Health Score: **??/20** ([rating band])
-- Total issues found (count by severity: P0/P1/P2/P3)
-- Top 3-5 critical issues
-- Recommended next steps
-
-### Detailed Findings by Severity
-
-Tag every issue with **P0-P3 severity**:
-- **P0 Blocking**: Prevents task completion. Fix immediately
-- **P1 Major**: Significant difficulty or WCAG AA violation. Fix before release
-- **P2 Minor**: Annoyance, workaround exists. Fix in next pass
-- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits
-
-For each issue, document:
-- **[P?] Issue name**
-- **Location**: Component, file, line
-- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern
-- **Impact**: How it affects users
-- **WCAG/Standard**: Which standard it violates (if applicable)
-- **Recommendation**: How to fix it
-- **Suggested command**: Which command to use (prefer: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-### Patterns & Systemic Issues
-
-Identify recurring problems that indicate systemic gaps rather than one-off mistakes:
-- "Hard-coded colors appear in 15+ components, should use design tokens"
-- "Touch targets consistently too small (<44px) throughout mobile experience"
-
-### Positive Findings
-
-Note what's working well: good practices to maintain and replicate.
-
-## Recommended Actions
-
-List recommended commands in priority order (P0 first, then P1, then P2):
-
-1. **[P?] `/command-name`**: Brief description (specific context from audit findings)
-2. **[P?] `/command-name`**: Brief description (specific context)
-
-**Rules**: Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset. Map findings to the most appropriate command. End with `/impeccable polish` as the final step if any fixes were recommended.
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable audit` after fixes to see your score improve.
-
-**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters.
-
-**NEVER**:
-- Report issues without explaining impact (why does this matter?)
-- Provide generic recommendations (be specific and actionable)
-- Skip positive findings (celebrate what works)
-- Forget to prioritize (everything can't be P0)
-- Report false positives without verification
-
@@ -1,113 +0,0 @@
-When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact and personality through stronger hierarchy, committed scale, and decisive type.
-
----
-
-## Register
-
-Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
-
-Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too safe or boring:
-
-1. **Identify weakness sources**:
- - **Generic choices**: System fonts, basic colors, standard layouts
- - **Timid scale**: Everything is medium-sized with no drama
- - **Low contrast**: Everything has similar visual weight
- - **Static**: No motion, no energy, no life
- - **Predictable**: Standard patterns with no surprises
- - **Flat hierarchy**: Nothing stands out or commands attention
-
-2. **Understand the context**:
- - What's the brand personality? (How far can we push?)
- - What's the purpose? (Marketing can be bolder than financial dashboards)
- - Who's the audience? (What will resonate?)
- - What are the constraints? (Brand guidelines, accessibility, performance)
-
-If any of these are unclear from the codebase, STOP and call the `question` tool to clarify.
-
-**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
-
-**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
-
-## Plan Amplification
-
-Create a strategy to increase impact while maintaining coherence:
-
-- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
-- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
-- **Risk budget**: How experimental can we be? Push boundaries within constraints.
-- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
-
-**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration.
-
-## Amplify the Design
-
-Systematically increase impact across these dimensions:
-
-### Typography Amplification
-- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and [typography.md](typography.md) for inspiration)
-- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
-- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
-- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
-
-### Color Intensification
-- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
-- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop
-- **Dominant color strategy**: Let one bold color own 60% of the design
-- **Sharp accents**: High-contrast accent colors that pop
-- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
-- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
-
-### Spatial Drama
-- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
-- **Break the grid**: Let hero elements escape containers and cross boundaries
-- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
-- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
-- **Overlap**: Layer elements intentionally for depth
-
-### Visual Effects
-- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
-- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
-- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop)
-- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
-- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
-
-### Motion & Animation
-- **Entrance choreography**: Staggered, dramatic page load animations with 50-100ms delays
-- **Scroll effects**: Parallax, reveal animations, scroll-triggered sequences
-- **Micro-interactions**: Satisfying hover effects, click feedback, state changes
-- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect)
-
-### Composition Boldness
-- **Hero moments**: Create clear focal points with dramatic treatment
-- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
-- **Full-bleed elements**: Use full viewport width/height for impact
-- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
-
-**NEVER**:
-- Add effects randomly without purpose (chaos ≠ bold)
-- Sacrifice readability for aesthetics (body text must be readable)
-- Make everything bold (then nothing is bold; you need contrast)
-- Ignore accessibility (bold design must still meet WCAG standards)
-- Overwhelm with motion (animation fatigue is real)
-- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
-
-## Verify Quality
-
-Ensure amplification maintains usability and coherence:
-
-- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over.
-- **Still functional**: Can users accomplish tasks without distraction?
-- **Coherent**: Does everything feel intentional and unified?
-- **Memorable**: Will users remember this experience?
-- **Performant**: Do all these effects run smoothly?
-- **Accessible**: Does it still meet accessibility standards?
-
-**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects."
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,118 +0,0 @@
-# Brand register
-
-When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made.
-
-The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look.
-
-## The brand slop test
-
-If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?"
-
-Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home.
-
-**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register.
-
-Then the inverse test: in one sentence, describe what you're about to build the way a competitor would describe theirs. If that sentence fits the modal landing page in the category, restart.
-
-## Typography
-
-### Font selection procedure
-
-Every project. Never skip.
-
-1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words.
-2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture.
-3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy."
-4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over.
-
-### Reflex-reject list
-
-Training-data defaults. Ban list. Look further:
-
-Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif
-
-### Reflex-reject aesthetic lanes
-
-Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further.
-
-- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery.
-
-(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.)
-
-The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md).
-
-### Pairing and voice
-
-Distinctive + refined is the goal. The specific shape depends on the brand:
-
-- **Editorial / long-form / luxury**: display serif + sans body (a magazine shape).
-- **Tech / dev tools / fintech**: one committed sans, usually; custom-tight tracking, strong weight contrast inside a single family.
-- **Consumer / food / travel**: warmer pairings, often a humanist sans plus a script or display serif.
-- **Creative studios / agencies**: rule-breaking welcome. Mono-only, or display-only, or custom-drawn type as voice.
-
-Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair.
-
-Vary across projects. If the last brief was a serif-display landing page, this one isn't.
-
-### Scale
-
-Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted.
-
-Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room.
-
-## Color
-
-Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register.
-
-- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige.
-- Palette IS voice. A calm brand and a restless brand should not share palette mechanics.
-- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit.
-- Don't converge across projects. If the last brand surface was restrained-on-cream, this one is not.
-- When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette.
-
-## Layout
-
-- Asymmetric compositions are one option. Break the grid intentionally for emphasis.
-- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings.
-- Alternative: a strict, visible grid as the voice (brutalist / Swiss / tech-spec aesthetics). Either asymmetric or rigorously-gridded can be "designed"; the failure mode is splitting the difference into a generic centered stack.
-- Don't default to centering everything. Left-aligned with asymmetric layouts feels more designed; a strict grid reads as confident structure. A centered-stack hero with icon-title-subtitle cards reads as template.
-- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness.
-
-## Imagery
-
-Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo.
-
-**When the brief implies imagery (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product), you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy.
-
-- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `<div>` placeholders.
-- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel".
-- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one.
-- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish".
-
-"Imagery" here is broader than stock photography: product screenshots, custom data visualizations, generated SVG, and canvas/WebGL scenes are all imagery. Text-only pages where typography alone carries the entire visual weight are the failure mode.
-
-## Motion
-
-- One well-orchestrated page-load with staggered reveals beats scattered micro-interactions, when the brand invites it. Tech-minimal brands often skip entrance motion entirely; the restraint is the voice.
-- For collapsing/expanding sections, transition `grid-template-rows` rather than `height`.
-
-## Brand bans (on top of the shared absolute bans)
-
-- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume.
-- Large rounded-corner icons above every heading. Screams template.
-- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.)
-- All-caps body copy. Reserve caps for short labels and headings.
-- Timid palettes and average layouts. Safe = invisible.
-- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs.
-- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic.
-- Repeated tiny uppercase tracked labels above every section heading. A single strong kicker can be voice; repeating it as section grammar is AI scaffolding unless it's a deliberate, named brand system.
-
-## Brand permissions
-
-Brand can afford things product can't. Take them.
-
-- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography.
-- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing.
-- Typographic risk. Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines, a single oversize word as a hero.
-- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics.
-- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment.
@@ -1,174 +0,0 @@
-> **Additional context needed**: audience technical level and users' mental state in context.
-
-Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task.
-
-
----
-
-## Assess Current Copy
-
-Identify what makes the text unclear or ineffective:
-
-1. **Find clarity problems**:
- - **Jargon**: Technical terms users won't understand
- - **Ambiguity**: Multiple interpretations possible
- - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file"
- - **Length**: Too wordy or too terse
- - **Assumptions**: Assuming user knowledge they don't have
- - **Missing context**: Users don't know what to do or why
- - **Tone mismatch**: Too formal, too casual, or inappropriate for situation
-
-2. **Understand the context**:
- - Who's the audience? (Technical? General? First-time users?)
- - What's the user's mental state? (Stressed during error? Confident during success?)
- - What's the action? (What do we want users to do?)
- - What's the constraint? (Character limits? Space limitations?)
-
-**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets.
-
-## Plan Copy Improvements
-
-Create a strategy for clearer communication:
-
-- **Primary message**: What's the ONE thing users need to know?
-- **Action needed**: What should users do next (if anything)?
-- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?)
-- **Constraints**: Length limits, brand voice, localization considerations
-
-**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words.
-
-## Improve Copy Systematically
-
-Refine text across these common areas:
-
-### Error Messages
-**Bad**: "Error 403: Forbidden"
-**Good**: "You don't have permission to view this page. Contact your admin for access."
-
-**Bad**: "Invalid input"
-**Good**: "Email addresses need an @ symbol. Try: name@example.com"
-
-**Principles**:
-- Explain what went wrong in plain language
-- Suggest how to fix it
-- Don't blame the user
-- Include examples when helpful
-- Link to help/support if applicable
-
-### Form Labels & Instructions
-**Bad**: "DOB (MM/DD/YYYY)"
-**Good**: "Date of birth" (with placeholder showing format)
-
-**Bad**: "Enter value here"
-**Good**: "Your email address" or "Company name"
-
-**Principles**:
-- Use clear, specific labels (not generic placeholders)
-- Show format expectations with examples
-- Explain why you're asking (when not obvious)
-- Put instructions before the field, not after
-- Keep required field indicators clear
-
-### Button & CTA Text
-**Bad**: "Click here" | "Submit" | "OK"
-**Good**: "Create account" | "Save changes" | "Got it, thanks"
-
-**Principles**:
-- Describe the action specifically
-- Use active voice (verb + noun)
-- Match user's mental model
-- Be specific ("Save" is better than "OK")
-
-### Help Text & Tooltips
-**Bad**: "This is the username field"
-**Good**: "Choose a username. You can change this later in Settings."
-
-**Principles**:
-- Add value (don't just repeat the label)
-- Answer the implicit question ("What is this?" or "Why do you need this?")
-- Keep it brief but complete
-- Link to detailed docs if needed
-
-### Empty States
-**Bad**: "No items"
-**Good**: "No projects yet. Create your first project to get started."
-
-**Principles**:
-- Explain why it's empty (if not obvious)
-- Show next action clearly
-- Make it welcoming, not dead-end
-
-### Success Messages
-**Bad**: "Success"
-**Good**: "Settings saved! Your changes will take effect immediately."
-
-**Principles**:
-- Confirm what happened
-- Explain what happens next (if relevant)
-- Be brief but complete
-- Match the user's emotional moment (celebrate big wins)
-
-### Loading States
-**Bad**: "Loading..." (for 30+ seconds)
-**Good**: "Analyzing your data... this usually takes 30-60 seconds"
-
-**Principles**:
-- Set expectations (how long?)
-- Explain what's happening (when it's not obvious)
-- Show progress when possible
-- Offer escape hatch if appropriate ("Cancel")
-
-### Confirmation Dialogs
-**Bad**: "Are you sure?"
-**Good**: "Delete 'Project Alpha'? This can't be undone."
-
-**Principles**:
-- State the specific action
-- Explain consequences (especially for destructive actions)
-- Use clear button labels ("Delete project" not "Yes")
-- Don't overuse confirmations (only for risky actions)
-
-### Navigation & Wayfinding
-**Bad**: Generic labels like "Items" | "Things" | "Stuff"
-**Good**: Specific labels like "Your projects" | "Team members" | "Settings"
-
-**Principles**:
-- Be specific and descriptive
-- Use language users understand (not internal jargon)
-- Make hierarchy clear
-- Consider information scent (breadcrumbs, current location)
-
-## Apply Clarity Principles
-
-Every piece of copy should follow these rules:
-
-1. **Be specific**: "Enter email" not "Enter value"
-2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity)
-3. **Be active**: "Save changes" not "Changes will be saved"
-4. **Be human**: "Oops, something went wrong" not "System error encountered"
-5. **Tell users what to do**, not just what happened
-6. **Be consistent**: Use same terms throughout (don't vary for variety)
-
-**NEVER**:
-- Use jargon without explanation
-- Blame users ("You made an error" → "This field is required")
-- Be vague ("Something went wrong" without explanation)
-- Use passive voice unnecessarily
-- Write overly long explanations (be concise)
-- Use humor for errors (be empathetic instead)
-- Assume technical knowledge
-- Vary terminology (pick one term and stick with it)
-- Repeat information (headers restating intros, redundant explanations)
-- Use placeholders as the only labels (they disappear when users type)
-
-## Verify Improvements
-
-Test that copy improvements work:
-
-- **Comprehension**: Can users understand without context?
-- **Actionability**: Do users know what to do next?
-- **Brevity**: Is it as short as possible while remaining clear?
-- **Consistency**: Does it match terminology elsewhere?
-- **Tone**: Is it appropriate for the situation?
-
-When the copy reads cleanly, hand off to `/impeccable polish` for the final pass.
@@ -1,105 +0,0 @@
-# Codex: Visual Direction & Asset Production
-
-This file is loaded by `/impeccable craft` when the harness has native image generation (currently Codex via `image_gen`). Other harnesses skip it. It covers the two craft steps that depend on real image generation: landing the visual direction, and producing the raster assets the implementation will compose.
-
-Read this *before* generating any images. The order matters, and the per-step user pauses are what keep generated imagery from drifting away from the brief.
-
-### Four stop points before code
-
-Steps A through D each end with the user. Do not advance past any of them on your own read of the situation.
-
-1. **STOP after Step A questions.** Wait for answers.
-2. **STOP after Step B palette generation.** Wait for "confirm palette."
-3. **STOP after Step C mocks.** Wait for direction approval or delegation.
-4. **Only after Step D approves a direction** do you return to craft.md Step 4 and write code.
-
-Prior shape approval does **not** satisfy any of these. Shape's "confirm or override" advances you into Step A; it is not a substitute for it.
-
-## Step A: Explore Directions with the User
-
-Before generating anything, run a brief direction conversation grounded in the shape brief.
-
-**Step A is required even when shape just produced a confirmed brief.** The shape questions and Step A questions cover different ground: shape pins purpose, content, scope; Step A pins palette, atmosphere, and named visual references for the comps you're about to generate. The only time you can skip Step A is when the user has already answered these exact palette/atmosphere/reference questions in the same session.
-
-Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions:
-
-- "Brief says 'editorial restraint, Klim-adjacent.' Are we closer to a quiet specimen page or a magazine-spread feel with hero imagery?"
-- "Palette strategy from shape was 'Committed.' Want it warm-grounded (deep oxblood + cream) or cool-grounded (slate + paper white)?"
-
-**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded.
-
-## Step B: Generate the Brand Palette First
-
-Generate **one** palette artifact before any mocks. This is a small, focused image: typography pairing on the chosen background, primary + accent color swatches, one signature ornament or motif. Single image, single pass.
-
-Why palette first: mocks generated against a vague color sense produce noise that drowns out the structural decisions. A confirmed palette is the first concrete contract for everything downstream.
-
-Show the palette to the user. Ask one question: "This is the palette I'm locking in for the mocks. Confirm, or call out what to shift?"
-
-**STOP and wait for confirmation.** Do not generate mocks against an unconfirmed palette. "Probably good enough" is the wrong call here; the palette is the contract for everything downstream.
-
-## Step C: Generate 1-3 Visual Mocks Against the Palette
-
-Once the palette is confirmed, generate **1 to 3** high-fidelity north-star comps. Each mock must use the confirmed palette and typography. Mocks differ in *structural* direction (hierarchy, topology, density, composition), not in color or motif.
-
-- Brand work: push visual identity, composition, mood, and signature motifs.
-- Product work: push hierarchy, topology, density, tone, grounded in realistic product structure.
-- Landing pages and long-form brand surfaces: show enough of the second fold to establish the system beyond the hero.
-
-Use the `image_gen` tool directly (or via the imagegen skill when available). Don't ask the user to install anything.
-
-## Step D: Approval Loop
-
-Show the comps. Ask what carries forward. Iterate until **one direction is approved** or the user explicitly delegates.
-
-**STOP and wait for the approval or the delegation.** Do not begin Step E or return to craft.md Step 4 until a single direction is named. If the user delegates, pick the strongest direction and explain it from the brief, not personal taste.
-
-Before moving to assets, summarize what to carry into code and what *not* to literalize from the mock. This is the handoff between visual exploration and semantic implementation.
-
-## Step E: Mock Fidelity Inventory
-
-Inventory the approved mock's major visible ingredients. For each, decide implementation: semantic HTML/CSS/SVG, generated raster, sourced raster, icon library, canvas/WebGL, or accepted omission.
-
-Common ingredients to inventory:
-
-- Hero silhouette and dominant composition
-- Signature motifs (planets, devices, portraits, charts, route lines, insets, badges, etc.)
-- Nav and primary CTA treatment
-- Section sequence, especially the second fold
-- Image-native content the concept depends on
-- Typography, density, color/material treatment, motion cues
-
-Treat the mock as a north star, not a screenshot to trace. Don't rasterize core UI text. But if the live result lacks the mock's major ingredients, the implementation is wrong.
-
-If a photographic, architectural, product, or place-led mock becomes generic CSS scenery, decorative diagrams, bullets, or copy, stop and fix it. That's a broken implementation, not a harmless interpretation.
-
-Don't substitute a different hero composition or visual driver post-approval without user sign-off.
-
-## Step F: Asset Slicing via the Asset Producer
-
-Raster ingredients identified in Step E need clean production assets. Use the bundled `impeccable_asset_producer` subagent rather than producing inline.
-
-Spawn it as a scoped subagent. If you do not have explicit permission to use agents, stop and ask:
-
-```text
-Asset production will work better as a scoped subagent job. Should I spawn the Impeccable asset producer subagent for this step?
-```
-
-Pass to the agent:
-
-- Approved mock path or screenshot reference
-- Crop paths or a contact sheet with crop ids
-- Output directory
-- Required dimensions, format, transparency needs
-- Avoid list
-- Notes on what should remain semantic HTML/CSS/SVG instead of raster
-
-Attach image generation capability to the spawned agent when the harness supports it. Do **not** load image-generation reference material into the parent thread.
-
-Inline asset production is allowed only if the user declines subagents, the harness cannot spawn the authorized agent, or the user explicitly asks for single-thread mode.
-
-Prefer HTML/CSS/SVG/canvas when they can credibly reproduce an ingredient; reach for real, generated, or stock imagery when the mock or subject matter calls for actual visual content.
-
-## After This File
-
-Once Steps A through F are complete, return to `craft.md` Step 5 (Build to Production Quality). The implementation builds against the confirmed palette, approved mock, and the assets the producer wrote.
@@ -1,106 +0,0 @@
-# Cognitive Load Assessment
-
-Cognitive load is the total mental effort required to use an interface. Overloaded users make mistakes, get frustrated, and leave. This reference helps identify and fix cognitive overload.
-
----
-
-## Three Types of Cognitive Load
-
-### Intrinsic Load: The Task Itself
-Complexity inherent to what the user is trying to do. You can't eliminate this, but you can structure it.
-
-**Manage it by**:
-- Breaking complex tasks into discrete steps
-- Providing scaffolding (templates, defaults, examples)
-- Progressive disclosure: show what's needed now, hide the rest
-- Grouping related decisions together
-
-### Extraneous Load: Bad Design
-Mental effort caused by poor design choices. **Eliminate this ruthlessly.** It's pure waste.
-
-**Common sources**:
-- Confusing navigation that requires mental mapping
-- Unclear labels that force users to guess meaning
-- Visual clutter competing for attention
-- Inconsistent patterns that prevent learning
-- Unnecessary steps between user intent and result
-
-### Germane Load: Learning Effort
-Mental effort spent building understanding. This is *good* cognitive load; it leads to mastery.
-
-**Support it by**:
-- Progressive disclosure that reveals complexity gradually
-- Consistent patterns that reward learning
-- Feedback that confirms correct understanding
-- Onboarding that teaches through action, not walls of text
-
----
-
-## Cognitive Load Checklist
-
-Evaluate the interface against these 8 items:
-
-- [ ] **Single focus**: Can the user complete their primary task without distraction from competing elements?
-- [ ] **Chunking**: Is information presented in digestible groups (≤4 items per group)?
-- [ ] **Grouping**: Are related items visually grouped together (proximity, borders, shared background)?
-- [ ] **Visual hierarchy**: Is it immediately clear what's most important on the screen?
-- [ ] **One thing at a time**: Can the user focus on a single decision before moving to the next?
-- [ ] **Minimal choices**: Are decisions simplified (≤4 visible options at any decision point)?
-- [ ] **Working memory**: Does the user need to remember information from a previous screen to act on the current one?
-- [ ] **Progressive disclosure**: Is complexity revealed only when the user needs it?
-
-**Scoring**: Count the failed items. 0–1 failures = low cognitive load (good). 2–3 = moderate (address soon). 4+ = high cognitive load (critical fix needed).
-
----
-
-## The Working Memory Rule
-
-**Humans can hold ≤4 items in working memory at once** (Miller's Law revised by Cowan, 2001).
-
-At any decision point, count the number of distinct options, actions, or pieces of information a user must simultaneously consider:
-- **≤4 items**: Within working memory limits, manageable
-- **5–7 items**: Pushing the boundary; consider grouping or progressive disclosure
-- **8+ items**: Overloaded; users will skip, misclick, or abandon
-
-**Practical applications**:
-- Navigation menus: ≤5 top-level items (group the rest under clear categories)
-- Form sections: ≤4 fields visible per group before a visual break
-- Action buttons: 1 primary, 1–2 secondary, group the rest in a menu
-- Dashboard widgets: ≤4 key metrics visible without scrolling
-- Pricing tiers: ≤3 options (more causes analysis paralysis)
-
----
-
-## Common Cognitive Load Violations
-
-### 1. The Wall of Options
-**Problem**: Presenting 10+ choices at once with no hierarchy.
-**Fix**: Group into categories, highlight recommended, use progressive disclosure.
-
-### 2. The Memory Bridge
-**Problem**: User must remember info from step 1 to complete step 3.
-**Fix**: Keep relevant context visible, or repeat it where it's needed.
-
-### 3. The Hidden Navigation
-**Problem**: User must build a mental map of where things are.
-**Fix**: Always show current location (breadcrumbs, active states, progress indicators).
-
-### 4. The Jargon Barrier
-**Problem**: Technical or domain language forces translation effort.
-**Fix**: Use plain language. If domain terms are unavoidable, define them inline.
-
-### 5. The Visual Noise Floor
-**Problem**: Every element has the same visual weight; nothing stands out.
-**Fix**: Establish clear hierarchy: one primary element, 2–3 secondary, everything else muted.
-
-### 6. The Inconsistent Pattern
-**Problem**: Similar actions work differently in different places.
-**Fix**: Standardize interaction patterns. Same type of action = same type of UI.
-
-### 7. The Multi-Task Demand
-**Problem**: Interface requires processing multiple simultaneous inputs (reading + deciding + navigating).
-**Fix**: Sequence the steps. Let the user do one thing at a time.
-
-### 8. The Context Switch
-**Problem**: User must jump between screens/tabs/modals to gather info for a single decision.
-**Fix**: Co-locate the information needed for each decision. Reduce back-and-forth.
@@ -1,105 +0,0 @@
-# Color & Contrast
-
-## Color Spaces: Use OKLCH
-
-**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark.
-
-The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish.
-
-The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand.
-
-## Building Functional Palettes
-
-### Tinted Neutrals
-
-**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces.
-
-The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette.
-
-**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects.
-
-### Palette Structure
-
-A complete system needs:
-
-| Role | Purpose | Example |
-|------|---------|---------|
-| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades |
-| **Neutral** | Text, backgrounds, borders | 9-11 shade scale |
-| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each |
-| **Surface** | Cards, modals, overlays | 2-3 elevation levels |
-
-**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise.
-
-### The 60-30-10 Rule (Applied Correctly)
-
-This rule is about **visual weight**, not pixel count:
-
-- **60%**: Neutral backgrounds, white space, base surfaces
-- **30%**: Secondary colors: text, borders, inactive states
-- **10%**: Accent: CTAs, highlights, focus states
-
-The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power.
-
-## Contrast & Accessibility
-
-### WCAG Requirements
-
-| Content Type | AA Minimum | AAA Target |
-|--------------|------------|------------|
-| Body text | 4.5:1 | 7:1 |
-| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 |
-| UI components, icons | 3:1 | 4.5:1 |
-| Non-essential decorations | None | None |
-
-**The gotcha**: Placeholder text still needs 4.5:1. That light gray placeholder you see everywhere? Usually fails WCAG.
-
-### Dangerous Color Combinations
-
-These commonly fail contrast or cause readability issues:
-
-- Light gray text on white (the #1 accessibility fail)
-- **Gray text on any colored background**: gray looks washed out and dead on color. Use a darker shade of the background color, or transparency
-- Red text on green background (or vice versa): 8% of men can't distinguish these
-- Blue text on red background (vibrates visually)
-- Yellow text on white (almost always fails)
-- Thin light text on images (unpredictable contrast)
-
-### Never Use Pure Gray or Pure Black
-
-Pure gray (`oklch(50% 0 0)`) and pure black (`#000`) don't exist in nature; real shadows and surfaces always have a color cast. Even a chroma of 0.005-0.01 is enough to feel natural without being obviously tinted. (See tinted neutrals example above.)
-
-### Testing
-
-Don't trust your eyes. Use tools:
-
-- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/)
-- Browser DevTools → Rendering → Emulate vision deficiencies
-- [Polypane](https://polypane.app/) for real-time testing
-
-## Theming: Light & Dark Mode
-
-### Dark Mode Is Not Inverted Light Mode
-
-You can't just swap colors. Dark mode requires different design decisions:
-
-| Light Mode | Dark Mode |
-|------------|-----------|
-| Shadows for depth | Lighter surfaces for depth (no shadows) |
-| Dark text on light | Light text on dark (reduce font weight) |
-| Vibrant accents | Desaturate accents slightly |
-| White backgrounds | Never pure black; use dark gray (oklch 12-18%) |
-
-In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light.
-
-### Token Hierarchy
-
-Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same.
-
-## Alpha Is A Design Smell
-
-Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed.
-
----
-
-**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Using pure black (#000) for large areas. Skipping color blindness testing (8% of men affected).
@@ -1,154 +0,0 @@
-> **Additional context needed**: existing brand colors.
-
-Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit.
-
----
-
-## Register
-
-Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it.
-
-Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen.
-
----
-
-## Assess Color Opportunity
-
-Analyze the current state and identify opportunities:
-
-1. **Understand current state**:
- - **Color absence**: Pure grayscale? Limited neutrals? One timid accent?
- - **Missed opportunities**: Where could color add meaning, hierarchy, or delight?
- - **Context**: What's appropriate for this domain and audience?
- - **Brand**: Are there existing brand colors we should use?
-
-2. **Identify where color adds value**:
- - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue)
- - **Hierarchy**: Drawing attention to important elements
- - **Categorization**: Different sections, types, or states
- - **Emotional tone**: Warmth, energy, trust, creativity
- - **Wayfinding**: Helping users navigate and understand structure
- - **Delight**: Moments of visual interest and personality
-
-If any of these are unclear from the codebase, STOP and call the `question` tool to clarify.
-
-**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose.
-
-## Plan Color Strategy
-
-Create a purposeful color introduction plan:
-
-- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals)
-- **Dominant color**: Which color owns 60% of colored elements?
-- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%)
-- **Application strategy**: Where does each color appear and why?
-
-**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more.
-
-## Introduce Color Strategically
-
-Add color systematically across these dimensions:
-
-### Semantic Color
-- **State indicators**:
- - Success: Green tones (emerald, forest, mint)
- - Error: Red/pink tones (rose, crimson, coral)
- - Warning: Orange/amber tones
- - Info: Blue tones (sky, ocean, indigo)
- - Neutral: Gray/slate for inactive states
-
-- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.)
-- **Progress indicators**: Colored bars, rings, or charts showing completion or health
-
-### Accent Color Application
-- **Primary actions**: Color the most important buttons/CTAs
-- **Links**: Add color to clickable text (maintain accessibility)
-- **Icons**: Colorize key icons for recognition and personality
-- **Headers/titles**: Add color to section headers or key labels
-- **Hover states**: Introduce color on interaction
-
-### Background & Surfaces
-- **Tinted backgrounds**: Replace pure gray (`#f5f5f5`) with warm neutrals (`oklch(97% 0.01 60)`) or cool tints (`oklch(97% 0.01 250)`)
-- **Colored sections**: Use subtle background colors to separate areas
-- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue)
-- **Cards & surfaces**: Tint cards or surfaces slightly for warmth
-
-**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
-
-### Data Visualization
-- **Charts & graphs**: Use color to encode categories or values
-- **Heatmaps**: Color intensity shows density or importance
-- **Comparison**: Color coding for different datasets or timeframes
-
-### Borders & Accents
-- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`)
-- **Underlines**: Color underlines for emphasis or active states
-- **Dividers**: Subtle colored dividers instead of gray lines
-- **Focus rings**: Colored focus indicators matching brand
-- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe
-
-**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe.
-
-### Typography Color
-- **Colored headings**: Use brand colors for section headings (maintain contrast)
-- **Highlight text**: Color for emphasis or categories
-- **Labels & tags**: Small colored labels for metadata or categories
-
-### Decorative Elements
-- **Illustrations**: Add colored illustrations or icons
-- **Shapes**: Geometric shapes in brand colors as background elements
-- **Gradients**: Colorful gradient overlays or mesh backgrounds
-- **Blobs/organic shapes**: Soft colored shapes for visual interest
-
-## Balance & Refinement
-
-Ensure color addition improves rather than overwhelms:
-
-### Maintain Hierarchy
-- **Dominant color** (60%): Primary brand color or most used accent
-- **Secondary color** (30%): Supporting color for variety
-- **Accent color** (10%): High contrast for key moments
-- **Neutrals** (remaining): Gray/black/white for structure
-
-### Accessibility
-- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components)
-- **Don't rely on color alone**: Use icons, labels, or patterns alongside color
-- **Test for color blindness**: Verify red/green combinations work for all users
-
-### Cohesion
-- **Consistent palette**: Use colors from defined palette, not arbitrary choices
-- **Systematic application**: Same color meanings throughout (green always = success)
-- **Temperature consistency**: Warm palette stays warm, cool stays cool
-
-**NEVER**:
-- Use every color in the rainbow (choose 2-4 colors beyond neutrals)
-- Apply color randomly without semantic meaning
-- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead
-- Use pure gray for neutrals. Add subtle color tint (warm or cool) for depth
-- Use pure black (`#000`) or pure white (`#fff`) for large areas
-- Violate WCAG contrast requirements
-- Use color as the only indicator (accessibility issue)
-- Make everything colorful (defeats the purpose)
-- Default to purple-blue gradients (AI slop aesthetic)
-
-## Verify Color Addition
-
-Test that colorization improves the experience:
-
-- **Better hierarchy**: Does color guide attention appropriately?
-- **Clearer meaning**: Does color help users understand states/categories?
-- **More engaging**: Does the interface feel warmer and more inviting?
-- **Still accessible**: Do all color combinations meet WCAG standards?
-- **Not overwhelming**: Is color balanced and purposeful?
-
-When the palette earns its place, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage.
-
-```json
-{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"}
-```
-
-Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract.
@@ -1,123 +0,0 @@
-# Craft Flow
-
-Build a feature with impeccable UX and UI quality: shape the design, land the visual direction, build real production code, inspect and improve in-browser until it meets a high-end studio bar.
-
-Before writing code, you need: PRODUCT.md loaded, register identified and the matching reference loaded, and a confirmed design direction for this task (either from `shape` or supplied by the user). PRODUCT.md is project context, not a task-specific brief.
-
-Treat any approved visual direction (generated mock or stated reference) as a concrete contract for composition, hierarchy, density, atmosphere, signature motifs, and distinctive visual moves. Don't let mocks replace structure, copy, accessibility, or state design. But if the live result lacks the approved direction's major ingredients, the implementation is wrong.
-
-### Gates: do not compress
-
-Craft has **multiple user gates**, not one. When the harness has native image generation (Codex via `image_gen`), the gate sequence before code is:
-
-1. **Shape brief confirmed** (Step 1)
-2. **Direction questions answered** (codex.md Step A)
-3. **Palette confirmed** (codex.md Step B)
-4. **One mock direction approved or delegated** (codex.md Step D)
-
-You must stop at every gate. **Shape confirmation alone is NOT a green light to start coding.** It is the green light to begin codex.md Step A. Compressing gates 2 through 4 because the shape brief felt complete is the dominant failure mode of this flow.
-
-When the harness lacks native image generation, gates 2-4 collapse into the brief itself, and shape confirmation does advance straight to code.
-
-## Step 0: Project Foundation
-
-Before shape, before code: figure out what kind of project you're working in.
-
-Look at the working directory. Run `ls`. Check for:
-
-- An existing framework: `astro.config.mjs/ts`, `next.config.js/ts`, `nuxt.config.ts`, `svelte.config.js`, `vite.config.js/ts`, `package.json` with framework deps, `Cargo.toml` + Leptos/Yew, `Gemfile` + Rails. **If found, use it.** Do not start a parallel build, do not introduce a second framework, do not write to `dist/` or `build/` directly. Whatever pipeline the project has, respect it.
-- An existing component library or design system: `src/components/`, `app/components/`, a `tokens.css` / `theme.ts`, an `astro.config` `integrations`. Read what's there before adding to it.
-- An existing icon set: `lucide-react`, `@phosphor-icons/react`, `@iconify/*`, hand-rolled SVG sprites in `assets/icons/`. **Use what's already in the project**; don't introduce a second set.
-
-If the directory is empty (greenfield), don't pick a framework silently. Ask the user via the AskUserQuestion tool, with sensible defaults framed by the brief:
-
-```text
-What should this be built on?
- - Astro (default for content-led brand sites, landing pages, marketing surfaces)
- - SvelteKit / Next.js / Nuxt (when the brief implies an app surface or significant interactivity)
- - Single index.html (one-shot demo, prototype, or a deliberately framework-free experiment)
-```
-
-Default: Astro for brand briefs, the project's existing framework for product briefs. Ask once; don't re-ask mid-task.
-
-## Step 1: Shape the Design
-
-Run /impeccable shape, passing along whatever feature description the user provided. Shape is **required** for craft; it is what produces a confirmed direction.
-
-Present the shape output and stop. Wait for the user to confirm, override, or course-correct before writing code.
-
-If the user already supplied a confirmed brief or ran shape separately, use it and skip this step.
-
-When the original prompt + PRODUCT.md already answer scope, content, and visual direction with no real ambiguity, the shape output can be **compact** (3-5 bullets stating what you're building and the visual lane, ending with one or two specific questions or "confirm or override"). The full 10-section structured brief is reserved for genuinely ambiguous, multi-screen, or stakeholder-heavy tasks. Don't pad a clear brief into a long one to look thorough; equally, don't skip the pause to look efficient.
-
-If the harness has native image generation (Codex), a compact shape's "confirm or override" advances to **Step 3 and the codex.md flow**, not to Step 4. Phrase the closing line accordingly: "Confirm or override; once we lock direction, I'll run a couple of palette and reference questions before generating any mocks." This stops the model from reading shape confirmation as code-green.
-
-## Step 2: Load References
-
-Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult:
-
-- [spatial-design.md](spatial-design.md) for layout and spacing
-- [typography.md](typography.md) for type hierarchy
-
-Then add references based on the brief's needs:
-- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md)
-- Animation or transitions? Consult [motion-design.md](motion-design.md)
-- Color-heavy or themed? Consult [color-and-contrast.md](color-and-contrast.md)
-- Responsive requirements? Consult [responsive-design.md](responsive-design.md)
-- Heavy on copy, labels, or errors? Consult [ux-writing.md](ux-writing.md)
-
-## Step 3: Visual Direction & Assets (Harness-Gated)
-
-If the harness has **native image generation** (currently Codex via `image_gen`), this step is mandatory. **Stop and load [codex.md](codex.md)**. It covers palette generation, mock exploration, the approval loop, mock-fidelity inventory, and asset slicing via the `impeccable_asset_producer` subagent. Follow Steps A-F in that file, then return here for Step 4.
-
-If the harness lacks native image generation, **state in one line that the visual-direction-by-generation step is being skipped because the harness lacks native image generation, then proceed**. The one-line announcement is required; it forces a conscious decision instead of letting the step quietly evaporate. The brief is your only visual reference. Implement directly from it, treating any named anchor references and the brief's "Design Direction" as the contract.
-
-Whether you generated mocks or not: don't replace required imagery with generic cards, bullets, emoji, fake metrics, decorative CSS panels, or filler copy. Image-led briefs (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product) need real or sourced imagery in the build, not CSS scenery.
-
-## Step 4: Build to Production Quality
-
-**Precondition.** If Step 3 routed you to codex.md (native image generation available), Steps A through D in that file must be complete before any code: questions answered, palette confirmed, mocks generated, one direction approved or delegated. **Do not mention implementation, file paths, or patch plans until that's done.** A confirmed shape brief is not enough; the model that compressed those gates is the model that already failed this flow.
-
-Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration.
-
-### Production bar
-
-- **Real content.** No placeholder copy, placeholder images, dead links, fake controls, or unused scaffold at presentation time.
-- **Preserve the approved mock's major ingredients.** Missing hero objects, world/product imagery, section structure, CTA/nav treatment, or distinctive motifs are blocking defects unless the user accepted the change.
-- **Semantic first.** Real headings, landmarks, labels, form associations, button/link semantics, accessible names, state announcements where needed.
-- **Deliberate spacing and alignment.** No default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment.
-- **Intentional typography.** Chosen loading strategy, clear hierarchy, readable measure, stable line breaks, no overflow at any width.
-- **Realistic state coverage.** Default, hover, focus-visible, active, disabled, loading, error, success, empty, overflow, long/short text, first-run.
-- **Finished interaction quality.** Keyboard paths, touch targets, feedback timing, scroll behavior, state transitions, no hover-only functionality.
-- **Coherent icon set.** Use the project's established set; otherwise pick one library or use accessible text. Don't mix.
-- **Respect the build pipeline.** Edit source files and run the project's build (`npm run build` or equivalent). Don't write to `build/` / `dist/` / `.next/` with `cat`, heredoc, or Bash redirects; that skips asset hashing, image optimization, code splitting, and CSS extraction, and produces output the dev server won't serve.
-- **Verify image URLs before referencing them.** Use image-search MCP or web-fetch when available; guessed photo IDs ship as broken-image placeholders. Without verification, prefer fewer images you're confident about.
-- **Optimized imagery and media.** Correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset`/`picture` for raster, no project-referenced asset left outside the workspace.
-- **Premium motion.** Use atmospheric blur, filter, mask, shadow, reveal when they improve the experience. Avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion.
-- **Maintainable.** Reusable local patterns, clear component boundaries, project conventions. No rasterized UI text or one-off hacks when a local pattern exists.
-- **Technically clean.** Production build passes, no console errors, no avoidable layout shift, no needless dependencies, no broken asset paths.
-- **Ask when uncertain.** If a discovery materially changes the brief or approved direction, stop and ask. Don't guess.
-
-## Step 5: Iterate Visually
-
-Look at what you built like a designer would. Your eyes are whatever the harness gives you: a connected browser, a screenshotting tool, Playwright, or asking the user. Use them for responsive testing (mobile, tablet, desktop minimum) and general visual validation.
-
-If your tool returns a file path, read the PNG back into the conversation. A screenshot you didn't read doesn't count.
-
-For long-form brand surfaces, inspect major sections individually. Thumbnails hide spacing, clipping, and cascade defects.
-
-After the first pass, write an honest critique against the brief, the approved mock's major ingredients (hero silhouette, motifs, imagery, nav/CTA, density), and impeccable's DON'Ts. Patch material defects and re-inspect. **Don't invent defects to demonstrate iteration.** A confident "first pass clean, shipping" beats a fake fix.
-
-Actively check: responsive behavior (composes, not shrinks), every state (empty / error / loading / edge), craft details (spacing, alignment, hierarchy, contrast, motion timing, focus), performance basics. The exit bar: defensible in a high-end studio review.
-
-Detector or QA output is defect evidence only; never proof the work is finished.
-
-## Step 6: Present
-
-Present the result to the user:
-- Show the feature in its primary state
-- Summarize the browser/viewports checked and the most important fixes made after inspection
-- Walk through the key states (empty, error, responsive)
-- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients.
-- Note any remaining limitations or follow-up risks honestly
-- Ask: "What's working? What isn't?"
@@ -1,236 +0,0 @@
-### Purpose
-
-Resolve one stable target, run two independent assessments, synthesize a design critique, persist a snapshot, and ask the user what to improve next. The chat response is the primary deliverable; the snapshot is an archive/backlog for future commands.
-
-### Hard Invariants
-
-- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
-- Assessment A must finish before detector findings enter the parent synthesis context. Detector output is deterministic, but it still anchors judgment.
-- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize.
-- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
-- Viewable targets require browser inspection when available.
-- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
-- Do not claim a user-visible overlay exists unless script injection succeeded and the detector ran in the page.
-
-### Setup
-
-1. **Resolve the target** to a concrete file path or URL. Prefer a source path over a dev-server URL when both identify the same surface; ports drift, paths do not.
- - "the homepage" -> `site/pages/index.astro` or `index.html`
- - "the settings modal" -> the primary component file
- - "this page" -> the current URL or source file
-2. **Compute the slug**:
- ```bash
- node .opencode/skills/impeccable/scripts/critique-storage.mjs slug "<resolved-path-or-url>"
- ```
- Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique.
-3. **Read `.impeccable/critique/ignore.md`** if it exists. Drop matching findings silently; it is the only prior-run input critique consumes.
-
-### Assessment Orchestration
-
-Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis.
-
-If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
-
-### Assessment A: Design Review
-
-Read relevant source files and visually inspect the live page when browser automation is available. Think like a design director.
-
-Evaluate:
-- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill.
-- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases.
-- **Cognitive load**: consult [cognitive-load](cognitive-load.md); report checklist failures and decision points with >4 visible options.
-- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments.
-- **Nielsen heuristics**: consult [heuristics-scoring](heuristics-scoring.md); score all 10 heuristics 0-4.
-
-Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions.
-
-### Assessment B: Detector + Browser Evidence
-
-Run the bundled detector and browser visualization evidence. Assessment B is mandatory and must remain isolated from Assessment A until both are complete.
-
-CLI scan:
-```bash
-node .opencode/skills/impeccable/scripts/detect.mjs --json [--fast] [target]
-```
-
-- Pass markup files/directories as `[target]`; do not pass CSS-only files.
-- For URLs, skip CLI scan and use browser visualization.
-- For 200+ scannable files, use `--fast`; for 500+, narrow scope or ask.
-- Exit code 0 = clean; 2 = findings.
-- If the detector entrypoint is missing or fails to load, report deterministic scan unavailable and continue with browser/manual review.
-
-Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
-
-1. Create a fresh tab and navigate.
-2. Preflight mutable injection by setting `document.title` and appending a `<script>` tag. Read-only evaluate APIs do not count.
-3. If mutation is unavailable, skip live server, browser presentation, and injection; report fallback signal.
-4. If mutation is available, start `node .opencode/skills/impeccable/scripts/live-server.mjs --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then stop the live server.
-5. For multi-view targets, inject on 3-5 representative pages.
-
-Return: CLI findings JSON/counts, browser console findings if applicable, false positives, and skipped/failed browser steps with concrete reasons.
-
-After Assessment B returns usable CLI findings, reuse them. Do not rerun `detect.mjs` in the parent unless Assessment B failed, was truncated, or omitted count, rule names, or file locations.
-
-### Generate Combined Critique Report
-
-Synthesize both assessments into a single report. Do NOT simply concatenate. Weave the findings together, noting where the LLM review and detector agree, where the detector caught issues the LLM missed, and where detector findings are false positives.
-
-The chat response is the primary user-facing deliverable. Present the full structured critique below in chat; do not replace it with a summary and a link. The persisted snapshot is only an archive/backlog for later commands.
-
-Structure your feedback as a design director would:
-
-#### Design Health Score
-> *Consult [heuristics-scoring](heuristics-scoring.md)*
-
-Present the Nielsen's 10 heuristics scores as a table:
-
-| # | Heuristic | Score | Key Issue |
-|---|-----------|-------|-----------|
-| 1 | Visibility of System Status | ? | [specific finding or "n/a" if solid] |
-| 2 | Match System / Real World | ? | |
-| 3 | User Control and Freedom | ? | |
-| 4 | Consistency and Standards | ? | |
-| 5 | Error Prevention | ? | |
-| 6 | Recognition Rather Than Recall | ? | |
-| 7 | Flexibility and Efficiency | ? | |
-| 8 | Aesthetic and Minimalist Design | ? | |
-| 9 | Error Recovery | ? | |
-| 10 | Help and Documentation | ? | |
-| **Total** | | **??/40** | **[Rating band]** |
-
-Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32.
-
-#### Anti-Patterns Verdict
-
-**Start here.** Does this look AI-generated?
-
-**LLM assessment**: Your own evaluation of AI slop tells. Cover overall aesthetic feel, layout sameness, generic composition, missed opportunities for personality.
-
-**Deterministic scan**: Summarize what the automated detector found, with counts and file locations. Note any additional issues the detector caught that you missed, and flag any false positives.
-
-**Visual overlays** (if injection succeeded): Tell the user that overlays are now visible in the **[Human]** tab in their browser, highlighting the detected issues. Summarize what the console output reported. If browser visualization was attempted but injection failed, say that no reliable user-visible overlay is available and report the fallback signal instead.
-
-#### Overall Impression
-A brief gut reaction: what works, what doesn't, and the single biggest opportunity.
-
-#### What's Working
-Highlight 2-3 things done well. Be specific about why they work.
-
-#### Priority Issues
-The 3-5 most impactful design problems, ordered by importance.
-
-For each issue, tag with **P0-P3 severity** (consult [heuristics-scoring](heuristics-scoring.md) for severity definitions):
-- **[P?] What**: Name the problem clearly
-- **Why it matters**: How this hurts users or undermines goals
-- **Fix**: What to do about it (be concrete)
-- **Suggested command**: Which command could address this (from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-#### Persona Red Flags
-> *Consult [personas](personas.md)*
-
-Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `AGENTS.md` contains a `## Design Context` section from `impeccable teach`, also generate 1-2 project-specific personas from the audience/brand info.
-
-For each selected persona, walk through the primary user action and list specific red flags found:
-
-**Alex (Power User)**: No keyboard shortcuts detected. Form requires 8 clicks for primary action. Forced modal onboarding. High abandonment risk.
-
-**Jordan (First-Timer)**: Icon-only nav in sidebar. Technical jargon in error messages ("404 Not Found"). No visible help. Will abandon at step 2.
-
-Be specific. Name the exact elements and interactions that fail each persona. Don't write generic persona descriptions; write what broke for them.
-
-#### Minor Observations
-Quick notes on smaller issues worth addressing.
-
-#### Questions to Consider
-Provocative questions that might unlock better solutions:
-- "What if the primary action were more prominent?"
-- "Does this need to feel this complex?"
-- "What would a confident version of this look like?"
-
-**Remember**:
-- Be direct. Vague feedback wastes everyone's time.
-- Be specific. "The submit button," not "some elements."
-- Say what's wrong AND why it matters to users.
-- Give concrete suggestions. Cut "consider exploring..." entirely.
-- Prioritize ruthlessly. If everything is important, nothing is.
-- Don't soften criticism. Developers need honest feedback to ship great design.
-
-### Persist the Snapshot
-
-Once the report above is finalized, write it to `.impeccable/critique/` so the user can refer back, and so `/impeccable polish` can pick up the priority issues without a copy-paste.
-
-Skip this step if the Setup slug was null (vague or root-level target).
-
-1. **Write the body to a temp file** so you can pipe it to the helper. Use the full critique report (heuristic table, anti-patterns verdict, priority issues, persona red flags, minor observations, and questions), but stop before the "Ask the User" / "Recommended Actions" sections that come later.
-
-2. **Pass the structured metadata** through `IMPECCABLE_CRITIQUE_META` (JSON), then run the write command:
- ```bash
- IMPECCABLE_CRITIQUE_META='{"target":"<user phrasing>","total_score":<n>,"p0_count":<n>,"p1_count":<n>}' \
- node .opencode/skills/impeccable/scripts/critique-storage.mjs write <slug> <body-file>
- ```
- The helper prints the absolute path it wrote.
-
-3. **Delete the temp body file** after the write attempt completes, whether the write succeeded or failed. If deletion fails, mention `temp-file cleanup failed: <reason>` briefly in the final output, but do not block the critique.
-
-4. **Read the trend** for context:
- ```bash
- node .opencode/skills/impeccable/scripts/critique-storage.mjs trend <slug> 5
- ```
- This returns a JSON array of the last 5 frontmatter entries (including the one you just wrote).
-
-5. **Append a single line to the user-visible output**, after the report and before the questions:
-
- > **Trend for `<slug>` (last 5 runs): 24 → 28 → 32 → 29 → 32**
- > Wrote `.impeccable/critique/<filename>`.
-
- If this is the first run for the slug, the trend is just one score; say so: "First run for this target, no trend yet."
-
-This is fire-and-forget. Do not show the user the helper's JSON output; only the human-readable trend line and the written path. Failures here should not block the rest of the flow; print the error and move on.
-
-### Ask the User
-
-**After presenting findings**, use targeted questions based on what was actually found. STOP and call the `question` tool to clarify. These answers will shape the action plan.
-
-Ask questions along these lines (adapt to the specific findings; do NOT ask generic questions):
-
-1. **Priority direction**: Based on the issues found, ask which category matters most to the user right now. For example: "I found problems with visual hierarchy, color usage, and information overload. Which area should we tackle first?" Offer the top 2-3 issue categories as options.
-
-2. **Design intent**: If the critique found a tonal mismatch, ask whether it was intentional. For example: "The interface feels clinical and corporate. Is that the intended tone, or should it feel warmer/bolder/more playful?" Offer 2-3 tonal directions as options based on what would fix the issues found.
-
-3. **Scope**: Ask how much the user wants to take on. For example: "I found N issues. Want to address everything, or focus on the top 3?" Offer scope options like "Top 3 only", "All issues", "Critical issues only".
-
-4. **Constraints** (optional; only ask if relevant): If the findings touch many areas, ask if anything is off-limits. For example: "Should any sections stay as-is?" This prevents the plan from touching things the user considers done.
-
-**Rules for questions**:
-- Every question must reference specific findings from the report. Never ask generic "who is your audience?" questions.
-- Keep it to 2-4 questions maximum. Respect the user's time.
-- Offer concrete options, not open-ended prompts.
-- If findings are straightforward (e.g., only 1-2 clear issues), skip questions and go directly to Recommended Actions.
-
-### Recommended Actions
-
-**After receiving the user's answers**, present a prioritized action summary reflecting the user's priorities and scope from Ask the User.
-
-#### Action Summary
-
-List recommended commands in priority order, based on the user's answers:
-
-1. **`/command-name`**: Brief description of what to fix (specific context from critique findings)
-2. **`/command-name`**: Brief description (specific context)
-...
-
-**Rules for recommendations**:
-- Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset
-- Order by the user's stated priorities first, then by impact
-- Each item's description should carry enough context that the command knows what to focus on
-- Map each Priority Issue to the appropriate command
-- Skip commands that would address zero issues
-- If the user chose a limited scope, only include items within that scope
-- If the user marked areas as off-limits, exclude commands that would touch those areas
-- End with `/impeccable polish` as the final step if any fixes were recommended
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable critique` after fixes to see your score improve.
@@ -1,302 +0,0 @@
-> **Additional context needed**: what's appropriate for the domain (playful vs professional vs quirky vs elegant).
-
-Find the moments where personality and unexpected polish would turn a functional interface into one users remember and tell other people about. Add only where the moment earns it; delight everywhere reads as noise.
-
----
-
-## Register
-
-Brand: delight can be distributed across copy voice, section transitions, discovery rewards, seasonal touches, personality across the whole surface.
-
-Product: delight at specific moments, not pages. Completion, first-time actions, error recovery, milestone crossings. Reliability and consistency carry the rest of the experience; delight pushed everywhere reads as noise.
-
----
-
-## Assess Delight Opportunities
-
-Identify where delight would enhance (not distract from) the experience:
-
-1. **Find natural delight moments**:
- - **Success states**: Completed actions (save, send, publish)
- - **Empty states**: First-time experiences, onboarding
- - **Loading states**: Waiting periods that could be entertaining
- - **Achievements**: Milestones, streaks, completions
- - **Interactions**: Hover states, clicks, drags
- - **Errors**: Softening frustrating moments
- - **Easter eggs**: Hidden discoveries for curious users
-
-2. **Understand the context**:
- - What's the brand personality? (Playful? Professional? Quirky? Elegant?)
- - Who's the audience? (Tech-savvy? Creative? Corporate?)
- - What's the emotional context? (Accomplishment? Exploration? Frustration?)
- - What's appropriate? (Banking app ≠ gaming app)
-
-3. **Define delight strategy**:
- - **Subtle sophistication**: Refined micro-interactions (luxury brands)
- - **Playful personality**: Whimsical illustrations and copy (consumer apps)
- - **Helpful surprises**: Anticipating needs before users ask (productivity tools)
- - **Sensory richness**: Satisfying sounds, smooth animations (creative tools)
-
-If any of these are unclear from the codebase, STOP and call the `question` tool to clarify.
-
-**CRITICAL**: Delight should enhance usability, never obscure it. If users notice the delight more than accomplishing their goal, you've gone too far.
-
-## Delight Principles
-
-Follow these guidelines:
-
-### Delight Amplifies, Never Blocks
-- Delight moments should be quick (< 1 second)
-- Never delay core functionality for delight
-- Make delight skippable or subtle
-- Respect user's time and task focus
-
-### Surprise and Discovery
-- Hide delightful details for users to discover
-- Reward exploration and curiosity
-- Don't announce every delight moment
-- Let users share discoveries with others
-
-### Appropriate to Context
-- Match delight to emotional moment (celebrate success, empathize with errors)
-- Respect the user's state (don't be playful during critical errors)
-- Match brand personality and audience expectations
-- Cultural sensitivity (what's delightful varies by culture)
-
-### Compound Over Time
-- Delight should remain fresh with repeated use
-- Vary responses (not same animation every time)
-- Reveal deeper layers with continued use
-- Build anticipation through patterns
-
-## Delight Techniques
-
-Add personality and joy through these methods:
-
-### Micro-interactions & Animation
-
-**Button delight**:
-```css
-/* Satisfying button press */
-.button {
- transition: transform 0.1s, box-shadow 0.1s;
-}
-.button:active {
- transform: translateY(2px);
- box-shadow: 0 2px 4px rgba(0,0,0,0.2);
-}
-
-/* Ripple effect on click */
-/* Smooth lift on hover */
-.button:hover {
- transform: translateY(-2px);
- transition: transform 0.2s cubic-bezier(0.25, 1, 0.5, 1); /* ease-out-quart */
-}
-```
-
-**Loading delight**:
-- Playful loading animations (not just spinners)
-- Personality in loading messages (write product-specific ones, not generic AI filler)
-- Progress indication with encouraging messages
-- Skeleton screens with subtle animations
-
-**Success animations**:
-- Checkmark draw animation
-- Confetti burst for major achievements
-- Gentle scale + fade for confirmation
-- Satisfying sound effects (subtle)
-
-**Hover surprises**:
-- Icons that animate on hover
-- Color shifts or glow effects
-- Tooltip reveals with personality
-- Cursor changes (custom cursors for branded experiences)
-
-### Personality in Copy
-
-**Playful error messages**:
-```
-"Error 404"
-"This page is playing hide and seek. (And winning)"
-
-"Connection failed"
-"Looks like the internet took a coffee break. Want to retry?"
-```
-
-**Encouraging empty states**:
-```
-"No projects"
-"Your canvas awaits. Create something amazing."
-
-"No messages"
-"Inbox zero! You're crushing it today."
-```
-
-**Playful labels & tooltips**:
-```
-"Delete"
-"Send to void" (for playful brand)
-
-"Help"
-"Rescue me" (tooltip)
-```
-
-**IMPORTANT**: Match copy personality to brand. Banks shouldn't be wacky, but they can be warm.
-
-### Illustrations & Visual Personality
-
-**Custom illustrations**:
-- Empty state illustrations (not stock icons)
-- Error state illustrations (friendly monsters, quirky characters)
-- Loading state illustrations (animated characters)
-- Success state illustrations (celebrations)
-
-**Icon personality**:
-- Custom icon set matching brand personality
-- Animated icons (subtle motion on hover/click)
-- Illustrative icons (more detailed than generic)
-- Consistent style across all icons
-
-**Background effects**:
-- Subtle particle effects
-- Gradient mesh backgrounds
-- Geometric patterns
-- Parallax depth
-- Time-of-day themes (morning vs night)
-
-### Satisfying Interactions
-
-**Drag and drop delight**:
-- Lift effect on drag (shadow, scale)
-- Snap animation when dropped
-- Satisfying placement sound
-- Undo toast ("Dropped in wrong place? [Undo]")
-
-**Toggle switches**:
-- Smooth slide with spring physics
-- Color transition
-- Haptic feedback on mobile
-- Optional sound effect
-
-**Progress & achievements**:
-- Streak counters with celebratory milestones
-- Progress bars that "celebrate" at 100%
-- Badge unlocks with animation
-- Playful stats ("You're on fire! 5 days in a row")
-
-**Form interactions**:
-- Input fields that animate on focus
-- Checkboxes with a satisfying scale pulse when checked
-- Success state that celebrates valid input
-- Auto-grow textareas
-
-### Sound Design
-
-**Subtle audio cues** (when appropriate):
-- Notification sounds (distinctive but not annoying)
-- Success sounds (satisfying "ding")
-- Error sounds (empathetic, not harsh)
-- Typing sounds for chat/messaging
-- Ambient background audio (very subtle)
-
-**IMPORTANT**:
-- Respect system sound settings
-- Provide mute option
-- Keep volumes quiet (subtle cues, not alarms)
-- Don't play on every interaction (sound fatigue is real)
-
-### Easter Eggs & Hidden Delights
-
-**Discovery rewards**:
-- Konami code unlocks special theme
-- Hidden keyboard shortcuts (Cmd+K for special features)
-- Hover reveals on logos or illustrations
-- Alt text jokes on images (for screen reader users too!)
-- Console messages for developers ("Like what you see? We're hiring!")
-
-**Seasonal touches**:
-- Holiday themes (subtle, tasteful)
-- Seasonal color shifts
-- Weather-based variations
-- Time-based changes (dark at night, light during day)
-
-**Contextual personality**:
-- Different messages based on time of day
-- Responses to specific user actions
-- Randomized variations (not same every time)
-- Progressive reveals with continued use
-
-### Loading & Waiting States
-
-**Make waiting engaging**:
-- Interesting loading messages that rotate
-- Progress bars with personality
-- Mini-games during long loads
-- Fun facts or tips while waiting
-- Countdown with encouraging messages
-
-```
-Loading messages: write ones specific to your product, not generic AI filler:
-- "Crunching your latest numbers..."
-- "Syncing with your team's changes..."
-- "Preparing your dashboard..."
-- "Checking for updates since yesterday..."
-```
-
-**WARNING**: Avoid cliched loading messages like "Herding pixels", "Teaching robots to dance", "Consulting the magic 8-ball", "Counting backwards from infinity". These are AI-slop copy, instantly recognizable as machine-generated. Write messages that are specific to what your product actually does.
-
-### Celebration Moments
-
-**Success celebrations**:
-- Confetti for major milestones
-- Animated checkmarks for completions
-- Progress bar celebrations at 100%
-- "Achievement unlocked" style notifications
-- Personalized messages ("You published your 10th article!")
-
-**Milestone recognition**:
-- First-time actions get special treatment
-- Streak tracking and celebration
-- Progress toward goals
-- Anniversary celebrations
-
-## Implementation Patterns
-
-**Animation libraries**:
-- Framer Motion (React)
-- GSAP (universal)
-- Lottie (After Effects animations)
-- Canvas confetti (party effects)
-
-**Sound libraries**:
-- Howler.js (audio management)
-- Use-sound (React hook)
-
-**Physics libraries**:
-- React Spring (spring physics)
-- Popmotion (animation primitives)
-
-**IMPORTANT**: File size matters. Compress images, optimize animations, lazy load delight features.
-
-**NEVER**:
-- Delay core functionality for delight
-- Force users through delightful moments (make skippable)
-- Use delight to hide poor UX
-- Overdo it (less is more)
-- Ignore accessibility (animate responsibly, provide alternatives)
-- Make every interaction delightful (special moments should be special)
-- Sacrifice performance for delight
-- Be inappropriate for context (read the room)
-
-## Verify Delight Quality
-
-Test that delight actually delights:
-
-- **User reactions**: Do users smile? Share screenshots?
-- **Doesn't annoy**: Still pleasant after 100th time?
-- **Doesn't block**: Can users opt out or skip?
-- **Performant**: No jank, no slowdown
-- **Appropriate**: Matches brand and context
-- **Accessible**: Works with reduced motion, screen readers
-
-When the moments feel earned, hand off to `/impeccable polish` for the final pass.
@@ -1,111 +0,0 @@
-Strip a design to its essence. Remove anything that doesn't earn its place: redundant elements, repeated information, decorative noise, cosmetic complexity.
-
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel complex or cluttered:
-
-1. **Identify complexity sources**:
- - **Too many elements**: Competing buttons, redundant information, visual clutter
- - **Excessive variation**: Too many colors, fonts, sizes, styles without purpose
- - **Information overload**: Everything visible at once, no progressive disclosure
- - **Visual noise**: Unnecessary borders, shadows, backgrounds, decorations
- - **Confusing hierarchy**: Unclear what matters most
- - **Feature creep**: Too many options, actions, or paths forward
-
-2. **Find the essence**:
- - What's the primary user goal? (There should be ONE)
- - What's actually necessary vs nice-to-have?
- - What can be removed, hidden, or combined?
- - What's the 20% that delivers 80% of value?
-
-If any of these are unclear from the codebase, STOP and call the `question` tool to clarify.
-
-**CRITICAL**: Simplicity is not about removing features. It's about removing obstacles between users and their goals. Every element should justify its existence.
-
-## Plan Simplification
-
-Create a ruthless editing strategy:
-
-- **Core purpose**: What's the ONE thing this should accomplish?
-- **Essential elements**: What's truly necessary to achieve that purpose?
-- **Progressive disclosure**: What can be hidden until needed?
-- **Consolidation opportunities**: What can be combined or integrated?
-
-**IMPORTANT**: Simplification is hard. It requires saying no to good ideas to make room for great execution. Be ruthless.
-
-## Simplify the Design
-
-Systematically remove complexity across these dimensions:
-
-### Information Architecture
-- **Reduce scope**: Remove secondary actions, optional features, redundant information
-- **Progressive disclosure**: Hide complexity behind clear entry points (accordions, modals, step-through flows)
-- **Combine related actions**: Merge similar buttons, consolidate forms, group related content
-- **Clear hierarchy**: ONE primary action, few secondary actions, everything else tertiary or hidden
-- **Remove redundancy**: If it's said elsewhere, don't repeat it here
-
-### Visual Simplification
-- **Reduce color palette**: Use 1-2 colors plus neutrals, not 5-7 colors
-- **Limit typography**: One font family, 3-4 sizes maximum, 2-3 weights
-- **Remove decorations**: Eliminate borders, shadows, backgrounds that don't serve hierarchy or function
-- **Flatten structure**: Reduce nesting, remove unnecessary containers; never nest cards inside cards
-- **Remove unnecessary cards**: Cards aren't needed for basic layout; use spacing and alignment instead
-- **Consistent spacing**: Use one spacing scale, remove arbitrary gaps
-
-### Layout Simplification
-- **Linear flow**: Replace complex grids with simple vertical flow where possible
-- **Remove sidebars**: Move secondary content inline or hide it
-- **Full-width**: Use available space generously instead of complex multi-column layouts
-- **Consistent alignment**: Pick left or center, stick with it
-- **Generous white space**: Let content breathe, don't pack everything tight
-
-### Interaction Simplification
-- **Reduce choices**: Fewer buttons, fewer options, clearer path forward (paradox of choice is real)
-- **Smart defaults**: Make common choices automatic, only ask when necessary
-- **Inline actions**: Replace modal flows with inline editing where possible
-- **Remove steps**: Can signup be one step instead of three? Can checkout be simplified?
-- **Clear CTAs**: ONE obvious next step, not five competing actions
-
-### Content Simplification
-- **Shorter copy**: Cut every sentence in half, then do it again
-- **Active voice**: "Save changes" not "Changes will be saved"
-- **Remove jargon**: Plain language always wins
-- **Scannable structure**: Short paragraphs, bullet points, clear headings
-- **Essential information only**: Remove marketing fluff, legalese, hedging
-- **Remove redundant copy**: No headers restating intros, no repeated explanations, say it once
-
-### Code Simplification
-- **Remove unused code**: Dead CSS, unused components, orphaned files
-- **Flatten component trees**: Reduce nesting depth
-- **Consolidate styles**: Merge similar styles, use utilities consistently
-- **Reduce variants**: Does that component need 12 variations, or can 3 cover 90% of cases?
-
-**NEVER**:
-- Remove necessary functionality (simplicity ≠ feature-less)
-- Sacrifice accessibility for simplicity (clear labels and ARIA still required)
-- Make things so simple they're unclear (mystery ≠ minimalism)
-- Remove information users need to make decisions
-- Eliminate hierarchy completely (some things should stand out)
-- Oversimplify complex domains (match complexity to actual task complexity)
-
-## Verify Simplification
-
-Ensure simplification improves usability:
-
-- **Faster task completion**: Can users accomplish goals more quickly?
-- **Reduced cognitive load**: Is it easier to understand what to do?
-- **Still complete**: Are all necessary features still accessible?
-- **Clearer hierarchy**: Is it obvious what matters most?
-- **Better performance**: Does simpler design load faster?
-
-## Document Removed Complexity
-
-If you removed features or options:
-- Document why they were removed
-- Consider if they need alternative access points
-- Note any user feedback to monitor
-
-When the cuts feel right, hand off to `/impeccable polish` for the final pass. As Antoine de Saint-Exupéry put it: "Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away."
@@ -1,427 +0,0 @@
-Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
-
-DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
-
-## The frontmatter: token schema
-
-The YAML frontmatter is the machine-readable layer. It's what Stitch's linter validates and what the live panel renders tiles from. Keep it tight; every entry should correspond to a token the project actually uses.
-
-```yaml
----
-name: <project title>
-description: <one-line tagline>
-colors:
- primary: "#b8422e"
- neutral-bg: "#faf7f2"
- # ...one entry per extracted color; key = descriptive slug
-typography:
- display:
- fontFamily: "Cormorant Garamond, Georgia, serif"
- fontSize: "clamp(2.5rem, 7vw, 4.5rem)"
- fontWeight: 300
- lineHeight: 1
- letterSpacing: "normal"
- body:
- # ...
-rounded:
- sm: "4px"
- md: "8px"
-spacing:
- sm: "8px"
- md: "16px"
-components:
- button-primary:
- backgroundColor: "{colors.primary}"
- textColor: "{colors.neutral-bg}"
- rounded: "{rounded.sm}"
- padding: "16px 48px"
- button-primary-hover:
- backgroundColor: "{colors.primary-deep}"
----
-```
-
-Rules that matter:
-
-- **Token refs** use `{path.to.token}` (e.g. `{colors.primary}`, `{rounded.md}`). Components may reference primitives; primitives may not reference each other.
-- **Stitch validates colors as hex sRGB only** (`#RGB` / `#RGBA` / `#RRGGBB` / `#RRGGBBAA`); OKLCH/HSL/P3 trigger a linter warning, not a hard error. YAML accepts the string either way and our own parser is format-agnostic. Choose based on project posture: (a) if the project has an "OKLCH-only" doctrine or uses Display-P3 values that don't round-trip through sRGB, put OKLCH directly in the frontmatter and accept the Stitch linter warning; (b) if the project wants strict Stitch compliance or plans to use their Tailwind/DTCG export pipeline, put hex in the frontmatter and keep OKLCH in prose as the canonical reference. Never split the source of truth without explicit reason.
-- **Component sub-tokens** are limited to 8 props: `backgroundColor`, `textColor`, `typography`, `rounded`, `padding`, `size`, `height`, `width`. Shadows, motion, focus rings, backdrop-filter: none of those fit. Carry them in the sidecar (Step 4b).
-- **Scale keys are open-ended.** Use whatever names the project already uses (`warm-ash-cream`, `surface-container-low`). Don't rename to Material defaults.
-- **Variants are naming convention, not schema.** `button-primary` / `button-primary-hover` / `button-primary-active` as sibling keys.
-
-## The markdown body: six sections (exact order)
-
-1. `## Overview`
-2. `## Colors`
-3. `## Typography`
-4. `## Elevation`
-5. `## Components`
-6. `## Do's and Don'ts`
-
-Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] Palette` (Stitch's own outputs do this), but the literal word in each header (Overview, Colors, Typography, Elevation, Components, Do's and Don'ts) must be present. Do NOT add extra top-level sections (Layout Principles, Responsive Behavior, Motion, Agent Prompt Guide). Fold that content into the six spec sections where it naturally belongs.
-
-## When to run
-
-- The user just ran `/impeccable teach` and needs the visual side documented.
-- The skill noticed no `DESIGN.md` exists and nudged the user to create one.
-- An existing `DESIGN.md` is stale (the design has drifted).
-- Before a large redesign, to capture the current state as a reference.
-
-If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user the existing file and STOP and call the `question` tool to clarify. whether to refresh, overwrite, or merge.
-
-## Two paths
-
-- **Scan mode** (default): the project has design tokens, components, or rendered output. Extract, then confirm descriptive language. Use when there's code to analyze.
-- **Seed mode**: the project is pre-implementation (fresh teach, nothing built yet). Interview for five high-level answers, write a minimal DESIGN.md marked `<!-- SEED -->`. Re-run in scan mode once there's code.
-
-Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode; don't silently switch. `/impeccable document --seed` forces seed mode regardless of code presence.
-
-## Scan mode (approach C: auto-extract, then confirm descriptive language)
-
-### Step 1: Find the design assets
-
-Search the codebase in priority order:
-
-1. **CSS custom properties**: grep for `--color-`, `--font-`, `--spacing-`, `--radius-`, `--shadow-`, `--ease-`, `--duration-` declarations in CSS files (usually `src/styles/`, `public/css/`, `app/globals.css`, etc.). Record name, value, and the file it's defined in.
-2. **Tailwind config**: if `tailwind.config.{js,ts,mjs}` exists, read the `theme.extend` block for colors, fontFamily, spacing, borderRadius, boxShadow.
-3. **CSS-in-JS theme files**: styled-components, emotion, vanilla-extract, stitches; look for `theme.ts`, `tokens.ts`, or equivalent.
-4. **Design token files**: `tokens.json`, `design-tokens.json`, Style Dictionary output, W3C token community group format.
-5. **Component library**: scan the main button, card, input, navigation, dialog components. Note their variant APIs and default styles.
-6. **Global stylesheet**: the root CSS file usually has the base typography and color assignments.
-7. **Visible rendered output**: if browser automation tools are available, load the live site and sample computed styles from key elements (body, h1, a, button, .card). This catches values that tokens miss.
-
-### Step 2: Auto-extract what can be auto-extracted
-
-Build a structured draft from the discovered tokens. For each token class:
-
-- **Colors**: Group into Primary / Secondary / Tertiary / Neutral (the Material-derived roles Stitch uses). If the project only has one accent, express it as Primary + Neutral; omit Secondary and Tertiary rather than inventing them.
-- **Typography**: Map observed sizes and weights to the Material hierarchy (display / headline / title / body / label). Note font-family stacks and the scale ratio.
-- **Elevation**: Catalogue the shadow vocabulary. If the project is flat and uses tonal layering instead, that's a valid answer; state it explicitly.
-- **Components**: For each common component (button, card, input, chip, list item, tooltip, nav), extract shape (radius), color assignment, hover/focus treatment, internal padding.
-- **Spacing + layout**: Fold into Overview or relevant Components. The spec does NOT have a Layout section.
-
-### Step 2b: Stage the frontmatter
-
-From the auto-extracted tokens, draft the YAML frontmatter now (you'll write it at the top of DESIGN.md in Step 4). This is the machine-readable layer: what the live panel and Stitch's linter consume.
-
-- **Colors**: one entry per extracted color. Key = descriptive slug (`warm-ash-cream`, `editorial-magenta`, not `blue-800`). Value = whichever format the project treats as canonical (OKLCH or hex; see the frontmatter rules above). Don't split the source of truth: one format in the frontmatter, don't redefine the same token in prose with a different value.
-- **Typography**: one entry per role (`display`, `headline`, `title`, `body`, `label`). Typography is an object; include only the props that are real for the project (`fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `fontFeature`, `fontVariation`).
-- **Rounded / Spacing**: whatever scale steps the project actually uses, keyed by whatever scale name the project uses (`sm` / `md` / `lg`, or `surface-sm`, or numeric steps).
-- **Components**: one entry per variant (`button-primary`, `button-primary-hover`, `button-ghost`). Reference primitives via `{colors.X}`, `{rounded.Y}`. If a variant needs a property Stitch's 8-prop set doesn't cover (shadow, focus ring, backdrop-filter), carry the full snippet in the sidecar instead.
-
-Skip anything the project doesn't have. Empty scale keys or fabricated tokens pollute the spec.
-
-### Step 3: Ask the user for qualitative language
-
-The following require creative input that cannot be auto-extracted. Group them into one `AskUserQuestion` interaction:
-
-- **Creative North Star**: a single named metaphor for the whole system ("The Editorial Sanctuary", "The Golden State Curator", "The Lab Notebook"). Offer 2-3 options that honor PRODUCT.md's brand personality.
-- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, anti-references (what the system should not feel like).
-- **Color character** (for auto-extracted colors): descriptive names ("Deep Muted Teal-Navy", not "blue-800"). Suggest 2-3 options per key color based on hue/saturation.
-- **Elevation philosophy**: flat/layered/lifted. If shadows exist, is their role ambient or structural?
-- **Component philosophy**: the feel of buttons, cards, inputs in one phrase ("tactile and confident" vs. "refined and restrained").
-
-Quote a line from PRODUCT.md when possible so the user sees their own strategic language carry forward.
-
-### Step 4: Write DESIGN.md
-
-The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the structure below. Headers must match character-for-character. Optional evocative subtitles (e.g. `## 2. Colors: The Coastal Palette`) are allowed.
-
-```markdown
----
-name: [Project Title]
-description: [one-line tagline]
-colors:
- # ... staged frontmatter from Step 2b
----
-
-# Design System: [Project Title]
-
-## 1. Overview
-
-**Creative North Star: "[Named metaphor in quotes]"**
-
-[2-3 paragraph holistic description: personality, density, aesthetic philosophy. Start from the North Star and work outward. State what this system explicitly rejects (pulled from PRODUCT.md's anti-references). End with a short **Key Characteristics:** bullet list.]
-
-## 2. Colors
-
-[Describe the palette character in one sentence.]
-
-### Primary
-- **[Descriptive Name]** (#HEX / oklch(...)): [Where and why this color is used. Be specific about context, not just role.]
-
-### Secondary (optional; omit if the project has only one accent)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Tertiary (optional)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Neutral
-- **[Descriptive Name]** (#HEX): [Text / background / border / divider role.]
-- [...]
-
-### Named Rules (optional, powerful)
-**The [Rule Name] Rule.** [Short, forceful prohibition or doctrine, e.g. "The One Voice Rule. The primary accent is used on ≤10% of any given screen. Its rarity is the point."]
-
-## 3. Typography
-
-**Display Font:** [Family] (with [fallback])
-**Body Font:** [Family] (with [fallback])
-**Label/Mono Font:** [Family, if distinct]
-
-**Character:** [1-2 sentence personality description of the pairing.]
-
-### Hierarchy
-- **Display** ([weight], [size/clamp], [line-height]): [Purpose; where it appears.]
-- **Headline** ([weight], [size], [line-height]): [Purpose.]
-- **Title** ([weight], [size], [line-height]): [Purpose.]
-- **Body** ([weight], [size], [line-height]): [Purpose. Include max line length like 65–75ch if relevant.]
-- **Label** ([weight], [size], [letter-spacing], [case if uppercase]): [Purpose.]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [Short doctrine about type use.]
-
-## 4. Elevation
-
-[One paragraph: does this system use shadows, tonal layering, or a hybrid? If "no shadows", say so explicitly and describe how depth is conveyed instead.]
-
-### Shadow Vocabulary (if applicable)
-- **[Role name]** (`box-shadow: [exact value]`): [When to use it.]
-- [...]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [e.g. "The Flat-By-Default Rule. Surfaces are flat at rest. Shadows appear only as a response to state (hover, elevation, focus)."]
-
-## 5. Components
-
-For each component, lead with a short character line, then specify shape, color assignment, states, and any distinctive behavior.
-
-### Buttons
-- **Shape:** [radius described, exact value in parens]
-- **Primary:** [color assignment + padding, in semantic + exact terms]
-- **Hover / Focus:** [transitions, treatments]
-- **Secondary / Ghost / Tertiary (if applicable):** [brief description]
-
-### Chips (if used)
-- **Style:** [background, text color, border treatment]
-- **State:** [selected / unselected, filter / action variants]
-
-### Cards / Containers
-- **Corner Style:** [radius]
-- **Background:** [colors used]
-- **Shadow Strategy:** [reference Elevation section]
-- **Border:** [if any]
-- **Internal Padding:** [scale]
-
-### Inputs / Fields
-- **Style:** [stroke, background, radius]
-- **Focus:** [treatment, e.g. glow, border shift, etc.]
-- **Error / Disabled:** [if applicable]
-
-### Navigation
-- **Style, typography, default/hover/active states, mobile treatment.**
-
-### [Signature Component] (optional; if the project has a distinctive custom component worth documenting)
-[Description.]
-
-## 6. Do's and Don'ts
-
-Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: include exact colors, pixel values, and named anti-patterns the user mentioned in PRODUCT.md. **Every anti-reference in PRODUCT.md should show up here as a "Don't" with the same language**, so the visual spec carries the strategic line through. Quote PRODUCT.md directly where possible: if PRODUCT.md says *"avoid dark mode with purple gradients, neon accents, glassmorphism"*, the Don'ts here should repeat that by name.
-
-### Do:
-- **Do** [specific prescription with exact values / named rule].
-- **Do** [...]
-
-### Don't:
-- **Don't** [specific prohibition, e.g. "use border-left greater than 1px as a colored stripe"].
-- **Don't** [...]
-- **Don't** [...]
-```
-
-### Step 4b: Write .impeccable/design.json sidecar (extensions only)
-
-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.
-
-Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.
-
-#### Schema
-
-```json
-{
- "schemaVersion": 2,
- "generatedAt": "ISO-8601 string",
- "title": "Design System: [Project Title]",
- "extensions": {
- "colorMeta": {
- "primary": { "role": "primary", "displayName": "Editorial Magenta", "canonical": "oklch(60% 0.25 350)", "tonalRamp": ["...", "...", "..."] },
- "warm-ash-cream": { "role": "neutral", "displayName": "Warm Ash Cream", "canonical": "oklch(96% 0.005 350)", "tonalRamp": ["...", "...", "..."] }
- },
- "typographyMeta": {
- "display": { "displayName": "Display", "purpose": "Hero headlines only." }
- },
- "shadows": [
- { "name": "ambient-low", "value": "0 4px 24px rgba(0,0,0,0.12)", "purpose": "Diffuse hover glow under accent elements." }
- ],
- "motion": [
- { "name": "ease-standard", "value": "cubic-bezier(0.4, 0, 0.2, 1)", "purpose": "Default easing for state transitions." }
- ],
- "breakpoints": [
- { "name": "sm", "value": "640px" }
- ]
- },
- "components": [
- {
- "name": "Primary Button",
- "kind": "button | input | nav | chip | card | custom",
- "refersTo": "button-primary",
- "description": "One-line what and when.",
- "html": "<button class=\"ds-btn-primary\">GET STARTED</button>",
- "css": ".ds-btn-primary { background: #191c1d; color: #fff; padding: 16px 48px; letter-spacing: 0.05em; text-transform: uppercase; font-weight: 500; border: none; border-radius: 0; transition: background 0.2s, transform 0.2s; } .ds-btn-primary:hover { background: oklch(60% 0.25 350); transform: translateY(-2px); }"
- }
- ],
- "narrative": {
- "northStar": "The Editorial Sanctuary",
- "overview": "2-3 paragraphs of the philosophy, pulled from DESIGN.md Overview section.",
- "keyCharacteristics": ["...", "..."],
- "rules": [{ "name": "The One Voice Rule", "body": "...", "section": "colors|typography|elevation" }],
- "dos": ["Do use ..."],
- "donts": ["Don't use ..."]
- }
-}
-```
-
-**What changed from schemaVersion 1.** The old sidecar carried token primitive arrays (`tokens.colors[]`, `tokens.typography[]`, etc.). Those values now live in the frontmatter. The sidecar only carries metadata that can't live in the frontmatter (tonal ramps, canonical OKLCH when the hex is an approximation, display names, role hints), keyed by the frontmatter token name (`colorMeta.<token-name>`, `typographyMeta.<token-name>`). Components still carry full HTML/CSS because Stitch's 8-prop set can't hold them.
-
-#### Component translation rules
-
-The `html` and `css` fields must be **self-contained, drop-in snippets** that render correctly when injected into a shadow DOM. The panel applies them directly: no post-processing, no framework runtime.
-
-1. **Tailwind expansion.** If the source uses Tailwind (className="bg-primary text-white rounded-lg px-6 py-3"), expand every utility to literal CSS properties in the `css` string. Do **not** reference Tailwind classes; do **not** assume a Tailwind CSS bundle is loaded. Each component is self-contained.
-2. **Token resolution.** If the project exposes tokens as CSS custom properties on `:root` (e.g. `--color-primary`, `--radius-md`), reference them via `var(--color-primary)`; they inherit through the shadow DOM and stay live-bound. If tokens live only in JS theme objects (styled-components, CSS-in-JS), resolve to literal values at generation time.
-3. **Icons.** Inline as SVG. Do not reference Lucide/Heroicons packages, icon fonts, or `<img src="...">`. A typical icon is 16-24px; copy the SVG path data directly.
-4. **States.** Include `:hover`, `:focus-visible`, and (if meaningful) `:active` rules inline. A static default-only snapshot makes the panel feel dead. Hover + focus rules in the CSS make it feel alive.
-5. **Reset bloat.** Extract only the component's *distinctive* CSS (background, color, padding, border-radius, typography, transition). Skip universal resets (`box-sizing: border-box`, `line-height: inherit`, `-webkit-font-smoothing`). The panel already has a neutral canvas; don't re-ship resets.
-6. **Scoped class names.** Prefix every class with `ds-` (e.g. `ds-btn-primary`, `ds-input-search`) so component CSS doesn't collide with other components' CSS in the same shadow DOM.
-
-#### What to include
-
-Aim for a tight set of **5-10 components** that best represent the visual system:
-
-- **Canonical primitives (always include if the project has them):** button (each variant as a separate component entry), input/text field, navigation, chip/tag, card.
-- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.
-- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.
-
-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.
-
-#### Tonal ramps
-
-For each color token, generate an 8-step `tonalRamp` array: dark to light, same hue and chroma, stepped lightness from ~15% to ~95%. The panel renders this as a strip under the swatch. If the project already defines a tonal scale (Material `surface-container-low` family, Tailwind-style `blue-50..blue-900`), use those values. Otherwise synthesize in OKLCH.
-
-#### Narrative mapping
-
-Pull directly from the DESIGN.md you just wrote:
-
-- `narrative.northStar` → the `**Creative North Star: "..."**` line from Overview
-- `narrative.overview` → the philosophy paragraphs from Overview
-- `narrative.keyCharacteristics` → the bulleted `**Key Characteristics:**` list
-- `narrative.rules` → every `**The [Name] Rule.** [body]` across all sections, tagged with `section`
-- `narrative.dos` / `narrative.donts` → the bullet lists from Do's and Don'ts verbatim
-
-Do not reword. The panel shows these as secondary collapsible context; the same voice that's in the Markdown carries through.
-
-### Step 5: Confirm, refine, and refresh session cache
-
-1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).
-2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.
-3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"
-4. **Refresh the session cache.** Run `node .opencode/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.
-
-## Seed mode
-
-For projects with no visual system to extract yet. Produces a minimal scaffold, not a full spec.
-
-### Step 1: Confirm seed mode
-
-Before interviewing: "There's no existing visual system to scan. I'll ask five quick questions to seed a starter DESIGN.md. You can re-run `/impeccable document` once there's code, to capture the real tokens and components. OK?"
-
-If the user prefers to skip, stop. No file.
-
-### Step 2: Five questions
-
-Group into one `AskUserQuestion` interaction. Options must be concrete.
-
-1. **Color strategy.** Pick one:
- - Restrained: tinted neutrals + one accent ≤10%
- - Committed: one saturated color carries 30–60% of the surface
- - Full palette: 3–4 named color roles, each deliberate
- - Drenched: the surface IS the color
-
- Then: one hue family or anchor reference ("deep teal", "mustard", "Klim #ff4500 orange").
-
-2. **Typography direction.** Pick one (specific fonts come later):
- - Serif display + sans body
- - Single sans (warm / technical / geometric / humanist; pick a feel)
- - Display + mono
- - Mono-forward
- - Editorial script + sans
-
-3. **Motion energy.** Pick one:
- - Restrained: state changes only
- - Responsive: feedback + transitions, no choreography
- - Choreographed: orchestrated entrances, scroll-driven sequences
-
-4. **Three named references.** Brands, products, printed objects. Not adjectives.
-
-5. **One anti-reference.** What it should NOT feel like. Also named.
-
-### Step 3: Write seed DESIGN.md
-
-Use the six-section spec from Scan mode. Populate what the interview answers; leave the rest as honest placeholders. The seed is a scaffold, not a fabricated spec.
-
-Lead the file with:
-
-```markdown
-<!-- SEED: re-run /impeccable document once there's code to capture the actual tokens and components. -->
-```
-
-Per-section guidance in seed mode:
-
-- **Overview**: Creative North Star and philosophy phrased from the answers (color strategy + motion energy + references). Reference the user's anti-reference directly.
-- **Colors**: Color strategy as a Named Rule (e.g. *"The Drenched Rule. The surface IS the color."*). Hue family or anchor reference. No hex values; mark as `[to be resolved during implementation]`.
-- **Typography**: the direction the user picked (e.g. "Serif display + sans body"). No font names yet: `[font pairing to be chosen at implementation]`.
-- **Elevation**: inferred from motion energy. Restrained/Responsive → flat by default; Choreographed → layered. One sentence.
-- **Components**: omit entirely; no components exist yet.
-- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.
-
-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.
-
-### Step 4: Confirm and refresh session cache
-
-1. Show the seed DESIGN.md. Call out that it is a seed (the marker is the literal commitment).
-2. Tell the user: "Re-run `/impeccable document` once you have some code. That pass will extract real tokens and generate the sidecar."
-3. Run `node .opencode/skills/impeccable/scripts/load-context.mjs` once so the seed lands in conversation for the rest of the session.
-
-## Style guidelines
-
-- **Frontmatter first, prose second.** Tokens go in the YAML frontmatter; prose contextualizes them. Don't redefine a token value in two places; the frontmatter is normative.
-- **Cite PRODUCT.md anti-references by name** in the Do's and Don'ts section. If PRODUCT.md lists "SaaS landing-page clichés" or "generic AI tool marketing" as anti-references, the DESIGN.md Don'ts should repeat those phrases verbatim so the visual spec enforces the strategic line.
-- **Match the spec, don't invent new sections.** The six section names are fixed. If you have Layout/Motion/Responsive content to document, fold it into Overview (philosophy-level rules) or Components (per-component behavior).
-- **Descriptive > technical**: "Gently curved edges (8px radius)" > "rounded-lg". Include the technical value in parens, lead with the description.
-- **Functional > decorative**: for each token, explain WHERE and WHY it's used, not just WHAT it is.
-- **Exact values in parens**: hex codes, px/rem values, font weights; always the number in parens alongside the description.
-- **Use Named Rules**: `**The [Name] Rule.** [short doctrine]`. These are memorable, citable, and much stickier for AI consumers than bullet lists. Stitch's own outputs use them heavily ("The No-Line Rule", "The Ghost Border Fallback"). Aim for 1-3 per section.
-- **Be forceful**. The voice of a design director. "Prohibited", "forbidden", "never", "always", not "consider", "might", "prefer". Match PRODUCT.md's tone.
-- **Concrete anti-pattern tests**. Stitch writes things like *"If it looks like a 2014 app, the shadow is too dark and the blur is too small."* A one-sentence audit test beats a paragraph of principle.
-- **Reference PRODUCT.md**. The anti-references section of PRODUCT.md should directly inform the Do's and Don'ts section here. Quote or paraphrase.
-- **Group colors by role**, not by hex-order or hue-order. Primary / Secondary / Tertiary / Neutral is the spec ordering.
-
-## Pitfalls
-
-- Don't paste raw CSS class names. Translate to descriptive language.
-- Don't extract every token. Stop at what's actually reused; one-offs pollute the system.
-- Don't invent components that don't exist. If the project only has buttons and cards, only document those.
-- Don't overwrite an existing DESIGN.md without asking.
-- Don't duplicate content from PRODUCT.md. DESIGN.md is strictly visual.
-- Don't add a "Layout Principles" or "Motion" or "Responsive Behavior" top-level section. The spec has six, not nine. Fold that content where it belongs.
-- Don't rename sections even slightly. "Colors" not "Color Palette & Roles". "Typography" not "Typography Rules". Tooling parsing depends on exact headers.
-- Don't duplicate token values between frontmatter and prose. If a color is in `colors.primary` as hex, the prose can name it and describe its role but should not reassert a different hex. The frontmatter is normative.
-- Don't invent frontmatter token groups outside Stitch's schema (no `motion:`, `breakpoints:`, `shadows:` at the top level). Stitch's Zod schema only accepts `colors`, `typography`, `rounded`, `spacing`, `components`. Anything else belongs in the sidecar's `extensions`.
@@ -1,69 +0,0 @@
-# Extract Flow
-
-Identify reusable patterns, components, and design tokens, then extract and consolidate them into the design system for systematic reuse.
-
-## Step 1: Discover the Design System
-
-Find the design system, component library, or shared UI directory. Understand its structure: component organization, naming conventions, design token structure, import/export conventions.
-
-**CRITICAL**: If no design system exists, STOP and call the `question` tool to clarify. before creating one. Understand the preferred location and structure first.
-
-## Step 2: Identify Patterns
-
-Look for extraction opportunities in the target area:
-
-- **Repeated components**: Similar UI patterns used 3+ times (buttons, cards, inputs)
-- **Hard-coded values**: Colors, spacing, typography, shadows that should be tokens
-- **Inconsistent variations**: Multiple implementations of the same concept
-- **Composition patterns**: Layout or interaction patterns that repeat (form rows, toolbar groups, empty states)
-- **Type styles**: Repeated font-size + weight + line-height combinations
-- **Animation patterns**: Repeated easing, duration, or keyframe combinations
-
-Assess value: only extract things used 3+ times with the same intent. Premature abstraction is worse than duplication.
-
-## Step 3: Plan Extraction
-
-Create a systematic plan:
-
-- **Components to extract**: Which UI elements become reusable components?
-- **Tokens to create**: Which hard-coded values become design tokens?
-- **Variants to support**: What variations does each component need?
-- **Naming conventions**: Component names, token names, prop names that match existing patterns
-- **Migration path**: How to refactor existing uses to consume the new shared versions
-
-**IMPORTANT**: Design systems grow incrementally. Extract what is clearly reusable now, not everything that might someday be reusable.
-
-## Step 4: Extract & Enrich
-
-Build improved, reusable versions:
-
-- **Components**: Clear props API with sensible defaults, proper variants for different use cases, accessibility built in (ARIA, keyboard navigation, focus management), documentation and usage examples
-- **Design tokens**: Clear naming (primitive vs semantic), proper hierarchy and organization, documentation of when to use each token
-- **Patterns**: When to use this pattern, code examples, variations and combinations
-
-## Step 5: Migrate
-
-Replace existing uses with the new shared versions:
-
-- **Find all instances**: Search for the patterns you extracted
-- **Replace systematically**: Update each use to consume the shared version
-- **Test thoroughly**: Ensure visual and functional parity
-- **Delete dead code**: Remove the old implementations
-
-## Step 6: Document
-
-Update design system documentation:
-
-- Add new components to the component library
-- Document token usage and values
-- Add examples and guidelines
-- Update any Storybook or component catalog
-
-**NEVER**:
-- Extract one-off, context-specific implementations without generalization
-- Create components so generic they are useless
-- Extract without considering existing design system conventions
-- Skip proper TypeScript types or prop documentation
-- Create tokens for every single value (tokens should have semantic meaning)
-- Extract things that differ in intent (two buttons that look similar but serve different purposes should stay separate)
-
@@ -1,347 +0,0 @@
-Designs that only work with perfect data aren't production-ready. Harden the interface against the inputs, errors, languages, and network conditions that real users will throw at it.
-
-## Assess Hardening Needs
-
-Identify weaknesses and edge cases:
-
-1. **Test with extreme inputs**:
- - Very long text (names, descriptions, titles)
- - Very short text (empty, single character)
- - Special characters (emoji, RTL text, accents)
- - Large numbers (millions, billions)
- - Many items (1000+ list items, 50+ options)
- - No data (empty states)
-
-2. **Test error scenarios**:
- - Network failures (offline, slow, timeout)
- - API errors (400, 401, 403, 404, 500)
- - Validation errors
- - Permission errors
- - Rate limiting
- - Concurrent operations
-
-3. **Test internationalization**:
- - Long translations (German is often 30% longer than English)
- - RTL languages (Arabic, Hebrew)
- - Character sets (Chinese, Japanese, Korean, emoji)
- - Date/time formats
- - Number formats (1,000 vs 1.000)
- - Currency symbols
-
-**CRITICAL**: Designs that only work with perfect data aren't production-ready. Harden against reality.
-
-## Hardening Dimensions
-
-Systematically improve resilience:
-
-### Text Overflow & Wrapping
-
-**Long text handling**:
-```css
-/* Single line with ellipsis */
-.truncate {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* Multi-line with clamp */
-.line-clamp {
- display: -webkit-box;
- -webkit-line-clamp: 3;
- -webkit-box-orient: vertical;
- overflow: hidden;
-}
-
-/* Allow wrapping */
-.wrap {
- word-wrap: break-word;
- overflow-wrap: break-word;
- hyphens: auto;
-}
-```
-
-**Flex/Grid overflow**:
-```css
-/* Prevent flex items from overflowing */
-.flex-item {
- min-width: 0; /* Allow shrinking below content size */
- overflow: hidden;
-}
-
-/* Prevent grid items from overflowing */
-.grid-item {
- min-width: 0;
- min-height: 0;
-}
-```
-
-**Responsive text sizing**:
-- Use `clamp()` for fluid typography
-- Set minimum readable sizes (14px on mobile)
-- Test text scaling (zoom to 200%)
-- Ensure containers expand with text
-
-### Internationalization (i18n)
-
-**Text expansion**:
-- Add 30-40% space budget for translations
-- Use flexbox/grid that adapts to content
-- Test with longest language (usually German)
-- Avoid fixed widths on text containers
-
-```jsx
-// ❌ Bad: Assumes short English text
-<button className="w-24">Submit</button>
-
-// ✅ Good: Adapts to content
-<button className="px-4 py-2">Submit</button>
-```
-
-**RTL (Right-to-Left) support**:
-```css
-/* Use logical properties */
-margin-inline-start: 1rem; /* Not margin-left */
-padding-inline: 1rem; /* Not padding-left/right */
-border-inline-end: 1px solid; /* Not border-right */
-
-/* Or use dir attribute */
-[dir="rtl"] .arrow { transform: scaleX(-1); }
-```
-
-**Character set support**:
-- Use UTF-8 encoding everywhere
-- Test with Chinese/Japanese/Korean (CJK) characters
-- Test with emoji (they can be 2-4 bytes)
-- Handle different scripts (Latin, Cyrillic, Arabic, etc.)
-
-**Date/Time formatting**:
-```javascript
-// ✅ Use Intl API for proper formatting
-new Intl.DateTimeFormat('en-US').format(date); // 1/15/2024
-new Intl.DateTimeFormat('de-DE').format(date); // 15.1.2024
-
-new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: 'USD'
-}).format(1234.56); // $1,234.56
-```
-
-**Pluralization**:
-```javascript
-// ❌ Bad: Assumes English pluralization
-`${count} item${count !== 1 ? 's' : ''}`
-
-// ✅ Good: Use proper i18n library
-t('items', { count }) // Handles complex plural rules
-```
-
-### Error Handling
-
-**Network errors**:
-- Show clear error messages
-- Provide retry button
-- Explain what happened
-- Offer offline mode (if applicable)
-- Handle timeout scenarios
-
-```jsx
-// Error states with recovery
-{error && (
- <ErrorMessage>
- <p>Failed to load data. {error.message}</p>
- <button onClick={retry}>Try again</button>
- </ErrorMessage>
-)}
-```
-
-**Form validation errors**:
-- Inline errors near fields
-- Clear, specific messages
-- Suggest corrections
-- Don't block submission unnecessarily
-- Preserve user input on error
-
-**API errors**:
-- Handle each status code appropriately
- - 400: Show validation errors
- - 401: Redirect to login
- - 403: Show permission error
- - 404: Show not found state
- - 429: Show rate limit message
- - 500: Show generic error, offer support
-
-**Graceful degradation**:
-- Core functionality works without JavaScript
-- Images have alt text
-- Progressive enhancement
-- Fallbacks for unsupported features
-
-### Edge Cases & Boundary Conditions
-
-**Empty states**:
-- No items in list
-- No search results
-- No notifications
-- No data to display
-- Provide clear next action
-
-**Loading states**:
-- Initial load
-- Pagination load
-- Refresh
-- Show what's loading ("Loading your projects...")
-- Time estimates for long operations
-
-**Large datasets**:
-- Pagination or virtual scrolling
-- Search/filter capabilities
-- Performance optimization
-- Don't load all 10,000 items at once
-
-**Concurrent operations**:
-- Prevent double-submission (disable button while loading)
-- Handle race conditions
-- Optimistic updates with rollback
-- Conflict resolution
-
-**Permission states**:
-- No permission to view
-- No permission to edit
-- Read-only mode
-- Clear explanation of why
-
-**Browser compatibility**:
-- Polyfills for modern features
-- Fallbacks for unsupported CSS
-- Feature detection (not browser detection)
-- Test in target browsers
-
-### Input Validation & Sanitization
-
-**Client-side validation**:
-- Required fields
-- Format validation (email, phone, URL)
-- Length limits
-- Pattern matching
-- Custom validation rules
-
-**Server-side validation** (always):
-- Never trust client-side only
-- Validate and sanitize all inputs
-- Protect against injection attacks
-- Rate limiting
-
-**Constraint handling**:
-```html
-<!-- Set clear constraints -->
-<input
- type="text"
- maxlength="100"
- pattern="[A-Za-z0-9]+"
- required
- aria-describedby="username-hint"
-/>
-<small id="username-hint">
- Letters and numbers only, up to 100 characters
-</small>
-```
-
-### Accessibility Resilience
-
-**Keyboard navigation**:
-- All functionality accessible via keyboard
-- Logical tab order
-- Focus management in modals
-- Skip links for long content
-
-**Screen reader support**:
-- Proper ARIA labels
-- Announce dynamic changes (live regions)
-- Descriptive alt text
-- Semantic HTML
-
-**Motion sensitivity**:
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**High contrast mode**:
-- Test in Windows high contrast mode
-- Don't rely only on color
-- Provide alternative visual cues
-
-### Performance Resilience
-
-**Slow connections**:
-- Progressive image loading
-- Skeleton screens
-- Optimistic UI updates
-- Offline support (service workers)
-
-**Memory leaks**:
-- Clean up event listeners
-- Cancel subscriptions
-- Clear timers/intervals
-- Abort pending requests on unmount
-
-**Throttling & Debouncing**:
-```javascript
-// Debounce search input
-const debouncedSearch = debounce(handleSearch, 300);
-
-// Throttle scroll handler
-const throttledScroll = throttle(handleScroll, 100);
-```
-
-## Testing Strategies
-
-**Manual testing**:
-- Test with extreme data (very long, very short, empty)
-- Test in different languages
-- Test offline
-- Test slow connection (throttle to 3G)
-- Test with screen reader
-- Test keyboard-only navigation
-- Test on old browsers
-
-**Automated testing**:
-- Unit tests for edge cases
-- Integration tests for error scenarios
-- E2E tests for critical paths
-- Visual regression tests
-- Accessibility tests (axe, WAVE)
-
-**IMPORTANT**: Hardening is about expecting the unexpected. Real users will do things you never imagined.
-
-**NEVER**:
-- Assume perfect input (validate everything)
-- Ignore internationalization (design for global)
-- Leave error messages generic ("Error occurred")
-- Forget offline scenarios
-- Trust client-side validation alone
-- Use fixed widths for text
-- Assume English-length text
-- Block entire interface when one component errors
-
-## Verify Hardening
-
-Test thoroughly with edge cases:
-
-- **Long text**: Try names with 100+ characters
-- **Emoji**: Use emoji in all text fields
-- **RTL**: Test with Arabic or Hebrew
-- **CJK**: Test with Chinese/Japanese/Korean
-- **Network issues**: Disable internet, throttle connection
-- **Large datasets**: Test with 1000+ items
-- **Concurrent actions**: Click submit 10 times rapidly
-- **Errors**: Force API errors, test all error states
-- **Empty**: Remove all data, test empty states
-
-When edge cases are covered, hand off to `/impeccable polish` for the final pass.
@@ -1,234 +0,0 @@
-# Heuristics Scoring Guide
-
-Score each of Nielsen's 10 Usability Heuristics on a 0–4 scale. Be honest: a 4 means genuinely excellent, not "good enough."
-
-## Nielsen's 10 Heuristics
-
-### 1. Visibility of System Status
-
-Keep users informed about what's happening through timely, appropriate feedback.
-
-**Check for**:
-- Loading indicators during async operations
-- Confirmation of user actions (save, submit, delete)
-- Progress indicators for multi-step processes
-- Current location in navigation (breadcrumbs, active states)
-- Form validation feedback (inline, not just on submit)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No feedback; user is guessing what happened |
-| 1 | Rare feedback; most actions produce no visible response |
-| 2 | Partial; some states communicated, major gaps remain |
-| 3 | Good; most operations give clear feedback, minor gaps |
-| 4 | Excellent; every action confirms, progress is always visible |
-
-### 2. Match Between System and Real World
-
-Speak the user's language. Follow real-world conventions. Information appears in natural, logical order.
-
-**Check for**:
-- Familiar terminology (no unexplained jargon)
-- Logical information order matching user expectations
-- Recognizable icons and metaphors
-- Domain-appropriate language for the target audience
-- Natural reading flow (left-to-right, top-to-bottom priority)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Pure tech jargon, alien to users |
-| 1 | Mostly confusing; requires domain expertise to navigate |
-| 2 | Mixed; some plain language, some jargon leaks through |
-| 3 | Mostly natural; occasional term needs context |
-| 4 | Speaks the user's language fluently throughout |
-
-### 3. User Control and Freedom
-
-Users need a clear "emergency exit" from unwanted states without extended dialogue.
-
-**Check for**:
-- Undo/redo functionality
-- Cancel buttons on forms and modals
-- Clear navigation back to safety (home, previous)
-- Easy way to clear filters, search, selections
-- Escape from long or multi-step processes
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Users get trapped; no way out without refreshing |
-| 1 | Difficult exits; must find obscure paths to escape |
-| 2 | Some exits; main flows have escape, edge cases don't |
-| 3 | Good control; users can exit and undo most actions |
-| 4 | Full control; undo, cancel, back, and escape everywhere |
-
-### 4. Consistency and Standards
-
-Users shouldn't wonder whether different words, situations, or actions mean the same thing.
-
-**Check for**:
-- Consistent terminology throughout the interface
-- Same actions produce same results everywhere
-- Platform conventions followed (standard UI patterns)
-- Visual consistency (colors, typography, spacing, components)
-- Consistent interaction patterns (same gesture = same behavior)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Inconsistent everywhere; feels like different products stitched together |
-| 1 | Many inconsistencies; similar things look/behave differently |
-| 2 | Partially consistent; main flows match, details diverge |
-| 3 | Mostly consistent; occasional deviation, nothing confusing |
-| 4 | Fully consistent; cohesive system, predictable behavior |
-
-### 5. Error Prevention
-
-Better than good error messages is a design that prevents problems in the first place.
-
-**Check for**:
-- Confirmation before destructive actions (delete, overwrite)
-- Constraints preventing invalid input (date pickers, dropdowns)
-- Smart defaults that reduce errors
-- Clear labels that prevent misunderstanding
-- Autosave and draft recovery
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Errors easy to make; no guardrails anywhere |
-| 1 | Few safeguards; some inputs validated, most aren't |
-| 2 | Partial prevention; common errors caught, edge cases slip |
-| 3 | Good prevention; most error paths blocked proactively |
-| 4 | Excellent; errors nearly impossible through smart constraints |
-
-### 6. Recognition Rather Than Recall
-
-Minimize memory load. Make objects, actions, and options visible or easily retrievable.
-
-**Check for**:
-- Visible options (not buried in hidden menus)
-- Contextual help when needed (tooltips, inline hints)
-- Recent items and history
-- Autocomplete and suggestions
-- Labels on icons (not icon-only navigation)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Heavy memorization; users must remember paths and commands |
-| 1 | Mostly recall; many hidden features, few visible cues |
-| 2 | Some aids; main actions visible, secondary features hidden |
-| 3 | Good recognition; most things discoverable, few memory demands |
-| 4 | Everything discoverable; users never need to memorize |
-
-### 7. Flexibility and Efficiency of Use
-
-Accelerators, invisible to novices, speed up expert interaction.
-
-**Check for**:
-- Keyboard shortcuts for common actions
-- Customizable interface elements
-- Recent items and favorites
-- Bulk/batch actions
-- Power user features that don't complicate the basics
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | One rigid path; no shortcuts or alternatives |
-| 1 | Limited flexibility; few alternatives to the main path |
-| 2 | Some shortcuts; basic keyboard support, limited bulk actions |
-| 3 | Good accelerators; keyboard nav, some customization |
-| 4 | Highly flexible; multiple paths, power features, customizable |
-
-### 8. Aesthetic and Minimalist Design
-
-Interfaces should not contain irrelevant or rarely needed information. Every element should serve a purpose.
-
-**Check for**:
-- Only necessary information visible at each step
-- Clear visual hierarchy directing attention
-- Purposeful use of color and emphasis
-- No decorative clutter competing for attention
-- Focused, uncluttered layouts
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Overwhelming; everything competes for attention equally |
-| 1 | Cluttered; too much noise, hard to find what matters |
-| 2 | Some clutter; main content clear, periphery noisy |
-| 3 | Mostly clean; focused design, minor visual noise |
-| 4 | Perfectly minimal; every element earns its pixel |
-
-### 9. Help Users Recognize, Diagnose, and Recover from Errors
-
-Error messages should use plain language, precisely indicate the problem, and constructively suggest a solution.
-
-**Check for**:
-- Plain language error messages (no error codes for users)
-- Specific problem identification ("Email is missing @" not "Invalid input")
-- Actionable recovery suggestions
-- Errors displayed near the source of the problem
-- Non-blocking error handling (don't wipe the form)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Cryptic errors; codes, jargon, or no message at all |
-| 1 | Vague errors; "Something went wrong" with no guidance |
-| 2 | Clear but unhelpful; names the problem but not the fix |
-| 3 | Clear with suggestions; identifies problem and offers next steps |
-| 4 | Perfect recovery; pinpoints issue, suggests fix, preserves user work |
-
-### 10. Help and Documentation
-
-Even if the system is usable without docs, help should be easy to find, task-focused, and concise.
-
-**Check for**:
-- Searchable help or documentation
-- Contextual help (tooltips, inline hints, guided tours)
-- Task-focused organization (not feature-organized)
-- Concise, scannable content
-- Easy access without leaving current context
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No help available anywhere |
-| 1 | Help exists but hard to find or irrelevant |
-| 2 | Basic help; FAQ or docs exist, not contextual |
-| 3 | Good documentation; searchable, mostly task-focused |
-| 4 | Excellent contextual help; right info at the right moment |
-
----
-
-## Score Summary
-
-**Total possible**: 40 points (10 heuristics × 4 max)
-
-| Score Range | Rating | What It Means |
-|-------------|--------|---------------|
-| 36–40 | Excellent | Minor polish only; ship it |
-| 28–35 | Good | Address weak areas, solid foundation |
-| 20–27 | Acceptable | Significant improvements needed before users are happy |
-| 12–19 | Poor | Major UX overhaul required; core experience broken |
-| 0–11 | Critical | Redesign needed; unusable in current state |
-
----
-
-## Issue Severity (P0–P3)
-
-Tag each individual issue found during scoring with a priority level:
-
-| Priority | Name | Description | Action |
-|----------|------|-------------|--------|
-| **P0** | Blocking | Prevents task completion entirely | Fix immediately; this is a showstopper |
-| **P1** | Major | Causes significant difficulty or confusion | Fix before release |
-| **P2** | Minor | Annoyance, but workaround exists | Fix in next pass |
-| **P3** | Polish | Nice-to-fix, no real user impact | Fix if time permits |
-
-**Tip**: If you're unsure between two levels, ask: "Would a user contact support about this?" If yes, it's at least P1.
@@ -1,195 +0,0 @@
-# Interaction Design
-
-## The Eight Interactive States
-
-Every interactive element needs these states designed:
-
-| State | When | Visual Treatment |
-|-------|------|------------------|
-| **Default** | At rest | Base styling |
-| **Hover** | Pointer over (not touch) | Subtle lift, color shift |
-| **Focus** | Keyboard/programmatic focus | Visible ring (see below) |
-| **Active** | Being pressed | Pressed in, darker |
-| **Disabled** | Not interactive | Reduced opacity, no pointer |
-| **Loading** | Processing | Spinner, skeleton |
-| **Error** | Invalid state | Red border, icon, message |
-| **Success** | Completed | Green check, confirmation |
-
-**The common miss**: Designing hover without focus, or vice versa. They're different. Keyboard users never see hover states.
-
-## Focus Rings: Do Them Right
-
-**Never `outline: none` without replacement.** It's an accessibility violation. Instead, use `:focus-visible` to show focus only for keyboard users:
-
-```css
-/* Hide focus ring for mouse/touch */
-button:focus {
- outline: none;
-}
-
-/* Show focus ring for keyboard */
-button:focus-visible {
- outline: 2px solid var(--color-accent);
- outline-offset: 2px;
-}
-```
-
-**Focus ring design**:
-- High contrast (3:1 minimum against adjacent colors)
-- 2-3px thick
-- Offset from element (not inside it)
-- Consistent across all interactive elements
-
-## Form Design: The Non-Obvious
-
-**Placeholders aren't labels.** They disappear on input. Always use visible `<label>` elements. **Validate on blur**, not on every keystroke (exception: password strength). Place errors **below** fields with `aria-describedby` connecting them.
-
-## Loading States
-
-**Optimistic updates**: Show success immediately, rollback on failure. Use for low-stakes actions (likes, follows), not payments or destructive actions. **Skeleton screens > spinners**: they preview content shape and feel faster than generic spinners.
-
-## Modals: The Inert Approach
-
-Focus trapping in modals used to require complex JavaScript. Now use the `inert` attribute:
-
-```html
-<!-- When modal is open -->
-<main inert>
- <!-- Content behind modal can't be focused or clicked -->
-</main>
-<dialog open>
- <h2>Modal Title</h2>
- <!-- Focus stays inside modal -->
-</dialog>
-```
-
-Or use the native `<dialog>` element:
-
-```javascript
-const dialog = document.querySelector('dialog');
-dialog.showModal(); // Opens with focus trap, closes on Escape
-```
-
-## The Popover API
-
-For tooltips, dropdowns, and non-modal overlays, use native popovers:
-
-```html
-<button popovertarget="menu">Open menu</button>
-<div id="menu" popover>
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-**Benefits**: Light-dismiss (click outside closes), proper stacking, no z-index wars, accessible by default.
-
-## Dropdown & Overlay Positioning
-
-Dropdowns rendered with `position: absolute` inside a container that has `overflow: hidden` or `overflow: auto` will be clipped. This is the single most common dropdown bug in generated code.
-
-### CSS Anchor Positioning
-
-The modern solution uses the CSS Anchor Positioning API to tether an overlay to its trigger without JavaScript:
-
-```css
-.trigger {
- anchor-name: --menu-trigger;
-}
-
-.dropdown {
- position: fixed;
- position-anchor: --menu-trigger;
- position-area: block-end span-inline-end;
- margin-top: 4px;
-}
-
-/* Flip above if no room below */
-@position-try --flip-above {
- position-area: block-start span-inline-end;
- margin-bottom: 4px;
-}
-```
-
-Because the dropdown uses `position: fixed`, it escapes any `overflow` clipping on ancestor elements. The `@position-try` block handles viewport edges automatically. **Browser support**: Chrome 125+, Edge 125+. Not yet in Firefox or Safari - use a fallback for those browsers.
-
-### Popover + Anchor Combo
-
-Combining the Popover API with anchor positioning gives you stacking, light-dismiss, accessibility, and correct positioning in one pattern:
-
-```html
-<button popovertarget="menu" class="trigger">Open</button>
-<div id="menu" popover class="dropdown">
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-The `popover` attribute places the element in the **top layer**, which sits above all other content regardless of z-index or overflow. No portal needed.
-
-### Portal / Teleport Pattern
-
-In component frameworks, render the dropdown at the document root and position it with JavaScript:
-
-- **React**: `createPortal(dropdown, document.body)`
-- **Vue**: `<Teleport to="body">`
-- **Svelte**: Use a portal library or mount to `document.body`
-
-Calculate position from the trigger's `getBoundingClientRect()`, then apply `position: fixed` with `top` and `left` values. Recalculate on scroll and resize.
-
-### Fixed Positioning Fallback
-
-For browsers without anchor positioning support, `position: fixed` with manual coordinates avoids overflow clipping:
-
-```css
-.dropdown {
- position: fixed;
- /* top/left set via JS from trigger's getBoundingClientRect() */
-}
-```
-
-Check viewport boundaries before rendering. If the dropdown would overflow the bottom edge, flip it above the trigger. If it would overflow the right edge, align it to the trigger's right side instead.
-
-### Anti-Patterns
-
-- **`position: absolute` inside `overflow: hidden`** - The dropdown will be clipped. Use `position: fixed` or the top layer instead.
-- **Arbitrary z-index values** like `z-index: 9999` - Use a semantic z-index scale: `dropdown (100) -> sticky (200) -> modal-backdrop (300) -> modal (400) -> toast (500) -> tooltip (600)`.
-- **Rendering dropdown markup inline** without an escape hatch from the parent's stacking context. Either use `popover` (top layer), a portal, or `position: fixed`.
-
-## Destructive Actions: Undo > Confirm
-
-**Undo is better than confirmation dialogs.** Users click through confirmations mindlessly. Remove from UI immediately, show undo toast, actually delete after toast expires. Use confirmation only for truly irreversible actions (account deletion), high-cost actions, or batch operations.
-
-## Keyboard Navigation Patterns
-
-### Roving Tabindex
-
-For component groups (tabs, menu items, radio groups), one item is tabbable; arrow keys move within:
-
-```html
-<div role="tablist">
- <button role="tab" tabindex="0">Tab 1</button>
- <button role="tab" tabindex="-1">Tab 2</button>
- <button role="tab" tabindex="-1">Tab 3</button>
-</div>
-```
-
-Arrow keys move `tabindex="0"` between items. Tab moves to the next component entirely.
-
-### Skip Links
-
-Provide skip links (`<a href="#main-content">Skip to main content</a>`) for keyboard users to jump past navigation. Hide off-screen, show on focus.
-
-## Gesture Discoverability
-
-Swipe-to-delete and similar gestures are invisible. Hint at their existence:
-
-- **Partially reveal**: Show delete button peeking from edge
-- **Onboarding**: Coach marks on first use
-- **Alternative**: Always provide a visible fallback (menu with "Delete")
-
-Don't rely on gestures as the only way to perform actions.
-
----
-
-**Avoid**: Removing focus indicators without alternatives. Using placeholder text as labels. Touch targets <44x44px. Generic error messages. Custom controls without ARIA/keyboard support.
@@ -1,141 +0,0 @@
-Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids, the centered-stack default) and fix the structure, not the surface.
-
----
-
-## Register
-
-Brand: asymmetric compositions, fluid spacing with `clamp()`, intentional grid-breaking for emphasis. Rhythm through contrast: tight groupings paired with generous separations.
-
-Product: predictable grids, consistent densities, familiar navigation patterns. Responsive behavior is structural (collapse sidebar, responsive table), not fluid typography. Consistency IS an affordance.
-
----
-
-## Assess Current Layout
-
-Analyze what's weak about the current spatial design:
-
-1. **Spacing**:
- - Is spacing consistent or arbitrary? (Random padding/margin values)
- - Is all spacing the same? (Equal padding everywhere = no rhythm)
- - Are related elements grouped tightly, with generous space between groups?
-
-2. **Visual hierarchy**:
- - Apply the squint test: blur your (metaphorical) eyes. Can you still identify the most important element, second most important, and clear groupings?
- - Is hierarchy achieved effectively? (Space and weight alone can be enough; is the current approach working?)
- - Does whitespace guide the eye to what matters?
-
-3. **Grid & structure**:
- - Is there a clear underlying structure, or does the layout feel random?
- - Are identical card grids used everywhere? (Icon + heading + text, repeated endlessly)
- - Is everything centered? (Left-aligned with asymmetric layouts feels more designed, but not a hard and fast rule)
-
-4. **Rhythm & variety**:
- - Does the layout have visual rhythm? (Alternating tight/generous spacing)
- - Is every section structured the same way? (Monotonous repetition)
- - Are there intentional moments of surprise or emphasis?
-
-5. **Density**:
- - Is the layout too cramped? (Not enough breathing room)
- - Is the layout too sparse? (Excessive whitespace without purpose)
- - Does density match the content type? (Data-dense UIs need tighter spacing; marketing pages need more air)
-
-**CRITICAL**: Layout problems are often the root cause of interfaces feeling "off" even when colors and fonts are fine. Space is a design material; use it with intention.
-
-## Plan Layout Improvements
-
-Consult the [spatial design reference](spatial-design.md) for detailed guidance on grids, rhythm, and container queries.
-
-Create a systematic plan:
-
-- **Spacing system**: Use a consistent scale (a framework's built-in scale like Tailwind's, rem-based tokens, or a custom system). The specific values matter less than consistency.
-- **Hierarchy strategy**: How will space communicate importance?
-- **Layout approach**: What structure fits the content? Flex for 1D, Grid for 2D, named areas for complex page layouts.
-- **Rhythm**: Where should spacing be tight vs generous?
-
-## Improve Layout Systematically
-
-### Establish a Spacing System
-
-- Use a consistent spacing scale (framework scales like Tailwind, rem-based tokens, or a custom scale all work). What matters is that values come from a defined set, not arbitrary numbers.
-- Name tokens semantically if using custom properties: `--space-xs` through `--space-xl`, not `--spacing-8`
-- Use `gap` for sibling spacing instead of margins; eliminates margin collapse hacks
-- Apply `clamp()` for fluid spacing that breathes on larger screens
-
-### Create Visual Rhythm
-
-- **Tight grouping** for related elements (8-12px between siblings)
-- **Generous separation** between distinct sections (48-96px)
-- **Varied spacing** within sections (not every row needs the same gap)
-- **Asymmetric compositions**: break the predictable centered-content pattern when it makes sense
-
-### Choose the Right Layout Tool
-
-- **Use Flexbox for 1D layouts**: Rows of items, nav bars, button groups, card contents, most component internals. Flex is simpler and more appropriate for the majority of layout tasks.
-- **Use Grid for 2D layouts**: Page-level structure, dashboards, data-dense interfaces, anything where rows AND columns need coordinated control.
-- **Don't default to Grid** when Flexbox with `flex-wrap` would be simpler and more flexible.
-- Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints.
-- Use named grid areas (`grid-template-areas`) for complex page layouts; redefine at breakpoints.
-
-### Break Card Grid Monotony
-
-- Don't default to card grids for everything; spacing and alignment create visual grouping naturally
-- Use cards only when content is truly distinct and actionable. Never nest cards inside cards
-- Vary card sizes, span columns, or mix cards with non-card content to break repetition
-
-### Strengthen Visual Hierarchy
-
-- Use the fewest dimensions needed for clear hierarchy. Space alone can be enough; generous whitespace around an element draws the eye. Some of the most polished designs achieve rhythm with just space and weight. Add color or size contrast only when simpler means aren't sufficient.
-- Be aware of reading flow: in LTR languages, the eye naturally scans top-left to bottom-right, but primary action placement depends on context (e.g., bottom-right in dialogs, top in navigation).
-- Create clear content groupings through proximity and separation.
-
-### Manage Depth & Elevation
-
-- Create a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip)
-- Build a consistent shadow scale (sm → md → lg → xl); shadows should be subtle
-- Use elevation to reinforce hierarchy, not as decoration
-
-### Optical Adjustments
-
-- If an icon looks visually off-center despite being geometrically centered, nudge it. But only if you're confident it actually looks wrong. Don't adjust speculatively.
-
-**NEVER**:
-- Use arbitrary spacing values outside your scale
-- Make all spacing equal (variety creates hierarchy)
-- Wrap everything in cards (not everything needs a container)
-- Nest cards inside cards (use spacing and dividers for hierarchy within)
-- Use identical card grids everywhere (icon + heading + text, repeated)
-- Center everything (left-aligned with asymmetry feels more designed)
-- Default to the hero metric layout (big number, small label, stats, gradient) as a template. If showing real user data, a prominent metric can work, but it should display actual data, not decorative numbers.
-- Default to CSS Grid when Flexbox would be simpler; use the simplest tool for the job
-- Use arbitrary z-index values (999, 9999); build a semantic scale
-
-## Verify Layout Improvements
-
-- **Squint test**: Can you identify primary, secondary, and groupings with blurred vision?
-- **Rhythm**: Does the page have a satisfying beat of tight and generous spacing?
-- **Hierarchy**: Is the most important content obvious within 2 seconds?
-- **Breathing room**: Does the layout feel comfortable, not cramped or wasteful?
-- **Consistency**: Is the spacing system applied uniformly?
-- **Responsiveness**: Does the layout adapt gracefully across screen sizes?
-
-When the rhythm and hierarchy land, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `density` param. Drive all spacing tokens in the variant's scoped CSS through `calc(var(--p-density, 1) * <base>)`: paddings, gaps, column widths. Users slide from airy to packed and see layout re-breathe with no regeneration.
-
-```json
-{"id":"density","kind":"range","min":0.6,"max":1.4,"step":0.05,"default":1,"label":"Density"}
-```
-
-For variants whose topology genuinely changes (stacked vs. side-by-side, grid vs. bento), use a `steps` param whose scoped CSS branches via `:scope[data-p-structure="X"]`. One structure param + one density param is a powerful combo; resist adding a third.
-
-```json
-{"id":"structure","kind":"steps","default":"grid","label":"Structure","options":[
- {"value":"stacked","label":"Stacked"},
- {"value":"grid","label":"Grid"},
- {"value":"bento","label":"Bento"}
-]}
-```
-
-See `reference/live.md` for the full params contract.
@@ -1,622 +0,0 @@
-Interactive live variant mode: select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via the dev server's HMR.
-
-## Prerequisites
-
-A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR a static HTML file open in the browser.
-
-## The contract (read once)
-
-Execute in order. No step skipped, no step reordered.
-
-1. `live.mjs`: boot.
-2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.
-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.
-5. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
-6. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
-7. On `exit`: run the cleanup at the bottom.
-
-Harness policy:
-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.
-- **Cursor**: run the poll in the **foreground** (blocking shell; not a background terminal, not a subagent). Cursor background terminals and subagents do not reliably resume the chat with poll stdout.
-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.
-- **Other harnesses**: foreground unless you know stdout reliably returns to this session.
-
-Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.
-
-## Start
-
-```bash
-node .opencode/skills/impeccable/scripts/live.mjs
-```
-
-Output JSON: `{ ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath, migrated }`. `pageFiles` is the list of HTML entries the live script was injected into. Keep PRODUCT.md and DESIGN.md in mind for variant generation; **DESIGN.md wins on visual decisions; PRODUCT.md wins on strategic/voice decisions.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt. If `migrated: true`, the loader auto-renamed legacy `.impeccable.md` to `PRODUCT.md`; mention this once and suggest `/impeccable document` for the matching DESIGN.md.
-
-`serverPort` and `serverToken` belong to the small **Impeccable live helper** HTTP server (serves `/live.js`, SSE, and `/poll`). That port is **not** your dev server and is usually not the URL you open to view the app. The browser page is whatever origin serves one of the `pageFiles` entries (Vite / Next / Bun / tunnel / LAN hostname).
-
-If output is `{ ok: false, error: "config_missing" | "config_invalid", path }`, this project hasn't been configured for live mode (or its config is stale). See **First-time setup** at the bottom.
-
-## Poll loop
-
-```
-LOOP:
- node .opencode/skills/impeccable/scripts/live-poll.mjs # default long timeout; no --timeout=
- Read JSON; dispatch on "type"
-
- "generate" → Handle Generate; reply done; LOOP
- "accept" → Handle Accept; complete carbonize cleanup if required; LOOP
- "discard" → Handle Discard; LOOP
- "prefetch" → Handle Prefetch; LOOP
- "timeout" → LOOP
- "exit" → break → Cleanup
-```
-
-## Recovery commands
-
-The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.
-
-Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:
-
-```bash
-node .opencode/skills/impeccable/scripts/live-status.mjs
-node .opencode/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID
-node .opencode/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID
-```
-
-- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.
-- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.
-- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.
-
-Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.
-
-## Handle `generate`
-
-Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.
-
-Speed matters; the user is watching a spinner. Minimize tool calls by using the `wrap` helper and writing all variants in a single edit.
-
-### 1. Read the screenshot (if present)
-
-`event.screenshotPath` is **only sent when the user placed at least one comment or stroke before Go.** When present, it's an absolute path to a PNG of the element as rendered with the annotations baked in. **Read it before planning**: annotations encode user intent not recoverable from `element.outerHTML` alone.
-
-When `screenshotPath` is absent, don't ask for one and don't go looking for the current rendering. The omission is deliberate: without annotations, a screenshot would anchor the model on the existing design and fight the three-distinct-directions brief. Work from `element.outerHTML`, the computed styles in `event.element`, and the freeform prompt if present.
-
-`event.comments` and `event.strokes` carry structured metadata alongside the visual. Treat the screenshot as primary; use the structured data for specifics worth quoting (e.g. the exact text of a comment).
-
-Reading annotations precisely:
-
-- **Comment position carries meaning.** Its `{x, y}` is element-local CSS px (same coord space as `element.boundingRect`). Find the child under that point and apply the comment text LOCALLY to that sub-element. A comment near the title is about the title, not a global description.
-- **Comments and strokes are independent annotations** unless clearly paired by overlap or tight proximity. Don't let the visual weight of a prominent stroke override the precise location of a textually-specific comment elsewhere.
-- **Strokes are gestures; read them by shape.** Closed loop = "this thing" (emphasis / focus); arrow = direction (move / point to); cross or slash = delete; free scribble = emphasis or delete depending on context. A loop around region X means "pay attention to X," not "only change pixels inside X."
-- **When a stroke's intent is ambiguous** (circle or arrow? emphasis or move?), state your reading in one sentence of rationale rather than silently guessing. If the uncertainty materially changes the brief, ask one short clarifying question before generating.
-
-### 2. Wrap the element
-
-```bash
-node .opencode/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"
-```
-
-Flag mapping. Keep them separate, don't collapse into `--query`:
-
-- `--element-id` ← `event.element.id`
-- `--classes` ← `event.element.classes` joined with commas
-- `--tag` ← `event.element.tagName`
-- `--text` ← first ~80 chars of `event.element.textContent` (trim, single-line). **Pass this every call.** When the picked element shares classes + tag with sibling components (a list of `<Card>`s, repeating sections), this is what disambiguates which branch in source to wrap. Without it, wrap silently lands on the first match and may rewrite the wrong element.
-
-The helper searches ID first, then classes, then tag + class combo. If `event.pageUrl` implies the file (e.g. `/` is usually `index.html`), pass `--file PATH` to skip the search. `--query` is a fallback for raw text search only; do not use it for normal element lookups.
-
-If `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.
-
-Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.
-
-`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:
-
-- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.
-- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.
-
-Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.
-
-**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:
-
-- `{ error: "file_is_generated", file, hint }`: user-supplied `--file` points at a generated file.
-- `{ error: "element_not_in_source", generatedMatch, hint }`: element exists only in a generated file (the next build would wipe any edits).
-- `{ error: "element_not_found", hint }`: element isn't in any project file; likely runtime-injected (JS component, dynamic render from data).
-
-All three carry `fallback: "agent-driven"`. Follow **Handle fallback** below.
-
-### 3. Load the action's reference
-
-If `event.action` is `impeccable` (the default freeform action), use SKILL.md's shared laws plus the loaded register reference (`brand.md` or `product.md`). Do not load a sub-command reference. **Freeform is not a pass to skip parameters:** you still follow the composition budget and the freeform bias in **§7 Parameters** below. Sub-command files list MUST-have signature knobs; freeform has no such file, so sizing knobs from surface weight and primary axes is entirely on you.
-
-Any other `event.action` (`bolder`, `quieter`, `distill`, `polish`, `typeset`, `colorize`, `layout`, `adapt`, `animate`, `delight`, `overdrive`): Read `reference/<action>.md` before planning. Each sub-command encodes a specific discipline; skipping its reference produces generic output. Those files may require specific params; layer them on top of the §7 budget, not instead of it.
-
-### 4. Plan three variants: identity first, then mode, then axes
-
-The wrong frame for live mode is "show three different design directions." Live runs on an existing surface; the brand has already been chosen. The job is variation **within identity**, not selection between identities. Failure mode: three editorial-typographic variants on a brief that wasn't editorial. Bigger failure mode: three off-brand variants the user can't accept because they don't look like their product.
-
-Four phases. Do them in order.
-
-#### Phase A: Extract the identity (non-skippable)
-
-The existing surface has an identity already. Read it before planning anything. Sources, in priority order:
-
-1. **DESIGN.md** if loaded: read the visual system fields (palette, type pairing, motion, components). This is the authoritative answer.
-2. **CSS custom properties** in the page's stylesheets (`:root { --color-...; --font-...; ... }`): these are de-facto tokens.
-3. **Computed styles** on the picked element and its parent: colors, fonts, spacing scales, corner radii.
-4. **Sibling components on the page**: what visual rhetoric do existing components use? (Asymmetric or centered? Dense or airy? Bold or quiet?)
-
-Write down what you see in **one sentence**. The sentence describes the surface that's actually on screen; it is not aspirational, not opinionated, not edited toward what the brand "should" be. Capture, in roughly this order:
-
-- The dominant surface color and accent color, by hex or token name (use the actual values, not categories like "warm" or "neutral").
-- The type pairing: the actual font names loaded, primary first.
-- The layout topology: how the dominant elements are arranged (stacked / side-by-side / grid / asymmetric / overlay).
-- The surface treatment: corners, borders, shadows, density of decoration.
-- The voice tone you read off the copy itself, not off the aesthetic feel.
-
-Be specific. "Modern" is not a color, "elegant" is not a type pairing, "clean" is not a layout. If you can't extract a real value for an axis, skip it rather than fabricate. The point is to record what is, not to describe what you wish it were.
-
-Do not include adjectives that name an aesthetic family ("editorial-leaning", "terminal-flavored", "brutalist"); those are conclusions, not data. They belong to Phase C lane selection in departure mode, not to identity description. Letting them sneak into Phase A is how the identity-lock collapses into a self-fulfilling prophecy.
-
-This sentence is the **identity lock**. Every variant must be readable as the same brand if rendered side by side. Skipping this phase is the primary cause of off-brand variants. Absence of DESIGN.md is never an excuse; extract from CSS and computed styles instead.
-
-#### Phase B: Pick mode (default vs departure)
-
-**Default mode**: the existing identity is preserved. Variants vary expression axes within it. *This is the right mode for ~90% of live sessions.* The user picked an element on a real product they're shipping; they expect variants of *their* hero, not three different brands' heroes.
-
-**Departure mode**: the existing identity is rejected. Variants propose alternatives consistent with PRODUCT.md voice. Trigger only when at least one is true:
-
-- PRODUCT.md anti-references explicitly call out the current surface ("the current `index.html` is itself an example"; "diffuse away from this"; "the page on screen is the failure"). Generic anti-references that describe what to avoid in general do **not** trigger departure mode; only ones that point at *this* surface specifically.
-- The user's freeform prompt explicitly asks for departure ("rebuild this from scratch", "what if it weren't editorial at all", "show me something completely different").
-
-If you're unsure, you're in default mode. The cost of being wrong about default is "three on-brand variants with similar feel": recoverable, the user picks none. The cost of being wrong about departure is "three off-brand variants": unrecoverable, the user is annoyed.
-
-#### Phase C: Plan three variants
-
-**Default mode.** Each variant commits to a different **primary axis** of difference, while preserving the identity sentence. The six axes:
-
-1. **Hierarchy**: which element commands the eye?
-2. **Layout topology**: stacked / side-by-side / grid / asymmetric / overlay
-3. **Typographic system**: pairing logic, scale ratio, case/weight strategy *within the available faces*
-4. **Color strategy**: which existing palette role carries the surface (Restrained / Committed / Full palette / Drenched). Use the brand's existing palette tokens, not new colors.
-5. **Density**: minimal / comfortable / dense
-6. **Structural decomposition**: merge, split, progressive disclosure
-
-Three variants → three DIFFERENT axes. The trio reads as *the same brand at three angles*. Do not introduce new fonts, new palette hues, or new aesthetic-family signals; those belong to departure mode.
-
-**While planning each variant, also name its 2–3 parameter knobs** (per the §7 budget table). Parameters are part of the design, not a decoration added afterward. If the variant explores density, expose a density knob. If it explores color commitment, expose a color-amount range. Deciding "what's tunable" during planning produces better knobs than retrofitting them onto finished HTML.
-
-**Departure mode.** Each variant anchors to a different **aesthetic direction**, derived from the brand's stated voice and register in PRODUCT.md. Do NOT pick from a fixed catalog of lane categories. The right three directions for this brand are not the same as the right three for another brand, and picking from a list is itself the training-data reflex (the model selects "Swiss-grid, Terminal, Industrial-signage" every time because those are the furthest-from-editorial items in any enumerated list).
-
-Instead, work from the brand:
-
-1. Read PRODUCT.md's Brand Personality words. What physical, spatial, or material experiences would embody those words if design were not involved? (A personality described as "specific, earned, unmistakable" evokes a hand-stamped letter, a numbered print, a watchmaker's loupe. A personality described as "restless, loud, unfiltered" evokes a concert poster, a spray-painted wall, a megaphone.)
-2. From those physical experiences, derive three visual directions that are genuinely different from each other AND from the current surface you're departing.
-3. Avoid the **reflex-reject lanes** in [brand.md](brand.md). Don't trade one monoculture for another. If you find yourself reaching for "Swiss-grid" or "Terminal" or "Industrial-signage" by reflex, you are pattern-matching a catalog in your training data, not reading the brand. Start over from the personality words.
-4. Each direction must be expressible in one concrete sentence that names a real-world referent ("a museum exhibition label system for a contemporary art gallery" not "clean and minimal"). If your sentence contains only adjectives, it's not concrete enough.
-5. **While planning each direction, also name its 2–3 parameter knobs** (per the §7 budget table). The same principle as default mode: decide "what's tunable" during planning, not after writing the HTML. A departure-mode hero with 0 parameters is not "bold creative vision," it's a missed opportunity for the user to fine-tune the direction they pick.
-
-#### Phase D: Squint test
-
-**Default mode squint.** Read each variant's identity sentence and compare to the locked identity from Phase A. If any variant has drifted to a different palette, type voice, or visual rhetoric, it has crossed into departure mode by accident; rework. Then check that each variant commits to a different primary axis. Three "tighter density" variants is failure.
-
-**Departure mode squint.** Two passes, family before sentence:
-
-1. **Family pass.** Label each variant with one design-family word of your own choosing (any concrete noun: *exhibition, storefront, cockpit, recipe-card, playbill, field-manual*). If any two variants share a label, or if the label could apply to the other variants equally well, rework. Do not use a fixed vocabulary list for the labels. *This pass is non-negotiable in departure mode and catches the monoculture failure that the sentence pass misses.*
-2. **Sentence pass.** Write three one-sentence descriptions side by side. If two of them rhyme ("both feature big type" / "both are stacks of sections" / "both center the CTA"), rework the offender.
-
-**When the primary axis is color or theme, forbid the trio from sharing theme + dominant hue.** Two dark-plus-one-dark is not distinct. Aim for three color worlds, not three shades of the same.
-
-**For action-specific invocations**, each variant must vary along the dimension the action names:
-
-- `bolder`: amplify a different dimension per variant (scale / saturation / structural change). Not three "slightly bigger" variants.
-- `quieter`: pull back a different dimension (color / ornament / spacing).
-- `distill`: remove a different class of excess (visual noise / redundant content / nested structure).
-- `polish`: target a different refinement axis (rhythm / hierarchy / micro-details like corner radii, focus states, optical kerning).
-- `typeset`: different type pairing AND different scale ratio each. Not three riffs on one pairing.
-- `colorize`: different hue family each (not shades of one hue). Vary chroma and contrast strategy.
-- `layout`: different structural arrangement (stacked / side-by-side / grid / asymmetric). Not spacing tweaks.
-- `adapt`: different target context per variant (mobile-first / tablet / desktop / print or low-data). Don't make three mobile layouts.
-- `animate`: different motion vocabulary (cascade stagger / clip wipe / scale-and-focus / morph / parallax). Not three staggered fades.
-- `delight`: different flavor of personality (unexpected micro-interaction / typographic surprise / illustrated accent / sonic-or-haptic moment / easter-egg interaction).
-- `overdrive`: different convention broken (scale / structure / motion / input model / state transitions). Skip `overdrive.md`'s "propose and ask" step; live mode is non-interactive.
-
-### 5. Apply the freeform prompt (if present)
-
-`event.freeformPrompt` is the user's ceiling on direction (all variants must honor it), but still explore meaningfully different *interpretations*. The interpretations stay within whichever mode you picked in Phase B.
-
-In **default mode**, the prompt narrows the axes you choose, not the identity. *"Make it feel more confident"* → variant 1 amplifies hierarchy (one element commands the eye), variant 2 commits the existing accent color (Committed strategy on the brand's hue), variant 3 tightens density and removes decorative slack. Three different axes, same brand.
-
-In **departure mode**, the prompt narrows the lanes you draw from, not the families. *"Make it feel like a newspaper front page"* would itself be a departure-mode prompt; honor it but pick three meaningfully different newspaper-adjacent lanes (broadsheet vs. tabloid vs. trade journal), and run the family pass to confirm they don't collapse into one.
-
-When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.
-
-### 6. Write all variants in a single edit
-
-Complete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).
-
-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).
-
-Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:
-
-```html
-<!-- Variants: insert below this line -->
-<style data-impeccable-css="SESSION_ID">
- /* rules matching cssAuthoring.rulePattern */
-</style>
-<div data-impeccable-variant="1">
- <!-- variant 1: full element replacement (single top-level element) -->
-</div>
-<div data-impeccable-variant="2" style="display: none">
- <!-- variant 2: full element replacement -->
-</div>
-<div data-impeccable-variant="3" style="display: none">
- <!-- variant 3: full element replacement -->
-</div>
-```
-
-**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.
-
-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.
-
-One edit, all variants; the browser's MutationObserver picks everything up in one pass.
-
-For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.
-
-**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:
-
-```tsx
-<style data-impeccable-css="SESSION_ID">{`
- @scope ([data-impeccable-variant="1"]) { ... }
- @scope ([data-impeccable-variant="2"]) { ... }
-`}</style>
-<div data-impeccable-variant="1">
- {/* variant 1 */}
-</div>
-<div data-impeccable-variant="2" style={{ display: 'none' }}>
- {/* variant 2 */}
-</div>
-```
-
-The wrap script already gives you a single-rooted JSX wrapper: a `<div data-impeccable-variants="…">` outer element with the marker comments tucked inside. Drop the variants block above into the "Variants: insert below this line" comment and the source stays valid TSX.
-
-### 7. Parameters (composition-sized, 0–4 per variant)
-
-Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement. The browser docks a small panel to the right of the outline with one control per parameter. The user drags/clicks and sees instant feedback: there is zero regeneration cost because the knob toggles a CSS variable or data attribute that the variant's scoped CSS is already authored against.
-
-**What “optional” does not mean.** Parameters are not nice-to-have decoration on large work. The word meant “omit controls that are redundant or cosmetic,” not “default to zero because three variants were enough work.”
-
-**When to add.** As soon as the variant’s scoped CSS has a meaningful continuous or stepped axis: density, color amount, type scale, motion intensity, column weight, and so on. If you can imagine the user muttering “a bit tighter” or “a touch more accent” **without** wanting a full regeneration, wire that axis. **Not** micro-margins or one-off nudges; those are not parameters.
-
-**Freeform (`action` is `impeccable`) bias.** You did not load a sub-command reference, so you must **choose** signature axes yourself. Match the budget table: for a hero or large composition, that means **2–3 axes per variant**, not 1. Prefer knobs that sit on the dimensions where your three variants actually differ (if density varies, expose it as a `steps` knob; if color commitment varies, expose it as a `range`). A hero that ships with **0** params is almost always a mistake, not a judgment call. A hero with exactly **1** param is underweight unless the design is genuinely a fixed-point comparison. Start from the budget table, not from zero.
-
-**Budget scales with the element's visual weight, not token budget.** Knobs need real estate to read as tunable; three sliders on a single control are noise.
-
-- **Leaf / tiny**: a single button, icon, input, bare heading, solitary paragraph: **0 params.**
-- **Small composition**: labeled input, simple card, short callout (≤ ~5 visual children): **0–1** params when one dominant axis is obvious; otherwise **0.**
-- **Medium composition**: section component, nav cluster, dense card, short feature block (6–15 visual children): **target 2**; **1** is acceptable if the block is simple; **0** only when variants are truly fixed points.
-- **Large composition**: hero section, full page region, spread layout, strong internal structure (16+ visual children or multiple sub-sections): **target 2–3**; **up to 4** when several independent axes (e.g. structure `steps` + `density` + one accent) are all authored in scoped CSS.
-
-**When in doubt, ask whether a dial exists before defaulting to zero.** The user can always request more variants, but the point of live mode is instant tuning without another Go. Crowding the panel is bad; **under-shipping** knobs on a dense composition is the more common failure for freeform. Count by **visual** children, not DOM depth; a shallow-but-wide hero is still large.
-
-**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.
-
-**How to declare.** Put a JSON manifest on the variant wrapper:
-
-```html
-<div data-impeccable-variant="1" data-impeccable-params='[
- {"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"},
- {"id":"density","kind":"steps","default":"snug","label":"Density","options":[
- {"value":"airy","label":"Airy"},
- {"value":"snug","label":"Snug"},
- {"value":"packed","label":"Packed"}
- ]},
- {"id":"serif","kind":"toggle","default":false,"label":"Serif display"}
-]'>
- ...variant content...
-</div>
-```
-
-**Three kinds:**
-
-- `range`: smooth slider. Drives a CSS custom property `--p-<id>` on the variant wrapper. Author CSS with `var(--p-color-amount, 0.5)`. Fields: `min`, `max`, `step`, `default` (number), `label`.
-- `steps`: segmented radio. Drives a data attribute `data-p-<id>` on the variant wrapper. Author CSS with `:scope[data-p-density="airy"] .grid { ... }`. Fields: `options` (array of `{value, label}`), `default` (string), `label`.
-- `toggle`: on/off switch. Drives BOTH a CSS var (`--p-<id>: 0|1`) and a data attribute (present when on, absent when off). Use whichever is more convenient. Fields: `default` (boolean), `label`.
-
-**Signature params per action.** For named sub-commands, read that action’s `reference/<action>.md` for one or two **MUST** params (e.g. `layout` → `density`). Those are non-negotiable when the design can express them. **Freeform has no file-level MUST**; the **Freeform (`impeccable`) bias** in this section is the stand-in. If the user’s action is both stylized and sub-command (e.g. `colorize`), the sub-command’s MUST list takes precedence for its axes; still respect the **Hard cap** and add no redundant duplicate knobs.
-
-**Reset on variant switch.** User dials density on v1, flips to v2, v2 starts at v2's declared defaults. Known limitation; preservation across variants may land later.
-
-**On accept**, the browser sends the user's current values in the accept event. `live-accept.mjs` writes them as a sibling comment:
-
-```html
-<!-- impeccable-param-values SESSION_ID: {"color-amount":0.7,"density":"packed"} -->
-```
-
-The carbonize cleanup step (see below) reads that comment and bakes the chosen values into the final CSS. For `steps`/`toggle` attribute selectors: keep only the branch matching the chosen value, drop the others, collapse `:scope[data-p-density="packed"] .grid` to a semantic class rule. For `range` vars: either substitute the literal or keep the var with the chosen value as its new default.
-
-### 8. Signal done
-
-```bash
-node .opencode/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
-```
-
-`RELATIVE_PATH` is relative to project root (`public/index.html`, `src/App.tsx`, etc.); the browser fetches source directly if the dev server lacks HMR.
-
-Then run `live-poll.mjs` again immediately.
-
-### Aborting an in-flight session
-
-If wrap or generation fails after the browser has flipped to GENERATING (e.g. wrap landed on the wrong source branch and you've already reverted it, or generation hit an unrecoverable error), tell the **browser** so its bar resets to PICKING:
-
-```bash
-node .opencode/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID error "Short reason"
-```
-
-Don't run `live-accept --discard` for this; that's a pure file mutator, the browser doesn't see it, and the bar gets stuck on the GENERATING dots forever (the user has to refresh). `--discard` is only correct when the **browser** initiated the discard (user clicked ✕ during CYCLING) and the agent is just running source-side cleanup the browser already triggered.
-
-## Handle fallback
-
-When wrap returns `fallback: "agent-driven"`, the deterministic flow doesn't apply. Pick up here.
-
-The goal is the same: give the user three variants to choose from AND persist the accepted one in a place the next build won't wipe. The difference is that you have to pick the right source file yourself.
-
-### Step 1: Identify where the element actually lives
-
-Use the error payload:
-
-- `element_not_in_source` with `generatedMatch: "public/docs/foo.html"`: the served HTML is generated. Find the generator (grep for writers of that path, e.g. `scripts/build-sub-pages.js`, an Astro/Next template) and locate the template or partial that emits this element.
-- `element_not_found`: the element is runtime-injected. Look for the component that renders it (React/Vue/Svelte), the JS that assembles it, or the data source that feeds it.
-- `file_is_generated` with `file: "..."`: user pointed at a generated file explicitly. Same resolution as `element_not_in_source`.
-
-Read the candidate source until you're confident where a change to the element would belong. If the change is purely visual, that source might be a shared stylesheet, not the template.
-
-### Step 2: Show three variants in the DOM for preview
-
-The browser bar is waiting for variants. Even without a wrapper in source, you still need to show something:
-
-1. Manually write the wrapper scaffold into the **served** file (the one the browser actually loaded). Use the same structure `live-wrap.mjs` produces; `<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents">…</div><!-- end -->`.
-2. Insert your three variant divs inside it, same shape as the deterministic path.
-3. Signal done with `--reply EVENT_ID done --file <served file>`. The browser's no-HMR fallback will fetch and inject.
-
-This served-file edit is **temporary**: next regen wipes it, and that's fine. The real work happens on accept.
-
-### Step 3: On accept, write to true source
-
-When the accept event arrives (`_acceptResult.handled` will usually be `false` here because accept also refuses to persist into generated files; see Handle accept for the carbonize branch), extract the accepted variant's content and write it into the source you identified in Step 1:
-
-- Structural change → edit the template / component source.
-- Visual-only change → add or update rules in the appropriate stylesheet; remove the inline `<style>` scope.
-- Dynamic from data → update the data source or the render logic.
-
-Then remove the temporary wrapper from the served file if it's still there.
-
-### Step 4: On discard, clean up the served file
-
-Remove the wrapper you inserted in Step 2. Nothing else to do.
-
-## Handle `accept`
-
-Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.
-
-- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.
-- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.
-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.
-- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.
-- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.
-
-### Required after accept (carbonize)
-
-When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.
-
-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.
-
-1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.
-2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).
-3. **Bake in parameter values while rewriting selectors.** For `@scope ([data-impeccable-variant="N"])` wrappers: retarget to real, semantic classes on the accepted HTML (`.why-visual--v2 .v2-label { … }`). For `:scope[data-p-<id>="VALUE"]` selectors: keep only the branch matching the chosen value from the param-values comment; drop the others (they're dead after accept). For `var(--p-<id>, DEFAULT)` in the CSS: either substitute the literal value, or if the param is still useful as a knob going forward, leave the var and update its initial declaration to the chosen value.
-4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; those are live-mode plumbing, not source.
-5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.
-
-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.
-
-A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.
-
-## Handle `discard`
-
-Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.
-
-## Handle `prefetch`
-
-Event: `{pageUrl}`. The browser fires this the first time the user selects an element on a given route, as a latency shortcut; it signals the user is likely about to Go on a page you haven't read yet.
-
-Resolve `pageUrl` to the underlying file:
-
-- Root `/` → the `pageFile` returned by `live.mjs` (usually `public/index.html` or equivalent).
-- Sub-routes (e.g. `/docs`, `/docs/live`) → the generated or source file for that route. Use your knowledge of the project layout (multi-page static sites often resolve `/foo` → `public/foo/index.html`; SPAs may map all routes to a single entry).
-
-Read the file into context, then poll again. No `--reply`: this is speculative pre-work; Go will come later. If you can't confidently resolve the route to a file, skip and poll again.
-
-Dedupe is the browser's job (one prefetch per unique pathname per session); trust it. If the same file shows up twice from different routes mapping to the same file, the second Read is cached anyway.
-
-## Exit
-
-The user can stop live mode by:
-- Saying "stop live mode" / "exit live" in chat
-- Closing the browser tab (SSE drops, poll returns `exit` after 8s)
-- The browser's exit button
-
-When the poll returns `exit`, proceed to cleanup. If the poll is still running as a background task, kill it first.
-
-## Cleanup
-
-```bash
-node .opencode/skills/impeccable/scripts/live-server.mjs stop
-```
-
-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.
-
-Then:
-- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).
-- Remove any leftover carbonize blocks (search for `impeccable-carbonize-start` markers).
-
-## First-time setup (config missing or invalid)
-
-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.
-
-Schema:
-
-```json
-{
- "files": ["<path-or-glob>", "<path-or-glob>", ...],
- "exclude": ["<optional-glob>", ...],
- "insertBefore": "</body>",
- "commentSyntax": "html",
- "cspChecked": true
-}
-```
-
-`files` is the inject target; **the HTML files the browser actually loads**, not necessarily source. Each entry is either a literal path (`"public/index.html"`) or a glob pattern (`"public/**/*.html"`). Tracked or generated doesn't matter here; wrap has its own generated-file guard and routes accepts through the fallback flow.
-
-`exclude` (optional) is a list of glob patterns matching files to skip, even if a `files` glob would have included them. Use for email templates, demo fixtures, or any HTML that isn't a live page.
-
-`cspChecked` tracks whether the CSP detection step below has already run. Absent on first setup; set to `true` after CSP is checked (whether patched, declined, or not needed).
-
-**Hard-excluded paths (cannot be overridden).** `**/node_modules/**` and `**/.git/**` are never matched regardless of what the user writes. These are vendor/metadata directories and injecting into them would silently instrument third-party code.
-
-**Glob syntax.** `**` matches any number of path segments (including zero), `*` matches any characters except `/`, `?` matches a single character except `/`. Paths are always relative to the project root with forward slashes.
-
-| Framework | `files` | `insertBefore` | `commentSyntax` |
-|-----------|---------|----------------|-----------------|
-| SPA with single shell (Vite / React / Plain HTML) | `["index.html"]` | `</body>` | `html` |
-| Next.js (App Router) | `["app/layout.tsx"]` | `</body>` | `jsx` |
-| Next.js (Pages) | `["pages/_document.tsx"]` | `</body>` | `jsx` |
-| Nuxt | `["app.vue"]` | `</body>` | `html` |
-| Svelte / SvelteKit | `["src/app.html"]` | `</body>` | `html` |
-| Astro | `[" <root layout .astro>"]` | `</body>` | `html` |
-| Multi-page (separate HTML per route) | `["public/**/*.html"]`: a glob covering the served directory | `</body>` | `html` |
-
-Pick an anchor that exists in every file (`</body>` almost always works). Use `insertAfter` if the anchor should match **after** a specific line.
-
-For multi-page sites, **prefer a glob over a literal file list**. New pages added later are picked up automatically on the next `live-inject.mjs` run; no config maintenance needed.
-
-For multi-page sites whose pages are *rebuilt* by a generator (Astro, static-site generators, custom scripts like `build-sub-pages.js`), the inject survives only until the next regeneration. Re-run `live.mjs` after each build. Accept is unaffected; it writes to true source via the fallback flow.
-
-### Drift-heal warning
-
-On every `live.mjs` boot, after inject, the project is scanned for HTML files under common page-source roots (`public/`, `src/`, `app/`, `pages/`). If any exist that aren't covered by the resolved `files` list, the output includes a `configDrift` field:
-
-```json
-{
- "ok": true,
- "serverPort": 8400,
- "pageFiles": [ "..." ],
- "configDrift": {
- "orphans": ["public/new-section/index.html", "public/docs/new-command.html"],
- "orphanCount": 2,
- "hint": "2 HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like \"public/**/*.html\"."
- }
-}
-```
-
-When `configDrift` is present, surface it to the user once per session before entering the poll loop:
-
-> Noticed N HTML file(s) in the project that aren't in `config.files`:
->
-> - `public/new-section/index.html`
-> - `public/docs/new-command.html`
->
-> Add them, or switch `files` to a glob like `["public/**/*.html"]` and let it track new pages automatically?
-
-Don't auto-update the config; let the user decide. `configDrift` is `null` when there's no drift.
-
-### CSP detection (first-time only)
-
-If `config.cspChecked === true`, skip this entire section. You already asked this user once; the answer sticks.
-
-Otherwise, run the detection helper:
-
-```bash
-node .opencode/skills/impeccable/scripts/detect-csp.mjs
-```
-
-Output: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.
-
-- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.
-- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:
- - Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)
- - SvelteKit `kit.csp.directives`
- - Nuxt `nuxt-security` module's `contentSecurityPolicy`
-- **`append-string`**: CSP written as a literal value string. Auto-patchable. See *append-string* below. Covers:
- - Inline `next.config.*` `headers()` with a CSP literal
- - Nuxt `routeRules` / `nitro.routeRules` headers
-- **`middleware`** or **`meta-tag`**: rarer. Detected but not auto-patched in v1. Show the user the detected files and ask them to add `http://localhost:8400` to `script-src` and `connect-src` manually, then mark `cspChecked: true` and proceed.
-
-#### Consent prompt template
-
-Use this phrasing so the experience is consistent across agents:
-
-> **CSP patch needed.** I detected a Content Security Policy in your project that blocks `http://localhost:8400`: the live picker won't load without an allowance. Here's the change I'd make:
->
-> ```diff
-> [file: <patchTarget>]
-> [exact diff, 2–5 lines]
-> ```
->
-> It's guarded by `NODE_ENV === "development"` so the extra entry only appears in dev and never reaches production. You can remove it any time by reverting this file. Apply? [y/n]
-
-On "no": skip the patch, mention live won't work until the user adds the allowance manually, still write `cspChecked: true` (the question's been asked).
-
-On "yes": apply the Shape-specific patch below, then write `cspChecked: true`.
-
-#### append-arrays
-
-CSP expressed as structured directive arrays. Patch mechanism: declare a dev-only array, spread it into the script-src and connect-src arrays.
-
-**Declare near the top of the file that holds the CSP arrays:**
-
-```ts
-// Dev-only allowance so impeccable live mode can load. Guarded by NODE_ENV.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? ["http://localhost:8400"] : [];
-```
-
-**Append `...__impeccableLiveDev` to the script-src and connect-src directive arrays.** Per-framework specifics:
-
-- **Next.js + monorepo helper**: edit the *app's* `next.config.*` (not the shared helper), appending to `additionalScriptSrc` and `additionalConnectSrc` passed into `createBaseNextConfig` (or equivalent). Keeps the shared package clean.
-- **SvelteKit**: edit `svelte.config.js`, appending to `kit.csp.directives['script-src']` and `kit.csp.directives['connect-src']`.
-- **Nuxt + nuxt-security**: edit `nuxt.config.*`, appending to `security.headers.contentSecurityPolicy['script-src']` and `['connect-src']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-turborepo/expected-after-patch.ts` (Next.js)
-- `tests/framework-fixtures/sveltekit-csp/expected-after-patch.js` (SvelteKit)
-
-Idempotency: if `__impeccableLiveDev` already exists in the file, the patch is already applied; skip asking and just mark `cspChecked: true`.
-
-#### append-string
-
-CSP built as a literal value string. Two-point patch: declare a dev-only string near the top, interpolate it into the CSP at the `script-src` and `connect-src` directives.
-
-```ts
-// Dev-only allowance so impeccable live mode can load.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? " http://localhost:8400" : "";
-```
-
-Then in the CSP value string:
-- `script-src 'self' 'unsafe-inline'` → `` `script-src 'self' 'unsafe-inline'${__impeccableLiveDev}` ``
-- `connect-src 'self'` → `` `connect-src 'self'${__impeccableLiveDev}` ``
-
-(Leading space on the dev string so it concatenates cleanly into the existing value. Convert the literal CSP directives into template strings as part of the edit if they aren't already.)
-
-Per-framework specifics:
-- **Next.js inline `headers()`**: edit `next.config.*`, splicing the variable into the CSP value.
-- **Nuxt `routeRules`**: edit `nuxt.config.*`, splicing into the CSP in `routeRules['/**'].headers['Content-Security-Policy']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-inline-csp/expected-after-patch.js` (Next.js)
-- `tests/framework-fixtures/nuxt-csp/expected-after-patch.ts` (Nuxt)
-
-### Troubleshooting
-
-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.
-
-Then re-run `live.mjs`.
@@ -1,109 +0,0 @@
-# Motion Design
-
-## Duration: The 100/300/500 Rule
-
-Timing matters more than easing. These durations feel right for most UI:
-
-| Duration | Use Case | Examples |
-|----------|----------|----------|
-| **100-150ms** | Instant feedback | Button press, toggle, color change |
-| **200-300ms** | State changes | Menu open, tooltip, hover states |
-| **300-500ms** | Layout changes | Accordion, modal, drawer |
-| **500-800ms** | Entrance animations | Page load, hero reveals |
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-## Easing: Pick the Right Curve
-
-**Don't use `ease`.** It's a compromise that's rarely optimal. Instead:
-
-| Curve | Use For | CSS |
-|-------|---------|-----|
-| **ease-out** | Elements entering | `cubic-bezier(0.16, 1, 0.3, 1)` |
-| **ease-in** | Elements leaving | `cubic-bezier(0.7, 0, 0.84, 0)` |
-| **ease-in-out** | State toggles (there → back) | `cubic-bezier(0.65, 0, 0.35, 1)` |
-
-**For micro-interactions, use exponential curves.** They feel natural because they mimic real physics (friction, deceleration):
-
-```css
-/* Quart out - smooth, refined (recommended default) */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1);
-
-/* Quint out - slightly more dramatic */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1);
-
-/* Expo out - snappy, confident */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1);
-```
-
-**Avoid bounce and elastic curves.** They were trendy in 2015 but now feel tacky and amateurish. Real objects don't bounce when they stop; they decelerate smoothly. Overshoot effects draw attention to the animation itself rather than the content.
-
-## Premium Motion Materials
-
-Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties: blur reveals, backdrop-filter panels, saturation or brightness shifts, shadow bloom, SVG filters, masks, clip paths, gradient-position movement, and variable font or shader-driven effects.
-
-Use the right material for the effect:
-
-- **Transform / opacity**: movement, press feedback, simple reveals, list choreography.
-- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances, atmospheric transitions.
-- **Clip path / masks**: wipes, reveals, editorial cropping, product-like transitions.
-- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state.
-- **Grid-template rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly.
-
-The hard rule is not "transform and opacity only." The hard rule is: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify in-browser that the result is smooth on the target viewports. If blur/filter makes the interaction feel significantly more premium and remains smooth, use it.
-
-## Staggered Animations
-
-Use CSS custom properties for cleaner stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"` on each item. **Cap total stagger time**: 10 items at 50ms = 500ms total. For many items, reduce per-item delay or cap staggered count.
-
-## Reduced Motion
-
-This is not optional. Vestibular disorders affect ~35% of adults over 40.
-
-```css
-/* Define animations normally */
-.card {
- animation: slide-up 500ms ease-out;
-}
-
-/* Provide alternative for reduced motion */
-@media (prefers-reduced-motion: reduce) {
- .card {
- animation: fade-in 200ms ease-out; /* Crossfade instead of motion */
- }
-}
-
-/* Or disable entirely */
-@media (prefers-reduced-motion: reduce) {
- *, *::before, *::after {
- animation-duration: 0.01ms !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**What to preserve**: Functional animations like progress bars, loading spinners (slowed down), and focus indicators should still work, just without spatial movement.
-
-## Perceived Performance
-
-**Nobody cares how fast your site is, just how fast it feels.** Perception can be as effective as actual performance.
-
-**The 80ms threshold**: Our brains buffer sensory input for ~80ms to synchronize perception. Anything under 80ms feels instant and simultaneous. This is your target for micro-interactions.
-
-**Active vs passive time**: Passive waiting (staring at a spinner) feels longer than active engagement. Strategies to shift the balance:
-
-- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening.
-- **Early completion**: Show content progressively, don't wait for everything. Video buffering, progressive images, streaming HTML.
-- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Instagram likes work offline; the UI updates instantly, syncs later. Use for low-stakes actions; avoid for payments or destructive operations.
-
-**Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances, but ease-in toward a task's end compresses perceived time.
-
-**Caution**: Too-fast responses can decrease perceived value. Users may distrust instant results for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
-
-## Performance
-
-Don't use `will-change` preemptively, only when animation is imminent (`:hover`, `.animating`). For scroll-triggered animations, use Intersection Observer instead of scroll events; unobserve after animating once. Create motion tokens for consistency (durations, easings, common transitions).
-
----
-
-**Avoid**: Animating everything (animation fatigue is real). Using >500ms for UI feedback. Ignoring `prefers-reduced-motion`. Using animation to hide slow loading.
@@ -1,234 +0,0 @@
-> **Additional context needed**: the "aha moment" you want users to reach, and users' experience level.
-
-Get users to first value as fast as possible. Onboarding's job is not to teach the product. Its job is to get people to the moment that proves the product is worth their time.
-
-## Assess Onboarding Needs
-
-Understand what users need to learn and why:
-
-1. **Identify the challenge**:
- - What are users trying to accomplish?
- - What's confusing or unclear about current experience?
- - Where do users get stuck or drop off?
- - What's the "aha moment" we want users to reach?
-
-2. **Understand the users**:
- - What's their experience level? (Beginners, power users, mixed?)
- - What's their motivation? (Excited and exploring? Required by work?)
- - What's their time commitment? (5 minutes? 30 minutes?)
- - What alternatives do they know? (Coming from competitor? New to category?)
-
-3. **Define success**:
- - What's the minimum users need to learn to be successful?
- - What's the key action we want them to take? (First project? First invite?)
- - How do we know onboarding worked? (Completion rate? Time to value?)
-
-**CRITICAL**: Onboarding should get users to value as quickly as possible, not teach everything possible.
-
-## Onboarding Principles
-
-Follow these core principles:
-
-### Show, Don't Tell
-- Demonstrate with working examples, not just descriptions
-- Provide real functionality in onboarding, not separate tutorial mode
-- Use progressive disclosure, teach one thing at a time
-
-### Make It Optional (When Possible)
-- Let experienced users skip onboarding
-- Don't block access to product
-- Provide "Skip" or "I'll explore on my own" options
-
-### Time to Value
-- Get users to their "aha moment" ASAP
-- Front-load most important concepts
-- Teach 20% that delivers 80% of value
-- Save advanced features for contextual discovery
-
-### Context Over Ceremony
-- Teach features when users need them, not upfront
-- Empty states are onboarding opportunities
-- Tooltips and hints at point of use
-
-### Respect User Intelligence
-- Don't patronize or over-explain
-- Be concise and clear
-- Assume users can figure out standard patterns
-
-## Design Onboarding Experiences
-
-Create appropriate onboarding for the context:
-
-### Initial Product Onboarding
-
-**Welcome Screen**:
-- Clear value proposition (what is this product?)
-- What users will learn/accomplish
-- Time estimate (honest about commitment)
-- Option to skip (for experienced users)
-
-**Account Setup**:
-- Minimal required information (collect more later)
-- Explain why you're asking for each piece of information
-- Smart defaults where possible
-- Social login when appropriate
-
-**Core Concept Introduction**:
-- Introduce 1-3 core concepts (not everything)
-- Use simple language and examples
-- Interactive when possible (do, don't just read)
-- Progress indication (step 1 of 3)
-
-**First Success**:
-- Guide users to accomplish something real
-- Pre-populated examples or templates
-- Celebrate completion (but don't overdo it)
-- Clear next steps
-
-### Feature Discovery & Adoption
-
-**Empty States**:
-Instead of blank space, show:
-- What will appear here (description + screenshot/illustration)
-- Why it's valuable
-- Clear CTA to create first item
-- Example or template option
-
-Example:
-```
-No projects yet
-Projects help you organize your work and collaborate with your team.
-[Create your first project] or [Start from template]
-```
-
-**Contextual Tooltips**:
-- Appear at relevant moment (first time user sees feature)
-- Point directly at relevant UI element
-- Brief explanation + benefit
-- Dismissable (with "Don't show again" option)
-- Optional "Learn more" link
-
-**Feature Announcements**:
-- Highlight new features when they're released
-- Show what's new and why it matters
-- Let users try immediately
-- Dismissable
-
-**Progressive Onboarding**:
-- Teach features when users encounter them
-- Badges or indicators on new/unused features
-- Unlock complexity gradually (don't show all options immediately)
-
-### Guided Tours & Walkthroughs
-
-**When to use**:
-- Complex interfaces with many features
-- Significant changes to existing product
-- Industry-specific tools needing domain knowledge
-
-**How to design**:
-- Spotlight specific UI elements (dim rest of page)
-- Keep steps short (3-7 steps max per tour)
-- Allow users to click through tour freely
-- Include "Skip tour" option
-- Make replayable (help menu)
-
-**Best practices**:
-- Interactive over passive (let users click real buttons)
-- Focus on workflow, not features ("Create a project" not "This is the project button")
-- Provide sample data so actions work
-
-### Interactive Tutorials
-
-**When to use**:
-- Users need hands-on practice
-- Concepts are complex or unfamiliar
-- High stakes (better to practice in safe environment)
-
-**How to design**:
-- Sandbox environment with sample data
-- Clear objectives ("Create a chart showing sales by region")
-- Step-by-step guidance
-- Validation (confirm they did it right)
-- Graduation moment (you're ready!)
-
-### Documentation & Help
-
-**In-product help**:
-- Contextual help links throughout interface
-- Keyboard shortcut reference
-- Search-able help center
-- Video tutorials for complex workflows
-
-**Help patterns**:
-- `?` icon near complex features
-- "Learn more" links in tooltips
-- Keyboard shortcut hints (`⌘K` shown on search box)
-
-## Empty State Design
-
-Every empty state needs:
-
-### What Will Be Here
-"Your recent projects will appear here"
-
-### Why It Matters
-"Projects help you organize your work and collaborate with your team"
-
-### How to Get Started
-[Create project] or [Import from template]
-
-### Visual Interest
-Illustration or icon (not just text on blank page)
-
-### Contextual Help
-"Need help getting started? [Watch 2-min tutorial]"
-
-**Empty state types**:
-- **First use**: Never used this feature (emphasize value, provide template)
-- **User cleared**: Intentionally deleted everything (light touch, easy to recreate)
-- **No results**: Search or filter returned nothing (suggest different query, clear filters)
-- **No permissions**: Can't access (explain why, how to get access)
-- **Error state**: Failed to load (explain what happened, retry option)
-
-## Implementation Patterns
-
-### Technical approaches:
-
-**Tooltip libraries**: Tippy.js, Popper.js
-**Tour libraries**: Intro.js, Shepherd.js, React Joyride
-**Modal patterns**: Focus trap, backdrop, ESC to close
-**Progress tracking**: LocalStorage for "seen" states
-**Analytics**: Track completion, drop-off points
-
-**Storage patterns**:
-```javascript
-// Track which onboarding steps user has seen
-localStorage.setItem('onboarding-completed', 'true');
-localStorage.setItem('feature-tooltip-seen-reports', 'true');
-```
-
-**IMPORTANT**: Don't show same onboarding twice (annoying). Track completion and respect dismissals.
-
-**NEVER**:
-- Force users through long onboarding before they can use product
-- Patronize users with obvious explanations
-- Show same tooltip repeatedly (respect dismissals)
-- Block all UI during tour (let users explore)
-- Create separate tutorial mode disconnected from real product
-- Overwhelm with information upfront (progressive disclosure!)
-- Hide "Skip" or make it hard to find
-- Forget about returning users (don't show initial onboarding again)
-
-## Verify Onboarding Quality
-
-Test with real users:
-
-- **Time to completion**: Can users complete onboarding quickly?
-- **Comprehension**: Do users understand after completing?
-- **Action**: Do users take desired next step?
-- **Skip rate**: Are too many users skipping? (Maybe it's too long or not valuable)
-- **Completion rate**: Are users completing? (If low, simplify)
-- **Time to value**: How long until users get first value?
-
-When users hit the aha moment fast and don't drop off, hand off to `/impeccable polish` for the final pass.
@@ -1,258 +0,0 @@
-Performance is a feature. Identify the actual bottleneck for THIS interface, fix it, then measure. Don't optimize what isn't slow.
-
-## Assess Performance Issues
-
-Understand current performance and identify problems:
-
-1. **Measure current state**:
- - **Core Web Vitals**: LCP, FID/INP, CLS scores
- - **Load time**: Time to interactive, first contentful paint
- - **Bundle size**: JavaScript, CSS, image sizes
- - **Runtime performance**: Frame rate, memory usage, CPU usage
- - **Network**: Request count, payload sizes, waterfall
-
-2. **Identify bottlenecks**:
- - What's slow? (Initial load? Interactions? Animations?)
- - What's causing it? (Large images? Expensive JavaScript? Layout thrashing?)
- - How bad is it? (Perceivable? Annoying? Blocking?)
- - Who's affected? (All users? Mobile only? Slow connections?)
-
-**CRITICAL**: Measure before and after. Premature optimization wastes time. Optimize what actually matters.
-
-## Optimization Strategy
-
-Create systematic improvement plan:
-
-### Loading Performance
-
-**Optimize Images**:
-- Use modern formats (WebP, AVIF)
-- Proper sizing (don't load 3000px image for 300px display)
-- Lazy loading for below-fold images
-- Responsive images (`srcset`, `picture` element)
-- Compress images (80-85% quality is usually imperceptible)
-- Use CDN for faster delivery
-
-```html
-<img
- src="hero.webp"
- srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
- sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
- loading="lazy"
- alt="Hero image"
-/>
-```
-
-**Reduce JavaScript Bundle**:
-- Code splitting (route-based, component-based)
-- Tree shaking (remove unused code)
-- Remove unused dependencies
-- Lazy load non-critical code
-- Use dynamic imports for large components
-
-```javascript
-// Lazy load heavy component
-const HeavyChart = lazy(() => import('./HeavyChart'));
-```
-
-**Optimize CSS**:
-- Remove unused CSS
-- Critical CSS inline, rest async
-- Minimize CSS files
-- Use CSS containment for independent regions
-
-**Optimize Fonts**:
-- Use `font-display: swap` or `optional`
-- Subset fonts (only characters you need)
-- Preload critical fonts
-- Use system fonts when appropriate
-- Limit font weights loaded
-
-```css
-@font-face {
- font-family: 'CustomFont';
- src: url('/fonts/custom.woff2') format('woff2');
- font-display: swap; /* Show fallback immediately */
- unicode-range: U+0020-007F; /* Basic Latin only */
-}
-```
-
-**Optimize Loading Strategy**:
-- Critical resources first (async/defer non-critical)
-- Preload critical assets
-- Prefetch likely next pages
-- Service worker for offline/caching
-- HTTP/2 or HTTP/3 for multiplexing
-
-### Rendering Performance
-
-**Avoid Layout Thrashing**:
-```javascript
-// ❌ Bad: Alternating reads and writes (causes reflows)
-elements.forEach(el => {
- const height = el.offsetHeight; // Read (forces layout)
- el.style.height = height * 2; // Write
-});
-
-// ✅ Good: Batch reads, then batch writes
-const heights = elements.map(el => el.offsetHeight); // All reads
-elements.forEach((el, i) => {
- el.style.height = heights[i] * 2; // All writes
-});
-```
-
-**Optimize Rendering**:
-- Use CSS `contain` property for independent regions
-- Minimize DOM depth (flatter is faster)
-- Reduce DOM size (fewer elements)
-- Use `content-visibility: auto` for long lists
-- Virtual scrolling for very long lists (react-window, react-virtualized)
-
-**Reduce Paint & Composite**:
-- Use `transform` and `opacity` for reliable movement, but allow blur, filters, masks, clip paths, shadows, and color shifts when they create meaningful polish
-- Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- Use `will-change` sparingly for known expensive operations
-- Bound expensive paint areas for blur/filter/shadow effects (smaller and isolated is faster)
-
-### Animation Performance
-
-**GPU Acceleration**:
-```css
-/* ✅ GPU-accelerated (fast) */
-.animated {
- transform: translateX(100px);
- opacity: 0.5;
-}
-
-/* ❌ CPU-bound (slow) */
-.animated {
- left: 100px;
- width: 300px;
-}
-```
-
-**Smooth 60fps**:
-- Target 16ms per frame (60fps)
-- Use `requestAnimationFrame` for JS animations
-- Debounce/throttle scroll handlers
-- Use CSS animations when possible
-- Avoid long-running JavaScript during animations
-
-**Intersection Observer**:
-```javascript
-// Efficiently detect when elements enter viewport
-const observer = new IntersectionObserver((entries) => {
- entries.forEach(entry => {
- if (entry.isIntersecting) {
- // Element is visible, lazy load or animate
- }
- });
-});
-```
-
-### React/Framework Optimization
-
-**React-specific**:
-- Use `memo()` for expensive components
-- `useMemo()` and `useCallback()` for expensive computations
-- Virtualize long lists
-- Code split routes
-- Avoid inline function creation in render
-- Use React DevTools Profiler
-
-**Framework-agnostic**:
-- Minimize re-renders
-- Debounce expensive operations
-- Memoize computed values
-- Lazy load routes and components
-
-### Network Optimization
-
-**Reduce Requests**:
-- Combine small files
-- Use SVG sprites for icons
-- Inline small critical assets
-- Remove unused third-party scripts
-
-**Optimize APIs**:
-- Use pagination (don't load everything)
-- GraphQL to request only needed fields
-- Response compression (gzip, brotli)
-- HTTP caching headers
-- CDN for static assets
-
-**Optimize for Slow Connections**:
-- Adaptive loading based on connection (navigator.connection)
-- Optimistic UI updates
-- Request prioritization
-- Progressive enhancement
-
-## Core Web Vitals Optimization
-
-### Largest Contentful Paint (LCP < 2.5s)
-- Optimize hero images
-- Inline critical CSS
-- Preload key resources
-- Use CDN
-- Server-side rendering
-
-### First Input Delay (FID < 100ms) / INP (< 200ms)
-- Break up long tasks
-- Defer non-critical JavaScript
-- Use web workers for heavy computation
-- Reduce JavaScript execution time
-
-### Cumulative Layout Shift (CLS < 0.1)
-- Set dimensions on images and videos
-- Don't inject content above existing content
-- Use `aspect-ratio` CSS property
-- Reserve space for ads/embeds
-- Avoid animations that cause layout shifts
-
-```css
-/* Reserve space for image */
-.image-container {
- aspect-ratio: 16 / 9;
-}
-```
-
-## Performance Monitoring
-
-**Tools to use**:
-- Chrome DevTools (Lighthouse, Performance panel)
-- WebPageTest
-- Core Web Vitals (Chrome UX Report)
-- Bundle analyzers (webpack-bundle-analyzer)
-- Performance monitoring (Sentry, DataDog, New Relic)
-
-**Key metrics**:
-- LCP, FID/INP, CLS (Core Web Vitals)
-- Time to Interactive (TTI)
-- First Contentful Paint (FCP)
-- Total Blocking Time (TBT)
-- Bundle size
-- Request count
-
-**IMPORTANT**: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.
-
-**NEVER**:
-- Optimize without measuring (premature optimization)
-- Sacrifice accessibility for performance
-- Break functionality while optimizing
-- Use `will-change` everywhere (creates new layers, uses memory)
-- Lazy load above-fold content
-- Optimize micro-optimizations while ignoring major issues (optimize the biggest bottleneck first)
-- Forget about mobile performance (often slower devices, slower connections)
-
-## Verify Improvements
-
-Test that optimizations worked:
-
-- **Before/after metrics**: Compare Lighthouse scores
-- **Real user monitoring**: Track improvements for real users
-- **Different devices**: Test on low-end Android, not just flagship iPhone
-- **Slow connections**: Throttle to 3G, test experience
-- **No regressions**: Ensure functionality still works
-- **User perception**: Does it *feel* faster?
-
-When the user-facing numbers move, hand off to `/impeccable polish` for the final pass.
@@ -1,130 +0,0 @@
-Start your response with:
-
-```
-──────────── ⚡ OVERDRIVE ─────────────
-》》》 Entering overdrive mode...
-```
-
-Push an interface past conventional limits. This isn't just about visual effects. It's about using the full power of the browser to make any part of an interface feel extraordinary: a table that handles a million rows, a dialog that morphs from its trigger, a form that validates in real-time with streaming feedback, a page transition that feels cinematic.
-
-**EXTRA IMPORTANT FOR THIS COMMAND**: Context determines what "extraordinary" means. A particle system on a creative portfolio is impressive. The same particle system on a settings page is embarrassing. But a settings page with instant optimistic saves and animated state transitions? That's extraordinary too. Understand the project's personality and goals before deciding what's appropriate.
-
-### Propose Before Building
-
-This command has the highest potential to misfire. Do NOT jump straight into implementation. You MUST:
-
-1. **Think through 2-3 different directions**: consider different techniques, levels of ambition, and aesthetic approaches. For each direction, briefly describe what the result would look and feel like.
-2. **STOP and call the `question` tool to clarify.** to present these directions and get the user's pick before writing any code. Explain trade-offs (browser support, performance cost, complexity).
-3. Only proceed with the direction the user confirms.
-
-Skipping this step risks building something embarrassing that needs to be thrown away.
-
-### Iterate with Browser Automation
-
-Technically ambitious effects almost never work on the first try. You MUST actively use browser automation tools to preview your work, visually verify the result, and iterate. Do not assume the effect looks right, check it. Expect multiple rounds of refinement. The gap between "technically works" and "looks extraordinary" is closed through visual iteration, not code alone.
-
----
-
-## Assess What "Extraordinary" Means Here
-
-The right kind of technical ambition depends entirely on what you're working with. Before choosing a technique, ask: **what would make a user of THIS specific interface say "wow, that's nice"?**
-
-### For visual/marketing surfaces
-Pages, hero sections, landing pages, portfolios: the "wow" is often sensory: a scroll-driven reveal, a shader background, a cinematic page transition, generative art that responds to the cursor.
-
-### For functional UI
-Tables, forms, dialogs, navigation: the "wow" is in how it FEELS: a dialog that morphs from the button that triggered it via View Transitions, a data table that renders 100k rows at 60fps via virtual scrolling, a form with streaming validation that feels instant, drag-and-drop with spring physics.
-
-### For performance-critical UI
-The "wow" is invisible but felt: a search that filters 50k items without a flicker, a complex form that never blocks the main thread, an image editor that processes in near-real-time. The interface just never hesitates.
-
-### For data-heavy interfaces
-Charts and dashboards: the "wow" is in fluidity: GPU-accelerated rendering via Canvas/WebGL for massive datasets, animated transitions between data states, force-directed graph layouts that settle naturally.
-
-**The common thread**: something about the implementation goes beyond what users expect from a web interface. The technique serves the experience, not the other way around.
-
-## The Toolkit
-
-Organized by what you're trying to achieve, not by technology name.
-
-### Make transitions feel cinematic
-- **View Transitions API** (same-document: all browsers; cross-document: no Firefox): shared element morphing between states. A list item expanding into a detail page. A button morphing into a dialog. This is the closest thing to native FLIP animations.
-- **`@starting-style`** (all browsers): animate elements from `display: none` to visible with CSS only, including entry keyframes
-- **Spring physics**: natural motion with mass, tension, and damping instead of cubic-bezier. Libraries: motion (formerly Framer Motion), GSAP, or roll your own spring solver.
-
-### Tie animation to scroll position
-- **Scroll-driven animations** (`animation-timeline: scroll()`): CSS-only, no JS. Parallax, progress bars, reveal sequences all driven by scroll position. (Chrome/Edge/Safari; Firefox: flag only; always provide a static fallback)
-
-### Render beyond CSS
-- **WebGL** (all browsers): shader effects, post-processing, particle systems. Libraries: Three.js, OGL (lightweight), regl. Use for effects CSS can't express.
-- **WebGPU** (Chrome/Edge; Safari partial; Firefox: flag only): next-gen GPU compute. More powerful than WebGL but limited browser support. Always fall back to WebGL2.
-- **Canvas 2D / OffscreenCanvas**: custom rendering, pixel manipulation, or moving heavy rendering off the main thread entirely via Web Workers + OffscreenCanvas.
-- **SVG filter chains**: displacement maps, turbulence, morphology for organic distortion effects. CSS-animatable.
-
-### Make data feel alive
-- **Virtual scrolling**: render only visible rows for tables/lists with tens of thousands of items. No library required for simple cases; TanStack Virtual for complex ones.
-- **GPU-accelerated charts**: Canvas or WebGL-rendered data visualization for datasets too large for SVG/DOM. Libraries: deck.gl, regl-based custom renderers.
-- **Animated data transitions**: morph between chart states rather than replacing. D3's `transition()` or View Transitions for DOM-based charts.
-
-### Animate complex properties
-- **`@property`** (all browsers): register custom CSS properties with types, enabling animation of gradients, colors, and complex values that CSS can't normally interpolate.
-- **Web Animations API** (all browsers): JavaScript-driven animations with the performance of CSS. Composable, cancellable, reversible. The foundation for complex choreography.
-
-### Push performance boundaries
-- **Web Workers**: move computation off the main thread. Heavy data processing, image manipulation, search indexing: anything that would cause jank.
-- **OffscreenCanvas**: render in a Worker thread. The main thread stays free while complex visuals render in the background.
-- **WASM**: near-native performance for computation-heavy features. Image processing, physics simulations, codecs.
-
-### Interact with the device
-- **Web Audio API**: spatial audio, audio-reactive visualizations, sonic feedback. Requires user gesture to start.
-- **Device APIs**: orientation, ambient light, geolocation. Use sparingly and always with user permission.
-
-**NOTE**: This command is about enhancing how an interface FEELS, not changing what a product DOES. Adding real-time collaboration, offline support, or new backend capabilities are product decisions, not UI enhancements. Focus on making existing features feel extraordinary.
-
-## Implement with Discipline
-
-### Progressive enhancement is non-negotiable
-
-Every technique must degrade gracefully. The experience without the enhancement must still be good.
-
-```css
-@supports (animation-timeline: scroll()) {
- .hero { animation-timeline: scroll(); }
-}
-```
-
-```javascript
-if ('gpu' in navigator) { /* WebGPU */ }
-else if (canvas.getContext('webgl2')) { /* WebGL2 fallback */ }
-/* CSS-only fallback must still look good */
-```
-
-### Performance rules
-
-- Target 60fps. If dropping below 50, simplify.
-- Respect `prefers-reduced-motion`, always. Provide a beautiful static alternative.
-- Lazy-initialize heavy resources (WebGL contexts, WASM modules) only when near viewport.
-- Pause off-screen rendering. Kill what you can't see.
-- Test on real mid-range devices, not just your development machine.
-
-### Polish is the difference
-
-The gap between "cool" and "extraordinary" is in the last 20% of refinement: the easing curve on a spring animation, the timing offset in a staggered reveal, the subtle secondary motion that makes a transition feel physical. Don't ship the first version that works; ship the version that feels inevitable.
-
-**NEVER**:
-- Ignore `prefers-reduced-motion`. This is an accessibility requirement, not a suggestion
-- Ship effects that cause jank on mid-range devices
-- Use bleeding-edge APIs without a functional fallback
-- Add sound without explicit user opt-in
-- Use technical ambition to mask weak design fundamentals; fix those first with other commands
-- Layer multiple competing extraordinary moments. Focus creates impact, excess creates noise
-
-## Verify the Result
-
-- **The wow test**: Show it to someone who hasn't seen it. Do they react?
-- **The removal test**: Take it away. Does the experience feel diminished, or does nobody notice?
-- **The device test**: Run it on a phone, a tablet, a Chromebook. Still smooth?
-- **The accessibility test**: Enable reduced motion. Still beautiful?
-- **The context test**: Does this make sense for THIS brand and audience?
-
-"Technically extraordinary" isn't about using the newest API. It's about making an interface do something users didn't think a website could do.
@@ -1,179 +0,0 @@
-# Persona-Based Design Testing
-
-Test the interface through the eyes of 5 distinct user archetypes. Each persona exposes different failure modes that a single "design director" perspective would miss.
-
-**How to use**: Select 2–3 personas most relevant to the interface being critiqued. Walk through the primary user action as each persona. Report specific red flags, not generic concerns.
-
----
-
-## 1. Impatient Power User: "Alex"
-
-
-**Profile**: Expert with similar products. Expects efficiency, hates hand-holding. Will find shortcuts or leave.
-
-**Behaviors**:
-- Skips all onboarding and instructions
-- Looks for keyboard shortcuts immediately
-- Tries to bulk-select, batch-edit, and automate
-- Gets frustrated by required steps that feel unnecessary
-- Abandons if anything feels slow or patronizing
-
-**Test Questions**:
-- Can Alex complete the core task in under 60 seconds?
-- Are there keyboard shortcuts for common actions?
-- Can onboarding be skipped entirely?
-- Do modals have keyboard dismiss (Esc)?
-- Is there a "power user" path (shortcuts, bulk actions)?
-
-**Red Flags** (report these specifically):
-- Forced tutorials or unskippable onboarding
-- No keyboard navigation for primary actions
-- Slow animations that can't be skipped
-- One-item-at-a-time workflows where batch would be natural
-- Redundant confirmation steps for low-risk actions
-
----
-
-## 2. Confused First-Timer: "Jordan"
-
-**Profile**: Never used this type of product. Needs guidance at every step. Will abandon rather than figure it out.
-
-**Behaviors**:
-- Reads all instructions carefully
-- Hesitates before clicking anything unfamiliar
-- Looks for help or support constantly
-- Misunderstands jargon and abbreviations
-- Takes the most literal interpretation of any label
-
-**Test Questions**:
-- Is the first action obviously clear within 5 seconds?
-- Are all icons labeled with text?
-- Is there contextual help at decision points?
-- Does terminology assume prior knowledge?
-- Is there a clear "back" or "undo" at every step?
-
-**Red Flags** (report these specifically):
-- Icon-only navigation with no labels
-- Technical jargon without explanation
-- No visible help option or guidance
-- Ambiguous next steps after completing an action
-- No confirmation that an action succeeded
-
----
-
-## 3. Accessibility-Dependent User: "Sam"
-
-**Profile**: Uses screen reader (VoiceOver/NVDA), keyboard-only navigation. May have low vision, motor impairment, or cognitive differences.
-
-**Behaviors**:
-- Tabs through the interface linearly
-- Relies on ARIA labels and heading structure
-- Cannot see hover states or visual-only indicators
-- Needs adequate color contrast (4.5:1 minimum)
-- May use browser zoom up to 200%
-
-**Test Questions**:
-- Can the entire primary flow be completed keyboard-only?
-- Are all interactive elements focusable with visible focus indicators?
-- Do images have meaningful alt text?
-- Is color contrast WCAG AA compliant (4.5:1 for text)?
-- Does the screen reader announce state changes (loading, success, errors)?
-
-**Red Flags** (report these specifically):
-- Click-only interactions with no keyboard alternative
-- Missing or invisible focus indicators
-- Meaning conveyed by color alone (red = error, green = success)
-- Unlabeled form fields or buttons
-- Time-limited actions without extension option
-- Custom components that break screen reader flow
-
----
-
-## 4. Deliberate Stress Tester: "Riley"
-
-**Profile**: Methodical user who pushes interfaces beyond the happy path. Tests edge cases, tries unexpected inputs, and probes for gaps in the experience.
-
-**Behaviors**:
-- Tests edge cases intentionally (empty states, long strings, special characters)
-- Submits forms with unexpected data (emoji, RTL text, very long values)
-- Tries to break workflows by navigating backwards, refreshing mid-flow, or opening in multiple tabs
-- Looks for inconsistencies between what the UI promises and what actually happens
-- Documents problems methodically
-
-**Test Questions**:
-- What happens at the edges (0 items, 1000 items, very long text)?
-- Do error states recover gracefully or leave the UI in a broken state?
-- What happens on refresh mid-workflow? Is state preserved?
-- Are there features that appear to work but produce broken results?
-- How does the UI handle unexpected input (emoji, special chars, paste from Excel)?
-
-**Red Flags** (report these specifically):
-- Features that appear to work but silently fail or produce wrong results
-- Error handling that exposes technical details or leaves UI in a broken state
-- Empty states that show nothing useful ("No results" with no guidance)
-- Workflows that lose user data on refresh or navigation
-- Inconsistent behavior between similar interactions in different parts of the UI
-
----
-
-## 5. Distracted Mobile User: "Casey"
-
-**Profile**: Using phone one-handed on the go. Frequently interrupted. Possibly on a slow connection.
-
-**Behaviors**:
-- Uses thumb only; prefers bottom-of-screen actions
-- Gets interrupted mid-flow and returns later
-- Switches between apps frequently
-- Has limited attention span and low patience
-- Types as little as possible, prefers taps and selections
-
-**Test Questions**:
-- Are primary actions in the thumb zone (bottom half of screen)?
-- Is state preserved if the user leaves and returns?
-- Does it work on slow connections (3G)?
-- Can forms use autocomplete and smart defaults?
-- Are touch targets at least 44×44pt?
-
-**Red Flags** (report these specifically):
-- Important actions positioned at the top of the screen (unreachable by thumb)
-- No state persistence; progress lost on tab switch or interruption
-- Large text inputs required where selection would work
-- Heavy assets loading on every page (no lazy loading)
-- Tiny tap targets or targets too close together
-
----
-
-## Selecting Personas
-
-Choose personas based on the interface type:
-
-| Interface Type | Primary Personas | Why |
-|---------------|-----------------|-----|
-| Landing page / marketing | Jordan, Riley, Casey | First impressions, trust, mobile |
-| Dashboard / admin | Alex, Sam | Power users, accessibility |
-| E-commerce / checkout | Casey, Riley, Jordan | Mobile, edge cases, clarity |
-| Onboarding flow | Jordan, Casey | Confusion, interruption |
-| Data-heavy / analytics | Alex, Sam | Efficiency, keyboard nav |
-| Form-heavy / wizard | Jordan, Sam, Casey | Clarity, accessibility, mobile |
-
----
-
-## Project-Specific Personas
-
-If `AGENTS.md` contains a `## Design Context` section (generated by `impeccable teach`), derive 1–2 additional personas from the audience and brand information:
-
-1. Read the target audience description
-2. Identify the primary user archetype not covered by the 5 predefined personas
-3. Create a persona following this template:
-
-```
-### [Role]: "[Name]"
-
-**Profile**: [2-3 key characteristics derived from Design Context]
-
-**Behaviors**: [3-4 specific behaviors based on the described audience]
-
-**Red Flags**: [3-4 things that would alienate this specific user type]
-```
-
-Only generate project-specific personas when real Design Context data is available. Don't invent audience details; use the 5 predefined personas when no context exists.
@@ -1,242 +0,0 @@
-> **Additional context needed**: quality bar (MVP vs flagship).
-
-Perform a meticulous final pass to catch all the small details that separate good work from great work. The difference between shipped and polished.
-
-Detector and automated QA output are defect evidence only. A clean script result is never proof that the design is strong; gather browser evidence and inspect the real interaction path.
-
-## Design System Discovery
-
-Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
-
-1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
-2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
-3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category: patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
-
-If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask. Never guess at design system principles.**
-
-## Pre-Polish Assessment
-
-Understand the current state and goals before touching anything:
-
-1. **Review completeness**:
- - Is it functionally complete?
- - Are there known issues to preserve (mark with TODOs)?
- - What's the quality bar? (MVP vs flagship feature?)
- - When does it ship? (How much time for polish?)
-
-2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish; a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
-
-3. **Identify polish areas**:
- - Visual inconsistencies
- - Spacing and alignment issues
- - Interaction state gaps
- - Copy inconsistencies
- - Edge cases and error states
- - Loading and transition smoothness
- - Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
-
-4. **Pull in any prior critique** (optional signal): If `/impeccable critique` has been run on the same target, its priority issues are a useful prior for what to address first. Resolve the target to a file path or URL, then:
- ```bash
- slug=$(node .opencode/skills/impeccable/scripts/critique-storage.mjs slug "<resolved>")
- node .opencode/skills/impeccable/scripts/critique-storage.mjs latest "$slug"
- ```
- Exit 0 with body = found; fold the P0/P1 items into your polish list and mention the snapshot path so the user sees what you read. Exit 2 = no snapshot, continue without it. The critique is one input among many. Do your own pass either way.
-
-5. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent; never perfect one corner while leaving another rough.
-
-**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
-
-## Polish Systematically
-
-Work through these dimensions methodically:
-
-### Visual Alignment & Spacing
-
-- **Pixel-perfect alignment**: Everything lines up to grid
-- **Consistent spacing**: All gaps use spacing scale (no random 13px gaps)
-- **Optical alignment**: Adjust for visual weight (icons may need offset for optical centering)
-- **Responsive consistency**: Spacing and alignment work at all breakpoints
-- **Grid adherence**: Elements snap to baseline grid
-
-**Check**:
-- Enable grid overlay and verify alignment
-- Check spacing with browser inspector
-- Test at multiple viewport sizes
-- Look for elements that "feel" off
-
-### Information Architecture & Flow
-
-Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
-
-- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
-- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere: modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
-- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
-- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
-- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
-
-### Typography Refinement
-
-- **Hierarchy consistency**: Same elements use same sizes/weights throughout
-- **Line length**: 45-75 characters for body text
-- **Line height**: Appropriate for font size and context
-- **Widows & orphans**: No single words on last line
-- **Hyphenation**: Appropriate for language and column width
-- **Kerning**: Adjust letter spacing where needed (especially headlines)
-- **Font loading**: No FOUT/FOIT flashes
-
-### Color & Contrast
-
-- **Contrast ratios**: All text meets WCAG standards
-- **Consistent token usage**: No hard-coded colors, all use design tokens
-- **Theme consistency**: Works in all theme variants
-- **Color meaning**: Same colors mean same things throughout
-- **Accessible focus**: Focus indicators visible with sufficient contrast
-- **Tinted neutrals**: No pure gray or pure black; add subtle color tint (0.01 chroma)
-- **Gray on color**: Never put gray text on colored backgrounds; use a shade of that color or transparency
-
-### Interaction States
-
-Every interactive element needs all states:
-
-- **Default**: Resting state
-- **Hover**: Subtle feedback (color, scale, shadow)
-- **Focus**: Keyboard focus indicator (never remove without replacement)
-- **Active**: Click/tap feedback
-- **Disabled**: Clearly non-interactive
-- **Loading**: Async action feedback
-- **Error**: Validation or error state
-- **Success**: Successful completion
-
-**Missing states create confusion and broken experiences**.
-
-### Micro-interactions & Transitions
-
-- **Smooth transitions**: All state changes animated appropriately (150-300ms)
-- **Consistent easing**: Use ease-out-quart/quint/expo for natural deceleration. Never bounce or elastic; they feel dated.
-- **No jank**: Smooth animations; use atmospheric blur/filter/mask/shadow effects when they add polish, but bound expensive paint areas and avoid casual layout-property animation
-- **Appropriate motion**: Motion serves purpose, not decoration
-- **Reduced motion**: Respects `prefers-reduced-motion`
-
-### Content & Copy
-
-- **Consistent terminology**: Same things called same names throughout
-- **Consistent capitalization**: Title Case vs Sentence case applied consistently
-- **Grammar & spelling**: No typos
-- **Appropriate length**: Not too wordy, not too terse
-- **Punctuation consistency**: Periods on sentences, not on labels (unless all labels have them)
-
-### Icons & Images
-
-- **Consistent style**: All icons from same family or matching style
-- **Appropriate sizing**: Icons sized consistently for context
-- **Proper alignment**: Icons align with adjacent text optically
-- **Alt text**: All images have descriptive alt text
-- **Loading states**: Images don't cause layout shift, proper aspect ratios
-- **Retina support**: 2x assets for high-DPI screens
-
-### Forms & Inputs
-
-- **Label consistency**: All inputs properly labeled
-- **Required indicators**: Clear and consistent
-- **Error messages**: Helpful and consistent
-- **Tab order**: Logical keyboard navigation
-- **Auto-focus**: Appropriate (don't overuse)
-- **Validation timing**: Consistent (on blur vs on submit)
-
-### Edge Cases & Error States
-
-- **Loading states**: All async actions have loading feedback
-- **Empty states**: Helpful empty states, not just blank space
-- **Error states**: Clear error messages with recovery paths
-- **Success states**: Confirmation of successful actions
-- **Long content**: Handles very long names, descriptions, etc.
-- **No content**: Handles missing data gracefully
-- **Offline**: Appropriate offline handling (if applicable)
-
-### Responsiveness
-
-- **All breakpoints**: Test mobile, tablet, desktop
-- **Touch targets**: 44x44px minimum on touch devices
-- **Readable text**: No text smaller than 14px on mobile
-- **No horizontal scroll**: Content fits viewport
-- **Appropriate reflow**: Content adapts logically
-
-### Performance
-
-- **Fast initial load**: Optimize critical path
-- **No layout shift**: Elements don't jump after load (CLS)
-- **Smooth interactions**: No lag or jank
-- **Optimized images**: Appropriate formats and sizes
-- **Lazy loading**: Off-screen content loads lazily
-
-### Code Quality
-
-- **Remove console logs**: No debug logging in production
-- **Remove commented code**: Clean up dead code
-- **Remove unused imports**: Clean up unused dependencies
-- **Consistent naming**: Variables and functions follow conventions
-- **Type safety**: No TypeScript `any` or ignored errors
-- **Accessibility**: Proper ARIA labels and semantic HTML
-
-## Polish Checklist
-
-Go through systematically:
-
-- [ ] Aligned to the design system (drift named and resolved by root cause)
-- [ ] Information architecture and flow shape match neighboring features
-- [ ] Visual alignment perfect at all breakpoints
-- [ ] Spacing uses design tokens consistently
-- [ ] Typography hierarchy consistent
-- [ ] All interactive states implemented
-- [ ] All transitions smooth (60fps)
-- [ ] Copy is consistent and polished
-- [ ] Icons are consistent and properly sized
-- [ ] All forms properly labeled and validated
-- [ ] Error states are helpful
-- [ ] Loading states are clear
-- [ ] Empty states are welcoming
-- [ ] Touch targets are 44x44px minimum
-- [ ] Contrast ratios meet WCAG AA
-- [ ] Keyboard navigation works
-- [ ] Focus indicators visible
-- [ ] No console errors or warnings
-- [ ] No layout shift on load
-- [ ] Works in all supported browsers
-- [ ] Respects reduced motion preference
-- [ ] Code is clean (no TODOs, console.logs, commented code)
-
-**IMPORTANT**: Polish is about details. Zoom in. Squint at it. Use it yourself. The little things add up.
-
-Sweat the details. Zoom in until the alignment is right and the spacing reads as deliberate. Then ship.
-
-**NEVER**:
-- Polish before it's functionally complete
-- Polish without aligning to the design system; that's decoration on drift
-- Guess at design system principles instead of asking when something is ambiguous
-- Spend hours on polish if it ships in 30 minutes (triage)
-- Introduce bugs while polishing (test thoroughly)
-- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
-- Perfect one thing while leaving others rough (consistent quality level)
-- Create new one-off components when design system equivalents exist
-- Hard-code values that should use design tokens
-- Introduce new patterns or flows that diverge from established ones
-
-## Final Verification
-
-Before marking as done:
-
-- **Use it yourself**: Actually interact with the feature.
-- **Test on real devices**: Not just browser DevTools.
-- **Ask someone else to review**: Fresh eyes catch things.
-- **Compare to design**: Match intended design.
-- **Check all states**: Don't just test happy path.
-- **Treat automation carefully**: Run detector or QA commands when they are available and relevant, fix their defects, but never cite a clean result as proof that the work is polished.
-
-## Clean Up
-
-After polishing, ensure code quality:
-
-- **Replace custom implementations**: If the design system provides a component you reimplemented, switch to the shared version.
-- **Remove orphaned code**: Delete unused styles, components, or files made obsolete by polish.
-- **Consolidate tokens**: If you introduced new values, check whether they should be tokens.
-- **Verify DRYness**: Look for duplication introduced during polishing and consolidate.
@@ -1,62 +0,0 @@
-# Product register
-
-When design SERVES the product: app UIs, admin dashboards, settings panels, data tables, tools, authenticated surfaces, anything where the user is in a task.
-
-## The product slop test
-
-Not "would someone say AI made this." Familiarity is often a feature here. The test is: would a user fluent in the category's best tools (Linear, Figma, Notion, Raycast, Stripe come to mind) sit down and trust this interface, or pause at every subtly-off component?
-
-Product UI's failure mode isn't flatness, it's strangeness without purpose: over-decorated buttons, mismatched form controls, gratuitous motion, display fonts where labels should be, invented affordances for standard tasks. The bar is earned familiarity. The tool should disappear into the task.
-
-## Typography
-
-- **System fonts are legitimate.** `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` gives you native feel on every platform. Inter is the common cross-platform default for a reason.
-- **One family is often right.** Product UIs don't need display/body pairing. A well-tuned sans carries headings, buttons, labels, body, data.
-- **Fixed rem scale, not fluid.** Clamp-sized headings don't serve product UI. Users view at consistent DPI, and a fluid h1 that shrinks in a sidebar looks worse, not better.
-- **Tighter scale ratio.** 1.125–1.2 between steps is typical. More type elements here than on brand surfaces; exaggerated contrast creates noise.
-- **Line length still applies for prose** (65–75ch). Data and compact UI can run denser; tables at 120ch+ are fine.
-
-## Color
-
-Product defaults to Restrained. A single surface can earn Committed (a dashboard where one category color carries a report, an onboarding flow with a drenched welcome screen), but Restrained is the floor.
-
-- State-rich semantic vocabulary: hover, focus, active, disabled, selected, loading, error, warning, success, info. Standardize these.
-- Accent color used for primary actions, current selection, and state indicators only, not decoration.
-- A second neutral layer for sidebars, toolbars, and panels (slightly cooler or warmer than the content surface).
-
-## Layout
-
-- Predictable grids. Consistency IS an affordance; users navigate faster when the structure is expected.
-- Familiar patterns are features. Standard navigation (top bar, side nav), breadcrumbs, tabs, and form layouts have established user expectations. Don't reinvent for flavor.
-- Responsive behavior is structural (collapse sidebar, responsive table, breakpoint-driven columns), not fluid typography.
-
-## Components
-
-Every interactive component has: default, hover, focus, active, disabled, loading, error. Don't ship with half of these.
-
-- Skeleton states for loading, not spinners in the middle of content.
-- Empty states that teach the interface, not "nothing here."
-- Consistent affordances across the surface. Same button shape. Same form-control vocabulary. Same icon style.
-
-## Motion
-
-- 150–250 ms on most transitions. Users are in flow; don't make them wait for choreography.
-- Motion conveys state, not decoration. State change, feedback, loading, reveal: nothing else.
-- No orchestrated page-load sequences. Product loads into a task; users don't want to watch it load.
-
-## Product bans (on top of the shared absolute bans)
-
-- Decorative motion that doesn't convey state.
-- Inconsistent component vocabulary across screens. If the "save" button looks different in two places, one is wrong.
-- Display fonts in UI labels, buttons, data.
-- Reinventing standard affordances for flavor (custom scrollbars, weird form controls, non-standard modals).
-- Heavy color or full-saturation accents on inactive states.
-
-## Product permissions
-
-Product can afford things brand surfaces can't.
-
-- System fonts and familiar sans defaults (Inter, SF Pro, system-ui stacks).
-- Standard navigation patterns: top bar + side nav, breadcrumbs, tabs, command palettes.
-- Density. Tables with many rows, panels with many labels, dense information when users need it.
-- Consistency over surprise. The same visual vocabulary screen to screen is a virtue; delight is saved for moments, not pages.
@@ -1,99 +0,0 @@
-Quiet design is harder than bold design. Subtlety needs precision. Reduce visual intensity in designs that are too loud, aggressive, or overstimulating without losing personality or making the result generic.
-
----
-
-## Register
-
-Brand: "quieter" means more restrained palette, more whitespace, more typographic air. Drama is reduced, not eliminated; the POV stays intact.
-
-Product: "quieter" means reducing visual noise. Fewer background accents, flatter cards, less color, less motion. The tool should disappear more completely into the task.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too intense:
-
-1. **Identify intensity sources**:
- - **Color saturation**: Overly bright or saturated colors
- - **Contrast extremes**: Too much high-contrast juxtaposition
- - **Visual weight**: Too many bold, heavy elements competing
- - **Animation excess**: Too much motion or overly dramatic effects
- - **Complexity**: Too many visual elements, patterns, or decorations
- - **Scale**: Everything is large and loud with no hierarchy
-
-2. **Understand the context**:
- - What's the purpose? (Marketing vs tool vs reading experience)
- - Who's the audience? (Some contexts need energy)
- - What's working? (Don't throw away good ideas)
- - What's the core message? (Preserve what matters)
-
-If any of these are unclear from the codebase, STOP and call the `question` tool to clarify.
-
-**CRITICAL**: "Quieter" doesn't mean boring or generic. It means refined and easier on the eyes. Think luxury, not laziness.
-
-## Plan Refinement
-
-Create a strategy to reduce intensity while maintaining impact:
-
-- **Color approach**: Desaturate or shift to more restrained tones?
-- **Hierarchy approach**: Which elements should stay bold (very few), which should recede?
-- **Simplification approach**: What can be removed entirely?
-- **Sophistication approach**: How can we signal quality through restraint?
-
-**IMPORTANT**: Subtlety requires precision. Quiet without intent collapses to generic.
-
-## Refine the Design
-
-Systematically reduce intensity across these dimensions:
-
-### Color Refinement
-- **Reduce saturation**: Shift from fully saturated to 70-85% saturation
-- **Soften palette**: Replace bright colors with muted tones
-- **Reduce color variety**: Use fewer colors more thoughtfully
-- **Neutral dominance**: Let neutrals do more work, use color as accent (10% rule)
-- **Gentler contrasts**: High contrast only where it matters most
-- **Tinted grays**: Use warm or cool tinted grays instead of pure gray. Adds depth without loudness
-- **Never gray on color**: If you have gray text on a colored background, use a darker shade of that color or transparency instead
-
-### Visual Weight Reduction
-- **Typography**: Reduce font weights (900 → 600, 700 → 500), decrease sizes where appropriate
-- **Hierarchy through subtlety**: Use weight, size, and space instead of color and boldness
-- **White space**: Increase breathing room, reduce density
-- **Borders & lines**: Reduce thickness, decrease opacity, or remove entirely
-
-### Simplification
-- **Remove decorative elements**: Gradients, shadows, patterns, textures that don't serve purpose
-- **Simplify shapes**: Reduce border radius extremes, simplify custom shapes
-- **Reduce layering**: Flatten visual hierarchy where possible
-- **Clean up effects**: Reduce or remove blur effects, glows, multiple shadows
-
-### Motion Reduction
-- **Reduce animation intensity**: Shorter distances (10-20px instead of 40px), gentler easing
-- **Remove decorative animations**: Keep functional motion, remove flourishes
-- **Subtle micro-interactions**: Replace dramatic effects with gentle feedback
-- **Refined easing**: Use ease-out-quart for smooth, understated motion. Never bounce or elastic
-- **Remove animations entirely** if they're not serving a clear purpose
-
-### Composition Refinement
-- **Reduce scale jumps**: Smaller contrast between sizes creates calmer feeling
-- **Align to grid**: Bring rogue elements back into systematic alignment
-- **Even out spacing**: Replace extreme spacing variations with consistent rhythm
-
-**NEVER**:
-- Make everything the same size/weight (hierarchy still matters)
-- Remove all color (quiet ≠ grayscale)
-- Eliminate all personality (maintain character through refinement)
-- Sacrifice usability for aesthetics (functional elements still need clear affordances)
-- Make everything small and light (some anchors needed)
-
-## Verify Quality
-
-Ensure refinement maintains quality:
-
-- **Still functional**: Can users still accomplish tasks easily?
-- **Still distinctive**: Does it have character, or is it generic now?
-- **Better reading**: Is text easier to read for extended periods?
-- **Restrained, not absent**: Does the POV survive the cuts?
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,114 +0,0 @@
-# Responsive Design
-
-## Mobile-First: Write It Right
-
-Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
-
-## Breakpoints: Content-Driven
-
-Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
-
-## Detect Input Method, Not Just Screen Size
-
-**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
-
-```css
-/* Fine pointer (mouse, trackpad) */
-@media (pointer: fine) {
- .button { padding: 8px 16px; }
-}
-
-/* Coarse pointer (touch, stylus) */
-@media (pointer: coarse) {
- .button { padding: 12px 20px; } /* Larger touch target */
-}
-
-/* Device supports hover */
-@media (hover: hover) {
- .card:hover { transform: translateY(-2px); }
-}
-
-/* Device doesn't support hover (touch) */
-@media (hover: none) {
- .card { /* No hover state - use active instead */ }
-}
-```
-
-**Critical**: Don't rely on hover for functionality. Touch users can't hover.
-
-## Safe Areas: Handle the Notch
-
-Modern phones have notches, rounded corners, and home indicators. Use `env()`:
-
-```css
-body {
- padding-top: env(safe-area-inset-top);
- padding-bottom: env(safe-area-inset-bottom);
- padding-left: env(safe-area-inset-left);
- padding-right: env(safe-area-inset-right);
-}
-
-/* With fallback */
-.footer {
- padding-bottom: max(1rem, env(safe-area-inset-bottom));
-}
-```
-
-**Enable viewport-fit** in your meta tag:
-```html
-<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
-```
-
-## Responsive Images: Get It Right
-
-### srcset with Width Descriptors
-
-```html
-<img
- src="hero-800.jpg"
- srcset="
- hero-400.jpg 400w,
- hero-800.jpg 800w,
- hero-1200.jpg 1200w
- "
- sizes="(max-width: 768px) 100vw, 50vw"
- alt="Hero image"
->
-```
-
-**How it works**:
-- `srcset` lists available images with their actual widths (`w` descriptors)
-- `sizes` tells the browser how wide the image will display
-- Browser picks the best file based on viewport width AND device pixel ratio
-
-### Picture Element for Art Direction
-
-When you need different crops/compositions (not just resolutions):
-
-```html
-<picture>
- <source media="(min-width: 768px)" srcset="wide.jpg">
- <source media="(max-width: 767px)" srcset="tall.jpg">
- <img src="fallback.jpg" alt="...">
-</picture>
-```
-
-## Layout Adaptation Patterns
-
-**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
-
-## Testing: Don't Trust DevTools Alone
-
-DevTools device emulation is useful for layout but misses:
-
-- Actual touch interactions
-- Real CPU/memory constraints
-- Network latency patterns
-- Font rendering differences
-- Browser chrome/keyboard appearances
-
-**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
-
----
-
-**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
@@ -1,165 +0,0 @@
-Shape the UX and UI for a feature before any code is written. This command produces a **design brief**: a structured artifact that guides implementation through discovery, not guesswork.
-
-**Scope**: Design planning only. This command does NOT write code. It produces the thinking that makes code good.
-
-**Output**: A design brief that can be handed off to /impeccable craft, or directly to /impeccable for freeform implementation. When visual direction probes are used, the images are supporting artifacts, not the primary output.
-
-## Philosophy
-
-Most AI-generated UIs fail not because of bad code, but because of skipped thinking. They jump to "here's a card grid" without asking "what is the user trying to accomplish?" This command inverts that: understand deeply first, so implementation is precise.
-
-## Phase 1: Discovery Interview
-
-**Do NOT write any code or make any design decisions during this phase.** Your only job is to understand the feature deeply enough to make excellent design decisions later.
-
-This is a required interaction, not optional guidance. Ask these questions in conversation, adapting based on answers. Don't dump them all at once; have a natural dialogue. STOP and call the `question` tool to clarify.
-
-### Interview cadence
-
-Discovery includes at least one user-answer round unless PRODUCT.md, DESIGN.md, or an already-confirmed brief directly answers the needed inputs. With a sparse prompt, do **not** synthesize a complete brief for confirmation on the first response.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Treat PRODUCT.md and DESIGN.md as anchors; they reduce repeated questions but do **not** replace shape for craft. Shape is task-specific.
-- One round is the default. Add a second only if the first answers leave material gaps. Don't run a second round just to feel thorough.
-- Round 1 should clarify purpose, audience/context, content/scope, and (for brand) visual direction.
-- Round 2, when needed, fills in whatever's still genuinely missing.
-
-**Assert-then-confirm, not menu-with-escape.** When PRODUCT.md and the user's prompt make one option obvious, name it and ask the user to confirm or override. Don't enumerate "Restrained / Committed / Or something else?" as a real choice; "This reads as Restrained, confirm?" beats a four-option menu when the answer is already clear.
-
-### Purpose & Context
-- What is this feature for? What problem does it solve?
-- Who specifically will use it? (Not "users"; be specific: role, context, frequency)
-- What does success look like? How will you know this feature is working?
-- What's the user's state of mind when they reach this feature? (Rushed? Exploring? Anxious? Focused?)
-
-### Content & Data
-- What content or data does this feature display or collect?
-- What are the realistic ranges? (Minimum, typical, maximum, e.g., 0 items, 5 items, 500 items)
-- What are the edge cases? (Empty state, error state, first-time use, power user)
-- Is any content dynamic? What changes and how often?
-- What visual assets are real content here? Note required images, product shots, illustrations, maps, textures, diagrams, generated objects, or existing project assets.
-
-### Design Direction
-
-Force a visual decision on three fronts. Skip anything PRODUCT.md or DESIGN.md already answers; ask only what's missing.
-
-- **Color strategy for this surface.** Pick one: Restrained / Committed / Full palette / Drenched. Can override the project default if the surface earns it (e.g. a drenched hero inside an otherwise Restrained product).
-- **Theme via scene sentence.** Write one sentence of physical context for this surface: who uses it, where, under what ambient light, in what mood. The sentence forces dark vs light. If it doesn't, add detail until it does.
-- **Two or three named anchor references.** Specific products, brands, objects. Not adjectives like "modern" or "clean."
-
-### Scope
-
-Always ask. Sketch quality and shipped quality are different outputs; don't guess between them.
-
-- **Fidelity.** Sketch / mid-fi / high-fi / production-ready?
-- **Breadth.** One screen / a flow / a whole surface?
-- **Interactivity.** Static visual / interactive prototype / shipped-quality component?
-- **Time intent.** Quick exploration, or polish until it ships?
-
-Scope answers are task-scoped. Don't write them to PRODUCT.md or DESIGN.md; carry them through the design brief only.
-
-### Constraints
-- Are there technical constraints? (Framework, performance budget, browser support)
-- Are there content constraints? (Localization, dynamic text length, user-generated content)
-- Mobile/responsive requirements?
-- Accessibility requirements beyond WCAG AA?
-
-### Anti-Goals
-- What should this NOT be? What would be a wrong direction?
-- What's the biggest risk of getting this wrong?
-
-## Phase 1.5: Visual Direction Probe (Capability-Gated)
-
-After the discovery interview, generate a small set of visual direction probes **before** writing the final brief when all of these are true:
-
-- The work is **net-new** or directionally ambiguous enough that visual exploration will clarify the brief.
-- The requested fidelity is **mid-fi, high-fi, or production-ready**. Skip for sketch-only planning.
-- The current harness gives you native image generation (Codex's `image_gen`, an equivalent MCP tool, or similar). Don't ask the user to install APIs or tooling.
-
-When those conditions are met, this step is mandatory. If image generation isn't natively available, do not ask the user to install APIs or tooling. State in one line that the image step is skipped because the harness lacks native image generation, then proceed. The one-line announcement is required, not optional; it forces a conscious decision instead of letting the step quietly evaporate.
-
-Use probes to explore visual lanes, not to replace the brief.
-
-Do not skip probes because the final UI will be semantic, editable, code-native, responsive, or accessible. Those are implementation requirements, not reasons to avoid visual exploration.
-
-### What to generate
-
-Generate **2 to 4** distinct direction probes based on the discovery answers, especially:
-
-- Color strategy
-- Theme scene sentence
-- Named anchor references
-- Scope and fidelity
-
-The probes should differ in primary visual direction (hierarchy, topology, density, typographic voice, or color strategy), not just palette tweaks.
-
-### How to use the probes
-
-- Treat them as **direction tests**, not final designs.
-- Use them to pressure-test whether the brief is pointing at the right lane.
-- Ask the user which direction feels closest, what feels off, and what should carry forward.
-- If the probes reveal a mismatch, revise the brief inputs before finalizing the brief.
-
-### Important limits
-
-- Do **not** skip discovery because image generation is available.
-- Do **not** treat generated imagery as final UX specification, final copy, or final accessibility behavior.
-- Do **not** use this step for minor refinements of existing work. It's for shaping a new surface or clarifying a big directional choice.
-
-If image generation isn't natively available, announce the skip in one line and proceed to the design brief.
-
-## Phase 2: Design Brief
-
-After the interview and any required probes, present a brief and **end your response**. The user must confirm before any implementation runs. Do not present a brief and then continue to code in the same response, even if the brief feels obvious to you. The user's confirmation is the gate.
-
-**Choose the brief shape based on how clear the answers are:**
-
-- **Compact form (3-5 bullets)** when discovery was crisp and the original prompt + PRODUCT.md already pinned scope, content, and direction. State what you're building, the visual lane, and end with one or two specific questions or a clear "confirm or override?" prompt. This is the default for typical craft requests with a clear prompt.
-- **Full structured form (sections below)** when the task is genuinely ambiguous, multi-screen, or when the user asked for shape as a standalone step. Use this when the discipline of structure earns its weight.
-
-Don't pad a clear brief into a long one to look thorough. A 70-line brief restating answers the user just gave is noise, not rigor. Equally, don't skip the confirmation pause to look efficient: the pause is the point.
-
-Present the brief, then **stop and wait for explicit confirmation**. You are not the judge of whether the user already approved. Even when the brief feels obviously right, ask once and wait. The pause is what separates shape from premature implementation.
-
-### Brief Structure
-
-**1. Feature Summary** (2-3 sentences)
-What this is, who it's for, what it needs to accomplish.
-
-**2. Primary User Action**
-The single most important thing a user should do or understand here.
-
-**3. Design Direction**
-Color strategy (Restrained / Committed / Full palette / Drenched) + the theme scene sentence + 2–3 named anchor references. Reference PRODUCT.md and DESIGN.md where they already answer, and note any per-surface overrides.
-
-If you ran the Visual Direction Probe step, name which probe direction won and what changed in the brief because of it.
-
-**4. Scope**
-Fidelity, breadth, interactivity, and time intent from the Scope section of the interview. Task-scoped; these don't persist beyond the brief.
-
-**5. Layout Strategy**
-High-level spatial approach: what gets emphasis, what's secondary, how information flows. Describe the visual hierarchy and rhythm, not specific CSS.
-
-**6. Key States**
-List every state the feature needs: default, empty, loading, error, success, edge cases. For each, note what the user needs to see and feel.
-
-**7. Interaction Model**
-How users interact with this feature. What happens on click, hover, scroll? What feedback do they get? What's the flow from entry to completion?
-
-**8. Content Requirements**
-What copy, labels, empty state messages, error messages, and microcopy are needed. Note any dynamic content and its realistic ranges. For image-led surfaces, also list the required image/media roles and their likely source (project asset, generated raster, semantic SVG/CSS, canvas/WebGL, icon library, or accepted omission).
-
-**9. Recommended References**
-Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., spatial-design.md for complex layouts, motion-design.md for animated features, interaction-design.md for form-heavy features).
-
-**10. Open Questions**
-Anything genuinely unresolved. Don't list "open questions" you've already recommended a default for; assert the default and move on. If you'd write `Recommend: X` next to a question, just decide X.
-
----
-
-STOP and call the `question` tool to clarify. Ask for explicit confirmation of the brief before finishing.
-
-If the user disagrees with any part, revisit the relevant discovery questions. A shape run is incomplete until the user confirms direction.
-
-Once confirmed, the brief is complete. The user can now hand it to /impeccable, or use it to guide any other implementation approach. (If the user wants the full discovery-then-build flow in one step, they should use /impeccable craft instead, which runs this command internally.)
@@ -1,100 +0,0 @@
-# Spatial Design
-
-## Spacing Systems
-
-### Use 4pt Base, Not 8pt
-
-8pt systems are too coarse; you'll frequently need 12px (between 8 and 16). Use 4pt for granularity: 4, 8, 12, 16, 24, 32, 48, 64, 96px.
-
-### Name Tokens Semantically
-
-Name by relationship (`--space-sm`, `--space-lg`), not value (`--spacing-8`). Use `gap` instead of margins for sibling spacing; it eliminates margin collapse and cleanup hacks.
-
-## Grid Systems
-
-### The Self-Adjusting Grid
-
-Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Columns are at least 280px, as many as fit per row, leftovers stretch. For complex layouts, use named grid areas (`grid-template-areas`) and redefine them at breakpoints.
-
-## Visual Hierarchy
-
-### The Squint Test
-
-Blur your eyes (or screenshot and blur). Can you still identify:
-- The most important element?
-- The second most important?
-- Clear groupings?
-
-If everything looks the same weight blurred, you have a hierarchy problem.
-
-### Hierarchy Through Multiple Dimensions
-
-Don't rely on size alone. Combine:
-
-| Tool | Strong Hierarchy | Weak Hierarchy |
-|------|------------------|----------------|
-| **Size** | 3:1 ratio or more | <2:1 ratio |
-| **Weight** | Bold vs Regular | Medium vs Regular |
-| **Color** | High contrast | Similar tones |
-| **Position** | Top/left (primary) | Bottom/right |
-| **Space** | Surrounded by white space | Crowded |
-
-**The best hierarchy uses 2-3 dimensions at once**: A heading that's larger, bolder, AND has more space above it.
-
-### Cards Are Not Required
-
-Cards are overused. Spacing and alignment create visual grouping naturally. Use cards only when content is truly distinct and actionable, items need visual comparison in a grid, or content needs clear interaction boundaries. **Never nest cards inside cards.** Use spacing, typography, and subtle dividers for hierarchy within a card.
-
-## Container Queries
-
-Viewport queries are for page layouts. **Container queries are for components**:
-
-```css
-.card-container {
- container-type: inline-size;
-}
-
-.card {
- display: grid;
- gap: var(--space-md);
-}
-
-/* Card layout changes based on its container, not viewport */
-@container (min-width: 400px) {
- .card {
- grid-template-columns: 120px 1fr;
- }
-}
-```
-
-**Why this matters**: A card in a narrow sidebar stays compact, while the same card in a main content area expands automatically, without viewport hacks.
-
-## Optical Adjustments
-
-Text at `margin-left: 0` looks indented due to letterform whitespace; use negative margin (`-0.05em`) to optically align. Geometrically centered icons often look off-center; play icons need to shift right, arrows shift toward their direction.
-
-### Touch Targets vs Visual Size
-
-Buttons can look small but need large touch targets (44px minimum). Use padding or pseudo-elements:
-
-```css
-.icon-button {
- width: 24px; /* Visual size */
- height: 24px;
- position: relative;
-}
-
-.icon-button::before {
- content: '';
- position: absolute;
- inset: -10px; /* Expand tap target to 44px */
-}
-```
-
-## Depth & Elevation
-
-Create semantic z-index scales (dropdown → sticky → modal-backdrop → modal → toast → tooltip) instead of arbitrary numbers. For shadows, create a consistent elevation scale (sm → md → lg → xl). **Key insight**: Shadows should be subtle. If you can clearly see it, it's probably too strong.
-
----
-
-**Avoid**: Arbitrary spacing values outside your scale. Making all spacing equal (variety creates hierarchy). Creating hierarchy through size alone - combine size, weight, color, and space.
@@ -1,156 +0,0 @@
-# Teach Flow
-
-Gathers design context for a project and writes two complementary files at the project root:
-
-- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
-- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
-
-Every other impeccable command reads these files before doing any work.
-
-## Step 1: Load current state
-
-Run the shared loader first so you know what already exists:
-
-```bash
-node .opencode/skills/impeccable/scripts/load-context.mjs
-```
-
-The output tells you whether PRODUCT.md and/or DESIGN.md already exist. If `migrated: true`, legacy `.impeccable.md` was auto-renamed to `PRODUCT.md`. Mention this once to the user.
-
-Decision tree:
-- **Neither file exists (empty project or no context yet)**: do Steps 2-4 (write PRODUCT.md), then decide on DESIGN.md based on whether there's code to analyze.
-- **PRODUCT.md exists, DESIGN.md missing**: skip to Step 5 and offer to run `/impeccable document` for DESIGN.md.
-- **PRODUCT.md exists but has no `## Register` section (legacy)**: add it. Infer a hypothesis from the codebase (see Step 2), confirm with the user, write the field.
-- **Both exist**: STOP and call the `question` tool to clarify. Ask which file to refresh. Skip the one the user doesn't want changed.
-- **Just DESIGN.md exists (unusual)**: do Steps 2-4 to produce PRODUCT.md.
-
-Never silently overwrite an existing file. Always confirm first.
-
-If teach was invoked as a setup blocker by another command, such as `/impeccable craft landing page`, pause that command here. Complete teach, re-run the loader, then resume the original command with the freshly loaded context. For craft, resume into shape next; teach creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
-
-## Step 2: Explore the codebase
-
-Before asking questions, thoroughly scan the project to discover what you can:
-
-- **README and docs**: Project purpose, target audience, any stated goals
-- **Package.json / config files**: Tech stack, dependencies, existing design libraries
-- **Existing components**: Current design patterns, spacing, typography in use
-- **Brand assets**: Logos, favicons, color values already defined
-- **Design tokens / CSS variables**: Existing color palettes, font stacks, spacing scales
-- **Any style guides or brand documentation**
-
-Also form a **register hypothesis** from what you find:
-
-- Brand signals: `/`, `/about`, `/pricing`, `/blog/*`, `/docs/*`, hero sections, big typography, scroll-driven sections, landing-page-shaped content.
-- Product signals: `/app/*`, `/dashboard`, `/settings`, `/(auth)`, forms, data tables, side/top nav, app-shell components.
-
-Register is a hypothesis at this point, not a decision; Step 3 confirms it.
-
-Note what you've learned and what remains unclear. This exploration feeds both PRODUCT.md and DESIGN.md.
-
-## Step 3: Ask strategic questions (for PRODUCT.md)
-
-STOP and call the `question` tool to clarify. Ask only about what you couldn't infer from the codebase.
-
-### Interview mode, not confirmation mode
-
-If the repo is empty or the user's brief is sparse, run a short interview before proposing PRODUCT.md. Do **not** turn a one-sentence request into a complete inferred PRODUCT.md and ask for blanket confirmation.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Use inferred answers as hypotheses or options, not as finished facts.
-- Complete at least one real user-answer round before drafting PRODUCT.md, unless every required answer is directly discoverable from repo docs.
-- Round 1 should establish register, users/purpose, and desired outcome.
-- Round 2 should establish brand personality or references, anti-references, and accessibility needs.
-
-### Minimum viable interview
-
-Ask enough to complete PRODUCT.md. At minimum, cover register confirmation, users and purpose, brand personality, anti-references, and accessibility needs unless each answer is directly discoverable from repo context. After at least one interview round, you may propose inferred answers, but the user must confirm them before you write PRODUCT.md. Never synthesize PRODUCT.md from the original task prompt alone.
-
-### Register (ask first; it shapes everything below)
-
-Every design task is either **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboards, tools: design SERVES the product).
-
-If Step 2 produced a clear hypothesis, lead with it: *"From the codebase, this looks like a [brand / product] surface. Does that match your intent, or should we treat it differently?"*
-
-If the signal is genuinely split (e.g. a product with a big marketing landing), STOP and call the `question` tool to clarify. Ask which register describes the **primary** surface. The register can be overridden per task later, but PRODUCT.md carries one default.
-
-### Users & Purpose
-- Who uses this? What's their context when using it?
-- What job are they trying to get done?
-- For brand: what emotions should the interface evoke? (confidence, delight, calm, urgency)
-- For product: what workflow are they in? What's the primary task on any given screen?
-
-### Brand & Personality
-- How would you describe the brand personality in 3 words?
-- Reference sites or apps that capture the right feel? What specifically about them?
- - For brand, push for real-world references in the right lane (tech-minimal, editorial-magazine, consumer-warm, brutalist-grid, etc.), not generic "modern" adjectives.
- - For product, push for category best-tool references (Linear, Figma, Notion, Raycast, Stripe).
-- What should this explicitly NOT look like? Any anti-references?
-
-### Accessibility & Inclusion
-- Specific accessibility requirements? (WCAG level, known user needs)
-- Considerations for reduced motion, color blindness, or other accommodations?
-
-Skip questions where the answer is already clear. **Do NOT ask about colors, fonts, radii, or visual styling here.** Those belong in DESIGN.md, not PRODUCT.md.
-
-## Step 4: Write PRODUCT.md
-
-Write PRODUCT.md only after the user has confirmed the strategic answers from Step 3. If an inferred answer is uncertain or unconfirmed, ask before writing.
-
-Synthesize into a strategic document:
-
-```markdown
-# Product
-
-## Register
-
-product
-
-## Users
-[Who they are, their context, the job to be done]
-
-## Product Purpose
-[What this product does, why it exists, what success looks like]
-
-## Brand Personality
-[Voice, tone, 3-word personality, emotional goals]
-
-## Anti-references
-[What this should NOT look like. Specific bad-example sites or patterns to avoid.]
-
-## Design Principles
-[3-5 strategic principles derived from the conversation. Principles like "practice what you preach", "show, don't tell", "expert confidence". NOT visual rules like "use OKLCH" or "magenta accent".]
-
-## Accessibility & Inclusion
-[WCAG level, known user needs, considerations]
-```
-
-Register is either `brand` or `product` as a bare value. No prose, no commentary.
-
-Write to `PROJECT_ROOT/PRODUCT.md`. If `.impeccable.md` existed, the loader already renamed it; merge into that content rather than starting from scratch.
-
-## Step 5: Decide on DESIGN.md
-
-Offer `/impeccable document` either way. Two paths:
-
-- **Code exists** (CSS tokens, components, a running site): "I can generate a DESIGN.md that captures your visual system (colors, typography, components) so variants stay on-brand. Want to do that now?"
-- **Pre-implementation** (empty project): "I can seed a starter DESIGN.md from five quick questions about color strategy, type direction, motion energy, and references. You can re-run once there's code, to capture the real tokens. Want to do that now?"
-
-If the user agrees, delegate to `/impeccable document` (it auto-detects scan vs seed). Load its reference and follow that flow.
-
-If the user prefers to skip, mention they can run `/impeccable document` any time later.
-
-## Step 6: Confirm and wrap up
-
-Summarize:
-- Register captured (brand / product)
-- What was written (PRODUCT.md, DESIGN.md, or both)
-- The 3-5 strategic principles from PRODUCT.md that will guide future work
-- If DESIGN.md is pending, remind the user how to generate it later
-
-**Critical: re-run the loader to refresh session context.** After writing PRODUCT.md, run `node .opencode/skills/impeccable/scripts/load-context.mjs` one final time and let its full JSON output land in conversation. This ensures subsequent commands in this session use the freshly-written PRODUCT.md, not a stale earlier version.
-
-If teach was invoked as a blocker by another impeccable command (e.g. the user ran `/impeccable polish` with no PRODUCT.md), resume that original task now with the fresh context.
-
-Optionally STOP and call the `question` tool to clarify. Ask whether they'd like a brief summary of PRODUCT.md appended to AGENTS.md for easier agent reference. If yes, append a short **Design Context** pointer section there.
@@ -1,124 +0,0 @@
-Typography carries most of the information on the page. Replace generic defaults (Inter, Roboto, system fallback at flat scale) with type that reflects the brand and scales with intentional contrast.
-
----
-
-## Register
-
-Brand: run the font selection procedure in [brand.md](brand.md). Pairing follows the brand's lane (display serif + sans body for editorial/luxury, one committed sans for tech, etc.). Fluid `clamp()` scale, ≥1.25 ratio between steps.
-
-Product: system fonts and familiar sans stacks are legitimate here. One well-tuned family typically carries the whole UI. Fixed `rem` scale, 1.125–1.2 ratio between more closely-spaced steps.
-
----
-
-## Assess Current Typography
-
-Analyze what's weak or generic about the current type:
-
-1. **Font choices**:
- - Are we using invisible defaults? (Inter, Roboto, Arial, Open Sans, system defaults)
- - Does the font match the brand personality? (A playful brand shouldn't use a corporate typeface)
- - Are there too many font families? (More than 2-3 is almost always a mess)
-
-2. **Hierarchy**:
- - Can you tell headings from body from captions at a glance?
- - Are font sizes too close together? (14px, 15px, 16px = muddy hierarchy)
- - Are weight contrasts strong enough? (Medium vs Regular is barely visible)
-
-3. **Sizing & scale**:
- - Is there a consistent type scale, or are sizes arbitrary?
- - Does body text meet minimum readability? (16px+)
- - Is the sizing strategy appropriate for the context? (Fixed `rem` scales for app UIs; fluid `clamp()` for marketing/content page headings)
-
-4. **Readability**:
- - Are line lengths comfortable? (45-75 characters ideal)
- - Is line-height appropriate for the font and context?
- - Is there enough contrast between text and background?
-
-5. **Consistency**:
- - Are the same elements styled the same way throughout?
- - Are font weights used consistently? (Not bold in one section, semibold in another for the same role)
- - Is letter-spacing intentional or default everywhere?
-
-**CRITICAL**: The goal isn't to make text "fancier." It's to make it clearer, more readable, and more intentional. Good typography is invisible; bad typography is distracting.
-
-## Plan Typography Improvements
-
-Consult the [typography reference](typography.md) for detailed guidance on scales, pairing, and loading strategies.
-
-Create a systematic plan:
-
-- **Font selection**: Do fonts need replacing? What fits the brand/context?
-- **Type scale**: Establish a modular scale (e.g., 1.25 ratio) with clear hierarchy
-- **Weight strategy**: Which weights serve which roles? (Regular for body, Semibold for labels, Bold for headings, or whatever fits)
-- **Spacing**: Line-heights, letter-spacing, and margins between typographic elements
-
-## Improve Typography Systematically
-
-### Font Selection
-
-If fonts need replacing:
-- Choose fonts that reflect the brand personality
-- Pair with genuine contrast (serif + sans, geometric + humanist), or use a single family in multiple weights
-- Ensure web font loading doesn't cause layout shift (`font-display: swap`, metric-matched fallbacks)
-
-### Establish Hierarchy
-
-Build a clear type scale:
-- **5 sizes cover most needs**: caption, secondary, body, subheading, heading
-- **Use a consistent ratio** between levels (1.25, 1.333, or 1.5)
-- **Combine dimensions**: Size + weight + color + space for strong hierarchy. Don't rely on size alone
-- **App UIs**: Use a fixed `rem`-based type scale, optionally adjusted at 1-2 breakpoints. Fluid sizing undermines the spatial predictability that dense, container-based layouts need
-- **Marketing / content pages**: Use fluid sizing via `clamp(min, preferred, max)` for headings and display text. Keep body text fixed
-
-### Fix Readability
-
-- Set `max-width` on text containers using `ch` units (`max-width: 65ch`)
-- Adjust line-height per context: tighter for headings (1.1-1.2), looser for body (1.5-1.7)
-- Increase line-height slightly for light-on-dark text
-- Ensure body text is at least 16px / 1rem
-
-### Refine Details
-
-- Use `tabular-nums` for data tables and numbers that should align
-- Apply proper `letter-spacing`: slightly open for small caps and uppercase, default or tight for large display text
-- Use semantic token names (`--text-body`, `--text-heading`), not value names (`--font-16`)
-- Set `font-kerning: normal` and consider OpenType features where appropriate
-
-### Weight Consistency
-
-- Define clear roles for each weight and stick to them
-- Don't use more than 3-4 weights (Regular, Medium, Semibold, Bold is plenty)
-- Load only the weights you actually use (each weight adds to page load)
-
-**NEVER**:
-- Use more than 2-3 font families
-- Pick sizes arbitrarily; commit to a scale
-- Set body text below 16px
-- Use decorative/display fonts for body text
-- Disable browser zoom (`user-scalable=no`)
-- Use `px` for font sizes; use `rem` to respect user settings
-- Default to Inter/Roboto/Open Sans when personality matters
-- Pair fonts that are similar but not identical (two geometric sans-serifs)
-
-## Verify Typography Improvements
-
-- **Hierarchy**: Can you identify heading vs body vs caption instantly?
-- **Readability**: Is body text comfortable to read in long passages?
-- **Consistency**: Are same-role elements styled identically throughout?
-- **Personality**: Does the typography reflect the brand?
-- **Performance**: Are web fonts loading efficiently without layout shift?
-- **Accessibility**: Does text meet WCAG contrast ratios? Is it zoomable to 200%?
-
-When the type carries the hierarchy on its own, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `scale` param controlling the hierarchy ratio. Express all font sizes in the variant's scoped CSS through `calc(var(--p-scale, 1) * <base>)` or, better, scale the type ramp via `clamp(min, calc(var(--p-scale, 1) * Npx), max)`. Users slide from subdued to commanding.
-
-```json
-{"id":"scale","kind":"range","min":0.85,"max":1.3,"step":0.05,"default":1,"label":"Scale"}
-```
-
-Where the variant riffs on a specific pairing, expose the pairing choice as a `steps` param (e.g. "serif display + sans body" vs. "mono display + sans body" vs. "all-sans"). Each branch routes through `:scope[data-p-pairing="X"]` selectors in scoped CSS.
-
-See `reference/live.md` for the full params contract.
@@ -1,159 +0,0 @@
-# Typography
-
-## Classic Typography Principles
-
-### Vertical Rhythm
-
-Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
-
-### Modular Scale & Hierarchy
-
-The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
-
-**Use fewer sizes with more contrast.** A 5-size system covers most needs:
-
-| Role | Typical Ratio | Use Case |
-|------|---------------|----------|
-| xs | 0.75rem | Captions, legal |
-| sm | 0.875rem | Secondary UI, metadata |
-| base | 1rem | Body text |
-| lg | 1.25-1.5rem | Subheadings, lead text |
-| xl+ | 2-4rem | Headlines, hero text |
-
-Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
-
-### Readability & Measure
-
-Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
-
-**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
-
-**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
-
-## Font Selection & Pairing
-
-The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
-
-### Anti-reflexes worth defending against
-
-- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
-- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
-- A children's product does NOT need a rounded display font. Kids' books use real type.
-- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
-
-**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
-
-### Pairing Principles
-
-**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
-
-When pairing, contrast on multiple axes:
-- Serif + Sans (structure contrast)
-- Geometric + Humanist (personality contrast)
-- Condensed display + Wide body (proportion contrast)
-
-**Never pair fonts that are similar but not identical** (e.g., two geometric sans-serifs). They create visual tension without clear hierarchy.
-
-### Web Font Loading
-
-The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
-
-```css
-/* 1. Use font-display: swap for visibility */
-@font-face {
- font-family: 'CustomFont';
- src: url('font.woff2') format('woff2');
- font-display: swap;
-}
-
-/* 2. Match fallback metrics to minimize shift */
-@font-face {
- font-family: 'CustomFont-Fallback';
- src: local('Arial');
- size-adjust: 105%; /* Scale to match x-height */
- ascent-override: 90%; /* Match ascender height */
- descent-override: 20%; /* Match descender depth */
- line-gap-override: 10%; /* Match line spacing */
-}
-
-body {
- font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
-}
-```
-
-Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
-
-**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
-
-**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
-
-**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
-
-## Modern Web Typography
-
-### Fluid Type
-
-Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
-
-**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
-
-**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
-
-**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
-
-**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
-
-### OpenType Features
-
-Most developers don't know these exist. Use them for polish:
-
-```css
-/* Tabular numbers for data alignment */
-.data-table { font-variant-numeric: tabular-nums; }
-
-/* Proper fractions */
-.recipe-amount { font-variant-numeric: diagonal-fractions; }
-
-/* Small caps for abbreviations */
-abbr { font-variant-caps: all-small-caps; }
-
-/* Disable ligatures in code */
-code { font-variant-ligatures: none; }
-
-/* Enable kerning (usually on by default, but be explicit) */
-body { font-kerning: normal; }
-```
-
-Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
-
-### Rendering polish
-
-```css
-/* Even out heading line lengths (browser picks better break points) */
-h1, h2, h3 { text-wrap: balance; }
-
-/* Reduce orphans and ragged endings in long prose */
-article p { text-wrap: pretty; }
-
-/* Variable fonts: pick the right optical-size master automatically */
-body { font-optical-sizing: auto; }
-```
-
-**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
-
-## Typography System Architecture
-
-Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
-
-## Accessibility Considerations
-
-Beyond contrast ratios (which are well-documented), consider:
-
-- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
-- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
-- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
-- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
-
----
-
-**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
@@ -1,107 +0,0 @@
-# UX Writing
-
-## The Button Label Problem
-
-**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
-
-| Bad | Good | Why |
-|-----|------|-----|
-| OK | Save changes | Says what will happen |
-| Submit | Create account | Outcome-focused |
-| Yes | Delete message | Confirms the action |
-| Cancel | Keep editing | Clarifies what "cancel" means |
-| Click here | Download PDF | Describes the destination |
-
-**For destructive actions**, name the destruction:
-- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
-- "Delete 5 items" not "Delete selected" (show the count)
-
-## Error Messages: The Formula
-
-Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
-
-### Error Message Templates
-
-| Situation | Template |
-|-----------|----------|
-| **Format error** | "[Field] needs to be [format]. Example: [example]" |
-| **Missing required** | "Please enter [what's missing]" |
-| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
-| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
-| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
-
-### Don't Blame the User
-
-Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
-
-## Empty States Are Opportunities
-
-Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
-
-## Voice vs Tone
-
-**Voice** is your brand's personality, consistent everywhere.
-**Tone** adapts to the moment.
-
-| Moment | Tone Shift |
-|--------|------------|
-| Success | Celebratory, brief: "Done! Your changes are live." |
-| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
-| Loading | Reassuring: "Saving your work..." |
-| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
-
-**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
-
-## Writing for Accessibility
-
-**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
-
-## Writing for Translation
-
-### Plan for Expansion
-
-German text is ~30% longer than English. Allocate space:
-
-| Language | Expansion |
-|----------|-----------|
-| German | +30% |
-| French | +20% |
-| Finnish | +30-40% |
-| Chinese | -30% (fewer chars, but same width) |
-
-### Translation-Friendly Patterns
-
-Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
-
-## Consistency: The Terminology Problem
-
-Pick one term and stick with it:
-
-| Inconsistent | Consistent |
-|--------------|------------|
-| Delete / Remove / Trash | Delete |
-| Settings / Preferences / Options | Settings |
-| Sign in / Log in / Enter | Sign in |
-| Create / Add / New | Create |
-
-Build a terminology glossary and enforce it. Variety creates confusion.
-
-## Avoid Redundant Copy
-
-If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
-
-## Loading States
-
-Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
-
-## Confirmation Dialogs: Use Sparingly
-
-Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
-
-## Form Instructions
-
-Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
-
----
-
-**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
@@ -1,284 +0,0 @@
-#!/usr/bin/env node
-/**
- * Cleans up deprecated Impeccable skill files, symlinks, and
- * skills-lock.json entries left over from previous versions.
- *
- * Safe to run repeatedly -- it is a no-op when nothing needs cleaning.
- *
- * Usage (from the project root):
- * node {{scripts_path}}/cleanup-deprecated.mjs
- *
- * What it does:
- * 1. Finds every harness-specific skills directory (.claude/skills,
- * .cursor/skills, .agents/skills, etc.).
- * 2. For each deprecated skill name (with and without i- prefix),
- * checks if the directory exists and its SKILL.md mentions
- * "impeccable" (to avoid deleting unrelated user skills).
- * 3. Deletes confirmed matches (files, directories, or symlinks).
- * 4. Removes the corresponding entries from skills-lock.json.
- */
-
-import { existsSync, readFileSync, writeFileSync, rmSync, readdirSync, statSync, lstatSync, unlinkSync } from 'node:fs';
-import { join, resolve } from 'node:path';
-
-// Skills that were renamed, merged, or folded in v2.0, v2.1, and v3.0.
-const DEPRECATED_NAMES = [
- // v2.0 renames
- 'frontend-design', // renamed to impeccable
- 'teach-impeccable', // folded into /impeccable teach
- // v2.1 merges
- 'arrange', // renamed to layout
- 'normalize', // merged into polish
- 'onboard', // merged into harden
- 'extract', // merged into /impeccable extract
- // v3.0 consolidation: all standalone skills -> /impeccable sub-commands
- 'adapt',
- 'animate',
- 'audit',
- 'bolder',
- 'clarify',
- 'colorize',
- 'critique',
- 'delight',
- 'distill',
- 'harden',
- 'layout',
- 'optimize',
- 'overdrive',
- 'polish',
- 'quieter',
- 'shape',
- 'typeset',
-];
-
-// All known harness directories that may contain a skills/ subfolder.
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Per-skill fingerprints for SKILL.md bodies that never mentioned
-// "impeccable" in their v2.x source. Used as a last-resort match
-// when no skills-lock.json exists and the word heuristic fails.
-// The strings are lifted verbatim from the v2.x frontmatter
-// descriptions, so collisions with hand-written user skills are
-// vanishingly unlikely.
-const SKILL_FINGERPRINTS = {
- harden: 'Make interfaces production-ready: error handling, empty states',
- optimize: 'Diagnoses and fixes UI performance across loading speed',
-};
-
-/**
- * Walk up from startDir until we find a directory that looks like a
- * project root (has package.json, .git, or skills-lock.json).
- */
-export function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- const { root } = { root: '/' };
- while (dir !== root) {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Load skills-lock.json from the project root, or null if missing/unreadable.
- */
-export function loadLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return null;
- try {
- return JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return null;
- }
-}
-
-/**
- * Check whether a skill directory belongs to Impeccable. Three layered
- * signals, in order of reliability:
- * 1. Lock source equals "pbakaus/impeccable" (authoritative).
- * 2. SKILL.md body contains the word "impeccable".
- * 3. SKILL.md body contains a per-skill fingerprint (for harden and
- * optimize, whose v2.x SKILL.md never mentioned the pack name).
- */
-export function isImpeccableSkill(skillDir, { skillName, lock } = {}) {
- // 1. Authoritative: the lock file claims this skill is ours.
- if (skillName && lock?.skills?.[skillName]?.source === 'pbakaus/impeccable') {
- return true;
- }
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) return false;
- let content;
- try {
- content = readFileSync(skillMd, 'utf-8');
- } catch {
- return false;
- }
- // 2. Word-level content heuristic.
- if (/impeccable/i.test(content)) return true;
- // 3. Per-skill fingerprint for old skills that never mentioned the pack.
- // Strip the i- prefix so both `harden` and `i-harden` resolve to the
- // same fingerprint entry.
- const unprefixed = skillName?.startsWith('i-') ? skillName.slice(2) : skillName;
- const fingerprint = unprefixed && SKILL_FINGERPRINTS[unprefixed];
- if (fingerprint && content.includes(fingerprint)) return true;
- return false;
-}
-
-/**
- * Build the full list of names to check: each deprecated name, plus
- * its i-prefixed variant.
- */
-export function buildTargetNames() {
- const names = [];
- for (const name of DEPRECATED_NAMES) {
- names.push(name);
- names.push(`i-${name}`);
- }
- return names;
-}
-
-/**
- * Find every skills directory across all harness dirs in the project.
- * Returns absolute paths that exist on disk.
- */
-export function findSkillsDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const candidate = join(projectRoot, harness, 'skills');
- if (existsSync(candidate)) {
- dirs.push(candidate);
- }
- }
- return dirs;
-}
-
-/**
- * Remove deprecated skill directories/symlinks from all harness dirs.
- * Reads skills-lock.json so the authoritative "source" field can
- * drive deletion even when SKILL.md never mentions impeccable.
- * Returns an array of paths that were deleted.
- */
-export function removeDeprecatedSkills(projectRoot, lock) {
- if (lock === undefined) lock = loadLock(projectRoot);
- const targets = buildTargetNames();
- const skillsDirs = findSkillsDirs(projectRoot);
- const deleted = [];
-
- for (const skillsDir of skillsDirs) {
- for (const name of targets) {
- const skillPath = join(skillsDir, name);
-
- // Use lstat to detect symlinks (existsSync follows symlinks and
- // returns false for dangling ones).
- let stat;
- try {
- stat = lstatSync(skillPath);
- } catch {
- continue; // does not exist at all
- }
-
- if (stat.isSymbolicLink()) {
- // Symlink: check the target if it's alive, otherwise treat
- // dangling symlinks to deprecated names as safe to remove.
- const targetAlive = existsSync(skillPath);
- const isMatch = targetAlive
- ? isImpeccableSkill(skillPath, { skillName: name, lock })
- : true;
- if (isMatch) {
- unlinkSync(skillPath);
- deleted.push(skillPath);
- }
- continue;
- }
-
- // Regular directory -- verify it belongs to impeccable
- if (isImpeccableSkill(skillPath, { skillName: name, lock })) {
- rmSync(skillPath, { recursive: true, force: true });
- deleted.push(skillPath);
- }
- }
- }
-
- return deleted;
-}
-
-/**
- * Remove deprecated entries from skills-lock.json.
- * Only removes entries whose source is "pbakaus/impeccable".
- * Returns the list of removed skill names.
- */
-export function cleanSkillsLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return [];
-
- let lock;
- try {
- lock = JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return [];
- }
-
- if (!lock.skills || typeof lock.skills !== 'object') return [];
-
- const targets = buildTargetNames();
- const removed = [];
-
- for (const name of targets) {
- const entry = lock.skills[name];
- if (!entry) continue;
- // Only remove if it belongs to impeccable
- if (entry.source === 'pbakaus/impeccable') {
- delete lock.skills[name];
- removed.push(name);
- }
- }
-
- if (removed.length > 0) {
- writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\n', 'utf-8');
- }
-
- return removed;
-}
-
-/**
- * Run the full cleanup. Returns a summary object.
- *
- * Order matters: read the lock and delete directories first, then
- * strip lock entries. Otherwise the authoritative signal is gone by
- * the time directory deletion runs.
- */
-export function cleanup(projectRoot) {
- const root = projectRoot || findProjectRoot();
- const lock = loadLock(root);
- const deletedPaths = removeDeprecatedSkills(root, lock);
- const removedLockEntries = cleanSkillsLock(root);
- return { deletedPaths, removedLockEntries, projectRoot: root };
-}
-
-// CLI entry point
-if (process.argv[1] && resolve(process.argv[1]) === resolve(new URL(import.meta.url).pathname)) {
- const result = cleanup();
- if (result.deletedPaths.length === 0 && result.removedLockEntries.length === 0) {
- console.log('No deprecated Impeccable skills found. Nothing to clean up.');
- } else {
- if (result.deletedPaths.length > 0) {
- console.log(`Removed ${result.deletedPaths.length} deprecated skill(s):`);
- for (const p of result.deletedPaths) console.log(` - ${p}`);
- }
- if (result.removedLockEntries.length > 0) {
- console.log(`Cleaned ${result.removedLockEntries.length} entry/entries from skills-lock.json:`);
- for (const name of result.removedLockEntries) console.log(` - ${name}`);
- }
- }
-}
@@ -1,94 +0,0 @@
-{
- "craft": {
- "description": "Full confirmed-brief-then-build flow. Runs multi-round shape discovery first, resolves visual probe and north-star mock gates when available, then builds and visually iterates. Use when building a new feature end-to-end.",
- "argumentHint": "[feature description]"
- },
- "teach": {
- "description": "Gathers design context for a project. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles) and, when code exists to analyze, DESIGN.md (visual: colors, typography, components). Every other command reads these files before doing work. Use once per project.",
- "argumentHint": ""
- },
- "document": {
- "description": "Generate a DESIGN.md file that captures the current visual design system. Auto-extracts colors, typography, spacing, radii, and component patterns from the codebase, then asks the user to confirm descriptive language for atmosphere and color character. Follows the Google Stitch DESIGN.md format so the file is tool-compatible. Use when you need a visual design spec an AI agent can follow to stay on-brand.",
- "argumentHint": ""
- },
- "extract": {
- "description": "Pull reusable patterns, components, and design tokens into the design system. Identifies repeated patterns and consolidates them. Use when you have drift across the codebase and want to bring things back to a consistent system.",
- "argumentHint": "[target]"
- },
- "live": {
- "description": "Interactive live variant mode. Select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via HMR. Requires a running dev server. Use when you want to visually experiment with design alternatives in real time.",
- "argumentHint": ""
- },
- "adapt": {
- "description": "Adapt designs to work across different screen sizes, devices, contexts, or platforms. Implements breakpoints, fluid layouts, and touch targets. Use when the user mentions responsive design, mobile layouts, breakpoints, viewport adaptation, or cross-device compatibility.",
- "argumentHint": "[target] [context (mobile, tablet, print...)]"
- },
- "animate": {
- "description": "Review a feature and enhance it with purposeful animations, micro-interactions, and motion effects that improve usability and delight. Use when the user mentions adding animation, transitions, micro-interactions, motion design, hover effects, or making the UI feel more alive.",
- "argumentHint": "[target]"
- },
- "audit": {
- "description": "Run technical quality checks across accessibility, performance, theming, responsive design, and anti-patterns. Generates a scored report with P0-P3 severity ratings and actionable plan. Use when the user wants an accessibility check, performance audit, or technical quality review.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "bolder": {
- "description": "Amplify safe or boring designs to make them more visually interesting and stimulating. Increases impact while maintaining usability. Use when the user says the design looks bland, generic, too safe, lacks personality, or wants more visual impact and character.",
- "argumentHint": "[target]"
- },
- "clarify": {
- "description": "Improve unclear UX copy, error messages, microcopy, labels, and instructions to make interfaces easier to understand. Use when the user mentions confusing text, unclear labels, bad error messages, hard-to-follow instructions, or wanting better UX writing.",
- "argumentHint": "[target]"
- },
- "colorize": {
- "description": "Add strategic color to features that are too monochromatic or lack visual interest, making interfaces more engaging and expressive. Use when the user mentions the design looking gray, dull, lacking warmth, needing more color, or wanting a more vibrant or expressive palette.",
- "argumentHint": "[target]"
- },
- "critique": {
- "description": "Evaluate design from a UX perspective, assessing visual hierarchy, information architecture, emotional resonance, cognitive load, and overall quality with quantitative scoring, persona-based testing, automated anti-pattern detection, and actionable feedback. Use when the user asks to review, critique, evaluate, or give feedback on a design or component.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "delight": {
- "description": "Add moments of joy, personality, and unexpected touches that make interfaces memorable and enjoyable to use. Elevates functional to delightful. Use when the user asks to add polish, personality, animations, micro-interactions, delight, or make an interface feel fun or memorable.",
- "argumentHint": "[target]"
- },
- "distill": {
- "description": "Strip designs to their essence by removing unnecessary complexity. Great design is simple, powerful, and clean. Use when the user asks to simplify, declutter, reduce noise, remove elements, or make a UI cleaner and more focused.",
- "argumentHint": "[target]"
- },
- "harden": {
- "description": "Make interfaces production-ready: error handling, i18n, text overflow, edge case management, and resilience under real-world data. Use when the user asks to harden, make production-ready, handle edge cases, add error states, or fix overflow and i18n issues.",
- "argumentHint": "[target]"
- },
- "onboard": {
- "description": "Design onboarding flows, first-run experiences, and empty states that guide new users to value. Covers welcome screens, account setup, progressive disclosure, contextual tooltips, feature announcements, and activation moments. Use when the user mentions onboarding, first-time users, empty states, activation, getting started, new user flows, or the aha moment.",
- "argumentHint": "[target]"
- },
- "layout": {
- "description": "Improve layout, spacing, and visual rhythm. Fixes monotonous grids, inconsistent spacing, and weak visual hierarchy. Use when the user mentions layout feeling off, spacing issues, visual hierarchy, crowded UI, alignment problems, or wanting better composition.",
- "argumentHint": "[target]"
- },
- "optimize": {
- "description": "Diagnoses and fixes UI performance across loading speed, rendering, animations, images, and bundle size. Use when the user mentions slow, laggy, janky, performance, bundle size, load time, or wants a faster, smoother experience.",
- "argumentHint": "[target]"
- },
- "overdrive": {
- "description": "Pushes interfaces past conventional limits with technically ambitious implementations — shaders, spring physics, scroll-driven reveals, 60fps animations. Use when the user wants to wow, impress, go all-out, or make something that feels extraordinary.",
- "argumentHint": "[target]"
- },
- "polish": {
- "description": "Performs a final quality pass fixing alignment, spacing, consistency, and micro-detail issues before shipping. Use when the user mentions polish, finishing touches, pre-launch review, something looks off, or wants to go from good to great.",
- "argumentHint": "[target]"
- },
- "quieter": {
- "description": "Tones down visually aggressive or overstimulating designs, reducing intensity while preserving quality. Use when the user mentions too bold, too loud, overwhelming, aggressive, garish, or wants a calmer, more refined aesthetic.",
- "argumentHint": "[target]"
- },
- "shape": {
- "description": "Plan UX and UI before code. Runs a required multi-round discovery interview, uses visual probes when available, and produces a user-confirmed design brief for implementation.",
- "argumentHint": "[feature to shape]"
- },
- "typeset": {
- "description": "Improves typography by fixing font choices, hierarchy, sizing, weight, and readability so text feels intentional. Use when the user mentions fonts, type, readability, text hierarchy, sizing looks off, or wants more polished, intentional typography.",
- "argumentHint": "[target]"
- }
-}
@@ -1,242 +0,0 @@
-#!/usr/bin/env node
-/**
- * Critique persistence helper.
- *
- * Each run of /impeccable critique writes a per-target snapshot to
- * .impeccable/critique/<timestamp>__<slug>.md
- * with a small YAML frontmatter carrying the score + P0/P1 counts.
- *
- * /impeccable polish reads the latest matching snapshot at start as its
- * fix backlog. No other skill auto-reads critique output.
- *
- * The slug is derived mechanically from the *resolved* primary artifact
- * (file path or URL), never from the user's natural-language phrasing.
- * Slug stability across runs is what lets the trend display work.
- *
- * CLI entry points (called from skill instructions):
- * node critique-storage.mjs slug <resolved-target>
- * node critique-storage.mjs write <slug> <snapshot-body-file>
- * node critique-storage.mjs latest <slug>
- * node critique-storage.mjs trend <slug> [limit]
- *
- * Note: there is intentionally no `ignore` subcommand. ignore.md is a plain
- * markdown file; the model reads it directly with its file-read tool. This
- * helper only exists for operations the model can't trivially do inline
- * (normalizing paths, generating filenames, globbing + parsing frontmatter).
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath, pathToFileURL } from 'node:url';
-import { getCritiqueDir } from './impeccable-paths.mjs';
-
-const SLUG_MAX = 50;
-
-/**
- * Mechanically derive a slug from a resolved target. Returns null if the
- * input doesn't look like a stable identifier (empty, project root, etc).
- *
- * Accepts file paths and URLs. The model resolves "the homepage" to a
- * concrete artifact before calling this — we never slug a natural-language
- * phrase.
- */
-export function slugFromTarget(resolved, { cwd = process.cwd() } = {}) {
- if (!resolved || typeof resolved !== 'string') return null;
- const trimmed = resolved.trim();
- if (!trimmed) return null;
-
- // URL
- if (/^https?:\/\//i.test(trimmed)) {
- let url;
- try { url = new URL(trimmed); } catch { return null; }
- const hostPath = `${url.hostname}${url.pathname}`;
- return kebab(hostPath);
- }
-
- // File path. Make it project-relative so two devs critiquing the same
- // checkout get the same slug regardless of where their repo is cloned.
- const abs = path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- let rel = path.relative(cwd, abs);
- // If the target is outside cwd, fall back to the basename so we still
- // produce a stable slug (vs the absolute path, which would include
- // home dirs / usernames).
- if (rel.startsWith('..') || path.isAbsolute(rel)) {
- rel = path.basename(abs);
- }
- if (!rel || rel === '.' || rel === '') return null;
- return kebab(rel);
-}
-
-function kebab(s) {
- const slug = s
- .toLowerCase()
- .replace(/[/\\.]+/g, '-')
- .replace(/[^a-z0-9-]+/g, '-')
- .replace(/-+/g, '-')
- .replace(/^-|-$/g, '');
- if (!slug) return null;
- // Cap from the tail — the tail (filename) is more identifying than the
- // top-level directory.
- return slug.length <= SLUG_MAX ? slug : slug.slice(slug.length - SLUG_MAX).replace(/^-/, '');
-}
-
-/**
- * Filename-safe UTC ISO timestamp: hyphens for separators, trailing Z.
- * Plain colons aren't allowed on Windows filesystems.
- */
-export function nowFilenameStamp(date = new Date()) {
- const iso = date.toISOString(); // 2026-05-12T18:30:00.123Z
- return iso.replace(/[:.]/g, '-').replace(/-\d+Z$/, 'Z');
-}
-
-/**
- * Write a snapshot for `slug`. `meta` carries the small structured frontmatter
- * keys read back by readTrend(). `body` is the human-readable critique
- * report (everything below the frontmatter).
- *
- * Returns the absolute path written.
- */
-export function writeSnapshot({ slug, meta, body, cwd = process.cwd(), now = new Date() }) {
- if (!slug) throw new Error('writeSnapshot requires a slug');
- const dir = getCritiqueDir(cwd);
- fs.mkdirSync(dir, { recursive: true });
- const timestamp = nowFilenameStamp(now);
- const filePath = path.join(dir, `${timestamp}__${slug}.md`);
- // Spread `meta` first so internally computed `timestamp` and `slug`
- // always win. Otherwise a caller-supplied meta blob (parsed from the
- // IMPECCABLE_CRITIQUE_META env var) could clobber them, leaving the
- // filename in disagreement with its frontmatter and corrupting trends.
- const front = serializeFrontmatter({ ...meta, timestamp, slug });
- fs.writeFileSync(filePath, `${front}\n${body.trim()}\n`, 'utf-8');
- return filePath;
-}
-
-function serializeFrontmatter(obj) {
- const lines = ['---'];
- for (const [key, value] of Object.entries(obj)) {
- if (value === undefined || value === null) continue;
- const str = typeof value === 'string' ? value : String(value);
- // Quote strings that contain : or # to keep parsing simple.
- const needsQuotes = typeof value === 'string' && /[:#]/.test(str);
- lines.push(`${key}: ${needsQuotes ? JSON.stringify(str) : str}`);
- }
- lines.push('---');
- return lines.join('\n');
-}
-
-function parseFrontmatter(text) {
- const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
- if (!match) return {};
- const out = {};
- for (const line of match[1].split(/\r?\n/)) {
- const colon = line.indexOf(':');
- if (colon < 0) continue;
- const key = line.slice(0, colon).trim();
- let value = line.slice(colon + 1).trim();
- if (/^".*"$/.test(value)) {
- try { value = JSON.parse(value); } catch { /* leave as-is */ }
- } else if (/^-?\d+$/.test(value)) {
- value = Number(value);
- }
- out[key] = value;
- }
- return out;
-}
-
-/**
- * Return all snapshot files for `slug`, sorted oldest → newest.
- */
-function listSnapshotsForSlug(slug, cwd) {
- const dir = getCritiqueDir(cwd);
- if (!fs.existsSync(dir)) return [];
- const suffix = `__${slug}.md`;
- return fs.readdirSync(dir)
- .filter((f) => f.endsWith(suffix))
- .sort()
- .map((f) => path.join(dir, f));
-}
-
-/**
- * Return the most recent snapshot for `slug`, or null. Polish reads this
- * to find its fix backlog when the slug matches.
- */
-export function readLatestSnapshot(slug, { cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- if (!all.length) return null;
- const latest = all[all.length - 1];
- const body = fs.readFileSync(latest, 'utf-8');
- return { path: latest, body, meta: parseFrontmatter(body) };
-}
-
-/**
- * Return the last `limit` snapshots' frontmatter, oldest → newest.
- * Critique appends a one-line trend to its output using this.
- */
-export function readTrend(slug, { limit = 5, cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- const slice = all.slice(-limit);
- return slice.map((file) => parseFrontmatter(fs.readFileSync(file, 'utf-8')));
-}
-
-// ---- CLI ---------------------------------------------------------------
-
-function main(argv) {
- const [cmd, ...args] = argv;
- switch (cmd) {
- case 'slug': {
- const slug = slugFromTarget(args[0]);
- if (!slug) { process.stderr.write('no stable slug for input\n'); process.exit(1); }
- process.stdout.write(`${slug}\n`);
- return;
- }
- case 'write': {
- const [slug, bodyFile] = args;
- if (!slug || !bodyFile) { process.stderr.write('usage: write <slug> <body-file>\n'); process.exit(1); }
- const raw = fs.readFileSync(bodyFile, 'utf-8');
- // The body file may be a full report. The caller passes the meta as
- // a JSON object on stdin if it wants structured frontmatter; otherwise
- // we write with minimal metadata.
- let meta = {};
- const metaArg = process.env.IMPECCABLE_CRITIQUE_META;
- if (metaArg) {
- try { meta = JSON.parse(metaArg); } catch { /* ignore */ }
- }
- const out = writeSnapshot({ slug, meta, body: raw });
- process.stdout.write(`${out}\n`);
- return;
- }
- case 'latest': {
- const latest = readLatestSnapshot(args[0]);
- if (!latest) { process.exit(2); }
- process.stdout.write(latest.body);
- return;
- }
- case 'trend': {
- const rows = readTrend(args[0], { limit: args[1] ? Number(args[1]) : 5 });
- process.stdout.write(JSON.stringify(rows, null, 2) + '\n');
- return;
- }
- default:
- process.stderr.write('usage: critique-storage.mjs <slug|write|latest|trend> [args]\n');
- process.exit(1);
- }
-}
-
-function isMainModule() {
- if (!process.argv[1]) return false;
- try {
- return fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1]);
- } catch {
- // pathToFileURL normalizes Windows paths; keep it as a fallback for any
- // environment where realpath is unavailable.
- return import.meta.url === pathToFileURL(process.argv[1]).href;
- }
-}
-
-// Why the realpath check: generated skills are often reached through symlinked
-// harness directories (for example a demo repo's `.agents` -> source `.agents`).
-// Node resolves import.meta.url to the real file, while process.argv[1] keeps
-// the symlink path. Comparing canonical paths prevents a silent exit-0 no-op.
-if (isMainModule()) {
- main(process.argv.slice(2));
-}
@@ -1,820 +0,0 @@
-// Parse a DESIGN.md (Stitch-spec format) into a structured JSON model that
-// the live-mode design-system panel can render. Deterministic, dependency-free.
-//
-// Two-layer: YAML frontmatter (machine-readable tokens) + markdown body
-// (prose with six canonical H2 sections). When frontmatter is present, it's
-// exposed on `model.frontmatter` alongside the prose-scraped sections;
-// consumers can prefer frontmatter values and fall back to prose.
-
-const CANONICAL_SECTIONS = [
- 'Overview',
- 'Colors',
- 'Typography',
- 'Elevation',
- 'Components',
- "Do's and Don'ts",
-];
-
-// ---------- Frontmatter (Stitch YAML subset) ----------
-
-function parseFrontmatter(md) {
- const lines = md.split(/\r?\n/);
- if (lines[0]?.trim() !== '---') return { frontmatter: null, body: md };
-
- let end = -1;
- for (let i = 1; i < lines.length; i++) {
- if (lines[i].trim() === '---') { end = i; break; }
- }
- if (end === -1) return { frontmatter: null, body: md };
-
- const yaml = lines.slice(1, end).join('\n');
- const body = lines.slice(end + 1).join('\n');
- try {
- return { frontmatter: parseYamlSubset(yaml), body };
- } catch {
- return { frontmatter: null, body: md };
- }
-}
-
-// Minimal YAML reader for the Stitch frontmatter subset: scalar maps with
-// one level of nested objects (typography roles, components). Indent-based,
-// 2-space convention. No arrays, no anchors, no multi-line scalars — Stitch's
-// schema doesn't need them and accepting them would require a real YAML
-// dependency we don't want to vendor.
-function parseYamlSubset(yaml) {
- const lines = yaml.split(/\r?\n/);
- const root = {};
- const stack = [{ indent: -1, obj: root }];
-
- for (const raw of lines) {
- // Skip blanks and line-only comments. Don't strip inline comments:
- // unquoted hex values start with `#` and can't be safely distinguished
- // from a comment after whitespace.
- if (!raw.trim() || /^\s*#/.test(raw)) continue;
-
- const indent = raw.match(/^\s*/)[0].length;
- const content = raw.slice(indent);
-
- const colonIdx = findTopLevelColon(content);
- if (colonIdx === -1) continue;
-
- while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
- stack.pop();
- }
-
- const key = content.slice(0, colonIdx).trim();
- const rest = content.slice(colonIdx + 1).trim();
- const parent = stack[stack.length - 1].obj;
-
- if (rest === '') {
- const obj = {};
- parent[key] = obj;
- stack.push({ indent, obj });
- } else {
- parent[key] = parseScalar(rest);
- }
- }
-
- return root;
-}
-
-function findTopLevelColon(s) {
- let inQuote = null;
- for (let i = 0; i < s.length; i++) {
- const ch = s[i];
- if (inQuote) {
- if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
- } else if (ch === '"' || ch === "'") {
- inQuote = ch;
- } else if (ch === ':') {
- return i;
- }
- }
- return -1;
-}
-
-function parseScalar(raw) {
- const s = raw.trim();
- if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
- return s.slice(1, -1);
- }
- if (s === 'true') return true;
- if (s === 'false') return false;
- if (s === 'null' || s === '~') return null;
- if (/^-?\d+$/.test(s)) return Number(s);
- if (/^-?\d*\.\d+$/.test(s)) return Number(s);
- return s;
-}
-
-const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
-const OKLCH_RE = /oklch\([^)]+\)/gi;
-const RGBA_RE = /rgba?\([^)]+\)/gi;
-const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
-const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
-
-// ---------- Section splitting ----------
-
-function splitSections(md) {
- const lines = md.split(/\r?\n/);
- let title = null;
- const sections = {};
- let current = null;
-
- for (const raw of lines) {
- const line = raw.trimEnd();
-
- if (!title && line.startsWith('# ') && !line.startsWith('## ')) {
- title = line.replace(/^#\s+/, '').trim();
- continue;
- }
-
- const h2 = line.match(/^##\s+(?:\d+\.\s*)?([^:\n]+?)(?::\s*(.+))?$/);
- if (h2) {
- const rawName = normalizeApostrophes(h2[1].trim());
- const subtitle = h2[2] ? h2[2].trim() : null;
- const canonical = matchCanonicalSection(rawName);
- if (canonical) {
- current = { name: canonical, subtitle, lines: [] };
- sections[canonical] = current;
- continue;
- }
- // non-canonical H2 — ignore but stop feeding into current
- current = null;
- continue;
- }
-
- if (current) current.lines.push(raw);
- }
-
- return { title, sections };
-}
-
-function normalizeApostrophes(s) {
- return s.replace(/[\u2018\u2019]/g, "'");
-}
-
-function matchCanonicalSection(name) {
- const normalized = normalizeApostrophes(name).toLowerCase();
- // Exact match first
- for (const c of CANONICAL_SECTIONS) {
- if (normalizeApostrophes(c).toLowerCase() === normalized) return c;
- }
- // Keyword-contained match: "Overview & Creative North Star" -> "Overview",
- // "Elevation & Depth" -> "Elevation", etc.
- for (const c of CANONICAL_SECTIONS) {
- const key = normalizeApostrophes(c).toLowerCase();
- const pattern = new RegExp(`\\b${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
- if (pattern.test(normalized)) return c;
- }
- return null;
-}
-
-// ---------- Subsection splitting (inside a canonical section) ----------
-
-function splitSubsections(lines) {
- const subs = [];
- let current = { name: null, lines: [] };
- subs.push(current);
-
- for (const raw of lines) {
- const h3 = raw.match(/^###\s+(.+?)\s*$/);
- if (h3) {
- current = { name: h3[1].trim(), lines: [] };
- subs.push(current);
- continue;
- }
- current.lines.push(raw);
- }
-
- return subs;
-}
-
-// ---------- Generic helpers ----------
-
-function collectParagraphs(lines) {
- const paragraphs = [];
- let buf = [];
- const flush = () => {
- if (buf.length) {
- paragraphs.push(buf.join(' ').trim());
- buf = [];
- }
- };
- for (const raw of lines) {
- const trimmed = raw.trim();
- if (trimmed === '') { flush(); continue; }
- // Horizontal rules (---, ***) and headings/bullets end a paragraph.
- if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { flush(); continue; }
- if (raw.startsWith('#') || raw.match(/^[-*]\s/)) { flush(); continue; }
- buf.push(trimmed);
- }
- flush();
- return paragraphs.filter(Boolean);
-}
-
-function collectBullets(lines) {
- const bullets = [];
- let current = null;
- for (const raw of lines) {
- const m = raw.match(/^\s*[-*]\s+(.+)$/);
- if (m) {
- if (current) bullets.push(current);
- current = m[1];
- continue;
- }
- // continuation of a bullet (indented line)
- if (current && raw.match(/^\s{2,}\S/)) {
- current += ' ' + raw.trim();
- continue;
- }
- // blank line ends a bullet
- if (raw.trim() === '' && current) {
- bullets.push(current);
- current = null;
- }
- }
- if (current) bullets.push(current);
- return bullets;
-}
-
-function stripBold(s) {
- return s.replace(/\*\*(.+?)\*\*/g, '$1');
-}
-
-function extractNamedRules(lines) {
- const rules = [];
- const seen = new Set();
-
- // Style A (Impeccable): "**The X Rule.** body body body" — can span lines.
- const joined = lines.join('\n');
- const inlineStart = /\*\*(The [^*]+?Rule)\.\*\*/g;
- const inlineMatches = [];
- let m;
- while ((m = inlineStart.exec(joined)) !== null) {
- inlineMatches.push({ name: m[1], start: m.index, end: inlineStart.lastIndex });
- }
- for (let i = 0; i < inlineMatches.length; i++) {
- const mm = inlineMatches[i];
- const bodyEnd = i + 1 < inlineMatches.length ? inlineMatches[i + 1].start : joined.length;
- const body = joined
- .slice(mm.end, bodyEnd)
- .replace(/\n##[^\n]*$/s, '')
- .replace(/\n###[^\n]*$/s, '')
- .trim();
- const name = stripBold(mm.name).trim();
- seen.add(name.toLowerCase());
- rules.push({ name, body: stripBold(body) });
- }
-
- // Style B (Stitch): `### The "X" Rule` or `### The X Fallback`, body is the
- // bullets/paragraphs until the next heading. Accept Rule / Fallback / Principle.
- for (let i = 0; i < lines.length; i++) {
- const h3 = lines[i].match(/^###\s+(.+?)\s*$/);
- if (!h3) continue;
- const headerName = stripBold(h3[1]).replace(/["“”]/g, '').trim();
- if (!/^The\b.*\b(Rule|Fallback|Principle)\b/i.test(headerName)) continue;
- if (seen.has(headerName.toLowerCase())) continue;
-
- const bodyLines = [];
- for (let j = i + 1; j < lines.length; j++) {
- if (/^##\s|^###\s/.test(lines[j])) break;
- bodyLines.push(lines[j]);
- }
- const body = stripBold(bodyLines.join('\n').replace(/\n+/g, ' ')).trim();
- if (body) {
- seen.add(headerName.toLowerCase());
- rules.push({ name: headerName, body });
- }
- }
-
- // Style C (Stitch bullet form): "* **The Layering Principle:** body"
- // Colon/period lives inside the bold, so match "**...**" then inspect.
- for (const b of collectBullets(lines)) {
- const mm = b.match(/^\*\*([^*]+?)\*\*\s*(.+)$/);
- if (!mm) continue;
- const nameRaw = mm[1].replace(/[.:]\s*$/, '').replace(/["“”]/g, '').trim();
- if (!/^The\b.+\b(Rule|Fallback|Principle)$/i.test(nameRaw)) continue;
- if (seen.has(nameRaw.toLowerCase())) continue;
- seen.add(nameRaw.toLowerCase());
- rules.push({ name: nameRaw, body: stripBold(mm[2]).trim() });
- }
-
- return rules;
-}
-
-// ---------- Per-section extractors ----------
-
-function extractOverview(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
- const northStar = text.match(/\*\*Creative North Star:\s*"([^"]+)"\*\*/);
- const keyChars = [];
- const keyCharMatch = text.match(/\*\*Key Characteristics:\*\*\s*\n([\s\S]+?)(?:\n##|\n###|$)/);
- if (keyCharMatch) {
- for (const line of keyCharMatch[1].split('\n')) {
- const m = line.match(/^\s*[-*]\s+(.+)$/);
- if (m) keyChars.push(stripBold(m[1].trim()));
- }
- }
-
- // Philosophy paragraphs: everything that isn't a rule header or key-char block
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) =>
- !p.startsWith('**Creative North Star') &&
- !p.startsWith('**Key Characteristics')
- );
-
- return {
- subtitle: section.subtitle,
- creativeNorthStar: northStar ? northStar[1] : null,
- philosophy: paragraphs,
- keyCharacteristics: keyChars,
- };
-}
-
-function extractColors(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ');
- const groups = [];
- const ROLE_KEYWORDS = /^(primary|secondary|tertiary|neutral|accent)\b/i;
-
- for (const sub of subs.slice(1)) {
- if (!sub.name || /Named Rules?/i.test(sub.name) || /^The\s/i.test(sub.name)) continue;
-
- const bullets = collectBullets(sub.lines);
- const parsed = bullets.map((b) => parseColorBullet(b)).filter(Boolean);
- if (parsed.length === 0) continue;
-
- // If every bullet starts with a role keyword (Primary/Secondary/...), promote
- // each bullet to its own group. Otherwise keep the subsection as the group.
- const allRoleBullets =
- parsed.length > 0 && parsed.every((p) => p.name && ROLE_KEYWORDS.test(p.name));
-
- if (allRoleBullets) {
- for (const p of parsed) {
- groups.push({ role: p.name, colors: [p] });
- }
- } else {
- groups.push({ role: sub.name, colors: parsed });
- }
- }
-
- // If the Colors section has no subsections at all (unlikely), fall back to
- // scanning the whole section as a flat bullet list.
- if (groups.length === 0) {
- const flat = collectBullets(section.lines)
- .map((b) => parseColorBullet(b))
- .filter(Boolean);
- if (flat.length) {
- for (const p of flat) {
- if (p.name && ROLE_KEYWORDS.test(p.name)) {
- groups.push({ role: p.name, colors: [p] });
- } else {
- const fallback = groups.find((g) => g.role === 'Palette');
- if (fallback) fallback.colors.push(p);
- else groups.push({ role: 'Palette', colors: [p] });
- }
- }
- }
- }
-
- return {
- subtitle: section.subtitle,
- description: description || null,
- groups,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function parseColorBullet(bullet) {
- const text = bullet.trim();
-
- // Case 1 (Impeccable): **Name** (value-with-maybe-nested-parens): description
- const bold = text.match(/^\*\*(.+?)\*\*\s*(.*)$/);
- if (bold && bold[2].startsWith('(')) {
- const value = extractParenGroup(bold[2]);
- if (value !== null) {
- const after = bold[2].slice(value.length + 2).trimStart();
- if (after.startsWith(':')) {
- return buildColor(bold[1], value, after.slice(1).trim());
- }
- }
- }
-
- // Case 2 (Stitch): **Name (values):** description — value embedded in bold.
- const stitch = text.match(/^\*\*([^*]+?)\s*\(([^)]+)\):\*\*\s*(.*)$/);
- if (stitch) {
- return buildColor(stitch[1].trim(), stitch[2], stitch[3]);
- }
-
- // Case 3: bullet without bold, just hex/oklch inside.
- const values = collectColorValues(text);
- if (values.length) {
- return buildColor(null, values.join(' to '), text);
- }
- return null;
-}
-
-function extractParenGroup(s) {
- if (s[0] !== '(') return null;
- let depth = 0;
- for (let i = 0; i < s.length; i++) {
- if (s[i] === '(') depth++;
- else if (s[i] === ')') {
- depth--;
- if (depth === 0) return s.slice(1, i);
- }
- }
- return null;
-}
-
-function buildColor(name, rawValue, description) {
- const values = collectColorValues(rawValue);
- const primary = values[0] ?? rawValue.trim();
- return {
- name: name ? stripBold(name).trim() : null,
- value: primary,
- valueRange: values.length > 1 ? values : null,
- format: detectFormat(primary),
- description: stripBold(description || '').trim() || null,
- };
-}
-
-function collectColorValues(s) {
- const out = [];
- s.replace(HEX_RE, (v) => {
- out.push(v);
- return v;
- });
- s.replace(OKLCH_RE, (v) => {
- out.push(v);
- return v;
- });
- return out;
-}
-
-function detectFormat(v) {
- if (!v) return 'unknown';
- if (v.startsWith('#')) return 'hex';
- if (/^oklch/i.test(v)) return 'oklch';
- if (/^rgb/i.test(v)) return 'rgb';
- return 'unknown';
-}
-
-function scanInlineColors(lines) {
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '');
- const color = parseColorBullet(trimmed);
- if (color) out.push(color);
- }
- return out;
-}
-
-function parseStitchInlineGroups(lines) {
- // Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
- // Each bullet IS its own role. Group them under the spoken role name.
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
- const m = trimmed.match(
- /^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
- );
- if (m) {
- const role = m[1];
- const color = buildColor(role, m[2], m[3]);
- out.push({ role, colors: [color] });
- }
- }
- return out;
-}
-
-function extractTypography(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
-
- const fonts = {};
- // Pattern A: **Display Font:** Family (with fallback)
- const fontLineRe = /\*\*([\w\s/]+?)Font:\*\*\s*([^\n(]+?)(?:\s*\(with\s+([^)]+)\))?\s*$/gm;
- let fm;
- while ((fm = fontLineRe.exec(text)) !== null) {
- const rawRole = fm[1].trim().toLowerCase().replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || 'display';
- fonts[role] = {
- family: fm[2].trim(),
- fallback: fm[3] ? fm[3].trim() : null,
- };
- }
-
- // Pattern B (Stitch): * **Display & Headlines (Noto Serif):** description
- if (Object.keys(fonts).length === 0) {
- const stitchRe = /\*\*([\w\s&/]+?)\s*\(([^)]+)\):\*\*\s*(.+)/g;
- let sm;
- while ((sm = stitchRe.exec(text)) !== null) {
- const rawRole = sm[1]
- .trim()
- .toLowerCase()
- .replace(/\s*&\s*/g, '-')
- .replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || rawRole;
- fonts[role] = { family: sm[2].trim(), fallback: null, purpose: sm[3].trim() };
- }
- }
-
- // Character paragraph — either a **Character:** label, or fall back to the
- // first free paragraph under the section header (Stitch style).
- const characterMatch = text.match(/\*\*Character:\*\*\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\n|\n###|\n##|$)/);
- let character = characterMatch ? characterMatch[1].replace(/\n/g, ' ').trim() : null;
- if (!character) {
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) => !/^\*\*[\w\s/&]+Font/i.test(p) && !/^\*\*[\w\s/&]+\([^)]+\)/.test(p)
- );
- if (paragraphs.length) character = paragraphs[0];
- }
-
- // Hierarchy bullets under ### Hierarchy
- const subs = splitSubsections(section.lines);
- let hierarchy = [];
- const hierSub = subs.find((s) => s.name && /hierarch/i.test(s.name));
- if (hierSub) {
- const bullets = collectBullets(hierSub.lines);
- hierarchy = bullets.map(parseTypeBullet).filter(Boolean);
- }
-
- return {
- subtitle: section.subtitle,
- fonts,
- character,
- hierarchy,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function normalizeFontRole(raw) {
- // Canonical roles the panel cares about: display, body, label, mono.
- // Stitch often writes compound roles like "display-&-headlines" or "ui-&-body"
- // — collapse them to the first canonical role present.
- const tokens = raw.split(/[-/&\s]+/).filter(Boolean);
- const priority = ['display', 'headline', 'body', 'ui', 'label', 'mono'];
- const canonical = { headline: 'display', ui: 'body' };
- for (const p of priority) {
- if (tokens.includes(p)) return canonical[p] || p;
- }
- return null;
-}
-
-function parseTypeBullet(bullet) {
- // - **Display** (family, weight 300, italic, clamp(...), line-height 1): purpose
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(([^)]+)\):\s*(.*)$/);
- if (!m) return null;
- const name = m[1].trim();
- const specs = m[2].split(',').map((s) => s.trim());
- return {
- name,
- specs,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractElevation(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ') || null;
-
- const shadows = [];
- const seen = new Set();
- const dedupe = (entry) => {
- const key = (entry.name || '') + '::' + entry.value;
- if (seen.has(key)) return;
- seen.add(key);
- shadows.push(entry);
- };
-
- for (const b of collectBullets(section.lines)) {
- const parsed = parseShadowBullet(b);
- if (parsed) dedupe(parsed);
- }
-
- // Fallback: extract shadows written inline in prose. Stitch style is
- // "...use an extra-diffused shadow: `box-shadow: 0 12px 40px rgba(...)`."
- for (const p of collectParagraphs(section.lines)) {
- for (const inline of extractInlineShadows(p)) dedupe(inline);
- }
- for (const b of collectBullets(section.lines)) {
- for (const inline of extractInlineShadows(b)) dedupe(inline);
- }
-
- return {
- subtitle: section.subtitle,
- description,
- shadows,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function extractInlineShadows(text) {
- // Find `box-shadow: ...` anywhere in prose and capture the value. Work on the
- // raw string so it handles both backtick-fenced and unfenced variants.
- const out = [];
- const re = /box-shadow\s*:\s*([^`;\n]+)/gi;
- let m;
- while ((m = re.exec(text)) !== null) {
- const value = m[1].replace(/[`.)]+$/, '').trim();
- if (!value) continue;
- // Name heuristic: the noun immediately before the shadow phrase.
- // e.g. "an extra-diffused shadow: ..." -> "extra-diffused shadow"
- const before = text.slice(0, m.index);
- const nameMatch = before.match(/\b([A-Za-z][A-Za-z\- ]{2,40})\s+shadow\b[^A-Za-z0-9]*$/i);
- let name = null;
- if (nameMatch) {
- const stripped = nameMatch[1]
- .replace(/^(?:use|using|apply|applying|is|are|looks? like)\s+/i, '')
- .replace(/^(?:a|an|the)\s+/i, '')
- .trim();
- if (stripped) {
- name =
- stripped.charAt(0).toUpperCase() + stripped.slice(1) + ' shadow';
- }
- }
- out.push({
- name,
- value,
- purpose: null,
- });
- }
- return out;
-}
-
-function parseShadowBullet(bullet) {
- // - **Name** (`box-shadow: value`): purpose
- // - **Name** (`value`): purpose
- // Only accept if the paren content looks like a shadow value (contains px,
- // rem, rgba, or box-shadow). This filters out `**Rule Name:**` bullets.
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(`?([^`]+?)`?\):\s*(.*)$/);
- if (!m) return null;
- const rawValue = m[2].replace(/^box-shadow:\s*/i, '').trim();
- const looksLikeShadow =
- /box-shadow|rgba?\(|\bpx\b|\brem\b|^-?\d+\s/i.test(rawValue) &&
- /\d/.test(rawValue);
- if (!looksLikeShadow) return null;
- const name = stripBold(m[1]).trim();
- return {
- name,
- value: rawValue,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractComponents(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const components = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
-
- const bullets = collectBullets(sub.lines);
- const paragraphs = collectParagraphs(sub.lines);
-
- const variants = [];
- const properties = {};
-
- for (const b of bullets) {
- // - **Key:** value
- const m = b.match(/^\*\*(.+?):?\*\*:?\s*(.+)$/);
- if (m) {
- const key = stripBold(m[1]).trim();
- const value = stripBold(m[2]).trim();
- // Heuristic: "Primary", "Secondary", "Hover", "Focus" etc are variants;
- // "Shape", "Background", "Padding" are properties.
- if (/^(primary|secondary|tertiary|ghost|hover|focus|active|disabled|default|error|selected|unselected|state)$/i.test(key.split(/[\s/]/)[0])) {
- variants.push({ name: key, description: value });
- } else {
- properties[key.toLowerCase()] = value;
- }
- }
- }
-
- components.push({
- name: sub.name,
- description: paragraphs.join(' ') || null,
- properties,
- variants,
- });
- }
-
- return {
- subtitle: section.subtitle,
- components,
- };
-}
-
-function extractDosDonts(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const dos = [];
- const donts = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
- const subName = normalizeApostrophes(sub.name);
- const bullets = collectBullets(sub.lines).map((b) => stripBold(b).trim());
- if (/^do'?t?:?$/i.test(subName) || /^do:?$/i.test(subName)) {
- dos.push(...bullets);
- } else if (/^don'?t:?$/i.test(subName)) {
- donts.push(...bullets);
- }
- }
-
- // Classify by bullet prefix as a backup (catches loose bullets outside H3 wrappers)
- for (const b of collectBullets(section.lines)) {
- const stripped = normalizeApostrophes(stripBold(b).trim());
- if (/^don'?t\b/i.test(stripped)) {
- if (!donts.some((d) => normalizeApostrophes(d) === stripped)) donts.push(stripped);
- } else if (/^do\b/i.test(stripped)) {
- if (!dos.some((d) => normalizeApostrophes(d) === stripped)) dos.push(stripped);
- }
- }
-
- return { dos, donts };
-}
-
-// ---------- Coverage assessment ----------
-
-function assessCoverage(model) {
- const report = {};
-
- report.overview = model.overview
- ? {
- northStar: Boolean(model.overview.creativeNorthStar),
- philosophy: model.overview.philosophy.length > 0,
- keyCharacteristics: model.overview.keyCharacteristics.length,
- }
- : 'missing';
-
- report.colors = model.colors
- ? {
- groups: model.colors.groups.length,
- totalColors: model.colors.groups.reduce((n, g) => n + g.colors.length, 0),
- rules: model.colors.rules.length,
- }
- : 'missing';
-
- report.typography = model.typography
- ? {
- fonts: Object.keys(model.typography.fonts).length,
- hierarchyEntries: model.typography.hierarchy.length,
- character: Boolean(model.typography.character),
- rules: model.typography.rules.length,
- }
- : 'missing';
-
- report.elevation = model.elevation
- ? {
- shadows: model.elevation.shadows.length,
- rules: model.elevation.rules.length,
- description: Boolean(model.elevation.description),
- }
- : 'missing';
-
- report.components = model.components
- ? {
- count: model.components.components.length,
- variantTotal: model.components.components.reduce((n, c) => n + c.variants.length, 0),
- }
- : 'missing';
-
- report.dosDonts = model.dosDonts
- ? {
- dos: model.dosDonts.dos.length,
- donts: model.dosDonts.donts.length,
- }
- : 'missing';
-
- return report;
-}
-
-// ---------- Main ----------
-
-export function parseDesignMd(md) {
- const { frontmatter, body } = parseFrontmatter(md);
- const { title, sections } = splitSections(body);
- return {
- schemaVersion: 2,
- title,
- frontmatter,
- overview: extractOverview(sections['Overview']),
- colors: extractColors(sections['Colors']),
- typography: extractTypography(sections['Typography']),
- elevation: extractElevation(sections['Elevation']),
- components: extractComponents(sections['Components']),
- dosDonts: extractDosDonts(sections["Do's and Don'ts"]),
- };
-}
-
-export { assessCoverage };
@@ -1,198 +0,0 @@
-/**
- * Scan a project tree for Content-Security-Policy signals and classify the
- * shape so the agent knows which patch template to propose.
- *
- * Used at first-time `live.mjs` setup. Mechanical (grep-based) — no network,
- * no dev server, no JS evaluation. The classification drives a user-facing
- * consent prompt; the agent does the actual patch writing.
- *
- * Shapes are named by patch mechanism, not framework origin:
- * - "append-arrays": CSP defined as structured directive arrays. Patch
- * appends a dev-only localhost entry. Covers:
- * - Monorepo helpers with additional*Src options
- * (e.g. createBaseNextConfig for Next)
- * - SvelteKit kit.csp.directives
- * - nuxt-security module's contentSecurityPolicy
- * - "append-string": CSP built as a literal value string. Patch splices
- * a dev-only token into script-src and connect-src.
- * Covers:
- * - Inline Next.js headers() with CSP string
- * - Nuxt routeRules / nitro.routeRules CSP headers
- * - "middleware": CSP set dynamically in middleware.{ts,js}.
- * Detected but not auto-patched in v1.
- * - "meta-tag": <meta http-equiv="Content-Security-Policy"> in
- * layout files. Detected but not auto-patched in v1.
- * - null: no CSP signals found; no patch needed.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const SKIP_DIRS = new Set([
- 'node_modules',
- '.git',
- '.next',
- '.turbo',
- '.svelte-kit',
- '.nuxt',
- '.astro',
- 'dist',
- 'build',
- 'out',
- '.vercel',
-]);
-
-const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.tsx', '.jsx']);
-const LAYOUT_EXTS = new Set(['.tsx', '.jsx', '.astro', '.vue', '.svelte', '.html']);
-const MAX_DEPTH = 6;
-const MAX_READ_BYTES = 64 * 1024;
-
-// append-arrays signals: CSP expressed as structured directive arrays
-const MONOREPO_HELPER_SIGNALS = [
- /\bbuildCSPConfig\b/,
- /\bbuildSecurityHeaders\b/,
- /\badditionalScriptSrc\b/,
- /\badditionalConnectSrc\b/,
- /\bcreateBaseNextConfig\b/,
-];
-const SVELTEKIT_CSP_SIGNALS = [
- /\bkit\s*:/,
- /\bcsp\s*:/,
- /\bdirectives\s*:/,
-];
-const NUXT_SECURITY_SIGNALS = [
- /['"]nuxt-security['"]/,
- /\bcontentSecurityPolicy\b/,
-];
-
-// append-string signals: CSP written as a literal value string
-const INLINE_HEADER_SIGNALS = [
- /["']Content-Security-Policy["']/i,
- /\bscript-src\b/,
- /\bconnect-src\b/,
-];
-const NUXT_ROUTE_RULES_SIGNALS = [
- /\brouteRules\b/,
- /Content-Security-Policy/i,
- /\bscript-src\b/,
-];
-
-const MIDDLEWARE_HINT = /headers\.set\(\s*["']Content-Security-Policy["']/i;
-const META_TAG_HINT = /http-equiv\s*=\s*["']Content-Security-Policy["']/i;
-
-/**
- * @param {string} cwd Project root.
- * @returns {{ shape: string|null, signals: string[] }}
- */
-export function detectCsp(cwd = process.cwd()) {
- const hits = { appendArrays: [], appendString: [], middleware: [], metaTag: [] };
-
- walk(cwd, cwd, 0, (absPath, relPath, body) => {
- const ext = path.extname(absPath);
- const base = path.basename(absPath).toLowerCase();
- const isConfig = (name) =>
- new RegExp('(^|/)' + name + '\\.config\\.').test(relPath);
-
- // === append-arrays candidates ===
-
- // Monorepo CSP helper: packages/*/src/.../(config|security)/*
- if (SCAN_EXTS.has(ext) &&
- /packages\/[^/]+\/src\/.*(config|next-config|security)/.test(relPath) &&
- MONOREPO_HELPER_SIGNALS.some((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // SvelteKit kit.csp.directives
- if (SCAN_EXTS.has(ext) && isConfig('svelte') &&
- SVELTEKIT_CSP_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // Nuxt nuxt-security module
- if (SCAN_EXTS.has(ext) && isConfig('nuxt') &&
- NUXT_SECURITY_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // === append-string candidates ===
-
- // Inline headers in Next/Nuxt/SvelteKit/Astro/Vite config
- if (SCAN_EXTS.has(ext) &&
- /(^|\/)(next|nuxt|vite|astro|svelte)\.config\./.test(relPath) &&
- INLINE_HEADER_SIGNALS.every((re) => re.test(body))) {
- // Nuxt routeRules is a sub-shape of append-string; we already covered
- // nuxt-security above via return, so any remaining Nuxt CSP match here
- // is a route-rules / inline-headers case. Either way, same patch
- // mechanism.
- hits.appendString.push(relPath);
- return;
- }
-
- // === detect-only shapes ===
-
- if ((base === 'middleware.ts' || base === 'middleware.js' || base === 'middleware.mjs') &&
- MIDDLEWARE_HINT.test(body)) {
- hits.middleware.push(relPath);
- }
-
- if (LAYOUT_EXTS.has(ext) && META_TAG_HINT.test(body)) {
- hits.metaTag.push(relPath);
- }
- });
-
- // Priority: append-arrays > append-string > middleware > meta-tag.
- // Structured patches are safer than string splices; runtime and HTML
- // injection patches are less reliable and v1 doesn't auto-apply them.
- if (hits.appendArrays.length > 0) {
- return { shape: 'append-arrays', signals: hits.appendArrays };
- }
- if (hits.appendString.length > 0) {
- return { shape: 'append-string', signals: hits.appendString };
- }
- if (hits.middleware.length > 0) {
- return { shape: 'middleware', signals: hits.middleware };
- }
- if (hits.metaTag.length > 0) {
- return { shape: 'meta-tag', signals: hits.metaTag };
- }
- return { shape: null, signals: [] };
-}
-
-function walk(root, dir, depth, visit) {
- if (depth > MAX_DEPTH) return;
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
-
- for (const entry of entries) {
- const abs = path.join(dir, entry.name);
- if (entry.isDirectory()) {
- if (SKIP_DIRS.has(entry.name)) continue;
- walk(root, abs, depth + 1, visit);
- continue;
- }
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name);
- if (!SCAN_EXTS.has(ext) && !LAYOUT_EXTS.has(ext)) continue;
- let body;
- try {
- const fd = fs.openSync(abs, 'r');
- try {
- const buf = Buffer.alloc(MAX_READ_BYTES);
- const n = fs.readSync(fd, buf, 0, MAX_READ_BYTES, 0);
- body = buf.slice(0, n).toString('utf-8');
- } finally { fs.closeSync(fd); }
- } catch { continue; }
- visit(abs, path.relative(root, abs), body);
- }
-}
-
-// CLI mode
-const _running = process.argv[1];
-if (_running?.endsWith('detect-csp.mjs') || _running?.endsWith('detect-csp.mjs/')) {
- const result = detectCsp(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
@@ -1,21 +0,0 @@
-#!/usr/bin/env node
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { pathToFileURL, fileURLToPath } from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const candidates = [
- path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
-];
-const detectorPath = candidates.find(p => fs.existsSync(p));
-
-if (!detectorPath) {
- process.stderr.write('Error: bundled detector not found.\n');
- process.exit(1);
-}
-
-const { detectCli } = await import(pathToFileURL(detectorPath));
-
-await detectCli();
@@ -1,1688 +0,0 @@
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
@@ -1,232 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
-import { detectHtml } from '../engines/static-html/detect-html.mjs';
-import { detectText } from '../engines/regex/detect-text.mjs';
-import {
- HTML_EXTENSIONS,
- buildImportGraph,
- detectFrameworkConfig,
- isPortListening,
- walkDir,
-} from '../node/file-system.mjs';
-
-// ---------------------------------------------------------------------------
-// Output formatting
-// ---------------------------------------------------------------------------
-
-function formatFindings(findings, jsonMode) {
- if (jsonMode) return JSON.stringify(findings, null, 2);
-
- const grouped = {};
- for (const f of findings) {
- if (!grouped[f.file]) grouped[f.file] = [];
- grouped[f.file].push(f);
- }
- const out = [];
- for (const [file, items] of Object.entries(grouped)) {
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
- out.push(`\n${file}${importNote}`);
- for (const item of items) {
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
- out.push(` → ${item.description}`);
- }
- }
- out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
- return out.join('\n');
-}
-
-// ---------------------------------------------------------------------------
-// Stdin handling
-// ---------------------------------------------------------------------------
-
-async function handleStdin() {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- const input = Buffer.concat(chunks).toString('utf-8');
- try {
- const parsed = JSON.parse(input);
- const fp = parsed?.tool_input?.file_path;
- if (fp && fs.existsSync(fp)) {
- return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
- ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
- }
- } catch { /* not JSON */ }
- return detectText(input, '<stdin>');
-}
-
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-async function confirm(question) {
- const rl = (await import('node:readline')).default.createInterface({
- input: process.stdin, output: process.stderr,
- });
- return new Promise((resolve) => {
- rl.question(`${question} [Y/n] `, (answer) => {
- rl.close();
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
- });
- });
-}
-
-function printUsage() {
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
-
-Scan files or URLs for UI anti-patterns and design quality issues.
-
-Options:
- --fast Regex-only mode (skip static HTML/CSS analysis, faster but misses linked stylesheets)
- --json Output results as JSON
- --help Show this help message
-
-Detection modes:
- HTML files Static HTML/CSS analysis (default, catches linked CSS)
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
- URLs Puppeteer full browser rendering (auto-detected)
- --fast Forces regex for all files
-
-Examples:
- impeccable detect src/
- impeccable detect index.html
- impeccable detect https://example.com
- impeccable detect --fast --json .`);
-}
-
-async function detectCli() {
- let args = process.argv.slice(2).map(arg => {
- if (arg === '-json') return '--json';
- if (arg === '-fast') return '--fast';
- return arg;
- });
- if (args[0] === 'detect') args = args.slice(1);
- const jsonMode = args.includes('--json');
- const helpMode = args.includes('--help');
- const fastMode = args.includes('--fast');
- const targets = args.filter(a => !a.startsWith('--'));
-
- if (helpMode) { printUsage(); process.exit(0); }
-
- let allFindings = [];
-
- if (!process.stdin.isTTY && targets.length === 0) {
- allFindings = await handleStdin();
- } else {
- const paths = targets.length > 0 ? targets : [process.cwd()];
- const urlTargetCount = paths.filter(target => /^https?:\/\//i.test(target)).length;
- const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
-
- try {
- for (const target of paths) {
- if (/^https?:\/\//i.test(target)) {
- try {
- const scanner = browserDetector
- ? (url) => browserDetector.detectUrl(url)
- : (url) => detectUrl(url);
- allFindings.push(...await scanner(target));
- } catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
- continue;
- }
-
- const resolved = path.resolve(target);
- let stat;
- try { stat = fs.statSync(resolved); }
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
-
- if (stat.isDirectory()) {
- // Check for framework dev server config (skip in JSON mode to avoid polluting output)
- if (!jsonMode) {
- const fwConfig = detectFrameworkConfig(resolved);
- if (fwConfig) {
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
- if (probe.listening && probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
- `For more accurate results, scan the running site:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- } else if (probe.listening && !probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
- );
- } else {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Start the dev server and scan via URL for best results:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- }
- }
- }
-
- const files = walkDir(resolved);
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
-
- // Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
- if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
- process.stderr.write(
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
- `Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
- `Use --fast to skip static HTML/CSS analysis, or target a specific subdirectory.\n`
- );
- const ok = await confirm('Continue?');
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
- }
-
- // Build import graph for multi-file awareness
- const graph = buildImportGraph(files);
- // Build reverse map: file -> set of files that import it
- const importedByMap = new Map();
- for (const [importer, imports] of graph) {
- for (const imported of imports) {
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
- importedByMap.get(imported).add(importer);
- }
- }
-
- for (const file of files) {
- const ext = path.extname(file).toLowerCase();
- let fileFindings;
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- fileFindings = await detectHtml(file);
- } else {
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
- }
- // Annotate findings with import context
- const importers = importedByMap.get(file);
- if (importers && importers.size > 0) {
- const importerNames = [...importers].map(f => path.basename(f));
- for (const f of fileFindings) {
- f.importedBy = importerNames;
- }
- }
- allFindings.push(...fileFindings);
- }
- } else if (stat.isFile()) {
- const ext = path.extname(resolved).toLowerCase();
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- allFindings.push(...await detectHtml(resolved));
- } else {
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
- }
- }
- }
- } finally {
- if (browserDetector) await browserDetector.close();
- }
- }
-
- if (allFindings.length > 0) {
- if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
- else process.stderr.write(formatFindings(allFindings, false) + '\n');
- process.exit(2);
- }
- if (jsonMode) process.stdout.write('[]\n');
- process.exit(0);
-}
-
-export { formatFindings, handleStdin, confirm, printUsage, detectCli };
@@ -1,4030 +0,0 @@
-/**
- * Anti-Pattern Browser Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * GENERATED -- do not edit. Source: cli/engine/browser/injected/index.mjs
- * Rebuild: node scripts/build-browser-detector.js
- *
- * Usage: <script src="detect-antipatterns-browser.js"></script>
- * Re-scan: window.impeccableScan()
- */
-(function () {
-if (typeof window === 'undefined') return;
-// --- cli/engine/shared/constants.mjs ---
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-// --- cli/engine/registry/antipatterns.mjs ---
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-// --- cli/engine/shared/color.mjs ---
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-// --- cli/engine/rules/checks.mjs ---
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-// --- cli/engine/browser/injected/index.mjs ---
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
-
-})();
@@ -1,43 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Anti-Pattern Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * Public API facade. Runtime engines live under cli/engine/engines/.
- */
-
-import { detectCli } from './cli/main.mjs';
-
-export { ANTIPATTERNS, RULE_ENGINE_SUPPORT, getAntipattern, getRulesForCategory, getRuleEngineSupport } from './registry/antipatterns.mjs';
-export { SAFE_TAGS, BORDER_SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS, KNOWN_SERIF_FONTS } from './shared/constants.mjs';
-export { isNeutralColor, parseRgb, relativeLuminance, contrastRatio, parseGradientColors, hasChroma, getHue, colorToHex } from './shared/color.mjs';
-export { isFullPage } from './shared/page.mjs';
-export {
- checkElementBorders,
- checkElementMotion,
- checkElementGlow,
- checkPageTypography,
- checkPageLayout,
- checkHtmlPatterns,
-} from './rules/checks.mjs';
-export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
-export { detectHtml } from './engines/static-html/detect-html.mjs';
-export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
-export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
-export {
- walkDir,
- SCANNABLE_EXTENSIONS,
- SKIP_DIRS,
- buildImportGraph,
- resolveImport,
- detectFrameworkConfig,
- isPortListening,
- FRAMEWORK_CONFIGS,
-} from './node/file-system.mjs';
-export { formatFindings, detectCli } from './cli/main.mjs';
-
-const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
-if (isMainModule) detectCli();
@@ -1,251 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { finding } from '../../findings.mjs';
-import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
-
-async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
- if (options?.visualContrast === false) return [];
- const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : 12;
- const scrollOffscreen = options?.visualContrastScrollOffscreen !== false;
- const existingLowContrastSelectors = new Set(
- serializedGroups
- .filter(group => group.findings?.some(f => f.type === 'low-contrast'))
- .map(group => group.selector)
- .filter(Boolean)
- );
-
- let browserAnalyses = [];
- const findings = [];
- if (options?.visualContrastBrowser !== false) {
- const browserFindings = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'browser-fallback',
- target,
- }, async () => {
- browserAnalyses = await page.evaluate(async ({ maxCandidates, scrollOffscreen }) => {
- if (typeof window.impeccableAnalyzeVisualContrast !== 'function') return [];
- return window.impeccableAnalyzeVisualContrast({ maxCandidates, scrollOffscreen });
- }, { maxCandidates, scrollOffscreen });
- return browserAnalyses
- .filter(result => result.finding && !existingLowContrastSelectors.has(result.selector))
- .map(result => result.finding);
- });
- findings.push(...browserFindings);
- }
-
- let candidates = browserAnalyses.length > 0 ? browserAnalyses : [];
- if (candidates.length === 0) {
- candidates = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'collect-candidates',
- target,
- }, () => page.evaluate(({ maxCandidates }) => {
- if (typeof window.impeccableCollectVisualContrastCandidates !== 'function') return [];
- return window.impeccableCollectVisualContrastCandidates({ maxCandidates });
- }, { maxCandidates }));
- }
-
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const browserResolvedSelectors = new Set(
- browserAnalyses
- .filter(result => result.status === 'fail' || result.status === 'pass')
- .map(result => result.selector)
- .filter(Boolean)
- );
- const filtered = candidates.filter(candidate =>
- !existingLowContrastSelectors.has(candidate.selector) &&
- !browserResolvedSelectors.has(candidate.selector)
- );
- if (options?.visualContrastPixel === false) return findings;
- for (const candidate of filtered) {
- const result = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'pixel-diff',
- target,
- }, async () => {
- const finding = await captureVisualContrastCandidate(page, candidate, viewport);
- return finding ? [finding] : [];
- });
- findings.push(...result);
- }
- return findings;
-}
-
-// ---------------------------------------------------------------------------
-// Puppeteer detection (for URLs)
-// ---------------------------------------------------------------------------
-
-async function detectUrl(url, options = {}) {
- const profile = options?.profile;
- const waitUntil = options?.waitUntil || 'networkidle0';
- const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const externalBrowser = options?.browser || null;
- let puppeteer;
- if (!externalBrowser) {
- try {
- puppeteer = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'import-puppeteer',
- target: url,
- }, () => import('puppeteer'));
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- }
-
- // Read the browser detection script — reuse it instead of reimplementing
- const browserScriptPath = path.resolve(
- path.dirname(fileURLToPath(import.meta.url)),
- '..',
- '..',
- 'detect-antipatterns-browser.js'
- );
- let browserScript;
- try {
- browserScript = profileStep(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'read-browser-script',
- target: url,
- }, () => fs.readFileSync(browserScriptPath, 'utf-8'));
- } catch {
- throw new Error(`Browser script not found at ${browserScriptPath}`);
- }
-
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
- // running in CI; local users keep the default hardened launch.
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
- const browser = externalBrowser || await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'launch-browser',
- target: url,
- }, () => puppeteer.default.launch({ headless: true, args: launchArgs }));
- const page = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'new-page',
- target: url,
- }, () => browser.newPage());
- let results = [];
- try {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'set-viewport',
- target: url,
- }, () => page.setViewport(viewport));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: `goto:${waitUntil}`,
- target: url,
- }, () => page.goto(url, { waitUntil, timeout: 30000 }));
- if (settleMs > 0) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'settle',
- target: url,
- }, () => new Promise(resolve => setTimeout(resolve, settleMs)));
- }
-
- // Inject the browser detection script and collect results
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'configure-pure-detect',
- target: url,
- }, () => page.evaluate(() => {
- window.__IMPECCABLE_CONFIG__ = {
- ...(window.__IMPECCABLE_CONFIG__ || {}),
- autoScan: false,
- };
- }));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'inject-browser-script',
- target: url,
- }, () => page.evaluate(browserScript));
- let serializedGroups = [];
- results = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'browser-scan',
- target: url,
- }, async () => {
- serializedGroups = await page.evaluate(() => {
- if (!window.impeccableDetect) return [];
- return window.impeccableDetect({ decorate: false, serialize: true });
- });
- return serializedGroups.flatMap(({ findings }) =>
- findings.map(f => ({ id: f.type, snippet: f.detail }))
- );
- });
- const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
- results.push(...visualFindings);
- } finally {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-page',
- target: url,
- }, () => page.close().catch(() => {}));
- if (!externalBrowser) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-browser',
- target: url,
- }, () => browser.close());
- }
- }
- return results.map(f => finding(f.id, url, f.snippet));
-}
-
-async function createBrowserDetector(options = {}) {
- let puppeteer;
- try {
- puppeteer = await import('puppeteer');
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- const launchArgs = options.launchArgs || (process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : []);
- const browser = options.browser || await puppeteer.default.launch({
- headless: options.headless ?? true,
- args: launchArgs,
- });
- const ownsBrowser = !options.browser;
- const defaults = {
- waitUntil: options.waitUntil || 'load',
- settleMs: Number.isFinite(options.settleMs) ? options.settleMs : 100,
- viewport: options.viewport || { width: 1280, height: 800 },
- };
- return {
- browser,
- async detectUrl(url, scanOptions = {}) {
- return detectUrl(url, {
- ...defaults,
- ...scanOptions,
- browser,
- });
- },
- async close() {
- if (ownsBrowser) await browser.close().catch(() => {});
- },
- };
-}
-
-export { runVisualContrastFallback, detectUrl, createBrowserDetector };
@@ -1,420 +0,0 @@
-import { GENERIC_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep } from '../../profile/profiler.mjs';
-
-// ---------------------------------------------------------------------------
-// Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
-// ---------------------------------------------------------------------------
-
-const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
-const hasBorderRadius = (line) => /border-radius/i.test(line);
-const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
-
-function isNeutralBorderColor(str) {
- const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
- if (!m) return false;
- const c = m[1].toLowerCase();
- if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
- const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
- if (hex) {
- const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
- if (shex) {
- const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- return false;
-}
-
-const REGEX_MATCHERS = [
- // --- Side-tab ---
- { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
- test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
- test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
- fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
- { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
- test: (m) => +m[1] >= 3,
- fmt: (m) => m[0] },
- // --- Border accent on rounded ---
- { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
- test: (m, line) => hasRounded(line) && +m[1] >= 1,
- fmt: (m) => m[0] },
- { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
- fmt: (m) => m[0] },
- // --- Overused font ---
- { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
- test: () => true,
- fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
- // --- Pure black background ---
- { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Gradient text ---
- { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
- test: (m, line) => /gradient/i.test(line),
- fmt: () => 'background-clip: text + gradient' },
- // --- Gradient text (Tailwind) ---
- { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
- test: (m, line) => /\bbg-gradient-to-/i.test(line),
- fmt: () => 'bg-clip-text + bg-gradient' },
- // --- Tailwind pure black background ---
- { id: 'pure-black-white', regex: /\bbg-black\b/g,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Tailwind gray on colored bg ---
- { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
- test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
- fmt: (m, line) => { const bg = line.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/); return `${m[0]} on ${bg?.[0] || '?'}`; } },
- // --- Tailwind AI palette ---
- { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
- fmt: (m) => `${m[0]} on heading` },
- { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
- fmt: (m) => `${m[0]} gradient` },
- // --- Bounce/elastic easing ---
- { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
- test: () => true,
- fmt: () => 'animate-bounce (Tailwind)' },
- { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
- test: (m) => {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
- },
- fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
- // --- Layout property transition ---
- { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition: ${found ? found.join(', ') : m[1].trim()}`;
- } },
- { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
- } },
-];
-
-const REGEX_ANALYZERS = [
- // Single font
- (content, filePath) => {
- const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
- const fonts = new Set();
- let m;
- while ((m = fontFamilyRe.exec(content)) !== null) {
- for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
- }
- }
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- while ((m = gfRe.exec(content)) !== null) {
- for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
- }
- if (fonts.size !== 1 || content.split('\n').length < 20) return [];
- const name = [...fonts][0];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
- return [finding('single-font', filePath, `only font used is ${name}`, line)];
- },
- // Flat type hierarchy
- (content, filePath) => {
- const sizes = new Set();
- const REM = 16;
- let m;
- const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
- while ((m = sizeRe.exec(content)) !== null) {
- const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
- if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
- }
- const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
- while ((m = clampRe.exec(content)) !== null) {
- sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
- sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
- }
- const TW = { 'text-xs': 12, 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24, 'text-3xl': 30, 'text-4xl': 36, 'text-5xl': 48, 'text-6xl': 60, 'text-7xl': 72, 'text-8xl': 96, 'text-9xl': 128 };
- for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
- if (sizes.size < 3) return [];
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio >= 2.0) return [];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (/font-size/i.test(lines[i]) || /\btext-(?:xs|sm|base|lg|xl|\d)/i.test(lines[i])) { line = i + 1; break; } }
- return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
- },
- // Monotonous spacing (regex)
- (content, filePath) => {
- const vals = [];
- let m;
- const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
- const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
- const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
- const rounded = vals.map(v => Math.round(v / 4) * 4);
- if (rounded.length < 10) return [];
- const counts = {};
- for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const pct = maxCount / rounded.length;
- const unique = [...new Set(rounded)].filter(v => v > 0);
- if (pct <= 0.6 || unique.length > 3) return [];
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
- },
- // Everything centered (regex)
- (content, filePath) => {
- const lines = content.split('\n');
- let centered = 0, total = 0;
- for (const line of lines) {
- if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
- total++;
- if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
- }
- }
- if (total < 5 || centered / total <= 0.7) return [];
- return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
- },
- // Dark glow (page-level: dark bg + colored box-shadow with blur)
- (content, filePath) => {
- // Check if page has a dark background
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
- if (!hasDarkBg) return [];
-
- // Check for colored box-shadow with blur > 4px
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let m;
- while ((m = shadowRe.exec(content)) !== null) {
- const val = m[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
- // Check blur: look for pattern like "0 0 20px" (third number > 4)
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- const lines = content.substring(0, m.index).split('\n');
- return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
- }
- }
- return [];
- },
-];
-
-// ---------------------------------------------------------------------------
-// Style block extraction (Vue/Svelte <style> blocks)
-// ---------------------------------------------------------------------------
-
-function extractStyleBlocks(content, ext) {
- ext = ext.toLowerCase();
- if (ext !== '.vue' && ext !== '.svelte') return [];
- const blocks = [];
- const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length + 1;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-// ---------------------------------------------------------------------------
-// CSS-in-JS extraction (styled-components, emotion)
-// ---------------------------------------------------------------------------
-
-const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
-
-function extractCSSinJS(content, ext) {
- ext = ext.toLowerCase();
- if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
- const blocks = [];
- const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null, options = {}) {
- const { profile, phase = 'regex-matchers' } = options || {};
- const findings = [];
- if (!profile) {
- for (const matcher of REGEX_MATCHERS) {
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- }
- return findings;
- }
-
- for (const matcher of REGEX_MATCHERS) {
- const matcherFindings = profileFindings(profile, {
- engine: 'regex',
- phase,
- ruleId: matcher.id,
- target: filePath,
- }, () => {
- const matches = [];
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- matches.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- return matches;
- });
- findings.push(...matcherFindings);
- }
- return findings;
-}
-
-function detectText(content, filePath, options = {}) {
- const profile = options?.profile;
- const findings = [];
- const lines = content.split('\n');
- const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
-
- // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
- // Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
- findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
- profile,
- phase: 'source',
- }));
-
- // Extract and scan <style> blocks from Vue/Svelte SFCs
- const styleBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'style-blocks',
- target: filePath,
- }, () => extractStyleBlocks(content, ext))
- : extractStyleBlocks(content, ext);
- for (const block of styleBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'style-block',
- }));
- }
-
- // Extract and scan CSS-in-JS template literals
- const cssJsBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'css-in-js',
- target: filePath,
- }, () => extractCSSinJS(content, ext))
- : extractCSSinJS(content, ext);
- for (const block of cssJsBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'css-in-js',
- }));
- }
-
- // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
- const deduped = [];
- for (const f of findings) {
- const isDupe = deduped.some(d =>
- d.antipattern === f.antipattern &&
- d.snippet === f.snippet &&
- Math.abs(d.line - f.line) <= 2
- );
- if (!isDupe) deduped.push(f);
- }
-
- // Page-level analyzers only run on full pages
- if (isFullPage(content)) {
- const analyzerIds = [
- 'single-font',
- 'flat-type-hierarchy',
- 'monotonous-spacing',
- 'everything-centered',
- 'dark-glow',
- ];
- for (let i = 0; i < REGEX_ANALYZERS.length; i++) {
- const analyzer = REGEX_ANALYZERS[i];
- deduped.push(...profileFindings(profile, {
- engine: 'regex',
- phase: 'page-analyzer',
- ruleId: analyzerIds[i] || `analyzer-${i + 1}`,
- target: filePath,
- }, () => analyzer(content, filePath)));
- }
- }
-
- return deduped;
-}
-
-export {
- REGEX_MATCHERS,
- REGEX_ANALYZERS,
- extractStyleBlocks,
- extractCSSinJS,
- runRegexMatchers,
- detectText,
-};
@@ -1,954 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { profileStep, recordProfileEvent } from '../../profile/profiler.mjs';
-import { parseAnyColor, resolveLengthPx, resolveVarRefs } from '../../rules/checks.mjs';
-
-// ---------------------------------------------------------------------------
-// jsdom CSS-variable border override map
-// ---------------------------------------------------------------------------
-//
-// jsdom's CSSOM silently drops any border shorthand that contains a var()
-// reference — the computed style for the element then shows empty width,
-// empty style, and a default black color. That's enough to hide the most
-// common real-world side-tab pattern in AI-generated pages:
-//
-// :root { --brand: #87a8ff; }
-// .card { border-left: 5px solid var(--brand); border-radius: 4px; }
-//
-// Real browsers (and therefore the browser detector path) resolve var()
-// natively, so this only affects the Node jsdom path.
-//
-// This pre-pass walks the stylesheets, finds any rule whose per-side or
-// all-sides border property contains var(), resolves the var() against
-// :root-level custom properties (read from the documentElement's computed
-// style, which jsdom DOES handle correctly), and attaches the resolved
-// width+color to every element that matches the rule's selector. The
-// Node-side `checkElementBorders` adapter consumes that map as a fallback
-// whenever jsdom's computed style came back empty.
-//
-// Limitations (intentional, to keep the pass simple):
-// * Only :root-level custom properties are resolved. Scoped overrides on
-// descendants are not tracked — uncommon in practice and would require
-// a per-element cascade walk.
-// * @media / @supports wrapped rules are ignored (jsdom often mishandles
-// these anyway).
-// * The fallback only fills sides that jsdom left empty, so any rule
-// whose border parses normally still wins via the computed style.
-
-const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
-
-// isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
-// CSS variables typically hold hex or named colors, so normalize those to
-// rgb() before handing the value off to the shared check. Anything we don't
-// recognise is passed through unchanged — isNeutralColor then treats it as
-// non-neutral, which is the safer default (matches the oklch-era bugfix).
-const NAMED_COLORS = {
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
-};
-
-function normalizeColorForCheck(value) {
- if (!value) return value;
- const v = value.trim();
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
- if (hex6) {
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
- if (hex3) {
- const [r, g, b] = [
- parseInt(hex3[1] + hex3[1], 16),
- parseInt(hex3[2] + hex3[2], 16),
- parseInt(hex3[3] + hex3[3], 16),
- ];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const named = NAMED_COLORS[v.toLowerCase()];
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
- return v;
-}
-
-function buildBorderOverrideMap(document, window) {
- const map = new Map();
- const rootStyle = window.getComputedStyle(document.documentElement);
-
- function resolveVar(value, depth = 0) {
- if (!value || depth > 10 || !value.includes('var(')) return value;
- return value.replace(
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
- (_, name, fallback) => {
- const v = rootStyle.getPropertyValue(name).trim();
- if (v) return resolveVar(v, depth + 1);
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
- return '';
- }
- );
- }
-
- function parseShorthand(text) {
- const m = text.trim().match(BORDER_SHORTHAND_RE);
- if (!m) return null;
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
- }
-
- // Read from the per-property accessors on rule.style. jsdom preserves
- // each border-* shorthand it parsed, even when the overall cssText has
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
- // `border-left: ...` loses the first declaration but keeps the second).
- const SIDE_PROPS = [
- ['borderLeft', 'Left'],
- ['borderRight', 'Right'],
- ['borderTop', 'Top'],
- ['borderBottom', 'Bottom'],
- ['borderInlineStart', 'Left'],
- ['borderInlineEnd', 'Right'],
- ];
-
- for (const sheet of document.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || []; } catch { continue; }
- for (const rule of rules) {
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
-
- const perSide = {};
-
- for (const [prop, side] of SIDE_PROPS) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const parsed = parseShorthand(resolveVar(val));
- if (parsed && parsed.color) perSide[side] = parsed;
- }
-
- // Uniform `border: <w> <style> var(...)` applies to every side the
- // per-side map didn't already claim.
- const borderAll = rule.style.border;
- if (borderAll && borderAll.includes('var(')) {
- const parsed = parseShorthand(resolveVar(borderAll));
- if (parsed && parsed.color) {
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
- if (!perSide[s]) perSide[s] = parsed;
- }
- }
- }
-
- // Longhand `border-*-color: var(...)` with width/style in separate
- // declarations. Rare in AI-generated pages, but cheap to cover.
- for (const [prop, side] of [
- ['borderLeftColor', 'Left'],
- ['borderRightColor', 'Right'],
- ['borderTopColor', 'Top'],
- ['borderBottomColor', 'Bottom'],
- ]) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const resolved = resolveVar(val).trim();
- if (!resolved) continue;
- // Width may or may not come from this rule — that's fine; the
- // adapter only substitutes the color when jsdom left it as a
- // literal var() string.
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
- }
-
- if (Object.keys(perSide).length === 0) continue;
-
- let matched;
- try { matched = document.querySelectorAll(rule.selectorText); }
- catch { continue; }
-
- for (const el of matched) {
- const existing = map.get(el);
- if (existing) {
- // Later rules overwrite earlier ones — approximates source-order
- // cascade for equal-specificity rules and is good enough for the
- // uncontested var()-dropped sides we're trying to recover.
- Object.assign(existing, perSide);
- } else {
- map.set(el, { ...perSide });
- }
- }
- }
- }
-
- return map;
-}
-
-// Strip `@layer NAME { … }` wrappers from a CSS / HTML source, leaving
-// the inner rules as flat CSS. jsdom doesn't implement CSS @layer, so
-// any rule inside a layer block becomes invisible to getComputedStyle.
-// Tailwind v4 makes this ubiquitous: every utility class lives in
-// `@layer utilities`, and Preflight lives in `@layer base`. Without
-// unwrapping, every Tailwind-styled element returns empty computed
-// styles. We walk the source character-by-character, balancing braces
-// so we correctly handle nested style rules inside the layer block.
-function unwrapCssAtLayer(source) {
- if (!source || !source.includes('@layer')) return source;
- // Find `@layer <name>? {` openers. The match starts at the @, and
- // we then balance braces from the opening { onward.
- const re = /@layer\b[^{;]*\{/g;
- let out = '';
- let lastIdx = 0;
- let m;
- while ((m = re.exec(source)) !== null) {
- const openStart = m.index;
- const openEnd = m.index + m[0].length; // position right after `{`
- let depth = 1;
- let i = openEnd;
- while (i < source.length && depth > 0) {
- const c = source.charCodeAt(i);
- if (c === 0x7b /* { */) depth++;
- else if (c === 0x7d /* } */) depth--;
- i++;
- }
- if (depth !== 0) {
- // Unbalanced — bail and return source unchanged.
- return source;
- }
- // Emit everything before the @layer, then the inner contents
- // (between the opening { and the matched closing }), then advance.
- out += source.slice(lastIdx, openStart);
- out += source.slice(openEnd, i - 1); // i-1 = position of the closing }
- lastIdx = i;
- re.lastIndex = i;
- }
- out += source.slice(lastIdx);
- return out;
-}
-
-// ---------------------------------------------------------------------------
-// Static HTML/CSS detection (default for local HTML files)
-// ---------------------------------------------------------------------------
-
-const STATIC_INHERITED_PROPS = new Set([
- 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight',
- 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'hyphens',
- 'webkitHyphens',
-]);
-
-const STATIC_DEFAULT_STYLE = {
- color: 'rgb(0, 0, 0)',
- backgroundColor: 'rgba(0, 0, 0, 0)',
- backgroundImage: 'none',
- borderTopWidth: '0px',
- borderRightWidth: '0px',
- borderBottomWidth: '0px',
- borderLeftWidth: '0px',
- borderTopColor: 'rgb(0, 0, 0)',
- borderRightColor: 'rgb(0, 0, 0)',
- borderBottomColor: 'rgb(0, 0, 0)',
- borderLeftColor: 'rgb(0, 0, 0)',
- borderRadius: '0px',
- boxShadow: 'none',
- fontFamily: '',
- fontSize: '16px',
- fontStyle: 'normal',
- fontWeight: '400',
- lineHeight: 'normal',
- letterSpacing: 'normal',
- textTransform: 'none',
- textAlign: 'start',
- hyphens: 'manual',
- webkitHyphens: 'manual',
- transitionProperty: '',
- transitionTimingFunction: '',
- animationName: '',
- animationTimingFunction: '',
- webkitBackgroundClip: '',
- backgroundClip: '',
- width: '',
- height: '',
- paddingTop: '0px',
- paddingRight: '0px',
- paddingBottom: '0px',
- paddingLeft: '0px',
- position: 'static',
- display: '',
-};
-
-const STATIC_PROP_MAP = {
- 'background-color': 'backgroundColor',
- 'background-image': 'backgroundImage',
- 'background-clip': 'backgroundClip',
- '-webkit-background-clip': 'webkitBackgroundClip',
- 'border-radius': 'borderRadius',
- 'border-top-width': 'borderTopWidth',
- 'border-right-width': 'borderRightWidth',
- 'border-bottom-width': 'borderBottomWidth',
- 'border-left-width': 'borderLeftWidth',
- 'border-top-color': 'borderTopColor',
- 'border-right-color': 'borderRightColor',
- 'border-bottom-color': 'borderBottomColor',
- 'border-left-color': 'borderLeftColor',
- 'box-shadow': 'boxShadow',
- 'font-family': 'fontFamily',
- 'font-size': 'fontSize',
- 'font-style': 'fontStyle',
- 'font-weight': 'fontWeight',
- 'line-height': 'lineHeight',
- 'letter-spacing': 'letterSpacing',
- 'text-transform': 'textTransform',
- 'text-align': 'textAlign',
- 'hyphens': 'hyphens',
- '-webkit-hyphens': 'webkitHyphens',
- 'transition-property': 'transitionProperty',
- 'transition-timing-function': 'transitionTimingFunction',
- 'animation-name': 'animationName',
- 'animation-timing-function': 'animationTimingFunction',
- 'width': 'width',
- 'height': 'height',
- 'padding-top': 'paddingTop',
- 'padding-right': 'paddingRight',
- 'padding-bottom': 'paddingBottom',
- 'padding-left': 'paddingLeft',
- 'position': 'position',
- 'display': 'display',
-};
-
-const STATIC_NAMED_COLORS = {
- black: { r: 0, g: 0, b: 0, a: 1 },
- white: { r: 255, g: 255, b: 255, a: 1 },
- transparent: { r: 0, g: 0, b: 0, a: 0 },
- gray: { r: 128, g: 128, b: 128, a: 1 },
- grey: { r: 128, g: 128, b: 128, a: 1 },
- silver: { r: 192, g: 192, b: 192, a: 1 },
- red: { r: 255, g: 0, b: 0, a: 1 },
- green: { r: 0, g: 128, b: 0, a: 1 },
- blue: { r: 0, g: 0, b: 255, a: 1 },
-};
-
-function splitCssList(value) {
- const parts = [];
- let depth = 0, quote = '', start = 0;
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; continue; }
- if (ch === '(' || ch === '[') depth++;
- else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);
- else if (ch === ',' && depth === 0) {
- parts.push(value.slice(start, i).trim());
- start = i + 1;
- }
- }
- const tail = value.slice(start).trim();
- if (tail) parts.push(tail);
- return parts;
-}
-
-function splitCssTokens(value) {
- const tokens = [];
- let depth = 0, quote = '', current = '';
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- current += ch;
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
- if (ch === '(') { depth++; current += ch; continue; }
- if (ch === ')') { depth = Math.max(0, depth - 1); current += ch; continue; }
- if (/\s/.test(ch) && depth === 0) {
- if (current) { tokens.push(current); current = ''; }
- continue;
- }
- current += ch;
- }
- if (current) tokens.push(current);
- return tokens;
-}
-
-function cssPropToCamel(prop) {
- if (!prop) return prop;
- const mapped = STATIC_PROP_MAP[prop];
- if (mapped) return mapped;
- return prop.replace(/-([a-z])/g, (_m, ch) => ch.toUpperCase());
-}
-
-function staticColorToCss(c) {
- if (!c) return '';
- if (c.a != null && c.a < 1) return `rgba(${c.r}, ${c.g}, ${c.b}, ${Number(c.a.toFixed(3))})`;
- return `rgb(${c.r}, ${c.g}, ${c.b})`;
-}
-
-function parseStaticColor(value) {
- const parsed = parseAnyColor(value);
- if (parsed) return parsed;
- const named = STATIC_NAMED_COLORS[String(value || '').trim().toLowerCase()];
- return named ? { ...named } : null;
-}
-
-function extractStaticColor(value) {
- if (!value) return '';
- const raw = String(value).trim();
- if (/^var\(/i.test(raw)) return raw;
- const colorLike = raw.match(/(?:rgba?\([^)]+\)|oklch\([^)]+\)|oklab\([^)]+\)|lch\([^)]+\)|lab\([^)]+\)|hsla?\([^)]+\)|hwb\([^)]+\)|#[0-9a-f]{3,8}\b|\b(?:black|white|gray|grey|silver|red|green|blue|transparent)\b)/i);
- if (!colorLike) return '';
- return colorLike[0];
-}
-
-function normalizeStaticCssValue(prop, value, customProps, parentStyle, currentStyle = null) {
- let resolved = resolveVarRefs(String(value || '').trim(), customProps);
- if (resolved === 'inherit') return parentStyle?.[prop] || STATIC_DEFAULT_STYLE[prop] || '';
- const isModernBorderColor = /^border[A-Z][a-z]+Color$/.test(prop) && /^(?:oklch|oklab|lch|lab|hsl|hwb)\(/i.test(resolved);
- if (!isModernBorderColor && (/color$/i.test(prop) || prop === 'color' || prop === 'backgroundColor')) {
- const parsed = parseStaticColor(resolved);
- if (parsed) resolved = staticColorToCss(parsed);
- }
- if (prop === 'fontSize') {
- const base = parseFloat(parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'letterSpacing') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'lineHeight' && resolved !== 'normal') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- return resolved;
-}
-
-function expandStaticBoxValues(tokens) {
- if (tokens.length === 0) return ['0px', '0px', '0px', '0px'];
- if (tokens.length === 1) return [tokens[0], tokens[0], tokens[0], tokens[0]];
- if (tokens.length === 2) return [tokens[0], tokens[1], tokens[0], tokens[1]];
- if (tokens.length === 3) return [tokens[0], tokens[1], tokens[2], tokens[1]];
- return [tokens[0], tokens[1], tokens[2], tokens[3]];
-}
-
-function parseStaticBorder(value) {
- const tokens = splitCssTokens(value);
- let width = '', color = '';
- for (const token of tokens) {
- if (!width && /^-?[\d.]+(?:px|rem|em|%)$/.test(token)) width = token;
- if (!color) color = extractStaticColor(token);
- }
- return { width, color };
-}
-
-function parseStaticFont(value) {
- const out = [];
- const slashParts = value.match(/(?:^|\s)([\d.]+(?:px|rem|em|%))(?:\/([^\s]+))?/);
- if (/\bitalic\b/i.test(value)) out.push(['fontStyle', 'italic']);
- const weight = value.match(/\b([1-9]00|bold|normal|lighter|bolder)\b/i);
- if (weight) out.push(['fontWeight', weight[1]]);
- if (slashParts) {
- out.push(['fontSize', slashParts[1]]);
- if (slashParts[2]) out.push(['lineHeight', slashParts[2]]);
- const familyStart = value.indexOf(slashParts[0]) + slashParts[0].length;
- const family = value.slice(familyStart).trim();
- if (family) out.push(['fontFamily', family]);
- }
- return out;
-}
-
-function parseStaticTransition(value) {
- const props = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const prop = tokens.find(token => /^[a-z-]+$/i.test(token) && !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none)$/.test(token) && !/s$/.test(token));
- if (prop) props.push(prop);
- }
- return {
- property: props.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function parseStaticAnimation(value) {
- const names = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const name = tokens.find(token =>
- /^[a-z_-][\w-]*$/i.test(token) &&
- !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none|running|paused)$/.test(token)
- );
- if (name) names.push(name);
- }
- return {
- name: names.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function expandStaticDeclaration(prop, value) {
- const p = prop.toLowerCase();
- const v = String(value || '').trim();
- if (!v) return [];
- if (p.startsWith('--')) return [[p, v]];
- if (p === 'background') {
- const out = [];
- const hasImage = /gradient|url\(/i.test(v);
- if (hasImage) out.push(['backgroundImage', v]);
- const beforeImage = hasImage ? v.split(/(?:repeating-)?(?:linear|radial|conic)-gradient\(|url\(/i)[0] : v;
- const color = extractStaticColor(hasImage ? beforeImage : v);
- if (color) out.push(['backgroundColor', color]);
- return out;
- }
- if (p === 'border') {
- const parsed = parseStaticBorder(v);
- const out = [];
- for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
- if (parsed.width) out.push([`border${side}Width`, parsed.width]);
- if (parsed.color) out.push([`border${side}Color`, parsed.color]);
- }
- return out;
- }
- const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
- if (sideMatch) {
- const parsed = parseStaticBorder(v);
- const side = sideMatch[1][0].toUpperCase() + sideMatch[1].slice(1);
- return [
- ...(parsed.width ? [[`border${side}Width`, parsed.width]] : []),
- ...(parsed.color ? [[`border${side}Color`, parsed.color]] : []),
- ];
- }
- if (p === 'border-width') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopWidth', vals[0]],
- ['borderRightWidth', vals[1]],
- ['borderBottomWidth', vals[2]],
- ['borderLeftWidth', vals[3]],
- ];
- }
- if (p === 'border-color') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopColor', vals[0]],
- ['borderRightColor', vals[1]],
- ['borderBottomColor', vals[2]],
- ['borderLeftColor', vals[3]],
- ];
- }
- if (p === 'padding') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['paddingTop', vals[0]],
- ['paddingRight', vals[1]],
- ['paddingBottom', vals[2]],
- ['paddingLeft', vals[3]],
- ];
- }
- if (p === 'font') return parseStaticFont(v);
- if (p === 'transition') {
- const parsed = parseStaticTransition(v);
- return [
- ...(parsed.property ? [['transitionProperty', parsed.property]] : []),
- ...(parsed.timing ? [['transitionTimingFunction', parsed.timing]] : []),
- ];
- }
- if (p === 'animation') {
- const parsed = parseStaticAnimation(v);
- return [
- ...(parsed.name ? [['animationName', parsed.name]] : []),
- ...(parsed.timing ? [['animationTimingFunction', parsed.timing]] : []),
- ];
- }
- const mapped = cssPropToCamel(p);
- if (STATIC_DEFAULT_STYLE[mapped] != null || STATIC_INHERITED_PROPS.has(mapped)) {
- return [[mapped, v]];
- }
- return [];
-}
-
-function compareStaticPriority(a, b) {
- if (!a) return true;
- if (!!b.important !== !!a.important) return !!b.important;
- if (!!b.inline !== !!a.inline) return !!b.inline;
- for (let i = 0; i < 3; i++) {
- if ((b.specificity[i] || 0) !== (a.specificity[i] || 0)) {
- return (b.specificity[i] || 0) > (a.specificity[i] || 0);
- }
- }
- return b.order >= a.order;
-}
-
-function staticSpecificity(selector) {
- const noWhere = selector.replace(/:where\([^)]*\)/g, '');
- const ids = (noWhere.match(/#[\w-]+/g) || []).length;
- const classes = (noWhere.match(/\.[\w-]+|\[[^\]]+\]|:(?!:)[\w-]+(?:\([^)]*\))?/g) || []).length;
- const stripped = noWhere
- .replace(/#[\w-]+/g, ' ')
- .replace(/\.[\w-]+|\[[^\]]+\]|:{1,2}[\w-]+(?:\([^)]*\))?/g, ' ')
- .replace(/[*>+~(),]/g, ' ');
- const types = (stripped.match(/\b[a-zA-Z][\w-]*\b/g) || []).length;
- return [ids, classes, types];
-}
-
-function applyStaticDeclaration(specified, node, prop, value, meta) {
- let map = specified.get(node);
- if (!map) { map = new Map(); specified.set(node, map); }
- for (const [expandedProp, expandedValue] of expandStaticDeclaration(prop, value)) {
- const existing = map.get(expandedProp);
- const next = { ...meta, prop: expandedProp, value: expandedValue };
- if (compareStaticPriority(existing, next)) map.set(expandedProp, next);
- }
-}
-
-function parseStaticStyleAttribute(styleText, orderBase = 0) {
- const decls = [];
- for (const part of String(styleText || '').split(';')) {
- const idx = part.indexOf(':');
- if (idx <= 0) continue;
- const prop = part.slice(0, idx).trim();
- let value = part.slice(idx + 1).trim();
- const important = /!important\s*$/i.test(value);
- value = value.replace(/\s*!important\s*$/i, '').trim();
- decls.push({ prop, value, important, order: orderBase + decls.length });
- }
- return decls;
-}
-
-function collectStaticCssRules(cssText, csstree) {
- const rules = [];
- let ast;
- try {
- ast = csstree.parse(cssText, { positions: false, parseValue: true, parseCustomProperty: false });
- } catch {
- return rules;
- }
- let order = 0;
- const walkList = (list, atRuleStack = []) => {
- list?.forEach?.(node => {
- if (node.type === 'Rule' && node.block) {
- if (atRuleStack.some(name => /keyframes$/i.test(name))) return;
- const selectorText = csstree.generate(node.prelude).trim();
- const declarations = [];
- node.block.children?.forEach?.(child => {
- if (child.type !== 'Declaration') return;
- declarations.push({
- prop: child.property,
- value: csstree.generate(child.value).trim(),
- important: !!child.important,
- });
- });
- for (const selector of splitCssList(selectorText)) {
- if (selector) rules.push({ selector, declarations, specificity: staticSpecificity(selector), order: order++ });
- }
- return;
- }
- if (node.type === 'Atrule' && node.block) {
- const name = String(node.name || '').toLowerCase();
- if (name === 'media' || name === 'supports' || name === 'layer') {
- walkList(node.block.children, [...atRuleStack, name]);
- }
- }
- });
- };
- walkList(ast.children);
- return rules;
-}
-
-class StaticElement {
- constructor(node, doc) {
- this.node = node;
- this._doc = doc;
- this.nodeType = 1;
- this.tagName = String(node.name || '').toUpperCase();
- this.nodeName = this.tagName;
- }
- get parentElement() {
- let cur = this.node.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- return cur ? this._doc.wrap(cur) : null;
- }
- get previousElementSibling() {
- let cur = this.node.prev;
- while (cur && cur.type !== 'tag') cur = cur.prev;
- return cur ? this._doc.wrap(cur) : null;
- }
- get children() {
- return (this.node.children || []).filter(child => child.type === 'tag').map(child => this._doc.wrap(child));
- }
- get childNodes() {
- return (this.node.children || []).map(child => {
- if (child.type === 'text') return { nodeType: 3, textContent: child.data || '' };
- if (child.type === 'tag') return this._doc.wrap(child);
- return { nodeType: 8, textContent: child.data || '' };
- });
- }
- get textContent() {
- return this._doc.domutils.textContent(this.node);
- }
- get className() {
- return this.getAttribute('class') || '';
- }
- get id() {
- return this.getAttribute('id') || '';
- }
- getAttribute(name) {
- return this.node.attribs?.[name] ?? null;
- }
- querySelector(selector) {
- try {
- const found = this._doc.selectOne(selector, this.node.children || []);
- return found ? this._doc.wrap(found) : null;
- } catch {
- return null;
- }
- }
- querySelectorAll(selector) {
- try {
- return this._doc.selectAll(selector, this.node.children || []).map(node => this._doc.wrap(node));
- } catch {
- return [];
- }
- }
- closest(selector) {
- let cur = this.node;
- while (cur && cur.type === 'tag') {
- try {
- if (this._doc.is(cur, selector)) return this._doc.wrap(cur);
- } catch {
- return null;
- }
- cur = cur.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- }
- return null;
- }
- contains(other) {
- let cur = other?.node || null;
- while (cur) {
- if (cur === this.node) return true;
- cur = cur.parent;
- }
- return false;
- }
-}
-
-class StaticDocument {
- constructor(root, modules) {
- this.root = root;
- this.selectAll = modules.selectAll;
- this.selectOne = modules.selectOne;
- this.is = modules.is;
- this.domutils = modules.domutils;
- this._wrappers = new WeakMap();
- this._styleMap = new WeakMap();
- }
- wrap(node) {
- let wrapped = this._wrappers.get(node);
- if (!wrapped) {
- wrapped = new StaticElement(node, this);
- this._wrappers.set(node, wrapped);
- }
- return wrapped;
- }
- querySelectorAll(selector) {
- try {
- return this.selectAll(selector, this.root.children || []).map(node => this.wrap(node));
- } catch {
- return [];
- }
- }
- querySelector(selector) {
- try {
- const found = this.selectOne(selector, this.root.children || []);
- return found ? this.wrap(found) : null;
- } catch {
- return null;
- }
- }
- get documentElement() {
- return this.querySelector('html');
- }
- get body() {
- return this.querySelector('body');
- }
- setStyle(node, style) {
- this._styleMap.set(node, style);
- }
- getStyle(el) {
- return this._styleMap.get(el.node) || makeStaticStyle();
- }
-}
-
-function makeStaticStyle(values = {}) {
- const style = { ...STATIC_DEFAULT_STYLE, ...values };
- style.getPropertyValue = (prop) => {
- const key = cssPropToCamel(prop);
- return style[key] || style[prop] || '';
- };
- return style;
-}
-
-function buildStaticWindow(staticDoc) {
- return {
- document: staticDoc,
- getComputedStyle: (el) => staticDoc.getStyle(el),
- };
-}
-
-function collectStaticCssText(root, fileDir, profile, filePath, modules) {
- const styleTexts = [];
- for (const styleEl of modules.selectAll('style', root.children || [])) {
- styleTexts.push(modules.domutils.textContent(styleEl));
- }
- const links = modules.selectAll('link', root.children || []);
- for (const link of links) {
- const rel = link.attribs?.rel || '';
- const href = link.attribs?.href || '';
- if (!/\bstylesheet\b/i.test(rel) || !href || /^(https?:)?\/\//i.test(href)) continue;
- const cssPath = path.resolve(fileDir, href);
- try {
- const css = profileStep(profile, {
- engine: 'static-html',
- phase: 'preprocess',
- ruleId: 'inline-linked-stylesheet',
- target: filePath,
- detail: href,
- }, () => fs.readFileSync(cssPath, 'utf-8'));
- styleTexts.push(css);
- } catch { /* skip unreadable */ }
- }
- return styleTexts.join('\n');
-}
-
-function buildStaticStyleMap(root, staticDoc, cssText, modules, profile, filePath) {
- const specified = new Map();
- const allNodes = modules.selectAll('*', root.children || []);
- const rules = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-css',
- ruleId: 'css-rules',
- target: filePath,
- }, () => collectStaticCssRules(cssText, modules.csstree));
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'css-selectors',
- target: filePath,
- }, () => {
- for (const rule of rules) {
- let matched;
- try {
- matched = modules.selectAll(rule.selector, root.children || []);
- } catch {
- recordProfileEvent(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'unsupported-selector',
- target: filePath,
- ms: 0,
- findings: 0,
- detail: rule.selector,
- });
- continue;
- }
- for (const node of matched) {
- for (const decl of rule.declarations) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: rule.specificity,
- order: rule.order,
- inline: false,
- });
- }
- }
- }
-
- let inlineOrder = rules.length + 1;
- for (const node of allNodes) {
- const styleText = node.attribs?.style;
- if (!styleText) continue;
- for (const decl of parseStaticStyleAttribute(styleText, inlineOrder)) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: [1, 0, 0],
- order: decl.order,
- inline: true,
- });
- }
- inlineOrder += 1000;
- }
- });
-
- const computeNode = (node, parentStyle = null, parentCustom = new Map()) => {
- const specifiedMap = specified.get(node) || new Map();
- const customProps = new Map(parentCustom);
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) customProps.set(prop, resolveVarRefs(decl.value, customProps));
- }
- const values = {};
- for (const prop of Object.keys(STATIC_DEFAULT_STYLE)) {
- if (STATIC_INHERITED_PROPS.has(prop) && parentStyle?.[prop] != null) values[prop] = parentStyle[prop];
- else values[prop] = STATIC_DEFAULT_STYLE[prop];
- }
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) continue;
- values[prop] = normalizeStaticCssValue(prop, decl.value, customProps, parentStyle, values);
- }
- const style = makeStaticStyle(values);
- staticDoc.setStyle(node, style);
- for (const child of node.children || []) {
- if (child.type === 'tag') computeNode(child, style, customProps);
- }
- };
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'cascade',
- ruleId: 'compute-styles',
- target: filePath,
- }, () => {
- for (const child of root.children || []) {
- if (child.type === 'tag') computeNode(child);
- }
- });
-}
-
-export {
- BORDER_SHORTHAND_RE,
- NAMED_COLORS,
- normalizeColorForCheck,
- buildBorderOverrideMap,
- unwrapCssAtLayer,
- STATIC_INHERITED_PROPS,
- STATIC_DEFAULT_STYLE,
- STATIC_PROP_MAP,
- STATIC_NAMED_COLORS,
- splitCssList,
- splitCssTokens,
- cssPropToCamel,
- staticColorToCss,
- parseStaticColor,
- extractStaticColor,
- normalizeStaticCssValue,
- expandStaticBoxValues,
- parseStaticBorder,
- parseStaticFont,
- parseStaticTransition,
- parseStaticAnimation,
- expandStaticDeclaration,
- compareStaticPriority,
- staticSpecificity,
- applyStaticDeclaration,
- parseStaticStyleAttribute,
- collectStaticCssRules,
- StaticElement,
- StaticDocument,
- makeStaticStyle,
- buildStaticWindow,
- collectStaticCssText,
- buildStaticStyleMap,
-};
@@ -1,174 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import {
- checkElementBorders,
- checkElementColors,
- checkElementGlow,
- checkElementHeroEyebrow,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementMotion,
- checkElementQuality,
- checkHtmlPatterns,
- checkPageLayout,
- checkPageQualityFromDoc,
- checkRepeatedSectionKickersFromDoc,
- resolveBackground,
- resolveBorderRadiusPx,
-} from '../../rules/checks.mjs';
-import { detectText } from '../regex/detect-text.mjs';
-import {
- StaticDocument,
- buildStaticStyleMap,
- buildStaticWindow,
- collectStaticCssText,
-} from './css-cascade.mjs';
-
-function checkStaticPageTypography(document, window) {
- const findings = [];
- const fonts = new Set();
- const overusedFound = new Set();
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span, div')) {
- const hasText = el.childNodes.some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const ff = window.getComputedStyle(el).fontFamily || '';
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
- if (fonts.size === 1 && document.querySelectorAll('*').length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div')) {
- const fontSize = parseFloat(window.getComputedStyle(el).fontSize);
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
- return findings;
-}
-
-const STATIC_ELEMENT_RULES = [
- { id: 'border-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementBorders(tag, style, null, resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window)) },
- { id: 'color-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementColors(el, style, tag, window, customPropMap, false) },
- { id: 'dark-glow', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window, customPropMap)) },
- { id: 'motion-rules', selector: '*', run: (el, tag, style) => checkElementMotion(tag, style) },
- { id: 'icon-tile-stack', selector: 'h1,h2,h3,h4,h5,h6', run: (el, tag, _style, window) => checkElementIconTile(el, tag, window) },
- { id: 'italic-serif-display', selector: 'h1,h2', run: (el, tag, style) => checkElementItalicSerif(el, style, tag) },
- { id: 'hero-eyebrow-chip', selector: 'h1', run: (el, tag, style, window, customPropMap) => checkElementHeroEyebrow(el, style, tag, window, customPropMap) },
- { id: 'quality-rules', selector: '*', run: (el, tag, style, window) => checkElementQuality(el, style, tag, window) },
-];
-
-async function detectHtml(filePath, options = {}) {
- const profile = options?.profile;
- const html = profileStep(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'read-html',
- target: filePath,
- }, () => fs.readFileSync(filePath, 'utf-8'));
-
- let modules;
- try {
- modules = await profileStepAsync(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'import-static-parser',
- target: filePath,
- }, async () => {
- const [htmlparser2, cssSelect, csstree, domutils] = await Promise.all([
- import('htmlparser2'),
- import('css-select'),
- import('css-tree'),
- import('domutils'),
- ]);
- return {
- parseDocument: htmlparser2.parseDocument,
- selectAll: cssSelect.selectAll,
- selectOne: cssSelect.selectOne,
- is: cssSelect.is,
- csstree,
- domutils,
- };
- });
- } catch {
- return detectText(html, filePath, options);
- }
-
- const resolvedPath = path.resolve(filePath);
- const fileDir = path.dirname(resolvedPath);
- const root = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-html',
- ruleId: 'parse-document',
- target: filePath,
- }, () => modules.parseDocument(html, { lowerCaseAttributeNames: false, lowerCaseTags: true }));
-
- const cssText = collectStaticCssText(root, fileDir, profile, filePath, modules);
- const document = new StaticDocument(root, modules);
- buildStaticStyleMap(root, document, cssText, modules, profile, filePath);
- const window = buildStaticWindow(document);
-
- const customPropMap = null;
-
- const findings = [];
- const runElementCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'element', ruleId, target: filePath }, callback)
- : callback();
-
- const visitedByRule = new Map();
- for (const rule of STATIC_ELEMENT_RULES) {
- const elements = document.querySelectorAll(rule.selector);
- visitedByRule.set(rule.id, elements.length);
- for (const el of elements) {
- const tag = el.tagName.toLowerCase();
- const style = window.getComputedStyle(el);
- for (const f of runElementCheck(rule.id, () => rule.run(el, tag, style, window, customPropMap))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
- }
-
- if (isFullPage(html)) {
- const runPageCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
- : callback();
- for (const f of runPageCheck('typography-rules', () => checkStaticPageTypography(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('repeated-section-kickers', () => checkRepeatedSectionKickersFromDoc(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('layout-rules', () => checkPageLayout(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('skipped-heading', () => checkPageQualityFromDoc(document))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('html-patterns', () => checkHtmlPatterns(html).filter(item =>
- item.id !== 'bounce-easing' && item.id !== 'layout-transition'
- ))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
-
- return findings;
-}
-
-export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -1,189 +0,0 @@
-function sanitizeScreenshotClip(clip, viewport) {
- if (!clip) return null;
- const x = Math.max(0, Math.floor(clip.x || 0));
- const y = Math.max(0, Math.floor(clip.y || 0));
- const width = Math.min(
- Math.max(1, Math.ceil(clip.width || 0)),
- Math.max(1, viewport?.width || 1600),
- );
- const height = Math.min(
- Math.max(1, Math.ceil(clip.height || 0)),
- 320,
- );
- if (width < 1 || height < 1) return null;
- return { x, y, width, height };
-}
-
-async function compareScreenshotContrast(page, beforeBase64, afterBase64, candidate) {
- return page.evaluate(async ({ beforeBase64, afterBase64, candidate }) => {
- const loadImage = (base64) => new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = () => reject(new Error('Could not decode contrast screenshot'));
- img.src = `data:image/png;base64,${base64}`;
- });
- const [before, after] = await Promise.all([loadImage(beforeBase64), loadImage(afterBase64)]);
- const width = Math.min(before.width, after.width);
- const height = Math.min(before.height, after.height);
- if (width < 1 || height < 1) return null;
-
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return null;
-
- ctx.drawImage(before, 0, 0, width, height);
- const beforePixels = ctx.getImageData(0, 0, width, height).data;
- ctx.clearRect(0, 0, width, height);
- ctx.drawImage(after, 0, 0, width, height);
- const afterPixels = ctx.getImageData(0, 0, width, height).data;
-
- const luminance = ({ r, g, b }) => {
- const convert = c => {
- const v = c / 255;
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
- };
- return 0.2126 * convert(r) + 0.7152 * convert(g) + 0.0722 * convert(b);
- };
- const ratio = (a, b) => {
- const l1 = luminance(a);
- const l2 = luminance(b);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
- };
-
- const cssTextColor = candidate.textColor && !candidate.preferRenderedForeground
- ? {
- r: candidate.textColor.r,
- g: candidate.textColor.g,
- b: candidate.textColor.b,
- }
- : null;
- const ratios = [];
- let glyphPixels = 0;
- let strongestDelta = 0;
- for (let i = 0; i < beforePixels.length; i += 4) {
- const delta = Math.abs(beforePixels[i] - afterPixels[i])
- + Math.abs(beforePixels[i + 1] - afterPixels[i + 1])
- + Math.abs(beforePixels[i + 2] - afterPixels[i + 2])
- + Math.abs(beforePixels[i + 3] - afterPixels[i + 3]);
- strongestDelta = Math.max(strongestDelta, delta);
- if (delta < 10) continue;
- glyphPixels++;
- const fg = cssTextColor || {
- r: beforePixels[i],
- g: beforePixels[i + 1],
- b: beforePixels[i + 2],
- };
- const bg = {
- r: afterPixels[i],
- g: afterPixels[i + 1],
- b: afterPixels[i + 2],
- };
- ratios.push(ratio(fg, bg));
- }
-
- if (ratios.length < 8) {
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: null,
- p10Ratio: null,
- medianRatio: null,
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: ratios[0],
- p10Ratio: pick(10),
- medianRatio: pick(50),
- };
- }, { beforeBase64, afterBase64, candidate });
-}
-
-async function captureVisualContrastCandidate(page, candidate, viewport) {
- const clip = sanitizeScreenshotClip(candidate.clip, viewport);
- if (!clip) return null;
-
- const beforeBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- const token = `impeccable-contrast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- const applied = await page.evaluate(({ selector, token, backgroundClipText }) => {
- let el;
- try {
- el = document.querySelector(selector);
- } catch {
- return false;
- }
- if (!el) return false;
- let style = document.getElementById('impeccable-visual-contrast-hide-style');
- if (!style) {
- style = document.createElement('style');
- style.id = 'impeccable-visual-contrast-hide-style';
- style.textContent = [
- '[data-impeccable-visual-contrast-target] {',
- ' color: transparent !important;',
- ' -webkit-text-fill-color: transparent !important;',
- ' text-shadow: none !important;',
- '}',
- '[data-impeccable-visual-contrast-target][data-impeccable-bgclip-text="true"] {',
- ' background-image: none !important;',
- '}',
- ].join('\n');
- document.head.appendChild(style);
- }
- el.setAttribute('data-impeccable-visual-contrast-target', token);
- if (backgroundClipText) el.setAttribute('data-impeccable-bgclip-text', 'true');
- return true;
- }, {
- selector: candidate.selector,
- token,
- backgroundClipText: candidate.backgroundClipText,
- });
- if (!applied) return null;
-
- let afterBase64;
- try {
- afterBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- } finally {
- await page.evaluate(({ selector }) => {
- try {
- const el = document.querySelector(selector);
- if (el) {
- el.removeAttribute('data-impeccable-visual-contrast-target');
- el.removeAttribute('data-impeccable-bgclip-text');
- }
- } catch {
- // Ignore invalid or stale selectors during cleanup.
- }
- }, { selector: candidate.selector }).catch(() => {});
- }
-
- const metrics = await compareScreenshotContrast(page, beforeBase64, afterBase64, candidate);
- if (!metrics || !Number.isFinite(metrics.p10Ratio) || metrics.glyphPixels < 8) return null;
- const measuredRatio = metrics.p10Ratio;
- if (measuredRatio >= candidate.threshold) return null;
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const reasonLabel = (candidate.reasons || []).slice(0, 3).join(', ') || 'visual background';
- return {
- id: 'low-contrast',
- snippet: `pixel contrast ${measuredRatio.toFixed(1)}:1 median ${metrics.medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) on ${reasonLabel}${textLabel}`,
- };
-}
-
-export {
- sanitizeScreenshotClip,
- compareScreenshotContrast,
- captureVisualContrastCandidate,
-};
@@ -1,12 +0,0 @@
-import { getAntipattern } from './registry/antipatterns.mjs';
-
-function getAP(id) {
- return getAntipattern(id);
-}
-
-function finding(id, filePath, snippet, line = 0) {
- const ap = getAP(id);
- return { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', file: filePath, line, snippet };
-}
-
-export { getAP, finding };
@@ -1,198 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-// ---------------------------------------------------------------------------
-// File walker
-// ---------------------------------------------------------------------------
-
-const SKIP_DIRS = new Set([
- 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
- '.svelte-kit', '__pycache__', '.turbo', '.vercel',
-]);
-
-const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
- '.jsx', '.tsx', '.js', '.ts',
- '.vue', '.svelte', '.astro',
-]);
-
-const HTML_EXTENSIONS = new Set(['.html', '.htm']);
-
-function walkDir(dir) {
- const files = [];
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
- for (const entry of entries) {
- if (SKIP_DIRS.has(entry.name)) continue;
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) files.push(...walkDir(full));
- else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
- }
- return files;
-}
-
-
-// ---------------------------------------------------------------------------
-// Import graph (multi-file awareness)
-// ---------------------------------------------------------------------------
-
-function resolveImport(specifier, fromDir, fileSet) {
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
- const base = path.resolve(fromDir, specifier);
- if (fileSet.has(base)) return base;
- for (const ext of SCANNABLE_EXTENSIONS) {
- const withExt = base + ext;
- if (fileSet.has(withExt)) return withExt;
- }
- // index file convention
- for (const ext of SCANNABLE_EXTENSIONS) {
- const indexFile = path.join(base, 'index' + ext);
- if (fileSet.has(indexFile)) return indexFile;
- }
- return null;
-}
-
-function buildImportGraph(files) {
- const fileSet = new Set(files);
- const graph = new Map();
-
- for (const file of files) {
- const content = fs.readFileSync(file, 'utf-8');
- const dir = path.dirname(file);
- const imports = new Set();
-
- // ES imports: import ... from '...' and import '...'
- const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
- let m;
- while ((m = esRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // CSS @import
- const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
- while ((m = cssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // SCSS @use / @forward
- const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
- while ((m = scssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- graph.set(file, imports);
- }
- return graph;
-}
-
-// ---------------------------------------------------------------------------
-// Framework dev server detection
-// ---------------------------------------------------------------------------
-
-const FRAMEWORK_CONFIGS = [
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /next/i } },
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-sveltekit-page', value: null } },
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /@vite\/client/ } },
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /astro/i } },
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
- portRe: /"port"\s*:\s*(\d+)/,
- fingerprint: { body: /ng-version/i } },
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
-];
-
-function detectFrameworkConfig(dir) {
- let entries;
- try { entries = fs.readdirSync(dir); } catch { return null; }
- const entrySet = new Set(entries);
-
- for (const cfg of FRAMEWORK_CONFIGS) {
- const match = cfg.files.find(f => entrySet.has(f));
- if (!match) continue;
-
- const configPath = path.join(dir, match);
- let port = cfg.defaultPort;
- try {
- const content = fs.readFileSync(configPath, 'utf-8');
- const portMatch = content.match(cfg.portRe);
- if (portMatch) port = parseInt(portMatch[1], 10);
- } catch { /* use default */ }
-
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
- }
- return null;
-}
-
-/**
- * Check if a port is listening and optionally verify it matches the expected framework.
- * Returns { listening: true, matched: true/false } or { listening: false }.
- */
-async function isPortListening(port, fingerprint = null) {
- if (!fingerprint) {
- // Simple TCP probe fallback
- const net = await import('node:net');
- return new Promise((resolve) => {
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
- sock.setTimeout(500);
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
- sock.on('error', () => resolve({ listening: false }));
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
- });
- }
-
- // HTTP probe with fingerprint matching
- try {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 2000);
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
- clearTimeout(timeout);
-
- // Check header fingerprint
- if (fingerprint.header) {
- const val = res.headers.get(fingerprint.header);
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
- return { listening: true, matched: true };
- }
- }
-
- // Check body fingerprint
- if (fingerprint.body) {
- const body = await res.text();
- if (fingerprint.body.test(body)) {
- return { listening: true, matched: true };
- }
- }
-
- // Port is listening but doesn't match the expected framework
- return { listening: true, matched: false };
- } catch {
- return { listening: false };
- }
-}
-
-export {
- SKIP_DIRS,
- SCANNABLE_EXTENSIONS,
- HTML_EXTENSIONS,
- walkDir,
- resolveImport,
- buildImportGraph,
- FRAMEWORK_CONFIGS,
- detectFrameworkConfig,
- isPortListening,
-};
@@ -1,166 +0,0 @@
-function profileNow() {
- return typeof performance !== 'undefined' && performance.now
- ? performance.now()
- : Date.now();
-}
-
-function createDetectorProfile() {
- return { events: [] };
-}
-
-function recordProfileEvent(profile, event) {
- if (!profile) return;
- const normalized = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- ms: Number.isFinite(event.ms) ? event.ms : 0,
- findings: Number.isFinite(event.findings) ? event.findings : 0,
- };
- if (event.detail) normalized.detail = event.detail;
- if (Array.isArray(event.findingIds) && event.findingIds.length) {
- normalized.findingIds = event.findingIds;
- }
- if (typeof profile === 'function') {
- profile(normalized);
- } else if (typeof profile.record === 'function') {
- profile.record(normalized);
- } else if (Array.isArray(profile.events)) {
- profile.events.push(normalized);
- } else if (Array.isArray(profile)) {
- profile.push(normalized);
- }
-}
-
-function extractFindingIds(findings) {
- if (!Array.isArray(findings) || findings.length === 0) return [];
- return [...new Set(findings.map(f => f?.id || f?.type || f?.antipattern).filter(Boolean))];
-}
-
-function profileFindings(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-function profileStep(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-async function profileFindingsAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = await callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-async function profileStepAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return await callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-function percentile(sortedValues, pct) {
- if (!sortedValues.length) return 0;
- const idx = Math.min(
- sortedValues.length - 1,
- Math.max(0, Math.ceil((pct / 100) * sortedValues.length) - 1),
- );
- return sortedValues[idx];
-}
-
-function summarizeDetectorProfile(profile) {
- const events = Array.isArray(profile)
- ? profile
- : (Array.isArray(profile?.events) ? profile.events : []);
- const groups = new Map();
- for (const event of events) {
- const key = [
- event.engine || 'unknown',
- event.phase || 'unknown',
- event.ruleId || 'unknown',
- event.target || '',
- ].join('\u0000');
- let group = groups.get(key);
- if (!group) {
- group = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- calls: 0,
- totalMs: 0,
- findings: 0,
- samples: [],
- };
- groups.set(key, group);
- }
- const ms = Number.isFinite(event.ms) ? event.ms : 0;
- group.calls += 1;
- group.totalMs += ms;
- group.findings += Number.isFinite(event.findings) ? event.findings : 0;
- group.samples.push(ms);
- }
- return [...groups.values()]
- .map(group => {
- const samples = group.samples.sort((a, b) => a - b);
- return {
- engine: group.engine,
- phase: group.phase,
- ruleId: group.ruleId,
- target: group.target,
- calls: group.calls,
- totalMs: Number(group.totalMs.toFixed(3)),
- avgMs: Number((group.totalMs / group.calls).toFixed(3)),
- p50: Number(percentile(samples, 50).toFixed(3)),
- p95: Number(percentile(samples, 95).toFixed(3)),
- findings: group.findings,
- };
- })
- .sort((a, b) => b.totalMs - a.totalMs);
-}
-
-export {
- profileNow,
- createDetectorProfile,
- recordProfileEvent,
- extractFindingIds,
- profileFindings,
- profileStep,
- profileFindingsAsync,
- profileStepAsync,
- percentile,
- summarizeDetectorProfile,
-};
@@ -1,278 +0,0 @@
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-const RULE_ENGINE_SUPPORT = {
- regex: new Set(['source', 'page-analyzer']),
- 'static-html': new Set(['element', 'page']),
- browser: new Set(['element', 'page', 'layout']),
- visual: new Set(['visual-contrast']),
-};
-
-function getAntipattern(id) {
- return ANTIPATTERNS.find(rule => rule.id === id);
-}
-
-function getRulesForCategory(category) {
- return ANTIPATTERNS.filter(rule => rule.category === category);
-}
-
-function getRuleEngineSupport(engine) {
- return RULE_ENGINE_SUPPORT[engine] || new Set();
-}
-
-export {
- ANTIPATTERNS,
- RULE_ENGINE_SUPPORT,
- getAntipattern,
- getRulesForCategory,
- getRuleEngineSupport,
-};
@@ -1,1948 +0,0 @@
-import {
- BORDER_SAFE_TAGS,
- GENERIC_FONTS,
- KNOWN_SERIF_FONTS,
- OVERUSED_FONTS,
- SAFE_TAGS,
- WCAG_LARGE_BOLD_TEXT_PX,
- WCAG_LARGE_TEXT_PX,
- isBrandFontOnOwnDomain,
-} from '../shared/constants.mjs';
-import {
- colorToHex,
- contrastRatio,
- getHue,
- hasChroma,
- isNeutralColor,
- parseGradientColors,
- parseRgb,
- relativeLuminance,
-} from '../shared/color.mjs';
-
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-export {
- checkBorders,
- isEmojiOnlyText,
- checkColors,
- isCardLikeFromProps,
- checkIconTile,
- resolveSerif,
- checkItalicSerif,
- isAccentColor,
- checkHeroEyebrow,
- checkRepeatedSectionKickers,
- checkMotion,
- checkGlow,
- checkHtmlPatterns,
- readOwnBackgroundColor,
- resolveBackground,
- resolveGradientStops,
- parseRadiusToPx,
- resolveBorderRadiusPx,
- checkElementBordersDOM,
- checkElementColorsDOM,
- checkElementIconTileDOM,
- checkElementItalicSerifDOM,
- checkElementHeroEyebrowDOM,
- buildCustomPropMap,
- resolveVarRefs,
- oklchToRgb,
- parseAnyColor,
- parseColorResolved,
- cleanInlineText,
- isRepeatedKickerCandidate,
- collectRepeatedSectionKickerCandidates,
- checkRepeatedSectionKickersDOM,
- checkElementMotionDOM,
- checkElementGlowDOM,
- checkElementAIPaletteDOM,
- resolveFontSizePx,
- resolveLengthPx,
- checkQuality,
- checkElementQualityDOM,
- checkPageQualityFromDoc,
- checkPageQualityDOM,
- checkElementQuality,
- checkElementBorders,
- checkElementColors,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementHeroEyebrow,
- checkRepeatedSectionKickersFromDoc,
- checkElementMotion,
- checkElementGlow,
- checkTypography,
- isCardLikeDOM,
- checkLayout,
- checkPageTypography,
- isCardLike,
- checkPageLayout,
-};
@@ -1,124 +0,0 @@
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-export {
- isNeutralColor,
- parseRgb,
- relativeLuminance,
- contrastRatio,
- parseGradientColors,
- hasChroma,
- getHue,
- colorToHex,
-};
@@ -1,101 +0,0 @@
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-export {
- SAFE_TAGS,
- BORDER_SAFE_TAGS,
- OVERUSED_FONTS,
- GOOGLE_DOMAINS,
- VERCEL_DOMAINS,
- GITHUB_DOMAINS,
- BRAND_FONT_DOMAINS,
- isBrandFontOnOwnDomain,
- GENERIC_FONTS,
- WCAG_LARGE_TEXT_PX,
- WCAG_LARGE_BOLD_TEXT_PX,
- KNOWN_SERIF_FONTS,
-};
@@ -1,7 +0,0 @@
-/** Check if content looks like a full page (not a component/partial) */
-function isFullPage(content) {
- const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
- return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
-}
-
-export { isFullPage };
@@ -1,110 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-export const IMPECCABLE_DIR = '.impeccable';
-export const LIVE_DIR = 'live';
-export const CRITIQUE_DIR = 'critique';
-
-export function getImpeccableDir(cwd = process.cwd()) {
- return path.join(cwd, IMPECCABLE_DIR);
-}
-
-export function getDesignSidecarPath(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), 'design.json');
-}
-
-export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {
- const candidates = [
- getDesignSidecarPath(cwd),
- path.join(cwd, 'DESIGN.json'),
- ];
- const contextLegacy = path.join(contextDir, 'DESIGN.json');
- if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
- return candidates;
-}
-
-export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
- return firstExisting(getDesignSidecarCandidates(cwd, contextDir));
-}
-
-export function getLiveDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), LIVE_DIR);
-}
-
-export function getLiveConfigPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'config.json');
-}
-
-export function getLegacyLiveConfigPath(scriptsDir) {
- return path.join(scriptsDir, 'config.json');
-}
-
-export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {
- if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
- const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
- return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
- }
- const primary = getLiveConfigPath(cwd);
- if (fs.existsSync(primary)) return primary;
- if (scriptsDir) {
- const legacy = getLegacyLiveConfigPath(scriptsDir);
- if (fs.existsSync(legacy)) return legacy;
- }
- return primary;
-}
-
-export function getLiveServerPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'server.json');
-}
-
-export function getLegacyLiveServerPath(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live.json');
-}
-
-export function readLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try {
- return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };
- } catch {
- /* try next */
- }
- }
- return null;
-}
-
-export function writeLiveServerInfo(cwd = process.cwd(), info) {
- const filePath = getLiveServerPath(cwd);
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- fs.writeFileSync(filePath, JSON.stringify(info));
- return filePath;
-}
-
-export function removeLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try { fs.unlinkSync(filePath); } catch {}
- }
-}
-
-export function getLiveSessionsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'sessions');
-}
-
-export function getLegacyLiveSessionsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'sessions');
-}
-
-export function getLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'annotations');
-}
-
-export function getCritiqueDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), CRITIQUE_DIR);
-}
-
-export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'annotations');
-}
-
-function firstExisting(paths) {
- return paths.find((filePath) => fs.existsSync(filePath)) || null;
-}
@@ -1,69 +0,0 @@
-/**
- * Decide whether a given file is "generated" (regenerated by a build step,
- * unsafe to write variants into) or "source" (safe to edit, changes persist).
- *
- * Why this matters: when the user picks an element on a page whose underlying
- * file is regenerated by a build step (e.g. `scripts/build-sub-pages.js`
- * rewriting `public/docs/*.html`), writing variants or accepted changes into
- * that file is silent data loss — the next build wipes them.
- *
- * Signals, in order of reliability:
- * 1. Git check-ignore: gitignored files are assumed generated.
- * 2. File-header markers ("GENERATED", "DO NOT EDIT", "AUTO-GENERATED")
- * within the first ~300 characters — catches non-git projects.
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-
-const HEADER_SCAN_BYTES = 300;
-const HEADER_MARKERS = [
- /@generated\b/i,
- /\bGENERATED\s+FILE\b/,
- /\bAUTO-?GENERATED\b/i,
- /\bDO\s+NOT\s+EDIT\b/i,
-];
-
-/**
- * @param {string} filePath - absolute or cwd-relative path
- * @param {object} [options]
- * @param {string} [options.cwd] - project root (defaults to process.cwd())
- */
-export function isGeneratedFile(filePath, options = {}) {
- const cwd = options.cwd || process.cwd();
- const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
-
- if (isGitIgnored(absPath, cwd)) return true;
- if (hasGeneratedHeader(absPath)) return true;
- return false;
-}
-
-function isGitIgnored(absPath, cwd) {
- try {
- execSync(`git check-ignore --quiet ${JSON.stringify(absPath)}`, {
- cwd,
- stdio: 'ignore',
- });
- return true; // exit 0 = ignored
- } catch (err) {
- // Exit code 1 = not ignored. Exit code 128 = not a git repo or other error.
- // In both cases, treat as "not known to be ignored."
- return false;
- }
-}
-
-function hasGeneratedHeader(absPath) {
- let fd;
- try {
- fd = fs.openSync(absPath, 'r');
- const buf = Buffer.alloc(HEADER_SCAN_BYTES);
- const bytesRead = fs.readSync(fd, buf, 0, HEADER_SCAN_BYTES, 0);
- const head = buf.slice(0, bytesRead).toString('utf-8');
- return HEADER_MARKERS.some((re) => re.test(head));
- } catch {
- return false;
- } finally {
- if (fd !== undefined) { try { fs.closeSync(fd); } catch {} }
- }
-}
@@ -1,595 +0,0 @@
-/**
- * CLI helper: deterministic accept/discard of variant sessions.
- *
- * Usage:
- * node live-accept.mjs --id SESSION_ID --discard
- * node live-accept.mjs --id SESSION_ID --variant N
- *
- * For discard: removes the entire variant wrapper and restores the original.
- * For accept: replaces the wrapper with the chosen variant's content. If the
- * session had a colocated <style> block, it's preserved with carbonize markers
- * for a background agent to integrate into the project's CSS.
- *
- * Output: JSON to stdout.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-export async function acceptCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-accept.mjs [options]
-
-Deterministic accept/discard for live variant sessions.
-
-Modes:
- --discard Remove variants, restore original
- --variant N Accept variant N, discard the rest
-
-Required:
- --id SESSION_ID Session ID of the variant wrapper
-
-Output (JSON):
- { handled, file, carbonize }`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const variantNum = argVal(args, '--variant');
- const paramValuesRaw = argVal(args, '--param-values');
- const isDiscard = args.includes('--discard');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }
-
- let paramValues = null;
- if (paramValuesRaw) {
- try { paramValues = JSON.parse(paramValuesRaw); }
- catch { paramValues = null; } // malformed blob: skip the comment rather than failing the accept
- }
-
- // Find the file containing this session's markers
- const found = findSessionFile(id, process.cwd());
- if (!found) {
- console.log(JSON.stringify({ handled: false, error: 'Session markers not found for id: ' + id }));
- process.exit(0);
- }
-
- const { file: targetFile, content, lines } = found;
- const relFile = path.relative(process.cwd(), targetFile);
-
- // Bail if the session lives in a generated file. The agent manually wrote
- // the wrapper there for preview, and is responsible for writing the
- // accepted variant to true source (or cleaning up on discard). See
- // "Handle fallback" in live.md.
- if (isGeneratedFile(targetFile, { cwd: process.cwd() })) {
- console.log(JSON.stringify({
- handled: false,
- mode: 'fallback',
- file: relFile,
- hint: 'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.',
- }));
- process.exit(0);
- }
-
- if (isDiscard) {
- const result = handleDiscard(id, lines, targetFile);
- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));
- } else {
- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);
- // Single-line attention-grabber when cleanup is required. The full
- // five-step checklist lives in reference/live.md (loaded once per
- // session); repeating it per-event would waste tokens.
- if (result.carbonize) {
- result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + relFile + '. See reference/live.md "Required after accept".';
- }
- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));
- }
-}
-
-// ---------------------------------------------------------------------------
-// Discard
-// ---------------------------------------------------------------------------
-
-function handleDiscard(id, lines, targetFile) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const original = extractOriginal(lines, block);
- const isJsx = detectCommentSyntax(targetFile).open === '{/*';
- const replaceRange = expandReplaceRange(block, lines, isJsx);
-
- // Restore at the line we're actually replacing FROM, not the marker line.
- // For JSX wrappers the marker comments live INSIDE the outer `<div>`, so
- // `block.start` sits 2 spaces deeper than the original element. Using that
- // as the deindent base would push the restored content 2 spaces too far
- // right on every JSX/TSX session. `replaceRange.start` is the outer wrapper
- // line, which is at the original element's indent for both HTML and JSX.
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
- const restored = deindentContent(original, indent);
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...restored,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
- return {};
-}
-
-// ---------------------------------------------------------------------------
-// Accept
-// ---------------------------------------------------------------------------
-
-function handleAccept(id, variantNum, lines, targetFile, paramValues) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const commentSyntax = detectCommentSyntax(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- // Anchor indent on the line we're replacing FROM (the outer wrapper),
- // not on `block.start` — for JSX that's the marker comment 2 spaces
- // deeper than the original element. See handleDiscard for the full
- // rationale.
- const replaceRange = expandReplaceRange(block, lines, isJsx);
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
-
- // Extract the chosen variant's inner content
- const variantContent = extractVariant(lines, block, variantNum);
- if (!variantContent) return { handled: false, error: 'Variant ' + variantNum + ' not found' };
-
- // Extract CSS block if present
- const cssContent = extractCss(lines, block, id);
-
- // Check if carbonizing is needed:
- // - CSS block exists, OR
- // - variant HTML contains helper classes/attributes that need cleanup
- const variantText = variantContent.join('\n');
- const hasHelperAttrs = variantText.includes('data-impeccable-variant');
- const needsCarbonize = !!(cssContent || hasHelperAttrs);
-
- // Build the replacement
- const restored = deindentContent(variantContent, indent);
- const replacement = [];
-
- if (cssContent) {
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
- // JSX targets need the CSS body wrapped in a template literal so that the
- // `{` and `}` in CSS rules don't get parsed as JSX expressions.
- replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
- // Re-indent CSS content to match
- for (const cssLine of cssContent) {
- replacement.push(indent + cssLine.trimStart());
- }
- replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
- if (paramValues && Object.keys(paramValues).length > 0) {
- // Preserve the user's knob positions for the carbonize-cleanup agent
- // to bake into the final CSS when it collapses scoped rules.
- replacement.push(indent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close);
- }
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close);
- }
-
- // Keep the `@scope ([data-impeccable-variant="N"])` selectors in the
- // carbonize CSS block working visually by re-wrapping the accepted content
- // in a data-impeccable-variant="N" div with `display: contents` (so layout
- // isn't affected). The carbonize agent strips this attribute + wrapper when
- // it moves the CSS to a proper stylesheet.
- //
- // Style attribute syntax has to follow the host file's flavor — JSX files
- // need the object form, otherwise React 19 throws "Failed to set indexed
- // property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
- if (cssContent) {
- const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
- replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
- replacement.push(...restored);
- replacement.push(indent + '</div>');
- } else {
- replacement.push(...restored);
- }
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...replacement,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- return { carbonize: needsCarbonize };
-}
-
-// ---------------------------------------------------------------------------
-// Parsing helpers
-// ---------------------------------------------------------------------------
-
-/**
- * Find the start/end marker lines for a session.
- * Returns { start, end } (0-indexed line numbers) or null.
- */
-function findMarkerBlock(id, lines) {
- let start = -1;
- let end = -1;
- const startPattern = 'impeccable-variants-start ' + id;
- const endPattern = 'impeccable-variants-end ' + id;
-
- for (let i = 0; i < lines.length; i++) {
- if (start === -1 && lines[i].includes(startPattern)) start = i;
- if (lines[i].includes(endPattern)) { end = i; break; }
- }
-
- return (start !== -1 && end !== -1) ? { start, end } : null;
-}
-
-/**
- * Compute the line range to REPLACE (vs. just the marker range to extract
- * from). For JSX/TSX wrappers, live-wrap places the marker comments INSIDE
- * the `<div data-impeccable-variants="ID">` outer wrapper so the picked
- * element's JSX slot keeps a single child — a Fragment `<></>` would have
- * solved the multi-sibling case but failed inside `asChild` / cloneElement
- * parents with "Invalid prop supplied to React.Fragment".
- *
- * That means the marker block is enclosed by the wrapper `<div>` opener
- * (with `data-impeccable-variants="ID"`) and its matching `</div>`. We
- * walk back to the opener and forward to the closer so accept/discard
- * remove the entire scaffold, not just the inner markers.
- *
- * Marker lines themselves stay where they were so extractOriginal /
- * extractVariant / extractCss continue to walk the same range.
- */
-function expandReplaceRange(block, lines, isJsx) {
- if (!isJsx) return { start: block.start, end: block.end };
-
- let { start, end } = block;
-
- // Walk back for the wrapper `<div data-impeccable-variants="..."` opener.
- // The attr may sit on a continuation line of a multi-line opening tag, so
- // also walk to the line that actually contains `<div`.
- for (let i = start - 1; i >= Math.max(0, start - 12); i--) {
- if (/data-impeccable-variants=/.test(lines[i])) {
- let opener = i;
- while (opener > 0 && !/<div\b/.test(lines[opener])) opener--;
- start = opener;
- break;
- }
- }
-
- // Walk forward to the matching `</div>` by div-depth tracking from the
- // wrapper opener. Operate on JOINED text instead of per-line: a
- // multi-line self-closing JSX `<div\n className="spacer"\n/>` would
- // fool per-line regex tracking (the `<div` line matches openRe but the
- // `/>` line never matches selfCloseRe since it needs `<div` on the same
- // line). That left depth permanently over-counted and the wrapper's
- // outer `</div>` orphaned after accept/discard. Single regex with
- // `[^>]*?` (which spans newlines in JS) handles either form correctly.
- const joined = lines.slice(start).join('\n');
- // Match either `<div … />` (self-close, group 1 is `/`), `<div … >`
- // (open, group 1 is empty), or `</div>`.
- const tagRe = /<div\b[^>]*?(\/?)>|<\/div\s*>/g;
- let depth = 0;
- let m;
- while ((m = tagRe.exec(joined)) !== null) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && m[1] === '/';
- if (isClose) depth--;
- else if (!isSelfClose) depth++;
- if (depth <= 0) {
- // m.index is offset within `joined`; convert back to a file line.
- const linesBefore = joined.slice(0, m.index + m[0].length).split('\n').length - 1;
- const candidateEnd = start + linesBefore;
- if (candidateEnd >= end) {
- end = candidateEnd;
- break;
- }
- }
- }
-
- return { start, end };
-}
-
-/**
- * Join wrapper lines into a single string with `<style>` elements removed so
- * marker matching and div-depth tracking aren't confused by:
- * - CSS `@scope ([data-impeccable-variant="N"])` strings that look like the
- * HTML marker we're searching for
- * - JSX self-closing `<style ... />` (no separate `</style>` to close on)
- * - Same-line `<style>…</style>` blocks
- * - Multi-line `<style>\n…\n</style>` blocks
- */
-function stripStyleAndJoin(lines, block) {
- const out = [];
- let inStyle = false;
- for (let i = block.start; i <= block.end; i++) {
- let line = lines[i];
-
- if (!inStyle) {
- // Strip any complete <style> elements on this line (self-closed or
- // same-line-closed), including their body content.
- line = line
- .replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/g, '')
- .replace(/<style\b[^>]*\/\s*>/g, '');
-
- // If a <style> opener remains (multi-line body starts here), strip from
- // the opener to end-of-line and flip into skip mode.
- const openerIdx = line.search(/<style\b/);
- if (openerIdx !== -1) {
- line = line.slice(0, openerIdx);
- inStyle = true;
- }
- out.push(line);
- } else {
- // In multi-line style body; drop everything until we see </style>.
- const closeIdx = line.search(/<\/style\s*>/);
- if (closeIdx !== -1) {
- inStyle = false;
- out.push(line.slice(closeIdx).replace(/<\/style\s*>/, ''));
- }
- // else: skip line entirely
- }
- }
- return out.join('\n');
-}
-
-/**
- * Find the inner content of `<TAG ...attrMatch...>…</TAG>` inside `text`,
- * handling nested same-tag elements via depth counting. `attrMatch` is a
- * regex source fragment that must appear inside the opener tag.
- * Returns the inner string (may be empty), or null if not found.
- */
-function extractInnerByAttr(text, attrMatch) {
- const openerRe = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*' + attrMatch + '[^>]*>');
- const openMatch = text.match(openerRe);
- if (!openMatch) return null;
-
- const tagName = openMatch[1];
- const innerStart = openMatch.index + openMatch[0].length;
-
- // Match any opener or closer of this tag name after innerStart.
- // (Does not match self-closing <TAG … />, which doesn't contribute to depth.)
- const tagRe = new RegExp('<(?:/)?' + tagName + '\\b[^>]*>', 'g');
- tagRe.lastIndex = innerStart;
-
- let depth = 1;
- let m;
- while ((m = tagRe.exec(text))) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && /\/\s*>$/.test(m[0]);
- if (isClose) {
- depth--;
- if (depth === 0) return text.slice(innerStart, m.index);
- } else if (!isSelfClose) {
- depth++;
- }
- }
- return null;
-}
-
-/**
- * Extract the original element content from within the variant wrapper.
- * Returns an array of lines.
- */
-function extractOriginal(lines, block) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="original"');
- if (inner === null) return [];
- return inner.split('\n');
-}
-
-/**
- * Extract a specific variant's inner content (stripping the wrapper div).
- * Returns an array of lines, or null if not found.
- */
-function extractVariant(lines, block, variantNum) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + variantNum + '"');
- if (inner === null) return null;
- const result = inner.split('\n');
- // Collapse a lone empty leading/trailing line (common after string splice).
- while (result.length > 1 && result[0].trim() === '') result.shift();
- while (result.length > 1 && result[result.length - 1].trim() === '') result.pop();
- return result.length > 0 ? result : null;
-}
-
-/**
- * Extract the colocated <style> block content (between the style tags).
- * Returns an array of CSS lines, or null if no style block found.
- *
- * Handles three shapes of `<style data-impeccable-css="ID" ...>`:
- * 1. Self-closing: `<style ... />` — no body; return null (nothing to carbonize).
- * 2. Same-line open+close: `<style>...</style>` — return the inner content.
- * 3. Multi-line: `<style>` on one line, `</style>` on a later line — return
- * the lines between them.
- */
-function extractCss(lines, block, id) {
- const styleAttr = 'data-impeccable-css="' + id + '"';
- let inStyle = false;
- const content = [];
-
- for (let i = block.start; i <= block.end; i++) {
- const line = lines[i];
-
- if (!inStyle && line.includes(styleAttr)) {
- // Self-closing: nothing to carbonize.
- if (/<style\b[^>]*\/\s*>/.test(line)) return null;
- // Same-line open + close: extract inner text.
- const sameLine = line.match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/);
- if (sameLine) {
- const inner = stripJsxTemplateWrap(sameLine[1]);
- return inner.length > 0 ? inner.split('\n') : null;
- }
- inStyle = true;
- continue; // skip the <style> opening tag
- }
-
- if (inStyle) {
- // Detect </style> anywhere on the line — JSX template-literal closes
- // (`}</style>`) put the close mid-line, and we don't want to absorb the
- // template-literal punctuation as CSS content.
- const closeIdx = line.indexOf('</style>');
- if (closeIdx !== -1) break;
- content.push(line);
- }
- }
-
- if (content.length === 0) return null;
- return stripJsxTemplateLines(content);
-}
-
-/**
- * Strip a JSX template-literal wrap (`{` … `}`) from CSS extracted out of a
- * `<style>` element in a JSX/TSX file. The agent may write the wrap with
- * `{` and `}` directly attached to the `<style>` tags, on their own lines,
- * or attached to the first/last CSS lines — all three are JSX-legal.
- *
- * Stripping is required because handleAccept re-wraps the CSS itself when
- * carbonizing. Without this, two consecutive accepts (or a previously-
- * accepted variants block being carbonized) would produce nested
- * `{` `{` … `}` `}`, which oxc rejects with "Expected `}` but found `@`".
- */
-function stripJsxTemplateLines(content) {
- const out = content.slice();
-
- // Drop any leading blank lines so we don't miss a `{` line buried below
- // them; same for trailing.
- while (out.length > 0 && out[0].trim() === '') out.shift();
- while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
- if (out.length === 0) return null;
-
- // Leading `{`: own line, or attached to the first CSS line.
- const firstTrim = out[0].trimStart();
- if (firstTrim === '{`') {
- out.shift();
- } else if (firstTrim.startsWith('{`')) {
- const idx = out[0].indexOf('{`');
- out[0] = out[0].slice(0, idx) + out[0].slice(idx + 2);
- if (out[0].trim() === '') out.shift();
- }
- if (out.length === 0) return null;
-
- // Trailing `` ` `` `}`: own line, or attached to the last CSS line.
- const lastIdx = out.length - 1;
- const lastTrim = out[lastIdx].trimEnd();
- if (lastTrim === '`}') {
- out.pop();
- } else if (lastTrim.endsWith('`}')) {
- const text = out[lastIdx];
- const idx = text.lastIndexOf('`}');
- out[lastIdx] = text.slice(0, idx) + text.slice(idx + 2);
- if (out[lastIdx].trim() === '') out.pop();
- }
-
- return out.length > 0 ? out : null;
-}
-
-function stripJsxTemplateWrap(text) {
- const lines = text.split('\n');
- const stripped = stripJsxTemplateLines(lines);
- return stripped ? stripped.join('\n') : '';
-}
-
-/**
- * De-indent content that was indented by live-wrap.mjs.
- * The wrap script adds `indent + ' '` (4 extra spaces) to each line.
- * We restore to just `indent` level.
- */
-function deindentContent(contentLines, baseIndent) {
- // Find the minimum indentation in the content to determine how much was added
- let minIndent = Infinity;
- for (const line of contentLines) {
- if (line.trim() === '') continue;
- const leadingSpaces = line.match(/^(\s*)/)[1].length;
- minIndent = Math.min(minIndent, leadingSpaces);
- }
- if (minIndent === Infinity) minIndent = 0;
-
- // Strip the extra indentation and re-add base indent
- return contentLines.map(line => {
- if (line.trim() === '') return '';
- return baseIndent + line.slice(minIndent);
- });
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- return { open: '<!--', close: '-->' };
-}
-
-// ---------------------------------------------------------------------------
-// File search (find the file containing session markers)
-// ---------------------------------------------------------------------------
-
-function findSessionFile(id, cwd) {
- const marker = 'impeccable-variants-start ' + id;
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, marker, seen, 0);
- if (result) {
- const content = fs.readFileSync(result, 'utf-8');
- return { file: result, content, lines: content.split('\n') };
- }
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth) {
- if (depth > 5) return null;
- let realDir;
- try { realDir = fs.realpathSync(dir); } catch { return null; }
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- if (!EXTENSIONS.includes(path.extname(entry.name).toLowerCase())) continue;
- const filePath = path.join(dir, entry.name);
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip */ }
- }
-
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
- if (result) return result;
- }
-
- return null;
-}
-
-// ---------------------------------------------------------------------------
-// Utilities
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-accept.mjs') || _running?.endsWith('live-accept.mjs/')) {
- acceptCli();
-}
-
-export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax };
@@ -1,123 +0,0 @@
-/**
- * Browser-side durable session helpers for Impeccable live mode.
- *
- * Kept separate from live-browser.js so recovery state can be tested without
- * booting the full overlay UI. Served before live-browser.js and attached to
- * window.__IMPECCABLE_LIVE_SESSION__.
- */
-(function (root) {
- 'use strict';
-
- function createLiveBrowserSessionState({ prefix, storage, idFactory }) {
- if (!prefix) throw new Error('prefix required');
- const store = storage || root.localStorage;
- const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };
- const sessionKey = prefix + '-session';
- const handledKey = sessionKey + '-handled';
- const scrollKey = sessionKey + '-scroll';
- let checkpointRevision = 0;
- const owner = makeId();
-
- function safeRead(key) {
- try { return store.getItem(key); } catch { return null; }
- }
-
- function safeWrite(key, value) {
- try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }
- }
-
- function safeRemove(key) {
- try { store.removeItem(key); } catch { /* unavailable storage */ }
- }
-
- function loadSession() {
- try {
- const raw = safeRead(sessionKey);
- if (!raw) return null;
- const parsed = JSON.parse(raw);
- if (Number.isInteger(parsed.checkpointRevision)) {
- checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);
- }
- return parsed;
- } catch { return null; }
- }
-
- function saveSession(session) {
- if (!session || !session.id) return;
- const payload = {
- ...session,
- checkpointRevision,
- };
- safeWrite(sessionKey, JSON.stringify(payload));
- }
-
- function clearSession() {
- safeRemove(sessionKey);
- }
-
- function nextCheckpointRevision() {
- checkpointRevision += 1;
- const existing = loadSession();
- if (existing?.id) saveSession(existing);
- return checkpointRevision;
- }
-
- function seedCheckpointRevision(value) {
- if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);
- return checkpointRevision;
- }
-
- function currentCheckpointRevision() {
- return checkpointRevision;
- }
-
- function markHandled(id) {
- if (!id) return;
- safeWrite(handledKey, id);
- }
-
- function isHandled(id) {
- return !!id && safeRead(handledKey) === id;
- }
-
- function clearHandled() {
- safeRemove(handledKey);
- }
-
- function writeScrollY(y) {
- safeWrite(scrollKey, String(y));
- }
-
- function readScrollY() {
- const raw = safeRead(scrollKey);
- if (raw == null) return null;
- const n = parseFloat(raw);
- return isFinite(n) ? n : null;
- }
-
- function clearScrollY() {
- safeRemove(scrollKey);
- }
-
- return {
- owner,
- sessionKey,
- handledKey,
- scrollKey,
- saveSession,
- loadSession,
- clearSession,
- nextCheckpointRevision,
- seedCheckpointRevision,
- currentCheckpointRevision,
- markHandled,
- isHandled,
- clearHandled,
- writeScrollY,
- readScrollY,
- clearScrollY,
- };
- }
-
- root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };
-})(typeof window !== 'undefined' ? window : globalThis);
@@ -1,4860 +0,0 @@
-/**
- * Impeccable Live Variant Mode — Browser Script
- *
- * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
- * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
- * before this code.
- *
- * UI: a single floating bar that morphs between three states —
- * configure (pick action + go), generating (progressive dots), and cycling
- * (prev/next + accept/discard). Feels like Spotlight, not a modal.
- */
-(function () {
- 'use strict';
- if (typeof window === 'undefined') return;
-
- // Guard against double-init. Bun's HTML loader may process the <script> tag
- // and create a bundled copy alongside the external load, or HMR may re-execute.
- // Check BEFORE reading token/port to catch all cases.
- if (window.__IMPECCABLE_LIVE_INIT__) return;
- window.__IMPECCABLE_LIVE_INIT__ = true;
-
- const TOKEN = window.__IMPECCABLE_TOKEN__;
- const PORT = window.__IMPECCABLE_PORT__;
- if (!TOKEN || !PORT) {
- window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
- return;
- }
-
- // ---------------------------------------------------------------------------
- // Design tokens
- // ---------------------------------------------------------------------------
-
- // Brand magenta is pinned to the site token (--color-accent in main.css)
- // so Accept / knobs / cycle-dots match the site's accent, not a washed
- // theme-adjusted one.
- const C = {
- brand: 'oklch(60% 0.25 350)',
- brandHov: 'oklch(52% 0.25 350)',
- brandSoft: 'oklch(60% 0.25 350 / 0.15)',
- ink: 'oklch(15% 0.01 350)',
- ash: 'oklch(55% 0 0)',
- paper: 'oklch(98% 0.005 350 / 0.92)',
- paperSolid:'oklch(98% 0.005 350)',
- mist: 'oklch(90% 0.01 350 / 0.6)',
- white: 'oklch(99% 0 0)',
- };
- const FONT = 'system-ui, -apple-system, sans-serif';
- const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
- // z-index: detect overlays use 99999, so our UI must be above them
- const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };
- const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
- const PREFIX = 'impeccable-live';
- const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
- prefix: PREFIX,
- storage: localStorage,
- idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),
- });
- if (!sessionState) {
- console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');
- window.__IMPECCABLE_LIVE_INIT__ = false;
- return;
- }
- const HIGHLIGHT_TRANSITION =
- 'top 140ms ' + EASE +
- ', left 140ms ' + EASE +
- ', width 140ms ' + EASE +
- ', height 140ms ' + EASE +
- ', opacity 150ms ease';
- const TOOLTIP_TRANSITION =
- 'top 140ms ' + EASE + ', left 140ms ' + EASE + ', opacity 150ms ease';
-
- const SKIP_TAGS = new Set([
- 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
- ]);
-
- // SVG icons stack above each chip label. All strokes use currentColor so the
- // icon recolors to C.brand when its chip is selected. 20x20 render, 24-viewBox,
- // 1.5 stroke — visually consistent with the Foundation grid on the homepage.
- const ICON_ATTRS = 'width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block"';
- const ICONS = {
- impeccable: `<svg ${ICON_ATTRS}><path d="M4 20l4-1L18 9l-3-3L5 16z"/><path d="M14 7l3 3"/></svg>`,
- bolder: `<svg ${ICON_ATTRS}><rect x="6" y="12" width="4" height="7" rx="0.5"/><rect x="14" y="5" width="4" height="14" rx="0.5"/></svg>`,
- quieter: `<svg ${ICON_ATTRS}><rect x="6" y="5" width="4" height="14" rx="0.5"/><rect x="14" y="12" width="4" height="7" rx="0.5"/></svg>`,
- distill: `<svg ${ICON_ATTRS}><path d="M4 5h16l-6 8v7l-4-2v-5z"/></svg>`,
- polish: `<svg ${ICON_ATTRS}><path d="M15 3l1 3 3 1-3 1-1 3-1-3-3-1 3-1z"/><path d="M7 13l0.6 1.8 1.8 0.6-1.8 0.6-0.6 1.8-0.6-1.8-1.8-0.6 1.8-0.6z"/></svg>`,
- typeset: `<svg ${ICON_ATTRS}><path d="M5 6h14" stroke-width="2.6"/><path d="M5 12h9" stroke-width="1.9"/><path d="M5 18h5" stroke-width="1.3"/></svg>`,
- colorize: `<svg ${ICON_ATTRS}><circle cx="9" cy="10" r="5"/><circle cx="15" cy="10" r="5"/><circle cx="12" cy="15" r="5"/></svg>`,
- layout: `<svg ${ICON_ATTRS}><rect x="3" y="4" width="8" height="16" rx="0.5"/><rect x="13" y="4" width="8" height="7" rx="0.5"/><rect x="13" y="13" width="8" height="7" rx="0.5"/></svg>`,
- adapt: `<svg ${ICON_ATTRS}><rect x="2.5" y="5" width="12" height="11" rx="1"/><line x1="2.5" y1="19" x2="14.5" y2="19"/><rect x="16.5" y="8" width="5" height="11" rx="1"/></svg>`,
- animate: `<svg ${ICON_ATTRS}><path d="M3 18c4-4 6-10 10-10"/><path d="M13 8c3 0 5 5 8 10"/><circle cx="13" cy="8" r="1.6" fill="currentColor" stroke="none"/></svg>`,
- delight: `<svg ${ICON_ATTRS}><path d="M12 3l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>`,
- overdrive: `<svg ${ICON_ATTRS}><path d="M13 3L5 13h5l-1 8 9-12h-6z"/></svg>`,
- };
-
- const ACTIONS = [
- { value: 'impeccable', label: 'Freeform' },
- { value: 'bolder', label: 'Bolder' },
- { value: 'quieter', label: 'Quieter' },
- { value: 'distill', label: 'Distill' },
- { value: 'polish', label: 'Polish' },
- { value: 'typeset', label: 'Typeset' },
- { value: 'colorize', label: 'Colorize' },
- { value: 'layout', label: 'Layout' },
- { value: 'adapt', label: 'Adapt' },
- { value: 'animate', label: 'Animate' },
- { value: 'delight', label: 'Delight' },
- { value: 'overdrive', label: 'Overdrive' },
- ];
-
- // ---------------------------------------------------------------------------
- // State
- // ---------------------------------------------------------------------------
-
- let state = 'IDLE';
- let hoveredElement = null;
- let selectedElement = null;
- let currentSessionId = null;
- let expectedVariants = 0;
- let arrivedVariants = 0;
- let visibleVariant = 0;
- let variantObserver = null;
- let hasProjectContext = false;
- let selectedAction = 'impeccable';
- let selectedCount = 3;
- const browserOwner = sessionState.owner;
- let checkpointTimer = null;
-
- // Scroll lock — holds window.scrollY at a fixed value while the session is
- // active, so HMR DOM patches and variant swaps can't drift the page. See
- // startScrollLock / stopScrollLock below.
- let scrollLockObserver = null;
- let scrollLockTargetY = null;
- let scrollLockRaf = null;
- let scrollLockAbort = null;
-
- // Dedicated key for scroll position — SEPARATE from LS_KEY so that
- // saveSession's state updates don't clobber a carefully-captured scrollY.
- // (Previously: saveSession wrote scrollY alongside state, so every call
- // during resume overwrote the pre-reload value with whatever the browser
- // had landed on, typically 0.)
- function writeScrollY(y) { sessionState.writeScrollY(y); }
- function readScrollY() { return sessionState.readScrollY(); }
- function clearScrollY() { sessionState.clearScrollY(); }
-
- // Pre-empt the browser: apply manual scroll restoration and jump to the
- // saved scrollY at script-parse time. Retries on fonts.ready and load
- // are essential: scrollTo(y) clamps to the current document.scrollHeight,
- // which is often hundreds of pixels short of the final value until
- // async-loaded fonts swap in and reflow.
- try {
- history.scrollRestoration = 'manual';
- const savedY = readScrollY();
- if (savedY != null) {
- const apply = () => {
- if (Math.abs(window.scrollY - savedY) > 0.5) {
- console.log('[impeccable.scroll] early restore', { from: window.scrollY, to: savedY });
- window.scrollTo(0, savedY);
- }
- };
- apply();
- if (document.fonts?.ready) document.fonts.ready.then(apply).catch(() => {});
- window.addEventListener('load', apply, { once: true });
- }
- } catch {}
-
- // UI refs
- let highlightEl = null;
- let tooltipEl = null;
- let barEl = null;
- let pickerEl = null;
- let toastEl = null;
- let scrollRaf = null;
-
- // ---------------------------------------------------------------------------
- // Helpers
- // ---------------------------------------------------------------------------
-
- function own(el) {
- return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
- }
-
- function pickable(el) {
- if (!el || el.nodeType !== 1) return false;
- if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
- if (own(el)) return false;
- const r = el.getBoundingClientRect();
- return r.width >= 20 && r.height >= 20;
- }
-
- function desc(el) {
- if (!el) return '';
- let s = el.tagName.toLowerCase();
- if (el.id) s += '#' + el.id;
- else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
- return s;
- }
-
- function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
-
- // Modal-aware chrome: keep our floating UI clickable inside Radix /
- // Headless UI / vaul portals.
- //
- // Two host-page behaviors break us when the picked element lives inside a
- // modal dialog:
- //
- // 1. Modal scroll-lock disables outside pointer events. Radix's
- // `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
- // while a modal is open and only restores `auto` on the layer. Our
- // chrome inherits `none` from <body> and becomes unclickable.
- // 2. The dialog's outside-interaction handler (Radix's
- // `usePointerDownOutside`) listens at document level and dismisses
- // the dialog whenever a `pointerdown` lands outside the layer node.
- // Our chrome is a sibling of <body>, so Radix classifies our clicks
- // as outside and tears the dialog down mid-task.
- //
- // We can't reliably re-parent our chrome into the dialog subtree (z-index
- // stacking, scroll containers, theming all become host-page concerns), so
- // we defang both behaviors at our root:
- //
- // - `pointer-events: auto !important` overrides the inherited `none`.
- // - Stop `pointerdown` / `mousedown` propagation so the document-level
- // dismiss listener never fires for our clicks.
- // - Stop `focusin` propagation so any focus shifts inside our chrome
- // don't read as "focus moved outside the dialog" to focus traps.
- //
- // Click events still bubble normally — only the early pointer/focus
- // signals that drive outside-interaction detection are silenced.
- function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
- if (!rootEl) return;
- if (setPointerEvents) {
- rootEl.style.setProperty('pointer-events', 'auto', 'important');
- }
- const stop = (e) => e.stopPropagation();
- rootEl.addEventListener('pointerdown', stop);
- rootEl.addEventListener('mousedown', stop);
- rootEl.addEventListener('focusin', stop);
- }
-
- // ---------------------------------------------------------------------------
- // Highlight overlay
- // ---------------------------------------------------------------------------
-
- function initHighlight() {
- highlightEl = document.createElement('div');
- highlightEl.id = PREFIX + '-highlight';
- Object.assign(highlightEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- border: '2px solid ' + C.brand, borderRadius: '3px',
- pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
- transition: HIGHLIGHT_TRANSITION,
- display: 'none', opacity: '0',
- });
- document.body.appendChild(highlightEl);
-
- tooltipEl = document.createElement('div');
- tooltipEl.id = PREFIX + '-tooltip';
- Object.assign(tooltipEl.style, {
- position: 'fixed',
- background: C.ink, color: C.white,
- fontFamily: MONO, fontSize: '10px', fontWeight: '500',
- padding: '2px 6px', borderRadius: '3px',
- zIndex: Z.highlight + 1, pointerEvents: 'none',
- whiteSpace: 'nowrap', display: 'none',
- letterSpacing: '0.02em',
- transition: TOOLTIP_TRANSITION,
- });
- document.body.appendChild(tooltipEl);
- }
-
- function showHighlight(el) {
- if (!el || !highlightEl) return;
- const r = el.getBoundingClientRect();
- const top = (r.top - 2) + 'px', left = (r.left - 2) + 'px';
- const width = (r.width + 4) + 'px', height = (r.height + 4) + 'px';
- const tipTop = r.top - 20;
- const tipY = (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px';
- const tipX = Math.max(4, r.left) + 'px';
- tooltipEl.textContent = desc(el);
-
- const hiWasHidden = highlightEl.style.display === 'none' || highlightEl.style.opacity === '0';
- if (hiWasHidden) {
- // Snap to first target without animating from (0,0), then fade in.
- highlightEl.style.transition = 'none';
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block' });
- tooltipEl.style.transition = 'none';
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block' });
- void highlightEl.offsetWidth;
- highlightEl.style.transition = HIGHLIGHT_TRANSITION;
- highlightEl.style.opacity = '1';
- tooltipEl.style.transition = TOOLTIP_TRANSITION;
- tooltipEl.style.opacity = '1';
- } else {
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block', opacity: '1' });
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block', opacity: '1' });
- }
- }
-
- function hideHighlight() {
- if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
- if (tooltipEl) { tooltipEl.style.opacity = '0'; tooltipEl.style.display = 'none'; }
- }
-
- // ---------------------------------------------------------------------------
- // Annotation overlay (comment pins + magenta strokes)
- //
- // Active while state === 'CONFIGURING'. The overlay is a fixed-positioned
- // sibling of <body> mirroring selectedElement's bounding rect. Click (no
- // drag) drops a comment pin; drag paints a magenta SVG stroke. All coords
- // are stored in element-local CSS px so they survive scroll / resize and
- // correlate directly with the captured PNG.
- // ---------------------------------------------------------------------------
-
- const DRAG_THRESHOLD = 5; // px — below this, treat pointerup as a click
- const PIN_DBL_CLICK_MS = 300; // two clicks on the same pin within this delete it
- let annotOverlayEl = null;
- let annotSvgEl = null;
- let annotPinsEl = null;
- let annotClearChipEl = null;
- let annotState = { comments: [], strokes: [] };
- let annotActive = false;
- // `annotPointer` is either:
- // { kind: 'new', x0, y0, moved, strokeEl, strokePoints } creating a stroke/pin
- // { kind: 'pin', idx, startPointer, startPin, moved } dragging an existing pin
- let annotPointer = null;
- let annotEditing = null; // { idx, input, wrapEl }
- let annotLastPinClick = { idx: -1, time: 0 }; // for click-click-to-delete
-
- function initAnnotOverlay() {
- annotOverlayEl = document.createElement('div');
- annotOverlayEl.id = PREFIX + '-annot';
- Object.assign(annotOverlayEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- pointerEvents: 'auto', zIndex: Z.highlight + 2,
- display: 'none', overflow: 'visible',
- cursor: 'crosshair', touchAction: 'none',
- });
-
- annotSvgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- annotSvgEl.id = PREFIX + '-annot-svg';
- Object.assign(annotSvgEl.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%',
- // The SVG itself doesn't absorb clicks; individual hit-paths opt-in via
- // pointer-events=stroke so gaps still fall through to the overlay.
- pointerEvents: 'none', overflow: 'visible',
- });
- annotOverlayEl.appendChild(annotSvgEl);
-
- annotPinsEl = document.createElement('div');
- annotPinsEl.id = PREFIX + '-annot-pins';
- Object.assign(annotPinsEl.style, {
- position: 'absolute', inset: '0',
- pointerEvents: 'none',
- });
- annotOverlayEl.appendChild(annotPinsEl);
-
- annotClearChipEl = document.createElement('div');
- annotClearChipEl.id = PREFIX + '-annot-clear';
- annotClearChipEl.dataset.annotClear = 'true';
- annotClearChipEl.textContent = 'Clear';
- Object.assign(annotClearChipEl.style, {
- position: 'absolute', top: '8px', right: '8px',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '10px', fontWeight: '500',
- letterSpacing: '0.08em', textTransform: 'uppercase',
- padding: '5px 12px', borderRadius: '999px',
- cursor: 'pointer', pointerEvents: 'auto',
- display: 'none', userSelect: 'none',
- boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
- });
- annotOverlayEl.appendChild(annotClearChipEl);
-
- annotOverlayEl.addEventListener('pointerdown', onAnnotDown);
- annotOverlayEl.addEventListener('pointermove', onAnnotMove);
- annotOverlayEl.addEventListener('pointerup', onAnnotUp);
- annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
- document.body.appendChild(annotOverlayEl);
- // Modal-host friendliness: pointer-events is already 'auto' on this
- // overlay; we only need to silence the host's outside-interaction
- // listeners. Don't override pointer-events here (the overlay toggles
- // visibility via display:none, which is fine).
- defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
- }
-
- function updateClearChip() {
- if (!annotClearChipEl) return;
- const hasAny = annotState.comments.length > 0 || annotState.strokes.length > 0;
- annotClearChipEl.style.display = hasAny ? 'block' : 'none';
- }
-
- function showAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- annotActive = true;
- positionAnnotOverlay(el);
- annotOverlayEl.style.display = 'block';
- }
-
- function hideAnnotOverlay() {
- annotActive = false;
- if (annotOverlayEl) annotOverlayEl.style.display = 'none';
- // Drop any in-progress edit without touching annotState — clearAnnotations
- // (if the caller is exiting configure mode) handles state reset.
- annotEditing = null;
- }
-
- function positionAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- const r = el.getBoundingClientRect();
- Object.assign(annotOverlayEl.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- annotSvgEl.setAttribute('viewBox', '0 0 ' + r.width + ' ' + r.height);
- }
-
- function clearAnnotations() {
- annotState.comments = [];
- annotState.strokes = [];
- if (annotSvgEl) while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- if (annotPinsEl) annotPinsEl.innerHTML = '';
- annotPointer = null;
- annotEditing = null;
- annotLastPinClick = { idx: -1, time: 0 };
- updateClearChip();
- }
-
- // Rebuild the SVG layer. Each stroke gets a wider invisible hit path
- // beneath the visible magenta path so clicks register on thin lines.
- function redrawStrokes() {
- while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- annotState.strokes.forEach((s, idx) => {
- const d = pointsToPath(s.points);
- const hit = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- hit.setAttribute('d', d);
- hit.setAttribute('stroke', 'transparent');
- hit.setAttribute('stroke-width', '16');
- hit.setAttribute('stroke-linecap', 'round');
- hit.setAttribute('stroke-linejoin', 'round');
- hit.setAttribute('fill', 'none');
- hit.setAttribute('pointer-events', 'stroke');
- hit.style.cursor = 'pointer';
- hit.dataset.annotStroke = String(idx);
- annotSvgEl.appendChild(hit);
- const visible = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- visible.setAttribute('d', d);
- visible.setAttribute('stroke', C.brand);
- visible.setAttribute('stroke-width', '3');
- visible.setAttribute('stroke-linecap', 'round');
- visible.setAttribute('stroke-linejoin', 'round');
- visible.setAttribute('fill', 'none');
- visible.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(visible);
- });
- updateClearChip();
- }
-
- function localCoords(e) {
- const rect = annotOverlayEl.getBoundingClientRect();
- return { x: e.clientX - rect.left, y: e.clientY - rect.top };
- }
-
- function onAnnotDown(e) {
- if (!annotActive) return;
-
- // 1) Clear chip → wipe all annotations
- if (e.target.closest?.('[data-annot-clear]')) {
- if (annotEditing) annotEditing = null;
- clearAnnotations();
- renderAllPins();
- redrawStrokes();
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 2) Stroke hit path → delete that stroke
- const strokeHit = e.target.closest?.('[data-annot-stroke]');
- if (strokeHit) {
- const idx = parseInt(strokeHit.dataset.annotStroke, 10);
- if (Number.isInteger(idx)) {
- annotState.strokes.splice(idx, 1);
- redrawStrokes();
- }
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 3) Pin → drag, edit, or delete-on-double-click
- const pinWrap = e.target.closest?.('[data-annot-pin]');
- if (pinWrap) {
- const idx = parseInt(pinWrap.dataset.annotPin, 10);
- if (!Number.isInteger(idx)) return;
- // Double-click (two pointerdowns on the same pin within window) → delete.
- const now = Date.now();
- if (annotLastPinClick.idx === idx && now - annotLastPinClick.time < PIN_DBL_CLICK_MS) {
- if (annotEditing && annotEditing.idx === idx) annotEditing = null;
- annotState.comments.splice(idx, 1);
- annotLastPinClick = { idx: -1, time: 0 };
- renderAllPins();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- annotLastPinClick = { idx, time: now };
- // If editing a different pin, commit that edit before starting here.
- if (annotEditing && annotEditing.idx !== idx) finalizeEditingPin();
- // If already editing THIS pin and the user clicked the dot, let the
- // input keep focus (don't start a drag — the click wasn't meant as one).
- if (annotEditing && annotEditing.idx === idx) return;
- const p = localCoords(e);
- const pin = annotState.comments[idx];
- annotPointer = {
- kind: 'pin', idx,
- startPointer: p,
- startPin: { x: pin.x, y: pin.y },
- moved: false,
- };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 4) Empty area → commit any open edit, then start new annotation
- if (annotEditing) {
- finalizeEditingPin();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- const p = localCoords(e);
- annotPointer = { kind: 'new', x0: p.x, y0: p.y, moved: false, strokeEl: null, strokePoints: null };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- }
-
- function onAnnotMove(e) {
- if (!annotActive || !annotPointer) return;
- const p = localCoords(e);
-
- if (annotPointer.kind === 'pin') {
- const dx = p.x - annotPointer.startPointer.x;
- const dy = p.y - annotPointer.startPointer.y;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- }
- const pin = annotState.comments[annotPointer.idx];
- if (!pin) { annotPointer = null; return; }
- pin.x = annotPointer.startPin.x + dx;
- pin.y = annotPointer.startPin.y + dy;
- renderAllPins();
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const dx = p.x - annotPointer.x0, dy = p.y - annotPointer.y0;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- const strokeEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- strokeEl.setAttribute('stroke', C.brand);
- strokeEl.setAttribute('stroke-width', '3');
- strokeEl.setAttribute('stroke-linecap', 'round');
- strokeEl.setAttribute('stroke-linejoin', 'round');
- strokeEl.setAttribute('fill', 'none');
- strokeEl.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(strokeEl);
- annotPointer.strokeEl = strokeEl;
- annotPointer.strokePoints = [[annotPointer.x0, annotPointer.y0]];
- }
- annotPointer.strokePoints.push([p.x, p.y]);
- annotPointer.strokeEl.setAttribute('d', pointsToPath(annotPointer.strokePoints));
- e.stopPropagation();
- }
-
- function onAnnotUp(e) {
- if (!annotActive || !annotPointer) return;
-
- if (annotPointer.kind === 'pin') {
- const wasDrag = annotPointer.moved;
- const idx = annotPointer.idx;
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- if (wasDrag) {
- // A drag is an intentional reposition; a follow-up click shouldn't be
- // interpreted as a double-click-to-delete.
- annotLastPinClick = { idx: -1, time: 0 };
- } else {
- beginEditPin(idx);
- }
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const wasDrag = annotPointer.moved;
- if (wasDrag) {
- annotState.strokes.push({ points: annotPointer.strokePoints });
- // Swap the temporary preview SVG path for the full render with hit paths.
- redrawStrokes();
- } else {
- const idx = annotState.comments.length;
- annotState.comments.push({ x: annotPointer.x0, y: annotPointer.y0, text: '' });
- renderAllPins();
- beginEditPin(idx);
- }
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- e.stopPropagation();
- }
-
- function pointsToPath(points) {
- if (!points || points.length === 0) return '';
- let d = 'M' + points[0][0].toFixed(1) + ' ' + points[0][1].toFixed(1);
- for (let i = 1; i < points.length; i++) {
- d += ' L' + points[i][0].toFixed(1) + ' ' + points[i][1].toFixed(1);
- }
- return d;
- }
-
- function renderAllPins() {
- annotPinsEl.innerHTML = '';
- annotState.comments.forEach((c, idx) => {
- annotPinsEl.appendChild(buildPinElement(c, idx));
- });
- updateClearChip();
- }
-
- function buildPinElement(comment, idx) {
- const interactive = idx >= 0;
- const wrap = document.createElement('div');
- if (interactive) wrap.dataset.annotPin = String(idx);
- Object.assign(wrap.style, {
- position: 'absolute',
- left: (comment.x - 7) + 'px', top: (comment.y - 7) + 'px',
- pointerEvents: interactive ? 'auto' : 'none',
- display: 'flex', alignItems: 'flex-start', gap: '6px',
- cursor: interactive ? 'grab' : 'default',
- touchAction: 'none',
- });
- const dot = document.createElement('div');
- Object.assign(dot.style, {
- width: '14px', height: '14px', borderRadius: '50%',
- background: C.brand, border: '2px solid ' + C.white,
- boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
- flexShrink: '0',
- });
- wrap.appendChild(dot);
-
- if (comment.text) {
- const bubble = document.createElement('div');
- bubble.textContent = comment.text;
- Object.assign(bubble.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- marginTop: '-2px', maxWidth: '220px',
- pointerEvents: 'none', whiteSpace: 'pre-wrap',
- wordBreak: 'break-word',
- });
- wrap.appendChild(bubble);
- }
- return wrap;
- }
-
- function beginEditPin(idx) {
- const wrapEl = annotPinsEl.querySelector('[data-annot-pin="' + idx + '"]');
- if (!wrapEl) return;
- // Strip any existing bubble (but keep the dot)
- wrapEl.querySelectorAll('div:not(:first-child)').forEach(n => n.remove());
- const input = document.createElement('input');
- input.type = 'text';
- input.placeholder = 'Note…';
- Object.assign(input.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- border: '1px solid ' + C.brand,
- outline: 'none', marginTop: '-2px',
- width: '220px', pointerEvents: 'auto',
- });
- const originalText = annotState.comments[idx].text || '';
- input.value = originalText;
- wrapEl.appendChild(input);
- annotEditing = { idx, input, wrapEl, originalText };
- input.addEventListener('keydown', onAnnotInputKey, true);
- input.addEventListener('blur', () => {
- // Fires on both focus-loss and programmatic blur; commit unless we
- // already handled it.
- if (annotEditing && annotEditing.input === input) finalizeEditingPin();
- });
- // Stop clicks/pointerdowns inside the input from bubbling to the overlay
- ['pointerdown', 'click'].forEach(ev => {
- input.addEventListener(ev, e => e.stopPropagation());
- });
- setTimeout(() => input.focus(), 0);
- }
-
- function onAnnotInputKey(e) {
- if (e.key === 'Enter') {
- e.preventDefault(); e.stopPropagation();
- finalizeEditingPin();
- } else if (e.key === 'Escape') {
- e.preventDefault(); e.stopPropagation();
- cancelEditingPin();
- } else {
- // Keep arrows / backspace from hitting global handlers
- e.stopPropagation();
- }
- }
-
- function finalizeEditingPin() {
- if (!annotEditing) return;
- const { idx, input } = annotEditing;
- const text = input.value.trim();
- annotEditing = null;
- if (text) annotState.comments[idx].text = text;
- else annotState.comments.splice(idx, 1);
- renderAllPins();
- }
-
- function cancelEditingPin() {
- if (!annotEditing) return;
- const { idx, originalText } = annotEditing;
- annotEditing = null;
- // If the pin had text before this edit, revert to it. If it was a
- // just-created empty pin, Escape removes it.
- if (originalText) {
- annotState.comments[idx].text = originalText;
- } else {
- annotState.comments.splice(idx, 1);
- }
- renderAllPins();
- }
-
- // Build a detached annotation subtree suitable for injection into the clone
- // modern-screenshot creates. Coordinates are element-local so this slots
- // straight into an element that's been made position:relative. Takes an
- // explicit snapshot so it works after annotState has been cleared.
- function buildAnnotationsForCapture(rect, snapshot) {
- const comments = snapshot ? snapshot.comments : annotState.comments;
- const strokes = snapshot ? snapshot.strokes : annotState.strokes;
- if (comments.length === 0 && strokes.length === 0) return null;
- const wrap = document.createElement('div');
- Object.assign(wrap.style, {
- position: 'absolute', top: '0', left: '0',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none', overflow: 'visible',
- });
- if (strokes.length > 0) {
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- svg.setAttribute('viewBox', '0 0 ' + rect.width + ' ' + rect.height);
- Object.assign(svg.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%', overflow: 'visible',
- });
- for (const s of strokes) {
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- path.setAttribute('stroke', C.brand);
- path.setAttribute('stroke-width', '3');
- path.setAttribute('stroke-linecap', 'round');
- path.setAttribute('stroke-linejoin', 'round');
- path.setAttribute('fill', 'none');
- path.setAttribute('d', pointsToPath(s.points));
- svg.appendChild(path);
- }
- wrap.appendChild(svg);
- }
- for (const c of comments) {
- // idx=-1 means non-interactive; pointerEvents stay off in the clone
- wrap.appendChild(buildPinElement(c, -1));
- }
- return wrap;
- }
-
- // ---------------------------------------------------------------------------
- // Element context extraction
- // ---------------------------------------------------------------------------
-
- function extractContext(el) {
- const cs = getComputedStyle(el);
- const r = el.getBoundingClientRect();
- const props = {};
- for (const sheet of document.styleSheets) {
- try {
- for (const rule of sheet.cssRules) {
- if (rule.style) for (let i = 0; i < rule.style.length; i++) {
- const p = rule.style[i];
- if (p.startsWith('--') && !props[p]) {
- const v = cs.getPropertyValue(p).trim();
- if (v) props[p] = v;
- }
- }
- }
- } catch { /* cross-origin */ }
- }
- return {
- tagName: el.tagName.toLowerCase(), id: el.id || null,
- classes: [...el.classList],
- textContent: (el.textContent || '').slice(0, 500),
- outerHTML: el.outerHTML.slice(0, 10000),
- computedStyles: {
- 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
- 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
- 'color': cs.color, 'background': cs.background,
- 'background-color': cs.backgroundColor,
- 'padding': cs.padding, 'margin': cs.margin,
- 'display': cs.display, 'position': cs.position,
- 'gap': cs.gap, 'border-radius': cs.borderRadius,
- 'box-shadow': cs.boxShadow,
- },
- cssCustomProperties: props,
- parentContext: el.parentElement
- ? '<' + el.parentElement.tagName.toLowerCase()
- + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
- + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
- + '>'
- : null,
- boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
- };
- }
-
- // ---------------------------------------------------------------------------
- // The Bar — one floating element, three modes
- // ---------------------------------------------------------------------------
-
- // Contextual-bar palette. Cached at init so every build*Row reads a
- // consistent set of colors; detectPageTheme runs once rather than on every
- // phase transition.
- let BP = null;
-
- // Bar shadow variants. The default projects down + subtle around. When
- // the Tune popover opens below the bar, a downward shadow lands on the
- // dark popover and reads as a bright ghost line. We swap to UP-only while
- // tune is open below so the popover's top edge is clean.
- const BAR_SHADOW_DEFAULT = '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_UP = '0 -4px 20px oklch(0% 0 0 / 0.08), 0 -1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_DOWN = BAR_SHADOW_DEFAULT;
-
- function initBar() {
- BP = barPaletteForTheme(detectPageTheme());
- barEl = document.createElement('div');
- barEl.id = PREFIX + '-bar';
- Object.assign(barEl.style, {
- position: 'fixed', zIndex: Z.bar,
- display: 'none', opacity: '0',
- transform: 'translateY(6px)',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- background: BP.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + BP.hairline,
- borderRadius: '10px',
- boxShadow: BAR_SHADOW_DEFAULT,
- transition: 'box-shadow 0.2s ease, opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- fontFamily: FONT, fontSize: '13px', color: BP.text,
- padding: '6px',
- maxWidth: '520px', minWidth: '320px',
- });
- document.body.appendChild(barEl);
- defangOutsideHandlers(barEl);
- }
-
- function positionBar() {
- if (!barEl || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- const barH = barEl.offsetHeight || 44;
- const barW = barEl.offsetWidth || 380;
- const GLOBAL_BAR_RESERVE = 64; // global bar height + bottom margin + breathing room
- const GAP = 8;
-
- // Prefer below the element; fall back to above; if neither fits (element
- // taller than viewport), pin to a stable viewport anchor so the bar
- // doesn't teleport between top and bottom as the user scrolls.
- let top;
- const belowTop = r.bottom + GAP;
- const aboveTop = r.top - barH - GAP;
- if (belowTop + barH + GAP <= window.innerHeight - GLOBAL_BAR_RESERVE) {
- top = belowTop;
- } else if (aboveTop >= GAP) {
- top = aboveTop;
- } else {
- top = window.innerHeight - barH - GLOBAL_BAR_RESERVE;
- }
-
- let left = r.left + (r.width - barW) / 2;
- if (left < GAP) left = GAP;
- if (left + barW > window.innerWidth - GAP) left = window.innerWidth - barW - GAP;
- Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
- }
-
- function showBar(mode) {
- barEl.innerHTML = '';
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- barEl.style.display = 'block';
- positionBar();
- requestAnimationFrame(() => {
- barEl.style.opacity = '1';
- barEl.style.transform = 'translateY(0)';
- });
- }
-
- function hideBar() {
- if (!barEl) return;
- barEl.style.opacity = '0';
- barEl.style.transform = 'translateY(6px)';
- setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
- hideActionPicker();
- closeTunePopover();
- }
-
- function updateBarContent(mode) {
- if (!barEl || barEl.style.display === 'none') return;
- barEl.innerHTML = '';
- // Reset bar styling to the theme-aware palette
- barEl.style.background = BP.surface;
- barEl.style.border = '1px solid ' + BP.hairline;
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- else if (mode === 'saving') barEl.appendChild(buildSavingRow());
- else if (mode === 'confirmed') {
- barEl.appendChild(buildConfirmedRow());
- barEl.style.background = 'oklch(95% 0.05 145)';
- barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
- }
- }
-
- // --- Configure row ---
-
- function buildConfigureRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
-
- // Action pill
- const pill = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '4px',
- padding: '5px 10px', borderRadius: '6px',
- background: BP.mark, color: BP.markText,
- fontFamily: FONT, fontSize: '12px', fontWeight: '500',
- border: 'none', cursor: 'pointer',
- transition: 'background 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap', flexShrink: '0',
- });
- pill.textContent = actionLabel() + ' \u25BE';
- pill.addEventListener('mouseenter', () => pill.style.background = BP.accent);
- pill.addEventListener('mouseleave', () => pill.style.background = BP.mark);
- pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
- pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
- pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
- row.appendChild(pill);
-
- // Freeform input. Focus state shows an accent-colored border only —
- // an earlier version tinted the background with `BP.accentSoft`, which
- // composited against the dark bar surface to a murky purple where the
- // browser's default placeholder gray was unreadable. Placeholder color
- // is set explicitly via a one-shot stylesheet keyed off this input's id
- // so it picks up the bar's `textDim` token in both themes.
- const input = document.createElement('input');
- input.id = PREFIX + '-input';
- input.type = 'text';
- input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
- Object.assign(input.style, {
- flex: '1', minWidth: '0',
- padding: '5px 8px', borderRadius: '6px',
- border: '1px solid transparent', background: 'transparent',
- fontFamily: FONT, fontSize: '12px', color: BP.text,
- outline: 'none',
- transition: 'border-color 0.15s ease',
- });
- if (!document.getElementById(PREFIX + '-input-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-input-style';
- s.textContent =
- '#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
- document.head.appendChild(s);
- }
- input.addEventListener('focus', () => {
- input.style.borderColor = BP.accent;
- });
- input.addEventListener('blur', () => {
- input.style.borderColor = 'transparent';
- });
- input.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
- if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; return; }
- // Let arrow keys pass through to the element picker when the input is empty
- if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && !input.value) return;
- e.stopPropagation();
- });
- row.appendChild(input);
-
- // Variant count toggle
- const count = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: MONO, fontSize: '11px', fontWeight: '600',
- color: BP.textDim, cursor: 'pointer',
- transition: 'color 0.12s ease, border-color 0.12s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- count.textContent = '\u00D7' + selectedCount;
- count.title = 'Variants: click to change';
- count.addEventListener('mouseenter', () => { count.style.color = BP.text; count.style.borderColor = BP.text; });
- count.addEventListener('mouseleave', () => { count.style.color = BP.textDim; count.style.borderColor = BP.hairline; });
- count.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
- count.textContent = '\u00D7' + selectedCount;
- });
- row.appendChild(count);
-
- // Go button
- const go = el('button', {
- padding: '5px 12px', borderRadius: '6px',
- border: 'none', background: BP.accent, color: BP.mark,
- fontFamily: FONT, fontSize: '12px', fontWeight: '600',
- cursor: 'pointer',
- transition: 'filter 0.12s ease, transform 0.1s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- go.textContent = 'Go \u2192';
- go.addEventListener('mouseenter', () => go.style.filter = 'brightness(1.1)');
- go.addEventListener('mouseleave', () => go.style.filter = 'none');
- go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
- go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
- go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
- row.appendChild(go);
-
- // Auto-focus input after a beat
- setTimeout(() => input.focus(), 60);
- return row;
- }
-
- // --- Generating row ---
-
- function buildGeneratingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 4px',
- });
-
- // Action label
- const label = el('span', {
- fontWeight: '600', fontSize: '12px', color: BP.text,
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- label.textContent = actionLabel();
- row.appendChild(label);
-
- // Dots
- row.appendChild(buildDots(false));
-
- // Status
- const status = el('span', {
- fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',
- marginLeft: 'auto',
- });
- // Variants currently arrive atomically in a single file edit, so a
- // per-variant counter would lie. Say what's true.
- status.textContent = arrivedVariants < expectedVariants
- ? 'Generating ' + expectedVariants + ' variants...'
- : 'Done';
- row.appendChild(status);
-
- return row;
- }
-
- // --- Cycling row ---
-
- const TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';
-
- function buildCyclingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '6px',
- padding: '1px 2px',
- });
-
- // Prev
- const prev = navBtn('\u2190');
- prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
- if (visibleVariant <= 1) prev.style.opacity = '0.3';
- row.appendChild(prev);
-
- // Dots (clickable)
- row.appendChild(buildDots(true));
-
- // Counter
- const counter = el('span', {
- fontFamily: MONO, fontSize: '11px', fontWeight: '500',
- color: BP.textDim, minWidth: '24px', textAlign: 'center',
- });
- counter.textContent = visibleVariant + '/' + arrivedVariants;
- row.appendChild(counter);
-
- // Next
- const next = navBtn('\u2192');
- next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
- if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
- row.appendChild(next);
-
- // Tune chip — only when the visible variant exposes params
- const visParams = parseVariantParams(getVisibleVariantEl());
- const hasParams = visParams.length > 0;
- if (hasParams) {
- const tune = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '6px',
- padding: '4px 10px', borderRadius: '5px',
- border: '1px solid transparent',
- background: tuneOpen ? BP.accentSoft : 'transparent',
- color: tuneOpen ? BP.accent : BP.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'color 0.12s ease, background 0.12s ease',
- whiteSpace: 'nowrap',
- });
- tune.innerHTML = TUNE_ICON_SVG;
- const tuneLabel = document.createElement('span');
- tuneLabel.textContent = 'Tune';
- tune.appendChild(tuneLabel);
- const tuneBadge = document.createElement('span');
- Object.assign(tuneBadge.style, {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- minWidth: '16px', height: '16px', padding: '0 4px',
- borderRadius: '999px',
- background: tuneOpen ? C.brand : BP.hairline,
- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',
- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',
- lineHeight: '1',
- boxSizing: 'border-box',
- });
- tuneBadge.textContent = String(visParams.length);
- tune.appendChild(tuneBadge);
- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';
- tune.addEventListener('mouseenter', () => {
- if (!tuneOpen) tune.style.background = BP.accentSoft;
- });
- tune.addEventListener('mouseleave', () => {
- if (!tuneOpen) tune.style.background = 'transparent';
- });
- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });
- tune.dataset.iceqTune = '1';
- row.appendChild(tune);
- }
-
- // Spacer
- row.appendChild(el('div', { flex: '1' }));
-
- // Accept — primary action, uses the site's saturated brand magenta
- // with paper-white text, not the theme-muted BP.accent.
- const accept = el('button', {
- padding: '5px 14px', borderRadius: '5px',
- border: 'none', background: C.brand, color: 'oklch(98% 0 0)',
- fontFamily: FONT, fontSize: '11px', fontWeight: '600',
- cursor: 'pointer', transition: 'filter 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap',
- });
- accept.textContent = '\u2713 Accept';
- accept.addEventListener('mouseenter', () => accept.style.filter = 'brightness(1.08)');
- accept.addEventListener('mouseleave', () => accept.style.filter = 'none');
- accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');
- accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');
- accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
- row.appendChild(accept);
-
- // Discard
- const discard = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: FONT, fontSize: '11px', color: BP.textDim,
- cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
- });
- discard.textContent = '\u2715';
- discard.title = 'Discard all variants';
- discard.addEventListener('mouseenter', () => { discard.style.color = BP.text; discard.style.borderColor = BP.text; });
- discard.addEventListener('mouseleave', () => { discard.style.color = BP.textDim; discard.style.borderColor = BP.hairline; });
- discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
- row.appendChild(discard);
-
- return row;
- }
-
- // --- Shared UI builders ---
-
- // --- Saving row (waiting for agent to process accept/discard) ---
-
- function buildSavingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const spinner = el('div', {
- width: '14px', height: '14px', borderRadius: '50%',
- border: '2px solid ' + BP.hairline,
- borderTopColor: BP.accent,
- animation: 'impeccable-spin 0.6s linear infinite',
- flexShrink: '0',
- });
- row.appendChild(spinner);
- const label = el('span', {
- fontSize: '12px', color: BP.textDim, fontWeight: '500',
- });
- label.textContent = 'Applying variant...';
- row.appendChild(label);
-
- // Inject the keyframes if not already present
- if (!document.getElementById(PREFIX + '-keyframes')) {
- const style = document.createElement('style');
- style.id = PREFIX + '-keyframes';
- style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
- document.head.appendChild(style);
- }
- return row;
- }
-
- // --- Confirmed row (green success, auto-dismisses) ---
-
- function buildConfirmedRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const check = el('span', {
- fontSize: '15px', lineHeight: '1', flexShrink: '0',
- color: 'oklch(45% 0.15 145)',
- });
- check.textContent = '\u2713';
- row.appendChild(check);
- const label = el('span', {
- fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
- });
- label.textContent = 'Variant applied';
- row.appendChild(label);
- return row;
- }
-
- // --- Shared UI builders ---
-
- function buildDots(clickable) {
- const container = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
- for (let i = 1; i <= expectedVariants; i++) {
- const arrived = i <= arrivedVariants;
- const active = i === visibleVariant;
- // active: solid site-brand magenta dot. arrived+inactive: muted neutral.
- // pending (not yet arrived): faint outline ring. No borders on arrived
- // dots — the previous "accent ring + ash fill" combo read as noisy
- // magenta chips, especially when all variants had arrived and every
- // dot wore an accent ring.
- const dotBg = active ? C.brand
- : arrived ? BP.textDim
- : 'transparent';
- const dotBorder = arrived ? 'none' : '1.5px solid ' + BP.hairline;
- const dot = el('div', {
- width: active ? '8px' : '6px',
- height: active ? '8px' : '6px',
- borderRadius: '50%',
- background: dotBg,
- border: dotBorder,
- boxSizing: 'border-box',
- transition: 'all 0.2s ' + EASE,
- cursor: (clickable && arrived) ? 'pointer' : 'default',
- transform: arrived ? 'scale(1)' : 'scale(0.85)',
- opacity: arrived ? (active ? '1' : '0.6') : '0.4',
- });
- if (clickable && arrived) {
- const idx = i;
- dot.addEventListener('click', (e) => {
- e.stopPropagation();
- visibleVariant = idx;
- showVariantInDOM(currentSessionId, idx);
- updateSelectedElement();
- updateBarContent('cycling');
- });
- }
- container.appendChild(dot);
- }
- return container;
- }
-
- function navBtn(text) {
- const b = el('button', {
- width: '26px', height: '26px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- color: BP.text, fontFamily: FONT, fontSize: '13px',
- cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
- transition: 'border-color 0.12s ease, background 0.12s ease',
- padding: '0', lineHeight: '1',
- });
- b.textContent = text;
- b.addEventListener('mouseenter', () => { b.style.borderColor = BP.text; });
- b.addEventListener('mouseleave', () => { b.style.borderColor = BP.hairline; });
- return b;
- }
-
- function actionLabel() {
- const a = ACTIONS.find(a => a.value === selectedAction);
- return a ? a.label : 'Freeform';
- }
-
- function el(tag, styles) {
- const e = document.createElement(tag);
- if (styles) Object.assign(e.style, styles);
- return e;
- }
-
- // ---------------------------------------------------------------------------
- // Action picker popover
- // ---------------------------------------------------------------------------
-
- function initActionPicker() {
- const P = barPaletteForTheme(detectPageTheme());
- pickerEl = document.createElement('div');
- pickerEl.id = PREFIX + '-picker';
- Object.assign(pickerEl.style, {
- position: 'fixed', zIndex: Z.picker,
- display: 'none', opacity: '0',
- transform: 'scale(0.96) translateY(4px)',
- transformOrigin: 'bottom left',
- transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
- background: P.surface,
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
- padding: '6px',
- fontFamily: FONT,
- backdropFilter: 'blur(10px)',
- WebkitBackdropFilter: 'blur(10px)',
- });
-
- // Build the chip grid
- const grid = el('div', {
- display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
- });
-
- ACTIONS.forEach(action => {
- const chip = el('button', {
- display: 'flex', flexDirection: 'column', alignItems: 'center',
- gap: '4px',
- padding: '8px 6px', borderRadius: '6px',
- border: 'none',
- background: action.value === selectedAction ? P.accentSoft : 'transparent',
- color: action.value === selectedAction ? P.accent : P.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.1s ease, color 0.1s ease',
- textAlign: 'center', whiteSpace: 'nowrap',
- });
- const iconWrap = el('span', {
- display: 'flex', alignItems: 'center', justifyContent: 'center',
- height: '20px', opacity: '0.9',
- });
- iconWrap.innerHTML = ICONS[action.value] || '';
- const labelEl = el('span', { lineHeight: '1' });
- labelEl.textContent = action.label;
- chip.appendChild(iconWrap);
- chip.appendChild(labelEl);
- chip.dataset.action = action.value;
- chip.addEventListener('mouseenter', () => {
- if (action.value !== selectedAction) chip.style.background = P.accentSoft;
- });
- chip.addEventListener('mouseleave', () => {
- chip.style.background = action.value === selectedAction ? P.accentSoft : 'transparent';
- });
- chip.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedAction = action.value;
- hideActionPicker();
- updateBarContent('configure');
- });
- grid.appendChild(chip);
- });
-
- pickerEl.appendChild(grid);
- document.body.appendChild(pickerEl);
- defangOutsideHandlers(pickerEl);
-
- // Cache the palette on the picker so toggleActionPicker's state refresh
- // uses the same theme-aware colors when it repaints chips.
- pickerEl.__iceq_palette = P;
- }
-
- function toggleActionPicker() {
- if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
- // Rebuild chips to reflect current selection
- const P = pickerEl.__iceq_palette || barPaletteForTheme(detectPageTheme());
- pickerEl.querySelectorAll('button').forEach(chip => {
- const isActive = chip.dataset.action === selectedAction;
- chip.style.background = isActive ? P.accentSoft : 'transparent';
- chip.style.color = isActive ? P.accent : P.text;
- });
- // Position above the bar
- const barRect = barEl.getBoundingClientRect();
- const pickerH = 170; // approximate; grows with icon + label rows
- let top = barRect.top - pickerH - 6;
- if (top < 8) top = barRect.bottom + 6;
- Object.assign(pickerEl.style, {
- top: top + 'px', left: barRect.left + 'px',
- display: 'block',
- });
- requestAnimationFrame(() => {
- pickerEl.style.opacity = '1';
- pickerEl.style.transform = 'scale(1) translateY(0)';
- });
- }
-
- function hideActionPicker() {
- if (!pickerEl) return;
- pickerEl.style.opacity = '0';
- pickerEl.style.transform = 'scale(0.96) translateY(4px)';
- setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
- }
-
- // ---------------------------------------------------------------------------
- // Params panel (per-variant coarse controls)
- //
- // Variants may declare a parameter manifest via a JSON attribute on the
- // variant wrapper:
- //
- // <div data-impeccable-variant="1"
- // data-impeccable-params='[{"id":"density","kind":"steps",...}]'>
- //
- // The panel docks to the right edge of the outline during CYCLING and
- // exposes 2-5 coarse knobs. Values apply to the variant wrapper so scoped
- // CSS can respond instantly without regeneration:
- //
- // range / numeric toggle → CSS var (`--p-<id>`) used via var(--p-foo, N)
- // steps / boolean toggle → data-p-<id> attribute used via :scope[data-p-foo="..."]
- //
- // On variant switch, values reset to that variant's declared defaults.
- // On accept, current values are sent in the event payload so the agent
- // can bake them into the source-file write.
- // ---------------------------------------------------------------------------
-
- let paramsPanelEl = null; // outer wrapper (overflow:hidden, clips the slide)
- let paramsPanelInner = null; // translating content (carries bg, padding, knobs)
- let paramsPanelBody = null; // grid holding the knob cells
- let paramsCurrentValues = {}; // {paramId: value} — mirror of the visible variant's live values
- let tuneOpen = false; // whether the Tune popover is open right now
-
- // Theme-aware Tune popover. Appears as a drawer that slides out from the
- // contextual bar's bar-facing edge (below if the bar sits below the
- // element, above otherwise). Same width as the bar. Auto-wraps to extra
- // rows when the knobs exceed one row. The bar's border-radius on the
- // popover side goes flat while open so the two shapes read as one.
- let paramsPanelPalette = null;
-
- function initParamsPanel() {
- paramsPanelPalette = barPaletteForTheme(detectPageTheme());
- const P = paramsPanelPalette;
-
- // Single element, always in the DOM. The slide animation is a CSS mask
- // with mask-size growing from 0% to 100% along the bar-facing axis — no
- // display toggle, no opacity toggle, no transform trickery. The mask
- // hides everything initially; as it grows, content is revealed from
- // the bar edge outward.
- paramsPanelEl = document.createElement('div');
- paramsPanelEl.id = PREFIX + '-params-panel';
- Object.assign(paramsPanelEl.style, {
- position: 'fixed', zIndex: String(Z.bar - 1),
- background: P.surfaceDeep,
- color: P.text,
- fontFamily: FONT,
- padding: '14px 18px',
- boxSizing: 'border-box',
- borderRadius: '0 0 10px 10px',
- pointerEvents: 'none',
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
-
- // clip-path is the same conceptual reveal as mask but with rock-solid
- // transition support across engines. Closed state clips from the far
- // edge; open = inset(0) shows everything.
- clipPath: 'inset(0 0 100% 0)',
- transition: 'clip-path 0.44s ' + EASE,
-
- // Park off-screen until positionParamsPanel places it. These are NOT
- // in the transition list, so they snap instantly — no fly-in from the
- // top-left when first shown.
- top: '-9999px', left: '-9999px', width: '0',
- });
-
- paramsPanelBody = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
- gap: '12px 16px',
- });
-
- paramsPanelEl.appendChild(paramsPanelBody);
- document.body.appendChild(paramsPanelEl);
- // Don't override pointer-events: the panel toggles between 'none' (closed,
- // click-through) and 'auto' (open) on its own. Just silence the host's
- // outside-interaction listeners while the panel is open.
- defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
- paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
- }
-
- function getVisibleVariantEl() {
- if (!currentSessionId) return null;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return null;
- return wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"]');
- }
-
- function parseVariantParams(variantEl) {
- if (!variantEl) return [];
- const raw = variantEl.getAttribute('data-impeccable-params');
- if (!raw) return [];
- try {
- const parsed = JSON.parse(raw);
- return Array.isArray(parsed) ? parsed : [];
- } catch (err) {
- console.warn('[impeccable] Invalid data-impeccable-params JSON:', err.message);
- return [];
- }
- }
-
- function applyParamValue(variantEl, param, value) {
- if (!variantEl) return;
- const attr = 'data-p-' + param.id;
- if (param.kind === 'range') {
- variantEl.style.setProperty('--p-' + param.id, String(value));
- } else if (param.kind === 'toggle') {
- const on = !!value;
- variantEl.style.setProperty('--p-' + param.id, on ? '1' : '0');
- if (on) variantEl.setAttribute(attr, 'on');
- else variantEl.removeAttribute(attr);
- } else if (param.kind === 'steps') {
- variantEl.setAttribute(attr, String(value));
- }
- }
-
- function applyParamDefaults(variantEl, params) {
- paramsCurrentValues = {};
- for (const p of params) {
- paramsCurrentValues[p.id] = p.default;
- applyParamValue(variantEl, p, p.default);
- }
- }
-
- function formatRangeValue(input) {
- const max = parseFloat(input.max), min = parseFloat(input.min);
- const v = parseFloat(input.value);
- if (!isFinite(v)) return input.value;
- return (max - min) <= 2 ? v.toFixed(2) : String(Math.round(v));
- }
-
- function buildParamsPanel(variantEl, params) {
- const P = paramsPanelPalette || barPaletteForTheme(detectPageTheme());
- paramsPanelBody.innerHTML = '';
- for (const p of params) {
- const row = el('div', { display: 'flex', flexDirection: 'column', gap: '6px' });
- const labelRow = el('div', {
- display: 'flex', justifyContent: 'space-between',
- alignItems: 'baseline', gap: '8px',
- });
- const lbl = el('span', {
- fontSize: '10.5px', fontWeight: '600', color: P.text,
- letterSpacing: '0.03em',
- });
- lbl.textContent = p.label || p.id;
- labelRow.appendChild(lbl);
- const readout = el('span', {
- fontSize: '10.5px', color: P.textDim,
- fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
- });
- labelRow.appendChild(readout);
- row.appendChild(labelRow);
-
- if (p.kind === 'range') {
- const input = document.createElement('input');
- input.type = 'range';
- input.min = String(p.min != null ? p.min : 0);
- input.max = String(p.max != null ? p.max : 1);
- input.step = String(p.step != null ? p.step : 0.05);
- input.value = String(p.default);
- Object.assign(input.style, {
- width: '100%', accentColor: C.brand, cursor: 'pointer',
- });
- readout.textContent = formatRangeValue(input);
- input.addEventListener('input', (e) => {
- e.stopPropagation();
- const v = parseFloat(input.value);
- paramsCurrentValues[p.id] = v;
- readout.textContent = formatRangeValue(input);
- applyParamValue(variantEl, p, v);
- queueCheckpoint('param_changed');
- });
- row.appendChild(input);
- } else if (p.kind === 'toggle') {
- const initial = !!p.default;
- readout.textContent = initial ? 'On' : 'Off';
- const track = el('button', {
- position: 'relative', width: '36px', height: '20px',
- borderRadius: '10px', border: 'none', padding: '0',
- cursor: 'pointer',
- background: initial ? C.brand : P.hairline,
- transition: 'background 0.15s ease',
- alignSelf: 'flex-start',
- });
- const knob = el('span', {
- position: 'absolute', top: '2px',
- left: initial ? '18px' : '2px',
- width: '16px', height: '16px', borderRadius: '50%',
- background: 'oklch(98% 0 0)',
- transition: 'left 0.18s ' + EASE,
- boxShadow: '0 1px 2px oklch(0% 0 0 / 0.2)',
- });
- track.appendChild(knob);
- track.addEventListener('click', (e) => {
- e.stopPropagation();
- const next = !paramsCurrentValues[p.id];
- paramsCurrentValues[p.id] = next;
- track.style.background = next ? C.brand : P.hairline;
- knob.style.left = next ? '18px' : '2px';
- readout.textContent = next ? 'On' : 'Off';
- applyParamValue(variantEl, p, next);
- queueCheckpoint('param_changed');
- });
- row.appendChild(track);
- } else if (p.kind === 'steps') {
- const opts = (p.options || []).map(o =>
- typeof o === 'string' ? { value: o, label: o } : o
- );
- const activeOpt = opts.find(o => o.value === p.default) || opts[0];
- readout.textContent = activeOpt ? activeOpt.label : String(p.default);
- const segRow = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(' + opts.length + ', 1fr)',
- gap: '1px', padding: '2px',
- background: P.hairline, borderRadius: '5px',
- });
- const segBtns = [];
- opts.forEach(o => {
- const active = o.value === p.default;
- const b = el('button', {
- padding: '5px 4px', border: 'none', borderRadius: '3px',
- background: active ? C.brand : 'transparent',
- color: active ? 'oklch(98% 0 0)' : P.text,
- fontFamily: FONT, fontSize: '10.5px', fontWeight: '500',
- cursor: 'pointer', whiteSpace: 'nowrap',
- transition: 'background 0.1s ease, color 0.1s ease',
- });
- b.textContent = o.label;
- b.addEventListener('click', (e) => {
- e.stopPropagation();
- paramsCurrentValues[p.id] = o.value;
- readout.textContent = o.label;
- segBtns.forEach(({ btn, val }) => {
- const on = val === o.value;
- btn.style.background = on ? C.brand : 'transparent';
- btn.style.color = on ? 'oklch(98% 0 0)' : P.text;
- });
- applyParamValue(variantEl, p, o.value);
- queueCheckpoint('param_changed');
- });
- segRow.appendChild(b);
- segBtns.push({ btn: b, val: o.value });
- });
- row.appendChild(segRow);
- }
-
- paramsPanelBody.appendChild(row);
- }
- }
-
- // Decide which way the popover opens: away from the picked element. If the
- // bar landed below the element, popover slides DOWN from the bar's bottom.
- // If the bar landed above, popover slides UP from the bar's top.
- function popoverDirection() {
- if (!barEl || !selectedElement) return 'below';
- const br = barEl.getBoundingClientRect();
- const er = selectedElement.getBoundingClientRect();
- return br.top >= er.bottom - 4 ? 'below' : 'above';
- }
-
- // The popover overlaps the bar by OVERLAP px on the bar-facing side. With
- // popover z-index below bar, that overlap sits behind bar (invisible) and
- // reinforces the "tucked behind" feel. Padding compensates so the real
- // content starts flush with bar's outer edge.
- const TUNE_OVERLAP = 6;
-
- // Closed clip-path depends on direction: for 'below' clip from the far
- // (bottom) edge so the reveal grows downward from the bar; for 'above'
- // clip from the top edge so the reveal grows upward from the bar.
- function closedClipPath(direction) {
- return direction === 'below' ? 'inset(0 0 100% 0)' : 'inset(100% 0 0 0)';
- }
-
- function setClipPath(value, withTransition) {
- const saved = paramsPanelEl.style.transition;
- if (!withTransition) paramsPanelEl.style.transition = 'none';
- paramsPanelEl.style.clipPath = value;
- if (!withTransition) {
- void paramsPanelEl.offsetHeight;
- paramsPanelEl.style.transition = saved;
- }
- }
-
- function positionParamsPanel() {
- if (!paramsPanelEl || !barEl || barEl.style.display === 'none') return;
- const br = barEl.getBoundingClientRect();
- const direction = popoverDirection();
- const prevDirection = paramsPanelEl.dataset.tuneDirection;
-
- // top/left/width are NOT in the transition list, so they snap instantly.
- paramsPanelEl.style.left = br.left + 'px';
- paramsPanelEl.style.width = br.width + 'px';
-
- if (direction === 'below') {
- paramsPanelEl.style.top = (br.bottom - TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '0 0 10px 10px';
- paramsPanelEl.style.paddingTop = (14 + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.paddingBottom = '14px';
- } else {
- const ih = paramsPanelEl.offsetHeight || 80;
- paramsPanelEl.style.top = (br.top - ih + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '10px 10px 0 0';
- paramsPanelEl.style.paddingTop = '14px';
- paramsPanelEl.style.paddingBottom = (14 + TUNE_OVERLAP) + 'px';
- }
- paramsPanelEl.dataset.tuneDirection = direction;
-
- // If currently closed and direction flipped (or first-time setup),
- // snap the clip-path to the new direction's closed pose without
- // transitioning (so the clip doesn't slide across the element).
- if (!tuneOpen && (!prevDirection || prevDirection !== direction)) {
- setClipPath(closedClipPath(direction), false);
- }
- }
-
- function showParamsPanel() {
- if (!paramsPanelEl) return;
- positionParamsPanel();
- paramsPanelEl.style.pointerEvents = 'auto';
- // rAF so the positioning paint commits before the transition fires.
- requestAnimationFrame(() => {
- setClipPath('inset(0 0 0 0)', true);
- });
- }
-
- function hideParamsPanel() {
- if (!paramsPanelEl) return;
- paramsPanelEl.style.pointerEvents = 'none';
- const direction = paramsPanelEl.dataset.tuneDirection || 'below';
- setClipPath(closedClipPath(direction), true);
- }
-
- // Build/rebuild the panel's contents for the current variant AND apply
- // its defaults to the variant wrapper (so scoped CSS responds even before
- // the user opens the popover). Visibility is governed by tuneOpen.
- function refreshParamsPanel() {
- if (state !== 'CYCLING') {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- if (tuneOpen) {
- // If already visible (variant cycled while open), refresh in place
- // instead of re-running the clip-path animation.
- const alreadyVisible = paramsPanelEl.style.display === 'block'
- && paramsPanelEl.style.opacity === '1';
- if (alreadyVisible) positionParamsPanel();
- else showParamsPanel();
- } else {
- hideParamsPanel();
- }
- }
-
- function toggleTunePopover() {
- if (tuneOpen) { closeTunePopover(); return; }
- openTunePopover();
- }
-
- function openTunePopover() {
- if (state !== 'CYCLING') return;
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) return;
- // Build fresh to ensure the current variant's controls are shown.
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- tuneOpen = true;
- showParamsPanel();
- // Kill the bar's shadow on the popover-facing side so the dark popover
- // doesn't pick up a bright glow line.
- if (barEl) {
- const direction = paramsPanelEl?.dataset.tuneDirection || 'below';
- barEl.style.boxShadow = direction === 'below' ? BAR_SHADOW_UP : BAR_SHADOW_DOWN;
- }
- // Re-render the bar so the Tune chip picks up the active styling.
- updateBarContent('cycling');
- }
-
- function closeTunePopover() {
- tuneOpen = false;
- hideParamsPanel();
- if (barEl) barEl.style.boxShadow = BAR_SHADOW_DEFAULT;
- if (barEl && barEl.style.display !== 'none' && state === 'CYCLING') {
- updateBarContent('cycling');
- }
- }
-
- // ---------------------------------------------------------------------------
- // Variant cycling in DOM
- // ---------------------------------------------------------------------------
-
- function showVariantInDOM(sessionId, num) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
- for (const child of wrapper.children) {
- const v = child.dataset ? child.dataset.impeccableVariant : null;
- if (!v) continue;
- child.style.display = (v === String(num)) ? '' : 'none';
- }
- // Unconditional refresh — covers first-reveal (no-op if state isn't
- // CYCLING yet, the subsequent CYCLING transition triggers its own
- // refresh) and every cycle step.
- refreshParamsPanel();
- }
-
- /**
- * No-HMR fallback: fetch the raw source file from the live server,
- * parse it, extract the variant wrapper, and inject it into the live DOM.
- * This works even when the dev server caches HTML (Bun, static servers).
- */
- function injectVariantsFromSource(filePath, sessionId) {
- const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
- fetch(url)
- .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
- .then(html => {
- // Parse the raw source HTML
- const parser = new DOMParser();
- const doc = parser.parseFromString(html, 'text/html');
- const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!srcWrapper) {
- console.error('[impeccable] Variant wrapper not found in source file.');
- return;
- }
-
- // Find the original element in the live DOM.
- // The original is inside the wrapper in the source. We find the
- // corresponding element in the live DOM by matching the first child's
- // tag + classes from the original snapshot.
- const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
- if (!origContent) return;
-
- const tag = origContent.tagName.toLowerCase();
- const cls = origContent.className;
- let liveEl = null;
- if (origContent.id) {
- liveEl = document.getElementById(origContent.id);
- } else if (cls) {
- // Find by tag + exact class match
- const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
- for (const c of candidates) {
- if (c.className === cls && !own(c)) { liveEl = c; break; }
- }
- }
-
- if (!liveEl) {
- console.error('[impeccable] Could not find original element in live DOM.');
- return;
- }
-
- const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;
-
- // Replace the live element with the full wrapper from source
- const wrapper = srcWrapper.cloneNode(true);
- liveEl.parentElement.replaceChild(wrapper, liveEl);
-
- // Update state: count variants, preserving the user's current variant
- // when a late HMR/source reinjection lands after they have cycled.
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants
- ? previousVisibleVariant
- : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);
- showVariantInDOM(sessionId, visibleVariant);
-
- // Update selectedElement to the visible variant's content
- selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;
-
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- saveSession();
- console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
- })
- .catch(err => {
- console.error('[impeccable] Failed to fetch source:', err);
- showToast('Could not load variants. Try refreshing the page.', 5000);
- });
- }
-
- function cycleVariant(dir) {
- const next = visibleVariant + dir;
- if (next < 1 || next > arrivedVariants) return;
- visibleVariant = next;
- showVariantInDOM(currentSessionId, next); // calls refreshParamsPanel itself
- updateSelectedElement();
- updateBarContent('cycling');
- saveSession();
- queueCheckpoint('variant_changed');
- }
-
- function updateSelectedElement() {
- if (!currentSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return;
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- function readVisibleVariantFromDOM(sessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return 0;
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- for (const variant of variants) {
- if (variant.style.display === 'none') continue;
- const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);
- if (idx > 0) return idx;
- }
- return 0;
- }
-
- // Resolve the element that represents the variant's visible content.
- // Contract: each variant div should contain exactly one top-level element
- // (the full replacement). In practice a model may ship loose siblings or
- // lead with <style>/<script>. Be defensive: skip non-visual elements, and
- // if the variant has multiple element children, use the variant div itself
- // (it wraps all of them and gets correct bounds).
- function pickVariantContent(wrapper, index) {
- if (!wrapper) return null;
- const variantDiv = wrapper.querySelector('[data-impeccable-variant="' + index + '"]');
- if (!variantDiv) return null;
- const NON_VISUAL = new Set(['STYLE', 'SCRIPT', 'LINK', 'META', 'TEMPLATE']);
- const visual = [];
- for (const child of variantDiv.children) {
- if (!NON_VISUAL.has(child.tagName)) visual.push(child);
- }
- if (visual.length === 1) return visual[0];
- return variantDiv;
- }
-
- // Hold window.scrollY at a fixed value across DOM mutations inside the
- // session's wrapper (HMR patches, variant inserts, cycle swaps).
- function startScrollLock(sessionId, initialTargetY) {
- stopScrollLock();
- scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)
- ? initialTargetY
- : window.scrollY;
- console.log('[impeccable.scroll] startScrollLock', { sessionId, scrollY: window.scrollY, targetY: scrollLockTargetY, initialOverride: initialTargetY });
-
- try { history.scrollRestoration = 'manual'; } catch {}
-
- const prevHtmlAnchor = document.documentElement.style.overflowAnchor;
- const prevBodyAnchor = document.body.style.overflowAnchor;
- document.documentElement.style.overflowAnchor = 'none';
- document.body.style.overflowAnchor = 'none';
-
- const correct = (why) => {
- scrollLockRaf = null;
- if (scrollLockTargetY == null) return;
- const before = window.scrollY;
- const delta = before - scrollLockTargetY;
- if (Math.abs(delta) < 0.5) {
- console.log('[impeccable.scroll] correct noop', { why, scrollY: before, targetY: scrollLockTargetY });
- return;
- }
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] corrected', { why, from: before, to: scrollLockTargetY, delta, nowAt: window.scrollY });
- };
- const schedule = (why) => {
- if (scrollLockRaf != null) return;
- scrollLockRaf = requestAnimationFrame(() => correct(why));
- };
-
- scrollLockObserver = new MutationObserver((mutations) => {
- for (const m of mutations) {
- if (m.target?.closest?.('[data-impeccable-variants="' + sessionId + '"]')) {
- const childAdds = Array.from(m.addedNodes).map(n => n.nodeType === 1 ? (n.tagName + (n.dataset?.impeccableVariant ? ('[variant=' + n.dataset.impeccableVariant + ']') : '')) : n.nodeType).join(',');
- console.log('[impeccable.scroll] mutation inside wrapper', { type: m.type, target: m.target?.tagName, adds: childAdds, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('mutation-in-wrapper');
- return;
- }
- for (const n of m.addedNodes) {
- if (n.nodeType === 1 && (n.matches?.('[data-impeccable-variants="' + sessionId + '"]') || n.querySelector?.('[data-impeccable-variants="' + sessionId + '"]'))) {
- console.log('[impeccable.scroll] wrapper node added', { tag: n.tagName, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('wrapper-added');
- return;
- }
- }
- }
- });
- scrollLockObserver.observe(document.body, { childList: true, subtree: true });
-
- scrollLockAbort = new AbortController();
- scrollLockAbort.signal.addEventListener('abort', () => {
- document.documentElement.style.overflowAnchor = prevHtmlAnchor;
- document.body.style.overflowAnchor = prevBodyAnchor;
- }, { once: true });
- const sig = { signal: scrollLockAbort.signal };
- // Track whether the most recent scroll came from a user gesture. We
- // gate user-scroll re-anchoring on this flag so programmatic smooth
- // scrolls (browser reload-restore, scrollIntoView from other scripts)
- // don't accidentally update our target.
- let userGestureAt = 0;
- const USER_GESTURE_WINDOW_MS = 250;
-
- const reanchor = (why) => {
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- const prevTarget = scrollLockTargetY;
- scrollLockTargetY = window.scrollY;
- writeScrollY(scrollLockTargetY);
- console.log('[impeccable.scroll] reanchor', { why, prevTarget, newTarget: scrollLockTargetY });
- };
- const markGesture = (why) => {
- userGestureAt = performance.now();
- reanchor(why);
- };
- window.addEventListener('wheel', () => markGesture('wheel'), { passive: true, ...sig });
- window.addEventListener('touchstart', () => markGesture('touchstart'), { passive: true, ...sig });
- window.addEventListener('touchmove', () => markGesture('touchmove'), { passive: true, ...sig });
- window.addEventListener('keydown', (e) => {
- if (['PageDown', 'PageUp', ' ', 'End', 'Home', 'ArrowDown', 'ArrowUp'].includes(e.key)) markGesture('key:' + e.key);
- }, sig);
-
- // Correct on EVERY scroll event: whether it's the browser's
- // post-reload animated restore or some other script calling
- // scrollIntoView, we want to snap back immediately. Only skip if a
- // user gesture fired in the last 250ms.
- let lastLoggedScrollY = window.scrollY;
- window.addEventListener('scroll', () => {
- const now = window.scrollY;
- if (Math.abs(now - lastLoggedScrollY) > 5) {
- console.log('[impeccable.scroll] scroll event', { from: lastLoggedScrollY, to: now, targetY: scrollLockTargetY });
- lastLoggedScrollY = now;
- }
- if (scrollLockTargetY == null) return;
- if (performance.now() - userGestureAt < USER_GESTURE_WINDOW_MS) return;
- if (Math.abs(now - scrollLockTargetY) < 0.5) return;
- console.log('[impeccable.scroll] scroll-event snap', { from: now, to: scrollLockTargetY });
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- }, { passive: true, ...sig });
-
- // Apply target synchronously, not via rAF — racing the browser's
- // restore or a smooth-scroll animation means we want to win now.
- if (Math.abs(window.scrollY - scrollLockTargetY) > 0.5) {
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] startScrollLock initial apply', { to: scrollLockTargetY });
- }
- }
-
- function stopScrollLock() {
- if (scrollLockObserver) { scrollLockObserver.disconnect(); scrollLockObserver = null; }
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }
- scrollLockTargetY = null;
- // NOTE: do NOT clear the persistent scroll key here. startScrollLock
- // calls us as a reset, and clearing the key would nuke the Go-time
- // scrollY that the next resume needs to read.
- }
-
- // ---------------------------------------------------------------------------
- // MutationObserver for progressive variant reveal
- // ---------------------------------------------------------------------------
-
- function startVariantObserver(sessionId) {
- let updating = false; // re-entrancy guard
-
- const obs = new MutationObserver((mutations) => {
- if (updating) return;
-
- // Only react to mutations that add nodes with data-impeccable-variant,
- // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
- let dominated = false;
- for (const m of mutations) {
- if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
- for (const n of m.addedNodes) {
- if (n.nodeType !== 1) continue;
- // Direct hit: the added node itself is the wrapper or a variant.
- if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
- dominated = true; break;
- }
- // Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
- // a whole subtree where the wrapper is a descendant of the added
- // node. Without this check, the observer ignores those mutations
- // and the session stays in GENERATING forever.
- if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
- dominated = true; break;
- }
- }
- if (dominated) break;
- }
- if (!dominated) return;
-
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
-
- // Re-anchor selectedElement if it was detached by live-wrap's HMR swap.
- // Without this, the shader / highlight / bar track a zero-rect phantom
- // and the overlay appears frozen.
- if (selectedElement && !document.body.contains(selectedElement)) {
- selectedElement = pickVariantContent(wrapper, 'original') || wrapper;
- }
-
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- const count = variants.length;
-
- // Nothing new
- if (count <= arrivedVariants) return;
-
- updating = true;
- arrivedVariants = count;
- if (visibleVariant === 0 && arrivedVariants > 0) {
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;
- showVariantInDOM(sessionId, visibleVariant);
- // showVariantInDOM hid the original (display:none); if we were still
- // anchored to the original's content, its boundingRect is now zero
- // and the bar snaps to (0,0). Re-point at the visible variant instead.
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- if (expected > 0) expectedVariants = expected;
-
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- } else if (state === 'GENERATING') {
- updateBarContent('generating');
- }
- saveSession();
- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');
- updating = false;
- });
-
- obs.observe(document.body, { childList: true, subtree: true });
- return obs;
- }
-
- // ---------------------------------------------------------------------------
- // Bar scroll tracking
- // ---------------------------------------------------------------------------
-
- function startScrollTracking() {
- function tick() {
- if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
- positionBar();
- showHighlight(selectedElement);
- if (tuneOpen) positionParamsPanel();
- }
- if (annotActive) positionAnnotOverlay(selectedElement);
- // Shader overlay (via debug P toggle or generation) is repositioned
- // by its own branch below; debug no longer has a separate overlay.
- if (shaderState) positionShaderOverlay();
- scrollRaf = requestAnimationFrame(tick);
- }
- scrollRaf = requestAnimationFrame(tick);
- }
-
- function stopScrollTracking() {
- if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
- }
-
- // ---------------------------------------------------------------------------
- // SSE (server→browser) + fetch POST (browser→server)
- // Zero-dependency replacement for WebSocket.
- // ---------------------------------------------------------------------------
-
- let evtSource = null;
- let sseRetries = 0;
- const SSE_MAX_RETRIES = 20; // generous: heartbeats keep the connection alive, so retries mean real trouble
-
- function connectSSE() {
- evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
-
- evtSource.onopen = () => {
- sseRetries = 0; // reset on successful (re)connect
- };
-
- evtSource.onmessage = (e) => {
- sseRetries = 0; // reset on any successful message
- let msg; try { msg = JSON.parse(e.data); } catch { return; }
- switch (msg.type) {
- case 'connected':
- hasProjectContext = !!msg.hasProjectContext;
- if (!hasProjectContext) showToast('No PRODUCT.md found. Variants will be brand-agnostic. Run /impeccable teach to generate one.', 7000);
- console.log('[impeccable] Live mode connected.');
- if (state === 'IDLE') state = 'PICKING';
- break;
- case 'done':
- // Variants already arrived via HMR → normal transition.
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- if (state === 'GENERATING') {
- state = 'CYCLING';
- updateBarContent('cycling');
- refreshParamsPanel();
- }
- break;
- }
- // Variants are in source but not in the DOM yet. Common when the
- // picked element lived inside conditional render (closed modal,
- // hidden tab, a route the user navigated away from). The variant
- // MutationObserver stays armed and auto-transitions to CYCLING
- // the moment the wrapper actually mounts. Nudge the user toward
- // that path with a toast — better than the prior force-reload
- // which reset framework state and left the session stuck.
- setTimeout(() => {
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
- if (state !== 'GENERATING') return;
- showToast(
- "Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
- 15000,
- );
- }, 2000);
- break;
- case 'error':
- console.error('[impeccable] Error:', msg.message);
- showToast('Error: ' + msg.message, 5000);
- hideBar();
- state = 'PICKING';
- break;
- }
- };
-
- evtSource.onerror = () => {
- sseRetries++;
- if (sseRetries <= SSE_MAX_RETRIES) {
- console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
- return; // EventSource auto-reconnects
- }
- // Server is gone. Clean up gracefully.
- console.log('[impeccable] Live server unreachable. Cleaning up UI.');
- evtSource.close();
- evtSource = null;
- handleServerLost();
- };
- }
-
- /** Server died or became unreachable. Reset UI to a clean state. */
- function handleServerLost() {
- const recoveryState = currentSessionId ? state : 'IDLE';
- if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
- showToast('Live server disconnected. Session ended.', 5000);
- }
- hideBar();
- hideHighlight();
- hideShaderOverlay();
- hideAnnotOverlay();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- // Preserve local session state on server loss. The durable journal is the
- // source of truth, but localStorage plus the variant wrapper lets the UI
- // resume after a helper restart or page reload instead of treating a
- // transient disconnect as an explicit discard.
- selectedElement = null;
- selectedAction = 'impeccable';
- state = recoveryState;
- if (currentSessionId) saveSession();
- }
-
- function sendEvent(msg, opts) {
- msg.token = TOKEN;
- function handleFailure(err) {
- console.error('[impeccable] Failed to send event:', err);
- if (opts && opts.throwOnError) throw err;
- return null;
- }
- return fetch('http://localhost:' + PORT + '/events', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(msg),
- }).then(res => {
- if (res.ok) return res;
- return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));
- }).catch(handleFailure);
- }
-
- function checkpointPayload(reason) {
- return {
- type: 'checkpoint',
- id: currentSessionId,
- revision: sessionState.nextCheckpointRevision(),
- owner: browserOwner,
- phase: String(state || '').toLowerCase(),
- reason,
- pageUrl: location.pathname,
- expectedVariants,
- arrivedVariants,
- visibleVariant,
- paramValues: { ...paramsCurrentValues },
- };
- }
-
- function sendCheckpoint(reason) {
- if (!currentSessionId) return Promise.resolve(null);
- return sendEvent(checkpointPayload(reason)).catch(() => null);
- }
-
- function queueCheckpoint(reason) {
- if (!currentSessionId) return;
- if (checkpointTimer) clearTimeout(checkpointTimer);
- checkpointTimer = setTimeout(() => {
- checkpointTimer = null;
- sendCheckpoint(reason);
- }, 120);
- }
-
- // ---------------------------------------------------------------------------
- // Event handlers
- // ---------------------------------------------------------------------------
-
- function handleMouseMove(e) {
- if (state !== 'PICKING' || !pickActive) return;
- const target = document.elementFromPoint(e.clientX, e.clientY);
- if (!target || !pickable(target) || target === hoveredElement) return;
- hoveredElement = target;
- showHighlight(target);
- }
-
- function handleClick(e) {
- // Close action picker on any outside click
- if (pickerEl?.style.display !== 'none' && !own(e.target)) {
- hideActionPicker();
- }
- // Close Tune popover on outside click (anything outside panel + bar)
- if (tuneOpen && paramsPanelEl && !paramsPanelEl.contains(e.target) && barEl && !barEl.contains(e.target)) {
- closeTunePopover();
- }
- // In CONFIGURING: click outside the bar and selected element returns to PICKING
- if (state === 'CONFIGURING' && !own(e.target) && selectedElement && !selectedElement.contains(e.target)) {
- hideBar();
- stopScrollTracking();
- hideAnnotOverlay();
- clearAnnotations();
- state = 'PICKING';
- hoveredElement = null;
- hideHighlight();
- return;
- }
- if (state !== 'PICKING' || !pickActive) return;
- if (own(e.target)) return;
- if (!hoveredElement || !pickable(hoveredElement)) return;
- e.preventDefault();
- e.stopPropagation();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- maybePrefetchPage();
- maybeWarnConditionalAncestor(selectedElement);
- }
-
- /**
- * Surface a brief, non-blocking heads-up when the picked element lives
- * inside a container whose visibility is gated by ephemeral state — modals,
- * collapsible panels, popovers, off-screen tab panels. If HMR remounts the
- * parent during generation (Vite Fast Refresh, SvelteKit page reload), the
- * variants land in source but stay invisible until the user re-opens the
- * container. Telling the user upfront is much friendlier than the silent
- * timeout-then-toast that they'd otherwise hit.
- *
- * Heuristic, intentionally narrow — only fires for unambiguous cases so
- * we don't cry wolf on every nested element.
- */
- function maybeWarnConditionalAncestor(el) {
- let node = el?.parentElement;
- let depth = 0;
- while (node && depth < 12) {
- // 1. Active dialog / modal
- if (node.getAttribute && node.getAttribute('role') === 'dialog'
- && node.getAttribute('aria-modal') === 'true') {
- showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 2. Common Radix / shadcn / headless-ui open-state attribute
- if (node.dataset && node.dataset.state === 'open') {
- showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 3. Tab panel — only meaningful when the page also shows ANOTHER
- // tab as selected. A single tabpanel with no tablist is just a static
- // section in disguise and isn't conditional.
- if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
- const list = document.querySelector('[role="tablist"]');
- if (list) {
- const tabs = list.querySelectorAll('[role="tab"]');
- if (tabs.length > 1) {
- showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
- return;
- }
- }
- }
- // 4. Collapsible: aria-expanded sibling. Look for the trigger button.
- if (node.id) {
- const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
- if (trigger) {
- showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
- return;
- }
- }
- node = node.parentElement;
- depth++;
- }
- }
-
- // Fire a lightweight prefetch event the first time the user selects an
- // element on a given route. The agent uses this to Read the underlying file
- // into context before Go is hit, shaving the read off the critical path.
- // Dedupe per session by pathname — clicking around on the same page doesn't
- // re-fire.
- //
- // DISABLED: quick-Go workflows pay an extra harness round trip because
- // prefetch + generate arrive as two events instead of one. Re-enable with
- // a browser-side debounce (~800–1000ms, cancelled on Go) if we want to
- // resurrect this. Server validator and skill dispatch remain in place so
- // flipping this flag is the only change needed.
- const PREFETCH_ENABLED = false;
- const prefetchedPaths = new Set();
- function maybePrefetchPage() {
- if (!PREFETCH_ENABLED) return;
- const path = location.pathname;
- if (prefetchedPaths.has(path)) return;
- prefetchedPaths.add(path);
- sendEvent({ type: 'prefetch', pageUrl: path });
- }
-
- function handleKeyDown(e) {
- // When the annotation input is focused, let it handle its own keys.
- if (annotEditing && annotEditing.input && e.target === annotEditing.input) return;
- if (e.key === 'Escape') {
- e.preventDefault();
- if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
- if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); hideAnnotOverlay(); clearAnnotations(); state = 'PICKING'; return; }
- if (state === 'CYCLING') { handleDiscard(); return; }
- if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
- if (state === 'PICKING') {
- // Use togglePick so the "Pick" button in the global bar also flips
- // off, otherwise the bar stays lit while nothing else is active.
- if (pickActive) togglePick();
- else { hideHighlight(); state = 'IDLE'; }
- return;
- }
- }
-
- // Arrow/Enter nav works in PICKING (hover) and CONFIGURING (selected, input empty)
- var navEl = (state === 'PICKING') ? hoveredElement : (state === 'CONFIGURING') ? selectedElement : null;
- if (navEl && (e.key === 'ArrowUp' || e.key === 'ArrowDown' || (e.key === 'Enter' && state === 'PICKING'))) {
- let next = null;
- if (e.key === 'ArrowDown' && !e.shiftKey) {
- next = navEl.nextElementSibling;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'ArrowUp' && !e.shiftKey) {
- next = navEl.previousElementSibling;
- while (next && !pickable(next)) next = next.previousElementSibling;
- } else if (e.key === 'ArrowUp' && e.shiftKey) {
- next = navEl.parentElement;
- if (next && !pickable(next)) next = null;
- } else if (e.key === 'ArrowDown' && e.shiftKey) {
- next = navEl.firstElementChild;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'Enter') {
- e.preventDefault();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- return;
- }
- if (next) {
- e.preventDefault();
- if (state === 'PICKING') {
- hoveredElement = next;
- } else {
- // CONFIGURING: re-select the new element and refresh the bar
- selectedElement = next;
- clearAnnotations();
- showAnnotOverlay(next);
- showBar('configure');
- startScrollTracking();
- }
- showHighlight(next);
- next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
- }
- return;
- }
-
- if (state === 'CYCLING') {
- if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
- if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
- if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
- }
- }
-
- function handleGo() {
- if (!selectedElement || state !== 'CONFIGURING') return;
- const input = document.getElementById(PREFIX + '-input');
- const prompt = input ? input.value.trim() : '';
-
- // Commit any pending pin edit BEFORE we snapshot annotations.
- if (annotEditing) finalizeEditingPin();
-
- currentSessionId = id8();
- expectedVariants = selectedCount;
- arrivedVariants = 0;
- visibleVariant = 0;
-
- // Flip to GENERATING immediately so the bar morphs without waiting on
- // capture + upload. The event is emitted from captureAndEmit() once the
- // screenshot is uploaded (or capture fails — we still emit, just without
- // screenshotPath).
- const elForCapture = selectedElement;
- const captureRect = elForCapture.getBoundingClientRect();
- const snapshot = {
- comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),
- strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),
- };
- const basePayload = {
- type: 'generate', id: currentSessionId,
- action: selectedAction,
- freeformPrompt: prompt || undefined,
- count: selectedCount,
- pageUrl: location.pathname,
- element: extractContext(elForCapture),
- };
- if (snapshot.comments.length > 0) basePayload.comments = snapshot.comments;
- if (snapshot.strokes.length > 0) basePayload.strokes = snapshot.strokes;
-
- // Hide the interactive overlay so it doesn't linger during generation.
- hideAnnotOverlay();
- clearAnnotations();
-
- state = 'GENERATING';
- showBar('generating');
- saveSession();
- sendCheckpoint('generate_started');
- writeScrollY(window.scrollY);
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
- console.log('[impeccable.scroll] Go pressed', { scrollY: window.scrollY, sessionId: currentSessionId });
- startScrollLock(currentSessionId);
-
- captureAndEmit(elForCapture, basePayload, snapshot, captureRect);
- }
-
- // ---------------------------------------------------------------------------
- // Screenshot capture + upload
- // ---------------------------------------------------------------------------
-
- let msLoadPromise = null;
- function loadModernScreenshot() {
- if (window.modernScreenshot) return Promise.resolve(window.modernScreenshot);
- if (msLoadPromise) return msLoadPromise;
- msLoadPromise = new Promise((resolve, reject) => {
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/modern-screenshot.js';
- s.onload = () => resolve(window.modernScreenshot);
- s.onerror = () => { msLoadPromise = null; reject(new Error('modern-screenshot failed to load')); };
- document.head.appendChild(s);
- });
- return msLoadPromise;
- }
-
- // Collect @font-face rules from every stylesheet on the page. Cross-origin
- // sheets (Google Fonts, Typekit, etc.) throw SecurityError on .cssRules
- // access, so modern-screenshot can't embed them on its own — the resulting
- // SVG falls back to system fonts and text re-wraps + renders with different
- // weight. We fetch the raw CSS text (CORS-permitted for these providers),
- // extract @font-face blocks, inline the referenced font files as base64
- // data URIs (SVGs rasterized via canvas can't fetch external resources,
- // so URLs inside the SVG silently fail without this), and pass the result
- // to modern-screenshot as font.cssText.
- const FONT_EXT_RE = /\.(woff2?|ttf|otf|eot)(\?.*)?$/i;
- const FONT_MIME = {
- woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', eot: 'application/vnd.ms-fontobject',
- };
- function bufferToBase64(buf) {
- const bytes = new Uint8Array(buf);
- let binary = '';
- const CHUNK = 0x8000;
- for (let i = 0; i < bytes.length; i += CHUNK) {
- binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
- }
- return btoa(binary);
- }
- async function inlineFontUrls(cssText) {
- const urlRe = /url\((['"]?)(https?:\/\/[^'")\s]+)\1\)/g;
- const urls = new Set();
- let m;
- while ((m = urlRe.exec(cssText))) {
- if (FONT_EXT_RE.test(m[2])) urls.add(m[2]);
- }
- const map = new Map();
- await Promise.all([...urls].map(async (url) => {
- try {
- const res = await fetch(url);
- if (!res.ok) return;
- const buf = await res.arrayBuffer();
- const ext = url.toLowerCase().match(FONT_EXT_RE)?.[1] || 'woff2';
- const mime = FONT_MIME[ext] || 'application/octet-stream';
- map.set(url, 'data:' + mime + ';base64,' + bufferToBase64(buf));
- } catch { /* skip; fall through to URL */ }
- }));
- return cssText.replace(urlRe, (orig, q, url) => {
- const data = map.get(url);
- return data ? 'url(' + q + data + q + ')' : orig;
- });
- }
- async function collectFontCssText() {
- const chunks = [];
- const fontFaceRe = /@font-face\s*\{[^}]*\}/g;
- for (const sheet of document.styleSheets) {
- try {
- const rules = sheet.cssRules;
- for (const rule of rules) {
- if (rule.constructor.name === 'CSSFontFaceRule' || rule.cssText?.startsWith('@font-face')) {
- chunks.push(rule.cssText);
- }
- }
- } catch {
- if (!sheet.href) continue;
- try {
- const res = await fetch(sheet.href);
- if (!res.ok) continue;
- const text = await res.text();
- let m2;
- while ((m2 = fontFaceRe.exec(text))) chunks.push(m2[0]);
- } catch { /* ignore; capture is best-effort */ }
- }
- }
- if (chunks.length === 0) return '';
- return inlineFontUrls(chunks.join('\n'));
- }
-
- // True if `s` is a computed color string that renders as nothing
- // (explicit `transparent`, or `rgba(...)` with alpha 0).
- function isTransparentColor(s) {
- if (!s) return true;
- if (s === 'transparent') return true;
- const m = /rgba?\(([^)]+)\)/.exec(s);
- if (!m) return false;
- const parts = m[1].split(',').map((p) => p.trim());
- if (parts.length === 4) return parseFloat(parts[3]) === 0;
- return false;
- }
-
- // modern-screenshot force-sets `background-color: X !important` on the
- // cloned root whenever `backgroundColor` is passed, clobbering the
- // element's own background. So we only pass it when the element is
- // genuinely transparent (no own color, no own image) — in that case
- // we resolve up the DOM to the nearest opaque ancestor so the capture
- // sits on the page's real background instead of rendering black.
- function resolveCanvasBackground(el) {
- const own = getComputedStyle(el);
- if (!isTransparentColor(own.backgroundColor)) return null;
- if (own.backgroundImage && own.backgroundImage !== 'none') return null;
- let node = el.parentElement;
- while (node) {
- const cs = getComputedStyle(node);
- if (!isTransparentColor(cs.backgroundColor)) return cs.backgroundColor;
- node = node.parentElement;
- }
- // The walk already passed through <body> and <html>; if they had been
- // opaque we would have returned. Falling through with the previous
- // `getComputedStyle(body).backgroundColor || …` chain is a trap: that
- // call returns the literal string `"rgba(0, 0, 0, 0)"` for a page that
- // never set its own bg, which is truthy and short-circuits the chain to
- // transparent-black — modern-screenshot then renders the capture on a
- // black canvas and the shader overlay flashes solid black during load.
- // The browser canvas defaults to white, so we do too.
- return '#ffffff';
- }
-
- // Capture the element (with current annotations baked in) and return a PNG
- // Blob. Shared between the Go flow (uploads it to the server) and the
- // debug toggle (displays it as an overlay for side-by-side comparison).
- async function captureElementToBlob(el, snapshot, rect) {
- try { if (document.fonts?.ready) await document.fonts.ready; } catch {}
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- let annotNode = null;
- let savedPosition = null;
- if (hasAnnotations) {
- const pos = getComputedStyle(el).position;
- if (pos === 'static') {
- savedPosition = el.style.position;
- el.style.position = 'relative';
- }
- annotNode = buildAnnotationsForCapture(rect, snapshot);
- el.appendChild(annotNode);
- }
- try {
- const ms = await loadModernScreenshot();
- const fontCssText = await collectFontCssText();
- const backgroundColor = resolveCanvasBackground(el);
- return await ms.domToBlob(el, {
- scale: Math.min(window.devicePixelRatio || 1, 2),
- font: fontCssText ? { cssText: fontCssText } : undefined,
- ...(backgroundColor ? { backgroundColor } : {}),
- });
- } finally {
- if (annotNode) annotNode.remove();
- if (savedPosition !== null) el.style.position = savedPosition;
- }
- }
-
- async function captureAndEmit(el, basePayload, snapshot, rect) {
- let screenshotPath;
- let blob;
- try {
- blob = await captureElementToBlob(el, snapshot, rect);
- } catch (err) {
- console.warn('[impeccable] capture failed, proceeding without screenshot:', err);
- }
- // Light up the shader overlay the moment capture is ready — no reason to
- // wait for the upload to complete before the user sees something alive.
- if (blob && state === 'GENERATING') {
- showShaderOverlay(el, blob, rect);
- }
- // Only upload + forward the screenshot when annotations (comments/strokes)
- // are present. Without annotations the image is pure visual anchoring —
- // it biases the model toward the current rendering and works against the
- // three-distinct-directions brief.
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- if (blob && hasAnnotations) {
- try {
- const uploadRes = await fetch(
- 'http://localhost:' + PORT + '/annotation?token=' + encodeURIComponent(TOKEN) +
- '&eventId=' + encodeURIComponent(basePayload.id),
- { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: blob },
- );
- if (uploadRes.ok) {
- const { path: p } = await uploadRes.json();
- screenshotPath = p;
- } else {
- console.warn('[impeccable] annotation upload failed:', uploadRes.status);
- }
- } catch (err) {
- console.warn('[impeccable] annotation upload failed:', err);
- }
- }
- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);
- }
-
- // ---------------------------------------------------------------------------
- // Shader overlay — renders the captured screenshot as a WebGL texture and
- // runs an editorial "ink-wash" fragment shader over it during generation.
- // A single rolling band sweeps top-to-bottom, desaturating + tinting magenta
- // and leaving a soft trail. Makes the wait feel like a letterpress scan
- // instead of a dead spinner.
- // ---------------------------------------------------------------------------
-
- const SHADER_VS = `attribute vec2 a_position;
-attribute vec2 a_uv;
-varying vec2 v_uv;
-void main() {
- v_uv = a_uv;
- gl_Position = vec4(a_position, 0.0, 1.0);
-}`;
-
- const SHADER_FS = `precision highp float;
-uniform sampler2D u_texture;
-uniform float u_time;
-uniform vec2 u_resolution;
-uniform vec3 u_accent;
-varying vec2 v_uv;
-
-// Asymmetric roller band. Product of two one-sided smoothsteps — peaks at
-// d=0 with a short sharp leading ramp and a longer soft trailing tail. Clean
-// outside the [-leadW, trailW] range (no rogue "trail=1 everywhere below"
-// failure that reversed-edge smoothstep would give).
-float bandAt(float d, float leadW, float trailW) {
- float above = smoothstep(-leadW, 0.0, d);
- float below = 1.0 - smoothstep(0.0, trailW, d);
- return above * below;
-}
-
-void main() {
- vec2 uv = v_uv;
- // Roller sweeps top-to-bottom with small overshoot so each cycle enters
- // and exits the element cleanly.
- float phase = fract(u_time / 3.4);
- float y = phase * 1.25 - 0.12;
- float band = bandAt(uv.y - y, 0.05, 0.32);
-
- // Halftone cell grid (fixed ~10 px pitch).
- float cellPx = 10.0;
- vec2 gridUv = uv * u_resolution / cellPx;
- vec2 cellId = floor(gridUv);
- vec2 cellUv = fract(gridUv) - 0.5;
- vec2 sampleCenter = (cellId + 0.5) * cellPx / u_resolution;
- vec3 cellImg = texture2D(u_texture, sampleCenter).rgb;
- float luma = dot(cellImg, vec3(0.299, 0.587, 0.114));
- // Darker cells → bigger magenta dots (classic risograph halftone curve).
- float radius = sqrt(clamp(1.0 - luma, 0.0, 1.0)) * 0.56;
- float dotMask = smoothstep(radius + 0.06, radius, length(cellUv));
- vec3 paper = vec3(0.975, 0.965, 0.955);
- vec3 dotLayer = mix(paper, u_accent, dotMask);
-
- // Blend the halftone layer in where the roller is passing; leave the
- // element pristine elsewhere.
- vec3 base = texture2D(u_texture, uv).rgb;
- gl_FragColor = vec4(mix(base, dotLayer, band), 1.0);
-}`;
-
- // Editorial Magenta converted to approximate sRGB 0-1 (matches oklch(60% 0.25 350))
- const SHADER_ACCENT = [0.82, 0.16, 0.47];
- let shaderState = null; // { canvas, gl, program, texture, rafId, startTime }
-
- function compileShader(gl, type, source) {
- const sh = gl.createShader(type);
- gl.shaderSource(sh, source);
- gl.compileShader(sh);
- if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
- const info = gl.getShaderInfoLog(sh);
- gl.deleteShader(sh);
- throw new Error('shader compile failed: ' + info);
- }
- return sh;
- }
-
- function positionShaderOverlay() {
- if (!shaderState || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- Object.assign(shaderState.canvas.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- }
-
- function hideShaderOverlay() {
- if (!shaderState) return;
- if (shaderState.rafId) cancelAnimationFrame(shaderState.rafId);
- if (shaderState.canvas) shaderState.canvas.remove();
- const lose = shaderState.gl?.getExtension?.('WEBGL_lose_context');
- try { lose?.loseContext(); } catch {}
- shaderState = null;
- }
-
- async function showShaderOverlay(el, blob, rect) {
- hideShaderOverlay();
- if (!blob || !el) return;
- const canvas = document.createElement('canvas');
- canvas.id = PREFIX + '-shader';
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
- canvas.width = Math.max(1, Math.floor(rect.width * dpr));
- canvas.height = Math.max(1, Math.floor(rect.height * dpr));
- Object.assign(canvas.style, {
- position: 'fixed',
- top: rect.top + 'px', left: rect.left + 'px',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none',
- zIndex: Z.bar - 1,
- });
- document.body.appendChild(canvas);
-
- const gl = canvas.getContext('webgl', { premultipliedAlpha: false, preserveDrawingBuffer: false })
- || canvas.getContext('experimental-webgl');
- if (!gl) {
- // WebGL unavailable — fall back to a plain <img> overlay so the user
- // still sees something meaningful during generation.
- canvas.remove();
- const img = document.createElement('img');
- img.src = URL.createObjectURL(blob);
- img.id = PREFIX + '-shader';
- // Copy positioning via cssText. Object.assign across CSSStyleDeclaration
- // throws in modern Chromium because the source's indexed properties
- // (style[0], [1], ...) are read-only and the engine forbids writing
- // them on the destination.
- img.style.cssText = canvas.style.cssText;
- img.style.outline = '2px dashed ' + C.brand;
- img.style.outlineOffset = '-2px';
- document.body.appendChild(img);
- shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
- return;
- }
-
- let program, texture;
- try {
- const vs = compileShader(gl, gl.VERTEX_SHADER, SHADER_VS);
- const fs = compileShader(gl, gl.FRAGMENT_SHADER, SHADER_FS);
- program = gl.createProgram();
- gl.attachShader(program, vs);
- gl.attachShader(program, fs);
- gl.linkProgram(program);
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- throw new Error('program link failed: ' + gl.getProgramInfoLog(program));
- }
- // Full-screen quad
- const buf = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
- -1, -1, 0, 1,
- 1, -1, 1, 1,
- -1, 1, 0, 0,
- -1, 1, 0, 0,
- 1, -1, 1, 1,
- 1, 1, 1, 0,
- ]), gl.STATIC_DRAW);
- const posLoc = gl.getAttribLocation(program, 'a_position');
- const uvLoc = gl.getAttribLocation(program, 'a_uv');
- gl.enableVertexAttribArray(posLoc);
- gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 16, 0);
- gl.enableVertexAttribArray(uvLoc);
- gl.vertexAttribPointer(uvLoc, 2, gl.FLOAT, false, 16, 8);
- } catch (err) {
- console.warn('[impeccable] shader setup failed:', err);
- canvas.remove();
- return;
- }
-
- // Upload the screenshot as a texture
- let bitmap;
- try {
- bitmap = await createImageBitmap(blob);
- } catch {
- // Safari fallback: go via a regular Image
- const imgUrl = URL.createObjectURL(blob);
- const img = new Image();
- img.src = imgUrl;
- await new Promise((r, rej) => { img.onload = r; img.onerror = rej; });
- bitmap = img;
- URL.revokeObjectURL(imgUrl);
- }
- texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
- if (bitmap.close) bitmap.close();
-
- const uTime = gl.getUniformLocation(program, 'u_time');
- const uRes = gl.getUniformLocation(program, 'u_resolution');
- const uAccent = gl.getUniformLocation(program, 'u_accent');
- const uTex = gl.getUniformLocation(program, 'u_texture');
- const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-
- shaderState = { canvas, gl, program, texture, rafId: 0, startTime: performance.now(), reduced };
- function frame() {
- if (!shaderState) return;
- const elapsed = (performance.now() - shaderState.startTime) / 1000;
- const t = shaderState.reduced ? 0.0 : elapsed;
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.useProgram(program);
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.uniform1i(uTex, 0);
- gl.uniform1f(uTime, t);
- gl.uniform2f(uRes, canvas.width, canvas.height);
- gl.uniform3f(uAccent, SHADER_ACCENT[0], SHADER_ACCENT[1], SHADER_ACCENT[2]);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- shaderState.rafId = requestAnimationFrame(frame);
- }
- frame();
- }
-
- function handleAccept() {
- if (!currentSessionId || arrivedVariants === 0) return;
- const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);
- if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;
- const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };
- if (Object.keys(paramsCurrentValues).length > 0) {
- acceptPayload.paramValues = { ...paramsCurrentValues };
- }
- // The accepted variant is already the only visible child of the wrapper
- // (all other variants are display:none). HMR from the source rewrite will
- // replace the wrapper imminently. Don't eagerly replaceChild here — React
- // reconciliation races with our mutation and throws NotFoundError in Next
- // 16 / Turbopack. Schedule a fallback that runs the manual swap only if
- // HMR hasn't cleaned up by then (keeps static-server flows working).
- const acceptedSessionId = currentSessionId;
- const acceptedVariant = visibleVariant;
-
- state = 'SAVING';
- updateBarContent('saving');
-
- sendEvent(acceptPayload, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- confirmAcceptAfterReceipt();
- })
- .catch(() => {
- state = 'CYCLING';
- updateBarContent('cycling');
- showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);
- });
-
- function confirmAcceptAfterReceipt() {
- state = 'CONFIRMED';
- updateBarContent('confirmed');
- scheduleAcceptCleanup();
- }
-
- function scheduleAcceptCleanup() {
- setTimeout(function() {
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }, 1800);
-
- // Static-server / no-HMR fallback: if the wrapper is still around 2s after
- // the cleanup above, swap it out manually. By now React has either moved
- // on or the app isn't React at all. Preserve the `data-impeccable-variant="N"`
- // div (with display:contents) so @scope rules anchored to the variant
- // attribute keep matching until reload replaces it with the carbonize block.
- setTimeout(function() {
- const wrapper = document.querySelector('[data-impeccable-variants="' + acceptedSessionId + '"]');
- if (!wrapper) return;
- const accepted = wrapper.querySelector('[data-impeccable-variant="' + acceptedVariant + '"]');
- if (accepted && accepted.firstElementChild) {
- const parent = wrapper.parentElement;
- if (!parent) return;
- accepted.style.display = 'contents';
- parent.replaceChild(accepted, wrapper);
- }
- }, 2000);
- }
- }
-
- function handleDiscard() {
- if (!currentSessionId) return;
- sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- cleanup();
- })
- .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));
- }
-
- // ---------------------------------------------------------------------------
- // Session persistence via live-browser-session.js
- // ---------------------------------------------------------------------------
- // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
-
- function saveSession() {
- if (!currentSessionId) return;
- // NOTE: scrollY is stored under a separate key (writeScrollY). Storing
- // it here would overwrite the Go-time value every time state changes.
- sessionState.saveSession({
- id: currentSessionId,
- state,
- action: selectedAction,
- count: selectedCount,
- expected: expectedVariants,
- arrived: arrivedVariants,
- visible: visibleVariant,
- });
- }
-
- function loadSession() {
- return sessionState.loadSession();
- }
-
- function clearSession() {
- sessionState.clearSession();
- }
-
- /** Mark session as handled (accepted/discarded). The agent will clean up
- * the source, but until it does the wrapper is still in the HTML. This
- * prevents resumeSession from picking it up again after reload. */
- function markSessionHandled() {
- if (!currentSessionId) return;
- sessionState.markHandled(currentSessionId);
- }
-
- function isSessionHandled(id) {
- return sessionState.isHandled(id);
- }
-
- function clearHandled() {
- sessionState.clearHandled();
- }
-
- function cleanup() {
- // Hide the wrapper immediately so variants disappear. DON'T structurally
- // mutate the DOM yet — HMR from the agent's source rewrite is on its way,
- // and a manual replaceChild under React causes NotFoundError when the
- // reconciler later tries to remove a wrapper we already removed.
- // Schedule a 2s fallback that does the manual swap only if HMR hasn't
- // replaced the wrapper by then (keeps static-server / no-HMR flows alive).
- const cleanupSessionId = currentSessionId;
- if (cleanupSessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (wrapper) wrapper.style.display = 'none';
- }
- setTimeout(function() {
- if (!cleanupSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (!wrapper) return;
- const orig = wrapper.querySelector('[data-impeccable-variant="original"]');
- if (orig) {
- const content = orig.firstElementChild;
- if (content) {
- wrapper.parentElement.replaceChild(content, wrapper);
- return;
- }
- }
- wrapper.remove();
- }, 2000);
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }
-
- // ---------------------------------------------------------------------------
- // Toast
- // ---------------------------------------------------------------------------
-
- function showToast(message, duration) {
- if (toastEl) toastEl.remove();
- // Stack the toast above the global bar (which sits at bottom:14px) so
- // the two never overlap. Read the bar's actual rect — its height varies
- // with hover-expanded labels — and fall back to a sensible default
- // when the bar isn't mounted yet.
- const barRect = globalBarEl?.getBoundingClientRect();
- const barTopFromBottom = barRect && barRect.height > 0
- ? Math.max(16, window.innerHeight - barRect.top + 12)
- : 16;
- toastEl = el('div', {
- position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
- transform: 'translateX(-50%) translateY(8px)',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px',
- padding: '8px 16px', borderRadius: '8px',
- zIndex: Z.toast, opacity: '0',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
- pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
- });
- toastEl.id = PREFIX + '-toast';
- toastEl.textContent = message;
- document.body.appendChild(toastEl);
- requestAnimationFrame(() => {
- toastEl.style.opacity = '1';
- toastEl.style.transform = 'translateX(-50%) translateY(0)';
- });
- setTimeout(() => {
- if (toastEl) {
- toastEl.style.opacity = '0';
- toastEl.style.transform = 'translateX(-50%) translateY(8px)';
- setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
- }
- }, duration);
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- // Resume an active variant session after HMR/page reload.
- // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
- // variants before HMR fired. Pick up where we left off.
- function resumeSession() {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) { clearSession(); clearHandled(); return false; }
-
- const sessionId = wrapper.dataset.impeccableVariants;
-
- // Don't resume if this session was already accepted/discarded
- if (isSessionHandled(sessionId)) return false;
-
- currentSessionId = sessionId;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
-
- // Restore state from localStorage if available
- const saved = loadSession();
- if (saved && saved.id === sessionId) {
- visibleVariant = (saved.visible > 0 && saved.visible <= arrivedVariants) ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
- if (saved.action) selectedAction = saved.action;
- if (saved.count) selectedCount = saved.count;
- } else {
- visibleVariant = arrivedVariants > 0 ? 1 : 0;
- }
-
- // Find the visible variant's content element for highlight positioning.
- // Try the visible variant first, fall back to the original's content.
- const visEl = visibleVariant > 0 ? pickVariantContent(wrapper, visibleVariant) : null;
- const origEl = pickVariantContent(wrapper, 'original');
- selectedElement = visEl || origEl || wrapper.parentElement;
-
- // Set display state BEFORE starting observer (avoid triggering it)
- if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
-
- state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
- showBar(state === 'CYCLING' ? 'cycling' : 'generating');
- startScrollTracking();
- // Build the params panel for the restored visible variant. Previously
- // this was missed on page-reload resume: showVariantInDOM above fires
- // refreshParamsPanel, but state was still IDLE at that moment so it
- // hid. Now that state is CYCLING, re-fire.
- if (state === 'CYCLING') refreshParamsPanel();
- saveSession();
- queueCheckpoint('browser_resumed');
-
- // Start observing for more variants AFTER initial setup
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
-
- // Hold the target at its saved viewport top through any subsequent
- // HMR patches, variant inserts, or cycle swaps.
- startScrollLock(currentSessionId, readScrollY());
-
- // If we reloaded mid-generation (Bun's HTML HMR destroys the shader
- // canvas), re-capture the original's content and restart the shader so
- // the wait doesn't go dead.
- if (state === 'GENERATING' && origEl) {
- (async () => {
- try {
- const rect = origEl.getBoundingClientRect();
- if (rect.width === 0 || rect.height === 0) return;
- const blob = await captureElementToBlob(origEl, null, rect);
- if (blob && state === 'GENERATING') {
- showShaderOverlay(origEl, blob, rect);
- }
- } catch (err) {
- console.warn('[impeccable] shader resume failed:', err);
- }
- })();
- }
- return true;
- }
-
- // ---------------------------------------------------------------------------
- // Global bar (always visible at bottom)
- // ---------------------------------------------------------------------------
-
- let globalBarEl = null;
- let detectActive = false;
- let pickActive = true;
- let detectCount = 0;
- let detectScriptLoaded = false;
-
- // Theme-aware color palette for the global bar. We detect the page's
- // ambient background and invert — dark bar on light pages, light bar on
- // dark pages. This keeps the bar from fighting with the host design.
- function detectPageTheme() {
- try {
- // Dev override: set localStorage 'impeccable-dev-theme' to 'light' or
- // 'dark' to preview the opposite palette without actually changing the
- // page bg. Used for screenshots and theme QA.
- const override = localStorage.getItem('impeccable-dev-theme');
- if (override === 'light' || override === 'dark') return override;
-
- // Walk body → html, taking the first opaque background. The browser's
- // default body / html background is `rgba(0, 0, 0, 0)`, which a naive
- // regex would read as black and mislabel a perfectly white page as
- // dark. Honoring alpha avoids that — and falling through to <html>
- // catches the common pattern of a bg only on <html> (or only on body).
- function readOpaque(el) {
- if (!el) return null;
- const bg = getComputedStyle(el).backgroundColor;
- const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
- if (!m) return null;
- const alpha = m[4] == null ? 1 : parseFloat(m[4]);
- if (alpha < 0.5) return null; // transparent / nearly transparent → skip
- return [+m[1], +m[2], +m[3]];
- }
-
- const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
- // Both transparent → fall back to the browser's effective canvas color.
- // White is the universal default; only one in a thousand sites swaps it
- // via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
- // us catch that case.
- if (!rgb) {
- return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
- }
- const [r, g, b] = rgb;
- // Perceptual luminance (Rec. 709)
- const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
- return L > 0.55 ? 'light' : 'dark';
- } catch { return 'light'; }
- }
-
- function barPaletteForTheme(theme) {
- if (theme === 'dark') {
- // Light bar on dark page
- return {
- surface: 'oklch(98% 0 0 / 0.92)',
- surfaceDeep: 'oklch(92% 0.005 60 / 0.96)', // slightly deeper, faint warm
- hairline: 'oklch(70% 0 0 / 0.35)',
- text: 'oklch(15% 0 0)',
- textDim: 'oklch(45% 0 0)',
- accent: 'oklch(60% 0.25 350)',
- accentSoft: 'oklch(60% 0.25 350 / 0.18)',
- mark: 'oklch(98% 0 0)', // logo mark fill
- markText: 'oklch(15% 0 0)', // logo "/" color
- exitHover: 'oklch(85% 0 0 / 0.5)',
- };
- }
- // Dark bar on light page. Bar is a warm charcoal, logo slab is much
- // deeper so the rounded-right shape reads as a clear sculpted mark.
- return {
- surface: 'oklch(26% 0 0 / 0.94)',
- surfaceDeep: 'oklch(18% 0 0 / 0.96)', // darker sand for Tune popover
- hairline: 'oklch(42% 0 0 / 0.5)',
- text: 'oklch(96% 0 0)',
- textDim: 'oklch(72% 0 0)',
- accent: 'oklch(72% 0.22 350)',
- accentSoft: 'oklch(72% 0.22 350 / 0.22)',
- mark: 'oklch(8% 0 0)',
- markText: 'oklch(96% 0 0)',
- exitHover: 'oklch(36% 0 0 / 0.6)',
- };
- }
-
- // Impeccable logo mark — matches the site-header SVG (rounded square + "/").
- function brandMarkSvg(fill, ink, size = 18) {
- return `<svg width="${size}" height="${size}" viewBox="0 0 32 32" aria-hidden="true">
- <rect width="32" height="32" rx="7" fill="${fill}"/>
- <text x="16" y="24" font-family="system-ui, -apple-system, sans-serif" font-size="22" font-weight="500" fill="${ink}" text-anchor="middle">/</text>
- </svg>`;
- }
-
- function initGlobalBar() {
- const theme = detectPageTheme();
- const P = barPaletteForTheme(theme);
-
- // Custom focus-visible for bar buttons. Browser default is a heavy
- // blue ring that looks jarring on the dark capsule. Replace with a
- // soft accent-tinted inner ring that respects the bar's palette.
- if (!document.getElementById(PREFIX + '-bar-focus-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-bar-focus-style';
- s.textContent =
- '#' + PREFIX + '-global-bar button:focus { outline: none; }' +
- '#' + PREFIX + '-global-bar button:focus-visible {' +
- ' outline: none;' +
- ' box-shadow: 0 0 0 2px ' + P.accentSoft + ', 0 0 0 3px ' + P.accent + ';' +
- '}';
- document.head.appendChild(s);
- }
-
- globalBarEl = el('div', {
- position: 'fixed', bottom: '14px', left: '50%',
- transform: 'translateX(-50%) translateY(20px)',
- zIndex: Z.bar + 5,
- display: 'flex', alignItems: 'stretch',
- gap: '2px',
- background: P.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 4px 20px oklch(0% 0 0 / 0.12), 0 1px 3px oklch(0% 0 0 / 0.08)',
- fontFamily: FONT, fontSize: '12px', lineHeight: '1',
- opacity: '0',
- overflow: 'hidden', // clip the full-bleed brand mark to the bar radius
- transition: 'opacity 0.3s ' + EASE + ', transform 0.3s ' + EASE,
- });
- globalBarEl.id = PREFIX + '-global-bar';
- globalBarEl.dataset.theme = theme;
-
- // Brand mark — fills bar height on the left. Left side inherits the bar's
- // rounded corner via overflow:hidden; right side is a clean hard edge since
- // the near-black/charcoal contrast does the shape-defining work.
- const brand = el('span', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- alignSelf: 'stretch',
- padding: '0 12px 0 14px',
- background: P.mark,
- color: P.markText,
- fontFamily: 'system-ui, -apple-system, sans-serif',
- fontWeight: '500',
- fontSize: '18px', lineHeight: '1',
- });
- brand.textContent = '/';
- brand.title = 'Impeccable';
- globalBarEl.appendChild(brand);
-
- // Inner wrapper: holds the toggles with normal bar padding.
- const inner = el('div', {
- display: 'flex', alignItems: 'center',
- padding: '4px 5px', gap: '2px',
- });
- inner.id = PREFIX + '-global-bar-inner';
- globalBarEl.appendChild(inner);
-
- // --- button factory: icon-only at rest, label slides in on hover/active ---
- function makeIconBtn({ id, svg, label, ariaLabel, labelFont, onClick }) {
- const b = el('button', {
- position: 'relative',
- display: 'inline-flex', alignItems: 'center',
- padding: '6px 8px', borderRadius: '7px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '11.5px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.15s ease, color 0.15s ease',
- whiteSpace: 'nowrap', overflow: 'hidden',
- });
- b.id = id;
- b.title = ariaLabel || label || '';
- b.setAttribute('aria-label', ariaLabel || label || '');
- b.innerHTML = svg + (label
- ? `<span class="icon-btn-label" style="display:inline-block;max-width:0;opacity:0;margin-left:0;overflow:hidden;font-family:${labelFont || FONT};transition:max-width 0.25s ${EASE}, opacity 0.2s ease, margin-left 0.25s ${EASE};">${label}</span>`
- : '');
- const labelEl = b.querySelector('.icon-btn-label');
- const expand = () => {
- if (!labelEl) return;
- labelEl.style.maxWidth = '120px'; labelEl.style.opacity = '1'; labelEl.style.marginLeft = '6px';
- };
- const collapse = () => {
- if (!labelEl || b.dataset.active === 'true') return;
- labelEl.style.maxWidth = '0'; labelEl.style.opacity = '0'; labelEl.style.marginLeft = '0';
- };
- // Per-button hover only changes color (no layout). The label expand/
- // collapse is driven by the bar-level mouseenter/mouseleave so moving
- // the mouse between adjacent buttons doesn't trigger per-button width
- // thrashing — the whole bar grows once and shrinks once.
- b.addEventListener('mouseenter', () => { if (b.dataset.active !== 'true') b.style.color = P.text; });
- b.addEventListener('mouseleave', () => { if (b.dataset.active !== 'true') b.style.color = P.textDim; });
- b.addEventListener('click', onClick);
- b._expandLabel = expand;
- b._collapseLabel = collapse;
- return b;
- }
-
- // Pick toggle — starts active (primary intent when entering live mode).
- const pickBtn = makeIconBtn({
- id: PREFIX + '-pick-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',
- label: 'Pick',
- ariaLabel: 'Pick element',
- onClick: () => togglePick(),
- });
- pickBtn.style.background = P.accentSoft;
- pickBtn.style.color = P.accent;
- pickBtn.dataset.active = 'true';
- pickBtn._expandLabel();
- inner.appendChild(pickBtn);
-
- // Detect toggle
- const detectBtn = makeIconBtn({
- id: PREFIX + '-detect-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',
- label: 'Detect',
- ariaLabel: 'Detect anti-patterns',
- onClick: () => toggleDetect(),
- });
- const detectBadge = el('span', {
- fontSize: '10px', fontWeight: '600',
- padding: '0px 5px', borderRadius: '7px', lineHeight: '16px',
- background: P.accent, color: P.surface.includes('18%') ? 'oklch(18% 0 0)' : 'oklch(98% 0 0)',
- display: 'none', fontFamily: MONO, marginLeft: '4px',
- });
- detectBadge.id = PREFIX + '-detect-badge';
- detectBtn.appendChild(detectBadge);
- inner.appendChild(detectBtn);
-
- // DESIGN.md panel toggle — quartet of color squares as the mark.
- const designBtn = makeIconBtn({
- id: PREFIX + '-design-toggle',
- svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px ${P.hairline};flex-shrink:0">
- <span style="background:oklch(60% 0.25 350)"></span>
- <span style="background:oklch(60% 0.15 45)"></span>
- <span style="background:oklch(55% 0.12 250)"></span>
- <span style="background:oklch(30% 0 0)"></span>
- </span>`,
- label: 'DESIGN.md',
- ariaLabel: 'Toggle DESIGN.md panel',
- labelFont: MONO,
- onClick: () => toggleDesignPanel(),
- });
- inner.appendChild(designBtn);
-
- // Thin divider before the exit button
- const divider = el('span', {
- width: '1px', height: '18px',
- background: P.hairline,
- margin: '0 4px 0 2px',
- });
- inner.appendChild(divider);
-
- // Exit × on the right — intentionally subtle (textDim at rest, text on
- // hover) so it sits behind the active toggles in visual hierarchy.
- //
- // Explicit padding + box-sizing here is load-bearing: a host page like
- // `button { padding: 0.5rem 1rem; }` (very common in resets) would
- // otherwise inflate this 24x24 button into 56x40 and push the SVG out
- // of the visible bar — the X stays invisible even though the styles in
- // DevTools look fine. Every other chrome button sets padding inline;
- // this one needed it too.
- const exitBtn = el('button', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- padding: '0', boxSizing: 'border-box',
- width: '24px', height: '24px', borderRadius: '6px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
- cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
- });
- exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
- exitBtn.title = 'Exit live mode';
- exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
- exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
- exitBtn.addEventListener('click', () => { sendEvent({ type: 'exit' }); teardown(); });
- inner.appendChild(exitBtn);
-
- // Bar-level hover: expand every toggle's label at once; collapse on leave.
- // Buttons with dataset.active="true" ignore collapse (their label stays).
- const toggles = [pickBtn, detectBtn, designBtn];
- globalBarEl.addEventListener('mouseenter', () => {
- toggles.forEach((t) => t._expandLabel && t._expandLabel());
- });
- globalBarEl.addEventListener('mouseleave', () => {
- toggles.forEach((t) => t._collapseLabel && t._collapseLabel());
- });
-
- document.body.appendChild(globalBarEl);
- defangOutsideHandlers(globalBarEl);
-
- requestAnimationFrame(() => {
- globalBarEl.style.opacity = '1';
- globalBarEl.style.transform = 'translateX(-50%) translateY(0)';
- });
-
- // Listen for detection results AND ready signal
- window.addEventListener('message', onDetectMessage);
- }
-
- function updateGlobalBarState() {
- const detectToggle = document.getElementById(PREFIX + '-detect-toggle');
- const detectBadge = document.getElementById(PREFIX + '-detect-badge');
- const pickToggle = document.getElementById(PREFIX + '-pick-toggle');
- const designToggle = document.getElementById(PREFIX + '-design-toggle');
- const theme = globalBarEl?.dataset.theme || 'light';
- const P = barPaletteForTheme(theme);
-
- // Sync one toggle's active state, colors, and slide-label visibility.
- function sync(btn, active) {
- if (!btn) return;
- btn.style.background = active ? P.accentSoft : 'transparent';
- btn.style.color = active ? P.accent : P.textDim;
- btn.dataset.active = active ? 'true' : 'false';
- if (active && btn._expandLabel) btn._expandLabel();
- else if (!active && btn._collapseLabel) btn._collapseLabel();
- }
- sync(pickToggle, pickActive);
- sync(detectToggle, detectActive);
- sync(designToggle, designState.open);
-
- // If the bar is currently under the cursor, keep all labels expanded —
- // otherwise clicking a toggle that deactivates (e.g. closing DESIGN.md)
- // would collapse its label while the user's mouse is still on the bar.
- if (globalBarEl && globalBarEl.matches(':hover')) {
- [pickToggle, detectToggle, designToggle].forEach((t) => t?._expandLabel?.());
- }
-
- if (detectBadge) {
- detectBadge.style.display = (detectActive && detectCount > 0) ? 'inline' : 'none';
- detectBadge.textContent = detectCount;
- }
-
- // When pick is active, make detect overlays click-through so the picker works
- document.querySelectorAll('.impeccable-overlay').forEach(o => {
- o.style.pointerEvents = pickActive ? 'none' : '';
- });
- }
-
- let detectReady = false; // true once detect script posts 'impeccable-ready'
- let detectPendingScan = false; // scan requested before script was ready
-
- function toggleDetect() {
- detectActive = !detectActive;
- updateGlobalBarState();
-
- if (detectActive) {
- if (!detectScriptLoaded) {
- detectPendingScan = true;
- loadDetectScript();
- } else if (detectReady) {
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- } else {
- detectPendingScan = true;
- }
- } else {
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- detectCount = 0;
- updateGlobalBarState();
- }
- }
-
- function togglePick() {
- pickActive = !pickActive;
- updateGlobalBarState();
-
- if (!pickActive) {
- // Disabling pick clears any in-flight selection and UI: highlight,
- // contextual bar, selectedElement. Otherwise a stale selection sits
- // on screen with no obvious way to dismiss.
- hideHighlight();
- hideBar();
- hideActionPicker();
- selectedElement = null;
- if (state === 'PICKING' || state === 'CONFIGURING') state = 'IDLE';
- } else {
- if (state === 'IDLE') state = 'PICKING';
- }
- }
-
- function loadDetectScript() {
- if (detectScriptLoaded) return;
- detectScriptLoaded = true;
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/detect.js';
- s.dataset.impeccableExtension = 'true';
- document.head.appendChild(s);
- }
-
- function onDetectMessage(e) {
- if (!e.data || typeof e.data.source !== 'string') return;
- // Detection script is loaded and ready
- if (e.data.source === 'impeccable-ready') {
- detectReady = true;
- if (detectPendingScan && detectActive) {
- detectPendingScan = false;
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- }
- }
- // Scan results arrived
- if (e.data.source === 'impeccable-results') {
- detectCount = e.data.count || 0;
- updateGlobalBarState();
- }
- }
-
- /** Full teardown: remove all UI, disconnect SSE, clean up. */
- function teardown() {
- cleanup();
- hideBar();
- if (globalBarEl) {
- globalBarEl.style.transform = 'translateY(100%)';
- setTimeout(() => { if (globalBarEl) globalBarEl.remove(); globalBarEl = null; }, 300);
- }
- if (highlightEl) { highlightEl.remove(); highlightEl = null; }
- if (tooltipEl) { tooltipEl.remove(); tooltipEl = null; }
- if (barEl) { barEl.remove(); barEl = null; }
- if (pickerEl) { pickerEl.remove(); pickerEl = null; }
- if (paramsPanelEl) { paramsPanelEl.remove(); paramsPanelEl = null; paramsPanelInner = null; paramsPanelBody = null; }
- if (evtSource) { evtSource.close(); evtSource = null; }
- document.removeEventListener('mousemove', handleMouseMove, true);
- document.removeEventListener('click', handleClick, true);
- document.removeEventListener('keydown', handleKeyDown, true);
- window.removeEventListener('message', onDetectMessage);
- // Remove detection overlays
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- state = 'IDLE';
- window.__IMPECCABLE_LIVE_INIT__ = false;
- console.log('[impeccable] Live mode exited.');
- }
-
- // ---------------------------------------------------------------------------
- // Design System Panel — visualizes the project's .impeccable/design.json sidecar
- // ---------------------------------------------------------------------------
-
- const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';
- const DESIGN_PANEL_WIDTH = 440;
-
- let designHost = null;
- let designShadow = null;
- let designState = {
- open: false,
- tab: 'visual', // 'visual' | 'raw'
- parsed: null, // parseDesignMd output (frontmatter + body sections)
- sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)
- hasMd: false,
- hasSidecar: false,
- present: null, // true/false once fetch resolves
- raw: null, // raw DESIGN.md for the raw tab
- mdNewerThanJson: false, // stale-hint flag
- loading: false,
- error: null,
- collapsed: { // narrative-section accordion state
- rules: true, dosdonts: true, overview: true,
- },
- };
-
- function loadDesignPrefs() {
- // `open` is intentionally NOT persisted — the panel always starts closed
- // so live mode doesn't auto-slide a big panel over the page on startup.
- try {
- const raw = localStorage.getItem(DESIGN_PREFS_KEY);
- if (!raw) return;
- const prefs = JSON.parse(raw);
- if (prefs.tab === 'visual' || prefs.tab === 'raw') designState.tab = prefs.tab;
- if (prefs.collapsed && typeof prefs.collapsed === 'object') {
- Object.assign(designState.collapsed, prefs.collapsed);
- }
- } catch { /* ignore */ }
- }
-
- function saveDesignPrefs() {
- try {
- localStorage.setItem(DESIGN_PREFS_KEY, JSON.stringify({
- tab: designState.tab,
- collapsed: designState.collapsed,
- }));
- } catch { /* ignore */ }
- }
-
- function initDesignPanel() {
- designHost = document.createElement('div');
- designHost.id = PREFIX + '-design-host';
- Object.assign(designHost.style, {
- position: 'fixed', top: '0', left: '0',
- width: '0', height: '0',
- zIndex: String(Z.bar + 10),
- pointerEvents: 'none',
- });
- designShadow = designHost.attachShadow({ mode: 'open' });
-
- const style = document.createElement('style');
- // Theme-match the bar: dark chrome on light pages, light chrome on dark pages.
- const theme = detectPageTheme();
- style.textContent = designPanelCss(barPaletteForTheme(theme));
- designShadow.appendChild(style);
-
- const root = document.createElement('div');
- root.className = 'root';
- designShadow.appendChild(root);
-
- document.body.appendChild(designHost);
- // The host is pointer-events: none; the panel inside the shadow DOM
- // manages its own auto/none. Events bubble through the shadow boundary,
- // so attaching here silences host-page outside-interaction handlers
- // without touching the host's click-through behavior.
- defangOutsideHandlers(designHost, { setPointerEvents: false });
-
- loadDesignPrefs();
- renderDesignChrome();
- if (designState.open) {
- fetchDesignSystem();
- }
- }
-
- // Neutral panel palette — deliberately NOT Impeccable-branded. The panel is
- // a viewer of the project's design system, not an Impeccable surface.
- const DP = {
- canvas: 'oklch(94% 0 0)', // panel background
- tile: 'oklch(98.5% 0 0)', // card-on-canvas
- tileAlt: 'oklch(96% 0 0)', // subtler tile for inner surfaces
- ink: 'oklch(15% 0 0)',
- ink2: 'oklch(35% 0 0)',
- meta: 'oklch(55% 0 0)',
- hairline: 'oklch(88% 0 0)',
- hairlineSoft: 'oklch(92% 0 0)',
- amber: 'oklch(70% 0.13 65)', // stale-hint accent
- amberBg: 'oklch(95% 0.05 80)',
- };
-
- function designPanelCss(BP) {
- // BP = bar palette (theme-aware, matches the global bar).
- // DP = internal content palette (neutral, so tiles render colors true).
- return `
- :host, .root { all: initial; }
- .root {
- font-family: ${FONT};
- color: ${DP.ink};
- pointer-events: none;
- }
- .root * { box-sizing: border-box; }
- button { font: inherit; color: inherit; }
-
- /* --- Panel shell: chrome matches the bar; body canvas stays neutral --- */
- .panel {
- position: fixed; top: 12px; bottom: 72px; right: 12px;
- width: ${DESIGN_PANEL_WIDTH}px; max-width: calc(100vw - 24px);
- background: ${BP.surface};
- border: 1px solid ${BP.hairline};
- border-radius: 14px;
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- box-shadow: 0 20px 60px oklch(0% 0 0 / 0.18), 0 4px 12px oklch(0% 0 0 / 0.08);
- display: flex; flex-direction: column;
- transform: translateX(calc(100% + 24px));
- opacity: 0;
- transition: transform 0.35s ${EASE}, opacity 0.25s ${EASE};
- pointer-events: none;
- overflow: hidden;
- }
- .panel[data-open="true"] { transform: translateX(0); opacity: 1; pointer-events: auto; }
-
- .panel-header {
- display: flex; align-items: center; gap: 10px;
- padding: 10px 10px 10px 14px;
- background: transparent;
- border-bottom: 1px solid ${BP.hairline};
- }
- .panel-title {
- flex: 1; min-width: 0;
- font-family: ${MONO};
- font-size: 11.5px; font-weight: 600;
- letter-spacing: 0.02em;
- color: ${BP.text};
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
- }
- .panel-close {
- border: none; background: transparent; color: ${BP.textDim};
- width: 26px; height: 26px; border-radius: 7px;
- display: inline-flex; align-items: center; justify-content: center;
- cursor: pointer; transition: background 0.15s ease, color 0.15s ease;
- }
- .panel-close:hover { background: ${BP.hairline}; color: ${BP.text}; }
-
- .tabs {
- display: inline-flex; padding: 2px;
- background: ${BP.hairline};
- border-radius: 7px;
- gap: 2px;
- }
- .tab {
- border: none; background: transparent;
- padding: 4px 10px; border-radius: 5px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 600; letter-spacing: 0.08em;
- text-transform: uppercase;
- color: ${BP.textDim}; cursor: pointer;
- transition: background 0.15s ease, color 0.15s ease;
- }
- .tab[data-active="true"] { background: ${BP.surface}; color: ${BP.text}; }
-
- .panel-body {
- flex: 1; overflow-y: auto;
- padding: 12px 12px 20px;
- background: ${DP.canvas};
- scrollbar-width: thin;
- scrollbar-color: ${DP.hairline} transparent;
- }
- .panel-body::-webkit-scrollbar { width: 8px; }
- .panel-body::-webkit-scrollbar-thumb { background: ${DP.hairline}; border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
-
- /* --- States --- */
- .empty, .loading, .error {
- margin: 16px 4px;
- padding: 28px 20px; text-align: center;
- background: ${DP.tile}; border-radius: 14px;
- color: ${DP.ink2}; font-size: 13px; line-height: 1.55;
- }
- .empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
- .empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
- .error { color: oklch(45% 0.15 25); }
-
- /* --- Stale hint --- */
- .stale {
- display: flex; align-items: center; gap: 8px;
- margin: 8px 4px 12px;
- padding: 8px 12px;
- background: ${DP.amberBg};
- border-radius: 10px;
- font-size: 11.5px; color: ${DP.ink2};
- }
- .stale-dot { width: 8px; height: 8px; border-radius: 50%; background: ${DP.amber}; flex-shrink: 0; }
- .stale-text { flex: 1; min-width: 0; }
- .stale-text strong { color: ${DP.ink}; font-weight: 600; }
-
- /* --- Parsed-md fallback banner --- */
- .parsed-md-cta {
- margin: 8px 4px 14px;
- padding: 14px 16px;
- background: ${DP.tile};
- border: 1px dashed ${DP.hairline};
- border-radius: 12px;
- font-size: 12px; color: ${DP.ink2}; line-height: 1.55;
- }
- .parsed-md-cta strong { color: ${DP.ink}; display: block; margin-bottom: 4px; font-size: 13px; font-weight: 600; }
- .parsed-md-cta code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; font-size: 11.5px; color: ${DP.ink}; }
-
- /* --- Tile primitives --- */
- .tile {
- position: relative;
- background: ${DP.tile};
- border-radius: 16px;
- padding: 16px;
- margin: 0 4px 10px;
- }
- .tile-row { margin: 0 4px 10px; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
- .tile-row .tile { margin: 0; }
- .tile-meta {
- display: flex; align-items: baseline; justify-content: space-between;
- gap: 10px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase;
- color: ${DP.meta};
- }
- .tile-meta .name { color: ${DP.ink}; font-weight: 600; letter-spacing: 0.05em; text-transform: none; font-family: ${FONT}; font-size: 12.5px; }
-
- /* --- Color tile --- */
- .c-tile { cursor: pointer; transition: transform 0.2s ${EASE}; }
- .c-tile:hover { transform: translateY(-1px); }
- .c-hero {
- height: 72px; border-radius: 10px; margin-top: 10px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.05);
- }
- .c-ramp {
- display: flex; gap: 0; height: 14px; border-radius: 4px; overflow: hidden;
- margin-top: 8px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.04);
- }
- .c-ramp > span { flex: 1; }
- .c-desc { margin-top: 8px; font-size: 11.5px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Type tile --- */
- .t-tile { }
- .t-specimen {
- margin: 4px 0 6px;
- color: ${DP.ink};
- line-height: 0.9;
- }
- .t-family { margin-top: 4px; font-size: 12px; font-weight: 600; color: ${DP.ink}; }
- .t-purpose { margin-top: 4px; font-size: 11px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Shadow tile --- */
- .s-tile { }
- .s-surface {
- height: 60px; margin: 8px 2px 10px;
- background: ${DP.tile};
- border-radius: 10px;
- }
- .s-value { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; word-break: break-all; line-height: 1.4; }
- .s-purpose { margin-top: 4px; font-size: 11px; color: ${DP.ink2}; line-height: 1.45; }
-
- /* --- Radii strip --- */
- .r-strip { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
- .r-item { display: flex; flex-direction: column; align-items: center; gap: 4px; flex: 1; min-width: 60px; }
- .r-sample { width: 44px; height: 44px; background: ${DP.canvas}; box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.08); }
- .r-label { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; text-transform: uppercase; }
- .r-val { font-family: ${MONO}; font-size: 10px; color: ${DP.ink}; }
-
- /* --- Component tile (hosts live primitives) --- */
- .cmp-tile { }
- .cmp-stage {
- margin: 12px -4px 0;
- padding: 18px 16px 10px;
- border-top: 1px solid ${DP.hairlineSoft};
- display: flex; flex-direction: column; align-items: center; justify-content: center;
- gap: 14px;
- min-height: 68px;
- }
- .cmp-stage + .cmp-stage { border-top: 1px dashed ${DP.hairlineSoft}; }
- .cmp-sublabel { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.06em; }
- .cmp-kind { font-family: ${MONO}; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; }
-
- /* --- Collapsible --- */
- .coll {
- margin: 0 4px 8px;
- background: ${DP.tile};
- border-radius: 12px;
- overflow: hidden;
- }
- .coll-head {
- display: flex; align-items: center; gap: 10px;
- width: 100%;
- padding: 12px 14px;
- background: transparent; border: none;
- cursor: pointer; text-align: left;
- font-family: ${FONT}; font-size: 12.5px; font-weight: 600; color: ${DP.ink};
- transition: background 0.12s ease;
- }
- .coll-head:hover { background: ${DP.tileAlt}; }
- .coll-chev {
- width: 12px; height: 12px; flex-shrink: 0;
- color: ${DP.meta};
- transition: transform 0.2s ${EASE};
- }
- .coll[data-open="true"] .coll-chev { transform: rotate(90deg); }
- .coll-count { margin-left: auto; font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; }
- .coll-body { padding: 0 14px 14px; display: none; }
- .coll[data-open="true"] .coll-body { display: block; }
-
- .rule-card {
- padding: 10px 0;
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .rule-card:first-child { border-top: none; padding-top: 2px; }
- .rule-card .name { font-size: 11.5px; font-weight: 700; color: ${DP.ink}; margin-bottom: 3px; }
- .rule-card .name .section { font-family: ${MONO}; font-size: 9px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; margin-left: 8px; }
- .rule-card .body { font-size: 11.5px; color: ${DP.ink2}; line-height: 1.5; }
-
- .coll .dos { display: grid; gap: 0; margin-top: 2px; }
- .coll .do, .coll .dont {
- position: relative;
- padding: 8px 0 8px 22px;
- font-size: 11.5px; line-height: 1.5; color: ${DP.ink2};
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .coll .do:first-child, .coll .dont:first-child,
- .coll .do:first-of-type { border-top: none; }
- .coll .do + .dont { border-top: 1px solid ${DP.hairlineSoft}; }
- .coll .do::before, .coll .dont::before {
- content: ''; position: absolute; left: 4px; top: 13px;
- width: 8px; height: 8px; border-radius: 50%;
- }
- .coll .do::before { background: oklch(62% 0.16 145); }
- .coll .dont::before { background: oklch(58% 0.22 25); }
-
- .coll .overview-body {
- font-size: 12px; line-height: 1.55; color: ${DP.ink2};
- }
- .coll .overview-body .north-star {
- display: block; font-family: ${FONT}; font-style: italic;
- font-size: 15px; line-height: 1.3; color: ${DP.ink};
- margin-bottom: 8px;
- }
- .coll .overview-body p { margin: 0 0 8px; }
- .coll .overview-body ul { margin: 6px 0 0; padding-left: 16px; font-size: 11.5px; }
- .coll .overview-body li { margin-bottom: 3px; }
-
- /* --- raw tab markdown (unchanged layout, neutralized palette) --- */
- .md { padding: 4px 10px 20px; font-size: 13px; line-height: 1.6; color: ${DP.ink}; }
- .md h1, .md h2, .md h3, .md h4 { margin: 20px 0 8px; color: ${DP.ink}; font-weight: 600; }
- .md h1 { font-size: 18px; }
- .md h2 { font-size: 15px; padding-bottom: 4px; border-bottom: 1px solid ${DP.hairlineSoft}; }
- .md h3 { font-size: 13px; }
- .md h4 { font-size: 12px; color: ${DP.meta}; }
- .md p { margin: 0 0 10px; }
- .md ul, .md ol { margin: 0 0 10px; padding-left: 20px; }
- .md li { margin-bottom: 4px; }
- .md code { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; }
- .md pre { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 10px 12px; border-radius: 8px; overflow-x: auto; margin: 0 0 10px; }
- .md pre code { background: none; padding: 0; }
- .md strong { font-weight: 700; }
- .md em { font-style: italic; }
- .md a { color: ${DP.ink}; text-decoration: underline; }
- .md hr { border: none; border-top: 1px solid ${DP.hairlineSoft}; margin: 16px 0; }
- `;
- }
-
- function renderDesignChrome() {
- const root = designShadow.querySelector('.root');
- root.innerHTML = '';
-
- // (Panel toggle lives in the global bar — no floating FAB.)
- // Panel
- const panel = document.createElement('aside');
- panel.className = 'panel';
- panel.setAttribute('data-open', designState.open ? 'true' : 'false');
- panel.appendChild(buildDesignHeader());
- const body = document.createElement('div');
- body.className = 'panel-body';
- body.id = 'panel-body';
- panel.appendChild(body);
- root.appendChild(panel);
-
- renderDesignBody();
- }
-
- function buildDesignHeader() {
- const header = document.createElement('div');
- header.className = 'panel-header';
-
- const title = document.createElement('div');
- title.className = 'panel-title';
- title.textContent = 'DESIGN.md';
- header.appendChild(title);
-
- const tabs = document.createElement('div');
- tabs.className = 'tabs';
- for (const t of [['visual', 'Visual'], ['raw', 'Raw']]) {
- const btn = document.createElement('button');
- btn.className = 'tab';
- btn.textContent = t[1];
- btn.setAttribute('data-active', designState.tab === t[0] ? 'true' : 'false');
- btn.addEventListener('click', () => {
- if (designState.tab === t[0]) return;
- designState.tab = t[0];
- saveDesignPrefs();
- renderDesignChrome();
- if (t[0] === 'raw' && designState.raw === null && !designState.loading) {
- fetchDesignSystem(); // raw is part of the same fetch pair
- }
- });
- tabs.appendChild(btn);
- }
- header.appendChild(tabs);
-
- const close = document.createElement('button');
- close.className = 'panel-close';
- close.innerHTML = '✕';
- close.setAttribute('aria-label', 'Close panel');
- close.addEventListener('click', toggleDesignPanel);
- header.appendChild(close);
-
- return header;
- }
-
- function toggleDesignPanel() {
- designState.open = !designState.open;
- renderDesignChrome();
- updateGlobalBarState();
- if (designState.open && designState.present === null && !designState.loading) {
- fetchDesignSystem();
- }
- }
-
- async function fetchDesignSystem() {
- designState.loading = true;
- designState.error = null;
- renderDesignBody();
- try {
- const [jsonRes, rawRes] = await Promise.all([
- fetch(`http://localhost:${PORT}/design-system.json?token=${TOKEN}`, { cache: 'no-store' }),
- fetch(`http://localhost:${PORT}/design-system/raw?token=${TOKEN}`, { cache: 'no-store' }),
- ]);
- const jsonData = await jsonRes.json();
- designState.present = jsonData.present === true;
- designState.parsed = jsonData.parsed || null;
- designState.sidecar = jsonData.sidecar || null;
- designState.hasMd = !!jsonData.hasMd;
- designState.hasSidecar = !!jsonData.hasSidecar;
- designState.mdNewerThanJson = !!jsonData.mdNewerThanJson;
- designState.raw = designState.present && rawRes.ok ? await rawRes.text() : null;
- designState.error = jsonData.parseError || jsonData.sidecarError || null;
- } catch (err) {
- designState.error = err?.message || 'Failed to load design system.';
- } finally {
- designState.loading = false;
- renderDesignChrome(); // refresh title from data
- }
- }
-
- function renderDesignBody() {
- const body = designShadow.querySelector('#panel-body');
- if (!body) return;
- body.innerHTML = '';
-
- if (designState.loading) {
- body.appendChild(msgDiv('loading', 'Loading design system…'));
- return;
- }
- if (designState.error) {
- body.appendChild(msgDiv('error', designState.error));
- return;
- }
- if (designState.present === false) {
- const empty = document.createElement('div');
- empty.className = 'empty';
- empty.innerHTML = `<strong>No DESIGN.md yet</strong>Create one by running <code>/impeccable document</code> in your terminal, then re-open this panel.`;
- body.appendChild(empty);
- return;
- }
-
- if (designState.tab === 'raw') {
- renderRawTab(body, designState.raw || '');
- return;
- }
-
- // Visual tab — single unified render path.
- if (designState.mdNewerThanJson) body.appendChild(renderStaleHint());
- if (designState.hasMd && !designState.hasSidecar) {
- body.appendChild(renderParsedMdCta());
- }
- renderDesignVisual(body, designState.parsed, designState.sidecar);
- }
-
- function msgDiv(cls, text) {
- const d = document.createElement('div');
- d.className = cls;
- d.textContent = text;
- return d;
- }
-
- function renderStaleHint() {
- const box = document.createElement('div');
- box.className = 'stale';
- box.innerHTML = `
- <span class="stale-dot"></span>
- <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>
- `;
- return box;
- }
-
- function renderParsedMdCta() {
- const box = document.createElement('div');
- box.className = 'parsed-md-cta';
- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;
- return box;
- }
-
- // --- Unified render: merge parsed DESIGN.md frontmatter with sidecar v2 ---
-
- function renderDesignVisual(body, parsed, sidecar) {
- const frontmatter = parsed?.frontmatter || {};
- const extensions = sidecar?.extensions || {};
- const proseColors = parsed?.colors || null;
-
- const colors = buildColorModels(frontmatter.colors, extensions.colorMeta, proseColors);
- if (colors.length) renderColorTiles(body, colors);
-
- const types = buildTypographyModels(frontmatter.typography, extensions.typographyMeta);
- if (types.length) renderTypeTiles(body, types);
-
- const radii = buildRadiiModels(frontmatter.rounded);
- if (radii.length) renderRadiiTile(body, radii);
-
- if (extensions.shadows?.length) renderShadowTiles(body, extensions.shadows);
-
- const components = sidecar?.components || [];
- if (components.length) renderComponentTiles(body, components);
-
- // Narrative: sidecar wins if present (richer, agent-curated). Otherwise
- // synthesize from prose sections.
- const narrative = sidecar?.narrative || synthesizeNarrative(parsed);
- if (narrative.rules?.length) body.appendChild(renderRulesCollapsible(narrative.rules));
- if ((narrative.dos?.length || narrative.donts?.length)) body.appendChild(renderDosDontsCollapsible(narrative));
- if (narrative.overview || narrative.northStar || narrative.keyCharacteristics?.length) {
- body.appendChild(renderOverviewCollapsible(narrative));
- }
-
- if (body.childElementCount === 0) {
- body.appendChild(msgDiv('empty', 'No design system data available.'));
- }
- }
-
- // Frontmatter primitives + sidecar colorMeta → tile-ready color models.
- // A matching prose bullet (when the slug sits in the bullet text) supplies
- // description as a last-resort fallback.
- function buildColorModels(fmColors, colorMeta, proseColors) {
- if (!fmColors) return [];
- const meta = colorMeta || {};
- return Object.entries(fmColors).map(([key, value]) => {
- const m = meta[key] || {};
- return {
- role: m.role || humanizeKey(key),
- name: m.displayName || humanizeKey(key),
- value: value,
- canonical: m.canonical || null,
- description: m.description || findProseDescription(proseColors, key, m.displayName),
- tonalRamp: m.tonalRamp || null,
- };
- });
- }
-
- function buildTypographyModels(fmTypography, typographyMeta) {
- if (!fmTypography) return [];
- const meta = typographyMeta || {};
- return Object.entries(fmTypography).map(([key, spec]) => {
- const m = meta[key] || {};
- const { family, fallback } = splitFontFamily(spec?.fontFamily);
- return {
- role: key,
- name: m.displayName || humanizeKey(key),
- family,
- fallback,
- weight: spec?.fontWeight ?? 400,
- // fontStyle isn't in Stitch's frontmatter schema; the sidecar carries
- // it when a role is rendered in italic (e.g. display italic).
- style: m.style || 'normal',
- sampleSize: spec?.fontSize || '1rem',
- lineHeight: spec?.lineHeight != null ? String(spec.lineHeight) : '',
- letterSpacing: spec?.letterSpacing,
- purpose: m.purpose,
- };
- });
- }
-
- function buildRadiiModels(fmRounded) {
- if (!fmRounded) return [];
- return Object.entries(fmRounded).map(([name, value]) => ({ name, value }));
- }
-
- function splitFontFamily(stack) {
- if (!stack || typeof stack !== 'string') return { family: '', fallback: '' };
- const parts = stack.split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, ''));
- return { family: parts[0] || '', fallback: parts.slice(1).join(', ') };
- }
-
- function humanizeKey(k) {
- return String(k || '').replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
- }
-
- function findProseDescription(proseColors, key, displayName) {
- if (!proseColors || !proseColors.groups) return null;
- const needles = [key, displayName].filter(Boolean).map((s) => s.toLowerCase());
- for (const g of proseColors.groups) {
- for (const c of g.colors || []) {
- const hay = String(c.name || '').toLowerCase();
- if (hay && needles.some((n) => hay.includes(n) || n.includes(hay))) {
- return c.description || null;
- }
- }
- }
- return null;
- }
-
- function synthesizeNarrative(parsed) {
- if (!parsed) return {};
- const md = parsed;
- return {
- northStar: md.overview?.creativeNorthStar,
- overview: (md.overview?.philosophy || []).join(' '),
- keyCharacteristics: md.overview?.keyCharacteristics || [],
- rules: [
- ...(md.colors?.rules || []).map((r) => ({ ...r, section: 'colors' })),
- ...(md.typography?.rules || []).map((r) => ({ ...r, section: 'typography' })),
- ...(md.elevation?.rules || []).map((r) => ({ ...r, section: 'elevation' })),
- ],
- dos: md.dosDonts?.dos || [],
- donts: md.dosDonts?.donts || [],
- };
- }
-
- function renderColorTiles(body, colors) {
- for (const c of colors) {
- const tile = document.createElement('div');
- tile.className = 'tile c-tile';
- tile.title = 'Click to copy';
- tile.addEventListener('click', () => copyToClipboard(c.value));
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(c.name || c.role || 'Color')}</span><span>${escapeHtml(c.value || '')}</span>`;
- tile.appendChild(meta);
-
- const hero = document.createElement('div');
- hero.className = 'c-hero';
- hero.style.background = c.value;
- tile.appendChild(hero);
-
- const ramp = synthesizeRamp(c);
- if (ramp.length) {
- const r = document.createElement('div');
- r.className = 'c-ramp';
- r.innerHTML = ramp.map((v) => `<span style="background:${cssSafe(v)}"></span>`).join('');
- tile.appendChild(r);
- }
-
- if (c.description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = c.description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function synthesizeRamp(c) {
- if (c.tonalRamp?.length) return c.tonalRamp;
- // If base value is OKLCH, synthesize an 8-step ramp across lightness.
- const m = typeof c.value === 'string' && c.value.match(/^oklch\(\s*([\d.]+)%\s+([\d.]+)\s+([\d.]+)\s*(?:\/\s*([\d.]+))?\s*\)$/i);
- if (!m) return [];
- const [, , chroma, hue] = m;
- const steps = [20, 32, 44, 56, 68, 80, 90, 96];
- return steps.map((l) => `oklch(${l}% ${chroma} ${hue})`);
- }
-
- function renderTypeTiles(body, types) {
- for (const t of types) {
- const tile = document.createElement('div');
- tile.className = 'tile t-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span>${escapeHtml(t.role || '')}</span><span>${escapeHtml(t.weight || '')} ${escapeHtml(t.style === 'italic' ? 'italic' : '')}</span>`;
- tile.appendChild(meta);
-
- const specimen = document.createElement('div');
- specimen.className = 't-specimen';
- specimen.textContent = 'Aa';
- specimen.style.fontFamily = fontStack(t);
- specimen.style.fontWeight = String(t.weight || 400);
- specimen.style.fontStyle = t.style || 'normal';
- specimen.style.fontSize = '56px'; // Fixed specimen size — compare faces, not scales.
- specimen.style.letterSpacing = 'normal';
- specimen.style.textTransform = 'none';
- tile.appendChild(specimen);
-
- // The system's actual sample size for this role, shown as small mono meta below.
- if (t.sampleSize) {
- const scale = document.createElement('div');
- scale.style.cssText = 'font-family:' + MONO + '; font-size: 10px; color:' + DP.meta + '; margin-top: 2px;';
- scale.textContent = t.sampleSize;
- tile.appendChild(scale);
- }
-
- const family = document.createElement('div');
- family.className = 't-family';
- family.textContent = t.family || t.name || '';
- tile.appendChild(family);
-
- if (t.purpose) {
- const p = document.createElement('div');
- p.className = 't-purpose';
- p.textContent = t.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function fontStack(t) {
- const fam = t.family || '';
- const fb = t.fallback || '';
- if (fam && /[,\s]/.test(fam) && !fam.includes("'") && !fam.includes('"')) {
- return `"${fam}", ${fb}`;
- }
- return fam && fb ? `"${fam}", ${fb}` : (fam || fb);
- }
-
- function renderRadiiTile(body, radii) {
- const tile = document.createElement('div');
- tile.className = 'tile';
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">Corner Radii</span><span>${radii.length}</span>`;
- tile.appendChild(meta);
-
- const strip = document.createElement('div');
- strip.className = 'r-strip';
- for (const r of radii) {
- const item = document.createElement('div');
- item.className = 'r-item';
- const s = document.createElement('div');
- s.className = 'r-sample';
- s.style.borderRadius = r.value || '0';
- item.appendChild(s);
- const lbl = document.createElement('div');
- lbl.className = 'r-label';
- lbl.textContent = r.name || '';
- item.appendChild(lbl);
- const val = document.createElement('div');
- val.className = 'r-val';
- val.textContent = r.value || '';
- item.appendChild(val);
- strip.appendChild(item);
- }
- tile.appendChild(strip);
- body.appendChild(tile);
- }
-
- function renderShadowTiles(body, shadows) {
- for (const sh of shadows) {
- const tile = document.createElement('div');
- tile.className = 'tile s-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(sh.name || 'Shadow')}</span><span>Elevation</span>`;
- tile.appendChild(meta);
-
- const surface = document.createElement('div');
- surface.className = 's-surface';
- surface.style.boxShadow = sh.value || 'none';
- tile.appendChild(surface);
-
- const val = document.createElement('div');
- val.className = 's-value';
- val.textContent = sh.value || '';
- tile.appendChild(val);
-
- if (sh.purpose) {
- const p = document.createElement('div');
- p.className = 's-purpose';
- p.textContent = sh.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function renderComponentTiles(body, components) {
- // Group consecutive components that share a kind into one tile. This avoids
- // a pile of one-component tiles (e.g., three button variants = three tiles)
- // and reads more like a proper category.
- const groups = groupByKind(components);
-
- for (const group of groups) {
- const tile = document.createElement('div');
- tile.className = 'tile cmp-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- const groupTitle = group.length === 1
- ? (group[0].name || group[0].kind || 'Component')
- : titleForKind(group[0].kind, group.length);
- meta.innerHTML = `<span class="name">${escapeHtml(groupTitle)}</span><span class="cmp-kind">${escapeHtml(group[0].kind || '')}</span>`;
- tile.appendChild(meta);
-
- for (const c of group) {
- const stage = document.createElement('div');
- stage.className = 'cmp-stage';
-
- // Render the component in its own shadow root so its CSS can't bleed.
- const host = document.createElement('div');
- const sub = host.attachShadow({ mode: 'open' });
- const style = document.createElement('style');
- style.textContent = c.css || '';
- sub.appendChild(style);
- const container = document.createElement('div');
- container.innerHTML = c.html || '';
- sub.appendChild(container);
- stage.appendChild(host);
-
- // Show component name as a sublabel only when the tile groups >1 item,
- // or when the component's display name differs from its kind.
- const showSublabel = group.length > 1;
- if (showSublabel) {
- const lbl = document.createElement('div');
- lbl.className = 'cmp-sublabel';
- lbl.textContent = c.name || '';
- stage.appendChild(lbl);
- }
- tile.appendChild(stage);
- }
-
- // Single shared description if all items carry the same one; otherwise
- // skip — per-item descriptions clutter a grouped tile.
- if (group.length === 1 && group[0].description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = group[0].description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function groupByKind(components) {
- const groups = [];
- for (const c of components) {
- const last = groups[groups.length - 1];
- if (last && last[0].kind && c.kind === last[0].kind) {
- last.push(c);
- } else {
- groups.push([c]);
- }
- }
- return groups;
- }
-
- function titleForKind(kind, count) {
- const labels = {
- button: 'Buttons',
- input: 'Inputs',
- nav: 'Navigation',
- chip: 'Chips',
- card: 'Cards',
- custom: 'Components',
- };
- return labels[kind] || (kind ? kind.charAt(0).toUpperCase() + kind.slice(1) + 's' : 'Components');
- }
-
- // --- Collapsibles ---------------------------------------------------------
-
- function buildCollapsible(key, label, count) {
- const wrap = document.createElement('div');
- wrap.className = 'coll';
- wrap.setAttribute('data-open', designState.collapsed[key] ? 'false' : 'true');
-
- const head = document.createElement('button');
- head.className = 'coll-head';
- head.innerHTML = `
- <svg class="coll-chev" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 2.5L8 6 4 9.5"/></svg>
- <span>${escapeHtml(label)}</span>
- ${count != null ? `<span class="coll-count">${escapeHtml(String(count))}</span>` : ''}
- `;
- head.addEventListener('click', () => {
- designState.collapsed[key] = !designState.collapsed[key];
- saveDesignPrefs();
- renderDesignBody();
- });
- wrap.appendChild(head);
-
- const body = document.createElement('div');
- body.className = 'coll-body';
- wrap.appendChild(body);
- return { wrap, body };
- }
-
- function renderRulesCollapsible(rules) {
- const { wrap, body } = buildCollapsible('rules', 'Named Rules', rules.length);
- for (const r of rules) {
- const card = document.createElement('div');
- card.className = 'rule-card';
- const name = document.createElement('div');
- name.className = 'name';
- name.innerHTML = `${escapeHtml(r.name)}${r.section ? `<span class="section">${escapeHtml(r.section)}</span>` : ''}`;
- card.appendChild(name);
- const b = document.createElement('div');
- b.className = 'body';
- b.textContent = r.body || '';
- card.appendChild(b);
- body.appendChild(card);
- }
- return wrap;
- }
-
- function renderDosDontsCollapsible(n) {
- const total = (n.dos?.length || 0) + (n.donts?.length || 0);
- const { wrap, body } = buildCollapsible('dosdonts', "Do's and Don'ts", total);
- const grid = document.createElement('div');
- grid.className = 'dos';
- for (const d of n.dos || []) {
- const el = document.createElement('div');
- el.className = 'do';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- for (const d of n.donts || []) {
- const el = document.createElement('div');
- el.className = 'dont';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- body.appendChild(grid);
- return wrap;
- }
-
- function renderOverviewCollapsible(n) {
- const { wrap, body } = buildCollapsible('overview', 'Overview', null);
- const ov = document.createElement('div');
- ov.className = 'overview-body';
- if (n.northStar) {
- const star = document.createElement('span');
- star.className = 'north-star';
- star.textContent = '“' + n.northStar + '”';
- ov.appendChild(star);
- }
- if (n.overview) {
- const p = document.createElement('p');
- p.innerHTML = inlineMd(n.overview);
- ov.appendChild(p);
- }
- if (n.keyCharacteristics?.length) {
- const ul = document.createElement('ul');
- ul.innerHTML = n.keyCharacteristics.map((k) => `<li>${inlineMd(k)}</li>`).join('');
- ov.appendChild(ul);
- }
- body.appendChild(ov);
- return wrap;
- }
-
- function cssSafe(v) {
- // Strip anything outside valid CSS value chars to prevent injection via
- // .impeccable/design.json values rendered into inline style strings.
- return String(v).replace(/[<>"'`\n]/g, '');
- }
-
- // --- Raw tab: minimal markdown renderer (subset) --------------------------
-
- function renderRawTab(body, md) {
- const wrap = document.createElement('div');
- wrap.className = 'md';
- wrap.innerHTML = renderMarkdown(md);
- body.appendChild(wrap);
- }
-
- function renderMarkdown(md) {
- const lines = md.split(/\r?\n/);
- const out = [];
- let i = 0;
- let inCode = false;
- let codeBuf = [];
- let paraBuf = [];
- let listBuf = []; // array of { indent, html }
- let listType = null; // 'ul' | 'ol'
-
- const flushPara = () => {
- if (paraBuf.length) {
- out.push(`<p>${inlineMd(paraBuf.join(' '))}</p>`);
- paraBuf = [];
- }
- };
- const flushList = () => {
- if (listBuf.length) {
- out.push(buildListHtml(listBuf, listType));
- listBuf = [];
- listType = null;
- }
- };
- const flushAll = () => { flushPara(); flushList(); };
-
- for (; i < lines.length; i++) {
- const line = lines[i];
-
- // Code fence
- const fence = line.match(/^```(\w*)\s*$/);
- if (fence) {
- if (!inCode) { flushAll(); inCode = true; codeBuf = []; }
- else {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- inCode = false;
- }
- continue;
- }
- if (inCode) { codeBuf.push(line); continue; }
-
- if (line.trim() === '') { flushAll(); continue; }
-
- const hr = line.match(/^\s*(?:---+|\*\*\*+)\s*$/);
- if (hr) { flushAll(); out.push('<hr />'); continue; }
-
- const heading = line.match(/^(#{1,4})\s+(.+)$/);
- if (heading) {
- flushAll();
- const lvl = heading[1].length;
- out.push(`<h${lvl}>${inlineMd(heading[2])}</h${lvl}>`);
- continue;
- }
-
- const bullet = line.match(/^(\s*)([-*])\s+(.+)$/);
- const ordered = line.match(/^(\s*)(\d+)\.\s+(.+)$/);
- if (bullet || ordered) {
- flushPara();
- const m = bullet || ordered;
- const indent = Math.floor(m[1].length / 2);
- const t = bullet ? 'ul' : 'ol';
- if (listType && listType !== t) flushList();
- listType = t;
- listBuf.push({ indent, html: inlineMd(m[3]) });
- continue;
- }
-
- paraBuf.push(line);
- }
- flushAll();
- if (inCode && codeBuf.length) {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- }
- return out.join('\n');
- }
-
- function buildListHtml(items, type) {
- // Nest by indent (one level deep is plenty for DESIGN.md).
- let html = `<${type}>`;
- let lastIndent = 0;
- for (const it of items) {
- if (it.indent > lastIndent) html += `<${type}>`;
- else if (it.indent < lastIndent) html += `</${type}>`.repeat(lastIndent - it.indent);
- html += `<li>${it.html}</li>`;
- lastIndent = it.indent;
- }
- html += `</${type}>`.repeat(lastIndent + 1);
- return html;
- }
-
- function inlineMd(text) {
- // Order matters: escape first, then re-inject tags.
- let s = escapeHtml(text);
- // Code spans
- s = s.replace(/`([^`]+)`/g, (_, code) => `<code>${code}</code>`);
- // Links [text](url)
- s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, t, u) => `<a href="${u}" target="_blank" rel="noopener noreferrer">${t}</a>`);
- // Bold
- s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
- // Italic (only single *…*, skip if inside bold already handled)
- s = s.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em>$2</em>');
- return s;
- }
-
- function highlightBold(text) {
- return inlineMd(text);
- }
-
- function escapeHtml(s) {
- return String(s)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
-
- function copyToClipboard(text) {
- if (!text) return;
- try {
- navigator.clipboard.writeText(text);
- showToast('Copied: ' + text);
- } catch { /* ignore */ }
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- function init() {
- try { history.scrollRestoration = 'manual'; } catch {}
- initHighlight();
- initAnnotOverlay();
- initBar();
- initActionPicker();
- initParamsPanel();
- initGlobalBar();
- initDesignPanel();
- document.addEventListener('mousemove', handleMouseMove, true);
- document.addEventListener('click', handleClick, true);
- document.addEventListener('keydown', handleKeyDown, true);
- connectSSE();
-
- // Check for an active session to resume (variant wrapper already in DOM after HMR)
- if (!resumeSession()) {
- console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
- // SvelteKit (and any framework that hydrates after HTML parse) may add
- // the variant wrapper AFTER init runs. Watch for it and retry resume
- // once it appears. Disconnect on first hit.
- const scout = new MutationObserver(() => {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) return;
- scout.disconnect();
- if (resumeSession()) {
- console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
- }
- });
- scout.observe(document.body, { childList: true, subtree: true });
- } else {
- console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
- }
- }
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
- } else {
- init();
- }
-})();
@@ -1,75 +0,0 @@
-#!/usr/bin/env node
-/**
- * Canonical durable completion acknowledgement for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function parseArgs(argv) {
- const out = { status: 'complete' };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';
- else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }
- else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function completeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help || !args.id) {
- console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);
- process.exit(args.help ? 0 : 1);
- }
-
- const serverInfo = readServerInfo();
- const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;
- if (serverResult?.ok) {
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const snapshot = store.getSnapshot(args.id, { includeCompleted: true });
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const event = args.status === 'discarded'
- ? { type: 'discarded', id: args.id }
- : args.status === 'agent_error'
- ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }
- : { type: 'complete', id: args.id };
- const snapshot = store.appendEvent(event);
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));
-}
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function completeThroughServer(info, args) {
- const type = args.status === 'discarded'
- ? 'discarded'
- : args.status === 'agent_error'
- ? 'error'
- : 'complete';
- try {
- const res = await fetch(`http://localhost:${info.port}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),
- });
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {
- completeCli();
-}
@@ -1,18 +0,0 @@
-export function completionTypeForAcceptResult(eventType, acceptResult) {
- if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';
- if (acceptResult?.handled === true) return 'complete';
- if (acceptResult?.mode === 'error') return 'error';
- return 'agent_done';
-}
-
-export function completionAckForAcceptResult(eventId, completionType, acceptResult) {
- const ack = { ok: true, type: completionType };
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) {
- ack.final = false;
- ack.requiresComplete = true;
- ack.nextCommand = `live-complete.mjs --id ${eventId}`;
- ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';
- }
- return ack;
-}
@@ -1,446 +0,0 @@
-/**
- * CLI helper: insert/remove the live variant mode script tag in the project's
- * main HTML entry point.
- *
- * On first live run, the agent generates `.impeccable/live/config.json`
- * with the project's insertion target (framework-specific). On
- * every subsequent run, this script handles insert/remove deterministically
- * with zero LLM involvement.
- *
- * Usage:
- * node live-inject.mjs --port PORT # Insert the live script tag
- * node live-inject.mjs --remove # Remove the live script tag
- * node live-inject.mjs --check # Check whether live config exists
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { resolveLiveConfigPath } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });
-const MARKER_OPEN_TEXT = 'impeccable-live-start';
-const MARKER_CLOSE_TEXT = 'impeccable-live-end';
-
-/**
- * Hard-excluded directory patterns. These are NEVER user-facing pages and
- * matching them would silently inject tracking scripts into third-party
- * code. The user cannot turn these off via config — they are the floor.
- */
-const HARD_EXCLUDES = [
- '**/node_modules/**',
- '**/.git/**',
-];
-
-export async function injectCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-inject.mjs [options]
-
-Insert or remove the live mode script tag in the project's HTML entry point.
-Reads configuration from .impeccable/live/config.json.
-
-Modes:
- --port PORT Insert script tag pointing at http://localhost:PORT/live.js
- --remove Remove the script tag (if present)
- --check Print whether .impeccable/live/config.json exists and its content
-
-Output (JSON):
- { ok, file, inserted|removed, config? }`);
- process.exit(0);
- }
-
- if (args.includes('--check')) {
- if (!fs.existsSync(CONFIG_PATH)) {
- console.log(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(0);
- }
- let cfg;
- try {
- cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- try {
- validateConfig(cfg);
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- console.log(JSON.stringify({ ok: true, config: cfg, path: CONFIG_PATH }));
- return;
- }
-
- // Load config
- if (!fs.existsSync(CONFIG_PATH)) {
- console.error(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(1);
- }
- const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- validateConfig(config);
-
- const resolvedFiles = resolveFiles(process.cwd(), config);
-
- if (args.includes('--remove')) {
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const detagged = removeTag(content, config.commentSyntax);
- const updated = revertCspMeta(detagged);
- if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- removed: detagged !== content,
- cspReverted: updated !== detagged,
- };
- });
- console.log(JSON.stringify({ ok: true, results }));
- return;
- }
-
- // Insert mode — need --port
- const portIdx = args.indexOf('--port');
- const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : NaN;
- if (!Number.isFinite(port)) {
- console.error(JSON.stringify({ ok: false, error: 'missing_port' }));
- process.exit(1);
- }
-
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
- const withTag = insertTag(withoutOld, config, port);
- if (withTag === withoutOld) {
- return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
- }
- const updated = patchCspMeta(withTag, port);
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- inserted: true,
- cspPatched: updated !== withTag,
- };
- });
- const anyInserted = results.some((r) => r.inserted);
- console.log(JSON.stringify({ ok: anyInserted, port, results }));
- if (!anyInserted) process.exit(1);
-}
-
-/**
- * Expand config.files (which may contain glob patterns) into a literal list
- * of existing file paths relative to rootDir. Literal entries pass through;
- * glob patterns are expanded via fs.globSync. HARD_EXCLUDES and config.exclude
- * are applied as filters. Duplicates are removed. Order is preserved by
- * first appearance.
- */
-export function resolveFiles(rootDir, config) {
- const patterns = config.files;
- const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
- const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
- const excludeRegexes = allExcludes.map(globToRegex);
-
- const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
- const isGlob = (s) => /[*?[]/.test(s);
-
- const seen = new Set();
- const out = [];
- for (const pat of patterns) {
- if (!isGlob(pat)) {
- // Literal path — include even if it doesn't exist yet; the caller
- // reports file_not_found per-entry. Exclude list doesn't apply to
- // explicit literal entries (user named it on purpose).
- if (!seen.has(pat)) {
- seen.add(pat);
- out.push(pat);
- }
- continue;
- }
- let matches;
- try {
- matches = fs.globSync(pat, { cwd: rootDir, withFileTypes: true });
- } catch {
- continue;
- }
- for (const ent of matches) {
- if (!ent.isFile || !ent.isFile()) continue;
- const abs = path.join(ent.parentPath || ent.path || rootDir, ent.name);
- const rel = path.relative(rootDir, abs).split(path.sep).join('/');
- if (isExcluded(rel)) continue;
- if (seen.has(rel)) continue;
- seen.add(rel);
- out.push(rel);
- }
- }
- return out;
-}
-
-/**
- * Convert a glob pattern to a RegExp. Supports:
- * ** → any number of path segments (including zero)
- * * → any chars except `/`
- * ? → any single char except `/`
- * Paths are normalized to forward slashes before matching.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- // ** — any number of segments, including zero. Handle the common
- // **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
- if (pattern[i + 2] === '/') {
- re += '(?:.*/)?';
- i += 3;
- } else {
- re += '.*';
- i += 2;
- }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Core operations
-// ---------------------------------------------------------------------------
-
-function validateConfig(cfg) {
- if (!cfg || typeof cfg !== 'object') throw new Error('config.json must be an object');
- if (!Array.isArray(cfg.files) || cfg.files.length === 0) {
- throw new Error('config.files (non-empty string array) required');
- }
- if (!cfg.files.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.files must contain only non-empty strings');
- }
- if (cfg.exclude !== undefined) {
- if (!Array.isArray(cfg.exclude)) {
- throw new Error('config.exclude, if present, must be a string array');
- }
- if (!cfg.exclude.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.exclude must contain only non-empty strings');
- }
- }
- if (typeof cfg.insertBefore !== 'string' && typeof cfg.insertAfter !== 'string') {
- throw new Error('config.insertBefore or config.insertAfter (string) required');
- }
- if (cfg.commentSyntax !== 'html' && cfg.commentSyntax !== 'jsx') {
- throw new Error("config.commentSyntax must be 'html' or 'jsx'");
- }
- if (cfg.cspChecked !== undefined && typeof cfg.cspChecked !== 'boolean') {
- throw new Error("config.cspChecked, if present, must be a boolean");
- }
-}
-
-function commentOpen(syntax) { return syntax === 'jsx' ? '{/*' : '<!--'; }
-function commentClose(syntax) { return syntax === 'jsx' ? '*/}' : '-->'; }
-
-function buildTagBlock(syntax, port) {
- const open = commentOpen(syntax);
- const close = commentClose(syntax);
- return (
- open + ' ' + MARKER_OPEN_TEXT + ' ' + close + '\n' +
- '<script src="http://localhost:' + port + '/live.js"></script>\n' +
- open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n'
- );
-}
-
-function insertTag(content, config, port) {
- const block = buildTagBlock(config.commentSyntax, port);
- // insertBefore: match the LAST occurrence. Anchors like `</body>` naturally
- // belong at the end, and the same literal can appear earlier in code blocks
- // within rendered documentation pages.
- if (config.insertBefore) {
- const idx = content.lastIndexOf(config.insertBefore);
- if (idx === -1) return content;
- return content.slice(0, idx) + block + content.slice(idx);
- }
- // insertAfter: match the FIRST occurrence — typical anchors like `<head>` or
- // `<body>` open near the top of the document.
- const idx = content.indexOf(config.insertAfter);
- if (idx === -1) return content;
- const after = idx + config.insertAfter.length;
- // Preserve a single trailing newline if the anchor didn't end with one
- const prefix = content[after] === '\n' ? content.slice(0, after + 1) : content.slice(0, after) + '\n';
- return prefix + block + content.slice(prefix.length);
-}
-
-/**
- * Remove the live script block. Matches either HTML or JSX comment markers
- * regardless of config (so stale tags from a wrong config can still be cleaned).
- *
- * Indent-preserving: captures any whitespace immediately preceding the opener
- * marker and re-emits it in place of the removed block. `insertTag` inserted
- * the block *after* the original line's indent and *before* the anchor (e.g.
- * `</body>`), which moved the indent onto the opener line and left the anchor
- * unindented. Replacing the whole block (plus its trailing newline) with just
- * the captured indent hands the indent back to the anchor that follows.
- */
-function removeTag(content, _syntax) {
- const patterns = [
- /([ \t]*)<!--\s*impeccable-live-start\s*-->[\s\S]*?<!--\s*impeccable-live-end\s*-->[ \t]*\n/,
- /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}[ \t]*\n/,
- ];
- for (const pat of patterns) {
- const next = content.replace(pat, '$1');
- if (next !== content) return next;
- }
- return content;
-}
-
-// ---------------------------------------------------------------------------
-// Content-Security-Policy meta-tag patcher
-//
-// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
-// the cross-origin load of /live.js (and the SSE/POST connection back to
-// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
-//
-// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
-// and stash the original `content` value in a `data-impeccable-csp-original`
-// attribute (base64) so revert is exact.
-//
-// On remove: detect the marker attribute, decode it, restore the original
-// content value verbatim, drop the marker.
-//
-// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
-// shared helpers) is NOT patched here — those need framework-specific config
-// edits and are handled via the existing detect-csp.mjs reference output.
-// Only the in-source meta-tag form gets the auto-patch.
-// ---------------------------------------------------------------------------
-
-const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
-
-function findCspMetaTags(content) {
- const out = [];
- const tagRe = /<meta\s+([^>]*?)\/?>/gis;
- let m;
- while ((m = tagRe.exec(content)) !== null) {
- const attrs = m[1];
- if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
- out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
- }
- return out;
-}
-
-function getAttr(attrs, name) {
- const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
- const m = attrs.match(re);
- return m ? { quote: m[1], value: m[2], full: m[0] } : null;
-}
-
-function appendOriginToDirective(csp, directive, origin) {
- const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
- const m = csp.match(re);
- if (m) {
- const tokens = m[4].trim().split(/\s+/);
- if (tokens.includes(origin)) return csp;
- return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
- }
- // Directive missing — add it. Use 'self' + origin so we don't inadvertently
- // narrow the policy compared to the default-src fallback (most users with
- // an explicit CSP have 'self' there).
- return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
-}
-
-export function patchCspMeta(content, port) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
- const origin = `http://localhost:${port}`;
-
- // Walk last-to-first so prior splices don't invalidate later indices.
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const attrs = tag.attrs;
- if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
- const contentAttr = getAttr(attrs, 'content');
- if (!contentAttr) continue;
-
- const original = contentAttr.value;
- let patched = original;
- patched = appendOriginToDirective(patched, 'script-src', origin);
- patched = appendOriginToDirective(patched, 'connect-src', origin);
- // The shader overlay during 'generating' creates a screenshot via
- // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
- // those. Add `blob:` so the overlay doesn't throw a CSP violation.
- patched = appendOriginToDirective(patched, 'img-src', 'blob:');
- if (patched === original) continue;
-
- const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
- const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
- // The tagRe captures any whitespace between the last attribute and the
- // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
- // a replace would land it BEFORE that trailing space, leaving a double
- // space inside attrs and clobbering the space before `/>`. Split off
- // the trailing whitespace, splice the marker into the attribute body,
- // and re-append the original trailing whitespace so a self-closing
- // `<meta … />` round-trips byte-for-byte.
- const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
- const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
- const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
- const newTag = tag.full.replace(attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-export function revertCspMeta(content) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
-
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
- if (!origAttr) continue;
- const contentAttr = getAttr(tag.attrs, 'content');
- if (!contentAttr) continue;
-
- let originalValue;
- try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
- catch { continue; }
-
- const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
- let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
- // Drop the marker attribute and any single space immediately preceding it.
- newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
- const newTag = tag.full.replace(tag.attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
- injectCli();
-}
-
-export { insertTag, removeTag, validateConfig, buildTagBlock };
-// patchCspMeta + revertCspMeta are exported above where they're defined.
@@ -1,200 +0,0 @@
-/**
- * CLI client for the live variant mode poll/reply protocol.
- *
- * Usage:
- * npx impeccable poll # Block until browser event, print JSON
- * npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
- * npx impeccable poll --reply <id> done # Reply "done" to event <id>
- * npx impeccable poll --reply <id> error "msg" # Reply with error
- */
-
-import { execFileSync } from 'node:child_process';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-// Node's built-in fetch (undici under the hood) enforces a 300s headers
-// timeout that can't be lowered per-request. We cap each request below
-// that ceiling and loop in `pollOnce` to synthesize a long poll without
-// depending on the standalone undici package.
-const PER_REQUEST_TIMEOUT_MS = 270_000;
-
-function readServerInfo() {
- const record = readLiveServerInfo(process.cwd());
- if (!record) {
- console.error('No running live server found. Start one with: npx impeccable live');
- process.exit(1);
- }
- return record.info;
-}
-
-export function buildPollReplyPayload(token, { id, type, message, file, data }) {
- return { token, id, type, message, file, data };
-}
-
-async function postReply(base, token, reply) {
- const res = await fetch(`${base}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(buildPollReplyPayload(token, reply)),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error || res.statusText);
- }
-}
-
-export async function pollCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable poll [options]
-
-Wait for a browser event from the live variant server, or reply to one.
-
-Modes:
- poll Block until a browser event arrives, print JSON
- poll --reply <id> done Reply "done" to event <id>
- poll --reply <id> error "msg" Reply with an error message
-
-Options:
- --timeout=MS Long-poll timeout in ms (default: 600000). Use the default unless the user asked to pause live; never use a short timeout to end the chat turn
- --help Show this help message`);
- process.exit(0);
- }
-
- const info = readServerInfo();
- const base = `http://localhost:${info.port}`;
-
- // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
- const replyIdx = args.indexOf('--reply');
- if (replyIdx !== -1) {
- const id = args[replyIdx + 1];
- const status = args[replyIdx + 2] || 'done';
- const fileIdx = args.indexOf('--file');
- const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
- // Message is any remaining positional arg that isn't a flag
- const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
-
- if (!id) {
- console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
- process.exit(1);
- }
-
- try {
- await postReply(base, info.token, { id, type: status, message, file: filePath });
-
- // Success — silent exit (agent doesn't need output for replies)
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Reply failed:', err.message);
- }
- process.exit(1);
- }
- return;
- }
-
- // Poll mode: block until browser event. Default 10 min. Node's built-in
- // fetch enforces a 300s headers timeout, so we loop in slices under that
- // ceiling and keep re-polling until we get a real event or the user's
- // total timeout runs out.
- const timeoutArg = args.find(a => a.startsWith('--timeout='));
- const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600000;
-
- const deadline = Date.now() + totalTimeout;
- let event;
- try {
- while (true) {
- const remaining = deadline - Date.now();
- if (remaining <= 0) {
- event = { type: 'timeout' };
- break;
- }
- const slice = Math.min(remaining, PER_REQUEST_TIMEOUT_MS);
- const res = await fetch(`${base}/poll?token=${info.token}&timeout=${slice}`);
-
- if (res.status === 401) {
- console.error('Authentication failed. The server token may have changed.');
- console.error('Try restarting: npx impeccable live stop && npx impeccable live');
- process.exit(1);
- }
-
- if (!res.ok) {
- console.error(`Poll failed: ${res.status} ${res.statusText}`);
- process.exit(1);
- }
-
- const next = await res.json();
- // Server-side timeout means no browser event arrived in this slice.
- // Loop and re-poll until we get a real event or we hit the user's
- // total deadline.
- if (next?.type === 'timeout' && Date.now() < deadline) continue;
- event = next;
- break;
- }
-
- // Auto-handle accept/discard via deterministic script
- if (event.type === 'accept' || event.type === 'discard') {
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const acceptScript = path.join(__dirname, 'live-accept.mjs');
- const scriptArgs = event.type === 'discard'
- ? ['--id', event.id, '--discard']
- : ['--id', event.id, '--variant', event.variantId];
- if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
- scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
- }
- try {
- const out = execFileSync(
- 'node',
- [acceptScript, ...scriptArgs],
- { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 }
- );
- event._acceptResult = JSON.parse(out.trim());
- } catch (err) {
- event._acceptResult = { handled: false, mode: 'error', error: err.message };
- }
-
- const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
- try {
- await postReply(base, info.token, {
- id: event.id,
- type: completionType,
- message: event._acceptResult?.error,
- file: event._acceptResult?.file,
- data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
- });
- } catch (err) {
- event._completionAck = { ok: false, error: err.message };
- }
- if (!event._completionAck) {
- event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
- }
- }
-
- // Second signal path: stderr banner in case the agent parses stdout
- // JSON but skips nested fields. One line is enough — the full checklist
- // is in reference/live.md.
- if (event._acceptResult?.carbonize === true) {
- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
- }
-
- // Print the event as JSON — the agent reads this from stdout
- console.log(JSON.stringify(event));
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Poll failed:', err.message);
- }
- process.exit(1);
- }
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
- pollCli();
-}
@@ -1,48 +0,0 @@
-#!/usr/bin/env node
-/**
- * Recover the next agent action from the durable live-session journal.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-
-function parseArgs(argv) {
- const out = { id: null };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function resumeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help) {
- console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });
- const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;
- if (!snapshot) {
- console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));
- return;
- }
-
- const pending = snapshot.pendingEvent || null;
- const nextAction = pending
- ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`
- : snapshot.phase === 'carbonize_required'
- ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`
- : snapshot.phase === 'accept_requested'
- ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`
- : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;
-
- console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {
- resumeCli();
-}
@@ -1,838 +0,0 @@
-#!/usr/bin/env node
-/**
- * Live variant mode server (self-contained, zero dependencies).
- *
- * Serves the browser script (/live.js), the detection overlay (/detect.js),
- * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
- * browser→server events. Agent communicates via HTTP long-poll (/poll).
- *
- * Usage:
- * node <scripts_path>/live-server.mjs # start
- * node <scripts_path>/live-server.mjs stop # stop + remove injected live.js tag
- * node <scripts_path>/live-server.mjs stop --keep-inject # stop only
- * node <scripts_path>/live-server.mjs --help
- */
-
-import http from 'node:http';
-import { randomUUID } from 'node:crypto';
-import { spawn, execFileSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import net from 'node:net';
-import { fileURLToPath } from 'node:url';
-import { parseDesignMd } from './design-parser.mjs';
-import { resolveContextDir } from './load-context.mjs';
-import { createLiveSessionStore } from './live-session-store.mjs';
-import {
- getDesignSidecarPath,
- getLiveAnnotationsDir,
- readLiveServerInfo,
- removeLiveServerInfo,
- resolveDesignSidecarPath,
- writeLiveServerInfo,
-} from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated
-// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
-// DESIGN.json fallback for existing projects.
-const CONTEXT_DIR = resolveContextDir(process.cwd());
-const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anyway
-const SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s
-
-// ---------------------------------------------------------------------------
-// Port detection
-// ---------------------------------------------------------------------------
-
-async function findOpenPort(start = 8400) {
- return new Promise((resolve) => {
- const srv = net.createServer();
- srv.listen(start, '127.0.0.1', () => {
- const port = srv.address().port;
- srv.close(() => resolve(port));
- });
- srv.on('error', () => resolve(findOpenPort(start + 1)));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Session state
-// ---------------------------------------------------------------------------
-
-const state = {
- token: null,
- port: null,
- sseClients: new Set(), // SSE response objects (server→browser push)
- pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
- pendingPolls: [], // agent poll callbacks waiting for browser events
- exitTimer: null,
- sessionDir: null, // per-session tmp dir for annotation screenshots
- sessionStore: null,
- leaseTimer: null,
-};
-
-// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;
-// cap at 10 MB to guard against runaway writes from a misbehaving client.
-const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
-
-function enqueueEvent(event) {
- if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;
- state.pendingEvents.push({ event, leaseUntil: 0 });
- flushPendingPolls();
-}
-
-function restorePendingEventsFromStore() {
- if (!state.sessionStore) return;
- for (const snapshot of state.sessionStore.listActiveSessions()) {
- if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);
- }
-}
-
-function findAvailablePendingEvent(now = Date.now()) {
- return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);
-}
-
-function leaseEvent(entry, leaseMs) {
- if (!entry.event?.id) {
- const idx = state.pendingEvents.indexOf(entry);
- if (idx !== -1) state.pendingEvents.splice(idx, 1);
- return entry.event;
- }
- entry.leaseUntil = Date.now() + leaseMs;
- return entry.event;
-}
-
-function acknowledgePendingEvent(id) {
- if (!id) return false;
- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);
- if (idx === -1) return false;
- state.pendingEvents.splice(idx, 1);
- scheduleLeaseFlush();
- return true;
-}
-
-function scheduleLeaseFlush() {
- if (state.leaseTimer) {
- clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- }
- if (state.pendingPolls.length === 0) return;
- const now = Date.now();
- const nextLeaseUntil = state.pendingEvents
- .map((entry) => entry.leaseUntil || 0)
- .filter((leaseUntil) => leaseUntil > now)
- .sort((a, b) => a - b)[0];
- if (!nextLeaseUntil) return;
- state.leaseTimer = setTimeout(() => {
- state.leaseTimer = null;
- flushPendingPolls();
- }, Math.max(0, nextLeaseUntil - now));
-}
-
-function flushPendingPolls() {
- while (state.pendingPolls.length > 0) {
- const entry = findAvailablePendingEvent();
- if (!entry) {
- scheduleLeaseFlush();
- return;
- }
- const poll = state.pendingPolls.shift();
- poll.resolve(leaseEvent(entry, poll.leaseMs));
- }
- scheduleLeaseFlush();
-}
-
-/** Push a message to all connected SSE clients. */
-function broadcast(msg) {
- const data = 'data: ' + JSON.stringify(msg) + '\n\n';
- for (const res of state.sseClients) {
- try { res.write(data); } catch { /* client gone */ }
- }
-}
-
-// ---------------------------------------------------------------------------
-// Load scripts
-// ---------------------------------------------------------------------------
-
-function loadBrowserScripts() {
- // Detection script: prefer the skill-bundled detector, then fall back to
- // source/npm package locations for local development and older installs.
- // This one IS cached — detect.js rarely changes during a session.
- const detectPaths = [
- path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(process.cwd(), 'node_modules', 'impeccable', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- ];
- let detectScript = '';
- for (const p of detectPaths) {
- try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
- }
-
- // live-browser.js: DO NOT cache. Return the path so the /live.js handler
- // can re-read on every request. Editing the browser script during iteration
- // should land on the next tab reload, not require a server restart.
- const sessionPath = path.join(__dirname, 'live-browser-session.js');
- const livePath = path.join(__dirname, 'live-browser.js');
- for (const p of [sessionPath, livePath]) {
- if (!fs.existsSync(p)) {
- process.stderr.write('Error: live browser script not found at ' + p + '\n');
- process.exit(1);
- }
- }
-
- return { detectScript, sessionPath, livePath };
-}
-
-function hasProjectContext() {
- // PRODUCT.md carries brand voice / anti-references — that's what determines
- // whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
- // concern, surfaced by the design panel's own empty state. Legacy
- // .impeccable.md is auto-migrated to PRODUCT.md by load-context.mjs.
- try {
- fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
- return true;
- } catch { return false; }
-}
-
-function statOrNull(filePath) {
- try { return fs.statSync(filePath); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// Validation (inline — no external import needed for self-contained script)
-// ---------------------------------------------------------------------------
-
-const VISUAL_ACTIONS = [
- 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
- 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
-];
-
-// Browser generates ids via crypto.randomUUID().slice(0, 8) (8 hex chars)
-// and variantIds via String(small integer). Restrict to those shapes so
-// any value that reaches a downstream child_process or DOM selector is
-// inert by construction.
-const ID_PATTERN = /^[0-9a-f]{8}$/;
-const VARIANT_ID_PATTERN = /^[0-9]{1,3}$/;
-
-function isValidId(v) { return typeof v === 'string' && ID_PATTERN.test(v); }
-function isValidVariantId(v) { return typeof v === 'string' && VARIANT_ID_PATTERN.test(v); }
-
-function validateEvent(msg) {
- if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
- switch (msg.type) {
- case 'generate':
- if (!isValidId(msg.id)) return 'generate: missing or malformed id';
- if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
- if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
- if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
- // Optional annotation fields (all-or-nothing: if any present, all must be well-formed).
- if (msg.screenshotPath !== undefined && typeof msg.screenshotPath !== 'string') return 'generate: screenshotPath must be string';
- if (msg.comments !== undefined && !Array.isArray(msg.comments)) return 'generate: comments must be array';
- if (msg.strokes !== undefined && !Array.isArray(msg.strokes)) return 'generate: strokes must be array';
- return null;
- case 'accept':
- if (!isValidId(msg.id)) return 'accept: missing or malformed id';
- if (!isValidVariantId(msg.variantId)) return 'accept: missing or malformed variantId';
- if (msg.paramValues !== undefined) {
- if (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues)) {
- return 'accept: paramValues must be an object';
- }
- }
- return null;
- case 'discard':
- return isValidId(msg.id) ? null : 'discard: missing or malformed id';
- case 'checkpoint':
- if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';
- if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';
- if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {
- return 'checkpoint: paramValues must be an object';
- }
- return null;
- case 'exit':
- return null;
- case 'prefetch':
- if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return 'prefetch: missing pageUrl';
- return null;
- default:
- return 'Unknown event type: ' + msg.type;
- }
-}
-
-// ---------------------------------------------------------------------------
-// HTTP request handler
-// ---------------------------------------------------------------------------
-
-function createRequestHandler({ detectScript, sessionPath, livePath }) {
- return (req, res) => {
- const url = new URL(req.url, `http://localhost:${state.port}`);
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
- if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
-
- const p = url.pathname;
-
- // --- Scripts ---
- if (p === '/live.js') {
- // Re-read from disk each request so edits to live-browser.js land on
- // the next tab reload. No-store headers prevent browser caching across
- // sessions — during iteration, a cached old script silently breaks
- // every subsequent session.
- let sessionScript;
- let liveScript;
- try {
- sessionScript = fs.readFileSync(sessionPath, 'utf-8');
- liveScript = fs.readFileSync(livePath, 'utf-8');
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'text/plain' });
- res.end('Error reading live browser scripts: ' + err.message);
- return;
- }
- const body =
- `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
- `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
- sessionScript + '\n' +
- liveScript;
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
- 'Pragma': 'no-cache',
- });
- res.end(body);
- return;
- }
- if (p === '/detect.js' || p === '/') {
- if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
- res.writeHead(200, { 'Content-Type': 'application/javascript' });
- res.end(detectScript);
- return;
- }
-
- // --- Vendored modern-screenshot (UMD build) ---
- // Lazy-loaded by live.js when the user clicks Go; exposes
- // window.modernScreenshot.domToBlob(...) for capture.
- if (p === '/modern-screenshot.js') {
- const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
- try {
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'public, max-age=31536000, immutable',
- });
- res.end(fs.readFileSync(vendorPath));
- } catch {
- res.writeHead(404); res.end('Vendor script not found');
- }
- return;
- }
-
- // --- Annotation upload (browser → server, raw PNG body) ---
- // Client generates the eventId, POSTs the PNG, then POSTs the generate
- // event with screenshotPath already set. Keeps bytes out of the SSE/poll
- // bridge and preserves the "one shot from the user's POV" UX.
- if (p === '/annotation' && req.method === 'POST') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const eventId = url.searchParams.get('eventId');
- if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid eventId' }));
- return;
- }
- if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
- res.writeHead(415, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
- return;
- }
- if (!state.sessionDir) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Session dir unavailable' }));
- return;
- }
- const chunks = [];
- let total = 0;
- let aborted = false;
- req.on('data', (c) => {
- if (aborted) return;
- total += c.length;
- if (total > MAX_ANNOTATION_BYTES) {
- aborted = true;
- res.writeHead(413, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Payload too large' }));
- req.destroy();
- return;
- }
- chunks.push(c);
- });
- req.on('end', () => {
- if (aborted) return;
- const absPath = path.join(state.sessionDir, eventId + '.png');
- try {
- fs.writeFileSync(absPath, Buffer.concat(chunks));
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Write failed: ' + err.message }));
- return;
- }
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true, path: absPath }));
- });
- req.on('error', () => {
- if (!aborted) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Upload failed' }));
- }
- });
- return;
- }
-
- // --- Health ---
- if (p === '/status') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
- const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok',
- port: state.port,
- connectedClients: state.sseClients.size,
- pendingEvents: state.pendingEvents.map((entry) => ({
- id: entry.event?.id,
- type: entry.event?.type,
- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),
- leaseUntil: entry.leaseUntil || null,
- })),
- activeSessions: sessions,
- }));
- return;
- }
-
- if (p === '/health') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok', port: state.port, mode: 'variant',
- hasProjectContext: hasProjectContext(),
- connectedClients: state.sseClients.size,
- }));
- return;
- }
-
- // --- Design system (unified v2 response) + raw ---
- // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json
- // sidecar when present. Panel merges them:
- // { present, parsed, sidecar, hasMd, hasSidecar,
- // mdNewerThanJson, parseError?, sidecarError? }
- // - parsed: output of parseDesignMd (frontmatter
- // + six canonical sections) when DESIGN.md exists.
- // - sidecar: .impeccable/design.json contents when present.
- // Expected shape: schemaVersion 2, carrying
- // extensions + components + narrative.
- // /design-system/raw returns DESIGN.md markdown verbatim
- if (p === '/design-system.json' || p === '/design-system/raw') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
-
- const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
- const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
- const mdStat = statOrNull(mdPath);
- const jsonStat = statOrNull(jsonPath);
-
- if (p === '/design-system/raw') {
- if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
- res.end(fs.readFileSync(mdPath, 'utf-8'));
- return;
- }
-
- if (!mdStat && !jsonStat) {
- res.writeHead(404, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ present: false }));
- return;
- }
-
- const response = {
- present: true,
- hasMd: !!mdStat,
- hasSidecar: !!jsonStat,
- mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
- };
-
- if (mdStat) {
- try {
- response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
- } catch (err) {
- response.parseError = err.message;
- }
- }
-
- if (jsonStat) {
- try {
- response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
- } catch (err) {
- response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;
- }
- }
-
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(response));
- return;
- }
-
- // --- Source file (no-HMR fallback) ---
- if (p === '/source') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const filePath = url.searchParams.get('path');
- if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
- const absPath = path.resolve(process.cwd(), filePath);
- if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
- let content;
- try { content = fs.readFileSync(absPath, 'utf-8'); }
- catch { res.writeHead(404); res.end('File not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
- res.end(content);
- return;
- }
-
- // --- SSE: server→browser push (replaces WebSocket) ---
- if (p === '/events' && req.method === 'GET') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- 'Connection': 'keep-alive',
- });
- res.write('data: ' + JSON.stringify({
- type: 'connected',
- hasProjectContext: hasProjectContext(),
- }) + '\n\n');
-
- state.sseClients.add(res);
- clearTimeout(state.exitTimer);
-
- // Keepalive: SSE comment every 30s prevents silent connection drops.
- const heartbeat = setInterval(() => {
- try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
- }, SSE_HEARTBEAT_INTERVAL);
-
- req.on('close', () => {
- clearInterval(heartbeat);
- state.sseClients.delete(res);
- if (state.sseClients.size === 0) {
- clearTimeout(state.exitTimer);
- state.exitTimer = setTimeout(() => {
- if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
- }, 8000);
- }
- });
- return;
- }
-
- // --- Browser→server events (replaces WebSocket messages) ---
- if (p === '/events' && req.method === 'POST') {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const error = validateEvent(msg);
- if (error) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error }));
- return;
- }
- if (state.sessionStore && msg.id) {
- try {
- state.sessionStore.appendEvent(msg);
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
- return;
- }
- }
- if (msg.type !== 'checkpoint') enqueueEvent(msg);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
- return;
- }
-
- // --- Stop ---
- if (p === '/stop') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.end('stopping');
- shutdown();
- return;
- }
-
- // --- Agent poll ---
- if (p === '/poll' && req.method === 'GET') {
- handlePollGet(req, res, url);
- return;
- }
- if (p === '/poll' && req.method === 'POST') {
- handlePollPost(req, res);
- return;
- }
-
- res.writeHead(404); res.end('Not found');
- };
-}
-
-// ---------------------------------------------------------------------------
-// Agent poll endpoints (unchanged from WS version)
-// ---------------------------------------------------------------------------
-
-function handlePollGet(req, res, url) {
- const token = url.searchParams.get('token');
- if (token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
- const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
- const available = findAvailablePendingEvent();
- if (available) {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(leaseEvent(available, leaseMs)));
- return;
- }
- const poll = { resolve, leaseMs };
- const timer = setTimeout(() => {
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ type: 'timeout' }));
- }, timeout);
- function resolve(event) {
- clearTimeout(timer);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(event));
- }
- state.pendingPolls.push(poll);
- scheduleLeaseFlush();
- req.on('close', () => {
- clearTimeout(timer);
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- });
-}
-
-function handlePollPost(req, res) {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- acknowledgePendingEvent(msg.id);
- if (state.sessionStore && msg.id) {
- try {
- const eventType = msg.type === 'discard' || msg.type === 'discarded'
- ? 'discarded'
- : msg.type === 'complete'
- ? 'complete'
- : msg.type === 'error'
- ? 'agent_error'
- : 'agent_done';
- state.sessionStore.appendEvent({
- type: eventType,
- id: msg.id,
- file: msg.file,
- message: msg.message,
- carbonize: msg.data?.carbonize === true,
- });
- } catch { /* keep reply path best-effort; browser still needs SSE */ }
- }
- flushPendingPolls();
- // Forward the reply to the browser via SSE
- broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Lifecycle
-// ---------------------------------------------------------------------------
-
-let httpServer = null;
-
-function shutdown() {
- removeLiveServerInfo(process.cwd());
- if (state.leaseTimer) clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- if (state.sessionDir) {
- try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}
- }
- for (const res of state.sseClients) { try { res.end(); } catch {} }
- state.sseClients.clear();
- for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });
- state.pendingPolls.length = 0;
- if (httpServer) httpServer.close();
- process.exit(0);
-}
-
-// ---------------------------------------------------------------------------
-// Main
-// ---------------------------------------------------------------------------
-
-const args = process.argv.slice(2);
-
-if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-server.mjs [options]
-
-Start the live variant mode server (zero dependencies).
-
-Commands:
- (default) Start the server (foreground)
- stop Stop the server and remove the injected live.js script tag
- stop --keep-inject Stop the server only (leave the script tag in the HTML entry)
-
-Options:
- --background Start detached, print connection JSON to stdout, then exit
- --port=PORT Use a specific port (default: auto-detect starting at 8400)
- --keep-inject Only with stop: skip live-inject.mjs --remove
- --help Show this help
-
-Endpoints:
- /live.js Browser script (element picker + variant cycling)
- /detect.js Detection overlay (backwards compatible)
- /modern-screenshot.js Vendored modern-screenshot UMD build (lazy-loaded by live.js)
- /annotation POST raw image/png to stage a variant screenshot
- /events SSE stream (server→browser) + POST (browser→server)
- /poll Long-poll for agent CLI
- /source Raw source file reader (no-HMR fallback)
- /status Durable recovery status (token-protected)
- /health Health check`);
- process.exit(0);
-}
-
-if (args.includes('stop')) {
- const keepInject = args.includes('--keep-inject');
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);
- if (res.ok) console.log(`Stopped live server on port ${info.port}.`);
- } catch {
- console.log('No running live server found.');
- }
- if (!keepInject) {
- const injectPath = path.join(__dirname, 'live-inject.mjs');
- try {
- const out = execFileSync(process.execPath, [injectPath, '--remove'], {
- encoding: 'utf-8',
- cwd: process.cwd(),
- });
- const line = out.trim().split('\n').filter(Boolean).pop();
- if (line) {
- try {
- const j = JSON.parse(line);
- if (j.removed === true) {
- console.log(`Removed live script tag from ${j.file}.`);
- }
- } catch {
- /* ignore non-JSON lines */
- }
- }
- } catch (err) {
- const detail = err.stderr?.toString?.().trim?.()
- || err.stdout?.toString?.().trim?.()
- || err.message
- || String(err);
- console.warn(`Note: could not remove live script tag (${detail.split('\n')[0]})`);
- }
- }
- process.exit(0);
-}
-
-// --background: spawn a detached child server, wait for it to be ready,
-// print the connection JSON, then exit. This keeps the startup command
-// simple (no shell backgrounding or chained commands).
-if (args.includes('--background')) {
- const childArgs = args.filter(a => a !== '--background');
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), ...childArgs], {
- detached: true,
- stdio: 'ignore',
- cwd: process.cwd(),
- });
- child.unref();
-
- // Poll for the PID file (the child writes it once the HTTP server is listening).
- const deadline = Date.now() + 10_000;
- while (Date.now() < deadline) {
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- if (info.pid !== process.pid) {
- // Output JSON so the agent can read port + token from stdout.
- console.log(JSON.stringify(info));
- process.exit(0);
- }
- } catch { /* not ready yet */ }
- await new Promise(r => setTimeout(r, 200));
- }
- console.error('Timed out waiting for live server to start.');
- process.exit(1);
-}
-
-// Check for existing session
-const existingRecord = readLiveServerInfo(process.cwd());
-if (existingRecord?.info) {
- const existing = existingRecord.info;
- try {
- process.kill(existing.pid, 0);
- console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
- console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');
- process.exit(1);
- } catch {
- try { fs.unlinkSync(existingRecord.path); } catch {}
- }
-}
-
-state.token = randomUUID();
-state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });
-restorePendingEventsFromStore();
-const portArg = args.find(a => a.startsWith('--port='));
-state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
-// Annotation screenshots live in the project root so the agent's Read tool
-// doesn't trip a per-file permission prompt. Sessioned by token so concurrent
-// projects (or quick restarts) don't collide.
-const annotRoot = getLiveAnnotationsDir(process.cwd());
-fs.mkdirSync(annotRoot, { recursive: true });
-state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));
-
-const { detectScript, sessionPath, livePath } = loadBrowserScripts();
-httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));
-
-httpServer.listen(state.port, '127.0.0.1', () => {
- writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });
- const url = `http://localhost:${state.port}`;
- console.log(`\nImpeccable live server running on ${url}`);
- console.log(`Token: ${state.token}\n`);
- console.log(`Inject: <script src="${url}/live.js"><\/script>`);
- console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
-});
-
-process.on('SIGINT', shutdown);
-process.on('SIGTERM', shutdown);
@@ -1,254 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';
-
-const COMPLETED_PHASES = new Set(['completed', 'discarded']);
-
-export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {
- const rootDir = getLiveSessionsDir(cwd);
- const legacyRootDir = getLegacyLiveSessionsDir(cwd);
- fs.mkdirSync(rootDir, { recursive: true });
- const snapshotCache = new Map();
-
- function loadCachedOrRebuild(id) {
- const cached = snapshotCache.get(id);
- if (cached) return cached;
- const journalPath = getReadableJournalPath(id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- return rebuilt;
- }
-
- function getReadableJournalPath(id) {
- const primary = getJournalPath(rootDir, id);
- if (fs.existsSync(primary)) return primary;
- const legacy = getJournalPath(legacyRootDir, id);
- if (fs.existsSync(legacy)) return legacy;
- return primary;
- }
-
- return {
- rootDir,
- legacyRootDir,
- appendEvent(event) {
- const normalized = normalizeEvent(event, sessionId);
- const journalPath = getJournalPath(rootDir, normalized.id);
- const snapshotPath = getSnapshotPath(rootDir, normalized.id);
- const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);
- if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {
- fs.copyFileSync(legacyJournalPath, journalPath);
- }
- const prior = loadCachedOrRebuild(normalized.id);
- const seq = prior.nextSeq;
- const entry = {
- seq,
- id: normalized.id,
- type: normalized.type,
- ts: new Date().toISOString(),
- event: normalized,
- };
- fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');
- const next = applyEvent(prior.snapshot, entry, prior.diagnostics);
- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });
- writeSnapshot(snapshotPath, next);
- return next;
- },
- getSnapshot(id = sessionId, opts = {}) {
- if (!id) throw new Error('session id required');
- const journalPath = getReadableJournalPath(id);
- const snapshotPath = getSnapshotPath(rootDir, id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- writeSnapshot(snapshotPath, rebuilt.snapshot);
- if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;
- return rebuilt.snapshot;
- },
- listActiveSessions() {
- const ids = new Set();
- for (const dir of [legacyRootDir, rootDir]) {
- if (!fs.existsSync(dir)) continue;
- for (const name of fs.readdirSync(dir)) {
- if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));
- }
- }
- return [...ids]
- .sort()
- .map((id) => this.getSnapshot(id))
- .filter(Boolean);
- },
- };
-}
-
-function normalizeEvent(event, fallbackId) {
- if (!event || typeof event !== 'object') throw new Error('event object required');
- const id = event.id || fallbackId;
- if (!id || typeof id !== 'string') throw new Error('event id required');
- if (!event.type || typeof event.type !== 'string') throw new Error('event type required');
- return { ...event, id };
-}
-
-function getJournalPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.jsonl');
-}
-
-function getSnapshotPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.snapshot.json');
-}
-
-function safeSessionId(id) {
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);
- return id;
-}
-
-function baseSnapshot(id) {
- return {
- id,
- phase: 'new',
- pageUrl: null,
- sourceFile: null,
- expectedVariants: 0,
- arrivedVariants: 0,
- visibleVariant: null,
- paramValues: {},
- pendingEventSeq: null,
- pendingEvent: null,
- deliveryLease: null,
- checkpointRevision: 0,
- activeOwner: null,
- sourceMarkers: {},
- fallbackMode: null,
- annotationArtifacts: [],
- diagnostics: [],
- updatedAt: null,
- };
-}
-
-function rebuildSnapshotFromJournal(journalPath, id) {
- let snapshot = baseSnapshot(id);
- const diagnostics = [];
- let nextSeq = 1;
- if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };
-
- const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- if (!line.trim()) continue;
- try {
- const entry = JSON.parse(line);
- if (!entry || typeof entry !== 'object') throw new Error('entry is not object');
- if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);
- snapshot = applyEvent(snapshot, entry);
- } catch (err) {
- diagnostics.push({
- error: 'journal_parse_failed',
- line: i + 1,
- message: err.message,
- });
- }
- }
- snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];
- return { snapshot, diagnostics, nextSeq };
-}
-
-function applyEvent(snapshot, entry, inheritedDiagnostics = []) {
- const event = entry.event || entry;
- const next = {
- ...snapshot,
- paramValues: { ...(snapshot.paramValues || {}) },
- sourceMarkers: { ...(snapshot.sourceMarkers || {}) },
- annotationArtifacts: [...(snapshot.annotationArtifacts || [])],
- diagnostics: [...(snapshot.diagnostics || [])],
- updatedAt: entry.ts || new Date().toISOString(),
- };
-
- if (inheritedDiagnostics.length && next.diagnostics.length === 0) {
- next.diagnostics = [...inheritedDiagnostics];
- }
-
- switch (event.type) {
- case 'generate':
- next.phase = 'generate_requested';
- next.pageUrl = event.pageUrl ?? next.pageUrl;
- next.expectedVariants = event.count ?? next.expectedVariants;
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });
- break;
- case 'variants_ready':
- case 'agent_done':
- next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';
- next.sourceFile = event.file ?? next.sourceFile;
- next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- if (event.carbonize === true) {
- next.diagnostics.push({
- error: 'carbonize_cleanup_required',
- file: event.file || null,
- message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',
- });
- }
- break;
- case 'checkpoint':
- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {
- next.phase = event.phase ?? next.phase;
- next.checkpointRevision = event.revision ?? next.checkpointRevision;
- next.activeOwner = event.owner ?? next.activeOwner;
- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;
- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- } else {
- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });
- }
- break;
- case 'accept':
- case 'accept_intent':
- next.phase = 'accept_requested';
- next.visibleVariant = Number(event.variantId ?? next.visibleVariant);
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discard':
- next.phase = 'discard_requested';
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discarded':
- next.phase = 'discarded';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'complete':
- next.phase = 'completed';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'agent_error':
- next.phase = 'agent_error';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });
- break;
- default:
- next.diagnostics.push({ error: 'unknown_event_type', type: event.type });
- break;
- }
- return next;
-}
-
-function toPendingEvent(event) {
- const pending = { ...event };
- delete pending.token;
- return pending;
-}
-
-function upsertArtifact(artifacts, artifact) {
- if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {
- artifacts.push(artifact);
- }
-}
-
-function writeSnapshot(snapshotPath, snapshot) {
- fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');
-}
@@ -1,47 +0,0 @@
-#!/usr/bin/env node
-/**
- * Print durable recovery status for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function fetchServerStatus(info) {
- if (!info) return null;
- try {
- const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-export async function statusCli() {
- const info = readServerInfo();
- const server = await fetchServerStatus(info);
- const store = createLiveSessionStore({ cwd: process.cwd() });
- const activeSessions = store.listActiveSessions();
- const payload = {
- liveServer: server ? {
- status: server.status,
- port: server.port,
- connectedClients: server.connectedClients,
- pendingEvents: server.pendingEvents,
- } : null,
- activeSessions: server?.activeSessions || activeSessions,
- recoveryHint: server
- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'
- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',
- };
- console.log(JSON.stringify(payload, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {
- statusCli();
-}
@@ -1,632 +0,0 @@
-/**
- * CLI helper: find an element in source and wrap it in a variant container.
- *
- * Usage:
- * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
- *
- * Searches project files for the element matching the query (class name, ID, or
- * text snippet), wraps it with the variant scaffolding, and prints the file path
- * + line range where the agent should insert variant HTML.
- *
- * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-export async function wrapCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable wrap [options]
-
-Find an element in source and wrap it in a variant container.
-
-Required:
- --id ID Session ID for the variant wrapper
- --count N Number of expected variants (1-8)
-
-Element identification (at least one required):
- --element-id ID HTML id attribute of the element
- --classes A,B,C Comma-separated CSS class names
- --tag TAG Tag name (div, section, etc.)
- --query TEXT Fallback: raw text to search for
-
-Optional:
- --file PATH Source file to search in (skips auto-detection)
- --text TEXT Picked element's textContent. Used to disambiguate when
- classes/tag match multiple sibling elements (e.g. a list
- of <Card>s with the same className). Pass the first ~80
- chars of event.element.textContent.
- --help Show this help message
-
-Output (JSON):
- { file, startLine, endLine, insertLine, commentSyntax }
-
-The agent should insert variant HTML at insertLine.`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const count = parseInt(argVal(args, '--count') || '3');
- const elementId = argVal(args, '--element-id');
- const classes = argVal(args, '--classes');
- const tag = argVal(args, '--tag');
- const query = argVal(args, '--query');
- const filePath = argVal(args, '--file');
- const text = argVal(args, '--text');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!elementId && !classes && !query) {
- console.error('Need at least one of: --element-id, --classes, --query');
- process.exit(1);
- }
-
- // Build search queries in priority order (most specific first)
- const queries = buildSearchQueries(elementId, classes, tag, query);
-
- const genOpts = { cwd: process.cwd() };
-
- // Find the source file. Generated files are excluded from auto-search so we
- // don't silently write variants into a file the next build will wipe.
- let targetFile = filePath;
- let matchedQuery = null;
- if (!targetFile) {
- for (const q of queries) {
- targetFile = findFileWithQuery(q, process.cwd(), genOpts);
- if (targetFile) { matchedQuery = q; break; }
- }
- if (!targetFile) {
- // Nothing in source. Did the element show up in a generated file? That
- // tells the agent "fall back to the agent-driven flow" vs "element just
- // doesn't exist in this project."
- let generatedHit = null;
- for (const q of queries) {
- generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
- if (generatedHit) break;
- }
- if (generatedHit) {
- console.error(JSON.stringify({
- error: 'element_not_in_source',
- fallback: 'agent-driven',
- generatedMatch: path.relative(process.cwd(), generatedHit),
- hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
- }));
- } else {
- console.error(JSON.stringify({
- error: 'element_not_found',
- fallback: 'agent-driven',
- hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
- }));
- }
- process.exit(1);
- }
- } else {
- if (isGeneratedFile(targetFile, genOpts)) {
- console.error(JSON.stringify({
- error: 'file_is_generated',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
- hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- matchedQuery = queries[0];
- }
-
- const content = fs.readFileSync(targetFile, 'utf-8');
- const lines = content.split('\n');
-
- // Find the element, trying each query in priority order. When `--text` is
- // supplied, collect every candidate the queries surface and disambiguate
- // by the picked element's textContent. Without `--text`, fall back to the
- // legacy first-match behavior so unmodified callers keep working.
- let match = null;
- if (text) {
- const candidates = [];
- for (const q of queries) {
- const all = findAllElements(lines, q, tag);
- for (const c of all) {
- if (!candidates.some((x) => x.startLine === c.startLine)) {
- candidates.push(c);
- }
- }
- // Once a more-specific query (ID, full className combo) yielded a unique
- // result, stop — falling through to the loose tag+single-class query
- // would readmit the siblings we just disambiguated past.
- if (candidates.length === 1) break;
- }
- if (candidates.length === 0) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- if (candidates.length === 1) {
- match = candidates[0];
- } else {
- const filtered = filterByText(candidates, lines, text);
- if (filtered.length === 1) {
- match = filtered[0];
- } else if (filtered.length === 0) {
- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the
- // browser-side textContent doesn't appear literally in source. Fall
- // back to first-match rather than refusing — this is the same
- // behavior unmodified callers see, just preserved.
- match = candidates[0];
- } else {
- // Multiple candidates ALSO match the text. Truly ambiguous — refuse
- // rather than pick wrong, and hand the agent the candidate locations
- // so it can disambiguate by reading the file.
- console.error(JSON.stringify({
- error: 'element_ambiguous',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), targetFile),
- candidates: filtered.map((c) => ({
- startLine: c.startLine + 1,
- endLine: c.endLine + 1,
- })),
- hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- }
- } else {
- for (const q of queries) {
- match = findElement(lines, q, tag);
- if (match) break;
- }
- if (!match) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- }
-
- const { startLine, endLine } = match;
- const commentSyntax = detectCommentSyntax(targetFile);
- const styleMode = detectStyleMode(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- const indent = lines[startLine].match(/^(\s*)/)[1];
-
- // Extract the original element. Reindent under the wrapper while preserving
- // the relative depth between lines — `l.trimStart()` would strip ALL leading
- // whitespace and collapse e.g. `<aside>`/` <h1>`/`</aside>` (6/8/6 spaces)
- // to a single uniform indent, so on accept/discard the round-trip restores
- // the inner element at its parent's depth instead of nested inside it.
- // Strip only the COMMON minimum leading whitespace across the picked lines;
- // `deindentContent` on the accept side already mirrors this convention.
- const originalLines = lines.slice(startLine, endLine + 1);
- const originalBaseIndent = minLeadingSpaces(originalLines);
- const reindentOriginal = (extra) => originalLines
- .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
- .join('\n');
- const originalIndented = reindentOriginal(' ');
-
- // Wrapper attributes differ by syntax. HTML allows plain string attrs;
- // JSX requires object-literal style and parses string attrs as HTML (which
- // either type-errors or renders a literal CSS string).
- const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
-
- // JSX/TSX guard: the picked element occupies a single JSX child slot
- // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
- // any other expression position). Replacing it with `comment + <div> +
- // comment` yields three adjacent siblings — invalid JSX. We can't use a
- // Fragment `<></>` either: parents that clone children (Radix `asChild`,
- // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
- // they try to pass an `id` through.
- //
- // Solution: keep the wrapper `<div>` as the single JSX-slot child and
- // tuck both marker comments INSIDE it. accept/discard then expands its
- // replacement range to include the wrapper's `<div>` open / close lines
- // so the entire scaffold gets removed cleanly.
- const wrapperLines = isJsx ? [
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- reindentOriginal(' '),
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- indent + '</div>',
- ] : [
- indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- originalIndented,
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + '</div>',
- indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- ];
-
- // Replace the original element with the wrapper
- const newLines = [
- ...lines.slice(0, startLine),
- ...wrapperLines,
- ...lines.slice(endLine + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- // Calculate insert line (the "insert below this line" comment).
- // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
- // the insert marker (HTML: start-comment + outer-div + Original-comment +
- // original-div + content + close-original-div; JSX: outer-div +
- // start-comment + Original-comment + original-div + content +
- // close-original-div). Multi-line originals push the marker by their
- // extra line count.
- const insertLine = startLine + 6 + (originalLines.length - 1);
-
- console.log(JSON.stringify({
- file: path.relative(process.cwd(), targetFile),
- startLine: startLine + 1, // 1-indexed for the agent
- // wrapperLines is an array but one element (the original-content slot)
- // is a `\n`-joined multi-line string, so the actual file-row count is
- // wrapperLines.length + (originalLines.length - 1). Without the offset,
- // endLine pointed inside the wrapper for any picked element that
- // spanned more than one source line.
- endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexed
- insertLine: insertLine + 1, // 1-indexed: where variants go
- commentSyntax: commentSyntax,
- styleMode: styleMode.mode,
- styleTag: styleMode.styleTag,
- cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
- cssAuthoring: buildCssAuthoring(styleMode, count),
- originalLineCount: originalLines.length,
- }));
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-/**
- * Build search query strings in priority order (most specific first).
- * ID is most reliable, then specific class combos, then single classes, then raw query.
- */
-function buildSearchQueries(elementId, classes, tag, query) {
- const queries = [];
-
- // 1. ID is the most specific
- if (elementId) {
- queries.push('id="' + elementId + '"');
- }
-
- // 2. Full class attribute match (for elements with distinctive multi-class combos).
- // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
- // convention the file uses will match.
- if (classes) {
- const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
- if (classList.length > 1) {
- const joined = classList.join(' ');
- const sorted = [...classList].sort((a, b) => b.length - a.length);
- queries.push('class="' + joined + '"');
- queries.push('className="' + joined + '"');
- queries.push(sorted[0]); // most distinctive single class, fallback
- } else if (classList.length === 1) {
- queries.push(classList[0]);
- }
- }
-
- // 3. Tag + class combo (e.g., <section class="hero">).
- // Same dual-emit for JSX compatibility.
- if (tag && classes) {
- const firstClass = classes.split(',')[0].trim();
- queries.push('<' + tag + ' class="' + firstClass);
- queries.push('<' + tag + ' className="' + firstClass);
- }
-
- // 4. Raw fallback query
- if (query) {
- queries.push(query);
- }
-
- return queries;
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- // HTML, Vue, Svelte, Astro all use HTML comments
- return { open: '<!--', close: '-->' };
-}
-
-function detectStyleMode(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.astro') {
- return {
- mode: 'astro-global-prefixed',
- styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',
- };
- }
- return {
- mode: 'scoped',
- styleTag: '<style data-impeccable-css="SESSION_ID">',
- };
-}
-
-function buildCssSelectorPrefixExamples(styleMode, count) {
- if (styleMode !== 'astro-global-prefixed') return [];
- return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);
-}
-
-function buildCssAuthoring(styleMode, count) {
- const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
- if (styleMode.mode === 'astro-global-prefixed') {
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'global-prefixed',
- rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',
- selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),
- requirements: [
- 'Use the styleTag exactly; the is:inline attribute is required for this file.',
- 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',
- 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
- ],
- forbidden: [
- 'Do not use @scope for this styleMode.',
- ],
- };
- }
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'scope-rule',
- rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',
- selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),
- requirements: [
- 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',
- 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
- 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
- ],
- forbidden: [
- 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',
- 'Do not add is:inline to the style tag for this styleMode.',
- ],
- };
-}
-
-/**
- * Search project files for the query string (class name, ID, etc.)
- * Returns the first matching file path, or null.
- */
-function findFileWithQuery(query, cwd, genOpts = {}) {
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, query, seen, 0, genOpts);
- if (result) return result;
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth, genOpts) {
- if (depth > 5) return null; // don't go too deep
- const realDir = fs.realpathSync(dir);
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- // Check files first
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name).toLowerCase();
- if (!EXTENSIONS.includes(ext)) continue;
-
- const filePath = path.join(dir, entry.name);
- if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip unreadable files */ }
- }
-
- // Then recurse into directories. Always skip node_modules and .git (never
- // project content). dist/build/out are left to the isGeneratedFile guard so
- // the includeGenerated second-pass can still find the element there and
- // report `generatedMatch`.
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
- if (result) return result;
- }
-
- return null;
-}
-
-/**
- * Regex that matches a tag opener on a line. Allows the tag name to be
- * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
- * openers (e.g. `<section\n className="..."\n>`) are recognised.
- */
-const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
-
-/**
- * Find the element's start and end line in the file.
- *
- * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
- * `id="..."`), or a raw text snippet. Because a query can appear on a
- * continuation line of a multi-line tag (e.g. the `className="..."` row of a
- * `<section\n className="..."\n>` JSX tag), we walk backward from the match
- * line to find the actual tag opener. When `tag` is provided, opener candidates
- * must match that tag name.
- */
-/**
- * Return the smallest leading-whitespace count across a set of lines,
- * ignoring blank lines (whose indent isn't load-bearing). Used to compute
- * the common base indent of a multi-line picked element so reindenting
- * under the wrapper preserves the relative depth between lines.
- */
-function minLeadingSpaces(lines) {
- let min = Infinity;
- for (const l of lines) {
- if (l.trim() === '') continue;
- const m = l.match(/^(\s*)/);
- if (m && m[1].length < min) min = m[1].length;
- }
- return min === Infinity ? 0 : min;
-}
-
-function findElement(lines, query, tag = null) {
- // Iterate all matches — the first substring hit isn't always the right one.
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
-
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- // Skip lines already inside a variant wrapper
- if (lines[i].includes('data-impeccable-variant')) continue;
-
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
-
- const endLine = findClosingLine(lines, openerLine);
- return { startLine: openerLine, endLine };
- }
-
- return null;
-}
-
-/**
- * Like findElement, but returns every match. Used for ambiguity detection
- * when the agent passes --text: when the same className appears on multiple
- * sibling elements (a list of cards, repeated section variants, etc.),
- * first-match silently lands on the wrong branch. Returning all matches lets
- * the caller narrow by textContent or fail with a structured ambiguity error.
- */
-function findAllElements(lines, query, tag = null) {
- const out = [];
- const seen = new Set();
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- if (lines[i].includes('data-impeccable-variant')) continue;
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
- if (seen.has(openerLine)) continue; // multiple matches inside the same element
- seen.add(openerLine);
- const endLine = findClosingLine(lines, openerLine);
- out.push({ startLine: openerLine, endLine });
- }
- return out;
-}
-
-/**
- * Narrow a candidate set to those whose source body matches a meaningful
- * prefix of the picked element's textContent. The compare strips tags and
- * JSX expressions, then checks two whitespace normalizations side-by-side:
- *
- * - single-space ("hero two second card body")
- * - no-whitespace ("herotwosecondcardbody")
- *
- * Both are needed because `el.textContent` concatenates sibling text without
- * inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
- * `"Hero TwoSecond…"`), while the source has whitespace between tags. If
- * EITHER normalization matches, the candidate keeps. A snippet shorter than
- * 8 chars after stripping is too weak to disambiguate — the caller falls
- * back to first-match.
- */
-function filterByText(candidates, lines, text) {
- const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
- // Too short to disambiguate. Return [] so the caller's `filtered.length
- // === 0` branch fires (fall back to first-match) — the previous
- // `candidates.slice()` return forced `filtered.length > 1` and surfaced
- // a spurious `element_ambiguous` error on every short-text picker event
- // with multiple candidates.
- if (trimmed.length < 8) return [];
- const targetSpaced = trimmed;
- const targetCompact = trimmed.replace(/\s+/g, '');
-
- return candidates.filter((c) => {
- const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
- const inner = body
- .replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
- .replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
- .toLowerCase();
- const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
- const sourceCompact = inner.replace(/\s+/g, '');
- return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
- });
-}
-
-/**
- * Resolve a match line to the real tag opener. If the match line itself opens
- * a tag, return it. Otherwise walk up to 10 lines backward looking for the
- * first tag opener. If `tag` is specified, the opener must match that tag
- * name; an opener with a different tag name aborts the backward walk for this
- * match (we don't jump across element boundaries).
- *
- * Returns the line index of the opener, or -1 if none can be resolved.
- */
-function findOpenerLine(lines, matchLine, tag) {
- const self = lines[matchLine].match(OPENER_RE);
- if (self) {
- if (!tag || self[1] === tag) return matchLine;
- return -1;
- }
- const MAX_BACKWALK = 10;
- for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
- const opener = lines[i].match(OPENER_RE);
- if (!opener) continue;
- if (!tag || opener[1] === tag) return i;
- // Different tag name than requested — abort; we're inside a non-target opener.
- return -1;
- }
- return -1;
-}
-
-/**
- * Starting from a line with an opening tag, find the line with the matching
- * closing tag by counting tag nesting depth.
- */
-function findClosingLine(lines, start) {
- const openMatch = lines[start].match(OPENER_RE);
- if (!openMatch) return start; // caller passed a non-opener; nothing to span
-
- const tagName = openMatch[1];
- let depth = 0;
- const openRe = new RegExp('<' + tagName + '(?=[\\s/>]|$)', 'g');
- const selfCloseRe = new RegExp('<' + tagName + '[^>]*/>', 'g');
- const closeRe = new RegExp('</' + tagName + '\\s*>', 'g');
-
- for (let i = start; i < lines.length; i++) {
- const line = lines[i];
- const opens = (line.match(openRe) || []).length;
- const selfCloses = (line.match(selfCloseRe) || []).length;
- const closes = (line.match(closeRe) || []).length;
-
- depth += opens - selfCloses - closes;
-
- if (depth <= 0) return i;
- }
-
- // If we can't find the close, return a reasonable guess
- return Math.min(start + 50, lines.length - 1);
-}
-
-// Auto-execute when run directly (node live-wrap.mjs ...)
-const _running = process.argv[1];
-if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {
- wrapCli();
-}
-
-// Test exports (used by tests/live-wrap.test.mjs)
-export { buildSearchQueries, findElement, findClosingLine, detectCommentSyntax };
@@ -1,247 +0,0 @@
-/**
- * CLI entry point: prepare everything needed to enter the live variant poll loop.
- *
- * Does (all in one command):
- * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)
- * 2. Start the live server in the background (or reuse a running one)
- * 3. Inject the browser script tag into the project's entry file
- * 4. Read PRODUCT.md / DESIGN.md for project context
- * 5. Print a single JSON blob with everything the agent needs
- *
- * After this, the agent's only remaining steps are:
- * - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll
- * - Enter the poll loop: `node live-poll.mjs`
- *
- * Usage:
- * node live.mjs # Prepare everything, print JSON, exit
- * node live.mjs --help
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { loadContext } from './load-context.mjs';
-import { resolveFiles } from './live-inject.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-async function liveCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live.mjs
-
-Prepare everything for live variant mode in a single command:
- - Checks .impeccable/live/config.json (required, created once per project)
- - Starts (or reuses) the live server in the background
- - Injects the browser script tag
- - Reads PRODUCT.md / DESIGN.md for project context
-
-On success, prints a JSON blob with:
- { ok, serverPort, serverToken, pageFile, hasContext, context }
-
-On config_missing, prints:
- { ok: false, error: "config_missing", configPath, hint }
-
-The agent should then:
- 1. If config_missing, create the config and re-run this script
- 2. Optionally open the project's dev/preview URL in the browser (see reference/live.md—not serverPort)
- 3. Enter the poll loop: node live-poll.mjs`);
- process.exit(0);
- }
-
- // 1. Check config (fail fast if missing — no point starting anything else)
- const checkOut = runScript('live-inject.mjs', ['--check']);
- const checkResult = safeParse(checkOut);
- if (!checkResult || !checkResult.ok) {
- console.log(JSON.stringify(checkResult || { ok: false, error: 'check_failed', raw: checkOut }));
- process.exit(0);
- }
-
- // 2. Start server (or reuse existing)
- const serverInfo = ensureServerRunning();
- if (!serverInfo) {
- console.log(JSON.stringify({ ok: false, error: 'server_start_failed' }));
- process.exit(1);
- }
-
- // 3. Inject the script tag at the current port
- const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)]);
- const injectResult = safeParse(injectOut);
- if (!injectResult || !injectResult.ok) {
- console.log(JSON.stringify({
- ok: false,
- error: 'inject_failed',
- detail: injectResult || injectOut,
- serverPort: serverInfo.port,
- }));
- process.exit(1);
- }
-
- // 4. Load PRODUCT.md + DESIGN.md context (auto-migrates legacy .impeccable.md)
- const ctx = loadContext(process.cwd());
-
- // 5. Compute drift-heal: compare resolved inject targets against the
- // project's HTML files. Orphans are HTML files not covered by config.
- // Warning only — the agent decides whether to act.
- const resolvedFiles = resolveFiles(process.cwd(), checkResult.config);
- const drift = scanForDrift(process.cwd(), resolvedFiles, checkResult.config);
-
- // 6. Emit everything the agent needs
- console.log(JSON.stringify({
- ok: true,
- serverPort: serverInfo.port,
- serverToken: serverInfo.token,
- pageFiles: resolvedFiles,
- configDrift: drift,
- hasProduct: ctx.hasProduct,
- product: ctx.product,
- productPath: ctx.productPath,
- hasDesign: ctx.hasDesign,
- design: ctx.design,
- designPath: ctx.designPath,
- migrated: ctx.migrated,
- }, null, 2));
-}
-
-/**
- * Drift-heal scan. Walks the project for HTML files under common
- * page-source directories (public/, src/, app/, pages/) and reports any
- * that aren't covered by the resolved inject targets. This is purely
- * advisory — the agent can ignore it, or suggest the user add the
- * orphans to config.files.
- *
- * Skipped if config.files already contains at least one glob pattern
- * covering everything in practice (signaled by the orphan count being 0).
- */
-function scanForDrift(rootDir, resolvedFiles, config) {
- const SCAN_ROOTS = ['public', 'src', 'app', 'pages'];
- const IGNORE_DIRS = new Set([
- 'node_modules', '.git', '.next', '.nuxt', '.svelte-kit', '.astro',
- '.turbo', '.vercel', '.cache', 'coverage', 'dist', 'build',
- ]);
-
- const resolvedSet = new Set(resolvedFiles.map((f) => f.split(path.sep).join('/')));
-
- // Files matching the user's `exclude` globs are intentional omissions,
- // not drift. Compile them to regexes so the orphan list stays signal.
- const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
- .map((p) => globToRegex(p));
- const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
-
- const orphans = [];
-
- const walk = (dir, relBase) => {
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
- for (const e of entries) {
- const rel = relBase ? `${relBase}/${e.name}` : e.name;
- if (e.isDirectory()) {
- if (IGNORE_DIRS.has(e.name) || e.name.startsWith('.')) continue;
- walk(path.join(dir, e.name), rel);
- } else if (e.isFile() && e.name.endsWith('.html')) {
- if (resolvedSet.has(rel)) continue;
- if (isUserExcluded(rel)) continue;
- orphans.push(rel);
- }
- }
- };
-
- for (const root of SCAN_ROOTS) {
- const abs = path.join(rootDir, root);
- if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
- walk(abs, root);
- }
- }
-
- if (orphans.length === 0) return null;
- const capped = orphans.slice(0, 20);
- return {
- orphans: capped,
- orphanCount: orphans.length,
- hint: `${orphans.length} HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like "public/**/*.html".`,
- };
-}
-
-/**
- * Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
- * to avoid a circular import (live-inject.mjs already imports nothing
- * from live.mjs). The two must stay in sync.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
- else { re += '.*'; i += 2; }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function runScript(name, args) {
- const scriptPath = path.join(__dirname, name);
- const cmd = `node "${scriptPath}" ${args.map(a => `"${a}"`).join(' ')}`;
- try {
- return execSync(cmd, { encoding: 'utf-8', cwd: process.cwd(), timeout: 15_000 });
- } catch (err) {
- // execSync throws on non-zero exit; return stdout if any
- return err.stdout || err.message || '';
- }
-}
-
-function safeParse(out) {
- try { return JSON.parse(String(out).trim()); } catch { return null; }
-}
-
-/**
- * Return { pid, port, token } for the running live server, starting one if needed.
- */
-function ensureServerRunning() {
- // Try to reuse an existing server
- try {
- const existing = readLiveServerInfo(process.cwd())?.info;
- if (existing && existing.pid) {
- try {
- process.kill(existing.pid, 0); // throws if dead
- return existing;
- } catch { /* stale PID file — the server script will clean it up */ }
- }
- } catch { /* no PID file */ }
-
- // Start a new server
- const out = runScript('live-server.mjs', ['--background']);
- return safeParse(out);
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live.mjs') || _running?.endsWith('live.mjs/')) {
- liveCli();
-}
@@ -1,141 +0,0 @@
-/**
- * Shared context loader for every impeccable command that needs to know
- * "who is this for" and "what does this look like".
- *
- * Input: project root (process.cwd()).
- *
- * Output (JSON to stdout):
- * {
- * hasProduct: boolean, // PRODUCT.md found (or auto-migrated)
- * product: string | null, // PRODUCT.md contents
- * productPath: string | null, // relative path
- * hasDesign: boolean, // DESIGN.md found
- * design: string | null, // DESIGN.md contents
- * designPath: string | null,
- * migrated: boolean, // true if we auto-renamed .impeccable.md -> PRODUCT.md
- * contextDir: string, // absolute path of the directory the files were found in
- * }
- *
- * Filename matching is case-insensitive for PRODUCT.md and DESIGN.md. The
- * Google DESIGN.md convention is uppercase at repo root; Kiro-style and
- * lowercase variants are also matched so users don't get punished for case.
- *
- * Lookup directory resolution (first match wins):
- * 1. process.env.IMPECCABLE_CONTEXT_DIR (absolute or relative to cwd)
- * 2. cwd, if PRODUCT.md / DESIGN.md / .impeccable.md is there (back-compat)
- * 3. Auto-fallback subdirectories of cwd: .agents/context/, then docs/
- * 4. cwd as a default "no context found" location
- *
- * Legacy `.impeccable.md` -> PRODUCT.md migration only fires at cwd root;
- * fallback directories are read-only as far as auto-rename is concerned.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
-const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
-const LEGACY_NAMES = ['.impeccable.md'];
-const FALLBACK_DIRS = ['.agents/context', 'docs'];
-
-/**
- * Resolve the directory that holds PRODUCT.md / DESIGN.md for
- * this project. Exported so other scripts (e.g. live-server.mjs) can read the
- * design files from the same location the loader uses.
- */
-export function resolveContextDir(cwd = process.cwd()) {
- // 1. Explicit override
- const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
- if (envDir && envDir.trim()) {
- const trimmed = envDir.trim();
- return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- }
-
- // 2. cwd wins if any canonical or legacy file is there. We check legacy too
- // so the auto-migration path in loadContext stays predictable.
- if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES, ...LEGACY_NAMES])) {
- return cwd;
- }
-
- // 3. Auto-fallback subdirs. Match if PRODUCT.md or DESIGN.md is present;
- // legacy `.impeccable.md` does not pull the lookup into a fallback dir.
- for (const rel of FALLBACK_DIRS) {
- const candidate = path.resolve(cwd, rel);
- if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
- return candidate;
- }
- }
-
- // 4. Nothing found — keep the historical "default to cwd" behaviour so the
- // caller's `hasProduct === false` branch still fires the same way.
- return cwd;
-}
-
-export function loadContext(cwd = process.cwd()) {
- let migrated = false;
- const contextDir = resolveContextDir(cwd);
-
- // 1. Look for PRODUCT.md (case-insensitive) in the resolved dir
- let productPath = firstExisting(contextDir, PRODUCT_NAMES);
-
- // 2. Legacy: if no PRODUCT.md but .impeccable.md exists at cwd root, rename
- // it in place. We only migrate at the root — fallback dirs are read-only
- // so we don't surprise users by mutating files under docs/ or .agents/.
- if (!productPath && contextDir === cwd) {
- const legacyPath = firstExisting(cwd, LEGACY_NAMES);
- if (legacyPath) {
- const newPath = path.join(cwd, 'PRODUCT.md');
- try {
- fs.renameSync(legacyPath, newPath);
- productPath = newPath;
- migrated = true;
- } catch {
- // Rename failed (permissions, etc.) — fall back to reading legacy in place
- productPath = legacyPath;
- }
- }
- }
-
- // 3. DESIGN.md (case-insensitive)
- const designPath = firstExisting(contextDir, DESIGN_NAMES);
-
- const product = productPath ? safeRead(productPath) : null;
- const design = designPath ? safeRead(designPath) : null;
-
- return {
- hasProduct: !!product,
- product,
- productPath: productPath ? path.relative(cwd, productPath) : null,
- hasDesign: !!design,
- design,
- designPath: designPath ? path.relative(cwd, designPath) : null,
- migrated,
- contextDir,
- };
-}
-
-function firstExisting(dir, names) {
- for (const name of names) {
- const abs = path.join(dir, name);
- if (fs.existsSync(abs)) return abs;
- }
- return null;
-}
-
-function safeRead(p) {
- try { return fs.readFileSync(p, 'utf-8'); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// CLI mode — print the context as JSON
-// ---------------------------------------------------------------------------
-
-function cli() {
- const result = loadContext(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('load-context.mjs') || _running?.endsWith('load-context.mjs/')) {
- cli();
-}
@@ -1,14 +0,0 @@
@@ -1,214 +0,0 @@
-#!/usr/bin/env node
-/**
- * Pin/unpin sub-commands as standalone skill shortcuts.
- *
- * Usage:
- * node <scripts_path>/pin.mjs pin <command>
- * node <scripts_path>/pin.mjs unpin <command>
- *
- * `pin audit` creates a lightweight /audit skill that redirects to /impeccable audit.
- * `unpin audit` removes that shortcut.
- *
- * The script discovers harness directories (.claude/skills, .cursor/skills, etc.)
- * in the project root and creates/removes the pin in all of them.
- */
-
-import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
-import { join, resolve, dirname } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-// All known harness directories
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Valid sub-command names
-const VALID_COMMANDS = [
- 'craft', 'teach', 'extract', 'document', 'shape',
- 'critique', 'audit',
- 'polish', 'bolder', 'quieter', 'distill', 'harden', 'onboard', 'live',
- 'animate', 'colorize', 'typeset', 'layout', 'delight', 'overdrive',
- 'clarify', 'adapt', 'optimize',
-];
-
-// Marker to identify pinned skills (so unpin doesn't delete user skills)
-const PIN_MARKER = '<!-- impeccable-pinned-skill -->';
-
-/**
- * Walk up from startDir to find a project root.
- */
-function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- while (dir !== '/') {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Find harness skill directories that have an impeccable skill installed.
- */
-function findHarnessDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const skillsDir = join(projectRoot, harness, 'skills');
- // Only pin in harness dirs that already have impeccable installed
- const impeccableDir = join(skillsDir, 'impeccable');
- if (existsSync(impeccableDir) || existsSync(join(skillsDir, 'i-impeccable'))) {
- dirs.push(skillsDir);
- }
- }
- return dirs;
-}
-
-/**
- * Load command metadata (descriptions for pinned skills).
- */
-function loadCommandMetadata() {
- const metadataPath = join(__dirname, 'command-metadata.json');
- if (existsSync(metadataPath)) {
- return JSON.parse(readFileSync(metadataPath, 'utf-8'));
- }
- return {};
-}
-
-/**
- * Generate a pinned skill's SKILL.md content.
- */
-function generatePinnedSkill(command, metadata) {
- const desc = metadata[command]?.description || `Shortcut for /impeccable ${command}.`;
- const hint = metadata[command]?.argumentHint || '[target]';
-
- return `---
-name: ${command}
-description: "${desc}"
-argument-hint: "${hint}"
-user-invocable: true
----
-
-${PIN_MARKER}
-
-This is a pinned shortcut for \`{{command_prefix}}impeccable ${command}\`.
-
-Invoke {{command_prefix}}impeccable ${command}, passing along any arguments provided here, and follow its instructions.
-`;
-}
-
-/**
- * Pin a command: create shortcut skill in all harness dirs.
- */
-function pin(command, projectRoot) {
- const metadata = loadCommandMetadata();
- const harnessDirs = findHarnessDirs(projectRoot);
-
- if (harnessDirs.length === 0) {
- console.log('No harness directories with impeccable installed found.');
- return false;
- }
-
- const content = generatePinnedSkill(command, metadata);
- let created = 0;
-
- for (const skillsDir of harnessDirs) {
- // Check if skill already exists (and isn't a pin)
- const skillDir = join(skillsDir, command);
- if (existsSync(skillDir)) {
- const existingMd = join(skillDir, 'SKILL.md');
- if (existsSync(existingMd)) {
- const existing = readFileSync(existingMd, 'utf-8');
- if (!existing.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (non-pinned skill already exists)`);
- continue;
- }
- }
- }
-
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(join(skillDir, 'SKILL.md'), content, 'utf-8');
- console.log(` + ${skillDir}`);
- created++;
- }
-
- if (created > 0) {
- console.log(`\nPinned '${command}' as a standalone shortcut in ${created} location(s).`);
- console.log(`You can now use /${command} directly.`);
- }
-
- return created > 0;
-}
-
-/**
- * Unpin a command: remove shortcut skill from all harness dirs.
- */
-function unpin(command, projectRoot) {
- const harnessDirs = findHarnessDirs(projectRoot);
- let removed = 0;
-
- for (const skillsDir of harnessDirs) {
- const skillDir = join(skillsDir, command);
- if (!existsSync(skillDir)) continue;
-
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) continue;
-
- // Safety: only remove if it's a pinned skill
- const content = readFileSync(skillMd, 'utf-8');
- if (!content.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (not a pinned skill)`);
- continue;
- }
-
- rmSync(skillDir, { recursive: true, force: true });
- console.log(` - ${skillDir}`);
- removed++;
- }
-
- if (removed > 0) {
- console.log(`\nUnpinned '${command}' from ${removed} location(s).`);
- console.log(`Use /impeccable ${command} to access it.`);
- } else {
- console.log(`No pinned '${command}' shortcut found.`);
- }
-
- return removed > 0;
-}
-
-// --- CLI ---
-const [,, action, command] = process.argv;
-
-if (!action || !command) {
- console.log('Usage: node pin.mjs <pin|unpin> <command>');
- console.log(`\nAvailable commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-if (action !== 'pin' && action !== 'unpin') {
- console.error(`Unknown action: ${action}. Use 'pin' or 'unpin'.`);
- process.exit(1);
-}
-
-if (!VALID_COMMANDS.includes(command)) {
- console.error(`Unknown command: ${command}`);
- console.error(`Available commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-const root = findProjectRoot();
-
-if (action === 'pin') {
- pin(command, root);
-} else {
- unpin(command, root);
-}
@@ -1,167 +0,0 @@
----
-name: impeccable
-description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
-version: 3.1.1
-license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
-allowed-tools:
- - Bash(npx impeccable *)
----
-
-Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
-
-## Setup
-
-Before any design work or file edits:
-
-1. Load context (PRODUCT.md / DESIGN.md) via the loader script.
-2. Identify the register and load the matching register reference (brand.md or product.md).
-3. **If the user invoked a sub-command (e.g. `craft`, `shape`, `audit`), load its reference file too.** This is non-negotiable: `craft` without `craft.md` loaded means you'll skip the shape-and-confirm step the user expects.
-
-Skipping these produces generic output that ignores the project.
-
-### 1. Context gathering
-
-Two files, case-insensitive. The loader looks at the project root by default and falls back to `.agents/context/` and `docs/` if the root is clean. Override with `IMPECCABLE_CONTEXT_DIR=path/to/dir` (absolute or relative to cwd).
-
-- **PRODUCT.md**: required. Users, brand, tone, anti-references, strategic principles.
-- **DESIGN.md**: optional, strongly recommended. Colors, typography, elevation, components.
-
-Load both in one call:
-
-```bash
-node .pi/skills/impeccable/scripts/load-context.mjs
-```
-
-Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`. The output's `contextDir` field tells you where the files were resolved from.
-
-If the output is already in this session's conversation history, don't re-run. Exceptions requiring a fresh load: you just ran `/impeccable teach` or `/impeccable document` (they rewrite the files), or the user manually edited one.
-
-`/impeccable live` already warms context via `live.mjs`. If you've run `live.mjs`, don't also run `load-context.mjs` this session.
-
-If PRODUCT.md is missing, empty, or placeholder (`[TODO]` markers, <200 chars): run `/impeccable teach`, then resume the user's original task with the fresh context. If the original task was `/impeccable craft`, resume into `/impeccable shape` before any implementation work.
-
-If DESIGN.md is missing: nudge once per session (*"Run `/impeccable document` for more on-brand output"*), then proceed.
-
-### 2. Register
-
-Every design task is **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboard, tool: design SERVES the product).
-
-Identify before designing. Priority: (1) cue in the task itself ("landing page" vs "dashboard"); (2) the surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. First match wins.
-
-If PRODUCT.md lacks the `register` field (legacy), infer it once from its "Users" and "Product Purpose" sections, then cache the inferred value for the session. Suggest the user run `/impeccable teach` to add the field explicitly.
-
-Load the matching reference: [reference/brand.md](reference/brand.md) or [reference/product.md](reference/product.md). The shared design laws below apply to both.
-
-## Shared design laws
-
-Apply to every design, both registers. Match implementation complexity to the aesthetic vision: maximalism needs elaborate code, minimalism needs precision. Interpret creatively. Vary across projects; never converge on the same choices. the model is capable of extraordinary work. Don't hold back.
-
-### Color
-
-- Use OKLCH. Reduce chroma as lightness approaches 0 or 100; high chroma at extremes looks garish.
-- Never use `#000` or `#fff`. Tint every neutral toward the brand hue (chroma 0.005–0.01 is enough).
-- Pick a **color strategy** before picking colors. Four steps on the commitment axis:
- - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism.
- - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages.
- - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz.
- - **Drenched**: the surface IS the color. Brand heroes, campaign pages.
-- The "one accent ≤10%" rule is Restrained only. Committed / Full palette / Drenched exceed it on purpose. Don't collapse every design to Restrained by reflex.
-
-### Theme
-
-Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe."
-
-Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does.
-
-"Observability dashboard" does not force an answer. "SRE glancing at incident severity on a 27-inch monitor at 2am in a dim room" does. Run the sentence, not the category.
-
-### Typography
-
-- Cap body line length at 65–75ch.
-- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales.
-
-### Layout
-
-- Vary spacing for rhythm. Same padding everywhere is monotony.
-- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
-- Don't wrap everything in a container. Most things don't need one.
-
-### Motion
-
-- Don't animate CSS layout properties.
-- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
-
-### Absolute bans
-
-Match-and-refuse. If you're about to write any of these, rewrite the element with different structure.
-
-- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing.
-- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size.
-- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing.
-- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché.
-- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly.
-- **Modal as first thought.** Modals are usually laziness. Exhaust inline / progressive alternatives first.
-
-### Copy
-
-- Every word earns its place. No restated headings, no intros that repeat the title.
-- **No em dashes.** Use commas, colons, semicolons, periods, or parentheses. Also not `--`.
-
-### The AI slop test
-
-If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference.
-
-**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses.
-
-- **First-order:** if someone could guess the theme + palette from the category alone ("observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black"), it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
-- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families.
-
-## Commands
-
-| Command | Category | Description | Reference |
-|---|---|---|---|
-| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) |
-| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) |
-| `teach` | Build | Set up PRODUCT.md and DESIGN.md context | [reference/teach.md](reference/teach.md) |
-| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) |
-| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) |
-| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) |
-| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) |
-| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) |
-| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) |
-| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) |
-| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) |
-| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) |
-| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) |
-| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) |
-| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) |
-| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) |
-| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) |
-| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) |
-| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) |
-| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) |
-| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) |
-| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
-| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
-
-### Routing rules
-
-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
-3. **First word doesn't match**: general design invocation. Apply the setup steps, shared design laws, and the loaded register reference, using the full argument as context.
-
-Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `/impeccable`.
-
-If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `teach` as a blocker, finish teach, refresh context, then resume the original command and target.
-
-## Pin / Unpin
-
-**Pin** creates a standalone shortcut so `/<command>` invokes `/impeccable <command>` directly. **Unpin** removes it. The script writes to every harness directory present in the project.
-
-```bash
-node .pi/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
-```
-
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
@@ -1,190 +0,0 @@
-> **Additional context needed**: target platforms/devices and usage contexts.
-
-Adapt an existing design to a different context: another screen size, device, platform, or use case. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context.
-
-
----
-
-## Assess Adaptation Challenge
-
-Understand what needs adaptation and why:
-
-1. **Identify the source context**:
- - What was it designed for originally? (Desktop web? Mobile app?)
- - What assumptions were made? (Large screen? Mouse input? Fast connection?)
- - What works well in current context?
-
-2. **Understand target context**:
- - **Device**: Mobile, tablet, desktop, TV, watch, print?
- - **Input method**: Touch, mouse, keyboard, voice, gamepad?
- - **Screen constraints**: Size, resolution, orientation?
- - **Connection**: Fast wifi, slow 3G, offline?
- - **Usage context**: On-the-go vs desk, quick glance vs focused reading?
- - **User expectations**: What do users expect on this platform?
-
-3. **Identify adaptation challenges**:
- - What won't fit? (Content, navigation, features)
- - What won't work? (Hover states on touch, tiny touch targets)
- - What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop)
-
-**CRITICAL**: Adaptation is rethinking the experience for the new context, not scaling pixels.
-
-## Plan Adaptation Strategy
-
-Create context-appropriate strategy:
-
-### Mobile Adaptation (Desktop → Mobile)
-
-**Layout Strategy**:
-- Single column instead of multi-column
-- Vertical stacking instead of side-by-side
-- Full-width components instead of fixed widths
-- Bottom navigation instead of top/side navigation
-
-**Interaction Strategy**:
-- Touch targets 44x44px minimum (not hover-dependent)
-- Swipe gestures where appropriate (lists, carousels)
-- Bottom sheets instead of dropdowns
-- Thumbs-first design (controls within thumb reach)
-- Larger tap areas with more spacing
-
-**Content Strategy**:
-- Progressive disclosure (don't show everything at once)
-- Prioritize primary content (secondary content in tabs/accordions)
-- Shorter text (more concise)
-- Larger text (16px minimum)
-
-**Navigation Strategy**:
-- Hamburger menu or bottom navigation
-- Reduce navigation complexity
-- Sticky headers for context
-- Back button in navigation flow
-
-### Tablet Adaptation (Hybrid Approach)
-
-**Layout Strategy**:
-- Two-column layouts (not single or three-column)
-- Side panels for secondary content
-- Master-detail views (list + detail)
-- Adaptive based on orientation (portrait vs landscape)
-
-**Interaction Strategy**:
-- Support both touch and pointer
-- Touch targets 44x44px but allow denser layouts than phone
-- Side navigation drawers
-- Multi-column forms where appropriate
-
-### Desktop Adaptation (Mobile → Desktop)
-
-**Layout Strategy**:
-- Multi-column layouts (use horizontal space)
-- Side navigation always visible
-- Multiple information panels simultaneously
-- Fixed widths with max-width constraints (don't stretch to 4K)
-
-**Interaction Strategy**:
-- Hover states for additional information
-- Keyboard shortcuts
-- Right-click context menus
-- Drag and drop where helpful
-- Multi-select with Shift/Cmd
-
-**Content Strategy**:
-- Show more information upfront (less progressive disclosure)
-- Data tables with many columns
-- Richer visualizations
-- More detailed descriptions
-
-### Print Adaptation (Screen → Print)
-
-**Layout Strategy**:
-- Page breaks at logical points
-- Remove navigation, footer, interactive elements
-- Black and white (or limited color)
-- Proper margins for binding
-
-**Content Strategy**:
-- Expand shortened content (show full URLs, hidden sections)
-- Add page numbers, headers, footers
-- Include metadata (print date, page title)
-- Convert charts to print-friendly versions
-
-### Email Adaptation (Web → Email)
-
-**Layout Strategy**:
-- Narrow width (600px max)
-- Single column only
-- Inline CSS (no external stylesheets)
-- Table-based layouts (for email client compatibility)
-
-**Interaction Strategy**:
-- Large, obvious CTAs (buttons not text links)
-- No hover states (not reliable)
-- Deep links to web app for complex interactions
-
-## Implement Adaptations
-
-Apply changes systematically:
-
-### Responsive Breakpoints
-
-Choose appropriate breakpoints:
-- Mobile: 320px-767px
-- Tablet: 768px-1023px
-- Desktop: 1024px+
-- Or content-driven breakpoints (where design breaks)
-
-### Layout Adaptation Techniques
-
-- **CSS Grid/Flexbox**: Reflow layouts automatically
-- **Container Queries**: Adapt based on container, not viewport
-- **`clamp()`**: Fluid sizing between min and max
-- **Media queries**: Different styles for different contexts
-- **Display properties**: Show/hide elements per context
-
-### Touch Adaptation
-
-- Increase touch target sizes (44x44px minimum)
-- Add more spacing between interactive elements
-- Remove hover-dependent interactions
-- Add touch feedback (ripples, highlights)
-- Consider thumb zones (easier to reach bottom than top)
-
-### Content Adaptation
-
-- Use `display: none` sparingly (still downloads)
-- Progressive enhancement (core content first, enhancements on larger screens)
-- Lazy loading for off-screen content
-- Responsive images (`srcset`, `picture` element)
-
-### Navigation Adaptation
-
-- Transform complex nav to hamburger/drawer on mobile
-- Bottom nav bar for mobile apps
-- Persistent side navigation on desktop
-- Breadcrumbs on smaller screens for context
-
-**IMPORTANT**: Test on real devices. Device emulation in DevTools is helpful but not perfect.
-
-**NEVER**:
-- Hide core functionality on mobile (if it matters, make it work)
-- Assume desktop = powerful device (consider accessibility, older machines)
-- Use different information architecture across contexts (confusing)
-- Break user expectations for platform (mobile users expect mobile patterns)
-- Forget landscape orientation on mobile/tablet
-- Use generic breakpoints blindly (use content-driven breakpoints)
-- Ignore touch on desktop (many desktop devices have touch)
-
-## Verify Adaptations
-
-Test thoroughly across contexts:
-
-- **Real devices**: Test on actual phones, tablets, desktops
-- **Different orientations**: Portrait and landscape
-- **Different browsers**: Safari, Chrome, Firefox, Edge
-- **Different OS**: iOS, Android, Windows, macOS
-- **Different input methods**: Touch, mouse, keyboard
-- **Edge cases**: Very small screens (320px), very large screens (4K)
-- **Slow connections**: Test on throttled network
-
-When the adaptation feels native to each context, hand off to `/impeccable polish` for the final pass.
@@ -1,175 +0,0 @@
-> **Additional context needed**: performance constraints.
-
-Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it.
-
----
-
-## Register
-
-Brand: orchestrated page-load sequences, staggered reveals, scroll-driven animation. Motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions.
-
-Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it.
-
----
-
-## Assess Animation Opportunities
-
-Analyze where motion would improve the experience:
-
-1. **Identify static areas**:
- - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.)
- - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes)
- - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious
- - **Lack of delight**: Functional but joyless interactions
- - **Missed guidance**: Opportunities to direct attention or explain behavior
-
-2. **Understand the context**:
- - What's the personality? (Playful vs serious, energetic vs calm)
- - What's the performance budget? (Mobile-first? Complex page?)
- - Who's the audience? (Motion-sensitive users? Power users who want speed?)
- - What matters most? (One hero animation vs many micro-interactions?)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them.
-
-## Plan Animation Strategy
-
-Create a purposeful animation plan:
-
-- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?)
-- **Feedback layer**: Which interactions need acknowledgment?
-- **Transition layer**: Which state changes need smoothing?
-- **Delight layer**: Where can we surprise and delight?
-
-**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments.
-
-## Implement Animations
-
-Add motion systematically across these categories:
-
-### Entrance Animations
-- **Page load choreography**: Stagger element reveals (100-150ms delays), fade + slide combinations
-- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects)
-- **Content reveals**: Scroll-triggered animations using intersection observer
-- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management
-
-### Micro-interactions
-- **Button feedback**:
- - Hover: Subtle scale (1.02-1.05), color shift, shadow increase
- - Click: Quick scale down then up (0.95 → 1), ripple effect
- - Loading: Spinner or pulse state
-- **Form interactions**:
- - Input focus: Border color transition, slight scale or glow
- - Validation: Shake on error, check mark on success, smooth color transitions
-- **Toggle switches**: Smooth slide + color transition (200-300ms)
-- **Checkboxes/radio**: Check mark animation, ripple effect
-- **Like/favorite**: Scale + rotation, particle effects, color transition
-
-### State Transitions
-- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms)
-- **Expand/collapse**: Height transition with overflow handling, icon rotation
-- **Loading states**: Skeleton screen fades, spinner animations, progress bars
-- **Success/error**: Color transitions, icon animations, gentle scale pulse
-- **Enable/disable**: Opacity transitions, cursor changes
-
-### Navigation & Flow
-- **Page transitions**: Crossfade between routes, shared element transitions
-- **Tab switching**: Slide indicator, content fade/slide
-- **Carousel/slider**: Smooth transforms, snap points, momentum
-- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators
-
-### Feedback & Guidance
-- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights
-- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning
-- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation
-- **Focus flow**: Highlight path through form or workflow
-
-### Delight Moments
-- **Empty states**: Subtle floating animations on illustrations
-- **Completed actions**: Confetti, check mark flourish, success celebrations
-- **Easter eggs**: Hidden interactions for discovery
-- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches
-
-## Technical Implementation
-
-Use appropriate techniques for each animation:
-
-### Timing & Easing
-
-**Durations by purpose:**
-- **100-150ms**: Instant feedback (button press, toggle)
-- **200-300ms**: State changes (hover, menu open)
-- **300-500ms**: Layout changes (accordion, modal)
-- **500-800ms**: Entrance animations (page load)
-
-**Easing curves (use these, not CSS defaults):**
-```css
-/* Recommended: natural deceleration */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */
-
-/* AVOID: feel dated and tacky */
-/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */
-/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */
-```
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-### CSS Animations
-```css
-/* Prefer for simple, declarative animations */
-- transitions for state changes
-- @keyframes for complex sequences
-- transform and opacity for reliable movement
-- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth
-```
-
-### JavaScript Animation
-```javascript
-/* Use for complex, interactive animations */
-- Web Animations API for programmatic control
-- Framer Motion for React
-- GSAP for complex sequences
-```
-
-### Performance
-- **Motion materials**: Use transform/opacity for reliable movement, but use blur, filters, masks, shadows, and color shifts when they materially improve the effect
-- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- **will-change**: Add sparingly for known expensive animations
-- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate
-- **Monitor FPS**: Ensure 60fps on target devices
-
-### Accessibility
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**NEVER**:
-- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself
-- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work
-- Use durations over 500ms for feedback (it feels laggy)
-- Animate without purpose (every animation needs a reason)
-- Ignore `prefers-reduced-motion` (this is an accessibility violation)
-- Animate everything (animation fatigue makes interfaces feel exhausting)
-- Block interaction during animations unless intentional
-
-## Verify Quality
-
-Test animations thoroughly:
-
-- **Smooth at 60fps**: No jank on target devices
-- **Feels natural**: Easing curves feel organic, not robotic
-- **Appropriate timing**: Not too fast (jarring) or too slow (laggy)
-- **Reduced motion works**: Animations disabled or simplified appropriately
-- **Doesn't block**: Users can interact during/after animations
-- **Adds value**: Makes interface clearer or more delightful
-
-When the motion clarifies state instead of decorating it, hand off to `/impeccable polish` for the final pass.
@@ -1,133 +0,0 @@
-Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues; document them for other commands to address.
-
-This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation.
-
-## Diagnostic Scan
-
-Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below.
-
-### 1. Accessibility (A11y)
-
-**Check for**:
-- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA)
-- **Missing ARIA**: Interactive elements without proper roles, labels, or states
-- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps
-- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons
-- **Alt text**: Missing or poor image descriptions
-- **Form issues**: Inputs without labels, poor error messaging, missing required indicators
-
-**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA)
-
-### 2. Performance
-
-**Check for**:
-- **Layout thrashing**: Reading/writing layout properties in loops
-- **Expensive animations**: Casual layout-property animation, unbounded blur/filter/shadow effects, or effects that visibly drop frames
-- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change
-- **Bundle size**: Unnecessary imports, unused dependencies
-- **Render performance**: Unnecessary re-renders, missing memoization
-
-**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized)
-
-### 3. Theming
-
-**Check for**:
-- **Hard-coded colors**: Colors not using design tokens
-- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme
-- **Inconsistent tokens**: Using wrong tokens, mixing token types
-- **Theme switching issues**: Values that don't update on theme change
-
-**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly)
-
-### 4. Responsive Design
-
-**Check for**:
-- **Fixed widths**: Hard-coded widths that break on mobile
-- **Touch targets**: Interactive elements < 44x44px
-- **Horizontal scroll**: Content overflow on narrow viewports
-- **Text scaling**: Layouts that break when text size increases
-- **Missing breakpoints**: No mobile/tablet variants
-
-**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets)
-
-### 5. Anti-Patterns (CRITICAL)
-
-Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy).
-
-**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design)
-
-## Generate Report
-
-### Audit Health Score
-
-| # | Dimension | Score | Key Finding |
-|---|-----------|-------|-------------|
-| 1 | Accessibility | ? | [most critical a11y issue or "--"] |
-| 2 | Performance | ? | |
-| 3 | Responsive Design | ? | |
-| 4 | Theming | ? | |
-| 5 | Anti-Patterns | ? | |
-| **Total** | | **??/20** | **[Rating band]** |
-
-**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues)
-
-### Anti-Patterns Verdict
-**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest.
-
-### Executive Summary
-- Audit Health Score: **??/20** ([rating band])
-- Total issues found (count by severity: P0/P1/P2/P3)
-- Top 3-5 critical issues
-- Recommended next steps
-
-### Detailed Findings by Severity
-
-Tag every issue with **P0-P3 severity**:
-- **P0 Blocking**: Prevents task completion. Fix immediately
-- **P1 Major**: Significant difficulty or WCAG AA violation. Fix before release
-- **P2 Minor**: Annoyance, workaround exists. Fix in next pass
-- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits
-
-For each issue, document:
-- **[P?] Issue name**
-- **Location**: Component, file, line
-- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern
-- **Impact**: How it affects users
-- **WCAG/Standard**: Which standard it violates (if applicable)
-- **Recommendation**: How to fix it
-- **Suggested command**: Which command to use (prefer: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-### Patterns & Systemic Issues
-
-Identify recurring problems that indicate systemic gaps rather than one-off mistakes:
-- "Hard-coded colors appear in 15+ components, should use design tokens"
-- "Touch targets consistently too small (<44px) throughout mobile experience"
-
-### Positive Findings
-
-Note what's working well: good practices to maintain and replicate.
-
-## Recommended Actions
-
-List recommended commands in priority order (P0 first, then P1, then P2):
-
-1. **[P?] `/command-name`**: Brief description (specific context from audit findings)
-2. **[P?] `/command-name`**: Brief description (specific context)
-
-**Rules**: Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset. Map findings to the most appropriate command. End with `/impeccable polish` as the final step if any fixes were recommended.
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable audit` after fixes to see your score improve.
-
-**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters.
-
-**NEVER**:
-- Report issues without explaining impact (why does this matter?)
-- Provide generic recommendations (be specific and actionable)
-- Skip positive findings (celebrate what works)
-- Forget to prioritize (everything can't be P0)
-- Report false positives without verification
-
@@ -1,113 +0,0 @@
-When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact and personality through stronger hierarchy, committed scale, and decisive type.
-
----
-
-## Register
-
-Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
-
-Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too safe or boring:
-
-1. **Identify weakness sources**:
- - **Generic choices**: System fonts, basic colors, standard layouts
- - **Timid scale**: Everything is medium-sized with no drama
- - **Low contrast**: Everything has similar visual weight
- - **Static**: No motion, no energy, no life
- - **Predictable**: Standard patterns with no surprises
- - **Flat hierarchy**: Nothing stands out or commands attention
-
-2. **Understand the context**:
- - What's the brand personality? (How far can we push?)
- - What's the purpose? (Marketing can be bolder than financial dashboards)
- - Who's the audience? (What will resonate?)
- - What are the constraints? (Brand guidelines, accessibility, performance)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
-
-**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
-
-## Plan Amplification
-
-Create a strategy to increase impact while maintaining coherence:
-
-- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
-- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
-- **Risk budget**: How experimental can we be? Push boundaries within constraints.
-- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
-
-**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration.
-
-## Amplify the Design
-
-Systematically increase impact across these dimensions:
-
-### Typography Amplification
-- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and [typography.md](typography.md) for inspiration)
-- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
-- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
-- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
-
-### Color Intensification
-- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
-- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop
-- **Dominant color strategy**: Let one bold color own 60% of the design
-- **Sharp accents**: High-contrast accent colors that pop
-- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
-- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
-
-### Spatial Drama
-- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
-- **Break the grid**: Let hero elements escape containers and cross boundaries
-- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
-- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
-- **Overlap**: Layer elements intentionally for depth
-
-### Visual Effects
-- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
-- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
-- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop)
-- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
-- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
-
-### Motion & Animation
-- **Entrance choreography**: Staggered, dramatic page load animations with 50-100ms delays
-- **Scroll effects**: Parallax, reveal animations, scroll-triggered sequences
-- **Micro-interactions**: Satisfying hover effects, click feedback, state changes
-- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect)
-
-### Composition Boldness
-- **Hero moments**: Create clear focal points with dramatic treatment
-- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
-- **Full-bleed elements**: Use full viewport width/height for impact
-- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
-
-**NEVER**:
-- Add effects randomly without purpose (chaos ≠ bold)
-- Sacrifice readability for aesthetics (body text must be readable)
-- Make everything bold (then nothing is bold; you need contrast)
-- Ignore accessibility (bold design must still meet WCAG standards)
-- Overwhelm with motion (animation fatigue is real)
-- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
-
-## Verify Quality
-
-Ensure amplification maintains usability and coherence:
-
-- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over.
-- **Still functional**: Can users accomplish tasks without distraction?
-- **Coherent**: Does everything feel intentional and unified?
-- **Memorable**: Will users remember this experience?
-- **Performant**: Do all these effects run smoothly?
-- **Accessible**: Does it still meet accessibility standards?
-
-**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects."
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,118 +0,0 @@
-# Brand register
-
-When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made.
-
-The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look.
-
-## The brand slop test
-
-If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?"
-
-Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home.
-
-**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register.
-
-Then the inverse test: in one sentence, describe what you're about to build the way a competitor would describe theirs. If that sentence fits the modal landing page in the category, restart.
-
-## Typography
-
-### Font selection procedure
-
-Every project. Never skip.
-
-1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words.
-2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture.
-3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy."
-4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over.
-
-### Reflex-reject list
-
-Training-data defaults. Ban list. Look further:
-
-Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif
-
-### Reflex-reject aesthetic lanes
-
-Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further.
-
-- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery.
-
-(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.)
-
-The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md).
-
-### Pairing and voice
-
-Distinctive + refined is the goal. The specific shape depends on the brand:
-
-- **Editorial / long-form / luxury**: display serif + sans body (a magazine shape).
-- **Tech / dev tools / fintech**: one committed sans, usually; custom-tight tracking, strong weight contrast inside a single family.
-- **Consumer / food / travel**: warmer pairings, often a humanist sans plus a script or display serif.
-- **Creative studios / agencies**: rule-breaking welcome. Mono-only, or display-only, or custom-drawn type as voice.
-
-Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair.
-
-Vary across projects. If the last brief was a serif-display landing page, this one isn't.
-
-### Scale
-
-Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted.
-
-Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room.
-
-## Color
-
-Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register.
-
-- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige.
-- Palette IS voice. A calm brand and a restless brand should not share palette mechanics.
-- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit.
-- Don't converge across projects. If the last brand surface was restrained-on-cream, this one is not.
-- When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette.
-
-## Layout
-
-- Asymmetric compositions are one option. Break the grid intentionally for emphasis.
-- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings.
-- Alternative: a strict, visible grid as the voice (brutalist / Swiss / tech-spec aesthetics). Either asymmetric or rigorously-gridded can be "designed"; the failure mode is splitting the difference into a generic centered stack.
-- Don't default to centering everything. Left-aligned with asymmetric layouts feels more designed; a strict grid reads as confident structure. A centered-stack hero with icon-title-subtitle cards reads as template.
-- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness.
-
-## Imagery
-
-Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo.
-
-**When the brief implies imagery (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product), you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy.
-
-- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `<div>` placeholders.
-- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel".
-- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one.
-- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish".
-
-"Imagery" here is broader than stock photography: product screenshots, custom data visualizations, generated SVG, and canvas/WebGL scenes are all imagery. Text-only pages where typography alone carries the entire visual weight are the failure mode.
-
-## Motion
-
-- One well-orchestrated page-load with staggered reveals beats scattered micro-interactions, when the brand invites it. Tech-minimal brands often skip entrance motion entirely; the restraint is the voice.
-- For collapsing/expanding sections, transition `grid-template-rows` rather than `height`.
-
-## Brand bans (on top of the shared absolute bans)
-
-- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume.
-- Large rounded-corner icons above every heading. Screams template.
-- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.)
-- All-caps body copy. Reserve caps for short labels and headings.
-- Timid palettes and average layouts. Safe = invisible.
-- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs.
-- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic.
-- Repeated tiny uppercase tracked labels above every section heading. A single strong kicker can be voice; repeating it as section grammar is AI scaffolding unless it's a deliberate, named brand system.
-
-## Brand permissions
-
-Brand can afford things product can't. Take them.
-
-- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography.
-- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing.
-- Typographic risk. Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines, a single oversize word as a hero.
-- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics.
-- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment.
@@ -1,174 +0,0 @@
-> **Additional context needed**: audience technical level and users' mental state in context.
-
-Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task.
-
-
----
-
-## Assess Current Copy
-
-Identify what makes the text unclear or ineffective:
-
-1. **Find clarity problems**:
- - **Jargon**: Technical terms users won't understand
- - **Ambiguity**: Multiple interpretations possible
- - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file"
- - **Length**: Too wordy or too terse
- - **Assumptions**: Assuming user knowledge they don't have
- - **Missing context**: Users don't know what to do or why
- - **Tone mismatch**: Too formal, too casual, or inappropriate for situation
-
-2. **Understand the context**:
- - Who's the audience? (Technical? General? First-time users?)
- - What's the user's mental state? (Stressed during error? Confident during success?)
- - What's the action? (What do we want users to do?)
- - What's the constraint? (Character limits? Space limitations?)
-
-**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets.
-
-## Plan Copy Improvements
-
-Create a strategy for clearer communication:
-
-- **Primary message**: What's the ONE thing users need to know?
-- **Action needed**: What should users do next (if anything)?
-- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?)
-- **Constraints**: Length limits, brand voice, localization considerations
-
-**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words.
-
-## Improve Copy Systematically
-
-Refine text across these common areas:
-
-### Error Messages
-**Bad**: "Error 403: Forbidden"
-**Good**: "You don't have permission to view this page. Contact your admin for access."
-
-**Bad**: "Invalid input"
-**Good**: "Email addresses need an @ symbol. Try: name@example.com"
-
-**Principles**:
-- Explain what went wrong in plain language
-- Suggest how to fix it
-- Don't blame the user
-- Include examples when helpful
-- Link to help/support if applicable
-
-### Form Labels & Instructions
-**Bad**: "DOB (MM/DD/YYYY)"
-**Good**: "Date of birth" (with placeholder showing format)
-
-**Bad**: "Enter value here"
-**Good**: "Your email address" or "Company name"
-
-**Principles**:
-- Use clear, specific labels (not generic placeholders)
-- Show format expectations with examples
-- Explain why you're asking (when not obvious)
-- Put instructions before the field, not after
-- Keep required field indicators clear
-
-### Button & CTA Text
-**Bad**: "Click here" | "Submit" | "OK"
-**Good**: "Create account" | "Save changes" | "Got it, thanks"
-
-**Principles**:
-- Describe the action specifically
-- Use active voice (verb + noun)
-- Match user's mental model
-- Be specific ("Save" is better than "OK")
-
-### Help Text & Tooltips
-**Bad**: "This is the username field"
-**Good**: "Choose a username. You can change this later in Settings."
-
-**Principles**:
-- Add value (don't just repeat the label)
-- Answer the implicit question ("What is this?" or "Why do you need this?")
-- Keep it brief but complete
-- Link to detailed docs if needed
-
-### Empty States
-**Bad**: "No items"
-**Good**: "No projects yet. Create your first project to get started."
-
-**Principles**:
-- Explain why it's empty (if not obvious)
-- Show next action clearly
-- Make it welcoming, not dead-end
-
-### Success Messages
-**Bad**: "Success"
-**Good**: "Settings saved! Your changes will take effect immediately."
-
-**Principles**:
-- Confirm what happened
-- Explain what happens next (if relevant)
-- Be brief but complete
-- Match the user's emotional moment (celebrate big wins)
-
-### Loading States
-**Bad**: "Loading..." (for 30+ seconds)
-**Good**: "Analyzing your data... this usually takes 30-60 seconds"
-
-**Principles**:
-- Set expectations (how long?)
-- Explain what's happening (when it's not obvious)
-- Show progress when possible
-- Offer escape hatch if appropriate ("Cancel")
-
-### Confirmation Dialogs
-**Bad**: "Are you sure?"
-**Good**: "Delete 'Project Alpha'? This can't be undone."
-
-**Principles**:
-- State the specific action
-- Explain consequences (especially for destructive actions)
-- Use clear button labels ("Delete project" not "Yes")
-- Don't overuse confirmations (only for risky actions)
-
-### Navigation & Wayfinding
-**Bad**: Generic labels like "Items" | "Things" | "Stuff"
-**Good**: Specific labels like "Your projects" | "Team members" | "Settings"
-
-**Principles**:
-- Be specific and descriptive
-- Use language users understand (not internal jargon)
-- Make hierarchy clear
-- Consider information scent (breadcrumbs, current location)
-
-## Apply Clarity Principles
-
-Every piece of copy should follow these rules:
-
-1. **Be specific**: "Enter email" not "Enter value"
-2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity)
-3. **Be active**: "Save changes" not "Changes will be saved"
-4. **Be human**: "Oops, something went wrong" not "System error encountered"
-5. **Tell users what to do**, not just what happened
-6. **Be consistent**: Use same terms throughout (don't vary for variety)
-
-**NEVER**:
-- Use jargon without explanation
-- Blame users ("You made an error" → "This field is required")
-- Be vague ("Something went wrong" without explanation)
-- Use passive voice unnecessarily
-- Write overly long explanations (be concise)
-- Use humor for errors (be empathetic instead)
-- Assume technical knowledge
-- Vary terminology (pick one term and stick with it)
-- Repeat information (headers restating intros, redundant explanations)
-- Use placeholders as the only labels (they disappear when users type)
-
-## Verify Improvements
-
-Test that copy improvements work:
-
-- **Comprehension**: Can users understand without context?
-- **Actionability**: Do users know what to do next?
-- **Brevity**: Is it as short as possible while remaining clear?
-- **Consistency**: Does it match terminology elsewhere?
-- **Tone**: Is it appropriate for the situation?
-
-When the copy reads cleanly, hand off to `/impeccable polish` for the final pass.
@@ -1,105 +0,0 @@
-# Codex: Visual Direction & Asset Production
-
-This file is loaded by `/impeccable craft` when the harness has native image generation (currently Codex via `image_gen`). Other harnesses skip it. It covers the two craft steps that depend on real image generation: landing the visual direction, and producing the raster assets the implementation will compose.
-
-Read this *before* generating any images. The order matters, and the per-step user pauses are what keep generated imagery from drifting away from the brief.
-
-### Four stop points before code
-
-Steps A through D each end with the user. Do not advance past any of them on your own read of the situation.
-
-1. **STOP after Step A questions.** Wait for answers.
-2. **STOP after Step B palette generation.** Wait for "confirm palette."
-3. **STOP after Step C mocks.** Wait for direction approval or delegation.
-4. **Only after Step D approves a direction** do you return to craft.md Step 4 and write code.
-
-Prior shape approval does **not** satisfy any of these. Shape's "confirm or override" advances you into Step A; it is not a substitute for it.
-
-## Step A: Explore Directions with the User
-
-Before generating anything, run a brief direction conversation grounded in the shape brief.
-
-**Step A is required even when shape just produced a confirmed brief.** The shape questions and Step A questions cover different ground: shape pins purpose, content, scope; Step A pins palette, atmosphere, and named visual references for the comps you're about to generate. The only time you can skip Step A is when the user has already answered these exact palette/atmosphere/reference questions in the same session.
-
-Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions:
-
-- "Brief says 'editorial restraint, Klim-adjacent.' Are we closer to a quiet specimen page or a magazine-spread feel with hero imagery?"
-- "Palette strategy from shape was 'Committed.' Want it warm-grounded (deep oxblood + cream) or cool-grounded (slate + paper white)?"
-
-**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded.
-
-## Step B: Generate the Brand Palette First
-
-Generate **one** palette artifact before any mocks. This is a small, focused image: typography pairing on the chosen background, primary + accent color swatches, one signature ornament or motif. Single image, single pass.
-
-Why palette first: mocks generated against a vague color sense produce noise that drowns out the structural decisions. A confirmed palette is the first concrete contract for everything downstream.
-
-Show the palette to the user. Ask one question: "This is the palette I'm locking in for the mocks. Confirm, or call out what to shift?"
-
-**STOP and wait for confirmation.** Do not generate mocks against an unconfirmed palette. "Probably good enough" is the wrong call here; the palette is the contract for everything downstream.
-
-## Step C: Generate 1-3 Visual Mocks Against the Palette
-
-Once the palette is confirmed, generate **1 to 3** high-fidelity north-star comps. Each mock must use the confirmed palette and typography. Mocks differ in *structural* direction (hierarchy, topology, density, composition), not in color or motif.
-
-- Brand work: push visual identity, composition, mood, and signature motifs.
-- Product work: push hierarchy, topology, density, tone, grounded in realistic product structure.
-- Landing pages and long-form brand surfaces: show enough of the second fold to establish the system beyond the hero.
-
-Use the `image_gen` tool directly (or via the imagegen skill when available). Don't ask the user to install anything.
-
-## Step D: Approval Loop
-
-Show the comps. Ask what carries forward. Iterate until **one direction is approved** or the user explicitly delegates.
-
-**STOP and wait for the approval or the delegation.** Do not begin Step E or return to craft.md Step 4 until a single direction is named. If the user delegates, pick the strongest direction and explain it from the brief, not personal taste.
-
-Before moving to assets, summarize what to carry into code and what *not* to literalize from the mock. This is the handoff between visual exploration and semantic implementation.
-
-## Step E: Mock Fidelity Inventory
-
-Inventory the approved mock's major visible ingredients. For each, decide implementation: semantic HTML/CSS/SVG, generated raster, sourced raster, icon library, canvas/WebGL, or accepted omission.
-
-Common ingredients to inventory:
-
-- Hero silhouette and dominant composition
-- Signature motifs (planets, devices, portraits, charts, route lines, insets, badges, etc.)
-- Nav and primary CTA treatment
-- Section sequence, especially the second fold
-- Image-native content the concept depends on
-- Typography, density, color/material treatment, motion cues
-
-Treat the mock as a north star, not a screenshot to trace. Don't rasterize core UI text. But if the live result lacks the mock's major ingredients, the implementation is wrong.
-
-If a photographic, architectural, product, or place-led mock becomes generic CSS scenery, decorative diagrams, bullets, or copy, stop and fix it. That's a broken implementation, not a harmless interpretation.
-
-Don't substitute a different hero composition or visual driver post-approval without user sign-off.
-
-## Step F: Asset Slicing via the Asset Producer
-
-Raster ingredients identified in Step E need clean production assets. Use the bundled `impeccable_asset_producer` subagent rather than producing inline.
-
-Spawn it as a scoped subagent. If you do not have explicit permission to use agents, stop and ask:
-
-```text
-Asset production will work better as a scoped subagent job. Should I spawn the Impeccable asset producer subagent for this step?
-```
-
-Pass to the agent:
-
-- Approved mock path or screenshot reference
-- Crop paths or a contact sheet with crop ids
-- Output directory
-- Required dimensions, format, transparency needs
-- Avoid list
-- Notes on what should remain semantic HTML/CSS/SVG instead of raster
-
-Attach image generation capability to the spawned agent when the harness supports it. Do **not** load image-generation reference material into the parent thread.
-
-Inline asset production is allowed only if the user declines subagents, the harness cannot spawn the authorized agent, or the user explicitly asks for single-thread mode.
-
-Prefer HTML/CSS/SVG/canvas when they can credibly reproduce an ingredient; reach for real, generated, or stock imagery when the mock or subject matter calls for actual visual content.
-
-## After This File
-
-Once Steps A through F are complete, return to `craft.md` Step 5 (Build to Production Quality). The implementation builds against the confirmed palette, approved mock, and the assets the producer wrote.
@@ -1,106 +0,0 @@
-# Cognitive Load Assessment
-
-Cognitive load is the total mental effort required to use an interface. Overloaded users make mistakes, get frustrated, and leave. This reference helps identify and fix cognitive overload.
-
----
-
-## Three Types of Cognitive Load
-
-### Intrinsic Load: The Task Itself
-Complexity inherent to what the user is trying to do. You can't eliminate this, but you can structure it.
-
-**Manage it by**:
-- Breaking complex tasks into discrete steps
-- Providing scaffolding (templates, defaults, examples)
-- Progressive disclosure: show what's needed now, hide the rest
-- Grouping related decisions together
-
-### Extraneous Load: Bad Design
-Mental effort caused by poor design choices. **Eliminate this ruthlessly.** It's pure waste.
-
-**Common sources**:
-- Confusing navigation that requires mental mapping
-- Unclear labels that force users to guess meaning
-- Visual clutter competing for attention
-- Inconsistent patterns that prevent learning
-- Unnecessary steps between user intent and result
-
-### Germane Load: Learning Effort
-Mental effort spent building understanding. This is *good* cognitive load; it leads to mastery.
-
-**Support it by**:
-- Progressive disclosure that reveals complexity gradually
-- Consistent patterns that reward learning
-- Feedback that confirms correct understanding
-- Onboarding that teaches through action, not walls of text
-
----
-
-## Cognitive Load Checklist
-
-Evaluate the interface against these 8 items:
-
-- [ ] **Single focus**: Can the user complete their primary task without distraction from competing elements?
-- [ ] **Chunking**: Is information presented in digestible groups (≤4 items per group)?
-- [ ] **Grouping**: Are related items visually grouped together (proximity, borders, shared background)?
-- [ ] **Visual hierarchy**: Is it immediately clear what's most important on the screen?
-- [ ] **One thing at a time**: Can the user focus on a single decision before moving to the next?
-- [ ] **Minimal choices**: Are decisions simplified (≤4 visible options at any decision point)?
-- [ ] **Working memory**: Does the user need to remember information from a previous screen to act on the current one?
-- [ ] **Progressive disclosure**: Is complexity revealed only when the user needs it?
-
-**Scoring**: Count the failed items. 0–1 failures = low cognitive load (good). 2–3 = moderate (address soon). 4+ = high cognitive load (critical fix needed).
-
----
-
-## The Working Memory Rule
-
-**Humans can hold ≤4 items in working memory at once** (Miller's Law revised by Cowan, 2001).
-
-At any decision point, count the number of distinct options, actions, or pieces of information a user must simultaneously consider:
-- **≤4 items**: Within working memory limits, manageable
-- **5–7 items**: Pushing the boundary; consider grouping or progressive disclosure
-- **8+ items**: Overloaded; users will skip, misclick, or abandon
-
-**Practical applications**:
-- Navigation menus: ≤5 top-level items (group the rest under clear categories)
-- Form sections: ≤4 fields visible per group before a visual break
-- Action buttons: 1 primary, 1–2 secondary, group the rest in a menu
-- Dashboard widgets: ≤4 key metrics visible without scrolling
-- Pricing tiers: ≤3 options (more causes analysis paralysis)
-
----
-
-## Common Cognitive Load Violations
-
-### 1. The Wall of Options
-**Problem**: Presenting 10+ choices at once with no hierarchy.
-**Fix**: Group into categories, highlight recommended, use progressive disclosure.
-
-### 2. The Memory Bridge
-**Problem**: User must remember info from step 1 to complete step 3.
-**Fix**: Keep relevant context visible, or repeat it where it's needed.
-
-### 3. The Hidden Navigation
-**Problem**: User must build a mental map of where things are.
-**Fix**: Always show current location (breadcrumbs, active states, progress indicators).
-
-### 4. The Jargon Barrier
-**Problem**: Technical or domain language forces translation effort.
-**Fix**: Use plain language. If domain terms are unavoidable, define them inline.
-
-### 5. The Visual Noise Floor
-**Problem**: Every element has the same visual weight; nothing stands out.
-**Fix**: Establish clear hierarchy: one primary element, 2–3 secondary, everything else muted.
-
-### 6. The Inconsistent Pattern
-**Problem**: Similar actions work differently in different places.
-**Fix**: Standardize interaction patterns. Same type of action = same type of UI.
-
-### 7. The Multi-Task Demand
-**Problem**: Interface requires processing multiple simultaneous inputs (reading + deciding + navigating).
-**Fix**: Sequence the steps. Let the user do one thing at a time.
-
-### 8. The Context Switch
-**Problem**: User must jump between screens/tabs/modals to gather info for a single decision.
-**Fix**: Co-locate the information needed for each decision. Reduce back-and-forth.
@@ -1,105 +0,0 @@
-# Color & Contrast
-
-## Color Spaces: Use OKLCH
-
-**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark.
-
-The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish.
-
-The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand.
-
-## Building Functional Palettes
-
-### Tinted Neutrals
-
-**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces.
-
-The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette.
-
-**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects.
-
-### Palette Structure
-
-A complete system needs:
-
-| Role | Purpose | Example |
-|------|---------|---------|
-| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades |
-| **Neutral** | Text, backgrounds, borders | 9-11 shade scale |
-| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each |
-| **Surface** | Cards, modals, overlays | 2-3 elevation levels |
-
-**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise.
-
-### The 60-30-10 Rule (Applied Correctly)
-
-This rule is about **visual weight**, not pixel count:
-
-- **60%**: Neutral backgrounds, white space, base surfaces
-- **30%**: Secondary colors: text, borders, inactive states
-- **10%**: Accent: CTAs, highlights, focus states
-
-The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power.
-
-## Contrast & Accessibility
-
-### WCAG Requirements
-
-| Content Type | AA Minimum | AAA Target |
-|--------------|------------|------------|
-| Body text | 4.5:1 | 7:1 |
-| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 |
-| UI components, icons | 3:1 | 4.5:1 |
-| Non-essential decorations | None | None |
-
-**The gotcha**: Placeholder text still needs 4.5:1. That light gray placeholder you see everywhere? Usually fails WCAG.
-
-### Dangerous Color Combinations
-
-These commonly fail contrast or cause readability issues:
-
-- Light gray text on white (the #1 accessibility fail)
-- **Gray text on any colored background**: gray looks washed out and dead on color. Use a darker shade of the background color, or transparency
-- Red text on green background (or vice versa): 8% of men can't distinguish these
-- Blue text on red background (vibrates visually)
-- Yellow text on white (almost always fails)
-- Thin light text on images (unpredictable contrast)
-
-### Never Use Pure Gray or Pure Black
-
-Pure gray (`oklch(50% 0 0)`) and pure black (`#000`) don't exist in nature; real shadows and surfaces always have a color cast. Even a chroma of 0.005-0.01 is enough to feel natural without being obviously tinted. (See tinted neutrals example above.)
-
-### Testing
-
-Don't trust your eyes. Use tools:
-
-- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/)
-- Browser DevTools → Rendering → Emulate vision deficiencies
-- [Polypane](https://polypane.app/) for real-time testing
-
-## Theming: Light & Dark Mode
-
-### Dark Mode Is Not Inverted Light Mode
-
-You can't just swap colors. Dark mode requires different design decisions:
-
-| Light Mode | Dark Mode |
-|------------|-----------|
-| Shadows for depth | Lighter surfaces for depth (no shadows) |
-| Dark text on light | Light text on dark (reduce font weight) |
-| Vibrant accents | Desaturate accents slightly |
-| White backgrounds | Never pure black; use dark gray (oklch 12-18%) |
-
-In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light.
-
-### Token Hierarchy
-
-Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same.
-
-## Alpha Is A Design Smell
-
-Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed.
-
----
-
-**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Using pure black (#000) for large areas. Skipping color blindness testing (8% of men affected).
@@ -1,154 +0,0 @@
-> **Additional context needed**: existing brand colors.
-
-Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit.
-
----
-
-## Register
-
-Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it.
-
-Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen.
-
----
-
-## Assess Color Opportunity
-
-Analyze the current state and identify opportunities:
-
-1. **Understand current state**:
- - **Color absence**: Pure grayscale? Limited neutrals? One timid accent?
- - **Missed opportunities**: Where could color add meaning, hierarchy, or delight?
- - **Context**: What's appropriate for this domain and audience?
- - **Brand**: Are there existing brand colors we should use?
-
-2. **Identify where color adds value**:
- - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue)
- - **Hierarchy**: Drawing attention to important elements
- - **Categorization**: Different sections, types, or states
- - **Emotional tone**: Warmth, energy, trust, creativity
- - **Wayfinding**: Helping users navigate and understand structure
- - **Delight**: Moments of visual interest and personality
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose.
-
-## Plan Color Strategy
-
-Create a purposeful color introduction plan:
-
-- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals)
-- **Dominant color**: Which color owns 60% of colored elements?
-- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%)
-- **Application strategy**: Where does each color appear and why?
-
-**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more.
-
-## Introduce Color Strategically
-
-Add color systematically across these dimensions:
-
-### Semantic Color
-- **State indicators**:
- - Success: Green tones (emerald, forest, mint)
- - Error: Red/pink tones (rose, crimson, coral)
- - Warning: Orange/amber tones
- - Info: Blue tones (sky, ocean, indigo)
- - Neutral: Gray/slate for inactive states
-
-- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.)
-- **Progress indicators**: Colored bars, rings, or charts showing completion or health
-
-### Accent Color Application
-- **Primary actions**: Color the most important buttons/CTAs
-- **Links**: Add color to clickable text (maintain accessibility)
-- **Icons**: Colorize key icons for recognition and personality
-- **Headers/titles**: Add color to section headers or key labels
-- **Hover states**: Introduce color on interaction
-
-### Background & Surfaces
-- **Tinted backgrounds**: Replace pure gray (`#f5f5f5`) with warm neutrals (`oklch(97% 0.01 60)`) or cool tints (`oklch(97% 0.01 250)`)
-- **Colored sections**: Use subtle background colors to separate areas
-- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue)
-- **Cards & surfaces**: Tint cards or surfaces slightly for warmth
-
-**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
-
-### Data Visualization
-- **Charts & graphs**: Use color to encode categories or values
-- **Heatmaps**: Color intensity shows density or importance
-- **Comparison**: Color coding for different datasets or timeframes
-
-### Borders & Accents
-- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`)
-- **Underlines**: Color underlines for emphasis or active states
-- **Dividers**: Subtle colored dividers instead of gray lines
-- **Focus rings**: Colored focus indicators matching brand
-- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe
-
-**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe.
-
-### Typography Color
-- **Colored headings**: Use brand colors for section headings (maintain contrast)
-- **Highlight text**: Color for emphasis or categories
-- **Labels & tags**: Small colored labels for metadata or categories
-
-### Decorative Elements
-- **Illustrations**: Add colored illustrations or icons
-- **Shapes**: Geometric shapes in brand colors as background elements
-- **Gradients**: Colorful gradient overlays or mesh backgrounds
-- **Blobs/organic shapes**: Soft colored shapes for visual interest
-
-## Balance & Refinement
-
-Ensure color addition improves rather than overwhelms:
-
-### Maintain Hierarchy
-- **Dominant color** (60%): Primary brand color or most used accent
-- **Secondary color** (30%): Supporting color for variety
-- **Accent color** (10%): High contrast for key moments
-- **Neutrals** (remaining): Gray/black/white for structure
-
-### Accessibility
-- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components)
-- **Don't rely on color alone**: Use icons, labels, or patterns alongside color
-- **Test for color blindness**: Verify red/green combinations work for all users
-
-### Cohesion
-- **Consistent palette**: Use colors from defined palette, not arbitrary choices
-- **Systematic application**: Same color meanings throughout (green always = success)
-- **Temperature consistency**: Warm palette stays warm, cool stays cool
-
-**NEVER**:
-- Use every color in the rainbow (choose 2-4 colors beyond neutrals)
-- Apply color randomly without semantic meaning
-- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead
-- Use pure gray for neutrals. Add subtle color tint (warm or cool) for depth
-- Use pure black (`#000`) or pure white (`#fff`) for large areas
-- Violate WCAG contrast requirements
-- Use color as the only indicator (accessibility issue)
-- Make everything colorful (defeats the purpose)
-- Default to purple-blue gradients (AI slop aesthetic)
-
-## Verify Color Addition
-
-Test that colorization improves the experience:
-
-- **Better hierarchy**: Does color guide attention appropriately?
-- **Clearer meaning**: Does color help users understand states/categories?
-- **More engaging**: Does the interface feel warmer and more inviting?
-- **Still accessible**: Do all color combinations meet WCAG standards?
-- **Not overwhelming**: Is color balanced and purposeful?
-
-When the palette earns its place, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage.
-
-```json
-{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"}
-```
-
-Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract.
@@ -1,123 +0,0 @@
-# Craft Flow
-
-Build a feature with impeccable UX and UI quality: shape the design, land the visual direction, build real production code, inspect and improve in-browser until it meets a high-end studio bar.
-
-Before writing code, you need: PRODUCT.md loaded, register identified and the matching reference loaded, and a confirmed design direction for this task (either from `shape` or supplied by the user). PRODUCT.md is project context, not a task-specific brief.
-
-Treat any approved visual direction (generated mock or stated reference) as a concrete contract for composition, hierarchy, density, atmosphere, signature motifs, and distinctive visual moves. Don't let mocks replace structure, copy, accessibility, or state design. But if the live result lacks the approved direction's major ingredients, the implementation is wrong.
-
-### Gates: do not compress
-
-Craft has **multiple user gates**, not one. When the harness has native image generation (Codex via `image_gen`), the gate sequence before code is:
-
-1. **Shape brief confirmed** (Step 1)
-2. **Direction questions answered** (codex.md Step A)
-3. **Palette confirmed** (codex.md Step B)
-4. **One mock direction approved or delegated** (codex.md Step D)
-
-You must stop at every gate. **Shape confirmation alone is NOT a green light to start coding.** It is the green light to begin codex.md Step A. Compressing gates 2 through 4 because the shape brief felt complete is the dominant failure mode of this flow.
-
-When the harness lacks native image generation, gates 2-4 collapse into the brief itself, and shape confirmation does advance straight to code.
-
-## Step 0: Project Foundation
-
-Before shape, before code: figure out what kind of project you're working in.
-
-Look at the working directory. Run `ls`. Check for:
-
-- An existing framework: `astro.config.mjs/ts`, `next.config.js/ts`, `nuxt.config.ts`, `svelte.config.js`, `vite.config.js/ts`, `package.json` with framework deps, `Cargo.toml` + Leptos/Yew, `Gemfile` + Rails. **If found, use it.** Do not start a parallel build, do not introduce a second framework, do not write to `dist/` or `build/` directly. Whatever pipeline the project has, respect it.
-- An existing component library or design system: `src/components/`, `app/components/`, a `tokens.css` / `theme.ts`, an `astro.config` `integrations`. Read what's there before adding to it.
-- An existing icon set: `lucide-react`, `@phosphor-icons/react`, `@iconify/*`, hand-rolled SVG sprites in `assets/icons/`. **Use what's already in the project**; don't introduce a second set.
-
-If the directory is empty (greenfield), don't pick a framework silently. Ask the user via the AskUserQuestion tool, with sensible defaults framed by the brief:
-
-```text
-What should this be built on?
- - Astro (default for content-led brand sites, landing pages, marketing surfaces)
- - SvelteKit / Next.js / Nuxt (when the brief implies an app surface or significant interactivity)
- - Single index.html (one-shot demo, prototype, or a deliberately framework-free experiment)
-```
-
-Default: Astro for brand briefs, the project's existing framework for product briefs. Ask once; don't re-ask mid-task.
-
-## Step 1: Shape the Design
-
-Run /impeccable shape, passing along whatever feature description the user provided. Shape is **required** for craft; it is what produces a confirmed direction.
-
-Present the shape output and stop. Wait for the user to confirm, override, or course-correct before writing code.
-
-If the user already supplied a confirmed brief or ran shape separately, use it and skip this step.
-
-When the original prompt + PRODUCT.md already answer scope, content, and visual direction with no real ambiguity, the shape output can be **compact** (3-5 bullets stating what you're building and the visual lane, ending with one or two specific questions or "confirm or override"). The full 10-section structured brief is reserved for genuinely ambiguous, multi-screen, or stakeholder-heavy tasks. Don't pad a clear brief into a long one to look thorough; equally, don't skip the pause to look efficient.
-
-If the harness has native image generation (Codex), a compact shape's "confirm or override" advances to **Step 3 and the codex.md flow**, not to Step 4. Phrase the closing line accordingly: "Confirm or override; once we lock direction, I'll run a couple of palette and reference questions before generating any mocks." This stops the model from reading shape confirmation as code-green.
-
-## Step 2: Load References
-
-Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult:
-
-- [spatial-design.md](spatial-design.md) for layout and spacing
-- [typography.md](typography.md) for type hierarchy
-
-Then add references based on the brief's needs:
-- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md)
-- Animation or transitions? Consult [motion-design.md](motion-design.md)
-- Color-heavy or themed? Consult [color-and-contrast.md](color-and-contrast.md)
-- Responsive requirements? Consult [responsive-design.md](responsive-design.md)
-- Heavy on copy, labels, or errors? Consult [ux-writing.md](ux-writing.md)
-
-## Step 3: Visual Direction & Assets (Harness-Gated)
-
-If the harness has **native image generation** (currently Codex via `image_gen`), this step is mandatory. **Stop and load [codex.md](codex.md)**. It covers palette generation, mock exploration, the approval loop, mock-fidelity inventory, and asset slicing via the `impeccable_asset_producer` subagent. Follow Steps A-F in that file, then return here for Step 4.
-
-If the harness lacks native image generation, **state in one line that the visual-direction-by-generation step is being skipped because the harness lacks native image generation, then proceed**. The one-line announcement is required; it forces a conscious decision instead of letting the step quietly evaporate. The brief is your only visual reference. Implement directly from it, treating any named anchor references and the brief's "Design Direction" as the contract.
-
-Whether you generated mocks or not: don't replace required imagery with generic cards, bullets, emoji, fake metrics, decorative CSS panels, or filler copy. Image-led briefs (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product) need real or sourced imagery in the build, not CSS scenery.
-
-## Step 4: Build to Production Quality
-
-**Precondition.** If Step 3 routed you to codex.md (native image generation available), Steps A through D in that file must be complete before any code: questions answered, palette confirmed, mocks generated, one direction approved or delegated. **Do not mention implementation, file paths, or patch plans until that's done.** A confirmed shape brief is not enough; the model that compressed those gates is the model that already failed this flow.
-
-Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration.
-
-### Production bar
-
-- **Real content.** No placeholder copy, placeholder images, dead links, fake controls, or unused scaffold at presentation time.
-- **Preserve the approved mock's major ingredients.** Missing hero objects, world/product imagery, section structure, CTA/nav treatment, or distinctive motifs are blocking defects unless the user accepted the change.
-- **Semantic first.** Real headings, landmarks, labels, form associations, button/link semantics, accessible names, state announcements where needed.
-- **Deliberate spacing and alignment.** No default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment.
-- **Intentional typography.** Chosen loading strategy, clear hierarchy, readable measure, stable line breaks, no overflow at any width.
-- **Realistic state coverage.** Default, hover, focus-visible, active, disabled, loading, error, success, empty, overflow, long/short text, first-run.
-- **Finished interaction quality.** Keyboard paths, touch targets, feedback timing, scroll behavior, state transitions, no hover-only functionality.
-- **Coherent icon set.** Use the project's established set; otherwise pick one library or use accessible text. Don't mix.
-- **Respect the build pipeline.** Edit source files and run the project's build (`npm run build` or equivalent). Don't write to `build/` / `dist/` / `.next/` with `cat`, heredoc, or Bash redirects; that skips asset hashing, image optimization, code splitting, and CSS extraction, and produces output the dev server won't serve.
-- **Verify image URLs before referencing them.** Use image-search MCP or web-fetch when available; guessed photo IDs ship as broken-image placeholders. Without verification, prefer fewer images you're confident about.
-- **Optimized imagery and media.** Correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset`/`picture` for raster, no project-referenced asset left outside the workspace.
-- **Premium motion.** Use atmospheric blur, filter, mask, shadow, reveal when they improve the experience. Avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion.
-- **Maintainable.** Reusable local patterns, clear component boundaries, project conventions. No rasterized UI text or one-off hacks when a local pattern exists.
-- **Technically clean.** Production build passes, no console errors, no avoidable layout shift, no needless dependencies, no broken asset paths.
-- **Ask when uncertain.** If a discovery materially changes the brief or approved direction, stop and ask. Don't guess.
-
-## Step 5: Iterate Visually
-
-Look at what you built like a designer would. Your eyes are whatever the harness gives you: a connected browser, a screenshotting tool, Playwright, or asking the user. Use them for responsive testing (mobile, tablet, desktop minimum) and general visual validation.
-
-If your tool returns a file path, read the PNG back into the conversation. A screenshot you didn't read doesn't count.
-
-For long-form brand surfaces, inspect major sections individually. Thumbnails hide spacing, clipping, and cascade defects.
-
-After the first pass, write an honest critique against the brief, the approved mock's major ingredients (hero silhouette, motifs, imagery, nav/CTA, density), and impeccable's DON'Ts. Patch material defects and re-inspect. **Don't invent defects to demonstrate iteration.** A confident "first pass clean, shipping" beats a fake fix.
-
-Actively check: responsive behavior (composes, not shrinks), every state (empty / error / loading / edge), craft details (spacing, alignment, hierarchy, contrast, motion timing, focus), performance basics. The exit bar: defensible in a high-end studio review.
-
-Detector or QA output is defect evidence only; never proof the work is finished.
-
-## Step 6: Present
-
-Present the result to the user:
-- Show the feature in its primary state
-- Summarize the browser/viewports checked and the most important fixes made after inspection
-- Walk through the key states (empty, error, responsive)
-- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients.
-- Note any remaining limitations or follow-up risks honestly
-- Ask: "What's working? What isn't?"
@@ -1,236 +0,0 @@
-### Purpose
-
-Resolve one stable target, run two independent assessments, synthesize a design critique, persist a snapshot, and ask the user what to improve next. The chat response is the primary deliverable; the snapshot is an archive/backlog for future commands.
-
-### Hard Invariants
-
-- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
-- Assessment A must finish before detector findings enter the parent synthesis context. Detector output is deterministic, but it still anchors judgment.
-- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize.
-- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
-- Viewable targets require browser inspection when available.
-- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
-- Do not claim a user-visible overlay exists unless script injection succeeded and the detector ran in the page.
-
-### Setup
-
-1. **Resolve the target** to a concrete file path or URL. Prefer a source path over a dev-server URL when both identify the same surface; ports drift, paths do not.
- - "the homepage" -> `site/pages/index.astro` or `index.html`
- - "the settings modal" -> the primary component file
- - "this page" -> the current URL or source file
-2. **Compute the slug**:
- ```bash
- node .pi/skills/impeccable/scripts/critique-storage.mjs slug "<resolved-path-or-url>"
- ```
- Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique.
-3. **Read `.impeccable/critique/ignore.md`** if it exists. Drop matching findings silently; it is the only prior-run input critique consumes.
-
-### Assessment Orchestration
-
-Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis.
-
-If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
-
-### Assessment A: Design Review
-
-Read relevant source files and visually inspect the live page when browser automation is available. Think like a design director.
-
-Evaluate:
-- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill.
-- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases.
-- **Cognitive load**: consult [cognitive-load](cognitive-load.md); report checklist failures and decision points with >4 visible options.
-- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments.
-- **Nielsen heuristics**: consult [heuristics-scoring](heuristics-scoring.md); score all 10 heuristics 0-4.
-
-Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions.
-
-### Assessment B: Detector + Browser Evidence
-
-Run the bundled detector and browser visualization evidence. Assessment B is mandatory and must remain isolated from Assessment A until both are complete.
-
-CLI scan:
-```bash
-node .pi/skills/impeccable/scripts/detect.mjs --json [--fast] [target]
-```
-
-- Pass markup files/directories as `[target]`; do not pass CSS-only files.
-- For URLs, skip CLI scan and use browser visualization.
-- For 200+ scannable files, use `--fast`; for 500+, narrow scope or ask.
-- Exit code 0 = clean; 2 = findings.
-- If the detector entrypoint is missing or fails to load, report deterministic scan unavailable and continue with browser/manual review.
-
-Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
-
-1. Create a fresh tab and navigate.
-2. Preflight mutable injection by setting `document.title` and appending a `<script>` tag. Read-only evaluate APIs do not count.
-3. If mutation is unavailable, skip live server, browser presentation, and injection; report fallback signal.
-4. If mutation is available, start `node .pi/skills/impeccable/scripts/live-server.mjs --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then stop the live server.
-5. For multi-view targets, inject on 3-5 representative pages.
-
-Return: CLI findings JSON/counts, browser console findings if applicable, false positives, and skipped/failed browser steps with concrete reasons.
-
-After Assessment B returns usable CLI findings, reuse them. Do not rerun `detect.mjs` in the parent unless Assessment B failed, was truncated, or omitted count, rule names, or file locations.
-
-### Generate Combined Critique Report
-
-Synthesize both assessments into a single report. Do NOT simply concatenate. Weave the findings together, noting where the LLM review and detector agree, where the detector caught issues the LLM missed, and where detector findings are false positives.
-
-The chat response is the primary user-facing deliverable. Present the full structured critique below in chat; do not replace it with a summary and a link. The persisted snapshot is only an archive/backlog for later commands.
-
-Structure your feedback as a design director would:
-
-#### Design Health Score
-> *Consult [heuristics-scoring](heuristics-scoring.md)*
-
-Present the Nielsen's 10 heuristics scores as a table:
-
-| # | Heuristic | Score | Key Issue |
-|---|-----------|-------|-----------|
-| 1 | Visibility of System Status | ? | [specific finding or "n/a" if solid] |
-| 2 | Match System / Real World | ? | |
-| 3 | User Control and Freedom | ? | |
-| 4 | Consistency and Standards | ? | |
-| 5 | Error Prevention | ? | |
-| 6 | Recognition Rather Than Recall | ? | |
-| 7 | Flexibility and Efficiency | ? | |
-| 8 | Aesthetic and Minimalist Design | ? | |
-| 9 | Error Recovery | ? | |
-| 10 | Help and Documentation | ? | |
-| **Total** | | **??/40** | **[Rating band]** |
-
-Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32.
-
-#### Anti-Patterns Verdict
-
-**Start here.** Does this look AI-generated?
-
-**LLM assessment**: Your own evaluation of AI slop tells. Cover overall aesthetic feel, layout sameness, generic composition, missed opportunities for personality.
-
-**Deterministic scan**: Summarize what the automated detector found, with counts and file locations. Note any additional issues the detector caught that you missed, and flag any false positives.
-
-**Visual overlays** (if injection succeeded): Tell the user that overlays are now visible in the **[Human]** tab in their browser, highlighting the detected issues. Summarize what the console output reported. If browser visualization was attempted but injection failed, say that no reliable user-visible overlay is available and report the fallback signal instead.
-
-#### Overall Impression
-A brief gut reaction: what works, what doesn't, and the single biggest opportunity.
-
-#### What's Working
-Highlight 2-3 things done well. Be specific about why they work.
-
-#### Priority Issues
-The 3-5 most impactful design problems, ordered by importance.
-
-For each issue, tag with **P0-P3 severity** (consult [heuristics-scoring](heuristics-scoring.md) for severity definitions):
-- **[P?] What**: Name the problem clearly
-- **Why it matters**: How this hurts users or undermines goals
-- **Fix**: What to do about it (be concrete)
-- **Suggested command**: Which command could address this (from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-#### Persona Red Flags
-> *Consult [personas](personas.md)*
-
-Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `AGENTS.md` contains a `## Design Context` section from `impeccable teach`, also generate 1-2 project-specific personas from the audience/brand info.
-
-For each selected persona, walk through the primary user action and list specific red flags found:
-
-**Alex (Power User)**: No keyboard shortcuts detected. Form requires 8 clicks for primary action. Forced modal onboarding. High abandonment risk.
-
-**Jordan (First-Timer)**: Icon-only nav in sidebar. Technical jargon in error messages ("404 Not Found"). No visible help. Will abandon at step 2.
-
-Be specific. Name the exact elements and interactions that fail each persona. Don't write generic persona descriptions; write what broke for them.
-
-#### Minor Observations
-Quick notes on smaller issues worth addressing.
-
-#### Questions to Consider
-Provocative questions that might unlock better solutions:
-- "What if the primary action were more prominent?"
-- "Does this need to feel this complex?"
-- "What would a confident version of this look like?"
-
-**Remember**:
-- Be direct. Vague feedback wastes everyone's time.
-- Be specific. "The submit button," not "some elements."
-- Say what's wrong AND why it matters to users.
-- Give concrete suggestions. Cut "consider exploring..." entirely.
-- Prioritize ruthlessly. If everything is important, nothing is.
-- Don't soften criticism. Developers need honest feedback to ship great design.
-
-### Persist the Snapshot
-
-Once the report above is finalized, write it to `.impeccable/critique/` so the user can refer back, and so `/impeccable polish` can pick up the priority issues without a copy-paste.
-
-Skip this step if the Setup slug was null (vague or root-level target).
-
-1. **Write the body to a temp file** so you can pipe it to the helper. Use the full critique report (heuristic table, anti-patterns verdict, priority issues, persona red flags, minor observations, and questions), but stop before the "Ask the User" / "Recommended Actions" sections that come later.
-
-2. **Pass the structured metadata** through `IMPECCABLE_CRITIQUE_META` (JSON), then run the write command:
- ```bash
- IMPECCABLE_CRITIQUE_META='{"target":"<user phrasing>","total_score":<n>,"p0_count":<n>,"p1_count":<n>}' \
- node .pi/skills/impeccable/scripts/critique-storage.mjs write <slug> <body-file>
- ```
- The helper prints the absolute path it wrote.
-
-3. **Delete the temp body file** after the write attempt completes, whether the write succeeded or failed. If deletion fails, mention `temp-file cleanup failed: <reason>` briefly in the final output, but do not block the critique.
-
-4. **Read the trend** for context:
- ```bash
- node .pi/skills/impeccable/scripts/critique-storage.mjs trend <slug> 5
- ```
- This returns a JSON array of the last 5 frontmatter entries (including the one you just wrote).
-
-5. **Append a single line to the user-visible output**, after the report and before the questions:
-
- > **Trend for `<slug>` (last 5 runs): 24 → 28 → 32 → 29 → 32**
- > Wrote `.impeccable/critique/<filename>`.
-
- If this is the first run for the slug, the trend is just one score; say so: "First run for this target, no trend yet."
-
-This is fire-and-forget. Do not show the user the helper's JSON output; only the human-readable trend line and the written path. Failures here should not block the rest of the flow; print the error and move on.
-
-### Ask the User
-
-**After presenting findings**, use targeted questions based on what was actually found. ask the user directly to clarify what you cannot infer. These answers will shape the action plan.
-
-Ask questions along these lines (adapt to the specific findings; do NOT ask generic questions):
-
-1. **Priority direction**: Based on the issues found, ask which category matters most to the user right now. For example: "I found problems with visual hierarchy, color usage, and information overload. Which area should we tackle first?" Offer the top 2-3 issue categories as options.
-
-2. **Design intent**: If the critique found a tonal mismatch, ask whether it was intentional. For example: "The interface feels clinical and corporate. Is that the intended tone, or should it feel warmer/bolder/more playful?" Offer 2-3 tonal directions as options based on what would fix the issues found.
-
-3. **Scope**: Ask how much the user wants to take on. For example: "I found N issues. Want to address everything, or focus on the top 3?" Offer scope options like "Top 3 only", "All issues", "Critical issues only".
-
-4. **Constraints** (optional; only ask if relevant): If the findings touch many areas, ask if anything is off-limits. For example: "Should any sections stay as-is?" This prevents the plan from touching things the user considers done.
-
-**Rules for questions**:
-- Every question must reference specific findings from the report. Never ask generic "who is your audience?" questions.
-- Keep it to 2-4 questions maximum. Respect the user's time.
-- Offer concrete options, not open-ended prompts.
-- If findings are straightforward (e.g., only 1-2 clear issues), skip questions and go directly to Recommended Actions.
-
-### Recommended Actions
-
-**After receiving the user's answers**, present a prioritized action summary reflecting the user's priorities and scope from Ask the User.
-
-#### Action Summary
-
-List recommended commands in priority order, based on the user's answers:
-
-1. **`/command-name`**: Brief description of what to fix (specific context from critique findings)
-2. **`/command-name`**: Brief description (specific context)
-...
-
-**Rules for recommendations**:
-- Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset
-- Order by the user's stated priorities first, then by impact
-- Each item's description should carry enough context that the command knows what to focus on
-- Map each Priority Issue to the appropriate command
-- Skip commands that would address zero issues
-- If the user chose a limited scope, only include items within that scope
-- If the user marked areas as off-limits, exclude commands that would touch those areas
-- End with `/impeccable polish` as the final step if any fixes were recommended
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable critique` after fixes to see your score improve.
@@ -1,302 +0,0 @@
-> **Additional context needed**: what's appropriate for the domain (playful vs professional vs quirky vs elegant).
-
-Find the moments where personality and unexpected polish would turn a functional interface into one users remember and tell other people about. Add only where the moment earns it; delight everywhere reads as noise.
-
----
-
-## Register
-
-Brand: delight can be distributed across copy voice, section transitions, discovery rewards, seasonal touches, personality across the whole surface.
-
-Product: delight at specific moments, not pages. Completion, first-time actions, error recovery, milestone crossings. Reliability and consistency carry the rest of the experience; delight pushed everywhere reads as noise.
-
----
-
-## Assess Delight Opportunities
-
-Identify where delight would enhance (not distract from) the experience:
-
-1. **Find natural delight moments**:
- - **Success states**: Completed actions (save, send, publish)
- - **Empty states**: First-time experiences, onboarding
- - **Loading states**: Waiting periods that could be entertaining
- - **Achievements**: Milestones, streaks, completions
- - **Interactions**: Hover states, clicks, drags
- - **Errors**: Softening frustrating moments
- - **Easter eggs**: Hidden discoveries for curious users
-
-2. **Understand the context**:
- - What's the brand personality? (Playful? Professional? Quirky? Elegant?)
- - Who's the audience? (Tech-savvy? Creative? Corporate?)
- - What's the emotional context? (Accomplishment? Exploration? Frustration?)
- - What's appropriate? (Banking app ≠ gaming app)
-
-3. **Define delight strategy**:
- - **Subtle sophistication**: Refined micro-interactions (luxury brands)
- - **Playful personality**: Whimsical illustrations and copy (consumer apps)
- - **Helpful surprises**: Anticipating needs before users ask (productivity tools)
- - **Sensory richness**: Satisfying sounds, smooth animations (creative tools)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Delight should enhance usability, never obscure it. If users notice the delight more than accomplishing their goal, you've gone too far.
-
-## Delight Principles
-
-Follow these guidelines:
-
-### Delight Amplifies, Never Blocks
-- Delight moments should be quick (< 1 second)
-- Never delay core functionality for delight
-- Make delight skippable or subtle
-- Respect user's time and task focus
-
-### Surprise and Discovery
-- Hide delightful details for users to discover
-- Reward exploration and curiosity
-- Don't announce every delight moment
-- Let users share discoveries with others
-
-### Appropriate to Context
-- Match delight to emotional moment (celebrate success, empathize with errors)
-- Respect the user's state (don't be playful during critical errors)
-- Match brand personality and audience expectations
-- Cultural sensitivity (what's delightful varies by culture)
-
-### Compound Over Time
-- Delight should remain fresh with repeated use
-- Vary responses (not same animation every time)
-- Reveal deeper layers with continued use
-- Build anticipation through patterns
-
-## Delight Techniques
-
-Add personality and joy through these methods:
-
-### Micro-interactions & Animation
-
-**Button delight**:
-```css
-/* Satisfying button press */
-.button {
- transition: transform 0.1s, box-shadow 0.1s;
-}
-.button:active {
- transform: translateY(2px);
- box-shadow: 0 2px 4px rgba(0,0,0,0.2);
-}
-
-/* Ripple effect on click */
-/* Smooth lift on hover */
-.button:hover {
- transform: translateY(-2px);
- transition: transform 0.2s cubic-bezier(0.25, 1, 0.5, 1); /* ease-out-quart */
-}
-```
-
-**Loading delight**:
-- Playful loading animations (not just spinners)
-- Personality in loading messages (write product-specific ones, not generic AI filler)
-- Progress indication with encouraging messages
-- Skeleton screens with subtle animations
-
-**Success animations**:
-- Checkmark draw animation
-- Confetti burst for major achievements
-- Gentle scale + fade for confirmation
-- Satisfying sound effects (subtle)
-
-**Hover surprises**:
-- Icons that animate on hover
-- Color shifts or glow effects
-- Tooltip reveals with personality
-- Cursor changes (custom cursors for branded experiences)
-
-### Personality in Copy
-
-**Playful error messages**:
-```
-"Error 404"
-"This page is playing hide and seek. (And winning)"
-
-"Connection failed"
-"Looks like the internet took a coffee break. Want to retry?"
-```
-
-**Encouraging empty states**:
-```
-"No projects"
-"Your canvas awaits. Create something amazing."
-
-"No messages"
-"Inbox zero! You're crushing it today."
-```
-
-**Playful labels & tooltips**:
-```
-"Delete"
-"Send to void" (for playful brand)
-
-"Help"
-"Rescue me" (tooltip)
-```
-
-**IMPORTANT**: Match copy personality to brand. Banks shouldn't be wacky, but they can be warm.
-
-### Illustrations & Visual Personality
-
-**Custom illustrations**:
-- Empty state illustrations (not stock icons)
-- Error state illustrations (friendly monsters, quirky characters)
-- Loading state illustrations (animated characters)
-- Success state illustrations (celebrations)
-
-**Icon personality**:
-- Custom icon set matching brand personality
-- Animated icons (subtle motion on hover/click)
-- Illustrative icons (more detailed than generic)
-- Consistent style across all icons
-
-**Background effects**:
-- Subtle particle effects
-- Gradient mesh backgrounds
-- Geometric patterns
-- Parallax depth
-- Time-of-day themes (morning vs night)
-
-### Satisfying Interactions
-
-**Drag and drop delight**:
-- Lift effect on drag (shadow, scale)
-- Snap animation when dropped
-- Satisfying placement sound
-- Undo toast ("Dropped in wrong place? [Undo]")
-
-**Toggle switches**:
-- Smooth slide with spring physics
-- Color transition
-- Haptic feedback on mobile
-- Optional sound effect
-
-**Progress & achievements**:
-- Streak counters with celebratory milestones
-- Progress bars that "celebrate" at 100%
-- Badge unlocks with animation
-- Playful stats ("You're on fire! 5 days in a row")
-
-**Form interactions**:
-- Input fields that animate on focus
-- Checkboxes with a satisfying scale pulse when checked
-- Success state that celebrates valid input
-- Auto-grow textareas
-
-### Sound Design
-
-**Subtle audio cues** (when appropriate):
-- Notification sounds (distinctive but not annoying)
-- Success sounds (satisfying "ding")
-- Error sounds (empathetic, not harsh)
-- Typing sounds for chat/messaging
-- Ambient background audio (very subtle)
-
-**IMPORTANT**:
-- Respect system sound settings
-- Provide mute option
-- Keep volumes quiet (subtle cues, not alarms)
-- Don't play on every interaction (sound fatigue is real)
-
-### Easter Eggs & Hidden Delights
-
-**Discovery rewards**:
-- Konami code unlocks special theme
-- Hidden keyboard shortcuts (Cmd+K for special features)
-- Hover reveals on logos or illustrations
-- Alt text jokes on images (for screen reader users too!)
-- Console messages for developers ("Like what you see? We're hiring!")
-
-**Seasonal touches**:
-- Holiday themes (subtle, tasteful)
-- Seasonal color shifts
-- Weather-based variations
-- Time-based changes (dark at night, light during day)
-
-**Contextual personality**:
-- Different messages based on time of day
-- Responses to specific user actions
-- Randomized variations (not same every time)
-- Progressive reveals with continued use
-
-### Loading & Waiting States
-
-**Make waiting engaging**:
-- Interesting loading messages that rotate
-- Progress bars with personality
-- Mini-games during long loads
-- Fun facts or tips while waiting
-- Countdown with encouraging messages
-
-```
-Loading messages: write ones specific to your product, not generic AI filler:
-- "Crunching your latest numbers..."
-- "Syncing with your team's changes..."
-- "Preparing your dashboard..."
-- "Checking for updates since yesterday..."
-```
-
-**WARNING**: Avoid cliched loading messages like "Herding pixels", "Teaching robots to dance", "Consulting the magic 8-ball", "Counting backwards from infinity". These are AI-slop copy, instantly recognizable as machine-generated. Write messages that are specific to what your product actually does.
-
-### Celebration Moments
-
-**Success celebrations**:
-- Confetti for major milestones
-- Animated checkmarks for completions
-- Progress bar celebrations at 100%
-- "Achievement unlocked" style notifications
-- Personalized messages ("You published your 10th article!")
-
-**Milestone recognition**:
-- First-time actions get special treatment
-- Streak tracking and celebration
-- Progress toward goals
-- Anniversary celebrations
-
-## Implementation Patterns
-
-**Animation libraries**:
-- Framer Motion (React)
-- GSAP (universal)
-- Lottie (After Effects animations)
-- Canvas confetti (party effects)
-
-**Sound libraries**:
-- Howler.js (audio management)
-- Use-sound (React hook)
-
-**Physics libraries**:
-- React Spring (spring physics)
-- Popmotion (animation primitives)
-
-**IMPORTANT**: File size matters. Compress images, optimize animations, lazy load delight features.
-
-**NEVER**:
-- Delay core functionality for delight
-- Force users through delightful moments (make skippable)
-- Use delight to hide poor UX
-- Overdo it (less is more)
-- Ignore accessibility (animate responsibly, provide alternatives)
-- Make every interaction delightful (special moments should be special)
-- Sacrifice performance for delight
-- Be inappropriate for context (read the room)
-
-## Verify Delight Quality
-
-Test that delight actually delights:
-
-- **User reactions**: Do users smile? Share screenshots?
-- **Doesn't annoy**: Still pleasant after 100th time?
-- **Doesn't block**: Can users opt out or skip?
-- **Performant**: No jank, no slowdown
-- **Appropriate**: Matches brand and context
-- **Accessible**: Works with reduced motion, screen readers
-
-When the moments feel earned, hand off to `/impeccable polish` for the final pass.
@@ -1,111 +0,0 @@
-Strip a design to its essence. Remove anything that doesn't earn its place: redundant elements, repeated information, decorative noise, cosmetic complexity.
-
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel complex or cluttered:
-
-1. **Identify complexity sources**:
- - **Too many elements**: Competing buttons, redundant information, visual clutter
- - **Excessive variation**: Too many colors, fonts, sizes, styles without purpose
- - **Information overload**: Everything visible at once, no progressive disclosure
- - **Visual noise**: Unnecessary borders, shadows, backgrounds, decorations
- - **Confusing hierarchy**: Unclear what matters most
- - **Feature creep**: Too many options, actions, or paths forward
-
-2. **Find the essence**:
- - What's the primary user goal? (There should be ONE)
- - What's actually necessary vs nice-to-have?
- - What can be removed, hidden, or combined?
- - What's the 20% that delivers 80% of value?
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Simplicity is not about removing features. It's about removing obstacles between users and their goals. Every element should justify its existence.
-
-## Plan Simplification
-
-Create a ruthless editing strategy:
-
-- **Core purpose**: What's the ONE thing this should accomplish?
-- **Essential elements**: What's truly necessary to achieve that purpose?
-- **Progressive disclosure**: What can be hidden until needed?
-- **Consolidation opportunities**: What can be combined or integrated?
-
-**IMPORTANT**: Simplification is hard. It requires saying no to good ideas to make room for great execution. Be ruthless.
-
-## Simplify the Design
-
-Systematically remove complexity across these dimensions:
-
-### Information Architecture
-- **Reduce scope**: Remove secondary actions, optional features, redundant information
-- **Progressive disclosure**: Hide complexity behind clear entry points (accordions, modals, step-through flows)
-- **Combine related actions**: Merge similar buttons, consolidate forms, group related content
-- **Clear hierarchy**: ONE primary action, few secondary actions, everything else tertiary or hidden
-- **Remove redundancy**: If it's said elsewhere, don't repeat it here
-
-### Visual Simplification
-- **Reduce color palette**: Use 1-2 colors plus neutrals, not 5-7 colors
-- **Limit typography**: One font family, 3-4 sizes maximum, 2-3 weights
-- **Remove decorations**: Eliminate borders, shadows, backgrounds that don't serve hierarchy or function
-- **Flatten structure**: Reduce nesting, remove unnecessary containers; never nest cards inside cards
-- **Remove unnecessary cards**: Cards aren't needed for basic layout; use spacing and alignment instead
-- **Consistent spacing**: Use one spacing scale, remove arbitrary gaps
-
-### Layout Simplification
-- **Linear flow**: Replace complex grids with simple vertical flow where possible
-- **Remove sidebars**: Move secondary content inline or hide it
-- **Full-width**: Use available space generously instead of complex multi-column layouts
-- **Consistent alignment**: Pick left or center, stick with it
-- **Generous white space**: Let content breathe, don't pack everything tight
-
-### Interaction Simplification
-- **Reduce choices**: Fewer buttons, fewer options, clearer path forward (paradox of choice is real)
-- **Smart defaults**: Make common choices automatic, only ask when necessary
-- **Inline actions**: Replace modal flows with inline editing where possible
-- **Remove steps**: Can signup be one step instead of three? Can checkout be simplified?
-- **Clear CTAs**: ONE obvious next step, not five competing actions
-
-### Content Simplification
-- **Shorter copy**: Cut every sentence in half, then do it again
-- **Active voice**: "Save changes" not "Changes will be saved"
-- **Remove jargon**: Plain language always wins
-- **Scannable structure**: Short paragraphs, bullet points, clear headings
-- **Essential information only**: Remove marketing fluff, legalese, hedging
-- **Remove redundant copy**: No headers restating intros, no repeated explanations, say it once
-
-### Code Simplification
-- **Remove unused code**: Dead CSS, unused components, orphaned files
-- **Flatten component trees**: Reduce nesting depth
-- **Consolidate styles**: Merge similar styles, use utilities consistently
-- **Reduce variants**: Does that component need 12 variations, or can 3 cover 90% of cases?
-
-**NEVER**:
-- Remove necessary functionality (simplicity ≠ feature-less)
-- Sacrifice accessibility for simplicity (clear labels and ARIA still required)
-- Make things so simple they're unclear (mystery ≠ minimalism)
-- Remove information users need to make decisions
-- Eliminate hierarchy completely (some things should stand out)
-- Oversimplify complex domains (match complexity to actual task complexity)
-
-## Verify Simplification
-
-Ensure simplification improves usability:
-
-- **Faster task completion**: Can users accomplish goals more quickly?
-- **Reduced cognitive load**: Is it easier to understand what to do?
-- **Still complete**: Are all necessary features still accessible?
-- **Clearer hierarchy**: Is it obvious what matters most?
-- **Better performance**: Does simpler design load faster?
-
-## Document Removed Complexity
-
-If you removed features or options:
-- Document why they were removed
-- Consider if they need alternative access points
-- Note any user feedback to monitor
-
-When the cuts feel right, hand off to `/impeccable polish` for the final pass. As Antoine de Saint-Exupéry put it: "Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away."
@@ -1,427 +0,0 @@
-Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
-
-DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
-
-## The frontmatter: token schema
-
-The YAML frontmatter is the machine-readable layer. It's what Stitch's linter validates and what the live panel renders tiles from. Keep it tight; every entry should correspond to a token the project actually uses.
-
-```yaml
----
-name: <project title>
-description: <one-line tagline>
-colors:
- primary: "#b8422e"
- neutral-bg: "#faf7f2"
- # ...one entry per extracted color; key = descriptive slug
-typography:
- display:
- fontFamily: "Cormorant Garamond, Georgia, serif"
- fontSize: "clamp(2.5rem, 7vw, 4.5rem)"
- fontWeight: 300
- lineHeight: 1
- letterSpacing: "normal"
- body:
- # ...
-rounded:
- sm: "4px"
- md: "8px"
-spacing:
- sm: "8px"
- md: "16px"
-components:
- button-primary:
- backgroundColor: "{colors.primary}"
- textColor: "{colors.neutral-bg}"
- rounded: "{rounded.sm}"
- padding: "16px 48px"
- button-primary-hover:
- backgroundColor: "{colors.primary-deep}"
----
-```
-
-Rules that matter:
-
-- **Token refs** use `{path.to.token}` (e.g. `{colors.primary}`, `{rounded.md}`). Components may reference primitives; primitives may not reference each other.
-- **Stitch validates colors as hex sRGB only** (`#RGB` / `#RGBA` / `#RRGGBB` / `#RRGGBBAA`); OKLCH/HSL/P3 trigger a linter warning, not a hard error. YAML accepts the string either way and our own parser is format-agnostic. Choose based on project posture: (a) if the project has an "OKLCH-only" doctrine or uses Display-P3 values that don't round-trip through sRGB, put OKLCH directly in the frontmatter and accept the Stitch linter warning; (b) if the project wants strict Stitch compliance or plans to use their Tailwind/DTCG export pipeline, put hex in the frontmatter and keep OKLCH in prose as the canonical reference. Never split the source of truth without explicit reason.
-- **Component sub-tokens** are limited to 8 props: `backgroundColor`, `textColor`, `typography`, `rounded`, `padding`, `size`, `height`, `width`. Shadows, motion, focus rings, backdrop-filter: none of those fit. Carry them in the sidecar (Step 4b).
-- **Scale keys are open-ended.** Use whatever names the project already uses (`warm-ash-cream`, `surface-container-low`). Don't rename to Material defaults.
-- **Variants are naming convention, not schema.** `button-primary` / `button-primary-hover` / `button-primary-active` as sibling keys.
-
-## The markdown body: six sections (exact order)
-
-1. `## Overview`
-2. `## Colors`
-3. `## Typography`
-4. `## Elevation`
-5. `## Components`
-6. `## Do's and Don'ts`
-
-Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] Palette` (Stitch's own outputs do this), but the literal word in each header (Overview, Colors, Typography, Elevation, Components, Do's and Don'ts) must be present. Do NOT add extra top-level sections (Layout Principles, Responsive Behavior, Motion, Agent Prompt Guide). Fold that content into the six spec sections where it naturally belongs.
-
-## When to run
-
-- The user just ran `/impeccable teach` and needs the visual side documented.
-- The skill noticed no `DESIGN.md` exists and nudged the user to create one.
-- An existing `DESIGN.md` is stale (the design has drifted).
-- Before a large redesign, to capture the current state as a reference.
-
-If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user the existing file and ask the user directly to clarify what you cannot infer. whether to refresh, overwrite, or merge.
-
-## Two paths
-
-- **Scan mode** (default): the project has design tokens, components, or rendered output. Extract, then confirm descriptive language. Use when there's code to analyze.
-- **Seed mode**: the project is pre-implementation (fresh teach, nothing built yet). Interview for five high-level answers, write a minimal DESIGN.md marked `<!-- SEED -->`. Re-run in scan mode once there's code.
-
-Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode; don't silently switch. `/impeccable document --seed` forces seed mode regardless of code presence.
-
-## Scan mode (approach C: auto-extract, then confirm descriptive language)
-
-### Step 1: Find the design assets
-
-Search the codebase in priority order:
-
-1. **CSS custom properties**: grep for `--color-`, `--font-`, `--spacing-`, `--radius-`, `--shadow-`, `--ease-`, `--duration-` declarations in CSS files (usually `src/styles/`, `public/css/`, `app/globals.css`, etc.). Record name, value, and the file it's defined in.
-2. **Tailwind config**: if `tailwind.config.{js,ts,mjs}` exists, read the `theme.extend` block for colors, fontFamily, spacing, borderRadius, boxShadow.
-3. **CSS-in-JS theme files**: styled-components, emotion, vanilla-extract, stitches; look for `theme.ts`, `tokens.ts`, or equivalent.
-4. **Design token files**: `tokens.json`, `design-tokens.json`, Style Dictionary output, W3C token community group format.
-5. **Component library**: scan the main button, card, input, navigation, dialog components. Note their variant APIs and default styles.
-6. **Global stylesheet**: the root CSS file usually has the base typography and color assignments.
-7. **Visible rendered output**: if browser automation tools are available, load the live site and sample computed styles from key elements (body, h1, a, button, .card). This catches values that tokens miss.
-
-### Step 2: Auto-extract what can be auto-extracted
-
-Build a structured draft from the discovered tokens. For each token class:
-
-- **Colors**: Group into Primary / Secondary / Tertiary / Neutral (the Material-derived roles Stitch uses). If the project only has one accent, express it as Primary + Neutral; omit Secondary and Tertiary rather than inventing them.
-- **Typography**: Map observed sizes and weights to the Material hierarchy (display / headline / title / body / label). Note font-family stacks and the scale ratio.
-- **Elevation**: Catalogue the shadow vocabulary. If the project is flat and uses tonal layering instead, that's a valid answer; state it explicitly.
-- **Components**: For each common component (button, card, input, chip, list item, tooltip, nav), extract shape (radius), color assignment, hover/focus treatment, internal padding.
-- **Spacing + layout**: Fold into Overview or relevant Components. The spec does NOT have a Layout section.
-
-### Step 2b: Stage the frontmatter
-
-From the auto-extracted tokens, draft the YAML frontmatter now (you'll write it at the top of DESIGN.md in Step 4). This is the machine-readable layer: what the live panel and Stitch's linter consume.
-
-- **Colors**: one entry per extracted color. Key = descriptive slug (`warm-ash-cream`, `editorial-magenta`, not `blue-800`). Value = whichever format the project treats as canonical (OKLCH or hex; see the frontmatter rules above). Don't split the source of truth: one format in the frontmatter, don't redefine the same token in prose with a different value.
-- **Typography**: one entry per role (`display`, `headline`, `title`, `body`, `label`). Typography is an object; include only the props that are real for the project (`fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `fontFeature`, `fontVariation`).
-- **Rounded / Spacing**: whatever scale steps the project actually uses, keyed by whatever scale name the project uses (`sm` / `md` / `lg`, or `surface-sm`, or numeric steps).
-- **Components**: one entry per variant (`button-primary`, `button-primary-hover`, `button-ghost`). Reference primitives via `{colors.X}`, `{rounded.Y}`. If a variant needs a property Stitch's 8-prop set doesn't cover (shadow, focus ring, backdrop-filter), carry the full snippet in the sidecar instead.
-
-Skip anything the project doesn't have. Empty scale keys or fabricated tokens pollute the spec.
-
-### Step 3: Ask the user for qualitative language
-
-The following require creative input that cannot be auto-extracted. Group them into one `AskUserQuestion` interaction:
-
-- **Creative North Star**: a single named metaphor for the whole system ("The Editorial Sanctuary", "The Golden State Curator", "The Lab Notebook"). Offer 2-3 options that honor PRODUCT.md's brand personality.
-- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, anti-references (what the system should not feel like).
-- **Color character** (for auto-extracted colors): descriptive names ("Deep Muted Teal-Navy", not "blue-800"). Suggest 2-3 options per key color based on hue/saturation.
-- **Elevation philosophy**: flat/layered/lifted. If shadows exist, is their role ambient or structural?
-- **Component philosophy**: the feel of buttons, cards, inputs in one phrase ("tactile and confident" vs. "refined and restrained").
-
-Quote a line from PRODUCT.md when possible so the user sees their own strategic language carry forward.
-
-### Step 4: Write DESIGN.md
-
-The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the structure below. Headers must match character-for-character. Optional evocative subtitles (e.g. `## 2. Colors: The Coastal Palette`) are allowed.
-
-```markdown
----
-name: [Project Title]
-description: [one-line tagline]
-colors:
- # ... staged frontmatter from Step 2b
----
-
-# Design System: [Project Title]
-
-## 1. Overview
-
-**Creative North Star: "[Named metaphor in quotes]"**
-
-[2-3 paragraph holistic description: personality, density, aesthetic philosophy. Start from the North Star and work outward. State what this system explicitly rejects (pulled from PRODUCT.md's anti-references). End with a short **Key Characteristics:** bullet list.]
-
-## 2. Colors
-
-[Describe the palette character in one sentence.]
-
-### Primary
-- **[Descriptive Name]** (#HEX / oklch(...)): [Where and why this color is used. Be specific about context, not just role.]
-
-### Secondary (optional; omit if the project has only one accent)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Tertiary (optional)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Neutral
-- **[Descriptive Name]** (#HEX): [Text / background / border / divider role.]
-- [...]
-
-### Named Rules (optional, powerful)
-**The [Rule Name] Rule.** [Short, forceful prohibition or doctrine, e.g. "The One Voice Rule. The primary accent is used on ≤10% of any given screen. Its rarity is the point."]
-
-## 3. Typography
-
-**Display Font:** [Family] (with [fallback])
-**Body Font:** [Family] (with [fallback])
-**Label/Mono Font:** [Family, if distinct]
-
-**Character:** [1-2 sentence personality description of the pairing.]
-
-### Hierarchy
-- **Display** ([weight], [size/clamp], [line-height]): [Purpose; where it appears.]
-- **Headline** ([weight], [size], [line-height]): [Purpose.]
-- **Title** ([weight], [size], [line-height]): [Purpose.]
-- **Body** ([weight], [size], [line-height]): [Purpose. Include max line length like 65–75ch if relevant.]
-- **Label** ([weight], [size], [letter-spacing], [case if uppercase]): [Purpose.]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [Short doctrine about type use.]
-
-## 4. Elevation
-
-[One paragraph: does this system use shadows, tonal layering, or a hybrid? If "no shadows", say so explicitly and describe how depth is conveyed instead.]
-
-### Shadow Vocabulary (if applicable)
-- **[Role name]** (`box-shadow: [exact value]`): [When to use it.]
-- [...]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [e.g. "The Flat-By-Default Rule. Surfaces are flat at rest. Shadows appear only as a response to state (hover, elevation, focus)."]
-
-## 5. Components
-
-For each component, lead with a short character line, then specify shape, color assignment, states, and any distinctive behavior.
-
-### Buttons
-- **Shape:** [radius described, exact value in parens]
-- **Primary:** [color assignment + padding, in semantic + exact terms]
-- **Hover / Focus:** [transitions, treatments]
-- **Secondary / Ghost / Tertiary (if applicable):** [brief description]
-
-### Chips (if used)
-- **Style:** [background, text color, border treatment]
-- **State:** [selected / unselected, filter / action variants]
-
-### Cards / Containers
-- **Corner Style:** [radius]
-- **Background:** [colors used]
-- **Shadow Strategy:** [reference Elevation section]
-- **Border:** [if any]
-- **Internal Padding:** [scale]
-
-### Inputs / Fields
-- **Style:** [stroke, background, radius]
-- **Focus:** [treatment, e.g. glow, border shift, etc.]
-- **Error / Disabled:** [if applicable]
-
-### Navigation
-- **Style, typography, default/hover/active states, mobile treatment.**
-
-### [Signature Component] (optional; if the project has a distinctive custom component worth documenting)
-[Description.]
-
-## 6. Do's and Don'ts
-
-Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: include exact colors, pixel values, and named anti-patterns the user mentioned in PRODUCT.md. **Every anti-reference in PRODUCT.md should show up here as a "Don't" with the same language**, so the visual spec carries the strategic line through. Quote PRODUCT.md directly where possible: if PRODUCT.md says *"avoid dark mode with purple gradients, neon accents, glassmorphism"*, the Don'ts here should repeat that by name.
-
-### Do:
-- **Do** [specific prescription with exact values / named rule].
-- **Do** [...]
-
-### Don't:
-- **Don't** [specific prohibition, e.g. "use border-left greater than 1px as a colored stripe"].
-- **Don't** [...]
-- **Don't** [...]
-```
-
-### Step 4b: Write .impeccable/design.json sidecar (extensions only)
-
-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.
-
-Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.
-
-#### Schema
-
-```json
-{
- "schemaVersion": 2,
- "generatedAt": "ISO-8601 string",
- "title": "Design System: [Project Title]",
- "extensions": {
- "colorMeta": {
- "primary": { "role": "primary", "displayName": "Editorial Magenta", "canonical": "oklch(60% 0.25 350)", "tonalRamp": ["...", "...", "..."] },
- "warm-ash-cream": { "role": "neutral", "displayName": "Warm Ash Cream", "canonical": "oklch(96% 0.005 350)", "tonalRamp": ["...", "...", "..."] }
- },
- "typographyMeta": {
- "display": { "displayName": "Display", "purpose": "Hero headlines only." }
- },
- "shadows": [
- { "name": "ambient-low", "value": "0 4px 24px rgba(0,0,0,0.12)", "purpose": "Diffuse hover glow under accent elements." }
- ],
- "motion": [
- { "name": "ease-standard", "value": "cubic-bezier(0.4, 0, 0.2, 1)", "purpose": "Default easing for state transitions." }
- ],
- "breakpoints": [
- { "name": "sm", "value": "640px" }
- ]
- },
- "components": [
- {
- "name": "Primary Button",
- "kind": "button | input | nav | chip | card | custom",
- "refersTo": "button-primary",
- "description": "One-line what and when.",
- "html": "<button class=\"ds-btn-primary\">GET STARTED</button>",
- "css": ".ds-btn-primary { background: #191c1d; color: #fff; padding: 16px 48px; letter-spacing: 0.05em; text-transform: uppercase; font-weight: 500; border: none; border-radius: 0; transition: background 0.2s, transform 0.2s; } .ds-btn-primary:hover { background: oklch(60% 0.25 350); transform: translateY(-2px); }"
- }
- ],
- "narrative": {
- "northStar": "The Editorial Sanctuary",
- "overview": "2-3 paragraphs of the philosophy, pulled from DESIGN.md Overview section.",
- "keyCharacteristics": ["...", "..."],
- "rules": [{ "name": "The One Voice Rule", "body": "...", "section": "colors|typography|elevation" }],
- "dos": ["Do use ..."],
- "donts": ["Don't use ..."]
- }
-}
-```
-
-**What changed from schemaVersion 1.** The old sidecar carried token primitive arrays (`tokens.colors[]`, `tokens.typography[]`, etc.). Those values now live in the frontmatter. The sidecar only carries metadata that can't live in the frontmatter (tonal ramps, canonical OKLCH when the hex is an approximation, display names, role hints), keyed by the frontmatter token name (`colorMeta.<token-name>`, `typographyMeta.<token-name>`). Components still carry full HTML/CSS because Stitch's 8-prop set can't hold them.
-
-#### Component translation rules
-
-The `html` and `css` fields must be **self-contained, drop-in snippets** that render correctly when injected into a shadow DOM. The panel applies them directly: no post-processing, no framework runtime.
-
-1. **Tailwind expansion.** If the source uses Tailwind (className="bg-primary text-white rounded-lg px-6 py-3"), expand every utility to literal CSS properties in the `css` string. Do **not** reference Tailwind classes; do **not** assume a Tailwind CSS bundle is loaded. Each component is self-contained.
-2. **Token resolution.** If the project exposes tokens as CSS custom properties on `:root` (e.g. `--color-primary`, `--radius-md`), reference them via `var(--color-primary)`; they inherit through the shadow DOM and stay live-bound. If tokens live only in JS theme objects (styled-components, CSS-in-JS), resolve to literal values at generation time.
-3. **Icons.** Inline as SVG. Do not reference Lucide/Heroicons packages, icon fonts, or `<img src="...">`. A typical icon is 16-24px; copy the SVG path data directly.
-4. **States.** Include `:hover`, `:focus-visible`, and (if meaningful) `:active` rules inline. A static default-only snapshot makes the panel feel dead. Hover + focus rules in the CSS make it feel alive.
-5. **Reset bloat.** Extract only the component's *distinctive* CSS (background, color, padding, border-radius, typography, transition). Skip universal resets (`box-sizing: border-box`, `line-height: inherit`, `-webkit-font-smoothing`). The panel already has a neutral canvas; don't re-ship resets.
-6. **Scoped class names.** Prefix every class with `ds-` (e.g. `ds-btn-primary`, `ds-input-search`) so component CSS doesn't collide with other components' CSS in the same shadow DOM.
-
-#### What to include
-
-Aim for a tight set of **5-10 components** that best represent the visual system:
-
-- **Canonical primitives (always include if the project has them):** button (each variant as a separate component entry), input/text field, navigation, chip/tag, card.
-- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.
-- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.
-
-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.
-
-#### Tonal ramps
-
-For each color token, generate an 8-step `tonalRamp` array: dark to light, same hue and chroma, stepped lightness from ~15% to ~95%. The panel renders this as a strip under the swatch. If the project already defines a tonal scale (Material `surface-container-low` family, Tailwind-style `blue-50..blue-900`), use those values. Otherwise synthesize in OKLCH.
-
-#### Narrative mapping
-
-Pull directly from the DESIGN.md you just wrote:
-
-- `narrative.northStar` → the `**Creative North Star: "..."**` line from Overview
-- `narrative.overview` → the philosophy paragraphs from Overview
-- `narrative.keyCharacteristics` → the bulleted `**Key Characteristics:**` list
-- `narrative.rules` → every `**The [Name] Rule.** [body]` across all sections, tagged with `section`
-- `narrative.dos` / `narrative.donts` → the bullet lists from Do's and Don'ts verbatim
-
-Do not reword. The panel shows these as secondary collapsible context; the same voice that's in the Markdown carries through.
-
-### Step 5: Confirm, refine, and refresh session cache
-
-1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).
-2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.
-3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"
-4. **Refresh the session cache.** Run `node .pi/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.
-
-## Seed mode
-
-For projects with no visual system to extract yet. Produces a minimal scaffold, not a full spec.
-
-### Step 1: Confirm seed mode
-
-Before interviewing: "There's no existing visual system to scan. I'll ask five quick questions to seed a starter DESIGN.md. You can re-run `/impeccable document` once there's code, to capture the real tokens and components. OK?"
-
-If the user prefers to skip, stop. No file.
-
-### Step 2: Five questions
-
-Group into one `AskUserQuestion` interaction. Options must be concrete.
-
-1. **Color strategy.** Pick one:
- - Restrained: tinted neutrals + one accent ≤10%
- - Committed: one saturated color carries 30–60% of the surface
- - Full palette: 3–4 named color roles, each deliberate
- - Drenched: the surface IS the color
-
- Then: one hue family or anchor reference ("deep teal", "mustard", "Klim #ff4500 orange").
-
-2. **Typography direction.** Pick one (specific fonts come later):
- - Serif display + sans body
- - Single sans (warm / technical / geometric / humanist; pick a feel)
- - Display + mono
- - Mono-forward
- - Editorial script + sans
-
-3. **Motion energy.** Pick one:
- - Restrained: state changes only
- - Responsive: feedback + transitions, no choreography
- - Choreographed: orchestrated entrances, scroll-driven sequences
-
-4. **Three named references.** Brands, products, printed objects. Not adjectives.
-
-5. **One anti-reference.** What it should NOT feel like. Also named.
-
-### Step 3: Write seed DESIGN.md
-
-Use the six-section spec from Scan mode. Populate what the interview answers; leave the rest as honest placeholders. The seed is a scaffold, not a fabricated spec.
-
-Lead the file with:
-
-```markdown
-<!-- SEED: re-run /impeccable document once there's code to capture the actual tokens and components. -->
-```
-
-Per-section guidance in seed mode:
-
-- **Overview**: Creative North Star and philosophy phrased from the answers (color strategy + motion energy + references). Reference the user's anti-reference directly.
-- **Colors**: Color strategy as a Named Rule (e.g. *"The Drenched Rule. The surface IS the color."*). Hue family or anchor reference. No hex values; mark as `[to be resolved during implementation]`.
-- **Typography**: the direction the user picked (e.g. "Serif display + sans body"). No font names yet: `[font pairing to be chosen at implementation]`.
-- **Elevation**: inferred from motion energy. Restrained/Responsive → flat by default; Choreographed → layered. One sentence.
-- **Components**: omit entirely; no components exist yet.
-- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.
-
-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.
-
-### Step 4: Confirm and refresh session cache
-
-1. Show the seed DESIGN.md. Call out that it is a seed (the marker is the literal commitment).
-2. Tell the user: "Re-run `/impeccable document` once you have some code. That pass will extract real tokens and generate the sidecar."
-3. Run `node .pi/skills/impeccable/scripts/load-context.mjs` once so the seed lands in conversation for the rest of the session.
-
-## Style guidelines
-
-- **Frontmatter first, prose second.** Tokens go in the YAML frontmatter; prose contextualizes them. Don't redefine a token value in two places; the frontmatter is normative.
-- **Cite PRODUCT.md anti-references by name** in the Do's and Don'ts section. If PRODUCT.md lists "SaaS landing-page clichés" or "generic AI tool marketing" as anti-references, the DESIGN.md Don'ts should repeat those phrases verbatim so the visual spec enforces the strategic line.
-- **Match the spec, don't invent new sections.** The six section names are fixed. If you have Layout/Motion/Responsive content to document, fold it into Overview (philosophy-level rules) or Components (per-component behavior).
-- **Descriptive > technical**: "Gently curved edges (8px radius)" > "rounded-lg". Include the technical value in parens, lead with the description.
-- **Functional > decorative**: for each token, explain WHERE and WHY it's used, not just WHAT it is.
-- **Exact values in parens**: hex codes, px/rem values, font weights; always the number in parens alongside the description.
-- **Use Named Rules**: `**The [Name] Rule.** [short doctrine]`. These are memorable, citable, and much stickier for AI consumers than bullet lists. Stitch's own outputs use them heavily ("The No-Line Rule", "The Ghost Border Fallback"). Aim for 1-3 per section.
-- **Be forceful**. The voice of a design director. "Prohibited", "forbidden", "never", "always", not "consider", "might", "prefer". Match PRODUCT.md's tone.
-- **Concrete anti-pattern tests**. Stitch writes things like *"If it looks like a 2014 app, the shadow is too dark and the blur is too small."* A one-sentence audit test beats a paragraph of principle.
-- **Reference PRODUCT.md**. The anti-references section of PRODUCT.md should directly inform the Do's and Don'ts section here. Quote or paraphrase.
-- **Group colors by role**, not by hex-order or hue-order. Primary / Secondary / Tertiary / Neutral is the spec ordering.
-
-## Pitfalls
-
-- Don't paste raw CSS class names. Translate to descriptive language.
-- Don't extract every token. Stop at what's actually reused; one-offs pollute the system.
-- Don't invent components that don't exist. If the project only has buttons and cards, only document those.
-- Don't overwrite an existing DESIGN.md without asking.
-- Don't duplicate content from PRODUCT.md. DESIGN.md is strictly visual.
-- Don't add a "Layout Principles" or "Motion" or "Responsive Behavior" top-level section. The spec has six, not nine. Fold that content where it belongs.
-- Don't rename sections even slightly. "Colors" not "Color Palette & Roles". "Typography" not "Typography Rules". Tooling parsing depends on exact headers.
-- Don't duplicate token values between frontmatter and prose. If a color is in `colors.primary` as hex, the prose can name it and describe its role but should not reassert a different hex. The frontmatter is normative.
-- Don't invent frontmatter token groups outside Stitch's schema (no `motion:`, `breakpoints:`, `shadows:` at the top level). Stitch's Zod schema only accepts `colors`, `typography`, `rounded`, `spacing`, `components`. Anything else belongs in the sidecar's `extensions`.
@@ -1,69 +0,0 @@
-# Extract Flow
-
-Identify reusable patterns, components, and design tokens, then extract and consolidate them into the design system for systematic reuse.
-
-## Step 1: Discover the Design System
-
-Find the design system, component library, or shared UI directory. Understand its structure: component organization, naming conventions, design token structure, import/export conventions.
-
-**CRITICAL**: If no design system exists, ask the user directly to clarify what you cannot infer. before creating one. Understand the preferred location and structure first.
-
-## Step 2: Identify Patterns
-
-Look for extraction opportunities in the target area:
-
-- **Repeated components**: Similar UI patterns used 3+ times (buttons, cards, inputs)
-- **Hard-coded values**: Colors, spacing, typography, shadows that should be tokens
-- **Inconsistent variations**: Multiple implementations of the same concept
-- **Composition patterns**: Layout or interaction patterns that repeat (form rows, toolbar groups, empty states)
-- **Type styles**: Repeated font-size + weight + line-height combinations
-- **Animation patterns**: Repeated easing, duration, or keyframe combinations
-
-Assess value: only extract things used 3+ times with the same intent. Premature abstraction is worse than duplication.
-
-## Step 3: Plan Extraction
-
-Create a systematic plan:
-
-- **Components to extract**: Which UI elements become reusable components?
-- **Tokens to create**: Which hard-coded values become design tokens?
-- **Variants to support**: What variations does each component need?
-- **Naming conventions**: Component names, token names, prop names that match existing patterns
-- **Migration path**: How to refactor existing uses to consume the new shared versions
-
-**IMPORTANT**: Design systems grow incrementally. Extract what is clearly reusable now, not everything that might someday be reusable.
-
-## Step 4: Extract & Enrich
-
-Build improved, reusable versions:
-
-- **Components**: Clear props API with sensible defaults, proper variants for different use cases, accessibility built in (ARIA, keyboard navigation, focus management), documentation and usage examples
-- **Design tokens**: Clear naming (primitive vs semantic), proper hierarchy and organization, documentation of when to use each token
-- **Patterns**: When to use this pattern, code examples, variations and combinations
-
-## Step 5: Migrate
-
-Replace existing uses with the new shared versions:
-
-- **Find all instances**: Search for the patterns you extracted
-- **Replace systematically**: Update each use to consume the shared version
-- **Test thoroughly**: Ensure visual and functional parity
-- **Delete dead code**: Remove the old implementations
-
-## Step 6: Document
-
-Update design system documentation:
-
-- Add new components to the component library
-- Document token usage and values
-- Add examples and guidelines
-- Update any Storybook or component catalog
-
-**NEVER**:
-- Extract one-off, context-specific implementations without generalization
-- Create components so generic they are useless
-- Extract without considering existing design system conventions
-- Skip proper TypeScript types or prop documentation
-- Create tokens for every single value (tokens should have semantic meaning)
-- Extract things that differ in intent (two buttons that look similar but serve different purposes should stay separate)
-
@@ -1,347 +0,0 @@
-Designs that only work with perfect data aren't production-ready. Harden the interface against the inputs, errors, languages, and network conditions that real users will throw at it.
-
-## Assess Hardening Needs
-
-Identify weaknesses and edge cases:
-
-1. **Test with extreme inputs**:
- - Very long text (names, descriptions, titles)
- - Very short text (empty, single character)
- - Special characters (emoji, RTL text, accents)
- - Large numbers (millions, billions)
- - Many items (1000+ list items, 50+ options)
- - No data (empty states)
-
-2. **Test error scenarios**:
- - Network failures (offline, slow, timeout)
- - API errors (400, 401, 403, 404, 500)
- - Validation errors
- - Permission errors
- - Rate limiting
- - Concurrent operations
-
-3. **Test internationalization**:
- - Long translations (German is often 30% longer than English)
- - RTL languages (Arabic, Hebrew)
- - Character sets (Chinese, Japanese, Korean, emoji)
- - Date/time formats
- - Number formats (1,000 vs 1.000)
- - Currency symbols
-
-**CRITICAL**: Designs that only work with perfect data aren't production-ready. Harden against reality.
-
-## Hardening Dimensions
-
-Systematically improve resilience:
-
-### Text Overflow & Wrapping
-
-**Long text handling**:
-```css
-/* Single line with ellipsis */
-.truncate {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* Multi-line with clamp */
-.line-clamp {
- display: -webkit-box;
- -webkit-line-clamp: 3;
- -webkit-box-orient: vertical;
- overflow: hidden;
-}
-
-/* Allow wrapping */
-.wrap {
- word-wrap: break-word;
- overflow-wrap: break-word;
- hyphens: auto;
-}
-```
-
-**Flex/Grid overflow**:
-```css
-/* Prevent flex items from overflowing */
-.flex-item {
- min-width: 0; /* Allow shrinking below content size */
- overflow: hidden;
-}
-
-/* Prevent grid items from overflowing */
-.grid-item {
- min-width: 0;
- min-height: 0;
-}
-```
-
-**Responsive text sizing**:
-- Use `clamp()` for fluid typography
-- Set minimum readable sizes (14px on mobile)
-- Test text scaling (zoom to 200%)
-- Ensure containers expand with text
-
-### Internationalization (i18n)
-
-**Text expansion**:
-- Add 30-40% space budget for translations
-- Use flexbox/grid that adapts to content
-- Test with longest language (usually German)
-- Avoid fixed widths on text containers
-
-```jsx
-// ❌ Bad: Assumes short English text
-<button className="w-24">Submit</button>
-
-// ✅ Good: Adapts to content
-<button className="px-4 py-2">Submit</button>
-```
-
-**RTL (Right-to-Left) support**:
-```css
-/* Use logical properties */
-margin-inline-start: 1rem; /* Not margin-left */
-padding-inline: 1rem; /* Not padding-left/right */
-border-inline-end: 1px solid; /* Not border-right */
-
-/* Or use dir attribute */
-[dir="rtl"] .arrow { transform: scaleX(-1); }
-```
-
-**Character set support**:
-- Use UTF-8 encoding everywhere
-- Test with Chinese/Japanese/Korean (CJK) characters
-- Test with emoji (they can be 2-4 bytes)
-- Handle different scripts (Latin, Cyrillic, Arabic, etc.)
-
-**Date/Time formatting**:
-```javascript
-// ✅ Use Intl API for proper formatting
-new Intl.DateTimeFormat('en-US').format(date); // 1/15/2024
-new Intl.DateTimeFormat('de-DE').format(date); // 15.1.2024
-
-new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: 'USD'
-}).format(1234.56); // $1,234.56
-```
-
-**Pluralization**:
-```javascript
-// ❌ Bad: Assumes English pluralization
-`${count} item${count !== 1 ? 's' : ''}`
-
-// ✅ Good: Use proper i18n library
-t('items', { count }) // Handles complex plural rules
-```
-
-### Error Handling
-
-**Network errors**:
-- Show clear error messages
-- Provide retry button
-- Explain what happened
-- Offer offline mode (if applicable)
-- Handle timeout scenarios
-
-```jsx
-// Error states with recovery
-{error && (
- <ErrorMessage>
- <p>Failed to load data. {error.message}</p>
- <button onClick={retry}>Try again</button>
- </ErrorMessage>
-)}
-```
-
-**Form validation errors**:
-- Inline errors near fields
-- Clear, specific messages
-- Suggest corrections
-- Don't block submission unnecessarily
-- Preserve user input on error
-
-**API errors**:
-- Handle each status code appropriately
- - 400: Show validation errors
- - 401: Redirect to login
- - 403: Show permission error
- - 404: Show not found state
- - 429: Show rate limit message
- - 500: Show generic error, offer support
-
-**Graceful degradation**:
-- Core functionality works without JavaScript
-- Images have alt text
-- Progressive enhancement
-- Fallbacks for unsupported features
-
-### Edge Cases & Boundary Conditions
-
-**Empty states**:
-- No items in list
-- No search results
-- No notifications
-- No data to display
-- Provide clear next action
-
-**Loading states**:
-- Initial load
-- Pagination load
-- Refresh
-- Show what's loading ("Loading your projects...")
-- Time estimates for long operations
-
-**Large datasets**:
-- Pagination or virtual scrolling
-- Search/filter capabilities
-- Performance optimization
-- Don't load all 10,000 items at once
-
-**Concurrent operations**:
-- Prevent double-submission (disable button while loading)
-- Handle race conditions
-- Optimistic updates with rollback
-- Conflict resolution
-
-**Permission states**:
-- No permission to view
-- No permission to edit
-- Read-only mode
-- Clear explanation of why
-
-**Browser compatibility**:
-- Polyfills for modern features
-- Fallbacks for unsupported CSS
-- Feature detection (not browser detection)
-- Test in target browsers
-
-### Input Validation & Sanitization
-
-**Client-side validation**:
-- Required fields
-- Format validation (email, phone, URL)
-- Length limits
-- Pattern matching
-- Custom validation rules
-
-**Server-side validation** (always):
-- Never trust client-side only
-- Validate and sanitize all inputs
-- Protect against injection attacks
-- Rate limiting
-
-**Constraint handling**:
-```html
-<!-- Set clear constraints -->
-<input
- type="text"
- maxlength="100"
- pattern="[A-Za-z0-9]+"
- required
- aria-describedby="username-hint"
-/>
-<small id="username-hint">
- Letters and numbers only, up to 100 characters
-</small>
-```
-
-### Accessibility Resilience
-
-**Keyboard navigation**:
-- All functionality accessible via keyboard
-- Logical tab order
-- Focus management in modals
-- Skip links for long content
-
-**Screen reader support**:
-- Proper ARIA labels
-- Announce dynamic changes (live regions)
-- Descriptive alt text
-- Semantic HTML
-
-**Motion sensitivity**:
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**High contrast mode**:
-- Test in Windows high contrast mode
-- Don't rely only on color
-- Provide alternative visual cues
-
-### Performance Resilience
-
-**Slow connections**:
-- Progressive image loading
-- Skeleton screens
-- Optimistic UI updates
-- Offline support (service workers)
-
-**Memory leaks**:
-- Clean up event listeners
-- Cancel subscriptions
-- Clear timers/intervals
-- Abort pending requests on unmount
-
-**Throttling & Debouncing**:
-```javascript
-// Debounce search input
-const debouncedSearch = debounce(handleSearch, 300);
-
-// Throttle scroll handler
-const throttledScroll = throttle(handleScroll, 100);
-```
-
-## Testing Strategies
-
-**Manual testing**:
-- Test with extreme data (very long, very short, empty)
-- Test in different languages
-- Test offline
-- Test slow connection (throttle to 3G)
-- Test with screen reader
-- Test keyboard-only navigation
-- Test on old browsers
-
-**Automated testing**:
-- Unit tests for edge cases
-- Integration tests for error scenarios
-- E2E tests for critical paths
-- Visual regression tests
-- Accessibility tests (axe, WAVE)
-
-**IMPORTANT**: Hardening is about expecting the unexpected. Real users will do things you never imagined.
-
-**NEVER**:
-- Assume perfect input (validate everything)
-- Ignore internationalization (design for global)
-- Leave error messages generic ("Error occurred")
-- Forget offline scenarios
-- Trust client-side validation alone
-- Use fixed widths for text
-- Assume English-length text
-- Block entire interface when one component errors
-
-## Verify Hardening
-
-Test thoroughly with edge cases:
-
-- **Long text**: Try names with 100+ characters
-- **Emoji**: Use emoji in all text fields
-- **RTL**: Test with Arabic or Hebrew
-- **CJK**: Test with Chinese/Japanese/Korean
-- **Network issues**: Disable internet, throttle connection
-- **Large datasets**: Test with 1000+ items
-- **Concurrent actions**: Click submit 10 times rapidly
-- **Errors**: Force API errors, test all error states
-- **Empty**: Remove all data, test empty states
-
-When edge cases are covered, hand off to `/impeccable polish` for the final pass.
@@ -1,234 +0,0 @@
-# Heuristics Scoring Guide
-
-Score each of Nielsen's 10 Usability Heuristics on a 0–4 scale. Be honest: a 4 means genuinely excellent, not "good enough."
-
-## Nielsen's 10 Heuristics
-
-### 1. Visibility of System Status
-
-Keep users informed about what's happening through timely, appropriate feedback.
-
-**Check for**:
-- Loading indicators during async operations
-- Confirmation of user actions (save, submit, delete)
-- Progress indicators for multi-step processes
-- Current location in navigation (breadcrumbs, active states)
-- Form validation feedback (inline, not just on submit)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No feedback; user is guessing what happened |
-| 1 | Rare feedback; most actions produce no visible response |
-| 2 | Partial; some states communicated, major gaps remain |
-| 3 | Good; most operations give clear feedback, minor gaps |
-| 4 | Excellent; every action confirms, progress is always visible |
-
-### 2. Match Between System and Real World
-
-Speak the user's language. Follow real-world conventions. Information appears in natural, logical order.
-
-**Check for**:
-- Familiar terminology (no unexplained jargon)
-- Logical information order matching user expectations
-- Recognizable icons and metaphors
-- Domain-appropriate language for the target audience
-- Natural reading flow (left-to-right, top-to-bottom priority)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Pure tech jargon, alien to users |
-| 1 | Mostly confusing; requires domain expertise to navigate |
-| 2 | Mixed; some plain language, some jargon leaks through |
-| 3 | Mostly natural; occasional term needs context |
-| 4 | Speaks the user's language fluently throughout |
-
-### 3. User Control and Freedom
-
-Users need a clear "emergency exit" from unwanted states without extended dialogue.
-
-**Check for**:
-- Undo/redo functionality
-- Cancel buttons on forms and modals
-- Clear navigation back to safety (home, previous)
-- Easy way to clear filters, search, selections
-- Escape from long or multi-step processes
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Users get trapped; no way out without refreshing |
-| 1 | Difficult exits; must find obscure paths to escape |
-| 2 | Some exits; main flows have escape, edge cases don't |
-| 3 | Good control; users can exit and undo most actions |
-| 4 | Full control; undo, cancel, back, and escape everywhere |
-
-### 4. Consistency and Standards
-
-Users shouldn't wonder whether different words, situations, or actions mean the same thing.
-
-**Check for**:
-- Consistent terminology throughout the interface
-- Same actions produce same results everywhere
-- Platform conventions followed (standard UI patterns)
-- Visual consistency (colors, typography, spacing, components)
-- Consistent interaction patterns (same gesture = same behavior)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Inconsistent everywhere; feels like different products stitched together |
-| 1 | Many inconsistencies; similar things look/behave differently |
-| 2 | Partially consistent; main flows match, details diverge |
-| 3 | Mostly consistent; occasional deviation, nothing confusing |
-| 4 | Fully consistent; cohesive system, predictable behavior |
-
-### 5. Error Prevention
-
-Better than good error messages is a design that prevents problems in the first place.
-
-**Check for**:
-- Confirmation before destructive actions (delete, overwrite)
-- Constraints preventing invalid input (date pickers, dropdowns)
-- Smart defaults that reduce errors
-- Clear labels that prevent misunderstanding
-- Autosave and draft recovery
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Errors easy to make; no guardrails anywhere |
-| 1 | Few safeguards; some inputs validated, most aren't |
-| 2 | Partial prevention; common errors caught, edge cases slip |
-| 3 | Good prevention; most error paths blocked proactively |
-| 4 | Excellent; errors nearly impossible through smart constraints |
-
-### 6. Recognition Rather Than Recall
-
-Minimize memory load. Make objects, actions, and options visible or easily retrievable.
-
-**Check for**:
-- Visible options (not buried in hidden menus)
-- Contextual help when needed (tooltips, inline hints)
-- Recent items and history
-- Autocomplete and suggestions
-- Labels on icons (not icon-only navigation)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Heavy memorization; users must remember paths and commands |
-| 1 | Mostly recall; many hidden features, few visible cues |
-| 2 | Some aids; main actions visible, secondary features hidden |
-| 3 | Good recognition; most things discoverable, few memory demands |
-| 4 | Everything discoverable; users never need to memorize |
-
-### 7. Flexibility and Efficiency of Use
-
-Accelerators, invisible to novices, speed up expert interaction.
-
-**Check for**:
-- Keyboard shortcuts for common actions
-- Customizable interface elements
-- Recent items and favorites
-- Bulk/batch actions
-- Power user features that don't complicate the basics
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | One rigid path; no shortcuts or alternatives |
-| 1 | Limited flexibility; few alternatives to the main path |
-| 2 | Some shortcuts; basic keyboard support, limited bulk actions |
-| 3 | Good accelerators; keyboard nav, some customization |
-| 4 | Highly flexible; multiple paths, power features, customizable |
-
-### 8. Aesthetic and Minimalist Design
-
-Interfaces should not contain irrelevant or rarely needed information. Every element should serve a purpose.
-
-**Check for**:
-- Only necessary information visible at each step
-- Clear visual hierarchy directing attention
-- Purposeful use of color and emphasis
-- No decorative clutter competing for attention
-- Focused, uncluttered layouts
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Overwhelming; everything competes for attention equally |
-| 1 | Cluttered; too much noise, hard to find what matters |
-| 2 | Some clutter; main content clear, periphery noisy |
-| 3 | Mostly clean; focused design, minor visual noise |
-| 4 | Perfectly minimal; every element earns its pixel |
-
-### 9. Help Users Recognize, Diagnose, and Recover from Errors
-
-Error messages should use plain language, precisely indicate the problem, and constructively suggest a solution.
-
-**Check for**:
-- Plain language error messages (no error codes for users)
-- Specific problem identification ("Email is missing @" not "Invalid input")
-- Actionable recovery suggestions
-- Errors displayed near the source of the problem
-- Non-blocking error handling (don't wipe the form)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Cryptic errors; codes, jargon, or no message at all |
-| 1 | Vague errors; "Something went wrong" with no guidance |
-| 2 | Clear but unhelpful; names the problem but not the fix |
-| 3 | Clear with suggestions; identifies problem and offers next steps |
-| 4 | Perfect recovery; pinpoints issue, suggests fix, preserves user work |
-
-### 10. Help and Documentation
-
-Even if the system is usable without docs, help should be easy to find, task-focused, and concise.
-
-**Check for**:
-- Searchable help or documentation
-- Contextual help (tooltips, inline hints, guided tours)
-- Task-focused organization (not feature-organized)
-- Concise, scannable content
-- Easy access without leaving current context
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No help available anywhere |
-| 1 | Help exists but hard to find or irrelevant |
-| 2 | Basic help; FAQ or docs exist, not contextual |
-| 3 | Good documentation; searchable, mostly task-focused |
-| 4 | Excellent contextual help; right info at the right moment |
-
----
-
-## Score Summary
-
-**Total possible**: 40 points (10 heuristics × 4 max)
-
-| Score Range | Rating | What It Means |
-|-------------|--------|---------------|
-| 36–40 | Excellent | Minor polish only; ship it |
-| 28–35 | Good | Address weak areas, solid foundation |
-| 20–27 | Acceptable | Significant improvements needed before users are happy |
-| 12–19 | Poor | Major UX overhaul required; core experience broken |
-| 0–11 | Critical | Redesign needed; unusable in current state |
-
----
-
-## Issue Severity (P0–P3)
-
-Tag each individual issue found during scoring with a priority level:
-
-| Priority | Name | Description | Action |
-|----------|------|-------------|--------|
-| **P0** | Blocking | Prevents task completion entirely | Fix immediately; this is a showstopper |
-| **P1** | Major | Causes significant difficulty or confusion | Fix before release |
-| **P2** | Minor | Annoyance, but workaround exists | Fix in next pass |
-| **P3** | Polish | Nice-to-fix, no real user impact | Fix if time permits |
-
-**Tip**: If you're unsure between two levels, ask: "Would a user contact support about this?" If yes, it's at least P1.
@@ -1,195 +0,0 @@
-# Interaction Design
-
-## The Eight Interactive States
-
-Every interactive element needs these states designed:
-
-| State | When | Visual Treatment |
-|-------|------|------------------|
-| **Default** | At rest | Base styling |
-| **Hover** | Pointer over (not touch) | Subtle lift, color shift |
-| **Focus** | Keyboard/programmatic focus | Visible ring (see below) |
-| **Active** | Being pressed | Pressed in, darker |
-| **Disabled** | Not interactive | Reduced opacity, no pointer |
-| **Loading** | Processing | Spinner, skeleton |
-| **Error** | Invalid state | Red border, icon, message |
-| **Success** | Completed | Green check, confirmation |
-
-**The common miss**: Designing hover without focus, or vice versa. They're different. Keyboard users never see hover states.
-
-## Focus Rings: Do Them Right
-
-**Never `outline: none` without replacement.** It's an accessibility violation. Instead, use `:focus-visible` to show focus only for keyboard users:
-
-```css
-/* Hide focus ring for mouse/touch */
-button:focus {
- outline: none;
-}
-
-/* Show focus ring for keyboard */
-button:focus-visible {
- outline: 2px solid var(--color-accent);
- outline-offset: 2px;
-}
-```
-
-**Focus ring design**:
-- High contrast (3:1 minimum against adjacent colors)
-- 2-3px thick
-- Offset from element (not inside it)
-- Consistent across all interactive elements
-
-## Form Design: The Non-Obvious
-
-**Placeholders aren't labels.** They disappear on input. Always use visible `<label>` elements. **Validate on blur**, not on every keystroke (exception: password strength). Place errors **below** fields with `aria-describedby` connecting them.
-
-## Loading States
-
-**Optimistic updates**: Show success immediately, rollback on failure. Use for low-stakes actions (likes, follows), not payments or destructive actions. **Skeleton screens > spinners**: they preview content shape and feel faster than generic spinners.
-
-## Modals: The Inert Approach
-
-Focus trapping in modals used to require complex JavaScript. Now use the `inert` attribute:
-
-```html
-<!-- When modal is open -->
-<main inert>
- <!-- Content behind modal can't be focused or clicked -->
-</main>
-<dialog open>
- <h2>Modal Title</h2>
- <!-- Focus stays inside modal -->
-</dialog>
-```
-
-Or use the native `<dialog>` element:
-
-```javascript
-const dialog = document.querySelector('dialog');
-dialog.showModal(); // Opens with focus trap, closes on Escape
-```
-
-## The Popover API
-
-For tooltips, dropdowns, and non-modal overlays, use native popovers:
-
-```html
-<button popovertarget="menu">Open menu</button>
-<div id="menu" popover>
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-**Benefits**: Light-dismiss (click outside closes), proper stacking, no z-index wars, accessible by default.
-
-## Dropdown & Overlay Positioning
-
-Dropdowns rendered with `position: absolute` inside a container that has `overflow: hidden` or `overflow: auto` will be clipped. This is the single most common dropdown bug in generated code.
-
-### CSS Anchor Positioning
-
-The modern solution uses the CSS Anchor Positioning API to tether an overlay to its trigger without JavaScript:
-
-```css
-.trigger {
- anchor-name: --menu-trigger;
-}
-
-.dropdown {
- position: fixed;
- position-anchor: --menu-trigger;
- position-area: block-end span-inline-end;
- margin-top: 4px;
-}
-
-/* Flip above if no room below */
-@position-try --flip-above {
- position-area: block-start span-inline-end;
- margin-bottom: 4px;
-}
-```
-
-Because the dropdown uses `position: fixed`, it escapes any `overflow` clipping on ancestor elements. The `@position-try` block handles viewport edges automatically. **Browser support**: Chrome 125+, Edge 125+. Not yet in Firefox or Safari - use a fallback for those browsers.
-
-### Popover + Anchor Combo
-
-Combining the Popover API with anchor positioning gives you stacking, light-dismiss, accessibility, and correct positioning in one pattern:
-
-```html
-<button popovertarget="menu" class="trigger">Open</button>
-<div id="menu" popover class="dropdown">
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-The `popover` attribute places the element in the **top layer**, which sits above all other content regardless of z-index or overflow. No portal needed.
-
-### Portal / Teleport Pattern
-
-In component frameworks, render the dropdown at the document root and position it with JavaScript:
-
-- **React**: `createPortal(dropdown, document.body)`
-- **Vue**: `<Teleport to="body">`
-- **Svelte**: Use a portal library or mount to `document.body`
-
-Calculate position from the trigger's `getBoundingClientRect()`, then apply `position: fixed` with `top` and `left` values. Recalculate on scroll and resize.
-
-### Fixed Positioning Fallback
-
-For browsers without anchor positioning support, `position: fixed` with manual coordinates avoids overflow clipping:
-
-```css
-.dropdown {
- position: fixed;
- /* top/left set via JS from trigger's getBoundingClientRect() */
-}
-```
-
-Check viewport boundaries before rendering. If the dropdown would overflow the bottom edge, flip it above the trigger. If it would overflow the right edge, align it to the trigger's right side instead.
-
-### Anti-Patterns
-
-- **`position: absolute` inside `overflow: hidden`** - The dropdown will be clipped. Use `position: fixed` or the top layer instead.
-- **Arbitrary z-index values** like `z-index: 9999` - Use a semantic z-index scale: `dropdown (100) -> sticky (200) -> modal-backdrop (300) -> modal (400) -> toast (500) -> tooltip (600)`.
-- **Rendering dropdown markup inline** without an escape hatch from the parent's stacking context. Either use `popover` (top layer), a portal, or `position: fixed`.
-
-## Destructive Actions: Undo > Confirm
-
-**Undo is better than confirmation dialogs.** Users click through confirmations mindlessly. Remove from UI immediately, show undo toast, actually delete after toast expires. Use confirmation only for truly irreversible actions (account deletion), high-cost actions, or batch operations.
-
-## Keyboard Navigation Patterns
-
-### Roving Tabindex
-
-For component groups (tabs, menu items, radio groups), one item is tabbable; arrow keys move within:
-
-```html
-<div role="tablist">
- <button role="tab" tabindex="0">Tab 1</button>
- <button role="tab" tabindex="-1">Tab 2</button>
- <button role="tab" tabindex="-1">Tab 3</button>
-</div>
-```
-
-Arrow keys move `tabindex="0"` between items. Tab moves to the next component entirely.
-
-### Skip Links
-
-Provide skip links (`<a href="#main-content">Skip to main content</a>`) for keyboard users to jump past navigation. Hide off-screen, show on focus.
-
-## Gesture Discoverability
-
-Swipe-to-delete and similar gestures are invisible. Hint at their existence:
-
-- **Partially reveal**: Show delete button peeking from edge
-- **Onboarding**: Coach marks on first use
-- **Alternative**: Always provide a visible fallback (menu with "Delete")
-
-Don't rely on gestures as the only way to perform actions.
-
----
-
-**Avoid**: Removing focus indicators without alternatives. Using placeholder text as labels. Touch targets <44x44px. Generic error messages. Custom controls without ARIA/keyboard support.
@@ -1,141 +0,0 @@
-Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids, the centered-stack default) and fix the structure, not the surface.
-
----
-
-## Register
-
-Brand: asymmetric compositions, fluid spacing with `clamp()`, intentional grid-breaking for emphasis. Rhythm through contrast: tight groupings paired with generous separations.
-
-Product: predictable grids, consistent densities, familiar navigation patterns. Responsive behavior is structural (collapse sidebar, responsive table), not fluid typography. Consistency IS an affordance.
-
----
-
-## Assess Current Layout
-
-Analyze what's weak about the current spatial design:
-
-1. **Spacing**:
- - Is spacing consistent or arbitrary? (Random padding/margin values)
- - Is all spacing the same? (Equal padding everywhere = no rhythm)
- - Are related elements grouped tightly, with generous space between groups?
-
-2. **Visual hierarchy**:
- - Apply the squint test: blur your (metaphorical) eyes. Can you still identify the most important element, second most important, and clear groupings?
- - Is hierarchy achieved effectively? (Space and weight alone can be enough; is the current approach working?)
- - Does whitespace guide the eye to what matters?
-
-3. **Grid & structure**:
- - Is there a clear underlying structure, or does the layout feel random?
- - Are identical card grids used everywhere? (Icon + heading + text, repeated endlessly)
- - Is everything centered? (Left-aligned with asymmetric layouts feels more designed, but not a hard and fast rule)
-
-4. **Rhythm & variety**:
- - Does the layout have visual rhythm? (Alternating tight/generous spacing)
- - Is every section structured the same way? (Monotonous repetition)
- - Are there intentional moments of surprise or emphasis?
-
-5. **Density**:
- - Is the layout too cramped? (Not enough breathing room)
- - Is the layout too sparse? (Excessive whitespace without purpose)
- - Does density match the content type? (Data-dense UIs need tighter spacing; marketing pages need more air)
-
-**CRITICAL**: Layout problems are often the root cause of interfaces feeling "off" even when colors and fonts are fine. Space is a design material; use it with intention.
-
-## Plan Layout Improvements
-
-Consult the [spatial design reference](spatial-design.md) for detailed guidance on grids, rhythm, and container queries.
-
-Create a systematic plan:
-
-- **Spacing system**: Use a consistent scale (a framework's built-in scale like Tailwind's, rem-based tokens, or a custom system). The specific values matter less than consistency.
-- **Hierarchy strategy**: How will space communicate importance?
-- **Layout approach**: What structure fits the content? Flex for 1D, Grid for 2D, named areas for complex page layouts.
-- **Rhythm**: Where should spacing be tight vs generous?
-
-## Improve Layout Systematically
-
-### Establish a Spacing System
-
-- Use a consistent spacing scale (framework scales like Tailwind, rem-based tokens, or a custom scale all work). What matters is that values come from a defined set, not arbitrary numbers.
-- Name tokens semantically if using custom properties: `--space-xs` through `--space-xl`, not `--spacing-8`
-- Use `gap` for sibling spacing instead of margins; eliminates margin collapse hacks
-- Apply `clamp()` for fluid spacing that breathes on larger screens
-
-### Create Visual Rhythm
-
-- **Tight grouping** for related elements (8-12px between siblings)
-- **Generous separation** between distinct sections (48-96px)
-- **Varied spacing** within sections (not every row needs the same gap)
-- **Asymmetric compositions**: break the predictable centered-content pattern when it makes sense
-
-### Choose the Right Layout Tool
-
-- **Use Flexbox for 1D layouts**: Rows of items, nav bars, button groups, card contents, most component internals. Flex is simpler and more appropriate for the majority of layout tasks.
-- **Use Grid for 2D layouts**: Page-level structure, dashboards, data-dense interfaces, anything where rows AND columns need coordinated control.
-- **Don't default to Grid** when Flexbox with `flex-wrap` would be simpler and more flexible.
-- Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints.
-- Use named grid areas (`grid-template-areas`) for complex page layouts; redefine at breakpoints.
-
-### Break Card Grid Monotony
-
-- Don't default to card grids for everything; spacing and alignment create visual grouping naturally
-- Use cards only when content is truly distinct and actionable. Never nest cards inside cards
-- Vary card sizes, span columns, or mix cards with non-card content to break repetition
-
-### Strengthen Visual Hierarchy
-
-- Use the fewest dimensions needed for clear hierarchy. Space alone can be enough; generous whitespace around an element draws the eye. Some of the most polished designs achieve rhythm with just space and weight. Add color or size contrast only when simpler means aren't sufficient.
-- Be aware of reading flow: in LTR languages, the eye naturally scans top-left to bottom-right, but primary action placement depends on context (e.g., bottom-right in dialogs, top in navigation).
-- Create clear content groupings through proximity and separation.
-
-### Manage Depth & Elevation
-
-- Create a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip)
-- Build a consistent shadow scale (sm → md → lg → xl); shadows should be subtle
-- Use elevation to reinforce hierarchy, not as decoration
-
-### Optical Adjustments
-
-- If an icon looks visually off-center despite being geometrically centered, nudge it. But only if you're confident it actually looks wrong. Don't adjust speculatively.
-
-**NEVER**:
-- Use arbitrary spacing values outside your scale
-- Make all spacing equal (variety creates hierarchy)
-- Wrap everything in cards (not everything needs a container)
-- Nest cards inside cards (use spacing and dividers for hierarchy within)
-- Use identical card grids everywhere (icon + heading + text, repeated)
-- Center everything (left-aligned with asymmetry feels more designed)
-- Default to the hero metric layout (big number, small label, stats, gradient) as a template. If showing real user data, a prominent metric can work, but it should display actual data, not decorative numbers.
-- Default to CSS Grid when Flexbox would be simpler; use the simplest tool for the job
-- Use arbitrary z-index values (999, 9999); build a semantic scale
-
-## Verify Layout Improvements
-
-- **Squint test**: Can you identify primary, secondary, and groupings with blurred vision?
-- **Rhythm**: Does the page have a satisfying beat of tight and generous spacing?
-- **Hierarchy**: Is the most important content obvious within 2 seconds?
-- **Breathing room**: Does the layout feel comfortable, not cramped or wasteful?
-- **Consistency**: Is the spacing system applied uniformly?
-- **Responsiveness**: Does the layout adapt gracefully across screen sizes?
-
-When the rhythm and hierarchy land, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `density` param. Drive all spacing tokens in the variant's scoped CSS through `calc(var(--p-density, 1) * <base>)`: paddings, gaps, column widths. Users slide from airy to packed and see layout re-breathe with no regeneration.
-
-```json
-{"id":"density","kind":"range","min":0.6,"max":1.4,"step":0.05,"default":1,"label":"Density"}
-```
-
-For variants whose topology genuinely changes (stacked vs. side-by-side, grid vs. bento), use a `steps` param whose scoped CSS branches via `:scope[data-p-structure="X"]`. One structure param + one density param is a powerful combo; resist adding a third.
-
-```json
-{"id":"structure","kind":"steps","default":"grid","label":"Structure","options":[
- {"value":"stacked","label":"Stacked"},
- {"value":"grid","label":"Grid"},
- {"value":"bento","label":"Bento"}
-]}
-```
-
-See `reference/live.md` for the full params contract.
@@ -1,622 +0,0 @@
-Interactive live variant mode: select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via the dev server's HMR.
-
-## Prerequisites
-
-A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR a static HTML file open in the browser.
-
-## The contract (read once)
-
-Execute in order. No step skipped, no step reordered.
-
-1. `live.mjs`: boot.
-2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.
-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.
-5. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
-6. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
-7. On `exit`: run the cleanup at the bottom.
-
-Harness policy:
-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.
-- **Cursor**: run the poll in the **foreground** (blocking shell; not a background terminal, not a subagent). Cursor background terminals and subagents do not reliably resume the chat with poll stdout.
-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.
-- **Other harnesses**: foreground unless you know stdout reliably returns to this session.
-
-Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.
-
-## Start
-
-```bash
-node .pi/skills/impeccable/scripts/live.mjs
-```
-
-Output JSON: `{ ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath, migrated }`. `pageFiles` is the list of HTML entries the live script was injected into. Keep PRODUCT.md and DESIGN.md in mind for variant generation; **DESIGN.md wins on visual decisions; PRODUCT.md wins on strategic/voice decisions.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt. If `migrated: true`, the loader auto-renamed legacy `.impeccable.md` to `PRODUCT.md`; mention this once and suggest `/impeccable document` for the matching DESIGN.md.
-
-`serverPort` and `serverToken` belong to the small **Impeccable live helper** HTTP server (serves `/live.js`, SSE, and `/poll`). That port is **not** your dev server and is usually not the URL you open to view the app. The browser page is whatever origin serves one of the `pageFiles` entries (Vite / Next / Bun / tunnel / LAN hostname).
-
-If output is `{ ok: false, error: "config_missing" | "config_invalid", path }`, this project hasn't been configured for live mode (or its config is stale). See **First-time setup** at the bottom.
-
-## Poll loop
-
-```
-LOOP:
- node .pi/skills/impeccable/scripts/live-poll.mjs # default long timeout; no --timeout=
- Read JSON; dispatch on "type"
-
- "generate" → Handle Generate; reply done; LOOP
- "accept" → Handle Accept; complete carbonize cleanup if required; LOOP
- "discard" → Handle Discard; LOOP
- "prefetch" → Handle Prefetch; LOOP
- "timeout" → LOOP
- "exit" → break → Cleanup
-```
-
-## Recovery commands
-
-The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.
-
-Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:
-
-```bash
-node .pi/skills/impeccable/scripts/live-status.mjs
-node .pi/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID
-node .pi/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID
-```
-
-- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.
-- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.
-- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.
-
-Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.
-
-## Handle `generate`
-
-Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.
-
-Speed matters; the user is watching a spinner. Minimize tool calls by using the `wrap` helper and writing all variants in a single edit.
-
-### 1. Read the screenshot (if present)
-
-`event.screenshotPath` is **only sent when the user placed at least one comment or stroke before Go.** When present, it's an absolute path to a PNG of the element as rendered with the annotations baked in. **Read it before planning**: annotations encode user intent not recoverable from `element.outerHTML` alone.
-
-When `screenshotPath` is absent, don't ask for one and don't go looking for the current rendering. The omission is deliberate: without annotations, a screenshot would anchor the model on the existing design and fight the three-distinct-directions brief. Work from `element.outerHTML`, the computed styles in `event.element`, and the freeform prompt if present.
-
-`event.comments` and `event.strokes` carry structured metadata alongside the visual. Treat the screenshot as primary; use the structured data for specifics worth quoting (e.g. the exact text of a comment).
-
-Reading annotations precisely:
-
-- **Comment position carries meaning.** Its `{x, y}` is element-local CSS px (same coord space as `element.boundingRect`). Find the child under that point and apply the comment text LOCALLY to that sub-element. A comment near the title is about the title, not a global description.
-- **Comments and strokes are independent annotations** unless clearly paired by overlap or tight proximity. Don't let the visual weight of a prominent stroke override the precise location of a textually-specific comment elsewhere.
-- **Strokes are gestures; read them by shape.** Closed loop = "this thing" (emphasis / focus); arrow = direction (move / point to); cross or slash = delete; free scribble = emphasis or delete depending on context. A loop around region X means "pay attention to X," not "only change pixels inside X."
-- **When a stroke's intent is ambiguous** (circle or arrow? emphasis or move?), state your reading in one sentence of rationale rather than silently guessing. If the uncertainty materially changes the brief, ask one short clarifying question before generating.
-
-### 2. Wrap the element
-
-```bash
-node .pi/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"
-```
-
-Flag mapping. Keep them separate, don't collapse into `--query`:
-
-- `--element-id` ← `event.element.id`
-- `--classes` ← `event.element.classes` joined with commas
-- `--tag` ← `event.element.tagName`
-- `--text` ← first ~80 chars of `event.element.textContent` (trim, single-line). **Pass this every call.** When the picked element shares classes + tag with sibling components (a list of `<Card>`s, repeating sections), this is what disambiguates which branch in source to wrap. Without it, wrap silently lands on the first match and may rewrite the wrong element.
-
-The helper searches ID first, then classes, then tag + class combo. If `event.pageUrl` implies the file (e.g. `/` is usually `index.html`), pass `--file PATH` to skip the search. `--query` is a fallback for raw text search only; do not use it for normal element lookups.
-
-If `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.
-
-Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.
-
-`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:
-
-- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.
-- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.
-
-Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.
-
-**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:
-
-- `{ error: "file_is_generated", file, hint }`: user-supplied `--file` points at a generated file.
-- `{ error: "element_not_in_source", generatedMatch, hint }`: element exists only in a generated file (the next build would wipe any edits).
-- `{ error: "element_not_found", hint }`: element isn't in any project file; likely runtime-injected (JS component, dynamic render from data).
-
-All three carry `fallback: "agent-driven"`. Follow **Handle fallback** below.
-
-### 3. Load the action's reference
-
-If `event.action` is `impeccable` (the default freeform action), use SKILL.md's shared laws plus the loaded register reference (`brand.md` or `product.md`). Do not load a sub-command reference. **Freeform is not a pass to skip parameters:** you still follow the composition budget and the freeform bias in **§7 Parameters** below. Sub-command files list MUST-have signature knobs; freeform has no such file, so sizing knobs from surface weight and primary axes is entirely on you.
-
-Any other `event.action` (`bolder`, `quieter`, `distill`, `polish`, `typeset`, `colorize`, `layout`, `adapt`, `animate`, `delight`, `overdrive`): Read `reference/<action>.md` before planning. Each sub-command encodes a specific discipline; skipping its reference produces generic output. Those files may require specific params; layer them on top of the §7 budget, not instead of it.
-
-### 4. Plan three variants: identity first, then mode, then axes
-
-The wrong frame for live mode is "show three different design directions." Live runs on an existing surface; the brand has already been chosen. The job is variation **within identity**, not selection between identities. Failure mode: three editorial-typographic variants on a brief that wasn't editorial. Bigger failure mode: three off-brand variants the user can't accept because they don't look like their product.
-
-Four phases. Do them in order.
-
-#### Phase A: Extract the identity (non-skippable)
-
-The existing surface has an identity already. Read it before planning anything. Sources, in priority order:
-
-1. **DESIGN.md** if loaded: read the visual system fields (palette, type pairing, motion, components). This is the authoritative answer.
-2. **CSS custom properties** in the page's stylesheets (`:root { --color-...; --font-...; ... }`): these are de-facto tokens.
-3. **Computed styles** on the picked element and its parent: colors, fonts, spacing scales, corner radii.
-4. **Sibling components on the page**: what visual rhetoric do existing components use? (Asymmetric or centered? Dense or airy? Bold or quiet?)
-
-Write down what you see in **one sentence**. The sentence describes the surface that's actually on screen; it is not aspirational, not opinionated, not edited toward what the brand "should" be. Capture, in roughly this order:
-
-- The dominant surface color and accent color, by hex or token name (use the actual values, not categories like "warm" or "neutral").
-- The type pairing: the actual font names loaded, primary first.
-- The layout topology: how the dominant elements are arranged (stacked / side-by-side / grid / asymmetric / overlay).
-- The surface treatment: corners, borders, shadows, density of decoration.
-- The voice tone you read off the copy itself, not off the aesthetic feel.
-
-Be specific. "Modern" is not a color, "elegant" is not a type pairing, "clean" is not a layout. If you can't extract a real value for an axis, skip it rather than fabricate. The point is to record what is, not to describe what you wish it were.
-
-Do not include adjectives that name an aesthetic family ("editorial-leaning", "terminal-flavored", "brutalist"); those are conclusions, not data. They belong to Phase C lane selection in departure mode, not to identity description. Letting them sneak into Phase A is how the identity-lock collapses into a self-fulfilling prophecy.
-
-This sentence is the **identity lock**. Every variant must be readable as the same brand if rendered side by side. Skipping this phase is the primary cause of off-brand variants. Absence of DESIGN.md is never an excuse; extract from CSS and computed styles instead.
-
-#### Phase B: Pick mode (default vs departure)
-
-**Default mode**: the existing identity is preserved. Variants vary expression axes within it. *This is the right mode for ~90% of live sessions.* The user picked an element on a real product they're shipping; they expect variants of *their* hero, not three different brands' heroes.
-
-**Departure mode**: the existing identity is rejected. Variants propose alternatives consistent with PRODUCT.md voice. Trigger only when at least one is true:
-
-- PRODUCT.md anti-references explicitly call out the current surface ("the current `index.html` is itself an example"; "diffuse away from this"; "the page on screen is the failure"). Generic anti-references that describe what to avoid in general do **not** trigger departure mode; only ones that point at *this* surface specifically.
-- The user's freeform prompt explicitly asks for departure ("rebuild this from scratch", "what if it weren't editorial at all", "show me something completely different").
-
-If you're unsure, you're in default mode. The cost of being wrong about default is "three on-brand variants with similar feel": recoverable, the user picks none. The cost of being wrong about departure is "three off-brand variants": unrecoverable, the user is annoyed.
-
-#### Phase C: Plan three variants
-
-**Default mode.** Each variant commits to a different **primary axis** of difference, while preserving the identity sentence. The six axes:
-
-1. **Hierarchy**: which element commands the eye?
-2. **Layout topology**: stacked / side-by-side / grid / asymmetric / overlay
-3. **Typographic system**: pairing logic, scale ratio, case/weight strategy *within the available faces*
-4. **Color strategy**: which existing palette role carries the surface (Restrained / Committed / Full palette / Drenched). Use the brand's existing palette tokens, not new colors.
-5. **Density**: minimal / comfortable / dense
-6. **Structural decomposition**: merge, split, progressive disclosure
-
-Three variants → three DIFFERENT axes. The trio reads as *the same brand at three angles*. Do not introduce new fonts, new palette hues, or new aesthetic-family signals; those belong to departure mode.
-
-**While planning each variant, also name its 2–3 parameter knobs** (per the §7 budget table). Parameters are part of the design, not a decoration added afterward. If the variant explores density, expose a density knob. If it explores color commitment, expose a color-amount range. Deciding "what's tunable" during planning produces better knobs than retrofitting them onto finished HTML.
-
-**Departure mode.** Each variant anchors to a different **aesthetic direction**, derived from the brand's stated voice and register in PRODUCT.md. Do NOT pick from a fixed catalog of lane categories. The right three directions for this brand are not the same as the right three for another brand, and picking from a list is itself the training-data reflex (the model selects "Swiss-grid, Terminal, Industrial-signage" every time because those are the furthest-from-editorial items in any enumerated list).
-
-Instead, work from the brand:
-
-1. Read PRODUCT.md's Brand Personality words. What physical, spatial, or material experiences would embody those words if design were not involved? (A personality described as "specific, earned, unmistakable" evokes a hand-stamped letter, a numbered print, a watchmaker's loupe. A personality described as "restless, loud, unfiltered" evokes a concert poster, a spray-painted wall, a megaphone.)
-2. From those physical experiences, derive three visual directions that are genuinely different from each other AND from the current surface you're departing.
-3. Avoid the **reflex-reject lanes** in [brand.md](brand.md). Don't trade one monoculture for another. If you find yourself reaching for "Swiss-grid" or "Terminal" or "Industrial-signage" by reflex, you are pattern-matching a catalog in your training data, not reading the brand. Start over from the personality words.
-4. Each direction must be expressible in one concrete sentence that names a real-world referent ("a museum exhibition label system for a contemporary art gallery" not "clean and minimal"). If your sentence contains only adjectives, it's not concrete enough.
-5. **While planning each direction, also name its 2–3 parameter knobs** (per the §7 budget table). The same principle as default mode: decide "what's tunable" during planning, not after writing the HTML. A departure-mode hero with 0 parameters is not "bold creative vision," it's a missed opportunity for the user to fine-tune the direction they pick.
-
-#### Phase D: Squint test
-
-**Default mode squint.** Read each variant's identity sentence and compare to the locked identity from Phase A. If any variant has drifted to a different palette, type voice, or visual rhetoric, it has crossed into departure mode by accident; rework. Then check that each variant commits to a different primary axis. Three "tighter density" variants is failure.
-
-**Departure mode squint.** Two passes, family before sentence:
-
-1. **Family pass.** Label each variant with one design-family word of your own choosing (any concrete noun: *exhibition, storefront, cockpit, recipe-card, playbill, field-manual*). If any two variants share a label, or if the label could apply to the other variants equally well, rework. Do not use a fixed vocabulary list for the labels. *This pass is non-negotiable in departure mode and catches the monoculture failure that the sentence pass misses.*
-2. **Sentence pass.** Write three one-sentence descriptions side by side. If two of them rhyme ("both feature big type" / "both are stacks of sections" / "both center the CTA"), rework the offender.
-
-**When the primary axis is color or theme, forbid the trio from sharing theme + dominant hue.** Two dark-plus-one-dark is not distinct. Aim for three color worlds, not three shades of the same.
-
-**For action-specific invocations**, each variant must vary along the dimension the action names:
-
-- `bolder`: amplify a different dimension per variant (scale / saturation / structural change). Not three "slightly bigger" variants.
-- `quieter`: pull back a different dimension (color / ornament / spacing).
-- `distill`: remove a different class of excess (visual noise / redundant content / nested structure).
-- `polish`: target a different refinement axis (rhythm / hierarchy / micro-details like corner radii, focus states, optical kerning).
-- `typeset`: different type pairing AND different scale ratio each. Not three riffs on one pairing.
-- `colorize`: different hue family each (not shades of one hue). Vary chroma and contrast strategy.
-- `layout`: different structural arrangement (stacked / side-by-side / grid / asymmetric). Not spacing tweaks.
-- `adapt`: different target context per variant (mobile-first / tablet / desktop / print or low-data). Don't make three mobile layouts.
-- `animate`: different motion vocabulary (cascade stagger / clip wipe / scale-and-focus / morph / parallax). Not three staggered fades.
-- `delight`: different flavor of personality (unexpected micro-interaction / typographic surprise / illustrated accent / sonic-or-haptic moment / easter-egg interaction).
-- `overdrive`: different convention broken (scale / structure / motion / input model / state transitions). Skip `overdrive.md`'s "propose and ask" step; live mode is non-interactive.
-
-### 5. Apply the freeform prompt (if present)
-
-`event.freeformPrompt` is the user's ceiling on direction (all variants must honor it), but still explore meaningfully different *interpretations*. The interpretations stay within whichever mode you picked in Phase B.
-
-In **default mode**, the prompt narrows the axes you choose, not the identity. *"Make it feel more confident"* → variant 1 amplifies hierarchy (one element commands the eye), variant 2 commits the existing accent color (Committed strategy on the brand's hue), variant 3 tightens density and removes decorative slack. Three different axes, same brand.
-
-In **departure mode**, the prompt narrows the lanes you draw from, not the families. *"Make it feel like a newspaper front page"* would itself be a departure-mode prompt; honor it but pick three meaningfully different newspaper-adjacent lanes (broadsheet vs. tabloid vs. trade journal), and run the family pass to confirm they don't collapse into one.
-
-When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.
-
-### 6. Write all variants in a single edit
-
-Complete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).
-
-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).
-
-Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:
-
-```html
-<!-- Variants: insert below this line -->
-<style data-impeccable-css="SESSION_ID">
- /* rules matching cssAuthoring.rulePattern */
-</style>
-<div data-impeccable-variant="1">
- <!-- variant 1: full element replacement (single top-level element) -->
-</div>
-<div data-impeccable-variant="2" style="display: none">
- <!-- variant 2: full element replacement -->
-</div>
-<div data-impeccable-variant="3" style="display: none">
- <!-- variant 3: full element replacement -->
-</div>
-```
-
-**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.
-
-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.
-
-One edit, all variants; the browser's MutationObserver picks everything up in one pass.
-
-For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.
-
-**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:
-
-```tsx
-<style data-impeccable-css="SESSION_ID">{`
- @scope ([data-impeccable-variant="1"]) { ... }
- @scope ([data-impeccable-variant="2"]) { ... }
-`}</style>
-<div data-impeccable-variant="1">
- {/* variant 1 */}
-</div>
-<div data-impeccable-variant="2" style={{ display: 'none' }}>
- {/* variant 2 */}
-</div>
-```
-
-The wrap script already gives you a single-rooted JSX wrapper: a `<div data-impeccable-variants="…">` outer element with the marker comments tucked inside. Drop the variants block above into the "Variants: insert below this line" comment and the source stays valid TSX.
-
-### 7. Parameters (composition-sized, 0–4 per variant)
-
-Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement. The browser docks a small panel to the right of the outline with one control per parameter. The user drags/clicks and sees instant feedback: there is zero regeneration cost because the knob toggles a CSS variable or data attribute that the variant's scoped CSS is already authored against.
-
-**What “optional” does not mean.** Parameters are not nice-to-have decoration on large work. The word meant “omit controls that are redundant or cosmetic,” not “default to zero because three variants were enough work.”
-
-**When to add.** As soon as the variant’s scoped CSS has a meaningful continuous or stepped axis: density, color amount, type scale, motion intensity, column weight, and so on. If you can imagine the user muttering “a bit tighter” or “a touch more accent” **without** wanting a full regeneration, wire that axis. **Not** micro-margins or one-off nudges; those are not parameters.
-
-**Freeform (`action` is `impeccable`) bias.** You did not load a sub-command reference, so you must **choose** signature axes yourself. Match the budget table: for a hero or large composition, that means **2–3 axes per variant**, not 1. Prefer knobs that sit on the dimensions where your three variants actually differ (if density varies, expose it as a `steps` knob; if color commitment varies, expose it as a `range`). A hero that ships with **0** params is almost always a mistake, not a judgment call. A hero with exactly **1** param is underweight unless the design is genuinely a fixed-point comparison. Start from the budget table, not from zero.
-
-**Budget scales with the element's visual weight, not token budget.** Knobs need real estate to read as tunable; three sliders on a single control are noise.
-
-- **Leaf / tiny**: a single button, icon, input, bare heading, solitary paragraph: **0 params.**
-- **Small composition**: labeled input, simple card, short callout (≤ ~5 visual children): **0–1** params when one dominant axis is obvious; otherwise **0.**
-- **Medium composition**: section component, nav cluster, dense card, short feature block (6–15 visual children): **target 2**; **1** is acceptable if the block is simple; **0** only when variants are truly fixed points.
-- **Large composition**: hero section, full page region, spread layout, strong internal structure (16+ visual children or multiple sub-sections): **target 2–3**; **up to 4** when several independent axes (e.g. structure `steps` + `density` + one accent) are all authored in scoped CSS.
-
-**When in doubt, ask whether a dial exists before defaulting to zero.** The user can always request more variants, but the point of live mode is instant tuning without another Go. Crowding the panel is bad; **under-shipping** knobs on a dense composition is the more common failure for freeform. Count by **visual** children, not DOM depth; a shallow-but-wide hero is still large.
-
-**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.
-
-**How to declare.** Put a JSON manifest on the variant wrapper:
-
-```html
-<div data-impeccable-variant="1" data-impeccable-params='[
- {"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"},
- {"id":"density","kind":"steps","default":"snug","label":"Density","options":[
- {"value":"airy","label":"Airy"},
- {"value":"snug","label":"Snug"},
- {"value":"packed","label":"Packed"}
- ]},
- {"id":"serif","kind":"toggle","default":false,"label":"Serif display"}
-]'>
- ...variant content...
-</div>
-```
-
-**Three kinds:**
-
-- `range`: smooth slider. Drives a CSS custom property `--p-<id>` on the variant wrapper. Author CSS with `var(--p-color-amount, 0.5)`. Fields: `min`, `max`, `step`, `default` (number), `label`.
-- `steps`: segmented radio. Drives a data attribute `data-p-<id>` on the variant wrapper. Author CSS with `:scope[data-p-density="airy"] .grid { ... }`. Fields: `options` (array of `{value, label}`), `default` (string), `label`.
-- `toggle`: on/off switch. Drives BOTH a CSS var (`--p-<id>: 0|1`) and a data attribute (present when on, absent when off). Use whichever is more convenient. Fields: `default` (boolean), `label`.
-
-**Signature params per action.** For named sub-commands, read that action’s `reference/<action>.md` for one or two **MUST** params (e.g. `layout` → `density`). Those are non-negotiable when the design can express them. **Freeform has no file-level MUST**; the **Freeform (`impeccable`) bias** in this section is the stand-in. If the user’s action is both stylized and sub-command (e.g. `colorize`), the sub-command’s MUST list takes precedence for its axes; still respect the **Hard cap** and add no redundant duplicate knobs.
-
-**Reset on variant switch.** User dials density on v1, flips to v2, v2 starts at v2's declared defaults. Known limitation; preservation across variants may land later.
-
-**On accept**, the browser sends the user's current values in the accept event. `live-accept.mjs` writes them as a sibling comment:
-
-```html
-<!-- impeccable-param-values SESSION_ID: {"color-amount":0.7,"density":"packed"} -->
-```
-
-The carbonize cleanup step (see below) reads that comment and bakes the chosen values into the final CSS. For `steps`/`toggle` attribute selectors: keep only the branch matching the chosen value, drop the others, collapse `:scope[data-p-density="packed"] .grid` to a semantic class rule. For `range` vars: either substitute the literal or keep the var with the chosen value as its new default.
-
-### 8. Signal done
-
-```bash
-node .pi/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
-```
-
-`RELATIVE_PATH` is relative to project root (`public/index.html`, `src/App.tsx`, etc.); the browser fetches source directly if the dev server lacks HMR.
-
-Then run `live-poll.mjs` again immediately.
-
-### Aborting an in-flight session
-
-If wrap or generation fails after the browser has flipped to GENERATING (e.g. wrap landed on the wrong source branch and you've already reverted it, or generation hit an unrecoverable error), tell the **browser** so its bar resets to PICKING:
-
-```bash
-node .pi/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID error "Short reason"
-```
-
-Don't run `live-accept --discard` for this; that's a pure file mutator, the browser doesn't see it, and the bar gets stuck on the GENERATING dots forever (the user has to refresh). `--discard` is only correct when the **browser** initiated the discard (user clicked ✕ during CYCLING) and the agent is just running source-side cleanup the browser already triggered.
-
-## Handle fallback
-
-When wrap returns `fallback: "agent-driven"`, the deterministic flow doesn't apply. Pick up here.
-
-The goal is the same: give the user three variants to choose from AND persist the accepted one in a place the next build won't wipe. The difference is that you have to pick the right source file yourself.
-
-### Step 1: Identify where the element actually lives
-
-Use the error payload:
-
-- `element_not_in_source` with `generatedMatch: "public/docs/foo.html"`: the served HTML is generated. Find the generator (grep for writers of that path, e.g. `scripts/build-sub-pages.js`, an Astro/Next template) and locate the template or partial that emits this element.
-- `element_not_found`: the element is runtime-injected. Look for the component that renders it (React/Vue/Svelte), the JS that assembles it, or the data source that feeds it.
-- `file_is_generated` with `file: "..."`: user pointed at a generated file explicitly. Same resolution as `element_not_in_source`.
-
-Read the candidate source until you're confident where a change to the element would belong. If the change is purely visual, that source might be a shared stylesheet, not the template.
-
-### Step 2: Show three variants in the DOM for preview
-
-The browser bar is waiting for variants. Even without a wrapper in source, you still need to show something:
-
-1. Manually write the wrapper scaffold into the **served** file (the one the browser actually loaded). Use the same structure `live-wrap.mjs` produces; `<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents">…</div><!-- end -->`.
-2. Insert your three variant divs inside it, same shape as the deterministic path.
-3. Signal done with `--reply EVENT_ID done --file <served file>`. The browser's no-HMR fallback will fetch and inject.
-
-This served-file edit is **temporary**: next regen wipes it, and that's fine. The real work happens on accept.
-
-### Step 3: On accept, write to true source
-
-When the accept event arrives (`_acceptResult.handled` will usually be `false` here because accept also refuses to persist into generated files; see Handle accept for the carbonize branch), extract the accepted variant's content and write it into the source you identified in Step 1:
-
-- Structural change → edit the template / component source.
-- Visual-only change → add or update rules in the appropriate stylesheet; remove the inline `<style>` scope.
-- Dynamic from data → update the data source or the render logic.
-
-Then remove the temporary wrapper from the served file if it's still there.
-
-### Step 4: On discard, clean up the served file
-
-Remove the wrapper you inserted in Step 2. Nothing else to do.
-
-## Handle `accept`
-
-Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.
-
-- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.
-- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.
-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.
-- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.
-- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.
-
-### Required after accept (carbonize)
-
-When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.
-
-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.
-
-1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.
-2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).
-3. **Bake in parameter values while rewriting selectors.** For `@scope ([data-impeccable-variant="N"])` wrappers: retarget to real, semantic classes on the accepted HTML (`.why-visual--v2 .v2-label { … }`). For `:scope[data-p-<id>="VALUE"]` selectors: keep only the branch matching the chosen value from the param-values comment; drop the others (they're dead after accept). For `var(--p-<id>, DEFAULT)` in the CSS: either substitute the literal value, or if the param is still useful as a knob going forward, leave the var and update its initial declaration to the chosen value.
-4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; those are live-mode plumbing, not source.
-5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.
-
-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.
-
-A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.
-
-## Handle `discard`
-
-Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.
-
-## Handle `prefetch`
-
-Event: `{pageUrl}`. The browser fires this the first time the user selects an element on a given route, as a latency shortcut; it signals the user is likely about to Go on a page you haven't read yet.
-
-Resolve `pageUrl` to the underlying file:
-
-- Root `/` → the `pageFile` returned by `live.mjs` (usually `public/index.html` or equivalent).
-- Sub-routes (e.g. `/docs`, `/docs/live`) → the generated or source file for that route. Use your knowledge of the project layout (multi-page static sites often resolve `/foo` → `public/foo/index.html`; SPAs may map all routes to a single entry).
-
-Read the file into context, then poll again. No `--reply`: this is speculative pre-work; Go will come later. If you can't confidently resolve the route to a file, skip and poll again.
-
-Dedupe is the browser's job (one prefetch per unique pathname per session); trust it. If the same file shows up twice from different routes mapping to the same file, the second Read is cached anyway.
-
-## Exit
-
-The user can stop live mode by:
-- Saying "stop live mode" / "exit live" in chat
-- Closing the browser tab (SSE drops, poll returns `exit` after 8s)
-- The browser's exit button
-
-When the poll returns `exit`, proceed to cleanup. If the poll is still running as a background task, kill it first.
-
-## Cleanup
-
-```bash
-node .pi/skills/impeccable/scripts/live-server.mjs stop
-```
-
-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.
-
-Then:
-- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).
-- Remove any leftover carbonize blocks (search for `impeccable-carbonize-start` markers).
-
-## First-time setup (config missing or invalid)
-
-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.
-
-Schema:
-
-```json
-{
- "files": ["<path-or-glob>", "<path-or-glob>", ...],
- "exclude": ["<optional-glob>", ...],
- "insertBefore": "</body>",
- "commentSyntax": "html",
- "cspChecked": true
-}
-```
-
-`files` is the inject target; **the HTML files the browser actually loads**, not necessarily source. Each entry is either a literal path (`"public/index.html"`) or a glob pattern (`"public/**/*.html"`). Tracked or generated doesn't matter here; wrap has its own generated-file guard and routes accepts through the fallback flow.
-
-`exclude` (optional) is a list of glob patterns matching files to skip, even if a `files` glob would have included them. Use for email templates, demo fixtures, or any HTML that isn't a live page.
-
-`cspChecked` tracks whether the CSP detection step below has already run. Absent on first setup; set to `true` after CSP is checked (whether patched, declined, or not needed).
-
-**Hard-excluded paths (cannot be overridden).** `**/node_modules/**` and `**/.git/**` are never matched regardless of what the user writes. These are vendor/metadata directories and injecting into them would silently instrument third-party code.
-
-**Glob syntax.** `**` matches any number of path segments (including zero), `*` matches any characters except `/`, `?` matches a single character except `/`. Paths are always relative to the project root with forward slashes.
-
-| Framework | `files` | `insertBefore` | `commentSyntax` |
-|-----------|---------|----------------|-----------------|
-| SPA with single shell (Vite / React / Plain HTML) | `["index.html"]` | `</body>` | `html` |
-| Next.js (App Router) | `["app/layout.tsx"]` | `</body>` | `jsx` |
-| Next.js (Pages) | `["pages/_document.tsx"]` | `</body>` | `jsx` |
-| Nuxt | `["app.vue"]` | `</body>` | `html` |
-| Svelte / SvelteKit | `["src/app.html"]` | `</body>` | `html` |
-| Astro | `[" <root layout .astro>"]` | `</body>` | `html` |
-| Multi-page (separate HTML per route) | `["public/**/*.html"]`: a glob covering the served directory | `</body>` | `html` |
-
-Pick an anchor that exists in every file (`</body>` almost always works). Use `insertAfter` if the anchor should match **after** a specific line.
-
-For multi-page sites, **prefer a glob over a literal file list**. New pages added later are picked up automatically on the next `live-inject.mjs` run; no config maintenance needed.
-
-For multi-page sites whose pages are *rebuilt* by a generator (Astro, static-site generators, custom scripts like `build-sub-pages.js`), the inject survives only until the next regeneration. Re-run `live.mjs` after each build. Accept is unaffected; it writes to true source via the fallback flow.
-
-### Drift-heal warning
-
-On every `live.mjs` boot, after inject, the project is scanned for HTML files under common page-source roots (`public/`, `src/`, `app/`, `pages/`). If any exist that aren't covered by the resolved `files` list, the output includes a `configDrift` field:
-
-```json
-{
- "ok": true,
- "serverPort": 8400,
- "pageFiles": [ "..." ],
- "configDrift": {
- "orphans": ["public/new-section/index.html", "public/docs/new-command.html"],
- "orphanCount": 2,
- "hint": "2 HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like \"public/**/*.html\"."
- }
-}
-```
-
-When `configDrift` is present, surface it to the user once per session before entering the poll loop:
-
-> Noticed N HTML file(s) in the project that aren't in `config.files`:
->
-> - `public/new-section/index.html`
-> - `public/docs/new-command.html`
->
-> Add them, or switch `files` to a glob like `["public/**/*.html"]` and let it track new pages automatically?
-
-Don't auto-update the config; let the user decide. `configDrift` is `null` when there's no drift.
-
-### CSP detection (first-time only)
-
-If `config.cspChecked === true`, skip this entire section. You already asked this user once; the answer sticks.
-
-Otherwise, run the detection helper:
-
-```bash
-node .pi/skills/impeccable/scripts/detect-csp.mjs
-```
-
-Output: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.
-
-- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.
-- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:
- - Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)
- - SvelteKit `kit.csp.directives`
- - Nuxt `nuxt-security` module's `contentSecurityPolicy`
-- **`append-string`**: CSP written as a literal value string. Auto-patchable. See *append-string* below. Covers:
- - Inline `next.config.*` `headers()` with a CSP literal
- - Nuxt `routeRules` / `nitro.routeRules` headers
-- **`middleware`** or **`meta-tag`**: rarer. Detected but not auto-patched in v1. Show the user the detected files and ask them to add `http://localhost:8400` to `script-src` and `connect-src` manually, then mark `cspChecked: true` and proceed.
-
-#### Consent prompt template
-
-Use this phrasing so the experience is consistent across agents:
-
-> **CSP patch needed.** I detected a Content Security Policy in your project that blocks `http://localhost:8400`: the live picker won't load without an allowance. Here's the change I'd make:
->
-> ```diff
-> [file: <patchTarget>]
-> [exact diff, 2–5 lines]
-> ```
->
-> It's guarded by `NODE_ENV === "development"` so the extra entry only appears in dev and never reaches production. You can remove it any time by reverting this file. Apply? [y/n]
-
-On "no": skip the patch, mention live won't work until the user adds the allowance manually, still write `cspChecked: true` (the question's been asked).
-
-On "yes": apply the Shape-specific patch below, then write `cspChecked: true`.
-
-#### append-arrays
-
-CSP expressed as structured directive arrays. Patch mechanism: declare a dev-only array, spread it into the script-src and connect-src arrays.
-
-**Declare near the top of the file that holds the CSP arrays:**
-
-```ts
-// Dev-only allowance so impeccable live mode can load. Guarded by NODE_ENV.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? ["http://localhost:8400"] : [];
-```
-
-**Append `...__impeccableLiveDev` to the script-src and connect-src directive arrays.** Per-framework specifics:
-
-- **Next.js + monorepo helper**: edit the *app's* `next.config.*` (not the shared helper), appending to `additionalScriptSrc` and `additionalConnectSrc` passed into `createBaseNextConfig` (or equivalent). Keeps the shared package clean.
-- **SvelteKit**: edit `svelte.config.js`, appending to `kit.csp.directives['script-src']` and `kit.csp.directives['connect-src']`.
-- **Nuxt + nuxt-security**: edit `nuxt.config.*`, appending to `security.headers.contentSecurityPolicy['script-src']` and `['connect-src']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-turborepo/expected-after-patch.ts` (Next.js)
-- `tests/framework-fixtures/sveltekit-csp/expected-after-patch.js` (SvelteKit)
-
-Idempotency: if `__impeccableLiveDev` already exists in the file, the patch is already applied; skip asking and just mark `cspChecked: true`.
-
-#### append-string
-
-CSP built as a literal value string. Two-point patch: declare a dev-only string near the top, interpolate it into the CSP at the `script-src` and `connect-src` directives.
-
-```ts
-// Dev-only allowance so impeccable live mode can load.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? " http://localhost:8400" : "";
-```
-
-Then in the CSP value string:
-- `script-src 'self' 'unsafe-inline'` → `` `script-src 'self' 'unsafe-inline'${__impeccableLiveDev}` ``
-- `connect-src 'self'` → `` `connect-src 'self'${__impeccableLiveDev}` ``
-
-(Leading space on the dev string so it concatenates cleanly into the existing value. Convert the literal CSP directives into template strings as part of the edit if they aren't already.)
-
-Per-framework specifics:
-- **Next.js inline `headers()`**: edit `next.config.*`, splicing the variable into the CSP value.
-- **Nuxt `routeRules`**: edit `nuxt.config.*`, splicing into the CSP in `routeRules['/**'].headers['Content-Security-Policy']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-inline-csp/expected-after-patch.js` (Next.js)
-- `tests/framework-fixtures/nuxt-csp/expected-after-patch.ts` (Nuxt)
-
-### Troubleshooting
-
-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.
-
-Then re-run `live.mjs`.
@@ -1,109 +0,0 @@
-# Motion Design
-
-## Duration: The 100/300/500 Rule
-
-Timing matters more than easing. These durations feel right for most UI:
-
-| Duration | Use Case | Examples |
-|----------|----------|----------|
-| **100-150ms** | Instant feedback | Button press, toggle, color change |
-| **200-300ms** | State changes | Menu open, tooltip, hover states |
-| **300-500ms** | Layout changes | Accordion, modal, drawer |
-| **500-800ms** | Entrance animations | Page load, hero reveals |
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-## Easing: Pick the Right Curve
-
-**Don't use `ease`.** It's a compromise that's rarely optimal. Instead:
-
-| Curve | Use For | CSS |
-|-------|---------|-----|
-| **ease-out** | Elements entering | `cubic-bezier(0.16, 1, 0.3, 1)` |
-| **ease-in** | Elements leaving | `cubic-bezier(0.7, 0, 0.84, 0)` |
-| **ease-in-out** | State toggles (there → back) | `cubic-bezier(0.65, 0, 0.35, 1)` |
-
-**For micro-interactions, use exponential curves.** They feel natural because they mimic real physics (friction, deceleration):
-
-```css
-/* Quart out - smooth, refined (recommended default) */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1);
-
-/* Quint out - slightly more dramatic */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1);
-
-/* Expo out - snappy, confident */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1);
-```
-
-**Avoid bounce and elastic curves.** They were trendy in 2015 but now feel tacky and amateurish. Real objects don't bounce when they stop; they decelerate smoothly. Overshoot effects draw attention to the animation itself rather than the content.
-
-## Premium Motion Materials
-
-Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties: blur reveals, backdrop-filter panels, saturation or brightness shifts, shadow bloom, SVG filters, masks, clip paths, gradient-position movement, and variable font or shader-driven effects.
-
-Use the right material for the effect:
-
-- **Transform / opacity**: movement, press feedback, simple reveals, list choreography.
-- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances, atmospheric transitions.
-- **Clip path / masks**: wipes, reveals, editorial cropping, product-like transitions.
-- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state.
-- **Grid-template rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly.
-
-The hard rule is not "transform and opacity only." The hard rule is: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify in-browser that the result is smooth on the target viewports. If blur/filter makes the interaction feel significantly more premium and remains smooth, use it.
-
-## Staggered Animations
-
-Use CSS custom properties for cleaner stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"` on each item. **Cap total stagger time**: 10 items at 50ms = 500ms total. For many items, reduce per-item delay or cap staggered count.
-
-## Reduced Motion
-
-This is not optional. Vestibular disorders affect ~35% of adults over 40.
-
-```css
-/* Define animations normally */
-.card {
- animation: slide-up 500ms ease-out;
-}
-
-/* Provide alternative for reduced motion */
-@media (prefers-reduced-motion: reduce) {
- .card {
- animation: fade-in 200ms ease-out; /* Crossfade instead of motion */
- }
-}
-
-/* Or disable entirely */
-@media (prefers-reduced-motion: reduce) {
- *, *::before, *::after {
- animation-duration: 0.01ms !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**What to preserve**: Functional animations like progress bars, loading spinners (slowed down), and focus indicators should still work, just without spatial movement.
-
-## Perceived Performance
-
-**Nobody cares how fast your site is, just how fast it feels.** Perception can be as effective as actual performance.
-
-**The 80ms threshold**: Our brains buffer sensory input for ~80ms to synchronize perception. Anything under 80ms feels instant and simultaneous. This is your target for micro-interactions.
-
-**Active vs passive time**: Passive waiting (staring at a spinner) feels longer than active engagement. Strategies to shift the balance:
-
-- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening.
-- **Early completion**: Show content progressively, don't wait for everything. Video buffering, progressive images, streaming HTML.
-- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Instagram likes work offline; the UI updates instantly, syncs later. Use for low-stakes actions; avoid for payments or destructive operations.
-
-**Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances, but ease-in toward a task's end compresses perceived time.
-
-**Caution**: Too-fast responses can decrease perceived value. Users may distrust instant results for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
-
-## Performance
-
-Don't use `will-change` preemptively, only when animation is imminent (`:hover`, `.animating`). For scroll-triggered animations, use Intersection Observer instead of scroll events; unobserve after animating once. Create motion tokens for consistency (durations, easings, common transitions).
-
----
-
-**Avoid**: Animating everything (animation fatigue is real). Using >500ms for UI feedback. Ignoring `prefers-reduced-motion`. Using animation to hide slow loading.
@@ -1,234 +0,0 @@
-> **Additional context needed**: the "aha moment" you want users to reach, and users' experience level.
-
-Get users to first value as fast as possible. Onboarding's job is not to teach the product. Its job is to get people to the moment that proves the product is worth their time.
-
-## Assess Onboarding Needs
-
-Understand what users need to learn and why:
-
-1. **Identify the challenge**:
- - What are users trying to accomplish?
- - What's confusing or unclear about current experience?
- - Where do users get stuck or drop off?
- - What's the "aha moment" we want users to reach?
-
-2. **Understand the users**:
- - What's their experience level? (Beginners, power users, mixed?)
- - What's their motivation? (Excited and exploring? Required by work?)
- - What's their time commitment? (5 minutes? 30 minutes?)
- - What alternatives do they know? (Coming from competitor? New to category?)
-
-3. **Define success**:
- - What's the minimum users need to learn to be successful?
- - What's the key action we want them to take? (First project? First invite?)
- - How do we know onboarding worked? (Completion rate? Time to value?)
-
-**CRITICAL**: Onboarding should get users to value as quickly as possible, not teach everything possible.
-
-## Onboarding Principles
-
-Follow these core principles:
-
-### Show, Don't Tell
-- Demonstrate with working examples, not just descriptions
-- Provide real functionality in onboarding, not separate tutorial mode
-- Use progressive disclosure, teach one thing at a time
-
-### Make It Optional (When Possible)
-- Let experienced users skip onboarding
-- Don't block access to product
-- Provide "Skip" or "I'll explore on my own" options
-
-### Time to Value
-- Get users to their "aha moment" ASAP
-- Front-load most important concepts
-- Teach 20% that delivers 80% of value
-- Save advanced features for contextual discovery
-
-### Context Over Ceremony
-- Teach features when users need them, not upfront
-- Empty states are onboarding opportunities
-- Tooltips and hints at point of use
-
-### Respect User Intelligence
-- Don't patronize or over-explain
-- Be concise and clear
-- Assume users can figure out standard patterns
-
-## Design Onboarding Experiences
-
-Create appropriate onboarding for the context:
-
-### Initial Product Onboarding
-
-**Welcome Screen**:
-- Clear value proposition (what is this product?)
-- What users will learn/accomplish
-- Time estimate (honest about commitment)
-- Option to skip (for experienced users)
-
-**Account Setup**:
-- Minimal required information (collect more later)
-- Explain why you're asking for each piece of information
-- Smart defaults where possible
-- Social login when appropriate
-
-**Core Concept Introduction**:
-- Introduce 1-3 core concepts (not everything)
-- Use simple language and examples
-- Interactive when possible (do, don't just read)
-- Progress indication (step 1 of 3)
-
-**First Success**:
-- Guide users to accomplish something real
-- Pre-populated examples or templates
-- Celebrate completion (but don't overdo it)
-- Clear next steps
-
-### Feature Discovery & Adoption
-
-**Empty States**:
-Instead of blank space, show:
-- What will appear here (description + screenshot/illustration)
-- Why it's valuable
-- Clear CTA to create first item
-- Example or template option
-
-Example:
-```
-No projects yet
-Projects help you organize your work and collaborate with your team.
-[Create your first project] or [Start from template]
-```
-
-**Contextual Tooltips**:
-- Appear at relevant moment (first time user sees feature)
-- Point directly at relevant UI element
-- Brief explanation + benefit
-- Dismissable (with "Don't show again" option)
-- Optional "Learn more" link
-
-**Feature Announcements**:
-- Highlight new features when they're released
-- Show what's new and why it matters
-- Let users try immediately
-- Dismissable
-
-**Progressive Onboarding**:
-- Teach features when users encounter them
-- Badges or indicators on new/unused features
-- Unlock complexity gradually (don't show all options immediately)
-
-### Guided Tours & Walkthroughs
-
-**When to use**:
-- Complex interfaces with many features
-- Significant changes to existing product
-- Industry-specific tools needing domain knowledge
-
-**How to design**:
-- Spotlight specific UI elements (dim rest of page)
-- Keep steps short (3-7 steps max per tour)
-- Allow users to click through tour freely
-- Include "Skip tour" option
-- Make replayable (help menu)
-
-**Best practices**:
-- Interactive over passive (let users click real buttons)
-- Focus on workflow, not features ("Create a project" not "This is the project button")
-- Provide sample data so actions work
-
-### Interactive Tutorials
-
-**When to use**:
-- Users need hands-on practice
-- Concepts are complex or unfamiliar
-- High stakes (better to practice in safe environment)
-
-**How to design**:
-- Sandbox environment with sample data
-- Clear objectives ("Create a chart showing sales by region")
-- Step-by-step guidance
-- Validation (confirm they did it right)
-- Graduation moment (you're ready!)
-
-### Documentation & Help
-
-**In-product help**:
-- Contextual help links throughout interface
-- Keyboard shortcut reference
-- Search-able help center
-- Video tutorials for complex workflows
-
-**Help patterns**:
-- `?` icon near complex features
-- "Learn more" links in tooltips
-- Keyboard shortcut hints (`⌘K` shown on search box)
-
-## Empty State Design
-
-Every empty state needs:
-
-### What Will Be Here
-"Your recent projects will appear here"
-
-### Why It Matters
-"Projects help you organize your work and collaborate with your team"
-
-### How to Get Started
-[Create project] or [Import from template]
-
-### Visual Interest
-Illustration or icon (not just text on blank page)
-
-### Contextual Help
-"Need help getting started? [Watch 2-min tutorial]"
-
-**Empty state types**:
-- **First use**: Never used this feature (emphasize value, provide template)
-- **User cleared**: Intentionally deleted everything (light touch, easy to recreate)
-- **No results**: Search or filter returned nothing (suggest different query, clear filters)
-- **No permissions**: Can't access (explain why, how to get access)
-- **Error state**: Failed to load (explain what happened, retry option)
-
-## Implementation Patterns
-
-### Technical approaches:
-
-**Tooltip libraries**: Tippy.js, Popper.js
-**Tour libraries**: Intro.js, Shepherd.js, React Joyride
-**Modal patterns**: Focus trap, backdrop, ESC to close
-**Progress tracking**: LocalStorage for "seen" states
-**Analytics**: Track completion, drop-off points
-
-**Storage patterns**:
-```javascript
-// Track which onboarding steps user has seen
-localStorage.setItem('onboarding-completed', 'true');
-localStorage.setItem('feature-tooltip-seen-reports', 'true');
-```
-
-**IMPORTANT**: Don't show same onboarding twice (annoying). Track completion and respect dismissals.
-
-**NEVER**:
-- Force users through long onboarding before they can use product
-- Patronize users with obvious explanations
-- Show same tooltip repeatedly (respect dismissals)
-- Block all UI during tour (let users explore)
-- Create separate tutorial mode disconnected from real product
-- Overwhelm with information upfront (progressive disclosure!)
-- Hide "Skip" or make it hard to find
-- Forget about returning users (don't show initial onboarding again)
-
-## Verify Onboarding Quality
-
-Test with real users:
-
-- **Time to completion**: Can users complete onboarding quickly?
-- **Comprehension**: Do users understand after completing?
-- **Action**: Do users take desired next step?
-- **Skip rate**: Are too many users skipping? (Maybe it's too long or not valuable)
-- **Completion rate**: Are users completing? (If low, simplify)
-- **Time to value**: How long until users get first value?
-
-When users hit the aha moment fast and don't drop off, hand off to `/impeccable polish` for the final pass.
@@ -1,258 +0,0 @@
-Performance is a feature. Identify the actual bottleneck for THIS interface, fix it, then measure. Don't optimize what isn't slow.
-
-## Assess Performance Issues
-
-Understand current performance and identify problems:
-
-1. **Measure current state**:
- - **Core Web Vitals**: LCP, FID/INP, CLS scores
- - **Load time**: Time to interactive, first contentful paint
- - **Bundle size**: JavaScript, CSS, image sizes
- - **Runtime performance**: Frame rate, memory usage, CPU usage
- - **Network**: Request count, payload sizes, waterfall
-
-2. **Identify bottlenecks**:
- - What's slow? (Initial load? Interactions? Animations?)
- - What's causing it? (Large images? Expensive JavaScript? Layout thrashing?)
- - How bad is it? (Perceivable? Annoying? Blocking?)
- - Who's affected? (All users? Mobile only? Slow connections?)
-
-**CRITICAL**: Measure before and after. Premature optimization wastes time. Optimize what actually matters.
-
-## Optimization Strategy
-
-Create systematic improvement plan:
-
-### Loading Performance
-
-**Optimize Images**:
-- Use modern formats (WebP, AVIF)
-- Proper sizing (don't load 3000px image for 300px display)
-- Lazy loading for below-fold images
-- Responsive images (`srcset`, `picture` element)
-- Compress images (80-85% quality is usually imperceptible)
-- Use CDN for faster delivery
-
-```html
-<img
- src="hero.webp"
- srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
- sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
- loading="lazy"
- alt="Hero image"
-/>
-```
-
-**Reduce JavaScript Bundle**:
-- Code splitting (route-based, component-based)
-- Tree shaking (remove unused code)
-- Remove unused dependencies
-- Lazy load non-critical code
-- Use dynamic imports for large components
-
-```javascript
-// Lazy load heavy component
-const HeavyChart = lazy(() => import('./HeavyChart'));
-```
-
-**Optimize CSS**:
-- Remove unused CSS
-- Critical CSS inline, rest async
-- Minimize CSS files
-- Use CSS containment for independent regions
-
-**Optimize Fonts**:
-- Use `font-display: swap` or `optional`
-- Subset fonts (only characters you need)
-- Preload critical fonts
-- Use system fonts when appropriate
-- Limit font weights loaded
-
-```css
-@font-face {
- font-family: 'CustomFont';
- src: url('/fonts/custom.woff2') format('woff2');
- font-display: swap; /* Show fallback immediately */
- unicode-range: U+0020-007F; /* Basic Latin only */
-}
-```
-
-**Optimize Loading Strategy**:
-- Critical resources first (async/defer non-critical)
-- Preload critical assets
-- Prefetch likely next pages
-- Service worker for offline/caching
-- HTTP/2 or HTTP/3 for multiplexing
-
-### Rendering Performance
-
-**Avoid Layout Thrashing**:
-```javascript
-// ❌ Bad: Alternating reads and writes (causes reflows)
-elements.forEach(el => {
- const height = el.offsetHeight; // Read (forces layout)
- el.style.height = height * 2; // Write
-});
-
-// ✅ Good: Batch reads, then batch writes
-const heights = elements.map(el => el.offsetHeight); // All reads
-elements.forEach((el, i) => {
- el.style.height = heights[i] * 2; // All writes
-});
-```
-
-**Optimize Rendering**:
-- Use CSS `contain` property for independent regions
-- Minimize DOM depth (flatter is faster)
-- Reduce DOM size (fewer elements)
-- Use `content-visibility: auto` for long lists
-- Virtual scrolling for very long lists (react-window, react-virtualized)
-
-**Reduce Paint & Composite**:
-- Use `transform` and `opacity` for reliable movement, but allow blur, filters, masks, clip paths, shadows, and color shifts when they create meaningful polish
-- Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- Use `will-change` sparingly for known expensive operations
-- Bound expensive paint areas for blur/filter/shadow effects (smaller and isolated is faster)
-
-### Animation Performance
-
-**GPU Acceleration**:
-```css
-/* ✅ GPU-accelerated (fast) */
-.animated {
- transform: translateX(100px);
- opacity: 0.5;
-}
-
-/* ❌ CPU-bound (slow) */
-.animated {
- left: 100px;
- width: 300px;
-}
-```
-
-**Smooth 60fps**:
-- Target 16ms per frame (60fps)
-- Use `requestAnimationFrame` for JS animations
-- Debounce/throttle scroll handlers
-- Use CSS animations when possible
-- Avoid long-running JavaScript during animations
-
-**Intersection Observer**:
-```javascript
-// Efficiently detect when elements enter viewport
-const observer = new IntersectionObserver((entries) => {
- entries.forEach(entry => {
- if (entry.isIntersecting) {
- // Element is visible, lazy load or animate
- }
- });
-});
-```
-
-### React/Framework Optimization
-
-**React-specific**:
-- Use `memo()` for expensive components
-- `useMemo()` and `useCallback()` for expensive computations
-- Virtualize long lists
-- Code split routes
-- Avoid inline function creation in render
-- Use React DevTools Profiler
-
-**Framework-agnostic**:
-- Minimize re-renders
-- Debounce expensive operations
-- Memoize computed values
-- Lazy load routes and components
-
-### Network Optimization
-
-**Reduce Requests**:
-- Combine small files
-- Use SVG sprites for icons
-- Inline small critical assets
-- Remove unused third-party scripts
-
-**Optimize APIs**:
-- Use pagination (don't load everything)
-- GraphQL to request only needed fields
-- Response compression (gzip, brotli)
-- HTTP caching headers
-- CDN for static assets
-
-**Optimize for Slow Connections**:
-- Adaptive loading based on connection (navigator.connection)
-- Optimistic UI updates
-- Request prioritization
-- Progressive enhancement
-
-## Core Web Vitals Optimization
-
-### Largest Contentful Paint (LCP < 2.5s)
-- Optimize hero images
-- Inline critical CSS
-- Preload key resources
-- Use CDN
-- Server-side rendering
-
-### First Input Delay (FID < 100ms) / INP (< 200ms)
-- Break up long tasks
-- Defer non-critical JavaScript
-- Use web workers for heavy computation
-- Reduce JavaScript execution time
-
-### Cumulative Layout Shift (CLS < 0.1)
-- Set dimensions on images and videos
-- Don't inject content above existing content
-- Use `aspect-ratio` CSS property
-- Reserve space for ads/embeds
-- Avoid animations that cause layout shifts
-
-```css
-/* Reserve space for image */
-.image-container {
- aspect-ratio: 16 / 9;
-}
-```
-
-## Performance Monitoring
-
-**Tools to use**:
-- Chrome DevTools (Lighthouse, Performance panel)
-- WebPageTest
-- Core Web Vitals (Chrome UX Report)
-- Bundle analyzers (webpack-bundle-analyzer)
-- Performance monitoring (Sentry, DataDog, New Relic)
-
-**Key metrics**:
-- LCP, FID/INP, CLS (Core Web Vitals)
-- Time to Interactive (TTI)
-- First Contentful Paint (FCP)
-- Total Blocking Time (TBT)
-- Bundle size
-- Request count
-
-**IMPORTANT**: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.
-
-**NEVER**:
-- Optimize without measuring (premature optimization)
-- Sacrifice accessibility for performance
-- Break functionality while optimizing
-- Use `will-change` everywhere (creates new layers, uses memory)
-- Lazy load above-fold content
-- Optimize micro-optimizations while ignoring major issues (optimize the biggest bottleneck first)
-- Forget about mobile performance (often slower devices, slower connections)
-
-## Verify Improvements
-
-Test that optimizations worked:
-
-- **Before/after metrics**: Compare Lighthouse scores
-- **Real user monitoring**: Track improvements for real users
-- **Different devices**: Test on low-end Android, not just flagship iPhone
-- **Slow connections**: Throttle to 3G, test experience
-- **No regressions**: Ensure functionality still works
-- **User perception**: Does it *feel* faster?
-
-When the user-facing numbers move, hand off to `/impeccable polish` for the final pass.
@@ -1,130 +0,0 @@
-Start your response with:
-
-```
-──────────── ⚡ OVERDRIVE ─────────────
-》》》 Entering overdrive mode...
-```
-
-Push an interface past conventional limits. This isn't just about visual effects. It's about using the full power of the browser to make any part of an interface feel extraordinary: a table that handles a million rows, a dialog that morphs from its trigger, a form that validates in real-time with streaming feedback, a page transition that feels cinematic.
-
-**EXTRA IMPORTANT FOR THIS COMMAND**: Context determines what "extraordinary" means. A particle system on a creative portfolio is impressive. The same particle system on a settings page is embarrassing. But a settings page with instant optimistic saves and animated state transitions? That's extraordinary too. Understand the project's personality and goals before deciding what's appropriate.
-
-### Propose Before Building
-
-This command has the highest potential to misfire. Do NOT jump straight into implementation. You MUST:
-
-1. **Think through 2-3 different directions**: consider different techniques, levels of ambition, and aesthetic approaches. For each direction, briefly describe what the result would look and feel like.
-2. **ask the user directly to clarify what you cannot infer.** to present these directions and get the user's pick before writing any code. Explain trade-offs (browser support, performance cost, complexity).
-3. Only proceed with the direction the user confirms.
-
-Skipping this step risks building something embarrassing that needs to be thrown away.
-
-### Iterate with Browser Automation
-
-Technically ambitious effects almost never work on the first try. You MUST actively use browser automation tools to preview your work, visually verify the result, and iterate. Do not assume the effect looks right, check it. Expect multiple rounds of refinement. The gap between "technically works" and "looks extraordinary" is closed through visual iteration, not code alone.
-
----
-
-## Assess What "Extraordinary" Means Here
-
-The right kind of technical ambition depends entirely on what you're working with. Before choosing a technique, ask: **what would make a user of THIS specific interface say "wow, that's nice"?**
-
-### For visual/marketing surfaces
-Pages, hero sections, landing pages, portfolios: the "wow" is often sensory: a scroll-driven reveal, a shader background, a cinematic page transition, generative art that responds to the cursor.
-
-### For functional UI
-Tables, forms, dialogs, navigation: the "wow" is in how it FEELS: a dialog that morphs from the button that triggered it via View Transitions, a data table that renders 100k rows at 60fps via virtual scrolling, a form with streaming validation that feels instant, drag-and-drop with spring physics.
-
-### For performance-critical UI
-The "wow" is invisible but felt: a search that filters 50k items without a flicker, a complex form that never blocks the main thread, an image editor that processes in near-real-time. The interface just never hesitates.
-
-### For data-heavy interfaces
-Charts and dashboards: the "wow" is in fluidity: GPU-accelerated rendering via Canvas/WebGL for massive datasets, animated transitions between data states, force-directed graph layouts that settle naturally.
-
-**The common thread**: something about the implementation goes beyond what users expect from a web interface. The technique serves the experience, not the other way around.
-
-## The Toolkit
-
-Organized by what you're trying to achieve, not by technology name.
-
-### Make transitions feel cinematic
-- **View Transitions API** (same-document: all browsers; cross-document: no Firefox): shared element morphing between states. A list item expanding into a detail page. A button morphing into a dialog. This is the closest thing to native FLIP animations.
-- **`@starting-style`** (all browsers): animate elements from `display: none` to visible with CSS only, including entry keyframes
-- **Spring physics**: natural motion with mass, tension, and damping instead of cubic-bezier. Libraries: motion (formerly Framer Motion), GSAP, or roll your own spring solver.
-
-### Tie animation to scroll position
-- **Scroll-driven animations** (`animation-timeline: scroll()`): CSS-only, no JS. Parallax, progress bars, reveal sequences all driven by scroll position. (Chrome/Edge/Safari; Firefox: flag only; always provide a static fallback)
-
-### Render beyond CSS
-- **WebGL** (all browsers): shader effects, post-processing, particle systems. Libraries: Three.js, OGL (lightweight), regl. Use for effects CSS can't express.
-- **WebGPU** (Chrome/Edge; Safari partial; Firefox: flag only): next-gen GPU compute. More powerful than WebGL but limited browser support. Always fall back to WebGL2.
-- **Canvas 2D / OffscreenCanvas**: custom rendering, pixel manipulation, or moving heavy rendering off the main thread entirely via Web Workers + OffscreenCanvas.
-- **SVG filter chains**: displacement maps, turbulence, morphology for organic distortion effects. CSS-animatable.
-
-### Make data feel alive
-- **Virtual scrolling**: render only visible rows for tables/lists with tens of thousands of items. No library required for simple cases; TanStack Virtual for complex ones.
-- **GPU-accelerated charts**: Canvas or WebGL-rendered data visualization for datasets too large for SVG/DOM. Libraries: deck.gl, regl-based custom renderers.
-- **Animated data transitions**: morph between chart states rather than replacing. D3's `transition()` or View Transitions for DOM-based charts.
-
-### Animate complex properties
-- **`@property`** (all browsers): register custom CSS properties with types, enabling animation of gradients, colors, and complex values that CSS can't normally interpolate.
-- **Web Animations API** (all browsers): JavaScript-driven animations with the performance of CSS. Composable, cancellable, reversible. The foundation for complex choreography.
-
-### Push performance boundaries
-- **Web Workers**: move computation off the main thread. Heavy data processing, image manipulation, search indexing: anything that would cause jank.
-- **OffscreenCanvas**: render in a Worker thread. The main thread stays free while complex visuals render in the background.
-- **WASM**: near-native performance for computation-heavy features. Image processing, physics simulations, codecs.
-
-### Interact with the device
-- **Web Audio API**: spatial audio, audio-reactive visualizations, sonic feedback. Requires user gesture to start.
-- **Device APIs**: orientation, ambient light, geolocation. Use sparingly and always with user permission.
-
-**NOTE**: This command is about enhancing how an interface FEELS, not changing what a product DOES. Adding real-time collaboration, offline support, or new backend capabilities are product decisions, not UI enhancements. Focus on making existing features feel extraordinary.
-
-## Implement with Discipline
-
-### Progressive enhancement is non-negotiable
-
-Every technique must degrade gracefully. The experience without the enhancement must still be good.
-
-```css
-@supports (animation-timeline: scroll()) {
- .hero { animation-timeline: scroll(); }
-}
-```
-
-```javascript
-if ('gpu' in navigator) { /* WebGPU */ }
-else if (canvas.getContext('webgl2')) { /* WebGL2 fallback */ }
-/* CSS-only fallback must still look good */
-```
-
-### Performance rules
-
-- Target 60fps. If dropping below 50, simplify.
-- Respect `prefers-reduced-motion`, always. Provide a beautiful static alternative.
-- Lazy-initialize heavy resources (WebGL contexts, WASM modules) only when near viewport.
-- Pause off-screen rendering. Kill what you can't see.
-- Test on real mid-range devices, not just your development machine.
-
-### Polish is the difference
-
-The gap between "cool" and "extraordinary" is in the last 20% of refinement: the easing curve on a spring animation, the timing offset in a staggered reveal, the subtle secondary motion that makes a transition feel physical. Don't ship the first version that works; ship the version that feels inevitable.
-
-**NEVER**:
-- Ignore `prefers-reduced-motion`. This is an accessibility requirement, not a suggestion
-- Ship effects that cause jank on mid-range devices
-- Use bleeding-edge APIs without a functional fallback
-- Add sound without explicit user opt-in
-- Use technical ambition to mask weak design fundamentals; fix those first with other commands
-- Layer multiple competing extraordinary moments. Focus creates impact, excess creates noise
-
-## Verify the Result
-
-- **The wow test**: Show it to someone who hasn't seen it. Do they react?
-- **The removal test**: Take it away. Does the experience feel diminished, or does nobody notice?
-- **The device test**: Run it on a phone, a tablet, a Chromebook. Still smooth?
-- **The accessibility test**: Enable reduced motion. Still beautiful?
-- **The context test**: Does this make sense for THIS brand and audience?
-
-"Technically extraordinary" isn't about using the newest API. It's about making an interface do something users didn't think a website could do.
@@ -1,179 +0,0 @@
-# Persona-Based Design Testing
-
-Test the interface through the eyes of 5 distinct user archetypes. Each persona exposes different failure modes that a single "design director" perspective would miss.
-
-**How to use**: Select 2–3 personas most relevant to the interface being critiqued. Walk through the primary user action as each persona. Report specific red flags, not generic concerns.
-
----
-
-## 1. Impatient Power User: "Alex"
-
-
-**Profile**: Expert with similar products. Expects efficiency, hates hand-holding. Will find shortcuts or leave.
-
-**Behaviors**:
-- Skips all onboarding and instructions
-- Looks for keyboard shortcuts immediately
-- Tries to bulk-select, batch-edit, and automate
-- Gets frustrated by required steps that feel unnecessary
-- Abandons if anything feels slow or patronizing
-
-**Test Questions**:
-- Can Alex complete the core task in under 60 seconds?
-- Are there keyboard shortcuts for common actions?
-- Can onboarding be skipped entirely?
-- Do modals have keyboard dismiss (Esc)?
-- Is there a "power user" path (shortcuts, bulk actions)?
-
-**Red Flags** (report these specifically):
-- Forced tutorials or unskippable onboarding
-- No keyboard navigation for primary actions
-- Slow animations that can't be skipped
-- One-item-at-a-time workflows where batch would be natural
-- Redundant confirmation steps for low-risk actions
-
----
-
-## 2. Confused First-Timer: "Jordan"
-
-**Profile**: Never used this type of product. Needs guidance at every step. Will abandon rather than figure it out.
-
-**Behaviors**:
-- Reads all instructions carefully
-- Hesitates before clicking anything unfamiliar
-- Looks for help or support constantly
-- Misunderstands jargon and abbreviations
-- Takes the most literal interpretation of any label
-
-**Test Questions**:
-- Is the first action obviously clear within 5 seconds?
-- Are all icons labeled with text?
-- Is there contextual help at decision points?
-- Does terminology assume prior knowledge?
-- Is there a clear "back" or "undo" at every step?
-
-**Red Flags** (report these specifically):
-- Icon-only navigation with no labels
-- Technical jargon without explanation
-- No visible help option or guidance
-- Ambiguous next steps after completing an action
-- No confirmation that an action succeeded
-
----
-
-## 3. Accessibility-Dependent User: "Sam"
-
-**Profile**: Uses screen reader (VoiceOver/NVDA), keyboard-only navigation. May have low vision, motor impairment, or cognitive differences.
-
-**Behaviors**:
-- Tabs through the interface linearly
-- Relies on ARIA labels and heading structure
-- Cannot see hover states or visual-only indicators
-- Needs adequate color contrast (4.5:1 minimum)
-- May use browser zoom up to 200%
-
-**Test Questions**:
-- Can the entire primary flow be completed keyboard-only?
-- Are all interactive elements focusable with visible focus indicators?
-- Do images have meaningful alt text?
-- Is color contrast WCAG AA compliant (4.5:1 for text)?
-- Does the screen reader announce state changes (loading, success, errors)?
-
-**Red Flags** (report these specifically):
-- Click-only interactions with no keyboard alternative
-- Missing or invisible focus indicators
-- Meaning conveyed by color alone (red = error, green = success)
-- Unlabeled form fields or buttons
-- Time-limited actions without extension option
-- Custom components that break screen reader flow
-
----
-
-## 4. Deliberate Stress Tester: "Riley"
-
-**Profile**: Methodical user who pushes interfaces beyond the happy path. Tests edge cases, tries unexpected inputs, and probes for gaps in the experience.
-
-**Behaviors**:
-- Tests edge cases intentionally (empty states, long strings, special characters)
-- Submits forms with unexpected data (emoji, RTL text, very long values)
-- Tries to break workflows by navigating backwards, refreshing mid-flow, or opening in multiple tabs
-- Looks for inconsistencies between what the UI promises and what actually happens
-- Documents problems methodically
-
-**Test Questions**:
-- What happens at the edges (0 items, 1000 items, very long text)?
-- Do error states recover gracefully or leave the UI in a broken state?
-- What happens on refresh mid-workflow? Is state preserved?
-- Are there features that appear to work but produce broken results?
-- How does the UI handle unexpected input (emoji, special chars, paste from Excel)?
-
-**Red Flags** (report these specifically):
-- Features that appear to work but silently fail or produce wrong results
-- Error handling that exposes technical details or leaves UI in a broken state
-- Empty states that show nothing useful ("No results" with no guidance)
-- Workflows that lose user data on refresh or navigation
-- Inconsistent behavior between similar interactions in different parts of the UI
-
----
-
-## 5. Distracted Mobile User: "Casey"
-
-**Profile**: Using phone one-handed on the go. Frequently interrupted. Possibly on a slow connection.
-
-**Behaviors**:
-- Uses thumb only; prefers bottom-of-screen actions
-- Gets interrupted mid-flow and returns later
-- Switches between apps frequently
-- Has limited attention span and low patience
-- Types as little as possible, prefers taps and selections
-
-**Test Questions**:
-- Are primary actions in the thumb zone (bottom half of screen)?
-- Is state preserved if the user leaves and returns?
-- Does it work on slow connections (3G)?
-- Can forms use autocomplete and smart defaults?
-- Are touch targets at least 44×44pt?
-
-**Red Flags** (report these specifically):
-- Important actions positioned at the top of the screen (unreachable by thumb)
-- No state persistence; progress lost on tab switch or interruption
-- Large text inputs required where selection would work
-- Heavy assets loading on every page (no lazy loading)
-- Tiny tap targets or targets too close together
-
----
-
-## Selecting Personas
-
-Choose personas based on the interface type:
-
-| Interface Type | Primary Personas | Why |
-|---------------|-----------------|-----|
-| Landing page / marketing | Jordan, Riley, Casey | First impressions, trust, mobile |
-| Dashboard / admin | Alex, Sam | Power users, accessibility |
-| E-commerce / checkout | Casey, Riley, Jordan | Mobile, edge cases, clarity |
-| Onboarding flow | Jordan, Casey | Confusion, interruption |
-| Data-heavy / analytics | Alex, Sam | Efficiency, keyboard nav |
-| Form-heavy / wizard | Jordan, Sam, Casey | Clarity, accessibility, mobile |
-
----
-
-## Project-Specific Personas
-
-If `AGENTS.md` contains a `## Design Context` section (generated by `impeccable teach`), derive 1–2 additional personas from the audience and brand information:
-
-1. Read the target audience description
-2. Identify the primary user archetype not covered by the 5 predefined personas
-3. Create a persona following this template:
-
-```
-### [Role]: "[Name]"
-
-**Profile**: [2-3 key characteristics derived from Design Context]
-
-**Behaviors**: [3-4 specific behaviors based on the described audience]
-
-**Red Flags**: [3-4 things that would alienate this specific user type]
-```
-
-Only generate project-specific personas when real Design Context data is available. Don't invent audience details; use the 5 predefined personas when no context exists.
@@ -1,242 +0,0 @@
-> **Additional context needed**: quality bar (MVP vs flagship).
-
-Perform a meticulous final pass to catch all the small details that separate good work from great work. The difference between shipped and polished.
-
-Detector and automated QA output are defect evidence only. A clean script result is never proof that the design is strong; gather browser evidence and inspect the real interaction path.
-
-## Design System Discovery
-
-Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
-
-1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
-2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
-3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category: patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
-
-If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask. Never guess at design system principles.**
-
-## Pre-Polish Assessment
-
-Understand the current state and goals before touching anything:
-
-1. **Review completeness**:
- - Is it functionally complete?
- - Are there known issues to preserve (mark with TODOs)?
- - What's the quality bar? (MVP vs flagship feature?)
- - When does it ship? (How much time for polish?)
-
-2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish; a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
-
-3. **Identify polish areas**:
- - Visual inconsistencies
- - Spacing and alignment issues
- - Interaction state gaps
- - Copy inconsistencies
- - Edge cases and error states
- - Loading and transition smoothness
- - Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
-
-4. **Pull in any prior critique** (optional signal): If `/impeccable critique` has been run on the same target, its priority issues are a useful prior for what to address first. Resolve the target to a file path or URL, then:
- ```bash
- slug=$(node .pi/skills/impeccable/scripts/critique-storage.mjs slug "<resolved>")
- node .pi/skills/impeccable/scripts/critique-storage.mjs latest "$slug"
- ```
- Exit 0 with body = found; fold the P0/P1 items into your polish list and mention the snapshot path so the user sees what you read. Exit 2 = no snapshot, continue without it. The critique is one input among many. Do your own pass either way.
-
-5. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent; never perfect one corner while leaving another rough.
-
-**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
-
-## Polish Systematically
-
-Work through these dimensions methodically:
-
-### Visual Alignment & Spacing
-
-- **Pixel-perfect alignment**: Everything lines up to grid
-- **Consistent spacing**: All gaps use spacing scale (no random 13px gaps)
-- **Optical alignment**: Adjust for visual weight (icons may need offset for optical centering)
-- **Responsive consistency**: Spacing and alignment work at all breakpoints
-- **Grid adherence**: Elements snap to baseline grid
-
-**Check**:
-- Enable grid overlay and verify alignment
-- Check spacing with browser inspector
-- Test at multiple viewport sizes
-- Look for elements that "feel" off
-
-### Information Architecture & Flow
-
-Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
-
-- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
-- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere: modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
-- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
-- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
-- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
-
-### Typography Refinement
-
-- **Hierarchy consistency**: Same elements use same sizes/weights throughout
-- **Line length**: 45-75 characters for body text
-- **Line height**: Appropriate for font size and context
-- **Widows & orphans**: No single words on last line
-- **Hyphenation**: Appropriate for language and column width
-- **Kerning**: Adjust letter spacing where needed (especially headlines)
-- **Font loading**: No FOUT/FOIT flashes
-
-### Color & Contrast
-
-- **Contrast ratios**: All text meets WCAG standards
-- **Consistent token usage**: No hard-coded colors, all use design tokens
-- **Theme consistency**: Works in all theme variants
-- **Color meaning**: Same colors mean same things throughout
-- **Accessible focus**: Focus indicators visible with sufficient contrast
-- **Tinted neutrals**: No pure gray or pure black; add subtle color tint (0.01 chroma)
-- **Gray on color**: Never put gray text on colored backgrounds; use a shade of that color or transparency
-
-### Interaction States
-
-Every interactive element needs all states:
-
-- **Default**: Resting state
-- **Hover**: Subtle feedback (color, scale, shadow)
-- **Focus**: Keyboard focus indicator (never remove without replacement)
-- **Active**: Click/tap feedback
-- **Disabled**: Clearly non-interactive
-- **Loading**: Async action feedback
-- **Error**: Validation or error state
-- **Success**: Successful completion
-
-**Missing states create confusion and broken experiences**.
-
-### Micro-interactions & Transitions
-
-- **Smooth transitions**: All state changes animated appropriately (150-300ms)
-- **Consistent easing**: Use ease-out-quart/quint/expo for natural deceleration. Never bounce or elastic; they feel dated.
-- **No jank**: Smooth animations; use atmospheric blur/filter/mask/shadow effects when they add polish, but bound expensive paint areas and avoid casual layout-property animation
-- **Appropriate motion**: Motion serves purpose, not decoration
-- **Reduced motion**: Respects `prefers-reduced-motion`
-
-### Content & Copy
-
-- **Consistent terminology**: Same things called same names throughout
-- **Consistent capitalization**: Title Case vs Sentence case applied consistently
-- **Grammar & spelling**: No typos
-- **Appropriate length**: Not too wordy, not too terse
-- **Punctuation consistency**: Periods on sentences, not on labels (unless all labels have them)
-
-### Icons & Images
-
-- **Consistent style**: All icons from same family or matching style
-- **Appropriate sizing**: Icons sized consistently for context
-- **Proper alignment**: Icons align with adjacent text optically
-- **Alt text**: All images have descriptive alt text
-- **Loading states**: Images don't cause layout shift, proper aspect ratios
-- **Retina support**: 2x assets for high-DPI screens
-
-### Forms & Inputs
-
-- **Label consistency**: All inputs properly labeled
-- **Required indicators**: Clear and consistent
-- **Error messages**: Helpful and consistent
-- **Tab order**: Logical keyboard navigation
-- **Auto-focus**: Appropriate (don't overuse)
-- **Validation timing**: Consistent (on blur vs on submit)
-
-### Edge Cases & Error States
-
-- **Loading states**: All async actions have loading feedback
-- **Empty states**: Helpful empty states, not just blank space
-- **Error states**: Clear error messages with recovery paths
-- **Success states**: Confirmation of successful actions
-- **Long content**: Handles very long names, descriptions, etc.
-- **No content**: Handles missing data gracefully
-- **Offline**: Appropriate offline handling (if applicable)
-
-### Responsiveness
-
-- **All breakpoints**: Test mobile, tablet, desktop
-- **Touch targets**: 44x44px minimum on touch devices
-- **Readable text**: No text smaller than 14px on mobile
-- **No horizontal scroll**: Content fits viewport
-- **Appropriate reflow**: Content adapts logically
-
-### Performance
-
-- **Fast initial load**: Optimize critical path
-- **No layout shift**: Elements don't jump after load (CLS)
-- **Smooth interactions**: No lag or jank
-- **Optimized images**: Appropriate formats and sizes
-- **Lazy loading**: Off-screen content loads lazily
-
-### Code Quality
-
-- **Remove console logs**: No debug logging in production
-- **Remove commented code**: Clean up dead code
-- **Remove unused imports**: Clean up unused dependencies
-- **Consistent naming**: Variables and functions follow conventions
-- **Type safety**: No TypeScript `any` or ignored errors
-- **Accessibility**: Proper ARIA labels and semantic HTML
-
-## Polish Checklist
-
-Go through systematically:
-
-- [ ] Aligned to the design system (drift named and resolved by root cause)
-- [ ] Information architecture and flow shape match neighboring features
-- [ ] Visual alignment perfect at all breakpoints
-- [ ] Spacing uses design tokens consistently
-- [ ] Typography hierarchy consistent
-- [ ] All interactive states implemented
-- [ ] All transitions smooth (60fps)
-- [ ] Copy is consistent and polished
-- [ ] Icons are consistent and properly sized
-- [ ] All forms properly labeled and validated
-- [ ] Error states are helpful
-- [ ] Loading states are clear
-- [ ] Empty states are welcoming
-- [ ] Touch targets are 44x44px minimum
-- [ ] Contrast ratios meet WCAG AA
-- [ ] Keyboard navigation works
-- [ ] Focus indicators visible
-- [ ] No console errors or warnings
-- [ ] No layout shift on load
-- [ ] Works in all supported browsers
-- [ ] Respects reduced motion preference
-- [ ] Code is clean (no TODOs, console.logs, commented code)
-
-**IMPORTANT**: Polish is about details. Zoom in. Squint at it. Use it yourself. The little things add up.
-
-Sweat the details. Zoom in until the alignment is right and the spacing reads as deliberate. Then ship.
-
-**NEVER**:
-- Polish before it's functionally complete
-- Polish without aligning to the design system; that's decoration on drift
-- Guess at design system principles instead of asking when something is ambiguous
-- Spend hours on polish if it ships in 30 minutes (triage)
-- Introduce bugs while polishing (test thoroughly)
-- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
-- Perfect one thing while leaving others rough (consistent quality level)
-- Create new one-off components when design system equivalents exist
-- Hard-code values that should use design tokens
-- Introduce new patterns or flows that diverge from established ones
-
-## Final Verification
-
-Before marking as done:
-
-- **Use it yourself**: Actually interact with the feature.
-- **Test on real devices**: Not just browser DevTools.
-- **Ask someone else to review**: Fresh eyes catch things.
-- **Compare to design**: Match intended design.
-- **Check all states**: Don't just test happy path.
-- **Treat automation carefully**: Run detector or QA commands when they are available and relevant, fix their defects, but never cite a clean result as proof that the work is polished.
-
-## Clean Up
-
-After polishing, ensure code quality:
-
-- **Replace custom implementations**: If the design system provides a component you reimplemented, switch to the shared version.
-- **Remove orphaned code**: Delete unused styles, components, or files made obsolete by polish.
-- **Consolidate tokens**: If you introduced new values, check whether they should be tokens.
-- **Verify DRYness**: Look for duplication introduced during polishing and consolidate.
@@ -1,62 +0,0 @@
-# Product register
-
-When design SERVES the product: app UIs, admin dashboards, settings panels, data tables, tools, authenticated surfaces, anything where the user is in a task.
-
-## The product slop test
-
-Not "would someone say AI made this." Familiarity is often a feature here. The test is: would a user fluent in the category's best tools (Linear, Figma, Notion, Raycast, Stripe come to mind) sit down and trust this interface, or pause at every subtly-off component?
-
-Product UI's failure mode isn't flatness, it's strangeness without purpose: over-decorated buttons, mismatched form controls, gratuitous motion, display fonts where labels should be, invented affordances for standard tasks. The bar is earned familiarity. The tool should disappear into the task.
-
-## Typography
-
-- **System fonts are legitimate.** `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` gives you native feel on every platform. Inter is the common cross-platform default for a reason.
-- **One family is often right.** Product UIs don't need display/body pairing. A well-tuned sans carries headings, buttons, labels, body, data.
-- **Fixed rem scale, not fluid.** Clamp-sized headings don't serve product UI. Users view at consistent DPI, and a fluid h1 that shrinks in a sidebar looks worse, not better.
-- **Tighter scale ratio.** 1.125–1.2 between steps is typical. More type elements here than on brand surfaces; exaggerated contrast creates noise.
-- **Line length still applies for prose** (65–75ch). Data and compact UI can run denser; tables at 120ch+ are fine.
-
-## Color
-
-Product defaults to Restrained. A single surface can earn Committed (a dashboard where one category color carries a report, an onboarding flow with a drenched welcome screen), but Restrained is the floor.
-
-- State-rich semantic vocabulary: hover, focus, active, disabled, selected, loading, error, warning, success, info. Standardize these.
-- Accent color used for primary actions, current selection, and state indicators only, not decoration.
-- A second neutral layer for sidebars, toolbars, and panels (slightly cooler or warmer than the content surface).
-
-## Layout
-
-- Predictable grids. Consistency IS an affordance; users navigate faster when the structure is expected.
-- Familiar patterns are features. Standard navigation (top bar, side nav), breadcrumbs, tabs, and form layouts have established user expectations. Don't reinvent for flavor.
-- Responsive behavior is structural (collapse sidebar, responsive table, breakpoint-driven columns), not fluid typography.
-
-## Components
-
-Every interactive component has: default, hover, focus, active, disabled, loading, error. Don't ship with half of these.
-
-- Skeleton states for loading, not spinners in the middle of content.
-- Empty states that teach the interface, not "nothing here."
-- Consistent affordances across the surface. Same button shape. Same form-control vocabulary. Same icon style.
-
-## Motion
-
-- 150–250 ms on most transitions. Users are in flow; don't make them wait for choreography.
-- Motion conveys state, not decoration. State change, feedback, loading, reveal: nothing else.
-- No orchestrated page-load sequences. Product loads into a task; users don't want to watch it load.
-
-## Product bans (on top of the shared absolute bans)
-
-- Decorative motion that doesn't convey state.
-- Inconsistent component vocabulary across screens. If the "save" button looks different in two places, one is wrong.
-- Display fonts in UI labels, buttons, data.
-- Reinventing standard affordances for flavor (custom scrollbars, weird form controls, non-standard modals).
-- Heavy color or full-saturation accents on inactive states.
-
-## Product permissions
-
-Product can afford things brand surfaces can't.
-
-- System fonts and familiar sans defaults (Inter, SF Pro, system-ui stacks).
-- Standard navigation patterns: top bar + side nav, breadcrumbs, tabs, command palettes.
-- Density. Tables with many rows, panels with many labels, dense information when users need it.
-- Consistency over surprise. The same visual vocabulary screen to screen is a virtue; delight is saved for moments, not pages.
@@ -1,99 +0,0 @@
-Quiet design is harder than bold design. Subtlety needs precision. Reduce visual intensity in designs that are too loud, aggressive, or overstimulating without losing personality or making the result generic.
-
----
-
-## Register
-
-Brand: "quieter" means more restrained palette, more whitespace, more typographic air. Drama is reduced, not eliminated; the POV stays intact.
-
-Product: "quieter" means reducing visual noise. Fewer background accents, flatter cards, less color, less motion. The tool should disappear more completely into the task.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too intense:
-
-1. **Identify intensity sources**:
- - **Color saturation**: Overly bright or saturated colors
- - **Contrast extremes**: Too much high-contrast juxtaposition
- - **Visual weight**: Too many bold, heavy elements competing
- - **Animation excess**: Too much motion or overly dramatic effects
- - **Complexity**: Too many visual elements, patterns, or decorations
- - **Scale**: Everything is large and loud with no hierarchy
-
-2. **Understand the context**:
- - What's the purpose? (Marketing vs tool vs reading experience)
- - Who's the audience? (Some contexts need energy)
- - What's working? (Don't throw away good ideas)
- - What's the core message? (Preserve what matters)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Quieter" doesn't mean boring or generic. It means refined and easier on the eyes. Think luxury, not laziness.
-
-## Plan Refinement
-
-Create a strategy to reduce intensity while maintaining impact:
-
-- **Color approach**: Desaturate or shift to more restrained tones?
-- **Hierarchy approach**: Which elements should stay bold (very few), which should recede?
-- **Simplification approach**: What can be removed entirely?
-- **Sophistication approach**: How can we signal quality through restraint?
-
-**IMPORTANT**: Subtlety requires precision. Quiet without intent collapses to generic.
-
-## Refine the Design
-
-Systematically reduce intensity across these dimensions:
-
-### Color Refinement
-- **Reduce saturation**: Shift from fully saturated to 70-85% saturation
-- **Soften palette**: Replace bright colors with muted tones
-- **Reduce color variety**: Use fewer colors more thoughtfully
-- **Neutral dominance**: Let neutrals do more work, use color as accent (10% rule)
-- **Gentler contrasts**: High contrast only where it matters most
-- **Tinted grays**: Use warm or cool tinted grays instead of pure gray. Adds depth without loudness
-- **Never gray on color**: If you have gray text on a colored background, use a darker shade of that color or transparency instead
-
-### Visual Weight Reduction
-- **Typography**: Reduce font weights (900 → 600, 700 → 500), decrease sizes where appropriate
-- **Hierarchy through subtlety**: Use weight, size, and space instead of color and boldness
-- **White space**: Increase breathing room, reduce density
-- **Borders & lines**: Reduce thickness, decrease opacity, or remove entirely
-
-### Simplification
-- **Remove decorative elements**: Gradients, shadows, patterns, textures that don't serve purpose
-- **Simplify shapes**: Reduce border radius extremes, simplify custom shapes
-- **Reduce layering**: Flatten visual hierarchy where possible
-- **Clean up effects**: Reduce or remove blur effects, glows, multiple shadows
-
-### Motion Reduction
-- **Reduce animation intensity**: Shorter distances (10-20px instead of 40px), gentler easing
-- **Remove decorative animations**: Keep functional motion, remove flourishes
-- **Subtle micro-interactions**: Replace dramatic effects with gentle feedback
-- **Refined easing**: Use ease-out-quart for smooth, understated motion. Never bounce or elastic
-- **Remove animations entirely** if they're not serving a clear purpose
-
-### Composition Refinement
-- **Reduce scale jumps**: Smaller contrast between sizes creates calmer feeling
-- **Align to grid**: Bring rogue elements back into systematic alignment
-- **Even out spacing**: Replace extreme spacing variations with consistent rhythm
-
-**NEVER**:
-- Make everything the same size/weight (hierarchy still matters)
-- Remove all color (quiet ≠ grayscale)
-- Eliminate all personality (maintain character through refinement)
-- Sacrifice usability for aesthetics (functional elements still need clear affordances)
-- Make everything small and light (some anchors needed)
-
-## Verify Quality
-
-Ensure refinement maintains quality:
-
-- **Still functional**: Can users still accomplish tasks easily?
-- **Still distinctive**: Does it have character, or is it generic now?
-- **Better reading**: Is text easier to read for extended periods?
-- **Restrained, not absent**: Does the POV survive the cuts?
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,114 +0,0 @@
-# Responsive Design
-
-## Mobile-First: Write It Right
-
-Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
-
-## Breakpoints: Content-Driven
-
-Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
-
-## Detect Input Method, Not Just Screen Size
-
-**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
-
-```css
-/* Fine pointer (mouse, trackpad) */
-@media (pointer: fine) {
- .button { padding: 8px 16px; }
-}
-
-/* Coarse pointer (touch, stylus) */
-@media (pointer: coarse) {
- .button { padding: 12px 20px; } /* Larger touch target */
-}
-
-/* Device supports hover */
-@media (hover: hover) {
- .card:hover { transform: translateY(-2px); }
-}
-
-/* Device doesn't support hover (touch) */
-@media (hover: none) {
- .card { /* No hover state - use active instead */ }
-}
-```
-
-**Critical**: Don't rely on hover for functionality. Touch users can't hover.
-
-## Safe Areas: Handle the Notch
-
-Modern phones have notches, rounded corners, and home indicators. Use `env()`:
-
-```css
-body {
- padding-top: env(safe-area-inset-top);
- padding-bottom: env(safe-area-inset-bottom);
- padding-left: env(safe-area-inset-left);
- padding-right: env(safe-area-inset-right);
-}
-
-/* With fallback */
-.footer {
- padding-bottom: max(1rem, env(safe-area-inset-bottom));
-}
-```
-
-**Enable viewport-fit** in your meta tag:
-```html
-<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
-```
-
-## Responsive Images: Get It Right
-
-### srcset with Width Descriptors
-
-```html
-<img
- src="hero-800.jpg"
- srcset="
- hero-400.jpg 400w,
- hero-800.jpg 800w,
- hero-1200.jpg 1200w
- "
- sizes="(max-width: 768px) 100vw, 50vw"
- alt="Hero image"
->
-```
-
-**How it works**:
-- `srcset` lists available images with their actual widths (`w` descriptors)
-- `sizes` tells the browser how wide the image will display
-- Browser picks the best file based on viewport width AND device pixel ratio
-
-### Picture Element for Art Direction
-
-When you need different crops/compositions (not just resolutions):
-
-```html
-<picture>
- <source media="(min-width: 768px)" srcset="wide.jpg">
- <source media="(max-width: 767px)" srcset="tall.jpg">
- <img src="fallback.jpg" alt="...">
-</picture>
-```
-
-## Layout Adaptation Patterns
-
-**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
-
-## Testing: Don't Trust DevTools Alone
-
-DevTools device emulation is useful for layout but misses:
-
-- Actual touch interactions
-- Real CPU/memory constraints
-- Network latency patterns
-- Font rendering differences
-- Browser chrome/keyboard appearances
-
-**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
-
----
-
-**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
@@ -1,165 +0,0 @@
-Shape the UX and UI for a feature before any code is written. This command produces a **design brief**: a structured artifact that guides implementation through discovery, not guesswork.
-
-**Scope**: Design planning only. This command does NOT write code. It produces the thinking that makes code good.
-
-**Output**: A design brief that can be handed off to /impeccable craft, or directly to /impeccable for freeform implementation. When visual direction probes are used, the images are supporting artifacts, not the primary output.
-
-## Philosophy
-
-Most AI-generated UIs fail not because of bad code, but because of skipped thinking. They jump to "here's a card grid" without asking "what is the user trying to accomplish?" This command inverts that: understand deeply first, so implementation is precise.
-
-## Phase 1: Discovery Interview
-
-**Do NOT write any code or make any design decisions during this phase.** Your only job is to understand the feature deeply enough to make excellent design decisions later.
-
-This is a required interaction, not optional guidance. Ask these questions in conversation, adapting based on answers. Don't dump them all at once; have a natural dialogue. ask the user directly to clarify what you cannot infer.
-
-### Interview cadence
-
-Discovery includes at least one user-answer round unless PRODUCT.md, DESIGN.md, or an already-confirmed brief directly answers the needed inputs. With a sparse prompt, do **not** synthesize a complete brief for confirmation on the first response.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Treat PRODUCT.md and DESIGN.md as anchors; they reduce repeated questions but do **not** replace shape for craft. Shape is task-specific.
-- One round is the default. Add a second only if the first answers leave material gaps. Don't run a second round just to feel thorough.
-- Round 1 should clarify purpose, audience/context, content/scope, and (for brand) visual direction.
-- Round 2, when needed, fills in whatever's still genuinely missing.
-
-**Assert-then-confirm, not menu-with-escape.** When PRODUCT.md and the user's prompt make one option obvious, name it and ask the user to confirm or override. Don't enumerate "Restrained / Committed / Or something else?" as a real choice; "This reads as Restrained, confirm?" beats a four-option menu when the answer is already clear.
-
-### Purpose & Context
-- What is this feature for? What problem does it solve?
-- Who specifically will use it? (Not "users"; be specific: role, context, frequency)
-- What does success look like? How will you know this feature is working?
-- What's the user's state of mind when they reach this feature? (Rushed? Exploring? Anxious? Focused?)
-
-### Content & Data
-- What content or data does this feature display or collect?
-- What are the realistic ranges? (Minimum, typical, maximum, e.g., 0 items, 5 items, 500 items)
-- What are the edge cases? (Empty state, error state, first-time use, power user)
-- Is any content dynamic? What changes and how often?
-- What visual assets are real content here? Note required images, product shots, illustrations, maps, textures, diagrams, generated objects, or existing project assets.
-
-### Design Direction
-
-Force a visual decision on three fronts. Skip anything PRODUCT.md or DESIGN.md already answers; ask only what's missing.
-
-- **Color strategy for this surface.** Pick one: Restrained / Committed / Full palette / Drenched. Can override the project default if the surface earns it (e.g. a drenched hero inside an otherwise Restrained product).
-- **Theme via scene sentence.** Write one sentence of physical context for this surface: who uses it, where, under what ambient light, in what mood. The sentence forces dark vs light. If it doesn't, add detail until it does.
-- **Two or three named anchor references.** Specific products, brands, objects. Not adjectives like "modern" or "clean."
-
-### Scope
-
-Always ask. Sketch quality and shipped quality are different outputs; don't guess between them.
-
-- **Fidelity.** Sketch / mid-fi / high-fi / production-ready?
-- **Breadth.** One screen / a flow / a whole surface?
-- **Interactivity.** Static visual / interactive prototype / shipped-quality component?
-- **Time intent.** Quick exploration, or polish until it ships?
-
-Scope answers are task-scoped. Don't write them to PRODUCT.md or DESIGN.md; carry them through the design brief only.
-
-### Constraints
-- Are there technical constraints? (Framework, performance budget, browser support)
-- Are there content constraints? (Localization, dynamic text length, user-generated content)
-- Mobile/responsive requirements?
-- Accessibility requirements beyond WCAG AA?
-
-### Anti-Goals
-- What should this NOT be? What would be a wrong direction?
-- What's the biggest risk of getting this wrong?
-
-## Phase 1.5: Visual Direction Probe (Capability-Gated)
-
-After the discovery interview, generate a small set of visual direction probes **before** writing the final brief when all of these are true:
-
-- The work is **net-new** or directionally ambiguous enough that visual exploration will clarify the brief.
-- The requested fidelity is **mid-fi, high-fi, or production-ready**. Skip for sketch-only planning.
-- The current harness gives you native image generation (Codex's `image_gen`, an equivalent MCP tool, or similar). Don't ask the user to install APIs or tooling.
-
-When those conditions are met, this step is mandatory. If image generation isn't natively available, do not ask the user to install APIs or tooling. State in one line that the image step is skipped because the harness lacks native image generation, then proceed. The one-line announcement is required, not optional; it forces a conscious decision instead of letting the step quietly evaporate.
-
-Use probes to explore visual lanes, not to replace the brief.
-
-Do not skip probes because the final UI will be semantic, editable, code-native, responsive, or accessible. Those are implementation requirements, not reasons to avoid visual exploration.
-
-### What to generate
-
-Generate **2 to 4** distinct direction probes based on the discovery answers, especially:
-
-- Color strategy
-- Theme scene sentence
-- Named anchor references
-- Scope and fidelity
-
-The probes should differ in primary visual direction (hierarchy, topology, density, typographic voice, or color strategy), not just palette tweaks.
-
-### How to use the probes
-
-- Treat them as **direction tests**, not final designs.
-- Use them to pressure-test whether the brief is pointing at the right lane.
-- Ask the user which direction feels closest, what feels off, and what should carry forward.
-- If the probes reveal a mismatch, revise the brief inputs before finalizing the brief.
-
-### Important limits
-
-- Do **not** skip discovery because image generation is available.
-- Do **not** treat generated imagery as final UX specification, final copy, or final accessibility behavior.
-- Do **not** use this step for minor refinements of existing work. It's for shaping a new surface or clarifying a big directional choice.
-
-If image generation isn't natively available, announce the skip in one line and proceed to the design brief.
-
-## Phase 2: Design Brief
-
-After the interview and any required probes, present a brief and **end your response**. The user must confirm before any implementation runs. Do not present a brief and then continue to code in the same response, even if the brief feels obvious to you. The user's confirmation is the gate.
-
-**Choose the brief shape based on how clear the answers are:**
-
-- **Compact form (3-5 bullets)** when discovery was crisp and the original prompt + PRODUCT.md already pinned scope, content, and direction. State what you're building, the visual lane, and end with one or two specific questions or a clear "confirm or override?" prompt. This is the default for typical craft requests with a clear prompt.
-- **Full structured form (sections below)** when the task is genuinely ambiguous, multi-screen, or when the user asked for shape as a standalone step. Use this when the discipline of structure earns its weight.
-
-Don't pad a clear brief into a long one to look thorough. A 70-line brief restating answers the user just gave is noise, not rigor. Equally, don't skip the confirmation pause to look efficient: the pause is the point.
-
-Present the brief, then **stop and wait for explicit confirmation**. You are not the judge of whether the user already approved. Even when the brief feels obviously right, ask once and wait. The pause is what separates shape from premature implementation.
-
-### Brief Structure
-
-**1. Feature Summary** (2-3 sentences)
-What this is, who it's for, what it needs to accomplish.
-
-**2. Primary User Action**
-The single most important thing a user should do or understand here.
-
-**3. Design Direction**
-Color strategy (Restrained / Committed / Full palette / Drenched) + the theme scene sentence + 2–3 named anchor references. Reference PRODUCT.md and DESIGN.md where they already answer, and note any per-surface overrides.
-
-If you ran the Visual Direction Probe step, name which probe direction won and what changed in the brief because of it.
-
-**4. Scope**
-Fidelity, breadth, interactivity, and time intent from the Scope section of the interview. Task-scoped; these don't persist beyond the brief.
-
-**5. Layout Strategy**
-High-level spatial approach: what gets emphasis, what's secondary, how information flows. Describe the visual hierarchy and rhythm, not specific CSS.
-
-**6. Key States**
-List every state the feature needs: default, empty, loading, error, success, edge cases. For each, note what the user needs to see and feel.
-
-**7. Interaction Model**
-How users interact with this feature. What happens on click, hover, scroll? What feedback do they get? What's the flow from entry to completion?
-
-**8. Content Requirements**
-What copy, labels, empty state messages, error messages, and microcopy are needed. Note any dynamic content and its realistic ranges. For image-led surfaces, also list the required image/media roles and their likely source (project asset, generated raster, semantic SVG/CSS, canvas/WebGL, icon library, or accepted omission).
-
-**9. Recommended References**
-Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., spatial-design.md for complex layouts, motion-design.md for animated features, interaction-design.md for form-heavy features).
-
-**10. Open Questions**
-Anything genuinely unresolved. Don't list "open questions" you've already recommended a default for; assert the default and move on. If you'd write `Recommend: X` next to a question, just decide X.
-
----
-
-ask the user directly to clarify what you cannot infer. Ask for explicit confirmation of the brief before finishing.
-
-If the user disagrees with any part, revisit the relevant discovery questions. A shape run is incomplete until the user confirms direction.
-
-Once confirmed, the brief is complete. The user can now hand it to /impeccable, or use it to guide any other implementation approach. (If the user wants the full discovery-then-build flow in one step, they should use /impeccable craft instead, which runs this command internally.)
@@ -1,100 +0,0 @@
-# Spatial Design
-
-## Spacing Systems
-
-### Use 4pt Base, Not 8pt
-
-8pt systems are too coarse; you'll frequently need 12px (between 8 and 16). Use 4pt for granularity: 4, 8, 12, 16, 24, 32, 48, 64, 96px.
-
-### Name Tokens Semantically
-
-Name by relationship (`--space-sm`, `--space-lg`), not value (`--spacing-8`). Use `gap` instead of margins for sibling spacing; it eliminates margin collapse and cleanup hacks.
-
-## Grid Systems
-
-### The Self-Adjusting Grid
-
-Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Columns are at least 280px, as many as fit per row, leftovers stretch. For complex layouts, use named grid areas (`grid-template-areas`) and redefine them at breakpoints.
-
-## Visual Hierarchy
-
-### The Squint Test
-
-Blur your eyes (or screenshot and blur). Can you still identify:
-- The most important element?
-- The second most important?
-- Clear groupings?
-
-If everything looks the same weight blurred, you have a hierarchy problem.
-
-### Hierarchy Through Multiple Dimensions
-
-Don't rely on size alone. Combine:
-
-| Tool | Strong Hierarchy | Weak Hierarchy |
-|------|------------------|----------------|
-| **Size** | 3:1 ratio or more | <2:1 ratio |
-| **Weight** | Bold vs Regular | Medium vs Regular |
-| **Color** | High contrast | Similar tones |
-| **Position** | Top/left (primary) | Bottom/right |
-| **Space** | Surrounded by white space | Crowded |
-
-**The best hierarchy uses 2-3 dimensions at once**: A heading that's larger, bolder, AND has more space above it.
-
-### Cards Are Not Required
-
-Cards are overused. Spacing and alignment create visual grouping naturally. Use cards only when content is truly distinct and actionable, items need visual comparison in a grid, or content needs clear interaction boundaries. **Never nest cards inside cards.** Use spacing, typography, and subtle dividers for hierarchy within a card.
-
-## Container Queries
-
-Viewport queries are for page layouts. **Container queries are for components**:
-
-```css
-.card-container {
- container-type: inline-size;
-}
-
-.card {
- display: grid;
- gap: var(--space-md);
-}
-
-/* Card layout changes based on its container, not viewport */
-@container (min-width: 400px) {
- .card {
- grid-template-columns: 120px 1fr;
- }
-}
-```
-
-**Why this matters**: A card in a narrow sidebar stays compact, while the same card in a main content area expands automatically, without viewport hacks.
-
-## Optical Adjustments
-
-Text at `margin-left: 0` looks indented due to letterform whitespace; use negative margin (`-0.05em`) to optically align. Geometrically centered icons often look off-center; play icons need to shift right, arrows shift toward their direction.
-
-### Touch Targets vs Visual Size
-
-Buttons can look small but need large touch targets (44px minimum). Use padding or pseudo-elements:
-
-```css
-.icon-button {
- width: 24px; /* Visual size */
- height: 24px;
- position: relative;
-}
-
-.icon-button::before {
- content: '';
- position: absolute;
- inset: -10px; /* Expand tap target to 44px */
-}
-```
-
-## Depth & Elevation
-
-Create semantic z-index scales (dropdown → sticky → modal-backdrop → modal → toast → tooltip) instead of arbitrary numbers. For shadows, create a consistent elevation scale (sm → md → lg → xl). **Key insight**: Shadows should be subtle. If you can clearly see it, it's probably too strong.
-
----
-
-**Avoid**: Arbitrary spacing values outside your scale. Making all spacing equal (variety creates hierarchy). Creating hierarchy through size alone - combine size, weight, color, and space.
@@ -1,156 +0,0 @@
-# Teach Flow
-
-Gathers design context for a project and writes two complementary files at the project root:
-
-- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
-- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
-
-Every other impeccable command reads these files before doing any work.
-
-## Step 1: Load current state
-
-Run the shared loader first so you know what already exists:
-
-```bash
-node .pi/skills/impeccable/scripts/load-context.mjs
-```
-
-The output tells you whether PRODUCT.md and/or DESIGN.md already exist. If `migrated: true`, legacy `.impeccable.md` was auto-renamed to `PRODUCT.md`. Mention this once to the user.
-
-Decision tree:
-- **Neither file exists (empty project or no context yet)**: do Steps 2-4 (write PRODUCT.md), then decide on DESIGN.md based on whether there's code to analyze.
-- **PRODUCT.md exists, DESIGN.md missing**: skip to Step 5 and offer to run `/impeccable document` for DESIGN.md.
-- **PRODUCT.md exists but has no `## Register` section (legacy)**: add it. Infer a hypothesis from the codebase (see Step 2), confirm with the user, write the field.
-- **Both exist**: ask the user directly to clarify what you cannot infer. Ask which file to refresh. Skip the one the user doesn't want changed.
-- **Just DESIGN.md exists (unusual)**: do Steps 2-4 to produce PRODUCT.md.
-
-Never silently overwrite an existing file. Always confirm first.
-
-If teach was invoked as a setup blocker by another command, such as `/impeccable craft landing page`, pause that command here. Complete teach, re-run the loader, then resume the original command with the freshly loaded context. For craft, resume into shape next; teach creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
-
-## Step 2: Explore the codebase
-
-Before asking questions, thoroughly scan the project to discover what you can:
-
-- **README and docs**: Project purpose, target audience, any stated goals
-- **Package.json / config files**: Tech stack, dependencies, existing design libraries
-- **Existing components**: Current design patterns, spacing, typography in use
-- **Brand assets**: Logos, favicons, color values already defined
-- **Design tokens / CSS variables**: Existing color palettes, font stacks, spacing scales
-- **Any style guides or brand documentation**
-
-Also form a **register hypothesis** from what you find:
-
-- Brand signals: `/`, `/about`, `/pricing`, `/blog/*`, `/docs/*`, hero sections, big typography, scroll-driven sections, landing-page-shaped content.
-- Product signals: `/app/*`, `/dashboard`, `/settings`, `/(auth)`, forms, data tables, side/top nav, app-shell components.
-
-Register is a hypothesis at this point, not a decision; Step 3 confirms it.
-
-Note what you've learned and what remains unclear. This exploration feeds both PRODUCT.md and DESIGN.md.
-
-## Step 3: Ask strategic questions (for PRODUCT.md)
-
-ask the user directly to clarify what you cannot infer. Ask only about what you couldn't infer from the codebase.
-
-### Interview mode, not confirmation mode
-
-If the repo is empty or the user's brief is sparse, run a short interview before proposing PRODUCT.md. Do **not** turn a one-sentence request into a complete inferred PRODUCT.md and ask for blanket confirmation.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Use inferred answers as hypotheses or options, not as finished facts.
-- Complete at least one real user-answer round before drafting PRODUCT.md, unless every required answer is directly discoverable from repo docs.
-- Round 1 should establish register, users/purpose, and desired outcome.
-- Round 2 should establish brand personality or references, anti-references, and accessibility needs.
-
-### Minimum viable interview
-
-Ask enough to complete PRODUCT.md. At minimum, cover register confirmation, users and purpose, brand personality, anti-references, and accessibility needs unless each answer is directly discoverable from repo context. After at least one interview round, you may propose inferred answers, but the user must confirm them before you write PRODUCT.md. Never synthesize PRODUCT.md from the original task prompt alone.
-
-### Register (ask first; it shapes everything below)
-
-Every design task is either **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboards, tools: design SERVES the product).
-
-If Step 2 produced a clear hypothesis, lead with it: *"From the codebase, this looks like a [brand / product] surface. Does that match your intent, or should we treat it differently?"*
-
-If the signal is genuinely split (e.g. a product with a big marketing landing), ask the user directly to clarify what you cannot infer. Ask which register describes the **primary** surface. The register can be overridden per task later, but PRODUCT.md carries one default.
-
-### Users & Purpose
-- Who uses this? What's their context when using it?
-- What job are they trying to get done?
-- For brand: what emotions should the interface evoke? (confidence, delight, calm, urgency)
-- For product: what workflow are they in? What's the primary task on any given screen?
-
-### Brand & Personality
-- How would you describe the brand personality in 3 words?
-- Reference sites or apps that capture the right feel? What specifically about them?
- - For brand, push for real-world references in the right lane (tech-minimal, editorial-magazine, consumer-warm, brutalist-grid, etc.), not generic "modern" adjectives.
- - For product, push for category best-tool references (Linear, Figma, Notion, Raycast, Stripe).
-- What should this explicitly NOT look like? Any anti-references?
-
-### Accessibility & Inclusion
-- Specific accessibility requirements? (WCAG level, known user needs)
-- Considerations for reduced motion, color blindness, or other accommodations?
-
-Skip questions where the answer is already clear. **Do NOT ask about colors, fonts, radii, or visual styling here.** Those belong in DESIGN.md, not PRODUCT.md.
-
-## Step 4: Write PRODUCT.md
-
-Write PRODUCT.md only after the user has confirmed the strategic answers from Step 3. If an inferred answer is uncertain or unconfirmed, ask before writing.
-
-Synthesize into a strategic document:
-
-```markdown
-# Product
-
-## Register
-
-product
-
-## Users
-[Who they are, their context, the job to be done]
-
-## Product Purpose
-[What this product does, why it exists, what success looks like]
-
-## Brand Personality
-[Voice, tone, 3-word personality, emotional goals]
-
-## Anti-references
-[What this should NOT look like. Specific bad-example sites or patterns to avoid.]
-
-## Design Principles
-[3-5 strategic principles derived from the conversation. Principles like "practice what you preach", "show, don't tell", "expert confidence". NOT visual rules like "use OKLCH" or "magenta accent".]
-
-## Accessibility & Inclusion
-[WCAG level, known user needs, considerations]
-```
-
-Register is either `brand` or `product` as a bare value. No prose, no commentary.
-
-Write to `PROJECT_ROOT/PRODUCT.md`. If `.impeccable.md` existed, the loader already renamed it; merge into that content rather than starting from scratch.
-
-## Step 5: Decide on DESIGN.md
-
-Offer `/impeccable document` either way. Two paths:
-
-- **Code exists** (CSS tokens, components, a running site): "I can generate a DESIGN.md that captures your visual system (colors, typography, components) so variants stay on-brand. Want to do that now?"
-- **Pre-implementation** (empty project): "I can seed a starter DESIGN.md from five quick questions about color strategy, type direction, motion energy, and references. You can re-run once there's code, to capture the real tokens. Want to do that now?"
-
-If the user agrees, delegate to `/impeccable document` (it auto-detects scan vs seed). Load its reference and follow that flow.
-
-If the user prefers to skip, mention they can run `/impeccable document` any time later.
-
-## Step 6: Confirm and wrap up
-
-Summarize:
-- Register captured (brand / product)
-- What was written (PRODUCT.md, DESIGN.md, or both)
-- The 3-5 strategic principles from PRODUCT.md that will guide future work
-- If DESIGN.md is pending, remind the user how to generate it later
-
-**Critical: re-run the loader to refresh session context.** After writing PRODUCT.md, run `node .pi/skills/impeccable/scripts/load-context.mjs` one final time and let its full JSON output land in conversation. This ensures subsequent commands in this session use the freshly-written PRODUCT.md, not a stale earlier version.
-
-If teach was invoked as a blocker by another impeccable command (e.g. the user ran `/impeccable polish` with no PRODUCT.md), resume that original task now with the fresh context.
-
-Optionally ask the user directly to clarify what you cannot infer. Ask whether they'd like a brief summary of PRODUCT.md appended to AGENTS.md for easier agent reference. If yes, append a short **Design Context** pointer section there.
@@ -1,124 +0,0 @@
-Typography carries most of the information on the page. Replace generic defaults (Inter, Roboto, system fallback at flat scale) with type that reflects the brand and scales with intentional contrast.
-
----
-
-## Register
-
-Brand: run the font selection procedure in [brand.md](brand.md). Pairing follows the brand's lane (display serif + sans body for editorial/luxury, one committed sans for tech, etc.). Fluid `clamp()` scale, ≥1.25 ratio between steps.
-
-Product: system fonts and familiar sans stacks are legitimate here. One well-tuned family typically carries the whole UI. Fixed `rem` scale, 1.125–1.2 ratio between more closely-spaced steps.
-
----
-
-## Assess Current Typography
-
-Analyze what's weak or generic about the current type:
-
-1. **Font choices**:
- - Are we using invisible defaults? (Inter, Roboto, Arial, Open Sans, system defaults)
- - Does the font match the brand personality? (A playful brand shouldn't use a corporate typeface)
- - Are there too many font families? (More than 2-3 is almost always a mess)
-
-2. **Hierarchy**:
- - Can you tell headings from body from captions at a glance?
- - Are font sizes too close together? (14px, 15px, 16px = muddy hierarchy)
- - Are weight contrasts strong enough? (Medium vs Regular is barely visible)
-
-3. **Sizing & scale**:
- - Is there a consistent type scale, or are sizes arbitrary?
- - Does body text meet minimum readability? (16px+)
- - Is the sizing strategy appropriate for the context? (Fixed `rem` scales for app UIs; fluid `clamp()` for marketing/content page headings)
-
-4. **Readability**:
- - Are line lengths comfortable? (45-75 characters ideal)
- - Is line-height appropriate for the font and context?
- - Is there enough contrast between text and background?
-
-5. **Consistency**:
- - Are the same elements styled the same way throughout?
- - Are font weights used consistently? (Not bold in one section, semibold in another for the same role)
- - Is letter-spacing intentional or default everywhere?
-
-**CRITICAL**: The goal isn't to make text "fancier." It's to make it clearer, more readable, and more intentional. Good typography is invisible; bad typography is distracting.
-
-## Plan Typography Improvements
-
-Consult the [typography reference](typography.md) for detailed guidance on scales, pairing, and loading strategies.
-
-Create a systematic plan:
-
-- **Font selection**: Do fonts need replacing? What fits the brand/context?
-- **Type scale**: Establish a modular scale (e.g., 1.25 ratio) with clear hierarchy
-- **Weight strategy**: Which weights serve which roles? (Regular for body, Semibold for labels, Bold for headings, or whatever fits)
-- **Spacing**: Line-heights, letter-spacing, and margins between typographic elements
-
-## Improve Typography Systematically
-
-### Font Selection
-
-If fonts need replacing:
-- Choose fonts that reflect the brand personality
-- Pair with genuine contrast (serif + sans, geometric + humanist), or use a single family in multiple weights
-- Ensure web font loading doesn't cause layout shift (`font-display: swap`, metric-matched fallbacks)
-
-### Establish Hierarchy
-
-Build a clear type scale:
-- **5 sizes cover most needs**: caption, secondary, body, subheading, heading
-- **Use a consistent ratio** between levels (1.25, 1.333, or 1.5)
-- **Combine dimensions**: Size + weight + color + space for strong hierarchy. Don't rely on size alone
-- **App UIs**: Use a fixed `rem`-based type scale, optionally adjusted at 1-2 breakpoints. Fluid sizing undermines the spatial predictability that dense, container-based layouts need
-- **Marketing / content pages**: Use fluid sizing via `clamp(min, preferred, max)` for headings and display text. Keep body text fixed
-
-### Fix Readability
-
-- Set `max-width` on text containers using `ch` units (`max-width: 65ch`)
-- Adjust line-height per context: tighter for headings (1.1-1.2), looser for body (1.5-1.7)
-- Increase line-height slightly for light-on-dark text
-- Ensure body text is at least 16px / 1rem
-
-### Refine Details
-
-- Use `tabular-nums` for data tables and numbers that should align
-- Apply proper `letter-spacing`: slightly open for small caps and uppercase, default or tight for large display text
-- Use semantic token names (`--text-body`, `--text-heading`), not value names (`--font-16`)
-- Set `font-kerning: normal` and consider OpenType features where appropriate
-
-### Weight Consistency
-
-- Define clear roles for each weight and stick to them
-- Don't use more than 3-4 weights (Regular, Medium, Semibold, Bold is plenty)
-- Load only the weights you actually use (each weight adds to page load)
-
-**NEVER**:
-- Use more than 2-3 font families
-- Pick sizes arbitrarily; commit to a scale
-- Set body text below 16px
-- Use decorative/display fonts for body text
-- Disable browser zoom (`user-scalable=no`)
-- Use `px` for font sizes; use `rem` to respect user settings
-- Default to Inter/Roboto/Open Sans when personality matters
-- Pair fonts that are similar but not identical (two geometric sans-serifs)
-
-## Verify Typography Improvements
-
-- **Hierarchy**: Can you identify heading vs body vs caption instantly?
-- **Readability**: Is body text comfortable to read in long passages?
-- **Consistency**: Are same-role elements styled identically throughout?
-- **Personality**: Does the typography reflect the brand?
-- **Performance**: Are web fonts loading efficiently without layout shift?
-- **Accessibility**: Does text meet WCAG contrast ratios? Is it zoomable to 200%?
-
-When the type carries the hierarchy on its own, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `scale` param controlling the hierarchy ratio. Express all font sizes in the variant's scoped CSS through `calc(var(--p-scale, 1) * <base>)` or, better, scale the type ramp via `clamp(min, calc(var(--p-scale, 1) * Npx), max)`. Users slide from subdued to commanding.
-
-```json
-{"id":"scale","kind":"range","min":0.85,"max":1.3,"step":0.05,"default":1,"label":"Scale"}
-```
-
-Where the variant riffs on a specific pairing, expose the pairing choice as a `steps` param (e.g. "serif display + sans body" vs. "mono display + sans body" vs. "all-sans"). Each branch routes through `:scope[data-p-pairing="X"]` selectors in scoped CSS.
-
-See `reference/live.md` for the full params contract.
@@ -1,159 +0,0 @@
-# Typography
-
-## Classic Typography Principles
-
-### Vertical Rhythm
-
-Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
-
-### Modular Scale & Hierarchy
-
-The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
-
-**Use fewer sizes with more contrast.** A 5-size system covers most needs:
-
-| Role | Typical Ratio | Use Case |
-|------|---------------|----------|
-| xs | 0.75rem | Captions, legal |
-| sm | 0.875rem | Secondary UI, metadata |
-| base | 1rem | Body text |
-| lg | 1.25-1.5rem | Subheadings, lead text |
-| xl+ | 2-4rem | Headlines, hero text |
-
-Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
-
-### Readability & Measure
-
-Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
-
-**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
-
-**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
-
-## Font Selection & Pairing
-
-The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
-
-### Anti-reflexes worth defending against
-
-- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
-- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
-- A children's product does NOT need a rounded display font. Kids' books use real type.
-- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
-
-**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
-
-### Pairing Principles
-
-**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
-
-When pairing, contrast on multiple axes:
-- Serif + Sans (structure contrast)
-- Geometric + Humanist (personality contrast)
-- Condensed display + Wide body (proportion contrast)
-
-**Never pair fonts that are similar but not identical** (e.g., two geometric sans-serifs). They create visual tension without clear hierarchy.
-
-### Web Font Loading
-
-The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
-
-```css
-/* 1. Use font-display: swap for visibility */
-@font-face {
- font-family: 'CustomFont';
- src: url('font.woff2') format('woff2');
- font-display: swap;
-}
-
-/* 2. Match fallback metrics to minimize shift */
-@font-face {
- font-family: 'CustomFont-Fallback';
- src: local('Arial');
- size-adjust: 105%; /* Scale to match x-height */
- ascent-override: 90%; /* Match ascender height */
- descent-override: 20%; /* Match descender depth */
- line-gap-override: 10%; /* Match line spacing */
-}
-
-body {
- font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
-}
-```
-
-Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
-
-**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
-
-**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
-
-**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
-
-## Modern Web Typography
-
-### Fluid Type
-
-Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
-
-**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
-
-**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
-
-**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
-
-**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
-
-### OpenType Features
-
-Most developers don't know these exist. Use them for polish:
-
-```css
-/* Tabular numbers for data alignment */
-.data-table { font-variant-numeric: tabular-nums; }
-
-/* Proper fractions */
-.recipe-amount { font-variant-numeric: diagonal-fractions; }
-
-/* Small caps for abbreviations */
-abbr { font-variant-caps: all-small-caps; }
-
-/* Disable ligatures in code */
-code { font-variant-ligatures: none; }
-
-/* Enable kerning (usually on by default, but be explicit) */
-body { font-kerning: normal; }
-```
-
-Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
-
-### Rendering polish
-
-```css
-/* Even out heading line lengths (browser picks better break points) */
-h1, h2, h3 { text-wrap: balance; }
-
-/* Reduce orphans and ragged endings in long prose */
-article p { text-wrap: pretty; }
-
-/* Variable fonts: pick the right optical-size master automatically */
-body { font-optical-sizing: auto; }
-```
-
-**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
-
-## Typography System Architecture
-
-Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
-
-## Accessibility Considerations
-
-Beyond contrast ratios (which are well-documented), consider:
-
-- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
-- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
-- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
-- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
-
----
-
-**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
@@ -1,107 +0,0 @@
-# UX Writing
-
-## The Button Label Problem
-
-**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
-
-| Bad | Good | Why |
-|-----|------|-----|
-| OK | Save changes | Says what will happen |
-| Submit | Create account | Outcome-focused |
-| Yes | Delete message | Confirms the action |
-| Cancel | Keep editing | Clarifies what "cancel" means |
-| Click here | Download PDF | Describes the destination |
-
-**For destructive actions**, name the destruction:
-- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
-- "Delete 5 items" not "Delete selected" (show the count)
-
-## Error Messages: The Formula
-
-Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
-
-### Error Message Templates
-
-| Situation | Template |
-|-----------|----------|
-| **Format error** | "[Field] needs to be [format]. Example: [example]" |
-| **Missing required** | "Please enter [what's missing]" |
-| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
-| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
-| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
-
-### Don't Blame the User
-
-Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
-
-## Empty States Are Opportunities
-
-Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
-
-## Voice vs Tone
-
-**Voice** is your brand's personality, consistent everywhere.
-**Tone** adapts to the moment.
-
-| Moment | Tone Shift |
-|--------|------------|
-| Success | Celebratory, brief: "Done! Your changes are live." |
-| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
-| Loading | Reassuring: "Saving your work..." |
-| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
-
-**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
-
-## Writing for Accessibility
-
-**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
-
-## Writing for Translation
-
-### Plan for Expansion
-
-German text is ~30% longer than English. Allocate space:
-
-| Language | Expansion |
-|----------|-----------|
-| German | +30% |
-| French | +20% |
-| Finnish | +30-40% |
-| Chinese | -30% (fewer chars, but same width) |
-
-### Translation-Friendly Patterns
-
-Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
-
-## Consistency: The Terminology Problem
-
-Pick one term and stick with it:
-
-| Inconsistent | Consistent |
-|--------------|------------|
-| Delete / Remove / Trash | Delete |
-| Settings / Preferences / Options | Settings |
-| Sign in / Log in / Enter | Sign in |
-| Create / Add / New | Create |
-
-Build a terminology glossary and enforce it. Variety creates confusion.
-
-## Avoid Redundant Copy
-
-If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
-
-## Loading States
-
-Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
-
-## Confirmation Dialogs: Use Sparingly
-
-Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
-
-## Form Instructions
-
-Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
-
----
-
-**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
@@ -1,284 +0,0 @@
-#!/usr/bin/env node
-/**
- * Cleans up deprecated Impeccable skill files, symlinks, and
- * skills-lock.json entries left over from previous versions.
- *
- * Safe to run repeatedly -- it is a no-op when nothing needs cleaning.
- *
- * Usage (from the project root):
- * node {{scripts_path}}/cleanup-deprecated.mjs
- *
- * What it does:
- * 1. Finds every harness-specific skills directory (.claude/skills,
- * .cursor/skills, .agents/skills, etc.).
- * 2. For each deprecated skill name (with and without i- prefix),
- * checks if the directory exists and its SKILL.md mentions
- * "impeccable" (to avoid deleting unrelated user skills).
- * 3. Deletes confirmed matches (files, directories, or symlinks).
- * 4. Removes the corresponding entries from skills-lock.json.
- */
-
-import { existsSync, readFileSync, writeFileSync, rmSync, readdirSync, statSync, lstatSync, unlinkSync } from 'node:fs';
-import { join, resolve } from 'node:path';
-
-// Skills that were renamed, merged, or folded in v2.0, v2.1, and v3.0.
-const DEPRECATED_NAMES = [
- // v2.0 renames
- 'frontend-design', // renamed to impeccable
- 'teach-impeccable', // folded into /impeccable teach
- // v2.1 merges
- 'arrange', // renamed to layout
- 'normalize', // merged into polish
- 'onboard', // merged into harden
- 'extract', // merged into /impeccable extract
- // v3.0 consolidation: all standalone skills -> /impeccable sub-commands
- 'adapt',
- 'animate',
- 'audit',
- 'bolder',
- 'clarify',
- 'colorize',
- 'critique',
- 'delight',
- 'distill',
- 'harden',
- 'layout',
- 'optimize',
- 'overdrive',
- 'polish',
- 'quieter',
- 'shape',
- 'typeset',
-];
-
-// All known harness directories that may contain a skills/ subfolder.
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Per-skill fingerprints for SKILL.md bodies that never mentioned
-// "impeccable" in their v2.x source. Used as a last-resort match
-// when no skills-lock.json exists and the word heuristic fails.
-// The strings are lifted verbatim from the v2.x frontmatter
-// descriptions, so collisions with hand-written user skills are
-// vanishingly unlikely.
-const SKILL_FINGERPRINTS = {
- harden: 'Make interfaces production-ready: error handling, empty states',
- optimize: 'Diagnoses and fixes UI performance across loading speed',
-};
-
-/**
- * Walk up from startDir until we find a directory that looks like a
- * project root (has package.json, .git, or skills-lock.json).
- */
-export function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- const { root } = { root: '/' };
- while (dir !== root) {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Load skills-lock.json from the project root, or null if missing/unreadable.
- */
-export function loadLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return null;
- try {
- return JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return null;
- }
-}
-
-/**
- * Check whether a skill directory belongs to Impeccable. Three layered
- * signals, in order of reliability:
- * 1. Lock source equals "pbakaus/impeccable" (authoritative).
- * 2. SKILL.md body contains the word "impeccable".
- * 3. SKILL.md body contains a per-skill fingerprint (for harden and
- * optimize, whose v2.x SKILL.md never mentioned the pack name).
- */
-export function isImpeccableSkill(skillDir, { skillName, lock } = {}) {
- // 1. Authoritative: the lock file claims this skill is ours.
- if (skillName && lock?.skills?.[skillName]?.source === 'pbakaus/impeccable') {
- return true;
- }
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) return false;
- let content;
- try {
- content = readFileSync(skillMd, 'utf-8');
- } catch {
- return false;
- }
- // 2. Word-level content heuristic.
- if (/impeccable/i.test(content)) return true;
- // 3. Per-skill fingerprint for old skills that never mentioned the pack.
- // Strip the i- prefix so both `harden` and `i-harden` resolve to the
- // same fingerprint entry.
- const unprefixed = skillName?.startsWith('i-') ? skillName.slice(2) : skillName;
- const fingerprint = unprefixed && SKILL_FINGERPRINTS[unprefixed];
- if (fingerprint && content.includes(fingerprint)) return true;
- return false;
-}
-
-/**
- * Build the full list of names to check: each deprecated name, plus
- * its i-prefixed variant.
- */
-export function buildTargetNames() {
- const names = [];
- for (const name of DEPRECATED_NAMES) {
- names.push(name);
- names.push(`i-${name}`);
- }
- return names;
-}
-
-/**
- * Find every skills directory across all harness dirs in the project.
- * Returns absolute paths that exist on disk.
- */
-export function findSkillsDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const candidate = join(projectRoot, harness, 'skills');
- if (existsSync(candidate)) {
- dirs.push(candidate);
- }
- }
- return dirs;
-}
-
-/**
- * Remove deprecated skill directories/symlinks from all harness dirs.
- * Reads skills-lock.json so the authoritative "source" field can
- * drive deletion even when SKILL.md never mentions impeccable.
- * Returns an array of paths that were deleted.
- */
-export function removeDeprecatedSkills(projectRoot, lock) {
- if (lock === undefined) lock = loadLock(projectRoot);
- const targets = buildTargetNames();
- const skillsDirs = findSkillsDirs(projectRoot);
- const deleted = [];
-
- for (const skillsDir of skillsDirs) {
- for (const name of targets) {
- const skillPath = join(skillsDir, name);
-
- // Use lstat to detect symlinks (existsSync follows symlinks and
- // returns false for dangling ones).
- let stat;
- try {
- stat = lstatSync(skillPath);
- } catch {
- continue; // does not exist at all
- }
-
- if (stat.isSymbolicLink()) {
- // Symlink: check the target if it's alive, otherwise treat
- // dangling symlinks to deprecated names as safe to remove.
- const targetAlive = existsSync(skillPath);
- const isMatch = targetAlive
- ? isImpeccableSkill(skillPath, { skillName: name, lock })
- : true;
- if (isMatch) {
- unlinkSync(skillPath);
- deleted.push(skillPath);
- }
- continue;
- }
-
- // Regular directory -- verify it belongs to impeccable
- if (isImpeccableSkill(skillPath, { skillName: name, lock })) {
- rmSync(skillPath, { recursive: true, force: true });
- deleted.push(skillPath);
- }
- }
- }
-
- return deleted;
-}
-
-/**
- * Remove deprecated entries from skills-lock.json.
- * Only removes entries whose source is "pbakaus/impeccable".
- * Returns the list of removed skill names.
- */
-export function cleanSkillsLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return [];
-
- let lock;
- try {
- lock = JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return [];
- }
-
- if (!lock.skills || typeof lock.skills !== 'object') return [];
-
- const targets = buildTargetNames();
- const removed = [];
-
- for (const name of targets) {
- const entry = lock.skills[name];
- if (!entry) continue;
- // Only remove if it belongs to impeccable
- if (entry.source === 'pbakaus/impeccable') {
- delete lock.skills[name];
- removed.push(name);
- }
- }
-
- if (removed.length > 0) {
- writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\n', 'utf-8');
- }
-
- return removed;
-}
-
-/**
- * Run the full cleanup. Returns a summary object.
- *
- * Order matters: read the lock and delete directories first, then
- * strip lock entries. Otherwise the authoritative signal is gone by
- * the time directory deletion runs.
- */
-export function cleanup(projectRoot) {
- const root = projectRoot || findProjectRoot();
- const lock = loadLock(root);
- const deletedPaths = removeDeprecatedSkills(root, lock);
- const removedLockEntries = cleanSkillsLock(root);
- return { deletedPaths, removedLockEntries, projectRoot: root };
-}
-
-// CLI entry point
-if (process.argv[1] && resolve(process.argv[1]) === resolve(new URL(import.meta.url).pathname)) {
- const result = cleanup();
- if (result.deletedPaths.length === 0 && result.removedLockEntries.length === 0) {
- console.log('No deprecated Impeccable skills found. Nothing to clean up.');
- } else {
- if (result.deletedPaths.length > 0) {
- console.log(`Removed ${result.deletedPaths.length} deprecated skill(s):`);
- for (const p of result.deletedPaths) console.log(` - ${p}`);
- }
- if (result.removedLockEntries.length > 0) {
- console.log(`Cleaned ${result.removedLockEntries.length} entry/entries from skills-lock.json:`);
- for (const name of result.removedLockEntries) console.log(` - ${name}`);
- }
- }
-}
@@ -1,94 +0,0 @@
-{
- "craft": {
- "description": "Full confirmed-brief-then-build flow. Runs multi-round shape discovery first, resolves visual probe and north-star mock gates when available, then builds and visually iterates. Use when building a new feature end-to-end.",
- "argumentHint": "[feature description]"
- },
- "teach": {
- "description": "Gathers design context for a project. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles) and, when code exists to analyze, DESIGN.md (visual: colors, typography, components). Every other command reads these files before doing work. Use once per project.",
- "argumentHint": ""
- },
- "document": {
- "description": "Generate a DESIGN.md file that captures the current visual design system. Auto-extracts colors, typography, spacing, radii, and component patterns from the codebase, then asks the user to confirm descriptive language for atmosphere and color character. Follows the Google Stitch DESIGN.md format so the file is tool-compatible. Use when you need a visual design spec an AI agent can follow to stay on-brand.",
- "argumentHint": ""
- },
- "extract": {
- "description": "Pull reusable patterns, components, and design tokens into the design system. Identifies repeated patterns and consolidates them. Use when you have drift across the codebase and want to bring things back to a consistent system.",
- "argumentHint": "[target]"
- },
- "live": {
- "description": "Interactive live variant mode. Select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via HMR. Requires a running dev server. Use when you want to visually experiment with design alternatives in real time.",
- "argumentHint": ""
- },
- "adapt": {
- "description": "Adapt designs to work across different screen sizes, devices, contexts, or platforms. Implements breakpoints, fluid layouts, and touch targets. Use when the user mentions responsive design, mobile layouts, breakpoints, viewport adaptation, or cross-device compatibility.",
- "argumentHint": "[target] [context (mobile, tablet, print...)]"
- },
- "animate": {
- "description": "Review a feature and enhance it with purposeful animations, micro-interactions, and motion effects that improve usability and delight. Use when the user mentions adding animation, transitions, micro-interactions, motion design, hover effects, or making the UI feel more alive.",
- "argumentHint": "[target]"
- },
- "audit": {
- "description": "Run technical quality checks across accessibility, performance, theming, responsive design, and anti-patterns. Generates a scored report with P0-P3 severity ratings and actionable plan. Use when the user wants an accessibility check, performance audit, or technical quality review.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "bolder": {
- "description": "Amplify safe or boring designs to make them more visually interesting and stimulating. Increases impact while maintaining usability. Use when the user says the design looks bland, generic, too safe, lacks personality, or wants more visual impact and character.",
- "argumentHint": "[target]"
- },
- "clarify": {
- "description": "Improve unclear UX copy, error messages, microcopy, labels, and instructions to make interfaces easier to understand. Use when the user mentions confusing text, unclear labels, bad error messages, hard-to-follow instructions, or wanting better UX writing.",
- "argumentHint": "[target]"
- },
- "colorize": {
- "description": "Add strategic color to features that are too monochromatic or lack visual interest, making interfaces more engaging and expressive. Use when the user mentions the design looking gray, dull, lacking warmth, needing more color, or wanting a more vibrant or expressive palette.",
- "argumentHint": "[target]"
- },
- "critique": {
- "description": "Evaluate design from a UX perspective, assessing visual hierarchy, information architecture, emotional resonance, cognitive load, and overall quality with quantitative scoring, persona-based testing, automated anti-pattern detection, and actionable feedback. Use when the user asks to review, critique, evaluate, or give feedback on a design or component.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "delight": {
- "description": "Add moments of joy, personality, and unexpected touches that make interfaces memorable and enjoyable to use. Elevates functional to delightful. Use when the user asks to add polish, personality, animations, micro-interactions, delight, or make an interface feel fun or memorable.",
- "argumentHint": "[target]"
- },
- "distill": {
- "description": "Strip designs to their essence by removing unnecessary complexity. Great design is simple, powerful, and clean. Use when the user asks to simplify, declutter, reduce noise, remove elements, or make a UI cleaner and more focused.",
- "argumentHint": "[target]"
- },
- "harden": {
- "description": "Make interfaces production-ready: error handling, i18n, text overflow, edge case management, and resilience under real-world data. Use when the user asks to harden, make production-ready, handle edge cases, add error states, or fix overflow and i18n issues.",
- "argumentHint": "[target]"
- },
- "onboard": {
- "description": "Design onboarding flows, first-run experiences, and empty states that guide new users to value. Covers welcome screens, account setup, progressive disclosure, contextual tooltips, feature announcements, and activation moments. Use when the user mentions onboarding, first-time users, empty states, activation, getting started, new user flows, or the aha moment.",
- "argumentHint": "[target]"
- },
- "layout": {
- "description": "Improve layout, spacing, and visual rhythm. Fixes monotonous grids, inconsistent spacing, and weak visual hierarchy. Use when the user mentions layout feeling off, spacing issues, visual hierarchy, crowded UI, alignment problems, or wanting better composition.",
- "argumentHint": "[target]"
- },
- "optimize": {
- "description": "Diagnoses and fixes UI performance across loading speed, rendering, animations, images, and bundle size. Use when the user mentions slow, laggy, janky, performance, bundle size, load time, or wants a faster, smoother experience.",
- "argumentHint": "[target]"
- },
- "overdrive": {
- "description": "Pushes interfaces past conventional limits with technically ambitious implementations — shaders, spring physics, scroll-driven reveals, 60fps animations. Use when the user wants to wow, impress, go all-out, or make something that feels extraordinary.",
- "argumentHint": "[target]"
- },
- "polish": {
- "description": "Performs a final quality pass fixing alignment, spacing, consistency, and micro-detail issues before shipping. Use when the user mentions polish, finishing touches, pre-launch review, something looks off, or wants to go from good to great.",
- "argumentHint": "[target]"
- },
- "quieter": {
- "description": "Tones down visually aggressive or overstimulating designs, reducing intensity while preserving quality. Use when the user mentions too bold, too loud, overwhelming, aggressive, garish, or wants a calmer, more refined aesthetic.",
- "argumentHint": "[target]"
- },
- "shape": {
- "description": "Plan UX and UI before code. Runs a required multi-round discovery interview, uses visual probes when available, and produces a user-confirmed design brief for implementation.",
- "argumentHint": "[feature to shape]"
- },
- "typeset": {
- "description": "Improves typography by fixing font choices, hierarchy, sizing, weight, and readability so text feels intentional. Use when the user mentions fonts, type, readability, text hierarchy, sizing looks off, or wants more polished, intentional typography.",
- "argumentHint": "[target]"
- }
-}
@@ -1,242 +0,0 @@
-#!/usr/bin/env node
-/**
- * Critique persistence helper.
- *
- * Each run of /impeccable critique writes a per-target snapshot to
- * .impeccable/critique/<timestamp>__<slug>.md
- * with a small YAML frontmatter carrying the score + P0/P1 counts.
- *
- * /impeccable polish reads the latest matching snapshot at start as its
- * fix backlog. No other skill auto-reads critique output.
- *
- * The slug is derived mechanically from the *resolved* primary artifact
- * (file path or URL), never from the user's natural-language phrasing.
- * Slug stability across runs is what lets the trend display work.
- *
- * CLI entry points (called from skill instructions):
- * node critique-storage.mjs slug <resolved-target>
- * node critique-storage.mjs write <slug> <snapshot-body-file>
- * node critique-storage.mjs latest <slug>
- * node critique-storage.mjs trend <slug> [limit]
- *
- * Note: there is intentionally no `ignore` subcommand. ignore.md is a plain
- * markdown file; the model reads it directly with its file-read tool. This
- * helper only exists for operations the model can't trivially do inline
- * (normalizing paths, generating filenames, globbing + parsing frontmatter).
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath, pathToFileURL } from 'node:url';
-import { getCritiqueDir } from './impeccable-paths.mjs';
-
-const SLUG_MAX = 50;
-
-/**
- * Mechanically derive a slug from a resolved target. Returns null if the
- * input doesn't look like a stable identifier (empty, project root, etc).
- *
- * Accepts file paths and URLs. The model resolves "the homepage" to a
- * concrete artifact before calling this — we never slug a natural-language
- * phrase.
- */
-export function slugFromTarget(resolved, { cwd = process.cwd() } = {}) {
- if (!resolved || typeof resolved !== 'string') return null;
- const trimmed = resolved.trim();
- if (!trimmed) return null;
-
- // URL
- if (/^https?:\/\//i.test(trimmed)) {
- let url;
- try { url = new URL(trimmed); } catch { return null; }
- const hostPath = `${url.hostname}${url.pathname}`;
- return kebab(hostPath);
- }
-
- // File path. Make it project-relative so two devs critiquing the same
- // checkout get the same slug regardless of where their repo is cloned.
- const abs = path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- let rel = path.relative(cwd, abs);
- // If the target is outside cwd, fall back to the basename so we still
- // produce a stable slug (vs the absolute path, which would include
- // home dirs / usernames).
- if (rel.startsWith('..') || path.isAbsolute(rel)) {
- rel = path.basename(abs);
- }
- if (!rel || rel === '.' || rel === '') return null;
- return kebab(rel);
-}
-
-function kebab(s) {
- const slug = s
- .toLowerCase()
- .replace(/[/\\.]+/g, '-')
- .replace(/[^a-z0-9-]+/g, '-')
- .replace(/-+/g, '-')
- .replace(/^-|-$/g, '');
- if (!slug) return null;
- // Cap from the tail — the tail (filename) is more identifying than the
- // top-level directory.
- return slug.length <= SLUG_MAX ? slug : slug.slice(slug.length - SLUG_MAX).replace(/^-/, '');
-}
-
-/**
- * Filename-safe UTC ISO timestamp: hyphens for separators, trailing Z.
- * Plain colons aren't allowed on Windows filesystems.
- */
-export function nowFilenameStamp(date = new Date()) {
- const iso = date.toISOString(); // 2026-05-12T18:30:00.123Z
- return iso.replace(/[:.]/g, '-').replace(/-\d+Z$/, 'Z');
-}
-
-/**
- * Write a snapshot for `slug`. `meta` carries the small structured frontmatter
- * keys read back by readTrend(). `body` is the human-readable critique
- * report (everything below the frontmatter).
- *
- * Returns the absolute path written.
- */
-export function writeSnapshot({ slug, meta, body, cwd = process.cwd(), now = new Date() }) {
- if (!slug) throw new Error('writeSnapshot requires a slug');
- const dir = getCritiqueDir(cwd);
- fs.mkdirSync(dir, { recursive: true });
- const timestamp = nowFilenameStamp(now);
- const filePath = path.join(dir, `${timestamp}__${slug}.md`);
- // Spread `meta` first so internally computed `timestamp` and `slug`
- // always win. Otherwise a caller-supplied meta blob (parsed from the
- // IMPECCABLE_CRITIQUE_META env var) could clobber them, leaving the
- // filename in disagreement with its frontmatter and corrupting trends.
- const front = serializeFrontmatter({ ...meta, timestamp, slug });
- fs.writeFileSync(filePath, `${front}\n${body.trim()}\n`, 'utf-8');
- return filePath;
-}
-
-function serializeFrontmatter(obj) {
- const lines = ['---'];
- for (const [key, value] of Object.entries(obj)) {
- if (value === undefined || value === null) continue;
- const str = typeof value === 'string' ? value : String(value);
- // Quote strings that contain : or # to keep parsing simple.
- const needsQuotes = typeof value === 'string' && /[:#]/.test(str);
- lines.push(`${key}: ${needsQuotes ? JSON.stringify(str) : str}`);
- }
- lines.push('---');
- return lines.join('\n');
-}
-
-function parseFrontmatter(text) {
- const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
- if (!match) return {};
- const out = {};
- for (const line of match[1].split(/\r?\n/)) {
- const colon = line.indexOf(':');
- if (colon < 0) continue;
- const key = line.slice(0, colon).trim();
- let value = line.slice(colon + 1).trim();
- if (/^".*"$/.test(value)) {
- try { value = JSON.parse(value); } catch { /* leave as-is */ }
- } else if (/^-?\d+$/.test(value)) {
- value = Number(value);
- }
- out[key] = value;
- }
- return out;
-}
-
-/**
- * Return all snapshot files for `slug`, sorted oldest → newest.
- */
-function listSnapshotsForSlug(slug, cwd) {
- const dir = getCritiqueDir(cwd);
- if (!fs.existsSync(dir)) return [];
- const suffix = `__${slug}.md`;
- return fs.readdirSync(dir)
- .filter((f) => f.endsWith(suffix))
- .sort()
- .map((f) => path.join(dir, f));
-}
-
-/**
- * Return the most recent snapshot for `slug`, or null. Polish reads this
- * to find its fix backlog when the slug matches.
- */
-export function readLatestSnapshot(slug, { cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- if (!all.length) return null;
- const latest = all[all.length - 1];
- const body = fs.readFileSync(latest, 'utf-8');
- return { path: latest, body, meta: parseFrontmatter(body) };
-}
-
-/**
- * Return the last `limit` snapshots' frontmatter, oldest → newest.
- * Critique appends a one-line trend to its output using this.
- */
-export function readTrend(slug, { limit = 5, cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- const slice = all.slice(-limit);
- return slice.map((file) => parseFrontmatter(fs.readFileSync(file, 'utf-8')));
-}
-
-// ---- CLI ---------------------------------------------------------------
-
-function main(argv) {
- const [cmd, ...args] = argv;
- switch (cmd) {
- case 'slug': {
- const slug = slugFromTarget(args[0]);
- if (!slug) { process.stderr.write('no stable slug for input\n'); process.exit(1); }
- process.stdout.write(`${slug}\n`);
- return;
- }
- case 'write': {
- const [slug, bodyFile] = args;
- if (!slug || !bodyFile) { process.stderr.write('usage: write <slug> <body-file>\n'); process.exit(1); }
- const raw = fs.readFileSync(bodyFile, 'utf-8');
- // The body file may be a full report. The caller passes the meta as
- // a JSON object on stdin if it wants structured frontmatter; otherwise
- // we write with minimal metadata.
- let meta = {};
- const metaArg = process.env.IMPECCABLE_CRITIQUE_META;
- if (metaArg) {
- try { meta = JSON.parse(metaArg); } catch { /* ignore */ }
- }
- const out = writeSnapshot({ slug, meta, body: raw });
- process.stdout.write(`${out}\n`);
- return;
- }
- case 'latest': {
- const latest = readLatestSnapshot(args[0]);
- if (!latest) { process.exit(2); }
- process.stdout.write(latest.body);
- return;
- }
- case 'trend': {
- const rows = readTrend(args[0], { limit: args[1] ? Number(args[1]) : 5 });
- process.stdout.write(JSON.stringify(rows, null, 2) + '\n');
- return;
- }
- default:
- process.stderr.write('usage: critique-storage.mjs <slug|write|latest|trend> [args]\n');
- process.exit(1);
- }
-}
-
-function isMainModule() {
- if (!process.argv[1]) return false;
- try {
- return fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1]);
- } catch {
- // pathToFileURL normalizes Windows paths; keep it as a fallback for any
- // environment where realpath is unavailable.
- return import.meta.url === pathToFileURL(process.argv[1]).href;
- }
-}
-
-// Why the realpath check: generated skills are often reached through symlinked
-// harness directories (for example a demo repo's `.agents` -> source `.agents`).
-// Node resolves import.meta.url to the real file, while process.argv[1] keeps
-// the symlink path. Comparing canonical paths prevents a silent exit-0 no-op.
-if (isMainModule()) {
- main(process.argv.slice(2));
-}
@@ -1,820 +0,0 @@
-// Parse a DESIGN.md (Stitch-spec format) into a structured JSON model that
-// the live-mode design-system panel can render. Deterministic, dependency-free.
-//
-// Two-layer: YAML frontmatter (machine-readable tokens) + markdown body
-// (prose with six canonical H2 sections). When frontmatter is present, it's
-// exposed on `model.frontmatter` alongside the prose-scraped sections;
-// consumers can prefer frontmatter values and fall back to prose.
-
-const CANONICAL_SECTIONS = [
- 'Overview',
- 'Colors',
- 'Typography',
- 'Elevation',
- 'Components',
- "Do's and Don'ts",
-];
-
-// ---------- Frontmatter (Stitch YAML subset) ----------
-
-function parseFrontmatter(md) {
- const lines = md.split(/\r?\n/);
- if (lines[0]?.trim() !== '---') return { frontmatter: null, body: md };
-
- let end = -1;
- for (let i = 1; i < lines.length; i++) {
- if (lines[i].trim() === '---') { end = i; break; }
- }
- if (end === -1) return { frontmatter: null, body: md };
-
- const yaml = lines.slice(1, end).join('\n');
- const body = lines.slice(end + 1).join('\n');
- try {
- return { frontmatter: parseYamlSubset(yaml), body };
- } catch {
- return { frontmatter: null, body: md };
- }
-}
-
-// Minimal YAML reader for the Stitch frontmatter subset: scalar maps with
-// one level of nested objects (typography roles, components). Indent-based,
-// 2-space convention. No arrays, no anchors, no multi-line scalars — Stitch's
-// schema doesn't need them and accepting them would require a real YAML
-// dependency we don't want to vendor.
-function parseYamlSubset(yaml) {
- const lines = yaml.split(/\r?\n/);
- const root = {};
- const stack = [{ indent: -1, obj: root }];
-
- for (const raw of lines) {
- // Skip blanks and line-only comments. Don't strip inline comments:
- // unquoted hex values start with `#` and can't be safely distinguished
- // from a comment after whitespace.
- if (!raw.trim() || /^\s*#/.test(raw)) continue;
-
- const indent = raw.match(/^\s*/)[0].length;
- const content = raw.slice(indent);
-
- const colonIdx = findTopLevelColon(content);
- if (colonIdx === -1) continue;
-
- while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
- stack.pop();
- }
-
- const key = content.slice(0, colonIdx).trim();
- const rest = content.slice(colonIdx + 1).trim();
- const parent = stack[stack.length - 1].obj;
-
- if (rest === '') {
- const obj = {};
- parent[key] = obj;
- stack.push({ indent, obj });
- } else {
- parent[key] = parseScalar(rest);
- }
- }
-
- return root;
-}
-
-function findTopLevelColon(s) {
- let inQuote = null;
- for (let i = 0; i < s.length; i++) {
- const ch = s[i];
- if (inQuote) {
- if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
- } else if (ch === '"' || ch === "'") {
- inQuote = ch;
- } else if (ch === ':') {
- return i;
- }
- }
- return -1;
-}
-
-function parseScalar(raw) {
- const s = raw.trim();
- if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
- return s.slice(1, -1);
- }
- if (s === 'true') return true;
- if (s === 'false') return false;
- if (s === 'null' || s === '~') return null;
- if (/^-?\d+$/.test(s)) return Number(s);
- if (/^-?\d*\.\d+$/.test(s)) return Number(s);
- return s;
-}
-
-const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
-const OKLCH_RE = /oklch\([^)]+\)/gi;
-const RGBA_RE = /rgba?\([^)]+\)/gi;
-const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
-const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
-
-// ---------- Section splitting ----------
-
-function splitSections(md) {
- const lines = md.split(/\r?\n/);
- let title = null;
- const sections = {};
- let current = null;
-
- for (const raw of lines) {
- const line = raw.trimEnd();
-
- if (!title && line.startsWith('# ') && !line.startsWith('## ')) {
- title = line.replace(/^#\s+/, '').trim();
- continue;
- }
-
- const h2 = line.match(/^##\s+(?:\d+\.\s*)?([^:\n]+?)(?::\s*(.+))?$/);
- if (h2) {
- const rawName = normalizeApostrophes(h2[1].trim());
- const subtitle = h2[2] ? h2[2].trim() : null;
- const canonical = matchCanonicalSection(rawName);
- if (canonical) {
- current = { name: canonical, subtitle, lines: [] };
- sections[canonical] = current;
- continue;
- }
- // non-canonical H2 — ignore but stop feeding into current
- current = null;
- continue;
- }
-
- if (current) current.lines.push(raw);
- }
-
- return { title, sections };
-}
-
-function normalizeApostrophes(s) {
- return s.replace(/[\u2018\u2019]/g, "'");
-}
-
-function matchCanonicalSection(name) {
- const normalized = normalizeApostrophes(name).toLowerCase();
- // Exact match first
- for (const c of CANONICAL_SECTIONS) {
- if (normalizeApostrophes(c).toLowerCase() === normalized) return c;
- }
- // Keyword-contained match: "Overview & Creative North Star" -> "Overview",
- // "Elevation & Depth" -> "Elevation", etc.
- for (const c of CANONICAL_SECTIONS) {
- const key = normalizeApostrophes(c).toLowerCase();
- const pattern = new RegExp(`\\b${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
- if (pattern.test(normalized)) return c;
- }
- return null;
-}
-
-// ---------- Subsection splitting (inside a canonical section) ----------
-
-function splitSubsections(lines) {
- const subs = [];
- let current = { name: null, lines: [] };
- subs.push(current);
-
- for (const raw of lines) {
- const h3 = raw.match(/^###\s+(.+?)\s*$/);
- if (h3) {
- current = { name: h3[1].trim(), lines: [] };
- subs.push(current);
- continue;
- }
- current.lines.push(raw);
- }
-
- return subs;
-}
-
-// ---------- Generic helpers ----------
-
-function collectParagraphs(lines) {
- const paragraphs = [];
- let buf = [];
- const flush = () => {
- if (buf.length) {
- paragraphs.push(buf.join(' ').trim());
- buf = [];
- }
- };
- for (const raw of lines) {
- const trimmed = raw.trim();
- if (trimmed === '') { flush(); continue; }
- // Horizontal rules (---, ***) and headings/bullets end a paragraph.
- if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { flush(); continue; }
- if (raw.startsWith('#') || raw.match(/^[-*]\s/)) { flush(); continue; }
- buf.push(trimmed);
- }
- flush();
- return paragraphs.filter(Boolean);
-}
-
-function collectBullets(lines) {
- const bullets = [];
- let current = null;
- for (const raw of lines) {
- const m = raw.match(/^\s*[-*]\s+(.+)$/);
- if (m) {
- if (current) bullets.push(current);
- current = m[1];
- continue;
- }
- // continuation of a bullet (indented line)
- if (current && raw.match(/^\s{2,}\S/)) {
- current += ' ' + raw.trim();
- continue;
- }
- // blank line ends a bullet
- if (raw.trim() === '' && current) {
- bullets.push(current);
- current = null;
- }
- }
- if (current) bullets.push(current);
- return bullets;
-}
-
-function stripBold(s) {
- return s.replace(/\*\*(.+?)\*\*/g, '$1');
-}
-
-function extractNamedRules(lines) {
- const rules = [];
- const seen = new Set();
-
- // Style A (Impeccable): "**The X Rule.** body body body" — can span lines.
- const joined = lines.join('\n');
- const inlineStart = /\*\*(The [^*]+?Rule)\.\*\*/g;
- const inlineMatches = [];
- let m;
- while ((m = inlineStart.exec(joined)) !== null) {
- inlineMatches.push({ name: m[1], start: m.index, end: inlineStart.lastIndex });
- }
- for (let i = 0; i < inlineMatches.length; i++) {
- const mm = inlineMatches[i];
- const bodyEnd = i + 1 < inlineMatches.length ? inlineMatches[i + 1].start : joined.length;
- const body = joined
- .slice(mm.end, bodyEnd)
- .replace(/\n##[^\n]*$/s, '')
- .replace(/\n###[^\n]*$/s, '')
- .trim();
- const name = stripBold(mm.name).trim();
- seen.add(name.toLowerCase());
- rules.push({ name, body: stripBold(body) });
- }
-
- // Style B (Stitch): `### The "X" Rule` or `### The X Fallback`, body is the
- // bullets/paragraphs until the next heading. Accept Rule / Fallback / Principle.
- for (let i = 0; i < lines.length; i++) {
- const h3 = lines[i].match(/^###\s+(.+?)\s*$/);
- if (!h3) continue;
- const headerName = stripBold(h3[1]).replace(/["“”]/g, '').trim();
- if (!/^The\b.*\b(Rule|Fallback|Principle)\b/i.test(headerName)) continue;
- if (seen.has(headerName.toLowerCase())) continue;
-
- const bodyLines = [];
- for (let j = i + 1; j < lines.length; j++) {
- if (/^##\s|^###\s/.test(lines[j])) break;
- bodyLines.push(lines[j]);
- }
- const body = stripBold(bodyLines.join('\n').replace(/\n+/g, ' ')).trim();
- if (body) {
- seen.add(headerName.toLowerCase());
- rules.push({ name: headerName, body });
- }
- }
-
- // Style C (Stitch bullet form): "* **The Layering Principle:** body"
- // Colon/period lives inside the bold, so match "**...**" then inspect.
- for (const b of collectBullets(lines)) {
- const mm = b.match(/^\*\*([^*]+?)\*\*\s*(.+)$/);
- if (!mm) continue;
- const nameRaw = mm[1].replace(/[.:]\s*$/, '').replace(/["“”]/g, '').trim();
- if (!/^The\b.+\b(Rule|Fallback|Principle)$/i.test(nameRaw)) continue;
- if (seen.has(nameRaw.toLowerCase())) continue;
- seen.add(nameRaw.toLowerCase());
- rules.push({ name: nameRaw, body: stripBold(mm[2]).trim() });
- }
-
- return rules;
-}
-
-// ---------- Per-section extractors ----------
-
-function extractOverview(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
- const northStar = text.match(/\*\*Creative North Star:\s*"([^"]+)"\*\*/);
- const keyChars = [];
- const keyCharMatch = text.match(/\*\*Key Characteristics:\*\*\s*\n([\s\S]+?)(?:\n##|\n###|$)/);
- if (keyCharMatch) {
- for (const line of keyCharMatch[1].split('\n')) {
- const m = line.match(/^\s*[-*]\s+(.+)$/);
- if (m) keyChars.push(stripBold(m[1].trim()));
- }
- }
-
- // Philosophy paragraphs: everything that isn't a rule header or key-char block
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) =>
- !p.startsWith('**Creative North Star') &&
- !p.startsWith('**Key Characteristics')
- );
-
- return {
- subtitle: section.subtitle,
- creativeNorthStar: northStar ? northStar[1] : null,
- philosophy: paragraphs,
- keyCharacteristics: keyChars,
- };
-}
-
-function extractColors(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ');
- const groups = [];
- const ROLE_KEYWORDS = /^(primary|secondary|tertiary|neutral|accent)\b/i;
-
- for (const sub of subs.slice(1)) {
- if (!sub.name || /Named Rules?/i.test(sub.name) || /^The\s/i.test(sub.name)) continue;
-
- const bullets = collectBullets(sub.lines);
- const parsed = bullets.map((b) => parseColorBullet(b)).filter(Boolean);
- if (parsed.length === 0) continue;
-
- // If every bullet starts with a role keyword (Primary/Secondary/...), promote
- // each bullet to its own group. Otherwise keep the subsection as the group.
- const allRoleBullets =
- parsed.length > 0 && parsed.every((p) => p.name && ROLE_KEYWORDS.test(p.name));
-
- if (allRoleBullets) {
- for (const p of parsed) {
- groups.push({ role: p.name, colors: [p] });
- }
- } else {
- groups.push({ role: sub.name, colors: parsed });
- }
- }
-
- // If the Colors section has no subsections at all (unlikely), fall back to
- // scanning the whole section as a flat bullet list.
- if (groups.length === 0) {
- const flat = collectBullets(section.lines)
- .map((b) => parseColorBullet(b))
- .filter(Boolean);
- if (flat.length) {
- for (const p of flat) {
- if (p.name && ROLE_KEYWORDS.test(p.name)) {
- groups.push({ role: p.name, colors: [p] });
- } else {
- const fallback = groups.find((g) => g.role === 'Palette');
- if (fallback) fallback.colors.push(p);
- else groups.push({ role: 'Palette', colors: [p] });
- }
- }
- }
- }
-
- return {
- subtitle: section.subtitle,
- description: description || null,
- groups,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function parseColorBullet(bullet) {
- const text = bullet.trim();
-
- // Case 1 (Impeccable): **Name** (value-with-maybe-nested-parens): description
- const bold = text.match(/^\*\*(.+?)\*\*\s*(.*)$/);
- if (bold && bold[2].startsWith('(')) {
- const value = extractParenGroup(bold[2]);
- if (value !== null) {
- const after = bold[2].slice(value.length + 2).trimStart();
- if (after.startsWith(':')) {
- return buildColor(bold[1], value, after.slice(1).trim());
- }
- }
- }
-
- // Case 2 (Stitch): **Name (values):** description — value embedded in bold.
- const stitch = text.match(/^\*\*([^*]+?)\s*\(([^)]+)\):\*\*\s*(.*)$/);
- if (stitch) {
- return buildColor(stitch[1].trim(), stitch[2], stitch[3]);
- }
-
- // Case 3: bullet without bold, just hex/oklch inside.
- const values = collectColorValues(text);
- if (values.length) {
- return buildColor(null, values.join(' to '), text);
- }
- return null;
-}
-
-function extractParenGroup(s) {
- if (s[0] !== '(') return null;
- let depth = 0;
- for (let i = 0; i < s.length; i++) {
- if (s[i] === '(') depth++;
- else if (s[i] === ')') {
- depth--;
- if (depth === 0) return s.slice(1, i);
- }
- }
- return null;
-}
-
-function buildColor(name, rawValue, description) {
- const values = collectColorValues(rawValue);
- const primary = values[0] ?? rawValue.trim();
- return {
- name: name ? stripBold(name).trim() : null,
- value: primary,
- valueRange: values.length > 1 ? values : null,
- format: detectFormat(primary),
- description: stripBold(description || '').trim() || null,
- };
-}
-
-function collectColorValues(s) {
- const out = [];
- s.replace(HEX_RE, (v) => {
- out.push(v);
- return v;
- });
- s.replace(OKLCH_RE, (v) => {
- out.push(v);
- return v;
- });
- return out;
-}
-
-function detectFormat(v) {
- if (!v) return 'unknown';
- if (v.startsWith('#')) return 'hex';
- if (/^oklch/i.test(v)) return 'oklch';
- if (/^rgb/i.test(v)) return 'rgb';
- return 'unknown';
-}
-
-function scanInlineColors(lines) {
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '');
- const color = parseColorBullet(trimmed);
- if (color) out.push(color);
- }
- return out;
-}
-
-function parseStitchInlineGroups(lines) {
- // Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
- // Each bullet IS its own role. Group them under the spoken role name.
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
- const m = trimmed.match(
- /^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
- );
- if (m) {
- const role = m[1];
- const color = buildColor(role, m[2], m[3]);
- out.push({ role, colors: [color] });
- }
- }
- return out;
-}
-
-function extractTypography(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
-
- const fonts = {};
- // Pattern A: **Display Font:** Family (with fallback)
- const fontLineRe = /\*\*([\w\s/]+?)Font:\*\*\s*([^\n(]+?)(?:\s*\(with\s+([^)]+)\))?\s*$/gm;
- let fm;
- while ((fm = fontLineRe.exec(text)) !== null) {
- const rawRole = fm[1].trim().toLowerCase().replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || 'display';
- fonts[role] = {
- family: fm[2].trim(),
- fallback: fm[3] ? fm[3].trim() : null,
- };
- }
-
- // Pattern B (Stitch): * **Display & Headlines (Noto Serif):** description
- if (Object.keys(fonts).length === 0) {
- const stitchRe = /\*\*([\w\s&/]+?)\s*\(([^)]+)\):\*\*\s*(.+)/g;
- let sm;
- while ((sm = stitchRe.exec(text)) !== null) {
- const rawRole = sm[1]
- .trim()
- .toLowerCase()
- .replace(/\s*&\s*/g, '-')
- .replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || rawRole;
- fonts[role] = { family: sm[2].trim(), fallback: null, purpose: sm[3].trim() };
- }
- }
-
- // Character paragraph — either a **Character:** label, or fall back to the
- // first free paragraph under the section header (Stitch style).
- const characterMatch = text.match(/\*\*Character:\*\*\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\n|\n###|\n##|$)/);
- let character = characterMatch ? characterMatch[1].replace(/\n/g, ' ').trim() : null;
- if (!character) {
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) => !/^\*\*[\w\s/&]+Font/i.test(p) && !/^\*\*[\w\s/&]+\([^)]+\)/.test(p)
- );
- if (paragraphs.length) character = paragraphs[0];
- }
-
- // Hierarchy bullets under ### Hierarchy
- const subs = splitSubsections(section.lines);
- let hierarchy = [];
- const hierSub = subs.find((s) => s.name && /hierarch/i.test(s.name));
- if (hierSub) {
- const bullets = collectBullets(hierSub.lines);
- hierarchy = bullets.map(parseTypeBullet).filter(Boolean);
- }
-
- return {
- subtitle: section.subtitle,
- fonts,
- character,
- hierarchy,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function normalizeFontRole(raw) {
- // Canonical roles the panel cares about: display, body, label, mono.
- // Stitch often writes compound roles like "display-&-headlines" or "ui-&-body"
- // — collapse them to the first canonical role present.
- const tokens = raw.split(/[-/&\s]+/).filter(Boolean);
- const priority = ['display', 'headline', 'body', 'ui', 'label', 'mono'];
- const canonical = { headline: 'display', ui: 'body' };
- for (const p of priority) {
- if (tokens.includes(p)) return canonical[p] || p;
- }
- return null;
-}
-
-function parseTypeBullet(bullet) {
- // - **Display** (family, weight 300, italic, clamp(...), line-height 1): purpose
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(([^)]+)\):\s*(.*)$/);
- if (!m) return null;
- const name = m[1].trim();
- const specs = m[2].split(',').map((s) => s.trim());
- return {
- name,
- specs,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractElevation(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ') || null;
-
- const shadows = [];
- const seen = new Set();
- const dedupe = (entry) => {
- const key = (entry.name || '') + '::' + entry.value;
- if (seen.has(key)) return;
- seen.add(key);
- shadows.push(entry);
- };
-
- for (const b of collectBullets(section.lines)) {
- const parsed = parseShadowBullet(b);
- if (parsed) dedupe(parsed);
- }
-
- // Fallback: extract shadows written inline in prose. Stitch style is
- // "...use an extra-diffused shadow: `box-shadow: 0 12px 40px rgba(...)`."
- for (const p of collectParagraphs(section.lines)) {
- for (const inline of extractInlineShadows(p)) dedupe(inline);
- }
- for (const b of collectBullets(section.lines)) {
- for (const inline of extractInlineShadows(b)) dedupe(inline);
- }
-
- return {
- subtitle: section.subtitle,
- description,
- shadows,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function extractInlineShadows(text) {
- // Find `box-shadow: ...` anywhere in prose and capture the value. Work on the
- // raw string so it handles both backtick-fenced and unfenced variants.
- const out = [];
- const re = /box-shadow\s*:\s*([^`;\n]+)/gi;
- let m;
- while ((m = re.exec(text)) !== null) {
- const value = m[1].replace(/[`.)]+$/, '').trim();
- if (!value) continue;
- // Name heuristic: the noun immediately before the shadow phrase.
- // e.g. "an extra-diffused shadow: ..." -> "extra-diffused shadow"
- const before = text.slice(0, m.index);
- const nameMatch = before.match(/\b([A-Za-z][A-Za-z\- ]{2,40})\s+shadow\b[^A-Za-z0-9]*$/i);
- let name = null;
- if (nameMatch) {
- const stripped = nameMatch[1]
- .replace(/^(?:use|using|apply|applying|is|are|looks? like)\s+/i, '')
- .replace(/^(?:a|an|the)\s+/i, '')
- .trim();
- if (stripped) {
- name =
- stripped.charAt(0).toUpperCase() + stripped.slice(1) + ' shadow';
- }
- }
- out.push({
- name,
- value,
- purpose: null,
- });
- }
- return out;
-}
-
-function parseShadowBullet(bullet) {
- // - **Name** (`box-shadow: value`): purpose
- // - **Name** (`value`): purpose
- // Only accept if the paren content looks like a shadow value (contains px,
- // rem, rgba, or box-shadow). This filters out `**Rule Name:**` bullets.
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(`?([^`]+?)`?\):\s*(.*)$/);
- if (!m) return null;
- const rawValue = m[2].replace(/^box-shadow:\s*/i, '').trim();
- const looksLikeShadow =
- /box-shadow|rgba?\(|\bpx\b|\brem\b|^-?\d+\s/i.test(rawValue) &&
- /\d/.test(rawValue);
- if (!looksLikeShadow) return null;
- const name = stripBold(m[1]).trim();
- return {
- name,
- value: rawValue,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractComponents(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const components = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
-
- const bullets = collectBullets(sub.lines);
- const paragraphs = collectParagraphs(sub.lines);
-
- const variants = [];
- const properties = {};
-
- for (const b of bullets) {
- // - **Key:** value
- const m = b.match(/^\*\*(.+?):?\*\*:?\s*(.+)$/);
- if (m) {
- const key = stripBold(m[1]).trim();
- const value = stripBold(m[2]).trim();
- // Heuristic: "Primary", "Secondary", "Hover", "Focus" etc are variants;
- // "Shape", "Background", "Padding" are properties.
- if (/^(primary|secondary|tertiary|ghost|hover|focus|active|disabled|default|error|selected|unselected|state)$/i.test(key.split(/[\s/]/)[0])) {
- variants.push({ name: key, description: value });
- } else {
- properties[key.toLowerCase()] = value;
- }
- }
- }
-
- components.push({
- name: sub.name,
- description: paragraphs.join(' ') || null,
- properties,
- variants,
- });
- }
-
- return {
- subtitle: section.subtitle,
- components,
- };
-}
-
-function extractDosDonts(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const dos = [];
- const donts = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
- const subName = normalizeApostrophes(sub.name);
- const bullets = collectBullets(sub.lines).map((b) => stripBold(b).trim());
- if (/^do'?t?:?$/i.test(subName) || /^do:?$/i.test(subName)) {
- dos.push(...bullets);
- } else if (/^don'?t:?$/i.test(subName)) {
- donts.push(...bullets);
- }
- }
-
- // Classify by bullet prefix as a backup (catches loose bullets outside H3 wrappers)
- for (const b of collectBullets(section.lines)) {
- const stripped = normalizeApostrophes(stripBold(b).trim());
- if (/^don'?t\b/i.test(stripped)) {
- if (!donts.some((d) => normalizeApostrophes(d) === stripped)) donts.push(stripped);
- } else if (/^do\b/i.test(stripped)) {
- if (!dos.some((d) => normalizeApostrophes(d) === stripped)) dos.push(stripped);
- }
- }
-
- return { dos, donts };
-}
-
-// ---------- Coverage assessment ----------
-
-function assessCoverage(model) {
- const report = {};
-
- report.overview = model.overview
- ? {
- northStar: Boolean(model.overview.creativeNorthStar),
- philosophy: model.overview.philosophy.length > 0,
- keyCharacteristics: model.overview.keyCharacteristics.length,
- }
- : 'missing';
-
- report.colors = model.colors
- ? {
- groups: model.colors.groups.length,
- totalColors: model.colors.groups.reduce((n, g) => n + g.colors.length, 0),
- rules: model.colors.rules.length,
- }
- : 'missing';
-
- report.typography = model.typography
- ? {
- fonts: Object.keys(model.typography.fonts).length,
- hierarchyEntries: model.typography.hierarchy.length,
- character: Boolean(model.typography.character),
- rules: model.typography.rules.length,
- }
- : 'missing';
-
- report.elevation = model.elevation
- ? {
- shadows: model.elevation.shadows.length,
- rules: model.elevation.rules.length,
- description: Boolean(model.elevation.description),
- }
- : 'missing';
-
- report.components = model.components
- ? {
- count: model.components.components.length,
- variantTotal: model.components.components.reduce((n, c) => n + c.variants.length, 0),
- }
- : 'missing';
-
- report.dosDonts = model.dosDonts
- ? {
- dos: model.dosDonts.dos.length,
- donts: model.dosDonts.donts.length,
- }
- : 'missing';
-
- return report;
-}
-
-// ---------- Main ----------
-
-export function parseDesignMd(md) {
- const { frontmatter, body } = parseFrontmatter(md);
- const { title, sections } = splitSections(body);
- return {
- schemaVersion: 2,
- title,
- frontmatter,
- overview: extractOverview(sections['Overview']),
- colors: extractColors(sections['Colors']),
- typography: extractTypography(sections['Typography']),
- elevation: extractElevation(sections['Elevation']),
- components: extractComponents(sections['Components']),
- dosDonts: extractDosDonts(sections["Do's and Don'ts"]),
- };
-}
-
-export { assessCoverage };
@@ -1,198 +0,0 @@
-/**
- * Scan a project tree for Content-Security-Policy signals and classify the
- * shape so the agent knows which patch template to propose.
- *
- * Used at first-time `live.mjs` setup. Mechanical (grep-based) — no network,
- * no dev server, no JS evaluation. The classification drives a user-facing
- * consent prompt; the agent does the actual patch writing.
- *
- * Shapes are named by patch mechanism, not framework origin:
- * - "append-arrays": CSP defined as structured directive arrays. Patch
- * appends a dev-only localhost entry. Covers:
- * - Monorepo helpers with additional*Src options
- * (e.g. createBaseNextConfig for Next)
- * - SvelteKit kit.csp.directives
- * - nuxt-security module's contentSecurityPolicy
- * - "append-string": CSP built as a literal value string. Patch splices
- * a dev-only token into script-src and connect-src.
- * Covers:
- * - Inline Next.js headers() with CSP string
- * - Nuxt routeRules / nitro.routeRules CSP headers
- * - "middleware": CSP set dynamically in middleware.{ts,js}.
- * Detected but not auto-patched in v1.
- * - "meta-tag": <meta http-equiv="Content-Security-Policy"> in
- * layout files. Detected but not auto-patched in v1.
- * - null: no CSP signals found; no patch needed.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const SKIP_DIRS = new Set([
- 'node_modules',
- '.git',
- '.next',
- '.turbo',
- '.svelte-kit',
- '.nuxt',
- '.astro',
- 'dist',
- 'build',
- 'out',
- '.vercel',
-]);
-
-const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.tsx', '.jsx']);
-const LAYOUT_EXTS = new Set(['.tsx', '.jsx', '.astro', '.vue', '.svelte', '.html']);
-const MAX_DEPTH = 6;
-const MAX_READ_BYTES = 64 * 1024;
-
-// append-arrays signals: CSP expressed as structured directive arrays
-const MONOREPO_HELPER_SIGNALS = [
- /\bbuildCSPConfig\b/,
- /\bbuildSecurityHeaders\b/,
- /\badditionalScriptSrc\b/,
- /\badditionalConnectSrc\b/,
- /\bcreateBaseNextConfig\b/,
-];
-const SVELTEKIT_CSP_SIGNALS = [
- /\bkit\s*:/,
- /\bcsp\s*:/,
- /\bdirectives\s*:/,
-];
-const NUXT_SECURITY_SIGNALS = [
- /['"]nuxt-security['"]/,
- /\bcontentSecurityPolicy\b/,
-];
-
-// append-string signals: CSP written as a literal value string
-const INLINE_HEADER_SIGNALS = [
- /["']Content-Security-Policy["']/i,
- /\bscript-src\b/,
- /\bconnect-src\b/,
-];
-const NUXT_ROUTE_RULES_SIGNALS = [
- /\brouteRules\b/,
- /Content-Security-Policy/i,
- /\bscript-src\b/,
-];
-
-const MIDDLEWARE_HINT = /headers\.set\(\s*["']Content-Security-Policy["']/i;
-const META_TAG_HINT = /http-equiv\s*=\s*["']Content-Security-Policy["']/i;
-
-/**
- * @param {string} cwd Project root.
- * @returns {{ shape: string|null, signals: string[] }}
- */
-export function detectCsp(cwd = process.cwd()) {
- const hits = { appendArrays: [], appendString: [], middleware: [], metaTag: [] };
-
- walk(cwd, cwd, 0, (absPath, relPath, body) => {
- const ext = path.extname(absPath);
- const base = path.basename(absPath).toLowerCase();
- const isConfig = (name) =>
- new RegExp('(^|/)' + name + '\\.config\\.').test(relPath);
-
- // === append-arrays candidates ===
-
- // Monorepo CSP helper: packages/*/src/.../(config|security)/*
- if (SCAN_EXTS.has(ext) &&
- /packages\/[^/]+\/src\/.*(config|next-config|security)/.test(relPath) &&
- MONOREPO_HELPER_SIGNALS.some((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // SvelteKit kit.csp.directives
- if (SCAN_EXTS.has(ext) && isConfig('svelte') &&
- SVELTEKIT_CSP_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // Nuxt nuxt-security module
- if (SCAN_EXTS.has(ext) && isConfig('nuxt') &&
- NUXT_SECURITY_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // === append-string candidates ===
-
- // Inline headers in Next/Nuxt/SvelteKit/Astro/Vite config
- if (SCAN_EXTS.has(ext) &&
- /(^|\/)(next|nuxt|vite|astro|svelte)\.config\./.test(relPath) &&
- INLINE_HEADER_SIGNALS.every((re) => re.test(body))) {
- // Nuxt routeRules is a sub-shape of append-string; we already covered
- // nuxt-security above via return, so any remaining Nuxt CSP match here
- // is a route-rules / inline-headers case. Either way, same patch
- // mechanism.
- hits.appendString.push(relPath);
- return;
- }
-
- // === detect-only shapes ===
-
- if ((base === 'middleware.ts' || base === 'middleware.js' || base === 'middleware.mjs') &&
- MIDDLEWARE_HINT.test(body)) {
- hits.middleware.push(relPath);
- }
-
- if (LAYOUT_EXTS.has(ext) && META_TAG_HINT.test(body)) {
- hits.metaTag.push(relPath);
- }
- });
-
- // Priority: append-arrays > append-string > middleware > meta-tag.
- // Structured patches are safer than string splices; runtime and HTML
- // injection patches are less reliable and v1 doesn't auto-apply them.
- if (hits.appendArrays.length > 0) {
- return { shape: 'append-arrays', signals: hits.appendArrays };
- }
- if (hits.appendString.length > 0) {
- return { shape: 'append-string', signals: hits.appendString };
- }
- if (hits.middleware.length > 0) {
- return { shape: 'middleware', signals: hits.middleware };
- }
- if (hits.metaTag.length > 0) {
- return { shape: 'meta-tag', signals: hits.metaTag };
- }
- return { shape: null, signals: [] };
-}
-
-function walk(root, dir, depth, visit) {
- if (depth > MAX_DEPTH) return;
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
-
- for (const entry of entries) {
- const abs = path.join(dir, entry.name);
- if (entry.isDirectory()) {
- if (SKIP_DIRS.has(entry.name)) continue;
- walk(root, abs, depth + 1, visit);
- continue;
- }
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name);
- if (!SCAN_EXTS.has(ext) && !LAYOUT_EXTS.has(ext)) continue;
- let body;
- try {
- const fd = fs.openSync(abs, 'r');
- try {
- const buf = Buffer.alloc(MAX_READ_BYTES);
- const n = fs.readSync(fd, buf, 0, MAX_READ_BYTES, 0);
- body = buf.slice(0, n).toString('utf-8');
- } finally { fs.closeSync(fd); }
- } catch { continue; }
- visit(abs, path.relative(root, abs), body);
- }
-}
-
-// CLI mode
-const _running = process.argv[1];
-if (_running?.endsWith('detect-csp.mjs') || _running?.endsWith('detect-csp.mjs/')) {
- const result = detectCsp(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
@@ -1,21 +0,0 @@
-#!/usr/bin/env node
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { pathToFileURL, fileURLToPath } from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const candidates = [
- path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
-];
-const detectorPath = candidates.find(p => fs.existsSync(p));
-
-if (!detectorPath) {
- process.stderr.write('Error: bundled detector not found.\n');
- process.exit(1);
-}
-
-const { detectCli } = await import(pathToFileURL(detectorPath));
-
-await detectCli();
@@ -1,1688 +0,0 @@
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
@@ -1,232 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
-import { detectHtml } from '../engines/static-html/detect-html.mjs';
-import { detectText } from '../engines/regex/detect-text.mjs';
-import {
- HTML_EXTENSIONS,
- buildImportGraph,
- detectFrameworkConfig,
- isPortListening,
- walkDir,
-} from '../node/file-system.mjs';
-
-// ---------------------------------------------------------------------------
-// Output formatting
-// ---------------------------------------------------------------------------
-
-function formatFindings(findings, jsonMode) {
- if (jsonMode) return JSON.stringify(findings, null, 2);
-
- const grouped = {};
- for (const f of findings) {
- if (!grouped[f.file]) grouped[f.file] = [];
- grouped[f.file].push(f);
- }
- const out = [];
- for (const [file, items] of Object.entries(grouped)) {
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
- out.push(`\n${file}${importNote}`);
- for (const item of items) {
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
- out.push(` → ${item.description}`);
- }
- }
- out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
- return out.join('\n');
-}
-
-// ---------------------------------------------------------------------------
-// Stdin handling
-// ---------------------------------------------------------------------------
-
-async function handleStdin() {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- const input = Buffer.concat(chunks).toString('utf-8');
- try {
- const parsed = JSON.parse(input);
- const fp = parsed?.tool_input?.file_path;
- if (fp && fs.existsSync(fp)) {
- return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
- ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
- }
- } catch { /* not JSON */ }
- return detectText(input, '<stdin>');
-}
-
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-async function confirm(question) {
- const rl = (await import('node:readline')).default.createInterface({
- input: process.stdin, output: process.stderr,
- });
- return new Promise((resolve) => {
- rl.question(`${question} [Y/n] `, (answer) => {
- rl.close();
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
- });
- });
-}
-
-function printUsage() {
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
-
-Scan files or URLs for UI anti-patterns and design quality issues.
-
-Options:
- --fast Regex-only mode (skip static HTML/CSS analysis, faster but misses linked stylesheets)
- --json Output results as JSON
- --help Show this help message
-
-Detection modes:
- HTML files Static HTML/CSS analysis (default, catches linked CSS)
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
- URLs Puppeteer full browser rendering (auto-detected)
- --fast Forces regex for all files
-
-Examples:
- impeccable detect src/
- impeccable detect index.html
- impeccable detect https://example.com
- impeccable detect --fast --json .`);
-}
-
-async function detectCli() {
- let args = process.argv.slice(2).map(arg => {
- if (arg === '-json') return '--json';
- if (arg === '-fast') return '--fast';
- return arg;
- });
- if (args[0] === 'detect') args = args.slice(1);
- const jsonMode = args.includes('--json');
- const helpMode = args.includes('--help');
- const fastMode = args.includes('--fast');
- const targets = args.filter(a => !a.startsWith('--'));
-
- if (helpMode) { printUsage(); process.exit(0); }
-
- let allFindings = [];
-
- if (!process.stdin.isTTY && targets.length === 0) {
- allFindings = await handleStdin();
- } else {
- const paths = targets.length > 0 ? targets : [process.cwd()];
- const urlTargetCount = paths.filter(target => /^https?:\/\//i.test(target)).length;
- const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
-
- try {
- for (const target of paths) {
- if (/^https?:\/\//i.test(target)) {
- try {
- const scanner = browserDetector
- ? (url) => browserDetector.detectUrl(url)
- : (url) => detectUrl(url);
- allFindings.push(...await scanner(target));
- } catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
- continue;
- }
-
- const resolved = path.resolve(target);
- let stat;
- try { stat = fs.statSync(resolved); }
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
-
- if (stat.isDirectory()) {
- // Check for framework dev server config (skip in JSON mode to avoid polluting output)
- if (!jsonMode) {
- const fwConfig = detectFrameworkConfig(resolved);
- if (fwConfig) {
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
- if (probe.listening && probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
- `For more accurate results, scan the running site:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- } else if (probe.listening && !probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
- );
- } else {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Start the dev server and scan via URL for best results:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- }
- }
- }
-
- const files = walkDir(resolved);
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
-
- // Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
- if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
- process.stderr.write(
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
- `Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
- `Use --fast to skip static HTML/CSS analysis, or target a specific subdirectory.\n`
- );
- const ok = await confirm('Continue?');
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
- }
-
- // Build import graph for multi-file awareness
- const graph = buildImportGraph(files);
- // Build reverse map: file -> set of files that import it
- const importedByMap = new Map();
- for (const [importer, imports] of graph) {
- for (const imported of imports) {
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
- importedByMap.get(imported).add(importer);
- }
- }
-
- for (const file of files) {
- const ext = path.extname(file).toLowerCase();
- let fileFindings;
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- fileFindings = await detectHtml(file);
- } else {
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
- }
- // Annotate findings with import context
- const importers = importedByMap.get(file);
- if (importers && importers.size > 0) {
- const importerNames = [...importers].map(f => path.basename(f));
- for (const f of fileFindings) {
- f.importedBy = importerNames;
- }
- }
- allFindings.push(...fileFindings);
- }
- } else if (stat.isFile()) {
- const ext = path.extname(resolved).toLowerCase();
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- allFindings.push(...await detectHtml(resolved));
- } else {
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
- }
- }
- }
- } finally {
- if (browserDetector) await browserDetector.close();
- }
- }
-
- if (allFindings.length > 0) {
- if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
- else process.stderr.write(formatFindings(allFindings, false) + '\n');
- process.exit(2);
- }
- if (jsonMode) process.stdout.write('[]\n');
- process.exit(0);
-}
-
-export { formatFindings, handleStdin, confirm, printUsage, detectCli };
@@ -1,4030 +0,0 @@
-/**
- * Anti-Pattern Browser Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * GENERATED -- do not edit. Source: cli/engine/browser/injected/index.mjs
- * Rebuild: node scripts/build-browser-detector.js
- *
- * Usage: <script src="detect-antipatterns-browser.js"></script>
- * Re-scan: window.impeccableScan()
- */
-(function () {
-if (typeof window === 'undefined') return;
-// --- cli/engine/shared/constants.mjs ---
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-// --- cli/engine/registry/antipatterns.mjs ---
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-// --- cli/engine/shared/color.mjs ---
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-// --- cli/engine/rules/checks.mjs ---
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-// --- cli/engine/browser/injected/index.mjs ---
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
-
-})();
@@ -1,43 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Anti-Pattern Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * Public API facade. Runtime engines live under cli/engine/engines/.
- */
-
-import { detectCli } from './cli/main.mjs';
-
-export { ANTIPATTERNS, RULE_ENGINE_SUPPORT, getAntipattern, getRulesForCategory, getRuleEngineSupport } from './registry/antipatterns.mjs';
-export { SAFE_TAGS, BORDER_SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS, KNOWN_SERIF_FONTS } from './shared/constants.mjs';
-export { isNeutralColor, parseRgb, relativeLuminance, contrastRatio, parseGradientColors, hasChroma, getHue, colorToHex } from './shared/color.mjs';
-export { isFullPage } from './shared/page.mjs';
-export {
- checkElementBorders,
- checkElementMotion,
- checkElementGlow,
- checkPageTypography,
- checkPageLayout,
- checkHtmlPatterns,
-} from './rules/checks.mjs';
-export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
-export { detectHtml } from './engines/static-html/detect-html.mjs';
-export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
-export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
-export {
- walkDir,
- SCANNABLE_EXTENSIONS,
- SKIP_DIRS,
- buildImportGraph,
- resolveImport,
- detectFrameworkConfig,
- isPortListening,
- FRAMEWORK_CONFIGS,
-} from './node/file-system.mjs';
-export { formatFindings, detectCli } from './cli/main.mjs';
-
-const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
-if (isMainModule) detectCli();
@@ -1,251 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { finding } from '../../findings.mjs';
-import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
-
-async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
- if (options?.visualContrast === false) return [];
- const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : 12;
- const scrollOffscreen = options?.visualContrastScrollOffscreen !== false;
- const existingLowContrastSelectors = new Set(
- serializedGroups
- .filter(group => group.findings?.some(f => f.type === 'low-contrast'))
- .map(group => group.selector)
- .filter(Boolean)
- );
-
- let browserAnalyses = [];
- const findings = [];
- if (options?.visualContrastBrowser !== false) {
- const browserFindings = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'browser-fallback',
- target,
- }, async () => {
- browserAnalyses = await page.evaluate(async ({ maxCandidates, scrollOffscreen }) => {
- if (typeof window.impeccableAnalyzeVisualContrast !== 'function') return [];
- return window.impeccableAnalyzeVisualContrast({ maxCandidates, scrollOffscreen });
- }, { maxCandidates, scrollOffscreen });
- return browserAnalyses
- .filter(result => result.finding && !existingLowContrastSelectors.has(result.selector))
- .map(result => result.finding);
- });
- findings.push(...browserFindings);
- }
-
- let candidates = browserAnalyses.length > 0 ? browserAnalyses : [];
- if (candidates.length === 0) {
- candidates = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'collect-candidates',
- target,
- }, () => page.evaluate(({ maxCandidates }) => {
- if (typeof window.impeccableCollectVisualContrastCandidates !== 'function') return [];
- return window.impeccableCollectVisualContrastCandidates({ maxCandidates });
- }, { maxCandidates }));
- }
-
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const browserResolvedSelectors = new Set(
- browserAnalyses
- .filter(result => result.status === 'fail' || result.status === 'pass')
- .map(result => result.selector)
- .filter(Boolean)
- );
- const filtered = candidates.filter(candidate =>
- !existingLowContrastSelectors.has(candidate.selector) &&
- !browserResolvedSelectors.has(candidate.selector)
- );
- if (options?.visualContrastPixel === false) return findings;
- for (const candidate of filtered) {
- const result = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'pixel-diff',
- target,
- }, async () => {
- const finding = await captureVisualContrastCandidate(page, candidate, viewport);
- return finding ? [finding] : [];
- });
- findings.push(...result);
- }
- return findings;
-}
-
-// ---------------------------------------------------------------------------
-// Puppeteer detection (for URLs)
-// ---------------------------------------------------------------------------
-
-async function detectUrl(url, options = {}) {
- const profile = options?.profile;
- const waitUntil = options?.waitUntil || 'networkidle0';
- const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const externalBrowser = options?.browser || null;
- let puppeteer;
- if (!externalBrowser) {
- try {
- puppeteer = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'import-puppeteer',
- target: url,
- }, () => import('puppeteer'));
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- }
-
- // Read the browser detection script — reuse it instead of reimplementing
- const browserScriptPath = path.resolve(
- path.dirname(fileURLToPath(import.meta.url)),
- '..',
- '..',
- 'detect-antipatterns-browser.js'
- );
- let browserScript;
- try {
- browserScript = profileStep(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'read-browser-script',
- target: url,
- }, () => fs.readFileSync(browserScriptPath, 'utf-8'));
- } catch {
- throw new Error(`Browser script not found at ${browserScriptPath}`);
- }
-
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
- // running in CI; local users keep the default hardened launch.
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
- const browser = externalBrowser || await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'launch-browser',
- target: url,
- }, () => puppeteer.default.launch({ headless: true, args: launchArgs }));
- const page = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'new-page',
- target: url,
- }, () => browser.newPage());
- let results = [];
- try {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'set-viewport',
- target: url,
- }, () => page.setViewport(viewport));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: `goto:${waitUntil}`,
- target: url,
- }, () => page.goto(url, { waitUntil, timeout: 30000 }));
- if (settleMs > 0) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'settle',
- target: url,
- }, () => new Promise(resolve => setTimeout(resolve, settleMs)));
- }
-
- // Inject the browser detection script and collect results
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'configure-pure-detect',
- target: url,
- }, () => page.evaluate(() => {
- window.__IMPECCABLE_CONFIG__ = {
- ...(window.__IMPECCABLE_CONFIG__ || {}),
- autoScan: false,
- };
- }));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'inject-browser-script',
- target: url,
- }, () => page.evaluate(browserScript));
- let serializedGroups = [];
- results = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'browser-scan',
- target: url,
- }, async () => {
- serializedGroups = await page.evaluate(() => {
- if (!window.impeccableDetect) return [];
- return window.impeccableDetect({ decorate: false, serialize: true });
- });
- return serializedGroups.flatMap(({ findings }) =>
- findings.map(f => ({ id: f.type, snippet: f.detail }))
- );
- });
- const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
- results.push(...visualFindings);
- } finally {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-page',
- target: url,
- }, () => page.close().catch(() => {}));
- if (!externalBrowser) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-browser',
- target: url,
- }, () => browser.close());
- }
- }
- return results.map(f => finding(f.id, url, f.snippet));
-}
-
-async function createBrowserDetector(options = {}) {
- let puppeteer;
- try {
- puppeteer = await import('puppeteer');
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- const launchArgs = options.launchArgs || (process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : []);
- const browser = options.browser || await puppeteer.default.launch({
- headless: options.headless ?? true,
- args: launchArgs,
- });
- const ownsBrowser = !options.browser;
- const defaults = {
- waitUntil: options.waitUntil || 'load',
- settleMs: Number.isFinite(options.settleMs) ? options.settleMs : 100,
- viewport: options.viewport || { width: 1280, height: 800 },
- };
- return {
- browser,
- async detectUrl(url, scanOptions = {}) {
- return detectUrl(url, {
- ...defaults,
- ...scanOptions,
- browser,
- });
- },
- async close() {
- if (ownsBrowser) await browser.close().catch(() => {});
- },
- };
-}
-
-export { runVisualContrastFallback, detectUrl, createBrowserDetector };
@@ -1,420 +0,0 @@
-import { GENERIC_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep } from '../../profile/profiler.mjs';
-
-// ---------------------------------------------------------------------------
-// Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
-// ---------------------------------------------------------------------------
-
-const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
-const hasBorderRadius = (line) => /border-radius/i.test(line);
-const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
-
-function isNeutralBorderColor(str) {
- const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
- if (!m) return false;
- const c = m[1].toLowerCase();
- if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
- const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
- if (hex) {
- const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
- if (shex) {
- const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- return false;
-}
-
-const REGEX_MATCHERS = [
- // --- Side-tab ---
- { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
- test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
- test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
- fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
- { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
- test: (m) => +m[1] >= 3,
- fmt: (m) => m[0] },
- // --- Border accent on rounded ---
- { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
- test: (m, line) => hasRounded(line) && +m[1] >= 1,
- fmt: (m) => m[0] },
- { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
- fmt: (m) => m[0] },
- // --- Overused font ---
- { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
- test: () => true,
- fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
- // --- Pure black background ---
- { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Gradient text ---
- { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
- test: (m, line) => /gradient/i.test(line),
- fmt: () => 'background-clip: text + gradient' },
- // --- Gradient text (Tailwind) ---
- { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
- test: (m, line) => /\bbg-gradient-to-/i.test(line),
- fmt: () => 'bg-clip-text + bg-gradient' },
- // --- Tailwind pure black background ---
- { id: 'pure-black-white', regex: /\bbg-black\b/g,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Tailwind gray on colored bg ---
- { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
- test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
- fmt: (m, line) => { const bg = line.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/); return `${m[0]} on ${bg?.[0] || '?'}`; } },
- // --- Tailwind AI palette ---
- { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
- fmt: (m) => `${m[0]} on heading` },
- { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
- fmt: (m) => `${m[0]} gradient` },
- // --- Bounce/elastic easing ---
- { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
- test: () => true,
- fmt: () => 'animate-bounce (Tailwind)' },
- { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
- test: (m) => {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
- },
- fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
- // --- Layout property transition ---
- { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition: ${found ? found.join(', ') : m[1].trim()}`;
- } },
- { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
- } },
-];
-
-const REGEX_ANALYZERS = [
- // Single font
- (content, filePath) => {
- const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
- const fonts = new Set();
- let m;
- while ((m = fontFamilyRe.exec(content)) !== null) {
- for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
- }
- }
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- while ((m = gfRe.exec(content)) !== null) {
- for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
- }
- if (fonts.size !== 1 || content.split('\n').length < 20) return [];
- const name = [...fonts][0];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
- return [finding('single-font', filePath, `only font used is ${name}`, line)];
- },
- // Flat type hierarchy
- (content, filePath) => {
- const sizes = new Set();
- const REM = 16;
- let m;
- const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
- while ((m = sizeRe.exec(content)) !== null) {
- const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
- if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
- }
- const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
- while ((m = clampRe.exec(content)) !== null) {
- sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
- sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
- }
- const TW = { 'text-xs': 12, 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24, 'text-3xl': 30, 'text-4xl': 36, 'text-5xl': 48, 'text-6xl': 60, 'text-7xl': 72, 'text-8xl': 96, 'text-9xl': 128 };
- for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
- if (sizes.size < 3) return [];
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio >= 2.0) return [];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (/font-size/i.test(lines[i]) || /\btext-(?:xs|sm|base|lg|xl|\d)/i.test(lines[i])) { line = i + 1; break; } }
- return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
- },
- // Monotonous spacing (regex)
- (content, filePath) => {
- const vals = [];
- let m;
- const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
- const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
- const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
- const rounded = vals.map(v => Math.round(v / 4) * 4);
- if (rounded.length < 10) return [];
- const counts = {};
- for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const pct = maxCount / rounded.length;
- const unique = [...new Set(rounded)].filter(v => v > 0);
- if (pct <= 0.6 || unique.length > 3) return [];
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
- },
- // Everything centered (regex)
- (content, filePath) => {
- const lines = content.split('\n');
- let centered = 0, total = 0;
- for (const line of lines) {
- if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
- total++;
- if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
- }
- }
- if (total < 5 || centered / total <= 0.7) return [];
- return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
- },
- // Dark glow (page-level: dark bg + colored box-shadow with blur)
- (content, filePath) => {
- // Check if page has a dark background
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
- if (!hasDarkBg) return [];
-
- // Check for colored box-shadow with blur > 4px
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let m;
- while ((m = shadowRe.exec(content)) !== null) {
- const val = m[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
- // Check blur: look for pattern like "0 0 20px" (third number > 4)
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- const lines = content.substring(0, m.index).split('\n');
- return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
- }
- }
- return [];
- },
-];
-
-// ---------------------------------------------------------------------------
-// Style block extraction (Vue/Svelte <style> blocks)
-// ---------------------------------------------------------------------------
-
-function extractStyleBlocks(content, ext) {
- ext = ext.toLowerCase();
- if (ext !== '.vue' && ext !== '.svelte') return [];
- const blocks = [];
- const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length + 1;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-// ---------------------------------------------------------------------------
-// CSS-in-JS extraction (styled-components, emotion)
-// ---------------------------------------------------------------------------
-
-const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
-
-function extractCSSinJS(content, ext) {
- ext = ext.toLowerCase();
- if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
- const blocks = [];
- const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null, options = {}) {
- const { profile, phase = 'regex-matchers' } = options || {};
- const findings = [];
- if (!profile) {
- for (const matcher of REGEX_MATCHERS) {
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- }
- return findings;
- }
-
- for (const matcher of REGEX_MATCHERS) {
- const matcherFindings = profileFindings(profile, {
- engine: 'regex',
- phase,
- ruleId: matcher.id,
- target: filePath,
- }, () => {
- const matches = [];
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- matches.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- return matches;
- });
- findings.push(...matcherFindings);
- }
- return findings;
-}
-
-function detectText(content, filePath, options = {}) {
- const profile = options?.profile;
- const findings = [];
- const lines = content.split('\n');
- const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
-
- // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
- // Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
- findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
- profile,
- phase: 'source',
- }));
-
- // Extract and scan <style> blocks from Vue/Svelte SFCs
- const styleBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'style-blocks',
- target: filePath,
- }, () => extractStyleBlocks(content, ext))
- : extractStyleBlocks(content, ext);
- for (const block of styleBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'style-block',
- }));
- }
-
- // Extract and scan CSS-in-JS template literals
- const cssJsBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'css-in-js',
- target: filePath,
- }, () => extractCSSinJS(content, ext))
- : extractCSSinJS(content, ext);
- for (const block of cssJsBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'css-in-js',
- }));
- }
-
- // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
- const deduped = [];
- for (const f of findings) {
- const isDupe = deduped.some(d =>
- d.antipattern === f.antipattern &&
- d.snippet === f.snippet &&
- Math.abs(d.line - f.line) <= 2
- );
- if (!isDupe) deduped.push(f);
- }
-
- // Page-level analyzers only run on full pages
- if (isFullPage(content)) {
- const analyzerIds = [
- 'single-font',
- 'flat-type-hierarchy',
- 'monotonous-spacing',
- 'everything-centered',
- 'dark-glow',
- ];
- for (let i = 0; i < REGEX_ANALYZERS.length; i++) {
- const analyzer = REGEX_ANALYZERS[i];
- deduped.push(...profileFindings(profile, {
- engine: 'regex',
- phase: 'page-analyzer',
- ruleId: analyzerIds[i] || `analyzer-${i + 1}`,
- target: filePath,
- }, () => analyzer(content, filePath)));
- }
- }
-
- return deduped;
-}
-
-export {
- REGEX_MATCHERS,
- REGEX_ANALYZERS,
- extractStyleBlocks,
- extractCSSinJS,
- runRegexMatchers,
- detectText,
-};
@@ -1,954 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { profileStep, recordProfileEvent } from '../../profile/profiler.mjs';
-import { parseAnyColor, resolveLengthPx, resolveVarRefs } from '../../rules/checks.mjs';
-
-// ---------------------------------------------------------------------------
-// jsdom CSS-variable border override map
-// ---------------------------------------------------------------------------
-//
-// jsdom's CSSOM silently drops any border shorthand that contains a var()
-// reference — the computed style for the element then shows empty width,
-// empty style, and a default black color. That's enough to hide the most
-// common real-world side-tab pattern in AI-generated pages:
-//
-// :root { --brand: #87a8ff; }
-// .card { border-left: 5px solid var(--brand); border-radius: 4px; }
-//
-// Real browsers (and therefore the browser detector path) resolve var()
-// natively, so this only affects the Node jsdom path.
-//
-// This pre-pass walks the stylesheets, finds any rule whose per-side or
-// all-sides border property contains var(), resolves the var() against
-// :root-level custom properties (read from the documentElement's computed
-// style, which jsdom DOES handle correctly), and attaches the resolved
-// width+color to every element that matches the rule's selector. The
-// Node-side `checkElementBorders` adapter consumes that map as a fallback
-// whenever jsdom's computed style came back empty.
-//
-// Limitations (intentional, to keep the pass simple):
-// * Only :root-level custom properties are resolved. Scoped overrides on
-// descendants are not tracked — uncommon in practice and would require
-// a per-element cascade walk.
-// * @media / @supports wrapped rules are ignored (jsdom often mishandles
-// these anyway).
-// * The fallback only fills sides that jsdom left empty, so any rule
-// whose border parses normally still wins via the computed style.
-
-const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
-
-// isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
-// CSS variables typically hold hex or named colors, so normalize those to
-// rgb() before handing the value off to the shared check. Anything we don't
-// recognise is passed through unchanged — isNeutralColor then treats it as
-// non-neutral, which is the safer default (matches the oklch-era bugfix).
-const NAMED_COLORS = {
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
-};
-
-function normalizeColorForCheck(value) {
- if (!value) return value;
- const v = value.trim();
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
- if (hex6) {
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
- if (hex3) {
- const [r, g, b] = [
- parseInt(hex3[1] + hex3[1], 16),
- parseInt(hex3[2] + hex3[2], 16),
- parseInt(hex3[3] + hex3[3], 16),
- ];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const named = NAMED_COLORS[v.toLowerCase()];
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
- return v;
-}
-
-function buildBorderOverrideMap(document, window) {
- const map = new Map();
- const rootStyle = window.getComputedStyle(document.documentElement);
-
- function resolveVar(value, depth = 0) {
- if (!value || depth > 10 || !value.includes('var(')) return value;
- return value.replace(
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
- (_, name, fallback) => {
- const v = rootStyle.getPropertyValue(name).trim();
- if (v) return resolveVar(v, depth + 1);
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
- return '';
- }
- );
- }
-
- function parseShorthand(text) {
- const m = text.trim().match(BORDER_SHORTHAND_RE);
- if (!m) return null;
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
- }
-
- // Read from the per-property accessors on rule.style. jsdom preserves
- // each border-* shorthand it parsed, even when the overall cssText has
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
- // `border-left: ...` loses the first declaration but keeps the second).
- const SIDE_PROPS = [
- ['borderLeft', 'Left'],
- ['borderRight', 'Right'],
- ['borderTop', 'Top'],
- ['borderBottom', 'Bottom'],
- ['borderInlineStart', 'Left'],
- ['borderInlineEnd', 'Right'],
- ];
-
- for (const sheet of document.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || []; } catch { continue; }
- for (const rule of rules) {
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
-
- const perSide = {};
-
- for (const [prop, side] of SIDE_PROPS) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const parsed = parseShorthand(resolveVar(val));
- if (parsed && parsed.color) perSide[side] = parsed;
- }
-
- // Uniform `border: <w> <style> var(...)` applies to every side the
- // per-side map didn't already claim.
- const borderAll = rule.style.border;
- if (borderAll && borderAll.includes('var(')) {
- const parsed = parseShorthand(resolveVar(borderAll));
- if (parsed && parsed.color) {
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
- if (!perSide[s]) perSide[s] = parsed;
- }
- }
- }
-
- // Longhand `border-*-color: var(...)` with width/style in separate
- // declarations. Rare in AI-generated pages, but cheap to cover.
- for (const [prop, side] of [
- ['borderLeftColor', 'Left'],
- ['borderRightColor', 'Right'],
- ['borderTopColor', 'Top'],
- ['borderBottomColor', 'Bottom'],
- ]) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const resolved = resolveVar(val).trim();
- if (!resolved) continue;
- // Width may or may not come from this rule — that's fine; the
- // adapter only substitutes the color when jsdom left it as a
- // literal var() string.
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
- }
-
- if (Object.keys(perSide).length === 0) continue;
-
- let matched;
- try { matched = document.querySelectorAll(rule.selectorText); }
- catch { continue; }
-
- for (const el of matched) {
- const existing = map.get(el);
- if (existing) {
- // Later rules overwrite earlier ones — approximates source-order
- // cascade for equal-specificity rules and is good enough for the
- // uncontested var()-dropped sides we're trying to recover.
- Object.assign(existing, perSide);
- } else {
- map.set(el, { ...perSide });
- }
- }
- }
- }
-
- return map;
-}
-
-// Strip `@layer NAME { … }` wrappers from a CSS / HTML source, leaving
-// the inner rules as flat CSS. jsdom doesn't implement CSS @layer, so
-// any rule inside a layer block becomes invisible to getComputedStyle.
-// Tailwind v4 makes this ubiquitous: every utility class lives in
-// `@layer utilities`, and Preflight lives in `@layer base`. Without
-// unwrapping, every Tailwind-styled element returns empty computed
-// styles. We walk the source character-by-character, balancing braces
-// so we correctly handle nested style rules inside the layer block.
-function unwrapCssAtLayer(source) {
- if (!source || !source.includes('@layer')) return source;
- // Find `@layer <name>? {` openers. The match starts at the @, and
- // we then balance braces from the opening { onward.
- const re = /@layer\b[^{;]*\{/g;
- let out = '';
- let lastIdx = 0;
- let m;
- while ((m = re.exec(source)) !== null) {
- const openStart = m.index;
- const openEnd = m.index + m[0].length; // position right after `{`
- let depth = 1;
- let i = openEnd;
- while (i < source.length && depth > 0) {
- const c = source.charCodeAt(i);
- if (c === 0x7b /* { */) depth++;
- else if (c === 0x7d /* } */) depth--;
- i++;
- }
- if (depth !== 0) {
- // Unbalanced — bail and return source unchanged.
- return source;
- }
- // Emit everything before the @layer, then the inner contents
- // (between the opening { and the matched closing }), then advance.
- out += source.slice(lastIdx, openStart);
- out += source.slice(openEnd, i - 1); // i-1 = position of the closing }
- lastIdx = i;
- re.lastIndex = i;
- }
- out += source.slice(lastIdx);
- return out;
-}
-
-// ---------------------------------------------------------------------------
-// Static HTML/CSS detection (default for local HTML files)
-// ---------------------------------------------------------------------------
-
-const STATIC_INHERITED_PROPS = new Set([
- 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight',
- 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'hyphens',
- 'webkitHyphens',
-]);
-
-const STATIC_DEFAULT_STYLE = {
- color: 'rgb(0, 0, 0)',
- backgroundColor: 'rgba(0, 0, 0, 0)',
- backgroundImage: 'none',
- borderTopWidth: '0px',
- borderRightWidth: '0px',
- borderBottomWidth: '0px',
- borderLeftWidth: '0px',
- borderTopColor: 'rgb(0, 0, 0)',
- borderRightColor: 'rgb(0, 0, 0)',
- borderBottomColor: 'rgb(0, 0, 0)',
- borderLeftColor: 'rgb(0, 0, 0)',
- borderRadius: '0px',
- boxShadow: 'none',
- fontFamily: '',
- fontSize: '16px',
- fontStyle: 'normal',
- fontWeight: '400',
- lineHeight: 'normal',
- letterSpacing: 'normal',
- textTransform: 'none',
- textAlign: 'start',
- hyphens: 'manual',
- webkitHyphens: 'manual',
- transitionProperty: '',
- transitionTimingFunction: '',
- animationName: '',
- animationTimingFunction: '',
- webkitBackgroundClip: '',
- backgroundClip: '',
- width: '',
- height: '',
- paddingTop: '0px',
- paddingRight: '0px',
- paddingBottom: '0px',
- paddingLeft: '0px',
- position: 'static',
- display: '',
-};
-
-const STATIC_PROP_MAP = {
- 'background-color': 'backgroundColor',
- 'background-image': 'backgroundImage',
- 'background-clip': 'backgroundClip',
- '-webkit-background-clip': 'webkitBackgroundClip',
- 'border-radius': 'borderRadius',
- 'border-top-width': 'borderTopWidth',
- 'border-right-width': 'borderRightWidth',
- 'border-bottom-width': 'borderBottomWidth',
- 'border-left-width': 'borderLeftWidth',
- 'border-top-color': 'borderTopColor',
- 'border-right-color': 'borderRightColor',
- 'border-bottom-color': 'borderBottomColor',
- 'border-left-color': 'borderLeftColor',
- 'box-shadow': 'boxShadow',
- 'font-family': 'fontFamily',
- 'font-size': 'fontSize',
- 'font-style': 'fontStyle',
- 'font-weight': 'fontWeight',
- 'line-height': 'lineHeight',
- 'letter-spacing': 'letterSpacing',
- 'text-transform': 'textTransform',
- 'text-align': 'textAlign',
- 'hyphens': 'hyphens',
- '-webkit-hyphens': 'webkitHyphens',
- 'transition-property': 'transitionProperty',
- 'transition-timing-function': 'transitionTimingFunction',
- 'animation-name': 'animationName',
- 'animation-timing-function': 'animationTimingFunction',
- 'width': 'width',
- 'height': 'height',
- 'padding-top': 'paddingTop',
- 'padding-right': 'paddingRight',
- 'padding-bottom': 'paddingBottom',
- 'padding-left': 'paddingLeft',
- 'position': 'position',
- 'display': 'display',
-};
-
-const STATIC_NAMED_COLORS = {
- black: { r: 0, g: 0, b: 0, a: 1 },
- white: { r: 255, g: 255, b: 255, a: 1 },
- transparent: { r: 0, g: 0, b: 0, a: 0 },
- gray: { r: 128, g: 128, b: 128, a: 1 },
- grey: { r: 128, g: 128, b: 128, a: 1 },
- silver: { r: 192, g: 192, b: 192, a: 1 },
- red: { r: 255, g: 0, b: 0, a: 1 },
- green: { r: 0, g: 128, b: 0, a: 1 },
- blue: { r: 0, g: 0, b: 255, a: 1 },
-};
-
-function splitCssList(value) {
- const parts = [];
- let depth = 0, quote = '', start = 0;
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; continue; }
- if (ch === '(' || ch === '[') depth++;
- else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);
- else if (ch === ',' && depth === 0) {
- parts.push(value.slice(start, i).trim());
- start = i + 1;
- }
- }
- const tail = value.slice(start).trim();
- if (tail) parts.push(tail);
- return parts;
-}
-
-function splitCssTokens(value) {
- const tokens = [];
- let depth = 0, quote = '', current = '';
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- current += ch;
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
- if (ch === '(') { depth++; current += ch; continue; }
- if (ch === ')') { depth = Math.max(0, depth - 1); current += ch; continue; }
- if (/\s/.test(ch) && depth === 0) {
- if (current) { tokens.push(current); current = ''; }
- continue;
- }
- current += ch;
- }
- if (current) tokens.push(current);
- return tokens;
-}
-
-function cssPropToCamel(prop) {
- if (!prop) return prop;
- const mapped = STATIC_PROP_MAP[prop];
- if (mapped) return mapped;
- return prop.replace(/-([a-z])/g, (_m, ch) => ch.toUpperCase());
-}
-
-function staticColorToCss(c) {
- if (!c) return '';
- if (c.a != null && c.a < 1) return `rgba(${c.r}, ${c.g}, ${c.b}, ${Number(c.a.toFixed(3))})`;
- return `rgb(${c.r}, ${c.g}, ${c.b})`;
-}
-
-function parseStaticColor(value) {
- const parsed = parseAnyColor(value);
- if (parsed) return parsed;
- const named = STATIC_NAMED_COLORS[String(value || '').trim().toLowerCase()];
- return named ? { ...named } : null;
-}
-
-function extractStaticColor(value) {
- if (!value) return '';
- const raw = String(value).trim();
- if (/^var\(/i.test(raw)) return raw;
- const colorLike = raw.match(/(?:rgba?\([^)]+\)|oklch\([^)]+\)|oklab\([^)]+\)|lch\([^)]+\)|lab\([^)]+\)|hsla?\([^)]+\)|hwb\([^)]+\)|#[0-9a-f]{3,8}\b|\b(?:black|white|gray|grey|silver|red|green|blue|transparent)\b)/i);
- if (!colorLike) return '';
- return colorLike[0];
-}
-
-function normalizeStaticCssValue(prop, value, customProps, parentStyle, currentStyle = null) {
- let resolved = resolveVarRefs(String(value || '').trim(), customProps);
- if (resolved === 'inherit') return parentStyle?.[prop] || STATIC_DEFAULT_STYLE[prop] || '';
- const isModernBorderColor = /^border[A-Z][a-z]+Color$/.test(prop) && /^(?:oklch|oklab|lch|lab|hsl|hwb)\(/i.test(resolved);
- if (!isModernBorderColor && (/color$/i.test(prop) || prop === 'color' || prop === 'backgroundColor')) {
- const parsed = parseStaticColor(resolved);
- if (parsed) resolved = staticColorToCss(parsed);
- }
- if (prop === 'fontSize') {
- const base = parseFloat(parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'letterSpacing') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'lineHeight' && resolved !== 'normal') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- return resolved;
-}
-
-function expandStaticBoxValues(tokens) {
- if (tokens.length === 0) return ['0px', '0px', '0px', '0px'];
- if (tokens.length === 1) return [tokens[0], tokens[0], tokens[0], tokens[0]];
- if (tokens.length === 2) return [tokens[0], tokens[1], tokens[0], tokens[1]];
- if (tokens.length === 3) return [tokens[0], tokens[1], tokens[2], tokens[1]];
- return [tokens[0], tokens[1], tokens[2], tokens[3]];
-}
-
-function parseStaticBorder(value) {
- const tokens = splitCssTokens(value);
- let width = '', color = '';
- for (const token of tokens) {
- if (!width && /^-?[\d.]+(?:px|rem|em|%)$/.test(token)) width = token;
- if (!color) color = extractStaticColor(token);
- }
- return { width, color };
-}
-
-function parseStaticFont(value) {
- const out = [];
- const slashParts = value.match(/(?:^|\s)([\d.]+(?:px|rem|em|%))(?:\/([^\s]+))?/);
- if (/\bitalic\b/i.test(value)) out.push(['fontStyle', 'italic']);
- const weight = value.match(/\b([1-9]00|bold|normal|lighter|bolder)\b/i);
- if (weight) out.push(['fontWeight', weight[1]]);
- if (slashParts) {
- out.push(['fontSize', slashParts[1]]);
- if (slashParts[2]) out.push(['lineHeight', slashParts[2]]);
- const familyStart = value.indexOf(slashParts[0]) + slashParts[0].length;
- const family = value.slice(familyStart).trim();
- if (family) out.push(['fontFamily', family]);
- }
- return out;
-}
-
-function parseStaticTransition(value) {
- const props = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const prop = tokens.find(token => /^[a-z-]+$/i.test(token) && !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none)$/.test(token) && !/s$/.test(token));
- if (prop) props.push(prop);
- }
- return {
- property: props.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function parseStaticAnimation(value) {
- const names = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const name = tokens.find(token =>
- /^[a-z_-][\w-]*$/i.test(token) &&
- !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none|running|paused)$/.test(token)
- );
- if (name) names.push(name);
- }
- return {
- name: names.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function expandStaticDeclaration(prop, value) {
- const p = prop.toLowerCase();
- const v = String(value || '').trim();
- if (!v) return [];
- if (p.startsWith('--')) return [[p, v]];
- if (p === 'background') {
- const out = [];
- const hasImage = /gradient|url\(/i.test(v);
- if (hasImage) out.push(['backgroundImage', v]);
- const beforeImage = hasImage ? v.split(/(?:repeating-)?(?:linear|radial|conic)-gradient\(|url\(/i)[0] : v;
- const color = extractStaticColor(hasImage ? beforeImage : v);
- if (color) out.push(['backgroundColor', color]);
- return out;
- }
- if (p === 'border') {
- const parsed = parseStaticBorder(v);
- const out = [];
- for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
- if (parsed.width) out.push([`border${side}Width`, parsed.width]);
- if (parsed.color) out.push([`border${side}Color`, parsed.color]);
- }
- return out;
- }
- const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
- if (sideMatch) {
- const parsed = parseStaticBorder(v);
- const side = sideMatch[1][0].toUpperCase() + sideMatch[1].slice(1);
- return [
- ...(parsed.width ? [[`border${side}Width`, parsed.width]] : []),
- ...(parsed.color ? [[`border${side}Color`, parsed.color]] : []),
- ];
- }
- if (p === 'border-width') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopWidth', vals[0]],
- ['borderRightWidth', vals[1]],
- ['borderBottomWidth', vals[2]],
- ['borderLeftWidth', vals[3]],
- ];
- }
- if (p === 'border-color') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopColor', vals[0]],
- ['borderRightColor', vals[1]],
- ['borderBottomColor', vals[2]],
- ['borderLeftColor', vals[3]],
- ];
- }
- if (p === 'padding') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['paddingTop', vals[0]],
- ['paddingRight', vals[1]],
- ['paddingBottom', vals[2]],
- ['paddingLeft', vals[3]],
- ];
- }
- if (p === 'font') return parseStaticFont(v);
- if (p === 'transition') {
- const parsed = parseStaticTransition(v);
- return [
- ...(parsed.property ? [['transitionProperty', parsed.property]] : []),
- ...(parsed.timing ? [['transitionTimingFunction', parsed.timing]] : []),
- ];
- }
- if (p === 'animation') {
- const parsed = parseStaticAnimation(v);
- return [
- ...(parsed.name ? [['animationName', parsed.name]] : []),
- ...(parsed.timing ? [['animationTimingFunction', parsed.timing]] : []),
- ];
- }
- const mapped = cssPropToCamel(p);
- if (STATIC_DEFAULT_STYLE[mapped] != null || STATIC_INHERITED_PROPS.has(mapped)) {
- return [[mapped, v]];
- }
- return [];
-}
-
-function compareStaticPriority(a, b) {
- if (!a) return true;
- if (!!b.important !== !!a.important) return !!b.important;
- if (!!b.inline !== !!a.inline) return !!b.inline;
- for (let i = 0; i < 3; i++) {
- if ((b.specificity[i] || 0) !== (a.specificity[i] || 0)) {
- return (b.specificity[i] || 0) > (a.specificity[i] || 0);
- }
- }
- return b.order >= a.order;
-}
-
-function staticSpecificity(selector) {
- const noWhere = selector.replace(/:where\([^)]*\)/g, '');
- const ids = (noWhere.match(/#[\w-]+/g) || []).length;
- const classes = (noWhere.match(/\.[\w-]+|\[[^\]]+\]|:(?!:)[\w-]+(?:\([^)]*\))?/g) || []).length;
- const stripped = noWhere
- .replace(/#[\w-]+/g, ' ')
- .replace(/\.[\w-]+|\[[^\]]+\]|:{1,2}[\w-]+(?:\([^)]*\))?/g, ' ')
- .replace(/[*>+~(),]/g, ' ');
- const types = (stripped.match(/\b[a-zA-Z][\w-]*\b/g) || []).length;
- return [ids, classes, types];
-}
-
-function applyStaticDeclaration(specified, node, prop, value, meta) {
- let map = specified.get(node);
- if (!map) { map = new Map(); specified.set(node, map); }
- for (const [expandedProp, expandedValue] of expandStaticDeclaration(prop, value)) {
- const existing = map.get(expandedProp);
- const next = { ...meta, prop: expandedProp, value: expandedValue };
- if (compareStaticPriority(existing, next)) map.set(expandedProp, next);
- }
-}
-
-function parseStaticStyleAttribute(styleText, orderBase = 0) {
- const decls = [];
- for (const part of String(styleText || '').split(';')) {
- const idx = part.indexOf(':');
- if (idx <= 0) continue;
- const prop = part.slice(0, idx).trim();
- let value = part.slice(idx + 1).trim();
- const important = /!important\s*$/i.test(value);
- value = value.replace(/\s*!important\s*$/i, '').trim();
- decls.push({ prop, value, important, order: orderBase + decls.length });
- }
- return decls;
-}
-
-function collectStaticCssRules(cssText, csstree) {
- const rules = [];
- let ast;
- try {
- ast = csstree.parse(cssText, { positions: false, parseValue: true, parseCustomProperty: false });
- } catch {
- return rules;
- }
- let order = 0;
- const walkList = (list, atRuleStack = []) => {
- list?.forEach?.(node => {
- if (node.type === 'Rule' && node.block) {
- if (atRuleStack.some(name => /keyframes$/i.test(name))) return;
- const selectorText = csstree.generate(node.prelude).trim();
- const declarations = [];
- node.block.children?.forEach?.(child => {
- if (child.type !== 'Declaration') return;
- declarations.push({
- prop: child.property,
- value: csstree.generate(child.value).trim(),
- important: !!child.important,
- });
- });
- for (const selector of splitCssList(selectorText)) {
- if (selector) rules.push({ selector, declarations, specificity: staticSpecificity(selector), order: order++ });
- }
- return;
- }
- if (node.type === 'Atrule' && node.block) {
- const name = String(node.name || '').toLowerCase();
- if (name === 'media' || name === 'supports' || name === 'layer') {
- walkList(node.block.children, [...atRuleStack, name]);
- }
- }
- });
- };
- walkList(ast.children);
- return rules;
-}
-
-class StaticElement {
- constructor(node, doc) {
- this.node = node;
- this._doc = doc;
- this.nodeType = 1;
- this.tagName = String(node.name || '').toUpperCase();
- this.nodeName = this.tagName;
- }
- get parentElement() {
- let cur = this.node.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- return cur ? this._doc.wrap(cur) : null;
- }
- get previousElementSibling() {
- let cur = this.node.prev;
- while (cur && cur.type !== 'tag') cur = cur.prev;
- return cur ? this._doc.wrap(cur) : null;
- }
- get children() {
- return (this.node.children || []).filter(child => child.type === 'tag').map(child => this._doc.wrap(child));
- }
- get childNodes() {
- return (this.node.children || []).map(child => {
- if (child.type === 'text') return { nodeType: 3, textContent: child.data || '' };
- if (child.type === 'tag') return this._doc.wrap(child);
- return { nodeType: 8, textContent: child.data || '' };
- });
- }
- get textContent() {
- return this._doc.domutils.textContent(this.node);
- }
- get className() {
- return this.getAttribute('class') || '';
- }
- get id() {
- return this.getAttribute('id') || '';
- }
- getAttribute(name) {
- return this.node.attribs?.[name] ?? null;
- }
- querySelector(selector) {
- try {
- const found = this._doc.selectOne(selector, this.node.children || []);
- return found ? this._doc.wrap(found) : null;
- } catch {
- return null;
- }
- }
- querySelectorAll(selector) {
- try {
- return this._doc.selectAll(selector, this.node.children || []).map(node => this._doc.wrap(node));
- } catch {
- return [];
- }
- }
- closest(selector) {
- let cur = this.node;
- while (cur && cur.type === 'tag') {
- try {
- if (this._doc.is(cur, selector)) return this._doc.wrap(cur);
- } catch {
- return null;
- }
- cur = cur.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- }
- return null;
- }
- contains(other) {
- let cur = other?.node || null;
- while (cur) {
- if (cur === this.node) return true;
- cur = cur.parent;
- }
- return false;
- }
-}
-
-class StaticDocument {
- constructor(root, modules) {
- this.root = root;
- this.selectAll = modules.selectAll;
- this.selectOne = modules.selectOne;
- this.is = modules.is;
- this.domutils = modules.domutils;
- this._wrappers = new WeakMap();
- this._styleMap = new WeakMap();
- }
- wrap(node) {
- let wrapped = this._wrappers.get(node);
- if (!wrapped) {
- wrapped = new StaticElement(node, this);
- this._wrappers.set(node, wrapped);
- }
- return wrapped;
- }
- querySelectorAll(selector) {
- try {
- return this.selectAll(selector, this.root.children || []).map(node => this.wrap(node));
- } catch {
- return [];
- }
- }
- querySelector(selector) {
- try {
- const found = this.selectOne(selector, this.root.children || []);
- return found ? this.wrap(found) : null;
- } catch {
- return null;
- }
- }
- get documentElement() {
- return this.querySelector('html');
- }
- get body() {
- return this.querySelector('body');
- }
- setStyle(node, style) {
- this._styleMap.set(node, style);
- }
- getStyle(el) {
- return this._styleMap.get(el.node) || makeStaticStyle();
- }
-}
-
-function makeStaticStyle(values = {}) {
- const style = { ...STATIC_DEFAULT_STYLE, ...values };
- style.getPropertyValue = (prop) => {
- const key = cssPropToCamel(prop);
- return style[key] || style[prop] || '';
- };
- return style;
-}
-
-function buildStaticWindow(staticDoc) {
- return {
- document: staticDoc,
- getComputedStyle: (el) => staticDoc.getStyle(el),
- };
-}
-
-function collectStaticCssText(root, fileDir, profile, filePath, modules) {
- const styleTexts = [];
- for (const styleEl of modules.selectAll('style', root.children || [])) {
- styleTexts.push(modules.domutils.textContent(styleEl));
- }
- const links = modules.selectAll('link', root.children || []);
- for (const link of links) {
- const rel = link.attribs?.rel || '';
- const href = link.attribs?.href || '';
- if (!/\bstylesheet\b/i.test(rel) || !href || /^(https?:)?\/\//i.test(href)) continue;
- const cssPath = path.resolve(fileDir, href);
- try {
- const css = profileStep(profile, {
- engine: 'static-html',
- phase: 'preprocess',
- ruleId: 'inline-linked-stylesheet',
- target: filePath,
- detail: href,
- }, () => fs.readFileSync(cssPath, 'utf-8'));
- styleTexts.push(css);
- } catch { /* skip unreadable */ }
- }
- return styleTexts.join('\n');
-}
-
-function buildStaticStyleMap(root, staticDoc, cssText, modules, profile, filePath) {
- const specified = new Map();
- const allNodes = modules.selectAll('*', root.children || []);
- const rules = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-css',
- ruleId: 'css-rules',
- target: filePath,
- }, () => collectStaticCssRules(cssText, modules.csstree));
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'css-selectors',
- target: filePath,
- }, () => {
- for (const rule of rules) {
- let matched;
- try {
- matched = modules.selectAll(rule.selector, root.children || []);
- } catch {
- recordProfileEvent(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'unsupported-selector',
- target: filePath,
- ms: 0,
- findings: 0,
- detail: rule.selector,
- });
- continue;
- }
- for (const node of matched) {
- for (const decl of rule.declarations) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: rule.specificity,
- order: rule.order,
- inline: false,
- });
- }
- }
- }
-
- let inlineOrder = rules.length + 1;
- for (const node of allNodes) {
- const styleText = node.attribs?.style;
- if (!styleText) continue;
- for (const decl of parseStaticStyleAttribute(styleText, inlineOrder)) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: [1, 0, 0],
- order: decl.order,
- inline: true,
- });
- }
- inlineOrder += 1000;
- }
- });
-
- const computeNode = (node, parentStyle = null, parentCustom = new Map()) => {
- const specifiedMap = specified.get(node) || new Map();
- const customProps = new Map(parentCustom);
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) customProps.set(prop, resolveVarRefs(decl.value, customProps));
- }
- const values = {};
- for (const prop of Object.keys(STATIC_DEFAULT_STYLE)) {
- if (STATIC_INHERITED_PROPS.has(prop) && parentStyle?.[prop] != null) values[prop] = parentStyle[prop];
- else values[prop] = STATIC_DEFAULT_STYLE[prop];
- }
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) continue;
- values[prop] = normalizeStaticCssValue(prop, decl.value, customProps, parentStyle, values);
- }
- const style = makeStaticStyle(values);
- staticDoc.setStyle(node, style);
- for (const child of node.children || []) {
- if (child.type === 'tag') computeNode(child, style, customProps);
- }
- };
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'cascade',
- ruleId: 'compute-styles',
- target: filePath,
- }, () => {
- for (const child of root.children || []) {
- if (child.type === 'tag') computeNode(child);
- }
- });
-}
-
-export {
- BORDER_SHORTHAND_RE,
- NAMED_COLORS,
- normalizeColorForCheck,
- buildBorderOverrideMap,
- unwrapCssAtLayer,
- STATIC_INHERITED_PROPS,
- STATIC_DEFAULT_STYLE,
- STATIC_PROP_MAP,
- STATIC_NAMED_COLORS,
- splitCssList,
- splitCssTokens,
- cssPropToCamel,
- staticColorToCss,
- parseStaticColor,
- extractStaticColor,
- normalizeStaticCssValue,
- expandStaticBoxValues,
- parseStaticBorder,
- parseStaticFont,
- parseStaticTransition,
- parseStaticAnimation,
- expandStaticDeclaration,
- compareStaticPriority,
- staticSpecificity,
- applyStaticDeclaration,
- parseStaticStyleAttribute,
- collectStaticCssRules,
- StaticElement,
- StaticDocument,
- makeStaticStyle,
- buildStaticWindow,
- collectStaticCssText,
- buildStaticStyleMap,
-};
@@ -1,174 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import {
- checkElementBorders,
- checkElementColors,
- checkElementGlow,
- checkElementHeroEyebrow,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementMotion,
- checkElementQuality,
- checkHtmlPatterns,
- checkPageLayout,
- checkPageQualityFromDoc,
- checkRepeatedSectionKickersFromDoc,
- resolveBackground,
- resolveBorderRadiusPx,
-} from '../../rules/checks.mjs';
-import { detectText } from '../regex/detect-text.mjs';
-import {
- StaticDocument,
- buildStaticStyleMap,
- buildStaticWindow,
- collectStaticCssText,
-} from './css-cascade.mjs';
-
-function checkStaticPageTypography(document, window) {
- const findings = [];
- const fonts = new Set();
- const overusedFound = new Set();
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span, div')) {
- const hasText = el.childNodes.some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const ff = window.getComputedStyle(el).fontFamily || '';
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
- if (fonts.size === 1 && document.querySelectorAll('*').length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div')) {
- const fontSize = parseFloat(window.getComputedStyle(el).fontSize);
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
- return findings;
-}
-
-const STATIC_ELEMENT_RULES = [
- { id: 'border-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementBorders(tag, style, null, resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window)) },
- { id: 'color-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementColors(el, style, tag, window, customPropMap, false) },
- { id: 'dark-glow', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window, customPropMap)) },
- { id: 'motion-rules', selector: '*', run: (el, tag, style) => checkElementMotion(tag, style) },
- { id: 'icon-tile-stack', selector: 'h1,h2,h3,h4,h5,h6', run: (el, tag, _style, window) => checkElementIconTile(el, tag, window) },
- { id: 'italic-serif-display', selector: 'h1,h2', run: (el, tag, style) => checkElementItalicSerif(el, style, tag) },
- { id: 'hero-eyebrow-chip', selector: 'h1', run: (el, tag, style, window, customPropMap) => checkElementHeroEyebrow(el, style, tag, window, customPropMap) },
- { id: 'quality-rules', selector: '*', run: (el, tag, style, window) => checkElementQuality(el, style, tag, window) },
-];
-
-async function detectHtml(filePath, options = {}) {
- const profile = options?.profile;
- const html = profileStep(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'read-html',
- target: filePath,
- }, () => fs.readFileSync(filePath, 'utf-8'));
-
- let modules;
- try {
- modules = await profileStepAsync(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'import-static-parser',
- target: filePath,
- }, async () => {
- const [htmlparser2, cssSelect, csstree, domutils] = await Promise.all([
- import('htmlparser2'),
- import('css-select'),
- import('css-tree'),
- import('domutils'),
- ]);
- return {
- parseDocument: htmlparser2.parseDocument,
- selectAll: cssSelect.selectAll,
- selectOne: cssSelect.selectOne,
- is: cssSelect.is,
- csstree,
- domutils,
- };
- });
- } catch {
- return detectText(html, filePath, options);
- }
-
- const resolvedPath = path.resolve(filePath);
- const fileDir = path.dirname(resolvedPath);
- const root = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-html',
- ruleId: 'parse-document',
- target: filePath,
- }, () => modules.parseDocument(html, { lowerCaseAttributeNames: false, lowerCaseTags: true }));
-
- const cssText = collectStaticCssText(root, fileDir, profile, filePath, modules);
- const document = new StaticDocument(root, modules);
- buildStaticStyleMap(root, document, cssText, modules, profile, filePath);
- const window = buildStaticWindow(document);
-
- const customPropMap = null;
-
- const findings = [];
- const runElementCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'element', ruleId, target: filePath }, callback)
- : callback();
-
- const visitedByRule = new Map();
- for (const rule of STATIC_ELEMENT_RULES) {
- const elements = document.querySelectorAll(rule.selector);
- visitedByRule.set(rule.id, elements.length);
- for (const el of elements) {
- const tag = el.tagName.toLowerCase();
- const style = window.getComputedStyle(el);
- for (const f of runElementCheck(rule.id, () => rule.run(el, tag, style, window, customPropMap))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
- }
-
- if (isFullPage(html)) {
- const runPageCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
- : callback();
- for (const f of runPageCheck('typography-rules', () => checkStaticPageTypography(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('repeated-section-kickers', () => checkRepeatedSectionKickersFromDoc(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('layout-rules', () => checkPageLayout(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('skipped-heading', () => checkPageQualityFromDoc(document))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('html-patterns', () => checkHtmlPatterns(html).filter(item =>
- item.id !== 'bounce-easing' && item.id !== 'layout-transition'
- ))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
-
- return findings;
-}
-
-export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -1,189 +0,0 @@
-function sanitizeScreenshotClip(clip, viewport) {
- if (!clip) return null;
- const x = Math.max(0, Math.floor(clip.x || 0));
- const y = Math.max(0, Math.floor(clip.y || 0));
- const width = Math.min(
- Math.max(1, Math.ceil(clip.width || 0)),
- Math.max(1, viewport?.width || 1600),
- );
- const height = Math.min(
- Math.max(1, Math.ceil(clip.height || 0)),
- 320,
- );
- if (width < 1 || height < 1) return null;
- return { x, y, width, height };
-}
-
-async function compareScreenshotContrast(page, beforeBase64, afterBase64, candidate) {
- return page.evaluate(async ({ beforeBase64, afterBase64, candidate }) => {
- const loadImage = (base64) => new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = () => reject(new Error('Could not decode contrast screenshot'));
- img.src = `data:image/png;base64,${base64}`;
- });
- const [before, after] = await Promise.all([loadImage(beforeBase64), loadImage(afterBase64)]);
- const width = Math.min(before.width, after.width);
- const height = Math.min(before.height, after.height);
- if (width < 1 || height < 1) return null;
-
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return null;
-
- ctx.drawImage(before, 0, 0, width, height);
- const beforePixels = ctx.getImageData(0, 0, width, height).data;
- ctx.clearRect(0, 0, width, height);
- ctx.drawImage(after, 0, 0, width, height);
- const afterPixels = ctx.getImageData(0, 0, width, height).data;
-
- const luminance = ({ r, g, b }) => {
- const convert = c => {
- const v = c / 255;
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
- };
- return 0.2126 * convert(r) + 0.7152 * convert(g) + 0.0722 * convert(b);
- };
- const ratio = (a, b) => {
- const l1 = luminance(a);
- const l2 = luminance(b);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
- };
-
- const cssTextColor = candidate.textColor && !candidate.preferRenderedForeground
- ? {
- r: candidate.textColor.r,
- g: candidate.textColor.g,
- b: candidate.textColor.b,
- }
- : null;
- const ratios = [];
- let glyphPixels = 0;
- let strongestDelta = 0;
- for (let i = 0; i < beforePixels.length; i += 4) {
- const delta = Math.abs(beforePixels[i] - afterPixels[i])
- + Math.abs(beforePixels[i + 1] - afterPixels[i + 1])
- + Math.abs(beforePixels[i + 2] - afterPixels[i + 2])
- + Math.abs(beforePixels[i + 3] - afterPixels[i + 3]);
- strongestDelta = Math.max(strongestDelta, delta);
- if (delta < 10) continue;
- glyphPixels++;
- const fg = cssTextColor || {
- r: beforePixels[i],
- g: beforePixels[i + 1],
- b: beforePixels[i + 2],
- };
- const bg = {
- r: afterPixels[i],
- g: afterPixels[i + 1],
- b: afterPixels[i + 2],
- };
- ratios.push(ratio(fg, bg));
- }
-
- if (ratios.length < 8) {
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: null,
- p10Ratio: null,
- medianRatio: null,
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: ratios[0],
- p10Ratio: pick(10),
- medianRatio: pick(50),
- };
- }, { beforeBase64, afterBase64, candidate });
-}
-
-async function captureVisualContrastCandidate(page, candidate, viewport) {
- const clip = sanitizeScreenshotClip(candidate.clip, viewport);
- if (!clip) return null;
-
- const beforeBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- const token = `impeccable-contrast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- const applied = await page.evaluate(({ selector, token, backgroundClipText }) => {
- let el;
- try {
- el = document.querySelector(selector);
- } catch {
- return false;
- }
- if (!el) return false;
- let style = document.getElementById('impeccable-visual-contrast-hide-style');
- if (!style) {
- style = document.createElement('style');
- style.id = 'impeccable-visual-contrast-hide-style';
- style.textContent = [
- '[data-impeccable-visual-contrast-target] {',
- ' color: transparent !important;',
- ' -webkit-text-fill-color: transparent !important;',
- ' text-shadow: none !important;',
- '}',
- '[data-impeccable-visual-contrast-target][data-impeccable-bgclip-text="true"] {',
- ' background-image: none !important;',
- '}',
- ].join('\n');
- document.head.appendChild(style);
- }
- el.setAttribute('data-impeccable-visual-contrast-target', token);
- if (backgroundClipText) el.setAttribute('data-impeccable-bgclip-text', 'true');
- return true;
- }, {
- selector: candidate.selector,
- token,
- backgroundClipText: candidate.backgroundClipText,
- });
- if (!applied) return null;
-
- let afterBase64;
- try {
- afterBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- } finally {
- await page.evaluate(({ selector }) => {
- try {
- const el = document.querySelector(selector);
- if (el) {
- el.removeAttribute('data-impeccable-visual-contrast-target');
- el.removeAttribute('data-impeccable-bgclip-text');
- }
- } catch {
- // Ignore invalid or stale selectors during cleanup.
- }
- }, { selector: candidate.selector }).catch(() => {});
- }
-
- const metrics = await compareScreenshotContrast(page, beforeBase64, afterBase64, candidate);
- if (!metrics || !Number.isFinite(metrics.p10Ratio) || metrics.glyphPixels < 8) return null;
- const measuredRatio = metrics.p10Ratio;
- if (measuredRatio >= candidate.threshold) return null;
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const reasonLabel = (candidate.reasons || []).slice(0, 3).join(', ') || 'visual background';
- return {
- id: 'low-contrast',
- snippet: `pixel contrast ${measuredRatio.toFixed(1)}:1 median ${metrics.medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) on ${reasonLabel}${textLabel}`,
- };
-}
-
-export {
- sanitizeScreenshotClip,
- compareScreenshotContrast,
- captureVisualContrastCandidate,
-};
@@ -1,12 +0,0 @@
-import { getAntipattern } from './registry/antipatterns.mjs';
-
-function getAP(id) {
- return getAntipattern(id);
-}
-
-function finding(id, filePath, snippet, line = 0) {
- const ap = getAP(id);
- return { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', file: filePath, line, snippet };
-}
-
-export { getAP, finding };
@@ -1,198 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-// ---------------------------------------------------------------------------
-// File walker
-// ---------------------------------------------------------------------------
-
-const SKIP_DIRS = new Set([
- 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
- '.svelte-kit', '__pycache__', '.turbo', '.vercel',
-]);
-
-const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
- '.jsx', '.tsx', '.js', '.ts',
- '.vue', '.svelte', '.astro',
-]);
-
-const HTML_EXTENSIONS = new Set(['.html', '.htm']);
-
-function walkDir(dir) {
- const files = [];
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
- for (const entry of entries) {
- if (SKIP_DIRS.has(entry.name)) continue;
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) files.push(...walkDir(full));
- else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
- }
- return files;
-}
-
-
-// ---------------------------------------------------------------------------
-// Import graph (multi-file awareness)
-// ---------------------------------------------------------------------------
-
-function resolveImport(specifier, fromDir, fileSet) {
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
- const base = path.resolve(fromDir, specifier);
- if (fileSet.has(base)) return base;
- for (const ext of SCANNABLE_EXTENSIONS) {
- const withExt = base + ext;
- if (fileSet.has(withExt)) return withExt;
- }
- // index file convention
- for (const ext of SCANNABLE_EXTENSIONS) {
- const indexFile = path.join(base, 'index' + ext);
- if (fileSet.has(indexFile)) return indexFile;
- }
- return null;
-}
-
-function buildImportGraph(files) {
- const fileSet = new Set(files);
- const graph = new Map();
-
- for (const file of files) {
- const content = fs.readFileSync(file, 'utf-8');
- const dir = path.dirname(file);
- const imports = new Set();
-
- // ES imports: import ... from '...' and import '...'
- const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
- let m;
- while ((m = esRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // CSS @import
- const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
- while ((m = cssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // SCSS @use / @forward
- const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
- while ((m = scssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- graph.set(file, imports);
- }
- return graph;
-}
-
-// ---------------------------------------------------------------------------
-// Framework dev server detection
-// ---------------------------------------------------------------------------
-
-const FRAMEWORK_CONFIGS = [
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /next/i } },
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-sveltekit-page', value: null } },
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /@vite\/client/ } },
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /astro/i } },
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
- portRe: /"port"\s*:\s*(\d+)/,
- fingerprint: { body: /ng-version/i } },
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
-];
-
-function detectFrameworkConfig(dir) {
- let entries;
- try { entries = fs.readdirSync(dir); } catch { return null; }
- const entrySet = new Set(entries);
-
- for (const cfg of FRAMEWORK_CONFIGS) {
- const match = cfg.files.find(f => entrySet.has(f));
- if (!match) continue;
-
- const configPath = path.join(dir, match);
- let port = cfg.defaultPort;
- try {
- const content = fs.readFileSync(configPath, 'utf-8');
- const portMatch = content.match(cfg.portRe);
- if (portMatch) port = parseInt(portMatch[1], 10);
- } catch { /* use default */ }
-
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
- }
- return null;
-}
-
-/**
- * Check if a port is listening and optionally verify it matches the expected framework.
- * Returns { listening: true, matched: true/false } or { listening: false }.
- */
-async function isPortListening(port, fingerprint = null) {
- if (!fingerprint) {
- // Simple TCP probe fallback
- const net = await import('node:net');
- return new Promise((resolve) => {
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
- sock.setTimeout(500);
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
- sock.on('error', () => resolve({ listening: false }));
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
- });
- }
-
- // HTTP probe with fingerprint matching
- try {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 2000);
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
- clearTimeout(timeout);
-
- // Check header fingerprint
- if (fingerprint.header) {
- const val = res.headers.get(fingerprint.header);
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
- return { listening: true, matched: true };
- }
- }
-
- // Check body fingerprint
- if (fingerprint.body) {
- const body = await res.text();
- if (fingerprint.body.test(body)) {
- return { listening: true, matched: true };
- }
- }
-
- // Port is listening but doesn't match the expected framework
- return { listening: true, matched: false };
- } catch {
- return { listening: false };
- }
-}
-
-export {
- SKIP_DIRS,
- SCANNABLE_EXTENSIONS,
- HTML_EXTENSIONS,
- walkDir,
- resolveImport,
- buildImportGraph,
- FRAMEWORK_CONFIGS,
- detectFrameworkConfig,
- isPortListening,
-};
@@ -1,166 +0,0 @@
-function profileNow() {
- return typeof performance !== 'undefined' && performance.now
- ? performance.now()
- : Date.now();
-}
-
-function createDetectorProfile() {
- return { events: [] };
-}
-
-function recordProfileEvent(profile, event) {
- if (!profile) return;
- const normalized = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- ms: Number.isFinite(event.ms) ? event.ms : 0,
- findings: Number.isFinite(event.findings) ? event.findings : 0,
- };
- if (event.detail) normalized.detail = event.detail;
- if (Array.isArray(event.findingIds) && event.findingIds.length) {
- normalized.findingIds = event.findingIds;
- }
- if (typeof profile === 'function') {
- profile(normalized);
- } else if (typeof profile.record === 'function') {
- profile.record(normalized);
- } else if (Array.isArray(profile.events)) {
- profile.events.push(normalized);
- } else if (Array.isArray(profile)) {
- profile.push(normalized);
- }
-}
-
-function extractFindingIds(findings) {
- if (!Array.isArray(findings) || findings.length === 0) return [];
- return [...new Set(findings.map(f => f?.id || f?.type || f?.antipattern).filter(Boolean))];
-}
-
-function profileFindings(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-function profileStep(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-async function profileFindingsAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = await callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-async function profileStepAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return await callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-function percentile(sortedValues, pct) {
- if (!sortedValues.length) return 0;
- const idx = Math.min(
- sortedValues.length - 1,
- Math.max(0, Math.ceil((pct / 100) * sortedValues.length) - 1),
- );
- return sortedValues[idx];
-}
-
-function summarizeDetectorProfile(profile) {
- const events = Array.isArray(profile)
- ? profile
- : (Array.isArray(profile?.events) ? profile.events : []);
- const groups = new Map();
- for (const event of events) {
- const key = [
- event.engine || 'unknown',
- event.phase || 'unknown',
- event.ruleId || 'unknown',
- event.target || '',
- ].join('\u0000');
- let group = groups.get(key);
- if (!group) {
- group = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- calls: 0,
- totalMs: 0,
- findings: 0,
- samples: [],
- };
- groups.set(key, group);
- }
- const ms = Number.isFinite(event.ms) ? event.ms : 0;
- group.calls += 1;
- group.totalMs += ms;
- group.findings += Number.isFinite(event.findings) ? event.findings : 0;
- group.samples.push(ms);
- }
- return [...groups.values()]
- .map(group => {
- const samples = group.samples.sort((a, b) => a - b);
- return {
- engine: group.engine,
- phase: group.phase,
- ruleId: group.ruleId,
- target: group.target,
- calls: group.calls,
- totalMs: Number(group.totalMs.toFixed(3)),
- avgMs: Number((group.totalMs / group.calls).toFixed(3)),
- p50: Number(percentile(samples, 50).toFixed(3)),
- p95: Number(percentile(samples, 95).toFixed(3)),
- findings: group.findings,
- };
- })
- .sort((a, b) => b.totalMs - a.totalMs);
-}
-
-export {
- profileNow,
- createDetectorProfile,
- recordProfileEvent,
- extractFindingIds,
- profileFindings,
- profileStep,
- profileFindingsAsync,
- profileStepAsync,
- percentile,
- summarizeDetectorProfile,
-};
@@ -1,278 +0,0 @@
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-const RULE_ENGINE_SUPPORT = {
- regex: new Set(['source', 'page-analyzer']),
- 'static-html': new Set(['element', 'page']),
- browser: new Set(['element', 'page', 'layout']),
- visual: new Set(['visual-contrast']),
-};
-
-function getAntipattern(id) {
- return ANTIPATTERNS.find(rule => rule.id === id);
-}
-
-function getRulesForCategory(category) {
- return ANTIPATTERNS.filter(rule => rule.category === category);
-}
-
-function getRuleEngineSupport(engine) {
- return RULE_ENGINE_SUPPORT[engine] || new Set();
-}
-
-export {
- ANTIPATTERNS,
- RULE_ENGINE_SUPPORT,
- getAntipattern,
- getRulesForCategory,
- getRuleEngineSupport,
-};
@@ -1,1948 +0,0 @@
-import {
- BORDER_SAFE_TAGS,
- GENERIC_FONTS,
- KNOWN_SERIF_FONTS,
- OVERUSED_FONTS,
- SAFE_TAGS,
- WCAG_LARGE_BOLD_TEXT_PX,
- WCAG_LARGE_TEXT_PX,
- isBrandFontOnOwnDomain,
-} from '../shared/constants.mjs';
-import {
- colorToHex,
- contrastRatio,
- getHue,
- hasChroma,
- isNeutralColor,
- parseGradientColors,
- parseRgb,
- relativeLuminance,
-} from '../shared/color.mjs';
-
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-export {
- checkBorders,
- isEmojiOnlyText,
- checkColors,
- isCardLikeFromProps,
- checkIconTile,
- resolveSerif,
- checkItalicSerif,
- isAccentColor,
- checkHeroEyebrow,
- checkRepeatedSectionKickers,
- checkMotion,
- checkGlow,
- checkHtmlPatterns,
- readOwnBackgroundColor,
- resolveBackground,
- resolveGradientStops,
- parseRadiusToPx,
- resolveBorderRadiusPx,
- checkElementBordersDOM,
- checkElementColorsDOM,
- checkElementIconTileDOM,
- checkElementItalicSerifDOM,
- checkElementHeroEyebrowDOM,
- buildCustomPropMap,
- resolveVarRefs,
- oklchToRgb,
- parseAnyColor,
- parseColorResolved,
- cleanInlineText,
- isRepeatedKickerCandidate,
- collectRepeatedSectionKickerCandidates,
- checkRepeatedSectionKickersDOM,
- checkElementMotionDOM,
- checkElementGlowDOM,
- checkElementAIPaletteDOM,
- resolveFontSizePx,
- resolveLengthPx,
- checkQuality,
- checkElementQualityDOM,
- checkPageQualityFromDoc,
- checkPageQualityDOM,
- checkElementQuality,
- checkElementBorders,
- checkElementColors,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementHeroEyebrow,
- checkRepeatedSectionKickersFromDoc,
- checkElementMotion,
- checkElementGlow,
- checkTypography,
- isCardLikeDOM,
- checkLayout,
- checkPageTypography,
- isCardLike,
- checkPageLayout,
-};
@@ -1,124 +0,0 @@
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-export {
- isNeutralColor,
- parseRgb,
- relativeLuminance,
- contrastRatio,
- parseGradientColors,
- hasChroma,
- getHue,
- colorToHex,
-};
@@ -1,101 +0,0 @@
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-export {
- SAFE_TAGS,
- BORDER_SAFE_TAGS,
- OVERUSED_FONTS,
- GOOGLE_DOMAINS,
- VERCEL_DOMAINS,
- GITHUB_DOMAINS,
- BRAND_FONT_DOMAINS,
- isBrandFontOnOwnDomain,
- GENERIC_FONTS,
- WCAG_LARGE_TEXT_PX,
- WCAG_LARGE_BOLD_TEXT_PX,
- KNOWN_SERIF_FONTS,
-};
@@ -1,7 +0,0 @@
-/** Check if content looks like a full page (not a component/partial) */
-function isFullPage(content) {
- const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
- return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
-}
-
-export { isFullPage };
@@ -1,110 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-export const IMPECCABLE_DIR = '.impeccable';
-export const LIVE_DIR = 'live';
-export const CRITIQUE_DIR = 'critique';
-
-export function getImpeccableDir(cwd = process.cwd()) {
- return path.join(cwd, IMPECCABLE_DIR);
-}
-
-export function getDesignSidecarPath(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), 'design.json');
-}
-
-export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {
- const candidates = [
- getDesignSidecarPath(cwd),
- path.join(cwd, 'DESIGN.json'),
- ];
- const contextLegacy = path.join(contextDir, 'DESIGN.json');
- if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
- return candidates;
-}
-
-export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
- return firstExisting(getDesignSidecarCandidates(cwd, contextDir));
-}
-
-export function getLiveDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), LIVE_DIR);
-}
-
-export function getLiveConfigPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'config.json');
-}
-
-export function getLegacyLiveConfigPath(scriptsDir) {
- return path.join(scriptsDir, 'config.json');
-}
-
-export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {
- if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
- const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
- return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
- }
- const primary = getLiveConfigPath(cwd);
- if (fs.existsSync(primary)) return primary;
- if (scriptsDir) {
- const legacy = getLegacyLiveConfigPath(scriptsDir);
- if (fs.existsSync(legacy)) return legacy;
- }
- return primary;
-}
-
-export function getLiveServerPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'server.json');
-}
-
-export function getLegacyLiveServerPath(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live.json');
-}
-
-export function readLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try {
- return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };
- } catch {
- /* try next */
- }
- }
- return null;
-}
-
-export function writeLiveServerInfo(cwd = process.cwd(), info) {
- const filePath = getLiveServerPath(cwd);
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- fs.writeFileSync(filePath, JSON.stringify(info));
- return filePath;
-}
-
-export function removeLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try { fs.unlinkSync(filePath); } catch {}
- }
-}
-
-export function getLiveSessionsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'sessions');
-}
-
-export function getLegacyLiveSessionsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'sessions');
-}
-
-export function getLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'annotations');
-}
-
-export function getCritiqueDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), CRITIQUE_DIR);
-}
-
-export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'annotations');
-}
-
-function firstExisting(paths) {
- return paths.find((filePath) => fs.existsSync(filePath)) || null;
-}
@@ -1,69 +0,0 @@
-/**
- * Decide whether a given file is "generated" (regenerated by a build step,
- * unsafe to write variants into) or "source" (safe to edit, changes persist).
- *
- * Why this matters: when the user picks an element on a page whose underlying
- * file is regenerated by a build step (e.g. `scripts/build-sub-pages.js`
- * rewriting `public/docs/*.html`), writing variants or accepted changes into
- * that file is silent data loss — the next build wipes them.
- *
- * Signals, in order of reliability:
- * 1. Git check-ignore: gitignored files are assumed generated.
- * 2. File-header markers ("GENERATED", "DO NOT EDIT", "AUTO-GENERATED")
- * within the first ~300 characters — catches non-git projects.
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-
-const HEADER_SCAN_BYTES = 300;
-const HEADER_MARKERS = [
- /@generated\b/i,
- /\bGENERATED\s+FILE\b/,
- /\bAUTO-?GENERATED\b/i,
- /\bDO\s+NOT\s+EDIT\b/i,
-];
-
-/**
- * @param {string} filePath - absolute or cwd-relative path
- * @param {object} [options]
- * @param {string} [options.cwd] - project root (defaults to process.cwd())
- */
-export function isGeneratedFile(filePath, options = {}) {
- const cwd = options.cwd || process.cwd();
- const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
-
- if (isGitIgnored(absPath, cwd)) return true;
- if (hasGeneratedHeader(absPath)) return true;
- return false;
-}
-
-function isGitIgnored(absPath, cwd) {
- try {
- execSync(`git check-ignore --quiet ${JSON.stringify(absPath)}`, {
- cwd,
- stdio: 'ignore',
- });
- return true; // exit 0 = ignored
- } catch (err) {
- // Exit code 1 = not ignored. Exit code 128 = not a git repo or other error.
- // In both cases, treat as "not known to be ignored."
- return false;
- }
-}
-
-function hasGeneratedHeader(absPath) {
- let fd;
- try {
- fd = fs.openSync(absPath, 'r');
- const buf = Buffer.alloc(HEADER_SCAN_BYTES);
- const bytesRead = fs.readSync(fd, buf, 0, HEADER_SCAN_BYTES, 0);
- const head = buf.slice(0, bytesRead).toString('utf-8');
- return HEADER_MARKERS.some((re) => re.test(head));
- } catch {
- return false;
- } finally {
- if (fd !== undefined) { try { fs.closeSync(fd); } catch {} }
- }
-}
@@ -1,595 +0,0 @@
-/**
- * CLI helper: deterministic accept/discard of variant sessions.
- *
- * Usage:
- * node live-accept.mjs --id SESSION_ID --discard
- * node live-accept.mjs --id SESSION_ID --variant N
- *
- * For discard: removes the entire variant wrapper and restores the original.
- * For accept: replaces the wrapper with the chosen variant's content. If the
- * session had a colocated <style> block, it's preserved with carbonize markers
- * for a background agent to integrate into the project's CSS.
- *
- * Output: JSON to stdout.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-export async function acceptCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-accept.mjs [options]
-
-Deterministic accept/discard for live variant sessions.
-
-Modes:
- --discard Remove variants, restore original
- --variant N Accept variant N, discard the rest
-
-Required:
- --id SESSION_ID Session ID of the variant wrapper
-
-Output (JSON):
- { handled, file, carbonize }`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const variantNum = argVal(args, '--variant');
- const paramValuesRaw = argVal(args, '--param-values');
- const isDiscard = args.includes('--discard');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }
-
- let paramValues = null;
- if (paramValuesRaw) {
- try { paramValues = JSON.parse(paramValuesRaw); }
- catch { paramValues = null; } // malformed blob: skip the comment rather than failing the accept
- }
-
- // Find the file containing this session's markers
- const found = findSessionFile(id, process.cwd());
- if (!found) {
- console.log(JSON.stringify({ handled: false, error: 'Session markers not found for id: ' + id }));
- process.exit(0);
- }
-
- const { file: targetFile, content, lines } = found;
- const relFile = path.relative(process.cwd(), targetFile);
-
- // Bail if the session lives in a generated file. The agent manually wrote
- // the wrapper there for preview, and is responsible for writing the
- // accepted variant to true source (or cleaning up on discard). See
- // "Handle fallback" in live.md.
- if (isGeneratedFile(targetFile, { cwd: process.cwd() })) {
- console.log(JSON.stringify({
- handled: false,
- mode: 'fallback',
- file: relFile,
- hint: 'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.',
- }));
- process.exit(0);
- }
-
- if (isDiscard) {
- const result = handleDiscard(id, lines, targetFile);
- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));
- } else {
- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);
- // Single-line attention-grabber when cleanup is required. The full
- // five-step checklist lives in reference/live.md (loaded once per
- // session); repeating it per-event would waste tokens.
- if (result.carbonize) {
- result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + relFile + '. See reference/live.md "Required after accept".';
- }
- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));
- }
-}
-
-// ---------------------------------------------------------------------------
-// Discard
-// ---------------------------------------------------------------------------
-
-function handleDiscard(id, lines, targetFile) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const original = extractOriginal(lines, block);
- const isJsx = detectCommentSyntax(targetFile).open === '{/*';
- const replaceRange = expandReplaceRange(block, lines, isJsx);
-
- // Restore at the line we're actually replacing FROM, not the marker line.
- // For JSX wrappers the marker comments live INSIDE the outer `<div>`, so
- // `block.start` sits 2 spaces deeper than the original element. Using that
- // as the deindent base would push the restored content 2 spaces too far
- // right on every JSX/TSX session. `replaceRange.start` is the outer wrapper
- // line, which is at the original element's indent for both HTML and JSX.
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
- const restored = deindentContent(original, indent);
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...restored,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
- return {};
-}
-
-// ---------------------------------------------------------------------------
-// Accept
-// ---------------------------------------------------------------------------
-
-function handleAccept(id, variantNum, lines, targetFile, paramValues) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const commentSyntax = detectCommentSyntax(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- // Anchor indent on the line we're replacing FROM (the outer wrapper),
- // not on `block.start` — for JSX that's the marker comment 2 spaces
- // deeper than the original element. See handleDiscard for the full
- // rationale.
- const replaceRange = expandReplaceRange(block, lines, isJsx);
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
-
- // Extract the chosen variant's inner content
- const variantContent = extractVariant(lines, block, variantNum);
- if (!variantContent) return { handled: false, error: 'Variant ' + variantNum + ' not found' };
-
- // Extract CSS block if present
- const cssContent = extractCss(lines, block, id);
-
- // Check if carbonizing is needed:
- // - CSS block exists, OR
- // - variant HTML contains helper classes/attributes that need cleanup
- const variantText = variantContent.join('\n');
- const hasHelperAttrs = variantText.includes('data-impeccable-variant');
- const needsCarbonize = !!(cssContent || hasHelperAttrs);
-
- // Build the replacement
- const restored = deindentContent(variantContent, indent);
- const replacement = [];
-
- if (cssContent) {
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
- // JSX targets need the CSS body wrapped in a template literal so that the
- // `{` and `}` in CSS rules don't get parsed as JSX expressions.
- replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
- // Re-indent CSS content to match
- for (const cssLine of cssContent) {
- replacement.push(indent + cssLine.trimStart());
- }
- replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
- if (paramValues && Object.keys(paramValues).length > 0) {
- // Preserve the user's knob positions for the carbonize-cleanup agent
- // to bake into the final CSS when it collapses scoped rules.
- replacement.push(indent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close);
- }
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close);
- }
-
- // Keep the `@scope ([data-impeccable-variant="N"])` selectors in the
- // carbonize CSS block working visually by re-wrapping the accepted content
- // in a data-impeccable-variant="N" div with `display: contents` (so layout
- // isn't affected). The carbonize agent strips this attribute + wrapper when
- // it moves the CSS to a proper stylesheet.
- //
- // Style attribute syntax has to follow the host file's flavor — JSX files
- // need the object form, otherwise React 19 throws "Failed to set indexed
- // property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
- if (cssContent) {
- const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
- replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
- replacement.push(...restored);
- replacement.push(indent + '</div>');
- } else {
- replacement.push(...restored);
- }
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...replacement,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- return { carbonize: needsCarbonize };
-}
-
-// ---------------------------------------------------------------------------
-// Parsing helpers
-// ---------------------------------------------------------------------------
-
-/**
- * Find the start/end marker lines for a session.
- * Returns { start, end } (0-indexed line numbers) or null.
- */
-function findMarkerBlock(id, lines) {
- let start = -1;
- let end = -1;
- const startPattern = 'impeccable-variants-start ' + id;
- const endPattern = 'impeccable-variants-end ' + id;
-
- for (let i = 0; i < lines.length; i++) {
- if (start === -1 && lines[i].includes(startPattern)) start = i;
- if (lines[i].includes(endPattern)) { end = i; break; }
- }
-
- return (start !== -1 && end !== -1) ? { start, end } : null;
-}
-
-/**
- * Compute the line range to REPLACE (vs. just the marker range to extract
- * from). For JSX/TSX wrappers, live-wrap places the marker comments INSIDE
- * the `<div data-impeccable-variants="ID">` outer wrapper so the picked
- * element's JSX slot keeps a single child — a Fragment `<></>` would have
- * solved the multi-sibling case but failed inside `asChild` / cloneElement
- * parents with "Invalid prop supplied to React.Fragment".
- *
- * That means the marker block is enclosed by the wrapper `<div>` opener
- * (with `data-impeccable-variants="ID"`) and its matching `</div>`. We
- * walk back to the opener and forward to the closer so accept/discard
- * remove the entire scaffold, not just the inner markers.
- *
- * Marker lines themselves stay where they were so extractOriginal /
- * extractVariant / extractCss continue to walk the same range.
- */
-function expandReplaceRange(block, lines, isJsx) {
- if (!isJsx) return { start: block.start, end: block.end };
-
- let { start, end } = block;
-
- // Walk back for the wrapper `<div data-impeccable-variants="..."` opener.
- // The attr may sit on a continuation line of a multi-line opening tag, so
- // also walk to the line that actually contains `<div`.
- for (let i = start - 1; i >= Math.max(0, start - 12); i--) {
- if (/data-impeccable-variants=/.test(lines[i])) {
- let opener = i;
- while (opener > 0 && !/<div\b/.test(lines[opener])) opener--;
- start = opener;
- break;
- }
- }
-
- // Walk forward to the matching `</div>` by div-depth tracking from the
- // wrapper opener. Operate on JOINED text instead of per-line: a
- // multi-line self-closing JSX `<div\n className="spacer"\n/>` would
- // fool per-line regex tracking (the `<div` line matches openRe but the
- // `/>` line never matches selfCloseRe since it needs `<div` on the same
- // line). That left depth permanently over-counted and the wrapper's
- // outer `</div>` orphaned after accept/discard. Single regex with
- // `[^>]*?` (which spans newlines in JS) handles either form correctly.
- const joined = lines.slice(start).join('\n');
- // Match either `<div … />` (self-close, group 1 is `/`), `<div … >`
- // (open, group 1 is empty), or `</div>`.
- const tagRe = /<div\b[^>]*?(\/?)>|<\/div\s*>/g;
- let depth = 0;
- let m;
- while ((m = tagRe.exec(joined)) !== null) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && m[1] === '/';
- if (isClose) depth--;
- else if (!isSelfClose) depth++;
- if (depth <= 0) {
- // m.index is offset within `joined`; convert back to a file line.
- const linesBefore = joined.slice(0, m.index + m[0].length).split('\n').length - 1;
- const candidateEnd = start + linesBefore;
- if (candidateEnd >= end) {
- end = candidateEnd;
- break;
- }
- }
- }
-
- return { start, end };
-}
-
-/**
- * Join wrapper lines into a single string with `<style>` elements removed so
- * marker matching and div-depth tracking aren't confused by:
- * - CSS `@scope ([data-impeccable-variant="N"])` strings that look like the
- * HTML marker we're searching for
- * - JSX self-closing `<style ... />` (no separate `</style>` to close on)
- * - Same-line `<style>…</style>` blocks
- * - Multi-line `<style>\n…\n</style>` blocks
- */
-function stripStyleAndJoin(lines, block) {
- const out = [];
- let inStyle = false;
- for (let i = block.start; i <= block.end; i++) {
- let line = lines[i];
-
- if (!inStyle) {
- // Strip any complete <style> elements on this line (self-closed or
- // same-line-closed), including their body content.
- line = line
- .replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/g, '')
- .replace(/<style\b[^>]*\/\s*>/g, '');
-
- // If a <style> opener remains (multi-line body starts here), strip from
- // the opener to end-of-line and flip into skip mode.
- const openerIdx = line.search(/<style\b/);
- if (openerIdx !== -1) {
- line = line.slice(0, openerIdx);
- inStyle = true;
- }
- out.push(line);
- } else {
- // In multi-line style body; drop everything until we see </style>.
- const closeIdx = line.search(/<\/style\s*>/);
- if (closeIdx !== -1) {
- inStyle = false;
- out.push(line.slice(closeIdx).replace(/<\/style\s*>/, ''));
- }
- // else: skip line entirely
- }
- }
- return out.join('\n');
-}
-
-/**
- * Find the inner content of `<TAG ...attrMatch...>…</TAG>` inside `text`,
- * handling nested same-tag elements via depth counting. `attrMatch` is a
- * regex source fragment that must appear inside the opener tag.
- * Returns the inner string (may be empty), or null if not found.
- */
-function extractInnerByAttr(text, attrMatch) {
- const openerRe = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*' + attrMatch + '[^>]*>');
- const openMatch = text.match(openerRe);
- if (!openMatch) return null;
-
- const tagName = openMatch[1];
- const innerStart = openMatch.index + openMatch[0].length;
-
- // Match any opener or closer of this tag name after innerStart.
- // (Does not match self-closing <TAG … />, which doesn't contribute to depth.)
- const tagRe = new RegExp('<(?:/)?' + tagName + '\\b[^>]*>', 'g');
- tagRe.lastIndex = innerStart;
-
- let depth = 1;
- let m;
- while ((m = tagRe.exec(text))) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && /\/\s*>$/.test(m[0]);
- if (isClose) {
- depth--;
- if (depth === 0) return text.slice(innerStart, m.index);
- } else if (!isSelfClose) {
- depth++;
- }
- }
- return null;
-}
-
-/**
- * Extract the original element content from within the variant wrapper.
- * Returns an array of lines.
- */
-function extractOriginal(lines, block) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="original"');
- if (inner === null) return [];
- return inner.split('\n');
-}
-
-/**
- * Extract a specific variant's inner content (stripping the wrapper div).
- * Returns an array of lines, or null if not found.
- */
-function extractVariant(lines, block, variantNum) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + variantNum + '"');
- if (inner === null) return null;
- const result = inner.split('\n');
- // Collapse a lone empty leading/trailing line (common after string splice).
- while (result.length > 1 && result[0].trim() === '') result.shift();
- while (result.length > 1 && result[result.length - 1].trim() === '') result.pop();
- return result.length > 0 ? result : null;
-}
-
-/**
- * Extract the colocated <style> block content (between the style tags).
- * Returns an array of CSS lines, or null if no style block found.
- *
- * Handles three shapes of `<style data-impeccable-css="ID" ...>`:
- * 1. Self-closing: `<style ... />` — no body; return null (nothing to carbonize).
- * 2. Same-line open+close: `<style>...</style>` — return the inner content.
- * 3. Multi-line: `<style>` on one line, `</style>` on a later line — return
- * the lines between them.
- */
-function extractCss(lines, block, id) {
- const styleAttr = 'data-impeccable-css="' + id + '"';
- let inStyle = false;
- const content = [];
-
- for (let i = block.start; i <= block.end; i++) {
- const line = lines[i];
-
- if (!inStyle && line.includes(styleAttr)) {
- // Self-closing: nothing to carbonize.
- if (/<style\b[^>]*\/\s*>/.test(line)) return null;
- // Same-line open + close: extract inner text.
- const sameLine = line.match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/);
- if (sameLine) {
- const inner = stripJsxTemplateWrap(sameLine[1]);
- return inner.length > 0 ? inner.split('\n') : null;
- }
- inStyle = true;
- continue; // skip the <style> opening tag
- }
-
- if (inStyle) {
- // Detect </style> anywhere on the line — JSX template-literal closes
- // (`}</style>`) put the close mid-line, and we don't want to absorb the
- // template-literal punctuation as CSS content.
- const closeIdx = line.indexOf('</style>');
- if (closeIdx !== -1) break;
- content.push(line);
- }
- }
-
- if (content.length === 0) return null;
- return stripJsxTemplateLines(content);
-}
-
-/**
- * Strip a JSX template-literal wrap (`{` … `}`) from CSS extracted out of a
- * `<style>` element in a JSX/TSX file. The agent may write the wrap with
- * `{` and `}` directly attached to the `<style>` tags, on their own lines,
- * or attached to the first/last CSS lines — all three are JSX-legal.
- *
- * Stripping is required because handleAccept re-wraps the CSS itself when
- * carbonizing. Without this, two consecutive accepts (or a previously-
- * accepted variants block being carbonized) would produce nested
- * `{` `{` … `}` `}`, which oxc rejects with "Expected `}` but found `@`".
- */
-function stripJsxTemplateLines(content) {
- const out = content.slice();
-
- // Drop any leading blank lines so we don't miss a `{` line buried below
- // them; same for trailing.
- while (out.length > 0 && out[0].trim() === '') out.shift();
- while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
- if (out.length === 0) return null;
-
- // Leading `{`: own line, or attached to the first CSS line.
- const firstTrim = out[0].trimStart();
- if (firstTrim === '{`') {
- out.shift();
- } else if (firstTrim.startsWith('{`')) {
- const idx = out[0].indexOf('{`');
- out[0] = out[0].slice(0, idx) + out[0].slice(idx + 2);
- if (out[0].trim() === '') out.shift();
- }
- if (out.length === 0) return null;
-
- // Trailing `` ` `` `}`: own line, or attached to the last CSS line.
- const lastIdx = out.length - 1;
- const lastTrim = out[lastIdx].trimEnd();
- if (lastTrim === '`}') {
- out.pop();
- } else if (lastTrim.endsWith('`}')) {
- const text = out[lastIdx];
- const idx = text.lastIndexOf('`}');
- out[lastIdx] = text.slice(0, idx) + text.slice(idx + 2);
- if (out[lastIdx].trim() === '') out.pop();
- }
-
- return out.length > 0 ? out : null;
-}
-
-function stripJsxTemplateWrap(text) {
- const lines = text.split('\n');
- const stripped = stripJsxTemplateLines(lines);
- return stripped ? stripped.join('\n') : '';
-}
-
-/**
- * De-indent content that was indented by live-wrap.mjs.
- * The wrap script adds `indent + ' '` (4 extra spaces) to each line.
- * We restore to just `indent` level.
- */
-function deindentContent(contentLines, baseIndent) {
- // Find the minimum indentation in the content to determine how much was added
- let minIndent = Infinity;
- for (const line of contentLines) {
- if (line.trim() === '') continue;
- const leadingSpaces = line.match(/^(\s*)/)[1].length;
- minIndent = Math.min(minIndent, leadingSpaces);
- }
- if (minIndent === Infinity) minIndent = 0;
-
- // Strip the extra indentation and re-add base indent
- return contentLines.map(line => {
- if (line.trim() === '') return '';
- return baseIndent + line.slice(minIndent);
- });
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- return { open: '<!--', close: '-->' };
-}
-
-// ---------------------------------------------------------------------------
-// File search (find the file containing session markers)
-// ---------------------------------------------------------------------------
-
-function findSessionFile(id, cwd) {
- const marker = 'impeccable-variants-start ' + id;
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, marker, seen, 0);
- if (result) {
- const content = fs.readFileSync(result, 'utf-8');
- return { file: result, content, lines: content.split('\n') };
- }
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth) {
- if (depth > 5) return null;
- let realDir;
- try { realDir = fs.realpathSync(dir); } catch { return null; }
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- if (!EXTENSIONS.includes(path.extname(entry.name).toLowerCase())) continue;
- const filePath = path.join(dir, entry.name);
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip */ }
- }
-
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
- if (result) return result;
- }
-
- return null;
-}
-
-// ---------------------------------------------------------------------------
-// Utilities
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-accept.mjs') || _running?.endsWith('live-accept.mjs/')) {
- acceptCli();
-}
-
-export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax };
@@ -1,123 +0,0 @@
-/**
- * Browser-side durable session helpers for Impeccable live mode.
- *
- * Kept separate from live-browser.js so recovery state can be tested without
- * booting the full overlay UI. Served before live-browser.js and attached to
- * window.__IMPECCABLE_LIVE_SESSION__.
- */
-(function (root) {
- 'use strict';
-
- function createLiveBrowserSessionState({ prefix, storage, idFactory }) {
- if (!prefix) throw new Error('prefix required');
- const store = storage || root.localStorage;
- const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };
- const sessionKey = prefix + '-session';
- const handledKey = sessionKey + '-handled';
- const scrollKey = sessionKey + '-scroll';
- let checkpointRevision = 0;
- const owner = makeId();
-
- function safeRead(key) {
- try { return store.getItem(key); } catch { return null; }
- }
-
- function safeWrite(key, value) {
- try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }
- }
-
- function safeRemove(key) {
- try { store.removeItem(key); } catch { /* unavailable storage */ }
- }
-
- function loadSession() {
- try {
- const raw = safeRead(sessionKey);
- if (!raw) return null;
- const parsed = JSON.parse(raw);
- if (Number.isInteger(parsed.checkpointRevision)) {
- checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);
- }
- return parsed;
- } catch { return null; }
- }
-
- function saveSession(session) {
- if (!session || !session.id) return;
- const payload = {
- ...session,
- checkpointRevision,
- };
- safeWrite(sessionKey, JSON.stringify(payload));
- }
-
- function clearSession() {
- safeRemove(sessionKey);
- }
-
- function nextCheckpointRevision() {
- checkpointRevision += 1;
- const existing = loadSession();
- if (existing?.id) saveSession(existing);
- return checkpointRevision;
- }
-
- function seedCheckpointRevision(value) {
- if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);
- return checkpointRevision;
- }
-
- function currentCheckpointRevision() {
- return checkpointRevision;
- }
-
- function markHandled(id) {
- if (!id) return;
- safeWrite(handledKey, id);
- }
-
- function isHandled(id) {
- return !!id && safeRead(handledKey) === id;
- }
-
- function clearHandled() {
- safeRemove(handledKey);
- }
-
- function writeScrollY(y) {
- safeWrite(scrollKey, String(y));
- }
-
- function readScrollY() {
- const raw = safeRead(scrollKey);
- if (raw == null) return null;
- const n = parseFloat(raw);
- return isFinite(n) ? n : null;
- }
-
- function clearScrollY() {
- safeRemove(scrollKey);
- }
-
- return {
- owner,
- sessionKey,
- handledKey,
- scrollKey,
- saveSession,
- loadSession,
- clearSession,
- nextCheckpointRevision,
- seedCheckpointRevision,
- currentCheckpointRevision,
- markHandled,
- isHandled,
- clearHandled,
- writeScrollY,
- readScrollY,
- clearScrollY,
- };
- }
-
- root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };
-})(typeof window !== 'undefined' ? window : globalThis);
@@ -1,4860 +0,0 @@
-/**
- * Impeccable Live Variant Mode — Browser Script
- *
- * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
- * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
- * before this code.
- *
- * UI: a single floating bar that morphs between three states —
- * configure (pick action + go), generating (progressive dots), and cycling
- * (prev/next + accept/discard). Feels like Spotlight, not a modal.
- */
-(function () {
- 'use strict';
- if (typeof window === 'undefined') return;
-
- // Guard against double-init. Bun's HTML loader may process the <script> tag
- // and create a bundled copy alongside the external load, or HMR may re-execute.
- // Check BEFORE reading token/port to catch all cases.
- if (window.__IMPECCABLE_LIVE_INIT__) return;
- window.__IMPECCABLE_LIVE_INIT__ = true;
-
- const TOKEN = window.__IMPECCABLE_TOKEN__;
- const PORT = window.__IMPECCABLE_PORT__;
- if (!TOKEN || !PORT) {
- window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
- return;
- }
-
- // ---------------------------------------------------------------------------
- // Design tokens
- // ---------------------------------------------------------------------------
-
- // Brand magenta is pinned to the site token (--color-accent in main.css)
- // so Accept / knobs / cycle-dots match the site's accent, not a washed
- // theme-adjusted one.
- const C = {
- brand: 'oklch(60% 0.25 350)',
- brandHov: 'oklch(52% 0.25 350)',
- brandSoft: 'oklch(60% 0.25 350 / 0.15)',
- ink: 'oklch(15% 0.01 350)',
- ash: 'oklch(55% 0 0)',
- paper: 'oklch(98% 0.005 350 / 0.92)',
- paperSolid:'oklch(98% 0.005 350)',
- mist: 'oklch(90% 0.01 350 / 0.6)',
- white: 'oklch(99% 0 0)',
- };
- const FONT = 'system-ui, -apple-system, sans-serif';
- const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
- // z-index: detect overlays use 99999, so our UI must be above them
- const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };
- const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
- const PREFIX = 'impeccable-live';
- const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
- prefix: PREFIX,
- storage: localStorage,
- idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),
- });
- if (!sessionState) {
- console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');
- window.__IMPECCABLE_LIVE_INIT__ = false;
- return;
- }
- const HIGHLIGHT_TRANSITION =
- 'top 140ms ' + EASE +
- ', left 140ms ' + EASE +
- ', width 140ms ' + EASE +
- ', height 140ms ' + EASE +
- ', opacity 150ms ease';
- const TOOLTIP_TRANSITION =
- 'top 140ms ' + EASE + ', left 140ms ' + EASE + ', opacity 150ms ease';
-
- const SKIP_TAGS = new Set([
- 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
- ]);
-
- // SVG icons stack above each chip label. All strokes use currentColor so the
- // icon recolors to C.brand when its chip is selected. 20x20 render, 24-viewBox,
- // 1.5 stroke — visually consistent with the Foundation grid on the homepage.
- const ICON_ATTRS = 'width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block"';
- const ICONS = {
- impeccable: `<svg ${ICON_ATTRS}><path d="M4 20l4-1L18 9l-3-3L5 16z"/><path d="M14 7l3 3"/></svg>`,
- bolder: `<svg ${ICON_ATTRS}><rect x="6" y="12" width="4" height="7" rx="0.5"/><rect x="14" y="5" width="4" height="14" rx="0.5"/></svg>`,
- quieter: `<svg ${ICON_ATTRS}><rect x="6" y="5" width="4" height="14" rx="0.5"/><rect x="14" y="12" width="4" height="7" rx="0.5"/></svg>`,
- distill: `<svg ${ICON_ATTRS}><path d="M4 5h16l-6 8v7l-4-2v-5z"/></svg>`,
- polish: `<svg ${ICON_ATTRS}><path d="M15 3l1 3 3 1-3 1-1 3-1-3-3-1 3-1z"/><path d="M7 13l0.6 1.8 1.8 0.6-1.8 0.6-0.6 1.8-0.6-1.8-1.8-0.6 1.8-0.6z"/></svg>`,
- typeset: `<svg ${ICON_ATTRS}><path d="M5 6h14" stroke-width="2.6"/><path d="M5 12h9" stroke-width="1.9"/><path d="M5 18h5" stroke-width="1.3"/></svg>`,
- colorize: `<svg ${ICON_ATTRS}><circle cx="9" cy="10" r="5"/><circle cx="15" cy="10" r="5"/><circle cx="12" cy="15" r="5"/></svg>`,
- layout: `<svg ${ICON_ATTRS}><rect x="3" y="4" width="8" height="16" rx="0.5"/><rect x="13" y="4" width="8" height="7" rx="0.5"/><rect x="13" y="13" width="8" height="7" rx="0.5"/></svg>`,
- adapt: `<svg ${ICON_ATTRS}><rect x="2.5" y="5" width="12" height="11" rx="1"/><line x1="2.5" y1="19" x2="14.5" y2="19"/><rect x="16.5" y="8" width="5" height="11" rx="1"/></svg>`,
- animate: `<svg ${ICON_ATTRS}><path d="M3 18c4-4 6-10 10-10"/><path d="M13 8c3 0 5 5 8 10"/><circle cx="13" cy="8" r="1.6" fill="currentColor" stroke="none"/></svg>`,
- delight: `<svg ${ICON_ATTRS}><path d="M12 3l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>`,
- overdrive: `<svg ${ICON_ATTRS}><path d="M13 3L5 13h5l-1 8 9-12h-6z"/></svg>`,
- };
-
- const ACTIONS = [
- { value: 'impeccable', label: 'Freeform' },
- { value: 'bolder', label: 'Bolder' },
- { value: 'quieter', label: 'Quieter' },
- { value: 'distill', label: 'Distill' },
- { value: 'polish', label: 'Polish' },
- { value: 'typeset', label: 'Typeset' },
- { value: 'colorize', label: 'Colorize' },
- { value: 'layout', label: 'Layout' },
- { value: 'adapt', label: 'Adapt' },
- { value: 'animate', label: 'Animate' },
- { value: 'delight', label: 'Delight' },
- { value: 'overdrive', label: 'Overdrive' },
- ];
-
- // ---------------------------------------------------------------------------
- // State
- // ---------------------------------------------------------------------------
-
- let state = 'IDLE';
- let hoveredElement = null;
- let selectedElement = null;
- let currentSessionId = null;
- let expectedVariants = 0;
- let arrivedVariants = 0;
- let visibleVariant = 0;
- let variantObserver = null;
- let hasProjectContext = false;
- let selectedAction = 'impeccable';
- let selectedCount = 3;
- const browserOwner = sessionState.owner;
- let checkpointTimer = null;
-
- // Scroll lock — holds window.scrollY at a fixed value while the session is
- // active, so HMR DOM patches and variant swaps can't drift the page. See
- // startScrollLock / stopScrollLock below.
- let scrollLockObserver = null;
- let scrollLockTargetY = null;
- let scrollLockRaf = null;
- let scrollLockAbort = null;
-
- // Dedicated key for scroll position — SEPARATE from LS_KEY so that
- // saveSession's state updates don't clobber a carefully-captured scrollY.
- // (Previously: saveSession wrote scrollY alongside state, so every call
- // during resume overwrote the pre-reload value with whatever the browser
- // had landed on, typically 0.)
- function writeScrollY(y) { sessionState.writeScrollY(y); }
- function readScrollY() { return sessionState.readScrollY(); }
- function clearScrollY() { sessionState.clearScrollY(); }
-
- // Pre-empt the browser: apply manual scroll restoration and jump to the
- // saved scrollY at script-parse time. Retries on fonts.ready and load
- // are essential: scrollTo(y) clamps to the current document.scrollHeight,
- // which is often hundreds of pixels short of the final value until
- // async-loaded fonts swap in and reflow.
- try {
- history.scrollRestoration = 'manual';
- const savedY = readScrollY();
- if (savedY != null) {
- const apply = () => {
- if (Math.abs(window.scrollY - savedY) > 0.5) {
- console.log('[impeccable.scroll] early restore', { from: window.scrollY, to: savedY });
- window.scrollTo(0, savedY);
- }
- };
- apply();
- if (document.fonts?.ready) document.fonts.ready.then(apply).catch(() => {});
- window.addEventListener('load', apply, { once: true });
- }
- } catch {}
-
- // UI refs
- let highlightEl = null;
- let tooltipEl = null;
- let barEl = null;
- let pickerEl = null;
- let toastEl = null;
- let scrollRaf = null;
-
- // ---------------------------------------------------------------------------
- // Helpers
- // ---------------------------------------------------------------------------
-
- function own(el) {
- return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
- }
-
- function pickable(el) {
- if (!el || el.nodeType !== 1) return false;
- if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
- if (own(el)) return false;
- const r = el.getBoundingClientRect();
- return r.width >= 20 && r.height >= 20;
- }
-
- function desc(el) {
- if (!el) return '';
- let s = el.tagName.toLowerCase();
- if (el.id) s += '#' + el.id;
- else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
- return s;
- }
-
- function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
-
- // Modal-aware chrome: keep our floating UI clickable inside Radix /
- // Headless UI / vaul portals.
- //
- // Two host-page behaviors break us when the picked element lives inside a
- // modal dialog:
- //
- // 1. Modal scroll-lock disables outside pointer events. Radix's
- // `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
- // while a modal is open and only restores `auto` on the layer. Our
- // chrome inherits `none` from <body> and becomes unclickable.
- // 2. The dialog's outside-interaction handler (Radix's
- // `usePointerDownOutside`) listens at document level and dismisses
- // the dialog whenever a `pointerdown` lands outside the layer node.
- // Our chrome is a sibling of <body>, so Radix classifies our clicks
- // as outside and tears the dialog down mid-task.
- //
- // We can't reliably re-parent our chrome into the dialog subtree (z-index
- // stacking, scroll containers, theming all become host-page concerns), so
- // we defang both behaviors at our root:
- //
- // - `pointer-events: auto !important` overrides the inherited `none`.
- // - Stop `pointerdown` / `mousedown` propagation so the document-level
- // dismiss listener never fires for our clicks.
- // - Stop `focusin` propagation so any focus shifts inside our chrome
- // don't read as "focus moved outside the dialog" to focus traps.
- //
- // Click events still bubble normally — only the early pointer/focus
- // signals that drive outside-interaction detection are silenced.
- function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
- if (!rootEl) return;
- if (setPointerEvents) {
- rootEl.style.setProperty('pointer-events', 'auto', 'important');
- }
- const stop = (e) => e.stopPropagation();
- rootEl.addEventListener('pointerdown', stop);
- rootEl.addEventListener('mousedown', stop);
- rootEl.addEventListener('focusin', stop);
- }
-
- // ---------------------------------------------------------------------------
- // Highlight overlay
- // ---------------------------------------------------------------------------
-
- function initHighlight() {
- highlightEl = document.createElement('div');
- highlightEl.id = PREFIX + '-highlight';
- Object.assign(highlightEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- border: '2px solid ' + C.brand, borderRadius: '3px',
- pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
- transition: HIGHLIGHT_TRANSITION,
- display: 'none', opacity: '0',
- });
- document.body.appendChild(highlightEl);
-
- tooltipEl = document.createElement('div');
- tooltipEl.id = PREFIX + '-tooltip';
- Object.assign(tooltipEl.style, {
- position: 'fixed',
- background: C.ink, color: C.white,
- fontFamily: MONO, fontSize: '10px', fontWeight: '500',
- padding: '2px 6px', borderRadius: '3px',
- zIndex: Z.highlight + 1, pointerEvents: 'none',
- whiteSpace: 'nowrap', display: 'none',
- letterSpacing: '0.02em',
- transition: TOOLTIP_TRANSITION,
- });
- document.body.appendChild(tooltipEl);
- }
-
- function showHighlight(el) {
- if (!el || !highlightEl) return;
- const r = el.getBoundingClientRect();
- const top = (r.top - 2) + 'px', left = (r.left - 2) + 'px';
- const width = (r.width + 4) + 'px', height = (r.height + 4) + 'px';
- const tipTop = r.top - 20;
- const tipY = (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px';
- const tipX = Math.max(4, r.left) + 'px';
- tooltipEl.textContent = desc(el);
-
- const hiWasHidden = highlightEl.style.display === 'none' || highlightEl.style.opacity === '0';
- if (hiWasHidden) {
- // Snap to first target without animating from (0,0), then fade in.
- highlightEl.style.transition = 'none';
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block' });
- tooltipEl.style.transition = 'none';
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block' });
- void highlightEl.offsetWidth;
- highlightEl.style.transition = HIGHLIGHT_TRANSITION;
- highlightEl.style.opacity = '1';
- tooltipEl.style.transition = TOOLTIP_TRANSITION;
- tooltipEl.style.opacity = '1';
- } else {
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block', opacity: '1' });
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block', opacity: '1' });
- }
- }
-
- function hideHighlight() {
- if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
- if (tooltipEl) { tooltipEl.style.opacity = '0'; tooltipEl.style.display = 'none'; }
- }
-
- // ---------------------------------------------------------------------------
- // Annotation overlay (comment pins + magenta strokes)
- //
- // Active while state === 'CONFIGURING'. The overlay is a fixed-positioned
- // sibling of <body> mirroring selectedElement's bounding rect. Click (no
- // drag) drops a comment pin; drag paints a magenta SVG stroke. All coords
- // are stored in element-local CSS px so they survive scroll / resize and
- // correlate directly with the captured PNG.
- // ---------------------------------------------------------------------------
-
- const DRAG_THRESHOLD = 5; // px — below this, treat pointerup as a click
- const PIN_DBL_CLICK_MS = 300; // two clicks on the same pin within this delete it
- let annotOverlayEl = null;
- let annotSvgEl = null;
- let annotPinsEl = null;
- let annotClearChipEl = null;
- let annotState = { comments: [], strokes: [] };
- let annotActive = false;
- // `annotPointer` is either:
- // { kind: 'new', x0, y0, moved, strokeEl, strokePoints } creating a stroke/pin
- // { kind: 'pin', idx, startPointer, startPin, moved } dragging an existing pin
- let annotPointer = null;
- let annotEditing = null; // { idx, input, wrapEl }
- let annotLastPinClick = { idx: -1, time: 0 }; // for click-click-to-delete
-
- function initAnnotOverlay() {
- annotOverlayEl = document.createElement('div');
- annotOverlayEl.id = PREFIX + '-annot';
- Object.assign(annotOverlayEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- pointerEvents: 'auto', zIndex: Z.highlight + 2,
- display: 'none', overflow: 'visible',
- cursor: 'crosshair', touchAction: 'none',
- });
-
- annotSvgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- annotSvgEl.id = PREFIX + '-annot-svg';
- Object.assign(annotSvgEl.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%',
- // The SVG itself doesn't absorb clicks; individual hit-paths opt-in via
- // pointer-events=stroke so gaps still fall through to the overlay.
- pointerEvents: 'none', overflow: 'visible',
- });
- annotOverlayEl.appendChild(annotSvgEl);
-
- annotPinsEl = document.createElement('div');
- annotPinsEl.id = PREFIX + '-annot-pins';
- Object.assign(annotPinsEl.style, {
- position: 'absolute', inset: '0',
- pointerEvents: 'none',
- });
- annotOverlayEl.appendChild(annotPinsEl);
-
- annotClearChipEl = document.createElement('div');
- annotClearChipEl.id = PREFIX + '-annot-clear';
- annotClearChipEl.dataset.annotClear = 'true';
- annotClearChipEl.textContent = 'Clear';
- Object.assign(annotClearChipEl.style, {
- position: 'absolute', top: '8px', right: '8px',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '10px', fontWeight: '500',
- letterSpacing: '0.08em', textTransform: 'uppercase',
- padding: '5px 12px', borderRadius: '999px',
- cursor: 'pointer', pointerEvents: 'auto',
- display: 'none', userSelect: 'none',
- boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
- });
- annotOverlayEl.appendChild(annotClearChipEl);
-
- annotOverlayEl.addEventListener('pointerdown', onAnnotDown);
- annotOverlayEl.addEventListener('pointermove', onAnnotMove);
- annotOverlayEl.addEventListener('pointerup', onAnnotUp);
- annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
- document.body.appendChild(annotOverlayEl);
- // Modal-host friendliness: pointer-events is already 'auto' on this
- // overlay; we only need to silence the host's outside-interaction
- // listeners. Don't override pointer-events here (the overlay toggles
- // visibility via display:none, which is fine).
- defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
- }
-
- function updateClearChip() {
- if (!annotClearChipEl) return;
- const hasAny = annotState.comments.length > 0 || annotState.strokes.length > 0;
- annotClearChipEl.style.display = hasAny ? 'block' : 'none';
- }
-
- function showAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- annotActive = true;
- positionAnnotOverlay(el);
- annotOverlayEl.style.display = 'block';
- }
-
- function hideAnnotOverlay() {
- annotActive = false;
- if (annotOverlayEl) annotOverlayEl.style.display = 'none';
- // Drop any in-progress edit without touching annotState — clearAnnotations
- // (if the caller is exiting configure mode) handles state reset.
- annotEditing = null;
- }
-
- function positionAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- const r = el.getBoundingClientRect();
- Object.assign(annotOverlayEl.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- annotSvgEl.setAttribute('viewBox', '0 0 ' + r.width + ' ' + r.height);
- }
-
- function clearAnnotations() {
- annotState.comments = [];
- annotState.strokes = [];
- if (annotSvgEl) while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- if (annotPinsEl) annotPinsEl.innerHTML = '';
- annotPointer = null;
- annotEditing = null;
- annotLastPinClick = { idx: -1, time: 0 };
- updateClearChip();
- }
-
- // Rebuild the SVG layer. Each stroke gets a wider invisible hit path
- // beneath the visible magenta path so clicks register on thin lines.
- function redrawStrokes() {
- while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- annotState.strokes.forEach((s, idx) => {
- const d = pointsToPath(s.points);
- const hit = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- hit.setAttribute('d', d);
- hit.setAttribute('stroke', 'transparent');
- hit.setAttribute('stroke-width', '16');
- hit.setAttribute('stroke-linecap', 'round');
- hit.setAttribute('stroke-linejoin', 'round');
- hit.setAttribute('fill', 'none');
- hit.setAttribute('pointer-events', 'stroke');
- hit.style.cursor = 'pointer';
- hit.dataset.annotStroke = String(idx);
- annotSvgEl.appendChild(hit);
- const visible = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- visible.setAttribute('d', d);
- visible.setAttribute('stroke', C.brand);
- visible.setAttribute('stroke-width', '3');
- visible.setAttribute('stroke-linecap', 'round');
- visible.setAttribute('stroke-linejoin', 'round');
- visible.setAttribute('fill', 'none');
- visible.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(visible);
- });
- updateClearChip();
- }
-
- function localCoords(e) {
- const rect = annotOverlayEl.getBoundingClientRect();
- return { x: e.clientX - rect.left, y: e.clientY - rect.top };
- }
-
- function onAnnotDown(e) {
- if (!annotActive) return;
-
- // 1) Clear chip → wipe all annotations
- if (e.target.closest?.('[data-annot-clear]')) {
- if (annotEditing) annotEditing = null;
- clearAnnotations();
- renderAllPins();
- redrawStrokes();
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 2) Stroke hit path → delete that stroke
- const strokeHit = e.target.closest?.('[data-annot-stroke]');
- if (strokeHit) {
- const idx = parseInt(strokeHit.dataset.annotStroke, 10);
- if (Number.isInteger(idx)) {
- annotState.strokes.splice(idx, 1);
- redrawStrokes();
- }
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 3) Pin → drag, edit, or delete-on-double-click
- const pinWrap = e.target.closest?.('[data-annot-pin]');
- if (pinWrap) {
- const idx = parseInt(pinWrap.dataset.annotPin, 10);
- if (!Number.isInteger(idx)) return;
- // Double-click (two pointerdowns on the same pin within window) → delete.
- const now = Date.now();
- if (annotLastPinClick.idx === idx && now - annotLastPinClick.time < PIN_DBL_CLICK_MS) {
- if (annotEditing && annotEditing.idx === idx) annotEditing = null;
- annotState.comments.splice(idx, 1);
- annotLastPinClick = { idx: -1, time: 0 };
- renderAllPins();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- annotLastPinClick = { idx, time: now };
- // If editing a different pin, commit that edit before starting here.
- if (annotEditing && annotEditing.idx !== idx) finalizeEditingPin();
- // If already editing THIS pin and the user clicked the dot, let the
- // input keep focus (don't start a drag — the click wasn't meant as one).
- if (annotEditing && annotEditing.idx === idx) return;
- const p = localCoords(e);
- const pin = annotState.comments[idx];
- annotPointer = {
- kind: 'pin', idx,
- startPointer: p,
- startPin: { x: pin.x, y: pin.y },
- moved: false,
- };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 4) Empty area → commit any open edit, then start new annotation
- if (annotEditing) {
- finalizeEditingPin();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- const p = localCoords(e);
- annotPointer = { kind: 'new', x0: p.x, y0: p.y, moved: false, strokeEl: null, strokePoints: null };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- }
-
- function onAnnotMove(e) {
- if (!annotActive || !annotPointer) return;
- const p = localCoords(e);
-
- if (annotPointer.kind === 'pin') {
- const dx = p.x - annotPointer.startPointer.x;
- const dy = p.y - annotPointer.startPointer.y;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- }
- const pin = annotState.comments[annotPointer.idx];
- if (!pin) { annotPointer = null; return; }
- pin.x = annotPointer.startPin.x + dx;
- pin.y = annotPointer.startPin.y + dy;
- renderAllPins();
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const dx = p.x - annotPointer.x0, dy = p.y - annotPointer.y0;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- const strokeEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- strokeEl.setAttribute('stroke', C.brand);
- strokeEl.setAttribute('stroke-width', '3');
- strokeEl.setAttribute('stroke-linecap', 'round');
- strokeEl.setAttribute('stroke-linejoin', 'round');
- strokeEl.setAttribute('fill', 'none');
- strokeEl.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(strokeEl);
- annotPointer.strokeEl = strokeEl;
- annotPointer.strokePoints = [[annotPointer.x0, annotPointer.y0]];
- }
- annotPointer.strokePoints.push([p.x, p.y]);
- annotPointer.strokeEl.setAttribute('d', pointsToPath(annotPointer.strokePoints));
- e.stopPropagation();
- }
-
- function onAnnotUp(e) {
- if (!annotActive || !annotPointer) return;
-
- if (annotPointer.kind === 'pin') {
- const wasDrag = annotPointer.moved;
- const idx = annotPointer.idx;
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- if (wasDrag) {
- // A drag is an intentional reposition; a follow-up click shouldn't be
- // interpreted as a double-click-to-delete.
- annotLastPinClick = { idx: -1, time: 0 };
- } else {
- beginEditPin(idx);
- }
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const wasDrag = annotPointer.moved;
- if (wasDrag) {
- annotState.strokes.push({ points: annotPointer.strokePoints });
- // Swap the temporary preview SVG path for the full render with hit paths.
- redrawStrokes();
- } else {
- const idx = annotState.comments.length;
- annotState.comments.push({ x: annotPointer.x0, y: annotPointer.y0, text: '' });
- renderAllPins();
- beginEditPin(idx);
- }
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- e.stopPropagation();
- }
-
- function pointsToPath(points) {
- if (!points || points.length === 0) return '';
- let d = 'M' + points[0][0].toFixed(1) + ' ' + points[0][1].toFixed(1);
- for (let i = 1; i < points.length; i++) {
- d += ' L' + points[i][0].toFixed(1) + ' ' + points[i][1].toFixed(1);
- }
- return d;
- }
-
- function renderAllPins() {
- annotPinsEl.innerHTML = '';
- annotState.comments.forEach((c, idx) => {
- annotPinsEl.appendChild(buildPinElement(c, idx));
- });
- updateClearChip();
- }
-
- function buildPinElement(comment, idx) {
- const interactive = idx >= 0;
- const wrap = document.createElement('div');
- if (interactive) wrap.dataset.annotPin = String(idx);
- Object.assign(wrap.style, {
- position: 'absolute',
- left: (comment.x - 7) + 'px', top: (comment.y - 7) + 'px',
- pointerEvents: interactive ? 'auto' : 'none',
- display: 'flex', alignItems: 'flex-start', gap: '6px',
- cursor: interactive ? 'grab' : 'default',
- touchAction: 'none',
- });
- const dot = document.createElement('div');
- Object.assign(dot.style, {
- width: '14px', height: '14px', borderRadius: '50%',
- background: C.brand, border: '2px solid ' + C.white,
- boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
- flexShrink: '0',
- });
- wrap.appendChild(dot);
-
- if (comment.text) {
- const bubble = document.createElement('div');
- bubble.textContent = comment.text;
- Object.assign(bubble.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- marginTop: '-2px', maxWidth: '220px',
- pointerEvents: 'none', whiteSpace: 'pre-wrap',
- wordBreak: 'break-word',
- });
- wrap.appendChild(bubble);
- }
- return wrap;
- }
-
- function beginEditPin(idx) {
- const wrapEl = annotPinsEl.querySelector('[data-annot-pin="' + idx + '"]');
- if (!wrapEl) return;
- // Strip any existing bubble (but keep the dot)
- wrapEl.querySelectorAll('div:not(:first-child)').forEach(n => n.remove());
- const input = document.createElement('input');
- input.type = 'text';
- input.placeholder = 'Note…';
- Object.assign(input.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- border: '1px solid ' + C.brand,
- outline: 'none', marginTop: '-2px',
- width: '220px', pointerEvents: 'auto',
- });
- const originalText = annotState.comments[idx].text || '';
- input.value = originalText;
- wrapEl.appendChild(input);
- annotEditing = { idx, input, wrapEl, originalText };
- input.addEventListener('keydown', onAnnotInputKey, true);
- input.addEventListener('blur', () => {
- // Fires on both focus-loss and programmatic blur; commit unless we
- // already handled it.
- if (annotEditing && annotEditing.input === input) finalizeEditingPin();
- });
- // Stop clicks/pointerdowns inside the input from bubbling to the overlay
- ['pointerdown', 'click'].forEach(ev => {
- input.addEventListener(ev, e => e.stopPropagation());
- });
- setTimeout(() => input.focus(), 0);
- }
-
- function onAnnotInputKey(e) {
- if (e.key === 'Enter') {
- e.preventDefault(); e.stopPropagation();
- finalizeEditingPin();
- } else if (e.key === 'Escape') {
- e.preventDefault(); e.stopPropagation();
- cancelEditingPin();
- } else {
- // Keep arrows / backspace from hitting global handlers
- e.stopPropagation();
- }
- }
-
- function finalizeEditingPin() {
- if (!annotEditing) return;
- const { idx, input } = annotEditing;
- const text = input.value.trim();
- annotEditing = null;
- if (text) annotState.comments[idx].text = text;
- else annotState.comments.splice(idx, 1);
- renderAllPins();
- }
-
- function cancelEditingPin() {
- if (!annotEditing) return;
- const { idx, originalText } = annotEditing;
- annotEditing = null;
- // If the pin had text before this edit, revert to it. If it was a
- // just-created empty pin, Escape removes it.
- if (originalText) {
- annotState.comments[idx].text = originalText;
- } else {
- annotState.comments.splice(idx, 1);
- }
- renderAllPins();
- }
-
- // Build a detached annotation subtree suitable for injection into the clone
- // modern-screenshot creates. Coordinates are element-local so this slots
- // straight into an element that's been made position:relative. Takes an
- // explicit snapshot so it works after annotState has been cleared.
- function buildAnnotationsForCapture(rect, snapshot) {
- const comments = snapshot ? snapshot.comments : annotState.comments;
- const strokes = snapshot ? snapshot.strokes : annotState.strokes;
- if (comments.length === 0 && strokes.length === 0) return null;
- const wrap = document.createElement('div');
- Object.assign(wrap.style, {
- position: 'absolute', top: '0', left: '0',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none', overflow: 'visible',
- });
- if (strokes.length > 0) {
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- svg.setAttribute('viewBox', '0 0 ' + rect.width + ' ' + rect.height);
- Object.assign(svg.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%', overflow: 'visible',
- });
- for (const s of strokes) {
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- path.setAttribute('stroke', C.brand);
- path.setAttribute('stroke-width', '3');
- path.setAttribute('stroke-linecap', 'round');
- path.setAttribute('stroke-linejoin', 'round');
- path.setAttribute('fill', 'none');
- path.setAttribute('d', pointsToPath(s.points));
- svg.appendChild(path);
- }
- wrap.appendChild(svg);
- }
- for (const c of comments) {
- // idx=-1 means non-interactive; pointerEvents stay off in the clone
- wrap.appendChild(buildPinElement(c, -1));
- }
- return wrap;
- }
-
- // ---------------------------------------------------------------------------
- // Element context extraction
- // ---------------------------------------------------------------------------
-
- function extractContext(el) {
- const cs = getComputedStyle(el);
- const r = el.getBoundingClientRect();
- const props = {};
- for (const sheet of document.styleSheets) {
- try {
- for (const rule of sheet.cssRules) {
- if (rule.style) for (let i = 0; i < rule.style.length; i++) {
- const p = rule.style[i];
- if (p.startsWith('--') && !props[p]) {
- const v = cs.getPropertyValue(p).trim();
- if (v) props[p] = v;
- }
- }
- }
- } catch { /* cross-origin */ }
- }
- return {
- tagName: el.tagName.toLowerCase(), id: el.id || null,
- classes: [...el.classList],
- textContent: (el.textContent || '').slice(0, 500),
- outerHTML: el.outerHTML.slice(0, 10000),
- computedStyles: {
- 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
- 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
- 'color': cs.color, 'background': cs.background,
- 'background-color': cs.backgroundColor,
- 'padding': cs.padding, 'margin': cs.margin,
- 'display': cs.display, 'position': cs.position,
- 'gap': cs.gap, 'border-radius': cs.borderRadius,
- 'box-shadow': cs.boxShadow,
- },
- cssCustomProperties: props,
- parentContext: el.parentElement
- ? '<' + el.parentElement.tagName.toLowerCase()
- + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
- + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
- + '>'
- : null,
- boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
- };
- }
-
- // ---------------------------------------------------------------------------
- // The Bar — one floating element, three modes
- // ---------------------------------------------------------------------------
-
- // Contextual-bar palette. Cached at init so every build*Row reads a
- // consistent set of colors; detectPageTheme runs once rather than on every
- // phase transition.
- let BP = null;
-
- // Bar shadow variants. The default projects down + subtle around. When
- // the Tune popover opens below the bar, a downward shadow lands on the
- // dark popover and reads as a bright ghost line. We swap to UP-only while
- // tune is open below so the popover's top edge is clean.
- const BAR_SHADOW_DEFAULT = '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_UP = '0 -4px 20px oklch(0% 0 0 / 0.08), 0 -1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_DOWN = BAR_SHADOW_DEFAULT;
-
- function initBar() {
- BP = barPaletteForTheme(detectPageTheme());
- barEl = document.createElement('div');
- barEl.id = PREFIX + '-bar';
- Object.assign(barEl.style, {
- position: 'fixed', zIndex: Z.bar,
- display: 'none', opacity: '0',
- transform: 'translateY(6px)',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- background: BP.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + BP.hairline,
- borderRadius: '10px',
- boxShadow: BAR_SHADOW_DEFAULT,
- transition: 'box-shadow 0.2s ease, opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- fontFamily: FONT, fontSize: '13px', color: BP.text,
- padding: '6px',
- maxWidth: '520px', minWidth: '320px',
- });
- document.body.appendChild(barEl);
- defangOutsideHandlers(barEl);
- }
-
- function positionBar() {
- if (!barEl || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- const barH = barEl.offsetHeight || 44;
- const barW = barEl.offsetWidth || 380;
- const GLOBAL_BAR_RESERVE = 64; // global bar height + bottom margin + breathing room
- const GAP = 8;
-
- // Prefer below the element; fall back to above; if neither fits (element
- // taller than viewport), pin to a stable viewport anchor so the bar
- // doesn't teleport between top and bottom as the user scrolls.
- let top;
- const belowTop = r.bottom + GAP;
- const aboveTop = r.top - barH - GAP;
- if (belowTop + barH + GAP <= window.innerHeight - GLOBAL_BAR_RESERVE) {
- top = belowTop;
- } else if (aboveTop >= GAP) {
- top = aboveTop;
- } else {
- top = window.innerHeight - barH - GLOBAL_BAR_RESERVE;
- }
-
- let left = r.left + (r.width - barW) / 2;
- if (left < GAP) left = GAP;
- if (left + barW > window.innerWidth - GAP) left = window.innerWidth - barW - GAP;
- Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
- }
-
- function showBar(mode) {
- barEl.innerHTML = '';
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- barEl.style.display = 'block';
- positionBar();
- requestAnimationFrame(() => {
- barEl.style.opacity = '1';
- barEl.style.transform = 'translateY(0)';
- });
- }
-
- function hideBar() {
- if (!barEl) return;
- barEl.style.opacity = '0';
- barEl.style.transform = 'translateY(6px)';
- setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
- hideActionPicker();
- closeTunePopover();
- }
-
- function updateBarContent(mode) {
- if (!barEl || barEl.style.display === 'none') return;
- barEl.innerHTML = '';
- // Reset bar styling to the theme-aware palette
- barEl.style.background = BP.surface;
- barEl.style.border = '1px solid ' + BP.hairline;
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- else if (mode === 'saving') barEl.appendChild(buildSavingRow());
- else if (mode === 'confirmed') {
- barEl.appendChild(buildConfirmedRow());
- barEl.style.background = 'oklch(95% 0.05 145)';
- barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
- }
- }
-
- // --- Configure row ---
-
- function buildConfigureRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
-
- // Action pill
- const pill = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '4px',
- padding: '5px 10px', borderRadius: '6px',
- background: BP.mark, color: BP.markText,
- fontFamily: FONT, fontSize: '12px', fontWeight: '500',
- border: 'none', cursor: 'pointer',
- transition: 'background 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap', flexShrink: '0',
- });
- pill.textContent = actionLabel() + ' \u25BE';
- pill.addEventListener('mouseenter', () => pill.style.background = BP.accent);
- pill.addEventListener('mouseleave', () => pill.style.background = BP.mark);
- pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
- pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
- pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
- row.appendChild(pill);
-
- // Freeform input. Focus state shows an accent-colored border only —
- // an earlier version tinted the background with `BP.accentSoft`, which
- // composited against the dark bar surface to a murky purple where the
- // browser's default placeholder gray was unreadable. Placeholder color
- // is set explicitly via a one-shot stylesheet keyed off this input's id
- // so it picks up the bar's `textDim` token in both themes.
- const input = document.createElement('input');
- input.id = PREFIX + '-input';
- input.type = 'text';
- input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
- Object.assign(input.style, {
- flex: '1', minWidth: '0',
- padding: '5px 8px', borderRadius: '6px',
- border: '1px solid transparent', background: 'transparent',
- fontFamily: FONT, fontSize: '12px', color: BP.text,
- outline: 'none',
- transition: 'border-color 0.15s ease',
- });
- if (!document.getElementById(PREFIX + '-input-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-input-style';
- s.textContent =
- '#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
- document.head.appendChild(s);
- }
- input.addEventListener('focus', () => {
- input.style.borderColor = BP.accent;
- });
- input.addEventListener('blur', () => {
- input.style.borderColor = 'transparent';
- });
- input.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
- if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; return; }
- // Let arrow keys pass through to the element picker when the input is empty
- if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && !input.value) return;
- e.stopPropagation();
- });
- row.appendChild(input);
-
- // Variant count toggle
- const count = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: MONO, fontSize: '11px', fontWeight: '600',
- color: BP.textDim, cursor: 'pointer',
- transition: 'color 0.12s ease, border-color 0.12s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- count.textContent = '\u00D7' + selectedCount;
- count.title = 'Variants: click to change';
- count.addEventListener('mouseenter', () => { count.style.color = BP.text; count.style.borderColor = BP.text; });
- count.addEventListener('mouseleave', () => { count.style.color = BP.textDim; count.style.borderColor = BP.hairline; });
- count.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
- count.textContent = '\u00D7' + selectedCount;
- });
- row.appendChild(count);
-
- // Go button
- const go = el('button', {
- padding: '5px 12px', borderRadius: '6px',
- border: 'none', background: BP.accent, color: BP.mark,
- fontFamily: FONT, fontSize: '12px', fontWeight: '600',
- cursor: 'pointer',
- transition: 'filter 0.12s ease, transform 0.1s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- go.textContent = 'Go \u2192';
- go.addEventListener('mouseenter', () => go.style.filter = 'brightness(1.1)');
- go.addEventListener('mouseleave', () => go.style.filter = 'none');
- go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
- go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
- go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
- row.appendChild(go);
-
- // Auto-focus input after a beat
- setTimeout(() => input.focus(), 60);
- return row;
- }
-
- // --- Generating row ---
-
- function buildGeneratingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 4px',
- });
-
- // Action label
- const label = el('span', {
- fontWeight: '600', fontSize: '12px', color: BP.text,
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- label.textContent = actionLabel();
- row.appendChild(label);
-
- // Dots
- row.appendChild(buildDots(false));
-
- // Status
- const status = el('span', {
- fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',
- marginLeft: 'auto',
- });
- // Variants currently arrive atomically in a single file edit, so a
- // per-variant counter would lie. Say what's true.
- status.textContent = arrivedVariants < expectedVariants
- ? 'Generating ' + expectedVariants + ' variants...'
- : 'Done';
- row.appendChild(status);
-
- return row;
- }
-
- // --- Cycling row ---
-
- const TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';
-
- function buildCyclingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '6px',
- padding: '1px 2px',
- });
-
- // Prev
- const prev = navBtn('\u2190');
- prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
- if (visibleVariant <= 1) prev.style.opacity = '0.3';
- row.appendChild(prev);
-
- // Dots (clickable)
- row.appendChild(buildDots(true));
-
- // Counter
- const counter = el('span', {
- fontFamily: MONO, fontSize: '11px', fontWeight: '500',
- color: BP.textDim, minWidth: '24px', textAlign: 'center',
- });
- counter.textContent = visibleVariant + '/' + arrivedVariants;
- row.appendChild(counter);
-
- // Next
- const next = navBtn('\u2192');
- next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
- if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
- row.appendChild(next);
-
- // Tune chip — only when the visible variant exposes params
- const visParams = parseVariantParams(getVisibleVariantEl());
- const hasParams = visParams.length > 0;
- if (hasParams) {
- const tune = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '6px',
- padding: '4px 10px', borderRadius: '5px',
- border: '1px solid transparent',
- background: tuneOpen ? BP.accentSoft : 'transparent',
- color: tuneOpen ? BP.accent : BP.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'color 0.12s ease, background 0.12s ease',
- whiteSpace: 'nowrap',
- });
- tune.innerHTML = TUNE_ICON_SVG;
- const tuneLabel = document.createElement('span');
- tuneLabel.textContent = 'Tune';
- tune.appendChild(tuneLabel);
- const tuneBadge = document.createElement('span');
- Object.assign(tuneBadge.style, {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- minWidth: '16px', height: '16px', padding: '0 4px',
- borderRadius: '999px',
- background: tuneOpen ? C.brand : BP.hairline,
- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',
- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',
- lineHeight: '1',
- boxSizing: 'border-box',
- });
- tuneBadge.textContent = String(visParams.length);
- tune.appendChild(tuneBadge);
- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';
- tune.addEventListener('mouseenter', () => {
- if (!tuneOpen) tune.style.background = BP.accentSoft;
- });
- tune.addEventListener('mouseleave', () => {
- if (!tuneOpen) tune.style.background = 'transparent';
- });
- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });
- tune.dataset.iceqTune = '1';
- row.appendChild(tune);
- }
-
- // Spacer
- row.appendChild(el('div', { flex: '1' }));
-
- // Accept — primary action, uses the site's saturated brand magenta
- // with paper-white text, not the theme-muted BP.accent.
- const accept = el('button', {
- padding: '5px 14px', borderRadius: '5px',
- border: 'none', background: C.brand, color: 'oklch(98% 0 0)',
- fontFamily: FONT, fontSize: '11px', fontWeight: '600',
- cursor: 'pointer', transition: 'filter 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap',
- });
- accept.textContent = '\u2713 Accept';
- accept.addEventListener('mouseenter', () => accept.style.filter = 'brightness(1.08)');
- accept.addEventListener('mouseleave', () => accept.style.filter = 'none');
- accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');
- accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');
- accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
- row.appendChild(accept);
-
- // Discard
- const discard = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: FONT, fontSize: '11px', color: BP.textDim,
- cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
- });
- discard.textContent = '\u2715';
- discard.title = 'Discard all variants';
- discard.addEventListener('mouseenter', () => { discard.style.color = BP.text; discard.style.borderColor = BP.text; });
- discard.addEventListener('mouseleave', () => { discard.style.color = BP.textDim; discard.style.borderColor = BP.hairline; });
- discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
- row.appendChild(discard);
-
- return row;
- }
-
- // --- Shared UI builders ---
-
- // --- Saving row (waiting for agent to process accept/discard) ---
-
- function buildSavingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const spinner = el('div', {
- width: '14px', height: '14px', borderRadius: '50%',
- border: '2px solid ' + BP.hairline,
- borderTopColor: BP.accent,
- animation: 'impeccable-spin 0.6s linear infinite',
- flexShrink: '0',
- });
- row.appendChild(spinner);
- const label = el('span', {
- fontSize: '12px', color: BP.textDim, fontWeight: '500',
- });
- label.textContent = 'Applying variant...';
- row.appendChild(label);
-
- // Inject the keyframes if not already present
- if (!document.getElementById(PREFIX + '-keyframes')) {
- const style = document.createElement('style');
- style.id = PREFIX + '-keyframes';
- style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
- document.head.appendChild(style);
- }
- return row;
- }
-
- // --- Confirmed row (green success, auto-dismisses) ---
-
- function buildConfirmedRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const check = el('span', {
- fontSize: '15px', lineHeight: '1', flexShrink: '0',
- color: 'oklch(45% 0.15 145)',
- });
- check.textContent = '\u2713';
- row.appendChild(check);
- const label = el('span', {
- fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
- });
- label.textContent = 'Variant applied';
- row.appendChild(label);
- return row;
- }
-
- // --- Shared UI builders ---
-
- function buildDots(clickable) {
- const container = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
- for (let i = 1; i <= expectedVariants; i++) {
- const arrived = i <= arrivedVariants;
- const active = i === visibleVariant;
- // active: solid site-brand magenta dot. arrived+inactive: muted neutral.
- // pending (not yet arrived): faint outline ring. No borders on arrived
- // dots — the previous "accent ring + ash fill" combo read as noisy
- // magenta chips, especially when all variants had arrived and every
- // dot wore an accent ring.
- const dotBg = active ? C.brand
- : arrived ? BP.textDim
- : 'transparent';
- const dotBorder = arrived ? 'none' : '1.5px solid ' + BP.hairline;
- const dot = el('div', {
- width: active ? '8px' : '6px',
- height: active ? '8px' : '6px',
- borderRadius: '50%',
- background: dotBg,
- border: dotBorder,
- boxSizing: 'border-box',
- transition: 'all 0.2s ' + EASE,
- cursor: (clickable && arrived) ? 'pointer' : 'default',
- transform: arrived ? 'scale(1)' : 'scale(0.85)',
- opacity: arrived ? (active ? '1' : '0.6') : '0.4',
- });
- if (clickable && arrived) {
- const idx = i;
- dot.addEventListener('click', (e) => {
- e.stopPropagation();
- visibleVariant = idx;
- showVariantInDOM(currentSessionId, idx);
- updateSelectedElement();
- updateBarContent('cycling');
- });
- }
- container.appendChild(dot);
- }
- return container;
- }
-
- function navBtn(text) {
- const b = el('button', {
- width: '26px', height: '26px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- color: BP.text, fontFamily: FONT, fontSize: '13px',
- cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
- transition: 'border-color 0.12s ease, background 0.12s ease',
- padding: '0', lineHeight: '1',
- });
- b.textContent = text;
- b.addEventListener('mouseenter', () => { b.style.borderColor = BP.text; });
- b.addEventListener('mouseleave', () => { b.style.borderColor = BP.hairline; });
- return b;
- }
-
- function actionLabel() {
- const a = ACTIONS.find(a => a.value === selectedAction);
- return a ? a.label : 'Freeform';
- }
-
- function el(tag, styles) {
- const e = document.createElement(tag);
- if (styles) Object.assign(e.style, styles);
- return e;
- }
-
- // ---------------------------------------------------------------------------
- // Action picker popover
- // ---------------------------------------------------------------------------
-
- function initActionPicker() {
- const P = barPaletteForTheme(detectPageTheme());
- pickerEl = document.createElement('div');
- pickerEl.id = PREFIX + '-picker';
- Object.assign(pickerEl.style, {
- position: 'fixed', zIndex: Z.picker,
- display: 'none', opacity: '0',
- transform: 'scale(0.96) translateY(4px)',
- transformOrigin: 'bottom left',
- transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
- background: P.surface,
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
- padding: '6px',
- fontFamily: FONT,
- backdropFilter: 'blur(10px)',
- WebkitBackdropFilter: 'blur(10px)',
- });
-
- // Build the chip grid
- const grid = el('div', {
- display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
- });
-
- ACTIONS.forEach(action => {
- const chip = el('button', {
- display: 'flex', flexDirection: 'column', alignItems: 'center',
- gap: '4px',
- padding: '8px 6px', borderRadius: '6px',
- border: 'none',
- background: action.value === selectedAction ? P.accentSoft : 'transparent',
- color: action.value === selectedAction ? P.accent : P.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.1s ease, color 0.1s ease',
- textAlign: 'center', whiteSpace: 'nowrap',
- });
- const iconWrap = el('span', {
- display: 'flex', alignItems: 'center', justifyContent: 'center',
- height: '20px', opacity: '0.9',
- });
- iconWrap.innerHTML = ICONS[action.value] || '';
- const labelEl = el('span', { lineHeight: '1' });
- labelEl.textContent = action.label;
- chip.appendChild(iconWrap);
- chip.appendChild(labelEl);
- chip.dataset.action = action.value;
- chip.addEventListener('mouseenter', () => {
- if (action.value !== selectedAction) chip.style.background = P.accentSoft;
- });
- chip.addEventListener('mouseleave', () => {
- chip.style.background = action.value === selectedAction ? P.accentSoft : 'transparent';
- });
- chip.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedAction = action.value;
- hideActionPicker();
- updateBarContent('configure');
- });
- grid.appendChild(chip);
- });
-
- pickerEl.appendChild(grid);
- document.body.appendChild(pickerEl);
- defangOutsideHandlers(pickerEl);
-
- // Cache the palette on the picker so toggleActionPicker's state refresh
- // uses the same theme-aware colors when it repaints chips.
- pickerEl.__iceq_palette = P;
- }
-
- function toggleActionPicker() {
- if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
- // Rebuild chips to reflect current selection
- const P = pickerEl.__iceq_palette || barPaletteForTheme(detectPageTheme());
- pickerEl.querySelectorAll('button').forEach(chip => {
- const isActive = chip.dataset.action === selectedAction;
- chip.style.background = isActive ? P.accentSoft : 'transparent';
- chip.style.color = isActive ? P.accent : P.text;
- });
- // Position above the bar
- const barRect = barEl.getBoundingClientRect();
- const pickerH = 170; // approximate; grows with icon + label rows
- let top = barRect.top - pickerH - 6;
- if (top < 8) top = barRect.bottom + 6;
- Object.assign(pickerEl.style, {
- top: top + 'px', left: barRect.left + 'px',
- display: 'block',
- });
- requestAnimationFrame(() => {
- pickerEl.style.opacity = '1';
- pickerEl.style.transform = 'scale(1) translateY(0)';
- });
- }
-
- function hideActionPicker() {
- if (!pickerEl) return;
- pickerEl.style.opacity = '0';
- pickerEl.style.transform = 'scale(0.96) translateY(4px)';
- setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
- }
-
- // ---------------------------------------------------------------------------
- // Params panel (per-variant coarse controls)
- //
- // Variants may declare a parameter manifest via a JSON attribute on the
- // variant wrapper:
- //
- // <div data-impeccable-variant="1"
- // data-impeccable-params='[{"id":"density","kind":"steps",...}]'>
- //
- // The panel docks to the right edge of the outline during CYCLING and
- // exposes 2-5 coarse knobs. Values apply to the variant wrapper so scoped
- // CSS can respond instantly without regeneration:
- //
- // range / numeric toggle → CSS var (`--p-<id>`) used via var(--p-foo, N)
- // steps / boolean toggle → data-p-<id> attribute used via :scope[data-p-foo="..."]
- //
- // On variant switch, values reset to that variant's declared defaults.
- // On accept, current values are sent in the event payload so the agent
- // can bake them into the source-file write.
- // ---------------------------------------------------------------------------
-
- let paramsPanelEl = null; // outer wrapper (overflow:hidden, clips the slide)
- let paramsPanelInner = null; // translating content (carries bg, padding, knobs)
- let paramsPanelBody = null; // grid holding the knob cells
- let paramsCurrentValues = {}; // {paramId: value} — mirror of the visible variant's live values
- let tuneOpen = false; // whether the Tune popover is open right now
-
- // Theme-aware Tune popover. Appears as a drawer that slides out from the
- // contextual bar's bar-facing edge (below if the bar sits below the
- // element, above otherwise). Same width as the bar. Auto-wraps to extra
- // rows when the knobs exceed one row. The bar's border-radius on the
- // popover side goes flat while open so the two shapes read as one.
- let paramsPanelPalette = null;
-
- function initParamsPanel() {
- paramsPanelPalette = barPaletteForTheme(detectPageTheme());
- const P = paramsPanelPalette;
-
- // Single element, always in the DOM. The slide animation is a CSS mask
- // with mask-size growing from 0% to 100% along the bar-facing axis — no
- // display toggle, no opacity toggle, no transform trickery. The mask
- // hides everything initially; as it grows, content is revealed from
- // the bar edge outward.
- paramsPanelEl = document.createElement('div');
- paramsPanelEl.id = PREFIX + '-params-panel';
- Object.assign(paramsPanelEl.style, {
- position: 'fixed', zIndex: String(Z.bar - 1),
- background: P.surfaceDeep,
- color: P.text,
- fontFamily: FONT,
- padding: '14px 18px',
- boxSizing: 'border-box',
- borderRadius: '0 0 10px 10px',
- pointerEvents: 'none',
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
-
- // clip-path is the same conceptual reveal as mask but with rock-solid
- // transition support across engines. Closed state clips from the far
- // edge; open = inset(0) shows everything.
- clipPath: 'inset(0 0 100% 0)',
- transition: 'clip-path 0.44s ' + EASE,
-
- // Park off-screen until positionParamsPanel places it. These are NOT
- // in the transition list, so they snap instantly — no fly-in from the
- // top-left when first shown.
- top: '-9999px', left: '-9999px', width: '0',
- });
-
- paramsPanelBody = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
- gap: '12px 16px',
- });
-
- paramsPanelEl.appendChild(paramsPanelBody);
- document.body.appendChild(paramsPanelEl);
- // Don't override pointer-events: the panel toggles between 'none' (closed,
- // click-through) and 'auto' (open) on its own. Just silence the host's
- // outside-interaction listeners while the panel is open.
- defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
- paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
- }
-
- function getVisibleVariantEl() {
- if (!currentSessionId) return null;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return null;
- return wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"]');
- }
-
- function parseVariantParams(variantEl) {
- if (!variantEl) return [];
- const raw = variantEl.getAttribute('data-impeccable-params');
- if (!raw) return [];
- try {
- const parsed = JSON.parse(raw);
- return Array.isArray(parsed) ? parsed : [];
- } catch (err) {
- console.warn('[impeccable] Invalid data-impeccable-params JSON:', err.message);
- return [];
- }
- }
-
- function applyParamValue(variantEl, param, value) {
- if (!variantEl) return;
- const attr = 'data-p-' + param.id;
- if (param.kind === 'range') {
- variantEl.style.setProperty('--p-' + param.id, String(value));
- } else if (param.kind === 'toggle') {
- const on = !!value;
- variantEl.style.setProperty('--p-' + param.id, on ? '1' : '0');
- if (on) variantEl.setAttribute(attr, 'on');
- else variantEl.removeAttribute(attr);
- } else if (param.kind === 'steps') {
- variantEl.setAttribute(attr, String(value));
- }
- }
-
- function applyParamDefaults(variantEl, params) {
- paramsCurrentValues = {};
- for (const p of params) {
- paramsCurrentValues[p.id] = p.default;
- applyParamValue(variantEl, p, p.default);
- }
- }
-
- function formatRangeValue(input) {
- const max = parseFloat(input.max), min = parseFloat(input.min);
- const v = parseFloat(input.value);
- if (!isFinite(v)) return input.value;
- return (max - min) <= 2 ? v.toFixed(2) : String(Math.round(v));
- }
-
- function buildParamsPanel(variantEl, params) {
- const P = paramsPanelPalette || barPaletteForTheme(detectPageTheme());
- paramsPanelBody.innerHTML = '';
- for (const p of params) {
- const row = el('div', { display: 'flex', flexDirection: 'column', gap: '6px' });
- const labelRow = el('div', {
- display: 'flex', justifyContent: 'space-between',
- alignItems: 'baseline', gap: '8px',
- });
- const lbl = el('span', {
- fontSize: '10.5px', fontWeight: '600', color: P.text,
- letterSpacing: '0.03em',
- });
- lbl.textContent = p.label || p.id;
- labelRow.appendChild(lbl);
- const readout = el('span', {
- fontSize: '10.5px', color: P.textDim,
- fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
- });
- labelRow.appendChild(readout);
- row.appendChild(labelRow);
-
- if (p.kind === 'range') {
- const input = document.createElement('input');
- input.type = 'range';
- input.min = String(p.min != null ? p.min : 0);
- input.max = String(p.max != null ? p.max : 1);
- input.step = String(p.step != null ? p.step : 0.05);
- input.value = String(p.default);
- Object.assign(input.style, {
- width: '100%', accentColor: C.brand, cursor: 'pointer',
- });
- readout.textContent = formatRangeValue(input);
- input.addEventListener('input', (e) => {
- e.stopPropagation();
- const v = parseFloat(input.value);
- paramsCurrentValues[p.id] = v;
- readout.textContent = formatRangeValue(input);
- applyParamValue(variantEl, p, v);
- queueCheckpoint('param_changed');
- });
- row.appendChild(input);
- } else if (p.kind === 'toggle') {
- const initial = !!p.default;
- readout.textContent = initial ? 'On' : 'Off';
- const track = el('button', {
- position: 'relative', width: '36px', height: '20px',
- borderRadius: '10px', border: 'none', padding: '0',
- cursor: 'pointer',
- background: initial ? C.brand : P.hairline,
- transition: 'background 0.15s ease',
- alignSelf: 'flex-start',
- });
- const knob = el('span', {
- position: 'absolute', top: '2px',
- left: initial ? '18px' : '2px',
- width: '16px', height: '16px', borderRadius: '50%',
- background: 'oklch(98% 0 0)',
- transition: 'left 0.18s ' + EASE,
- boxShadow: '0 1px 2px oklch(0% 0 0 / 0.2)',
- });
- track.appendChild(knob);
- track.addEventListener('click', (e) => {
- e.stopPropagation();
- const next = !paramsCurrentValues[p.id];
- paramsCurrentValues[p.id] = next;
- track.style.background = next ? C.brand : P.hairline;
- knob.style.left = next ? '18px' : '2px';
- readout.textContent = next ? 'On' : 'Off';
- applyParamValue(variantEl, p, next);
- queueCheckpoint('param_changed');
- });
- row.appendChild(track);
- } else if (p.kind === 'steps') {
- const opts = (p.options || []).map(o =>
- typeof o === 'string' ? { value: o, label: o } : o
- );
- const activeOpt = opts.find(o => o.value === p.default) || opts[0];
- readout.textContent = activeOpt ? activeOpt.label : String(p.default);
- const segRow = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(' + opts.length + ', 1fr)',
- gap: '1px', padding: '2px',
- background: P.hairline, borderRadius: '5px',
- });
- const segBtns = [];
- opts.forEach(o => {
- const active = o.value === p.default;
- const b = el('button', {
- padding: '5px 4px', border: 'none', borderRadius: '3px',
- background: active ? C.brand : 'transparent',
- color: active ? 'oklch(98% 0 0)' : P.text,
- fontFamily: FONT, fontSize: '10.5px', fontWeight: '500',
- cursor: 'pointer', whiteSpace: 'nowrap',
- transition: 'background 0.1s ease, color 0.1s ease',
- });
- b.textContent = o.label;
- b.addEventListener('click', (e) => {
- e.stopPropagation();
- paramsCurrentValues[p.id] = o.value;
- readout.textContent = o.label;
- segBtns.forEach(({ btn, val }) => {
- const on = val === o.value;
- btn.style.background = on ? C.brand : 'transparent';
- btn.style.color = on ? 'oklch(98% 0 0)' : P.text;
- });
- applyParamValue(variantEl, p, o.value);
- queueCheckpoint('param_changed');
- });
- segRow.appendChild(b);
- segBtns.push({ btn: b, val: o.value });
- });
- row.appendChild(segRow);
- }
-
- paramsPanelBody.appendChild(row);
- }
- }
-
- // Decide which way the popover opens: away from the picked element. If the
- // bar landed below the element, popover slides DOWN from the bar's bottom.
- // If the bar landed above, popover slides UP from the bar's top.
- function popoverDirection() {
- if (!barEl || !selectedElement) return 'below';
- const br = barEl.getBoundingClientRect();
- const er = selectedElement.getBoundingClientRect();
- return br.top >= er.bottom - 4 ? 'below' : 'above';
- }
-
- // The popover overlaps the bar by OVERLAP px on the bar-facing side. With
- // popover z-index below bar, that overlap sits behind bar (invisible) and
- // reinforces the "tucked behind" feel. Padding compensates so the real
- // content starts flush with bar's outer edge.
- const TUNE_OVERLAP = 6;
-
- // Closed clip-path depends on direction: for 'below' clip from the far
- // (bottom) edge so the reveal grows downward from the bar; for 'above'
- // clip from the top edge so the reveal grows upward from the bar.
- function closedClipPath(direction) {
- return direction === 'below' ? 'inset(0 0 100% 0)' : 'inset(100% 0 0 0)';
- }
-
- function setClipPath(value, withTransition) {
- const saved = paramsPanelEl.style.transition;
- if (!withTransition) paramsPanelEl.style.transition = 'none';
- paramsPanelEl.style.clipPath = value;
- if (!withTransition) {
- void paramsPanelEl.offsetHeight;
- paramsPanelEl.style.transition = saved;
- }
- }
-
- function positionParamsPanel() {
- if (!paramsPanelEl || !barEl || barEl.style.display === 'none') return;
- const br = barEl.getBoundingClientRect();
- const direction = popoverDirection();
- const prevDirection = paramsPanelEl.dataset.tuneDirection;
-
- // top/left/width are NOT in the transition list, so they snap instantly.
- paramsPanelEl.style.left = br.left + 'px';
- paramsPanelEl.style.width = br.width + 'px';
-
- if (direction === 'below') {
- paramsPanelEl.style.top = (br.bottom - TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '0 0 10px 10px';
- paramsPanelEl.style.paddingTop = (14 + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.paddingBottom = '14px';
- } else {
- const ih = paramsPanelEl.offsetHeight || 80;
- paramsPanelEl.style.top = (br.top - ih + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '10px 10px 0 0';
- paramsPanelEl.style.paddingTop = '14px';
- paramsPanelEl.style.paddingBottom = (14 + TUNE_OVERLAP) + 'px';
- }
- paramsPanelEl.dataset.tuneDirection = direction;
-
- // If currently closed and direction flipped (or first-time setup),
- // snap the clip-path to the new direction's closed pose without
- // transitioning (so the clip doesn't slide across the element).
- if (!tuneOpen && (!prevDirection || prevDirection !== direction)) {
- setClipPath(closedClipPath(direction), false);
- }
- }
-
- function showParamsPanel() {
- if (!paramsPanelEl) return;
- positionParamsPanel();
- paramsPanelEl.style.pointerEvents = 'auto';
- // rAF so the positioning paint commits before the transition fires.
- requestAnimationFrame(() => {
- setClipPath('inset(0 0 0 0)', true);
- });
- }
-
- function hideParamsPanel() {
- if (!paramsPanelEl) return;
- paramsPanelEl.style.pointerEvents = 'none';
- const direction = paramsPanelEl.dataset.tuneDirection || 'below';
- setClipPath(closedClipPath(direction), true);
- }
-
- // Build/rebuild the panel's contents for the current variant AND apply
- // its defaults to the variant wrapper (so scoped CSS responds even before
- // the user opens the popover). Visibility is governed by tuneOpen.
- function refreshParamsPanel() {
- if (state !== 'CYCLING') {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- if (tuneOpen) {
- // If already visible (variant cycled while open), refresh in place
- // instead of re-running the clip-path animation.
- const alreadyVisible = paramsPanelEl.style.display === 'block'
- && paramsPanelEl.style.opacity === '1';
- if (alreadyVisible) positionParamsPanel();
- else showParamsPanel();
- } else {
- hideParamsPanel();
- }
- }
-
- function toggleTunePopover() {
- if (tuneOpen) { closeTunePopover(); return; }
- openTunePopover();
- }
-
- function openTunePopover() {
- if (state !== 'CYCLING') return;
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) return;
- // Build fresh to ensure the current variant's controls are shown.
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- tuneOpen = true;
- showParamsPanel();
- // Kill the bar's shadow on the popover-facing side so the dark popover
- // doesn't pick up a bright glow line.
- if (barEl) {
- const direction = paramsPanelEl?.dataset.tuneDirection || 'below';
- barEl.style.boxShadow = direction === 'below' ? BAR_SHADOW_UP : BAR_SHADOW_DOWN;
- }
- // Re-render the bar so the Tune chip picks up the active styling.
- updateBarContent('cycling');
- }
-
- function closeTunePopover() {
- tuneOpen = false;
- hideParamsPanel();
- if (barEl) barEl.style.boxShadow = BAR_SHADOW_DEFAULT;
- if (barEl && barEl.style.display !== 'none' && state === 'CYCLING') {
- updateBarContent('cycling');
- }
- }
-
- // ---------------------------------------------------------------------------
- // Variant cycling in DOM
- // ---------------------------------------------------------------------------
-
- function showVariantInDOM(sessionId, num) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
- for (const child of wrapper.children) {
- const v = child.dataset ? child.dataset.impeccableVariant : null;
- if (!v) continue;
- child.style.display = (v === String(num)) ? '' : 'none';
- }
- // Unconditional refresh — covers first-reveal (no-op if state isn't
- // CYCLING yet, the subsequent CYCLING transition triggers its own
- // refresh) and every cycle step.
- refreshParamsPanel();
- }
-
- /**
- * No-HMR fallback: fetch the raw source file from the live server,
- * parse it, extract the variant wrapper, and inject it into the live DOM.
- * This works even when the dev server caches HTML (Bun, static servers).
- */
- function injectVariantsFromSource(filePath, sessionId) {
- const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
- fetch(url)
- .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
- .then(html => {
- // Parse the raw source HTML
- const parser = new DOMParser();
- const doc = parser.parseFromString(html, 'text/html');
- const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!srcWrapper) {
- console.error('[impeccable] Variant wrapper not found in source file.');
- return;
- }
-
- // Find the original element in the live DOM.
- // The original is inside the wrapper in the source. We find the
- // corresponding element in the live DOM by matching the first child's
- // tag + classes from the original snapshot.
- const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
- if (!origContent) return;
-
- const tag = origContent.tagName.toLowerCase();
- const cls = origContent.className;
- let liveEl = null;
- if (origContent.id) {
- liveEl = document.getElementById(origContent.id);
- } else if (cls) {
- // Find by tag + exact class match
- const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
- for (const c of candidates) {
- if (c.className === cls && !own(c)) { liveEl = c; break; }
- }
- }
-
- if (!liveEl) {
- console.error('[impeccable] Could not find original element in live DOM.');
- return;
- }
-
- const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;
-
- // Replace the live element with the full wrapper from source
- const wrapper = srcWrapper.cloneNode(true);
- liveEl.parentElement.replaceChild(wrapper, liveEl);
-
- // Update state: count variants, preserving the user's current variant
- // when a late HMR/source reinjection lands after they have cycled.
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants
- ? previousVisibleVariant
- : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);
- showVariantInDOM(sessionId, visibleVariant);
-
- // Update selectedElement to the visible variant's content
- selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;
-
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- saveSession();
- console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
- })
- .catch(err => {
- console.error('[impeccable] Failed to fetch source:', err);
- showToast('Could not load variants. Try refreshing the page.', 5000);
- });
- }
-
- function cycleVariant(dir) {
- const next = visibleVariant + dir;
- if (next < 1 || next > arrivedVariants) return;
- visibleVariant = next;
- showVariantInDOM(currentSessionId, next); // calls refreshParamsPanel itself
- updateSelectedElement();
- updateBarContent('cycling');
- saveSession();
- queueCheckpoint('variant_changed');
- }
-
- function updateSelectedElement() {
- if (!currentSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return;
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- function readVisibleVariantFromDOM(sessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return 0;
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- for (const variant of variants) {
- if (variant.style.display === 'none') continue;
- const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);
- if (idx > 0) return idx;
- }
- return 0;
- }
-
- // Resolve the element that represents the variant's visible content.
- // Contract: each variant div should contain exactly one top-level element
- // (the full replacement). In practice a model may ship loose siblings or
- // lead with <style>/<script>. Be defensive: skip non-visual elements, and
- // if the variant has multiple element children, use the variant div itself
- // (it wraps all of them and gets correct bounds).
- function pickVariantContent(wrapper, index) {
- if (!wrapper) return null;
- const variantDiv = wrapper.querySelector('[data-impeccable-variant="' + index + '"]');
- if (!variantDiv) return null;
- const NON_VISUAL = new Set(['STYLE', 'SCRIPT', 'LINK', 'META', 'TEMPLATE']);
- const visual = [];
- for (const child of variantDiv.children) {
- if (!NON_VISUAL.has(child.tagName)) visual.push(child);
- }
- if (visual.length === 1) return visual[0];
- return variantDiv;
- }
-
- // Hold window.scrollY at a fixed value across DOM mutations inside the
- // session's wrapper (HMR patches, variant inserts, cycle swaps).
- function startScrollLock(sessionId, initialTargetY) {
- stopScrollLock();
- scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)
- ? initialTargetY
- : window.scrollY;
- console.log('[impeccable.scroll] startScrollLock', { sessionId, scrollY: window.scrollY, targetY: scrollLockTargetY, initialOverride: initialTargetY });
-
- try { history.scrollRestoration = 'manual'; } catch {}
-
- const prevHtmlAnchor = document.documentElement.style.overflowAnchor;
- const prevBodyAnchor = document.body.style.overflowAnchor;
- document.documentElement.style.overflowAnchor = 'none';
- document.body.style.overflowAnchor = 'none';
-
- const correct = (why) => {
- scrollLockRaf = null;
- if (scrollLockTargetY == null) return;
- const before = window.scrollY;
- const delta = before - scrollLockTargetY;
- if (Math.abs(delta) < 0.5) {
- console.log('[impeccable.scroll] correct noop', { why, scrollY: before, targetY: scrollLockTargetY });
- return;
- }
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] corrected', { why, from: before, to: scrollLockTargetY, delta, nowAt: window.scrollY });
- };
- const schedule = (why) => {
- if (scrollLockRaf != null) return;
- scrollLockRaf = requestAnimationFrame(() => correct(why));
- };
-
- scrollLockObserver = new MutationObserver((mutations) => {
- for (const m of mutations) {
- if (m.target?.closest?.('[data-impeccable-variants="' + sessionId + '"]')) {
- const childAdds = Array.from(m.addedNodes).map(n => n.nodeType === 1 ? (n.tagName + (n.dataset?.impeccableVariant ? ('[variant=' + n.dataset.impeccableVariant + ']') : '')) : n.nodeType).join(',');
- console.log('[impeccable.scroll] mutation inside wrapper', { type: m.type, target: m.target?.tagName, adds: childAdds, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('mutation-in-wrapper');
- return;
- }
- for (const n of m.addedNodes) {
- if (n.nodeType === 1 && (n.matches?.('[data-impeccable-variants="' + sessionId + '"]') || n.querySelector?.('[data-impeccable-variants="' + sessionId + '"]'))) {
- console.log('[impeccable.scroll] wrapper node added', { tag: n.tagName, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('wrapper-added');
- return;
- }
- }
- }
- });
- scrollLockObserver.observe(document.body, { childList: true, subtree: true });
-
- scrollLockAbort = new AbortController();
- scrollLockAbort.signal.addEventListener('abort', () => {
- document.documentElement.style.overflowAnchor = prevHtmlAnchor;
- document.body.style.overflowAnchor = prevBodyAnchor;
- }, { once: true });
- const sig = { signal: scrollLockAbort.signal };
- // Track whether the most recent scroll came from a user gesture. We
- // gate user-scroll re-anchoring on this flag so programmatic smooth
- // scrolls (browser reload-restore, scrollIntoView from other scripts)
- // don't accidentally update our target.
- let userGestureAt = 0;
- const USER_GESTURE_WINDOW_MS = 250;
-
- const reanchor = (why) => {
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- const prevTarget = scrollLockTargetY;
- scrollLockTargetY = window.scrollY;
- writeScrollY(scrollLockTargetY);
- console.log('[impeccable.scroll] reanchor', { why, prevTarget, newTarget: scrollLockTargetY });
- };
- const markGesture = (why) => {
- userGestureAt = performance.now();
- reanchor(why);
- };
- window.addEventListener('wheel', () => markGesture('wheel'), { passive: true, ...sig });
- window.addEventListener('touchstart', () => markGesture('touchstart'), { passive: true, ...sig });
- window.addEventListener('touchmove', () => markGesture('touchmove'), { passive: true, ...sig });
- window.addEventListener('keydown', (e) => {
- if (['PageDown', 'PageUp', ' ', 'End', 'Home', 'ArrowDown', 'ArrowUp'].includes(e.key)) markGesture('key:' + e.key);
- }, sig);
-
- // Correct on EVERY scroll event: whether it's the browser's
- // post-reload animated restore or some other script calling
- // scrollIntoView, we want to snap back immediately. Only skip if a
- // user gesture fired in the last 250ms.
- let lastLoggedScrollY = window.scrollY;
- window.addEventListener('scroll', () => {
- const now = window.scrollY;
- if (Math.abs(now - lastLoggedScrollY) > 5) {
- console.log('[impeccable.scroll] scroll event', { from: lastLoggedScrollY, to: now, targetY: scrollLockTargetY });
- lastLoggedScrollY = now;
- }
- if (scrollLockTargetY == null) return;
- if (performance.now() - userGestureAt < USER_GESTURE_WINDOW_MS) return;
- if (Math.abs(now - scrollLockTargetY) < 0.5) return;
- console.log('[impeccable.scroll] scroll-event snap', { from: now, to: scrollLockTargetY });
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- }, { passive: true, ...sig });
-
- // Apply target synchronously, not via rAF — racing the browser's
- // restore or a smooth-scroll animation means we want to win now.
- if (Math.abs(window.scrollY - scrollLockTargetY) > 0.5) {
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] startScrollLock initial apply', { to: scrollLockTargetY });
- }
- }
-
- function stopScrollLock() {
- if (scrollLockObserver) { scrollLockObserver.disconnect(); scrollLockObserver = null; }
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }
- scrollLockTargetY = null;
- // NOTE: do NOT clear the persistent scroll key here. startScrollLock
- // calls us as a reset, and clearing the key would nuke the Go-time
- // scrollY that the next resume needs to read.
- }
-
- // ---------------------------------------------------------------------------
- // MutationObserver for progressive variant reveal
- // ---------------------------------------------------------------------------
-
- function startVariantObserver(sessionId) {
- let updating = false; // re-entrancy guard
-
- const obs = new MutationObserver((mutations) => {
- if (updating) return;
-
- // Only react to mutations that add nodes with data-impeccable-variant,
- // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
- let dominated = false;
- for (const m of mutations) {
- if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
- for (const n of m.addedNodes) {
- if (n.nodeType !== 1) continue;
- // Direct hit: the added node itself is the wrapper or a variant.
- if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
- dominated = true; break;
- }
- // Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
- // a whole subtree where the wrapper is a descendant of the added
- // node. Without this check, the observer ignores those mutations
- // and the session stays in GENERATING forever.
- if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
- dominated = true; break;
- }
- }
- if (dominated) break;
- }
- if (!dominated) return;
-
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
-
- // Re-anchor selectedElement if it was detached by live-wrap's HMR swap.
- // Without this, the shader / highlight / bar track a zero-rect phantom
- // and the overlay appears frozen.
- if (selectedElement && !document.body.contains(selectedElement)) {
- selectedElement = pickVariantContent(wrapper, 'original') || wrapper;
- }
-
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- const count = variants.length;
-
- // Nothing new
- if (count <= arrivedVariants) return;
-
- updating = true;
- arrivedVariants = count;
- if (visibleVariant === 0 && arrivedVariants > 0) {
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;
- showVariantInDOM(sessionId, visibleVariant);
- // showVariantInDOM hid the original (display:none); if we were still
- // anchored to the original's content, its boundingRect is now zero
- // and the bar snaps to (0,0). Re-point at the visible variant instead.
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- if (expected > 0) expectedVariants = expected;
-
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- } else if (state === 'GENERATING') {
- updateBarContent('generating');
- }
- saveSession();
- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');
- updating = false;
- });
-
- obs.observe(document.body, { childList: true, subtree: true });
- return obs;
- }
-
- // ---------------------------------------------------------------------------
- // Bar scroll tracking
- // ---------------------------------------------------------------------------
-
- function startScrollTracking() {
- function tick() {
- if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
- positionBar();
- showHighlight(selectedElement);
- if (tuneOpen) positionParamsPanel();
- }
- if (annotActive) positionAnnotOverlay(selectedElement);
- // Shader overlay (via debug P toggle or generation) is repositioned
- // by its own branch below; debug no longer has a separate overlay.
- if (shaderState) positionShaderOverlay();
- scrollRaf = requestAnimationFrame(tick);
- }
- scrollRaf = requestAnimationFrame(tick);
- }
-
- function stopScrollTracking() {
- if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
- }
-
- // ---------------------------------------------------------------------------
- // SSE (server→browser) + fetch POST (browser→server)
- // Zero-dependency replacement for WebSocket.
- // ---------------------------------------------------------------------------
-
- let evtSource = null;
- let sseRetries = 0;
- const SSE_MAX_RETRIES = 20; // generous: heartbeats keep the connection alive, so retries mean real trouble
-
- function connectSSE() {
- evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
-
- evtSource.onopen = () => {
- sseRetries = 0; // reset on successful (re)connect
- };
-
- evtSource.onmessage = (e) => {
- sseRetries = 0; // reset on any successful message
- let msg; try { msg = JSON.parse(e.data); } catch { return; }
- switch (msg.type) {
- case 'connected':
- hasProjectContext = !!msg.hasProjectContext;
- if (!hasProjectContext) showToast('No PRODUCT.md found. Variants will be brand-agnostic. Run /impeccable teach to generate one.', 7000);
- console.log('[impeccable] Live mode connected.');
- if (state === 'IDLE') state = 'PICKING';
- break;
- case 'done':
- // Variants already arrived via HMR → normal transition.
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- if (state === 'GENERATING') {
- state = 'CYCLING';
- updateBarContent('cycling');
- refreshParamsPanel();
- }
- break;
- }
- // Variants are in source but not in the DOM yet. Common when the
- // picked element lived inside conditional render (closed modal,
- // hidden tab, a route the user navigated away from). The variant
- // MutationObserver stays armed and auto-transitions to CYCLING
- // the moment the wrapper actually mounts. Nudge the user toward
- // that path with a toast — better than the prior force-reload
- // which reset framework state and left the session stuck.
- setTimeout(() => {
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
- if (state !== 'GENERATING') return;
- showToast(
- "Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
- 15000,
- );
- }, 2000);
- break;
- case 'error':
- console.error('[impeccable] Error:', msg.message);
- showToast('Error: ' + msg.message, 5000);
- hideBar();
- state = 'PICKING';
- break;
- }
- };
-
- evtSource.onerror = () => {
- sseRetries++;
- if (sseRetries <= SSE_MAX_RETRIES) {
- console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
- return; // EventSource auto-reconnects
- }
- // Server is gone. Clean up gracefully.
- console.log('[impeccable] Live server unreachable. Cleaning up UI.');
- evtSource.close();
- evtSource = null;
- handleServerLost();
- };
- }
-
- /** Server died or became unreachable. Reset UI to a clean state. */
- function handleServerLost() {
- const recoveryState = currentSessionId ? state : 'IDLE';
- if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
- showToast('Live server disconnected. Session ended.', 5000);
- }
- hideBar();
- hideHighlight();
- hideShaderOverlay();
- hideAnnotOverlay();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- // Preserve local session state on server loss. The durable journal is the
- // source of truth, but localStorage plus the variant wrapper lets the UI
- // resume after a helper restart or page reload instead of treating a
- // transient disconnect as an explicit discard.
- selectedElement = null;
- selectedAction = 'impeccable';
- state = recoveryState;
- if (currentSessionId) saveSession();
- }
-
- function sendEvent(msg, opts) {
- msg.token = TOKEN;
- function handleFailure(err) {
- console.error('[impeccable] Failed to send event:', err);
- if (opts && opts.throwOnError) throw err;
- return null;
- }
- return fetch('http://localhost:' + PORT + '/events', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(msg),
- }).then(res => {
- if (res.ok) return res;
- return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));
- }).catch(handleFailure);
- }
-
- function checkpointPayload(reason) {
- return {
- type: 'checkpoint',
- id: currentSessionId,
- revision: sessionState.nextCheckpointRevision(),
- owner: browserOwner,
- phase: String(state || '').toLowerCase(),
- reason,
- pageUrl: location.pathname,
- expectedVariants,
- arrivedVariants,
- visibleVariant,
- paramValues: { ...paramsCurrentValues },
- };
- }
-
- function sendCheckpoint(reason) {
- if (!currentSessionId) return Promise.resolve(null);
- return sendEvent(checkpointPayload(reason)).catch(() => null);
- }
-
- function queueCheckpoint(reason) {
- if (!currentSessionId) return;
- if (checkpointTimer) clearTimeout(checkpointTimer);
- checkpointTimer = setTimeout(() => {
- checkpointTimer = null;
- sendCheckpoint(reason);
- }, 120);
- }
-
- // ---------------------------------------------------------------------------
- // Event handlers
- // ---------------------------------------------------------------------------
-
- function handleMouseMove(e) {
- if (state !== 'PICKING' || !pickActive) return;
- const target = document.elementFromPoint(e.clientX, e.clientY);
- if (!target || !pickable(target) || target === hoveredElement) return;
- hoveredElement = target;
- showHighlight(target);
- }
-
- function handleClick(e) {
- // Close action picker on any outside click
- if (pickerEl?.style.display !== 'none' && !own(e.target)) {
- hideActionPicker();
- }
- // Close Tune popover on outside click (anything outside panel + bar)
- if (tuneOpen && paramsPanelEl && !paramsPanelEl.contains(e.target) && barEl && !barEl.contains(e.target)) {
- closeTunePopover();
- }
- // In CONFIGURING: click outside the bar and selected element returns to PICKING
- if (state === 'CONFIGURING' && !own(e.target) && selectedElement && !selectedElement.contains(e.target)) {
- hideBar();
- stopScrollTracking();
- hideAnnotOverlay();
- clearAnnotations();
- state = 'PICKING';
- hoveredElement = null;
- hideHighlight();
- return;
- }
- if (state !== 'PICKING' || !pickActive) return;
- if (own(e.target)) return;
- if (!hoveredElement || !pickable(hoveredElement)) return;
- e.preventDefault();
- e.stopPropagation();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- maybePrefetchPage();
- maybeWarnConditionalAncestor(selectedElement);
- }
-
- /**
- * Surface a brief, non-blocking heads-up when the picked element lives
- * inside a container whose visibility is gated by ephemeral state — modals,
- * collapsible panels, popovers, off-screen tab panels. If HMR remounts the
- * parent during generation (Vite Fast Refresh, SvelteKit page reload), the
- * variants land in source but stay invisible until the user re-opens the
- * container. Telling the user upfront is much friendlier than the silent
- * timeout-then-toast that they'd otherwise hit.
- *
- * Heuristic, intentionally narrow — only fires for unambiguous cases so
- * we don't cry wolf on every nested element.
- */
- function maybeWarnConditionalAncestor(el) {
- let node = el?.parentElement;
- let depth = 0;
- while (node && depth < 12) {
- // 1. Active dialog / modal
- if (node.getAttribute && node.getAttribute('role') === 'dialog'
- && node.getAttribute('aria-modal') === 'true') {
- showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 2. Common Radix / shadcn / headless-ui open-state attribute
- if (node.dataset && node.dataset.state === 'open') {
- showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 3. Tab panel — only meaningful when the page also shows ANOTHER
- // tab as selected. A single tabpanel with no tablist is just a static
- // section in disguise and isn't conditional.
- if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
- const list = document.querySelector('[role="tablist"]');
- if (list) {
- const tabs = list.querySelectorAll('[role="tab"]');
- if (tabs.length > 1) {
- showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
- return;
- }
- }
- }
- // 4. Collapsible: aria-expanded sibling. Look for the trigger button.
- if (node.id) {
- const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
- if (trigger) {
- showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
- return;
- }
- }
- node = node.parentElement;
- depth++;
- }
- }
-
- // Fire a lightweight prefetch event the first time the user selects an
- // element on a given route. The agent uses this to Read the underlying file
- // into context before Go is hit, shaving the read off the critical path.
- // Dedupe per session by pathname — clicking around on the same page doesn't
- // re-fire.
- //
- // DISABLED: quick-Go workflows pay an extra harness round trip because
- // prefetch + generate arrive as two events instead of one. Re-enable with
- // a browser-side debounce (~800–1000ms, cancelled on Go) if we want to
- // resurrect this. Server validator and skill dispatch remain in place so
- // flipping this flag is the only change needed.
- const PREFETCH_ENABLED = false;
- const prefetchedPaths = new Set();
- function maybePrefetchPage() {
- if (!PREFETCH_ENABLED) return;
- const path = location.pathname;
- if (prefetchedPaths.has(path)) return;
- prefetchedPaths.add(path);
- sendEvent({ type: 'prefetch', pageUrl: path });
- }
-
- function handleKeyDown(e) {
- // When the annotation input is focused, let it handle its own keys.
- if (annotEditing && annotEditing.input && e.target === annotEditing.input) return;
- if (e.key === 'Escape') {
- e.preventDefault();
- if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
- if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); hideAnnotOverlay(); clearAnnotations(); state = 'PICKING'; return; }
- if (state === 'CYCLING') { handleDiscard(); return; }
- if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
- if (state === 'PICKING') {
- // Use togglePick so the "Pick" button in the global bar also flips
- // off, otherwise the bar stays lit while nothing else is active.
- if (pickActive) togglePick();
- else { hideHighlight(); state = 'IDLE'; }
- return;
- }
- }
-
- // Arrow/Enter nav works in PICKING (hover) and CONFIGURING (selected, input empty)
- var navEl = (state === 'PICKING') ? hoveredElement : (state === 'CONFIGURING') ? selectedElement : null;
- if (navEl && (e.key === 'ArrowUp' || e.key === 'ArrowDown' || (e.key === 'Enter' && state === 'PICKING'))) {
- let next = null;
- if (e.key === 'ArrowDown' && !e.shiftKey) {
- next = navEl.nextElementSibling;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'ArrowUp' && !e.shiftKey) {
- next = navEl.previousElementSibling;
- while (next && !pickable(next)) next = next.previousElementSibling;
- } else if (e.key === 'ArrowUp' && e.shiftKey) {
- next = navEl.parentElement;
- if (next && !pickable(next)) next = null;
- } else if (e.key === 'ArrowDown' && e.shiftKey) {
- next = navEl.firstElementChild;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'Enter') {
- e.preventDefault();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- return;
- }
- if (next) {
- e.preventDefault();
- if (state === 'PICKING') {
- hoveredElement = next;
- } else {
- // CONFIGURING: re-select the new element and refresh the bar
- selectedElement = next;
- clearAnnotations();
- showAnnotOverlay(next);
- showBar('configure');
- startScrollTracking();
- }
- showHighlight(next);
- next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
- }
- return;
- }
-
- if (state === 'CYCLING') {
- if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
- if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
- if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
- }
- }
-
- function handleGo() {
- if (!selectedElement || state !== 'CONFIGURING') return;
- const input = document.getElementById(PREFIX + '-input');
- const prompt = input ? input.value.trim() : '';
-
- // Commit any pending pin edit BEFORE we snapshot annotations.
- if (annotEditing) finalizeEditingPin();
-
- currentSessionId = id8();
- expectedVariants = selectedCount;
- arrivedVariants = 0;
- visibleVariant = 0;
-
- // Flip to GENERATING immediately so the bar morphs without waiting on
- // capture + upload. The event is emitted from captureAndEmit() once the
- // screenshot is uploaded (or capture fails — we still emit, just without
- // screenshotPath).
- const elForCapture = selectedElement;
- const captureRect = elForCapture.getBoundingClientRect();
- const snapshot = {
- comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),
- strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),
- };
- const basePayload = {
- type: 'generate', id: currentSessionId,
- action: selectedAction,
- freeformPrompt: prompt || undefined,
- count: selectedCount,
- pageUrl: location.pathname,
- element: extractContext(elForCapture),
- };
- if (snapshot.comments.length > 0) basePayload.comments = snapshot.comments;
- if (snapshot.strokes.length > 0) basePayload.strokes = snapshot.strokes;
-
- // Hide the interactive overlay so it doesn't linger during generation.
- hideAnnotOverlay();
- clearAnnotations();
-
- state = 'GENERATING';
- showBar('generating');
- saveSession();
- sendCheckpoint('generate_started');
- writeScrollY(window.scrollY);
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
- console.log('[impeccable.scroll] Go pressed', { scrollY: window.scrollY, sessionId: currentSessionId });
- startScrollLock(currentSessionId);
-
- captureAndEmit(elForCapture, basePayload, snapshot, captureRect);
- }
-
- // ---------------------------------------------------------------------------
- // Screenshot capture + upload
- // ---------------------------------------------------------------------------
-
- let msLoadPromise = null;
- function loadModernScreenshot() {
- if (window.modernScreenshot) return Promise.resolve(window.modernScreenshot);
- if (msLoadPromise) return msLoadPromise;
- msLoadPromise = new Promise((resolve, reject) => {
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/modern-screenshot.js';
- s.onload = () => resolve(window.modernScreenshot);
- s.onerror = () => { msLoadPromise = null; reject(new Error('modern-screenshot failed to load')); };
- document.head.appendChild(s);
- });
- return msLoadPromise;
- }
-
- // Collect @font-face rules from every stylesheet on the page. Cross-origin
- // sheets (Google Fonts, Typekit, etc.) throw SecurityError on .cssRules
- // access, so modern-screenshot can't embed them on its own — the resulting
- // SVG falls back to system fonts and text re-wraps + renders with different
- // weight. We fetch the raw CSS text (CORS-permitted for these providers),
- // extract @font-face blocks, inline the referenced font files as base64
- // data URIs (SVGs rasterized via canvas can't fetch external resources,
- // so URLs inside the SVG silently fail without this), and pass the result
- // to modern-screenshot as font.cssText.
- const FONT_EXT_RE = /\.(woff2?|ttf|otf|eot)(\?.*)?$/i;
- const FONT_MIME = {
- woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', eot: 'application/vnd.ms-fontobject',
- };
- function bufferToBase64(buf) {
- const bytes = new Uint8Array(buf);
- let binary = '';
- const CHUNK = 0x8000;
- for (let i = 0; i < bytes.length; i += CHUNK) {
- binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
- }
- return btoa(binary);
- }
- async function inlineFontUrls(cssText) {
- const urlRe = /url\((['"]?)(https?:\/\/[^'")\s]+)\1\)/g;
- const urls = new Set();
- let m;
- while ((m = urlRe.exec(cssText))) {
- if (FONT_EXT_RE.test(m[2])) urls.add(m[2]);
- }
- const map = new Map();
- await Promise.all([...urls].map(async (url) => {
- try {
- const res = await fetch(url);
- if (!res.ok) return;
- const buf = await res.arrayBuffer();
- const ext = url.toLowerCase().match(FONT_EXT_RE)?.[1] || 'woff2';
- const mime = FONT_MIME[ext] || 'application/octet-stream';
- map.set(url, 'data:' + mime + ';base64,' + bufferToBase64(buf));
- } catch { /* skip; fall through to URL */ }
- }));
- return cssText.replace(urlRe, (orig, q, url) => {
- const data = map.get(url);
- return data ? 'url(' + q + data + q + ')' : orig;
- });
- }
- async function collectFontCssText() {
- const chunks = [];
- const fontFaceRe = /@font-face\s*\{[^}]*\}/g;
- for (const sheet of document.styleSheets) {
- try {
- const rules = sheet.cssRules;
- for (const rule of rules) {
- if (rule.constructor.name === 'CSSFontFaceRule' || rule.cssText?.startsWith('@font-face')) {
- chunks.push(rule.cssText);
- }
- }
- } catch {
- if (!sheet.href) continue;
- try {
- const res = await fetch(sheet.href);
- if (!res.ok) continue;
- const text = await res.text();
- let m2;
- while ((m2 = fontFaceRe.exec(text))) chunks.push(m2[0]);
- } catch { /* ignore; capture is best-effort */ }
- }
- }
- if (chunks.length === 0) return '';
- return inlineFontUrls(chunks.join('\n'));
- }
-
- // True if `s` is a computed color string that renders as nothing
- // (explicit `transparent`, or `rgba(...)` with alpha 0).
- function isTransparentColor(s) {
- if (!s) return true;
- if (s === 'transparent') return true;
- const m = /rgba?\(([^)]+)\)/.exec(s);
- if (!m) return false;
- const parts = m[1].split(',').map((p) => p.trim());
- if (parts.length === 4) return parseFloat(parts[3]) === 0;
- return false;
- }
-
- // modern-screenshot force-sets `background-color: X !important` on the
- // cloned root whenever `backgroundColor` is passed, clobbering the
- // element's own background. So we only pass it when the element is
- // genuinely transparent (no own color, no own image) — in that case
- // we resolve up the DOM to the nearest opaque ancestor so the capture
- // sits on the page's real background instead of rendering black.
- function resolveCanvasBackground(el) {
- const own = getComputedStyle(el);
- if (!isTransparentColor(own.backgroundColor)) return null;
- if (own.backgroundImage && own.backgroundImage !== 'none') return null;
- let node = el.parentElement;
- while (node) {
- const cs = getComputedStyle(node);
- if (!isTransparentColor(cs.backgroundColor)) return cs.backgroundColor;
- node = node.parentElement;
- }
- // The walk already passed through <body> and <html>; if they had been
- // opaque we would have returned. Falling through with the previous
- // `getComputedStyle(body).backgroundColor || …` chain is a trap: that
- // call returns the literal string `"rgba(0, 0, 0, 0)"` for a page that
- // never set its own bg, which is truthy and short-circuits the chain to
- // transparent-black — modern-screenshot then renders the capture on a
- // black canvas and the shader overlay flashes solid black during load.
- // The browser canvas defaults to white, so we do too.
- return '#ffffff';
- }
-
- // Capture the element (with current annotations baked in) and return a PNG
- // Blob. Shared between the Go flow (uploads it to the server) and the
- // debug toggle (displays it as an overlay for side-by-side comparison).
- async function captureElementToBlob(el, snapshot, rect) {
- try { if (document.fonts?.ready) await document.fonts.ready; } catch {}
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- let annotNode = null;
- let savedPosition = null;
- if (hasAnnotations) {
- const pos = getComputedStyle(el).position;
- if (pos === 'static') {
- savedPosition = el.style.position;
- el.style.position = 'relative';
- }
- annotNode = buildAnnotationsForCapture(rect, snapshot);
- el.appendChild(annotNode);
- }
- try {
- const ms = await loadModernScreenshot();
- const fontCssText = await collectFontCssText();
- const backgroundColor = resolveCanvasBackground(el);
- return await ms.domToBlob(el, {
- scale: Math.min(window.devicePixelRatio || 1, 2),
- font: fontCssText ? { cssText: fontCssText } : undefined,
- ...(backgroundColor ? { backgroundColor } : {}),
- });
- } finally {
- if (annotNode) annotNode.remove();
- if (savedPosition !== null) el.style.position = savedPosition;
- }
- }
-
- async function captureAndEmit(el, basePayload, snapshot, rect) {
- let screenshotPath;
- let blob;
- try {
- blob = await captureElementToBlob(el, snapshot, rect);
- } catch (err) {
- console.warn('[impeccable] capture failed, proceeding without screenshot:', err);
- }
- // Light up the shader overlay the moment capture is ready — no reason to
- // wait for the upload to complete before the user sees something alive.
- if (blob && state === 'GENERATING') {
- showShaderOverlay(el, blob, rect);
- }
- // Only upload + forward the screenshot when annotations (comments/strokes)
- // are present. Without annotations the image is pure visual anchoring —
- // it biases the model toward the current rendering and works against the
- // three-distinct-directions brief.
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- if (blob && hasAnnotations) {
- try {
- const uploadRes = await fetch(
- 'http://localhost:' + PORT + '/annotation?token=' + encodeURIComponent(TOKEN) +
- '&eventId=' + encodeURIComponent(basePayload.id),
- { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: blob },
- );
- if (uploadRes.ok) {
- const { path: p } = await uploadRes.json();
- screenshotPath = p;
- } else {
- console.warn('[impeccable] annotation upload failed:', uploadRes.status);
- }
- } catch (err) {
- console.warn('[impeccable] annotation upload failed:', err);
- }
- }
- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);
- }
-
- // ---------------------------------------------------------------------------
- // Shader overlay — renders the captured screenshot as a WebGL texture and
- // runs an editorial "ink-wash" fragment shader over it during generation.
- // A single rolling band sweeps top-to-bottom, desaturating + tinting magenta
- // and leaving a soft trail. Makes the wait feel like a letterpress scan
- // instead of a dead spinner.
- // ---------------------------------------------------------------------------
-
- const SHADER_VS = `attribute vec2 a_position;
-attribute vec2 a_uv;
-varying vec2 v_uv;
-void main() {
- v_uv = a_uv;
- gl_Position = vec4(a_position, 0.0, 1.0);
-}`;
-
- const SHADER_FS = `precision highp float;
-uniform sampler2D u_texture;
-uniform float u_time;
-uniform vec2 u_resolution;
-uniform vec3 u_accent;
-varying vec2 v_uv;
-
-// Asymmetric roller band. Product of two one-sided smoothsteps — peaks at
-// d=0 with a short sharp leading ramp and a longer soft trailing tail. Clean
-// outside the [-leadW, trailW] range (no rogue "trail=1 everywhere below"
-// failure that reversed-edge smoothstep would give).
-float bandAt(float d, float leadW, float trailW) {
- float above = smoothstep(-leadW, 0.0, d);
- float below = 1.0 - smoothstep(0.0, trailW, d);
- return above * below;
-}
-
-void main() {
- vec2 uv = v_uv;
- // Roller sweeps top-to-bottom with small overshoot so each cycle enters
- // and exits the element cleanly.
- float phase = fract(u_time / 3.4);
- float y = phase * 1.25 - 0.12;
- float band = bandAt(uv.y - y, 0.05, 0.32);
-
- // Halftone cell grid (fixed ~10 px pitch).
- float cellPx = 10.0;
- vec2 gridUv = uv * u_resolution / cellPx;
- vec2 cellId = floor(gridUv);
- vec2 cellUv = fract(gridUv) - 0.5;
- vec2 sampleCenter = (cellId + 0.5) * cellPx / u_resolution;
- vec3 cellImg = texture2D(u_texture, sampleCenter).rgb;
- float luma = dot(cellImg, vec3(0.299, 0.587, 0.114));
- // Darker cells → bigger magenta dots (classic risograph halftone curve).
- float radius = sqrt(clamp(1.0 - luma, 0.0, 1.0)) * 0.56;
- float dotMask = smoothstep(radius + 0.06, radius, length(cellUv));
- vec3 paper = vec3(0.975, 0.965, 0.955);
- vec3 dotLayer = mix(paper, u_accent, dotMask);
-
- // Blend the halftone layer in where the roller is passing; leave the
- // element pristine elsewhere.
- vec3 base = texture2D(u_texture, uv).rgb;
- gl_FragColor = vec4(mix(base, dotLayer, band), 1.0);
-}`;
-
- // Editorial Magenta converted to approximate sRGB 0-1 (matches oklch(60% 0.25 350))
- const SHADER_ACCENT = [0.82, 0.16, 0.47];
- let shaderState = null; // { canvas, gl, program, texture, rafId, startTime }
-
- function compileShader(gl, type, source) {
- const sh = gl.createShader(type);
- gl.shaderSource(sh, source);
- gl.compileShader(sh);
- if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
- const info = gl.getShaderInfoLog(sh);
- gl.deleteShader(sh);
- throw new Error('shader compile failed: ' + info);
- }
- return sh;
- }
-
- function positionShaderOverlay() {
- if (!shaderState || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- Object.assign(shaderState.canvas.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- }
-
- function hideShaderOverlay() {
- if (!shaderState) return;
- if (shaderState.rafId) cancelAnimationFrame(shaderState.rafId);
- if (shaderState.canvas) shaderState.canvas.remove();
- const lose = shaderState.gl?.getExtension?.('WEBGL_lose_context');
- try { lose?.loseContext(); } catch {}
- shaderState = null;
- }
-
- async function showShaderOverlay(el, blob, rect) {
- hideShaderOverlay();
- if (!blob || !el) return;
- const canvas = document.createElement('canvas');
- canvas.id = PREFIX + '-shader';
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
- canvas.width = Math.max(1, Math.floor(rect.width * dpr));
- canvas.height = Math.max(1, Math.floor(rect.height * dpr));
- Object.assign(canvas.style, {
- position: 'fixed',
- top: rect.top + 'px', left: rect.left + 'px',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none',
- zIndex: Z.bar - 1,
- });
- document.body.appendChild(canvas);
-
- const gl = canvas.getContext('webgl', { premultipliedAlpha: false, preserveDrawingBuffer: false })
- || canvas.getContext('experimental-webgl');
- if (!gl) {
- // WebGL unavailable — fall back to a plain <img> overlay so the user
- // still sees something meaningful during generation.
- canvas.remove();
- const img = document.createElement('img');
- img.src = URL.createObjectURL(blob);
- img.id = PREFIX + '-shader';
- // Copy positioning via cssText. Object.assign across CSSStyleDeclaration
- // throws in modern Chromium because the source's indexed properties
- // (style[0], [1], ...) are read-only and the engine forbids writing
- // them on the destination.
- img.style.cssText = canvas.style.cssText;
- img.style.outline = '2px dashed ' + C.brand;
- img.style.outlineOffset = '-2px';
- document.body.appendChild(img);
- shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
- return;
- }
-
- let program, texture;
- try {
- const vs = compileShader(gl, gl.VERTEX_SHADER, SHADER_VS);
- const fs = compileShader(gl, gl.FRAGMENT_SHADER, SHADER_FS);
- program = gl.createProgram();
- gl.attachShader(program, vs);
- gl.attachShader(program, fs);
- gl.linkProgram(program);
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- throw new Error('program link failed: ' + gl.getProgramInfoLog(program));
- }
- // Full-screen quad
- const buf = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
- -1, -1, 0, 1,
- 1, -1, 1, 1,
- -1, 1, 0, 0,
- -1, 1, 0, 0,
- 1, -1, 1, 1,
- 1, 1, 1, 0,
- ]), gl.STATIC_DRAW);
- const posLoc = gl.getAttribLocation(program, 'a_position');
- const uvLoc = gl.getAttribLocation(program, 'a_uv');
- gl.enableVertexAttribArray(posLoc);
- gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 16, 0);
- gl.enableVertexAttribArray(uvLoc);
- gl.vertexAttribPointer(uvLoc, 2, gl.FLOAT, false, 16, 8);
- } catch (err) {
- console.warn('[impeccable] shader setup failed:', err);
- canvas.remove();
- return;
- }
-
- // Upload the screenshot as a texture
- let bitmap;
- try {
- bitmap = await createImageBitmap(blob);
- } catch {
- // Safari fallback: go via a regular Image
- const imgUrl = URL.createObjectURL(blob);
- const img = new Image();
- img.src = imgUrl;
- await new Promise((r, rej) => { img.onload = r; img.onerror = rej; });
- bitmap = img;
- URL.revokeObjectURL(imgUrl);
- }
- texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
- if (bitmap.close) bitmap.close();
-
- const uTime = gl.getUniformLocation(program, 'u_time');
- const uRes = gl.getUniformLocation(program, 'u_resolution');
- const uAccent = gl.getUniformLocation(program, 'u_accent');
- const uTex = gl.getUniformLocation(program, 'u_texture');
- const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-
- shaderState = { canvas, gl, program, texture, rafId: 0, startTime: performance.now(), reduced };
- function frame() {
- if (!shaderState) return;
- const elapsed = (performance.now() - shaderState.startTime) / 1000;
- const t = shaderState.reduced ? 0.0 : elapsed;
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.useProgram(program);
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.uniform1i(uTex, 0);
- gl.uniform1f(uTime, t);
- gl.uniform2f(uRes, canvas.width, canvas.height);
- gl.uniform3f(uAccent, SHADER_ACCENT[0], SHADER_ACCENT[1], SHADER_ACCENT[2]);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- shaderState.rafId = requestAnimationFrame(frame);
- }
- frame();
- }
-
- function handleAccept() {
- if (!currentSessionId || arrivedVariants === 0) return;
- const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);
- if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;
- const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };
- if (Object.keys(paramsCurrentValues).length > 0) {
- acceptPayload.paramValues = { ...paramsCurrentValues };
- }
- // The accepted variant is already the only visible child of the wrapper
- // (all other variants are display:none). HMR from the source rewrite will
- // replace the wrapper imminently. Don't eagerly replaceChild here — React
- // reconciliation races with our mutation and throws NotFoundError in Next
- // 16 / Turbopack. Schedule a fallback that runs the manual swap only if
- // HMR hasn't cleaned up by then (keeps static-server flows working).
- const acceptedSessionId = currentSessionId;
- const acceptedVariant = visibleVariant;
-
- state = 'SAVING';
- updateBarContent('saving');
-
- sendEvent(acceptPayload, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- confirmAcceptAfterReceipt();
- })
- .catch(() => {
- state = 'CYCLING';
- updateBarContent('cycling');
- showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);
- });
-
- function confirmAcceptAfterReceipt() {
- state = 'CONFIRMED';
- updateBarContent('confirmed');
- scheduleAcceptCleanup();
- }
-
- function scheduleAcceptCleanup() {
- setTimeout(function() {
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }, 1800);
-
- // Static-server / no-HMR fallback: if the wrapper is still around 2s after
- // the cleanup above, swap it out manually. By now React has either moved
- // on or the app isn't React at all. Preserve the `data-impeccable-variant="N"`
- // div (with display:contents) so @scope rules anchored to the variant
- // attribute keep matching until reload replaces it with the carbonize block.
- setTimeout(function() {
- const wrapper = document.querySelector('[data-impeccable-variants="' + acceptedSessionId + '"]');
- if (!wrapper) return;
- const accepted = wrapper.querySelector('[data-impeccable-variant="' + acceptedVariant + '"]');
- if (accepted && accepted.firstElementChild) {
- const parent = wrapper.parentElement;
- if (!parent) return;
- accepted.style.display = 'contents';
- parent.replaceChild(accepted, wrapper);
- }
- }, 2000);
- }
- }
-
- function handleDiscard() {
- if (!currentSessionId) return;
- sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- cleanup();
- })
- .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));
- }
-
- // ---------------------------------------------------------------------------
- // Session persistence via live-browser-session.js
- // ---------------------------------------------------------------------------
- // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
-
- function saveSession() {
- if (!currentSessionId) return;
- // NOTE: scrollY is stored under a separate key (writeScrollY). Storing
- // it here would overwrite the Go-time value every time state changes.
- sessionState.saveSession({
- id: currentSessionId,
- state,
- action: selectedAction,
- count: selectedCount,
- expected: expectedVariants,
- arrived: arrivedVariants,
- visible: visibleVariant,
- });
- }
-
- function loadSession() {
- return sessionState.loadSession();
- }
-
- function clearSession() {
- sessionState.clearSession();
- }
-
- /** Mark session as handled (accepted/discarded). The agent will clean up
- * the source, but until it does the wrapper is still in the HTML. This
- * prevents resumeSession from picking it up again after reload. */
- function markSessionHandled() {
- if (!currentSessionId) return;
- sessionState.markHandled(currentSessionId);
- }
-
- function isSessionHandled(id) {
- return sessionState.isHandled(id);
- }
-
- function clearHandled() {
- sessionState.clearHandled();
- }
-
- function cleanup() {
- // Hide the wrapper immediately so variants disappear. DON'T structurally
- // mutate the DOM yet — HMR from the agent's source rewrite is on its way,
- // and a manual replaceChild under React causes NotFoundError when the
- // reconciler later tries to remove a wrapper we already removed.
- // Schedule a 2s fallback that does the manual swap only if HMR hasn't
- // replaced the wrapper by then (keeps static-server / no-HMR flows alive).
- const cleanupSessionId = currentSessionId;
- if (cleanupSessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (wrapper) wrapper.style.display = 'none';
- }
- setTimeout(function() {
- if (!cleanupSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (!wrapper) return;
- const orig = wrapper.querySelector('[data-impeccable-variant="original"]');
- if (orig) {
- const content = orig.firstElementChild;
- if (content) {
- wrapper.parentElement.replaceChild(content, wrapper);
- return;
- }
- }
- wrapper.remove();
- }, 2000);
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }
-
- // ---------------------------------------------------------------------------
- // Toast
- // ---------------------------------------------------------------------------
-
- function showToast(message, duration) {
- if (toastEl) toastEl.remove();
- // Stack the toast above the global bar (which sits at bottom:14px) so
- // the two never overlap. Read the bar's actual rect — its height varies
- // with hover-expanded labels — and fall back to a sensible default
- // when the bar isn't mounted yet.
- const barRect = globalBarEl?.getBoundingClientRect();
- const barTopFromBottom = barRect && barRect.height > 0
- ? Math.max(16, window.innerHeight - barRect.top + 12)
- : 16;
- toastEl = el('div', {
- position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
- transform: 'translateX(-50%) translateY(8px)',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px',
- padding: '8px 16px', borderRadius: '8px',
- zIndex: Z.toast, opacity: '0',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
- pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
- });
- toastEl.id = PREFIX + '-toast';
- toastEl.textContent = message;
- document.body.appendChild(toastEl);
- requestAnimationFrame(() => {
- toastEl.style.opacity = '1';
- toastEl.style.transform = 'translateX(-50%) translateY(0)';
- });
- setTimeout(() => {
- if (toastEl) {
- toastEl.style.opacity = '0';
- toastEl.style.transform = 'translateX(-50%) translateY(8px)';
- setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
- }
- }, duration);
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- // Resume an active variant session after HMR/page reload.
- // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
- // variants before HMR fired. Pick up where we left off.
- function resumeSession() {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) { clearSession(); clearHandled(); return false; }
-
- const sessionId = wrapper.dataset.impeccableVariants;
-
- // Don't resume if this session was already accepted/discarded
- if (isSessionHandled(sessionId)) return false;
-
- currentSessionId = sessionId;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
-
- // Restore state from localStorage if available
- const saved = loadSession();
- if (saved && saved.id === sessionId) {
- visibleVariant = (saved.visible > 0 && saved.visible <= arrivedVariants) ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
- if (saved.action) selectedAction = saved.action;
- if (saved.count) selectedCount = saved.count;
- } else {
- visibleVariant = arrivedVariants > 0 ? 1 : 0;
- }
-
- // Find the visible variant's content element for highlight positioning.
- // Try the visible variant first, fall back to the original's content.
- const visEl = visibleVariant > 0 ? pickVariantContent(wrapper, visibleVariant) : null;
- const origEl = pickVariantContent(wrapper, 'original');
- selectedElement = visEl || origEl || wrapper.parentElement;
-
- // Set display state BEFORE starting observer (avoid triggering it)
- if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
-
- state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
- showBar(state === 'CYCLING' ? 'cycling' : 'generating');
- startScrollTracking();
- // Build the params panel for the restored visible variant. Previously
- // this was missed on page-reload resume: showVariantInDOM above fires
- // refreshParamsPanel, but state was still IDLE at that moment so it
- // hid. Now that state is CYCLING, re-fire.
- if (state === 'CYCLING') refreshParamsPanel();
- saveSession();
- queueCheckpoint('browser_resumed');
-
- // Start observing for more variants AFTER initial setup
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
-
- // Hold the target at its saved viewport top through any subsequent
- // HMR patches, variant inserts, or cycle swaps.
- startScrollLock(currentSessionId, readScrollY());
-
- // If we reloaded mid-generation (Bun's HTML HMR destroys the shader
- // canvas), re-capture the original's content and restart the shader so
- // the wait doesn't go dead.
- if (state === 'GENERATING' && origEl) {
- (async () => {
- try {
- const rect = origEl.getBoundingClientRect();
- if (rect.width === 0 || rect.height === 0) return;
- const blob = await captureElementToBlob(origEl, null, rect);
- if (blob && state === 'GENERATING') {
- showShaderOverlay(origEl, blob, rect);
- }
- } catch (err) {
- console.warn('[impeccable] shader resume failed:', err);
- }
- })();
- }
- return true;
- }
-
- // ---------------------------------------------------------------------------
- // Global bar (always visible at bottom)
- // ---------------------------------------------------------------------------
-
- let globalBarEl = null;
- let detectActive = false;
- let pickActive = true;
- let detectCount = 0;
- let detectScriptLoaded = false;
-
- // Theme-aware color palette for the global bar. We detect the page's
- // ambient background and invert — dark bar on light pages, light bar on
- // dark pages. This keeps the bar from fighting with the host design.
- function detectPageTheme() {
- try {
- // Dev override: set localStorage 'impeccable-dev-theme' to 'light' or
- // 'dark' to preview the opposite palette without actually changing the
- // page bg. Used for screenshots and theme QA.
- const override = localStorage.getItem('impeccable-dev-theme');
- if (override === 'light' || override === 'dark') return override;
-
- // Walk body → html, taking the first opaque background. The browser's
- // default body / html background is `rgba(0, 0, 0, 0)`, which a naive
- // regex would read as black and mislabel a perfectly white page as
- // dark. Honoring alpha avoids that — and falling through to <html>
- // catches the common pattern of a bg only on <html> (or only on body).
- function readOpaque(el) {
- if (!el) return null;
- const bg = getComputedStyle(el).backgroundColor;
- const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
- if (!m) return null;
- const alpha = m[4] == null ? 1 : parseFloat(m[4]);
- if (alpha < 0.5) return null; // transparent / nearly transparent → skip
- return [+m[1], +m[2], +m[3]];
- }
-
- const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
- // Both transparent → fall back to the browser's effective canvas color.
- // White is the universal default; only one in a thousand sites swaps it
- // via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
- // us catch that case.
- if (!rgb) {
- return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
- }
- const [r, g, b] = rgb;
- // Perceptual luminance (Rec. 709)
- const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
- return L > 0.55 ? 'light' : 'dark';
- } catch { return 'light'; }
- }
-
- function barPaletteForTheme(theme) {
- if (theme === 'dark') {
- // Light bar on dark page
- return {
- surface: 'oklch(98% 0 0 / 0.92)',
- surfaceDeep: 'oklch(92% 0.005 60 / 0.96)', // slightly deeper, faint warm
- hairline: 'oklch(70% 0 0 / 0.35)',
- text: 'oklch(15% 0 0)',
- textDim: 'oklch(45% 0 0)',
- accent: 'oklch(60% 0.25 350)',
- accentSoft: 'oklch(60% 0.25 350 / 0.18)',
- mark: 'oklch(98% 0 0)', // logo mark fill
- markText: 'oklch(15% 0 0)', // logo "/" color
- exitHover: 'oklch(85% 0 0 / 0.5)',
- };
- }
- // Dark bar on light page. Bar is a warm charcoal, logo slab is much
- // deeper so the rounded-right shape reads as a clear sculpted mark.
- return {
- surface: 'oklch(26% 0 0 / 0.94)',
- surfaceDeep: 'oklch(18% 0 0 / 0.96)', // darker sand for Tune popover
- hairline: 'oklch(42% 0 0 / 0.5)',
- text: 'oklch(96% 0 0)',
- textDim: 'oklch(72% 0 0)',
- accent: 'oklch(72% 0.22 350)',
- accentSoft: 'oklch(72% 0.22 350 / 0.22)',
- mark: 'oklch(8% 0 0)',
- markText: 'oklch(96% 0 0)',
- exitHover: 'oklch(36% 0 0 / 0.6)',
- };
- }
-
- // Impeccable logo mark — matches the site-header SVG (rounded square + "/").
- function brandMarkSvg(fill, ink, size = 18) {
- return `<svg width="${size}" height="${size}" viewBox="0 0 32 32" aria-hidden="true">
- <rect width="32" height="32" rx="7" fill="${fill}"/>
- <text x="16" y="24" font-family="system-ui, -apple-system, sans-serif" font-size="22" font-weight="500" fill="${ink}" text-anchor="middle">/</text>
- </svg>`;
- }
-
- function initGlobalBar() {
- const theme = detectPageTheme();
- const P = barPaletteForTheme(theme);
-
- // Custom focus-visible for bar buttons. Browser default is a heavy
- // blue ring that looks jarring on the dark capsule. Replace with a
- // soft accent-tinted inner ring that respects the bar's palette.
- if (!document.getElementById(PREFIX + '-bar-focus-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-bar-focus-style';
- s.textContent =
- '#' + PREFIX + '-global-bar button:focus { outline: none; }' +
- '#' + PREFIX + '-global-bar button:focus-visible {' +
- ' outline: none;' +
- ' box-shadow: 0 0 0 2px ' + P.accentSoft + ', 0 0 0 3px ' + P.accent + ';' +
- '}';
- document.head.appendChild(s);
- }
-
- globalBarEl = el('div', {
- position: 'fixed', bottom: '14px', left: '50%',
- transform: 'translateX(-50%) translateY(20px)',
- zIndex: Z.bar + 5,
- display: 'flex', alignItems: 'stretch',
- gap: '2px',
- background: P.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 4px 20px oklch(0% 0 0 / 0.12), 0 1px 3px oklch(0% 0 0 / 0.08)',
- fontFamily: FONT, fontSize: '12px', lineHeight: '1',
- opacity: '0',
- overflow: 'hidden', // clip the full-bleed brand mark to the bar radius
- transition: 'opacity 0.3s ' + EASE + ', transform 0.3s ' + EASE,
- });
- globalBarEl.id = PREFIX + '-global-bar';
- globalBarEl.dataset.theme = theme;
-
- // Brand mark — fills bar height on the left. Left side inherits the bar's
- // rounded corner via overflow:hidden; right side is a clean hard edge since
- // the near-black/charcoal contrast does the shape-defining work.
- const brand = el('span', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- alignSelf: 'stretch',
- padding: '0 12px 0 14px',
- background: P.mark,
- color: P.markText,
- fontFamily: 'system-ui, -apple-system, sans-serif',
- fontWeight: '500',
- fontSize: '18px', lineHeight: '1',
- });
- brand.textContent = '/';
- brand.title = 'Impeccable';
- globalBarEl.appendChild(brand);
-
- // Inner wrapper: holds the toggles with normal bar padding.
- const inner = el('div', {
- display: 'flex', alignItems: 'center',
- padding: '4px 5px', gap: '2px',
- });
- inner.id = PREFIX + '-global-bar-inner';
- globalBarEl.appendChild(inner);
-
- // --- button factory: icon-only at rest, label slides in on hover/active ---
- function makeIconBtn({ id, svg, label, ariaLabel, labelFont, onClick }) {
- const b = el('button', {
- position: 'relative',
- display: 'inline-flex', alignItems: 'center',
- padding: '6px 8px', borderRadius: '7px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '11.5px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.15s ease, color 0.15s ease',
- whiteSpace: 'nowrap', overflow: 'hidden',
- });
- b.id = id;
- b.title = ariaLabel || label || '';
- b.setAttribute('aria-label', ariaLabel || label || '');
- b.innerHTML = svg + (label
- ? `<span class="icon-btn-label" style="display:inline-block;max-width:0;opacity:0;margin-left:0;overflow:hidden;font-family:${labelFont || FONT};transition:max-width 0.25s ${EASE}, opacity 0.2s ease, margin-left 0.25s ${EASE};">${label}</span>`
- : '');
- const labelEl = b.querySelector('.icon-btn-label');
- const expand = () => {
- if (!labelEl) return;
- labelEl.style.maxWidth = '120px'; labelEl.style.opacity = '1'; labelEl.style.marginLeft = '6px';
- };
- const collapse = () => {
- if (!labelEl || b.dataset.active === 'true') return;
- labelEl.style.maxWidth = '0'; labelEl.style.opacity = '0'; labelEl.style.marginLeft = '0';
- };
- // Per-button hover only changes color (no layout). The label expand/
- // collapse is driven by the bar-level mouseenter/mouseleave so moving
- // the mouse between adjacent buttons doesn't trigger per-button width
- // thrashing — the whole bar grows once and shrinks once.
- b.addEventListener('mouseenter', () => { if (b.dataset.active !== 'true') b.style.color = P.text; });
- b.addEventListener('mouseleave', () => { if (b.dataset.active !== 'true') b.style.color = P.textDim; });
- b.addEventListener('click', onClick);
- b._expandLabel = expand;
- b._collapseLabel = collapse;
- return b;
- }
-
- // Pick toggle — starts active (primary intent when entering live mode).
- const pickBtn = makeIconBtn({
- id: PREFIX + '-pick-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',
- label: 'Pick',
- ariaLabel: 'Pick element',
- onClick: () => togglePick(),
- });
- pickBtn.style.background = P.accentSoft;
- pickBtn.style.color = P.accent;
- pickBtn.dataset.active = 'true';
- pickBtn._expandLabel();
- inner.appendChild(pickBtn);
-
- // Detect toggle
- const detectBtn = makeIconBtn({
- id: PREFIX + '-detect-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',
- label: 'Detect',
- ariaLabel: 'Detect anti-patterns',
- onClick: () => toggleDetect(),
- });
- const detectBadge = el('span', {
- fontSize: '10px', fontWeight: '600',
- padding: '0px 5px', borderRadius: '7px', lineHeight: '16px',
- background: P.accent, color: P.surface.includes('18%') ? 'oklch(18% 0 0)' : 'oklch(98% 0 0)',
- display: 'none', fontFamily: MONO, marginLeft: '4px',
- });
- detectBadge.id = PREFIX + '-detect-badge';
- detectBtn.appendChild(detectBadge);
- inner.appendChild(detectBtn);
-
- // DESIGN.md panel toggle — quartet of color squares as the mark.
- const designBtn = makeIconBtn({
- id: PREFIX + '-design-toggle',
- svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px ${P.hairline};flex-shrink:0">
- <span style="background:oklch(60% 0.25 350)"></span>
- <span style="background:oklch(60% 0.15 45)"></span>
- <span style="background:oklch(55% 0.12 250)"></span>
- <span style="background:oklch(30% 0 0)"></span>
- </span>`,
- label: 'DESIGN.md',
- ariaLabel: 'Toggle DESIGN.md panel',
- labelFont: MONO,
- onClick: () => toggleDesignPanel(),
- });
- inner.appendChild(designBtn);
-
- // Thin divider before the exit button
- const divider = el('span', {
- width: '1px', height: '18px',
- background: P.hairline,
- margin: '0 4px 0 2px',
- });
- inner.appendChild(divider);
-
- // Exit × on the right — intentionally subtle (textDim at rest, text on
- // hover) so it sits behind the active toggles in visual hierarchy.
- //
- // Explicit padding + box-sizing here is load-bearing: a host page like
- // `button { padding: 0.5rem 1rem; }` (very common in resets) would
- // otherwise inflate this 24x24 button into 56x40 and push the SVG out
- // of the visible bar — the X stays invisible even though the styles in
- // DevTools look fine. Every other chrome button sets padding inline;
- // this one needed it too.
- const exitBtn = el('button', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- padding: '0', boxSizing: 'border-box',
- width: '24px', height: '24px', borderRadius: '6px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
- cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
- });
- exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
- exitBtn.title = 'Exit live mode';
- exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
- exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
- exitBtn.addEventListener('click', () => { sendEvent({ type: 'exit' }); teardown(); });
- inner.appendChild(exitBtn);
-
- // Bar-level hover: expand every toggle's label at once; collapse on leave.
- // Buttons with dataset.active="true" ignore collapse (their label stays).
- const toggles = [pickBtn, detectBtn, designBtn];
- globalBarEl.addEventListener('mouseenter', () => {
- toggles.forEach((t) => t._expandLabel && t._expandLabel());
- });
- globalBarEl.addEventListener('mouseleave', () => {
- toggles.forEach((t) => t._collapseLabel && t._collapseLabel());
- });
-
- document.body.appendChild(globalBarEl);
- defangOutsideHandlers(globalBarEl);
-
- requestAnimationFrame(() => {
- globalBarEl.style.opacity = '1';
- globalBarEl.style.transform = 'translateX(-50%) translateY(0)';
- });
-
- // Listen for detection results AND ready signal
- window.addEventListener('message', onDetectMessage);
- }
-
- function updateGlobalBarState() {
- const detectToggle = document.getElementById(PREFIX + '-detect-toggle');
- const detectBadge = document.getElementById(PREFIX + '-detect-badge');
- const pickToggle = document.getElementById(PREFIX + '-pick-toggle');
- const designToggle = document.getElementById(PREFIX + '-design-toggle');
- const theme = globalBarEl?.dataset.theme || 'light';
- const P = barPaletteForTheme(theme);
-
- // Sync one toggle's active state, colors, and slide-label visibility.
- function sync(btn, active) {
- if (!btn) return;
- btn.style.background = active ? P.accentSoft : 'transparent';
- btn.style.color = active ? P.accent : P.textDim;
- btn.dataset.active = active ? 'true' : 'false';
- if (active && btn._expandLabel) btn._expandLabel();
- else if (!active && btn._collapseLabel) btn._collapseLabel();
- }
- sync(pickToggle, pickActive);
- sync(detectToggle, detectActive);
- sync(designToggle, designState.open);
-
- // If the bar is currently under the cursor, keep all labels expanded —
- // otherwise clicking a toggle that deactivates (e.g. closing DESIGN.md)
- // would collapse its label while the user's mouse is still on the bar.
- if (globalBarEl && globalBarEl.matches(':hover')) {
- [pickToggle, detectToggle, designToggle].forEach((t) => t?._expandLabel?.());
- }
-
- if (detectBadge) {
- detectBadge.style.display = (detectActive && detectCount > 0) ? 'inline' : 'none';
- detectBadge.textContent = detectCount;
- }
-
- // When pick is active, make detect overlays click-through so the picker works
- document.querySelectorAll('.impeccable-overlay').forEach(o => {
- o.style.pointerEvents = pickActive ? 'none' : '';
- });
- }
-
- let detectReady = false; // true once detect script posts 'impeccable-ready'
- let detectPendingScan = false; // scan requested before script was ready
-
- function toggleDetect() {
- detectActive = !detectActive;
- updateGlobalBarState();
-
- if (detectActive) {
- if (!detectScriptLoaded) {
- detectPendingScan = true;
- loadDetectScript();
- } else if (detectReady) {
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- } else {
- detectPendingScan = true;
- }
- } else {
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- detectCount = 0;
- updateGlobalBarState();
- }
- }
-
- function togglePick() {
- pickActive = !pickActive;
- updateGlobalBarState();
-
- if (!pickActive) {
- // Disabling pick clears any in-flight selection and UI: highlight,
- // contextual bar, selectedElement. Otherwise a stale selection sits
- // on screen with no obvious way to dismiss.
- hideHighlight();
- hideBar();
- hideActionPicker();
- selectedElement = null;
- if (state === 'PICKING' || state === 'CONFIGURING') state = 'IDLE';
- } else {
- if (state === 'IDLE') state = 'PICKING';
- }
- }
-
- function loadDetectScript() {
- if (detectScriptLoaded) return;
- detectScriptLoaded = true;
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/detect.js';
- s.dataset.impeccableExtension = 'true';
- document.head.appendChild(s);
- }
-
- function onDetectMessage(e) {
- if (!e.data || typeof e.data.source !== 'string') return;
- // Detection script is loaded and ready
- if (e.data.source === 'impeccable-ready') {
- detectReady = true;
- if (detectPendingScan && detectActive) {
- detectPendingScan = false;
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- }
- }
- // Scan results arrived
- if (e.data.source === 'impeccable-results') {
- detectCount = e.data.count || 0;
- updateGlobalBarState();
- }
- }
-
- /** Full teardown: remove all UI, disconnect SSE, clean up. */
- function teardown() {
- cleanup();
- hideBar();
- if (globalBarEl) {
- globalBarEl.style.transform = 'translateY(100%)';
- setTimeout(() => { if (globalBarEl) globalBarEl.remove(); globalBarEl = null; }, 300);
- }
- if (highlightEl) { highlightEl.remove(); highlightEl = null; }
- if (tooltipEl) { tooltipEl.remove(); tooltipEl = null; }
- if (barEl) { barEl.remove(); barEl = null; }
- if (pickerEl) { pickerEl.remove(); pickerEl = null; }
- if (paramsPanelEl) { paramsPanelEl.remove(); paramsPanelEl = null; paramsPanelInner = null; paramsPanelBody = null; }
- if (evtSource) { evtSource.close(); evtSource = null; }
- document.removeEventListener('mousemove', handleMouseMove, true);
- document.removeEventListener('click', handleClick, true);
- document.removeEventListener('keydown', handleKeyDown, true);
- window.removeEventListener('message', onDetectMessage);
- // Remove detection overlays
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- state = 'IDLE';
- window.__IMPECCABLE_LIVE_INIT__ = false;
- console.log('[impeccable] Live mode exited.');
- }
-
- // ---------------------------------------------------------------------------
- // Design System Panel — visualizes the project's .impeccable/design.json sidecar
- // ---------------------------------------------------------------------------
-
- const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';
- const DESIGN_PANEL_WIDTH = 440;
-
- let designHost = null;
- let designShadow = null;
- let designState = {
- open: false,
- tab: 'visual', // 'visual' | 'raw'
- parsed: null, // parseDesignMd output (frontmatter + body sections)
- sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)
- hasMd: false,
- hasSidecar: false,
- present: null, // true/false once fetch resolves
- raw: null, // raw DESIGN.md for the raw tab
- mdNewerThanJson: false, // stale-hint flag
- loading: false,
- error: null,
- collapsed: { // narrative-section accordion state
- rules: true, dosdonts: true, overview: true,
- },
- };
-
- function loadDesignPrefs() {
- // `open` is intentionally NOT persisted — the panel always starts closed
- // so live mode doesn't auto-slide a big panel over the page on startup.
- try {
- const raw = localStorage.getItem(DESIGN_PREFS_KEY);
- if (!raw) return;
- const prefs = JSON.parse(raw);
- if (prefs.tab === 'visual' || prefs.tab === 'raw') designState.tab = prefs.tab;
- if (prefs.collapsed && typeof prefs.collapsed === 'object') {
- Object.assign(designState.collapsed, prefs.collapsed);
- }
- } catch { /* ignore */ }
- }
-
- function saveDesignPrefs() {
- try {
- localStorage.setItem(DESIGN_PREFS_KEY, JSON.stringify({
- tab: designState.tab,
- collapsed: designState.collapsed,
- }));
- } catch { /* ignore */ }
- }
-
- function initDesignPanel() {
- designHost = document.createElement('div');
- designHost.id = PREFIX + '-design-host';
- Object.assign(designHost.style, {
- position: 'fixed', top: '0', left: '0',
- width: '0', height: '0',
- zIndex: String(Z.bar + 10),
- pointerEvents: 'none',
- });
- designShadow = designHost.attachShadow({ mode: 'open' });
-
- const style = document.createElement('style');
- // Theme-match the bar: dark chrome on light pages, light chrome on dark pages.
- const theme = detectPageTheme();
- style.textContent = designPanelCss(barPaletteForTheme(theme));
- designShadow.appendChild(style);
-
- const root = document.createElement('div');
- root.className = 'root';
- designShadow.appendChild(root);
-
- document.body.appendChild(designHost);
- // The host is pointer-events: none; the panel inside the shadow DOM
- // manages its own auto/none. Events bubble through the shadow boundary,
- // so attaching here silences host-page outside-interaction handlers
- // without touching the host's click-through behavior.
- defangOutsideHandlers(designHost, { setPointerEvents: false });
-
- loadDesignPrefs();
- renderDesignChrome();
- if (designState.open) {
- fetchDesignSystem();
- }
- }
-
- // Neutral panel palette — deliberately NOT Impeccable-branded. The panel is
- // a viewer of the project's design system, not an Impeccable surface.
- const DP = {
- canvas: 'oklch(94% 0 0)', // panel background
- tile: 'oklch(98.5% 0 0)', // card-on-canvas
- tileAlt: 'oklch(96% 0 0)', // subtler tile for inner surfaces
- ink: 'oklch(15% 0 0)',
- ink2: 'oklch(35% 0 0)',
- meta: 'oklch(55% 0 0)',
- hairline: 'oklch(88% 0 0)',
- hairlineSoft: 'oklch(92% 0 0)',
- amber: 'oklch(70% 0.13 65)', // stale-hint accent
- amberBg: 'oklch(95% 0.05 80)',
- };
-
- function designPanelCss(BP) {
- // BP = bar palette (theme-aware, matches the global bar).
- // DP = internal content palette (neutral, so tiles render colors true).
- return `
- :host, .root { all: initial; }
- .root {
- font-family: ${FONT};
- color: ${DP.ink};
- pointer-events: none;
- }
- .root * { box-sizing: border-box; }
- button { font: inherit; color: inherit; }
-
- /* --- Panel shell: chrome matches the bar; body canvas stays neutral --- */
- .panel {
- position: fixed; top: 12px; bottom: 72px; right: 12px;
- width: ${DESIGN_PANEL_WIDTH}px; max-width: calc(100vw - 24px);
- background: ${BP.surface};
- border: 1px solid ${BP.hairline};
- border-radius: 14px;
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- box-shadow: 0 20px 60px oklch(0% 0 0 / 0.18), 0 4px 12px oklch(0% 0 0 / 0.08);
- display: flex; flex-direction: column;
- transform: translateX(calc(100% + 24px));
- opacity: 0;
- transition: transform 0.35s ${EASE}, opacity 0.25s ${EASE};
- pointer-events: none;
- overflow: hidden;
- }
- .panel[data-open="true"] { transform: translateX(0); opacity: 1; pointer-events: auto; }
-
- .panel-header {
- display: flex; align-items: center; gap: 10px;
- padding: 10px 10px 10px 14px;
- background: transparent;
- border-bottom: 1px solid ${BP.hairline};
- }
- .panel-title {
- flex: 1; min-width: 0;
- font-family: ${MONO};
- font-size: 11.5px; font-weight: 600;
- letter-spacing: 0.02em;
- color: ${BP.text};
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
- }
- .panel-close {
- border: none; background: transparent; color: ${BP.textDim};
- width: 26px; height: 26px; border-radius: 7px;
- display: inline-flex; align-items: center; justify-content: center;
- cursor: pointer; transition: background 0.15s ease, color 0.15s ease;
- }
- .panel-close:hover { background: ${BP.hairline}; color: ${BP.text}; }
-
- .tabs {
- display: inline-flex; padding: 2px;
- background: ${BP.hairline};
- border-radius: 7px;
- gap: 2px;
- }
- .tab {
- border: none; background: transparent;
- padding: 4px 10px; border-radius: 5px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 600; letter-spacing: 0.08em;
- text-transform: uppercase;
- color: ${BP.textDim}; cursor: pointer;
- transition: background 0.15s ease, color 0.15s ease;
- }
- .tab[data-active="true"] { background: ${BP.surface}; color: ${BP.text}; }
-
- .panel-body {
- flex: 1; overflow-y: auto;
- padding: 12px 12px 20px;
- background: ${DP.canvas};
- scrollbar-width: thin;
- scrollbar-color: ${DP.hairline} transparent;
- }
- .panel-body::-webkit-scrollbar { width: 8px; }
- .panel-body::-webkit-scrollbar-thumb { background: ${DP.hairline}; border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
-
- /* --- States --- */
- .empty, .loading, .error {
- margin: 16px 4px;
- padding: 28px 20px; text-align: center;
- background: ${DP.tile}; border-radius: 14px;
- color: ${DP.ink2}; font-size: 13px; line-height: 1.55;
- }
- .empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
- .empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
- .error { color: oklch(45% 0.15 25); }
-
- /* --- Stale hint --- */
- .stale {
- display: flex; align-items: center; gap: 8px;
- margin: 8px 4px 12px;
- padding: 8px 12px;
- background: ${DP.amberBg};
- border-radius: 10px;
- font-size: 11.5px; color: ${DP.ink2};
- }
- .stale-dot { width: 8px; height: 8px; border-radius: 50%; background: ${DP.amber}; flex-shrink: 0; }
- .stale-text { flex: 1; min-width: 0; }
- .stale-text strong { color: ${DP.ink}; font-weight: 600; }
-
- /* --- Parsed-md fallback banner --- */
- .parsed-md-cta {
- margin: 8px 4px 14px;
- padding: 14px 16px;
- background: ${DP.tile};
- border: 1px dashed ${DP.hairline};
- border-radius: 12px;
- font-size: 12px; color: ${DP.ink2}; line-height: 1.55;
- }
- .parsed-md-cta strong { color: ${DP.ink}; display: block; margin-bottom: 4px; font-size: 13px; font-weight: 600; }
- .parsed-md-cta code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; font-size: 11.5px; color: ${DP.ink}; }
-
- /* --- Tile primitives --- */
- .tile {
- position: relative;
- background: ${DP.tile};
- border-radius: 16px;
- padding: 16px;
- margin: 0 4px 10px;
- }
- .tile-row { margin: 0 4px 10px; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
- .tile-row .tile { margin: 0; }
- .tile-meta {
- display: flex; align-items: baseline; justify-content: space-between;
- gap: 10px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase;
- color: ${DP.meta};
- }
- .tile-meta .name { color: ${DP.ink}; font-weight: 600; letter-spacing: 0.05em; text-transform: none; font-family: ${FONT}; font-size: 12.5px; }
-
- /* --- Color tile --- */
- .c-tile { cursor: pointer; transition: transform 0.2s ${EASE}; }
- .c-tile:hover { transform: translateY(-1px); }
- .c-hero {
- height: 72px; border-radius: 10px; margin-top: 10px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.05);
- }
- .c-ramp {
- display: flex; gap: 0; height: 14px; border-radius: 4px; overflow: hidden;
- margin-top: 8px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.04);
- }
- .c-ramp > span { flex: 1; }
- .c-desc { margin-top: 8px; font-size: 11.5px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Type tile --- */
- .t-tile { }
- .t-specimen {
- margin: 4px 0 6px;
- color: ${DP.ink};
- line-height: 0.9;
- }
- .t-family { margin-top: 4px; font-size: 12px; font-weight: 600; color: ${DP.ink}; }
- .t-purpose { margin-top: 4px; font-size: 11px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Shadow tile --- */
- .s-tile { }
- .s-surface {
- height: 60px; margin: 8px 2px 10px;
- background: ${DP.tile};
- border-radius: 10px;
- }
- .s-value { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; word-break: break-all; line-height: 1.4; }
- .s-purpose { margin-top: 4px; font-size: 11px; color: ${DP.ink2}; line-height: 1.45; }
-
- /* --- Radii strip --- */
- .r-strip { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
- .r-item { display: flex; flex-direction: column; align-items: center; gap: 4px; flex: 1; min-width: 60px; }
- .r-sample { width: 44px; height: 44px; background: ${DP.canvas}; box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.08); }
- .r-label { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; text-transform: uppercase; }
- .r-val { font-family: ${MONO}; font-size: 10px; color: ${DP.ink}; }
-
- /* --- Component tile (hosts live primitives) --- */
- .cmp-tile { }
- .cmp-stage {
- margin: 12px -4px 0;
- padding: 18px 16px 10px;
- border-top: 1px solid ${DP.hairlineSoft};
- display: flex; flex-direction: column; align-items: center; justify-content: center;
- gap: 14px;
- min-height: 68px;
- }
- .cmp-stage + .cmp-stage { border-top: 1px dashed ${DP.hairlineSoft}; }
- .cmp-sublabel { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.06em; }
- .cmp-kind { font-family: ${MONO}; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; }
-
- /* --- Collapsible --- */
- .coll {
- margin: 0 4px 8px;
- background: ${DP.tile};
- border-radius: 12px;
- overflow: hidden;
- }
- .coll-head {
- display: flex; align-items: center; gap: 10px;
- width: 100%;
- padding: 12px 14px;
- background: transparent; border: none;
- cursor: pointer; text-align: left;
- font-family: ${FONT}; font-size: 12.5px; font-weight: 600; color: ${DP.ink};
- transition: background 0.12s ease;
- }
- .coll-head:hover { background: ${DP.tileAlt}; }
- .coll-chev {
- width: 12px; height: 12px; flex-shrink: 0;
- color: ${DP.meta};
- transition: transform 0.2s ${EASE};
- }
- .coll[data-open="true"] .coll-chev { transform: rotate(90deg); }
- .coll-count { margin-left: auto; font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; }
- .coll-body { padding: 0 14px 14px; display: none; }
- .coll[data-open="true"] .coll-body { display: block; }
-
- .rule-card {
- padding: 10px 0;
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .rule-card:first-child { border-top: none; padding-top: 2px; }
- .rule-card .name { font-size: 11.5px; font-weight: 700; color: ${DP.ink}; margin-bottom: 3px; }
- .rule-card .name .section { font-family: ${MONO}; font-size: 9px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; margin-left: 8px; }
- .rule-card .body { font-size: 11.5px; color: ${DP.ink2}; line-height: 1.5; }
-
- .coll .dos { display: grid; gap: 0; margin-top: 2px; }
- .coll .do, .coll .dont {
- position: relative;
- padding: 8px 0 8px 22px;
- font-size: 11.5px; line-height: 1.5; color: ${DP.ink2};
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .coll .do:first-child, .coll .dont:first-child,
- .coll .do:first-of-type { border-top: none; }
- .coll .do + .dont { border-top: 1px solid ${DP.hairlineSoft}; }
- .coll .do::before, .coll .dont::before {
- content: ''; position: absolute; left: 4px; top: 13px;
- width: 8px; height: 8px; border-radius: 50%;
- }
- .coll .do::before { background: oklch(62% 0.16 145); }
- .coll .dont::before { background: oklch(58% 0.22 25); }
-
- .coll .overview-body {
- font-size: 12px; line-height: 1.55; color: ${DP.ink2};
- }
- .coll .overview-body .north-star {
- display: block; font-family: ${FONT}; font-style: italic;
- font-size: 15px; line-height: 1.3; color: ${DP.ink};
- margin-bottom: 8px;
- }
- .coll .overview-body p { margin: 0 0 8px; }
- .coll .overview-body ul { margin: 6px 0 0; padding-left: 16px; font-size: 11.5px; }
- .coll .overview-body li { margin-bottom: 3px; }
-
- /* --- raw tab markdown (unchanged layout, neutralized palette) --- */
- .md { padding: 4px 10px 20px; font-size: 13px; line-height: 1.6; color: ${DP.ink}; }
- .md h1, .md h2, .md h3, .md h4 { margin: 20px 0 8px; color: ${DP.ink}; font-weight: 600; }
- .md h1 { font-size: 18px; }
- .md h2 { font-size: 15px; padding-bottom: 4px; border-bottom: 1px solid ${DP.hairlineSoft}; }
- .md h3 { font-size: 13px; }
- .md h4 { font-size: 12px; color: ${DP.meta}; }
- .md p { margin: 0 0 10px; }
- .md ul, .md ol { margin: 0 0 10px; padding-left: 20px; }
- .md li { margin-bottom: 4px; }
- .md code { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; }
- .md pre { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 10px 12px; border-radius: 8px; overflow-x: auto; margin: 0 0 10px; }
- .md pre code { background: none; padding: 0; }
- .md strong { font-weight: 700; }
- .md em { font-style: italic; }
- .md a { color: ${DP.ink}; text-decoration: underline; }
- .md hr { border: none; border-top: 1px solid ${DP.hairlineSoft}; margin: 16px 0; }
- `;
- }
-
- function renderDesignChrome() {
- const root = designShadow.querySelector('.root');
- root.innerHTML = '';
-
- // (Panel toggle lives in the global bar — no floating FAB.)
- // Panel
- const panel = document.createElement('aside');
- panel.className = 'panel';
- panel.setAttribute('data-open', designState.open ? 'true' : 'false');
- panel.appendChild(buildDesignHeader());
- const body = document.createElement('div');
- body.className = 'panel-body';
- body.id = 'panel-body';
- panel.appendChild(body);
- root.appendChild(panel);
-
- renderDesignBody();
- }
-
- function buildDesignHeader() {
- const header = document.createElement('div');
- header.className = 'panel-header';
-
- const title = document.createElement('div');
- title.className = 'panel-title';
- title.textContent = 'DESIGN.md';
- header.appendChild(title);
-
- const tabs = document.createElement('div');
- tabs.className = 'tabs';
- for (const t of [['visual', 'Visual'], ['raw', 'Raw']]) {
- const btn = document.createElement('button');
- btn.className = 'tab';
- btn.textContent = t[1];
- btn.setAttribute('data-active', designState.tab === t[0] ? 'true' : 'false');
- btn.addEventListener('click', () => {
- if (designState.tab === t[0]) return;
- designState.tab = t[0];
- saveDesignPrefs();
- renderDesignChrome();
- if (t[0] === 'raw' && designState.raw === null && !designState.loading) {
- fetchDesignSystem(); // raw is part of the same fetch pair
- }
- });
- tabs.appendChild(btn);
- }
- header.appendChild(tabs);
-
- const close = document.createElement('button');
- close.className = 'panel-close';
- close.innerHTML = '✕';
- close.setAttribute('aria-label', 'Close panel');
- close.addEventListener('click', toggleDesignPanel);
- header.appendChild(close);
-
- return header;
- }
-
- function toggleDesignPanel() {
- designState.open = !designState.open;
- renderDesignChrome();
- updateGlobalBarState();
- if (designState.open && designState.present === null && !designState.loading) {
- fetchDesignSystem();
- }
- }
-
- async function fetchDesignSystem() {
- designState.loading = true;
- designState.error = null;
- renderDesignBody();
- try {
- const [jsonRes, rawRes] = await Promise.all([
- fetch(`http://localhost:${PORT}/design-system.json?token=${TOKEN}`, { cache: 'no-store' }),
- fetch(`http://localhost:${PORT}/design-system/raw?token=${TOKEN}`, { cache: 'no-store' }),
- ]);
- const jsonData = await jsonRes.json();
- designState.present = jsonData.present === true;
- designState.parsed = jsonData.parsed || null;
- designState.sidecar = jsonData.sidecar || null;
- designState.hasMd = !!jsonData.hasMd;
- designState.hasSidecar = !!jsonData.hasSidecar;
- designState.mdNewerThanJson = !!jsonData.mdNewerThanJson;
- designState.raw = designState.present && rawRes.ok ? await rawRes.text() : null;
- designState.error = jsonData.parseError || jsonData.sidecarError || null;
- } catch (err) {
- designState.error = err?.message || 'Failed to load design system.';
- } finally {
- designState.loading = false;
- renderDesignChrome(); // refresh title from data
- }
- }
-
- function renderDesignBody() {
- const body = designShadow.querySelector('#panel-body');
- if (!body) return;
- body.innerHTML = '';
-
- if (designState.loading) {
- body.appendChild(msgDiv('loading', 'Loading design system…'));
- return;
- }
- if (designState.error) {
- body.appendChild(msgDiv('error', designState.error));
- return;
- }
- if (designState.present === false) {
- const empty = document.createElement('div');
- empty.className = 'empty';
- empty.innerHTML = `<strong>No DESIGN.md yet</strong>Create one by running <code>/impeccable document</code> in your terminal, then re-open this panel.`;
- body.appendChild(empty);
- return;
- }
-
- if (designState.tab === 'raw') {
- renderRawTab(body, designState.raw || '');
- return;
- }
-
- // Visual tab — single unified render path.
- if (designState.mdNewerThanJson) body.appendChild(renderStaleHint());
- if (designState.hasMd && !designState.hasSidecar) {
- body.appendChild(renderParsedMdCta());
- }
- renderDesignVisual(body, designState.parsed, designState.sidecar);
- }
-
- function msgDiv(cls, text) {
- const d = document.createElement('div');
- d.className = cls;
- d.textContent = text;
- return d;
- }
-
- function renderStaleHint() {
- const box = document.createElement('div');
- box.className = 'stale';
- box.innerHTML = `
- <span class="stale-dot"></span>
- <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>
- `;
- return box;
- }
-
- function renderParsedMdCta() {
- const box = document.createElement('div');
- box.className = 'parsed-md-cta';
- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;
- return box;
- }
-
- // --- Unified render: merge parsed DESIGN.md frontmatter with sidecar v2 ---
-
- function renderDesignVisual(body, parsed, sidecar) {
- const frontmatter = parsed?.frontmatter || {};
- const extensions = sidecar?.extensions || {};
- const proseColors = parsed?.colors || null;
-
- const colors = buildColorModels(frontmatter.colors, extensions.colorMeta, proseColors);
- if (colors.length) renderColorTiles(body, colors);
-
- const types = buildTypographyModels(frontmatter.typography, extensions.typographyMeta);
- if (types.length) renderTypeTiles(body, types);
-
- const radii = buildRadiiModels(frontmatter.rounded);
- if (radii.length) renderRadiiTile(body, radii);
-
- if (extensions.shadows?.length) renderShadowTiles(body, extensions.shadows);
-
- const components = sidecar?.components || [];
- if (components.length) renderComponentTiles(body, components);
-
- // Narrative: sidecar wins if present (richer, agent-curated). Otherwise
- // synthesize from prose sections.
- const narrative = sidecar?.narrative || synthesizeNarrative(parsed);
- if (narrative.rules?.length) body.appendChild(renderRulesCollapsible(narrative.rules));
- if ((narrative.dos?.length || narrative.donts?.length)) body.appendChild(renderDosDontsCollapsible(narrative));
- if (narrative.overview || narrative.northStar || narrative.keyCharacteristics?.length) {
- body.appendChild(renderOverviewCollapsible(narrative));
- }
-
- if (body.childElementCount === 0) {
- body.appendChild(msgDiv('empty', 'No design system data available.'));
- }
- }
-
- // Frontmatter primitives + sidecar colorMeta → tile-ready color models.
- // A matching prose bullet (when the slug sits in the bullet text) supplies
- // description as a last-resort fallback.
- function buildColorModels(fmColors, colorMeta, proseColors) {
- if (!fmColors) return [];
- const meta = colorMeta || {};
- return Object.entries(fmColors).map(([key, value]) => {
- const m = meta[key] || {};
- return {
- role: m.role || humanizeKey(key),
- name: m.displayName || humanizeKey(key),
- value: value,
- canonical: m.canonical || null,
- description: m.description || findProseDescription(proseColors, key, m.displayName),
- tonalRamp: m.tonalRamp || null,
- };
- });
- }
-
- function buildTypographyModels(fmTypography, typographyMeta) {
- if (!fmTypography) return [];
- const meta = typographyMeta || {};
- return Object.entries(fmTypography).map(([key, spec]) => {
- const m = meta[key] || {};
- const { family, fallback } = splitFontFamily(spec?.fontFamily);
- return {
- role: key,
- name: m.displayName || humanizeKey(key),
- family,
- fallback,
- weight: spec?.fontWeight ?? 400,
- // fontStyle isn't in Stitch's frontmatter schema; the sidecar carries
- // it when a role is rendered in italic (e.g. display italic).
- style: m.style || 'normal',
- sampleSize: spec?.fontSize || '1rem',
- lineHeight: spec?.lineHeight != null ? String(spec.lineHeight) : '',
- letterSpacing: spec?.letterSpacing,
- purpose: m.purpose,
- };
- });
- }
-
- function buildRadiiModels(fmRounded) {
- if (!fmRounded) return [];
- return Object.entries(fmRounded).map(([name, value]) => ({ name, value }));
- }
-
- function splitFontFamily(stack) {
- if (!stack || typeof stack !== 'string') return { family: '', fallback: '' };
- const parts = stack.split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, ''));
- return { family: parts[0] || '', fallback: parts.slice(1).join(', ') };
- }
-
- function humanizeKey(k) {
- return String(k || '').replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
- }
-
- function findProseDescription(proseColors, key, displayName) {
- if (!proseColors || !proseColors.groups) return null;
- const needles = [key, displayName].filter(Boolean).map((s) => s.toLowerCase());
- for (const g of proseColors.groups) {
- for (const c of g.colors || []) {
- const hay = String(c.name || '').toLowerCase();
- if (hay && needles.some((n) => hay.includes(n) || n.includes(hay))) {
- return c.description || null;
- }
- }
- }
- return null;
- }
-
- function synthesizeNarrative(parsed) {
- if (!parsed) return {};
- const md = parsed;
- return {
- northStar: md.overview?.creativeNorthStar,
- overview: (md.overview?.philosophy || []).join(' '),
- keyCharacteristics: md.overview?.keyCharacteristics || [],
- rules: [
- ...(md.colors?.rules || []).map((r) => ({ ...r, section: 'colors' })),
- ...(md.typography?.rules || []).map((r) => ({ ...r, section: 'typography' })),
- ...(md.elevation?.rules || []).map((r) => ({ ...r, section: 'elevation' })),
- ],
- dos: md.dosDonts?.dos || [],
- donts: md.dosDonts?.donts || [],
- };
- }
-
- function renderColorTiles(body, colors) {
- for (const c of colors) {
- const tile = document.createElement('div');
- tile.className = 'tile c-tile';
- tile.title = 'Click to copy';
- tile.addEventListener('click', () => copyToClipboard(c.value));
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(c.name || c.role || 'Color')}</span><span>${escapeHtml(c.value || '')}</span>`;
- tile.appendChild(meta);
-
- const hero = document.createElement('div');
- hero.className = 'c-hero';
- hero.style.background = c.value;
- tile.appendChild(hero);
-
- const ramp = synthesizeRamp(c);
- if (ramp.length) {
- const r = document.createElement('div');
- r.className = 'c-ramp';
- r.innerHTML = ramp.map((v) => `<span style="background:${cssSafe(v)}"></span>`).join('');
- tile.appendChild(r);
- }
-
- if (c.description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = c.description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function synthesizeRamp(c) {
- if (c.tonalRamp?.length) return c.tonalRamp;
- // If base value is OKLCH, synthesize an 8-step ramp across lightness.
- const m = typeof c.value === 'string' && c.value.match(/^oklch\(\s*([\d.]+)%\s+([\d.]+)\s+([\d.]+)\s*(?:\/\s*([\d.]+))?\s*\)$/i);
- if (!m) return [];
- const [, , chroma, hue] = m;
- const steps = [20, 32, 44, 56, 68, 80, 90, 96];
- return steps.map((l) => `oklch(${l}% ${chroma} ${hue})`);
- }
-
- function renderTypeTiles(body, types) {
- for (const t of types) {
- const tile = document.createElement('div');
- tile.className = 'tile t-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span>${escapeHtml(t.role || '')}</span><span>${escapeHtml(t.weight || '')} ${escapeHtml(t.style === 'italic' ? 'italic' : '')}</span>`;
- tile.appendChild(meta);
-
- const specimen = document.createElement('div');
- specimen.className = 't-specimen';
- specimen.textContent = 'Aa';
- specimen.style.fontFamily = fontStack(t);
- specimen.style.fontWeight = String(t.weight || 400);
- specimen.style.fontStyle = t.style || 'normal';
- specimen.style.fontSize = '56px'; // Fixed specimen size — compare faces, not scales.
- specimen.style.letterSpacing = 'normal';
- specimen.style.textTransform = 'none';
- tile.appendChild(specimen);
-
- // The system's actual sample size for this role, shown as small mono meta below.
- if (t.sampleSize) {
- const scale = document.createElement('div');
- scale.style.cssText = 'font-family:' + MONO + '; font-size: 10px; color:' + DP.meta + '; margin-top: 2px;';
- scale.textContent = t.sampleSize;
- tile.appendChild(scale);
- }
-
- const family = document.createElement('div');
- family.className = 't-family';
- family.textContent = t.family || t.name || '';
- tile.appendChild(family);
-
- if (t.purpose) {
- const p = document.createElement('div');
- p.className = 't-purpose';
- p.textContent = t.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function fontStack(t) {
- const fam = t.family || '';
- const fb = t.fallback || '';
- if (fam && /[,\s]/.test(fam) && !fam.includes("'") && !fam.includes('"')) {
- return `"${fam}", ${fb}`;
- }
- return fam && fb ? `"${fam}", ${fb}` : (fam || fb);
- }
-
- function renderRadiiTile(body, radii) {
- const tile = document.createElement('div');
- tile.className = 'tile';
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">Corner Radii</span><span>${radii.length}</span>`;
- tile.appendChild(meta);
-
- const strip = document.createElement('div');
- strip.className = 'r-strip';
- for (const r of radii) {
- const item = document.createElement('div');
- item.className = 'r-item';
- const s = document.createElement('div');
- s.className = 'r-sample';
- s.style.borderRadius = r.value || '0';
- item.appendChild(s);
- const lbl = document.createElement('div');
- lbl.className = 'r-label';
- lbl.textContent = r.name || '';
- item.appendChild(lbl);
- const val = document.createElement('div');
- val.className = 'r-val';
- val.textContent = r.value || '';
- item.appendChild(val);
- strip.appendChild(item);
- }
- tile.appendChild(strip);
- body.appendChild(tile);
- }
-
- function renderShadowTiles(body, shadows) {
- for (const sh of shadows) {
- const tile = document.createElement('div');
- tile.className = 'tile s-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(sh.name || 'Shadow')}</span><span>Elevation</span>`;
- tile.appendChild(meta);
-
- const surface = document.createElement('div');
- surface.className = 's-surface';
- surface.style.boxShadow = sh.value || 'none';
- tile.appendChild(surface);
-
- const val = document.createElement('div');
- val.className = 's-value';
- val.textContent = sh.value || '';
- tile.appendChild(val);
-
- if (sh.purpose) {
- const p = document.createElement('div');
- p.className = 's-purpose';
- p.textContent = sh.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function renderComponentTiles(body, components) {
- // Group consecutive components that share a kind into one tile. This avoids
- // a pile of one-component tiles (e.g., three button variants = three tiles)
- // and reads more like a proper category.
- const groups = groupByKind(components);
-
- for (const group of groups) {
- const tile = document.createElement('div');
- tile.className = 'tile cmp-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- const groupTitle = group.length === 1
- ? (group[0].name || group[0].kind || 'Component')
- : titleForKind(group[0].kind, group.length);
- meta.innerHTML = `<span class="name">${escapeHtml(groupTitle)}</span><span class="cmp-kind">${escapeHtml(group[0].kind || '')}</span>`;
- tile.appendChild(meta);
-
- for (const c of group) {
- const stage = document.createElement('div');
- stage.className = 'cmp-stage';
-
- // Render the component in its own shadow root so its CSS can't bleed.
- const host = document.createElement('div');
- const sub = host.attachShadow({ mode: 'open' });
- const style = document.createElement('style');
- style.textContent = c.css || '';
- sub.appendChild(style);
- const container = document.createElement('div');
- container.innerHTML = c.html || '';
- sub.appendChild(container);
- stage.appendChild(host);
-
- // Show component name as a sublabel only when the tile groups >1 item,
- // or when the component's display name differs from its kind.
- const showSublabel = group.length > 1;
- if (showSublabel) {
- const lbl = document.createElement('div');
- lbl.className = 'cmp-sublabel';
- lbl.textContent = c.name || '';
- stage.appendChild(lbl);
- }
- tile.appendChild(stage);
- }
-
- // Single shared description if all items carry the same one; otherwise
- // skip — per-item descriptions clutter a grouped tile.
- if (group.length === 1 && group[0].description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = group[0].description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function groupByKind(components) {
- const groups = [];
- for (const c of components) {
- const last = groups[groups.length - 1];
- if (last && last[0].kind && c.kind === last[0].kind) {
- last.push(c);
- } else {
- groups.push([c]);
- }
- }
- return groups;
- }
-
- function titleForKind(kind, count) {
- const labels = {
- button: 'Buttons',
- input: 'Inputs',
- nav: 'Navigation',
- chip: 'Chips',
- card: 'Cards',
- custom: 'Components',
- };
- return labels[kind] || (kind ? kind.charAt(0).toUpperCase() + kind.slice(1) + 's' : 'Components');
- }
-
- // --- Collapsibles ---------------------------------------------------------
-
- function buildCollapsible(key, label, count) {
- const wrap = document.createElement('div');
- wrap.className = 'coll';
- wrap.setAttribute('data-open', designState.collapsed[key] ? 'false' : 'true');
-
- const head = document.createElement('button');
- head.className = 'coll-head';
- head.innerHTML = `
- <svg class="coll-chev" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 2.5L8 6 4 9.5"/></svg>
- <span>${escapeHtml(label)}</span>
- ${count != null ? `<span class="coll-count">${escapeHtml(String(count))}</span>` : ''}
- `;
- head.addEventListener('click', () => {
- designState.collapsed[key] = !designState.collapsed[key];
- saveDesignPrefs();
- renderDesignBody();
- });
- wrap.appendChild(head);
-
- const body = document.createElement('div');
- body.className = 'coll-body';
- wrap.appendChild(body);
- return { wrap, body };
- }
-
- function renderRulesCollapsible(rules) {
- const { wrap, body } = buildCollapsible('rules', 'Named Rules', rules.length);
- for (const r of rules) {
- const card = document.createElement('div');
- card.className = 'rule-card';
- const name = document.createElement('div');
- name.className = 'name';
- name.innerHTML = `${escapeHtml(r.name)}${r.section ? `<span class="section">${escapeHtml(r.section)}</span>` : ''}`;
- card.appendChild(name);
- const b = document.createElement('div');
- b.className = 'body';
- b.textContent = r.body || '';
- card.appendChild(b);
- body.appendChild(card);
- }
- return wrap;
- }
-
- function renderDosDontsCollapsible(n) {
- const total = (n.dos?.length || 0) + (n.donts?.length || 0);
- const { wrap, body } = buildCollapsible('dosdonts', "Do's and Don'ts", total);
- const grid = document.createElement('div');
- grid.className = 'dos';
- for (const d of n.dos || []) {
- const el = document.createElement('div');
- el.className = 'do';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- for (const d of n.donts || []) {
- const el = document.createElement('div');
- el.className = 'dont';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- body.appendChild(grid);
- return wrap;
- }
-
- function renderOverviewCollapsible(n) {
- const { wrap, body } = buildCollapsible('overview', 'Overview', null);
- const ov = document.createElement('div');
- ov.className = 'overview-body';
- if (n.northStar) {
- const star = document.createElement('span');
- star.className = 'north-star';
- star.textContent = '“' + n.northStar + '”';
- ov.appendChild(star);
- }
- if (n.overview) {
- const p = document.createElement('p');
- p.innerHTML = inlineMd(n.overview);
- ov.appendChild(p);
- }
- if (n.keyCharacteristics?.length) {
- const ul = document.createElement('ul');
- ul.innerHTML = n.keyCharacteristics.map((k) => `<li>${inlineMd(k)}</li>`).join('');
- ov.appendChild(ul);
- }
- body.appendChild(ov);
- return wrap;
- }
-
- function cssSafe(v) {
- // Strip anything outside valid CSS value chars to prevent injection via
- // .impeccable/design.json values rendered into inline style strings.
- return String(v).replace(/[<>"'`\n]/g, '');
- }
-
- // --- Raw tab: minimal markdown renderer (subset) --------------------------
-
- function renderRawTab(body, md) {
- const wrap = document.createElement('div');
- wrap.className = 'md';
- wrap.innerHTML = renderMarkdown(md);
- body.appendChild(wrap);
- }
-
- function renderMarkdown(md) {
- const lines = md.split(/\r?\n/);
- const out = [];
- let i = 0;
- let inCode = false;
- let codeBuf = [];
- let paraBuf = [];
- let listBuf = []; // array of { indent, html }
- let listType = null; // 'ul' | 'ol'
-
- const flushPara = () => {
- if (paraBuf.length) {
- out.push(`<p>${inlineMd(paraBuf.join(' '))}</p>`);
- paraBuf = [];
- }
- };
- const flushList = () => {
- if (listBuf.length) {
- out.push(buildListHtml(listBuf, listType));
- listBuf = [];
- listType = null;
- }
- };
- const flushAll = () => { flushPara(); flushList(); };
-
- for (; i < lines.length; i++) {
- const line = lines[i];
-
- // Code fence
- const fence = line.match(/^```(\w*)\s*$/);
- if (fence) {
- if (!inCode) { flushAll(); inCode = true; codeBuf = []; }
- else {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- inCode = false;
- }
- continue;
- }
- if (inCode) { codeBuf.push(line); continue; }
-
- if (line.trim() === '') { flushAll(); continue; }
-
- const hr = line.match(/^\s*(?:---+|\*\*\*+)\s*$/);
- if (hr) { flushAll(); out.push('<hr />'); continue; }
-
- const heading = line.match(/^(#{1,4})\s+(.+)$/);
- if (heading) {
- flushAll();
- const lvl = heading[1].length;
- out.push(`<h${lvl}>${inlineMd(heading[2])}</h${lvl}>`);
- continue;
- }
-
- const bullet = line.match(/^(\s*)([-*])\s+(.+)$/);
- const ordered = line.match(/^(\s*)(\d+)\.\s+(.+)$/);
- if (bullet || ordered) {
- flushPara();
- const m = bullet || ordered;
- const indent = Math.floor(m[1].length / 2);
- const t = bullet ? 'ul' : 'ol';
- if (listType && listType !== t) flushList();
- listType = t;
- listBuf.push({ indent, html: inlineMd(m[3]) });
- continue;
- }
-
- paraBuf.push(line);
- }
- flushAll();
- if (inCode && codeBuf.length) {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- }
- return out.join('\n');
- }
-
- function buildListHtml(items, type) {
- // Nest by indent (one level deep is plenty for DESIGN.md).
- let html = `<${type}>`;
- let lastIndent = 0;
- for (const it of items) {
- if (it.indent > lastIndent) html += `<${type}>`;
- else if (it.indent < lastIndent) html += `</${type}>`.repeat(lastIndent - it.indent);
- html += `<li>${it.html}</li>`;
- lastIndent = it.indent;
- }
- html += `</${type}>`.repeat(lastIndent + 1);
- return html;
- }
-
- function inlineMd(text) {
- // Order matters: escape first, then re-inject tags.
- let s = escapeHtml(text);
- // Code spans
- s = s.replace(/`([^`]+)`/g, (_, code) => `<code>${code}</code>`);
- // Links [text](url)
- s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, t, u) => `<a href="${u}" target="_blank" rel="noopener noreferrer">${t}</a>`);
- // Bold
- s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
- // Italic (only single *…*, skip if inside bold already handled)
- s = s.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em>$2</em>');
- return s;
- }
-
- function highlightBold(text) {
- return inlineMd(text);
- }
-
- function escapeHtml(s) {
- return String(s)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
-
- function copyToClipboard(text) {
- if (!text) return;
- try {
- navigator.clipboard.writeText(text);
- showToast('Copied: ' + text);
- } catch { /* ignore */ }
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- function init() {
- try { history.scrollRestoration = 'manual'; } catch {}
- initHighlight();
- initAnnotOverlay();
- initBar();
- initActionPicker();
- initParamsPanel();
- initGlobalBar();
- initDesignPanel();
- document.addEventListener('mousemove', handleMouseMove, true);
- document.addEventListener('click', handleClick, true);
- document.addEventListener('keydown', handleKeyDown, true);
- connectSSE();
-
- // Check for an active session to resume (variant wrapper already in DOM after HMR)
- if (!resumeSession()) {
- console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
- // SvelteKit (and any framework that hydrates after HTML parse) may add
- // the variant wrapper AFTER init runs. Watch for it and retry resume
- // once it appears. Disconnect on first hit.
- const scout = new MutationObserver(() => {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) return;
- scout.disconnect();
- if (resumeSession()) {
- console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
- }
- });
- scout.observe(document.body, { childList: true, subtree: true });
- } else {
- console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
- }
- }
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
- } else {
- init();
- }
-})();
@@ -1,75 +0,0 @@
-#!/usr/bin/env node
-/**
- * Canonical durable completion acknowledgement for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function parseArgs(argv) {
- const out = { status: 'complete' };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';
- else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }
- else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function completeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help || !args.id) {
- console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);
- process.exit(args.help ? 0 : 1);
- }
-
- const serverInfo = readServerInfo();
- const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;
- if (serverResult?.ok) {
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const snapshot = store.getSnapshot(args.id, { includeCompleted: true });
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const event = args.status === 'discarded'
- ? { type: 'discarded', id: args.id }
- : args.status === 'agent_error'
- ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }
- : { type: 'complete', id: args.id };
- const snapshot = store.appendEvent(event);
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));
-}
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function completeThroughServer(info, args) {
- const type = args.status === 'discarded'
- ? 'discarded'
- : args.status === 'agent_error'
- ? 'error'
- : 'complete';
- try {
- const res = await fetch(`http://localhost:${info.port}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),
- });
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {
- completeCli();
-}
@@ -1,18 +0,0 @@
-export function completionTypeForAcceptResult(eventType, acceptResult) {
- if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';
- if (acceptResult?.handled === true) return 'complete';
- if (acceptResult?.mode === 'error') return 'error';
- return 'agent_done';
-}
-
-export function completionAckForAcceptResult(eventId, completionType, acceptResult) {
- const ack = { ok: true, type: completionType };
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) {
- ack.final = false;
- ack.requiresComplete = true;
- ack.nextCommand = `live-complete.mjs --id ${eventId}`;
- ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';
- }
- return ack;
-}
@@ -1,446 +0,0 @@
-/**
- * CLI helper: insert/remove the live variant mode script tag in the project's
- * main HTML entry point.
- *
- * On first live run, the agent generates `.impeccable/live/config.json`
- * with the project's insertion target (framework-specific). On
- * every subsequent run, this script handles insert/remove deterministically
- * with zero LLM involvement.
- *
- * Usage:
- * node live-inject.mjs --port PORT # Insert the live script tag
- * node live-inject.mjs --remove # Remove the live script tag
- * node live-inject.mjs --check # Check whether live config exists
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { resolveLiveConfigPath } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });
-const MARKER_OPEN_TEXT = 'impeccable-live-start';
-const MARKER_CLOSE_TEXT = 'impeccable-live-end';
-
-/**
- * Hard-excluded directory patterns. These are NEVER user-facing pages and
- * matching them would silently inject tracking scripts into third-party
- * code. The user cannot turn these off via config — they are the floor.
- */
-const HARD_EXCLUDES = [
- '**/node_modules/**',
- '**/.git/**',
-];
-
-export async function injectCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-inject.mjs [options]
-
-Insert or remove the live mode script tag in the project's HTML entry point.
-Reads configuration from .impeccable/live/config.json.
-
-Modes:
- --port PORT Insert script tag pointing at http://localhost:PORT/live.js
- --remove Remove the script tag (if present)
- --check Print whether .impeccable/live/config.json exists and its content
-
-Output (JSON):
- { ok, file, inserted|removed, config? }`);
- process.exit(0);
- }
-
- if (args.includes('--check')) {
- if (!fs.existsSync(CONFIG_PATH)) {
- console.log(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(0);
- }
- let cfg;
- try {
- cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- try {
- validateConfig(cfg);
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- console.log(JSON.stringify({ ok: true, config: cfg, path: CONFIG_PATH }));
- return;
- }
-
- // Load config
- if (!fs.existsSync(CONFIG_PATH)) {
- console.error(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(1);
- }
- const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- validateConfig(config);
-
- const resolvedFiles = resolveFiles(process.cwd(), config);
-
- if (args.includes('--remove')) {
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const detagged = removeTag(content, config.commentSyntax);
- const updated = revertCspMeta(detagged);
- if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- removed: detagged !== content,
- cspReverted: updated !== detagged,
- };
- });
- console.log(JSON.stringify({ ok: true, results }));
- return;
- }
-
- // Insert mode — need --port
- const portIdx = args.indexOf('--port');
- const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : NaN;
- if (!Number.isFinite(port)) {
- console.error(JSON.stringify({ ok: false, error: 'missing_port' }));
- process.exit(1);
- }
-
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
- const withTag = insertTag(withoutOld, config, port);
- if (withTag === withoutOld) {
- return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
- }
- const updated = patchCspMeta(withTag, port);
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- inserted: true,
- cspPatched: updated !== withTag,
- };
- });
- const anyInserted = results.some((r) => r.inserted);
- console.log(JSON.stringify({ ok: anyInserted, port, results }));
- if (!anyInserted) process.exit(1);
-}
-
-/**
- * Expand config.files (which may contain glob patterns) into a literal list
- * of existing file paths relative to rootDir. Literal entries pass through;
- * glob patterns are expanded via fs.globSync. HARD_EXCLUDES and config.exclude
- * are applied as filters. Duplicates are removed. Order is preserved by
- * first appearance.
- */
-export function resolveFiles(rootDir, config) {
- const patterns = config.files;
- const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
- const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
- const excludeRegexes = allExcludes.map(globToRegex);
-
- const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
- const isGlob = (s) => /[*?[]/.test(s);
-
- const seen = new Set();
- const out = [];
- for (const pat of patterns) {
- if (!isGlob(pat)) {
- // Literal path — include even if it doesn't exist yet; the caller
- // reports file_not_found per-entry. Exclude list doesn't apply to
- // explicit literal entries (user named it on purpose).
- if (!seen.has(pat)) {
- seen.add(pat);
- out.push(pat);
- }
- continue;
- }
- let matches;
- try {
- matches = fs.globSync(pat, { cwd: rootDir, withFileTypes: true });
- } catch {
- continue;
- }
- for (const ent of matches) {
- if (!ent.isFile || !ent.isFile()) continue;
- const abs = path.join(ent.parentPath || ent.path || rootDir, ent.name);
- const rel = path.relative(rootDir, abs).split(path.sep).join('/');
- if (isExcluded(rel)) continue;
- if (seen.has(rel)) continue;
- seen.add(rel);
- out.push(rel);
- }
- }
- return out;
-}
-
-/**
- * Convert a glob pattern to a RegExp. Supports:
- * ** → any number of path segments (including zero)
- * * → any chars except `/`
- * ? → any single char except `/`
- * Paths are normalized to forward slashes before matching.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- // ** — any number of segments, including zero. Handle the common
- // **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
- if (pattern[i + 2] === '/') {
- re += '(?:.*/)?';
- i += 3;
- } else {
- re += '.*';
- i += 2;
- }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Core operations
-// ---------------------------------------------------------------------------
-
-function validateConfig(cfg) {
- if (!cfg || typeof cfg !== 'object') throw new Error('config.json must be an object');
- if (!Array.isArray(cfg.files) || cfg.files.length === 0) {
- throw new Error('config.files (non-empty string array) required');
- }
- if (!cfg.files.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.files must contain only non-empty strings');
- }
- if (cfg.exclude !== undefined) {
- if (!Array.isArray(cfg.exclude)) {
- throw new Error('config.exclude, if present, must be a string array');
- }
- if (!cfg.exclude.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.exclude must contain only non-empty strings');
- }
- }
- if (typeof cfg.insertBefore !== 'string' && typeof cfg.insertAfter !== 'string') {
- throw new Error('config.insertBefore or config.insertAfter (string) required');
- }
- if (cfg.commentSyntax !== 'html' && cfg.commentSyntax !== 'jsx') {
- throw new Error("config.commentSyntax must be 'html' or 'jsx'");
- }
- if (cfg.cspChecked !== undefined && typeof cfg.cspChecked !== 'boolean') {
- throw new Error("config.cspChecked, if present, must be a boolean");
- }
-}
-
-function commentOpen(syntax) { return syntax === 'jsx' ? '{/*' : '<!--'; }
-function commentClose(syntax) { return syntax === 'jsx' ? '*/}' : '-->'; }
-
-function buildTagBlock(syntax, port) {
- const open = commentOpen(syntax);
- const close = commentClose(syntax);
- return (
- open + ' ' + MARKER_OPEN_TEXT + ' ' + close + '\n' +
- '<script src="http://localhost:' + port + '/live.js"></script>\n' +
- open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n'
- );
-}
-
-function insertTag(content, config, port) {
- const block = buildTagBlock(config.commentSyntax, port);
- // insertBefore: match the LAST occurrence. Anchors like `</body>` naturally
- // belong at the end, and the same literal can appear earlier in code blocks
- // within rendered documentation pages.
- if (config.insertBefore) {
- const idx = content.lastIndexOf(config.insertBefore);
- if (idx === -1) return content;
- return content.slice(0, idx) + block + content.slice(idx);
- }
- // insertAfter: match the FIRST occurrence — typical anchors like `<head>` or
- // `<body>` open near the top of the document.
- const idx = content.indexOf(config.insertAfter);
- if (idx === -1) return content;
- const after = idx + config.insertAfter.length;
- // Preserve a single trailing newline if the anchor didn't end with one
- const prefix = content[after] === '\n' ? content.slice(0, after + 1) : content.slice(0, after) + '\n';
- return prefix + block + content.slice(prefix.length);
-}
-
-/**
- * Remove the live script block. Matches either HTML or JSX comment markers
- * regardless of config (so stale tags from a wrong config can still be cleaned).
- *
- * Indent-preserving: captures any whitespace immediately preceding the opener
- * marker and re-emits it in place of the removed block. `insertTag` inserted
- * the block *after* the original line's indent and *before* the anchor (e.g.
- * `</body>`), which moved the indent onto the opener line and left the anchor
- * unindented. Replacing the whole block (plus its trailing newline) with just
- * the captured indent hands the indent back to the anchor that follows.
- */
-function removeTag(content, _syntax) {
- const patterns = [
- /([ \t]*)<!--\s*impeccable-live-start\s*-->[\s\S]*?<!--\s*impeccable-live-end\s*-->[ \t]*\n/,
- /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}[ \t]*\n/,
- ];
- for (const pat of patterns) {
- const next = content.replace(pat, '$1');
- if (next !== content) return next;
- }
- return content;
-}
-
-// ---------------------------------------------------------------------------
-// Content-Security-Policy meta-tag patcher
-//
-// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
-// the cross-origin load of /live.js (and the SSE/POST connection back to
-// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
-//
-// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
-// and stash the original `content` value in a `data-impeccable-csp-original`
-// attribute (base64) so revert is exact.
-//
-// On remove: detect the marker attribute, decode it, restore the original
-// content value verbatim, drop the marker.
-//
-// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
-// shared helpers) is NOT patched here — those need framework-specific config
-// edits and are handled via the existing detect-csp.mjs reference output.
-// Only the in-source meta-tag form gets the auto-patch.
-// ---------------------------------------------------------------------------
-
-const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
-
-function findCspMetaTags(content) {
- const out = [];
- const tagRe = /<meta\s+([^>]*?)\/?>/gis;
- let m;
- while ((m = tagRe.exec(content)) !== null) {
- const attrs = m[1];
- if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
- out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
- }
- return out;
-}
-
-function getAttr(attrs, name) {
- const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
- const m = attrs.match(re);
- return m ? { quote: m[1], value: m[2], full: m[0] } : null;
-}
-
-function appendOriginToDirective(csp, directive, origin) {
- const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
- const m = csp.match(re);
- if (m) {
- const tokens = m[4].trim().split(/\s+/);
- if (tokens.includes(origin)) return csp;
- return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
- }
- // Directive missing — add it. Use 'self' + origin so we don't inadvertently
- // narrow the policy compared to the default-src fallback (most users with
- // an explicit CSP have 'self' there).
- return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
-}
-
-export function patchCspMeta(content, port) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
- const origin = `http://localhost:${port}`;
-
- // Walk last-to-first so prior splices don't invalidate later indices.
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const attrs = tag.attrs;
- if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
- const contentAttr = getAttr(attrs, 'content');
- if (!contentAttr) continue;
-
- const original = contentAttr.value;
- let patched = original;
- patched = appendOriginToDirective(patched, 'script-src', origin);
- patched = appendOriginToDirective(patched, 'connect-src', origin);
- // The shader overlay during 'generating' creates a screenshot via
- // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
- // those. Add `blob:` so the overlay doesn't throw a CSP violation.
- patched = appendOriginToDirective(patched, 'img-src', 'blob:');
- if (patched === original) continue;
-
- const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
- const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
- // The tagRe captures any whitespace between the last attribute and the
- // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
- // a replace would land it BEFORE that trailing space, leaving a double
- // space inside attrs and clobbering the space before `/>`. Split off
- // the trailing whitespace, splice the marker into the attribute body,
- // and re-append the original trailing whitespace so a self-closing
- // `<meta … />` round-trips byte-for-byte.
- const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
- const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
- const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
- const newTag = tag.full.replace(attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-export function revertCspMeta(content) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
-
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
- if (!origAttr) continue;
- const contentAttr = getAttr(tag.attrs, 'content');
- if (!contentAttr) continue;
-
- let originalValue;
- try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
- catch { continue; }
-
- const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
- let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
- // Drop the marker attribute and any single space immediately preceding it.
- newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
- const newTag = tag.full.replace(tag.attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
- injectCli();
-}
-
-export { insertTag, removeTag, validateConfig, buildTagBlock };
-// patchCspMeta + revertCspMeta are exported above where they're defined.
@@ -1,200 +0,0 @@
-/**
- * CLI client for the live variant mode poll/reply protocol.
- *
- * Usage:
- * npx impeccable poll # Block until browser event, print JSON
- * npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
- * npx impeccable poll --reply <id> done # Reply "done" to event <id>
- * npx impeccable poll --reply <id> error "msg" # Reply with error
- */
-
-import { execFileSync } from 'node:child_process';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-// Node's built-in fetch (undici under the hood) enforces a 300s headers
-// timeout that can't be lowered per-request. We cap each request below
-// that ceiling and loop in `pollOnce` to synthesize a long poll without
-// depending on the standalone undici package.
-const PER_REQUEST_TIMEOUT_MS = 270_000;
-
-function readServerInfo() {
- const record = readLiveServerInfo(process.cwd());
- if (!record) {
- console.error('No running live server found. Start one with: npx impeccable live');
- process.exit(1);
- }
- return record.info;
-}
-
-export function buildPollReplyPayload(token, { id, type, message, file, data }) {
- return { token, id, type, message, file, data };
-}
-
-async function postReply(base, token, reply) {
- const res = await fetch(`${base}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(buildPollReplyPayload(token, reply)),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error || res.statusText);
- }
-}
-
-export async function pollCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable poll [options]
-
-Wait for a browser event from the live variant server, or reply to one.
-
-Modes:
- poll Block until a browser event arrives, print JSON
- poll --reply <id> done Reply "done" to event <id>
- poll --reply <id> error "msg" Reply with an error message
-
-Options:
- --timeout=MS Long-poll timeout in ms (default: 600000). Use the default unless the user asked to pause live; never use a short timeout to end the chat turn
- --help Show this help message`);
- process.exit(0);
- }
-
- const info = readServerInfo();
- const base = `http://localhost:${info.port}`;
-
- // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
- const replyIdx = args.indexOf('--reply');
- if (replyIdx !== -1) {
- const id = args[replyIdx + 1];
- const status = args[replyIdx + 2] || 'done';
- const fileIdx = args.indexOf('--file');
- const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
- // Message is any remaining positional arg that isn't a flag
- const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
-
- if (!id) {
- console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
- process.exit(1);
- }
-
- try {
- await postReply(base, info.token, { id, type: status, message, file: filePath });
-
- // Success — silent exit (agent doesn't need output for replies)
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Reply failed:', err.message);
- }
- process.exit(1);
- }
- return;
- }
-
- // Poll mode: block until browser event. Default 10 min. Node's built-in
- // fetch enforces a 300s headers timeout, so we loop in slices under that
- // ceiling and keep re-polling until we get a real event or the user's
- // total timeout runs out.
- const timeoutArg = args.find(a => a.startsWith('--timeout='));
- const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600000;
-
- const deadline = Date.now() + totalTimeout;
- let event;
- try {
- while (true) {
- const remaining = deadline - Date.now();
- if (remaining <= 0) {
- event = { type: 'timeout' };
- break;
- }
- const slice = Math.min(remaining, PER_REQUEST_TIMEOUT_MS);
- const res = await fetch(`${base}/poll?token=${info.token}&timeout=${slice}`);
-
- if (res.status === 401) {
- console.error('Authentication failed. The server token may have changed.');
- console.error('Try restarting: npx impeccable live stop && npx impeccable live');
- process.exit(1);
- }
-
- if (!res.ok) {
- console.error(`Poll failed: ${res.status} ${res.statusText}`);
- process.exit(1);
- }
-
- const next = await res.json();
- // Server-side timeout means no browser event arrived in this slice.
- // Loop and re-poll until we get a real event or we hit the user's
- // total deadline.
- if (next?.type === 'timeout' && Date.now() < deadline) continue;
- event = next;
- break;
- }
-
- // Auto-handle accept/discard via deterministic script
- if (event.type === 'accept' || event.type === 'discard') {
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const acceptScript = path.join(__dirname, 'live-accept.mjs');
- const scriptArgs = event.type === 'discard'
- ? ['--id', event.id, '--discard']
- : ['--id', event.id, '--variant', event.variantId];
- if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
- scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
- }
- try {
- const out = execFileSync(
- 'node',
- [acceptScript, ...scriptArgs],
- { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 }
- );
- event._acceptResult = JSON.parse(out.trim());
- } catch (err) {
- event._acceptResult = { handled: false, mode: 'error', error: err.message };
- }
-
- const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
- try {
- await postReply(base, info.token, {
- id: event.id,
- type: completionType,
- message: event._acceptResult?.error,
- file: event._acceptResult?.file,
- data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
- });
- } catch (err) {
- event._completionAck = { ok: false, error: err.message };
- }
- if (!event._completionAck) {
- event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
- }
- }
-
- // Second signal path: stderr banner in case the agent parses stdout
- // JSON but skips nested fields. One line is enough — the full checklist
- // is in reference/live.md.
- if (event._acceptResult?.carbonize === true) {
- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
- }
-
- // Print the event as JSON — the agent reads this from stdout
- console.log(JSON.stringify(event));
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Poll failed:', err.message);
- }
- process.exit(1);
- }
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
- pollCli();
-}
@@ -1,48 +0,0 @@
-#!/usr/bin/env node
-/**
- * Recover the next agent action from the durable live-session journal.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-
-function parseArgs(argv) {
- const out = { id: null };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function resumeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help) {
- console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });
- const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;
- if (!snapshot) {
- console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));
- return;
- }
-
- const pending = snapshot.pendingEvent || null;
- const nextAction = pending
- ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`
- : snapshot.phase === 'carbonize_required'
- ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`
- : snapshot.phase === 'accept_requested'
- ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`
- : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;
-
- console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {
- resumeCli();
-}
@@ -1,838 +0,0 @@
-#!/usr/bin/env node
-/**
- * Live variant mode server (self-contained, zero dependencies).
- *
- * Serves the browser script (/live.js), the detection overlay (/detect.js),
- * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
- * browser→server events. Agent communicates via HTTP long-poll (/poll).
- *
- * Usage:
- * node <scripts_path>/live-server.mjs # start
- * node <scripts_path>/live-server.mjs stop # stop + remove injected live.js tag
- * node <scripts_path>/live-server.mjs stop --keep-inject # stop only
- * node <scripts_path>/live-server.mjs --help
- */
-
-import http from 'node:http';
-import { randomUUID } from 'node:crypto';
-import { spawn, execFileSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import net from 'node:net';
-import { fileURLToPath } from 'node:url';
-import { parseDesignMd } from './design-parser.mjs';
-import { resolveContextDir } from './load-context.mjs';
-import { createLiveSessionStore } from './live-session-store.mjs';
-import {
- getDesignSidecarPath,
- getLiveAnnotationsDir,
- readLiveServerInfo,
- removeLiveServerInfo,
- resolveDesignSidecarPath,
- writeLiveServerInfo,
-} from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated
-// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
-// DESIGN.json fallback for existing projects.
-const CONTEXT_DIR = resolveContextDir(process.cwd());
-const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anyway
-const SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s
-
-// ---------------------------------------------------------------------------
-// Port detection
-// ---------------------------------------------------------------------------
-
-async function findOpenPort(start = 8400) {
- return new Promise((resolve) => {
- const srv = net.createServer();
- srv.listen(start, '127.0.0.1', () => {
- const port = srv.address().port;
- srv.close(() => resolve(port));
- });
- srv.on('error', () => resolve(findOpenPort(start + 1)));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Session state
-// ---------------------------------------------------------------------------
-
-const state = {
- token: null,
- port: null,
- sseClients: new Set(), // SSE response objects (server→browser push)
- pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
- pendingPolls: [], // agent poll callbacks waiting for browser events
- exitTimer: null,
- sessionDir: null, // per-session tmp dir for annotation screenshots
- sessionStore: null,
- leaseTimer: null,
-};
-
-// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;
-// cap at 10 MB to guard against runaway writes from a misbehaving client.
-const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
-
-function enqueueEvent(event) {
- if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;
- state.pendingEvents.push({ event, leaseUntil: 0 });
- flushPendingPolls();
-}
-
-function restorePendingEventsFromStore() {
- if (!state.sessionStore) return;
- for (const snapshot of state.sessionStore.listActiveSessions()) {
- if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);
- }
-}
-
-function findAvailablePendingEvent(now = Date.now()) {
- return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);
-}
-
-function leaseEvent(entry, leaseMs) {
- if (!entry.event?.id) {
- const idx = state.pendingEvents.indexOf(entry);
- if (idx !== -1) state.pendingEvents.splice(idx, 1);
- return entry.event;
- }
- entry.leaseUntil = Date.now() + leaseMs;
- return entry.event;
-}
-
-function acknowledgePendingEvent(id) {
- if (!id) return false;
- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);
- if (idx === -1) return false;
- state.pendingEvents.splice(idx, 1);
- scheduleLeaseFlush();
- return true;
-}
-
-function scheduleLeaseFlush() {
- if (state.leaseTimer) {
- clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- }
- if (state.pendingPolls.length === 0) return;
- const now = Date.now();
- const nextLeaseUntil = state.pendingEvents
- .map((entry) => entry.leaseUntil || 0)
- .filter((leaseUntil) => leaseUntil > now)
- .sort((a, b) => a - b)[0];
- if (!nextLeaseUntil) return;
- state.leaseTimer = setTimeout(() => {
- state.leaseTimer = null;
- flushPendingPolls();
- }, Math.max(0, nextLeaseUntil - now));
-}
-
-function flushPendingPolls() {
- while (state.pendingPolls.length > 0) {
- const entry = findAvailablePendingEvent();
- if (!entry) {
- scheduleLeaseFlush();
- return;
- }
- const poll = state.pendingPolls.shift();
- poll.resolve(leaseEvent(entry, poll.leaseMs));
- }
- scheduleLeaseFlush();
-}
-
-/** Push a message to all connected SSE clients. */
-function broadcast(msg) {
- const data = 'data: ' + JSON.stringify(msg) + '\n\n';
- for (const res of state.sseClients) {
- try { res.write(data); } catch { /* client gone */ }
- }
-}
-
-// ---------------------------------------------------------------------------
-// Load scripts
-// ---------------------------------------------------------------------------
-
-function loadBrowserScripts() {
- // Detection script: prefer the skill-bundled detector, then fall back to
- // source/npm package locations for local development and older installs.
- // This one IS cached — detect.js rarely changes during a session.
- const detectPaths = [
- path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(process.cwd(), 'node_modules', 'impeccable', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- ];
- let detectScript = '';
- for (const p of detectPaths) {
- try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
- }
-
- // live-browser.js: DO NOT cache. Return the path so the /live.js handler
- // can re-read on every request. Editing the browser script during iteration
- // should land on the next tab reload, not require a server restart.
- const sessionPath = path.join(__dirname, 'live-browser-session.js');
- const livePath = path.join(__dirname, 'live-browser.js');
- for (const p of [sessionPath, livePath]) {
- if (!fs.existsSync(p)) {
- process.stderr.write('Error: live browser script not found at ' + p + '\n');
- process.exit(1);
- }
- }
-
- return { detectScript, sessionPath, livePath };
-}
-
-function hasProjectContext() {
- // PRODUCT.md carries brand voice / anti-references — that's what determines
- // whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
- // concern, surfaced by the design panel's own empty state. Legacy
- // .impeccable.md is auto-migrated to PRODUCT.md by load-context.mjs.
- try {
- fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
- return true;
- } catch { return false; }
-}
-
-function statOrNull(filePath) {
- try { return fs.statSync(filePath); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// Validation (inline — no external import needed for self-contained script)
-// ---------------------------------------------------------------------------
-
-const VISUAL_ACTIONS = [
- 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
- 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
-];
-
-// Browser generates ids via crypto.randomUUID().slice(0, 8) (8 hex chars)
-// and variantIds via String(small integer). Restrict to those shapes so
-// any value that reaches a downstream child_process or DOM selector is
-// inert by construction.
-const ID_PATTERN = /^[0-9a-f]{8}$/;
-const VARIANT_ID_PATTERN = /^[0-9]{1,3}$/;
-
-function isValidId(v) { return typeof v === 'string' && ID_PATTERN.test(v); }
-function isValidVariantId(v) { return typeof v === 'string' && VARIANT_ID_PATTERN.test(v); }
-
-function validateEvent(msg) {
- if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
- switch (msg.type) {
- case 'generate':
- if (!isValidId(msg.id)) return 'generate: missing or malformed id';
- if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
- if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
- if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
- // Optional annotation fields (all-or-nothing: if any present, all must be well-formed).
- if (msg.screenshotPath !== undefined && typeof msg.screenshotPath !== 'string') return 'generate: screenshotPath must be string';
- if (msg.comments !== undefined && !Array.isArray(msg.comments)) return 'generate: comments must be array';
- if (msg.strokes !== undefined && !Array.isArray(msg.strokes)) return 'generate: strokes must be array';
- return null;
- case 'accept':
- if (!isValidId(msg.id)) return 'accept: missing or malformed id';
- if (!isValidVariantId(msg.variantId)) return 'accept: missing or malformed variantId';
- if (msg.paramValues !== undefined) {
- if (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues)) {
- return 'accept: paramValues must be an object';
- }
- }
- return null;
- case 'discard':
- return isValidId(msg.id) ? null : 'discard: missing or malformed id';
- case 'checkpoint':
- if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';
- if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';
- if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {
- return 'checkpoint: paramValues must be an object';
- }
- return null;
- case 'exit':
- return null;
- case 'prefetch':
- if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return 'prefetch: missing pageUrl';
- return null;
- default:
- return 'Unknown event type: ' + msg.type;
- }
-}
-
-// ---------------------------------------------------------------------------
-// HTTP request handler
-// ---------------------------------------------------------------------------
-
-function createRequestHandler({ detectScript, sessionPath, livePath }) {
- return (req, res) => {
- const url = new URL(req.url, `http://localhost:${state.port}`);
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
- if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
-
- const p = url.pathname;
-
- // --- Scripts ---
- if (p === '/live.js') {
- // Re-read from disk each request so edits to live-browser.js land on
- // the next tab reload. No-store headers prevent browser caching across
- // sessions — during iteration, a cached old script silently breaks
- // every subsequent session.
- let sessionScript;
- let liveScript;
- try {
- sessionScript = fs.readFileSync(sessionPath, 'utf-8');
- liveScript = fs.readFileSync(livePath, 'utf-8');
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'text/plain' });
- res.end('Error reading live browser scripts: ' + err.message);
- return;
- }
- const body =
- `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
- `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
- sessionScript + '\n' +
- liveScript;
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
- 'Pragma': 'no-cache',
- });
- res.end(body);
- return;
- }
- if (p === '/detect.js' || p === '/') {
- if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
- res.writeHead(200, { 'Content-Type': 'application/javascript' });
- res.end(detectScript);
- return;
- }
-
- // --- Vendored modern-screenshot (UMD build) ---
- // Lazy-loaded by live.js when the user clicks Go; exposes
- // window.modernScreenshot.domToBlob(...) for capture.
- if (p === '/modern-screenshot.js') {
- const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
- try {
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'public, max-age=31536000, immutable',
- });
- res.end(fs.readFileSync(vendorPath));
- } catch {
- res.writeHead(404); res.end('Vendor script not found');
- }
- return;
- }
-
- // --- Annotation upload (browser → server, raw PNG body) ---
- // Client generates the eventId, POSTs the PNG, then POSTs the generate
- // event with screenshotPath already set. Keeps bytes out of the SSE/poll
- // bridge and preserves the "one shot from the user's POV" UX.
- if (p === '/annotation' && req.method === 'POST') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const eventId = url.searchParams.get('eventId');
- if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid eventId' }));
- return;
- }
- if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
- res.writeHead(415, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
- return;
- }
- if (!state.sessionDir) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Session dir unavailable' }));
- return;
- }
- const chunks = [];
- let total = 0;
- let aborted = false;
- req.on('data', (c) => {
- if (aborted) return;
- total += c.length;
- if (total > MAX_ANNOTATION_BYTES) {
- aborted = true;
- res.writeHead(413, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Payload too large' }));
- req.destroy();
- return;
- }
- chunks.push(c);
- });
- req.on('end', () => {
- if (aborted) return;
- const absPath = path.join(state.sessionDir, eventId + '.png');
- try {
- fs.writeFileSync(absPath, Buffer.concat(chunks));
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Write failed: ' + err.message }));
- return;
- }
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true, path: absPath }));
- });
- req.on('error', () => {
- if (!aborted) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Upload failed' }));
- }
- });
- return;
- }
-
- // --- Health ---
- if (p === '/status') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
- const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok',
- port: state.port,
- connectedClients: state.sseClients.size,
- pendingEvents: state.pendingEvents.map((entry) => ({
- id: entry.event?.id,
- type: entry.event?.type,
- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),
- leaseUntil: entry.leaseUntil || null,
- })),
- activeSessions: sessions,
- }));
- return;
- }
-
- if (p === '/health') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok', port: state.port, mode: 'variant',
- hasProjectContext: hasProjectContext(),
- connectedClients: state.sseClients.size,
- }));
- return;
- }
-
- // --- Design system (unified v2 response) + raw ---
- // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json
- // sidecar when present. Panel merges them:
- // { present, parsed, sidecar, hasMd, hasSidecar,
- // mdNewerThanJson, parseError?, sidecarError? }
- // - parsed: output of parseDesignMd (frontmatter
- // + six canonical sections) when DESIGN.md exists.
- // - sidecar: .impeccable/design.json contents when present.
- // Expected shape: schemaVersion 2, carrying
- // extensions + components + narrative.
- // /design-system/raw returns DESIGN.md markdown verbatim
- if (p === '/design-system.json' || p === '/design-system/raw') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
-
- const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
- const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
- const mdStat = statOrNull(mdPath);
- const jsonStat = statOrNull(jsonPath);
-
- if (p === '/design-system/raw') {
- if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
- res.end(fs.readFileSync(mdPath, 'utf-8'));
- return;
- }
-
- if (!mdStat && !jsonStat) {
- res.writeHead(404, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ present: false }));
- return;
- }
-
- const response = {
- present: true,
- hasMd: !!mdStat,
- hasSidecar: !!jsonStat,
- mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
- };
-
- if (mdStat) {
- try {
- response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
- } catch (err) {
- response.parseError = err.message;
- }
- }
-
- if (jsonStat) {
- try {
- response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
- } catch (err) {
- response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;
- }
- }
-
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(response));
- return;
- }
-
- // --- Source file (no-HMR fallback) ---
- if (p === '/source') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const filePath = url.searchParams.get('path');
- if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
- const absPath = path.resolve(process.cwd(), filePath);
- if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
- let content;
- try { content = fs.readFileSync(absPath, 'utf-8'); }
- catch { res.writeHead(404); res.end('File not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
- res.end(content);
- return;
- }
-
- // --- SSE: server→browser push (replaces WebSocket) ---
- if (p === '/events' && req.method === 'GET') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- 'Connection': 'keep-alive',
- });
- res.write('data: ' + JSON.stringify({
- type: 'connected',
- hasProjectContext: hasProjectContext(),
- }) + '\n\n');
-
- state.sseClients.add(res);
- clearTimeout(state.exitTimer);
-
- // Keepalive: SSE comment every 30s prevents silent connection drops.
- const heartbeat = setInterval(() => {
- try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
- }, SSE_HEARTBEAT_INTERVAL);
-
- req.on('close', () => {
- clearInterval(heartbeat);
- state.sseClients.delete(res);
- if (state.sseClients.size === 0) {
- clearTimeout(state.exitTimer);
- state.exitTimer = setTimeout(() => {
- if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
- }, 8000);
- }
- });
- return;
- }
-
- // --- Browser→server events (replaces WebSocket messages) ---
- if (p === '/events' && req.method === 'POST') {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const error = validateEvent(msg);
- if (error) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error }));
- return;
- }
- if (state.sessionStore && msg.id) {
- try {
- state.sessionStore.appendEvent(msg);
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
- return;
- }
- }
- if (msg.type !== 'checkpoint') enqueueEvent(msg);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
- return;
- }
-
- // --- Stop ---
- if (p === '/stop') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.end('stopping');
- shutdown();
- return;
- }
-
- // --- Agent poll ---
- if (p === '/poll' && req.method === 'GET') {
- handlePollGet(req, res, url);
- return;
- }
- if (p === '/poll' && req.method === 'POST') {
- handlePollPost(req, res);
- return;
- }
-
- res.writeHead(404); res.end('Not found');
- };
-}
-
-// ---------------------------------------------------------------------------
-// Agent poll endpoints (unchanged from WS version)
-// ---------------------------------------------------------------------------
-
-function handlePollGet(req, res, url) {
- const token = url.searchParams.get('token');
- if (token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
- const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
- const available = findAvailablePendingEvent();
- if (available) {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(leaseEvent(available, leaseMs)));
- return;
- }
- const poll = { resolve, leaseMs };
- const timer = setTimeout(() => {
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ type: 'timeout' }));
- }, timeout);
- function resolve(event) {
- clearTimeout(timer);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(event));
- }
- state.pendingPolls.push(poll);
- scheduleLeaseFlush();
- req.on('close', () => {
- clearTimeout(timer);
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- });
-}
-
-function handlePollPost(req, res) {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- acknowledgePendingEvent(msg.id);
- if (state.sessionStore && msg.id) {
- try {
- const eventType = msg.type === 'discard' || msg.type === 'discarded'
- ? 'discarded'
- : msg.type === 'complete'
- ? 'complete'
- : msg.type === 'error'
- ? 'agent_error'
- : 'agent_done';
- state.sessionStore.appendEvent({
- type: eventType,
- id: msg.id,
- file: msg.file,
- message: msg.message,
- carbonize: msg.data?.carbonize === true,
- });
- } catch { /* keep reply path best-effort; browser still needs SSE */ }
- }
- flushPendingPolls();
- // Forward the reply to the browser via SSE
- broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Lifecycle
-// ---------------------------------------------------------------------------
-
-let httpServer = null;
-
-function shutdown() {
- removeLiveServerInfo(process.cwd());
- if (state.leaseTimer) clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- if (state.sessionDir) {
- try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}
- }
- for (const res of state.sseClients) { try { res.end(); } catch {} }
- state.sseClients.clear();
- for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });
- state.pendingPolls.length = 0;
- if (httpServer) httpServer.close();
- process.exit(0);
-}
-
-// ---------------------------------------------------------------------------
-// Main
-// ---------------------------------------------------------------------------
-
-const args = process.argv.slice(2);
-
-if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-server.mjs [options]
-
-Start the live variant mode server (zero dependencies).
-
-Commands:
- (default) Start the server (foreground)
- stop Stop the server and remove the injected live.js script tag
- stop --keep-inject Stop the server only (leave the script tag in the HTML entry)
-
-Options:
- --background Start detached, print connection JSON to stdout, then exit
- --port=PORT Use a specific port (default: auto-detect starting at 8400)
- --keep-inject Only with stop: skip live-inject.mjs --remove
- --help Show this help
-
-Endpoints:
- /live.js Browser script (element picker + variant cycling)
- /detect.js Detection overlay (backwards compatible)
- /modern-screenshot.js Vendored modern-screenshot UMD build (lazy-loaded by live.js)
- /annotation POST raw image/png to stage a variant screenshot
- /events SSE stream (server→browser) + POST (browser→server)
- /poll Long-poll for agent CLI
- /source Raw source file reader (no-HMR fallback)
- /status Durable recovery status (token-protected)
- /health Health check`);
- process.exit(0);
-}
-
-if (args.includes('stop')) {
- const keepInject = args.includes('--keep-inject');
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);
- if (res.ok) console.log(`Stopped live server on port ${info.port}.`);
- } catch {
- console.log('No running live server found.');
- }
- if (!keepInject) {
- const injectPath = path.join(__dirname, 'live-inject.mjs');
- try {
- const out = execFileSync(process.execPath, [injectPath, '--remove'], {
- encoding: 'utf-8',
- cwd: process.cwd(),
- });
- const line = out.trim().split('\n').filter(Boolean).pop();
- if (line) {
- try {
- const j = JSON.parse(line);
- if (j.removed === true) {
- console.log(`Removed live script tag from ${j.file}.`);
- }
- } catch {
- /* ignore non-JSON lines */
- }
- }
- } catch (err) {
- const detail = err.stderr?.toString?.().trim?.()
- || err.stdout?.toString?.().trim?.()
- || err.message
- || String(err);
- console.warn(`Note: could not remove live script tag (${detail.split('\n')[0]})`);
- }
- }
- process.exit(0);
-}
-
-// --background: spawn a detached child server, wait for it to be ready,
-// print the connection JSON, then exit. This keeps the startup command
-// simple (no shell backgrounding or chained commands).
-if (args.includes('--background')) {
- const childArgs = args.filter(a => a !== '--background');
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), ...childArgs], {
- detached: true,
- stdio: 'ignore',
- cwd: process.cwd(),
- });
- child.unref();
-
- // Poll for the PID file (the child writes it once the HTTP server is listening).
- const deadline = Date.now() + 10_000;
- while (Date.now() < deadline) {
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- if (info.pid !== process.pid) {
- // Output JSON so the agent can read port + token from stdout.
- console.log(JSON.stringify(info));
- process.exit(0);
- }
- } catch { /* not ready yet */ }
- await new Promise(r => setTimeout(r, 200));
- }
- console.error('Timed out waiting for live server to start.');
- process.exit(1);
-}
-
-// Check for existing session
-const existingRecord = readLiveServerInfo(process.cwd());
-if (existingRecord?.info) {
- const existing = existingRecord.info;
- try {
- process.kill(existing.pid, 0);
- console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
- console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');
- process.exit(1);
- } catch {
- try { fs.unlinkSync(existingRecord.path); } catch {}
- }
-}
-
-state.token = randomUUID();
-state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });
-restorePendingEventsFromStore();
-const portArg = args.find(a => a.startsWith('--port='));
-state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
-// Annotation screenshots live in the project root so the agent's Read tool
-// doesn't trip a per-file permission prompt. Sessioned by token so concurrent
-// projects (or quick restarts) don't collide.
-const annotRoot = getLiveAnnotationsDir(process.cwd());
-fs.mkdirSync(annotRoot, { recursive: true });
-state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));
-
-const { detectScript, sessionPath, livePath } = loadBrowserScripts();
-httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));
-
-httpServer.listen(state.port, '127.0.0.1', () => {
- writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });
- const url = `http://localhost:${state.port}`;
- console.log(`\nImpeccable live server running on ${url}`);
- console.log(`Token: ${state.token}\n`);
- console.log(`Inject: <script src="${url}/live.js"><\/script>`);
- console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
-});
-
-process.on('SIGINT', shutdown);
-process.on('SIGTERM', shutdown);
@@ -1,254 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';
-
-const COMPLETED_PHASES = new Set(['completed', 'discarded']);
-
-export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {
- const rootDir = getLiveSessionsDir(cwd);
- const legacyRootDir = getLegacyLiveSessionsDir(cwd);
- fs.mkdirSync(rootDir, { recursive: true });
- const snapshotCache = new Map();
-
- function loadCachedOrRebuild(id) {
- const cached = snapshotCache.get(id);
- if (cached) return cached;
- const journalPath = getReadableJournalPath(id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- return rebuilt;
- }
-
- function getReadableJournalPath(id) {
- const primary = getJournalPath(rootDir, id);
- if (fs.existsSync(primary)) return primary;
- const legacy = getJournalPath(legacyRootDir, id);
- if (fs.existsSync(legacy)) return legacy;
- return primary;
- }
-
- return {
- rootDir,
- legacyRootDir,
- appendEvent(event) {
- const normalized = normalizeEvent(event, sessionId);
- const journalPath = getJournalPath(rootDir, normalized.id);
- const snapshotPath = getSnapshotPath(rootDir, normalized.id);
- const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);
- if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {
- fs.copyFileSync(legacyJournalPath, journalPath);
- }
- const prior = loadCachedOrRebuild(normalized.id);
- const seq = prior.nextSeq;
- const entry = {
- seq,
- id: normalized.id,
- type: normalized.type,
- ts: new Date().toISOString(),
- event: normalized,
- };
- fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');
- const next = applyEvent(prior.snapshot, entry, prior.diagnostics);
- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });
- writeSnapshot(snapshotPath, next);
- return next;
- },
- getSnapshot(id = sessionId, opts = {}) {
- if (!id) throw new Error('session id required');
- const journalPath = getReadableJournalPath(id);
- const snapshotPath = getSnapshotPath(rootDir, id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- writeSnapshot(snapshotPath, rebuilt.snapshot);
- if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;
- return rebuilt.snapshot;
- },
- listActiveSessions() {
- const ids = new Set();
- for (const dir of [legacyRootDir, rootDir]) {
- if (!fs.existsSync(dir)) continue;
- for (const name of fs.readdirSync(dir)) {
- if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));
- }
- }
- return [...ids]
- .sort()
- .map((id) => this.getSnapshot(id))
- .filter(Boolean);
- },
- };
-}
-
-function normalizeEvent(event, fallbackId) {
- if (!event || typeof event !== 'object') throw new Error('event object required');
- const id = event.id || fallbackId;
- if (!id || typeof id !== 'string') throw new Error('event id required');
- if (!event.type || typeof event.type !== 'string') throw new Error('event type required');
- return { ...event, id };
-}
-
-function getJournalPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.jsonl');
-}
-
-function getSnapshotPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.snapshot.json');
-}
-
-function safeSessionId(id) {
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);
- return id;
-}
-
-function baseSnapshot(id) {
- return {
- id,
- phase: 'new',
- pageUrl: null,
- sourceFile: null,
- expectedVariants: 0,
- arrivedVariants: 0,
- visibleVariant: null,
- paramValues: {},
- pendingEventSeq: null,
- pendingEvent: null,
- deliveryLease: null,
- checkpointRevision: 0,
- activeOwner: null,
- sourceMarkers: {},
- fallbackMode: null,
- annotationArtifacts: [],
- diagnostics: [],
- updatedAt: null,
- };
-}
-
-function rebuildSnapshotFromJournal(journalPath, id) {
- let snapshot = baseSnapshot(id);
- const diagnostics = [];
- let nextSeq = 1;
- if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };
-
- const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- if (!line.trim()) continue;
- try {
- const entry = JSON.parse(line);
- if (!entry || typeof entry !== 'object') throw new Error('entry is not object');
- if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);
- snapshot = applyEvent(snapshot, entry);
- } catch (err) {
- diagnostics.push({
- error: 'journal_parse_failed',
- line: i + 1,
- message: err.message,
- });
- }
- }
- snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];
- return { snapshot, diagnostics, nextSeq };
-}
-
-function applyEvent(snapshot, entry, inheritedDiagnostics = []) {
- const event = entry.event || entry;
- const next = {
- ...snapshot,
- paramValues: { ...(snapshot.paramValues || {}) },
- sourceMarkers: { ...(snapshot.sourceMarkers || {}) },
- annotationArtifacts: [...(snapshot.annotationArtifacts || [])],
- diagnostics: [...(snapshot.diagnostics || [])],
- updatedAt: entry.ts || new Date().toISOString(),
- };
-
- if (inheritedDiagnostics.length && next.diagnostics.length === 0) {
- next.diagnostics = [...inheritedDiagnostics];
- }
-
- switch (event.type) {
- case 'generate':
- next.phase = 'generate_requested';
- next.pageUrl = event.pageUrl ?? next.pageUrl;
- next.expectedVariants = event.count ?? next.expectedVariants;
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });
- break;
- case 'variants_ready':
- case 'agent_done':
- next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';
- next.sourceFile = event.file ?? next.sourceFile;
- next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- if (event.carbonize === true) {
- next.diagnostics.push({
- error: 'carbonize_cleanup_required',
- file: event.file || null,
- message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',
- });
- }
- break;
- case 'checkpoint':
- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {
- next.phase = event.phase ?? next.phase;
- next.checkpointRevision = event.revision ?? next.checkpointRevision;
- next.activeOwner = event.owner ?? next.activeOwner;
- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;
- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- } else {
- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });
- }
- break;
- case 'accept':
- case 'accept_intent':
- next.phase = 'accept_requested';
- next.visibleVariant = Number(event.variantId ?? next.visibleVariant);
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discard':
- next.phase = 'discard_requested';
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discarded':
- next.phase = 'discarded';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'complete':
- next.phase = 'completed';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'agent_error':
- next.phase = 'agent_error';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });
- break;
- default:
- next.diagnostics.push({ error: 'unknown_event_type', type: event.type });
- break;
- }
- return next;
-}
-
-function toPendingEvent(event) {
- const pending = { ...event };
- delete pending.token;
- return pending;
-}
-
-function upsertArtifact(artifacts, artifact) {
- if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {
- artifacts.push(artifact);
- }
-}
-
-function writeSnapshot(snapshotPath, snapshot) {
- fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');
-}
@@ -1,47 +0,0 @@
-#!/usr/bin/env node
-/**
- * Print durable recovery status for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function fetchServerStatus(info) {
- if (!info) return null;
- try {
- const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-export async function statusCli() {
- const info = readServerInfo();
- const server = await fetchServerStatus(info);
- const store = createLiveSessionStore({ cwd: process.cwd() });
- const activeSessions = store.listActiveSessions();
- const payload = {
- liveServer: server ? {
- status: server.status,
- port: server.port,
- connectedClients: server.connectedClients,
- pendingEvents: server.pendingEvents,
- } : null,
- activeSessions: server?.activeSessions || activeSessions,
- recoveryHint: server
- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'
- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',
- };
- console.log(JSON.stringify(payload, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {
- statusCli();
-}
@@ -1,632 +0,0 @@
-/**
- * CLI helper: find an element in source and wrap it in a variant container.
- *
- * Usage:
- * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
- *
- * Searches project files for the element matching the query (class name, ID, or
- * text snippet), wraps it with the variant scaffolding, and prints the file path
- * + line range where the agent should insert variant HTML.
- *
- * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-export async function wrapCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable wrap [options]
-
-Find an element in source and wrap it in a variant container.
-
-Required:
- --id ID Session ID for the variant wrapper
- --count N Number of expected variants (1-8)
-
-Element identification (at least one required):
- --element-id ID HTML id attribute of the element
- --classes A,B,C Comma-separated CSS class names
- --tag TAG Tag name (div, section, etc.)
- --query TEXT Fallback: raw text to search for
-
-Optional:
- --file PATH Source file to search in (skips auto-detection)
- --text TEXT Picked element's textContent. Used to disambiguate when
- classes/tag match multiple sibling elements (e.g. a list
- of <Card>s with the same className). Pass the first ~80
- chars of event.element.textContent.
- --help Show this help message
-
-Output (JSON):
- { file, startLine, endLine, insertLine, commentSyntax }
-
-The agent should insert variant HTML at insertLine.`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const count = parseInt(argVal(args, '--count') || '3');
- const elementId = argVal(args, '--element-id');
- const classes = argVal(args, '--classes');
- const tag = argVal(args, '--tag');
- const query = argVal(args, '--query');
- const filePath = argVal(args, '--file');
- const text = argVal(args, '--text');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!elementId && !classes && !query) {
- console.error('Need at least one of: --element-id, --classes, --query');
- process.exit(1);
- }
-
- // Build search queries in priority order (most specific first)
- const queries = buildSearchQueries(elementId, classes, tag, query);
-
- const genOpts = { cwd: process.cwd() };
-
- // Find the source file. Generated files are excluded from auto-search so we
- // don't silently write variants into a file the next build will wipe.
- let targetFile = filePath;
- let matchedQuery = null;
- if (!targetFile) {
- for (const q of queries) {
- targetFile = findFileWithQuery(q, process.cwd(), genOpts);
- if (targetFile) { matchedQuery = q; break; }
- }
- if (!targetFile) {
- // Nothing in source. Did the element show up in a generated file? That
- // tells the agent "fall back to the agent-driven flow" vs "element just
- // doesn't exist in this project."
- let generatedHit = null;
- for (const q of queries) {
- generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
- if (generatedHit) break;
- }
- if (generatedHit) {
- console.error(JSON.stringify({
- error: 'element_not_in_source',
- fallback: 'agent-driven',
- generatedMatch: path.relative(process.cwd(), generatedHit),
- hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
- }));
- } else {
- console.error(JSON.stringify({
- error: 'element_not_found',
- fallback: 'agent-driven',
- hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
- }));
- }
- process.exit(1);
- }
- } else {
- if (isGeneratedFile(targetFile, genOpts)) {
- console.error(JSON.stringify({
- error: 'file_is_generated',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
- hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- matchedQuery = queries[0];
- }
-
- const content = fs.readFileSync(targetFile, 'utf-8');
- const lines = content.split('\n');
-
- // Find the element, trying each query in priority order. When `--text` is
- // supplied, collect every candidate the queries surface and disambiguate
- // by the picked element's textContent. Without `--text`, fall back to the
- // legacy first-match behavior so unmodified callers keep working.
- let match = null;
- if (text) {
- const candidates = [];
- for (const q of queries) {
- const all = findAllElements(lines, q, tag);
- for (const c of all) {
- if (!candidates.some((x) => x.startLine === c.startLine)) {
- candidates.push(c);
- }
- }
- // Once a more-specific query (ID, full className combo) yielded a unique
- // result, stop — falling through to the loose tag+single-class query
- // would readmit the siblings we just disambiguated past.
- if (candidates.length === 1) break;
- }
- if (candidates.length === 0) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- if (candidates.length === 1) {
- match = candidates[0];
- } else {
- const filtered = filterByText(candidates, lines, text);
- if (filtered.length === 1) {
- match = filtered[0];
- } else if (filtered.length === 0) {
- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the
- // browser-side textContent doesn't appear literally in source. Fall
- // back to first-match rather than refusing — this is the same
- // behavior unmodified callers see, just preserved.
- match = candidates[0];
- } else {
- // Multiple candidates ALSO match the text. Truly ambiguous — refuse
- // rather than pick wrong, and hand the agent the candidate locations
- // so it can disambiguate by reading the file.
- console.error(JSON.stringify({
- error: 'element_ambiguous',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), targetFile),
- candidates: filtered.map((c) => ({
- startLine: c.startLine + 1,
- endLine: c.endLine + 1,
- })),
- hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- }
- } else {
- for (const q of queries) {
- match = findElement(lines, q, tag);
- if (match) break;
- }
- if (!match) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- }
-
- const { startLine, endLine } = match;
- const commentSyntax = detectCommentSyntax(targetFile);
- const styleMode = detectStyleMode(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- const indent = lines[startLine].match(/^(\s*)/)[1];
-
- // Extract the original element. Reindent under the wrapper while preserving
- // the relative depth between lines — `l.trimStart()` would strip ALL leading
- // whitespace and collapse e.g. `<aside>`/` <h1>`/`</aside>` (6/8/6 spaces)
- // to a single uniform indent, so on accept/discard the round-trip restores
- // the inner element at its parent's depth instead of nested inside it.
- // Strip only the COMMON minimum leading whitespace across the picked lines;
- // `deindentContent` on the accept side already mirrors this convention.
- const originalLines = lines.slice(startLine, endLine + 1);
- const originalBaseIndent = minLeadingSpaces(originalLines);
- const reindentOriginal = (extra) => originalLines
- .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
- .join('\n');
- const originalIndented = reindentOriginal(' ');
-
- // Wrapper attributes differ by syntax. HTML allows plain string attrs;
- // JSX requires object-literal style and parses string attrs as HTML (which
- // either type-errors or renders a literal CSS string).
- const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
-
- // JSX/TSX guard: the picked element occupies a single JSX child slot
- // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
- // any other expression position). Replacing it with `comment + <div> +
- // comment` yields three adjacent siblings — invalid JSX. We can't use a
- // Fragment `<></>` either: parents that clone children (Radix `asChild`,
- // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
- // they try to pass an `id` through.
- //
- // Solution: keep the wrapper `<div>` as the single JSX-slot child and
- // tuck both marker comments INSIDE it. accept/discard then expands its
- // replacement range to include the wrapper's `<div>` open / close lines
- // so the entire scaffold gets removed cleanly.
- const wrapperLines = isJsx ? [
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- reindentOriginal(' '),
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- indent + '</div>',
- ] : [
- indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- originalIndented,
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + '</div>',
- indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- ];
-
- // Replace the original element with the wrapper
- const newLines = [
- ...lines.slice(0, startLine),
- ...wrapperLines,
- ...lines.slice(endLine + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- // Calculate insert line (the "insert below this line" comment).
- // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
- // the insert marker (HTML: start-comment + outer-div + Original-comment +
- // original-div + content + close-original-div; JSX: outer-div +
- // start-comment + Original-comment + original-div + content +
- // close-original-div). Multi-line originals push the marker by their
- // extra line count.
- const insertLine = startLine + 6 + (originalLines.length - 1);
-
- console.log(JSON.stringify({
- file: path.relative(process.cwd(), targetFile),
- startLine: startLine + 1, // 1-indexed for the agent
- // wrapperLines is an array but one element (the original-content slot)
- // is a `\n`-joined multi-line string, so the actual file-row count is
- // wrapperLines.length + (originalLines.length - 1). Without the offset,
- // endLine pointed inside the wrapper for any picked element that
- // spanned more than one source line.
- endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexed
- insertLine: insertLine + 1, // 1-indexed: where variants go
- commentSyntax: commentSyntax,
- styleMode: styleMode.mode,
- styleTag: styleMode.styleTag,
- cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
- cssAuthoring: buildCssAuthoring(styleMode, count),
- originalLineCount: originalLines.length,
- }));
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-/**
- * Build search query strings in priority order (most specific first).
- * ID is most reliable, then specific class combos, then single classes, then raw query.
- */
-function buildSearchQueries(elementId, classes, tag, query) {
- const queries = [];
-
- // 1. ID is the most specific
- if (elementId) {
- queries.push('id="' + elementId + '"');
- }
-
- // 2. Full class attribute match (for elements with distinctive multi-class combos).
- // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
- // convention the file uses will match.
- if (classes) {
- const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
- if (classList.length > 1) {
- const joined = classList.join(' ');
- const sorted = [...classList].sort((a, b) => b.length - a.length);
- queries.push('class="' + joined + '"');
- queries.push('className="' + joined + '"');
- queries.push(sorted[0]); // most distinctive single class, fallback
- } else if (classList.length === 1) {
- queries.push(classList[0]);
- }
- }
-
- // 3. Tag + class combo (e.g., <section class="hero">).
- // Same dual-emit for JSX compatibility.
- if (tag && classes) {
- const firstClass = classes.split(',')[0].trim();
- queries.push('<' + tag + ' class="' + firstClass);
- queries.push('<' + tag + ' className="' + firstClass);
- }
-
- // 4. Raw fallback query
- if (query) {
- queries.push(query);
- }
-
- return queries;
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- // HTML, Vue, Svelte, Astro all use HTML comments
- return { open: '<!--', close: '-->' };
-}
-
-function detectStyleMode(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.astro') {
- return {
- mode: 'astro-global-prefixed',
- styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',
- };
- }
- return {
- mode: 'scoped',
- styleTag: '<style data-impeccable-css="SESSION_ID">',
- };
-}
-
-function buildCssSelectorPrefixExamples(styleMode, count) {
- if (styleMode !== 'astro-global-prefixed') return [];
- return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);
-}
-
-function buildCssAuthoring(styleMode, count) {
- const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
- if (styleMode.mode === 'astro-global-prefixed') {
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'global-prefixed',
- rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',
- selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),
- requirements: [
- 'Use the styleTag exactly; the is:inline attribute is required for this file.',
- 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',
- 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
- ],
- forbidden: [
- 'Do not use @scope for this styleMode.',
- ],
- };
- }
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'scope-rule',
- rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',
- selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),
- requirements: [
- 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',
- 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
- 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
- ],
- forbidden: [
- 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',
- 'Do not add is:inline to the style tag for this styleMode.',
- ],
- };
-}
-
-/**
- * Search project files for the query string (class name, ID, etc.)
- * Returns the first matching file path, or null.
- */
-function findFileWithQuery(query, cwd, genOpts = {}) {
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, query, seen, 0, genOpts);
- if (result) return result;
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth, genOpts) {
- if (depth > 5) return null; // don't go too deep
- const realDir = fs.realpathSync(dir);
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- // Check files first
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name).toLowerCase();
- if (!EXTENSIONS.includes(ext)) continue;
-
- const filePath = path.join(dir, entry.name);
- if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip unreadable files */ }
- }
-
- // Then recurse into directories. Always skip node_modules and .git (never
- // project content). dist/build/out are left to the isGeneratedFile guard so
- // the includeGenerated second-pass can still find the element there and
- // report `generatedMatch`.
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
- if (result) return result;
- }
-
- return null;
-}
-
-/**
- * Regex that matches a tag opener on a line. Allows the tag name to be
- * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
- * openers (e.g. `<section\n className="..."\n>`) are recognised.
- */
-const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
-
-/**
- * Find the element's start and end line in the file.
- *
- * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
- * `id="..."`), or a raw text snippet. Because a query can appear on a
- * continuation line of a multi-line tag (e.g. the `className="..."` row of a
- * `<section\n className="..."\n>` JSX tag), we walk backward from the match
- * line to find the actual tag opener. When `tag` is provided, opener candidates
- * must match that tag name.
- */
-/**
- * Return the smallest leading-whitespace count across a set of lines,
- * ignoring blank lines (whose indent isn't load-bearing). Used to compute
- * the common base indent of a multi-line picked element so reindenting
- * under the wrapper preserves the relative depth between lines.
- */
-function minLeadingSpaces(lines) {
- let min = Infinity;
- for (const l of lines) {
- if (l.trim() === '') continue;
- const m = l.match(/^(\s*)/);
- if (m && m[1].length < min) min = m[1].length;
- }
- return min === Infinity ? 0 : min;
-}
-
-function findElement(lines, query, tag = null) {
- // Iterate all matches — the first substring hit isn't always the right one.
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
-
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- // Skip lines already inside a variant wrapper
- if (lines[i].includes('data-impeccable-variant')) continue;
-
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
-
- const endLine = findClosingLine(lines, openerLine);
- return { startLine: openerLine, endLine };
- }
-
- return null;
-}
-
-/**
- * Like findElement, but returns every match. Used for ambiguity detection
- * when the agent passes --text: when the same className appears on multiple
- * sibling elements (a list of cards, repeated section variants, etc.),
- * first-match silently lands on the wrong branch. Returning all matches lets
- * the caller narrow by textContent or fail with a structured ambiguity error.
- */
-function findAllElements(lines, query, tag = null) {
- const out = [];
- const seen = new Set();
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- if (lines[i].includes('data-impeccable-variant')) continue;
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
- if (seen.has(openerLine)) continue; // multiple matches inside the same element
- seen.add(openerLine);
- const endLine = findClosingLine(lines, openerLine);
- out.push({ startLine: openerLine, endLine });
- }
- return out;
-}
-
-/**
- * Narrow a candidate set to those whose source body matches a meaningful
- * prefix of the picked element's textContent. The compare strips tags and
- * JSX expressions, then checks two whitespace normalizations side-by-side:
- *
- * - single-space ("hero two second card body")
- * - no-whitespace ("herotwosecondcardbody")
- *
- * Both are needed because `el.textContent` concatenates sibling text without
- * inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
- * `"Hero TwoSecond…"`), while the source has whitespace between tags. If
- * EITHER normalization matches, the candidate keeps. A snippet shorter than
- * 8 chars after stripping is too weak to disambiguate — the caller falls
- * back to first-match.
- */
-function filterByText(candidates, lines, text) {
- const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
- // Too short to disambiguate. Return [] so the caller's `filtered.length
- // === 0` branch fires (fall back to first-match) — the previous
- // `candidates.slice()` return forced `filtered.length > 1` and surfaced
- // a spurious `element_ambiguous` error on every short-text picker event
- // with multiple candidates.
- if (trimmed.length < 8) return [];
- const targetSpaced = trimmed;
- const targetCompact = trimmed.replace(/\s+/g, '');
-
- return candidates.filter((c) => {
- const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
- const inner = body
- .replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
- .replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
- .toLowerCase();
- const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
- const sourceCompact = inner.replace(/\s+/g, '');
- return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
- });
-}
-
-/**
- * Resolve a match line to the real tag opener. If the match line itself opens
- * a tag, return it. Otherwise walk up to 10 lines backward looking for the
- * first tag opener. If `tag` is specified, the opener must match that tag
- * name; an opener with a different tag name aborts the backward walk for this
- * match (we don't jump across element boundaries).
- *
- * Returns the line index of the opener, or -1 if none can be resolved.
- */
-function findOpenerLine(lines, matchLine, tag) {
- const self = lines[matchLine].match(OPENER_RE);
- if (self) {
- if (!tag || self[1] === tag) return matchLine;
- return -1;
- }
- const MAX_BACKWALK = 10;
- for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
- const opener = lines[i].match(OPENER_RE);
- if (!opener) continue;
- if (!tag || opener[1] === tag) return i;
- // Different tag name than requested — abort; we're inside a non-target opener.
- return -1;
- }
- return -1;
-}
-
-/**
- * Starting from a line with an opening tag, find the line with the matching
- * closing tag by counting tag nesting depth.
- */
-function findClosingLine(lines, start) {
- const openMatch = lines[start].match(OPENER_RE);
- if (!openMatch) return start; // caller passed a non-opener; nothing to span
-
- const tagName = openMatch[1];
- let depth = 0;
- const openRe = new RegExp('<' + tagName + '(?=[\\s/>]|$)', 'g');
- const selfCloseRe = new RegExp('<' + tagName + '[^>]*/>', 'g');
- const closeRe = new RegExp('</' + tagName + '\\s*>', 'g');
-
- for (let i = start; i < lines.length; i++) {
- const line = lines[i];
- const opens = (line.match(openRe) || []).length;
- const selfCloses = (line.match(selfCloseRe) || []).length;
- const closes = (line.match(closeRe) || []).length;
-
- depth += opens - selfCloses - closes;
-
- if (depth <= 0) return i;
- }
-
- // If we can't find the close, return a reasonable guess
- return Math.min(start + 50, lines.length - 1);
-}
-
-// Auto-execute when run directly (node live-wrap.mjs ...)
-const _running = process.argv[1];
-if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {
- wrapCli();
-}
-
-// Test exports (used by tests/live-wrap.test.mjs)
-export { buildSearchQueries, findElement, findClosingLine, detectCommentSyntax };
@@ -1,247 +0,0 @@
-/**
- * CLI entry point: prepare everything needed to enter the live variant poll loop.
- *
- * Does (all in one command):
- * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)
- * 2. Start the live server in the background (or reuse a running one)
- * 3. Inject the browser script tag into the project's entry file
- * 4. Read PRODUCT.md / DESIGN.md for project context
- * 5. Print a single JSON blob with everything the agent needs
- *
- * After this, the agent's only remaining steps are:
- * - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll
- * - Enter the poll loop: `node live-poll.mjs`
- *
- * Usage:
- * node live.mjs # Prepare everything, print JSON, exit
- * node live.mjs --help
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { loadContext } from './load-context.mjs';
-import { resolveFiles } from './live-inject.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-async function liveCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live.mjs
-
-Prepare everything for live variant mode in a single command:
- - Checks .impeccable/live/config.json (required, created once per project)
- - Starts (or reuses) the live server in the background
- - Injects the browser script tag
- - Reads PRODUCT.md / DESIGN.md for project context
-
-On success, prints a JSON blob with:
- { ok, serverPort, serverToken, pageFile, hasContext, context }
-
-On config_missing, prints:
- { ok: false, error: "config_missing", configPath, hint }
-
-The agent should then:
- 1. If config_missing, create the config and re-run this script
- 2. Optionally open the project's dev/preview URL in the browser (see reference/live.md—not serverPort)
- 3. Enter the poll loop: node live-poll.mjs`);
- process.exit(0);
- }
-
- // 1. Check config (fail fast if missing — no point starting anything else)
- const checkOut = runScript('live-inject.mjs', ['--check']);
- const checkResult = safeParse(checkOut);
- if (!checkResult || !checkResult.ok) {
- console.log(JSON.stringify(checkResult || { ok: false, error: 'check_failed', raw: checkOut }));
- process.exit(0);
- }
-
- // 2. Start server (or reuse existing)
- const serverInfo = ensureServerRunning();
- if (!serverInfo) {
- console.log(JSON.stringify({ ok: false, error: 'server_start_failed' }));
- process.exit(1);
- }
-
- // 3. Inject the script tag at the current port
- const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)]);
- const injectResult = safeParse(injectOut);
- if (!injectResult || !injectResult.ok) {
- console.log(JSON.stringify({
- ok: false,
- error: 'inject_failed',
- detail: injectResult || injectOut,
- serverPort: serverInfo.port,
- }));
- process.exit(1);
- }
-
- // 4. Load PRODUCT.md + DESIGN.md context (auto-migrates legacy .impeccable.md)
- const ctx = loadContext(process.cwd());
-
- // 5. Compute drift-heal: compare resolved inject targets against the
- // project's HTML files. Orphans are HTML files not covered by config.
- // Warning only — the agent decides whether to act.
- const resolvedFiles = resolveFiles(process.cwd(), checkResult.config);
- const drift = scanForDrift(process.cwd(), resolvedFiles, checkResult.config);
-
- // 6. Emit everything the agent needs
- console.log(JSON.stringify({
- ok: true,
- serverPort: serverInfo.port,
- serverToken: serverInfo.token,
- pageFiles: resolvedFiles,
- configDrift: drift,
- hasProduct: ctx.hasProduct,
- product: ctx.product,
- productPath: ctx.productPath,
- hasDesign: ctx.hasDesign,
- design: ctx.design,
- designPath: ctx.designPath,
- migrated: ctx.migrated,
- }, null, 2));
-}
-
-/**
- * Drift-heal scan. Walks the project for HTML files under common
- * page-source directories (public/, src/, app/, pages/) and reports any
- * that aren't covered by the resolved inject targets. This is purely
- * advisory — the agent can ignore it, or suggest the user add the
- * orphans to config.files.
- *
- * Skipped if config.files already contains at least one glob pattern
- * covering everything in practice (signaled by the orphan count being 0).
- */
-function scanForDrift(rootDir, resolvedFiles, config) {
- const SCAN_ROOTS = ['public', 'src', 'app', 'pages'];
- const IGNORE_DIRS = new Set([
- 'node_modules', '.git', '.next', '.nuxt', '.svelte-kit', '.astro',
- '.turbo', '.vercel', '.cache', 'coverage', 'dist', 'build',
- ]);
-
- const resolvedSet = new Set(resolvedFiles.map((f) => f.split(path.sep).join('/')));
-
- // Files matching the user's `exclude` globs are intentional omissions,
- // not drift. Compile them to regexes so the orphan list stays signal.
- const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
- .map((p) => globToRegex(p));
- const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
-
- const orphans = [];
-
- const walk = (dir, relBase) => {
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
- for (const e of entries) {
- const rel = relBase ? `${relBase}/${e.name}` : e.name;
- if (e.isDirectory()) {
- if (IGNORE_DIRS.has(e.name) || e.name.startsWith('.')) continue;
- walk(path.join(dir, e.name), rel);
- } else if (e.isFile() && e.name.endsWith('.html')) {
- if (resolvedSet.has(rel)) continue;
- if (isUserExcluded(rel)) continue;
- orphans.push(rel);
- }
- }
- };
-
- for (const root of SCAN_ROOTS) {
- const abs = path.join(rootDir, root);
- if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
- walk(abs, root);
- }
- }
-
- if (orphans.length === 0) return null;
- const capped = orphans.slice(0, 20);
- return {
- orphans: capped,
- orphanCount: orphans.length,
- hint: `${orphans.length} HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like "public/**/*.html".`,
- };
-}
-
-/**
- * Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
- * to avoid a circular import (live-inject.mjs already imports nothing
- * from live.mjs). The two must stay in sync.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
- else { re += '.*'; i += 2; }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function runScript(name, args) {
- const scriptPath = path.join(__dirname, name);
- const cmd = `node "${scriptPath}" ${args.map(a => `"${a}"`).join(' ')}`;
- try {
- return execSync(cmd, { encoding: 'utf-8', cwd: process.cwd(), timeout: 15_000 });
- } catch (err) {
- // execSync throws on non-zero exit; return stdout if any
- return err.stdout || err.message || '';
- }
-}
-
-function safeParse(out) {
- try { return JSON.parse(String(out).trim()); } catch { return null; }
-}
-
-/**
- * Return { pid, port, token } for the running live server, starting one if needed.
- */
-function ensureServerRunning() {
- // Try to reuse an existing server
- try {
- const existing = readLiveServerInfo(process.cwd())?.info;
- if (existing && existing.pid) {
- try {
- process.kill(existing.pid, 0); // throws if dead
- return existing;
- } catch { /* stale PID file — the server script will clean it up */ }
- }
- } catch { /* no PID file */ }
-
- // Start a new server
- const out = runScript('live-server.mjs', ['--background']);
- return safeParse(out);
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live.mjs') || _running?.endsWith('live.mjs/')) {
- liveCli();
-}
@@ -1,141 +0,0 @@
-/**
- * Shared context loader for every impeccable command that needs to know
- * "who is this for" and "what does this look like".
- *
- * Input: project root (process.cwd()).
- *
- * Output (JSON to stdout):
- * {
- * hasProduct: boolean, // PRODUCT.md found (or auto-migrated)
- * product: string | null, // PRODUCT.md contents
- * productPath: string | null, // relative path
- * hasDesign: boolean, // DESIGN.md found
- * design: string | null, // DESIGN.md contents
- * designPath: string | null,
- * migrated: boolean, // true if we auto-renamed .impeccable.md -> PRODUCT.md
- * contextDir: string, // absolute path of the directory the files were found in
- * }
- *
- * Filename matching is case-insensitive for PRODUCT.md and DESIGN.md. The
- * Google DESIGN.md convention is uppercase at repo root; Kiro-style and
- * lowercase variants are also matched so users don't get punished for case.
- *
- * Lookup directory resolution (first match wins):
- * 1. process.env.IMPECCABLE_CONTEXT_DIR (absolute or relative to cwd)
- * 2. cwd, if PRODUCT.md / DESIGN.md / .impeccable.md is there (back-compat)
- * 3. Auto-fallback subdirectories of cwd: .agents/context/, then docs/
- * 4. cwd as a default "no context found" location
- *
- * Legacy `.impeccable.md` -> PRODUCT.md migration only fires at cwd root;
- * fallback directories are read-only as far as auto-rename is concerned.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
-const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
-const LEGACY_NAMES = ['.impeccable.md'];
-const FALLBACK_DIRS = ['.agents/context', 'docs'];
-
-/**
- * Resolve the directory that holds PRODUCT.md / DESIGN.md for
- * this project. Exported so other scripts (e.g. live-server.mjs) can read the
- * design files from the same location the loader uses.
- */
-export function resolveContextDir(cwd = process.cwd()) {
- // 1. Explicit override
- const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
- if (envDir && envDir.trim()) {
- const trimmed = envDir.trim();
- return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- }
-
- // 2. cwd wins if any canonical or legacy file is there. We check legacy too
- // so the auto-migration path in loadContext stays predictable.
- if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES, ...LEGACY_NAMES])) {
- return cwd;
- }
-
- // 3. Auto-fallback subdirs. Match if PRODUCT.md or DESIGN.md is present;
- // legacy `.impeccable.md` does not pull the lookup into a fallback dir.
- for (const rel of FALLBACK_DIRS) {
- const candidate = path.resolve(cwd, rel);
- if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
- return candidate;
- }
- }
-
- // 4. Nothing found — keep the historical "default to cwd" behaviour so the
- // caller's `hasProduct === false` branch still fires the same way.
- return cwd;
-}
-
-export function loadContext(cwd = process.cwd()) {
- let migrated = false;
- const contextDir = resolveContextDir(cwd);
-
- // 1. Look for PRODUCT.md (case-insensitive) in the resolved dir
- let productPath = firstExisting(contextDir, PRODUCT_NAMES);
-
- // 2. Legacy: if no PRODUCT.md but .impeccable.md exists at cwd root, rename
- // it in place. We only migrate at the root — fallback dirs are read-only
- // so we don't surprise users by mutating files under docs/ or .agents/.
- if (!productPath && contextDir === cwd) {
- const legacyPath = firstExisting(cwd, LEGACY_NAMES);
- if (legacyPath) {
- const newPath = path.join(cwd, 'PRODUCT.md');
- try {
- fs.renameSync(legacyPath, newPath);
- productPath = newPath;
- migrated = true;
- } catch {
- // Rename failed (permissions, etc.) — fall back to reading legacy in place
- productPath = legacyPath;
- }
- }
- }
-
- // 3. DESIGN.md (case-insensitive)
- const designPath = firstExisting(contextDir, DESIGN_NAMES);
-
- const product = productPath ? safeRead(productPath) : null;
- const design = designPath ? safeRead(designPath) : null;
-
- return {
- hasProduct: !!product,
- product,
- productPath: productPath ? path.relative(cwd, productPath) : null,
- hasDesign: !!design,
- design,
- designPath: designPath ? path.relative(cwd, designPath) : null,
- migrated,
- contextDir,
- };
-}
-
-function firstExisting(dir, names) {
- for (const name of names) {
- const abs = path.join(dir, name);
- if (fs.existsSync(abs)) return abs;
- }
- return null;
-}
-
-function safeRead(p) {
- try { return fs.readFileSync(p, 'utf-8'); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// CLI mode — print the context as JSON
-// ---------------------------------------------------------------------------
-
-function cli() {
- const result = loadContext(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('load-context.mjs') || _running?.endsWith('load-context.mjs/')) {
- cli();
-}
@@ -1,14 +0,0 @@
@@ -1,214 +0,0 @@
-#!/usr/bin/env node
-/**
- * Pin/unpin sub-commands as standalone skill shortcuts.
- *
- * Usage:
- * node <scripts_path>/pin.mjs pin <command>
- * node <scripts_path>/pin.mjs unpin <command>
- *
- * `pin audit` creates a lightweight /audit skill that redirects to /impeccable audit.
- * `unpin audit` removes that shortcut.
- *
- * The script discovers harness directories (.claude/skills, .cursor/skills, etc.)
- * in the project root and creates/removes the pin in all of them.
- */
-
-import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
-import { join, resolve, dirname } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-// All known harness directories
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Valid sub-command names
-const VALID_COMMANDS = [
- 'craft', 'teach', 'extract', 'document', 'shape',
- 'critique', 'audit',
- 'polish', 'bolder', 'quieter', 'distill', 'harden', 'onboard', 'live',
- 'animate', 'colorize', 'typeset', 'layout', 'delight', 'overdrive',
- 'clarify', 'adapt', 'optimize',
-];
-
-// Marker to identify pinned skills (so unpin doesn't delete user skills)
-const PIN_MARKER = '<!-- impeccable-pinned-skill -->';
-
-/**
- * Walk up from startDir to find a project root.
- */
-function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- while (dir !== '/') {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Find harness skill directories that have an impeccable skill installed.
- */
-function findHarnessDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const skillsDir = join(projectRoot, harness, 'skills');
- // Only pin in harness dirs that already have impeccable installed
- const impeccableDir = join(skillsDir, 'impeccable');
- if (existsSync(impeccableDir) || existsSync(join(skillsDir, 'i-impeccable'))) {
- dirs.push(skillsDir);
- }
- }
- return dirs;
-}
-
-/**
- * Load command metadata (descriptions for pinned skills).
- */
-function loadCommandMetadata() {
- const metadataPath = join(__dirname, 'command-metadata.json');
- if (existsSync(metadataPath)) {
- return JSON.parse(readFileSync(metadataPath, 'utf-8'));
- }
- return {};
-}
-
-/**
- * Generate a pinned skill's SKILL.md content.
- */
-function generatePinnedSkill(command, metadata) {
- const desc = metadata[command]?.description || `Shortcut for /impeccable ${command}.`;
- const hint = metadata[command]?.argumentHint || '[target]';
-
- return `---
-name: ${command}
-description: "${desc}"
-argument-hint: "${hint}"
-user-invocable: true
----
-
-${PIN_MARKER}
-
-This is a pinned shortcut for \`{{command_prefix}}impeccable ${command}\`.
-
-Invoke {{command_prefix}}impeccable ${command}, passing along any arguments provided here, and follow its instructions.
-`;
-}
-
-/**
- * Pin a command: create shortcut skill in all harness dirs.
- */
-function pin(command, projectRoot) {
- const metadata = loadCommandMetadata();
- const harnessDirs = findHarnessDirs(projectRoot);
-
- if (harnessDirs.length === 0) {
- console.log('No harness directories with impeccable installed found.');
- return false;
- }
-
- const content = generatePinnedSkill(command, metadata);
- let created = 0;
-
- for (const skillsDir of harnessDirs) {
- // Check if skill already exists (and isn't a pin)
- const skillDir = join(skillsDir, command);
- if (existsSync(skillDir)) {
- const existingMd = join(skillDir, 'SKILL.md');
- if (existsSync(existingMd)) {
- const existing = readFileSync(existingMd, 'utf-8');
- if (!existing.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (non-pinned skill already exists)`);
- continue;
- }
- }
- }
-
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(join(skillDir, 'SKILL.md'), content, 'utf-8');
- console.log(` + ${skillDir}`);
- created++;
- }
-
- if (created > 0) {
- console.log(`\nPinned '${command}' as a standalone shortcut in ${created} location(s).`);
- console.log(`You can now use /${command} directly.`);
- }
-
- return created > 0;
-}
-
-/**
- * Unpin a command: remove shortcut skill from all harness dirs.
- */
-function unpin(command, projectRoot) {
- const harnessDirs = findHarnessDirs(projectRoot);
- let removed = 0;
-
- for (const skillsDir of harnessDirs) {
- const skillDir = join(skillsDir, command);
- if (!existsSync(skillDir)) continue;
-
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) continue;
-
- // Safety: only remove if it's a pinned skill
- const content = readFileSync(skillMd, 'utf-8');
- if (!content.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (not a pinned skill)`);
- continue;
- }
-
- rmSync(skillDir, { recursive: true, force: true });
- console.log(` - ${skillDir}`);
- removed++;
- }
-
- if (removed > 0) {
- console.log(`\nUnpinned '${command}' from ${removed} location(s).`);
- console.log(`Use /impeccable ${command} to access it.`);
- } else {
- console.log(`No pinned '${command}' shortcut found.`);
- }
-
- return removed > 0;
-}
-
-// --- CLI ---
-const [,, action, command] = process.argv;
-
-if (!action || !command) {
- console.log('Usage: node pin.mjs <pin|unpin> <command>');
- console.log(`\nAvailable commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-if (action !== 'pin' && action !== 'unpin') {
- console.error(`Unknown action: ${action}. Use 'pin' or 'unpin'.`);
- process.exit(1);
-}
-
-if (!VALID_COMMANDS.includes(command)) {
- console.error(`Unknown command: ${command}`);
- console.error(`Available commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-const root = findProjectRoot();
-
-if (action === 'pin') {
- pin(command, root);
-} else {
- unpin(command, root);
-}
@@ -1,169 +0,0 @@
----
-name: impeccable
-description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
-version: 3.1.1
-user-invocable: true
-argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · teach|document|extract|live] [target]"
-license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
-allowed-tools:
- - Bash(npx impeccable *)
----
-
-Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
-
-## Setup
-
-Before any design work or file edits:
-
-1. Load context (PRODUCT.md / DESIGN.md) via the loader script.
-2. Identify the register and load the matching register reference (brand.md or product.md).
-3. **If the user invoked a sub-command (e.g. `craft`, `shape`, `audit`), load its reference file too.** This is non-negotiable: `craft` without `craft.md` loaded means you'll skip the shape-and-confirm step the user expects.
-
-Skipping these produces generic output that ignores the project.
-
-### 1. Context gathering
-
-Two files, case-insensitive. The loader looks at the project root by default and falls back to `.agents/context/` and `docs/` if the root is clean. Override with `IMPECCABLE_CONTEXT_DIR=path/to/dir` (absolute or relative to cwd).
-
-- **PRODUCT.md**: required. Users, brand, tone, anti-references, strategic principles.
-- **DESIGN.md**: optional, strongly recommended. Colors, typography, elevation, components.
-
-Load both in one call:
-
-```bash
-node .qoder/skills/impeccable/scripts/load-context.mjs
-```
-
-Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`. The output's `contextDir` field tells you where the files were resolved from.
-
-If the output is already in this session's conversation history, don't re-run. Exceptions requiring a fresh load: you just ran `/impeccable teach` or `/impeccable document` (they rewrite the files), or the user manually edited one.
-
-`/impeccable live` already warms context via `live.mjs`. If you've run `live.mjs`, don't also run `load-context.mjs` this session.
-
-If PRODUCT.md is missing, empty, or placeholder (`[TODO]` markers, <200 chars): run `/impeccable teach`, then resume the user's original task with the fresh context. If the original task was `/impeccable craft`, resume into `/impeccable shape` before any implementation work.
-
-If DESIGN.md is missing: nudge once per session (*"Run `/impeccable document` for more on-brand output"*), then proceed.
-
-### 2. Register
-
-Every design task is **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboard, tool: design SERVES the product).
-
-Identify before designing. Priority: (1) cue in the task itself ("landing page" vs "dashboard"); (2) the surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. First match wins.
-
-If PRODUCT.md lacks the `register` field (legacy), infer it once from its "Users" and "Product Purpose" sections, then cache the inferred value for the session. Suggest the user run `/impeccable teach` to add the field explicitly.
-
-Load the matching reference: [reference/brand.md](reference/brand.md) or [reference/product.md](reference/product.md). The shared design laws below apply to both.
-
-## Shared design laws
-
-Apply to every design, both registers. Match implementation complexity to the aesthetic vision: maximalism needs elaborate code, minimalism needs precision. Interpret creatively. Vary across projects; never converge on the same choices. the model is capable of extraordinary work. Don't hold back.
-
-### Color
-
-- Use OKLCH. Reduce chroma as lightness approaches 0 or 100; high chroma at extremes looks garish.
-- Never use `#000` or `#fff`. Tint every neutral toward the brand hue (chroma 0.005–0.01 is enough).
-- Pick a **color strategy** before picking colors. Four steps on the commitment axis:
- - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism.
- - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages.
- - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz.
- - **Drenched**: the surface IS the color. Brand heroes, campaign pages.
-- The "one accent ≤10%" rule is Restrained only. Committed / Full palette / Drenched exceed it on purpose. Don't collapse every design to Restrained by reflex.
-
-### Theme
-
-Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe."
-
-Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does.
-
-"Observability dashboard" does not force an answer. "SRE glancing at incident severity on a 27-inch monitor at 2am in a dim room" does. Run the sentence, not the category.
-
-### Typography
-
-- Cap body line length at 65–75ch.
-- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales.
-
-### Layout
-
-- Vary spacing for rhythm. Same padding everywhere is monotony.
-- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
-- Don't wrap everything in a container. Most things don't need one.
-
-### Motion
-
-- Don't animate CSS layout properties.
-- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
-
-### Absolute bans
-
-Match-and-refuse. If you're about to write any of these, rewrite the element with different structure.
-
-- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing.
-- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size.
-- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing.
-- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché.
-- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly.
-- **Modal as first thought.** Modals are usually laziness. Exhaust inline / progressive alternatives first.
-
-### Copy
-
-- Every word earns its place. No restated headings, no intros that repeat the title.
-- **No em dashes.** Use commas, colons, semicolons, periods, or parentheses. Also not `--`.
-
-### The AI slop test
-
-If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference.
-
-**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses.
-
-- **First-order:** if someone could guess the theme + palette from the category alone ("observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black"), it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
-- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families.
-
-## Commands
-
-| Command | Category | Description | Reference |
-|---|---|---|---|
-| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) |
-| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) |
-| `teach` | Build | Set up PRODUCT.md and DESIGN.md context | [reference/teach.md](reference/teach.md) |
-| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) |
-| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) |
-| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) |
-| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) |
-| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) |
-| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) |
-| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) |
-| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) |
-| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) |
-| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) |
-| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) |
-| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) |
-| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) |
-| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) |
-| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) |
-| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) |
-| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) |
-| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) |
-| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
-| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
-
-### Routing rules
-
-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
-3. **First word doesn't match**: general design invocation. Apply the setup steps, shared design laws, and the loaded register reference, using the full argument as context.
-
-Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `/impeccable`.
-
-If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `teach` as a blocker, finish teach, refresh context, then resume the original command and target.
-
-## Pin / Unpin
-
-**Pin** creates a standalone shortcut so `/<command>` invokes `/impeccable <command>` directly. **Unpin** removes it. The script writes to every harness directory present in the project.
-
-```bash
-node .qoder/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
-```
-
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
@@ -1,190 +0,0 @@
-> **Additional context needed**: target platforms/devices and usage contexts.
-
-Adapt an existing design to a different context: another screen size, device, platform, or use case. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context.
-
-
----
-
-## Assess Adaptation Challenge
-
-Understand what needs adaptation and why:
-
-1. **Identify the source context**:
- - What was it designed for originally? (Desktop web? Mobile app?)
- - What assumptions were made? (Large screen? Mouse input? Fast connection?)
- - What works well in current context?
-
-2. **Understand target context**:
- - **Device**: Mobile, tablet, desktop, TV, watch, print?
- - **Input method**: Touch, mouse, keyboard, voice, gamepad?
- - **Screen constraints**: Size, resolution, orientation?
- - **Connection**: Fast wifi, slow 3G, offline?
- - **Usage context**: On-the-go vs desk, quick glance vs focused reading?
- - **User expectations**: What do users expect on this platform?
-
-3. **Identify adaptation challenges**:
- - What won't fit? (Content, navigation, features)
- - What won't work? (Hover states on touch, tiny touch targets)
- - What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop)
-
-**CRITICAL**: Adaptation is rethinking the experience for the new context, not scaling pixels.
-
-## Plan Adaptation Strategy
-
-Create context-appropriate strategy:
-
-### Mobile Adaptation (Desktop → Mobile)
-
-**Layout Strategy**:
-- Single column instead of multi-column
-- Vertical stacking instead of side-by-side
-- Full-width components instead of fixed widths
-- Bottom navigation instead of top/side navigation
-
-**Interaction Strategy**:
-- Touch targets 44x44px minimum (not hover-dependent)
-- Swipe gestures where appropriate (lists, carousels)
-- Bottom sheets instead of dropdowns
-- Thumbs-first design (controls within thumb reach)
-- Larger tap areas with more spacing
-
-**Content Strategy**:
-- Progressive disclosure (don't show everything at once)
-- Prioritize primary content (secondary content in tabs/accordions)
-- Shorter text (more concise)
-- Larger text (16px minimum)
-
-**Navigation Strategy**:
-- Hamburger menu or bottom navigation
-- Reduce navigation complexity
-- Sticky headers for context
-- Back button in navigation flow
-
-### Tablet Adaptation (Hybrid Approach)
-
-**Layout Strategy**:
-- Two-column layouts (not single or three-column)
-- Side panels for secondary content
-- Master-detail views (list + detail)
-- Adaptive based on orientation (portrait vs landscape)
-
-**Interaction Strategy**:
-- Support both touch and pointer
-- Touch targets 44x44px but allow denser layouts than phone
-- Side navigation drawers
-- Multi-column forms where appropriate
-
-### Desktop Adaptation (Mobile → Desktop)
-
-**Layout Strategy**:
-- Multi-column layouts (use horizontal space)
-- Side navigation always visible
-- Multiple information panels simultaneously
-- Fixed widths with max-width constraints (don't stretch to 4K)
-
-**Interaction Strategy**:
-- Hover states for additional information
-- Keyboard shortcuts
-- Right-click context menus
-- Drag and drop where helpful
-- Multi-select with Shift/Cmd
-
-**Content Strategy**:
-- Show more information upfront (less progressive disclosure)
-- Data tables with many columns
-- Richer visualizations
-- More detailed descriptions
-
-### Print Adaptation (Screen → Print)
-
-**Layout Strategy**:
-- Page breaks at logical points
-- Remove navigation, footer, interactive elements
-- Black and white (or limited color)
-- Proper margins for binding
-
-**Content Strategy**:
-- Expand shortened content (show full URLs, hidden sections)
-- Add page numbers, headers, footers
-- Include metadata (print date, page title)
-- Convert charts to print-friendly versions
-
-### Email Adaptation (Web → Email)
-
-**Layout Strategy**:
-- Narrow width (600px max)
-- Single column only
-- Inline CSS (no external stylesheets)
-- Table-based layouts (for email client compatibility)
-
-**Interaction Strategy**:
-- Large, obvious CTAs (buttons not text links)
-- No hover states (not reliable)
-- Deep links to web app for complex interactions
-
-## Implement Adaptations
-
-Apply changes systematically:
-
-### Responsive Breakpoints
-
-Choose appropriate breakpoints:
-- Mobile: 320px-767px
-- Tablet: 768px-1023px
-- Desktop: 1024px+
-- Or content-driven breakpoints (where design breaks)
-
-### Layout Adaptation Techniques
-
-- **CSS Grid/Flexbox**: Reflow layouts automatically
-- **Container Queries**: Adapt based on container, not viewport
-- **`clamp()`**: Fluid sizing between min and max
-- **Media queries**: Different styles for different contexts
-- **Display properties**: Show/hide elements per context
-
-### Touch Adaptation
-
-- Increase touch target sizes (44x44px minimum)
-- Add more spacing between interactive elements
-- Remove hover-dependent interactions
-- Add touch feedback (ripples, highlights)
-- Consider thumb zones (easier to reach bottom than top)
-
-### Content Adaptation
-
-- Use `display: none` sparingly (still downloads)
-- Progressive enhancement (core content first, enhancements on larger screens)
-- Lazy loading for off-screen content
-- Responsive images (`srcset`, `picture` element)
-
-### Navigation Adaptation
-
-- Transform complex nav to hamburger/drawer on mobile
-- Bottom nav bar for mobile apps
-- Persistent side navigation on desktop
-- Breadcrumbs on smaller screens for context
-
-**IMPORTANT**: Test on real devices. Device emulation in DevTools is helpful but not perfect.
-
-**NEVER**:
-- Hide core functionality on mobile (if it matters, make it work)
-- Assume desktop = powerful device (consider accessibility, older machines)
-- Use different information architecture across contexts (confusing)
-- Break user expectations for platform (mobile users expect mobile patterns)
-- Forget landscape orientation on mobile/tablet
-- Use generic breakpoints blindly (use content-driven breakpoints)
-- Ignore touch on desktop (many desktop devices have touch)
-
-## Verify Adaptations
-
-Test thoroughly across contexts:
-
-- **Real devices**: Test on actual phones, tablets, desktops
-- **Different orientations**: Portrait and landscape
-- **Different browsers**: Safari, Chrome, Firefox, Edge
-- **Different OS**: iOS, Android, Windows, macOS
-- **Different input methods**: Touch, mouse, keyboard
-- **Edge cases**: Very small screens (320px), very large screens (4K)
-- **Slow connections**: Test on throttled network
-
-When the adaptation feels native to each context, hand off to `/impeccable polish` for the final pass.
@@ -1,175 +0,0 @@
-> **Additional context needed**: performance constraints.
-
-Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it.
-
----
-
-## Register
-
-Brand: orchestrated page-load sequences, staggered reveals, scroll-driven animation. Motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions.
-
-Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it.
-
----
-
-## Assess Animation Opportunities
-
-Analyze where motion would improve the experience:
-
-1. **Identify static areas**:
- - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.)
- - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes)
- - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious
- - **Lack of delight**: Functional but joyless interactions
- - **Missed guidance**: Opportunities to direct attention or explain behavior
-
-2. **Understand the context**:
- - What's the personality? (Playful vs serious, energetic vs calm)
- - What's the performance budget? (Mobile-first? Complex page?)
- - Who's the audience? (Motion-sensitive users? Power users who want speed?)
- - What matters most? (One hero animation vs many micro-interactions?)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them.
-
-## Plan Animation Strategy
-
-Create a purposeful animation plan:
-
-- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?)
-- **Feedback layer**: Which interactions need acknowledgment?
-- **Transition layer**: Which state changes need smoothing?
-- **Delight layer**: Where can we surprise and delight?
-
-**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments.
-
-## Implement Animations
-
-Add motion systematically across these categories:
-
-### Entrance Animations
-- **Page load choreography**: Stagger element reveals (100-150ms delays), fade + slide combinations
-- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects)
-- **Content reveals**: Scroll-triggered animations using intersection observer
-- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management
-
-### Micro-interactions
-- **Button feedback**:
- - Hover: Subtle scale (1.02-1.05), color shift, shadow increase
- - Click: Quick scale down then up (0.95 → 1), ripple effect
- - Loading: Spinner or pulse state
-- **Form interactions**:
- - Input focus: Border color transition, slight scale or glow
- - Validation: Shake on error, check mark on success, smooth color transitions
-- **Toggle switches**: Smooth slide + color transition (200-300ms)
-- **Checkboxes/radio**: Check mark animation, ripple effect
-- **Like/favorite**: Scale + rotation, particle effects, color transition
-
-### State Transitions
-- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms)
-- **Expand/collapse**: Height transition with overflow handling, icon rotation
-- **Loading states**: Skeleton screen fades, spinner animations, progress bars
-- **Success/error**: Color transitions, icon animations, gentle scale pulse
-- **Enable/disable**: Opacity transitions, cursor changes
-
-### Navigation & Flow
-- **Page transitions**: Crossfade between routes, shared element transitions
-- **Tab switching**: Slide indicator, content fade/slide
-- **Carousel/slider**: Smooth transforms, snap points, momentum
-- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators
-
-### Feedback & Guidance
-- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights
-- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning
-- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation
-- **Focus flow**: Highlight path through form or workflow
-
-### Delight Moments
-- **Empty states**: Subtle floating animations on illustrations
-- **Completed actions**: Confetti, check mark flourish, success celebrations
-- **Easter eggs**: Hidden interactions for discovery
-- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches
-
-## Technical Implementation
-
-Use appropriate techniques for each animation:
-
-### Timing & Easing
-
-**Durations by purpose:**
-- **100-150ms**: Instant feedback (button press, toggle)
-- **200-300ms**: State changes (hover, menu open)
-- **300-500ms**: Layout changes (accordion, modal)
-- **500-800ms**: Entrance animations (page load)
-
-**Easing curves (use these, not CSS defaults):**
-```css
-/* Recommended: natural deceleration */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */
-
-/* AVOID: feel dated and tacky */
-/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */
-/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */
-```
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-### CSS Animations
-```css
-/* Prefer for simple, declarative animations */
-- transitions for state changes
-- @keyframes for complex sequences
-- transform and opacity for reliable movement
-- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth
-```
-
-### JavaScript Animation
-```javascript
-/* Use for complex, interactive animations */
-- Web Animations API for programmatic control
-- Framer Motion for React
-- GSAP for complex sequences
-```
-
-### Performance
-- **Motion materials**: Use transform/opacity for reliable movement, but use blur, filters, masks, shadows, and color shifts when they materially improve the effect
-- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- **will-change**: Add sparingly for known expensive animations
-- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate
-- **Monitor FPS**: Ensure 60fps on target devices
-
-### Accessibility
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**NEVER**:
-- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself
-- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work
-- Use durations over 500ms for feedback (it feels laggy)
-- Animate without purpose (every animation needs a reason)
-- Ignore `prefers-reduced-motion` (this is an accessibility violation)
-- Animate everything (animation fatigue makes interfaces feel exhausting)
-- Block interaction during animations unless intentional
-
-## Verify Quality
-
-Test animations thoroughly:
-
-- **Smooth at 60fps**: No jank on target devices
-- **Feels natural**: Easing curves feel organic, not robotic
-- **Appropriate timing**: Not too fast (jarring) or too slow (laggy)
-- **Reduced motion works**: Animations disabled or simplified appropriately
-- **Doesn't block**: Users can interact during/after animations
-- **Adds value**: Makes interface clearer or more delightful
-
-When the motion clarifies state instead of decorating it, hand off to `/impeccable polish` for the final pass.
@@ -1,133 +0,0 @@
-Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues; document them for other commands to address.
-
-This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation.
-
-## Diagnostic Scan
-
-Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below.
-
-### 1. Accessibility (A11y)
-
-**Check for**:
-- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA)
-- **Missing ARIA**: Interactive elements without proper roles, labels, or states
-- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps
-- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons
-- **Alt text**: Missing or poor image descriptions
-- **Form issues**: Inputs without labels, poor error messaging, missing required indicators
-
-**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA)
-
-### 2. Performance
-
-**Check for**:
-- **Layout thrashing**: Reading/writing layout properties in loops
-- **Expensive animations**: Casual layout-property animation, unbounded blur/filter/shadow effects, or effects that visibly drop frames
-- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change
-- **Bundle size**: Unnecessary imports, unused dependencies
-- **Render performance**: Unnecessary re-renders, missing memoization
-
-**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized)
-
-### 3. Theming
-
-**Check for**:
-- **Hard-coded colors**: Colors not using design tokens
-- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme
-- **Inconsistent tokens**: Using wrong tokens, mixing token types
-- **Theme switching issues**: Values that don't update on theme change
-
-**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly)
-
-### 4. Responsive Design
-
-**Check for**:
-- **Fixed widths**: Hard-coded widths that break on mobile
-- **Touch targets**: Interactive elements < 44x44px
-- **Horizontal scroll**: Content overflow on narrow viewports
-- **Text scaling**: Layouts that break when text size increases
-- **Missing breakpoints**: No mobile/tablet variants
-
-**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets)
-
-### 5. Anti-Patterns (CRITICAL)
-
-Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy).
-
-**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design)
-
-## Generate Report
-
-### Audit Health Score
-
-| # | Dimension | Score | Key Finding |
-|---|-----------|-------|-------------|
-| 1 | Accessibility | ? | [most critical a11y issue or "--"] |
-| 2 | Performance | ? | |
-| 3 | Responsive Design | ? | |
-| 4 | Theming | ? | |
-| 5 | Anti-Patterns | ? | |
-| **Total** | | **??/20** | **[Rating band]** |
-
-**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues)
-
-### Anti-Patterns Verdict
-**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest.
-
-### Executive Summary
-- Audit Health Score: **??/20** ([rating band])
-- Total issues found (count by severity: P0/P1/P2/P3)
-- Top 3-5 critical issues
-- Recommended next steps
-
-### Detailed Findings by Severity
-
-Tag every issue with **P0-P3 severity**:
-- **P0 Blocking**: Prevents task completion. Fix immediately
-- **P1 Major**: Significant difficulty or WCAG AA violation. Fix before release
-- **P2 Minor**: Annoyance, workaround exists. Fix in next pass
-- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits
-
-For each issue, document:
-- **[P?] Issue name**
-- **Location**: Component, file, line
-- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern
-- **Impact**: How it affects users
-- **WCAG/Standard**: Which standard it violates (if applicable)
-- **Recommendation**: How to fix it
-- **Suggested command**: Which command to use (prefer: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-### Patterns & Systemic Issues
-
-Identify recurring problems that indicate systemic gaps rather than one-off mistakes:
-- "Hard-coded colors appear in 15+ components, should use design tokens"
-- "Touch targets consistently too small (<44px) throughout mobile experience"
-
-### Positive Findings
-
-Note what's working well: good practices to maintain and replicate.
-
-## Recommended Actions
-
-List recommended commands in priority order (P0 first, then P1, then P2):
-
-1. **[P?] `/command-name`**: Brief description (specific context from audit findings)
-2. **[P?] `/command-name`**: Brief description (specific context)
-
-**Rules**: Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset. Map findings to the most appropriate command. End with `/impeccable polish` as the final step if any fixes were recommended.
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable audit` after fixes to see your score improve.
-
-**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters.
-
-**NEVER**:
-- Report issues without explaining impact (why does this matter?)
-- Provide generic recommendations (be specific and actionable)
-- Skip positive findings (celebrate what works)
-- Forget to prioritize (everything can't be P0)
-- Report false positives without verification
-
@@ -1,113 +0,0 @@
-When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact and personality through stronger hierarchy, committed scale, and decisive type.
-
----
-
-## Register
-
-Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
-
-Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too safe or boring:
-
-1. **Identify weakness sources**:
- - **Generic choices**: System fonts, basic colors, standard layouts
- - **Timid scale**: Everything is medium-sized with no drama
- - **Low contrast**: Everything has similar visual weight
- - **Static**: No motion, no energy, no life
- - **Predictable**: Standard patterns with no surprises
- - **Flat hierarchy**: Nothing stands out or commands attention
-
-2. **Understand the context**:
- - What's the brand personality? (How far can we push?)
- - What's the purpose? (Marketing can be bolder than financial dashboards)
- - Who's the audience? (What will resonate?)
- - What are the constraints? (Brand guidelines, accessibility, performance)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
-
-**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
-
-## Plan Amplification
-
-Create a strategy to increase impact while maintaining coherence:
-
-- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
-- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
-- **Risk budget**: How experimental can we be? Push boundaries within constraints.
-- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
-
-**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration.
-
-## Amplify the Design
-
-Systematically increase impact across these dimensions:
-
-### Typography Amplification
-- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and [typography.md](typography.md) for inspiration)
-- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
-- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
-- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
-
-### Color Intensification
-- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
-- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop
-- **Dominant color strategy**: Let one bold color own 60% of the design
-- **Sharp accents**: High-contrast accent colors that pop
-- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
-- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
-
-### Spatial Drama
-- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
-- **Break the grid**: Let hero elements escape containers and cross boundaries
-- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
-- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
-- **Overlap**: Layer elements intentionally for depth
-
-### Visual Effects
-- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
-- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
-- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop)
-- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
-- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
-
-### Motion & Animation
-- **Entrance choreography**: Staggered, dramatic page load animations with 50-100ms delays
-- **Scroll effects**: Parallax, reveal animations, scroll-triggered sequences
-- **Micro-interactions**: Satisfying hover effects, click feedback, state changes
-- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect)
-
-### Composition Boldness
-- **Hero moments**: Create clear focal points with dramatic treatment
-- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
-- **Full-bleed elements**: Use full viewport width/height for impact
-- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
-
-**NEVER**:
-- Add effects randomly without purpose (chaos ≠ bold)
-- Sacrifice readability for aesthetics (body text must be readable)
-- Make everything bold (then nothing is bold; you need contrast)
-- Ignore accessibility (bold design must still meet WCAG standards)
-- Overwhelm with motion (animation fatigue is real)
-- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
-
-## Verify Quality
-
-Ensure amplification maintains usability and coherence:
-
-- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over.
-- **Still functional**: Can users accomplish tasks without distraction?
-- **Coherent**: Does everything feel intentional and unified?
-- **Memorable**: Will users remember this experience?
-- **Performant**: Do all these effects run smoothly?
-- **Accessible**: Does it still meet accessibility standards?
-
-**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects."
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,118 +0,0 @@
-# Brand register
-
-When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made.
-
-The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look.
-
-## The brand slop test
-
-If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?"
-
-Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home.
-
-**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register.
-
-Then the inverse test: in one sentence, describe what you're about to build the way a competitor would describe theirs. If that sentence fits the modal landing page in the category, restart.
-
-## Typography
-
-### Font selection procedure
-
-Every project. Never skip.
-
-1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words.
-2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture.
-3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy."
-4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over.
-
-### Reflex-reject list
-
-Training-data defaults. Ban list. Look further:
-
-Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif
-
-### Reflex-reject aesthetic lanes
-
-Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further.
-
-- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery.
-
-(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.)
-
-The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md).
-
-### Pairing and voice
-
-Distinctive + refined is the goal. The specific shape depends on the brand:
-
-- **Editorial / long-form / luxury**: display serif + sans body (a magazine shape).
-- **Tech / dev tools / fintech**: one committed sans, usually; custom-tight tracking, strong weight contrast inside a single family.
-- **Consumer / food / travel**: warmer pairings, often a humanist sans plus a script or display serif.
-- **Creative studios / agencies**: rule-breaking welcome. Mono-only, or display-only, or custom-drawn type as voice.
-
-Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair.
-
-Vary across projects. If the last brief was a serif-display landing page, this one isn't.
-
-### Scale
-
-Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted.
-
-Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room.
-
-## Color
-
-Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register.
-
-- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige.
-- Palette IS voice. A calm brand and a restless brand should not share palette mechanics.
-- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit.
-- Don't converge across projects. If the last brand surface was restrained-on-cream, this one is not.
-- When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette.
-
-## Layout
-
-- Asymmetric compositions are one option. Break the grid intentionally for emphasis.
-- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings.
-- Alternative: a strict, visible grid as the voice (brutalist / Swiss / tech-spec aesthetics). Either asymmetric or rigorously-gridded can be "designed"; the failure mode is splitting the difference into a generic centered stack.
-- Don't default to centering everything. Left-aligned with asymmetric layouts feels more designed; a strict grid reads as confident structure. A centered-stack hero with icon-title-subtitle cards reads as template.
-- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness.
-
-## Imagery
-
-Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo.
-
-**When the brief implies imagery (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product), you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy.
-
-- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `<div>` placeholders.
-- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel".
-- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one.
-- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish".
-
-"Imagery" here is broader than stock photography: product screenshots, custom data visualizations, generated SVG, and canvas/WebGL scenes are all imagery. Text-only pages where typography alone carries the entire visual weight are the failure mode.
-
-## Motion
-
-- One well-orchestrated page-load with staggered reveals beats scattered micro-interactions, when the brand invites it. Tech-minimal brands often skip entrance motion entirely; the restraint is the voice.
-- For collapsing/expanding sections, transition `grid-template-rows` rather than `height`.
-
-## Brand bans (on top of the shared absolute bans)
-
-- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume.
-- Large rounded-corner icons above every heading. Screams template.
-- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.)
-- All-caps body copy. Reserve caps for short labels and headings.
-- Timid palettes and average layouts. Safe = invisible.
-- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs.
-- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic.
-- Repeated tiny uppercase tracked labels above every section heading. A single strong kicker can be voice; repeating it as section grammar is AI scaffolding unless it's a deliberate, named brand system.
-
-## Brand permissions
-
-Brand can afford things product can't. Take them.
-
-- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography.
-- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing.
-- Typographic risk. Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines, a single oversize word as a hero.
-- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics.
-- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment.
@@ -1,174 +0,0 @@
-> **Additional context needed**: audience technical level and users' mental state in context.
-
-Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task.
-
-
----
-
-## Assess Current Copy
-
-Identify what makes the text unclear or ineffective:
-
-1. **Find clarity problems**:
- - **Jargon**: Technical terms users won't understand
- - **Ambiguity**: Multiple interpretations possible
- - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file"
- - **Length**: Too wordy or too terse
- - **Assumptions**: Assuming user knowledge they don't have
- - **Missing context**: Users don't know what to do or why
- - **Tone mismatch**: Too formal, too casual, or inappropriate for situation
-
-2. **Understand the context**:
- - Who's the audience? (Technical? General? First-time users?)
- - What's the user's mental state? (Stressed during error? Confident during success?)
- - What's the action? (What do we want users to do?)
- - What's the constraint? (Character limits? Space limitations?)
-
-**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets.
-
-## Plan Copy Improvements
-
-Create a strategy for clearer communication:
-
-- **Primary message**: What's the ONE thing users need to know?
-- **Action needed**: What should users do next (if anything)?
-- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?)
-- **Constraints**: Length limits, brand voice, localization considerations
-
-**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words.
-
-## Improve Copy Systematically
-
-Refine text across these common areas:
-
-### Error Messages
-**Bad**: "Error 403: Forbidden"
-**Good**: "You don't have permission to view this page. Contact your admin for access."
-
-**Bad**: "Invalid input"
-**Good**: "Email addresses need an @ symbol. Try: name@example.com"
-
-**Principles**:
-- Explain what went wrong in plain language
-- Suggest how to fix it
-- Don't blame the user
-- Include examples when helpful
-- Link to help/support if applicable
-
-### Form Labels & Instructions
-**Bad**: "DOB (MM/DD/YYYY)"
-**Good**: "Date of birth" (with placeholder showing format)
-
-**Bad**: "Enter value here"
-**Good**: "Your email address" or "Company name"
-
-**Principles**:
-- Use clear, specific labels (not generic placeholders)
-- Show format expectations with examples
-- Explain why you're asking (when not obvious)
-- Put instructions before the field, not after
-- Keep required field indicators clear
-
-### Button & CTA Text
-**Bad**: "Click here" | "Submit" | "OK"
-**Good**: "Create account" | "Save changes" | "Got it, thanks"
-
-**Principles**:
-- Describe the action specifically
-- Use active voice (verb + noun)
-- Match user's mental model
-- Be specific ("Save" is better than "OK")
-
-### Help Text & Tooltips
-**Bad**: "This is the username field"
-**Good**: "Choose a username. You can change this later in Settings."
-
-**Principles**:
-- Add value (don't just repeat the label)
-- Answer the implicit question ("What is this?" or "Why do you need this?")
-- Keep it brief but complete
-- Link to detailed docs if needed
-
-### Empty States
-**Bad**: "No items"
-**Good**: "No projects yet. Create your first project to get started."
-
-**Principles**:
-- Explain why it's empty (if not obvious)
-- Show next action clearly
-- Make it welcoming, not dead-end
-
-### Success Messages
-**Bad**: "Success"
-**Good**: "Settings saved! Your changes will take effect immediately."
-
-**Principles**:
-- Confirm what happened
-- Explain what happens next (if relevant)
-- Be brief but complete
-- Match the user's emotional moment (celebrate big wins)
-
-### Loading States
-**Bad**: "Loading..." (for 30+ seconds)
-**Good**: "Analyzing your data... this usually takes 30-60 seconds"
-
-**Principles**:
-- Set expectations (how long?)
-- Explain what's happening (when it's not obvious)
-- Show progress when possible
-- Offer escape hatch if appropriate ("Cancel")
-
-### Confirmation Dialogs
-**Bad**: "Are you sure?"
-**Good**: "Delete 'Project Alpha'? This can't be undone."
-
-**Principles**:
-- State the specific action
-- Explain consequences (especially for destructive actions)
-- Use clear button labels ("Delete project" not "Yes")
-- Don't overuse confirmations (only for risky actions)
-
-### Navigation & Wayfinding
-**Bad**: Generic labels like "Items" | "Things" | "Stuff"
-**Good**: Specific labels like "Your projects" | "Team members" | "Settings"
-
-**Principles**:
-- Be specific and descriptive
-- Use language users understand (not internal jargon)
-- Make hierarchy clear
-- Consider information scent (breadcrumbs, current location)
-
-## Apply Clarity Principles
-
-Every piece of copy should follow these rules:
-
-1. **Be specific**: "Enter email" not "Enter value"
-2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity)
-3. **Be active**: "Save changes" not "Changes will be saved"
-4. **Be human**: "Oops, something went wrong" not "System error encountered"
-5. **Tell users what to do**, not just what happened
-6. **Be consistent**: Use same terms throughout (don't vary for variety)
-
-**NEVER**:
-- Use jargon without explanation
-- Blame users ("You made an error" → "This field is required")
-- Be vague ("Something went wrong" without explanation)
-- Use passive voice unnecessarily
-- Write overly long explanations (be concise)
-- Use humor for errors (be empathetic instead)
-- Assume technical knowledge
-- Vary terminology (pick one term and stick with it)
-- Repeat information (headers restating intros, redundant explanations)
-- Use placeholders as the only labels (they disappear when users type)
-
-## Verify Improvements
-
-Test that copy improvements work:
-
-- **Comprehension**: Can users understand without context?
-- **Actionability**: Do users know what to do next?
-- **Brevity**: Is it as short as possible while remaining clear?
-- **Consistency**: Does it match terminology elsewhere?
-- **Tone**: Is it appropriate for the situation?
-
-When the copy reads cleanly, hand off to `/impeccable polish` for the final pass.
@@ -1,105 +0,0 @@
-# Codex: Visual Direction & Asset Production
-
-This file is loaded by `/impeccable craft` when the harness has native image generation (currently Codex via `image_gen`). Other harnesses skip it. It covers the two craft steps that depend on real image generation: landing the visual direction, and producing the raster assets the implementation will compose.
-
-Read this *before* generating any images. The order matters, and the per-step user pauses are what keep generated imagery from drifting away from the brief.
-
-### Four stop points before code
-
-Steps A through D each end with the user. Do not advance past any of them on your own read of the situation.
-
-1. **STOP after Step A questions.** Wait for answers.
-2. **STOP after Step B palette generation.** Wait for "confirm palette."
-3. **STOP after Step C mocks.** Wait for direction approval or delegation.
-4. **Only after Step D approves a direction** do you return to craft.md Step 4 and write code.
-
-Prior shape approval does **not** satisfy any of these. Shape's "confirm or override" advances you into Step A; it is not a substitute for it.
-
-## Step A: Explore Directions with the User
-
-Before generating anything, run a brief direction conversation grounded in the shape brief.
-
-**Step A is required even when shape just produced a confirmed brief.** The shape questions and Step A questions cover different ground: shape pins purpose, content, scope; Step A pins palette, atmosphere, and named visual references for the comps you're about to generate. The only time you can skip Step A is when the user has already answered these exact palette/atmosphere/reference questions in the same session.
-
-Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions:
-
-- "Brief says 'editorial restraint, Klim-adjacent.' Are we closer to a quiet specimen page or a magazine-spread feel with hero imagery?"
-- "Palette strategy from shape was 'Committed.' Want it warm-grounded (deep oxblood + cream) or cool-grounded (slate + paper white)?"
-
-**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded.
-
-## Step B: Generate the Brand Palette First
-
-Generate **one** palette artifact before any mocks. This is a small, focused image: typography pairing on the chosen background, primary + accent color swatches, one signature ornament or motif. Single image, single pass.
-
-Why palette first: mocks generated against a vague color sense produce noise that drowns out the structural decisions. A confirmed palette is the first concrete contract for everything downstream.
-
-Show the palette to the user. Ask one question: "This is the palette I'm locking in for the mocks. Confirm, or call out what to shift?"
-
-**STOP and wait for confirmation.** Do not generate mocks against an unconfirmed palette. "Probably good enough" is the wrong call here; the palette is the contract for everything downstream.
-
-## Step C: Generate 1-3 Visual Mocks Against the Palette
-
-Once the palette is confirmed, generate **1 to 3** high-fidelity north-star comps. Each mock must use the confirmed palette and typography. Mocks differ in *structural* direction (hierarchy, topology, density, composition), not in color or motif.
-
-- Brand work: push visual identity, composition, mood, and signature motifs.
-- Product work: push hierarchy, topology, density, tone, grounded in realistic product structure.
-- Landing pages and long-form brand surfaces: show enough of the second fold to establish the system beyond the hero.
-
-Use the `image_gen` tool directly (or via the imagegen skill when available). Don't ask the user to install anything.
-
-## Step D: Approval Loop
-
-Show the comps. Ask what carries forward. Iterate until **one direction is approved** or the user explicitly delegates.
-
-**STOP and wait for the approval or the delegation.** Do not begin Step E or return to craft.md Step 4 until a single direction is named. If the user delegates, pick the strongest direction and explain it from the brief, not personal taste.
-
-Before moving to assets, summarize what to carry into code and what *not* to literalize from the mock. This is the handoff between visual exploration and semantic implementation.
-
-## Step E: Mock Fidelity Inventory
-
-Inventory the approved mock's major visible ingredients. For each, decide implementation: semantic HTML/CSS/SVG, generated raster, sourced raster, icon library, canvas/WebGL, or accepted omission.
-
-Common ingredients to inventory:
-
-- Hero silhouette and dominant composition
-- Signature motifs (planets, devices, portraits, charts, route lines, insets, badges, etc.)
-- Nav and primary CTA treatment
-- Section sequence, especially the second fold
-- Image-native content the concept depends on
-- Typography, density, color/material treatment, motion cues
-
-Treat the mock as a north star, not a screenshot to trace. Don't rasterize core UI text. But if the live result lacks the mock's major ingredients, the implementation is wrong.
-
-If a photographic, architectural, product, or place-led mock becomes generic CSS scenery, decorative diagrams, bullets, or copy, stop and fix it. That's a broken implementation, not a harmless interpretation.
-
-Don't substitute a different hero composition or visual driver post-approval without user sign-off.
-
-## Step F: Asset Slicing via the Asset Producer
-
-Raster ingredients identified in Step E need clean production assets. Use the bundled `impeccable_asset_producer` subagent rather than producing inline.
-
-Spawn it as a scoped subagent. If you do not have explicit permission to use agents, stop and ask:
-
-```text
-Asset production will work better as a scoped subagent job. Should I spawn the Impeccable asset producer subagent for this step?
-```
-
-Pass to the agent:
-
-- Approved mock path or screenshot reference
-- Crop paths or a contact sheet with crop ids
-- Output directory
-- Required dimensions, format, transparency needs
-- Avoid list
-- Notes on what should remain semantic HTML/CSS/SVG instead of raster
-
-Attach image generation capability to the spawned agent when the harness supports it. Do **not** load image-generation reference material into the parent thread.
-
-Inline asset production is allowed only if the user declines subagents, the harness cannot spawn the authorized agent, or the user explicitly asks for single-thread mode.
-
-Prefer HTML/CSS/SVG/canvas when they can credibly reproduce an ingredient; reach for real, generated, or stock imagery when the mock or subject matter calls for actual visual content.
-
-## After This File
-
-Once Steps A through F are complete, return to `craft.md` Step 5 (Build to Production Quality). The implementation builds against the confirmed palette, approved mock, and the assets the producer wrote.
@@ -1,106 +0,0 @@
-# Cognitive Load Assessment
-
-Cognitive load is the total mental effort required to use an interface. Overloaded users make mistakes, get frustrated, and leave. This reference helps identify and fix cognitive overload.
-
----
-
-## Three Types of Cognitive Load
-
-### Intrinsic Load: The Task Itself
-Complexity inherent to what the user is trying to do. You can't eliminate this, but you can structure it.
-
-**Manage it by**:
-- Breaking complex tasks into discrete steps
-- Providing scaffolding (templates, defaults, examples)
-- Progressive disclosure: show what's needed now, hide the rest
-- Grouping related decisions together
-
-### Extraneous Load: Bad Design
-Mental effort caused by poor design choices. **Eliminate this ruthlessly.** It's pure waste.
-
-**Common sources**:
-- Confusing navigation that requires mental mapping
-- Unclear labels that force users to guess meaning
-- Visual clutter competing for attention
-- Inconsistent patterns that prevent learning
-- Unnecessary steps between user intent and result
-
-### Germane Load: Learning Effort
-Mental effort spent building understanding. This is *good* cognitive load; it leads to mastery.
-
-**Support it by**:
-- Progressive disclosure that reveals complexity gradually
-- Consistent patterns that reward learning
-- Feedback that confirms correct understanding
-- Onboarding that teaches through action, not walls of text
-
----
-
-## Cognitive Load Checklist
-
-Evaluate the interface against these 8 items:
-
-- [ ] **Single focus**: Can the user complete their primary task without distraction from competing elements?
-- [ ] **Chunking**: Is information presented in digestible groups (≤4 items per group)?
-- [ ] **Grouping**: Are related items visually grouped together (proximity, borders, shared background)?
-- [ ] **Visual hierarchy**: Is it immediately clear what's most important on the screen?
-- [ ] **One thing at a time**: Can the user focus on a single decision before moving to the next?
-- [ ] **Minimal choices**: Are decisions simplified (≤4 visible options at any decision point)?
-- [ ] **Working memory**: Does the user need to remember information from a previous screen to act on the current one?
-- [ ] **Progressive disclosure**: Is complexity revealed only when the user needs it?
-
-**Scoring**: Count the failed items. 0–1 failures = low cognitive load (good). 2–3 = moderate (address soon). 4+ = high cognitive load (critical fix needed).
-
----
-
-## The Working Memory Rule
-
-**Humans can hold ≤4 items in working memory at once** (Miller's Law revised by Cowan, 2001).
-
-At any decision point, count the number of distinct options, actions, or pieces of information a user must simultaneously consider:
-- **≤4 items**: Within working memory limits, manageable
-- **5–7 items**: Pushing the boundary; consider grouping or progressive disclosure
-- **8+ items**: Overloaded; users will skip, misclick, or abandon
-
-**Practical applications**:
-- Navigation menus: ≤5 top-level items (group the rest under clear categories)
-- Form sections: ≤4 fields visible per group before a visual break
-- Action buttons: 1 primary, 1–2 secondary, group the rest in a menu
-- Dashboard widgets: ≤4 key metrics visible without scrolling
-- Pricing tiers: ≤3 options (more causes analysis paralysis)
-
----
-
-## Common Cognitive Load Violations
-
-### 1. The Wall of Options
-**Problem**: Presenting 10+ choices at once with no hierarchy.
-**Fix**: Group into categories, highlight recommended, use progressive disclosure.
-
-### 2. The Memory Bridge
-**Problem**: User must remember info from step 1 to complete step 3.
-**Fix**: Keep relevant context visible, or repeat it where it's needed.
-
-### 3. The Hidden Navigation
-**Problem**: User must build a mental map of where things are.
-**Fix**: Always show current location (breadcrumbs, active states, progress indicators).
-
-### 4. The Jargon Barrier
-**Problem**: Technical or domain language forces translation effort.
-**Fix**: Use plain language. If domain terms are unavoidable, define them inline.
-
-### 5. The Visual Noise Floor
-**Problem**: Every element has the same visual weight; nothing stands out.
-**Fix**: Establish clear hierarchy: one primary element, 2–3 secondary, everything else muted.
-
-### 6. The Inconsistent Pattern
-**Problem**: Similar actions work differently in different places.
-**Fix**: Standardize interaction patterns. Same type of action = same type of UI.
-
-### 7. The Multi-Task Demand
-**Problem**: Interface requires processing multiple simultaneous inputs (reading + deciding + navigating).
-**Fix**: Sequence the steps. Let the user do one thing at a time.
-
-### 8. The Context Switch
-**Problem**: User must jump between screens/tabs/modals to gather info for a single decision.
-**Fix**: Co-locate the information needed for each decision. Reduce back-and-forth.
@@ -1,105 +0,0 @@
-# Color & Contrast
-
-## Color Spaces: Use OKLCH
-
-**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark.
-
-The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish.
-
-The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand.
-
-## Building Functional Palettes
-
-### Tinted Neutrals
-
-**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces.
-
-The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette.
-
-**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects.
-
-### Palette Structure
-
-A complete system needs:
-
-| Role | Purpose | Example |
-|------|---------|---------|
-| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades |
-| **Neutral** | Text, backgrounds, borders | 9-11 shade scale |
-| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each |
-| **Surface** | Cards, modals, overlays | 2-3 elevation levels |
-
-**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise.
-
-### The 60-30-10 Rule (Applied Correctly)
-
-This rule is about **visual weight**, not pixel count:
-
-- **60%**: Neutral backgrounds, white space, base surfaces
-- **30%**: Secondary colors: text, borders, inactive states
-- **10%**: Accent: CTAs, highlights, focus states
-
-The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power.
-
-## Contrast & Accessibility
-
-### WCAG Requirements
-
-| Content Type | AA Minimum | AAA Target |
-|--------------|------------|------------|
-| Body text | 4.5:1 | 7:1 |
-| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 |
-| UI components, icons | 3:1 | 4.5:1 |
-| Non-essential decorations | None | None |
-
-**The gotcha**: Placeholder text still needs 4.5:1. That light gray placeholder you see everywhere? Usually fails WCAG.
-
-### Dangerous Color Combinations
-
-These commonly fail contrast or cause readability issues:
-
-- Light gray text on white (the #1 accessibility fail)
-- **Gray text on any colored background**: gray looks washed out and dead on color. Use a darker shade of the background color, or transparency
-- Red text on green background (or vice versa): 8% of men can't distinguish these
-- Blue text on red background (vibrates visually)
-- Yellow text on white (almost always fails)
-- Thin light text on images (unpredictable contrast)
-
-### Never Use Pure Gray or Pure Black
-
-Pure gray (`oklch(50% 0 0)`) and pure black (`#000`) don't exist in nature; real shadows and surfaces always have a color cast. Even a chroma of 0.005-0.01 is enough to feel natural without being obviously tinted. (See tinted neutrals example above.)
-
-### Testing
-
-Don't trust your eyes. Use tools:
-
-- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/)
-- Browser DevTools → Rendering → Emulate vision deficiencies
-- [Polypane](https://polypane.app/) for real-time testing
-
-## Theming: Light & Dark Mode
-
-### Dark Mode Is Not Inverted Light Mode
-
-You can't just swap colors. Dark mode requires different design decisions:
-
-| Light Mode | Dark Mode |
-|------------|-----------|
-| Shadows for depth | Lighter surfaces for depth (no shadows) |
-| Dark text on light | Light text on dark (reduce font weight) |
-| Vibrant accents | Desaturate accents slightly |
-| White backgrounds | Never pure black; use dark gray (oklch 12-18%) |
-
-In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light.
-
-### Token Hierarchy
-
-Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same.
-
-## Alpha Is A Design Smell
-
-Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed.
-
----
-
-**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Using pure black (#000) for large areas. Skipping color blindness testing (8% of men affected).
@@ -1,154 +0,0 @@
-> **Additional context needed**: existing brand colors.
-
-Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit.
-
----
-
-## Register
-
-Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it.
-
-Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen.
-
----
-
-## Assess Color Opportunity
-
-Analyze the current state and identify opportunities:
-
-1. **Understand current state**:
- - **Color absence**: Pure grayscale? Limited neutrals? One timid accent?
- - **Missed opportunities**: Where could color add meaning, hierarchy, or delight?
- - **Context**: What's appropriate for this domain and audience?
- - **Brand**: Are there existing brand colors we should use?
-
-2. **Identify where color adds value**:
- - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue)
- - **Hierarchy**: Drawing attention to important elements
- - **Categorization**: Different sections, types, or states
- - **Emotional tone**: Warmth, energy, trust, creativity
- - **Wayfinding**: Helping users navigate and understand structure
- - **Delight**: Moments of visual interest and personality
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose.
-
-## Plan Color Strategy
-
-Create a purposeful color introduction plan:
-
-- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals)
-- **Dominant color**: Which color owns 60% of colored elements?
-- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%)
-- **Application strategy**: Where does each color appear and why?
-
-**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more.
-
-## Introduce Color Strategically
-
-Add color systematically across these dimensions:
-
-### Semantic Color
-- **State indicators**:
- - Success: Green tones (emerald, forest, mint)
- - Error: Red/pink tones (rose, crimson, coral)
- - Warning: Orange/amber tones
- - Info: Blue tones (sky, ocean, indigo)
- - Neutral: Gray/slate for inactive states
-
-- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.)
-- **Progress indicators**: Colored bars, rings, or charts showing completion or health
-
-### Accent Color Application
-- **Primary actions**: Color the most important buttons/CTAs
-- **Links**: Add color to clickable text (maintain accessibility)
-- **Icons**: Colorize key icons for recognition and personality
-- **Headers/titles**: Add color to section headers or key labels
-- **Hover states**: Introduce color on interaction
-
-### Background & Surfaces
-- **Tinted backgrounds**: Replace pure gray (`#f5f5f5`) with warm neutrals (`oklch(97% 0.01 60)`) or cool tints (`oklch(97% 0.01 250)`)
-- **Colored sections**: Use subtle background colors to separate areas
-- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue)
-- **Cards & surfaces**: Tint cards or surfaces slightly for warmth
-
-**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
-
-### Data Visualization
-- **Charts & graphs**: Use color to encode categories or values
-- **Heatmaps**: Color intensity shows density or importance
-- **Comparison**: Color coding for different datasets or timeframes
-
-### Borders & Accents
-- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`)
-- **Underlines**: Color underlines for emphasis or active states
-- **Dividers**: Subtle colored dividers instead of gray lines
-- **Focus rings**: Colored focus indicators matching brand
-- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe
-
-**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe.
-
-### Typography Color
-- **Colored headings**: Use brand colors for section headings (maintain contrast)
-- **Highlight text**: Color for emphasis or categories
-- **Labels & tags**: Small colored labels for metadata or categories
-
-### Decorative Elements
-- **Illustrations**: Add colored illustrations or icons
-- **Shapes**: Geometric shapes in brand colors as background elements
-- **Gradients**: Colorful gradient overlays or mesh backgrounds
-- **Blobs/organic shapes**: Soft colored shapes for visual interest
-
-## Balance & Refinement
-
-Ensure color addition improves rather than overwhelms:
-
-### Maintain Hierarchy
-- **Dominant color** (60%): Primary brand color or most used accent
-- **Secondary color** (30%): Supporting color for variety
-- **Accent color** (10%): High contrast for key moments
-- **Neutrals** (remaining): Gray/black/white for structure
-
-### Accessibility
-- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components)
-- **Don't rely on color alone**: Use icons, labels, or patterns alongside color
-- **Test for color blindness**: Verify red/green combinations work for all users
-
-### Cohesion
-- **Consistent palette**: Use colors from defined palette, not arbitrary choices
-- **Systematic application**: Same color meanings throughout (green always = success)
-- **Temperature consistency**: Warm palette stays warm, cool stays cool
-
-**NEVER**:
-- Use every color in the rainbow (choose 2-4 colors beyond neutrals)
-- Apply color randomly without semantic meaning
-- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead
-- Use pure gray for neutrals. Add subtle color tint (warm or cool) for depth
-- Use pure black (`#000`) or pure white (`#fff`) for large areas
-- Violate WCAG contrast requirements
-- Use color as the only indicator (accessibility issue)
-- Make everything colorful (defeats the purpose)
-- Default to purple-blue gradients (AI slop aesthetic)
-
-## Verify Color Addition
-
-Test that colorization improves the experience:
-
-- **Better hierarchy**: Does color guide attention appropriately?
-- **Clearer meaning**: Does color help users understand states/categories?
-- **More engaging**: Does the interface feel warmer and more inviting?
-- **Still accessible**: Do all color combinations meet WCAG standards?
-- **Not overwhelming**: Is color balanced and purposeful?
-
-When the palette earns its place, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage.
-
-```json
-{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"}
-```
-
-Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract.
@@ -1,123 +0,0 @@
-# Craft Flow
-
-Build a feature with impeccable UX and UI quality: shape the design, land the visual direction, build real production code, inspect and improve in-browser until it meets a high-end studio bar.
-
-Before writing code, you need: PRODUCT.md loaded, register identified and the matching reference loaded, and a confirmed design direction for this task (either from `shape` or supplied by the user). PRODUCT.md is project context, not a task-specific brief.
-
-Treat any approved visual direction (generated mock or stated reference) as a concrete contract for composition, hierarchy, density, atmosphere, signature motifs, and distinctive visual moves. Don't let mocks replace structure, copy, accessibility, or state design. But if the live result lacks the approved direction's major ingredients, the implementation is wrong.
-
-### Gates: do not compress
-
-Craft has **multiple user gates**, not one. When the harness has native image generation (Codex via `image_gen`), the gate sequence before code is:
-
-1. **Shape brief confirmed** (Step 1)
-2. **Direction questions answered** (codex.md Step A)
-3. **Palette confirmed** (codex.md Step B)
-4. **One mock direction approved or delegated** (codex.md Step D)
-
-You must stop at every gate. **Shape confirmation alone is NOT a green light to start coding.** It is the green light to begin codex.md Step A. Compressing gates 2 through 4 because the shape brief felt complete is the dominant failure mode of this flow.
-
-When the harness lacks native image generation, gates 2-4 collapse into the brief itself, and shape confirmation does advance straight to code.
-
-## Step 0: Project Foundation
-
-Before shape, before code: figure out what kind of project you're working in.
-
-Look at the working directory. Run `ls`. Check for:
-
-- An existing framework: `astro.config.mjs/ts`, `next.config.js/ts`, `nuxt.config.ts`, `svelte.config.js`, `vite.config.js/ts`, `package.json` with framework deps, `Cargo.toml` + Leptos/Yew, `Gemfile` + Rails. **If found, use it.** Do not start a parallel build, do not introduce a second framework, do not write to `dist/` or `build/` directly. Whatever pipeline the project has, respect it.
-- An existing component library or design system: `src/components/`, `app/components/`, a `tokens.css` / `theme.ts`, an `astro.config` `integrations`. Read what's there before adding to it.
-- An existing icon set: `lucide-react`, `@phosphor-icons/react`, `@iconify/*`, hand-rolled SVG sprites in `assets/icons/`. **Use what's already in the project**; don't introduce a second set.
-
-If the directory is empty (greenfield), don't pick a framework silently. Ask the user via the AskUserQuestion tool, with sensible defaults framed by the brief:
-
-```text
-What should this be built on?
- - Astro (default for content-led brand sites, landing pages, marketing surfaces)
- - SvelteKit / Next.js / Nuxt (when the brief implies an app surface or significant interactivity)
- - Single index.html (one-shot demo, prototype, or a deliberately framework-free experiment)
-```
-
-Default: Astro for brand briefs, the project's existing framework for product briefs. Ask once; don't re-ask mid-task.
-
-## Step 1: Shape the Design
-
-Run /impeccable shape, passing along whatever feature description the user provided. Shape is **required** for craft; it is what produces a confirmed direction.
-
-Present the shape output and stop. Wait for the user to confirm, override, or course-correct before writing code.
-
-If the user already supplied a confirmed brief or ran shape separately, use it and skip this step.
-
-When the original prompt + PRODUCT.md already answer scope, content, and visual direction with no real ambiguity, the shape output can be **compact** (3-5 bullets stating what you're building and the visual lane, ending with one or two specific questions or "confirm or override"). The full 10-section structured brief is reserved for genuinely ambiguous, multi-screen, or stakeholder-heavy tasks. Don't pad a clear brief into a long one to look thorough; equally, don't skip the pause to look efficient.
-
-If the harness has native image generation (Codex), a compact shape's "confirm or override" advances to **Step 3 and the codex.md flow**, not to Step 4. Phrase the closing line accordingly: "Confirm or override; once we lock direction, I'll run a couple of palette and reference questions before generating any mocks." This stops the model from reading shape confirmation as code-green.
-
-## Step 2: Load References
-
-Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult:
-
-- [spatial-design.md](spatial-design.md) for layout and spacing
-- [typography.md](typography.md) for type hierarchy
-
-Then add references based on the brief's needs:
-- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md)
-- Animation or transitions? Consult [motion-design.md](motion-design.md)
-- Color-heavy or themed? Consult [color-and-contrast.md](color-and-contrast.md)
-- Responsive requirements? Consult [responsive-design.md](responsive-design.md)
-- Heavy on copy, labels, or errors? Consult [ux-writing.md](ux-writing.md)
-
-## Step 3: Visual Direction & Assets (Harness-Gated)
-
-If the harness has **native image generation** (currently Codex via `image_gen`), this step is mandatory. **Stop and load [codex.md](codex.md)**. It covers palette generation, mock exploration, the approval loop, mock-fidelity inventory, and asset slicing via the `impeccable_asset_producer` subagent. Follow Steps A-F in that file, then return here for Step 4.
-
-If the harness lacks native image generation, **state in one line that the visual-direction-by-generation step is being skipped because the harness lacks native image generation, then proceed**. The one-line announcement is required; it forces a conscious decision instead of letting the step quietly evaporate. The brief is your only visual reference. Implement directly from it, treating any named anchor references and the brief's "Design Direction" as the contract.
-
-Whether you generated mocks or not: don't replace required imagery with generic cards, bullets, emoji, fake metrics, decorative CSS panels, or filler copy. Image-led briefs (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product) need real or sourced imagery in the build, not CSS scenery.
-
-## Step 4: Build to Production Quality
-
-**Precondition.** If Step 3 routed you to codex.md (native image generation available), Steps A through D in that file must be complete before any code: questions answered, palette confirmed, mocks generated, one direction approved or delegated. **Do not mention implementation, file paths, or patch plans until that's done.** A confirmed shape brief is not enough; the model that compressed those gates is the model that already failed this flow.
-
-Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration.
-
-### Production bar
-
-- **Real content.** No placeholder copy, placeholder images, dead links, fake controls, or unused scaffold at presentation time.
-- **Preserve the approved mock's major ingredients.** Missing hero objects, world/product imagery, section structure, CTA/nav treatment, or distinctive motifs are blocking defects unless the user accepted the change.
-- **Semantic first.** Real headings, landmarks, labels, form associations, button/link semantics, accessible names, state announcements where needed.
-- **Deliberate spacing and alignment.** No default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment.
-- **Intentional typography.** Chosen loading strategy, clear hierarchy, readable measure, stable line breaks, no overflow at any width.
-- **Realistic state coverage.** Default, hover, focus-visible, active, disabled, loading, error, success, empty, overflow, long/short text, first-run.
-- **Finished interaction quality.** Keyboard paths, touch targets, feedback timing, scroll behavior, state transitions, no hover-only functionality.
-- **Coherent icon set.** Use the project's established set; otherwise pick one library or use accessible text. Don't mix.
-- **Respect the build pipeline.** Edit source files and run the project's build (`npm run build` or equivalent). Don't write to `build/` / `dist/` / `.next/` with `cat`, heredoc, or Bash redirects; that skips asset hashing, image optimization, code splitting, and CSS extraction, and produces output the dev server won't serve.
-- **Verify image URLs before referencing them.** Use image-search MCP or web-fetch when available; guessed photo IDs ship as broken-image placeholders. Without verification, prefer fewer images you're confident about.
-- **Optimized imagery and media.** Correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset`/`picture` for raster, no project-referenced asset left outside the workspace.
-- **Premium motion.** Use atmospheric blur, filter, mask, shadow, reveal when they improve the experience. Avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion.
-- **Maintainable.** Reusable local patterns, clear component boundaries, project conventions. No rasterized UI text or one-off hacks when a local pattern exists.
-- **Technically clean.** Production build passes, no console errors, no avoidable layout shift, no needless dependencies, no broken asset paths.
-- **Ask when uncertain.** If a discovery materially changes the brief or approved direction, stop and ask. Don't guess.
-
-## Step 5: Iterate Visually
-
-Look at what you built like a designer would. Your eyes are whatever the harness gives you: a connected browser, a screenshotting tool, Playwright, or asking the user. Use them for responsive testing (mobile, tablet, desktop minimum) and general visual validation.
-
-If your tool returns a file path, read the PNG back into the conversation. A screenshot you didn't read doesn't count.
-
-For long-form brand surfaces, inspect major sections individually. Thumbnails hide spacing, clipping, and cascade defects.
-
-After the first pass, write an honest critique against the brief, the approved mock's major ingredients (hero silhouette, motifs, imagery, nav/CTA, density), and impeccable's DON'Ts. Patch material defects and re-inspect. **Don't invent defects to demonstrate iteration.** A confident "first pass clean, shipping" beats a fake fix.
-
-Actively check: responsive behavior (composes, not shrinks), every state (empty / error / loading / edge), craft details (spacing, alignment, hierarchy, contrast, motion timing, focus), performance basics. The exit bar: defensible in a high-end studio review.
-
-Detector or QA output is defect evidence only; never proof the work is finished.
-
-## Step 6: Present
-
-Present the result to the user:
-- Show the feature in its primary state
-- Summarize the browser/viewports checked and the most important fixes made after inspection
-- Walk through the key states (empty, error, responsive)
-- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients.
-- Note any remaining limitations or follow-up risks honestly
-- Ask: "What's working? What isn't?"
@@ -1,236 +0,0 @@
-### Purpose
-
-Resolve one stable target, run two independent assessments, synthesize a design critique, persist a snapshot, and ask the user what to improve next. The chat response is the primary deliverable; the snapshot is an archive/backlog for future commands.
-
-### Hard Invariants
-
-- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
-- Assessment A must finish before detector findings enter the parent synthesis context. Detector output is deterministic, but it still anchors judgment.
-- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize.
-- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
-- Viewable targets require browser inspection when available.
-- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
-- Do not claim a user-visible overlay exists unless script injection succeeded and the detector ran in the page.
-
-### Setup
-
-1. **Resolve the target** to a concrete file path or URL. Prefer a source path over a dev-server URL when both identify the same surface; ports drift, paths do not.
- - "the homepage" -> `site/pages/index.astro` or `index.html`
- - "the settings modal" -> the primary component file
- - "this page" -> the current URL or source file
-2. **Compute the slug**:
- ```bash
- node .qoder/skills/impeccable/scripts/critique-storage.mjs slug "<resolved-path-or-url>"
- ```
- Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique.
-3. **Read `.impeccable/critique/ignore.md`** if it exists. Drop matching findings silently; it is the only prior-run input critique consumes.
-
-### Assessment Orchestration
-
-Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis.
-
-If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
-
-### Assessment A: Design Review
-
-Read relevant source files and visually inspect the live page when browser automation is available. Think like a design director.
-
-Evaluate:
-- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill.
-- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases.
-- **Cognitive load**: consult [cognitive-load](cognitive-load.md); report checklist failures and decision points with >4 visible options.
-- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments.
-- **Nielsen heuristics**: consult [heuristics-scoring](heuristics-scoring.md); score all 10 heuristics 0-4.
-
-Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions.
-
-### Assessment B: Detector + Browser Evidence
-
-Run the bundled detector and browser visualization evidence. Assessment B is mandatory and must remain isolated from Assessment A until both are complete.
-
-CLI scan:
-```bash
-node .qoder/skills/impeccable/scripts/detect.mjs --json [--fast] [target]
-```
-
-- Pass markup files/directories as `[target]`; do not pass CSS-only files.
-- For URLs, skip CLI scan and use browser visualization.
-- For 200+ scannable files, use `--fast`; for 500+, narrow scope or ask.
-- Exit code 0 = clean; 2 = findings.
-- If the detector entrypoint is missing or fails to load, report deterministic scan unavailable and continue with browser/manual review.
-
-Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
-
-1. Create a fresh tab and navigate.
-2. Preflight mutable injection by setting `document.title` and appending a `<script>` tag. Read-only evaluate APIs do not count.
-3. If mutation is unavailable, skip live server, browser presentation, and injection; report fallback signal.
-4. If mutation is available, start `node .qoder/skills/impeccable/scripts/live-server.mjs --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then stop the live server.
-5. For multi-view targets, inject on 3-5 representative pages.
-
-Return: CLI findings JSON/counts, browser console findings if applicable, false positives, and skipped/failed browser steps with concrete reasons.
-
-After Assessment B returns usable CLI findings, reuse them. Do not rerun `detect.mjs` in the parent unless Assessment B failed, was truncated, or omitted count, rule names, or file locations.
-
-### Generate Combined Critique Report
-
-Synthesize both assessments into a single report. Do NOT simply concatenate. Weave the findings together, noting where the LLM review and detector agree, where the detector caught issues the LLM missed, and where detector findings are false positives.
-
-The chat response is the primary user-facing deliverable. Present the full structured critique below in chat; do not replace it with a summary and a link. The persisted snapshot is only an archive/backlog for later commands.
-
-Structure your feedback as a design director would:
-
-#### Design Health Score
-> *Consult [heuristics-scoring](heuristics-scoring.md)*
-
-Present the Nielsen's 10 heuristics scores as a table:
-
-| # | Heuristic | Score | Key Issue |
-|---|-----------|-------|-----------|
-| 1 | Visibility of System Status | ? | [specific finding or "n/a" if solid] |
-| 2 | Match System / Real World | ? | |
-| 3 | User Control and Freedom | ? | |
-| 4 | Consistency and Standards | ? | |
-| 5 | Error Prevention | ? | |
-| 6 | Recognition Rather Than Recall | ? | |
-| 7 | Flexibility and Efficiency | ? | |
-| 8 | Aesthetic and Minimalist Design | ? | |
-| 9 | Error Recovery | ? | |
-| 10 | Help and Documentation | ? | |
-| **Total** | | **??/40** | **[Rating band]** |
-
-Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32.
-
-#### Anti-Patterns Verdict
-
-**Start here.** Does this look AI-generated?
-
-**LLM assessment**: Your own evaluation of AI slop tells. Cover overall aesthetic feel, layout sameness, generic composition, missed opportunities for personality.
-
-**Deterministic scan**: Summarize what the automated detector found, with counts and file locations. Note any additional issues the detector caught that you missed, and flag any false positives.
-
-**Visual overlays** (if injection succeeded): Tell the user that overlays are now visible in the **[Human]** tab in their browser, highlighting the detected issues. Summarize what the console output reported. If browser visualization was attempted but injection failed, say that no reliable user-visible overlay is available and report the fallback signal instead.
-
-#### Overall Impression
-A brief gut reaction: what works, what doesn't, and the single biggest opportunity.
-
-#### What's Working
-Highlight 2-3 things done well. Be specific about why they work.
-
-#### Priority Issues
-The 3-5 most impactful design problems, ordered by importance.
-
-For each issue, tag with **P0-P3 severity** (consult [heuristics-scoring](heuristics-scoring.md) for severity definitions):
-- **[P?] What**: Name the problem clearly
-- **Why it matters**: How this hurts users or undermines goals
-- **Fix**: What to do about it (be concrete)
-- **Suggested command**: Which command could address this (from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-#### Persona Red Flags
-> *Consult [personas](personas.md)*
-
-Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `AGENTS.md` contains a `## Design Context` section from `impeccable teach`, also generate 1-2 project-specific personas from the audience/brand info.
-
-For each selected persona, walk through the primary user action and list specific red flags found:
-
-**Alex (Power User)**: No keyboard shortcuts detected. Form requires 8 clicks for primary action. Forced modal onboarding. High abandonment risk.
-
-**Jordan (First-Timer)**: Icon-only nav in sidebar. Technical jargon in error messages ("404 Not Found"). No visible help. Will abandon at step 2.
-
-Be specific. Name the exact elements and interactions that fail each persona. Don't write generic persona descriptions; write what broke for them.
-
-#### Minor Observations
-Quick notes on smaller issues worth addressing.
-
-#### Questions to Consider
-Provocative questions that might unlock better solutions:
-- "What if the primary action were more prominent?"
-- "Does this need to feel this complex?"
-- "What would a confident version of this look like?"
-
-**Remember**:
-- Be direct. Vague feedback wastes everyone's time.
-- Be specific. "The submit button," not "some elements."
-- Say what's wrong AND why it matters to users.
-- Give concrete suggestions. Cut "consider exploring..." entirely.
-- Prioritize ruthlessly. If everything is important, nothing is.
-- Don't soften criticism. Developers need honest feedback to ship great design.
-
-### Persist the Snapshot
-
-Once the report above is finalized, write it to `.impeccable/critique/` so the user can refer back, and so `/impeccable polish` can pick up the priority issues without a copy-paste.
-
-Skip this step if the Setup slug was null (vague or root-level target).
-
-1. **Write the body to a temp file** so you can pipe it to the helper. Use the full critique report (heuristic table, anti-patterns verdict, priority issues, persona red flags, minor observations, and questions), but stop before the "Ask the User" / "Recommended Actions" sections that come later.
-
-2. **Pass the structured metadata** through `IMPECCABLE_CRITIQUE_META` (JSON), then run the write command:
- ```bash
- IMPECCABLE_CRITIQUE_META='{"target":"<user phrasing>","total_score":<n>,"p0_count":<n>,"p1_count":<n>}' \
- node .qoder/skills/impeccable/scripts/critique-storage.mjs write <slug> <body-file>
- ```
- The helper prints the absolute path it wrote.
-
-3. **Delete the temp body file** after the write attempt completes, whether the write succeeded or failed. If deletion fails, mention `temp-file cleanup failed: <reason>` briefly in the final output, but do not block the critique.
-
-4. **Read the trend** for context:
- ```bash
- node .qoder/skills/impeccable/scripts/critique-storage.mjs trend <slug> 5
- ```
- This returns a JSON array of the last 5 frontmatter entries (including the one you just wrote).
-
-5. **Append a single line to the user-visible output**, after the report and before the questions:
-
- > **Trend for `<slug>` (last 5 runs): 24 → 28 → 32 → 29 → 32**
- > Wrote `.impeccable/critique/<filename>`.
-
- If this is the first run for the slug, the trend is just one score; say so: "First run for this target, no trend yet."
-
-This is fire-and-forget. Do not show the user the helper's JSON output; only the human-readable trend line and the written path. Failures here should not block the rest of the flow; print the error and move on.
-
-### Ask the User
-
-**After presenting findings**, use targeted questions based on what was actually found. ask the user directly to clarify what you cannot infer. These answers will shape the action plan.
-
-Ask questions along these lines (adapt to the specific findings; do NOT ask generic questions):
-
-1. **Priority direction**: Based on the issues found, ask which category matters most to the user right now. For example: "I found problems with visual hierarchy, color usage, and information overload. Which area should we tackle first?" Offer the top 2-3 issue categories as options.
-
-2. **Design intent**: If the critique found a tonal mismatch, ask whether it was intentional. For example: "The interface feels clinical and corporate. Is that the intended tone, or should it feel warmer/bolder/more playful?" Offer 2-3 tonal directions as options based on what would fix the issues found.
-
-3. **Scope**: Ask how much the user wants to take on. For example: "I found N issues. Want to address everything, or focus on the top 3?" Offer scope options like "Top 3 only", "All issues", "Critical issues only".
-
-4. **Constraints** (optional; only ask if relevant): If the findings touch many areas, ask if anything is off-limits. For example: "Should any sections stay as-is?" This prevents the plan from touching things the user considers done.
-
-**Rules for questions**:
-- Every question must reference specific findings from the report. Never ask generic "who is your audience?" questions.
-- Keep it to 2-4 questions maximum. Respect the user's time.
-- Offer concrete options, not open-ended prompts.
-- If findings are straightforward (e.g., only 1-2 clear issues), skip questions and go directly to Recommended Actions.
-
-### Recommended Actions
-
-**After receiving the user's answers**, present a prioritized action summary reflecting the user's priorities and scope from Ask the User.
-
-#### Action Summary
-
-List recommended commands in priority order, based on the user's answers:
-
-1. **`/command-name`**: Brief description of what to fix (specific context from critique findings)
-2. **`/command-name`**: Brief description (specific context)
-...
-
-**Rules for recommendations**:
-- Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset
-- Order by the user's stated priorities first, then by impact
-- Each item's description should carry enough context that the command knows what to focus on
-- Map each Priority Issue to the appropriate command
-- Skip commands that would address zero issues
-- If the user chose a limited scope, only include items within that scope
-- If the user marked areas as off-limits, exclude commands that would touch those areas
-- End with `/impeccable polish` as the final step if any fixes were recommended
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable critique` after fixes to see your score improve.
@@ -1,302 +0,0 @@
-> **Additional context needed**: what's appropriate for the domain (playful vs professional vs quirky vs elegant).
-
-Find the moments where personality and unexpected polish would turn a functional interface into one users remember and tell other people about. Add only where the moment earns it; delight everywhere reads as noise.
-
----
-
-## Register
-
-Brand: delight can be distributed across copy voice, section transitions, discovery rewards, seasonal touches, personality across the whole surface.
-
-Product: delight at specific moments, not pages. Completion, first-time actions, error recovery, milestone crossings. Reliability and consistency carry the rest of the experience; delight pushed everywhere reads as noise.
-
----
-
-## Assess Delight Opportunities
-
-Identify where delight would enhance (not distract from) the experience:
-
-1. **Find natural delight moments**:
- - **Success states**: Completed actions (save, send, publish)
- - **Empty states**: First-time experiences, onboarding
- - **Loading states**: Waiting periods that could be entertaining
- - **Achievements**: Milestones, streaks, completions
- - **Interactions**: Hover states, clicks, drags
- - **Errors**: Softening frustrating moments
- - **Easter eggs**: Hidden discoveries for curious users
-
-2. **Understand the context**:
- - What's the brand personality? (Playful? Professional? Quirky? Elegant?)
- - Who's the audience? (Tech-savvy? Creative? Corporate?)
- - What's the emotional context? (Accomplishment? Exploration? Frustration?)
- - What's appropriate? (Banking app ≠ gaming app)
-
-3. **Define delight strategy**:
- - **Subtle sophistication**: Refined micro-interactions (luxury brands)
- - **Playful personality**: Whimsical illustrations and copy (consumer apps)
- - **Helpful surprises**: Anticipating needs before users ask (productivity tools)
- - **Sensory richness**: Satisfying sounds, smooth animations (creative tools)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Delight should enhance usability, never obscure it. If users notice the delight more than accomplishing their goal, you've gone too far.
-
-## Delight Principles
-
-Follow these guidelines:
-
-### Delight Amplifies, Never Blocks
-- Delight moments should be quick (< 1 second)
-- Never delay core functionality for delight
-- Make delight skippable or subtle
-- Respect user's time and task focus
-
-### Surprise and Discovery
-- Hide delightful details for users to discover
-- Reward exploration and curiosity
-- Don't announce every delight moment
-- Let users share discoveries with others
-
-### Appropriate to Context
-- Match delight to emotional moment (celebrate success, empathize with errors)
-- Respect the user's state (don't be playful during critical errors)
-- Match brand personality and audience expectations
-- Cultural sensitivity (what's delightful varies by culture)
-
-### Compound Over Time
-- Delight should remain fresh with repeated use
-- Vary responses (not same animation every time)
-- Reveal deeper layers with continued use
-- Build anticipation through patterns
-
-## Delight Techniques
-
-Add personality and joy through these methods:
-
-### Micro-interactions & Animation
-
-**Button delight**:
-```css
-/* Satisfying button press */
-.button {
- transition: transform 0.1s, box-shadow 0.1s;
-}
-.button:active {
- transform: translateY(2px);
- box-shadow: 0 2px 4px rgba(0,0,0,0.2);
-}
-
-/* Ripple effect on click */
-/* Smooth lift on hover */
-.button:hover {
- transform: translateY(-2px);
- transition: transform 0.2s cubic-bezier(0.25, 1, 0.5, 1); /* ease-out-quart */
-}
-```
-
-**Loading delight**:
-- Playful loading animations (not just spinners)
-- Personality in loading messages (write product-specific ones, not generic AI filler)
-- Progress indication with encouraging messages
-- Skeleton screens with subtle animations
-
-**Success animations**:
-- Checkmark draw animation
-- Confetti burst for major achievements
-- Gentle scale + fade for confirmation
-- Satisfying sound effects (subtle)
-
-**Hover surprises**:
-- Icons that animate on hover
-- Color shifts or glow effects
-- Tooltip reveals with personality
-- Cursor changes (custom cursors for branded experiences)
-
-### Personality in Copy
-
-**Playful error messages**:
-```
-"Error 404"
-"This page is playing hide and seek. (And winning)"
-
-"Connection failed"
-"Looks like the internet took a coffee break. Want to retry?"
-```
-
-**Encouraging empty states**:
-```
-"No projects"
-"Your canvas awaits. Create something amazing."
-
-"No messages"
-"Inbox zero! You're crushing it today."
-```
-
-**Playful labels & tooltips**:
-```
-"Delete"
-"Send to void" (for playful brand)
-
-"Help"
-"Rescue me" (tooltip)
-```
-
-**IMPORTANT**: Match copy personality to brand. Banks shouldn't be wacky, but they can be warm.
-
-### Illustrations & Visual Personality
-
-**Custom illustrations**:
-- Empty state illustrations (not stock icons)
-- Error state illustrations (friendly monsters, quirky characters)
-- Loading state illustrations (animated characters)
-- Success state illustrations (celebrations)
-
-**Icon personality**:
-- Custom icon set matching brand personality
-- Animated icons (subtle motion on hover/click)
-- Illustrative icons (more detailed than generic)
-- Consistent style across all icons
-
-**Background effects**:
-- Subtle particle effects
-- Gradient mesh backgrounds
-- Geometric patterns
-- Parallax depth
-- Time-of-day themes (morning vs night)
-
-### Satisfying Interactions
-
-**Drag and drop delight**:
-- Lift effect on drag (shadow, scale)
-- Snap animation when dropped
-- Satisfying placement sound
-- Undo toast ("Dropped in wrong place? [Undo]")
-
-**Toggle switches**:
-- Smooth slide with spring physics
-- Color transition
-- Haptic feedback on mobile
-- Optional sound effect
-
-**Progress & achievements**:
-- Streak counters with celebratory milestones
-- Progress bars that "celebrate" at 100%
-- Badge unlocks with animation
-- Playful stats ("You're on fire! 5 days in a row")
-
-**Form interactions**:
-- Input fields that animate on focus
-- Checkboxes with a satisfying scale pulse when checked
-- Success state that celebrates valid input
-- Auto-grow textareas
-
-### Sound Design
-
-**Subtle audio cues** (when appropriate):
-- Notification sounds (distinctive but not annoying)
-- Success sounds (satisfying "ding")
-- Error sounds (empathetic, not harsh)
-- Typing sounds for chat/messaging
-- Ambient background audio (very subtle)
-
-**IMPORTANT**:
-- Respect system sound settings
-- Provide mute option
-- Keep volumes quiet (subtle cues, not alarms)
-- Don't play on every interaction (sound fatigue is real)
-
-### Easter Eggs & Hidden Delights
-
-**Discovery rewards**:
-- Konami code unlocks special theme
-- Hidden keyboard shortcuts (Cmd+K for special features)
-- Hover reveals on logos or illustrations
-- Alt text jokes on images (for screen reader users too!)
-- Console messages for developers ("Like what you see? We're hiring!")
-
-**Seasonal touches**:
-- Holiday themes (subtle, tasteful)
-- Seasonal color shifts
-- Weather-based variations
-- Time-based changes (dark at night, light during day)
-
-**Contextual personality**:
-- Different messages based on time of day
-- Responses to specific user actions
-- Randomized variations (not same every time)
-- Progressive reveals with continued use
-
-### Loading & Waiting States
-
-**Make waiting engaging**:
-- Interesting loading messages that rotate
-- Progress bars with personality
-- Mini-games during long loads
-- Fun facts or tips while waiting
-- Countdown with encouraging messages
-
-```
-Loading messages: write ones specific to your product, not generic AI filler:
-- "Crunching your latest numbers..."
-- "Syncing with your team's changes..."
-- "Preparing your dashboard..."
-- "Checking for updates since yesterday..."
-```
-
-**WARNING**: Avoid cliched loading messages like "Herding pixels", "Teaching robots to dance", "Consulting the magic 8-ball", "Counting backwards from infinity". These are AI-slop copy, instantly recognizable as machine-generated. Write messages that are specific to what your product actually does.
-
-### Celebration Moments
-
-**Success celebrations**:
-- Confetti for major milestones
-- Animated checkmarks for completions
-- Progress bar celebrations at 100%
-- "Achievement unlocked" style notifications
-- Personalized messages ("You published your 10th article!")
-
-**Milestone recognition**:
-- First-time actions get special treatment
-- Streak tracking and celebration
-- Progress toward goals
-- Anniversary celebrations
-
-## Implementation Patterns
-
-**Animation libraries**:
-- Framer Motion (React)
-- GSAP (universal)
-- Lottie (After Effects animations)
-- Canvas confetti (party effects)
-
-**Sound libraries**:
-- Howler.js (audio management)
-- Use-sound (React hook)
-
-**Physics libraries**:
-- React Spring (spring physics)
-- Popmotion (animation primitives)
-
-**IMPORTANT**: File size matters. Compress images, optimize animations, lazy load delight features.
-
-**NEVER**:
-- Delay core functionality for delight
-- Force users through delightful moments (make skippable)
-- Use delight to hide poor UX
-- Overdo it (less is more)
-- Ignore accessibility (animate responsibly, provide alternatives)
-- Make every interaction delightful (special moments should be special)
-- Sacrifice performance for delight
-- Be inappropriate for context (read the room)
-
-## Verify Delight Quality
-
-Test that delight actually delights:
-
-- **User reactions**: Do users smile? Share screenshots?
-- **Doesn't annoy**: Still pleasant after 100th time?
-- **Doesn't block**: Can users opt out or skip?
-- **Performant**: No jank, no slowdown
-- **Appropriate**: Matches brand and context
-- **Accessible**: Works with reduced motion, screen readers
-
-When the moments feel earned, hand off to `/impeccable polish` for the final pass.
@@ -1,111 +0,0 @@
-Strip a design to its essence. Remove anything that doesn't earn its place: redundant elements, repeated information, decorative noise, cosmetic complexity.
-
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel complex or cluttered:
-
-1. **Identify complexity sources**:
- - **Too many elements**: Competing buttons, redundant information, visual clutter
- - **Excessive variation**: Too many colors, fonts, sizes, styles without purpose
- - **Information overload**: Everything visible at once, no progressive disclosure
- - **Visual noise**: Unnecessary borders, shadows, backgrounds, decorations
- - **Confusing hierarchy**: Unclear what matters most
- - **Feature creep**: Too many options, actions, or paths forward
-
-2. **Find the essence**:
- - What's the primary user goal? (There should be ONE)
- - What's actually necessary vs nice-to-have?
- - What can be removed, hidden, or combined?
- - What's the 20% that delivers 80% of value?
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Simplicity is not about removing features. It's about removing obstacles between users and their goals. Every element should justify its existence.
-
-## Plan Simplification
-
-Create a ruthless editing strategy:
-
-- **Core purpose**: What's the ONE thing this should accomplish?
-- **Essential elements**: What's truly necessary to achieve that purpose?
-- **Progressive disclosure**: What can be hidden until needed?
-- **Consolidation opportunities**: What can be combined or integrated?
-
-**IMPORTANT**: Simplification is hard. It requires saying no to good ideas to make room for great execution. Be ruthless.
-
-## Simplify the Design
-
-Systematically remove complexity across these dimensions:
-
-### Information Architecture
-- **Reduce scope**: Remove secondary actions, optional features, redundant information
-- **Progressive disclosure**: Hide complexity behind clear entry points (accordions, modals, step-through flows)
-- **Combine related actions**: Merge similar buttons, consolidate forms, group related content
-- **Clear hierarchy**: ONE primary action, few secondary actions, everything else tertiary or hidden
-- **Remove redundancy**: If it's said elsewhere, don't repeat it here
-
-### Visual Simplification
-- **Reduce color palette**: Use 1-2 colors plus neutrals, not 5-7 colors
-- **Limit typography**: One font family, 3-4 sizes maximum, 2-3 weights
-- **Remove decorations**: Eliminate borders, shadows, backgrounds that don't serve hierarchy or function
-- **Flatten structure**: Reduce nesting, remove unnecessary containers; never nest cards inside cards
-- **Remove unnecessary cards**: Cards aren't needed for basic layout; use spacing and alignment instead
-- **Consistent spacing**: Use one spacing scale, remove arbitrary gaps
-
-### Layout Simplification
-- **Linear flow**: Replace complex grids with simple vertical flow where possible
-- **Remove sidebars**: Move secondary content inline or hide it
-- **Full-width**: Use available space generously instead of complex multi-column layouts
-- **Consistent alignment**: Pick left or center, stick with it
-- **Generous white space**: Let content breathe, don't pack everything tight
-
-### Interaction Simplification
-- **Reduce choices**: Fewer buttons, fewer options, clearer path forward (paradox of choice is real)
-- **Smart defaults**: Make common choices automatic, only ask when necessary
-- **Inline actions**: Replace modal flows with inline editing where possible
-- **Remove steps**: Can signup be one step instead of three? Can checkout be simplified?
-- **Clear CTAs**: ONE obvious next step, not five competing actions
-
-### Content Simplification
-- **Shorter copy**: Cut every sentence in half, then do it again
-- **Active voice**: "Save changes" not "Changes will be saved"
-- **Remove jargon**: Plain language always wins
-- **Scannable structure**: Short paragraphs, bullet points, clear headings
-- **Essential information only**: Remove marketing fluff, legalese, hedging
-- **Remove redundant copy**: No headers restating intros, no repeated explanations, say it once
-
-### Code Simplification
-- **Remove unused code**: Dead CSS, unused components, orphaned files
-- **Flatten component trees**: Reduce nesting depth
-- **Consolidate styles**: Merge similar styles, use utilities consistently
-- **Reduce variants**: Does that component need 12 variations, or can 3 cover 90% of cases?
-
-**NEVER**:
-- Remove necessary functionality (simplicity ≠ feature-less)
-- Sacrifice accessibility for simplicity (clear labels and ARIA still required)
-- Make things so simple they're unclear (mystery ≠ minimalism)
-- Remove information users need to make decisions
-- Eliminate hierarchy completely (some things should stand out)
-- Oversimplify complex domains (match complexity to actual task complexity)
-
-## Verify Simplification
-
-Ensure simplification improves usability:
-
-- **Faster task completion**: Can users accomplish goals more quickly?
-- **Reduced cognitive load**: Is it easier to understand what to do?
-- **Still complete**: Are all necessary features still accessible?
-- **Clearer hierarchy**: Is it obvious what matters most?
-- **Better performance**: Does simpler design load faster?
-
-## Document Removed Complexity
-
-If you removed features or options:
-- Document why they were removed
-- Consider if they need alternative access points
-- Note any user feedback to monitor
-
-When the cuts feel right, hand off to `/impeccable polish` for the final pass. As Antoine de Saint-Exupéry put it: "Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away."
@@ -1,427 +0,0 @@
-Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
-
-DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
-
-## The frontmatter: token schema
-
-The YAML frontmatter is the machine-readable layer. It's what Stitch's linter validates and what the live panel renders tiles from. Keep it tight; every entry should correspond to a token the project actually uses.
-
-```yaml
----
-name: <project title>
-description: <one-line tagline>
-colors:
- primary: "#b8422e"
- neutral-bg: "#faf7f2"
- # ...one entry per extracted color; key = descriptive slug
-typography:
- display:
- fontFamily: "Cormorant Garamond, Georgia, serif"
- fontSize: "clamp(2.5rem, 7vw, 4.5rem)"
- fontWeight: 300
- lineHeight: 1
- letterSpacing: "normal"
- body:
- # ...
-rounded:
- sm: "4px"
- md: "8px"
-spacing:
- sm: "8px"
- md: "16px"
-components:
- button-primary:
- backgroundColor: "{colors.primary}"
- textColor: "{colors.neutral-bg}"
- rounded: "{rounded.sm}"
- padding: "16px 48px"
- button-primary-hover:
- backgroundColor: "{colors.primary-deep}"
----
-```
-
-Rules that matter:
-
-- **Token refs** use `{path.to.token}` (e.g. `{colors.primary}`, `{rounded.md}`). Components may reference primitives; primitives may not reference each other.
-- **Stitch validates colors as hex sRGB only** (`#RGB` / `#RGBA` / `#RRGGBB` / `#RRGGBBAA`); OKLCH/HSL/P3 trigger a linter warning, not a hard error. YAML accepts the string either way and our own parser is format-agnostic. Choose based on project posture: (a) if the project has an "OKLCH-only" doctrine or uses Display-P3 values that don't round-trip through sRGB, put OKLCH directly in the frontmatter and accept the Stitch linter warning; (b) if the project wants strict Stitch compliance or plans to use their Tailwind/DTCG export pipeline, put hex in the frontmatter and keep OKLCH in prose as the canonical reference. Never split the source of truth without explicit reason.
-- **Component sub-tokens** are limited to 8 props: `backgroundColor`, `textColor`, `typography`, `rounded`, `padding`, `size`, `height`, `width`. Shadows, motion, focus rings, backdrop-filter: none of those fit. Carry them in the sidecar (Step 4b).
-- **Scale keys are open-ended.** Use whatever names the project already uses (`warm-ash-cream`, `surface-container-low`). Don't rename to Material defaults.
-- **Variants are naming convention, not schema.** `button-primary` / `button-primary-hover` / `button-primary-active` as sibling keys.
-
-## The markdown body: six sections (exact order)
-
-1. `## Overview`
-2. `## Colors`
-3. `## Typography`
-4. `## Elevation`
-5. `## Components`
-6. `## Do's and Don'ts`
-
-Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] Palette` (Stitch's own outputs do this), but the literal word in each header (Overview, Colors, Typography, Elevation, Components, Do's and Don'ts) must be present. Do NOT add extra top-level sections (Layout Principles, Responsive Behavior, Motion, Agent Prompt Guide). Fold that content into the six spec sections where it naturally belongs.
-
-## When to run
-
-- The user just ran `/impeccable teach` and needs the visual side documented.
-- The skill noticed no `DESIGN.md` exists and nudged the user to create one.
-- An existing `DESIGN.md` is stale (the design has drifted).
-- Before a large redesign, to capture the current state as a reference.
-
-If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user the existing file and ask the user directly to clarify what you cannot infer. whether to refresh, overwrite, or merge.
-
-## Two paths
-
-- **Scan mode** (default): the project has design tokens, components, or rendered output. Extract, then confirm descriptive language. Use when there's code to analyze.
-- **Seed mode**: the project is pre-implementation (fresh teach, nothing built yet). Interview for five high-level answers, write a minimal DESIGN.md marked `<!-- SEED -->`. Re-run in scan mode once there's code.
-
-Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode; don't silently switch. `/impeccable document --seed` forces seed mode regardless of code presence.
-
-## Scan mode (approach C: auto-extract, then confirm descriptive language)
-
-### Step 1: Find the design assets
-
-Search the codebase in priority order:
-
-1. **CSS custom properties**: grep for `--color-`, `--font-`, `--spacing-`, `--radius-`, `--shadow-`, `--ease-`, `--duration-` declarations in CSS files (usually `src/styles/`, `public/css/`, `app/globals.css`, etc.). Record name, value, and the file it's defined in.
-2. **Tailwind config**: if `tailwind.config.{js,ts,mjs}` exists, read the `theme.extend` block for colors, fontFamily, spacing, borderRadius, boxShadow.
-3. **CSS-in-JS theme files**: styled-components, emotion, vanilla-extract, stitches; look for `theme.ts`, `tokens.ts`, or equivalent.
-4. **Design token files**: `tokens.json`, `design-tokens.json`, Style Dictionary output, W3C token community group format.
-5. **Component library**: scan the main button, card, input, navigation, dialog components. Note their variant APIs and default styles.
-6. **Global stylesheet**: the root CSS file usually has the base typography and color assignments.
-7. **Visible rendered output**: if browser automation tools are available, load the live site and sample computed styles from key elements (body, h1, a, button, .card). This catches values that tokens miss.
-
-### Step 2: Auto-extract what can be auto-extracted
-
-Build a structured draft from the discovered tokens. For each token class:
-
-- **Colors**: Group into Primary / Secondary / Tertiary / Neutral (the Material-derived roles Stitch uses). If the project only has one accent, express it as Primary + Neutral; omit Secondary and Tertiary rather than inventing them.
-- **Typography**: Map observed sizes and weights to the Material hierarchy (display / headline / title / body / label). Note font-family stacks and the scale ratio.
-- **Elevation**: Catalogue the shadow vocabulary. If the project is flat and uses tonal layering instead, that's a valid answer; state it explicitly.
-- **Components**: For each common component (button, card, input, chip, list item, tooltip, nav), extract shape (radius), color assignment, hover/focus treatment, internal padding.
-- **Spacing + layout**: Fold into Overview or relevant Components. The spec does NOT have a Layout section.
-
-### Step 2b: Stage the frontmatter
-
-From the auto-extracted tokens, draft the YAML frontmatter now (you'll write it at the top of DESIGN.md in Step 4). This is the machine-readable layer: what the live panel and Stitch's linter consume.
-
-- **Colors**: one entry per extracted color. Key = descriptive slug (`warm-ash-cream`, `editorial-magenta`, not `blue-800`). Value = whichever format the project treats as canonical (OKLCH or hex; see the frontmatter rules above). Don't split the source of truth: one format in the frontmatter, don't redefine the same token in prose with a different value.
-- **Typography**: one entry per role (`display`, `headline`, `title`, `body`, `label`). Typography is an object; include only the props that are real for the project (`fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `fontFeature`, `fontVariation`).
-- **Rounded / Spacing**: whatever scale steps the project actually uses, keyed by whatever scale name the project uses (`sm` / `md` / `lg`, or `surface-sm`, or numeric steps).
-- **Components**: one entry per variant (`button-primary`, `button-primary-hover`, `button-ghost`). Reference primitives via `{colors.X}`, `{rounded.Y}`. If a variant needs a property Stitch's 8-prop set doesn't cover (shadow, focus ring, backdrop-filter), carry the full snippet in the sidecar instead.
-
-Skip anything the project doesn't have. Empty scale keys or fabricated tokens pollute the spec.
-
-### Step 3: Ask the user for qualitative language
-
-The following require creative input that cannot be auto-extracted. Group them into one `AskUserQuestion` interaction:
-
-- **Creative North Star**: a single named metaphor for the whole system ("The Editorial Sanctuary", "The Golden State Curator", "The Lab Notebook"). Offer 2-3 options that honor PRODUCT.md's brand personality.
-- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, anti-references (what the system should not feel like).
-- **Color character** (for auto-extracted colors): descriptive names ("Deep Muted Teal-Navy", not "blue-800"). Suggest 2-3 options per key color based on hue/saturation.
-- **Elevation philosophy**: flat/layered/lifted. If shadows exist, is their role ambient or structural?
-- **Component philosophy**: the feel of buttons, cards, inputs in one phrase ("tactile and confident" vs. "refined and restrained").
-
-Quote a line from PRODUCT.md when possible so the user sees their own strategic language carry forward.
-
-### Step 4: Write DESIGN.md
-
-The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the structure below. Headers must match character-for-character. Optional evocative subtitles (e.g. `## 2. Colors: The Coastal Palette`) are allowed.
-
-```markdown
----
-name: [Project Title]
-description: [one-line tagline]
-colors:
- # ... staged frontmatter from Step 2b
----
-
-# Design System: [Project Title]
-
-## 1. Overview
-
-**Creative North Star: "[Named metaphor in quotes]"**
-
-[2-3 paragraph holistic description: personality, density, aesthetic philosophy. Start from the North Star and work outward. State what this system explicitly rejects (pulled from PRODUCT.md's anti-references). End with a short **Key Characteristics:** bullet list.]
-
-## 2. Colors
-
-[Describe the palette character in one sentence.]
-
-### Primary
-- **[Descriptive Name]** (#HEX / oklch(...)): [Where and why this color is used. Be specific about context, not just role.]
-
-### Secondary (optional; omit if the project has only one accent)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Tertiary (optional)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Neutral
-- **[Descriptive Name]** (#HEX): [Text / background / border / divider role.]
-- [...]
-
-### Named Rules (optional, powerful)
-**The [Rule Name] Rule.** [Short, forceful prohibition or doctrine, e.g. "The One Voice Rule. The primary accent is used on ≤10% of any given screen. Its rarity is the point."]
-
-## 3. Typography
-
-**Display Font:** [Family] (with [fallback])
-**Body Font:** [Family] (with [fallback])
-**Label/Mono Font:** [Family, if distinct]
-
-**Character:** [1-2 sentence personality description of the pairing.]
-
-### Hierarchy
-- **Display** ([weight], [size/clamp], [line-height]): [Purpose; where it appears.]
-- **Headline** ([weight], [size], [line-height]): [Purpose.]
-- **Title** ([weight], [size], [line-height]): [Purpose.]
-- **Body** ([weight], [size], [line-height]): [Purpose. Include max line length like 65–75ch if relevant.]
-- **Label** ([weight], [size], [letter-spacing], [case if uppercase]): [Purpose.]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [Short doctrine about type use.]
-
-## 4. Elevation
-
-[One paragraph: does this system use shadows, tonal layering, or a hybrid? If "no shadows", say so explicitly and describe how depth is conveyed instead.]
-
-### Shadow Vocabulary (if applicable)
-- **[Role name]** (`box-shadow: [exact value]`): [When to use it.]
-- [...]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [e.g. "The Flat-By-Default Rule. Surfaces are flat at rest. Shadows appear only as a response to state (hover, elevation, focus)."]
-
-## 5. Components
-
-For each component, lead with a short character line, then specify shape, color assignment, states, and any distinctive behavior.
-
-### Buttons
-- **Shape:** [radius described, exact value in parens]
-- **Primary:** [color assignment + padding, in semantic + exact terms]
-- **Hover / Focus:** [transitions, treatments]
-- **Secondary / Ghost / Tertiary (if applicable):** [brief description]
-
-### Chips (if used)
-- **Style:** [background, text color, border treatment]
-- **State:** [selected / unselected, filter / action variants]
-
-### Cards / Containers
-- **Corner Style:** [radius]
-- **Background:** [colors used]
-- **Shadow Strategy:** [reference Elevation section]
-- **Border:** [if any]
-- **Internal Padding:** [scale]
-
-### Inputs / Fields
-- **Style:** [stroke, background, radius]
-- **Focus:** [treatment, e.g. glow, border shift, etc.]
-- **Error / Disabled:** [if applicable]
-
-### Navigation
-- **Style, typography, default/hover/active states, mobile treatment.**
-
-### [Signature Component] (optional; if the project has a distinctive custom component worth documenting)
-[Description.]
-
-## 6. Do's and Don'ts
-
-Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: include exact colors, pixel values, and named anti-patterns the user mentioned in PRODUCT.md. **Every anti-reference in PRODUCT.md should show up here as a "Don't" with the same language**, so the visual spec carries the strategic line through. Quote PRODUCT.md directly where possible: if PRODUCT.md says *"avoid dark mode with purple gradients, neon accents, glassmorphism"*, the Don'ts here should repeat that by name.
-
-### Do:
-- **Do** [specific prescription with exact values / named rule].
-- **Do** [...]
-
-### Don't:
-- **Don't** [specific prohibition, e.g. "use border-left greater than 1px as a colored stripe"].
-- **Don't** [...]
-- **Don't** [...]
-```
-
-### Step 4b: Write .impeccable/design.json sidecar (extensions only)
-
-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.
-
-Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.
-
-#### Schema
-
-```json
-{
- "schemaVersion": 2,
- "generatedAt": "ISO-8601 string",
- "title": "Design System: [Project Title]",
- "extensions": {
- "colorMeta": {
- "primary": { "role": "primary", "displayName": "Editorial Magenta", "canonical": "oklch(60% 0.25 350)", "tonalRamp": ["...", "...", "..."] },
- "warm-ash-cream": { "role": "neutral", "displayName": "Warm Ash Cream", "canonical": "oklch(96% 0.005 350)", "tonalRamp": ["...", "...", "..."] }
- },
- "typographyMeta": {
- "display": { "displayName": "Display", "purpose": "Hero headlines only." }
- },
- "shadows": [
- { "name": "ambient-low", "value": "0 4px 24px rgba(0,0,0,0.12)", "purpose": "Diffuse hover glow under accent elements." }
- ],
- "motion": [
- { "name": "ease-standard", "value": "cubic-bezier(0.4, 0, 0.2, 1)", "purpose": "Default easing for state transitions." }
- ],
- "breakpoints": [
- { "name": "sm", "value": "640px" }
- ]
- },
- "components": [
- {
- "name": "Primary Button",
- "kind": "button | input | nav | chip | card | custom",
- "refersTo": "button-primary",
- "description": "One-line what and when.",
- "html": "<button class=\"ds-btn-primary\">GET STARTED</button>",
- "css": ".ds-btn-primary { background: #191c1d; color: #fff; padding: 16px 48px; letter-spacing: 0.05em; text-transform: uppercase; font-weight: 500; border: none; border-radius: 0; transition: background 0.2s, transform 0.2s; } .ds-btn-primary:hover { background: oklch(60% 0.25 350); transform: translateY(-2px); }"
- }
- ],
- "narrative": {
- "northStar": "The Editorial Sanctuary",
- "overview": "2-3 paragraphs of the philosophy, pulled from DESIGN.md Overview section.",
- "keyCharacteristics": ["...", "..."],
- "rules": [{ "name": "The One Voice Rule", "body": "...", "section": "colors|typography|elevation" }],
- "dos": ["Do use ..."],
- "donts": ["Don't use ..."]
- }
-}
-```
-
-**What changed from schemaVersion 1.** The old sidecar carried token primitive arrays (`tokens.colors[]`, `tokens.typography[]`, etc.). Those values now live in the frontmatter. The sidecar only carries metadata that can't live in the frontmatter (tonal ramps, canonical OKLCH when the hex is an approximation, display names, role hints), keyed by the frontmatter token name (`colorMeta.<token-name>`, `typographyMeta.<token-name>`). Components still carry full HTML/CSS because Stitch's 8-prop set can't hold them.
-
-#### Component translation rules
-
-The `html` and `css` fields must be **self-contained, drop-in snippets** that render correctly when injected into a shadow DOM. The panel applies them directly: no post-processing, no framework runtime.
-
-1. **Tailwind expansion.** If the source uses Tailwind (className="bg-primary text-white rounded-lg px-6 py-3"), expand every utility to literal CSS properties in the `css` string. Do **not** reference Tailwind classes; do **not** assume a Tailwind CSS bundle is loaded. Each component is self-contained.
-2. **Token resolution.** If the project exposes tokens as CSS custom properties on `:root` (e.g. `--color-primary`, `--radius-md`), reference them via `var(--color-primary)`; they inherit through the shadow DOM and stay live-bound. If tokens live only in JS theme objects (styled-components, CSS-in-JS), resolve to literal values at generation time.
-3. **Icons.** Inline as SVG. Do not reference Lucide/Heroicons packages, icon fonts, or `<img src="...">`. A typical icon is 16-24px; copy the SVG path data directly.
-4. **States.** Include `:hover`, `:focus-visible`, and (if meaningful) `:active` rules inline. A static default-only snapshot makes the panel feel dead. Hover + focus rules in the CSS make it feel alive.
-5. **Reset bloat.** Extract only the component's *distinctive* CSS (background, color, padding, border-radius, typography, transition). Skip universal resets (`box-sizing: border-box`, `line-height: inherit`, `-webkit-font-smoothing`). The panel already has a neutral canvas; don't re-ship resets.
-6. **Scoped class names.** Prefix every class with `ds-` (e.g. `ds-btn-primary`, `ds-input-search`) so component CSS doesn't collide with other components' CSS in the same shadow DOM.
-
-#### What to include
-
-Aim for a tight set of **5-10 components** that best represent the visual system:
-
-- **Canonical primitives (always include if the project has them):** button (each variant as a separate component entry), input/text field, navigation, chip/tag, card.
-- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.
-- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.
-
-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.
-
-#### Tonal ramps
-
-For each color token, generate an 8-step `tonalRamp` array: dark to light, same hue and chroma, stepped lightness from ~15% to ~95%. The panel renders this as a strip under the swatch. If the project already defines a tonal scale (Material `surface-container-low` family, Tailwind-style `blue-50..blue-900`), use those values. Otherwise synthesize in OKLCH.
-
-#### Narrative mapping
-
-Pull directly from the DESIGN.md you just wrote:
-
-- `narrative.northStar` → the `**Creative North Star: "..."**` line from Overview
-- `narrative.overview` → the philosophy paragraphs from Overview
-- `narrative.keyCharacteristics` → the bulleted `**Key Characteristics:**` list
-- `narrative.rules` → every `**The [Name] Rule.** [body]` across all sections, tagged with `section`
-- `narrative.dos` / `narrative.donts` → the bullet lists from Do's and Don'ts verbatim
-
-Do not reword. The panel shows these as secondary collapsible context; the same voice that's in the Markdown carries through.
-
-### Step 5: Confirm, refine, and refresh session cache
-
-1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).
-2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.
-3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"
-4. **Refresh the session cache.** Run `node .qoder/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.
-
-## Seed mode
-
-For projects with no visual system to extract yet. Produces a minimal scaffold, not a full spec.
-
-### Step 1: Confirm seed mode
-
-Before interviewing: "There's no existing visual system to scan. I'll ask five quick questions to seed a starter DESIGN.md. You can re-run `/impeccable document` once there's code, to capture the real tokens and components. OK?"
-
-If the user prefers to skip, stop. No file.
-
-### Step 2: Five questions
-
-Group into one `AskUserQuestion` interaction. Options must be concrete.
-
-1. **Color strategy.** Pick one:
- - Restrained: tinted neutrals + one accent ≤10%
- - Committed: one saturated color carries 30–60% of the surface
- - Full palette: 3–4 named color roles, each deliberate
- - Drenched: the surface IS the color
-
- Then: one hue family or anchor reference ("deep teal", "mustard", "Klim #ff4500 orange").
-
-2. **Typography direction.** Pick one (specific fonts come later):
- - Serif display + sans body
- - Single sans (warm / technical / geometric / humanist; pick a feel)
- - Display + mono
- - Mono-forward
- - Editorial script + sans
-
-3. **Motion energy.** Pick one:
- - Restrained: state changes only
- - Responsive: feedback + transitions, no choreography
- - Choreographed: orchestrated entrances, scroll-driven sequences
-
-4. **Three named references.** Brands, products, printed objects. Not adjectives.
-
-5. **One anti-reference.** What it should NOT feel like. Also named.
-
-### Step 3: Write seed DESIGN.md
-
-Use the six-section spec from Scan mode. Populate what the interview answers; leave the rest as honest placeholders. The seed is a scaffold, not a fabricated spec.
-
-Lead the file with:
-
-```markdown
-<!-- SEED: re-run /impeccable document once there's code to capture the actual tokens and components. -->
-```
-
-Per-section guidance in seed mode:
-
-- **Overview**: Creative North Star and philosophy phrased from the answers (color strategy + motion energy + references). Reference the user's anti-reference directly.
-- **Colors**: Color strategy as a Named Rule (e.g. *"The Drenched Rule. The surface IS the color."*). Hue family or anchor reference. No hex values; mark as `[to be resolved during implementation]`.
-- **Typography**: the direction the user picked (e.g. "Serif display + sans body"). No font names yet: `[font pairing to be chosen at implementation]`.
-- **Elevation**: inferred from motion energy. Restrained/Responsive → flat by default; Choreographed → layered. One sentence.
-- **Components**: omit entirely; no components exist yet.
-- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.
-
-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.
-
-### Step 4: Confirm and refresh session cache
-
-1. Show the seed DESIGN.md. Call out that it is a seed (the marker is the literal commitment).
-2. Tell the user: "Re-run `/impeccable document` once you have some code. That pass will extract real tokens and generate the sidecar."
-3. Run `node .qoder/skills/impeccable/scripts/load-context.mjs` once so the seed lands in conversation for the rest of the session.
-
-## Style guidelines
-
-- **Frontmatter first, prose second.** Tokens go in the YAML frontmatter; prose contextualizes them. Don't redefine a token value in two places; the frontmatter is normative.
-- **Cite PRODUCT.md anti-references by name** in the Do's and Don'ts section. If PRODUCT.md lists "SaaS landing-page clichés" or "generic AI tool marketing" as anti-references, the DESIGN.md Don'ts should repeat those phrases verbatim so the visual spec enforces the strategic line.
-- **Match the spec, don't invent new sections.** The six section names are fixed. If you have Layout/Motion/Responsive content to document, fold it into Overview (philosophy-level rules) or Components (per-component behavior).
-- **Descriptive > technical**: "Gently curved edges (8px radius)" > "rounded-lg". Include the technical value in parens, lead with the description.
-- **Functional > decorative**: for each token, explain WHERE and WHY it's used, not just WHAT it is.
-- **Exact values in parens**: hex codes, px/rem values, font weights; always the number in parens alongside the description.
-- **Use Named Rules**: `**The [Name] Rule.** [short doctrine]`. These are memorable, citable, and much stickier for AI consumers than bullet lists. Stitch's own outputs use them heavily ("The No-Line Rule", "The Ghost Border Fallback"). Aim for 1-3 per section.
-- **Be forceful**. The voice of a design director. "Prohibited", "forbidden", "never", "always", not "consider", "might", "prefer". Match PRODUCT.md's tone.
-- **Concrete anti-pattern tests**. Stitch writes things like *"If it looks like a 2014 app, the shadow is too dark and the blur is too small."* A one-sentence audit test beats a paragraph of principle.
-- **Reference PRODUCT.md**. The anti-references section of PRODUCT.md should directly inform the Do's and Don'ts section here. Quote or paraphrase.
-- **Group colors by role**, not by hex-order or hue-order. Primary / Secondary / Tertiary / Neutral is the spec ordering.
-
-## Pitfalls
-
-- Don't paste raw CSS class names. Translate to descriptive language.
-- Don't extract every token. Stop at what's actually reused; one-offs pollute the system.
-- Don't invent components that don't exist. If the project only has buttons and cards, only document those.
-- Don't overwrite an existing DESIGN.md without asking.
-- Don't duplicate content from PRODUCT.md. DESIGN.md is strictly visual.
-- Don't add a "Layout Principles" or "Motion" or "Responsive Behavior" top-level section. The spec has six, not nine. Fold that content where it belongs.
-- Don't rename sections even slightly. "Colors" not "Color Palette & Roles". "Typography" not "Typography Rules". Tooling parsing depends on exact headers.
-- Don't duplicate token values between frontmatter and prose. If a color is in `colors.primary` as hex, the prose can name it and describe its role but should not reassert a different hex. The frontmatter is normative.
-- Don't invent frontmatter token groups outside Stitch's schema (no `motion:`, `breakpoints:`, `shadows:` at the top level). Stitch's Zod schema only accepts `colors`, `typography`, `rounded`, `spacing`, `components`. Anything else belongs in the sidecar's `extensions`.
@@ -1,69 +0,0 @@
-# Extract Flow
-
-Identify reusable patterns, components, and design tokens, then extract and consolidate them into the design system for systematic reuse.
-
-## Step 1: Discover the Design System
-
-Find the design system, component library, or shared UI directory. Understand its structure: component organization, naming conventions, design token structure, import/export conventions.
-
-**CRITICAL**: If no design system exists, ask the user directly to clarify what you cannot infer. before creating one. Understand the preferred location and structure first.
-
-## Step 2: Identify Patterns
-
-Look for extraction opportunities in the target area:
-
-- **Repeated components**: Similar UI patterns used 3+ times (buttons, cards, inputs)
-- **Hard-coded values**: Colors, spacing, typography, shadows that should be tokens
-- **Inconsistent variations**: Multiple implementations of the same concept
-- **Composition patterns**: Layout or interaction patterns that repeat (form rows, toolbar groups, empty states)
-- **Type styles**: Repeated font-size + weight + line-height combinations
-- **Animation patterns**: Repeated easing, duration, or keyframe combinations
-
-Assess value: only extract things used 3+ times with the same intent. Premature abstraction is worse than duplication.
-
-## Step 3: Plan Extraction
-
-Create a systematic plan:
-
-- **Components to extract**: Which UI elements become reusable components?
-- **Tokens to create**: Which hard-coded values become design tokens?
-- **Variants to support**: What variations does each component need?
-- **Naming conventions**: Component names, token names, prop names that match existing patterns
-- **Migration path**: How to refactor existing uses to consume the new shared versions
-
-**IMPORTANT**: Design systems grow incrementally. Extract what is clearly reusable now, not everything that might someday be reusable.
-
-## Step 4: Extract & Enrich
-
-Build improved, reusable versions:
-
-- **Components**: Clear props API with sensible defaults, proper variants for different use cases, accessibility built in (ARIA, keyboard navigation, focus management), documentation and usage examples
-- **Design tokens**: Clear naming (primitive vs semantic), proper hierarchy and organization, documentation of when to use each token
-- **Patterns**: When to use this pattern, code examples, variations and combinations
-
-## Step 5: Migrate
-
-Replace existing uses with the new shared versions:
-
-- **Find all instances**: Search for the patterns you extracted
-- **Replace systematically**: Update each use to consume the shared version
-- **Test thoroughly**: Ensure visual and functional parity
-- **Delete dead code**: Remove the old implementations
-
-## Step 6: Document
-
-Update design system documentation:
-
-- Add new components to the component library
-- Document token usage and values
-- Add examples and guidelines
-- Update any Storybook or component catalog
-
-**NEVER**:
-- Extract one-off, context-specific implementations without generalization
-- Create components so generic they are useless
-- Extract without considering existing design system conventions
-- Skip proper TypeScript types or prop documentation
-- Create tokens for every single value (tokens should have semantic meaning)
-- Extract things that differ in intent (two buttons that look similar but serve different purposes should stay separate)
-
@@ -1,347 +0,0 @@
-Designs that only work with perfect data aren't production-ready. Harden the interface against the inputs, errors, languages, and network conditions that real users will throw at it.
-
-## Assess Hardening Needs
-
-Identify weaknesses and edge cases:
-
-1. **Test with extreme inputs**:
- - Very long text (names, descriptions, titles)
- - Very short text (empty, single character)
- - Special characters (emoji, RTL text, accents)
- - Large numbers (millions, billions)
- - Many items (1000+ list items, 50+ options)
- - No data (empty states)
-
-2. **Test error scenarios**:
- - Network failures (offline, slow, timeout)
- - API errors (400, 401, 403, 404, 500)
- - Validation errors
- - Permission errors
- - Rate limiting
- - Concurrent operations
-
-3. **Test internationalization**:
- - Long translations (German is often 30% longer than English)
- - RTL languages (Arabic, Hebrew)
- - Character sets (Chinese, Japanese, Korean, emoji)
- - Date/time formats
- - Number formats (1,000 vs 1.000)
- - Currency symbols
-
-**CRITICAL**: Designs that only work with perfect data aren't production-ready. Harden against reality.
-
-## Hardening Dimensions
-
-Systematically improve resilience:
-
-### Text Overflow & Wrapping
-
-**Long text handling**:
-```css
-/* Single line with ellipsis */
-.truncate {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* Multi-line with clamp */
-.line-clamp {
- display: -webkit-box;
- -webkit-line-clamp: 3;
- -webkit-box-orient: vertical;
- overflow: hidden;
-}
-
-/* Allow wrapping */
-.wrap {
- word-wrap: break-word;
- overflow-wrap: break-word;
- hyphens: auto;
-}
-```
-
-**Flex/Grid overflow**:
-```css
-/* Prevent flex items from overflowing */
-.flex-item {
- min-width: 0; /* Allow shrinking below content size */
- overflow: hidden;
-}
-
-/* Prevent grid items from overflowing */
-.grid-item {
- min-width: 0;
- min-height: 0;
-}
-```
-
-**Responsive text sizing**:
-- Use `clamp()` for fluid typography
-- Set minimum readable sizes (14px on mobile)
-- Test text scaling (zoom to 200%)
-- Ensure containers expand with text
-
-### Internationalization (i18n)
-
-**Text expansion**:
-- Add 30-40% space budget for translations
-- Use flexbox/grid that adapts to content
-- Test with longest language (usually German)
-- Avoid fixed widths on text containers
-
-```jsx
-// ❌ Bad: Assumes short English text
-<button className="w-24">Submit</button>
-
-// ✅ Good: Adapts to content
-<button className="px-4 py-2">Submit</button>
-```
-
-**RTL (Right-to-Left) support**:
-```css
-/* Use logical properties */
-margin-inline-start: 1rem; /* Not margin-left */
-padding-inline: 1rem; /* Not padding-left/right */
-border-inline-end: 1px solid; /* Not border-right */
-
-/* Or use dir attribute */
-[dir="rtl"] .arrow { transform: scaleX(-1); }
-```
-
-**Character set support**:
-- Use UTF-8 encoding everywhere
-- Test with Chinese/Japanese/Korean (CJK) characters
-- Test with emoji (they can be 2-4 bytes)
-- Handle different scripts (Latin, Cyrillic, Arabic, etc.)
-
-**Date/Time formatting**:
-```javascript
-// ✅ Use Intl API for proper formatting
-new Intl.DateTimeFormat('en-US').format(date); // 1/15/2024
-new Intl.DateTimeFormat('de-DE').format(date); // 15.1.2024
-
-new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: 'USD'
-}).format(1234.56); // $1,234.56
-```
-
-**Pluralization**:
-```javascript
-// ❌ Bad: Assumes English pluralization
-`${count} item${count !== 1 ? 's' : ''}`
-
-// ✅ Good: Use proper i18n library
-t('items', { count }) // Handles complex plural rules
-```
-
-### Error Handling
-
-**Network errors**:
-- Show clear error messages
-- Provide retry button
-- Explain what happened
-- Offer offline mode (if applicable)
-- Handle timeout scenarios
-
-```jsx
-// Error states with recovery
-{error && (
- <ErrorMessage>
- <p>Failed to load data. {error.message}</p>
- <button onClick={retry}>Try again</button>
- </ErrorMessage>
-)}
-```
-
-**Form validation errors**:
-- Inline errors near fields
-- Clear, specific messages
-- Suggest corrections
-- Don't block submission unnecessarily
-- Preserve user input on error
-
-**API errors**:
-- Handle each status code appropriately
- - 400: Show validation errors
- - 401: Redirect to login
- - 403: Show permission error
- - 404: Show not found state
- - 429: Show rate limit message
- - 500: Show generic error, offer support
-
-**Graceful degradation**:
-- Core functionality works without JavaScript
-- Images have alt text
-- Progressive enhancement
-- Fallbacks for unsupported features
-
-### Edge Cases & Boundary Conditions
-
-**Empty states**:
-- No items in list
-- No search results
-- No notifications
-- No data to display
-- Provide clear next action
-
-**Loading states**:
-- Initial load
-- Pagination load
-- Refresh
-- Show what's loading ("Loading your projects...")
-- Time estimates for long operations
-
-**Large datasets**:
-- Pagination or virtual scrolling
-- Search/filter capabilities
-- Performance optimization
-- Don't load all 10,000 items at once
-
-**Concurrent operations**:
-- Prevent double-submission (disable button while loading)
-- Handle race conditions
-- Optimistic updates with rollback
-- Conflict resolution
-
-**Permission states**:
-- No permission to view
-- No permission to edit
-- Read-only mode
-- Clear explanation of why
-
-**Browser compatibility**:
-- Polyfills for modern features
-- Fallbacks for unsupported CSS
-- Feature detection (not browser detection)
-- Test in target browsers
-
-### Input Validation & Sanitization
-
-**Client-side validation**:
-- Required fields
-- Format validation (email, phone, URL)
-- Length limits
-- Pattern matching
-- Custom validation rules
-
-**Server-side validation** (always):
-- Never trust client-side only
-- Validate and sanitize all inputs
-- Protect against injection attacks
-- Rate limiting
-
-**Constraint handling**:
-```html
-<!-- Set clear constraints -->
-<input
- type="text"
- maxlength="100"
- pattern="[A-Za-z0-9]+"
- required
- aria-describedby="username-hint"
-/>
-<small id="username-hint">
- Letters and numbers only, up to 100 characters
-</small>
-```
-
-### Accessibility Resilience
-
-**Keyboard navigation**:
-- All functionality accessible via keyboard
-- Logical tab order
-- Focus management in modals
-- Skip links for long content
-
-**Screen reader support**:
-- Proper ARIA labels
-- Announce dynamic changes (live regions)
-- Descriptive alt text
-- Semantic HTML
-
-**Motion sensitivity**:
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**High contrast mode**:
-- Test in Windows high contrast mode
-- Don't rely only on color
-- Provide alternative visual cues
-
-### Performance Resilience
-
-**Slow connections**:
-- Progressive image loading
-- Skeleton screens
-- Optimistic UI updates
-- Offline support (service workers)
-
-**Memory leaks**:
-- Clean up event listeners
-- Cancel subscriptions
-- Clear timers/intervals
-- Abort pending requests on unmount
-
-**Throttling & Debouncing**:
-```javascript
-// Debounce search input
-const debouncedSearch = debounce(handleSearch, 300);
-
-// Throttle scroll handler
-const throttledScroll = throttle(handleScroll, 100);
-```
-
-## Testing Strategies
-
-**Manual testing**:
-- Test with extreme data (very long, very short, empty)
-- Test in different languages
-- Test offline
-- Test slow connection (throttle to 3G)
-- Test with screen reader
-- Test keyboard-only navigation
-- Test on old browsers
-
-**Automated testing**:
-- Unit tests for edge cases
-- Integration tests for error scenarios
-- E2E tests for critical paths
-- Visual regression tests
-- Accessibility tests (axe, WAVE)
-
-**IMPORTANT**: Hardening is about expecting the unexpected. Real users will do things you never imagined.
-
-**NEVER**:
-- Assume perfect input (validate everything)
-- Ignore internationalization (design for global)
-- Leave error messages generic ("Error occurred")
-- Forget offline scenarios
-- Trust client-side validation alone
-- Use fixed widths for text
-- Assume English-length text
-- Block entire interface when one component errors
-
-## Verify Hardening
-
-Test thoroughly with edge cases:
-
-- **Long text**: Try names with 100+ characters
-- **Emoji**: Use emoji in all text fields
-- **RTL**: Test with Arabic or Hebrew
-- **CJK**: Test with Chinese/Japanese/Korean
-- **Network issues**: Disable internet, throttle connection
-- **Large datasets**: Test with 1000+ items
-- **Concurrent actions**: Click submit 10 times rapidly
-- **Errors**: Force API errors, test all error states
-- **Empty**: Remove all data, test empty states
-
-When edge cases are covered, hand off to `/impeccable polish` for the final pass.
@@ -1,234 +0,0 @@
-# Heuristics Scoring Guide
-
-Score each of Nielsen's 10 Usability Heuristics on a 0–4 scale. Be honest: a 4 means genuinely excellent, not "good enough."
-
-## Nielsen's 10 Heuristics
-
-### 1. Visibility of System Status
-
-Keep users informed about what's happening through timely, appropriate feedback.
-
-**Check for**:
-- Loading indicators during async operations
-- Confirmation of user actions (save, submit, delete)
-- Progress indicators for multi-step processes
-- Current location in navigation (breadcrumbs, active states)
-- Form validation feedback (inline, not just on submit)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No feedback; user is guessing what happened |
-| 1 | Rare feedback; most actions produce no visible response |
-| 2 | Partial; some states communicated, major gaps remain |
-| 3 | Good; most operations give clear feedback, minor gaps |
-| 4 | Excellent; every action confirms, progress is always visible |
-
-### 2. Match Between System and Real World
-
-Speak the user's language. Follow real-world conventions. Information appears in natural, logical order.
-
-**Check for**:
-- Familiar terminology (no unexplained jargon)
-- Logical information order matching user expectations
-- Recognizable icons and metaphors
-- Domain-appropriate language for the target audience
-- Natural reading flow (left-to-right, top-to-bottom priority)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Pure tech jargon, alien to users |
-| 1 | Mostly confusing; requires domain expertise to navigate |
-| 2 | Mixed; some plain language, some jargon leaks through |
-| 3 | Mostly natural; occasional term needs context |
-| 4 | Speaks the user's language fluently throughout |
-
-### 3. User Control and Freedom
-
-Users need a clear "emergency exit" from unwanted states without extended dialogue.
-
-**Check for**:
-- Undo/redo functionality
-- Cancel buttons on forms and modals
-- Clear navigation back to safety (home, previous)
-- Easy way to clear filters, search, selections
-- Escape from long or multi-step processes
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Users get trapped; no way out without refreshing |
-| 1 | Difficult exits; must find obscure paths to escape |
-| 2 | Some exits; main flows have escape, edge cases don't |
-| 3 | Good control; users can exit and undo most actions |
-| 4 | Full control; undo, cancel, back, and escape everywhere |
-
-### 4. Consistency and Standards
-
-Users shouldn't wonder whether different words, situations, or actions mean the same thing.
-
-**Check for**:
-- Consistent terminology throughout the interface
-- Same actions produce same results everywhere
-- Platform conventions followed (standard UI patterns)
-- Visual consistency (colors, typography, spacing, components)
-- Consistent interaction patterns (same gesture = same behavior)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Inconsistent everywhere; feels like different products stitched together |
-| 1 | Many inconsistencies; similar things look/behave differently |
-| 2 | Partially consistent; main flows match, details diverge |
-| 3 | Mostly consistent; occasional deviation, nothing confusing |
-| 4 | Fully consistent; cohesive system, predictable behavior |
-
-### 5. Error Prevention
-
-Better than good error messages is a design that prevents problems in the first place.
-
-**Check for**:
-- Confirmation before destructive actions (delete, overwrite)
-- Constraints preventing invalid input (date pickers, dropdowns)
-- Smart defaults that reduce errors
-- Clear labels that prevent misunderstanding
-- Autosave and draft recovery
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Errors easy to make; no guardrails anywhere |
-| 1 | Few safeguards; some inputs validated, most aren't |
-| 2 | Partial prevention; common errors caught, edge cases slip |
-| 3 | Good prevention; most error paths blocked proactively |
-| 4 | Excellent; errors nearly impossible through smart constraints |
-
-### 6. Recognition Rather Than Recall
-
-Minimize memory load. Make objects, actions, and options visible or easily retrievable.
-
-**Check for**:
-- Visible options (not buried in hidden menus)
-- Contextual help when needed (tooltips, inline hints)
-- Recent items and history
-- Autocomplete and suggestions
-- Labels on icons (not icon-only navigation)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Heavy memorization; users must remember paths and commands |
-| 1 | Mostly recall; many hidden features, few visible cues |
-| 2 | Some aids; main actions visible, secondary features hidden |
-| 3 | Good recognition; most things discoverable, few memory demands |
-| 4 | Everything discoverable; users never need to memorize |
-
-### 7. Flexibility and Efficiency of Use
-
-Accelerators, invisible to novices, speed up expert interaction.
-
-**Check for**:
-- Keyboard shortcuts for common actions
-- Customizable interface elements
-- Recent items and favorites
-- Bulk/batch actions
-- Power user features that don't complicate the basics
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | One rigid path; no shortcuts or alternatives |
-| 1 | Limited flexibility; few alternatives to the main path |
-| 2 | Some shortcuts; basic keyboard support, limited bulk actions |
-| 3 | Good accelerators; keyboard nav, some customization |
-| 4 | Highly flexible; multiple paths, power features, customizable |
-
-### 8. Aesthetic and Minimalist Design
-
-Interfaces should not contain irrelevant or rarely needed information. Every element should serve a purpose.
-
-**Check for**:
-- Only necessary information visible at each step
-- Clear visual hierarchy directing attention
-- Purposeful use of color and emphasis
-- No decorative clutter competing for attention
-- Focused, uncluttered layouts
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Overwhelming; everything competes for attention equally |
-| 1 | Cluttered; too much noise, hard to find what matters |
-| 2 | Some clutter; main content clear, periphery noisy |
-| 3 | Mostly clean; focused design, minor visual noise |
-| 4 | Perfectly minimal; every element earns its pixel |
-
-### 9. Help Users Recognize, Diagnose, and Recover from Errors
-
-Error messages should use plain language, precisely indicate the problem, and constructively suggest a solution.
-
-**Check for**:
-- Plain language error messages (no error codes for users)
-- Specific problem identification ("Email is missing @" not "Invalid input")
-- Actionable recovery suggestions
-- Errors displayed near the source of the problem
-- Non-blocking error handling (don't wipe the form)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Cryptic errors; codes, jargon, or no message at all |
-| 1 | Vague errors; "Something went wrong" with no guidance |
-| 2 | Clear but unhelpful; names the problem but not the fix |
-| 3 | Clear with suggestions; identifies problem and offers next steps |
-| 4 | Perfect recovery; pinpoints issue, suggests fix, preserves user work |
-
-### 10. Help and Documentation
-
-Even if the system is usable without docs, help should be easy to find, task-focused, and concise.
-
-**Check for**:
-- Searchable help or documentation
-- Contextual help (tooltips, inline hints, guided tours)
-- Task-focused organization (not feature-organized)
-- Concise, scannable content
-- Easy access without leaving current context
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No help available anywhere |
-| 1 | Help exists but hard to find or irrelevant |
-| 2 | Basic help; FAQ or docs exist, not contextual |
-| 3 | Good documentation; searchable, mostly task-focused |
-| 4 | Excellent contextual help; right info at the right moment |
-
----
-
-## Score Summary
-
-**Total possible**: 40 points (10 heuristics × 4 max)
-
-| Score Range | Rating | What It Means |
-|-------------|--------|---------------|
-| 36–40 | Excellent | Minor polish only; ship it |
-| 28–35 | Good | Address weak areas, solid foundation |
-| 20–27 | Acceptable | Significant improvements needed before users are happy |
-| 12–19 | Poor | Major UX overhaul required; core experience broken |
-| 0–11 | Critical | Redesign needed; unusable in current state |
-
----
-
-## Issue Severity (P0–P3)
-
-Tag each individual issue found during scoring with a priority level:
-
-| Priority | Name | Description | Action |
-|----------|------|-------------|--------|
-| **P0** | Blocking | Prevents task completion entirely | Fix immediately; this is a showstopper |
-| **P1** | Major | Causes significant difficulty or confusion | Fix before release |
-| **P2** | Minor | Annoyance, but workaround exists | Fix in next pass |
-| **P3** | Polish | Nice-to-fix, no real user impact | Fix if time permits |
-
-**Tip**: If you're unsure between two levels, ask: "Would a user contact support about this?" If yes, it's at least P1.
@@ -1,195 +0,0 @@
-# Interaction Design
-
-## The Eight Interactive States
-
-Every interactive element needs these states designed:
-
-| State | When | Visual Treatment |
-|-------|------|------------------|
-| **Default** | At rest | Base styling |
-| **Hover** | Pointer over (not touch) | Subtle lift, color shift |
-| **Focus** | Keyboard/programmatic focus | Visible ring (see below) |
-| **Active** | Being pressed | Pressed in, darker |
-| **Disabled** | Not interactive | Reduced opacity, no pointer |
-| **Loading** | Processing | Spinner, skeleton |
-| **Error** | Invalid state | Red border, icon, message |
-| **Success** | Completed | Green check, confirmation |
-
-**The common miss**: Designing hover without focus, or vice versa. They're different. Keyboard users never see hover states.
-
-## Focus Rings: Do Them Right
-
-**Never `outline: none` without replacement.** It's an accessibility violation. Instead, use `:focus-visible` to show focus only for keyboard users:
-
-```css
-/* Hide focus ring for mouse/touch */
-button:focus {
- outline: none;
-}
-
-/* Show focus ring for keyboard */
-button:focus-visible {
- outline: 2px solid var(--color-accent);
- outline-offset: 2px;
-}
-```
-
-**Focus ring design**:
-- High contrast (3:1 minimum against adjacent colors)
-- 2-3px thick
-- Offset from element (not inside it)
-- Consistent across all interactive elements
-
-## Form Design: The Non-Obvious
-
-**Placeholders aren't labels.** They disappear on input. Always use visible `<label>` elements. **Validate on blur**, not on every keystroke (exception: password strength). Place errors **below** fields with `aria-describedby` connecting them.
-
-## Loading States
-
-**Optimistic updates**: Show success immediately, rollback on failure. Use for low-stakes actions (likes, follows), not payments or destructive actions. **Skeleton screens > spinners**: they preview content shape and feel faster than generic spinners.
-
-## Modals: The Inert Approach
-
-Focus trapping in modals used to require complex JavaScript. Now use the `inert` attribute:
-
-```html
-<!-- When modal is open -->
-<main inert>
- <!-- Content behind modal can't be focused or clicked -->
-</main>
-<dialog open>
- <h2>Modal Title</h2>
- <!-- Focus stays inside modal -->
-</dialog>
-```
-
-Or use the native `<dialog>` element:
-
-```javascript
-const dialog = document.querySelector('dialog');
-dialog.showModal(); // Opens with focus trap, closes on Escape
-```
-
-## The Popover API
-
-For tooltips, dropdowns, and non-modal overlays, use native popovers:
-
-```html
-<button popovertarget="menu">Open menu</button>
-<div id="menu" popover>
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-**Benefits**: Light-dismiss (click outside closes), proper stacking, no z-index wars, accessible by default.
-
-## Dropdown & Overlay Positioning
-
-Dropdowns rendered with `position: absolute` inside a container that has `overflow: hidden` or `overflow: auto` will be clipped. This is the single most common dropdown bug in generated code.
-
-### CSS Anchor Positioning
-
-The modern solution uses the CSS Anchor Positioning API to tether an overlay to its trigger without JavaScript:
-
-```css
-.trigger {
- anchor-name: --menu-trigger;
-}
-
-.dropdown {
- position: fixed;
- position-anchor: --menu-trigger;
- position-area: block-end span-inline-end;
- margin-top: 4px;
-}
-
-/* Flip above if no room below */
-@position-try --flip-above {
- position-area: block-start span-inline-end;
- margin-bottom: 4px;
-}
-```
-
-Because the dropdown uses `position: fixed`, it escapes any `overflow` clipping on ancestor elements. The `@position-try` block handles viewport edges automatically. **Browser support**: Chrome 125+, Edge 125+. Not yet in Firefox or Safari - use a fallback for those browsers.
-
-### Popover + Anchor Combo
-
-Combining the Popover API with anchor positioning gives you stacking, light-dismiss, accessibility, and correct positioning in one pattern:
-
-```html
-<button popovertarget="menu" class="trigger">Open</button>
-<div id="menu" popover class="dropdown">
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-The `popover` attribute places the element in the **top layer**, which sits above all other content regardless of z-index or overflow. No portal needed.
-
-### Portal / Teleport Pattern
-
-In component frameworks, render the dropdown at the document root and position it with JavaScript:
-
-- **React**: `createPortal(dropdown, document.body)`
-- **Vue**: `<Teleport to="body">`
-- **Svelte**: Use a portal library or mount to `document.body`
-
-Calculate position from the trigger's `getBoundingClientRect()`, then apply `position: fixed` with `top` and `left` values. Recalculate on scroll and resize.
-
-### Fixed Positioning Fallback
-
-For browsers without anchor positioning support, `position: fixed` with manual coordinates avoids overflow clipping:
-
-```css
-.dropdown {
- position: fixed;
- /* top/left set via JS from trigger's getBoundingClientRect() */
-}
-```
-
-Check viewport boundaries before rendering. If the dropdown would overflow the bottom edge, flip it above the trigger. If it would overflow the right edge, align it to the trigger's right side instead.
-
-### Anti-Patterns
-
-- **`position: absolute` inside `overflow: hidden`** - The dropdown will be clipped. Use `position: fixed` or the top layer instead.
-- **Arbitrary z-index values** like `z-index: 9999` - Use a semantic z-index scale: `dropdown (100) -> sticky (200) -> modal-backdrop (300) -> modal (400) -> toast (500) -> tooltip (600)`.
-- **Rendering dropdown markup inline** without an escape hatch from the parent's stacking context. Either use `popover` (top layer), a portal, or `position: fixed`.
-
-## Destructive Actions: Undo > Confirm
-
-**Undo is better than confirmation dialogs.** Users click through confirmations mindlessly. Remove from UI immediately, show undo toast, actually delete after toast expires. Use confirmation only for truly irreversible actions (account deletion), high-cost actions, or batch operations.
-
-## Keyboard Navigation Patterns
-
-### Roving Tabindex
-
-For component groups (tabs, menu items, radio groups), one item is tabbable; arrow keys move within:
-
-```html
-<div role="tablist">
- <button role="tab" tabindex="0">Tab 1</button>
- <button role="tab" tabindex="-1">Tab 2</button>
- <button role="tab" tabindex="-1">Tab 3</button>
-</div>
-```
-
-Arrow keys move `tabindex="0"` between items. Tab moves to the next component entirely.
-
-### Skip Links
-
-Provide skip links (`<a href="#main-content">Skip to main content</a>`) for keyboard users to jump past navigation. Hide off-screen, show on focus.
-
-## Gesture Discoverability
-
-Swipe-to-delete and similar gestures are invisible. Hint at their existence:
-
-- **Partially reveal**: Show delete button peeking from edge
-- **Onboarding**: Coach marks on first use
-- **Alternative**: Always provide a visible fallback (menu with "Delete")
-
-Don't rely on gestures as the only way to perform actions.
-
----
-
-**Avoid**: Removing focus indicators without alternatives. Using placeholder text as labels. Touch targets <44x44px. Generic error messages. Custom controls without ARIA/keyboard support.
@@ -1,141 +0,0 @@
-Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids, the centered-stack default) and fix the structure, not the surface.
-
----
-
-## Register
-
-Brand: asymmetric compositions, fluid spacing with `clamp()`, intentional grid-breaking for emphasis. Rhythm through contrast: tight groupings paired with generous separations.
-
-Product: predictable grids, consistent densities, familiar navigation patterns. Responsive behavior is structural (collapse sidebar, responsive table), not fluid typography. Consistency IS an affordance.
-
----
-
-## Assess Current Layout
-
-Analyze what's weak about the current spatial design:
-
-1. **Spacing**:
- - Is spacing consistent or arbitrary? (Random padding/margin values)
- - Is all spacing the same? (Equal padding everywhere = no rhythm)
- - Are related elements grouped tightly, with generous space between groups?
-
-2. **Visual hierarchy**:
- - Apply the squint test: blur your (metaphorical) eyes. Can you still identify the most important element, second most important, and clear groupings?
- - Is hierarchy achieved effectively? (Space and weight alone can be enough; is the current approach working?)
- - Does whitespace guide the eye to what matters?
-
-3. **Grid & structure**:
- - Is there a clear underlying structure, or does the layout feel random?
- - Are identical card grids used everywhere? (Icon + heading + text, repeated endlessly)
- - Is everything centered? (Left-aligned with asymmetric layouts feels more designed, but not a hard and fast rule)
-
-4. **Rhythm & variety**:
- - Does the layout have visual rhythm? (Alternating tight/generous spacing)
- - Is every section structured the same way? (Monotonous repetition)
- - Are there intentional moments of surprise or emphasis?
-
-5. **Density**:
- - Is the layout too cramped? (Not enough breathing room)
- - Is the layout too sparse? (Excessive whitespace without purpose)
- - Does density match the content type? (Data-dense UIs need tighter spacing; marketing pages need more air)
-
-**CRITICAL**: Layout problems are often the root cause of interfaces feeling "off" even when colors and fonts are fine. Space is a design material; use it with intention.
-
-## Plan Layout Improvements
-
-Consult the [spatial design reference](spatial-design.md) for detailed guidance on grids, rhythm, and container queries.
-
-Create a systematic plan:
-
-- **Spacing system**: Use a consistent scale (a framework's built-in scale like Tailwind's, rem-based tokens, or a custom system). The specific values matter less than consistency.
-- **Hierarchy strategy**: How will space communicate importance?
-- **Layout approach**: What structure fits the content? Flex for 1D, Grid for 2D, named areas for complex page layouts.
-- **Rhythm**: Where should spacing be tight vs generous?
-
-## Improve Layout Systematically
-
-### Establish a Spacing System
-
-- Use a consistent spacing scale (framework scales like Tailwind, rem-based tokens, or a custom scale all work). What matters is that values come from a defined set, not arbitrary numbers.
-- Name tokens semantically if using custom properties: `--space-xs` through `--space-xl`, not `--spacing-8`
-- Use `gap` for sibling spacing instead of margins; eliminates margin collapse hacks
-- Apply `clamp()` for fluid spacing that breathes on larger screens
-
-### Create Visual Rhythm
-
-- **Tight grouping** for related elements (8-12px between siblings)
-- **Generous separation** between distinct sections (48-96px)
-- **Varied spacing** within sections (not every row needs the same gap)
-- **Asymmetric compositions**: break the predictable centered-content pattern when it makes sense
-
-### Choose the Right Layout Tool
-
-- **Use Flexbox for 1D layouts**: Rows of items, nav bars, button groups, card contents, most component internals. Flex is simpler and more appropriate for the majority of layout tasks.
-- **Use Grid for 2D layouts**: Page-level structure, dashboards, data-dense interfaces, anything where rows AND columns need coordinated control.
-- **Don't default to Grid** when Flexbox with `flex-wrap` would be simpler and more flexible.
-- Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints.
-- Use named grid areas (`grid-template-areas`) for complex page layouts; redefine at breakpoints.
-
-### Break Card Grid Monotony
-
-- Don't default to card grids for everything; spacing and alignment create visual grouping naturally
-- Use cards only when content is truly distinct and actionable. Never nest cards inside cards
-- Vary card sizes, span columns, or mix cards with non-card content to break repetition
-
-### Strengthen Visual Hierarchy
-
-- Use the fewest dimensions needed for clear hierarchy. Space alone can be enough; generous whitespace around an element draws the eye. Some of the most polished designs achieve rhythm with just space and weight. Add color or size contrast only when simpler means aren't sufficient.
-- Be aware of reading flow: in LTR languages, the eye naturally scans top-left to bottom-right, but primary action placement depends on context (e.g., bottom-right in dialogs, top in navigation).
-- Create clear content groupings through proximity and separation.
-
-### Manage Depth & Elevation
-
-- Create a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip)
-- Build a consistent shadow scale (sm → md → lg → xl); shadows should be subtle
-- Use elevation to reinforce hierarchy, not as decoration
-
-### Optical Adjustments
-
-- If an icon looks visually off-center despite being geometrically centered, nudge it. But only if you're confident it actually looks wrong. Don't adjust speculatively.
-
-**NEVER**:
-- Use arbitrary spacing values outside your scale
-- Make all spacing equal (variety creates hierarchy)
-- Wrap everything in cards (not everything needs a container)
-- Nest cards inside cards (use spacing and dividers for hierarchy within)
-- Use identical card grids everywhere (icon + heading + text, repeated)
-- Center everything (left-aligned with asymmetry feels more designed)
-- Default to the hero metric layout (big number, small label, stats, gradient) as a template. If showing real user data, a prominent metric can work, but it should display actual data, not decorative numbers.
-- Default to CSS Grid when Flexbox would be simpler; use the simplest tool for the job
-- Use arbitrary z-index values (999, 9999); build a semantic scale
-
-## Verify Layout Improvements
-
-- **Squint test**: Can you identify primary, secondary, and groupings with blurred vision?
-- **Rhythm**: Does the page have a satisfying beat of tight and generous spacing?
-- **Hierarchy**: Is the most important content obvious within 2 seconds?
-- **Breathing room**: Does the layout feel comfortable, not cramped or wasteful?
-- **Consistency**: Is the spacing system applied uniformly?
-- **Responsiveness**: Does the layout adapt gracefully across screen sizes?
-
-When the rhythm and hierarchy land, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `density` param. Drive all spacing tokens in the variant's scoped CSS through `calc(var(--p-density, 1) * <base>)`: paddings, gaps, column widths. Users slide from airy to packed and see layout re-breathe with no regeneration.
-
-```json
-{"id":"density","kind":"range","min":0.6,"max":1.4,"step":0.05,"default":1,"label":"Density"}
-```
-
-For variants whose topology genuinely changes (stacked vs. side-by-side, grid vs. bento), use a `steps` param whose scoped CSS branches via `:scope[data-p-structure="X"]`. One structure param + one density param is a powerful combo; resist adding a third.
-
-```json
-{"id":"structure","kind":"steps","default":"grid","label":"Structure","options":[
- {"value":"stacked","label":"Stacked"},
- {"value":"grid","label":"Grid"},
- {"value":"bento","label":"Bento"}
-]}
-```
-
-See `reference/live.md` for the full params contract.
@@ -1,622 +0,0 @@
-Interactive live variant mode: select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via the dev server's HMR.
-
-## Prerequisites
-
-A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR a static HTML file open in the browser.
-
-## The contract (read once)
-
-Execute in order. No step skipped, no step reordered.
-
-1. `live.mjs`: boot.
-2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.
-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.
-5. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
-6. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
-7. On `exit`: run the cleanup at the bottom.
-
-Harness policy:
-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.
-- **Cursor**: run the poll in the **foreground** (blocking shell; not a background terminal, not a subagent). Cursor background terminals and subagents do not reliably resume the chat with poll stdout.
-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.
-- **Other harnesses**: foreground unless you know stdout reliably returns to this session.
-
-Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.
-
-## Start
-
-```bash
-node .qoder/skills/impeccable/scripts/live.mjs
-```
-
-Output JSON: `{ ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath, migrated }`. `pageFiles` is the list of HTML entries the live script was injected into. Keep PRODUCT.md and DESIGN.md in mind for variant generation; **DESIGN.md wins on visual decisions; PRODUCT.md wins on strategic/voice decisions.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt. If `migrated: true`, the loader auto-renamed legacy `.impeccable.md` to `PRODUCT.md`; mention this once and suggest `/impeccable document` for the matching DESIGN.md.
-
-`serverPort` and `serverToken` belong to the small **Impeccable live helper** HTTP server (serves `/live.js`, SSE, and `/poll`). That port is **not** your dev server and is usually not the URL you open to view the app. The browser page is whatever origin serves one of the `pageFiles` entries (Vite / Next / Bun / tunnel / LAN hostname).
-
-If output is `{ ok: false, error: "config_missing" | "config_invalid", path }`, this project hasn't been configured for live mode (or its config is stale). See **First-time setup** at the bottom.
-
-## Poll loop
-
-```
-LOOP:
- node .qoder/skills/impeccable/scripts/live-poll.mjs # default long timeout; no --timeout=
- Read JSON; dispatch on "type"
-
- "generate" → Handle Generate; reply done; LOOP
- "accept" → Handle Accept; complete carbonize cleanup if required; LOOP
- "discard" → Handle Discard; LOOP
- "prefetch" → Handle Prefetch; LOOP
- "timeout" → LOOP
- "exit" → break → Cleanup
-```
-
-## Recovery commands
-
-The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.
-
-Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:
-
-```bash
-node .qoder/skills/impeccable/scripts/live-status.mjs
-node .qoder/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID
-node .qoder/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID
-```
-
-- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.
-- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.
-- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.
-
-Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.
-
-## Handle `generate`
-
-Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.
-
-Speed matters; the user is watching a spinner. Minimize tool calls by using the `wrap` helper and writing all variants in a single edit.
-
-### 1. Read the screenshot (if present)
-
-`event.screenshotPath` is **only sent when the user placed at least one comment or stroke before Go.** When present, it's an absolute path to a PNG of the element as rendered with the annotations baked in. **Read it before planning**: annotations encode user intent not recoverable from `element.outerHTML` alone.
-
-When `screenshotPath` is absent, don't ask for one and don't go looking for the current rendering. The omission is deliberate: without annotations, a screenshot would anchor the model on the existing design and fight the three-distinct-directions brief. Work from `element.outerHTML`, the computed styles in `event.element`, and the freeform prompt if present.
-
-`event.comments` and `event.strokes` carry structured metadata alongside the visual. Treat the screenshot as primary; use the structured data for specifics worth quoting (e.g. the exact text of a comment).
-
-Reading annotations precisely:
-
-- **Comment position carries meaning.** Its `{x, y}` is element-local CSS px (same coord space as `element.boundingRect`). Find the child under that point and apply the comment text LOCALLY to that sub-element. A comment near the title is about the title, not a global description.
-- **Comments and strokes are independent annotations** unless clearly paired by overlap or tight proximity. Don't let the visual weight of a prominent stroke override the precise location of a textually-specific comment elsewhere.
-- **Strokes are gestures; read them by shape.** Closed loop = "this thing" (emphasis / focus); arrow = direction (move / point to); cross or slash = delete; free scribble = emphasis or delete depending on context. A loop around region X means "pay attention to X," not "only change pixels inside X."
-- **When a stroke's intent is ambiguous** (circle or arrow? emphasis or move?), state your reading in one sentence of rationale rather than silently guessing. If the uncertainty materially changes the brief, ask one short clarifying question before generating.
-
-### 2. Wrap the element
-
-```bash
-node .qoder/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"
-```
-
-Flag mapping. Keep them separate, don't collapse into `--query`:
-
-- `--element-id` ← `event.element.id`
-- `--classes` ← `event.element.classes` joined with commas
-- `--tag` ← `event.element.tagName`
-- `--text` ← first ~80 chars of `event.element.textContent` (trim, single-line). **Pass this every call.** When the picked element shares classes + tag with sibling components (a list of `<Card>`s, repeating sections), this is what disambiguates which branch in source to wrap. Without it, wrap silently lands on the first match and may rewrite the wrong element.
-
-The helper searches ID first, then classes, then tag + class combo. If `event.pageUrl` implies the file (e.g. `/` is usually `index.html`), pass `--file PATH` to skip the search. `--query` is a fallback for raw text search only; do not use it for normal element lookups.
-
-If `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.
-
-Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.
-
-`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:
-
-- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.
-- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.
-
-Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.
-
-**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:
-
-- `{ error: "file_is_generated", file, hint }`: user-supplied `--file` points at a generated file.
-- `{ error: "element_not_in_source", generatedMatch, hint }`: element exists only in a generated file (the next build would wipe any edits).
-- `{ error: "element_not_found", hint }`: element isn't in any project file; likely runtime-injected (JS component, dynamic render from data).
-
-All three carry `fallback: "agent-driven"`. Follow **Handle fallback** below.
-
-### 3. Load the action's reference
-
-If `event.action` is `impeccable` (the default freeform action), use SKILL.md's shared laws plus the loaded register reference (`brand.md` or `product.md`). Do not load a sub-command reference. **Freeform is not a pass to skip parameters:** you still follow the composition budget and the freeform bias in **§7 Parameters** below. Sub-command files list MUST-have signature knobs; freeform has no such file, so sizing knobs from surface weight and primary axes is entirely on you.
-
-Any other `event.action` (`bolder`, `quieter`, `distill`, `polish`, `typeset`, `colorize`, `layout`, `adapt`, `animate`, `delight`, `overdrive`): Read `reference/<action>.md` before planning. Each sub-command encodes a specific discipline; skipping its reference produces generic output. Those files may require specific params; layer them on top of the §7 budget, not instead of it.
-
-### 4. Plan three variants: identity first, then mode, then axes
-
-The wrong frame for live mode is "show three different design directions." Live runs on an existing surface; the brand has already been chosen. The job is variation **within identity**, not selection between identities. Failure mode: three editorial-typographic variants on a brief that wasn't editorial. Bigger failure mode: three off-brand variants the user can't accept because they don't look like their product.
-
-Four phases. Do them in order.
-
-#### Phase A: Extract the identity (non-skippable)
-
-The existing surface has an identity already. Read it before planning anything. Sources, in priority order:
-
-1. **DESIGN.md** if loaded: read the visual system fields (palette, type pairing, motion, components). This is the authoritative answer.
-2. **CSS custom properties** in the page's stylesheets (`:root { --color-...; --font-...; ... }`): these are de-facto tokens.
-3. **Computed styles** on the picked element and its parent: colors, fonts, spacing scales, corner radii.
-4. **Sibling components on the page**: what visual rhetoric do existing components use? (Asymmetric or centered? Dense or airy? Bold or quiet?)
-
-Write down what you see in **one sentence**. The sentence describes the surface that's actually on screen; it is not aspirational, not opinionated, not edited toward what the brand "should" be. Capture, in roughly this order:
-
-- The dominant surface color and accent color, by hex or token name (use the actual values, not categories like "warm" or "neutral").
-- The type pairing: the actual font names loaded, primary first.
-- The layout topology: how the dominant elements are arranged (stacked / side-by-side / grid / asymmetric / overlay).
-- The surface treatment: corners, borders, shadows, density of decoration.
-- The voice tone you read off the copy itself, not off the aesthetic feel.
-
-Be specific. "Modern" is not a color, "elegant" is not a type pairing, "clean" is not a layout. If you can't extract a real value for an axis, skip it rather than fabricate. The point is to record what is, not to describe what you wish it were.
-
-Do not include adjectives that name an aesthetic family ("editorial-leaning", "terminal-flavored", "brutalist"); those are conclusions, not data. They belong to Phase C lane selection in departure mode, not to identity description. Letting them sneak into Phase A is how the identity-lock collapses into a self-fulfilling prophecy.
-
-This sentence is the **identity lock**. Every variant must be readable as the same brand if rendered side by side. Skipping this phase is the primary cause of off-brand variants. Absence of DESIGN.md is never an excuse; extract from CSS and computed styles instead.
-
-#### Phase B: Pick mode (default vs departure)
-
-**Default mode**: the existing identity is preserved. Variants vary expression axes within it. *This is the right mode for ~90% of live sessions.* The user picked an element on a real product they're shipping; they expect variants of *their* hero, not three different brands' heroes.
-
-**Departure mode**: the existing identity is rejected. Variants propose alternatives consistent with PRODUCT.md voice. Trigger only when at least one is true:
-
-- PRODUCT.md anti-references explicitly call out the current surface ("the current `index.html` is itself an example"; "diffuse away from this"; "the page on screen is the failure"). Generic anti-references that describe what to avoid in general do **not** trigger departure mode; only ones that point at *this* surface specifically.
-- The user's freeform prompt explicitly asks for departure ("rebuild this from scratch", "what if it weren't editorial at all", "show me something completely different").
-
-If you're unsure, you're in default mode. The cost of being wrong about default is "three on-brand variants with similar feel": recoverable, the user picks none. The cost of being wrong about departure is "three off-brand variants": unrecoverable, the user is annoyed.
-
-#### Phase C: Plan three variants
-
-**Default mode.** Each variant commits to a different **primary axis** of difference, while preserving the identity sentence. The six axes:
-
-1. **Hierarchy**: which element commands the eye?
-2. **Layout topology**: stacked / side-by-side / grid / asymmetric / overlay
-3. **Typographic system**: pairing logic, scale ratio, case/weight strategy *within the available faces*
-4. **Color strategy**: which existing palette role carries the surface (Restrained / Committed / Full palette / Drenched). Use the brand's existing palette tokens, not new colors.
-5. **Density**: minimal / comfortable / dense
-6. **Structural decomposition**: merge, split, progressive disclosure
-
-Three variants → three DIFFERENT axes. The trio reads as *the same brand at three angles*. Do not introduce new fonts, new palette hues, or new aesthetic-family signals; those belong to departure mode.
-
-**While planning each variant, also name its 2–3 parameter knobs** (per the §7 budget table). Parameters are part of the design, not a decoration added afterward. If the variant explores density, expose a density knob. If it explores color commitment, expose a color-amount range. Deciding "what's tunable" during planning produces better knobs than retrofitting them onto finished HTML.
-
-**Departure mode.** Each variant anchors to a different **aesthetic direction**, derived from the brand's stated voice and register in PRODUCT.md. Do NOT pick from a fixed catalog of lane categories. The right three directions for this brand are not the same as the right three for another brand, and picking from a list is itself the training-data reflex (the model selects "Swiss-grid, Terminal, Industrial-signage" every time because those are the furthest-from-editorial items in any enumerated list).
-
-Instead, work from the brand:
-
-1. Read PRODUCT.md's Brand Personality words. What physical, spatial, or material experiences would embody those words if design were not involved? (A personality described as "specific, earned, unmistakable" evokes a hand-stamped letter, a numbered print, a watchmaker's loupe. A personality described as "restless, loud, unfiltered" evokes a concert poster, a spray-painted wall, a megaphone.)
-2. From those physical experiences, derive three visual directions that are genuinely different from each other AND from the current surface you're departing.
-3. Avoid the **reflex-reject lanes** in [brand.md](brand.md). Don't trade one monoculture for another. If you find yourself reaching for "Swiss-grid" or "Terminal" or "Industrial-signage" by reflex, you are pattern-matching a catalog in your training data, not reading the brand. Start over from the personality words.
-4. Each direction must be expressible in one concrete sentence that names a real-world referent ("a museum exhibition label system for a contemporary art gallery" not "clean and minimal"). If your sentence contains only adjectives, it's not concrete enough.
-5. **While planning each direction, also name its 2–3 parameter knobs** (per the §7 budget table). The same principle as default mode: decide "what's tunable" during planning, not after writing the HTML. A departure-mode hero with 0 parameters is not "bold creative vision," it's a missed opportunity for the user to fine-tune the direction they pick.
-
-#### Phase D: Squint test
-
-**Default mode squint.** Read each variant's identity sentence and compare to the locked identity from Phase A. If any variant has drifted to a different palette, type voice, or visual rhetoric, it has crossed into departure mode by accident; rework. Then check that each variant commits to a different primary axis. Three "tighter density" variants is failure.
-
-**Departure mode squint.** Two passes, family before sentence:
-
-1. **Family pass.** Label each variant with one design-family word of your own choosing (any concrete noun: *exhibition, storefront, cockpit, recipe-card, playbill, field-manual*). If any two variants share a label, or if the label could apply to the other variants equally well, rework. Do not use a fixed vocabulary list for the labels. *This pass is non-negotiable in departure mode and catches the monoculture failure that the sentence pass misses.*
-2. **Sentence pass.** Write three one-sentence descriptions side by side. If two of them rhyme ("both feature big type" / "both are stacks of sections" / "both center the CTA"), rework the offender.
-
-**When the primary axis is color or theme, forbid the trio from sharing theme + dominant hue.** Two dark-plus-one-dark is not distinct. Aim for three color worlds, not three shades of the same.
-
-**For action-specific invocations**, each variant must vary along the dimension the action names:
-
-- `bolder`: amplify a different dimension per variant (scale / saturation / structural change). Not three "slightly bigger" variants.
-- `quieter`: pull back a different dimension (color / ornament / spacing).
-- `distill`: remove a different class of excess (visual noise / redundant content / nested structure).
-- `polish`: target a different refinement axis (rhythm / hierarchy / micro-details like corner radii, focus states, optical kerning).
-- `typeset`: different type pairing AND different scale ratio each. Not three riffs on one pairing.
-- `colorize`: different hue family each (not shades of one hue). Vary chroma and contrast strategy.
-- `layout`: different structural arrangement (stacked / side-by-side / grid / asymmetric). Not spacing tweaks.
-- `adapt`: different target context per variant (mobile-first / tablet / desktop / print or low-data). Don't make three mobile layouts.
-- `animate`: different motion vocabulary (cascade stagger / clip wipe / scale-and-focus / morph / parallax). Not three staggered fades.
-- `delight`: different flavor of personality (unexpected micro-interaction / typographic surprise / illustrated accent / sonic-or-haptic moment / easter-egg interaction).
-- `overdrive`: different convention broken (scale / structure / motion / input model / state transitions). Skip `overdrive.md`'s "propose and ask" step; live mode is non-interactive.
-
-### 5. Apply the freeform prompt (if present)
-
-`event.freeformPrompt` is the user's ceiling on direction (all variants must honor it), but still explore meaningfully different *interpretations*. The interpretations stay within whichever mode you picked in Phase B.
-
-In **default mode**, the prompt narrows the axes you choose, not the identity. *"Make it feel more confident"* → variant 1 amplifies hierarchy (one element commands the eye), variant 2 commits the existing accent color (Committed strategy on the brand's hue), variant 3 tightens density and removes decorative slack. Three different axes, same brand.
-
-In **departure mode**, the prompt narrows the lanes you draw from, not the families. *"Make it feel like a newspaper front page"* would itself be a departure-mode prompt; honor it but pick three meaningfully different newspaper-adjacent lanes (broadsheet vs. tabloid vs. trade journal), and run the family pass to confirm they don't collapse into one.
-
-When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.
-
-### 6. Write all variants in a single edit
-
-Complete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).
-
-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).
-
-Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:
-
-```html
-<!-- Variants: insert below this line -->
-<style data-impeccable-css="SESSION_ID">
- /* rules matching cssAuthoring.rulePattern */
-</style>
-<div data-impeccable-variant="1">
- <!-- variant 1: full element replacement (single top-level element) -->
-</div>
-<div data-impeccable-variant="2" style="display: none">
- <!-- variant 2: full element replacement -->
-</div>
-<div data-impeccable-variant="3" style="display: none">
- <!-- variant 3: full element replacement -->
-</div>
-```
-
-**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.
-
-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.
-
-One edit, all variants; the browser's MutationObserver picks everything up in one pass.
-
-For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.
-
-**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:
-
-```tsx
-<style data-impeccable-css="SESSION_ID">{`
- @scope ([data-impeccable-variant="1"]) { ... }
- @scope ([data-impeccable-variant="2"]) { ... }
-`}</style>
-<div data-impeccable-variant="1">
- {/* variant 1 */}
-</div>
-<div data-impeccable-variant="2" style={{ display: 'none' }}>
- {/* variant 2 */}
-</div>
-```
-
-The wrap script already gives you a single-rooted JSX wrapper: a `<div data-impeccable-variants="…">` outer element with the marker comments tucked inside. Drop the variants block above into the "Variants: insert below this line" comment and the source stays valid TSX.
-
-### 7. Parameters (composition-sized, 0–4 per variant)
-
-Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement. The browser docks a small panel to the right of the outline with one control per parameter. The user drags/clicks and sees instant feedback: there is zero regeneration cost because the knob toggles a CSS variable or data attribute that the variant's scoped CSS is already authored against.
-
-**What “optional” does not mean.** Parameters are not nice-to-have decoration on large work. The word meant “omit controls that are redundant or cosmetic,” not “default to zero because three variants were enough work.”
-
-**When to add.** As soon as the variant’s scoped CSS has a meaningful continuous or stepped axis: density, color amount, type scale, motion intensity, column weight, and so on. If you can imagine the user muttering “a bit tighter” or “a touch more accent” **without** wanting a full regeneration, wire that axis. **Not** micro-margins or one-off nudges; those are not parameters.
-
-**Freeform (`action` is `impeccable`) bias.** You did not load a sub-command reference, so you must **choose** signature axes yourself. Match the budget table: for a hero or large composition, that means **2–3 axes per variant**, not 1. Prefer knobs that sit on the dimensions where your three variants actually differ (if density varies, expose it as a `steps` knob; if color commitment varies, expose it as a `range`). A hero that ships with **0** params is almost always a mistake, not a judgment call. A hero with exactly **1** param is underweight unless the design is genuinely a fixed-point comparison. Start from the budget table, not from zero.
-
-**Budget scales with the element's visual weight, not token budget.** Knobs need real estate to read as tunable; three sliders on a single control are noise.
-
-- **Leaf / tiny**: a single button, icon, input, bare heading, solitary paragraph: **0 params.**
-- **Small composition**: labeled input, simple card, short callout (≤ ~5 visual children): **0–1** params when one dominant axis is obvious; otherwise **0.**
-- **Medium composition**: section component, nav cluster, dense card, short feature block (6–15 visual children): **target 2**; **1** is acceptable if the block is simple; **0** only when variants are truly fixed points.
-- **Large composition**: hero section, full page region, spread layout, strong internal structure (16+ visual children or multiple sub-sections): **target 2–3**; **up to 4** when several independent axes (e.g. structure `steps` + `density` + one accent) are all authored in scoped CSS.
-
-**When in doubt, ask whether a dial exists before defaulting to zero.** The user can always request more variants, but the point of live mode is instant tuning without another Go. Crowding the panel is bad; **under-shipping** knobs on a dense composition is the more common failure for freeform. Count by **visual** children, not DOM depth; a shallow-but-wide hero is still large.
-
-**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.
-
-**How to declare.** Put a JSON manifest on the variant wrapper:
-
-```html
-<div data-impeccable-variant="1" data-impeccable-params='[
- {"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"},
- {"id":"density","kind":"steps","default":"snug","label":"Density","options":[
- {"value":"airy","label":"Airy"},
- {"value":"snug","label":"Snug"},
- {"value":"packed","label":"Packed"}
- ]},
- {"id":"serif","kind":"toggle","default":false,"label":"Serif display"}
-]'>
- ...variant content...
-</div>
-```
-
-**Three kinds:**
-
-- `range`: smooth slider. Drives a CSS custom property `--p-<id>` on the variant wrapper. Author CSS with `var(--p-color-amount, 0.5)`. Fields: `min`, `max`, `step`, `default` (number), `label`.
-- `steps`: segmented radio. Drives a data attribute `data-p-<id>` on the variant wrapper. Author CSS with `:scope[data-p-density="airy"] .grid { ... }`. Fields: `options` (array of `{value, label}`), `default` (string), `label`.
-- `toggle`: on/off switch. Drives BOTH a CSS var (`--p-<id>: 0|1`) and a data attribute (present when on, absent when off). Use whichever is more convenient. Fields: `default` (boolean), `label`.
-
-**Signature params per action.** For named sub-commands, read that action’s `reference/<action>.md` for one or two **MUST** params (e.g. `layout` → `density`). Those are non-negotiable when the design can express them. **Freeform has no file-level MUST**; the **Freeform (`impeccable`) bias** in this section is the stand-in. If the user’s action is both stylized and sub-command (e.g. `colorize`), the sub-command’s MUST list takes precedence for its axes; still respect the **Hard cap** and add no redundant duplicate knobs.
-
-**Reset on variant switch.** User dials density on v1, flips to v2, v2 starts at v2's declared defaults. Known limitation; preservation across variants may land later.
-
-**On accept**, the browser sends the user's current values in the accept event. `live-accept.mjs` writes them as a sibling comment:
-
-```html
-<!-- impeccable-param-values SESSION_ID: {"color-amount":0.7,"density":"packed"} -->
-```
-
-The carbonize cleanup step (see below) reads that comment and bakes the chosen values into the final CSS. For `steps`/`toggle` attribute selectors: keep only the branch matching the chosen value, drop the others, collapse `:scope[data-p-density="packed"] .grid` to a semantic class rule. For `range` vars: either substitute the literal or keep the var with the chosen value as its new default.
-
-### 8. Signal done
-
-```bash
-node .qoder/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
-```
-
-`RELATIVE_PATH` is relative to project root (`public/index.html`, `src/App.tsx`, etc.); the browser fetches source directly if the dev server lacks HMR.
-
-Then run `live-poll.mjs` again immediately.
-
-### Aborting an in-flight session
-
-If wrap or generation fails after the browser has flipped to GENERATING (e.g. wrap landed on the wrong source branch and you've already reverted it, or generation hit an unrecoverable error), tell the **browser** so its bar resets to PICKING:
-
-```bash
-node .qoder/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID error "Short reason"
-```
-
-Don't run `live-accept --discard` for this; that's a pure file mutator, the browser doesn't see it, and the bar gets stuck on the GENERATING dots forever (the user has to refresh). `--discard` is only correct when the **browser** initiated the discard (user clicked ✕ during CYCLING) and the agent is just running source-side cleanup the browser already triggered.
-
-## Handle fallback
-
-When wrap returns `fallback: "agent-driven"`, the deterministic flow doesn't apply. Pick up here.
-
-The goal is the same: give the user three variants to choose from AND persist the accepted one in a place the next build won't wipe. The difference is that you have to pick the right source file yourself.
-
-### Step 1: Identify where the element actually lives
-
-Use the error payload:
-
-- `element_not_in_source` with `generatedMatch: "public/docs/foo.html"`: the served HTML is generated. Find the generator (grep for writers of that path, e.g. `scripts/build-sub-pages.js`, an Astro/Next template) and locate the template or partial that emits this element.
-- `element_not_found`: the element is runtime-injected. Look for the component that renders it (React/Vue/Svelte), the JS that assembles it, or the data source that feeds it.
-- `file_is_generated` with `file: "..."`: user pointed at a generated file explicitly. Same resolution as `element_not_in_source`.
-
-Read the candidate source until you're confident where a change to the element would belong. If the change is purely visual, that source might be a shared stylesheet, not the template.
-
-### Step 2: Show three variants in the DOM for preview
-
-The browser bar is waiting for variants. Even without a wrapper in source, you still need to show something:
-
-1. Manually write the wrapper scaffold into the **served** file (the one the browser actually loaded). Use the same structure `live-wrap.mjs` produces; `<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents">…</div><!-- end -->`.
-2. Insert your three variant divs inside it, same shape as the deterministic path.
-3. Signal done with `--reply EVENT_ID done --file <served file>`. The browser's no-HMR fallback will fetch and inject.
-
-This served-file edit is **temporary**: next regen wipes it, and that's fine. The real work happens on accept.
-
-### Step 3: On accept, write to true source
-
-When the accept event arrives (`_acceptResult.handled` will usually be `false` here because accept also refuses to persist into generated files; see Handle accept for the carbonize branch), extract the accepted variant's content and write it into the source you identified in Step 1:
-
-- Structural change → edit the template / component source.
-- Visual-only change → add or update rules in the appropriate stylesheet; remove the inline `<style>` scope.
-- Dynamic from data → update the data source or the render logic.
-
-Then remove the temporary wrapper from the served file if it's still there.
-
-### Step 4: On discard, clean up the served file
-
-Remove the wrapper you inserted in Step 2. Nothing else to do.
-
-## Handle `accept`
-
-Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.
-
-- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.
-- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.
-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.
-- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.
-- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.
-
-### Required after accept (carbonize)
-
-When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.
-
-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.
-
-1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.
-2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).
-3. **Bake in parameter values while rewriting selectors.** For `@scope ([data-impeccable-variant="N"])` wrappers: retarget to real, semantic classes on the accepted HTML (`.why-visual--v2 .v2-label { … }`). For `:scope[data-p-<id>="VALUE"]` selectors: keep only the branch matching the chosen value from the param-values comment; drop the others (they're dead after accept). For `var(--p-<id>, DEFAULT)` in the CSS: either substitute the literal value, or if the param is still useful as a knob going forward, leave the var and update its initial declaration to the chosen value.
-4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; those are live-mode plumbing, not source.
-5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.
-
-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.
-
-A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.
-
-## Handle `discard`
-
-Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.
-
-## Handle `prefetch`
-
-Event: `{pageUrl}`. The browser fires this the first time the user selects an element on a given route, as a latency shortcut; it signals the user is likely about to Go on a page you haven't read yet.
-
-Resolve `pageUrl` to the underlying file:
-
-- Root `/` → the `pageFile` returned by `live.mjs` (usually `public/index.html` or equivalent).
-- Sub-routes (e.g. `/docs`, `/docs/live`) → the generated or source file for that route. Use your knowledge of the project layout (multi-page static sites often resolve `/foo` → `public/foo/index.html`; SPAs may map all routes to a single entry).
-
-Read the file into context, then poll again. No `--reply`: this is speculative pre-work; Go will come later. If you can't confidently resolve the route to a file, skip and poll again.
-
-Dedupe is the browser's job (one prefetch per unique pathname per session); trust it. If the same file shows up twice from different routes mapping to the same file, the second Read is cached anyway.
-
-## Exit
-
-The user can stop live mode by:
-- Saying "stop live mode" / "exit live" in chat
-- Closing the browser tab (SSE drops, poll returns `exit` after 8s)
-- The browser's exit button
-
-When the poll returns `exit`, proceed to cleanup. If the poll is still running as a background task, kill it first.
-
-## Cleanup
-
-```bash
-node .qoder/skills/impeccable/scripts/live-server.mjs stop
-```
-
-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.
-
-Then:
-- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).
-- Remove any leftover carbonize blocks (search for `impeccable-carbonize-start` markers).
-
-## First-time setup (config missing or invalid)
-
-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.
-
-Schema:
-
-```json
-{
- "files": ["<path-or-glob>", "<path-or-glob>", ...],
- "exclude": ["<optional-glob>", ...],
- "insertBefore": "</body>",
- "commentSyntax": "html",
- "cspChecked": true
-}
-```
-
-`files` is the inject target; **the HTML files the browser actually loads**, not necessarily source. Each entry is either a literal path (`"public/index.html"`) or a glob pattern (`"public/**/*.html"`). Tracked or generated doesn't matter here; wrap has its own generated-file guard and routes accepts through the fallback flow.
-
-`exclude` (optional) is a list of glob patterns matching files to skip, even if a `files` glob would have included them. Use for email templates, demo fixtures, or any HTML that isn't a live page.
-
-`cspChecked` tracks whether the CSP detection step below has already run. Absent on first setup; set to `true` after CSP is checked (whether patched, declined, or not needed).
-
-**Hard-excluded paths (cannot be overridden).** `**/node_modules/**` and `**/.git/**` are never matched regardless of what the user writes. These are vendor/metadata directories and injecting into them would silently instrument third-party code.
-
-**Glob syntax.** `**` matches any number of path segments (including zero), `*` matches any characters except `/`, `?` matches a single character except `/`. Paths are always relative to the project root with forward slashes.
-
-| Framework | `files` | `insertBefore` | `commentSyntax` |
-|-----------|---------|----------------|-----------------|
-| SPA with single shell (Vite / React / Plain HTML) | `["index.html"]` | `</body>` | `html` |
-| Next.js (App Router) | `["app/layout.tsx"]` | `</body>` | `jsx` |
-| Next.js (Pages) | `["pages/_document.tsx"]` | `</body>` | `jsx` |
-| Nuxt | `["app.vue"]` | `</body>` | `html` |
-| Svelte / SvelteKit | `["src/app.html"]` | `</body>` | `html` |
-| Astro | `[" <root layout .astro>"]` | `</body>` | `html` |
-| Multi-page (separate HTML per route) | `["public/**/*.html"]`: a glob covering the served directory | `</body>` | `html` |
-
-Pick an anchor that exists in every file (`</body>` almost always works). Use `insertAfter` if the anchor should match **after** a specific line.
-
-For multi-page sites, **prefer a glob over a literal file list**. New pages added later are picked up automatically on the next `live-inject.mjs` run; no config maintenance needed.
-
-For multi-page sites whose pages are *rebuilt* by a generator (Astro, static-site generators, custom scripts like `build-sub-pages.js`), the inject survives only until the next regeneration. Re-run `live.mjs` after each build. Accept is unaffected; it writes to true source via the fallback flow.
-
-### Drift-heal warning
-
-On every `live.mjs` boot, after inject, the project is scanned for HTML files under common page-source roots (`public/`, `src/`, `app/`, `pages/`). If any exist that aren't covered by the resolved `files` list, the output includes a `configDrift` field:
-
-```json
-{
- "ok": true,
- "serverPort": 8400,
- "pageFiles": [ "..." ],
- "configDrift": {
- "orphans": ["public/new-section/index.html", "public/docs/new-command.html"],
- "orphanCount": 2,
- "hint": "2 HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like \"public/**/*.html\"."
- }
-}
-```
-
-When `configDrift` is present, surface it to the user once per session before entering the poll loop:
-
-> Noticed N HTML file(s) in the project that aren't in `config.files`:
->
-> - `public/new-section/index.html`
-> - `public/docs/new-command.html`
->
-> Add them, or switch `files` to a glob like `["public/**/*.html"]` and let it track new pages automatically?
-
-Don't auto-update the config; let the user decide. `configDrift` is `null` when there's no drift.
-
-### CSP detection (first-time only)
-
-If `config.cspChecked === true`, skip this entire section. You already asked this user once; the answer sticks.
-
-Otherwise, run the detection helper:
-
-```bash
-node .qoder/skills/impeccable/scripts/detect-csp.mjs
-```
-
-Output: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.
-
-- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.
-- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:
- - Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)
- - SvelteKit `kit.csp.directives`
- - Nuxt `nuxt-security` module's `contentSecurityPolicy`
-- **`append-string`**: CSP written as a literal value string. Auto-patchable. See *append-string* below. Covers:
- - Inline `next.config.*` `headers()` with a CSP literal
- - Nuxt `routeRules` / `nitro.routeRules` headers
-- **`middleware`** or **`meta-tag`**: rarer. Detected but not auto-patched in v1. Show the user the detected files and ask them to add `http://localhost:8400` to `script-src` and `connect-src` manually, then mark `cspChecked: true` and proceed.
-
-#### Consent prompt template
-
-Use this phrasing so the experience is consistent across agents:
-
-> **CSP patch needed.** I detected a Content Security Policy in your project that blocks `http://localhost:8400`: the live picker won't load without an allowance. Here's the change I'd make:
->
-> ```diff
-> [file: <patchTarget>]
-> [exact diff, 2–5 lines]
-> ```
->
-> It's guarded by `NODE_ENV === "development"` so the extra entry only appears in dev and never reaches production. You can remove it any time by reverting this file. Apply? [y/n]
-
-On "no": skip the patch, mention live won't work until the user adds the allowance manually, still write `cspChecked: true` (the question's been asked).
-
-On "yes": apply the Shape-specific patch below, then write `cspChecked: true`.
-
-#### append-arrays
-
-CSP expressed as structured directive arrays. Patch mechanism: declare a dev-only array, spread it into the script-src and connect-src arrays.
-
-**Declare near the top of the file that holds the CSP arrays:**
-
-```ts
-// Dev-only allowance so impeccable live mode can load. Guarded by NODE_ENV.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? ["http://localhost:8400"] : [];
-```
-
-**Append `...__impeccableLiveDev` to the script-src and connect-src directive arrays.** Per-framework specifics:
-
-- **Next.js + monorepo helper**: edit the *app's* `next.config.*` (not the shared helper), appending to `additionalScriptSrc` and `additionalConnectSrc` passed into `createBaseNextConfig` (or equivalent). Keeps the shared package clean.
-- **SvelteKit**: edit `svelte.config.js`, appending to `kit.csp.directives['script-src']` and `kit.csp.directives['connect-src']`.
-- **Nuxt + nuxt-security**: edit `nuxt.config.*`, appending to `security.headers.contentSecurityPolicy['script-src']` and `['connect-src']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-turborepo/expected-after-patch.ts` (Next.js)
-- `tests/framework-fixtures/sveltekit-csp/expected-after-patch.js` (SvelteKit)
-
-Idempotency: if `__impeccableLiveDev` already exists in the file, the patch is already applied; skip asking and just mark `cspChecked: true`.
-
-#### append-string
-
-CSP built as a literal value string. Two-point patch: declare a dev-only string near the top, interpolate it into the CSP at the `script-src` and `connect-src` directives.
-
-```ts
-// Dev-only allowance so impeccable live mode can load.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? " http://localhost:8400" : "";
-```
-
-Then in the CSP value string:
-- `script-src 'self' 'unsafe-inline'` → `` `script-src 'self' 'unsafe-inline'${__impeccableLiveDev}` ``
-- `connect-src 'self'` → `` `connect-src 'self'${__impeccableLiveDev}` ``
-
-(Leading space on the dev string so it concatenates cleanly into the existing value. Convert the literal CSP directives into template strings as part of the edit if they aren't already.)
-
-Per-framework specifics:
-- **Next.js inline `headers()`**: edit `next.config.*`, splicing the variable into the CSP value.
-- **Nuxt `routeRules`**: edit `nuxt.config.*`, splicing into the CSP in `routeRules['/**'].headers['Content-Security-Policy']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-inline-csp/expected-after-patch.js` (Next.js)
-- `tests/framework-fixtures/nuxt-csp/expected-after-patch.ts` (Nuxt)
-
-### Troubleshooting
-
-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.
-
-Then re-run `live.mjs`.
@@ -1,109 +0,0 @@
-# Motion Design
-
-## Duration: The 100/300/500 Rule
-
-Timing matters more than easing. These durations feel right for most UI:
-
-| Duration | Use Case | Examples |
-|----------|----------|----------|
-| **100-150ms** | Instant feedback | Button press, toggle, color change |
-| **200-300ms** | State changes | Menu open, tooltip, hover states |
-| **300-500ms** | Layout changes | Accordion, modal, drawer |
-| **500-800ms** | Entrance animations | Page load, hero reveals |
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-## Easing: Pick the Right Curve
-
-**Don't use `ease`.** It's a compromise that's rarely optimal. Instead:
-
-| Curve | Use For | CSS |
-|-------|---------|-----|
-| **ease-out** | Elements entering | `cubic-bezier(0.16, 1, 0.3, 1)` |
-| **ease-in** | Elements leaving | `cubic-bezier(0.7, 0, 0.84, 0)` |
-| **ease-in-out** | State toggles (there → back) | `cubic-bezier(0.65, 0, 0.35, 1)` |
-
-**For micro-interactions, use exponential curves.** They feel natural because they mimic real physics (friction, deceleration):
-
-```css
-/* Quart out - smooth, refined (recommended default) */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1);
-
-/* Quint out - slightly more dramatic */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1);
-
-/* Expo out - snappy, confident */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1);
-```
-
-**Avoid bounce and elastic curves.** They were trendy in 2015 but now feel tacky and amateurish. Real objects don't bounce when they stop; they decelerate smoothly. Overshoot effects draw attention to the animation itself rather than the content.
-
-## Premium Motion Materials
-
-Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties: blur reveals, backdrop-filter panels, saturation or brightness shifts, shadow bloom, SVG filters, masks, clip paths, gradient-position movement, and variable font or shader-driven effects.
-
-Use the right material for the effect:
-
-- **Transform / opacity**: movement, press feedback, simple reveals, list choreography.
-- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances, atmospheric transitions.
-- **Clip path / masks**: wipes, reveals, editorial cropping, product-like transitions.
-- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state.
-- **Grid-template rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly.
-
-The hard rule is not "transform and opacity only." The hard rule is: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify in-browser that the result is smooth on the target viewports. If blur/filter makes the interaction feel significantly more premium and remains smooth, use it.
-
-## Staggered Animations
-
-Use CSS custom properties for cleaner stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"` on each item. **Cap total stagger time**: 10 items at 50ms = 500ms total. For many items, reduce per-item delay or cap staggered count.
-
-## Reduced Motion
-
-This is not optional. Vestibular disorders affect ~35% of adults over 40.
-
-```css
-/* Define animations normally */
-.card {
- animation: slide-up 500ms ease-out;
-}
-
-/* Provide alternative for reduced motion */
-@media (prefers-reduced-motion: reduce) {
- .card {
- animation: fade-in 200ms ease-out; /* Crossfade instead of motion */
- }
-}
-
-/* Or disable entirely */
-@media (prefers-reduced-motion: reduce) {
- *, *::before, *::after {
- animation-duration: 0.01ms !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**What to preserve**: Functional animations like progress bars, loading spinners (slowed down), and focus indicators should still work, just without spatial movement.
-
-## Perceived Performance
-
-**Nobody cares how fast your site is, just how fast it feels.** Perception can be as effective as actual performance.
-
-**The 80ms threshold**: Our brains buffer sensory input for ~80ms to synchronize perception. Anything under 80ms feels instant and simultaneous. This is your target for micro-interactions.
-
-**Active vs passive time**: Passive waiting (staring at a spinner) feels longer than active engagement. Strategies to shift the balance:
-
-- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening.
-- **Early completion**: Show content progressively, don't wait for everything. Video buffering, progressive images, streaming HTML.
-- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Instagram likes work offline; the UI updates instantly, syncs later. Use for low-stakes actions; avoid for payments or destructive operations.
-
-**Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances, but ease-in toward a task's end compresses perceived time.
-
-**Caution**: Too-fast responses can decrease perceived value. Users may distrust instant results for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
-
-## Performance
-
-Don't use `will-change` preemptively, only when animation is imminent (`:hover`, `.animating`). For scroll-triggered animations, use Intersection Observer instead of scroll events; unobserve after animating once. Create motion tokens for consistency (durations, easings, common transitions).
-
----
-
-**Avoid**: Animating everything (animation fatigue is real). Using >500ms for UI feedback. Ignoring `prefers-reduced-motion`. Using animation to hide slow loading.
@@ -1,234 +0,0 @@
-> **Additional context needed**: the "aha moment" you want users to reach, and users' experience level.
-
-Get users to first value as fast as possible. Onboarding's job is not to teach the product. Its job is to get people to the moment that proves the product is worth their time.
-
-## Assess Onboarding Needs
-
-Understand what users need to learn and why:
-
-1. **Identify the challenge**:
- - What are users trying to accomplish?
- - What's confusing or unclear about current experience?
- - Where do users get stuck or drop off?
- - What's the "aha moment" we want users to reach?
-
-2. **Understand the users**:
- - What's their experience level? (Beginners, power users, mixed?)
- - What's their motivation? (Excited and exploring? Required by work?)
- - What's their time commitment? (5 minutes? 30 minutes?)
- - What alternatives do they know? (Coming from competitor? New to category?)
-
-3. **Define success**:
- - What's the minimum users need to learn to be successful?
- - What's the key action we want them to take? (First project? First invite?)
- - How do we know onboarding worked? (Completion rate? Time to value?)
-
-**CRITICAL**: Onboarding should get users to value as quickly as possible, not teach everything possible.
-
-## Onboarding Principles
-
-Follow these core principles:
-
-### Show, Don't Tell
-- Demonstrate with working examples, not just descriptions
-- Provide real functionality in onboarding, not separate tutorial mode
-- Use progressive disclosure, teach one thing at a time
-
-### Make It Optional (When Possible)
-- Let experienced users skip onboarding
-- Don't block access to product
-- Provide "Skip" or "I'll explore on my own" options
-
-### Time to Value
-- Get users to their "aha moment" ASAP
-- Front-load most important concepts
-- Teach 20% that delivers 80% of value
-- Save advanced features for contextual discovery
-
-### Context Over Ceremony
-- Teach features when users need them, not upfront
-- Empty states are onboarding opportunities
-- Tooltips and hints at point of use
-
-### Respect User Intelligence
-- Don't patronize or over-explain
-- Be concise and clear
-- Assume users can figure out standard patterns
-
-## Design Onboarding Experiences
-
-Create appropriate onboarding for the context:
-
-### Initial Product Onboarding
-
-**Welcome Screen**:
-- Clear value proposition (what is this product?)
-- What users will learn/accomplish
-- Time estimate (honest about commitment)
-- Option to skip (for experienced users)
-
-**Account Setup**:
-- Minimal required information (collect more later)
-- Explain why you're asking for each piece of information
-- Smart defaults where possible
-- Social login when appropriate
-
-**Core Concept Introduction**:
-- Introduce 1-3 core concepts (not everything)
-- Use simple language and examples
-- Interactive when possible (do, don't just read)
-- Progress indication (step 1 of 3)
-
-**First Success**:
-- Guide users to accomplish something real
-- Pre-populated examples or templates
-- Celebrate completion (but don't overdo it)
-- Clear next steps
-
-### Feature Discovery & Adoption
-
-**Empty States**:
-Instead of blank space, show:
-- What will appear here (description + screenshot/illustration)
-- Why it's valuable
-- Clear CTA to create first item
-- Example or template option
-
-Example:
-```
-No projects yet
-Projects help you organize your work and collaborate with your team.
-[Create your first project] or [Start from template]
-```
-
-**Contextual Tooltips**:
-- Appear at relevant moment (first time user sees feature)
-- Point directly at relevant UI element
-- Brief explanation + benefit
-- Dismissable (with "Don't show again" option)
-- Optional "Learn more" link
-
-**Feature Announcements**:
-- Highlight new features when they're released
-- Show what's new and why it matters
-- Let users try immediately
-- Dismissable
-
-**Progressive Onboarding**:
-- Teach features when users encounter them
-- Badges or indicators on new/unused features
-- Unlock complexity gradually (don't show all options immediately)
-
-### Guided Tours & Walkthroughs
-
-**When to use**:
-- Complex interfaces with many features
-- Significant changes to existing product
-- Industry-specific tools needing domain knowledge
-
-**How to design**:
-- Spotlight specific UI elements (dim rest of page)
-- Keep steps short (3-7 steps max per tour)
-- Allow users to click through tour freely
-- Include "Skip tour" option
-- Make replayable (help menu)
-
-**Best practices**:
-- Interactive over passive (let users click real buttons)
-- Focus on workflow, not features ("Create a project" not "This is the project button")
-- Provide sample data so actions work
-
-### Interactive Tutorials
-
-**When to use**:
-- Users need hands-on practice
-- Concepts are complex or unfamiliar
-- High stakes (better to practice in safe environment)
-
-**How to design**:
-- Sandbox environment with sample data
-- Clear objectives ("Create a chart showing sales by region")
-- Step-by-step guidance
-- Validation (confirm they did it right)
-- Graduation moment (you're ready!)
-
-### Documentation & Help
-
-**In-product help**:
-- Contextual help links throughout interface
-- Keyboard shortcut reference
-- Search-able help center
-- Video tutorials for complex workflows
-
-**Help patterns**:
-- `?` icon near complex features
-- "Learn more" links in tooltips
-- Keyboard shortcut hints (`⌘K` shown on search box)
-
-## Empty State Design
-
-Every empty state needs:
-
-### What Will Be Here
-"Your recent projects will appear here"
-
-### Why It Matters
-"Projects help you organize your work and collaborate with your team"
-
-### How to Get Started
-[Create project] or [Import from template]
-
-### Visual Interest
-Illustration or icon (not just text on blank page)
-
-### Contextual Help
-"Need help getting started? [Watch 2-min tutorial]"
-
-**Empty state types**:
-- **First use**: Never used this feature (emphasize value, provide template)
-- **User cleared**: Intentionally deleted everything (light touch, easy to recreate)
-- **No results**: Search or filter returned nothing (suggest different query, clear filters)
-- **No permissions**: Can't access (explain why, how to get access)
-- **Error state**: Failed to load (explain what happened, retry option)
-
-## Implementation Patterns
-
-### Technical approaches:
-
-**Tooltip libraries**: Tippy.js, Popper.js
-**Tour libraries**: Intro.js, Shepherd.js, React Joyride
-**Modal patterns**: Focus trap, backdrop, ESC to close
-**Progress tracking**: LocalStorage for "seen" states
-**Analytics**: Track completion, drop-off points
-
-**Storage patterns**:
-```javascript
-// Track which onboarding steps user has seen
-localStorage.setItem('onboarding-completed', 'true');
-localStorage.setItem('feature-tooltip-seen-reports', 'true');
-```
-
-**IMPORTANT**: Don't show same onboarding twice (annoying). Track completion and respect dismissals.
-
-**NEVER**:
-- Force users through long onboarding before they can use product
-- Patronize users with obvious explanations
-- Show same tooltip repeatedly (respect dismissals)
-- Block all UI during tour (let users explore)
-- Create separate tutorial mode disconnected from real product
-- Overwhelm with information upfront (progressive disclosure!)
-- Hide "Skip" or make it hard to find
-- Forget about returning users (don't show initial onboarding again)
-
-## Verify Onboarding Quality
-
-Test with real users:
-
-- **Time to completion**: Can users complete onboarding quickly?
-- **Comprehension**: Do users understand after completing?
-- **Action**: Do users take desired next step?
-- **Skip rate**: Are too many users skipping? (Maybe it's too long or not valuable)
-- **Completion rate**: Are users completing? (If low, simplify)
-- **Time to value**: How long until users get first value?
-
-When users hit the aha moment fast and don't drop off, hand off to `/impeccable polish` for the final pass.
@@ -1,258 +0,0 @@
-Performance is a feature. Identify the actual bottleneck for THIS interface, fix it, then measure. Don't optimize what isn't slow.
-
-## Assess Performance Issues
-
-Understand current performance and identify problems:
-
-1. **Measure current state**:
- - **Core Web Vitals**: LCP, FID/INP, CLS scores
- - **Load time**: Time to interactive, first contentful paint
- - **Bundle size**: JavaScript, CSS, image sizes
- - **Runtime performance**: Frame rate, memory usage, CPU usage
- - **Network**: Request count, payload sizes, waterfall
-
-2. **Identify bottlenecks**:
- - What's slow? (Initial load? Interactions? Animations?)
- - What's causing it? (Large images? Expensive JavaScript? Layout thrashing?)
- - How bad is it? (Perceivable? Annoying? Blocking?)
- - Who's affected? (All users? Mobile only? Slow connections?)
-
-**CRITICAL**: Measure before and after. Premature optimization wastes time. Optimize what actually matters.
-
-## Optimization Strategy
-
-Create systematic improvement plan:
-
-### Loading Performance
-
-**Optimize Images**:
-- Use modern formats (WebP, AVIF)
-- Proper sizing (don't load 3000px image for 300px display)
-- Lazy loading for below-fold images
-- Responsive images (`srcset`, `picture` element)
-- Compress images (80-85% quality is usually imperceptible)
-- Use CDN for faster delivery
-
-```html
-<img
- src="hero.webp"
- srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
- sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
- loading="lazy"
- alt="Hero image"
-/>
-```
-
-**Reduce JavaScript Bundle**:
-- Code splitting (route-based, component-based)
-- Tree shaking (remove unused code)
-- Remove unused dependencies
-- Lazy load non-critical code
-- Use dynamic imports for large components
-
-```javascript
-// Lazy load heavy component
-const HeavyChart = lazy(() => import('./HeavyChart'));
-```
-
-**Optimize CSS**:
-- Remove unused CSS
-- Critical CSS inline, rest async
-- Minimize CSS files
-- Use CSS containment for independent regions
-
-**Optimize Fonts**:
-- Use `font-display: swap` or `optional`
-- Subset fonts (only characters you need)
-- Preload critical fonts
-- Use system fonts when appropriate
-- Limit font weights loaded
-
-```css
-@font-face {
- font-family: 'CustomFont';
- src: url('/fonts/custom.woff2') format('woff2');
- font-display: swap; /* Show fallback immediately */
- unicode-range: U+0020-007F; /* Basic Latin only */
-}
-```
-
-**Optimize Loading Strategy**:
-- Critical resources first (async/defer non-critical)
-- Preload critical assets
-- Prefetch likely next pages
-- Service worker for offline/caching
-- HTTP/2 or HTTP/3 for multiplexing
-
-### Rendering Performance
-
-**Avoid Layout Thrashing**:
-```javascript
-// ❌ Bad: Alternating reads and writes (causes reflows)
-elements.forEach(el => {
- const height = el.offsetHeight; // Read (forces layout)
- el.style.height = height * 2; // Write
-});
-
-// ✅ Good: Batch reads, then batch writes
-const heights = elements.map(el => el.offsetHeight); // All reads
-elements.forEach((el, i) => {
- el.style.height = heights[i] * 2; // All writes
-});
-```
-
-**Optimize Rendering**:
-- Use CSS `contain` property for independent regions
-- Minimize DOM depth (flatter is faster)
-- Reduce DOM size (fewer elements)
-- Use `content-visibility: auto` for long lists
-- Virtual scrolling for very long lists (react-window, react-virtualized)
-
-**Reduce Paint & Composite**:
-- Use `transform` and `opacity` for reliable movement, but allow blur, filters, masks, clip paths, shadows, and color shifts when they create meaningful polish
-- Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- Use `will-change` sparingly for known expensive operations
-- Bound expensive paint areas for blur/filter/shadow effects (smaller and isolated is faster)
-
-### Animation Performance
-
-**GPU Acceleration**:
-```css
-/* ✅ GPU-accelerated (fast) */
-.animated {
- transform: translateX(100px);
- opacity: 0.5;
-}
-
-/* ❌ CPU-bound (slow) */
-.animated {
- left: 100px;
- width: 300px;
-}
-```
-
-**Smooth 60fps**:
-- Target 16ms per frame (60fps)
-- Use `requestAnimationFrame` for JS animations
-- Debounce/throttle scroll handlers
-- Use CSS animations when possible
-- Avoid long-running JavaScript during animations
-
-**Intersection Observer**:
-```javascript
-// Efficiently detect when elements enter viewport
-const observer = new IntersectionObserver((entries) => {
- entries.forEach(entry => {
- if (entry.isIntersecting) {
- // Element is visible, lazy load or animate
- }
- });
-});
-```
-
-### React/Framework Optimization
-
-**React-specific**:
-- Use `memo()` for expensive components
-- `useMemo()` and `useCallback()` for expensive computations
-- Virtualize long lists
-- Code split routes
-- Avoid inline function creation in render
-- Use React DevTools Profiler
-
-**Framework-agnostic**:
-- Minimize re-renders
-- Debounce expensive operations
-- Memoize computed values
-- Lazy load routes and components
-
-### Network Optimization
-
-**Reduce Requests**:
-- Combine small files
-- Use SVG sprites for icons
-- Inline small critical assets
-- Remove unused third-party scripts
-
-**Optimize APIs**:
-- Use pagination (don't load everything)
-- GraphQL to request only needed fields
-- Response compression (gzip, brotli)
-- HTTP caching headers
-- CDN for static assets
-
-**Optimize for Slow Connections**:
-- Adaptive loading based on connection (navigator.connection)
-- Optimistic UI updates
-- Request prioritization
-- Progressive enhancement
-
-## Core Web Vitals Optimization
-
-### Largest Contentful Paint (LCP < 2.5s)
-- Optimize hero images
-- Inline critical CSS
-- Preload key resources
-- Use CDN
-- Server-side rendering
-
-### First Input Delay (FID < 100ms) / INP (< 200ms)
-- Break up long tasks
-- Defer non-critical JavaScript
-- Use web workers for heavy computation
-- Reduce JavaScript execution time
-
-### Cumulative Layout Shift (CLS < 0.1)
-- Set dimensions on images and videos
-- Don't inject content above existing content
-- Use `aspect-ratio` CSS property
-- Reserve space for ads/embeds
-- Avoid animations that cause layout shifts
-
-```css
-/* Reserve space for image */
-.image-container {
- aspect-ratio: 16 / 9;
-}
-```
-
-## Performance Monitoring
-
-**Tools to use**:
-- Chrome DevTools (Lighthouse, Performance panel)
-- WebPageTest
-- Core Web Vitals (Chrome UX Report)
-- Bundle analyzers (webpack-bundle-analyzer)
-- Performance monitoring (Sentry, DataDog, New Relic)
-
-**Key metrics**:
-- LCP, FID/INP, CLS (Core Web Vitals)
-- Time to Interactive (TTI)
-- First Contentful Paint (FCP)
-- Total Blocking Time (TBT)
-- Bundle size
-- Request count
-
-**IMPORTANT**: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.
-
-**NEVER**:
-- Optimize without measuring (premature optimization)
-- Sacrifice accessibility for performance
-- Break functionality while optimizing
-- Use `will-change` everywhere (creates new layers, uses memory)
-- Lazy load above-fold content
-- Optimize micro-optimizations while ignoring major issues (optimize the biggest bottleneck first)
-- Forget about mobile performance (often slower devices, slower connections)
-
-## Verify Improvements
-
-Test that optimizations worked:
-
-- **Before/after metrics**: Compare Lighthouse scores
-- **Real user monitoring**: Track improvements for real users
-- **Different devices**: Test on low-end Android, not just flagship iPhone
-- **Slow connections**: Throttle to 3G, test experience
-- **No regressions**: Ensure functionality still works
-- **User perception**: Does it *feel* faster?
-
-When the user-facing numbers move, hand off to `/impeccable polish` for the final pass.
@@ -1,130 +0,0 @@
-Start your response with:
-
-```
-──────────── ⚡ OVERDRIVE ─────────────
-》》》 Entering overdrive mode...
-```
-
-Push an interface past conventional limits. This isn't just about visual effects. It's about using the full power of the browser to make any part of an interface feel extraordinary: a table that handles a million rows, a dialog that morphs from its trigger, a form that validates in real-time with streaming feedback, a page transition that feels cinematic.
-
-**EXTRA IMPORTANT FOR THIS COMMAND**: Context determines what "extraordinary" means. A particle system on a creative portfolio is impressive. The same particle system on a settings page is embarrassing. But a settings page with instant optimistic saves and animated state transitions? That's extraordinary too. Understand the project's personality and goals before deciding what's appropriate.
-
-### Propose Before Building
-
-This command has the highest potential to misfire. Do NOT jump straight into implementation. You MUST:
-
-1. **Think through 2-3 different directions**: consider different techniques, levels of ambition, and aesthetic approaches. For each direction, briefly describe what the result would look and feel like.
-2. **ask the user directly to clarify what you cannot infer.** to present these directions and get the user's pick before writing any code. Explain trade-offs (browser support, performance cost, complexity).
-3. Only proceed with the direction the user confirms.
-
-Skipping this step risks building something embarrassing that needs to be thrown away.
-
-### Iterate with Browser Automation
-
-Technically ambitious effects almost never work on the first try. You MUST actively use browser automation tools to preview your work, visually verify the result, and iterate. Do not assume the effect looks right, check it. Expect multiple rounds of refinement. The gap between "technically works" and "looks extraordinary" is closed through visual iteration, not code alone.
-
----
-
-## Assess What "Extraordinary" Means Here
-
-The right kind of technical ambition depends entirely on what you're working with. Before choosing a technique, ask: **what would make a user of THIS specific interface say "wow, that's nice"?**
-
-### For visual/marketing surfaces
-Pages, hero sections, landing pages, portfolios: the "wow" is often sensory: a scroll-driven reveal, a shader background, a cinematic page transition, generative art that responds to the cursor.
-
-### For functional UI
-Tables, forms, dialogs, navigation: the "wow" is in how it FEELS: a dialog that morphs from the button that triggered it via View Transitions, a data table that renders 100k rows at 60fps via virtual scrolling, a form with streaming validation that feels instant, drag-and-drop with spring physics.
-
-### For performance-critical UI
-The "wow" is invisible but felt: a search that filters 50k items without a flicker, a complex form that never blocks the main thread, an image editor that processes in near-real-time. The interface just never hesitates.
-
-### For data-heavy interfaces
-Charts and dashboards: the "wow" is in fluidity: GPU-accelerated rendering via Canvas/WebGL for massive datasets, animated transitions between data states, force-directed graph layouts that settle naturally.
-
-**The common thread**: something about the implementation goes beyond what users expect from a web interface. The technique serves the experience, not the other way around.
-
-## The Toolkit
-
-Organized by what you're trying to achieve, not by technology name.
-
-### Make transitions feel cinematic
-- **View Transitions API** (same-document: all browsers; cross-document: no Firefox): shared element morphing between states. A list item expanding into a detail page. A button morphing into a dialog. This is the closest thing to native FLIP animations.
-- **`@starting-style`** (all browsers): animate elements from `display: none` to visible with CSS only, including entry keyframes
-- **Spring physics**: natural motion with mass, tension, and damping instead of cubic-bezier. Libraries: motion (formerly Framer Motion), GSAP, or roll your own spring solver.
-
-### Tie animation to scroll position
-- **Scroll-driven animations** (`animation-timeline: scroll()`): CSS-only, no JS. Parallax, progress bars, reveal sequences all driven by scroll position. (Chrome/Edge/Safari; Firefox: flag only; always provide a static fallback)
-
-### Render beyond CSS
-- **WebGL** (all browsers): shader effects, post-processing, particle systems. Libraries: Three.js, OGL (lightweight), regl. Use for effects CSS can't express.
-- **WebGPU** (Chrome/Edge; Safari partial; Firefox: flag only): next-gen GPU compute. More powerful than WebGL but limited browser support. Always fall back to WebGL2.
-- **Canvas 2D / OffscreenCanvas**: custom rendering, pixel manipulation, or moving heavy rendering off the main thread entirely via Web Workers + OffscreenCanvas.
-- **SVG filter chains**: displacement maps, turbulence, morphology for organic distortion effects. CSS-animatable.
-
-### Make data feel alive
-- **Virtual scrolling**: render only visible rows for tables/lists with tens of thousands of items. No library required for simple cases; TanStack Virtual for complex ones.
-- **GPU-accelerated charts**: Canvas or WebGL-rendered data visualization for datasets too large for SVG/DOM. Libraries: deck.gl, regl-based custom renderers.
-- **Animated data transitions**: morph between chart states rather than replacing. D3's `transition()` or View Transitions for DOM-based charts.
-
-### Animate complex properties
-- **`@property`** (all browsers): register custom CSS properties with types, enabling animation of gradients, colors, and complex values that CSS can't normally interpolate.
-- **Web Animations API** (all browsers): JavaScript-driven animations with the performance of CSS. Composable, cancellable, reversible. The foundation for complex choreography.
-
-### Push performance boundaries
-- **Web Workers**: move computation off the main thread. Heavy data processing, image manipulation, search indexing: anything that would cause jank.
-- **OffscreenCanvas**: render in a Worker thread. The main thread stays free while complex visuals render in the background.
-- **WASM**: near-native performance for computation-heavy features. Image processing, physics simulations, codecs.
-
-### Interact with the device
-- **Web Audio API**: spatial audio, audio-reactive visualizations, sonic feedback. Requires user gesture to start.
-- **Device APIs**: orientation, ambient light, geolocation. Use sparingly and always with user permission.
-
-**NOTE**: This command is about enhancing how an interface FEELS, not changing what a product DOES. Adding real-time collaboration, offline support, or new backend capabilities are product decisions, not UI enhancements. Focus on making existing features feel extraordinary.
-
-## Implement with Discipline
-
-### Progressive enhancement is non-negotiable
-
-Every technique must degrade gracefully. The experience without the enhancement must still be good.
-
-```css
-@supports (animation-timeline: scroll()) {
- .hero { animation-timeline: scroll(); }
-}
-```
-
-```javascript
-if ('gpu' in navigator) { /* WebGPU */ }
-else if (canvas.getContext('webgl2')) { /* WebGL2 fallback */ }
-/* CSS-only fallback must still look good */
-```
-
-### Performance rules
-
-- Target 60fps. If dropping below 50, simplify.
-- Respect `prefers-reduced-motion`, always. Provide a beautiful static alternative.
-- Lazy-initialize heavy resources (WebGL contexts, WASM modules) only when near viewport.
-- Pause off-screen rendering. Kill what you can't see.
-- Test on real mid-range devices, not just your development machine.
-
-### Polish is the difference
-
-The gap between "cool" and "extraordinary" is in the last 20% of refinement: the easing curve on a spring animation, the timing offset in a staggered reveal, the subtle secondary motion that makes a transition feel physical. Don't ship the first version that works; ship the version that feels inevitable.
-
-**NEVER**:
-- Ignore `prefers-reduced-motion`. This is an accessibility requirement, not a suggestion
-- Ship effects that cause jank on mid-range devices
-- Use bleeding-edge APIs without a functional fallback
-- Add sound without explicit user opt-in
-- Use technical ambition to mask weak design fundamentals; fix those first with other commands
-- Layer multiple competing extraordinary moments. Focus creates impact, excess creates noise
-
-## Verify the Result
-
-- **The wow test**: Show it to someone who hasn't seen it. Do they react?
-- **The removal test**: Take it away. Does the experience feel diminished, or does nobody notice?
-- **The device test**: Run it on a phone, a tablet, a Chromebook. Still smooth?
-- **The accessibility test**: Enable reduced motion. Still beautiful?
-- **The context test**: Does this make sense for THIS brand and audience?
-
-"Technically extraordinary" isn't about using the newest API. It's about making an interface do something users didn't think a website could do.
@@ -1,179 +0,0 @@
-# Persona-Based Design Testing
-
-Test the interface through the eyes of 5 distinct user archetypes. Each persona exposes different failure modes that a single "design director" perspective would miss.
-
-**How to use**: Select 2–3 personas most relevant to the interface being critiqued. Walk through the primary user action as each persona. Report specific red flags, not generic concerns.
-
----
-
-## 1. Impatient Power User: "Alex"
-
-
-**Profile**: Expert with similar products. Expects efficiency, hates hand-holding. Will find shortcuts or leave.
-
-**Behaviors**:
-- Skips all onboarding and instructions
-- Looks for keyboard shortcuts immediately
-- Tries to bulk-select, batch-edit, and automate
-- Gets frustrated by required steps that feel unnecessary
-- Abandons if anything feels slow or patronizing
-
-**Test Questions**:
-- Can Alex complete the core task in under 60 seconds?
-- Are there keyboard shortcuts for common actions?
-- Can onboarding be skipped entirely?
-- Do modals have keyboard dismiss (Esc)?
-- Is there a "power user" path (shortcuts, bulk actions)?
-
-**Red Flags** (report these specifically):
-- Forced tutorials or unskippable onboarding
-- No keyboard navigation for primary actions
-- Slow animations that can't be skipped
-- One-item-at-a-time workflows where batch would be natural
-- Redundant confirmation steps for low-risk actions
-
----
-
-## 2. Confused First-Timer: "Jordan"
-
-**Profile**: Never used this type of product. Needs guidance at every step. Will abandon rather than figure it out.
-
-**Behaviors**:
-- Reads all instructions carefully
-- Hesitates before clicking anything unfamiliar
-- Looks for help or support constantly
-- Misunderstands jargon and abbreviations
-- Takes the most literal interpretation of any label
-
-**Test Questions**:
-- Is the first action obviously clear within 5 seconds?
-- Are all icons labeled with text?
-- Is there contextual help at decision points?
-- Does terminology assume prior knowledge?
-- Is there a clear "back" or "undo" at every step?
-
-**Red Flags** (report these specifically):
-- Icon-only navigation with no labels
-- Technical jargon without explanation
-- No visible help option or guidance
-- Ambiguous next steps after completing an action
-- No confirmation that an action succeeded
-
----
-
-## 3. Accessibility-Dependent User: "Sam"
-
-**Profile**: Uses screen reader (VoiceOver/NVDA), keyboard-only navigation. May have low vision, motor impairment, or cognitive differences.
-
-**Behaviors**:
-- Tabs through the interface linearly
-- Relies on ARIA labels and heading structure
-- Cannot see hover states or visual-only indicators
-- Needs adequate color contrast (4.5:1 minimum)
-- May use browser zoom up to 200%
-
-**Test Questions**:
-- Can the entire primary flow be completed keyboard-only?
-- Are all interactive elements focusable with visible focus indicators?
-- Do images have meaningful alt text?
-- Is color contrast WCAG AA compliant (4.5:1 for text)?
-- Does the screen reader announce state changes (loading, success, errors)?
-
-**Red Flags** (report these specifically):
-- Click-only interactions with no keyboard alternative
-- Missing or invisible focus indicators
-- Meaning conveyed by color alone (red = error, green = success)
-- Unlabeled form fields or buttons
-- Time-limited actions without extension option
-- Custom components that break screen reader flow
-
----
-
-## 4. Deliberate Stress Tester: "Riley"
-
-**Profile**: Methodical user who pushes interfaces beyond the happy path. Tests edge cases, tries unexpected inputs, and probes for gaps in the experience.
-
-**Behaviors**:
-- Tests edge cases intentionally (empty states, long strings, special characters)
-- Submits forms with unexpected data (emoji, RTL text, very long values)
-- Tries to break workflows by navigating backwards, refreshing mid-flow, or opening in multiple tabs
-- Looks for inconsistencies between what the UI promises and what actually happens
-- Documents problems methodically
-
-**Test Questions**:
-- What happens at the edges (0 items, 1000 items, very long text)?
-- Do error states recover gracefully or leave the UI in a broken state?
-- What happens on refresh mid-workflow? Is state preserved?
-- Are there features that appear to work but produce broken results?
-- How does the UI handle unexpected input (emoji, special chars, paste from Excel)?
-
-**Red Flags** (report these specifically):
-- Features that appear to work but silently fail or produce wrong results
-- Error handling that exposes technical details or leaves UI in a broken state
-- Empty states that show nothing useful ("No results" with no guidance)
-- Workflows that lose user data on refresh or navigation
-- Inconsistent behavior between similar interactions in different parts of the UI
-
----
-
-## 5. Distracted Mobile User: "Casey"
-
-**Profile**: Using phone one-handed on the go. Frequently interrupted. Possibly on a slow connection.
-
-**Behaviors**:
-- Uses thumb only; prefers bottom-of-screen actions
-- Gets interrupted mid-flow and returns later
-- Switches between apps frequently
-- Has limited attention span and low patience
-- Types as little as possible, prefers taps and selections
-
-**Test Questions**:
-- Are primary actions in the thumb zone (bottom half of screen)?
-- Is state preserved if the user leaves and returns?
-- Does it work on slow connections (3G)?
-- Can forms use autocomplete and smart defaults?
-- Are touch targets at least 44×44pt?
-
-**Red Flags** (report these specifically):
-- Important actions positioned at the top of the screen (unreachable by thumb)
-- No state persistence; progress lost on tab switch or interruption
-- Large text inputs required where selection would work
-- Heavy assets loading on every page (no lazy loading)
-- Tiny tap targets or targets too close together
-
----
-
-## Selecting Personas
-
-Choose personas based on the interface type:
-
-| Interface Type | Primary Personas | Why |
-|---------------|-----------------|-----|
-| Landing page / marketing | Jordan, Riley, Casey | First impressions, trust, mobile |
-| Dashboard / admin | Alex, Sam | Power users, accessibility |
-| E-commerce / checkout | Casey, Riley, Jordan | Mobile, edge cases, clarity |
-| Onboarding flow | Jordan, Casey | Confusion, interruption |
-| Data-heavy / analytics | Alex, Sam | Efficiency, keyboard nav |
-| Form-heavy / wizard | Jordan, Sam, Casey | Clarity, accessibility, mobile |
-
----
-
-## Project-Specific Personas
-
-If `AGENTS.md` contains a `## Design Context` section (generated by `impeccable teach`), derive 1–2 additional personas from the audience and brand information:
-
-1. Read the target audience description
-2. Identify the primary user archetype not covered by the 5 predefined personas
-3. Create a persona following this template:
-
-```
-### [Role]: "[Name]"
-
-**Profile**: [2-3 key characteristics derived from Design Context]
-
-**Behaviors**: [3-4 specific behaviors based on the described audience]
-
-**Red Flags**: [3-4 things that would alienate this specific user type]
-```
-
-Only generate project-specific personas when real Design Context data is available. Don't invent audience details; use the 5 predefined personas when no context exists.
@@ -1,242 +0,0 @@
-> **Additional context needed**: quality bar (MVP vs flagship).
-
-Perform a meticulous final pass to catch all the small details that separate good work from great work. The difference between shipped and polished.
-
-Detector and automated QA output are defect evidence only. A clean script result is never proof that the design is strong; gather browser evidence and inspect the real interaction path.
-
-## Design System Discovery
-
-Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
-
-1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
-2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
-3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category: patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
-
-If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask. Never guess at design system principles.**
-
-## Pre-Polish Assessment
-
-Understand the current state and goals before touching anything:
-
-1. **Review completeness**:
- - Is it functionally complete?
- - Are there known issues to preserve (mark with TODOs)?
- - What's the quality bar? (MVP vs flagship feature?)
- - When does it ship? (How much time for polish?)
-
-2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish; a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
-
-3. **Identify polish areas**:
- - Visual inconsistencies
- - Spacing and alignment issues
- - Interaction state gaps
- - Copy inconsistencies
- - Edge cases and error states
- - Loading and transition smoothness
- - Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
-
-4. **Pull in any prior critique** (optional signal): If `/impeccable critique` has been run on the same target, its priority issues are a useful prior for what to address first. Resolve the target to a file path or URL, then:
- ```bash
- slug=$(node .qoder/skills/impeccable/scripts/critique-storage.mjs slug "<resolved>")
- node .qoder/skills/impeccable/scripts/critique-storage.mjs latest "$slug"
- ```
- Exit 0 with body = found; fold the P0/P1 items into your polish list and mention the snapshot path so the user sees what you read. Exit 2 = no snapshot, continue without it. The critique is one input among many. Do your own pass either way.
-
-5. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent; never perfect one corner while leaving another rough.
-
-**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
-
-## Polish Systematically
-
-Work through these dimensions methodically:
-
-### Visual Alignment & Spacing
-
-- **Pixel-perfect alignment**: Everything lines up to grid
-- **Consistent spacing**: All gaps use spacing scale (no random 13px gaps)
-- **Optical alignment**: Adjust for visual weight (icons may need offset for optical centering)
-- **Responsive consistency**: Spacing and alignment work at all breakpoints
-- **Grid adherence**: Elements snap to baseline grid
-
-**Check**:
-- Enable grid overlay and verify alignment
-- Check spacing with browser inspector
-- Test at multiple viewport sizes
-- Look for elements that "feel" off
-
-### Information Architecture & Flow
-
-Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
-
-- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
-- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere: modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
-- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
-- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
-- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
-
-### Typography Refinement
-
-- **Hierarchy consistency**: Same elements use same sizes/weights throughout
-- **Line length**: 45-75 characters for body text
-- **Line height**: Appropriate for font size and context
-- **Widows & orphans**: No single words on last line
-- **Hyphenation**: Appropriate for language and column width
-- **Kerning**: Adjust letter spacing where needed (especially headlines)
-- **Font loading**: No FOUT/FOIT flashes
-
-### Color & Contrast
-
-- **Contrast ratios**: All text meets WCAG standards
-- **Consistent token usage**: No hard-coded colors, all use design tokens
-- **Theme consistency**: Works in all theme variants
-- **Color meaning**: Same colors mean same things throughout
-- **Accessible focus**: Focus indicators visible with sufficient contrast
-- **Tinted neutrals**: No pure gray or pure black; add subtle color tint (0.01 chroma)
-- **Gray on color**: Never put gray text on colored backgrounds; use a shade of that color or transparency
-
-### Interaction States
-
-Every interactive element needs all states:
-
-- **Default**: Resting state
-- **Hover**: Subtle feedback (color, scale, shadow)
-- **Focus**: Keyboard focus indicator (never remove without replacement)
-- **Active**: Click/tap feedback
-- **Disabled**: Clearly non-interactive
-- **Loading**: Async action feedback
-- **Error**: Validation or error state
-- **Success**: Successful completion
-
-**Missing states create confusion and broken experiences**.
-
-### Micro-interactions & Transitions
-
-- **Smooth transitions**: All state changes animated appropriately (150-300ms)
-- **Consistent easing**: Use ease-out-quart/quint/expo for natural deceleration. Never bounce or elastic; they feel dated.
-- **No jank**: Smooth animations; use atmospheric blur/filter/mask/shadow effects when they add polish, but bound expensive paint areas and avoid casual layout-property animation
-- **Appropriate motion**: Motion serves purpose, not decoration
-- **Reduced motion**: Respects `prefers-reduced-motion`
-
-### Content & Copy
-
-- **Consistent terminology**: Same things called same names throughout
-- **Consistent capitalization**: Title Case vs Sentence case applied consistently
-- **Grammar & spelling**: No typos
-- **Appropriate length**: Not too wordy, not too terse
-- **Punctuation consistency**: Periods on sentences, not on labels (unless all labels have them)
-
-### Icons & Images
-
-- **Consistent style**: All icons from same family or matching style
-- **Appropriate sizing**: Icons sized consistently for context
-- **Proper alignment**: Icons align with adjacent text optically
-- **Alt text**: All images have descriptive alt text
-- **Loading states**: Images don't cause layout shift, proper aspect ratios
-- **Retina support**: 2x assets for high-DPI screens
-
-### Forms & Inputs
-
-- **Label consistency**: All inputs properly labeled
-- **Required indicators**: Clear and consistent
-- **Error messages**: Helpful and consistent
-- **Tab order**: Logical keyboard navigation
-- **Auto-focus**: Appropriate (don't overuse)
-- **Validation timing**: Consistent (on blur vs on submit)
-
-### Edge Cases & Error States
-
-- **Loading states**: All async actions have loading feedback
-- **Empty states**: Helpful empty states, not just blank space
-- **Error states**: Clear error messages with recovery paths
-- **Success states**: Confirmation of successful actions
-- **Long content**: Handles very long names, descriptions, etc.
-- **No content**: Handles missing data gracefully
-- **Offline**: Appropriate offline handling (if applicable)
-
-### Responsiveness
-
-- **All breakpoints**: Test mobile, tablet, desktop
-- **Touch targets**: 44x44px minimum on touch devices
-- **Readable text**: No text smaller than 14px on mobile
-- **No horizontal scroll**: Content fits viewport
-- **Appropriate reflow**: Content adapts logically
-
-### Performance
-
-- **Fast initial load**: Optimize critical path
-- **No layout shift**: Elements don't jump after load (CLS)
-- **Smooth interactions**: No lag or jank
-- **Optimized images**: Appropriate formats and sizes
-- **Lazy loading**: Off-screen content loads lazily
-
-### Code Quality
-
-- **Remove console logs**: No debug logging in production
-- **Remove commented code**: Clean up dead code
-- **Remove unused imports**: Clean up unused dependencies
-- **Consistent naming**: Variables and functions follow conventions
-- **Type safety**: No TypeScript `any` or ignored errors
-- **Accessibility**: Proper ARIA labels and semantic HTML
-
-## Polish Checklist
-
-Go through systematically:
-
-- [ ] Aligned to the design system (drift named and resolved by root cause)
-- [ ] Information architecture and flow shape match neighboring features
-- [ ] Visual alignment perfect at all breakpoints
-- [ ] Spacing uses design tokens consistently
-- [ ] Typography hierarchy consistent
-- [ ] All interactive states implemented
-- [ ] All transitions smooth (60fps)
-- [ ] Copy is consistent and polished
-- [ ] Icons are consistent and properly sized
-- [ ] All forms properly labeled and validated
-- [ ] Error states are helpful
-- [ ] Loading states are clear
-- [ ] Empty states are welcoming
-- [ ] Touch targets are 44x44px minimum
-- [ ] Contrast ratios meet WCAG AA
-- [ ] Keyboard navigation works
-- [ ] Focus indicators visible
-- [ ] No console errors or warnings
-- [ ] No layout shift on load
-- [ ] Works in all supported browsers
-- [ ] Respects reduced motion preference
-- [ ] Code is clean (no TODOs, console.logs, commented code)
-
-**IMPORTANT**: Polish is about details. Zoom in. Squint at it. Use it yourself. The little things add up.
-
-Sweat the details. Zoom in until the alignment is right and the spacing reads as deliberate. Then ship.
-
-**NEVER**:
-- Polish before it's functionally complete
-- Polish without aligning to the design system; that's decoration on drift
-- Guess at design system principles instead of asking when something is ambiguous
-- Spend hours on polish if it ships in 30 minutes (triage)
-- Introduce bugs while polishing (test thoroughly)
-- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
-- Perfect one thing while leaving others rough (consistent quality level)
-- Create new one-off components when design system equivalents exist
-- Hard-code values that should use design tokens
-- Introduce new patterns or flows that diverge from established ones
-
-## Final Verification
-
-Before marking as done:
-
-- **Use it yourself**: Actually interact with the feature.
-- **Test on real devices**: Not just browser DevTools.
-- **Ask someone else to review**: Fresh eyes catch things.
-- **Compare to design**: Match intended design.
-- **Check all states**: Don't just test happy path.
-- **Treat automation carefully**: Run detector or QA commands when they are available and relevant, fix their defects, but never cite a clean result as proof that the work is polished.
-
-## Clean Up
-
-After polishing, ensure code quality:
-
-- **Replace custom implementations**: If the design system provides a component you reimplemented, switch to the shared version.
-- **Remove orphaned code**: Delete unused styles, components, or files made obsolete by polish.
-- **Consolidate tokens**: If you introduced new values, check whether they should be tokens.
-- **Verify DRYness**: Look for duplication introduced during polishing and consolidate.
@@ -1,62 +0,0 @@
-# Product register
-
-When design SERVES the product: app UIs, admin dashboards, settings panels, data tables, tools, authenticated surfaces, anything where the user is in a task.
-
-## The product slop test
-
-Not "would someone say AI made this." Familiarity is often a feature here. The test is: would a user fluent in the category's best tools (Linear, Figma, Notion, Raycast, Stripe come to mind) sit down and trust this interface, or pause at every subtly-off component?
-
-Product UI's failure mode isn't flatness, it's strangeness without purpose: over-decorated buttons, mismatched form controls, gratuitous motion, display fonts where labels should be, invented affordances for standard tasks. The bar is earned familiarity. The tool should disappear into the task.
-
-## Typography
-
-- **System fonts are legitimate.** `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` gives you native feel on every platform. Inter is the common cross-platform default for a reason.
-- **One family is often right.** Product UIs don't need display/body pairing. A well-tuned sans carries headings, buttons, labels, body, data.
-- **Fixed rem scale, not fluid.** Clamp-sized headings don't serve product UI. Users view at consistent DPI, and a fluid h1 that shrinks in a sidebar looks worse, not better.
-- **Tighter scale ratio.** 1.125–1.2 between steps is typical. More type elements here than on brand surfaces; exaggerated contrast creates noise.
-- **Line length still applies for prose** (65–75ch). Data and compact UI can run denser; tables at 120ch+ are fine.
-
-## Color
-
-Product defaults to Restrained. A single surface can earn Committed (a dashboard where one category color carries a report, an onboarding flow with a drenched welcome screen), but Restrained is the floor.
-
-- State-rich semantic vocabulary: hover, focus, active, disabled, selected, loading, error, warning, success, info. Standardize these.
-- Accent color used for primary actions, current selection, and state indicators only, not decoration.
-- A second neutral layer for sidebars, toolbars, and panels (slightly cooler or warmer than the content surface).
-
-## Layout
-
-- Predictable grids. Consistency IS an affordance; users navigate faster when the structure is expected.
-- Familiar patterns are features. Standard navigation (top bar, side nav), breadcrumbs, tabs, and form layouts have established user expectations. Don't reinvent for flavor.
-- Responsive behavior is structural (collapse sidebar, responsive table, breakpoint-driven columns), not fluid typography.
-
-## Components
-
-Every interactive component has: default, hover, focus, active, disabled, loading, error. Don't ship with half of these.
-
-- Skeleton states for loading, not spinners in the middle of content.
-- Empty states that teach the interface, not "nothing here."
-- Consistent affordances across the surface. Same button shape. Same form-control vocabulary. Same icon style.
-
-## Motion
-
-- 150–250 ms on most transitions. Users are in flow; don't make them wait for choreography.
-- Motion conveys state, not decoration. State change, feedback, loading, reveal: nothing else.
-- No orchestrated page-load sequences. Product loads into a task; users don't want to watch it load.
-
-## Product bans (on top of the shared absolute bans)
-
-- Decorative motion that doesn't convey state.
-- Inconsistent component vocabulary across screens. If the "save" button looks different in two places, one is wrong.
-- Display fonts in UI labels, buttons, data.
-- Reinventing standard affordances for flavor (custom scrollbars, weird form controls, non-standard modals).
-- Heavy color or full-saturation accents on inactive states.
-
-## Product permissions
-
-Product can afford things brand surfaces can't.
-
-- System fonts and familiar sans defaults (Inter, SF Pro, system-ui stacks).
-- Standard navigation patterns: top bar + side nav, breadcrumbs, tabs, command palettes.
-- Density. Tables with many rows, panels with many labels, dense information when users need it.
-- Consistency over surprise. The same visual vocabulary screen to screen is a virtue; delight is saved for moments, not pages.
@@ -1,99 +0,0 @@
-Quiet design is harder than bold design. Subtlety needs precision. Reduce visual intensity in designs that are too loud, aggressive, or overstimulating without losing personality or making the result generic.
-
----
-
-## Register
-
-Brand: "quieter" means more restrained palette, more whitespace, more typographic air. Drama is reduced, not eliminated; the POV stays intact.
-
-Product: "quieter" means reducing visual noise. Fewer background accents, flatter cards, less color, less motion. The tool should disappear more completely into the task.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too intense:
-
-1. **Identify intensity sources**:
- - **Color saturation**: Overly bright or saturated colors
- - **Contrast extremes**: Too much high-contrast juxtaposition
- - **Visual weight**: Too many bold, heavy elements competing
- - **Animation excess**: Too much motion or overly dramatic effects
- - **Complexity**: Too many visual elements, patterns, or decorations
- - **Scale**: Everything is large and loud with no hierarchy
-
-2. **Understand the context**:
- - What's the purpose? (Marketing vs tool vs reading experience)
- - Who's the audience? (Some contexts need energy)
- - What's working? (Don't throw away good ideas)
- - What's the core message? (Preserve what matters)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Quieter" doesn't mean boring or generic. It means refined and easier on the eyes. Think luxury, not laziness.
-
-## Plan Refinement
-
-Create a strategy to reduce intensity while maintaining impact:
-
-- **Color approach**: Desaturate or shift to more restrained tones?
-- **Hierarchy approach**: Which elements should stay bold (very few), which should recede?
-- **Simplification approach**: What can be removed entirely?
-- **Sophistication approach**: How can we signal quality through restraint?
-
-**IMPORTANT**: Subtlety requires precision. Quiet without intent collapses to generic.
-
-## Refine the Design
-
-Systematically reduce intensity across these dimensions:
-
-### Color Refinement
-- **Reduce saturation**: Shift from fully saturated to 70-85% saturation
-- **Soften palette**: Replace bright colors with muted tones
-- **Reduce color variety**: Use fewer colors more thoughtfully
-- **Neutral dominance**: Let neutrals do more work, use color as accent (10% rule)
-- **Gentler contrasts**: High contrast only where it matters most
-- **Tinted grays**: Use warm or cool tinted grays instead of pure gray. Adds depth without loudness
-- **Never gray on color**: If you have gray text on a colored background, use a darker shade of that color or transparency instead
-
-### Visual Weight Reduction
-- **Typography**: Reduce font weights (900 → 600, 700 → 500), decrease sizes where appropriate
-- **Hierarchy through subtlety**: Use weight, size, and space instead of color and boldness
-- **White space**: Increase breathing room, reduce density
-- **Borders & lines**: Reduce thickness, decrease opacity, or remove entirely
-
-### Simplification
-- **Remove decorative elements**: Gradients, shadows, patterns, textures that don't serve purpose
-- **Simplify shapes**: Reduce border radius extremes, simplify custom shapes
-- **Reduce layering**: Flatten visual hierarchy where possible
-- **Clean up effects**: Reduce or remove blur effects, glows, multiple shadows
-
-### Motion Reduction
-- **Reduce animation intensity**: Shorter distances (10-20px instead of 40px), gentler easing
-- **Remove decorative animations**: Keep functional motion, remove flourishes
-- **Subtle micro-interactions**: Replace dramatic effects with gentle feedback
-- **Refined easing**: Use ease-out-quart for smooth, understated motion. Never bounce or elastic
-- **Remove animations entirely** if they're not serving a clear purpose
-
-### Composition Refinement
-- **Reduce scale jumps**: Smaller contrast between sizes creates calmer feeling
-- **Align to grid**: Bring rogue elements back into systematic alignment
-- **Even out spacing**: Replace extreme spacing variations with consistent rhythm
-
-**NEVER**:
-- Make everything the same size/weight (hierarchy still matters)
-- Remove all color (quiet ≠ grayscale)
-- Eliminate all personality (maintain character through refinement)
-- Sacrifice usability for aesthetics (functional elements still need clear affordances)
-- Make everything small and light (some anchors needed)
-
-## Verify Quality
-
-Ensure refinement maintains quality:
-
-- **Still functional**: Can users still accomplish tasks easily?
-- **Still distinctive**: Does it have character, or is it generic now?
-- **Better reading**: Is text easier to read for extended periods?
-- **Restrained, not absent**: Does the POV survive the cuts?
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,114 +0,0 @@
-# Responsive Design
-
-## Mobile-First: Write It Right
-
-Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
-
-## Breakpoints: Content-Driven
-
-Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
-
-## Detect Input Method, Not Just Screen Size
-
-**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
-
-```css
-/* Fine pointer (mouse, trackpad) */
-@media (pointer: fine) {
- .button { padding: 8px 16px; }
-}
-
-/* Coarse pointer (touch, stylus) */
-@media (pointer: coarse) {
- .button { padding: 12px 20px; } /* Larger touch target */
-}
-
-/* Device supports hover */
-@media (hover: hover) {
- .card:hover { transform: translateY(-2px); }
-}
-
-/* Device doesn't support hover (touch) */
-@media (hover: none) {
- .card { /* No hover state - use active instead */ }
-}
-```
-
-**Critical**: Don't rely on hover for functionality. Touch users can't hover.
-
-## Safe Areas: Handle the Notch
-
-Modern phones have notches, rounded corners, and home indicators. Use `env()`:
-
-```css
-body {
- padding-top: env(safe-area-inset-top);
- padding-bottom: env(safe-area-inset-bottom);
- padding-left: env(safe-area-inset-left);
- padding-right: env(safe-area-inset-right);
-}
-
-/* With fallback */
-.footer {
- padding-bottom: max(1rem, env(safe-area-inset-bottom));
-}
-```
-
-**Enable viewport-fit** in your meta tag:
-```html
-<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
-```
-
-## Responsive Images: Get It Right
-
-### srcset with Width Descriptors
-
-```html
-<img
- src="hero-800.jpg"
- srcset="
- hero-400.jpg 400w,
- hero-800.jpg 800w,
- hero-1200.jpg 1200w
- "
- sizes="(max-width: 768px) 100vw, 50vw"
- alt="Hero image"
->
-```
-
-**How it works**:
-- `srcset` lists available images with their actual widths (`w` descriptors)
-- `sizes` tells the browser how wide the image will display
-- Browser picks the best file based on viewport width AND device pixel ratio
-
-### Picture Element for Art Direction
-
-When you need different crops/compositions (not just resolutions):
-
-```html
-<picture>
- <source media="(min-width: 768px)" srcset="wide.jpg">
- <source media="(max-width: 767px)" srcset="tall.jpg">
- <img src="fallback.jpg" alt="...">
-</picture>
-```
-
-## Layout Adaptation Patterns
-
-**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
-
-## Testing: Don't Trust DevTools Alone
-
-DevTools device emulation is useful for layout but misses:
-
-- Actual touch interactions
-- Real CPU/memory constraints
-- Network latency patterns
-- Font rendering differences
-- Browser chrome/keyboard appearances
-
-**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
-
----
-
-**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
@@ -1,165 +0,0 @@
-Shape the UX and UI for a feature before any code is written. This command produces a **design brief**: a structured artifact that guides implementation through discovery, not guesswork.
-
-**Scope**: Design planning only. This command does NOT write code. It produces the thinking that makes code good.
-
-**Output**: A design brief that can be handed off to /impeccable craft, or directly to /impeccable for freeform implementation. When visual direction probes are used, the images are supporting artifacts, not the primary output.
-
-## Philosophy
-
-Most AI-generated UIs fail not because of bad code, but because of skipped thinking. They jump to "here's a card grid" without asking "what is the user trying to accomplish?" This command inverts that: understand deeply first, so implementation is precise.
-
-## Phase 1: Discovery Interview
-
-**Do NOT write any code or make any design decisions during this phase.** Your only job is to understand the feature deeply enough to make excellent design decisions later.
-
-This is a required interaction, not optional guidance. Ask these questions in conversation, adapting based on answers. Don't dump them all at once; have a natural dialogue. ask the user directly to clarify what you cannot infer.
-
-### Interview cadence
-
-Discovery includes at least one user-answer round unless PRODUCT.md, DESIGN.md, or an already-confirmed brief directly answers the needed inputs. With a sparse prompt, do **not** synthesize a complete brief for confirmation on the first response.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Treat PRODUCT.md and DESIGN.md as anchors; they reduce repeated questions but do **not** replace shape for craft. Shape is task-specific.
-- One round is the default. Add a second only if the first answers leave material gaps. Don't run a second round just to feel thorough.
-- Round 1 should clarify purpose, audience/context, content/scope, and (for brand) visual direction.
-- Round 2, when needed, fills in whatever's still genuinely missing.
-
-**Assert-then-confirm, not menu-with-escape.** When PRODUCT.md and the user's prompt make one option obvious, name it and ask the user to confirm or override. Don't enumerate "Restrained / Committed / Or something else?" as a real choice; "This reads as Restrained, confirm?" beats a four-option menu when the answer is already clear.
-
-### Purpose & Context
-- What is this feature for? What problem does it solve?
-- Who specifically will use it? (Not "users"; be specific: role, context, frequency)
-- What does success look like? How will you know this feature is working?
-- What's the user's state of mind when they reach this feature? (Rushed? Exploring? Anxious? Focused?)
-
-### Content & Data
-- What content or data does this feature display or collect?
-- What are the realistic ranges? (Minimum, typical, maximum, e.g., 0 items, 5 items, 500 items)
-- What are the edge cases? (Empty state, error state, first-time use, power user)
-- Is any content dynamic? What changes and how often?
-- What visual assets are real content here? Note required images, product shots, illustrations, maps, textures, diagrams, generated objects, or existing project assets.
-
-### Design Direction
-
-Force a visual decision on three fronts. Skip anything PRODUCT.md or DESIGN.md already answers; ask only what's missing.
-
-- **Color strategy for this surface.** Pick one: Restrained / Committed / Full palette / Drenched. Can override the project default if the surface earns it (e.g. a drenched hero inside an otherwise Restrained product).
-- **Theme via scene sentence.** Write one sentence of physical context for this surface: who uses it, where, under what ambient light, in what mood. The sentence forces dark vs light. If it doesn't, add detail until it does.
-- **Two or three named anchor references.** Specific products, brands, objects. Not adjectives like "modern" or "clean."
-
-### Scope
-
-Always ask. Sketch quality and shipped quality are different outputs; don't guess between them.
-
-- **Fidelity.** Sketch / mid-fi / high-fi / production-ready?
-- **Breadth.** One screen / a flow / a whole surface?
-- **Interactivity.** Static visual / interactive prototype / shipped-quality component?
-- **Time intent.** Quick exploration, or polish until it ships?
-
-Scope answers are task-scoped. Don't write them to PRODUCT.md or DESIGN.md; carry them through the design brief only.
-
-### Constraints
-- Are there technical constraints? (Framework, performance budget, browser support)
-- Are there content constraints? (Localization, dynamic text length, user-generated content)
-- Mobile/responsive requirements?
-- Accessibility requirements beyond WCAG AA?
-
-### Anti-Goals
-- What should this NOT be? What would be a wrong direction?
-- What's the biggest risk of getting this wrong?
-
-## Phase 1.5: Visual Direction Probe (Capability-Gated)
-
-After the discovery interview, generate a small set of visual direction probes **before** writing the final brief when all of these are true:
-
-- The work is **net-new** or directionally ambiguous enough that visual exploration will clarify the brief.
-- The requested fidelity is **mid-fi, high-fi, or production-ready**. Skip for sketch-only planning.
-- The current harness gives you native image generation (Codex's `image_gen`, an equivalent MCP tool, or similar). Don't ask the user to install APIs or tooling.
-
-When those conditions are met, this step is mandatory. If image generation isn't natively available, do not ask the user to install APIs or tooling. State in one line that the image step is skipped because the harness lacks native image generation, then proceed. The one-line announcement is required, not optional; it forces a conscious decision instead of letting the step quietly evaporate.
-
-Use probes to explore visual lanes, not to replace the brief.
-
-Do not skip probes because the final UI will be semantic, editable, code-native, responsive, or accessible. Those are implementation requirements, not reasons to avoid visual exploration.
-
-### What to generate
-
-Generate **2 to 4** distinct direction probes based on the discovery answers, especially:
-
-- Color strategy
-- Theme scene sentence
-- Named anchor references
-- Scope and fidelity
-
-The probes should differ in primary visual direction (hierarchy, topology, density, typographic voice, or color strategy), not just palette tweaks.
-
-### How to use the probes
-
-- Treat them as **direction tests**, not final designs.
-- Use them to pressure-test whether the brief is pointing at the right lane.
-- Ask the user which direction feels closest, what feels off, and what should carry forward.
-- If the probes reveal a mismatch, revise the brief inputs before finalizing the brief.
-
-### Important limits
-
-- Do **not** skip discovery because image generation is available.
-- Do **not** treat generated imagery as final UX specification, final copy, or final accessibility behavior.
-- Do **not** use this step for minor refinements of existing work. It's for shaping a new surface or clarifying a big directional choice.
-
-If image generation isn't natively available, announce the skip in one line and proceed to the design brief.
-
-## Phase 2: Design Brief
-
-After the interview and any required probes, present a brief and **end your response**. The user must confirm before any implementation runs. Do not present a brief and then continue to code in the same response, even if the brief feels obvious to you. The user's confirmation is the gate.
-
-**Choose the brief shape based on how clear the answers are:**
-
-- **Compact form (3-5 bullets)** when discovery was crisp and the original prompt + PRODUCT.md already pinned scope, content, and direction. State what you're building, the visual lane, and end with one or two specific questions or a clear "confirm or override?" prompt. This is the default for typical craft requests with a clear prompt.
-- **Full structured form (sections below)** when the task is genuinely ambiguous, multi-screen, or when the user asked for shape as a standalone step. Use this when the discipline of structure earns its weight.
-
-Don't pad a clear brief into a long one to look thorough. A 70-line brief restating answers the user just gave is noise, not rigor. Equally, don't skip the confirmation pause to look efficient: the pause is the point.
-
-Present the brief, then **stop and wait for explicit confirmation**. You are not the judge of whether the user already approved. Even when the brief feels obviously right, ask once and wait. The pause is what separates shape from premature implementation.
-
-### Brief Structure
-
-**1. Feature Summary** (2-3 sentences)
-What this is, who it's for, what it needs to accomplish.
-
-**2. Primary User Action**
-The single most important thing a user should do or understand here.
-
-**3. Design Direction**
-Color strategy (Restrained / Committed / Full palette / Drenched) + the theme scene sentence + 2–3 named anchor references. Reference PRODUCT.md and DESIGN.md where they already answer, and note any per-surface overrides.
-
-If you ran the Visual Direction Probe step, name which probe direction won and what changed in the brief because of it.
-
-**4. Scope**
-Fidelity, breadth, interactivity, and time intent from the Scope section of the interview. Task-scoped; these don't persist beyond the brief.
-
-**5. Layout Strategy**
-High-level spatial approach: what gets emphasis, what's secondary, how information flows. Describe the visual hierarchy and rhythm, not specific CSS.
-
-**6. Key States**
-List every state the feature needs: default, empty, loading, error, success, edge cases. For each, note what the user needs to see and feel.
-
-**7. Interaction Model**
-How users interact with this feature. What happens on click, hover, scroll? What feedback do they get? What's the flow from entry to completion?
-
-**8. Content Requirements**
-What copy, labels, empty state messages, error messages, and microcopy are needed. Note any dynamic content and its realistic ranges. For image-led surfaces, also list the required image/media roles and their likely source (project asset, generated raster, semantic SVG/CSS, canvas/WebGL, icon library, or accepted omission).
-
-**9. Recommended References**
-Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., spatial-design.md for complex layouts, motion-design.md for animated features, interaction-design.md for form-heavy features).
-
-**10. Open Questions**
-Anything genuinely unresolved. Don't list "open questions" you've already recommended a default for; assert the default and move on. If you'd write `Recommend: X` next to a question, just decide X.
-
----
-
-ask the user directly to clarify what you cannot infer. Ask for explicit confirmation of the brief before finishing.
-
-If the user disagrees with any part, revisit the relevant discovery questions. A shape run is incomplete until the user confirms direction.
-
-Once confirmed, the brief is complete. The user can now hand it to /impeccable, or use it to guide any other implementation approach. (If the user wants the full discovery-then-build flow in one step, they should use /impeccable craft instead, which runs this command internally.)
@@ -1,100 +0,0 @@
-# Spatial Design
-
-## Spacing Systems
-
-### Use 4pt Base, Not 8pt
-
-8pt systems are too coarse; you'll frequently need 12px (between 8 and 16). Use 4pt for granularity: 4, 8, 12, 16, 24, 32, 48, 64, 96px.
-
-### Name Tokens Semantically
-
-Name by relationship (`--space-sm`, `--space-lg`), not value (`--spacing-8`). Use `gap` instead of margins for sibling spacing; it eliminates margin collapse and cleanup hacks.
-
-## Grid Systems
-
-### The Self-Adjusting Grid
-
-Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Columns are at least 280px, as many as fit per row, leftovers stretch. For complex layouts, use named grid areas (`grid-template-areas`) and redefine them at breakpoints.
-
-## Visual Hierarchy
-
-### The Squint Test
-
-Blur your eyes (or screenshot and blur). Can you still identify:
-- The most important element?
-- The second most important?
-- Clear groupings?
-
-If everything looks the same weight blurred, you have a hierarchy problem.
-
-### Hierarchy Through Multiple Dimensions
-
-Don't rely on size alone. Combine:
-
-| Tool | Strong Hierarchy | Weak Hierarchy |
-|------|------------------|----------------|
-| **Size** | 3:1 ratio or more | <2:1 ratio |
-| **Weight** | Bold vs Regular | Medium vs Regular |
-| **Color** | High contrast | Similar tones |
-| **Position** | Top/left (primary) | Bottom/right |
-| **Space** | Surrounded by white space | Crowded |
-
-**The best hierarchy uses 2-3 dimensions at once**: A heading that's larger, bolder, AND has more space above it.
-
-### Cards Are Not Required
-
-Cards are overused. Spacing and alignment create visual grouping naturally. Use cards only when content is truly distinct and actionable, items need visual comparison in a grid, or content needs clear interaction boundaries. **Never nest cards inside cards.** Use spacing, typography, and subtle dividers for hierarchy within a card.
-
-## Container Queries
-
-Viewport queries are for page layouts. **Container queries are for components**:
-
-```css
-.card-container {
- container-type: inline-size;
-}
-
-.card {
- display: grid;
- gap: var(--space-md);
-}
-
-/* Card layout changes based on its container, not viewport */
-@container (min-width: 400px) {
- .card {
- grid-template-columns: 120px 1fr;
- }
-}
-```
-
-**Why this matters**: A card in a narrow sidebar stays compact, while the same card in a main content area expands automatically, without viewport hacks.
-
-## Optical Adjustments
-
-Text at `margin-left: 0` looks indented due to letterform whitespace; use negative margin (`-0.05em`) to optically align. Geometrically centered icons often look off-center; play icons need to shift right, arrows shift toward their direction.
-
-### Touch Targets vs Visual Size
-
-Buttons can look small but need large touch targets (44px minimum). Use padding or pseudo-elements:
-
-```css
-.icon-button {
- width: 24px; /* Visual size */
- height: 24px;
- position: relative;
-}
-
-.icon-button::before {
- content: '';
- position: absolute;
- inset: -10px; /* Expand tap target to 44px */
-}
-```
-
-## Depth & Elevation
-
-Create semantic z-index scales (dropdown → sticky → modal-backdrop → modal → toast → tooltip) instead of arbitrary numbers. For shadows, create a consistent elevation scale (sm → md → lg → xl). **Key insight**: Shadows should be subtle. If you can clearly see it, it's probably too strong.
-
----
-
-**Avoid**: Arbitrary spacing values outside your scale. Making all spacing equal (variety creates hierarchy). Creating hierarchy through size alone - combine size, weight, color, and space.
@@ -1,156 +0,0 @@
-# Teach Flow
-
-Gathers design context for a project and writes two complementary files at the project root:
-
-- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
-- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
-
-Every other impeccable command reads these files before doing any work.
-
-## Step 1: Load current state
-
-Run the shared loader first so you know what already exists:
-
-```bash
-node .qoder/skills/impeccable/scripts/load-context.mjs
-```
-
-The output tells you whether PRODUCT.md and/or DESIGN.md already exist. If `migrated: true`, legacy `.impeccable.md` was auto-renamed to `PRODUCT.md`. Mention this once to the user.
-
-Decision tree:
-- **Neither file exists (empty project or no context yet)**: do Steps 2-4 (write PRODUCT.md), then decide on DESIGN.md based on whether there's code to analyze.
-- **PRODUCT.md exists, DESIGN.md missing**: skip to Step 5 and offer to run `/impeccable document` for DESIGN.md.
-- **PRODUCT.md exists but has no `## Register` section (legacy)**: add it. Infer a hypothesis from the codebase (see Step 2), confirm with the user, write the field.
-- **Both exist**: ask the user directly to clarify what you cannot infer. Ask which file to refresh. Skip the one the user doesn't want changed.
-- **Just DESIGN.md exists (unusual)**: do Steps 2-4 to produce PRODUCT.md.
-
-Never silently overwrite an existing file. Always confirm first.
-
-If teach was invoked as a setup blocker by another command, such as `/impeccable craft landing page`, pause that command here. Complete teach, re-run the loader, then resume the original command with the freshly loaded context. For craft, resume into shape next; teach creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
-
-## Step 2: Explore the codebase
-
-Before asking questions, thoroughly scan the project to discover what you can:
-
-- **README and docs**: Project purpose, target audience, any stated goals
-- **Package.json / config files**: Tech stack, dependencies, existing design libraries
-- **Existing components**: Current design patterns, spacing, typography in use
-- **Brand assets**: Logos, favicons, color values already defined
-- **Design tokens / CSS variables**: Existing color palettes, font stacks, spacing scales
-- **Any style guides or brand documentation**
-
-Also form a **register hypothesis** from what you find:
-
-- Brand signals: `/`, `/about`, `/pricing`, `/blog/*`, `/docs/*`, hero sections, big typography, scroll-driven sections, landing-page-shaped content.
-- Product signals: `/app/*`, `/dashboard`, `/settings`, `/(auth)`, forms, data tables, side/top nav, app-shell components.
-
-Register is a hypothesis at this point, not a decision; Step 3 confirms it.
-
-Note what you've learned and what remains unclear. This exploration feeds both PRODUCT.md and DESIGN.md.
-
-## Step 3: Ask strategic questions (for PRODUCT.md)
-
-ask the user directly to clarify what you cannot infer. Ask only about what you couldn't infer from the codebase.
-
-### Interview mode, not confirmation mode
-
-If the repo is empty or the user's brief is sparse, run a short interview before proposing PRODUCT.md. Do **not** turn a one-sentence request into a complete inferred PRODUCT.md and ask for blanket confirmation.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Use inferred answers as hypotheses or options, not as finished facts.
-- Complete at least one real user-answer round before drafting PRODUCT.md, unless every required answer is directly discoverable from repo docs.
-- Round 1 should establish register, users/purpose, and desired outcome.
-- Round 2 should establish brand personality or references, anti-references, and accessibility needs.
-
-### Minimum viable interview
-
-Ask enough to complete PRODUCT.md. At minimum, cover register confirmation, users and purpose, brand personality, anti-references, and accessibility needs unless each answer is directly discoverable from repo context. After at least one interview round, you may propose inferred answers, but the user must confirm them before you write PRODUCT.md. Never synthesize PRODUCT.md from the original task prompt alone.
-
-### Register (ask first; it shapes everything below)
-
-Every design task is either **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboards, tools: design SERVES the product).
-
-If Step 2 produced a clear hypothesis, lead with it: *"From the codebase, this looks like a [brand / product] surface. Does that match your intent, or should we treat it differently?"*
-
-If the signal is genuinely split (e.g. a product with a big marketing landing), ask the user directly to clarify what you cannot infer. Ask which register describes the **primary** surface. The register can be overridden per task later, but PRODUCT.md carries one default.
-
-### Users & Purpose
-- Who uses this? What's their context when using it?
-- What job are they trying to get done?
-- For brand: what emotions should the interface evoke? (confidence, delight, calm, urgency)
-- For product: what workflow are they in? What's the primary task on any given screen?
-
-### Brand & Personality
-- How would you describe the brand personality in 3 words?
-- Reference sites or apps that capture the right feel? What specifically about them?
- - For brand, push for real-world references in the right lane (tech-minimal, editorial-magazine, consumer-warm, brutalist-grid, etc.), not generic "modern" adjectives.
- - For product, push for category best-tool references (Linear, Figma, Notion, Raycast, Stripe).
-- What should this explicitly NOT look like? Any anti-references?
-
-### Accessibility & Inclusion
-- Specific accessibility requirements? (WCAG level, known user needs)
-- Considerations for reduced motion, color blindness, or other accommodations?
-
-Skip questions where the answer is already clear. **Do NOT ask about colors, fonts, radii, or visual styling here.** Those belong in DESIGN.md, not PRODUCT.md.
-
-## Step 4: Write PRODUCT.md
-
-Write PRODUCT.md only after the user has confirmed the strategic answers from Step 3. If an inferred answer is uncertain or unconfirmed, ask before writing.
-
-Synthesize into a strategic document:
-
-```markdown
-# Product
-
-## Register
-
-product
-
-## Users
-[Who they are, their context, the job to be done]
-
-## Product Purpose
-[What this product does, why it exists, what success looks like]
-
-## Brand Personality
-[Voice, tone, 3-word personality, emotional goals]
-
-## Anti-references
-[What this should NOT look like. Specific bad-example sites or patterns to avoid.]
-
-## Design Principles
-[3-5 strategic principles derived from the conversation. Principles like "practice what you preach", "show, don't tell", "expert confidence". NOT visual rules like "use OKLCH" or "magenta accent".]
-
-## Accessibility & Inclusion
-[WCAG level, known user needs, considerations]
-```
-
-Register is either `brand` or `product` as a bare value. No prose, no commentary.
-
-Write to `PROJECT_ROOT/PRODUCT.md`. If `.impeccable.md` existed, the loader already renamed it; merge into that content rather than starting from scratch.
-
-## Step 5: Decide on DESIGN.md
-
-Offer `/impeccable document` either way. Two paths:
-
-- **Code exists** (CSS tokens, components, a running site): "I can generate a DESIGN.md that captures your visual system (colors, typography, components) so variants stay on-brand. Want to do that now?"
-- **Pre-implementation** (empty project): "I can seed a starter DESIGN.md from five quick questions about color strategy, type direction, motion energy, and references. You can re-run once there's code, to capture the real tokens. Want to do that now?"
-
-If the user agrees, delegate to `/impeccable document` (it auto-detects scan vs seed). Load its reference and follow that flow.
-
-If the user prefers to skip, mention they can run `/impeccable document` any time later.
-
-## Step 6: Confirm and wrap up
-
-Summarize:
-- Register captured (brand / product)
-- What was written (PRODUCT.md, DESIGN.md, or both)
-- The 3-5 strategic principles from PRODUCT.md that will guide future work
-- If DESIGN.md is pending, remind the user how to generate it later
-
-**Critical: re-run the loader to refresh session context.** After writing PRODUCT.md, run `node .qoder/skills/impeccable/scripts/load-context.mjs` one final time and let its full JSON output land in conversation. This ensures subsequent commands in this session use the freshly-written PRODUCT.md, not a stale earlier version.
-
-If teach was invoked as a blocker by another impeccable command (e.g. the user ran `/impeccable polish` with no PRODUCT.md), resume that original task now with the fresh context.
-
-Optionally ask the user directly to clarify what you cannot infer. Ask whether they'd like a brief summary of PRODUCT.md appended to AGENTS.md for easier agent reference. If yes, append a short **Design Context** pointer section there.
@@ -1,124 +0,0 @@
-Typography carries most of the information on the page. Replace generic defaults (Inter, Roboto, system fallback at flat scale) with type that reflects the brand and scales with intentional contrast.
-
----
-
-## Register
-
-Brand: run the font selection procedure in [brand.md](brand.md). Pairing follows the brand's lane (display serif + sans body for editorial/luxury, one committed sans for tech, etc.). Fluid `clamp()` scale, ≥1.25 ratio between steps.
-
-Product: system fonts and familiar sans stacks are legitimate here. One well-tuned family typically carries the whole UI. Fixed `rem` scale, 1.125–1.2 ratio between more closely-spaced steps.
-
----
-
-## Assess Current Typography
-
-Analyze what's weak or generic about the current type:
-
-1. **Font choices**:
- - Are we using invisible defaults? (Inter, Roboto, Arial, Open Sans, system defaults)
- - Does the font match the brand personality? (A playful brand shouldn't use a corporate typeface)
- - Are there too many font families? (More than 2-3 is almost always a mess)
-
-2. **Hierarchy**:
- - Can you tell headings from body from captions at a glance?
- - Are font sizes too close together? (14px, 15px, 16px = muddy hierarchy)
- - Are weight contrasts strong enough? (Medium vs Regular is barely visible)
-
-3. **Sizing & scale**:
- - Is there a consistent type scale, or are sizes arbitrary?
- - Does body text meet minimum readability? (16px+)
- - Is the sizing strategy appropriate for the context? (Fixed `rem` scales for app UIs; fluid `clamp()` for marketing/content page headings)
-
-4. **Readability**:
- - Are line lengths comfortable? (45-75 characters ideal)
- - Is line-height appropriate for the font and context?
- - Is there enough contrast between text and background?
-
-5. **Consistency**:
- - Are the same elements styled the same way throughout?
- - Are font weights used consistently? (Not bold in one section, semibold in another for the same role)
- - Is letter-spacing intentional or default everywhere?
-
-**CRITICAL**: The goal isn't to make text "fancier." It's to make it clearer, more readable, and more intentional. Good typography is invisible; bad typography is distracting.
-
-## Plan Typography Improvements
-
-Consult the [typography reference](typography.md) for detailed guidance on scales, pairing, and loading strategies.
-
-Create a systematic plan:
-
-- **Font selection**: Do fonts need replacing? What fits the brand/context?
-- **Type scale**: Establish a modular scale (e.g., 1.25 ratio) with clear hierarchy
-- **Weight strategy**: Which weights serve which roles? (Regular for body, Semibold for labels, Bold for headings, or whatever fits)
-- **Spacing**: Line-heights, letter-spacing, and margins between typographic elements
-
-## Improve Typography Systematically
-
-### Font Selection
-
-If fonts need replacing:
-- Choose fonts that reflect the brand personality
-- Pair with genuine contrast (serif + sans, geometric + humanist), or use a single family in multiple weights
-- Ensure web font loading doesn't cause layout shift (`font-display: swap`, metric-matched fallbacks)
-
-### Establish Hierarchy
-
-Build a clear type scale:
-- **5 sizes cover most needs**: caption, secondary, body, subheading, heading
-- **Use a consistent ratio** between levels (1.25, 1.333, or 1.5)
-- **Combine dimensions**: Size + weight + color + space for strong hierarchy. Don't rely on size alone
-- **App UIs**: Use a fixed `rem`-based type scale, optionally adjusted at 1-2 breakpoints. Fluid sizing undermines the spatial predictability that dense, container-based layouts need
-- **Marketing / content pages**: Use fluid sizing via `clamp(min, preferred, max)` for headings and display text. Keep body text fixed
-
-### Fix Readability
-
-- Set `max-width` on text containers using `ch` units (`max-width: 65ch`)
-- Adjust line-height per context: tighter for headings (1.1-1.2), looser for body (1.5-1.7)
-- Increase line-height slightly for light-on-dark text
-- Ensure body text is at least 16px / 1rem
-
-### Refine Details
-
-- Use `tabular-nums` for data tables and numbers that should align
-- Apply proper `letter-spacing`: slightly open for small caps and uppercase, default or tight for large display text
-- Use semantic token names (`--text-body`, `--text-heading`), not value names (`--font-16`)
-- Set `font-kerning: normal` and consider OpenType features where appropriate
-
-### Weight Consistency
-
-- Define clear roles for each weight and stick to them
-- Don't use more than 3-4 weights (Regular, Medium, Semibold, Bold is plenty)
-- Load only the weights you actually use (each weight adds to page load)
-
-**NEVER**:
-- Use more than 2-3 font families
-- Pick sizes arbitrarily; commit to a scale
-- Set body text below 16px
-- Use decorative/display fonts for body text
-- Disable browser zoom (`user-scalable=no`)
-- Use `px` for font sizes; use `rem` to respect user settings
-- Default to Inter/Roboto/Open Sans when personality matters
-- Pair fonts that are similar but not identical (two geometric sans-serifs)
-
-## Verify Typography Improvements
-
-- **Hierarchy**: Can you identify heading vs body vs caption instantly?
-- **Readability**: Is body text comfortable to read in long passages?
-- **Consistency**: Are same-role elements styled identically throughout?
-- **Personality**: Does the typography reflect the brand?
-- **Performance**: Are web fonts loading efficiently without layout shift?
-- **Accessibility**: Does text meet WCAG contrast ratios? Is it zoomable to 200%?
-
-When the type carries the hierarchy on its own, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `scale` param controlling the hierarchy ratio. Express all font sizes in the variant's scoped CSS through `calc(var(--p-scale, 1) * <base>)` or, better, scale the type ramp via `clamp(min, calc(var(--p-scale, 1) * Npx), max)`. Users slide from subdued to commanding.
-
-```json
-{"id":"scale","kind":"range","min":0.85,"max":1.3,"step":0.05,"default":1,"label":"Scale"}
-```
-
-Where the variant riffs on a specific pairing, expose the pairing choice as a `steps` param (e.g. "serif display + sans body" vs. "mono display + sans body" vs. "all-sans"). Each branch routes through `:scope[data-p-pairing="X"]` selectors in scoped CSS.
-
-See `reference/live.md` for the full params contract.
@@ -1,159 +0,0 @@
-# Typography
-
-## Classic Typography Principles
-
-### Vertical Rhythm
-
-Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
-
-### Modular Scale & Hierarchy
-
-The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
-
-**Use fewer sizes with more contrast.** A 5-size system covers most needs:
-
-| Role | Typical Ratio | Use Case |
-|------|---------------|----------|
-| xs | 0.75rem | Captions, legal |
-| sm | 0.875rem | Secondary UI, metadata |
-| base | 1rem | Body text |
-| lg | 1.25-1.5rem | Subheadings, lead text |
-| xl+ | 2-4rem | Headlines, hero text |
-
-Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
-
-### Readability & Measure
-
-Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
-
-**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
-
-**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
-
-## Font Selection & Pairing
-
-The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
-
-### Anti-reflexes worth defending against
-
-- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
-- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
-- A children's product does NOT need a rounded display font. Kids' books use real type.
-- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
-
-**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
-
-### Pairing Principles
-
-**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
-
-When pairing, contrast on multiple axes:
-- Serif + Sans (structure contrast)
-- Geometric + Humanist (personality contrast)
-- Condensed display + Wide body (proportion contrast)
-
-**Never pair fonts that are similar but not identical** (e.g., two geometric sans-serifs). They create visual tension without clear hierarchy.
-
-### Web Font Loading
-
-The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
-
-```css
-/* 1. Use font-display: swap for visibility */
-@font-face {
- font-family: 'CustomFont';
- src: url('font.woff2') format('woff2');
- font-display: swap;
-}
-
-/* 2. Match fallback metrics to minimize shift */
-@font-face {
- font-family: 'CustomFont-Fallback';
- src: local('Arial');
- size-adjust: 105%; /* Scale to match x-height */
- ascent-override: 90%; /* Match ascender height */
- descent-override: 20%; /* Match descender depth */
- line-gap-override: 10%; /* Match line spacing */
-}
-
-body {
- font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
-}
-```
-
-Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
-
-**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
-
-**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
-
-**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
-
-## Modern Web Typography
-
-### Fluid Type
-
-Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
-
-**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
-
-**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
-
-**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
-
-**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
-
-### OpenType Features
-
-Most developers don't know these exist. Use them for polish:
-
-```css
-/* Tabular numbers for data alignment */
-.data-table { font-variant-numeric: tabular-nums; }
-
-/* Proper fractions */
-.recipe-amount { font-variant-numeric: diagonal-fractions; }
-
-/* Small caps for abbreviations */
-abbr { font-variant-caps: all-small-caps; }
-
-/* Disable ligatures in code */
-code { font-variant-ligatures: none; }
-
-/* Enable kerning (usually on by default, but be explicit) */
-body { font-kerning: normal; }
-```
-
-Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
-
-### Rendering polish
-
-```css
-/* Even out heading line lengths (browser picks better break points) */
-h1, h2, h3 { text-wrap: balance; }
-
-/* Reduce orphans and ragged endings in long prose */
-article p { text-wrap: pretty; }
-
-/* Variable fonts: pick the right optical-size master automatically */
-body { font-optical-sizing: auto; }
-```
-
-**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
-
-## Typography System Architecture
-
-Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
-
-## Accessibility Considerations
-
-Beyond contrast ratios (which are well-documented), consider:
-
-- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
-- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
-- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
-- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
-
----
-
-**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
@@ -1,107 +0,0 @@
-# UX Writing
-
-## The Button Label Problem
-
-**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
-
-| Bad | Good | Why |
-|-----|------|-----|
-| OK | Save changes | Says what will happen |
-| Submit | Create account | Outcome-focused |
-| Yes | Delete message | Confirms the action |
-| Cancel | Keep editing | Clarifies what "cancel" means |
-| Click here | Download PDF | Describes the destination |
-
-**For destructive actions**, name the destruction:
-- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
-- "Delete 5 items" not "Delete selected" (show the count)
-
-## Error Messages: The Formula
-
-Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
-
-### Error Message Templates
-
-| Situation | Template |
-|-----------|----------|
-| **Format error** | "[Field] needs to be [format]. Example: [example]" |
-| **Missing required** | "Please enter [what's missing]" |
-| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
-| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
-| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
-
-### Don't Blame the User
-
-Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
-
-## Empty States Are Opportunities
-
-Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
-
-## Voice vs Tone
-
-**Voice** is your brand's personality, consistent everywhere.
-**Tone** adapts to the moment.
-
-| Moment | Tone Shift |
-|--------|------------|
-| Success | Celebratory, brief: "Done! Your changes are live." |
-| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
-| Loading | Reassuring: "Saving your work..." |
-| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
-
-**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
-
-## Writing for Accessibility
-
-**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
-
-## Writing for Translation
-
-### Plan for Expansion
-
-German text is ~30% longer than English. Allocate space:
-
-| Language | Expansion |
-|----------|-----------|
-| German | +30% |
-| French | +20% |
-| Finnish | +30-40% |
-| Chinese | -30% (fewer chars, but same width) |
-
-### Translation-Friendly Patterns
-
-Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
-
-## Consistency: The Terminology Problem
-
-Pick one term and stick with it:
-
-| Inconsistent | Consistent |
-|--------------|------------|
-| Delete / Remove / Trash | Delete |
-| Settings / Preferences / Options | Settings |
-| Sign in / Log in / Enter | Sign in |
-| Create / Add / New | Create |
-
-Build a terminology glossary and enforce it. Variety creates confusion.
-
-## Avoid Redundant Copy
-
-If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
-
-## Loading States
-
-Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
-
-## Confirmation Dialogs: Use Sparingly
-
-Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
-
-## Form Instructions
-
-Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
-
----
-
-**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
@@ -1,284 +0,0 @@
-#!/usr/bin/env node
-/**
- * Cleans up deprecated Impeccable skill files, symlinks, and
- * skills-lock.json entries left over from previous versions.
- *
- * Safe to run repeatedly -- it is a no-op when nothing needs cleaning.
- *
- * Usage (from the project root):
- * node {{scripts_path}}/cleanup-deprecated.mjs
- *
- * What it does:
- * 1. Finds every harness-specific skills directory (.claude/skills,
- * .cursor/skills, .agents/skills, etc.).
- * 2. For each deprecated skill name (with and without i- prefix),
- * checks if the directory exists and its SKILL.md mentions
- * "impeccable" (to avoid deleting unrelated user skills).
- * 3. Deletes confirmed matches (files, directories, or symlinks).
- * 4. Removes the corresponding entries from skills-lock.json.
- */
-
-import { existsSync, readFileSync, writeFileSync, rmSync, readdirSync, statSync, lstatSync, unlinkSync } from 'node:fs';
-import { join, resolve } from 'node:path';
-
-// Skills that were renamed, merged, or folded in v2.0, v2.1, and v3.0.
-const DEPRECATED_NAMES = [
- // v2.0 renames
- 'frontend-design', // renamed to impeccable
- 'teach-impeccable', // folded into /impeccable teach
- // v2.1 merges
- 'arrange', // renamed to layout
- 'normalize', // merged into polish
- 'onboard', // merged into harden
- 'extract', // merged into /impeccable extract
- // v3.0 consolidation: all standalone skills -> /impeccable sub-commands
- 'adapt',
- 'animate',
- 'audit',
- 'bolder',
- 'clarify',
- 'colorize',
- 'critique',
- 'delight',
- 'distill',
- 'harden',
- 'layout',
- 'optimize',
- 'overdrive',
- 'polish',
- 'quieter',
- 'shape',
- 'typeset',
-];
-
-// All known harness directories that may contain a skills/ subfolder.
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Per-skill fingerprints for SKILL.md bodies that never mentioned
-// "impeccable" in their v2.x source. Used as a last-resort match
-// when no skills-lock.json exists and the word heuristic fails.
-// The strings are lifted verbatim from the v2.x frontmatter
-// descriptions, so collisions with hand-written user skills are
-// vanishingly unlikely.
-const SKILL_FINGERPRINTS = {
- harden: 'Make interfaces production-ready: error handling, empty states',
- optimize: 'Diagnoses and fixes UI performance across loading speed',
-};
-
-/**
- * Walk up from startDir until we find a directory that looks like a
- * project root (has package.json, .git, or skills-lock.json).
- */
-export function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- const { root } = { root: '/' };
- while (dir !== root) {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Load skills-lock.json from the project root, or null if missing/unreadable.
- */
-export function loadLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return null;
- try {
- return JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return null;
- }
-}
-
-/**
- * Check whether a skill directory belongs to Impeccable. Three layered
- * signals, in order of reliability:
- * 1. Lock source equals "pbakaus/impeccable" (authoritative).
- * 2. SKILL.md body contains the word "impeccable".
- * 3. SKILL.md body contains a per-skill fingerprint (for harden and
- * optimize, whose v2.x SKILL.md never mentioned the pack name).
- */
-export function isImpeccableSkill(skillDir, { skillName, lock } = {}) {
- // 1. Authoritative: the lock file claims this skill is ours.
- if (skillName && lock?.skills?.[skillName]?.source === 'pbakaus/impeccable') {
- return true;
- }
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) return false;
- let content;
- try {
- content = readFileSync(skillMd, 'utf-8');
- } catch {
- return false;
- }
- // 2. Word-level content heuristic.
- if (/impeccable/i.test(content)) return true;
- // 3. Per-skill fingerprint for old skills that never mentioned the pack.
- // Strip the i- prefix so both `harden` and `i-harden` resolve to the
- // same fingerprint entry.
- const unprefixed = skillName?.startsWith('i-') ? skillName.slice(2) : skillName;
- const fingerprint = unprefixed && SKILL_FINGERPRINTS[unprefixed];
- if (fingerprint && content.includes(fingerprint)) return true;
- return false;
-}
-
-/**
- * Build the full list of names to check: each deprecated name, plus
- * its i-prefixed variant.
- */
-export function buildTargetNames() {
- const names = [];
- for (const name of DEPRECATED_NAMES) {
- names.push(name);
- names.push(`i-${name}`);
- }
- return names;
-}
-
-/**
- * Find every skills directory across all harness dirs in the project.
- * Returns absolute paths that exist on disk.
- */
-export function findSkillsDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const candidate = join(projectRoot, harness, 'skills');
- if (existsSync(candidate)) {
- dirs.push(candidate);
- }
- }
- return dirs;
-}
-
-/**
- * Remove deprecated skill directories/symlinks from all harness dirs.
- * Reads skills-lock.json so the authoritative "source" field can
- * drive deletion even when SKILL.md never mentions impeccable.
- * Returns an array of paths that were deleted.
- */
-export function removeDeprecatedSkills(projectRoot, lock) {
- if (lock === undefined) lock = loadLock(projectRoot);
- const targets = buildTargetNames();
- const skillsDirs = findSkillsDirs(projectRoot);
- const deleted = [];
-
- for (const skillsDir of skillsDirs) {
- for (const name of targets) {
- const skillPath = join(skillsDir, name);
-
- // Use lstat to detect symlinks (existsSync follows symlinks and
- // returns false for dangling ones).
- let stat;
- try {
- stat = lstatSync(skillPath);
- } catch {
- continue; // does not exist at all
- }
-
- if (stat.isSymbolicLink()) {
- // Symlink: check the target if it's alive, otherwise treat
- // dangling symlinks to deprecated names as safe to remove.
- const targetAlive = existsSync(skillPath);
- const isMatch = targetAlive
- ? isImpeccableSkill(skillPath, { skillName: name, lock })
- : true;
- if (isMatch) {
- unlinkSync(skillPath);
- deleted.push(skillPath);
- }
- continue;
- }
-
- // Regular directory -- verify it belongs to impeccable
- if (isImpeccableSkill(skillPath, { skillName: name, lock })) {
- rmSync(skillPath, { recursive: true, force: true });
- deleted.push(skillPath);
- }
- }
- }
-
- return deleted;
-}
-
-/**
- * Remove deprecated entries from skills-lock.json.
- * Only removes entries whose source is "pbakaus/impeccable".
- * Returns the list of removed skill names.
- */
-export function cleanSkillsLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return [];
-
- let lock;
- try {
- lock = JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return [];
- }
-
- if (!lock.skills || typeof lock.skills !== 'object') return [];
-
- const targets = buildTargetNames();
- const removed = [];
-
- for (const name of targets) {
- const entry = lock.skills[name];
- if (!entry) continue;
- // Only remove if it belongs to impeccable
- if (entry.source === 'pbakaus/impeccable') {
- delete lock.skills[name];
- removed.push(name);
- }
- }
-
- if (removed.length > 0) {
- writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\n', 'utf-8');
- }
-
- return removed;
-}
-
-/**
- * Run the full cleanup. Returns a summary object.
- *
- * Order matters: read the lock and delete directories first, then
- * strip lock entries. Otherwise the authoritative signal is gone by
- * the time directory deletion runs.
- */
-export function cleanup(projectRoot) {
- const root = projectRoot || findProjectRoot();
- const lock = loadLock(root);
- const deletedPaths = removeDeprecatedSkills(root, lock);
- const removedLockEntries = cleanSkillsLock(root);
- return { deletedPaths, removedLockEntries, projectRoot: root };
-}
-
-// CLI entry point
-if (process.argv[1] && resolve(process.argv[1]) === resolve(new URL(import.meta.url).pathname)) {
- const result = cleanup();
- if (result.deletedPaths.length === 0 && result.removedLockEntries.length === 0) {
- console.log('No deprecated Impeccable skills found. Nothing to clean up.');
- } else {
- if (result.deletedPaths.length > 0) {
- console.log(`Removed ${result.deletedPaths.length} deprecated skill(s):`);
- for (const p of result.deletedPaths) console.log(` - ${p}`);
- }
- if (result.removedLockEntries.length > 0) {
- console.log(`Cleaned ${result.removedLockEntries.length} entry/entries from skills-lock.json:`);
- for (const name of result.removedLockEntries) console.log(` - ${name}`);
- }
- }
-}
@@ -1,94 +0,0 @@
-{
- "craft": {
- "description": "Full confirmed-brief-then-build flow. Runs multi-round shape discovery first, resolves visual probe and north-star mock gates when available, then builds and visually iterates. Use when building a new feature end-to-end.",
- "argumentHint": "[feature description]"
- },
- "teach": {
- "description": "Gathers design context for a project. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles) and, when code exists to analyze, DESIGN.md (visual: colors, typography, components). Every other command reads these files before doing work. Use once per project.",
- "argumentHint": ""
- },
- "document": {
- "description": "Generate a DESIGN.md file that captures the current visual design system. Auto-extracts colors, typography, spacing, radii, and component patterns from the codebase, then asks the user to confirm descriptive language for atmosphere and color character. Follows the Google Stitch DESIGN.md format so the file is tool-compatible. Use when you need a visual design spec an AI agent can follow to stay on-brand.",
- "argumentHint": ""
- },
- "extract": {
- "description": "Pull reusable patterns, components, and design tokens into the design system. Identifies repeated patterns and consolidates them. Use when you have drift across the codebase and want to bring things back to a consistent system.",
- "argumentHint": "[target]"
- },
- "live": {
- "description": "Interactive live variant mode. Select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via HMR. Requires a running dev server. Use when you want to visually experiment with design alternatives in real time.",
- "argumentHint": ""
- },
- "adapt": {
- "description": "Adapt designs to work across different screen sizes, devices, contexts, or platforms. Implements breakpoints, fluid layouts, and touch targets. Use when the user mentions responsive design, mobile layouts, breakpoints, viewport adaptation, or cross-device compatibility.",
- "argumentHint": "[target] [context (mobile, tablet, print...)]"
- },
- "animate": {
- "description": "Review a feature and enhance it with purposeful animations, micro-interactions, and motion effects that improve usability and delight. Use when the user mentions adding animation, transitions, micro-interactions, motion design, hover effects, or making the UI feel more alive.",
- "argumentHint": "[target]"
- },
- "audit": {
- "description": "Run technical quality checks across accessibility, performance, theming, responsive design, and anti-patterns. Generates a scored report with P0-P3 severity ratings and actionable plan. Use when the user wants an accessibility check, performance audit, or technical quality review.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "bolder": {
- "description": "Amplify safe or boring designs to make them more visually interesting and stimulating. Increases impact while maintaining usability. Use when the user says the design looks bland, generic, too safe, lacks personality, or wants more visual impact and character.",
- "argumentHint": "[target]"
- },
- "clarify": {
- "description": "Improve unclear UX copy, error messages, microcopy, labels, and instructions to make interfaces easier to understand. Use when the user mentions confusing text, unclear labels, bad error messages, hard-to-follow instructions, or wanting better UX writing.",
- "argumentHint": "[target]"
- },
- "colorize": {
- "description": "Add strategic color to features that are too monochromatic or lack visual interest, making interfaces more engaging and expressive. Use when the user mentions the design looking gray, dull, lacking warmth, needing more color, or wanting a more vibrant or expressive palette.",
- "argumentHint": "[target]"
- },
- "critique": {
- "description": "Evaluate design from a UX perspective, assessing visual hierarchy, information architecture, emotional resonance, cognitive load, and overall quality with quantitative scoring, persona-based testing, automated anti-pattern detection, and actionable feedback. Use when the user asks to review, critique, evaluate, or give feedback on a design or component.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "delight": {
- "description": "Add moments of joy, personality, and unexpected touches that make interfaces memorable and enjoyable to use. Elevates functional to delightful. Use when the user asks to add polish, personality, animations, micro-interactions, delight, or make an interface feel fun or memorable.",
- "argumentHint": "[target]"
- },
- "distill": {
- "description": "Strip designs to their essence by removing unnecessary complexity. Great design is simple, powerful, and clean. Use when the user asks to simplify, declutter, reduce noise, remove elements, or make a UI cleaner and more focused.",
- "argumentHint": "[target]"
- },
- "harden": {
- "description": "Make interfaces production-ready: error handling, i18n, text overflow, edge case management, and resilience under real-world data. Use when the user asks to harden, make production-ready, handle edge cases, add error states, or fix overflow and i18n issues.",
- "argumentHint": "[target]"
- },
- "onboard": {
- "description": "Design onboarding flows, first-run experiences, and empty states that guide new users to value. Covers welcome screens, account setup, progressive disclosure, contextual tooltips, feature announcements, and activation moments. Use when the user mentions onboarding, first-time users, empty states, activation, getting started, new user flows, or the aha moment.",
- "argumentHint": "[target]"
- },
- "layout": {
- "description": "Improve layout, spacing, and visual rhythm. Fixes monotonous grids, inconsistent spacing, and weak visual hierarchy. Use when the user mentions layout feeling off, spacing issues, visual hierarchy, crowded UI, alignment problems, or wanting better composition.",
- "argumentHint": "[target]"
- },
- "optimize": {
- "description": "Diagnoses and fixes UI performance across loading speed, rendering, animations, images, and bundle size. Use when the user mentions slow, laggy, janky, performance, bundle size, load time, or wants a faster, smoother experience.",
- "argumentHint": "[target]"
- },
- "overdrive": {
- "description": "Pushes interfaces past conventional limits with technically ambitious implementations — shaders, spring physics, scroll-driven reveals, 60fps animations. Use when the user wants to wow, impress, go all-out, or make something that feels extraordinary.",
- "argumentHint": "[target]"
- },
- "polish": {
- "description": "Performs a final quality pass fixing alignment, spacing, consistency, and micro-detail issues before shipping. Use when the user mentions polish, finishing touches, pre-launch review, something looks off, or wants to go from good to great.",
- "argumentHint": "[target]"
- },
- "quieter": {
- "description": "Tones down visually aggressive or overstimulating designs, reducing intensity while preserving quality. Use when the user mentions too bold, too loud, overwhelming, aggressive, garish, or wants a calmer, more refined aesthetic.",
- "argumentHint": "[target]"
- },
- "shape": {
- "description": "Plan UX and UI before code. Runs a required multi-round discovery interview, uses visual probes when available, and produces a user-confirmed design brief for implementation.",
- "argumentHint": "[feature to shape]"
- },
- "typeset": {
- "description": "Improves typography by fixing font choices, hierarchy, sizing, weight, and readability so text feels intentional. Use when the user mentions fonts, type, readability, text hierarchy, sizing looks off, or wants more polished, intentional typography.",
- "argumentHint": "[target]"
- }
-}
@@ -1,242 +0,0 @@
-#!/usr/bin/env node
-/**
- * Critique persistence helper.
- *
- * Each run of /impeccable critique writes a per-target snapshot to
- * .impeccable/critique/<timestamp>__<slug>.md
- * with a small YAML frontmatter carrying the score + P0/P1 counts.
- *
- * /impeccable polish reads the latest matching snapshot at start as its
- * fix backlog. No other skill auto-reads critique output.
- *
- * The slug is derived mechanically from the *resolved* primary artifact
- * (file path or URL), never from the user's natural-language phrasing.
- * Slug stability across runs is what lets the trend display work.
- *
- * CLI entry points (called from skill instructions):
- * node critique-storage.mjs slug <resolved-target>
- * node critique-storage.mjs write <slug> <snapshot-body-file>
- * node critique-storage.mjs latest <slug>
- * node critique-storage.mjs trend <slug> [limit]
- *
- * Note: there is intentionally no `ignore` subcommand. ignore.md is a plain
- * markdown file; the model reads it directly with its file-read tool. This
- * helper only exists for operations the model can't trivially do inline
- * (normalizing paths, generating filenames, globbing + parsing frontmatter).
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath, pathToFileURL } from 'node:url';
-import { getCritiqueDir } from './impeccable-paths.mjs';
-
-const SLUG_MAX = 50;
-
-/**
- * Mechanically derive a slug from a resolved target. Returns null if the
- * input doesn't look like a stable identifier (empty, project root, etc).
- *
- * Accepts file paths and URLs. The model resolves "the homepage" to a
- * concrete artifact before calling this — we never slug a natural-language
- * phrase.
- */
-export function slugFromTarget(resolved, { cwd = process.cwd() } = {}) {
- if (!resolved || typeof resolved !== 'string') return null;
- const trimmed = resolved.trim();
- if (!trimmed) return null;
-
- // URL
- if (/^https?:\/\//i.test(trimmed)) {
- let url;
- try { url = new URL(trimmed); } catch { return null; }
- const hostPath = `${url.hostname}${url.pathname}`;
- return kebab(hostPath);
- }
-
- // File path. Make it project-relative so two devs critiquing the same
- // checkout get the same slug regardless of where their repo is cloned.
- const abs = path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- let rel = path.relative(cwd, abs);
- // If the target is outside cwd, fall back to the basename so we still
- // produce a stable slug (vs the absolute path, which would include
- // home dirs / usernames).
- if (rel.startsWith('..') || path.isAbsolute(rel)) {
- rel = path.basename(abs);
- }
- if (!rel || rel === '.' || rel === '') return null;
- return kebab(rel);
-}
-
-function kebab(s) {
- const slug = s
- .toLowerCase()
- .replace(/[/\\.]+/g, '-')
- .replace(/[^a-z0-9-]+/g, '-')
- .replace(/-+/g, '-')
- .replace(/^-|-$/g, '');
- if (!slug) return null;
- // Cap from the tail — the tail (filename) is more identifying than the
- // top-level directory.
- return slug.length <= SLUG_MAX ? slug : slug.slice(slug.length - SLUG_MAX).replace(/^-/, '');
-}
-
-/**
- * Filename-safe UTC ISO timestamp: hyphens for separators, trailing Z.
- * Plain colons aren't allowed on Windows filesystems.
- */
-export function nowFilenameStamp(date = new Date()) {
- const iso = date.toISOString(); // 2026-05-12T18:30:00.123Z
- return iso.replace(/[:.]/g, '-').replace(/-\d+Z$/, 'Z');
-}
-
-/**
- * Write a snapshot for `slug`. `meta` carries the small structured frontmatter
- * keys read back by readTrend(). `body` is the human-readable critique
- * report (everything below the frontmatter).
- *
- * Returns the absolute path written.
- */
-export function writeSnapshot({ slug, meta, body, cwd = process.cwd(), now = new Date() }) {
- if (!slug) throw new Error('writeSnapshot requires a slug');
- const dir = getCritiqueDir(cwd);
- fs.mkdirSync(dir, { recursive: true });
- const timestamp = nowFilenameStamp(now);
- const filePath = path.join(dir, `${timestamp}__${slug}.md`);
- // Spread `meta` first so internally computed `timestamp` and `slug`
- // always win. Otherwise a caller-supplied meta blob (parsed from the
- // IMPECCABLE_CRITIQUE_META env var) could clobber them, leaving the
- // filename in disagreement with its frontmatter and corrupting trends.
- const front = serializeFrontmatter({ ...meta, timestamp, slug });
- fs.writeFileSync(filePath, `${front}\n${body.trim()}\n`, 'utf-8');
- return filePath;
-}
-
-function serializeFrontmatter(obj) {
- const lines = ['---'];
- for (const [key, value] of Object.entries(obj)) {
- if (value === undefined || value === null) continue;
- const str = typeof value === 'string' ? value : String(value);
- // Quote strings that contain : or # to keep parsing simple.
- const needsQuotes = typeof value === 'string' && /[:#]/.test(str);
- lines.push(`${key}: ${needsQuotes ? JSON.stringify(str) : str}`);
- }
- lines.push('---');
- return lines.join('\n');
-}
-
-function parseFrontmatter(text) {
- const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
- if (!match) return {};
- const out = {};
- for (const line of match[1].split(/\r?\n/)) {
- const colon = line.indexOf(':');
- if (colon < 0) continue;
- const key = line.slice(0, colon).trim();
- let value = line.slice(colon + 1).trim();
- if (/^".*"$/.test(value)) {
- try { value = JSON.parse(value); } catch { /* leave as-is */ }
- } else if (/^-?\d+$/.test(value)) {
- value = Number(value);
- }
- out[key] = value;
- }
- return out;
-}
-
-/**
- * Return all snapshot files for `slug`, sorted oldest → newest.
- */
-function listSnapshotsForSlug(slug, cwd) {
- const dir = getCritiqueDir(cwd);
- if (!fs.existsSync(dir)) return [];
- const suffix = `__${slug}.md`;
- return fs.readdirSync(dir)
- .filter((f) => f.endsWith(suffix))
- .sort()
- .map((f) => path.join(dir, f));
-}
-
-/**
- * Return the most recent snapshot for `slug`, or null. Polish reads this
- * to find its fix backlog when the slug matches.
- */
-export function readLatestSnapshot(slug, { cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- if (!all.length) return null;
- const latest = all[all.length - 1];
- const body = fs.readFileSync(latest, 'utf-8');
- return { path: latest, body, meta: parseFrontmatter(body) };
-}
-
-/**
- * Return the last `limit` snapshots' frontmatter, oldest → newest.
- * Critique appends a one-line trend to its output using this.
- */
-export function readTrend(slug, { limit = 5, cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- const slice = all.slice(-limit);
- return slice.map((file) => parseFrontmatter(fs.readFileSync(file, 'utf-8')));
-}
-
-// ---- CLI ---------------------------------------------------------------
-
-function main(argv) {
- const [cmd, ...args] = argv;
- switch (cmd) {
- case 'slug': {
- const slug = slugFromTarget(args[0]);
- if (!slug) { process.stderr.write('no stable slug for input\n'); process.exit(1); }
- process.stdout.write(`${slug}\n`);
- return;
- }
- case 'write': {
- const [slug, bodyFile] = args;
- if (!slug || !bodyFile) { process.stderr.write('usage: write <slug> <body-file>\n'); process.exit(1); }
- const raw = fs.readFileSync(bodyFile, 'utf-8');
- // The body file may be a full report. The caller passes the meta as
- // a JSON object on stdin if it wants structured frontmatter; otherwise
- // we write with minimal metadata.
- let meta = {};
- const metaArg = process.env.IMPECCABLE_CRITIQUE_META;
- if (metaArg) {
- try { meta = JSON.parse(metaArg); } catch { /* ignore */ }
- }
- const out = writeSnapshot({ slug, meta, body: raw });
- process.stdout.write(`${out}\n`);
- return;
- }
- case 'latest': {
- const latest = readLatestSnapshot(args[0]);
- if (!latest) { process.exit(2); }
- process.stdout.write(latest.body);
- return;
- }
- case 'trend': {
- const rows = readTrend(args[0], { limit: args[1] ? Number(args[1]) : 5 });
- process.stdout.write(JSON.stringify(rows, null, 2) + '\n');
- return;
- }
- default:
- process.stderr.write('usage: critique-storage.mjs <slug|write|latest|trend> [args]\n');
- process.exit(1);
- }
-}
-
-function isMainModule() {
- if (!process.argv[1]) return false;
- try {
- return fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1]);
- } catch {
- // pathToFileURL normalizes Windows paths; keep it as a fallback for any
- // environment where realpath is unavailable.
- return import.meta.url === pathToFileURL(process.argv[1]).href;
- }
-}
-
-// Why the realpath check: generated skills are often reached through symlinked
-// harness directories (for example a demo repo's `.agents` -> source `.agents`).
-// Node resolves import.meta.url to the real file, while process.argv[1] keeps
-// the symlink path. Comparing canonical paths prevents a silent exit-0 no-op.
-if (isMainModule()) {
- main(process.argv.slice(2));
-}
@@ -1,820 +0,0 @@
-// Parse a DESIGN.md (Stitch-spec format) into a structured JSON model that
-// the live-mode design-system panel can render. Deterministic, dependency-free.
-//
-// Two-layer: YAML frontmatter (machine-readable tokens) + markdown body
-// (prose with six canonical H2 sections). When frontmatter is present, it's
-// exposed on `model.frontmatter` alongside the prose-scraped sections;
-// consumers can prefer frontmatter values and fall back to prose.
-
-const CANONICAL_SECTIONS = [
- 'Overview',
- 'Colors',
- 'Typography',
- 'Elevation',
- 'Components',
- "Do's and Don'ts",
-];
-
-// ---------- Frontmatter (Stitch YAML subset) ----------
-
-function parseFrontmatter(md) {
- const lines = md.split(/\r?\n/);
- if (lines[0]?.trim() !== '---') return { frontmatter: null, body: md };
-
- let end = -1;
- for (let i = 1; i < lines.length; i++) {
- if (lines[i].trim() === '---') { end = i; break; }
- }
- if (end === -1) return { frontmatter: null, body: md };
-
- const yaml = lines.slice(1, end).join('\n');
- const body = lines.slice(end + 1).join('\n');
- try {
- return { frontmatter: parseYamlSubset(yaml), body };
- } catch {
- return { frontmatter: null, body: md };
- }
-}
-
-// Minimal YAML reader for the Stitch frontmatter subset: scalar maps with
-// one level of nested objects (typography roles, components). Indent-based,
-// 2-space convention. No arrays, no anchors, no multi-line scalars — Stitch's
-// schema doesn't need them and accepting them would require a real YAML
-// dependency we don't want to vendor.
-function parseYamlSubset(yaml) {
- const lines = yaml.split(/\r?\n/);
- const root = {};
- const stack = [{ indent: -1, obj: root }];
-
- for (const raw of lines) {
- // Skip blanks and line-only comments. Don't strip inline comments:
- // unquoted hex values start with `#` and can't be safely distinguished
- // from a comment after whitespace.
- if (!raw.trim() || /^\s*#/.test(raw)) continue;
-
- const indent = raw.match(/^\s*/)[0].length;
- const content = raw.slice(indent);
-
- const colonIdx = findTopLevelColon(content);
- if (colonIdx === -1) continue;
-
- while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
- stack.pop();
- }
-
- const key = content.slice(0, colonIdx).trim();
- const rest = content.slice(colonIdx + 1).trim();
- const parent = stack[stack.length - 1].obj;
-
- if (rest === '') {
- const obj = {};
- parent[key] = obj;
- stack.push({ indent, obj });
- } else {
- parent[key] = parseScalar(rest);
- }
- }
-
- return root;
-}
-
-function findTopLevelColon(s) {
- let inQuote = null;
- for (let i = 0; i < s.length; i++) {
- const ch = s[i];
- if (inQuote) {
- if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
- } else if (ch === '"' || ch === "'") {
- inQuote = ch;
- } else if (ch === ':') {
- return i;
- }
- }
- return -1;
-}
-
-function parseScalar(raw) {
- const s = raw.trim();
- if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
- return s.slice(1, -1);
- }
- if (s === 'true') return true;
- if (s === 'false') return false;
- if (s === 'null' || s === '~') return null;
- if (/^-?\d+$/.test(s)) return Number(s);
- if (/^-?\d*\.\d+$/.test(s)) return Number(s);
- return s;
-}
-
-const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
-const OKLCH_RE = /oklch\([^)]+\)/gi;
-const RGBA_RE = /rgba?\([^)]+\)/gi;
-const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
-const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
-
-// ---------- Section splitting ----------
-
-function splitSections(md) {
- const lines = md.split(/\r?\n/);
- let title = null;
- const sections = {};
- let current = null;
-
- for (const raw of lines) {
- const line = raw.trimEnd();
-
- if (!title && line.startsWith('# ') && !line.startsWith('## ')) {
- title = line.replace(/^#\s+/, '').trim();
- continue;
- }
-
- const h2 = line.match(/^##\s+(?:\d+\.\s*)?([^:\n]+?)(?::\s*(.+))?$/);
- if (h2) {
- const rawName = normalizeApostrophes(h2[1].trim());
- const subtitle = h2[2] ? h2[2].trim() : null;
- const canonical = matchCanonicalSection(rawName);
- if (canonical) {
- current = { name: canonical, subtitle, lines: [] };
- sections[canonical] = current;
- continue;
- }
- // non-canonical H2 — ignore but stop feeding into current
- current = null;
- continue;
- }
-
- if (current) current.lines.push(raw);
- }
-
- return { title, sections };
-}
-
-function normalizeApostrophes(s) {
- return s.replace(/[\u2018\u2019]/g, "'");
-}
-
-function matchCanonicalSection(name) {
- const normalized = normalizeApostrophes(name).toLowerCase();
- // Exact match first
- for (const c of CANONICAL_SECTIONS) {
- if (normalizeApostrophes(c).toLowerCase() === normalized) return c;
- }
- // Keyword-contained match: "Overview & Creative North Star" -> "Overview",
- // "Elevation & Depth" -> "Elevation", etc.
- for (const c of CANONICAL_SECTIONS) {
- const key = normalizeApostrophes(c).toLowerCase();
- const pattern = new RegExp(`\\b${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
- if (pattern.test(normalized)) return c;
- }
- return null;
-}
-
-// ---------- Subsection splitting (inside a canonical section) ----------
-
-function splitSubsections(lines) {
- const subs = [];
- let current = { name: null, lines: [] };
- subs.push(current);
-
- for (const raw of lines) {
- const h3 = raw.match(/^###\s+(.+?)\s*$/);
- if (h3) {
- current = { name: h3[1].trim(), lines: [] };
- subs.push(current);
- continue;
- }
- current.lines.push(raw);
- }
-
- return subs;
-}
-
-// ---------- Generic helpers ----------
-
-function collectParagraphs(lines) {
- const paragraphs = [];
- let buf = [];
- const flush = () => {
- if (buf.length) {
- paragraphs.push(buf.join(' ').trim());
- buf = [];
- }
- };
- for (const raw of lines) {
- const trimmed = raw.trim();
- if (trimmed === '') { flush(); continue; }
- // Horizontal rules (---, ***) and headings/bullets end a paragraph.
- if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { flush(); continue; }
- if (raw.startsWith('#') || raw.match(/^[-*]\s/)) { flush(); continue; }
- buf.push(trimmed);
- }
- flush();
- return paragraphs.filter(Boolean);
-}
-
-function collectBullets(lines) {
- const bullets = [];
- let current = null;
- for (const raw of lines) {
- const m = raw.match(/^\s*[-*]\s+(.+)$/);
- if (m) {
- if (current) bullets.push(current);
- current = m[1];
- continue;
- }
- // continuation of a bullet (indented line)
- if (current && raw.match(/^\s{2,}\S/)) {
- current += ' ' + raw.trim();
- continue;
- }
- // blank line ends a bullet
- if (raw.trim() === '' && current) {
- bullets.push(current);
- current = null;
- }
- }
- if (current) bullets.push(current);
- return bullets;
-}
-
-function stripBold(s) {
- return s.replace(/\*\*(.+?)\*\*/g, '$1');
-}
-
-function extractNamedRules(lines) {
- const rules = [];
- const seen = new Set();
-
- // Style A (Impeccable): "**The X Rule.** body body body" — can span lines.
- const joined = lines.join('\n');
- const inlineStart = /\*\*(The [^*]+?Rule)\.\*\*/g;
- const inlineMatches = [];
- let m;
- while ((m = inlineStart.exec(joined)) !== null) {
- inlineMatches.push({ name: m[1], start: m.index, end: inlineStart.lastIndex });
- }
- for (let i = 0; i < inlineMatches.length; i++) {
- const mm = inlineMatches[i];
- const bodyEnd = i + 1 < inlineMatches.length ? inlineMatches[i + 1].start : joined.length;
- const body = joined
- .slice(mm.end, bodyEnd)
- .replace(/\n##[^\n]*$/s, '')
- .replace(/\n###[^\n]*$/s, '')
- .trim();
- const name = stripBold(mm.name).trim();
- seen.add(name.toLowerCase());
- rules.push({ name, body: stripBold(body) });
- }
-
- // Style B (Stitch): `### The "X" Rule` or `### The X Fallback`, body is the
- // bullets/paragraphs until the next heading. Accept Rule / Fallback / Principle.
- for (let i = 0; i < lines.length; i++) {
- const h3 = lines[i].match(/^###\s+(.+?)\s*$/);
- if (!h3) continue;
- const headerName = stripBold(h3[1]).replace(/["“”]/g, '').trim();
- if (!/^The\b.*\b(Rule|Fallback|Principle)\b/i.test(headerName)) continue;
- if (seen.has(headerName.toLowerCase())) continue;
-
- const bodyLines = [];
- for (let j = i + 1; j < lines.length; j++) {
- if (/^##\s|^###\s/.test(lines[j])) break;
- bodyLines.push(lines[j]);
- }
- const body = stripBold(bodyLines.join('\n').replace(/\n+/g, ' ')).trim();
- if (body) {
- seen.add(headerName.toLowerCase());
- rules.push({ name: headerName, body });
- }
- }
-
- // Style C (Stitch bullet form): "* **The Layering Principle:** body"
- // Colon/period lives inside the bold, so match "**...**" then inspect.
- for (const b of collectBullets(lines)) {
- const mm = b.match(/^\*\*([^*]+?)\*\*\s*(.+)$/);
- if (!mm) continue;
- const nameRaw = mm[1].replace(/[.:]\s*$/, '').replace(/["“”]/g, '').trim();
- if (!/^The\b.+\b(Rule|Fallback|Principle)$/i.test(nameRaw)) continue;
- if (seen.has(nameRaw.toLowerCase())) continue;
- seen.add(nameRaw.toLowerCase());
- rules.push({ name: nameRaw, body: stripBold(mm[2]).trim() });
- }
-
- return rules;
-}
-
-// ---------- Per-section extractors ----------
-
-function extractOverview(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
- const northStar = text.match(/\*\*Creative North Star:\s*"([^"]+)"\*\*/);
- const keyChars = [];
- const keyCharMatch = text.match(/\*\*Key Characteristics:\*\*\s*\n([\s\S]+?)(?:\n##|\n###|$)/);
- if (keyCharMatch) {
- for (const line of keyCharMatch[1].split('\n')) {
- const m = line.match(/^\s*[-*]\s+(.+)$/);
- if (m) keyChars.push(stripBold(m[1].trim()));
- }
- }
-
- // Philosophy paragraphs: everything that isn't a rule header or key-char block
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) =>
- !p.startsWith('**Creative North Star') &&
- !p.startsWith('**Key Characteristics')
- );
-
- return {
- subtitle: section.subtitle,
- creativeNorthStar: northStar ? northStar[1] : null,
- philosophy: paragraphs,
- keyCharacteristics: keyChars,
- };
-}
-
-function extractColors(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ');
- const groups = [];
- const ROLE_KEYWORDS = /^(primary|secondary|tertiary|neutral|accent)\b/i;
-
- for (const sub of subs.slice(1)) {
- if (!sub.name || /Named Rules?/i.test(sub.name) || /^The\s/i.test(sub.name)) continue;
-
- const bullets = collectBullets(sub.lines);
- const parsed = bullets.map((b) => parseColorBullet(b)).filter(Boolean);
- if (parsed.length === 0) continue;
-
- // If every bullet starts with a role keyword (Primary/Secondary/...), promote
- // each bullet to its own group. Otherwise keep the subsection as the group.
- const allRoleBullets =
- parsed.length > 0 && parsed.every((p) => p.name && ROLE_KEYWORDS.test(p.name));
-
- if (allRoleBullets) {
- for (const p of parsed) {
- groups.push({ role: p.name, colors: [p] });
- }
- } else {
- groups.push({ role: sub.name, colors: parsed });
- }
- }
-
- // If the Colors section has no subsections at all (unlikely), fall back to
- // scanning the whole section as a flat bullet list.
- if (groups.length === 0) {
- const flat = collectBullets(section.lines)
- .map((b) => parseColorBullet(b))
- .filter(Boolean);
- if (flat.length) {
- for (const p of flat) {
- if (p.name && ROLE_KEYWORDS.test(p.name)) {
- groups.push({ role: p.name, colors: [p] });
- } else {
- const fallback = groups.find((g) => g.role === 'Palette');
- if (fallback) fallback.colors.push(p);
- else groups.push({ role: 'Palette', colors: [p] });
- }
- }
- }
- }
-
- return {
- subtitle: section.subtitle,
- description: description || null,
- groups,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function parseColorBullet(bullet) {
- const text = bullet.trim();
-
- // Case 1 (Impeccable): **Name** (value-with-maybe-nested-parens): description
- const bold = text.match(/^\*\*(.+?)\*\*\s*(.*)$/);
- if (bold && bold[2].startsWith('(')) {
- const value = extractParenGroup(bold[2]);
- if (value !== null) {
- const after = bold[2].slice(value.length + 2).trimStart();
- if (after.startsWith(':')) {
- return buildColor(bold[1], value, after.slice(1).trim());
- }
- }
- }
-
- // Case 2 (Stitch): **Name (values):** description — value embedded in bold.
- const stitch = text.match(/^\*\*([^*]+?)\s*\(([^)]+)\):\*\*\s*(.*)$/);
- if (stitch) {
- return buildColor(stitch[1].trim(), stitch[2], stitch[3]);
- }
-
- // Case 3: bullet without bold, just hex/oklch inside.
- const values = collectColorValues(text);
- if (values.length) {
- return buildColor(null, values.join(' to '), text);
- }
- return null;
-}
-
-function extractParenGroup(s) {
- if (s[0] !== '(') return null;
- let depth = 0;
- for (let i = 0; i < s.length; i++) {
- if (s[i] === '(') depth++;
- else if (s[i] === ')') {
- depth--;
- if (depth === 0) return s.slice(1, i);
- }
- }
- return null;
-}
-
-function buildColor(name, rawValue, description) {
- const values = collectColorValues(rawValue);
- const primary = values[0] ?? rawValue.trim();
- return {
- name: name ? stripBold(name).trim() : null,
- value: primary,
- valueRange: values.length > 1 ? values : null,
- format: detectFormat(primary),
- description: stripBold(description || '').trim() || null,
- };
-}
-
-function collectColorValues(s) {
- const out = [];
- s.replace(HEX_RE, (v) => {
- out.push(v);
- return v;
- });
- s.replace(OKLCH_RE, (v) => {
- out.push(v);
- return v;
- });
- return out;
-}
-
-function detectFormat(v) {
- if (!v) return 'unknown';
- if (v.startsWith('#')) return 'hex';
- if (/^oklch/i.test(v)) return 'oklch';
- if (/^rgb/i.test(v)) return 'rgb';
- return 'unknown';
-}
-
-function scanInlineColors(lines) {
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '');
- const color = parseColorBullet(trimmed);
- if (color) out.push(color);
- }
- return out;
-}
-
-function parseStitchInlineGroups(lines) {
- // Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
- // Each bullet IS its own role. Group them under the spoken role name.
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
- const m = trimmed.match(
- /^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
- );
- if (m) {
- const role = m[1];
- const color = buildColor(role, m[2], m[3]);
- out.push({ role, colors: [color] });
- }
- }
- return out;
-}
-
-function extractTypography(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
-
- const fonts = {};
- // Pattern A: **Display Font:** Family (with fallback)
- const fontLineRe = /\*\*([\w\s/]+?)Font:\*\*\s*([^\n(]+?)(?:\s*\(with\s+([^)]+)\))?\s*$/gm;
- let fm;
- while ((fm = fontLineRe.exec(text)) !== null) {
- const rawRole = fm[1].trim().toLowerCase().replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || 'display';
- fonts[role] = {
- family: fm[2].trim(),
- fallback: fm[3] ? fm[3].trim() : null,
- };
- }
-
- // Pattern B (Stitch): * **Display & Headlines (Noto Serif):** description
- if (Object.keys(fonts).length === 0) {
- const stitchRe = /\*\*([\w\s&/]+?)\s*\(([^)]+)\):\*\*\s*(.+)/g;
- let sm;
- while ((sm = stitchRe.exec(text)) !== null) {
- const rawRole = sm[1]
- .trim()
- .toLowerCase()
- .replace(/\s*&\s*/g, '-')
- .replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || rawRole;
- fonts[role] = { family: sm[2].trim(), fallback: null, purpose: sm[3].trim() };
- }
- }
-
- // Character paragraph — either a **Character:** label, or fall back to the
- // first free paragraph under the section header (Stitch style).
- const characterMatch = text.match(/\*\*Character:\*\*\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\n|\n###|\n##|$)/);
- let character = characterMatch ? characterMatch[1].replace(/\n/g, ' ').trim() : null;
- if (!character) {
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) => !/^\*\*[\w\s/&]+Font/i.test(p) && !/^\*\*[\w\s/&]+\([^)]+\)/.test(p)
- );
- if (paragraphs.length) character = paragraphs[0];
- }
-
- // Hierarchy bullets under ### Hierarchy
- const subs = splitSubsections(section.lines);
- let hierarchy = [];
- const hierSub = subs.find((s) => s.name && /hierarch/i.test(s.name));
- if (hierSub) {
- const bullets = collectBullets(hierSub.lines);
- hierarchy = bullets.map(parseTypeBullet).filter(Boolean);
- }
-
- return {
- subtitle: section.subtitle,
- fonts,
- character,
- hierarchy,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function normalizeFontRole(raw) {
- // Canonical roles the panel cares about: display, body, label, mono.
- // Stitch often writes compound roles like "display-&-headlines" or "ui-&-body"
- // — collapse them to the first canonical role present.
- const tokens = raw.split(/[-/&\s]+/).filter(Boolean);
- const priority = ['display', 'headline', 'body', 'ui', 'label', 'mono'];
- const canonical = { headline: 'display', ui: 'body' };
- for (const p of priority) {
- if (tokens.includes(p)) return canonical[p] || p;
- }
- return null;
-}
-
-function parseTypeBullet(bullet) {
- // - **Display** (family, weight 300, italic, clamp(...), line-height 1): purpose
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(([^)]+)\):\s*(.*)$/);
- if (!m) return null;
- const name = m[1].trim();
- const specs = m[2].split(',').map((s) => s.trim());
- return {
- name,
- specs,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractElevation(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ') || null;
-
- const shadows = [];
- const seen = new Set();
- const dedupe = (entry) => {
- const key = (entry.name || '') + '::' + entry.value;
- if (seen.has(key)) return;
- seen.add(key);
- shadows.push(entry);
- };
-
- for (const b of collectBullets(section.lines)) {
- const parsed = parseShadowBullet(b);
- if (parsed) dedupe(parsed);
- }
-
- // Fallback: extract shadows written inline in prose. Stitch style is
- // "...use an extra-diffused shadow: `box-shadow: 0 12px 40px rgba(...)`."
- for (const p of collectParagraphs(section.lines)) {
- for (const inline of extractInlineShadows(p)) dedupe(inline);
- }
- for (const b of collectBullets(section.lines)) {
- for (const inline of extractInlineShadows(b)) dedupe(inline);
- }
-
- return {
- subtitle: section.subtitle,
- description,
- shadows,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function extractInlineShadows(text) {
- // Find `box-shadow: ...` anywhere in prose and capture the value. Work on the
- // raw string so it handles both backtick-fenced and unfenced variants.
- const out = [];
- const re = /box-shadow\s*:\s*([^`;\n]+)/gi;
- let m;
- while ((m = re.exec(text)) !== null) {
- const value = m[1].replace(/[`.)]+$/, '').trim();
- if (!value) continue;
- // Name heuristic: the noun immediately before the shadow phrase.
- // e.g. "an extra-diffused shadow: ..." -> "extra-diffused shadow"
- const before = text.slice(0, m.index);
- const nameMatch = before.match(/\b([A-Za-z][A-Za-z\- ]{2,40})\s+shadow\b[^A-Za-z0-9]*$/i);
- let name = null;
- if (nameMatch) {
- const stripped = nameMatch[1]
- .replace(/^(?:use|using|apply|applying|is|are|looks? like)\s+/i, '')
- .replace(/^(?:a|an|the)\s+/i, '')
- .trim();
- if (stripped) {
- name =
- stripped.charAt(0).toUpperCase() + stripped.slice(1) + ' shadow';
- }
- }
- out.push({
- name,
- value,
- purpose: null,
- });
- }
- return out;
-}
-
-function parseShadowBullet(bullet) {
- // - **Name** (`box-shadow: value`): purpose
- // - **Name** (`value`): purpose
- // Only accept if the paren content looks like a shadow value (contains px,
- // rem, rgba, or box-shadow). This filters out `**Rule Name:**` bullets.
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(`?([^`]+?)`?\):\s*(.*)$/);
- if (!m) return null;
- const rawValue = m[2].replace(/^box-shadow:\s*/i, '').trim();
- const looksLikeShadow =
- /box-shadow|rgba?\(|\bpx\b|\brem\b|^-?\d+\s/i.test(rawValue) &&
- /\d/.test(rawValue);
- if (!looksLikeShadow) return null;
- const name = stripBold(m[1]).trim();
- return {
- name,
- value: rawValue,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractComponents(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const components = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
-
- const bullets = collectBullets(sub.lines);
- const paragraphs = collectParagraphs(sub.lines);
-
- const variants = [];
- const properties = {};
-
- for (const b of bullets) {
- // - **Key:** value
- const m = b.match(/^\*\*(.+?):?\*\*:?\s*(.+)$/);
- if (m) {
- const key = stripBold(m[1]).trim();
- const value = stripBold(m[2]).trim();
- // Heuristic: "Primary", "Secondary", "Hover", "Focus" etc are variants;
- // "Shape", "Background", "Padding" are properties.
- if (/^(primary|secondary|tertiary|ghost|hover|focus|active|disabled|default|error|selected|unselected|state)$/i.test(key.split(/[\s/]/)[0])) {
- variants.push({ name: key, description: value });
- } else {
- properties[key.toLowerCase()] = value;
- }
- }
- }
-
- components.push({
- name: sub.name,
- description: paragraphs.join(' ') || null,
- properties,
- variants,
- });
- }
-
- return {
- subtitle: section.subtitle,
- components,
- };
-}
-
-function extractDosDonts(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const dos = [];
- const donts = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
- const subName = normalizeApostrophes(sub.name);
- const bullets = collectBullets(sub.lines).map((b) => stripBold(b).trim());
- if (/^do'?t?:?$/i.test(subName) || /^do:?$/i.test(subName)) {
- dos.push(...bullets);
- } else if (/^don'?t:?$/i.test(subName)) {
- donts.push(...bullets);
- }
- }
-
- // Classify by bullet prefix as a backup (catches loose bullets outside H3 wrappers)
- for (const b of collectBullets(section.lines)) {
- const stripped = normalizeApostrophes(stripBold(b).trim());
- if (/^don'?t\b/i.test(stripped)) {
- if (!donts.some((d) => normalizeApostrophes(d) === stripped)) donts.push(stripped);
- } else if (/^do\b/i.test(stripped)) {
- if (!dos.some((d) => normalizeApostrophes(d) === stripped)) dos.push(stripped);
- }
- }
-
- return { dos, donts };
-}
-
-// ---------- Coverage assessment ----------
-
-function assessCoverage(model) {
- const report = {};
-
- report.overview = model.overview
- ? {
- northStar: Boolean(model.overview.creativeNorthStar),
- philosophy: model.overview.philosophy.length > 0,
- keyCharacteristics: model.overview.keyCharacteristics.length,
- }
- : 'missing';
-
- report.colors = model.colors
- ? {
- groups: model.colors.groups.length,
- totalColors: model.colors.groups.reduce((n, g) => n + g.colors.length, 0),
- rules: model.colors.rules.length,
- }
- : 'missing';
-
- report.typography = model.typography
- ? {
- fonts: Object.keys(model.typography.fonts).length,
- hierarchyEntries: model.typography.hierarchy.length,
- character: Boolean(model.typography.character),
- rules: model.typography.rules.length,
- }
- : 'missing';
-
- report.elevation = model.elevation
- ? {
- shadows: model.elevation.shadows.length,
- rules: model.elevation.rules.length,
- description: Boolean(model.elevation.description),
- }
- : 'missing';
-
- report.components = model.components
- ? {
- count: model.components.components.length,
- variantTotal: model.components.components.reduce((n, c) => n + c.variants.length, 0),
- }
- : 'missing';
-
- report.dosDonts = model.dosDonts
- ? {
- dos: model.dosDonts.dos.length,
- donts: model.dosDonts.donts.length,
- }
- : 'missing';
-
- return report;
-}
-
-// ---------- Main ----------
-
-export function parseDesignMd(md) {
- const { frontmatter, body } = parseFrontmatter(md);
- const { title, sections } = splitSections(body);
- return {
- schemaVersion: 2,
- title,
- frontmatter,
- overview: extractOverview(sections['Overview']),
- colors: extractColors(sections['Colors']),
- typography: extractTypography(sections['Typography']),
- elevation: extractElevation(sections['Elevation']),
- components: extractComponents(sections['Components']),
- dosDonts: extractDosDonts(sections["Do's and Don'ts"]),
- };
-}
-
-export { assessCoverage };
@@ -1,198 +0,0 @@
-/**
- * Scan a project tree for Content-Security-Policy signals and classify the
- * shape so the agent knows which patch template to propose.
- *
- * Used at first-time `live.mjs` setup. Mechanical (grep-based) — no network,
- * no dev server, no JS evaluation. The classification drives a user-facing
- * consent prompt; the agent does the actual patch writing.
- *
- * Shapes are named by patch mechanism, not framework origin:
- * - "append-arrays": CSP defined as structured directive arrays. Patch
- * appends a dev-only localhost entry. Covers:
- * - Monorepo helpers with additional*Src options
- * (e.g. createBaseNextConfig for Next)
- * - SvelteKit kit.csp.directives
- * - nuxt-security module's contentSecurityPolicy
- * - "append-string": CSP built as a literal value string. Patch splices
- * a dev-only token into script-src and connect-src.
- * Covers:
- * - Inline Next.js headers() with CSP string
- * - Nuxt routeRules / nitro.routeRules CSP headers
- * - "middleware": CSP set dynamically in middleware.{ts,js}.
- * Detected but not auto-patched in v1.
- * - "meta-tag": <meta http-equiv="Content-Security-Policy"> in
- * layout files. Detected but not auto-patched in v1.
- * - null: no CSP signals found; no patch needed.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const SKIP_DIRS = new Set([
- 'node_modules',
- '.git',
- '.next',
- '.turbo',
- '.svelte-kit',
- '.nuxt',
- '.astro',
- 'dist',
- 'build',
- 'out',
- '.vercel',
-]);
-
-const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.tsx', '.jsx']);
-const LAYOUT_EXTS = new Set(['.tsx', '.jsx', '.astro', '.vue', '.svelte', '.html']);
-const MAX_DEPTH = 6;
-const MAX_READ_BYTES = 64 * 1024;
-
-// append-arrays signals: CSP expressed as structured directive arrays
-const MONOREPO_HELPER_SIGNALS = [
- /\bbuildCSPConfig\b/,
- /\bbuildSecurityHeaders\b/,
- /\badditionalScriptSrc\b/,
- /\badditionalConnectSrc\b/,
- /\bcreateBaseNextConfig\b/,
-];
-const SVELTEKIT_CSP_SIGNALS = [
- /\bkit\s*:/,
- /\bcsp\s*:/,
- /\bdirectives\s*:/,
-];
-const NUXT_SECURITY_SIGNALS = [
- /['"]nuxt-security['"]/,
- /\bcontentSecurityPolicy\b/,
-];
-
-// append-string signals: CSP written as a literal value string
-const INLINE_HEADER_SIGNALS = [
- /["']Content-Security-Policy["']/i,
- /\bscript-src\b/,
- /\bconnect-src\b/,
-];
-const NUXT_ROUTE_RULES_SIGNALS = [
- /\brouteRules\b/,
- /Content-Security-Policy/i,
- /\bscript-src\b/,
-];
-
-const MIDDLEWARE_HINT = /headers\.set\(\s*["']Content-Security-Policy["']/i;
-const META_TAG_HINT = /http-equiv\s*=\s*["']Content-Security-Policy["']/i;
-
-/**
- * @param {string} cwd Project root.
- * @returns {{ shape: string|null, signals: string[] }}
- */
-export function detectCsp(cwd = process.cwd()) {
- const hits = { appendArrays: [], appendString: [], middleware: [], metaTag: [] };
-
- walk(cwd, cwd, 0, (absPath, relPath, body) => {
- const ext = path.extname(absPath);
- const base = path.basename(absPath).toLowerCase();
- const isConfig = (name) =>
- new RegExp('(^|/)' + name + '\\.config\\.').test(relPath);
-
- // === append-arrays candidates ===
-
- // Monorepo CSP helper: packages/*/src/.../(config|security)/*
- if (SCAN_EXTS.has(ext) &&
- /packages\/[^/]+\/src\/.*(config|next-config|security)/.test(relPath) &&
- MONOREPO_HELPER_SIGNALS.some((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // SvelteKit kit.csp.directives
- if (SCAN_EXTS.has(ext) && isConfig('svelte') &&
- SVELTEKIT_CSP_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // Nuxt nuxt-security module
- if (SCAN_EXTS.has(ext) && isConfig('nuxt') &&
- NUXT_SECURITY_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // === append-string candidates ===
-
- // Inline headers in Next/Nuxt/SvelteKit/Astro/Vite config
- if (SCAN_EXTS.has(ext) &&
- /(^|\/)(next|nuxt|vite|astro|svelte)\.config\./.test(relPath) &&
- INLINE_HEADER_SIGNALS.every((re) => re.test(body))) {
- // Nuxt routeRules is a sub-shape of append-string; we already covered
- // nuxt-security above via return, so any remaining Nuxt CSP match here
- // is a route-rules / inline-headers case. Either way, same patch
- // mechanism.
- hits.appendString.push(relPath);
- return;
- }
-
- // === detect-only shapes ===
-
- if ((base === 'middleware.ts' || base === 'middleware.js' || base === 'middleware.mjs') &&
- MIDDLEWARE_HINT.test(body)) {
- hits.middleware.push(relPath);
- }
-
- if (LAYOUT_EXTS.has(ext) && META_TAG_HINT.test(body)) {
- hits.metaTag.push(relPath);
- }
- });
-
- // Priority: append-arrays > append-string > middleware > meta-tag.
- // Structured patches are safer than string splices; runtime and HTML
- // injection patches are less reliable and v1 doesn't auto-apply them.
- if (hits.appendArrays.length > 0) {
- return { shape: 'append-arrays', signals: hits.appendArrays };
- }
- if (hits.appendString.length > 0) {
- return { shape: 'append-string', signals: hits.appendString };
- }
- if (hits.middleware.length > 0) {
- return { shape: 'middleware', signals: hits.middleware };
- }
- if (hits.metaTag.length > 0) {
- return { shape: 'meta-tag', signals: hits.metaTag };
- }
- return { shape: null, signals: [] };
-}
-
-function walk(root, dir, depth, visit) {
- if (depth > MAX_DEPTH) return;
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
-
- for (const entry of entries) {
- const abs = path.join(dir, entry.name);
- if (entry.isDirectory()) {
- if (SKIP_DIRS.has(entry.name)) continue;
- walk(root, abs, depth + 1, visit);
- continue;
- }
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name);
- if (!SCAN_EXTS.has(ext) && !LAYOUT_EXTS.has(ext)) continue;
- let body;
- try {
- const fd = fs.openSync(abs, 'r');
- try {
- const buf = Buffer.alloc(MAX_READ_BYTES);
- const n = fs.readSync(fd, buf, 0, MAX_READ_BYTES, 0);
- body = buf.slice(0, n).toString('utf-8');
- } finally { fs.closeSync(fd); }
- } catch { continue; }
- visit(abs, path.relative(root, abs), body);
- }
-}
-
-// CLI mode
-const _running = process.argv[1];
-if (_running?.endsWith('detect-csp.mjs') || _running?.endsWith('detect-csp.mjs/')) {
- const result = detectCsp(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
@@ -1,21 +0,0 @@
-#!/usr/bin/env node
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { pathToFileURL, fileURLToPath } from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const candidates = [
- path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
-];
-const detectorPath = candidates.find(p => fs.existsSync(p));
-
-if (!detectorPath) {
- process.stderr.write('Error: bundled detector not found.\n');
- process.exit(1);
-}
-
-const { detectCli } = await import(pathToFileURL(detectorPath));
-
-await detectCli();
@@ -1,1688 +0,0 @@
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
@@ -1,232 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
-import { detectHtml } from '../engines/static-html/detect-html.mjs';
-import { detectText } from '../engines/regex/detect-text.mjs';
-import {
- HTML_EXTENSIONS,
- buildImportGraph,
- detectFrameworkConfig,
- isPortListening,
- walkDir,
-} from '../node/file-system.mjs';
-
-// ---------------------------------------------------------------------------
-// Output formatting
-// ---------------------------------------------------------------------------
-
-function formatFindings(findings, jsonMode) {
- if (jsonMode) return JSON.stringify(findings, null, 2);
-
- const grouped = {};
- for (const f of findings) {
- if (!grouped[f.file]) grouped[f.file] = [];
- grouped[f.file].push(f);
- }
- const out = [];
- for (const [file, items] of Object.entries(grouped)) {
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
- out.push(`\n${file}${importNote}`);
- for (const item of items) {
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
- out.push(` → ${item.description}`);
- }
- }
- out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
- return out.join('\n');
-}
-
-// ---------------------------------------------------------------------------
-// Stdin handling
-// ---------------------------------------------------------------------------
-
-async function handleStdin() {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- const input = Buffer.concat(chunks).toString('utf-8');
- try {
- const parsed = JSON.parse(input);
- const fp = parsed?.tool_input?.file_path;
- if (fp && fs.existsSync(fp)) {
- return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
- ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
- }
- } catch { /* not JSON */ }
- return detectText(input, '<stdin>');
-}
-
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-async function confirm(question) {
- const rl = (await import('node:readline')).default.createInterface({
- input: process.stdin, output: process.stderr,
- });
- return new Promise((resolve) => {
- rl.question(`${question} [Y/n] `, (answer) => {
- rl.close();
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
- });
- });
-}
-
-function printUsage() {
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
-
-Scan files or URLs for UI anti-patterns and design quality issues.
-
-Options:
- --fast Regex-only mode (skip static HTML/CSS analysis, faster but misses linked stylesheets)
- --json Output results as JSON
- --help Show this help message
-
-Detection modes:
- HTML files Static HTML/CSS analysis (default, catches linked CSS)
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
- URLs Puppeteer full browser rendering (auto-detected)
- --fast Forces regex for all files
-
-Examples:
- impeccable detect src/
- impeccable detect index.html
- impeccable detect https://example.com
- impeccable detect --fast --json .`);
-}
-
-async function detectCli() {
- let args = process.argv.slice(2).map(arg => {
- if (arg === '-json') return '--json';
- if (arg === '-fast') return '--fast';
- return arg;
- });
- if (args[0] === 'detect') args = args.slice(1);
- const jsonMode = args.includes('--json');
- const helpMode = args.includes('--help');
- const fastMode = args.includes('--fast');
- const targets = args.filter(a => !a.startsWith('--'));
-
- if (helpMode) { printUsage(); process.exit(0); }
-
- let allFindings = [];
-
- if (!process.stdin.isTTY && targets.length === 0) {
- allFindings = await handleStdin();
- } else {
- const paths = targets.length > 0 ? targets : [process.cwd()];
- const urlTargetCount = paths.filter(target => /^https?:\/\//i.test(target)).length;
- const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
-
- try {
- for (const target of paths) {
- if (/^https?:\/\//i.test(target)) {
- try {
- const scanner = browserDetector
- ? (url) => browserDetector.detectUrl(url)
- : (url) => detectUrl(url);
- allFindings.push(...await scanner(target));
- } catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
- continue;
- }
-
- const resolved = path.resolve(target);
- let stat;
- try { stat = fs.statSync(resolved); }
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
-
- if (stat.isDirectory()) {
- // Check for framework dev server config (skip in JSON mode to avoid polluting output)
- if (!jsonMode) {
- const fwConfig = detectFrameworkConfig(resolved);
- if (fwConfig) {
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
- if (probe.listening && probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
- `For more accurate results, scan the running site:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- } else if (probe.listening && !probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
- );
- } else {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Start the dev server and scan via URL for best results:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- }
- }
- }
-
- const files = walkDir(resolved);
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
-
- // Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
- if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
- process.stderr.write(
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
- `Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
- `Use --fast to skip static HTML/CSS analysis, or target a specific subdirectory.\n`
- );
- const ok = await confirm('Continue?');
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
- }
-
- // Build import graph for multi-file awareness
- const graph = buildImportGraph(files);
- // Build reverse map: file -> set of files that import it
- const importedByMap = new Map();
- for (const [importer, imports] of graph) {
- for (const imported of imports) {
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
- importedByMap.get(imported).add(importer);
- }
- }
-
- for (const file of files) {
- const ext = path.extname(file).toLowerCase();
- let fileFindings;
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- fileFindings = await detectHtml(file);
- } else {
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
- }
- // Annotate findings with import context
- const importers = importedByMap.get(file);
- if (importers && importers.size > 0) {
- const importerNames = [...importers].map(f => path.basename(f));
- for (const f of fileFindings) {
- f.importedBy = importerNames;
- }
- }
- allFindings.push(...fileFindings);
- }
- } else if (stat.isFile()) {
- const ext = path.extname(resolved).toLowerCase();
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- allFindings.push(...await detectHtml(resolved));
- } else {
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
- }
- }
- }
- } finally {
- if (browserDetector) await browserDetector.close();
- }
- }
-
- if (allFindings.length > 0) {
- if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
- else process.stderr.write(formatFindings(allFindings, false) + '\n');
- process.exit(2);
- }
- if (jsonMode) process.stdout.write('[]\n');
- process.exit(0);
-}
-
-export { formatFindings, handleStdin, confirm, printUsage, detectCli };
@@ -1,4030 +0,0 @@
-/**
- * Anti-Pattern Browser Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * GENERATED -- do not edit. Source: cli/engine/browser/injected/index.mjs
- * Rebuild: node scripts/build-browser-detector.js
- *
- * Usage: <script src="detect-antipatterns-browser.js"></script>
- * Re-scan: window.impeccableScan()
- */
-(function () {
-if (typeof window === 'undefined') return;
-// --- cli/engine/shared/constants.mjs ---
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-// --- cli/engine/registry/antipatterns.mjs ---
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-// --- cli/engine/shared/color.mjs ---
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-// --- cli/engine/rules/checks.mjs ---
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-// --- cli/engine/browser/injected/index.mjs ---
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
-
-})();
@@ -1,43 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Anti-Pattern Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * Public API facade. Runtime engines live under cli/engine/engines/.
- */
-
-import { detectCli } from './cli/main.mjs';
-
-export { ANTIPATTERNS, RULE_ENGINE_SUPPORT, getAntipattern, getRulesForCategory, getRuleEngineSupport } from './registry/antipatterns.mjs';
-export { SAFE_TAGS, BORDER_SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS, KNOWN_SERIF_FONTS } from './shared/constants.mjs';
-export { isNeutralColor, parseRgb, relativeLuminance, contrastRatio, parseGradientColors, hasChroma, getHue, colorToHex } from './shared/color.mjs';
-export { isFullPage } from './shared/page.mjs';
-export {
- checkElementBorders,
- checkElementMotion,
- checkElementGlow,
- checkPageTypography,
- checkPageLayout,
- checkHtmlPatterns,
-} from './rules/checks.mjs';
-export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
-export { detectHtml } from './engines/static-html/detect-html.mjs';
-export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
-export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
-export {
- walkDir,
- SCANNABLE_EXTENSIONS,
- SKIP_DIRS,
- buildImportGraph,
- resolveImport,
- detectFrameworkConfig,
- isPortListening,
- FRAMEWORK_CONFIGS,
-} from './node/file-system.mjs';
-export { formatFindings, detectCli } from './cli/main.mjs';
-
-const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
-if (isMainModule) detectCli();
@@ -1,251 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { finding } from '../../findings.mjs';
-import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
-
-async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
- if (options?.visualContrast === false) return [];
- const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : 12;
- const scrollOffscreen = options?.visualContrastScrollOffscreen !== false;
- const existingLowContrastSelectors = new Set(
- serializedGroups
- .filter(group => group.findings?.some(f => f.type === 'low-contrast'))
- .map(group => group.selector)
- .filter(Boolean)
- );
-
- let browserAnalyses = [];
- const findings = [];
- if (options?.visualContrastBrowser !== false) {
- const browserFindings = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'browser-fallback',
- target,
- }, async () => {
- browserAnalyses = await page.evaluate(async ({ maxCandidates, scrollOffscreen }) => {
- if (typeof window.impeccableAnalyzeVisualContrast !== 'function') return [];
- return window.impeccableAnalyzeVisualContrast({ maxCandidates, scrollOffscreen });
- }, { maxCandidates, scrollOffscreen });
- return browserAnalyses
- .filter(result => result.finding && !existingLowContrastSelectors.has(result.selector))
- .map(result => result.finding);
- });
- findings.push(...browserFindings);
- }
-
- let candidates = browserAnalyses.length > 0 ? browserAnalyses : [];
- if (candidates.length === 0) {
- candidates = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'collect-candidates',
- target,
- }, () => page.evaluate(({ maxCandidates }) => {
- if (typeof window.impeccableCollectVisualContrastCandidates !== 'function') return [];
- return window.impeccableCollectVisualContrastCandidates({ maxCandidates });
- }, { maxCandidates }));
- }
-
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const browserResolvedSelectors = new Set(
- browserAnalyses
- .filter(result => result.status === 'fail' || result.status === 'pass')
- .map(result => result.selector)
- .filter(Boolean)
- );
- const filtered = candidates.filter(candidate =>
- !existingLowContrastSelectors.has(candidate.selector) &&
- !browserResolvedSelectors.has(candidate.selector)
- );
- if (options?.visualContrastPixel === false) return findings;
- for (const candidate of filtered) {
- const result = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'pixel-diff',
- target,
- }, async () => {
- const finding = await captureVisualContrastCandidate(page, candidate, viewport);
- return finding ? [finding] : [];
- });
- findings.push(...result);
- }
- return findings;
-}
-
-// ---------------------------------------------------------------------------
-// Puppeteer detection (for URLs)
-// ---------------------------------------------------------------------------
-
-async function detectUrl(url, options = {}) {
- const profile = options?.profile;
- const waitUntil = options?.waitUntil || 'networkidle0';
- const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const externalBrowser = options?.browser || null;
- let puppeteer;
- if (!externalBrowser) {
- try {
- puppeteer = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'import-puppeteer',
- target: url,
- }, () => import('puppeteer'));
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- }
-
- // Read the browser detection script — reuse it instead of reimplementing
- const browserScriptPath = path.resolve(
- path.dirname(fileURLToPath(import.meta.url)),
- '..',
- '..',
- 'detect-antipatterns-browser.js'
- );
- let browserScript;
- try {
- browserScript = profileStep(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'read-browser-script',
- target: url,
- }, () => fs.readFileSync(browserScriptPath, 'utf-8'));
- } catch {
- throw new Error(`Browser script not found at ${browserScriptPath}`);
- }
-
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
- // running in CI; local users keep the default hardened launch.
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
- const browser = externalBrowser || await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'launch-browser',
- target: url,
- }, () => puppeteer.default.launch({ headless: true, args: launchArgs }));
- const page = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'new-page',
- target: url,
- }, () => browser.newPage());
- let results = [];
- try {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'set-viewport',
- target: url,
- }, () => page.setViewport(viewport));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: `goto:${waitUntil}`,
- target: url,
- }, () => page.goto(url, { waitUntil, timeout: 30000 }));
- if (settleMs > 0) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'settle',
- target: url,
- }, () => new Promise(resolve => setTimeout(resolve, settleMs)));
- }
-
- // Inject the browser detection script and collect results
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'configure-pure-detect',
- target: url,
- }, () => page.evaluate(() => {
- window.__IMPECCABLE_CONFIG__ = {
- ...(window.__IMPECCABLE_CONFIG__ || {}),
- autoScan: false,
- };
- }));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'inject-browser-script',
- target: url,
- }, () => page.evaluate(browserScript));
- let serializedGroups = [];
- results = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'browser-scan',
- target: url,
- }, async () => {
- serializedGroups = await page.evaluate(() => {
- if (!window.impeccableDetect) return [];
- return window.impeccableDetect({ decorate: false, serialize: true });
- });
- return serializedGroups.flatMap(({ findings }) =>
- findings.map(f => ({ id: f.type, snippet: f.detail }))
- );
- });
- const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
- results.push(...visualFindings);
- } finally {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-page',
- target: url,
- }, () => page.close().catch(() => {}));
- if (!externalBrowser) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-browser',
- target: url,
- }, () => browser.close());
- }
- }
- return results.map(f => finding(f.id, url, f.snippet));
-}
-
-async function createBrowserDetector(options = {}) {
- let puppeteer;
- try {
- puppeteer = await import('puppeteer');
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- const launchArgs = options.launchArgs || (process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : []);
- const browser = options.browser || await puppeteer.default.launch({
- headless: options.headless ?? true,
- args: launchArgs,
- });
- const ownsBrowser = !options.browser;
- const defaults = {
- waitUntil: options.waitUntil || 'load',
- settleMs: Number.isFinite(options.settleMs) ? options.settleMs : 100,
- viewport: options.viewport || { width: 1280, height: 800 },
- };
- return {
- browser,
- async detectUrl(url, scanOptions = {}) {
- return detectUrl(url, {
- ...defaults,
- ...scanOptions,
- browser,
- });
- },
- async close() {
- if (ownsBrowser) await browser.close().catch(() => {});
- },
- };
-}
-
-export { runVisualContrastFallback, detectUrl, createBrowserDetector };
@@ -1,420 +0,0 @@
-import { GENERIC_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep } from '../../profile/profiler.mjs';
-
-// ---------------------------------------------------------------------------
-// Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
-// ---------------------------------------------------------------------------
-
-const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
-const hasBorderRadius = (line) => /border-radius/i.test(line);
-const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
-
-function isNeutralBorderColor(str) {
- const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
- if (!m) return false;
- const c = m[1].toLowerCase();
- if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
- const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
- if (hex) {
- const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
- if (shex) {
- const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- return false;
-}
-
-const REGEX_MATCHERS = [
- // --- Side-tab ---
- { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
- test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
- test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
- fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
- { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
- test: (m) => +m[1] >= 3,
- fmt: (m) => m[0] },
- // --- Border accent on rounded ---
- { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
- test: (m, line) => hasRounded(line) && +m[1] >= 1,
- fmt: (m) => m[0] },
- { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
- fmt: (m) => m[0] },
- // --- Overused font ---
- { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
- test: () => true,
- fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
- // --- Pure black background ---
- { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Gradient text ---
- { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
- test: (m, line) => /gradient/i.test(line),
- fmt: () => 'background-clip: text + gradient' },
- // --- Gradient text (Tailwind) ---
- { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
- test: (m, line) => /\bbg-gradient-to-/i.test(line),
- fmt: () => 'bg-clip-text + bg-gradient' },
- // --- Tailwind pure black background ---
- { id: 'pure-black-white', regex: /\bbg-black\b/g,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Tailwind gray on colored bg ---
- { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
- test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
- fmt: (m, line) => { const bg = line.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/); return `${m[0]} on ${bg?.[0] || '?'}`; } },
- // --- Tailwind AI palette ---
- { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
- fmt: (m) => `${m[0]} on heading` },
- { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
- fmt: (m) => `${m[0]} gradient` },
- // --- Bounce/elastic easing ---
- { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
- test: () => true,
- fmt: () => 'animate-bounce (Tailwind)' },
- { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
- test: (m) => {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
- },
- fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
- // --- Layout property transition ---
- { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition: ${found ? found.join(', ') : m[1].trim()}`;
- } },
- { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
- } },
-];
-
-const REGEX_ANALYZERS = [
- // Single font
- (content, filePath) => {
- const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
- const fonts = new Set();
- let m;
- while ((m = fontFamilyRe.exec(content)) !== null) {
- for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
- }
- }
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- while ((m = gfRe.exec(content)) !== null) {
- for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
- }
- if (fonts.size !== 1 || content.split('\n').length < 20) return [];
- const name = [...fonts][0];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
- return [finding('single-font', filePath, `only font used is ${name}`, line)];
- },
- // Flat type hierarchy
- (content, filePath) => {
- const sizes = new Set();
- const REM = 16;
- let m;
- const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
- while ((m = sizeRe.exec(content)) !== null) {
- const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
- if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
- }
- const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
- while ((m = clampRe.exec(content)) !== null) {
- sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
- sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
- }
- const TW = { 'text-xs': 12, 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24, 'text-3xl': 30, 'text-4xl': 36, 'text-5xl': 48, 'text-6xl': 60, 'text-7xl': 72, 'text-8xl': 96, 'text-9xl': 128 };
- for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
- if (sizes.size < 3) return [];
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio >= 2.0) return [];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (/font-size/i.test(lines[i]) || /\btext-(?:xs|sm|base|lg|xl|\d)/i.test(lines[i])) { line = i + 1; break; } }
- return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
- },
- // Monotonous spacing (regex)
- (content, filePath) => {
- const vals = [];
- let m;
- const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
- const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
- const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
- const rounded = vals.map(v => Math.round(v / 4) * 4);
- if (rounded.length < 10) return [];
- const counts = {};
- for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const pct = maxCount / rounded.length;
- const unique = [...new Set(rounded)].filter(v => v > 0);
- if (pct <= 0.6 || unique.length > 3) return [];
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
- },
- // Everything centered (regex)
- (content, filePath) => {
- const lines = content.split('\n');
- let centered = 0, total = 0;
- for (const line of lines) {
- if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
- total++;
- if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
- }
- }
- if (total < 5 || centered / total <= 0.7) return [];
- return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
- },
- // Dark glow (page-level: dark bg + colored box-shadow with blur)
- (content, filePath) => {
- // Check if page has a dark background
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
- if (!hasDarkBg) return [];
-
- // Check for colored box-shadow with blur > 4px
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let m;
- while ((m = shadowRe.exec(content)) !== null) {
- const val = m[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
- // Check blur: look for pattern like "0 0 20px" (third number > 4)
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- const lines = content.substring(0, m.index).split('\n');
- return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
- }
- }
- return [];
- },
-];
-
-// ---------------------------------------------------------------------------
-// Style block extraction (Vue/Svelte <style> blocks)
-// ---------------------------------------------------------------------------
-
-function extractStyleBlocks(content, ext) {
- ext = ext.toLowerCase();
- if (ext !== '.vue' && ext !== '.svelte') return [];
- const blocks = [];
- const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length + 1;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-// ---------------------------------------------------------------------------
-// CSS-in-JS extraction (styled-components, emotion)
-// ---------------------------------------------------------------------------
-
-const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
-
-function extractCSSinJS(content, ext) {
- ext = ext.toLowerCase();
- if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
- const blocks = [];
- const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null, options = {}) {
- const { profile, phase = 'regex-matchers' } = options || {};
- const findings = [];
- if (!profile) {
- for (const matcher of REGEX_MATCHERS) {
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- }
- return findings;
- }
-
- for (const matcher of REGEX_MATCHERS) {
- const matcherFindings = profileFindings(profile, {
- engine: 'regex',
- phase,
- ruleId: matcher.id,
- target: filePath,
- }, () => {
- const matches = [];
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- matches.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- return matches;
- });
- findings.push(...matcherFindings);
- }
- return findings;
-}
-
-function detectText(content, filePath, options = {}) {
- const profile = options?.profile;
- const findings = [];
- const lines = content.split('\n');
- const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
-
- // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
- // Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
- findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
- profile,
- phase: 'source',
- }));
-
- // Extract and scan <style> blocks from Vue/Svelte SFCs
- const styleBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'style-blocks',
- target: filePath,
- }, () => extractStyleBlocks(content, ext))
- : extractStyleBlocks(content, ext);
- for (const block of styleBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'style-block',
- }));
- }
-
- // Extract and scan CSS-in-JS template literals
- const cssJsBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'css-in-js',
- target: filePath,
- }, () => extractCSSinJS(content, ext))
- : extractCSSinJS(content, ext);
- for (const block of cssJsBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'css-in-js',
- }));
- }
-
- // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
- const deduped = [];
- for (const f of findings) {
- const isDupe = deduped.some(d =>
- d.antipattern === f.antipattern &&
- d.snippet === f.snippet &&
- Math.abs(d.line - f.line) <= 2
- );
- if (!isDupe) deduped.push(f);
- }
-
- // Page-level analyzers only run on full pages
- if (isFullPage(content)) {
- const analyzerIds = [
- 'single-font',
- 'flat-type-hierarchy',
- 'monotonous-spacing',
- 'everything-centered',
- 'dark-glow',
- ];
- for (let i = 0; i < REGEX_ANALYZERS.length; i++) {
- const analyzer = REGEX_ANALYZERS[i];
- deduped.push(...profileFindings(profile, {
- engine: 'regex',
- phase: 'page-analyzer',
- ruleId: analyzerIds[i] || `analyzer-${i + 1}`,
- target: filePath,
- }, () => analyzer(content, filePath)));
- }
- }
-
- return deduped;
-}
-
-export {
- REGEX_MATCHERS,
- REGEX_ANALYZERS,
- extractStyleBlocks,
- extractCSSinJS,
- runRegexMatchers,
- detectText,
-};
@@ -1,954 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { profileStep, recordProfileEvent } from '../../profile/profiler.mjs';
-import { parseAnyColor, resolveLengthPx, resolveVarRefs } from '../../rules/checks.mjs';
-
-// ---------------------------------------------------------------------------
-// jsdom CSS-variable border override map
-// ---------------------------------------------------------------------------
-//
-// jsdom's CSSOM silently drops any border shorthand that contains a var()
-// reference — the computed style for the element then shows empty width,
-// empty style, and a default black color. That's enough to hide the most
-// common real-world side-tab pattern in AI-generated pages:
-//
-// :root { --brand: #87a8ff; }
-// .card { border-left: 5px solid var(--brand); border-radius: 4px; }
-//
-// Real browsers (and therefore the browser detector path) resolve var()
-// natively, so this only affects the Node jsdom path.
-//
-// This pre-pass walks the stylesheets, finds any rule whose per-side or
-// all-sides border property contains var(), resolves the var() against
-// :root-level custom properties (read from the documentElement's computed
-// style, which jsdom DOES handle correctly), and attaches the resolved
-// width+color to every element that matches the rule's selector. The
-// Node-side `checkElementBorders` adapter consumes that map as a fallback
-// whenever jsdom's computed style came back empty.
-//
-// Limitations (intentional, to keep the pass simple):
-// * Only :root-level custom properties are resolved. Scoped overrides on
-// descendants are not tracked — uncommon in practice and would require
-// a per-element cascade walk.
-// * @media / @supports wrapped rules are ignored (jsdom often mishandles
-// these anyway).
-// * The fallback only fills sides that jsdom left empty, so any rule
-// whose border parses normally still wins via the computed style.
-
-const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
-
-// isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
-// CSS variables typically hold hex or named colors, so normalize those to
-// rgb() before handing the value off to the shared check. Anything we don't
-// recognise is passed through unchanged — isNeutralColor then treats it as
-// non-neutral, which is the safer default (matches the oklch-era bugfix).
-const NAMED_COLORS = {
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
-};
-
-function normalizeColorForCheck(value) {
- if (!value) return value;
- const v = value.trim();
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
- if (hex6) {
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
- if (hex3) {
- const [r, g, b] = [
- parseInt(hex3[1] + hex3[1], 16),
- parseInt(hex3[2] + hex3[2], 16),
- parseInt(hex3[3] + hex3[3], 16),
- ];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const named = NAMED_COLORS[v.toLowerCase()];
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
- return v;
-}
-
-function buildBorderOverrideMap(document, window) {
- const map = new Map();
- const rootStyle = window.getComputedStyle(document.documentElement);
-
- function resolveVar(value, depth = 0) {
- if (!value || depth > 10 || !value.includes('var(')) return value;
- return value.replace(
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
- (_, name, fallback) => {
- const v = rootStyle.getPropertyValue(name).trim();
- if (v) return resolveVar(v, depth + 1);
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
- return '';
- }
- );
- }
-
- function parseShorthand(text) {
- const m = text.trim().match(BORDER_SHORTHAND_RE);
- if (!m) return null;
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
- }
-
- // Read from the per-property accessors on rule.style. jsdom preserves
- // each border-* shorthand it parsed, even when the overall cssText has
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
- // `border-left: ...` loses the first declaration but keeps the second).
- const SIDE_PROPS = [
- ['borderLeft', 'Left'],
- ['borderRight', 'Right'],
- ['borderTop', 'Top'],
- ['borderBottom', 'Bottom'],
- ['borderInlineStart', 'Left'],
- ['borderInlineEnd', 'Right'],
- ];
-
- for (const sheet of document.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || []; } catch { continue; }
- for (const rule of rules) {
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
-
- const perSide = {};
-
- for (const [prop, side] of SIDE_PROPS) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const parsed = parseShorthand(resolveVar(val));
- if (parsed && parsed.color) perSide[side] = parsed;
- }
-
- // Uniform `border: <w> <style> var(...)` applies to every side the
- // per-side map didn't already claim.
- const borderAll = rule.style.border;
- if (borderAll && borderAll.includes('var(')) {
- const parsed = parseShorthand(resolveVar(borderAll));
- if (parsed && parsed.color) {
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
- if (!perSide[s]) perSide[s] = parsed;
- }
- }
- }
-
- // Longhand `border-*-color: var(...)` with width/style in separate
- // declarations. Rare in AI-generated pages, but cheap to cover.
- for (const [prop, side] of [
- ['borderLeftColor', 'Left'],
- ['borderRightColor', 'Right'],
- ['borderTopColor', 'Top'],
- ['borderBottomColor', 'Bottom'],
- ]) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const resolved = resolveVar(val).trim();
- if (!resolved) continue;
- // Width may or may not come from this rule — that's fine; the
- // adapter only substitutes the color when jsdom left it as a
- // literal var() string.
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
- }
-
- if (Object.keys(perSide).length === 0) continue;
-
- let matched;
- try { matched = document.querySelectorAll(rule.selectorText); }
- catch { continue; }
-
- for (const el of matched) {
- const existing = map.get(el);
- if (existing) {
- // Later rules overwrite earlier ones — approximates source-order
- // cascade for equal-specificity rules and is good enough for the
- // uncontested var()-dropped sides we're trying to recover.
- Object.assign(existing, perSide);
- } else {
- map.set(el, { ...perSide });
- }
- }
- }
- }
-
- return map;
-}
-
-// Strip `@layer NAME { … }` wrappers from a CSS / HTML source, leaving
-// the inner rules as flat CSS. jsdom doesn't implement CSS @layer, so
-// any rule inside a layer block becomes invisible to getComputedStyle.
-// Tailwind v4 makes this ubiquitous: every utility class lives in
-// `@layer utilities`, and Preflight lives in `@layer base`. Without
-// unwrapping, every Tailwind-styled element returns empty computed
-// styles. We walk the source character-by-character, balancing braces
-// so we correctly handle nested style rules inside the layer block.
-function unwrapCssAtLayer(source) {
- if (!source || !source.includes('@layer')) return source;
- // Find `@layer <name>? {` openers. The match starts at the @, and
- // we then balance braces from the opening { onward.
- const re = /@layer\b[^{;]*\{/g;
- let out = '';
- let lastIdx = 0;
- let m;
- while ((m = re.exec(source)) !== null) {
- const openStart = m.index;
- const openEnd = m.index + m[0].length; // position right after `{`
- let depth = 1;
- let i = openEnd;
- while (i < source.length && depth > 0) {
- const c = source.charCodeAt(i);
- if (c === 0x7b /* { */) depth++;
- else if (c === 0x7d /* } */) depth--;
- i++;
- }
- if (depth !== 0) {
- // Unbalanced — bail and return source unchanged.
- return source;
- }
- // Emit everything before the @layer, then the inner contents
- // (between the opening { and the matched closing }), then advance.
- out += source.slice(lastIdx, openStart);
- out += source.slice(openEnd, i - 1); // i-1 = position of the closing }
- lastIdx = i;
- re.lastIndex = i;
- }
- out += source.slice(lastIdx);
- return out;
-}
-
-// ---------------------------------------------------------------------------
-// Static HTML/CSS detection (default for local HTML files)
-// ---------------------------------------------------------------------------
-
-const STATIC_INHERITED_PROPS = new Set([
- 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight',
- 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'hyphens',
- 'webkitHyphens',
-]);
-
-const STATIC_DEFAULT_STYLE = {
- color: 'rgb(0, 0, 0)',
- backgroundColor: 'rgba(0, 0, 0, 0)',
- backgroundImage: 'none',
- borderTopWidth: '0px',
- borderRightWidth: '0px',
- borderBottomWidth: '0px',
- borderLeftWidth: '0px',
- borderTopColor: 'rgb(0, 0, 0)',
- borderRightColor: 'rgb(0, 0, 0)',
- borderBottomColor: 'rgb(0, 0, 0)',
- borderLeftColor: 'rgb(0, 0, 0)',
- borderRadius: '0px',
- boxShadow: 'none',
- fontFamily: '',
- fontSize: '16px',
- fontStyle: 'normal',
- fontWeight: '400',
- lineHeight: 'normal',
- letterSpacing: 'normal',
- textTransform: 'none',
- textAlign: 'start',
- hyphens: 'manual',
- webkitHyphens: 'manual',
- transitionProperty: '',
- transitionTimingFunction: '',
- animationName: '',
- animationTimingFunction: '',
- webkitBackgroundClip: '',
- backgroundClip: '',
- width: '',
- height: '',
- paddingTop: '0px',
- paddingRight: '0px',
- paddingBottom: '0px',
- paddingLeft: '0px',
- position: 'static',
- display: '',
-};
-
-const STATIC_PROP_MAP = {
- 'background-color': 'backgroundColor',
- 'background-image': 'backgroundImage',
- 'background-clip': 'backgroundClip',
- '-webkit-background-clip': 'webkitBackgroundClip',
- 'border-radius': 'borderRadius',
- 'border-top-width': 'borderTopWidth',
- 'border-right-width': 'borderRightWidth',
- 'border-bottom-width': 'borderBottomWidth',
- 'border-left-width': 'borderLeftWidth',
- 'border-top-color': 'borderTopColor',
- 'border-right-color': 'borderRightColor',
- 'border-bottom-color': 'borderBottomColor',
- 'border-left-color': 'borderLeftColor',
- 'box-shadow': 'boxShadow',
- 'font-family': 'fontFamily',
- 'font-size': 'fontSize',
- 'font-style': 'fontStyle',
- 'font-weight': 'fontWeight',
- 'line-height': 'lineHeight',
- 'letter-spacing': 'letterSpacing',
- 'text-transform': 'textTransform',
- 'text-align': 'textAlign',
- 'hyphens': 'hyphens',
- '-webkit-hyphens': 'webkitHyphens',
- 'transition-property': 'transitionProperty',
- 'transition-timing-function': 'transitionTimingFunction',
- 'animation-name': 'animationName',
- 'animation-timing-function': 'animationTimingFunction',
- 'width': 'width',
- 'height': 'height',
- 'padding-top': 'paddingTop',
- 'padding-right': 'paddingRight',
- 'padding-bottom': 'paddingBottom',
- 'padding-left': 'paddingLeft',
- 'position': 'position',
- 'display': 'display',
-};
-
-const STATIC_NAMED_COLORS = {
- black: { r: 0, g: 0, b: 0, a: 1 },
- white: { r: 255, g: 255, b: 255, a: 1 },
- transparent: { r: 0, g: 0, b: 0, a: 0 },
- gray: { r: 128, g: 128, b: 128, a: 1 },
- grey: { r: 128, g: 128, b: 128, a: 1 },
- silver: { r: 192, g: 192, b: 192, a: 1 },
- red: { r: 255, g: 0, b: 0, a: 1 },
- green: { r: 0, g: 128, b: 0, a: 1 },
- blue: { r: 0, g: 0, b: 255, a: 1 },
-};
-
-function splitCssList(value) {
- const parts = [];
- let depth = 0, quote = '', start = 0;
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; continue; }
- if (ch === '(' || ch === '[') depth++;
- else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);
- else if (ch === ',' && depth === 0) {
- parts.push(value.slice(start, i).trim());
- start = i + 1;
- }
- }
- const tail = value.slice(start).trim();
- if (tail) parts.push(tail);
- return parts;
-}
-
-function splitCssTokens(value) {
- const tokens = [];
- let depth = 0, quote = '', current = '';
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- current += ch;
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
- if (ch === '(') { depth++; current += ch; continue; }
- if (ch === ')') { depth = Math.max(0, depth - 1); current += ch; continue; }
- if (/\s/.test(ch) && depth === 0) {
- if (current) { tokens.push(current); current = ''; }
- continue;
- }
- current += ch;
- }
- if (current) tokens.push(current);
- return tokens;
-}
-
-function cssPropToCamel(prop) {
- if (!prop) return prop;
- const mapped = STATIC_PROP_MAP[prop];
- if (mapped) return mapped;
- return prop.replace(/-([a-z])/g, (_m, ch) => ch.toUpperCase());
-}
-
-function staticColorToCss(c) {
- if (!c) return '';
- if (c.a != null && c.a < 1) return `rgba(${c.r}, ${c.g}, ${c.b}, ${Number(c.a.toFixed(3))})`;
- return `rgb(${c.r}, ${c.g}, ${c.b})`;
-}
-
-function parseStaticColor(value) {
- const parsed = parseAnyColor(value);
- if (parsed) return parsed;
- const named = STATIC_NAMED_COLORS[String(value || '').trim().toLowerCase()];
- return named ? { ...named } : null;
-}
-
-function extractStaticColor(value) {
- if (!value) return '';
- const raw = String(value).trim();
- if (/^var\(/i.test(raw)) return raw;
- const colorLike = raw.match(/(?:rgba?\([^)]+\)|oklch\([^)]+\)|oklab\([^)]+\)|lch\([^)]+\)|lab\([^)]+\)|hsla?\([^)]+\)|hwb\([^)]+\)|#[0-9a-f]{3,8}\b|\b(?:black|white|gray|grey|silver|red|green|blue|transparent)\b)/i);
- if (!colorLike) return '';
- return colorLike[0];
-}
-
-function normalizeStaticCssValue(prop, value, customProps, parentStyle, currentStyle = null) {
- let resolved = resolveVarRefs(String(value || '').trim(), customProps);
- if (resolved === 'inherit') return parentStyle?.[prop] || STATIC_DEFAULT_STYLE[prop] || '';
- const isModernBorderColor = /^border[A-Z][a-z]+Color$/.test(prop) && /^(?:oklch|oklab|lch|lab|hsl|hwb)\(/i.test(resolved);
- if (!isModernBorderColor && (/color$/i.test(prop) || prop === 'color' || prop === 'backgroundColor')) {
- const parsed = parseStaticColor(resolved);
- if (parsed) resolved = staticColorToCss(parsed);
- }
- if (prop === 'fontSize') {
- const base = parseFloat(parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'letterSpacing') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'lineHeight' && resolved !== 'normal') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- return resolved;
-}
-
-function expandStaticBoxValues(tokens) {
- if (tokens.length === 0) return ['0px', '0px', '0px', '0px'];
- if (tokens.length === 1) return [tokens[0], tokens[0], tokens[0], tokens[0]];
- if (tokens.length === 2) return [tokens[0], tokens[1], tokens[0], tokens[1]];
- if (tokens.length === 3) return [tokens[0], tokens[1], tokens[2], tokens[1]];
- return [tokens[0], tokens[1], tokens[2], tokens[3]];
-}
-
-function parseStaticBorder(value) {
- const tokens = splitCssTokens(value);
- let width = '', color = '';
- for (const token of tokens) {
- if (!width && /^-?[\d.]+(?:px|rem|em|%)$/.test(token)) width = token;
- if (!color) color = extractStaticColor(token);
- }
- return { width, color };
-}
-
-function parseStaticFont(value) {
- const out = [];
- const slashParts = value.match(/(?:^|\s)([\d.]+(?:px|rem|em|%))(?:\/([^\s]+))?/);
- if (/\bitalic\b/i.test(value)) out.push(['fontStyle', 'italic']);
- const weight = value.match(/\b([1-9]00|bold|normal|lighter|bolder)\b/i);
- if (weight) out.push(['fontWeight', weight[1]]);
- if (slashParts) {
- out.push(['fontSize', slashParts[1]]);
- if (slashParts[2]) out.push(['lineHeight', slashParts[2]]);
- const familyStart = value.indexOf(slashParts[0]) + slashParts[0].length;
- const family = value.slice(familyStart).trim();
- if (family) out.push(['fontFamily', family]);
- }
- return out;
-}
-
-function parseStaticTransition(value) {
- const props = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const prop = tokens.find(token => /^[a-z-]+$/i.test(token) && !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none)$/.test(token) && !/s$/.test(token));
- if (prop) props.push(prop);
- }
- return {
- property: props.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function parseStaticAnimation(value) {
- const names = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const name = tokens.find(token =>
- /^[a-z_-][\w-]*$/i.test(token) &&
- !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none|running|paused)$/.test(token)
- );
- if (name) names.push(name);
- }
- return {
- name: names.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function expandStaticDeclaration(prop, value) {
- const p = prop.toLowerCase();
- const v = String(value || '').trim();
- if (!v) return [];
- if (p.startsWith('--')) return [[p, v]];
- if (p === 'background') {
- const out = [];
- const hasImage = /gradient|url\(/i.test(v);
- if (hasImage) out.push(['backgroundImage', v]);
- const beforeImage = hasImage ? v.split(/(?:repeating-)?(?:linear|radial|conic)-gradient\(|url\(/i)[0] : v;
- const color = extractStaticColor(hasImage ? beforeImage : v);
- if (color) out.push(['backgroundColor', color]);
- return out;
- }
- if (p === 'border') {
- const parsed = parseStaticBorder(v);
- const out = [];
- for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
- if (parsed.width) out.push([`border${side}Width`, parsed.width]);
- if (parsed.color) out.push([`border${side}Color`, parsed.color]);
- }
- return out;
- }
- const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
- if (sideMatch) {
- const parsed = parseStaticBorder(v);
- const side = sideMatch[1][0].toUpperCase() + sideMatch[1].slice(1);
- return [
- ...(parsed.width ? [[`border${side}Width`, parsed.width]] : []),
- ...(parsed.color ? [[`border${side}Color`, parsed.color]] : []),
- ];
- }
- if (p === 'border-width') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopWidth', vals[0]],
- ['borderRightWidth', vals[1]],
- ['borderBottomWidth', vals[2]],
- ['borderLeftWidth', vals[3]],
- ];
- }
- if (p === 'border-color') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopColor', vals[0]],
- ['borderRightColor', vals[1]],
- ['borderBottomColor', vals[2]],
- ['borderLeftColor', vals[3]],
- ];
- }
- if (p === 'padding') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['paddingTop', vals[0]],
- ['paddingRight', vals[1]],
- ['paddingBottom', vals[2]],
- ['paddingLeft', vals[3]],
- ];
- }
- if (p === 'font') return parseStaticFont(v);
- if (p === 'transition') {
- const parsed = parseStaticTransition(v);
- return [
- ...(parsed.property ? [['transitionProperty', parsed.property]] : []),
- ...(parsed.timing ? [['transitionTimingFunction', parsed.timing]] : []),
- ];
- }
- if (p === 'animation') {
- const parsed = parseStaticAnimation(v);
- return [
- ...(parsed.name ? [['animationName', parsed.name]] : []),
- ...(parsed.timing ? [['animationTimingFunction', parsed.timing]] : []),
- ];
- }
- const mapped = cssPropToCamel(p);
- if (STATIC_DEFAULT_STYLE[mapped] != null || STATIC_INHERITED_PROPS.has(mapped)) {
- return [[mapped, v]];
- }
- return [];
-}
-
-function compareStaticPriority(a, b) {
- if (!a) return true;
- if (!!b.important !== !!a.important) return !!b.important;
- if (!!b.inline !== !!a.inline) return !!b.inline;
- for (let i = 0; i < 3; i++) {
- if ((b.specificity[i] || 0) !== (a.specificity[i] || 0)) {
- return (b.specificity[i] || 0) > (a.specificity[i] || 0);
- }
- }
- return b.order >= a.order;
-}
-
-function staticSpecificity(selector) {
- const noWhere = selector.replace(/:where\([^)]*\)/g, '');
- const ids = (noWhere.match(/#[\w-]+/g) || []).length;
- const classes = (noWhere.match(/\.[\w-]+|\[[^\]]+\]|:(?!:)[\w-]+(?:\([^)]*\))?/g) || []).length;
- const stripped = noWhere
- .replace(/#[\w-]+/g, ' ')
- .replace(/\.[\w-]+|\[[^\]]+\]|:{1,2}[\w-]+(?:\([^)]*\))?/g, ' ')
- .replace(/[*>+~(),]/g, ' ');
- const types = (stripped.match(/\b[a-zA-Z][\w-]*\b/g) || []).length;
- return [ids, classes, types];
-}
-
-function applyStaticDeclaration(specified, node, prop, value, meta) {
- let map = specified.get(node);
- if (!map) { map = new Map(); specified.set(node, map); }
- for (const [expandedProp, expandedValue] of expandStaticDeclaration(prop, value)) {
- const existing = map.get(expandedProp);
- const next = { ...meta, prop: expandedProp, value: expandedValue };
- if (compareStaticPriority(existing, next)) map.set(expandedProp, next);
- }
-}
-
-function parseStaticStyleAttribute(styleText, orderBase = 0) {
- const decls = [];
- for (const part of String(styleText || '').split(';')) {
- const idx = part.indexOf(':');
- if (idx <= 0) continue;
- const prop = part.slice(0, idx).trim();
- let value = part.slice(idx + 1).trim();
- const important = /!important\s*$/i.test(value);
- value = value.replace(/\s*!important\s*$/i, '').trim();
- decls.push({ prop, value, important, order: orderBase + decls.length });
- }
- return decls;
-}
-
-function collectStaticCssRules(cssText, csstree) {
- const rules = [];
- let ast;
- try {
- ast = csstree.parse(cssText, { positions: false, parseValue: true, parseCustomProperty: false });
- } catch {
- return rules;
- }
- let order = 0;
- const walkList = (list, atRuleStack = []) => {
- list?.forEach?.(node => {
- if (node.type === 'Rule' && node.block) {
- if (atRuleStack.some(name => /keyframes$/i.test(name))) return;
- const selectorText = csstree.generate(node.prelude).trim();
- const declarations = [];
- node.block.children?.forEach?.(child => {
- if (child.type !== 'Declaration') return;
- declarations.push({
- prop: child.property,
- value: csstree.generate(child.value).trim(),
- important: !!child.important,
- });
- });
- for (const selector of splitCssList(selectorText)) {
- if (selector) rules.push({ selector, declarations, specificity: staticSpecificity(selector), order: order++ });
- }
- return;
- }
- if (node.type === 'Atrule' && node.block) {
- const name = String(node.name || '').toLowerCase();
- if (name === 'media' || name === 'supports' || name === 'layer') {
- walkList(node.block.children, [...atRuleStack, name]);
- }
- }
- });
- };
- walkList(ast.children);
- return rules;
-}
-
-class StaticElement {
- constructor(node, doc) {
- this.node = node;
- this._doc = doc;
- this.nodeType = 1;
- this.tagName = String(node.name || '').toUpperCase();
- this.nodeName = this.tagName;
- }
- get parentElement() {
- let cur = this.node.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- return cur ? this._doc.wrap(cur) : null;
- }
- get previousElementSibling() {
- let cur = this.node.prev;
- while (cur && cur.type !== 'tag') cur = cur.prev;
- return cur ? this._doc.wrap(cur) : null;
- }
- get children() {
- return (this.node.children || []).filter(child => child.type === 'tag').map(child => this._doc.wrap(child));
- }
- get childNodes() {
- return (this.node.children || []).map(child => {
- if (child.type === 'text') return { nodeType: 3, textContent: child.data || '' };
- if (child.type === 'tag') return this._doc.wrap(child);
- return { nodeType: 8, textContent: child.data || '' };
- });
- }
- get textContent() {
- return this._doc.domutils.textContent(this.node);
- }
- get className() {
- return this.getAttribute('class') || '';
- }
- get id() {
- return this.getAttribute('id') || '';
- }
- getAttribute(name) {
- return this.node.attribs?.[name] ?? null;
- }
- querySelector(selector) {
- try {
- const found = this._doc.selectOne(selector, this.node.children || []);
- return found ? this._doc.wrap(found) : null;
- } catch {
- return null;
- }
- }
- querySelectorAll(selector) {
- try {
- return this._doc.selectAll(selector, this.node.children || []).map(node => this._doc.wrap(node));
- } catch {
- return [];
- }
- }
- closest(selector) {
- let cur = this.node;
- while (cur && cur.type === 'tag') {
- try {
- if (this._doc.is(cur, selector)) return this._doc.wrap(cur);
- } catch {
- return null;
- }
- cur = cur.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- }
- return null;
- }
- contains(other) {
- let cur = other?.node || null;
- while (cur) {
- if (cur === this.node) return true;
- cur = cur.parent;
- }
- return false;
- }
-}
-
-class StaticDocument {
- constructor(root, modules) {
- this.root = root;
- this.selectAll = modules.selectAll;
- this.selectOne = modules.selectOne;
- this.is = modules.is;
- this.domutils = modules.domutils;
- this._wrappers = new WeakMap();
- this._styleMap = new WeakMap();
- }
- wrap(node) {
- let wrapped = this._wrappers.get(node);
- if (!wrapped) {
- wrapped = new StaticElement(node, this);
- this._wrappers.set(node, wrapped);
- }
- return wrapped;
- }
- querySelectorAll(selector) {
- try {
- return this.selectAll(selector, this.root.children || []).map(node => this.wrap(node));
- } catch {
- return [];
- }
- }
- querySelector(selector) {
- try {
- const found = this.selectOne(selector, this.root.children || []);
- return found ? this.wrap(found) : null;
- } catch {
- return null;
- }
- }
- get documentElement() {
- return this.querySelector('html');
- }
- get body() {
- return this.querySelector('body');
- }
- setStyle(node, style) {
- this._styleMap.set(node, style);
- }
- getStyle(el) {
- return this._styleMap.get(el.node) || makeStaticStyle();
- }
-}
-
-function makeStaticStyle(values = {}) {
- const style = { ...STATIC_DEFAULT_STYLE, ...values };
- style.getPropertyValue = (prop) => {
- const key = cssPropToCamel(prop);
- return style[key] || style[prop] || '';
- };
- return style;
-}
-
-function buildStaticWindow(staticDoc) {
- return {
- document: staticDoc,
- getComputedStyle: (el) => staticDoc.getStyle(el),
- };
-}
-
-function collectStaticCssText(root, fileDir, profile, filePath, modules) {
- const styleTexts = [];
- for (const styleEl of modules.selectAll('style', root.children || [])) {
- styleTexts.push(modules.domutils.textContent(styleEl));
- }
- const links = modules.selectAll('link', root.children || []);
- for (const link of links) {
- const rel = link.attribs?.rel || '';
- const href = link.attribs?.href || '';
- if (!/\bstylesheet\b/i.test(rel) || !href || /^(https?:)?\/\//i.test(href)) continue;
- const cssPath = path.resolve(fileDir, href);
- try {
- const css = profileStep(profile, {
- engine: 'static-html',
- phase: 'preprocess',
- ruleId: 'inline-linked-stylesheet',
- target: filePath,
- detail: href,
- }, () => fs.readFileSync(cssPath, 'utf-8'));
- styleTexts.push(css);
- } catch { /* skip unreadable */ }
- }
- return styleTexts.join('\n');
-}
-
-function buildStaticStyleMap(root, staticDoc, cssText, modules, profile, filePath) {
- const specified = new Map();
- const allNodes = modules.selectAll('*', root.children || []);
- const rules = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-css',
- ruleId: 'css-rules',
- target: filePath,
- }, () => collectStaticCssRules(cssText, modules.csstree));
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'css-selectors',
- target: filePath,
- }, () => {
- for (const rule of rules) {
- let matched;
- try {
- matched = modules.selectAll(rule.selector, root.children || []);
- } catch {
- recordProfileEvent(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'unsupported-selector',
- target: filePath,
- ms: 0,
- findings: 0,
- detail: rule.selector,
- });
- continue;
- }
- for (const node of matched) {
- for (const decl of rule.declarations) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: rule.specificity,
- order: rule.order,
- inline: false,
- });
- }
- }
- }
-
- let inlineOrder = rules.length + 1;
- for (const node of allNodes) {
- const styleText = node.attribs?.style;
- if (!styleText) continue;
- for (const decl of parseStaticStyleAttribute(styleText, inlineOrder)) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: [1, 0, 0],
- order: decl.order,
- inline: true,
- });
- }
- inlineOrder += 1000;
- }
- });
-
- const computeNode = (node, parentStyle = null, parentCustom = new Map()) => {
- const specifiedMap = specified.get(node) || new Map();
- const customProps = new Map(parentCustom);
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) customProps.set(prop, resolveVarRefs(decl.value, customProps));
- }
- const values = {};
- for (const prop of Object.keys(STATIC_DEFAULT_STYLE)) {
- if (STATIC_INHERITED_PROPS.has(prop) && parentStyle?.[prop] != null) values[prop] = parentStyle[prop];
- else values[prop] = STATIC_DEFAULT_STYLE[prop];
- }
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) continue;
- values[prop] = normalizeStaticCssValue(prop, decl.value, customProps, parentStyle, values);
- }
- const style = makeStaticStyle(values);
- staticDoc.setStyle(node, style);
- for (const child of node.children || []) {
- if (child.type === 'tag') computeNode(child, style, customProps);
- }
- };
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'cascade',
- ruleId: 'compute-styles',
- target: filePath,
- }, () => {
- for (const child of root.children || []) {
- if (child.type === 'tag') computeNode(child);
- }
- });
-}
-
-export {
- BORDER_SHORTHAND_RE,
- NAMED_COLORS,
- normalizeColorForCheck,
- buildBorderOverrideMap,
- unwrapCssAtLayer,
- STATIC_INHERITED_PROPS,
- STATIC_DEFAULT_STYLE,
- STATIC_PROP_MAP,
- STATIC_NAMED_COLORS,
- splitCssList,
- splitCssTokens,
- cssPropToCamel,
- staticColorToCss,
- parseStaticColor,
- extractStaticColor,
- normalizeStaticCssValue,
- expandStaticBoxValues,
- parseStaticBorder,
- parseStaticFont,
- parseStaticTransition,
- parseStaticAnimation,
- expandStaticDeclaration,
- compareStaticPriority,
- staticSpecificity,
- applyStaticDeclaration,
- parseStaticStyleAttribute,
- collectStaticCssRules,
- StaticElement,
- StaticDocument,
- makeStaticStyle,
- buildStaticWindow,
- collectStaticCssText,
- buildStaticStyleMap,
-};
@@ -1,174 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import {
- checkElementBorders,
- checkElementColors,
- checkElementGlow,
- checkElementHeroEyebrow,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementMotion,
- checkElementQuality,
- checkHtmlPatterns,
- checkPageLayout,
- checkPageQualityFromDoc,
- checkRepeatedSectionKickersFromDoc,
- resolveBackground,
- resolveBorderRadiusPx,
-} from '../../rules/checks.mjs';
-import { detectText } from '../regex/detect-text.mjs';
-import {
- StaticDocument,
- buildStaticStyleMap,
- buildStaticWindow,
- collectStaticCssText,
-} from './css-cascade.mjs';
-
-function checkStaticPageTypography(document, window) {
- const findings = [];
- const fonts = new Set();
- const overusedFound = new Set();
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span, div')) {
- const hasText = el.childNodes.some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const ff = window.getComputedStyle(el).fontFamily || '';
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
- if (fonts.size === 1 && document.querySelectorAll('*').length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div')) {
- const fontSize = parseFloat(window.getComputedStyle(el).fontSize);
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
- return findings;
-}
-
-const STATIC_ELEMENT_RULES = [
- { id: 'border-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementBorders(tag, style, null, resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window)) },
- { id: 'color-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementColors(el, style, tag, window, customPropMap, false) },
- { id: 'dark-glow', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window, customPropMap)) },
- { id: 'motion-rules', selector: '*', run: (el, tag, style) => checkElementMotion(tag, style) },
- { id: 'icon-tile-stack', selector: 'h1,h2,h3,h4,h5,h6', run: (el, tag, _style, window) => checkElementIconTile(el, tag, window) },
- { id: 'italic-serif-display', selector: 'h1,h2', run: (el, tag, style) => checkElementItalicSerif(el, style, tag) },
- { id: 'hero-eyebrow-chip', selector: 'h1', run: (el, tag, style, window, customPropMap) => checkElementHeroEyebrow(el, style, tag, window, customPropMap) },
- { id: 'quality-rules', selector: '*', run: (el, tag, style, window) => checkElementQuality(el, style, tag, window) },
-];
-
-async function detectHtml(filePath, options = {}) {
- const profile = options?.profile;
- const html = profileStep(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'read-html',
- target: filePath,
- }, () => fs.readFileSync(filePath, 'utf-8'));
-
- let modules;
- try {
- modules = await profileStepAsync(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'import-static-parser',
- target: filePath,
- }, async () => {
- const [htmlparser2, cssSelect, csstree, domutils] = await Promise.all([
- import('htmlparser2'),
- import('css-select'),
- import('css-tree'),
- import('domutils'),
- ]);
- return {
- parseDocument: htmlparser2.parseDocument,
- selectAll: cssSelect.selectAll,
- selectOne: cssSelect.selectOne,
- is: cssSelect.is,
- csstree,
- domutils,
- };
- });
- } catch {
- return detectText(html, filePath, options);
- }
-
- const resolvedPath = path.resolve(filePath);
- const fileDir = path.dirname(resolvedPath);
- const root = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-html',
- ruleId: 'parse-document',
- target: filePath,
- }, () => modules.parseDocument(html, { lowerCaseAttributeNames: false, lowerCaseTags: true }));
-
- const cssText = collectStaticCssText(root, fileDir, profile, filePath, modules);
- const document = new StaticDocument(root, modules);
- buildStaticStyleMap(root, document, cssText, modules, profile, filePath);
- const window = buildStaticWindow(document);
-
- const customPropMap = null;
-
- const findings = [];
- const runElementCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'element', ruleId, target: filePath }, callback)
- : callback();
-
- const visitedByRule = new Map();
- for (const rule of STATIC_ELEMENT_RULES) {
- const elements = document.querySelectorAll(rule.selector);
- visitedByRule.set(rule.id, elements.length);
- for (const el of elements) {
- const tag = el.tagName.toLowerCase();
- const style = window.getComputedStyle(el);
- for (const f of runElementCheck(rule.id, () => rule.run(el, tag, style, window, customPropMap))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
- }
-
- if (isFullPage(html)) {
- const runPageCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
- : callback();
- for (const f of runPageCheck('typography-rules', () => checkStaticPageTypography(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('repeated-section-kickers', () => checkRepeatedSectionKickersFromDoc(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('layout-rules', () => checkPageLayout(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('skipped-heading', () => checkPageQualityFromDoc(document))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('html-patterns', () => checkHtmlPatterns(html).filter(item =>
- item.id !== 'bounce-easing' && item.id !== 'layout-transition'
- ))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
-
- return findings;
-}
-
-export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -1,189 +0,0 @@
-function sanitizeScreenshotClip(clip, viewport) {
- if (!clip) return null;
- const x = Math.max(0, Math.floor(clip.x || 0));
- const y = Math.max(0, Math.floor(clip.y || 0));
- const width = Math.min(
- Math.max(1, Math.ceil(clip.width || 0)),
- Math.max(1, viewport?.width || 1600),
- );
- const height = Math.min(
- Math.max(1, Math.ceil(clip.height || 0)),
- 320,
- );
- if (width < 1 || height < 1) return null;
- return { x, y, width, height };
-}
-
-async function compareScreenshotContrast(page, beforeBase64, afterBase64, candidate) {
- return page.evaluate(async ({ beforeBase64, afterBase64, candidate }) => {
- const loadImage = (base64) => new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = () => reject(new Error('Could not decode contrast screenshot'));
- img.src = `data:image/png;base64,${base64}`;
- });
- const [before, after] = await Promise.all([loadImage(beforeBase64), loadImage(afterBase64)]);
- const width = Math.min(before.width, after.width);
- const height = Math.min(before.height, after.height);
- if (width < 1 || height < 1) return null;
-
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return null;
-
- ctx.drawImage(before, 0, 0, width, height);
- const beforePixels = ctx.getImageData(0, 0, width, height).data;
- ctx.clearRect(0, 0, width, height);
- ctx.drawImage(after, 0, 0, width, height);
- const afterPixels = ctx.getImageData(0, 0, width, height).data;
-
- const luminance = ({ r, g, b }) => {
- const convert = c => {
- const v = c / 255;
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
- };
- return 0.2126 * convert(r) + 0.7152 * convert(g) + 0.0722 * convert(b);
- };
- const ratio = (a, b) => {
- const l1 = luminance(a);
- const l2 = luminance(b);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
- };
-
- const cssTextColor = candidate.textColor && !candidate.preferRenderedForeground
- ? {
- r: candidate.textColor.r,
- g: candidate.textColor.g,
- b: candidate.textColor.b,
- }
- : null;
- const ratios = [];
- let glyphPixels = 0;
- let strongestDelta = 0;
- for (let i = 0; i < beforePixels.length; i += 4) {
- const delta = Math.abs(beforePixels[i] - afterPixels[i])
- + Math.abs(beforePixels[i + 1] - afterPixels[i + 1])
- + Math.abs(beforePixels[i + 2] - afterPixels[i + 2])
- + Math.abs(beforePixels[i + 3] - afterPixels[i + 3]);
- strongestDelta = Math.max(strongestDelta, delta);
- if (delta < 10) continue;
- glyphPixels++;
- const fg = cssTextColor || {
- r: beforePixels[i],
- g: beforePixels[i + 1],
- b: beforePixels[i + 2],
- };
- const bg = {
- r: afterPixels[i],
- g: afterPixels[i + 1],
- b: afterPixels[i + 2],
- };
- ratios.push(ratio(fg, bg));
- }
-
- if (ratios.length < 8) {
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: null,
- p10Ratio: null,
- medianRatio: null,
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: ratios[0],
- p10Ratio: pick(10),
- medianRatio: pick(50),
- };
- }, { beforeBase64, afterBase64, candidate });
-}
-
-async function captureVisualContrastCandidate(page, candidate, viewport) {
- const clip = sanitizeScreenshotClip(candidate.clip, viewport);
- if (!clip) return null;
-
- const beforeBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- const token = `impeccable-contrast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- const applied = await page.evaluate(({ selector, token, backgroundClipText }) => {
- let el;
- try {
- el = document.querySelector(selector);
- } catch {
- return false;
- }
- if (!el) return false;
- let style = document.getElementById('impeccable-visual-contrast-hide-style');
- if (!style) {
- style = document.createElement('style');
- style.id = 'impeccable-visual-contrast-hide-style';
- style.textContent = [
- '[data-impeccable-visual-contrast-target] {',
- ' color: transparent !important;',
- ' -webkit-text-fill-color: transparent !important;',
- ' text-shadow: none !important;',
- '}',
- '[data-impeccable-visual-contrast-target][data-impeccable-bgclip-text="true"] {',
- ' background-image: none !important;',
- '}',
- ].join('\n');
- document.head.appendChild(style);
- }
- el.setAttribute('data-impeccable-visual-contrast-target', token);
- if (backgroundClipText) el.setAttribute('data-impeccable-bgclip-text', 'true');
- return true;
- }, {
- selector: candidate.selector,
- token,
- backgroundClipText: candidate.backgroundClipText,
- });
- if (!applied) return null;
-
- let afterBase64;
- try {
- afterBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- } finally {
- await page.evaluate(({ selector }) => {
- try {
- const el = document.querySelector(selector);
- if (el) {
- el.removeAttribute('data-impeccable-visual-contrast-target');
- el.removeAttribute('data-impeccable-bgclip-text');
- }
- } catch {
- // Ignore invalid or stale selectors during cleanup.
- }
- }, { selector: candidate.selector }).catch(() => {});
- }
-
- const metrics = await compareScreenshotContrast(page, beforeBase64, afterBase64, candidate);
- if (!metrics || !Number.isFinite(metrics.p10Ratio) || metrics.glyphPixels < 8) return null;
- const measuredRatio = metrics.p10Ratio;
- if (measuredRatio >= candidate.threshold) return null;
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const reasonLabel = (candidate.reasons || []).slice(0, 3).join(', ') || 'visual background';
- return {
- id: 'low-contrast',
- snippet: `pixel contrast ${measuredRatio.toFixed(1)}:1 median ${metrics.medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) on ${reasonLabel}${textLabel}`,
- };
-}
-
-export {
- sanitizeScreenshotClip,
- compareScreenshotContrast,
- captureVisualContrastCandidate,
-};
@@ -1,12 +0,0 @@
-import { getAntipattern } from './registry/antipatterns.mjs';
-
-function getAP(id) {
- return getAntipattern(id);
-}
-
-function finding(id, filePath, snippet, line = 0) {
- const ap = getAP(id);
- return { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', file: filePath, line, snippet };
-}
-
-export { getAP, finding };
@@ -1,198 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-// ---------------------------------------------------------------------------
-// File walker
-// ---------------------------------------------------------------------------
-
-const SKIP_DIRS = new Set([
- 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
- '.svelte-kit', '__pycache__', '.turbo', '.vercel',
-]);
-
-const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
- '.jsx', '.tsx', '.js', '.ts',
- '.vue', '.svelte', '.astro',
-]);
-
-const HTML_EXTENSIONS = new Set(['.html', '.htm']);
-
-function walkDir(dir) {
- const files = [];
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
- for (const entry of entries) {
- if (SKIP_DIRS.has(entry.name)) continue;
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) files.push(...walkDir(full));
- else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
- }
- return files;
-}
-
-
-// ---------------------------------------------------------------------------
-// Import graph (multi-file awareness)
-// ---------------------------------------------------------------------------
-
-function resolveImport(specifier, fromDir, fileSet) {
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
- const base = path.resolve(fromDir, specifier);
- if (fileSet.has(base)) return base;
- for (const ext of SCANNABLE_EXTENSIONS) {
- const withExt = base + ext;
- if (fileSet.has(withExt)) return withExt;
- }
- // index file convention
- for (const ext of SCANNABLE_EXTENSIONS) {
- const indexFile = path.join(base, 'index' + ext);
- if (fileSet.has(indexFile)) return indexFile;
- }
- return null;
-}
-
-function buildImportGraph(files) {
- const fileSet = new Set(files);
- const graph = new Map();
-
- for (const file of files) {
- const content = fs.readFileSync(file, 'utf-8');
- const dir = path.dirname(file);
- const imports = new Set();
-
- // ES imports: import ... from '...' and import '...'
- const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
- let m;
- while ((m = esRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // CSS @import
- const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
- while ((m = cssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // SCSS @use / @forward
- const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
- while ((m = scssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- graph.set(file, imports);
- }
- return graph;
-}
-
-// ---------------------------------------------------------------------------
-// Framework dev server detection
-// ---------------------------------------------------------------------------
-
-const FRAMEWORK_CONFIGS = [
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /next/i } },
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-sveltekit-page', value: null } },
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /@vite\/client/ } },
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /astro/i } },
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
- portRe: /"port"\s*:\s*(\d+)/,
- fingerprint: { body: /ng-version/i } },
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
-];
-
-function detectFrameworkConfig(dir) {
- let entries;
- try { entries = fs.readdirSync(dir); } catch { return null; }
- const entrySet = new Set(entries);
-
- for (const cfg of FRAMEWORK_CONFIGS) {
- const match = cfg.files.find(f => entrySet.has(f));
- if (!match) continue;
-
- const configPath = path.join(dir, match);
- let port = cfg.defaultPort;
- try {
- const content = fs.readFileSync(configPath, 'utf-8');
- const portMatch = content.match(cfg.portRe);
- if (portMatch) port = parseInt(portMatch[1], 10);
- } catch { /* use default */ }
-
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
- }
- return null;
-}
-
-/**
- * Check if a port is listening and optionally verify it matches the expected framework.
- * Returns { listening: true, matched: true/false } or { listening: false }.
- */
-async function isPortListening(port, fingerprint = null) {
- if (!fingerprint) {
- // Simple TCP probe fallback
- const net = await import('node:net');
- return new Promise((resolve) => {
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
- sock.setTimeout(500);
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
- sock.on('error', () => resolve({ listening: false }));
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
- });
- }
-
- // HTTP probe with fingerprint matching
- try {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 2000);
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
- clearTimeout(timeout);
-
- // Check header fingerprint
- if (fingerprint.header) {
- const val = res.headers.get(fingerprint.header);
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
- return { listening: true, matched: true };
- }
- }
-
- // Check body fingerprint
- if (fingerprint.body) {
- const body = await res.text();
- if (fingerprint.body.test(body)) {
- return { listening: true, matched: true };
- }
- }
-
- // Port is listening but doesn't match the expected framework
- return { listening: true, matched: false };
- } catch {
- return { listening: false };
- }
-}
-
-export {
- SKIP_DIRS,
- SCANNABLE_EXTENSIONS,
- HTML_EXTENSIONS,
- walkDir,
- resolveImport,
- buildImportGraph,
- FRAMEWORK_CONFIGS,
- detectFrameworkConfig,
- isPortListening,
-};
@@ -1,166 +0,0 @@
-function profileNow() {
- return typeof performance !== 'undefined' && performance.now
- ? performance.now()
- : Date.now();
-}
-
-function createDetectorProfile() {
- return { events: [] };
-}
-
-function recordProfileEvent(profile, event) {
- if (!profile) return;
- const normalized = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- ms: Number.isFinite(event.ms) ? event.ms : 0,
- findings: Number.isFinite(event.findings) ? event.findings : 0,
- };
- if (event.detail) normalized.detail = event.detail;
- if (Array.isArray(event.findingIds) && event.findingIds.length) {
- normalized.findingIds = event.findingIds;
- }
- if (typeof profile === 'function') {
- profile(normalized);
- } else if (typeof profile.record === 'function') {
- profile.record(normalized);
- } else if (Array.isArray(profile.events)) {
- profile.events.push(normalized);
- } else if (Array.isArray(profile)) {
- profile.push(normalized);
- }
-}
-
-function extractFindingIds(findings) {
- if (!Array.isArray(findings) || findings.length === 0) return [];
- return [...new Set(findings.map(f => f?.id || f?.type || f?.antipattern).filter(Boolean))];
-}
-
-function profileFindings(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-function profileStep(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-async function profileFindingsAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = await callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-async function profileStepAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return await callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-function percentile(sortedValues, pct) {
- if (!sortedValues.length) return 0;
- const idx = Math.min(
- sortedValues.length - 1,
- Math.max(0, Math.ceil((pct / 100) * sortedValues.length) - 1),
- );
- return sortedValues[idx];
-}
-
-function summarizeDetectorProfile(profile) {
- const events = Array.isArray(profile)
- ? profile
- : (Array.isArray(profile?.events) ? profile.events : []);
- const groups = new Map();
- for (const event of events) {
- const key = [
- event.engine || 'unknown',
- event.phase || 'unknown',
- event.ruleId || 'unknown',
- event.target || '',
- ].join('\u0000');
- let group = groups.get(key);
- if (!group) {
- group = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- calls: 0,
- totalMs: 0,
- findings: 0,
- samples: [],
- };
- groups.set(key, group);
- }
- const ms = Number.isFinite(event.ms) ? event.ms : 0;
- group.calls += 1;
- group.totalMs += ms;
- group.findings += Number.isFinite(event.findings) ? event.findings : 0;
- group.samples.push(ms);
- }
- return [...groups.values()]
- .map(group => {
- const samples = group.samples.sort((a, b) => a - b);
- return {
- engine: group.engine,
- phase: group.phase,
- ruleId: group.ruleId,
- target: group.target,
- calls: group.calls,
- totalMs: Number(group.totalMs.toFixed(3)),
- avgMs: Number((group.totalMs / group.calls).toFixed(3)),
- p50: Number(percentile(samples, 50).toFixed(3)),
- p95: Number(percentile(samples, 95).toFixed(3)),
- findings: group.findings,
- };
- })
- .sort((a, b) => b.totalMs - a.totalMs);
-}
-
-export {
- profileNow,
- createDetectorProfile,
- recordProfileEvent,
- extractFindingIds,
- profileFindings,
- profileStep,
- profileFindingsAsync,
- profileStepAsync,
- percentile,
- summarizeDetectorProfile,
-};
@@ -1,278 +0,0 @@
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-const RULE_ENGINE_SUPPORT = {
- regex: new Set(['source', 'page-analyzer']),
- 'static-html': new Set(['element', 'page']),
- browser: new Set(['element', 'page', 'layout']),
- visual: new Set(['visual-contrast']),
-};
-
-function getAntipattern(id) {
- return ANTIPATTERNS.find(rule => rule.id === id);
-}
-
-function getRulesForCategory(category) {
- return ANTIPATTERNS.filter(rule => rule.category === category);
-}
-
-function getRuleEngineSupport(engine) {
- return RULE_ENGINE_SUPPORT[engine] || new Set();
-}
-
-export {
- ANTIPATTERNS,
- RULE_ENGINE_SUPPORT,
- getAntipattern,
- getRulesForCategory,
- getRuleEngineSupport,
-};
@@ -1,1948 +0,0 @@
-import {
- BORDER_SAFE_TAGS,
- GENERIC_FONTS,
- KNOWN_SERIF_FONTS,
- OVERUSED_FONTS,
- SAFE_TAGS,
- WCAG_LARGE_BOLD_TEXT_PX,
- WCAG_LARGE_TEXT_PX,
- isBrandFontOnOwnDomain,
-} from '../shared/constants.mjs';
-import {
- colorToHex,
- contrastRatio,
- getHue,
- hasChroma,
- isNeutralColor,
- parseGradientColors,
- parseRgb,
- relativeLuminance,
-} from '../shared/color.mjs';
-
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-export {
- checkBorders,
- isEmojiOnlyText,
- checkColors,
- isCardLikeFromProps,
- checkIconTile,
- resolveSerif,
- checkItalicSerif,
- isAccentColor,
- checkHeroEyebrow,
- checkRepeatedSectionKickers,
- checkMotion,
- checkGlow,
- checkHtmlPatterns,
- readOwnBackgroundColor,
- resolveBackground,
- resolveGradientStops,
- parseRadiusToPx,
- resolveBorderRadiusPx,
- checkElementBordersDOM,
- checkElementColorsDOM,
- checkElementIconTileDOM,
- checkElementItalicSerifDOM,
- checkElementHeroEyebrowDOM,
- buildCustomPropMap,
- resolveVarRefs,
- oklchToRgb,
- parseAnyColor,
- parseColorResolved,
- cleanInlineText,
- isRepeatedKickerCandidate,
- collectRepeatedSectionKickerCandidates,
- checkRepeatedSectionKickersDOM,
- checkElementMotionDOM,
- checkElementGlowDOM,
- checkElementAIPaletteDOM,
- resolveFontSizePx,
- resolveLengthPx,
- checkQuality,
- checkElementQualityDOM,
- checkPageQualityFromDoc,
- checkPageQualityDOM,
- checkElementQuality,
- checkElementBorders,
- checkElementColors,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementHeroEyebrow,
- checkRepeatedSectionKickersFromDoc,
- checkElementMotion,
- checkElementGlow,
- checkTypography,
- isCardLikeDOM,
- checkLayout,
- checkPageTypography,
- isCardLike,
- checkPageLayout,
-};
@@ -1,124 +0,0 @@
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-export {
- isNeutralColor,
- parseRgb,
- relativeLuminance,
- contrastRatio,
- parseGradientColors,
- hasChroma,
- getHue,
- colorToHex,
-};
@@ -1,101 +0,0 @@
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-export {
- SAFE_TAGS,
- BORDER_SAFE_TAGS,
- OVERUSED_FONTS,
- GOOGLE_DOMAINS,
- VERCEL_DOMAINS,
- GITHUB_DOMAINS,
- BRAND_FONT_DOMAINS,
- isBrandFontOnOwnDomain,
- GENERIC_FONTS,
- WCAG_LARGE_TEXT_PX,
- WCAG_LARGE_BOLD_TEXT_PX,
- KNOWN_SERIF_FONTS,
-};
@@ -1,7 +0,0 @@
-/** Check if content looks like a full page (not a component/partial) */
-function isFullPage(content) {
- const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
- return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
-}
-
-export { isFullPage };
@@ -1,110 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-export const IMPECCABLE_DIR = '.impeccable';
-export const LIVE_DIR = 'live';
-export const CRITIQUE_DIR = 'critique';
-
-export function getImpeccableDir(cwd = process.cwd()) {
- return path.join(cwd, IMPECCABLE_DIR);
-}
-
-export function getDesignSidecarPath(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), 'design.json');
-}
-
-export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {
- const candidates = [
- getDesignSidecarPath(cwd),
- path.join(cwd, 'DESIGN.json'),
- ];
- const contextLegacy = path.join(contextDir, 'DESIGN.json');
- if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
- return candidates;
-}
-
-export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
- return firstExisting(getDesignSidecarCandidates(cwd, contextDir));
-}
-
-export function getLiveDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), LIVE_DIR);
-}
-
-export function getLiveConfigPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'config.json');
-}
-
-export function getLegacyLiveConfigPath(scriptsDir) {
- return path.join(scriptsDir, 'config.json');
-}
-
-export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {
- if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
- const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
- return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
- }
- const primary = getLiveConfigPath(cwd);
- if (fs.existsSync(primary)) return primary;
- if (scriptsDir) {
- const legacy = getLegacyLiveConfigPath(scriptsDir);
- if (fs.existsSync(legacy)) return legacy;
- }
- return primary;
-}
-
-export function getLiveServerPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'server.json');
-}
-
-export function getLegacyLiveServerPath(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live.json');
-}
-
-export function readLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try {
- return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };
- } catch {
- /* try next */
- }
- }
- return null;
-}
-
-export function writeLiveServerInfo(cwd = process.cwd(), info) {
- const filePath = getLiveServerPath(cwd);
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- fs.writeFileSync(filePath, JSON.stringify(info));
- return filePath;
-}
-
-export function removeLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try { fs.unlinkSync(filePath); } catch {}
- }
-}
-
-export function getLiveSessionsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'sessions');
-}
-
-export function getLegacyLiveSessionsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'sessions');
-}
-
-export function getLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'annotations');
-}
-
-export function getCritiqueDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), CRITIQUE_DIR);
-}
-
-export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'annotations');
-}
-
-function firstExisting(paths) {
- return paths.find((filePath) => fs.existsSync(filePath)) || null;
-}
@@ -1,69 +0,0 @@
-/**
- * Decide whether a given file is "generated" (regenerated by a build step,
- * unsafe to write variants into) or "source" (safe to edit, changes persist).
- *
- * Why this matters: when the user picks an element on a page whose underlying
- * file is regenerated by a build step (e.g. `scripts/build-sub-pages.js`
- * rewriting `public/docs/*.html`), writing variants or accepted changes into
- * that file is silent data loss — the next build wipes them.
- *
- * Signals, in order of reliability:
- * 1. Git check-ignore: gitignored files are assumed generated.
- * 2. File-header markers ("GENERATED", "DO NOT EDIT", "AUTO-GENERATED")
- * within the first ~300 characters — catches non-git projects.
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-
-const HEADER_SCAN_BYTES = 300;
-const HEADER_MARKERS = [
- /@generated\b/i,
- /\bGENERATED\s+FILE\b/,
- /\bAUTO-?GENERATED\b/i,
- /\bDO\s+NOT\s+EDIT\b/i,
-];
-
-/**
- * @param {string} filePath - absolute or cwd-relative path
- * @param {object} [options]
- * @param {string} [options.cwd] - project root (defaults to process.cwd())
- */
-export function isGeneratedFile(filePath, options = {}) {
- const cwd = options.cwd || process.cwd();
- const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
-
- if (isGitIgnored(absPath, cwd)) return true;
- if (hasGeneratedHeader(absPath)) return true;
- return false;
-}
-
-function isGitIgnored(absPath, cwd) {
- try {
- execSync(`git check-ignore --quiet ${JSON.stringify(absPath)}`, {
- cwd,
- stdio: 'ignore',
- });
- return true; // exit 0 = ignored
- } catch (err) {
- // Exit code 1 = not ignored. Exit code 128 = not a git repo or other error.
- // In both cases, treat as "not known to be ignored."
- return false;
- }
-}
-
-function hasGeneratedHeader(absPath) {
- let fd;
- try {
- fd = fs.openSync(absPath, 'r');
- const buf = Buffer.alloc(HEADER_SCAN_BYTES);
- const bytesRead = fs.readSync(fd, buf, 0, HEADER_SCAN_BYTES, 0);
- const head = buf.slice(0, bytesRead).toString('utf-8');
- return HEADER_MARKERS.some((re) => re.test(head));
- } catch {
- return false;
- } finally {
- if (fd !== undefined) { try { fs.closeSync(fd); } catch {} }
- }
-}
@@ -1,595 +0,0 @@
-/**
- * CLI helper: deterministic accept/discard of variant sessions.
- *
- * Usage:
- * node live-accept.mjs --id SESSION_ID --discard
- * node live-accept.mjs --id SESSION_ID --variant N
- *
- * For discard: removes the entire variant wrapper and restores the original.
- * For accept: replaces the wrapper with the chosen variant's content. If the
- * session had a colocated <style> block, it's preserved with carbonize markers
- * for a background agent to integrate into the project's CSS.
- *
- * Output: JSON to stdout.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-export async function acceptCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-accept.mjs [options]
-
-Deterministic accept/discard for live variant sessions.
-
-Modes:
- --discard Remove variants, restore original
- --variant N Accept variant N, discard the rest
-
-Required:
- --id SESSION_ID Session ID of the variant wrapper
-
-Output (JSON):
- { handled, file, carbonize }`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const variantNum = argVal(args, '--variant');
- const paramValuesRaw = argVal(args, '--param-values');
- const isDiscard = args.includes('--discard');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }
-
- let paramValues = null;
- if (paramValuesRaw) {
- try { paramValues = JSON.parse(paramValuesRaw); }
- catch { paramValues = null; } // malformed blob: skip the comment rather than failing the accept
- }
-
- // Find the file containing this session's markers
- const found = findSessionFile(id, process.cwd());
- if (!found) {
- console.log(JSON.stringify({ handled: false, error: 'Session markers not found for id: ' + id }));
- process.exit(0);
- }
-
- const { file: targetFile, content, lines } = found;
- const relFile = path.relative(process.cwd(), targetFile);
-
- // Bail if the session lives in a generated file. The agent manually wrote
- // the wrapper there for preview, and is responsible for writing the
- // accepted variant to true source (or cleaning up on discard). See
- // "Handle fallback" in live.md.
- if (isGeneratedFile(targetFile, { cwd: process.cwd() })) {
- console.log(JSON.stringify({
- handled: false,
- mode: 'fallback',
- file: relFile,
- hint: 'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.',
- }));
- process.exit(0);
- }
-
- if (isDiscard) {
- const result = handleDiscard(id, lines, targetFile);
- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));
- } else {
- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);
- // Single-line attention-grabber when cleanup is required. The full
- // five-step checklist lives in reference/live.md (loaded once per
- // session); repeating it per-event would waste tokens.
- if (result.carbonize) {
- result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + relFile + '. See reference/live.md "Required after accept".';
- }
- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));
- }
-}
-
-// ---------------------------------------------------------------------------
-// Discard
-// ---------------------------------------------------------------------------
-
-function handleDiscard(id, lines, targetFile) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const original = extractOriginal(lines, block);
- const isJsx = detectCommentSyntax(targetFile).open === '{/*';
- const replaceRange = expandReplaceRange(block, lines, isJsx);
-
- // Restore at the line we're actually replacing FROM, not the marker line.
- // For JSX wrappers the marker comments live INSIDE the outer `<div>`, so
- // `block.start` sits 2 spaces deeper than the original element. Using that
- // as the deindent base would push the restored content 2 spaces too far
- // right on every JSX/TSX session. `replaceRange.start` is the outer wrapper
- // line, which is at the original element's indent for both HTML and JSX.
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
- const restored = deindentContent(original, indent);
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...restored,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
- return {};
-}
-
-// ---------------------------------------------------------------------------
-// Accept
-// ---------------------------------------------------------------------------
-
-function handleAccept(id, variantNum, lines, targetFile, paramValues) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const commentSyntax = detectCommentSyntax(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- // Anchor indent on the line we're replacing FROM (the outer wrapper),
- // not on `block.start` — for JSX that's the marker comment 2 spaces
- // deeper than the original element. See handleDiscard for the full
- // rationale.
- const replaceRange = expandReplaceRange(block, lines, isJsx);
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
-
- // Extract the chosen variant's inner content
- const variantContent = extractVariant(lines, block, variantNum);
- if (!variantContent) return { handled: false, error: 'Variant ' + variantNum + ' not found' };
-
- // Extract CSS block if present
- const cssContent = extractCss(lines, block, id);
-
- // Check if carbonizing is needed:
- // - CSS block exists, OR
- // - variant HTML contains helper classes/attributes that need cleanup
- const variantText = variantContent.join('\n');
- const hasHelperAttrs = variantText.includes('data-impeccable-variant');
- const needsCarbonize = !!(cssContent || hasHelperAttrs);
-
- // Build the replacement
- const restored = deindentContent(variantContent, indent);
- const replacement = [];
-
- if (cssContent) {
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
- // JSX targets need the CSS body wrapped in a template literal so that the
- // `{` and `}` in CSS rules don't get parsed as JSX expressions.
- replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
- // Re-indent CSS content to match
- for (const cssLine of cssContent) {
- replacement.push(indent + cssLine.trimStart());
- }
- replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
- if (paramValues && Object.keys(paramValues).length > 0) {
- // Preserve the user's knob positions for the carbonize-cleanup agent
- // to bake into the final CSS when it collapses scoped rules.
- replacement.push(indent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close);
- }
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close);
- }
-
- // Keep the `@scope ([data-impeccable-variant="N"])` selectors in the
- // carbonize CSS block working visually by re-wrapping the accepted content
- // in a data-impeccable-variant="N" div with `display: contents` (so layout
- // isn't affected). The carbonize agent strips this attribute + wrapper when
- // it moves the CSS to a proper stylesheet.
- //
- // Style attribute syntax has to follow the host file's flavor — JSX files
- // need the object form, otherwise React 19 throws "Failed to set indexed
- // property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
- if (cssContent) {
- const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
- replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
- replacement.push(...restored);
- replacement.push(indent + '</div>');
- } else {
- replacement.push(...restored);
- }
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...replacement,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- return { carbonize: needsCarbonize };
-}
-
-// ---------------------------------------------------------------------------
-// Parsing helpers
-// ---------------------------------------------------------------------------
-
-/**
- * Find the start/end marker lines for a session.
- * Returns { start, end } (0-indexed line numbers) or null.
- */
-function findMarkerBlock(id, lines) {
- let start = -1;
- let end = -1;
- const startPattern = 'impeccable-variants-start ' + id;
- const endPattern = 'impeccable-variants-end ' + id;
-
- for (let i = 0; i < lines.length; i++) {
- if (start === -1 && lines[i].includes(startPattern)) start = i;
- if (lines[i].includes(endPattern)) { end = i; break; }
- }
-
- return (start !== -1 && end !== -1) ? { start, end } : null;
-}
-
-/**
- * Compute the line range to REPLACE (vs. just the marker range to extract
- * from). For JSX/TSX wrappers, live-wrap places the marker comments INSIDE
- * the `<div data-impeccable-variants="ID">` outer wrapper so the picked
- * element's JSX slot keeps a single child — a Fragment `<></>` would have
- * solved the multi-sibling case but failed inside `asChild` / cloneElement
- * parents with "Invalid prop supplied to React.Fragment".
- *
- * That means the marker block is enclosed by the wrapper `<div>` opener
- * (with `data-impeccable-variants="ID"`) and its matching `</div>`. We
- * walk back to the opener and forward to the closer so accept/discard
- * remove the entire scaffold, not just the inner markers.
- *
- * Marker lines themselves stay where they were so extractOriginal /
- * extractVariant / extractCss continue to walk the same range.
- */
-function expandReplaceRange(block, lines, isJsx) {
- if (!isJsx) return { start: block.start, end: block.end };
-
- let { start, end } = block;
-
- // Walk back for the wrapper `<div data-impeccable-variants="..."` opener.
- // The attr may sit on a continuation line of a multi-line opening tag, so
- // also walk to the line that actually contains `<div`.
- for (let i = start - 1; i >= Math.max(0, start - 12); i--) {
- if (/data-impeccable-variants=/.test(lines[i])) {
- let opener = i;
- while (opener > 0 && !/<div\b/.test(lines[opener])) opener--;
- start = opener;
- break;
- }
- }
-
- // Walk forward to the matching `</div>` by div-depth tracking from the
- // wrapper opener. Operate on JOINED text instead of per-line: a
- // multi-line self-closing JSX `<div\n className="spacer"\n/>` would
- // fool per-line regex tracking (the `<div` line matches openRe but the
- // `/>` line never matches selfCloseRe since it needs `<div` on the same
- // line). That left depth permanently over-counted and the wrapper's
- // outer `</div>` orphaned after accept/discard. Single regex with
- // `[^>]*?` (which spans newlines in JS) handles either form correctly.
- const joined = lines.slice(start).join('\n');
- // Match either `<div … />` (self-close, group 1 is `/`), `<div … >`
- // (open, group 1 is empty), or `</div>`.
- const tagRe = /<div\b[^>]*?(\/?)>|<\/div\s*>/g;
- let depth = 0;
- let m;
- while ((m = tagRe.exec(joined)) !== null) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && m[1] === '/';
- if (isClose) depth--;
- else if (!isSelfClose) depth++;
- if (depth <= 0) {
- // m.index is offset within `joined`; convert back to a file line.
- const linesBefore = joined.slice(0, m.index + m[0].length).split('\n').length - 1;
- const candidateEnd = start + linesBefore;
- if (candidateEnd >= end) {
- end = candidateEnd;
- break;
- }
- }
- }
-
- return { start, end };
-}
-
-/**
- * Join wrapper lines into a single string with `<style>` elements removed so
- * marker matching and div-depth tracking aren't confused by:
- * - CSS `@scope ([data-impeccable-variant="N"])` strings that look like the
- * HTML marker we're searching for
- * - JSX self-closing `<style ... />` (no separate `</style>` to close on)
- * - Same-line `<style>…</style>` blocks
- * - Multi-line `<style>\n…\n</style>` blocks
- */
-function stripStyleAndJoin(lines, block) {
- const out = [];
- let inStyle = false;
- for (let i = block.start; i <= block.end; i++) {
- let line = lines[i];
-
- if (!inStyle) {
- // Strip any complete <style> elements on this line (self-closed or
- // same-line-closed), including their body content.
- line = line
- .replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/g, '')
- .replace(/<style\b[^>]*\/\s*>/g, '');
-
- // If a <style> opener remains (multi-line body starts here), strip from
- // the opener to end-of-line and flip into skip mode.
- const openerIdx = line.search(/<style\b/);
- if (openerIdx !== -1) {
- line = line.slice(0, openerIdx);
- inStyle = true;
- }
- out.push(line);
- } else {
- // In multi-line style body; drop everything until we see </style>.
- const closeIdx = line.search(/<\/style\s*>/);
- if (closeIdx !== -1) {
- inStyle = false;
- out.push(line.slice(closeIdx).replace(/<\/style\s*>/, ''));
- }
- // else: skip line entirely
- }
- }
- return out.join('\n');
-}
-
-/**
- * Find the inner content of `<TAG ...attrMatch...>…</TAG>` inside `text`,
- * handling nested same-tag elements via depth counting. `attrMatch` is a
- * regex source fragment that must appear inside the opener tag.
- * Returns the inner string (may be empty), or null if not found.
- */
-function extractInnerByAttr(text, attrMatch) {
- const openerRe = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*' + attrMatch + '[^>]*>');
- const openMatch = text.match(openerRe);
- if (!openMatch) return null;
-
- const tagName = openMatch[1];
- const innerStart = openMatch.index + openMatch[0].length;
-
- // Match any opener or closer of this tag name after innerStart.
- // (Does not match self-closing <TAG … />, which doesn't contribute to depth.)
- const tagRe = new RegExp('<(?:/)?' + tagName + '\\b[^>]*>', 'g');
- tagRe.lastIndex = innerStart;
-
- let depth = 1;
- let m;
- while ((m = tagRe.exec(text))) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && /\/\s*>$/.test(m[0]);
- if (isClose) {
- depth--;
- if (depth === 0) return text.slice(innerStart, m.index);
- } else if (!isSelfClose) {
- depth++;
- }
- }
- return null;
-}
-
-/**
- * Extract the original element content from within the variant wrapper.
- * Returns an array of lines.
- */
-function extractOriginal(lines, block) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="original"');
- if (inner === null) return [];
- return inner.split('\n');
-}
-
-/**
- * Extract a specific variant's inner content (stripping the wrapper div).
- * Returns an array of lines, or null if not found.
- */
-function extractVariant(lines, block, variantNum) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + variantNum + '"');
- if (inner === null) return null;
- const result = inner.split('\n');
- // Collapse a lone empty leading/trailing line (common after string splice).
- while (result.length > 1 && result[0].trim() === '') result.shift();
- while (result.length > 1 && result[result.length - 1].trim() === '') result.pop();
- return result.length > 0 ? result : null;
-}
-
-/**
- * Extract the colocated <style> block content (between the style tags).
- * Returns an array of CSS lines, or null if no style block found.
- *
- * Handles three shapes of `<style data-impeccable-css="ID" ...>`:
- * 1. Self-closing: `<style ... />` — no body; return null (nothing to carbonize).
- * 2. Same-line open+close: `<style>...</style>` — return the inner content.
- * 3. Multi-line: `<style>` on one line, `</style>` on a later line — return
- * the lines between them.
- */
-function extractCss(lines, block, id) {
- const styleAttr = 'data-impeccable-css="' + id + '"';
- let inStyle = false;
- const content = [];
-
- for (let i = block.start; i <= block.end; i++) {
- const line = lines[i];
-
- if (!inStyle && line.includes(styleAttr)) {
- // Self-closing: nothing to carbonize.
- if (/<style\b[^>]*\/\s*>/.test(line)) return null;
- // Same-line open + close: extract inner text.
- const sameLine = line.match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/);
- if (sameLine) {
- const inner = stripJsxTemplateWrap(sameLine[1]);
- return inner.length > 0 ? inner.split('\n') : null;
- }
- inStyle = true;
- continue; // skip the <style> opening tag
- }
-
- if (inStyle) {
- // Detect </style> anywhere on the line — JSX template-literal closes
- // (`}</style>`) put the close mid-line, and we don't want to absorb the
- // template-literal punctuation as CSS content.
- const closeIdx = line.indexOf('</style>');
- if (closeIdx !== -1) break;
- content.push(line);
- }
- }
-
- if (content.length === 0) return null;
- return stripJsxTemplateLines(content);
-}
-
-/**
- * Strip a JSX template-literal wrap (`{` … `}`) from CSS extracted out of a
- * `<style>` element in a JSX/TSX file. The agent may write the wrap with
- * `{` and `}` directly attached to the `<style>` tags, on their own lines,
- * or attached to the first/last CSS lines — all three are JSX-legal.
- *
- * Stripping is required because handleAccept re-wraps the CSS itself when
- * carbonizing. Without this, two consecutive accepts (or a previously-
- * accepted variants block being carbonized) would produce nested
- * `{` `{` … `}` `}`, which oxc rejects with "Expected `}` but found `@`".
- */
-function stripJsxTemplateLines(content) {
- const out = content.slice();
-
- // Drop any leading blank lines so we don't miss a `{` line buried below
- // them; same for trailing.
- while (out.length > 0 && out[0].trim() === '') out.shift();
- while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
- if (out.length === 0) return null;
-
- // Leading `{`: own line, or attached to the first CSS line.
- const firstTrim = out[0].trimStart();
- if (firstTrim === '{`') {
- out.shift();
- } else if (firstTrim.startsWith('{`')) {
- const idx = out[0].indexOf('{`');
- out[0] = out[0].slice(0, idx) + out[0].slice(idx + 2);
- if (out[0].trim() === '') out.shift();
- }
- if (out.length === 0) return null;
-
- // Trailing `` ` `` `}`: own line, or attached to the last CSS line.
- const lastIdx = out.length - 1;
- const lastTrim = out[lastIdx].trimEnd();
- if (lastTrim === '`}') {
- out.pop();
- } else if (lastTrim.endsWith('`}')) {
- const text = out[lastIdx];
- const idx = text.lastIndexOf('`}');
- out[lastIdx] = text.slice(0, idx) + text.slice(idx + 2);
- if (out[lastIdx].trim() === '') out.pop();
- }
-
- return out.length > 0 ? out : null;
-}
-
-function stripJsxTemplateWrap(text) {
- const lines = text.split('\n');
- const stripped = stripJsxTemplateLines(lines);
- return stripped ? stripped.join('\n') : '';
-}
-
-/**
- * De-indent content that was indented by live-wrap.mjs.
- * The wrap script adds `indent + ' '` (4 extra spaces) to each line.
- * We restore to just `indent` level.
- */
-function deindentContent(contentLines, baseIndent) {
- // Find the minimum indentation in the content to determine how much was added
- let minIndent = Infinity;
- for (const line of contentLines) {
- if (line.trim() === '') continue;
- const leadingSpaces = line.match(/^(\s*)/)[1].length;
- minIndent = Math.min(minIndent, leadingSpaces);
- }
- if (minIndent === Infinity) minIndent = 0;
-
- // Strip the extra indentation and re-add base indent
- return contentLines.map(line => {
- if (line.trim() === '') return '';
- return baseIndent + line.slice(minIndent);
- });
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- return { open: '<!--', close: '-->' };
-}
-
-// ---------------------------------------------------------------------------
-// File search (find the file containing session markers)
-// ---------------------------------------------------------------------------
-
-function findSessionFile(id, cwd) {
- const marker = 'impeccable-variants-start ' + id;
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, marker, seen, 0);
- if (result) {
- const content = fs.readFileSync(result, 'utf-8');
- return { file: result, content, lines: content.split('\n') };
- }
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth) {
- if (depth > 5) return null;
- let realDir;
- try { realDir = fs.realpathSync(dir); } catch { return null; }
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- if (!EXTENSIONS.includes(path.extname(entry.name).toLowerCase())) continue;
- const filePath = path.join(dir, entry.name);
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip */ }
- }
-
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
- if (result) return result;
- }
-
- return null;
-}
-
-// ---------------------------------------------------------------------------
-// Utilities
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-accept.mjs') || _running?.endsWith('live-accept.mjs/')) {
- acceptCli();
-}
-
-export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax };
@@ -1,123 +0,0 @@
-/**
- * Browser-side durable session helpers for Impeccable live mode.
- *
- * Kept separate from live-browser.js so recovery state can be tested without
- * booting the full overlay UI. Served before live-browser.js and attached to
- * window.__IMPECCABLE_LIVE_SESSION__.
- */
-(function (root) {
- 'use strict';
-
- function createLiveBrowserSessionState({ prefix, storage, idFactory }) {
- if (!prefix) throw new Error('prefix required');
- const store = storage || root.localStorage;
- const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };
- const sessionKey = prefix + '-session';
- const handledKey = sessionKey + '-handled';
- const scrollKey = sessionKey + '-scroll';
- let checkpointRevision = 0;
- const owner = makeId();
-
- function safeRead(key) {
- try { return store.getItem(key); } catch { return null; }
- }
-
- function safeWrite(key, value) {
- try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }
- }
-
- function safeRemove(key) {
- try { store.removeItem(key); } catch { /* unavailable storage */ }
- }
-
- function loadSession() {
- try {
- const raw = safeRead(sessionKey);
- if (!raw) return null;
- const parsed = JSON.parse(raw);
- if (Number.isInteger(parsed.checkpointRevision)) {
- checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);
- }
- return parsed;
- } catch { return null; }
- }
-
- function saveSession(session) {
- if (!session || !session.id) return;
- const payload = {
- ...session,
- checkpointRevision,
- };
- safeWrite(sessionKey, JSON.stringify(payload));
- }
-
- function clearSession() {
- safeRemove(sessionKey);
- }
-
- function nextCheckpointRevision() {
- checkpointRevision += 1;
- const existing = loadSession();
- if (existing?.id) saveSession(existing);
- return checkpointRevision;
- }
-
- function seedCheckpointRevision(value) {
- if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);
- return checkpointRevision;
- }
-
- function currentCheckpointRevision() {
- return checkpointRevision;
- }
-
- function markHandled(id) {
- if (!id) return;
- safeWrite(handledKey, id);
- }
-
- function isHandled(id) {
- return !!id && safeRead(handledKey) === id;
- }
-
- function clearHandled() {
- safeRemove(handledKey);
- }
-
- function writeScrollY(y) {
- safeWrite(scrollKey, String(y));
- }
-
- function readScrollY() {
- const raw = safeRead(scrollKey);
- if (raw == null) return null;
- const n = parseFloat(raw);
- return isFinite(n) ? n : null;
- }
-
- function clearScrollY() {
- safeRemove(scrollKey);
- }
-
- return {
- owner,
- sessionKey,
- handledKey,
- scrollKey,
- saveSession,
- loadSession,
- clearSession,
- nextCheckpointRevision,
- seedCheckpointRevision,
- currentCheckpointRevision,
- markHandled,
- isHandled,
- clearHandled,
- writeScrollY,
- readScrollY,
- clearScrollY,
- };
- }
-
- root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };
-})(typeof window !== 'undefined' ? window : globalThis);
@@ -1,4860 +0,0 @@
-/**
- * Impeccable Live Variant Mode — Browser Script
- *
- * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
- * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
- * before this code.
- *
- * UI: a single floating bar that morphs between three states —
- * configure (pick action + go), generating (progressive dots), and cycling
- * (prev/next + accept/discard). Feels like Spotlight, not a modal.
- */
-(function () {
- 'use strict';
- if (typeof window === 'undefined') return;
-
- // Guard against double-init. Bun's HTML loader may process the <script> tag
- // and create a bundled copy alongside the external load, or HMR may re-execute.
- // Check BEFORE reading token/port to catch all cases.
- if (window.__IMPECCABLE_LIVE_INIT__) return;
- window.__IMPECCABLE_LIVE_INIT__ = true;
-
- const TOKEN = window.__IMPECCABLE_TOKEN__;
- const PORT = window.__IMPECCABLE_PORT__;
- if (!TOKEN || !PORT) {
- window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
- return;
- }
-
- // ---------------------------------------------------------------------------
- // Design tokens
- // ---------------------------------------------------------------------------
-
- // Brand magenta is pinned to the site token (--color-accent in main.css)
- // so Accept / knobs / cycle-dots match the site's accent, not a washed
- // theme-adjusted one.
- const C = {
- brand: 'oklch(60% 0.25 350)',
- brandHov: 'oklch(52% 0.25 350)',
- brandSoft: 'oklch(60% 0.25 350 / 0.15)',
- ink: 'oklch(15% 0.01 350)',
- ash: 'oklch(55% 0 0)',
- paper: 'oklch(98% 0.005 350 / 0.92)',
- paperSolid:'oklch(98% 0.005 350)',
- mist: 'oklch(90% 0.01 350 / 0.6)',
- white: 'oklch(99% 0 0)',
- };
- const FONT = 'system-ui, -apple-system, sans-serif';
- const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
- // z-index: detect overlays use 99999, so our UI must be above them
- const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };
- const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
- const PREFIX = 'impeccable-live';
- const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
- prefix: PREFIX,
- storage: localStorage,
- idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),
- });
- if (!sessionState) {
- console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');
- window.__IMPECCABLE_LIVE_INIT__ = false;
- return;
- }
- const HIGHLIGHT_TRANSITION =
- 'top 140ms ' + EASE +
- ', left 140ms ' + EASE +
- ', width 140ms ' + EASE +
- ', height 140ms ' + EASE +
- ', opacity 150ms ease';
- const TOOLTIP_TRANSITION =
- 'top 140ms ' + EASE + ', left 140ms ' + EASE + ', opacity 150ms ease';
-
- const SKIP_TAGS = new Set([
- 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
- ]);
-
- // SVG icons stack above each chip label. All strokes use currentColor so the
- // icon recolors to C.brand when its chip is selected. 20x20 render, 24-viewBox,
- // 1.5 stroke — visually consistent with the Foundation grid on the homepage.
- const ICON_ATTRS = 'width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block"';
- const ICONS = {
- impeccable: `<svg ${ICON_ATTRS}><path d="M4 20l4-1L18 9l-3-3L5 16z"/><path d="M14 7l3 3"/></svg>`,
- bolder: `<svg ${ICON_ATTRS}><rect x="6" y="12" width="4" height="7" rx="0.5"/><rect x="14" y="5" width="4" height="14" rx="0.5"/></svg>`,
- quieter: `<svg ${ICON_ATTRS}><rect x="6" y="5" width="4" height="14" rx="0.5"/><rect x="14" y="12" width="4" height="7" rx="0.5"/></svg>`,
- distill: `<svg ${ICON_ATTRS}><path d="M4 5h16l-6 8v7l-4-2v-5z"/></svg>`,
- polish: `<svg ${ICON_ATTRS}><path d="M15 3l1 3 3 1-3 1-1 3-1-3-3-1 3-1z"/><path d="M7 13l0.6 1.8 1.8 0.6-1.8 0.6-0.6 1.8-0.6-1.8-1.8-0.6 1.8-0.6z"/></svg>`,
- typeset: `<svg ${ICON_ATTRS}><path d="M5 6h14" stroke-width="2.6"/><path d="M5 12h9" stroke-width="1.9"/><path d="M5 18h5" stroke-width="1.3"/></svg>`,
- colorize: `<svg ${ICON_ATTRS}><circle cx="9" cy="10" r="5"/><circle cx="15" cy="10" r="5"/><circle cx="12" cy="15" r="5"/></svg>`,
- layout: `<svg ${ICON_ATTRS}><rect x="3" y="4" width="8" height="16" rx="0.5"/><rect x="13" y="4" width="8" height="7" rx="0.5"/><rect x="13" y="13" width="8" height="7" rx="0.5"/></svg>`,
- adapt: `<svg ${ICON_ATTRS}><rect x="2.5" y="5" width="12" height="11" rx="1"/><line x1="2.5" y1="19" x2="14.5" y2="19"/><rect x="16.5" y="8" width="5" height="11" rx="1"/></svg>`,
- animate: `<svg ${ICON_ATTRS}><path d="M3 18c4-4 6-10 10-10"/><path d="M13 8c3 0 5 5 8 10"/><circle cx="13" cy="8" r="1.6" fill="currentColor" stroke="none"/></svg>`,
- delight: `<svg ${ICON_ATTRS}><path d="M12 3l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>`,
- overdrive: `<svg ${ICON_ATTRS}><path d="M13 3L5 13h5l-1 8 9-12h-6z"/></svg>`,
- };
-
- const ACTIONS = [
- { value: 'impeccable', label: 'Freeform' },
- { value: 'bolder', label: 'Bolder' },
- { value: 'quieter', label: 'Quieter' },
- { value: 'distill', label: 'Distill' },
- { value: 'polish', label: 'Polish' },
- { value: 'typeset', label: 'Typeset' },
- { value: 'colorize', label: 'Colorize' },
- { value: 'layout', label: 'Layout' },
- { value: 'adapt', label: 'Adapt' },
- { value: 'animate', label: 'Animate' },
- { value: 'delight', label: 'Delight' },
- { value: 'overdrive', label: 'Overdrive' },
- ];
-
- // ---------------------------------------------------------------------------
- // State
- // ---------------------------------------------------------------------------
-
- let state = 'IDLE';
- let hoveredElement = null;
- let selectedElement = null;
- let currentSessionId = null;
- let expectedVariants = 0;
- let arrivedVariants = 0;
- let visibleVariant = 0;
- let variantObserver = null;
- let hasProjectContext = false;
- let selectedAction = 'impeccable';
- let selectedCount = 3;
- const browserOwner = sessionState.owner;
- let checkpointTimer = null;
-
- // Scroll lock — holds window.scrollY at a fixed value while the session is
- // active, so HMR DOM patches and variant swaps can't drift the page. See
- // startScrollLock / stopScrollLock below.
- let scrollLockObserver = null;
- let scrollLockTargetY = null;
- let scrollLockRaf = null;
- let scrollLockAbort = null;
-
- // Dedicated key for scroll position — SEPARATE from LS_KEY so that
- // saveSession's state updates don't clobber a carefully-captured scrollY.
- // (Previously: saveSession wrote scrollY alongside state, so every call
- // during resume overwrote the pre-reload value with whatever the browser
- // had landed on, typically 0.)
- function writeScrollY(y) { sessionState.writeScrollY(y); }
- function readScrollY() { return sessionState.readScrollY(); }
- function clearScrollY() { sessionState.clearScrollY(); }
-
- // Pre-empt the browser: apply manual scroll restoration and jump to the
- // saved scrollY at script-parse time. Retries on fonts.ready and load
- // are essential: scrollTo(y) clamps to the current document.scrollHeight,
- // which is often hundreds of pixels short of the final value until
- // async-loaded fonts swap in and reflow.
- try {
- history.scrollRestoration = 'manual';
- const savedY = readScrollY();
- if (savedY != null) {
- const apply = () => {
- if (Math.abs(window.scrollY - savedY) > 0.5) {
- console.log('[impeccable.scroll] early restore', { from: window.scrollY, to: savedY });
- window.scrollTo(0, savedY);
- }
- };
- apply();
- if (document.fonts?.ready) document.fonts.ready.then(apply).catch(() => {});
- window.addEventListener('load', apply, { once: true });
- }
- } catch {}
-
- // UI refs
- let highlightEl = null;
- let tooltipEl = null;
- let barEl = null;
- let pickerEl = null;
- let toastEl = null;
- let scrollRaf = null;
-
- // ---------------------------------------------------------------------------
- // Helpers
- // ---------------------------------------------------------------------------
-
- function own(el) {
- return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
- }
-
- function pickable(el) {
- if (!el || el.nodeType !== 1) return false;
- if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
- if (own(el)) return false;
- const r = el.getBoundingClientRect();
- return r.width >= 20 && r.height >= 20;
- }
-
- function desc(el) {
- if (!el) return '';
- let s = el.tagName.toLowerCase();
- if (el.id) s += '#' + el.id;
- else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
- return s;
- }
-
- function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
-
- // Modal-aware chrome: keep our floating UI clickable inside Radix /
- // Headless UI / vaul portals.
- //
- // Two host-page behaviors break us when the picked element lives inside a
- // modal dialog:
- //
- // 1. Modal scroll-lock disables outside pointer events. Radix's
- // `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
- // while a modal is open and only restores `auto` on the layer. Our
- // chrome inherits `none` from <body> and becomes unclickable.
- // 2. The dialog's outside-interaction handler (Radix's
- // `usePointerDownOutside`) listens at document level and dismisses
- // the dialog whenever a `pointerdown` lands outside the layer node.
- // Our chrome is a sibling of <body>, so Radix classifies our clicks
- // as outside and tears the dialog down mid-task.
- //
- // We can't reliably re-parent our chrome into the dialog subtree (z-index
- // stacking, scroll containers, theming all become host-page concerns), so
- // we defang both behaviors at our root:
- //
- // - `pointer-events: auto !important` overrides the inherited `none`.
- // - Stop `pointerdown` / `mousedown` propagation so the document-level
- // dismiss listener never fires for our clicks.
- // - Stop `focusin` propagation so any focus shifts inside our chrome
- // don't read as "focus moved outside the dialog" to focus traps.
- //
- // Click events still bubble normally — only the early pointer/focus
- // signals that drive outside-interaction detection are silenced.
- function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
- if (!rootEl) return;
- if (setPointerEvents) {
- rootEl.style.setProperty('pointer-events', 'auto', 'important');
- }
- const stop = (e) => e.stopPropagation();
- rootEl.addEventListener('pointerdown', stop);
- rootEl.addEventListener('mousedown', stop);
- rootEl.addEventListener('focusin', stop);
- }
-
- // ---------------------------------------------------------------------------
- // Highlight overlay
- // ---------------------------------------------------------------------------
-
- function initHighlight() {
- highlightEl = document.createElement('div');
- highlightEl.id = PREFIX + '-highlight';
- Object.assign(highlightEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- border: '2px solid ' + C.brand, borderRadius: '3px',
- pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
- transition: HIGHLIGHT_TRANSITION,
- display: 'none', opacity: '0',
- });
- document.body.appendChild(highlightEl);
-
- tooltipEl = document.createElement('div');
- tooltipEl.id = PREFIX + '-tooltip';
- Object.assign(tooltipEl.style, {
- position: 'fixed',
- background: C.ink, color: C.white,
- fontFamily: MONO, fontSize: '10px', fontWeight: '500',
- padding: '2px 6px', borderRadius: '3px',
- zIndex: Z.highlight + 1, pointerEvents: 'none',
- whiteSpace: 'nowrap', display: 'none',
- letterSpacing: '0.02em',
- transition: TOOLTIP_TRANSITION,
- });
- document.body.appendChild(tooltipEl);
- }
-
- function showHighlight(el) {
- if (!el || !highlightEl) return;
- const r = el.getBoundingClientRect();
- const top = (r.top - 2) + 'px', left = (r.left - 2) + 'px';
- const width = (r.width + 4) + 'px', height = (r.height + 4) + 'px';
- const tipTop = r.top - 20;
- const tipY = (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px';
- const tipX = Math.max(4, r.left) + 'px';
- tooltipEl.textContent = desc(el);
-
- const hiWasHidden = highlightEl.style.display === 'none' || highlightEl.style.opacity === '0';
- if (hiWasHidden) {
- // Snap to first target without animating from (0,0), then fade in.
- highlightEl.style.transition = 'none';
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block' });
- tooltipEl.style.transition = 'none';
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block' });
- void highlightEl.offsetWidth;
- highlightEl.style.transition = HIGHLIGHT_TRANSITION;
- highlightEl.style.opacity = '1';
- tooltipEl.style.transition = TOOLTIP_TRANSITION;
- tooltipEl.style.opacity = '1';
- } else {
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block', opacity: '1' });
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block', opacity: '1' });
- }
- }
-
- function hideHighlight() {
- if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
- if (tooltipEl) { tooltipEl.style.opacity = '0'; tooltipEl.style.display = 'none'; }
- }
-
- // ---------------------------------------------------------------------------
- // Annotation overlay (comment pins + magenta strokes)
- //
- // Active while state === 'CONFIGURING'. The overlay is a fixed-positioned
- // sibling of <body> mirroring selectedElement's bounding rect. Click (no
- // drag) drops a comment pin; drag paints a magenta SVG stroke. All coords
- // are stored in element-local CSS px so they survive scroll / resize and
- // correlate directly with the captured PNG.
- // ---------------------------------------------------------------------------
-
- const DRAG_THRESHOLD = 5; // px — below this, treat pointerup as a click
- const PIN_DBL_CLICK_MS = 300; // two clicks on the same pin within this delete it
- let annotOverlayEl = null;
- let annotSvgEl = null;
- let annotPinsEl = null;
- let annotClearChipEl = null;
- let annotState = { comments: [], strokes: [] };
- let annotActive = false;
- // `annotPointer` is either:
- // { kind: 'new', x0, y0, moved, strokeEl, strokePoints } creating a stroke/pin
- // { kind: 'pin', idx, startPointer, startPin, moved } dragging an existing pin
- let annotPointer = null;
- let annotEditing = null; // { idx, input, wrapEl }
- let annotLastPinClick = { idx: -1, time: 0 }; // for click-click-to-delete
-
- function initAnnotOverlay() {
- annotOverlayEl = document.createElement('div');
- annotOverlayEl.id = PREFIX + '-annot';
- Object.assign(annotOverlayEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- pointerEvents: 'auto', zIndex: Z.highlight + 2,
- display: 'none', overflow: 'visible',
- cursor: 'crosshair', touchAction: 'none',
- });
-
- annotSvgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- annotSvgEl.id = PREFIX + '-annot-svg';
- Object.assign(annotSvgEl.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%',
- // The SVG itself doesn't absorb clicks; individual hit-paths opt-in via
- // pointer-events=stroke so gaps still fall through to the overlay.
- pointerEvents: 'none', overflow: 'visible',
- });
- annotOverlayEl.appendChild(annotSvgEl);
-
- annotPinsEl = document.createElement('div');
- annotPinsEl.id = PREFIX + '-annot-pins';
- Object.assign(annotPinsEl.style, {
- position: 'absolute', inset: '0',
- pointerEvents: 'none',
- });
- annotOverlayEl.appendChild(annotPinsEl);
-
- annotClearChipEl = document.createElement('div');
- annotClearChipEl.id = PREFIX + '-annot-clear';
- annotClearChipEl.dataset.annotClear = 'true';
- annotClearChipEl.textContent = 'Clear';
- Object.assign(annotClearChipEl.style, {
- position: 'absolute', top: '8px', right: '8px',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '10px', fontWeight: '500',
- letterSpacing: '0.08em', textTransform: 'uppercase',
- padding: '5px 12px', borderRadius: '999px',
- cursor: 'pointer', pointerEvents: 'auto',
- display: 'none', userSelect: 'none',
- boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
- });
- annotOverlayEl.appendChild(annotClearChipEl);
-
- annotOverlayEl.addEventListener('pointerdown', onAnnotDown);
- annotOverlayEl.addEventListener('pointermove', onAnnotMove);
- annotOverlayEl.addEventListener('pointerup', onAnnotUp);
- annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
- document.body.appendChild(annotOverlayEl);
- // Modal-host friendliness: pointer-events is already 'auto' on this
- // overlay; we only need to silence the host's outside-interaction
- // listeners. Don't override pointer-events here (the overlay toggles
- // visibility via display:none, which is fine).
- defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
- }
-
- function updateClearChip() {
- if (!annotClearChipEl) return;
- const hasAny = annotState.comments.length > 0 || annotState.strokes.length > 0;
- annotClearChipEl.style.display = hasAny ? 'block' : 'none';
- }
-
- function showAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- annotActive = true;
- positionAnnotOverlay(el);
- annotOverlayEl.style.display = 'block';
- }
-
- function hideAnnotOverlay() {
- annotActive = false;
- if (annotOverlayEl) annotOverlayEl.style.display = 'none';
- // Drop any in-progress edit without touching annotState — clearAnnotations
- // (if the caller is exiting configure mode) handles state reset.
- annotEditing = null;
- }
-
- function positionAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- const r = el.getBoundingClientRect();
- Object.assign(annotOverlayEl.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- annotSvgEl.setAttribute('viewBox', '0 0 ' + r.width + ' ' + r.height);
- }
-
- function clearAnnotations() {
- annotState.comments = [];
- annotState.strokes = [];
- if (annotSvgEl) while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- if (annotPinsEl) annotPinsEl.innerHTML = '';
- annotPointer = null;
- annotEditing = null;
- annotLastPinClick = { idx: -1, time: 0 };
- updateClearChip();
- }
-
- // Rebuild the SVG layer. Each stroke gets a wider invisible hit path
- // beneath the visible magenta path so clicks register on thin lines.
- function redrawStrokes() {
- while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- annotState.strokes.forEach((s, idx) => {
- const d = pointsToPath(s.points);
- const hit = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- hit.setAttribute('d', d);
- hit.setAttribute('stroke', 'transparent');
- hit.setAttribute('stroke-width', '16');
- hit.setAttribute('stroke-linecap', 'round');
- hit.setAttribute('stroke-linejoin', 'round');
- hit.setAttribute('fill', 'none');
- hit.setAttribute('pointer-events', 'stroke');
- hit.style.cursor = 'pointer';
- hit.dataset.annotStroke = String(idx);
- annotSvgEl.appendChild(hit);
- const visible = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- visible.setAttribute('d', d);
- visible.setAttribute('stroke', C.brand);
- visible.setAttribute('stroke-width', '3');
- visible.setAttribute('stroke-linecap', 'round');
- visible.setAttribute('stroke-linejoin', 'round');
- visible.setAttribute('fill', 'none');
- visible.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(visible);
- });
- updateClearChip();
- }
-
- function localCoords(e) {
- const rect = annotOverlayEl.getBoundingClientRect();
- return { x: e.clientX - rect.left, y: e.clientY - rect.top };
- }
-
- function onAnnotDown(e) {
- if (!annotActive) return;
-
- // 1) Clear chip → wipe all annotations
- if (e.target.closest?.('[data-annot-clear]')) {
- if (annotEditing) annotEditing = null;
- clearAnnotations();
- renderAllPins();
- redrawStrokes();
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 2) Stroke hit path → delete that stroke
- const strokeHit = e.target.closest?.('[data-annot-stroke]');
- if (strokeHit) {
- const idx = parseInt(strokeHit.dataset.annotStroke, 10);
- if (Number.isInteger(idx)) {
- annotState.strokes.splice(idx, 1);
- redrawStrokes();
- }
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 3) Pin → drag, edit, or delete-on-double-click
- const pinWrap = e.target.closest?.('[data-annot-pin]');
- if (pinWrap) {
- const idx = parseInt(pinWrap.dataset.annotPin, 10);
- if (!Number.isInteger(idx)) return;
- // Double-click (two pointerdowns on the same pin within window) → delete.
- const now = Date.now();
- if (annotLastPinClick.idx === idx && now - annotLastPinClick.time < PIN_DBL_CLICK_MS) {
- if (annotEditing && annotEditing.idx === idx) annotEditing = null;
- annotState.comments.splice(idx, 1);
- annotLastPinClick = { idx: -1, time: 0 };
- renderAllPins();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- annotLastPinClick = { idx, time: now };
- // If editing a different pin, commit that edit before starting here.
- if (annotEditing && annotEditing.idx !== idx) finalizeEditingPin();
- // If already editing THIS pin and the user clicked the dot, let the
- // input keep focus (don't start a drag — the click wasn't meant as one).
- if (annotEditing && annotEditing.idx === idx) return;
- const p = localCoords(e);
- const pin = annotState.comments[idx];
- annotPointer = {
- kind: 'pin', idx,
- startPointer: p,
- startPin: { x: pin.x, y: pin.y },
- moved: false,
- };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 4) Empty area → commit any open edit, then start new annotation
- if (annotEditing) {
- finalizeEditingPin();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- const p = localCoords(e);
- annotPointer = { kind: 'new', x0: p.x, y0: p.y, moved: false, strokeEl: null, strokePoints: null };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- }
-
- function onAnnotMove(e) {
- if (!annotActive || !annotPointer) return;
- const p = localCoords(e);
-
- if (annotPointer.kind === 'pin') {
- const dx = p.x - annotPointer.startPointer.x;
- const dy = p.y - annotPointer.startPointer.y;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- }
- const pin = annotState.comments[annotPointer.idx];
- if (!pin) { annotPointer = null; return; }
- pin.x = annotPointer.startPin.x + dx;
- pin.y = annotPointer.startPin.y + dy;
- renderAllPins();
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const dx = p.x - annotPointer.x0, dy = p.y - annotPointer.y0;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- const strokeEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- strokeEl.setAttribute('stroke', C.brand);
- strokeEl.setAttribute('stroke-width', '3');
- strokeEl.setAttribute('stroke-linecap', 'round');
- strokeEl.setAttribute('stroke-linejoin', 'round');
- strokeEl.setAttribute('fill', 'none');
- strokeEl.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(strokeEl);
- annotPointer.strokeEl = strokeEl;
- annotPointer.strokePoints = [[annotPointer.x0, annotPointer.y0]];
- }
- annotPointer.strokePoints.push([p.x, p.y]);
- annotPointer.strokeEl.setAttribute('d', pointsToPath(annotPointer.strokePoints));
- e.stopPropagation();
- }
-
- function onAnnotUp(e) {
- if (!annotActive || !annotPointer) return;
-
- if (annotPointer.kind === 'pin') {
- const wasDrag = annotPointer.moved;
- const idx = annotPointer.idx;
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- if (wasDrag) {
- // A drag is an intentional reposition; a follow-up click shouldn't be
- // interpreted as a double-click-to-delete.
- annotLastPinClick = { idx: -1, time: 0 };
- } else {
- beginEditPin(idx);
- }
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const wasDrag = annotPointer.moved;
- if (wasDrag) {
- annotState.strokes.push({ points: annotPointer.strokePoints });
- // Swap the temporary preview SVG path for the full render with hit paths.
- redrawStrokes();
- } else {
- const idx = annotState.comments.length;
- annotState.comments.push({ x: annotPointer.x0, y: annotPointer.y0, text: '' });
- renderAllPins();
- beginEditPin(idx);
- }
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- e.stopPropagation();
- }
-
- function pointsToPath(points) {
- if (!points || points.length === 0) return '';
- let d = 'M' + points[0][0].toFixed(1) + ' ' + points[0][1].toFixed(1);
- for (let i = 1; i < points.length; i++) {
- d += ' L' + points[i][0].toFixed(1) + ' ' + points[i][1].toFixed(1);
- }
- return d;
- }
-
- function renderAllPins() {
- annotPinsEl.innerHTML = '';
- annotState.comments.forEach((c, idx) => {
- annotPinsEl.appendChild(buildPinElement(c, idx));
- });
- updateClearChip();
- }
-
- function buildPinElement(comment, idx) {
- const interactive = idx >= 0;
- const wrap = document.createElement('div');
- if (interactive) wrap.dataset.annotPin = String(idx);
- Object.assign(wrap.style, {
- position: 'absolute',
- left: (comment.x - 7) + 'px', top: (comment.y - 7) + 'px',
- pointerEvents: interactive ? 'auto' : 'none',
- display: 'flex', alignItems: 'flex-start', gap: '6px',
- cursor: interactive ? 'grab' : 'default',
- touchAction: 'none',
- });
- const dot = document.createElement('div');
- Object.assign(dot.style, {
- width: '14px', height: '14px', borderRadius: '50%',
- background: C.brand, border: '2px solid ' + C.white,
- boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
- flexShrink: '0',
- });
- wrap.appendChild(dot);
-
- if (comment.text) {
- const bubble = document.createElement('div');
- bubble.textContent = comment.text;
- Object.assign(bubble.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- marginTop: '-2px', maxWidth: '220px',
- pointerEvents: 'none', whiteSpace: 'pre-wrap',
- wordBreak: 'break-word',
- });
- wrap.appendChild(bubble);
- }
- return wrap;
- }
-
- function beginEditPin(idx) {
- const wrapEl = annotPinsEl.querySelector('[data-annot-pin="' + idx + '"]');
- if (!wrapEl) return;
- // Strip any existing bubble (but keep the dot)
- wrapEl.querySelectorAll('div:not(:first-child)').forEach(n => n.remove());
- const input = document.createElement('input');
- input.type = 'text';
- input.placeholder = 'Note…';
- Object.assign(input.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- border: '1px solid ' + C.brand,
- outline: 'none', marginTop: '-2px',
- width: '220px', pointerEvents: 'auto',
- });
- const originalText = annotState.comments[idx].text || '';
- input.value = originalText;
- wrapEl.appendChild(input);
- annotEditing = { idx, input, wrapEl, originalText };
- input.addEventListener('keydown', onAnnotInputKey, true);
- input.addEventListener('blur', () => {
- // Fires on both focus-loss and programmatic blur; commit unless we
- // already handled it.
- if (annotEditing && annotEditing.input === input) finalizeEditingPin();
- });
- // Stop clicks/pointerdowns inside the input from bubbling to the overlay
- ['pointerdown', 'click'].forEach(ev => {
- input.addEventListener(ev, e => e.stopPropagation());
- });
- setTimeout(() => input.focus(), 0);
- }
-
- function onAnnotInputKey(e) {
- if (e.key === 'Enter') {
- e.preventDefault(); e.stopPropagation();
- finalizeEditingPin();
- } else if (e.key === 'Escape') {
- e.preventDefault(); e.stopPropagation();
- cancelEditingPin();
- } else {
- // Keep arrows / backspace from hitting global handlers
- e.stopPropagation();
- }
- }
-
- function finalizeEditingPin() {
- if (!annotEditing) return;
- const { idx, input } = annotEditing;
- const text = input.value.trim();
- annotEditing = null;
- if (text) annotState.comments[idx].text = text;
- else annotState.comments.splice(idx, 1);
- renderAllPins();
- }
-
- function cancelEditingPin() {
- if (!annotEditing) return;
- const { idx, originalText } = annotEditing;
- annotEditing = null;
- // If the pin had text before this edit, revert to it. If it was a
- // just-created empty pin, Escape removes it.
- if (originalText) {
- annotState.comments[idx].text = originalText;
- } else {
- annotState.comments.splice(idx, 1);
- }
- renderAllPins();
- }
-
- // Build a detached annotation subtree suitable for injection into the clone
- // modern-screenshot creates. Coordinates are element-local so this slots
- // straight into an element that's been made position:relative. Takes an
- // explicit snapshot so it works after annotState has been cleared.
- function buildAnnotationsForCapture(rect, snapshot) {
- const comments = snapshot ? snapshot.comments : annotState.comments;
- const strokes = snapshot ? snapshot.strokes : annotState.strokes;
- if (comments.length === 0 && strokes.length === 0) return null;
- const wrap = document.createElement('div');
- Object.assign(wrap.style, {
- position: 'absolute', top: '0', left: '0',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none', overflow: 'visible',
- });
- if (strokes.length > 0) {
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- svg.setAttribute('viewBox', '0 0 ' + rect.width + ' ' + rect.height);
- Object.assign(svg.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%', overflow: 'visible',
- });
- for (const s of strokes) {
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- path.setAttribute('stroke', C.brand);
- path.setAttribute('stroke-width', '3');
- path.setAttribute('stroke-linecap', 'round');
- path.setAttribute('stroke-linejoin', 'round');
- path.setAttribute('fill', 'none');
- path.setAttribute('d', pointsToPath(s.points));
- svg.appendChild(path);
- }
- wrap.appendChild(svg);
- }
- for (const c of comments) {
- // idx=-1 means non-interactive; pointerEvents stay off in the clone
- wrap.appendChild(buildPinElement(c, -1));
- }
- return wrap;
- }
-
- // ---------------------------------------------------------------------------
- // Element context extraction
- // ---------------------------------------------------------------------------
-
- function extractContext(el) {
- const cs = getComputedStyle(el);
- const r = el.getBoundingClientRect();
- const props = {};
- for (const sheet of document.styleSheets) {
- try {
- for (const rule of sheet.cssRules) {
- if (rule.style) for (let i = 0; i < rule.style.length; i++) {
- const p = rule.style[i];
- if (p.startsWith('--') && !props[p]) {
- const v = cs.getPropertyValue(p).trim();
- if (v) props[p] = v;
- }
- }
- }
- } catch { /* cross-origin */ }
- }
- return {
- tagName: el.tagName.toLowerCase(), id: el.id || null,
- classes: [...el.classList],
- textContent: (el.textContent || '').slice(0, 500),
- outerHTML: el.outerHTML.slice(0, 10000),
- computedStyles: {
- 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
- 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
- 'color': cs.color, 'background': cs.background,
- 'background-color': cs.backgroundColor,
- 'padding': cs.padding, 'margin': cs.margin,
- 'display': cs.display, 'position': cs.position,
- 'gap': cs.gap, 'border-radius': cs.borderRadius,
- 'box-shadow': cs.boxShadow,
- },
- cssCustomProperties: props,
- parentContext: el.parentElement
- ? '<' + el.parentElement.tagName.toLowerCase()
- + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
- + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
- + '>'
- : null,
- boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
- };
- }
-
- // ---------------------------------------------------------------------------
- // The Bar — one floating element, three modes
- // ---------------------------------------------------------------------------
-
- // Contextual-bar palette. Cached at init so every build*Row reads a
- // consistent set of colors; detectPageTheme runs once rather than on every
- // phase transition.
- let BP = null;
-
- // Bar shadow variants. The default projects down + subtle around. When
- // the Tune popover opens below the bar, a downward shadow lands on the
- // dark popover and reads as a bright ghost line. We swap to UP-only while
- // tune is open below so the popover's top edge is clean.
- const BAR_SHADOW_DEFAULT = '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_UP = '0 -4px 20px oklch(0% 0 0 / 0.08), 0 -1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_DOWN = BAR_SHADOW_DEFAULT;
-
- function initBar() {
- BP = barPaletteForTheme(detectPageTheme());
- barEl = document.createElement('div');
- barEl.id = PREFIX + '-bar';
- Object.assign(barEl.style, {
- position: 'fixed', zIndex: Z.bar,
- display: 'none', opacity: '0',
- transform: 'translateY(6px)',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- background: BP.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + BP.hairline,
- borderRadius: '10px',
- boxShadow: BAR_SHADOW_DEFAULT,
- transition: 'box-shadow 0.2s ease, opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- fontFamily: FONT, fontSize: '13px', color: BP.text,
- padding: '6px',
- maxWidth: '520px', minWidth: '320px',
- });
- document.body.appendChild(barEl);
- defangOutsideHandlers(barEl);
- }
-
- function positionBar() {
- if (!barEl || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- const barH = barEl.offsetHeight || 44;
- const barW = barEl.offsetWidth || 380;
- const GLOBAL_BAR_RESERVE = 64; // global bar height + bottom margin + breathing room
- const GAP = 8;
-
- // Prefer below the element; fall back to above; if neither fits (element
- // taller than viewport), pin to a stable viewport anchor so the bar
- // doesn't teleport between top and bottom as the user scrolls.
- let top;
- const belowTop = r.bottom + GAP;
- const aboveTop = r.top - barH - GAP;
- if (belowTop + barH + GAP <= window.innerHeight - GLOBAL_BAR_RESERVE) {
- top = belowTop;
- } else if (aboveTop >= GAP) {
- top = aboveTop;
- } else {
- top = window.innerHeight - barH - GLOBAL_BAR_RESERVE;
- }
-
- let left = r.left + (r.width - barW) / 2;
- if (left < GAP) left = GAP;
- if (left + barW > window.innerWidth - GAP) left = window.innerWidth - barW - GAP;
- Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
- }
-
- function showBar(mode) {
- barEl.innerHTML = '';
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- barEl.style.display = 'block';
- positionBar();
- requestAnimationFrame(() => {
- barEl.style.opacity = '1';
- barEl.style.transform = 'translateY(0)';
- });
- }
-
- function hideBar() {
- if (!barEl) return;
- barEl.style.opacity = '0';
- barEl.style.transform = 'translateY(6px)';
- setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
- hideActionPicker();
- closeTunePopover();
- }
-
- function updateBarContent(mode) {
- if (!barEl || barEl.style.display === 'none') return;
- barEl.innerHTML = '';
- // Reset bar styling to the theme-aware palette
- barEl.style.background = BP.surface;
- barEl.style.border = '1px solid ' + BP.hairline;
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- else if (mode === 'saving') barEl.appendChild(buildSavingRow());
- else if (mode === 'confirmed') {
- barEl.appendChild(buildConfirmedRow());
- barEl.style.background = 'oklch(95% 0.05 145)';
- barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
- }
- }
-
- // --- Configure row ---
-
- function buildConfigureRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
-
- // Action pill
- const pill = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '4px',
- padding: '5px 10px', borderRadius: '6px',
- background: BP.mark, color: BP.markText,
- fontFamily: FONT, fontSize: '12px', fontWeight: '500',
- border: 'none', cursor: 'pointer',
- transition: 'background 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap', flexShrink: '0',
- });
- pill.textContent = actionLabel() + ' \u25BE';
- pill.addEventListener('mouseenter', () => pill.style.background = BP.accent);
- pill.addEventListener('mouseleave', () => pill.style.background = BP.mark);
- pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
- pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
- pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
- row.appendChild(pill);
-
- // Freeform input. Focus state shows an accent-colored border only —
- // an earlier version tinted the background with `BP.accentSoft`, which
- // composited against the dark bar surface to a murky purple where the
- // browser's default placeholder gray was unreadable. Placeholder color
- // is set explicitly via a one-shot stylesheet keyed off this input's id
- // so it picks up the bar's `textDim` token in both themes.
- const input = document.createElement('input');
- input.id = PREFIX + '-input';
- input.type = 'text';
- input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
- Object.assign(input.style, {
- flex: '1', minWidth: '0',
- padding: '5px 8px', borderRadius: '6px',
- border: '1px solid transparent', background: 'transparent',
- fontFamily: FONT, fontSize: '12px', color: BP.text,
- outline: 'none',
- transition: 'border-color 0.15s ease',
- });
- if (!document.getElementById(PREFIX + '-input-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-input-style';
- s.textContent =
- '#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
- document.head.appendChild(s);
- }
- input.addEventListener('focus', () => {
- input.style.borderColor = BP.accent;
- });
- input.addEventListener('blur', () => {
- input.style.borderColor = 'transparent';
- });
- input.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
- if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; return; }
- // Let arrow keys pass through to the element picker when the input is empty
- if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && !input.value) return;
- e.stopPropagation();
- });
- row.appendChild(input);
-
- // Variant count toggle
- const count = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: MONO, fontSize: '11px', fontWeight: '600',
- color: BP.textDim, cursor: 'pointer',
- transition: 'color 0.12s ease, border-color 0.12s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- count.textContent = '\u00D7' + selectedCount;
- count.title = 'Variants: click to change';
- count.addEventListener('mouseenter', () => { count.style.color = BP.text; count.style.borderColor = BP.text; });
- count.addEventListener('mouseleave', () => { count.style.color = BP.textDim; count.style.borderColor = BP.hairline; });
- count.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
- count.textContent = '\u00D7' + selectedCount;
- });
- row.appendChild(count);
-
- // Go button
- const go = el('button', {
- padding: '5px 12px', borderRadius: '6px',
- border: 'none', background: BP.accent, color: BP.mark,
- fontFamily: FONT, fontSize: '12px', fontWeight: '600',
- cursor: 'pointer',
- transition: 'filter 0.12s ease, transform 0.1s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- go.textContent = 'Go \u2192';
- go.addEventListener('mouseenter', () => go.style.filter = 'brightness(1.1)');
- go.addEventListener('mouseleave', () => go.style.filter = 'none');
- go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
- go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
- go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
- row.appendChild(go);
-
- // Auto-focus input after a beat
- setTimeout(() => input.focus(), 60);
- return row;
- }
-
- // --- Generating row ---
-
- function buildGeneratingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 4px',
- });
-
- // Action label
- const label = el('span', {
- fontWeight: '600', fontSize: '12px', color: BP.text,
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- label.textContent = actionLabel();
- row.appendChild(label);
-
- // Dots
- row.appendChild(buildDots(false));
-
- // Status
- const status = el('span', {
- fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',
- marginLeft: 'auto',
- });
- // Variants currently arrive atomically in a single file edit, so a
- // per-variant counter would lie. Say what's true.
- status.textContent = arrivedVariants < expectedVariants
- ? 'Generating ' + expectedVariants + ' variants...'
- : 'Done';
- row.appendChild(status);
-
- return row;
- }
-
- // --- Cycling row ---
-
- const TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';
-
- function buildCyclingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '6px',
- padding: '1px 2px',
- });
-
- // Prev
- const prev = navBtn('\u2190');
- prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
- if (visibleVariant <= 1) prev.style.opacity = '0.3';
- row.appendChild(prev);
-
- // Dots (clickable)
- row.appendChild(buildDots(true));
-
- // Counter
- const counter = el('span', {
- fontFamily: MONO, fontSize: '11px', fontWeight: '500',
- color: BP.textDim, minWidth: '24px', textAlign: 'center',
- });
- counter.textContent = visibleVariant + '/' + arrivedVariants;
- row.appendChild(counter);
-
- // Next
- const next = navBtn('\u2192');
- next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
- if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
- row.appendChild(next);
-
- // Tune chip — only when the visible variant exposes params
- const visParams = parseVariantParams(getVisibleVariantEl());
- const hasParams = visParams.length > 0;
- if (hasParams) {
- const tune = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '6px',
- padding: '4px 10px', borderRadius: '5px',
- border: '1px solid transparent',
- background: tuneOpen ? BP.accentSoft : 'transparent',
- color: tuneOpen ? BP.accent : BP.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'color 0.12s ease, background 0.12s ease',
- whiteSpace: 'nowrap',
- });
- tune.innerHTML = TUNE_ICON_SVG;
- const tuneLabel = document.createElement('span');
- tuneLabel.textContent = 'Tune';
- tune.appendChild(tuneLabel);
- const tuneBadge = document.createElement('span');
- Object.assign(tuneBadge.style, {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- minWidth: '16px', height: '16px', padding: '0 4px',
- borderRadius: '999px',
- background: tuneOpen ? C.brand : BP.hairline,
- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',
- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',
- lineHeight: '1',
- boxSizing: 'border-box',
- });
- tuneBadge.textContent = String(visParams.length);
- tune.appendChild(tuneBadge);
- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';
- tune.addEventListener('mouseenter', () => {
- if (!tuneOpen) tune.style.background = BP.accentSoft;
- });
- tune.addEventListener('mouseleave', () => {
- if (!tuneOpen) tune.style.background = 'transparent';
- });
- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });
- tune.dataset.iceqTune = '1';
- row.appendChild(tune);
- }
-
- // Spacer
- row.appendChild(el('div', { flex: '1' }));
-
- // Accept — primary action, uses the site's saturated brand magenta
- // with paper-white text, not the theme-muted BP.accent.
- const accept = el('button', {
- padding: '5px 14px', borderRadius: '5px',
- border: 'none', background: C.brand, color: 'oklch(98% 0 0)',
- fontFamily: FONT, fontSize: '11px', fontWeight: '600',
- cursor: 'pointer', transition: 'filter 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap',
- });
- accept.textContent = '\u2713 Accept';
- accept.addEventListener('mouseenter', () => accept.style.filter = 'brightness(1.08)');
- accept.addEventListener('mouseleave', () => accept.style.filter = 'none');
- accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');
- accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');
- accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
- row.appendChild(accept);
-
- // Discard
- const discard = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: FONT, fontSize: '11px', color: BP.textDim,
- cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
- });
- discard.textContent = '\u2715';
- discard.title = 'Discard all variants';
- discard.addEventListener('mouseenter', () => { discard.style.color = BP.text; discard.style.borderColor = BP.text; });
- discard.addEventListener('mouseleave', () => { discard.style.color = BP.textDim; discard.style.borderColor = BP.hairline; });
- discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
- row.appendChild(discard);
-
- return row;
- }
-
- // --- Shared UI builders ---
-
- // --- Saving row (waiting for agent to process accept/discard) ---
-
- function buildSavingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const spinner = el('div', {
- width: '14px', height: '14px', borderRadius: '50%',
- border: '2px solid ' + BP.hairline,
- borderTopColor: BP.accent,
- animation: 'impeccable-spin 0.6s linear infinite',
- flexShrink: '0',
- });
- row.appendChild(spinner);
- const label = el('span', {
- fontSize: '12px', color: BP.textDim, fontWeight: '500',
- });
- label.textContent = 'Applying variant...';
- row.appendChild(label);
-
- // Inject the keyframes if not already present
- if (!document.getElementById(PREFIX + '-keyframes')) {
- const style = document.createElement('style');
- style.id = PREFIX + '-keyframes';
- style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
- document.head.appendChild(style);
- }
- return row;
- }
-
- // --- Confirmed row (green success, auto-dismisses) ---
-
- function buildConfirmedRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const check = el('span', {
- fontSize: '15px', lineHeight: '1', flexShrink: '0',
- color: 'oklch(45% 0.15 145)',
- });
- check.textContent = '\u2713';
- row.appendChild(check);
- const label = el('span', {
- fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
- });
- label.textContent = 'Variant applied';
- row.appendChild(label);
- return row;
- }
-
- // --- Shared UI builders ---
-
- function buildDots(clickable) {
- const container = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
- for (let i = 1; i <= expectedVariants; i++) {
- const arrived = i <= arrivedVariants;
- const active = i === visibleVariant;
- // active: solid site-brand magenta dot. arrived+inactive: muted neutral.
- // pending (not yet arrived): faint outline ring. No borders on arrived
- // dots — the previous "accent ring + ash fill" combo read as noisy
- // magenta chips, especially when all variants had arrived and every
- // dot wore an accent ring.
- const dotBg = active ? C.brand
- : arrived ? BP.textDim
- : 'transparent';
- const dotBorder = arrived ? 'none' : '1.5px solid ' + BP.hairline;
- const dot = el('div', {
- width: active ? '8px' : '6px',
- height: active ? '8px' : '6px',
- borderRadius: '50%',
- background: dotBg,
- border: dotBorder,
- boxSizing: 'border-box',
- transition: 'all 0.2s ' + EASE,
- cursor: (clickable && arrived) ? 'pointer' : 'default',
- transform: arrived ? 'scale(1)' : 'scale(0.85)',
- opacity: arrived ? (active ? '1' : '0.6') : '0.4',
- });
- if (clickable && arrived) {
- const idx = i;
- dot.addEventListener('click', (e) => {
- e.stopPropagation();
- visibleVariant = idx;
- showVariantInDOM(currentSessionId, idx);
- updateSelectedElement();
- updateBarContent('cycling');
- });
- }
- container.appendChild(dot);
- }
- return container;
- }
-
- function navBtn(text) {
- const b = el('button', {
- width: '26px', height: '26px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- color: BP.text, fontFamily: FONT, fontSize: '13px',
- cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
- transition: 'border-color 0.12s ease, background 0.12s ease',
- padding: '0', lineHeight: '1',
- });
- b.textContent = text;
- b.addEventListener('mouseenter', () => { b.style.borderColor = BP.text; });
- b.addEventListener('mouseleave', () => { b.style.borderColor = BP.hairline; });
- return b;
- }
-
- function actionLabel() {
- const a = ACTIONS.find(a => a.value === selectedAction);
- return a ? a.label : 'Freeform';
- }
-
- function el(tag, styles) {
- const e = document.createElement(tag);
- if (styles) Object.assign(e.style, styles);
- return e;
- }
-
- // ---------------------------------------------------------------------------
- // Action picker popover
- // ---------------------------------------------------------------------------
-
- function initActionPicker() {
- const P = barPaletteForTheme(detectPageTheme());
- pickerEl = document.createElement('div');
- pickerEl.id = PREFIX + '-picker';
- Object.assign(pickerEl.style, {
- position: 'fixed', zIndex: Z.picker,
- display: 'none', opacity: '0',
- transform: 'scale(0.96) translateY(4px)',
- transformOrigin: 'bottom left',
- transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
- background: P.surface,
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
- padding: '6px',
- fontFamily: FONT,
- backdropFilter: 'blur(10px)',
- WebkitBackdropFilter: 'blur(10px)',
- });
-
- // Build the chip grid
- const grid = el('div', {
- display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
- });
-
- ACTIONS.forEach(action => {
- const chip = el('button', {
- display: 'flex', flexDirection: 'column', alignItems: 'center',
- gap: '4px',
- padding: '8px 6px', borderRadius: '6px',
- border: 'none',
- background: action.value === selectedAction ? P.accentSoft : 'transparent',
- color: action.value === selectedAction ? P.accent : P.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.1s ease, color 0.1s ease',
- textAlign: 'center', whiteSpace: 'nowrap',
- });
- const iconWrap = el('span', {
- display: 'flex', alignItems: 'center', justifyContent: 'center',
- height: '20px', opacity: '0.9',
- });
- iconWrap.innerHTML = ICONS[action.value] || '';
- const labelEl = el('span', { lineHeight: '1' });
- labelEl.textContent = action.label;
- chip.appendChild(iconWrap);
- chip.appendChild(labelEl);
- chip.dataset.action = action.value;
- chip.addEventListener('mouseenter', () => {
- if (action.value !== selectedAction) chip.style.background = P.accentSoft;
- });
- chip.addEventListener('mouseleave', () => {
- chip.style.background = action.value === selectedAction ? P.accentSoft : 'transparent';
- });
- chip.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedAction = action.value;
- hideActionPicker();
- updateBarContent('configure');
- });
- grid.appendChild(chip);
- });
-
- pickerEl.appendChild(grid);
- document.body.appendChild(pickerEl);
- defangOutsideHandlers(pickerEl);
-
- // Cache the palette on the picker so toggleActionPicker's state refresh
- // uses the same theme-aware colors when it repaints chips.
- pickerEl.__iceq_palette = P;
- }
-
- function toggleActionPicker() {
- if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
- // Rebuild chips to reflect current selection
- const P = pickerEl.__iceq_palette || barPaletteForTheme(detectPageTheme());
- pickerEl.querySelectorAll('button').forEach(chip => {
- const isActive = chip.dataset.action === selectedAction;
- chip.style.background = isActive ? P.accentSoft : 'transparent';
- chip.style.color = isActive ? P.accent : P.text;
- });
- // Position above the bar
- const barRect = barEl.getBoundingClientRect();
- const pickerH = 170; // approximate; grows with icon + label rows
- let top = barRect.top - pickerH - 6;
- if (top < 8) top = barRect.bottom + 6;
- Object.assign(pickerEl.style, {
- top: top + 'px', left: barRect.left + 'px',
- display: 'block',
- });
- requestAnimationFrame(() => {
- pickerEl.style.opacity = '1';
- pickerEl.style.transform = 'scale(1) translateY(0)';
- });
- }
-
- function hideActionPicker() {
- if (!pickerEl) return;
- pickerEl.style.opacity = '0';
- pickerEl.style.transform = 'scale(0.96) translateY(4px)';
- setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
- }
-
- // ---------------------------------------------------------------------------
- // Params panel (per-variant coarse controls)
- //
- // Variants may declare a parameter manifest via a JSON attribute on the
- // variant wrapper:
- //
- // <div data-impeccable-variant="1"
- // data-impeccable-params='[{"id":"density","kind":"steps",...}]'>
- //
- // The panel docks to the right edge of the outline during CYCLING and
- // exposes 2-5 coarse knobs. Values apply to the variant wrapper so scoped
- // CSS can respond instantly without regeneration:
- //
- // range / numeric toggle → CSS var (`--p-<id>`) used via var(--p-foo, N)
- // steps / boolean toggle → data-p-<id> attribute used via :scope[data-p-foo="..."]
- //
- // On variant switch, values reset to that variant's declared defaults.
- // On accept, current values are sent in the event payload so the agent
- // can bake them into the source-file write.
- // ---------------------------------------------------------------------------
-
- let paramsPanelEl = null; // outer wrapper (overflow:hidden, clips the slide)
- let paramsPanelInner = null; // translating content (carries bg, padding, knobs)
- let paramsPanelBody = null; // grid holding the knob cells
- let paramsCurrentValues = {}; // {paramId: value} — mirror of the visible variant's live values
- let tuneOpen = false; // whether the Tune popover is open right now
-
- // Theme-aware Tune popover. Appears as a drawer that slides out from the
- // contextual bar's bar-facing edge (below if the bar sits below the
- // element, above otherwise). Same width as the bar. Auto-wraps to extra
- // rows when the knobs exceed one row. The bar's border-radius on the
- // popover side goes flat while open so the two shapes read as one.
- let paramsPanelPalette = null;
-
- function initParamsPanel() {
- paramsPanelPalette = barPaletteForTheme(detectPageTheme());
- const P = paramsPanelPalette;
-
- // Single element, always in the DOM. The slide animation is a CSS mask
- // with mask-size growing from 0% to 100% along the bar-facing axis — no
- // display toggle, no opacity toggle, no transform trickery. The mask
- // hides everything initially; as it grows, content is revealed from
- // the bar edge outward.
- paramsPanelEl = document.createElement('div');
- paramsPanelEl.id = PREFIX + '-params-panel';
- Object.assign(paramsPanelEl.style, {
- position: 'fixed', zIndex: String(Z.bar - 1),
- background: P.surfaceDeep,
- color: P.text,
- fontFamily: FONT,
- padding: '14px 18px',
- boxSizing: 'border-box',
- borderRadius: '0 0 10px 10px',
- pointerEvents: 'none',
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
-
- // clip-path is the same conceptual reveal as mask but with rock-solid
- // transition support across engines. Closed state clips from the far
- // edge; open = inset(0) shows everything.
- clipPath: 'inset(0 0 100% 0)',
- transition: 'clip-path 0.44s ' + EASE,
-
- // Park off-screen until positionParamsPanel places it. These are NOT
- // in the transition list, so they snap instantly — no fly-in from the
- // top-left when first shown.
- top: '-9999px', left: '-9999px', width: '0',
- });
-
- paramsPanelBody = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
- gap: '12px 16px',
- });
-
- paramsPanelEl.appendChild(paramsPanelBody);
- document.body.appendChild(paramsPanelEl);
- // Don't override pointer-events: the panel toggles between 'none' (closed,
- // click-through) and 'auto' (open) on its own. Just silence the host's
- // outside-interaction listeners while the panel is open.
- defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
- paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
- }
-
- function getVisibleVariantEl() {
- if (!currentSessionId) return null;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return null;
- return wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"]');
- }
-
- function parseVariantParams(variantEl) {
- if (!variantEl) return [];
- const raw = variantEl.getAttribute('data-impeccable-params');
- if (!raw) return [];
- try {
- const parsed = JSON.parse(raw);
- return Array.isArray(parsed) ? parsed : [];
- } catch (err) {
- console.warn('[impeccable] Invalid data-impeccable-params JSON:', err.message);
- return [];
- }
- }
-
- function applyParamValue(variantEl, param, value) {
- if (!variantEl) return;
- const attr = 'data-p-' + param.id;
- if (param.kind === 'range') {
- variantEl.style.setProperty('--p-' + param.id, String(value));
- } else if (param.kind === 'toggle') {
- const on = !!value;
- variantEl.style.setProperty('--p-' + param.id, on ? '1' : '0');
- if (on) variantEl.setAttribute(attr, 'on');
- else variantEl.removeAttribute(attr);
- } else if (param.kind === 'steps') {
- variantEl.setAttribute(attr, String(value));
- }
- }
-
- function applyParamDefaults(variantEl, params) {
- paramsCurrentValues = {};
- for (const p of params) {
- paramsCurrentValues[p.id] = p.default;
- applyParamValue(variantEl, p, p.default);
- }
- }
-
- function formatRangeValue(input) {
- const max = parseFloat(input.max), min = parseFloat(input.min);
- const v = parseFloat(input.value);
- if (!isFinite(v)) return input.value;
- return (max - min) <= 2 ? v.toFixed(2) : String(Math.round(v));
- }
-
- function buildParamsPanel(variantEl, params) {
- const P = paramsPanelPalette || barPaletteForTheme(detectPageTheme());
- paramsPanelBody.innerHTML = '';
- for (const p of params) {
- const row = el('div', { display: 'flex', flexDirection: 'column', gap: '6px' });
- const labelRow = el('div', {
- display: 'flex', justifyContent: 'space-between',
- alignItems: 'baseline', gap: '8px',
- });
- const lbl = el('span', {
- fontSize: '10.5px', fontWeight: '600', color: P.text,
- letterSpacing: '0.03em',
- });
- lbl.textContent = p.label || p.id;
- labelRow.appendChild(lbl);
- const readout = el('span', {
- fontSize: '10.5px', color: P.textDim,
- fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
- });
- labelRow.appendChild(readout);
- row.appendChild(labelRow);
-
- if (p.kind === 'range') {
- const input = document.createElement('input');
- input.type = 'range';
- input.min = String(p.min != null ? p.min : 0);
- input.max = String(p.max != null ? p.max : 1);
- input.step = String(p.step != null ? p.step : 0.05);
- input.value = String(p.default);
- Object.assign(input.style, {
- width: '100%', accentColor: C.brand, cursor: 'pointer',
- });
- readout.textContent = formatRangeValue(input);
- input.addEventListener('input', (e) => {
- e.stopPropagation();
- const v = parseFloat(input.value);
- paramsCurrentValues[p.id] = v;
- readout.textContent = formatRangeValue(input);
- applyParamValue(variantEl, p, v);
- queueCheckpoint('param_changed');
- });
- row.appendChild(input);
- } else if (p.kind === 'toggle') {
- const initial = !!p.default;
- readout.textContent = initial ? 'On' : 'Off';
- const track = el('button', {
- position: 'relative', width: '36px', height: '20px',
- borderRadius: '10px', border: 'none', padding: '0',
- cursor: 'pointer',
- background: initial ? C.brand : P.hairline,
- transition: 'background 0.15s ease',
- alignSelf: 'flex-start',
- });
- const knob = el('span', {
- position: 'absolute', top: '2px',
- left: initial ? '18px' : '2px',
- width: '16px', height: '16px', borderRadius: '50%',
- background: 'oklch(98% 0 0)',
- transition: 'left 0.18s ' + EASE,
- boxShadow: '0 1px 2px oklch(0% 0 0 / 0.2)',
- });
- track.appendChild(knob);
- track.addEventListener('click', (e) => {
- e.stopPropagation();
- const next = !paramsCurrentValues[p.id];
- paramsCurrentValues[p.id] = next;
- track.style.background = next ? C.brand : P.hairline;
- knob.style.left = next ? '18px' : '2px';
- readout.textContent = next ? 'On' : 'Off';
- applyParamValue(variantEl, p, next);
- queueCheckpoint('param_changed');
- });
- row.appendChild(track);
- } else if (p.kind === 'steps') {
- const opts = (p.options || []).map(o =>
- typeof o === 'string' ? { value: o, label: o } : o
- );
- const activeOpt = opts.find(o => o.value === p.default) || opts[0];
- readout.textContent = activeOpt ? activeOpt.label : String(p.default);
- const segRow = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(' + opts.length + ', 1fr)',
- gap: '1px', padding: '2px',
- background: P.hairline, borderRadius: '5px',
- });
- const segBtns = [];
- opts.forEach(o => {
- const active = o.value === p.default;
- const b = el('button', {
- padding: '5px 4px', border: 'none', borderRadius: '3px',
- background: active ? C.brand : 'transparent',
- color: active ? 'oklch(98% 0 0)' : P.text,
- fontFamily: FONT, fontSize: '10.5px', fontWeight: '500',
- cursor: 'pointer', whiteSpace: 'nowrap',
- transition: 'background 0.1s ease, color 0.1s ease',
- });
- b.textContent = o.label;
- b.addEventListener('click', (e) => {
- e.stopPropagation();
- paramsCurrentValues[p.id] = o.value;
- readout.textContent = o.label;
- segBtns.forEach(({ btn, val }) => {
- const on = val === o.value;
- btn.style.background = on ? C.brand : 'transparent';
- btn.style.color = on ? 'oklch(98% 0 0)' : P.text;
- });
- applyParamValue(variantEl, p, o.value);
- queueCheckpoint('param_changed');
- });
- segRow.appendChild(b);
- segBtns.push({ btn: b, val: o.value });
- });
- row.appendChild(segRow);
- }
-
- paramsPanelBody.appendChild(row);
- }
- }
-
- // Decide which way the popover opens: away from the picked element. If the
- // bar landed below the element, popover slides DOWN from the bar's bottom.
- // If the bar landed above, popover slides UP from the bar's top.
- function popoverDirection() {
- if (!barEl || !selectedElement) return 'below';
- const br = barEl.getBoundingClientRect();
- const er = selectedElement.getBoundingClientRect();
- return br.top >= er.bottom - 4 ? 'below' : 'above';
- }
-
- // The popover overlaps the bar by OVERLAP px on the bar-facing side. With
- // popover z-index below bar, that overlap sits behind bar (invisible) and
- // reinforces the "tucked behind" feel. Padding compensates so the real
- // content starts flush with bar's outer edge.
- const TUNE_OVERLAP = 6;
-
- // Closed clip-path depends on direction: for 'below' clip from the far
- // (bottom) edge so the reveal grows downward from the bar; for 'above'
- // clip from the top edge so the reveal grows upward from the bar.
- function closedClipPath(direction) {
- return direction === 'below' ? 'inset(0 0 100% 0)' : 'inset(100% 0 0 0)';
- }
-
- function setClipPath(value, withTransition) {
- const saved = paramsPanelEl.style.transition;
- if (!withTransition) paramsPanelEl.style.transition = 'none';
- paramsPanelEl.style.clipPath = value;
- if (!withTransition) {
- void paramsPanelEl.offsetHeight;
- paramsPanelEl.style.transition = saved;
- }
- }
-
- function positionParamsPanel() {
- if (!paramsPanelEl || !barEl || barEl.style.display === 'none') return;
- const br = barEl.getBoundingClientRect();
- const direction = popoverDirection();
- const prevDirection = paramsPanelEl.dataset.tuneDirection;
-
- // top/left/width are NOT in the transition list, so they snap instantly.
- paramsPanelEl.style.left = br.left + 'px';
- paramsPanelEl.style.width = br.width + 'px';
-
- if (direction === 'below') {
- paramsPanelEl.style.top = (br.bottom - TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '0 0 10px 10px';
- paramsPanelEl.style.paddingTop = (14 + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.paddingBottom = '14px';
- } else {
- const ih = paramsPanelEl.offsetHeight || 80;
- paramsPanelEl.style.top = (br.top - ih + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '10px 10px 0 0';
- paramsPanelEl.style.paddingTop = '14px';
- paramsPanelEl.style.paddingBottom = (14 + TUNE_OVERLAP) + 'px';
- }
- paramsPanelEl.dataset.tuneDirection = direction;
-
- // If currently closed and direction flipped (or first-time setup),
- // snap the clip-path to the new direction's closed pose without
- // transitioning (so the clip doesn't slide across the element).
- if (!tuneOpen && (!prevDirection || prevDirection !== direction)) {
- setClipPath(closedClipPath(direction), false);
- }
- }
-
- function showParamsPanel() {
- if (!paramsPanelEl) return;
- positionParamsPanel();
- paramsPanelEl.style.pointerEvents = 'auto';
- // rAF so the positioning paint commits before the transition fires.
- requestAnimationFrame(() => {
- setClipPath('inset(0 0 0 0)', true);
- });
- }
-
- function hideParamsPanel() {
- if (!paramsPanelEl) return;
- paramsPanelEl.style.pointerEvents = 'none';
- const direction = paramsPanelEl.dataset.tuneDirection || 'below';
- setClipPath(closedClipPath(direction), true);
- }
-
- // Build/rebuild the panel's contents for the current variant AND apply
- // its defaults to the variant wrapper (so scoped CSS responds even before
- // the user opens the popover). Visibility is governed by tuneOpen.
- function refreshParamsPanel() {
- if (state !== 'CYCLING') {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- if (tuneOpen) {
- // If already visible (variant cycled while open), refresh in place
- // instead of re-running the clip-path animation.
- const alreadyVisible = paramsPanelEl.style.display === 'block'
- && paramsPanelEl.style.opacity === '1';
- if (alreadyVisible) positionParamsPanel();
- else showParamsPanel();
- } else {
- hideParamsPanel();
- }
- }
-
- function toggleTunePopover() {
- if (tuneOpen) { closeTunePopover(); return; }
- openTunePopover();
- }
-
- function openTunePopover() {
- if (state !== 'CYCLING') return;
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) return;
- // Build fresh to ensure the current variant's controls are shown.
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- tuneOpen = true;
- showParamsPanel();
- // Kill the bar's shadow on the popover-facing side so the dark popover
- // doesn't pick up a bright glow line.
- if (barEl) {
- const direction = paramsPanelEl?.dataset.tuneDirection || 'below';
- barEl.style.boxShadow = direction === 'below' ? BAR_SHADOW_UP : BAR_SHADOW_DOWN;
- }
- // Re-render the bar so the Tune chip picks up the active styling.
- updateBarContent('cycling');
- }
-
- function closeTunePopover() {
- tuneOpen = false;
- hideParamsPanel();
- if (barEl) barEl.style.boxShadow = BAR_SHADOW_DEFAULT;
- if (barEl && barEl.style.display !== 'none' && state === 'CYCLING') {
- updateBarContent('cycling');
- }
- }
-
- // ---------------------------------------------------------------------------
- // Variant cycling in DOM
- // ---------------------------------------------------------------------------
-
- function showVariantInDOM(sessionId, num) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
- for (const child of wrapper.children) {
- const v = child.dataset ? child.dataset.impeccableVariant : null;
- if (!v) continue;
- child.style.display = (v === String(num)) ? '' : 'none';
- }
- // Unconditional refresh — covers first-reveal (no-op if state isn't
- // CYCLING yet, the subsequent CYCLING transition triggers its own
- // refresh) and every cycle step.
- refreshParamsPanel();
- }
-
- /**
- * No-HMR fallback: fetch the raw source file from the live server,
- * parse it, extract the variant wrapper, and inject it into the live DOM.
- * This works even when the dev server caches HTML (Bun, static servers).
- */
- function injectVariantsFromSource(filePath, sessionId) {
- const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
- fetch(url)
- .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
- .then(html => {
- // Parse the raw source HTML
- const parser = new DOMParser();
- const doc = parser.parseFromString(html, 'text/html');
- const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!srcWrapper) {
- console.error('[impeccable] Variant wrapper not found in source file.');
- return;
- }
-
- // Find the original element in the live DOM.
- // The original is inside the wrapper in the source. We find the
- // corresponding element in the live DOM by matching the first child's
- // tag + classes from the original snapshot.
- const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
- if (!origContent) return;
-
- const tag = origContent.tagName.toLowerCase();
- const cls = origContent.className;
- let liveEl = null;
- if (origContent.id) {
- liveEl = document.getElementById(origContent.id);
- } else if (cls) {
- // Find by tag + exact class match
- const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
- for (const c of candidates) {
- if (c.className === cls && !own(c)) { liveEl = c; break; }
- }
- }
-
- if (!liveEl) {
- console.error('[impeccable] Could not find original element in live DOM.');
- return;
- }
-
- const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;
-
- // Replace the live element with the full wrapper from source
- const wrapper = srcWrapper.cloneNode(true);
- liveEl.parentElement.replaceChild(wrapper, liveEl);
-
- // Update state: count variants, preserving the user's current variant
- // when a late HMR/source reinjection lands after they have cycled.
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants
- ? previousVisibleVariant
- : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);
- showVariantInDOM(sessionId, visibleVariant);
-
- // Update selectedElement to the visible variant's content
- selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;
-
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- saveSession();
- console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
- })
- .catch(err => {
- console.error('[impeccable] Failed to fetch source:', err);
- showToast('Could not load variants. Try refreshing the page.', 5000);
- });
- }
-
- function cycleVariant(dir) {
- const next = visibleVariant + dir;
- if (next < 1 || next > arrivedVariants) return;
- visibleVariant = next;
- showVariantInDOM(currentSessionId, next); // calls refreshParamsPanel itself
- updateSelectedElement();
- updateBarContent('cycling');
- saveSession();
- queueCheckpoint('variant_changed');
- }
-
- function updateSelectedElement() {
- if (!currentSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return;
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- function readVisibleVariantFromDOM(sessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return 0;
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- for (const variant of variants) {
- if (variant.style.display === 'none') continue;
- const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);
- if (idx > 0) return idx;
- }
- return 0;
- }
-
- // Resolve the element that represents the variant's visible content.
- // Contract: each variant div should contain exactly one top-level element
- // (the full replacement). In practice a model may ship loose siblings or
- // lead with <style>/<script>. Be defensive: skip non-visual elements, and
- // if the variant has multiple element children, use the variant div itself
- // (it wraps all of them and gets correct bounds).
- function pickVariantContent(wrapper, index) {
- if (!wrapper) return null;
- const variantDiv = wrapper.querySelector('[data-impeccable-variant="' + index + '"]');
- if (!variantDiv) return null;
- const NON_VISUAL = new Set(['STYLE', 'SCRIPT', 'LINK', 'META', 'TEMPLATE']);
- const visual = [];
- for (const child of variantDiv.children) {
- if (!NON_VISUAL.has(child.tagName)) visual.push(child);
- }
- if (visual.length === 1) return visual[0];
- return variantDiv;
- }
-
- // Hold window.scrollY at a fixed value across DOM mutations inside the
- // session's wrapper (HMR patches, variant inserts, cycle swaps).
- function startScrollLock(sessionId, initialTargetY) {
- stopScrollLock();
- scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)
- ? initialTargetY
- : window.scrollY;
- console.log('[impeccable.scroll] startScrollLock', { sessionId, scrollY: window.scrollY, targetY: scrollLockTargetY, initialOverride: initialTargetY });
-
- try { history.scrollRestoration = 'manual'; } catch {}
-
- const prevHtmlAnchor = document.documentElement.style.overflowAnchor;
- const prevBodyAnchor = document.body.style.overflowAnchor;
- document.documentElement.style.overflowAnchor = 'none';
- document.body.style.overflowAnchor = 'none';
-
- const correct = (why) => {
- scrollLockRaf = null;
- if (scrollLockTargetY == null) return;
- const before = window.scrollY;
- const delta = before - scrollLockTargetY;
- if (Math.abs(delta) < 0.5) {
- console.log('[impeccable.scroll] correct noop', { why, scrollY: before, targetY: scrollLockTargetY });
- return;
- }
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] corrected', { why, from: before, to: scrollLockTargetY, delta, nowAt: window.scrollY });
- };
- const schedule = (why) => {
- if (scrollLockRaf != null) return;
- scrollLockRaf = requestAnimationFrame(() => correct(why));
- };
-
- scrollLockObserver = new MutationObserver((mutations) => {
- for (const m of mutations) {
- if (m.target?.closest?.('[data-impeccable-variants="' + sessionId + '"]')) {
- const childAdds = Array.from(m.addedNodes).map(n => n.nodeType === 1 ? (n.tagName + (n.dataset?.impeccableVariant ? ('[variant=' + n.dataset.impeccableVariant + ']') : '')) : n.nodeType).join(',');
- console.log('[impeccable.scroll] mutation inside wrapper', { type: m.type, target: m.target?.tagName, adds: childAdds, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('mutation-in-wrapper');
- return;
- }
- for (const n of m.addedNodes) {
- if (n.nodeType === 1 && (n.matches?.('[data-impeccable-variants="' + sessionId + '"]') || n.querySelector?.('[data-impeccable-variants="' + sessionId + '"]'))) {
- console.log('[impeccable.scroll] wrapper node added', { tag: n.tagName, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('wrapper-added');
- return;
- }
- }
- }
- });
- scrollLockObserver.observe(document.body, { childList: true, subtree: true });
-
- scrollLockAbort = new AbortController();
- scrollLockAbort.signal.addEventListener('abort', () => {
- document.documentElement.style.overflowAnchor = prevHtmlAnchor;
- document.body.style.overflowAnchor = prevBodyAnchor;
- }, { once: true });
- const sig = { signal: scrollLockAbort.signal };
- // Track whether the most recent scroll came from a user gesture. We
- // gate user-scroll re-anchoring on this flag so programmatic smooth
- // scrolls (browser reload-restore, scrollIntoView from other scripts)
- // don't accidentally update our target.
- let userGestureAt = 0;
- const USER_GESTURE_WINDOW_MS = 250;
-
- const reanchor = (why) => {
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- const prevTarget = scrollLockTargetY;
- scrollLockTargetY = window.scrollY;
- writeScrollY(scrollLockTargetY);
- console.log('[impeccable.scroll] reanchor', { why, prevTarget, newTarget: scrollLockTargetY });
- };
- const markGesture = (why) => {
- userGestureAt = performance.now();
- reanchor(why);
- };
- window.addEventListener('wheel', () => markGesture('wheel'), { passive: true, ...sig });
- window.addEventListener('touchstart', () => markGesture('touchstart'), { passive: true, ...sig });
- window.addEventListener('touchmove', () => markGesture('touchmove'), { passive: true, ...sig });
- window.addEventListener('keydown', (e) => {
- if (['PageDown', 'PageUp', ' ', 'End', 'Home', 'ArrowDown', 'ArrowUp'].includes(e.key)) markGesture('key:' + e.key);
- }, sig);
-
- // Correct on EVERY scroll event: whether it's the browser's
- // post-reload animated restore or some other script calling
- // scrollIntoView, we want to snap back immediately. Only skip if a
- // user gesture fired in the last 250ms.
- let lastLoggedScrollY = window.scrollY;
- window.addEventListener('scroll', () => {
- const now = window.scrollY;
- if (Math.abs(now - lastLoggedScrollY) > 5) {
- console.log('[impeccable.scroll] scroll event', { from: lastLoggedScrollY, to: now, targetY: scrollLockTargetY });
- lastLoggedScrollY = now;
- }
- if (scrollLockTargetY == null) return;
- if (performance.now() - userGestureAt < USER_GESTURE_WINDOW_MS) return;
- if (Math.abs(now - scrollLockTargetY) < 0.5) return;
- console.log('[impeccable.scroll] scroll-event snap', { from: now, to: scrollLockTargetY });
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- }, { passive: true, ...sig });
-
- // Apply target synchronously, not via rAF — racing the browser's
- // restore or a smooth-scroll animation means we want to win now.
- if (Math.abs(window.scrollY - scrollLockTargetY) > 0.5) {
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] startScrollLock initial apply', { to: scrollLockTargetY });
- }
- }
-
- function stopScrollLock() {
- if (scrollLockObserver) { scrollLockObserver.disconnect(); scrollLockObserver = null; }
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }
- scrollLockTargetY = null;
- // NOTE: do NOT clear the persistent scroll key here. startScrollLock
- // calls us as a reset, and clearing the key would nuke the Go-time
- // scrollY that the next resume needs to read.
- }
-
- // ---------------------------------------------------------------------------
- // MutationObserver for progressive variant reveal
- // ---------------------------------------------------------------------------
-
- function startVariantObserver(sessionId) {
- let updating = false; // re-entrancy guard
-
- const obs = new MutationObserver((mutations) => {
- if (updating) return;
-
- // Only react to mutations that add nodes with data-impeccable-variant,
- // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
- let dominated = false;
- for (const m of mutations) {
- if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
- for (const n of m.addedNodes) {
- if (n.nodeType !== 1) continue;
- // Direct hit: the added node itself is the wrapper or a variant.
- if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
- dominated = true; break;
- }
- // Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
- // a whole subtree where the wrapper is a descendant of the added
- // node. Without this check, the observer ignores those mutations
- // and the session stays in GENERATING forever.
- if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
- dominated = true; break;
- }
- }
- if (dominated) break;
- }
- if (!dominated) return;
-
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
-
- // Re-anchor selectedElement if it was detached by live-wrap's HMR swap.
- // Without this, the shader / highlight / bar track a zero-rect phantom
- // and the overlay appears frozen.
- if (selectedElement && !document.body.contains(selectedElement)) {
- selectedElement = pickVariantContent(wrapper, 'original') || wrapper;
- }
-
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- const count = variants.length;
-
- // Nothing new
- if (count <= arrivedVariants) return;
-
- updating = true;
- arrivedVariants = count;
- if (visibleVariant === 0 && arrivedVariants > 0) {
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;
- showVariantInDOM(sessionId, visibleVariant);
- // showVariantInDOM hid the original (display:none); if we were still
- // anchored to the original's content, its boundingRect is now zero
- // and the bar snaps to (0,0). Re-point at the visible variant instead.
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- if (expected > 0) expectedVariants = expected;
-
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- } else if (state === 'GENERATING') {
- updateBarContent('generating');
- }
- saveSession();
- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');
- updating = false;
- });
-
- obs.observe(document.body, { childList: true, subtree: true });
- return obs;
- }
-
- // ---------------------------------------------------------------------------
- // Bar scroll tracking
- // ---------------------------------------------------------------------------
-
- function startScrollTracking() {
- function tick() {
- if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
- positionBar();
- showHighlight(selectedElement);
- if (tuneOpen) positionParamsPanel();
- }
- if (annotActive) positionAnnotOverlay(selectedElement);
- // Shader overlay (via debug P toggle or generation) is repositioned
- // by its own branch below; debug no longer has a separate overlay.
- if (shaderState) positionShaderOverlay();
- scrollRaf = requestAnimationFrame(tick);
- }
- scrollRaf = requestAnimationFrame(tick);
- }
-
- function stopScrollTracking() {
- if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
- }
-
- // ---------------------------------------------------------------------------
- // SSE (server→browser) + fetch POST (browser→server)
- // Zero-dependency replacement for WebSocket.
- // ---------------------------------------------------------------------------
-
- let evtSource = null;
- let sseRetries = 0;
- const SSE_MAX_RETRIES = 20; // generous: heartbeats keep the connection alive, so retries mean real trouble
-
- function connectSSE() {
- evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
-
- evtSource.onopen = () => {
- sseRetries = 0; // reset on successful (re)connect
- };
-
- evtSource.onmessage = (e) => {
- sseRetries = 0; // reset on any successful message
- let msg; try { msg = JSON.parse(e.data); } catch { return; }
- switch (msg.type) {
- case 'connected':
- hasProjectContext = !!msg.hasProjectContext;
- if (!hasProjectContext) showToast('No PRODUCT.md found. Variants will be brand-agnostic. Run /impeccable teach to generate one.', 7000);
- console.log('[impeccable] Live mode connected.');
- if (state === 'IDLE') state = 'PICKING';
- break;
- case 'done':
- // Variants already arrived via HMR → normal transition.
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- if (state === 'GENERATING') {
- state = 'CYCLING';
- updateBarContent('cycling');
- refreshParamsPanel();
- }
- break;
- }
- // Variants are in source but not in the DOM yet. Common when the
- // picked element lived inside conditional render (closed modal,
- // hidden tab, a route the user navigated away from). The variant
- // MutationObserver stays armed and auto-transitions to CYCLING
- // the moment the wrapper actually mounts. Nudge the user toward
- // that path with a toast — better than the prior force-reload
- // which reset framework state and left the session stuck.
- setTimeout(() => {
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
- if (state !== 'GENERATING') return;
- showToast(
- "Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
- 15000,
- );
- }, 2000);
- break;
- case 'error':
- console.error('[impeccable] Error:', msg.message);
- showToast('Error: ' + msg.message, 5000);
- hideBar();
- state = 'PICKING';
- break;
- }
- };
-
- evtSource.onerror = () => {
- sseRetries++;
- if (sseRetries <= SSE_MAX_RETRIES) {
- console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
- return; // EventSource auto-reconnects
- }
- // Server is gone. Clean up gracefully.
- console.log('[impeccable] Live server unreachable. Cleaning up UI.');
- evtSource.close();
- evtSource = null;
- handleServerLost();
- };
- }
-
- /** Server died or became unreachable. Reset UI to a clean state. */
- function handleServerLost() {
- const recoveryState = currentSessionId ? state : 'IDLE';
- if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
- showToast('Live server disconnected. Session ended.', 5000);
- }
- hideBar();
- hideHighlight();
- hideShaderOverlay();
- hideAnnotOverlay();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- // Preserve local session state on server loss. The durable journal is the
- // source of truth, but localStorage plus the variant wrapper lets the UI
- // resume after a helper restart or page reload instead of treating a
- // transient disconnect as an explicit discard.
- selectedElement = null;
- selectedAction = 'impeccable';
- state = recoveryState;
- if (currentSessionId) saveSession();
- }
-
- function sendEvent(msg, opts) {
- msg.token = TOKEN;
- function handleFailure(err) {
- console.error('[impeccable] Failed to send event:', err);
- if (opts && opts.throwOnError) throw err;
- return null;
- }
- return fetch('http://localhost:' + PORT + '/events', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(msg),
- }).then(res => {
- if (res.ok) return res;
- return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));
- }).catch(handleFailure);
- }
-
- function checkpointPayload(reason) {
- return {
- type: 'checkpoint',
- id: currentSessionId,
- revision: sessionState.nextCheckpointRevision(),
- owner: browserOwner,
- phase: String(state || '').toLowerCase(),
- reason,
- pageUrl: location.pathname,
- expectedVariants,
- arrivedVariants,
- visibleVariant,
- paramValues: { ...paramsCurrentValues },
- };
- }
-
- function sendCheckpoint(reason) {
- if (!currentSessionId) return Promise.resolve(null);
- return sendEvent(checkpointPayload(reason)).catch(() => null);
- }
-
- function queueCheckpoint(reason) {
- if (!currentSessionId) return;
- if (checkpointTimer) clearTimeout(checkpointTimer);
- checkpointTimer = setTimeout(() => {
- checkpointTimer = null;
- sendCheckpoint(reason);
- }, 120);
- }
-
- // ---------------------------------------------------------------------------
- // Event handlers
- // ---------------------------------------------------------------------------
-
- function handleMouseMove(e) {
- if (state !== 'PICKING' || !pickActive) return;
- const target = document.elementFromPoint(e.clientX, e.clientY);
- if (!target || !pickable(target) || target === hoveredElement) return;
- hoveredElement = target;
- showHighlight(target);
- }
-
- function handleClick(e) {
- // Close action picker on any outside click
- if (pickerEl?.style.display !== 'none' && !own(e.target)) {
- hideActionPicker();
- }
- // Close Tune popover on outside click (anything outside panel + bar)
- if (tuneOpen && paramsPanelEl && !paramsPanelEl.contains(e.target) && barEl && !barEl.contains(e.target)) {
- closeTunePopover();
- }
- // In CONFIGURING: click outside the bar and selected element returns to PICKING
- if (state === 'CONFIGURING' && !own(e.target) && selectedElement && !selectedElement.contains(e.target)) {
- hideBar();
- stopScrollTracking();
- hideAnnotOverlay();
- clearAnnotations();
- state = 'PICKING';
- hoveredElement = null;
- hideHighlight();
- return;
- }
- if (state !== 'PICKING' || !pickActive) return;
- if (own(e.target)) return;
- if (!hoveredElement || !pickable(hoveredElement)) return;
- e.preventDefault();
- e.stopPropagation();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- maybePrefetchPage();
- maybeWarnConditionalAncestor(selectedElement);
- }
-
- /**
- * Surface a brief, non-blocking heads-up when the picked element lives
- * inside a container whose visibility is gated by ephemeral state — modals,
- * collapsible panels, popovers, off-screen tab panels. If HMR remounts the
- * parent during generation (Vite Fast Refresh, SvelteKit page reload), the
- * variants land in source but stay invisible until the user re-opens the
- * container. Telling the user upfront is much friendlier than the silent
- * timeout-then-toast that they'd otherwise hit.
- *
- * Heuristic, intentionally narrow — only fires for unambiguous cases so
- * we don't cry wolf on every nested element.
- */
- function maybeWarnConditionalAncestor(el) {
- let node = el?.parentElement;
- let depth = 0;
- while (node && depth < 12) {
- // 1. Active dialog / modal
- if (node.getAttribute && node.getAttribute('role') === 'dialog'
- && node.getAttribute('aria-modal') === 'true') {
- showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 2. Common Radix / shadcn / headless-ui open-state attribute
- if (node.dataset && node.dataset.state === 'open') {
- showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 3. Tab panel — only meaningful when the page also shows ANOTHER
- // tab as selected. A single tabpanel with no tablist is just a static
- // section in disguise and isn't conditional.
- if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
- const list = document.querySelector('[role="tablist"]');
- if (list) {
- const tabs = list.querySelectorAll('[role="tab"]');
- if (tabs.length > 1) {
- showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
- return;
- }
- }
- }
- // 4. Collapsible: aria-expanded sibling. Look for the trigger button.
- if (node.id) {
- const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
- if (trigger) {
- showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
- return;
- }
- }
- node = node.parentElement;
- depth++;
- }
- }
-
- // Fire a lightweight prefetch event the first time the user selects an
- // element on a given route. The agent uses this to Read the underlying file
- // into context before Go is hit, shaving the read off the critical path.
- // Dedupe per session by pathname — clicking around on the same page doesn't
- // re-fire.
- //
- // DISABLED: quick-Go workflows pay an extra harness round trip because
- // prefetch + generate arrive as two events instead of one. Re-enable with
- // a browser-side debounce (~800–1000ms, cancelled on Go) if we want to
- // resurrect this. Server validator and skill dispatch remain in place so
- // flipping this flag is the only change needed.
- const PREFETCH_ENABLED = false;
- const prefetchedPaths = new Set();
- function maybePrefetchPage() {
- if (!PREFETCH_ENABLED) return;
- const path = location.pathname;
- if (prefetchedPaths.has(path)) return;
- prefetchedPaths.add(path);
- sendEvent({ type: 'prefetch', pageUrl: path });
- }
-
- function handleKeyDown(e) {
- // When the annotation input is focused, let it handle its own keys.
- if (annotEditing && annotEditing.input && e.target === annotEditing.input) return;
- if (e.key === 'Escape') {
- e.preventDefault();
- if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
- if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); hideAnnotOverlay(); clearAnnotations(); state = 'PICKING'; return; }
- if (state === 'CYCLING') { handleDiscard(); return; }
- if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
- if (state === 'PICKING') {
- // Use togglePick so the "Pick" button in the global bar also flips
- // off, otherwise the bar stays lit while nothing else is active.
- if (pickActive) togglePick();
- else { hideHighlight(); state = 'IDLE'; }
- return;
- }
- }
-
- // Arrow/Enter nav works in PICKING (hover) and CONFIGURING (selected, input empty)
- var navEl = (state === 'PICKING') ? hoveredElement : (state === 'CONFIGURING') ? selectedElement : null;
- if (navEl && (e.key === 'ArrowUp' || e.key === 'ArrowDown' || (e.key === 'Enter' && state === 'PICKING'))) {
- let next = null;
- if (e.key === 'ArrowDown' && !e.shiftKey) {
- next = navEl.nextElementSibling;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'ArrowUp' && !e.shiftKey) {
- next = navEl.previousElementSibling;
- while (next && !pickable(next)) next = next.previousElementSibling;
- } else if (e.key === 'ArrowUp' && e.shiftKey) {
- next = navEl.parentElement;
- if (next && !pickable(next)) next = null;
- } else if (e.key === 'ArrowDown' && e.shiftKey) {
- next = navEl.firstElementChild;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'Enter') {
- e.preventDefault();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- return;
- }
- if (next) {
- e.preventDefault();
- if (state === 'PICKING') {
- hoveredElement = next;
- } else {
- // CONFIGURING: re-select the new element and refresh the bar
- selectedElement = next;
- clearAnnotations();
- showAnnotOverlay(next);
- showBar('configure');
- startScrollTracking();
- }
- showHighlight(next);
- next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
- }
- return;
- }
-
- if (state === 'CYCLING') {
- if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
- if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
- if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
- }
- }
-
- function handleGo() {
- if (!selectedElement || state !== 'CONFIGURING') return;
- const input = document.getElementById(PREFIX + '-input');
- const prompt = input ? input.value.trim() : '';
-
- // Commit any pending pin edit BEFORE we snapshot annotations.
- if (annotEditing) finalizeEditingPin();
-
- currentSessionId = id8();
- expectedVariants = selectedCount;
- arrivedVariants = 0;
- visibleVariant = 0;
-
- // Flip to GENERATING immediately so the bar morphs without waiting on
- // capture + upload. The event is emitted from captureAndEmit() once the
- // screenshot is uploaded (or capture fails — we still emit, just without
- // screenshotPath).
- const elForCapture = selectedElement;
- const captureRect = elForCapture.getBoundingClientRect();
- const snapshot = {
- comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),
- strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),
- };
- const basePayload = {
- type: 'generate', id: currentSessionId,
- action: selectedAction,
- freeformPrompt: prompt || undefined,
- count: selectedCount,
- pageUrl: location.pathname,
- element: extractContext(elForCapture),
- };
- if (snapshot.comments.length > 0) basePayload.comments = snapshot.comments;
- if (snapshot.strokes.length > 0) basePayload.strokes = snapshot.strokes;
-
- // Hide the interactive overlay so it doesn't linger during generation.
- hideAnnotOverlay();
- clearAnnotations();
-
- state = 'GENERATING';
- showBar('generating');
- saveSession();
- sendCheckpoint('generate_started');
- writeScrollY(window.scrollY);
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
- console.log('[impeccable.scroll] Go pressed', { scrollY: window.scrollY, sessionId: currentSessionId });
- startScrollLock(currentSessionId);
-
- captureAndEmit(elForCapture, basePayload, snapshot, captureRect);
- }
-
- // ---------------------------------------------------------------------------
- // Screenshot capture + upload
- // ---------------------------------------------------------------------------
-
- let msLoadPromise = null;
- function loadModernScreenshot() {
- if (window.modernScreenshot) return Promise.resolve(window.modernScreenshot);
- if (msLoadPromise) return msLoadPromise;
- msLoadPromise = new Promise((resolve, reject) => {
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/modern-screenshot.js';
- s.onload = () => resolve(window.modernScreenshot);
- s.onerror = () => { msLoadPromise = null; reject(new Error('modern-screenshot failed to load')); };
- document.head.appendChild(s);
- });
- return msLoadPromise;
- }
-
- // Collect @font-face rules from every stylesheet on the page. Cross-origin
- // sheets (Google Fonts, Typekit, etc.) throw SecurityError on .cssRules
- // access, so modern-screenshot can't embed them on its own — the resulting
- // SVG falls back to system fonts and text re-wraps + renders with different
- // weight. We fetch the raw CSS text (CORS-permitted for these providers),
- // extract @font-face blocks, inline the referenced font files as base64
- // data URIs (SVGs rasterized via canvas can't fetch external resources,
- // so URLs inside the SVG silently fail without this), and pass the result
- // to modern-screenshot as font.cssText.
- const FONT_EXT_RE = /\.(woff2?|ttf|otf|eot)(\?.*)?$/i;
- const FONT_MIME = {
- woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', eot: 'application/vnd.ms-fontobject',
- };
- function bufferToBase64(buf) {
- const bytes = new Uint8Array(buf);
- let binary = '';
- const CHUNK = 0x8000;
- for (let i = 0; i < bytes.length; i += CHUNK) {
- binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
- }
- return btoa(binary);
- }
- async function inlineFontUrls(cssText) {
- const urlRe = /url\((['"]?)(https?:\/\/[^'")\s]+)\1\)/g;
- const urls = new Set();
- let m;
- while ((m = urlRe.exec(cssText))) {
- if (FONT_EXT_RE.test(m[2])) urls.add(m[2]);
- }
- const map = new Map();
- await Promise.all([...urls].map(async (url) => {
- try {
- const res = await fetch(url);
- if (!res.ok) return;
- const buf = await res.arrayBuffer();
- const ext = url.toLowerCase().match(FONT_EXT_RE)?.[1] || 'woff2';
- const mime = FONT_MIME[ext] || 'application/octet-stream';
- map.set(url, 'data:' + mime + ';base64,' + bufferToBase64(buf));
- } catch { /* skip; fall through to URL */ }
- }));
- return cssText.replace(urlRe, (orig, q, url) => {
- const data = map.get(url);
- return data ? 'url(' + q + data + q + ')' : orig;
- });
- }
- async function collectFontCssText() {
- const chunks = [];
- const fontFaceRe = /@font-face\s*\{[^}]*\}/g;
- for (const sheet of document.styleSheets) {
- try {
- const rules = sheet.cssRules;
- for (const rule of rules) {
- if (rule.constructor.name === 'CSSFontFaceRule' || rule.cssText?.startsWith('@font-face')) {
- chunks.push(rule.cssText);
- }
- }
- } catch {
- if (!sheet.href) continue;
- try {
- const res = await fetch(sheet.href);
- if (!res.ok) continue;
- const text = await res.text();
- let m2;
- while ((m2 = fontFaceRe.exec(text))) chunks.push(m2[0]);
- } catch { /* ignore; capture is best-effort */ }
- }
- }
- if (chunks.length === 0) return '';
- return inlineFontUrls(chunks.join('\n'));
- }
-
- // True if `s` is a computed color string that renders as nothing
- // (explicit `transparent`, or `rgba(...)` with alpha 0).
- function isTransparentColor(s) {
- if (!s) return true;
- if (s === 'transparent') return true;
- const m = /rgba?\(([^)]+)\)/.exec(s);
- if (!m) return false;
- const parts = m[1].split(',').map((p) => p.trim());
- if (parts.length === 4) return parseFloat(parts[3]) === 0;
- return false;
- }
-
- // modern-screenshot force-sets `background-color: X !important` on the
- // cloned root whenever `backgroundColor` is passed, clobbering the
- // element's own background. So we only pass it when the element is
- // genuinely transparent (no own color, no own image) — in that case
- // we resolve up the DOM to the nearest opaque ancestor so the capture
- // sits on the page's real background instead of rendering black.
- function resolveCanvasBackground(el) {
- const own = getComputedStyle(el);
- if (!isTransparentColor(own.backgroundColor)) return null;
- if (own.backgroundImage && own.backgroundImage !== 'none') return null;
- let node = el.parentElement;
- while (node) {
- const cs = getComputedStyle(node);
- if (!isTransparentColor(cs.backgroundColor)) return cs.backgroundColor;
- node = node.parentElement;
- }
- // The walk already passed through <body> and <html>; if they had been
- // opaque we would have returned. Falling through with the previous
- // `getComputedStyle(body).backgroundColor || …` chain is a trap: that
- // call returns the literal string `"rgba(0, 0, 0, 0)"` for a page that
- // never set its own bg, which is truthy and short-circuits the chain to
- // transparent-black — modern-screenshot then renders the capture on a
- // black canvas and the shader overlay flashes solid black during load.
- // The browser canvas defaults to white, so we do too.
- return '#ffffff';
- }
-
- // Capture the element (with current annotations baked in) and return a PNG
- // Blob. Shared between the Go flow (uploads it to the server) and the
- // debug toggle (displays it as an overlay for side-by-side comparison).
- async function captureElementToBlob(el, snapshot, rect) {
- try { if (document.fonts?.ready) await document.fonts.ready; } catch {}
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- let annotNode = null;
- let savedPosition = null;
- if (hasAnnotations) {
- const pos = getComputedStyle(el).position;
- if (pos === 'static') {
- savedPosition = el.style.position;
- el.style.position = 'relative';
- }
- annotNode = buildAnnotationsForCapture(rect, snapshot);
- el.appendChild(annotNode);
- }
- try {
- const ms = await loadModernScreenshot();
- const fontCssText = await collectFontCssText();
- const backgroundColor = resolveCanvasBackground(el);
- return await ms.domToBlob(el, {
- scale: Math.min(window.devicePixelRatio || 1, 2),
- font: fontCssText ? { cssText: fontCssText } : undefined,
- ...(backgroundColor ? { backgroundColor } : {}),
- });
- } finally {
- if (annotNode) annotNode.remove();
- if (savedPosition !== null) el.style.position = savedPosition;
- }
- }
-
- async function captureAndEmit(el, basePayload, snapshot, rect) {
- let screenshotPath;
- let blob;
- try {
- blob = await captureElementToBlob(el, snapshot, rect);
- } catch (err) {
- console.warn('[impeccable] capture failed, proceeding without screenshot:', err);
- }
- // Light up the shader overlay the moment capture is ready — no reason to
- // wait for the upload to complete before the user sees something alive.
- if (blob && state === 'GENERATING') {
- showShaderOverlay(el, blob, rect);
- }
- // Only upload + forward the screenshot when annotations (comments/strokes)
- // are present. Without annotations the image is pure visual anchoring —
- // it biases the model toward the current rendering and works against the
- // three-distinct-directions brief.
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- if (blob && hasAnnotations) {
- try {
- const uploadRes = await fetch(
- 'http://localhost:' + PORT + '/annotation?token=' + encodeURIComponent(TOKEN) +
- '&eventId=' + encodeURIComponent(basePayload.id),
- { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: blob },
- );
- if (uploadRes.ok) {
- const { path: p } = await uploadRes.json();
- screenshotPath = p;
- } else {
- console.warn('[impeccable] annotation upload failed:', uploadRes.status);
- }
- } catch (err) {
- console.warn('[impeccable] annotation upload failed:', err);
- }
- }
- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);
- }
-
- // ---------------------------------------------------------------------------
- // Shader overlay — renders the captured screenshot as a WebGL texture and
- // runs an editorial "ink-wash" fragment shader over it during generation.
- // A single rolling band sweeps top-to-bottom, desaturating + tinting magenta
- // and leaving a soft trail. Makes the wait feel like a letterpress scan
- // instead of a dead spinner.
- // ---------------------------------------------------------------------------
-
- const SHADER_VS = `attribute vec2 a_position;
-attribute vec2 a_uv;
-varying vec2 v_uv;
-void main() {
- v_uv = a_uv;
- gl_Position = vec4(a_position, 0.0, 1.0);
-}`;
-
- const SHADER_FS = `precision highp float;
-uniform sampler2D u_texture;
-uniform float u_time;
-uniform vec2 u_resolution;
-uniform vec3 u_accent;
-varying vec2 v_uv;
-
-// Asymmetric roller band. Product of two one-sided smoothsteps — peaks at
-// d=0 with a short sharp leading ramp and a longer soft trailing tail. Clean
-// outside the [-leadW, trailW] range (no rogue "trail=1 everywhere below"
-// failure that reversed-edge smoothstep would give).
-float bandAt(float d, float leadW, float trailW) {
- float above = smoothstep(-leadW, 0.0, d);
- float below = 1.0 - smoothstep(0.0, trailW, d);
- return above * below;
-}
-
-void main() {
- vec2 uv = v_uv;
- // Roller sweeps top-to-bottom with small overshoot so each cycle enters
- // and exits the element cleanly.
- float phase = fract(u_time / 3.4);
- float y = phase * 1.25 - 0.12;
- float band = bandAt(uv.y - y, 0.05, 0.32);
-
- // Halftone cell grid (fixed ~10 px pitch).
- float cellPx = 10.0;
- vec2 gridUv = uv * u_resolution / cellPx;
- vec2 cellId = floor(gridUv);
- vec2 cellUv = fract(gridUv) - 0.5;
- vec2 sampleCenter = (cellId + 0.5) * cellPx / u_resolution;
- vec3 cellImg = texture2D(u_texture, sampleCenter).rgb;
- float luma = dot(cellImg, vec3(0.299, 0.587, 0.114));
- // Darker cells → bigger magenta dots (classic risograph halftone curve).
- float radius = sqrt(clamp(1.0 - luma, 0.0, 1.0)) * 0.56;
- float dotMask = smoothstep(radius + 0.06, radius, length(cellUv));
- vec3 paper = vec3(0.975, 0.965, 0.955);
- vec3 dotLayer = mix(paper, u_accent, dotMask);
-
- // Blend the halftone layer in where the roller is passing; leave the
- // element pristine elsewhere.
- vec3 base = texture2D(u_texture, uv).rgb;
- gl_FragColor = vec4(mix(base, dotLayer, band), 1.0);
-}`;
-
- // Editorial Magenta converted to approximate sRGB 0-1 (matches oklch(60% 0.25 350))
- const SHADER_ACCENT = [0.82, 0.16, 0.47];
- let shaderState = null; // { canvas, gl, program, texture, rafId, startTime }
-
- function compileShader(gl, type, source) {
- const sh = gl.createShader(type);
- gl.shaderSource(sh, source);
- gl.compileShader(sh);
- if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
- const info = gl.getShaderInfoLog(sh);
- gl.deleteShader(sh);
- throw new Error('shader compile failed: ' + info);
- }
- return sh;
- }
-
- function positionShaderOverlay() {
- if (!shaderState || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- Object.assign(shaderState.canvas.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- }
-
- function hideShaderOverlay() {
- if (!shaderState) return;
- if (shaderState.rafId) cancelAnimationFrame(shaderState.rafId);
- if (shaderState.canvas) shaderState.canvas.remove();
- const lose = shaderState.gl?.getExtension?.('WEBGL_lose_context');
- try { lose?.loseContext(); } catch {}
- shaderState = null;
- }
-
- async function showShaderOverlay(el, blob, rect) {
- hideShaderOverlay();
- if (!blob || !el) return;
- const canvas = document.createElement('canvas');
- canvas.id = PREFIX + '-shader';
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
- canvas.width = Math.max(1, Math.floor(rect.width * dpr));
- canvas.height = Math.max(1, Math.floor(rect.height * dpr));
- Object.assign(canvas.style, {
- position: 'fixed',
- top: rect.top + 'px', left: rect.left + 'px',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none',
- zIndex: Z.bar - 1,
- });
- document.body.appendChild(canvas);
-
- const gl = canvas.getContext('webgl', { premultipliedAlpha: false, preserveDrawingBuffer: false })
- || canvas.getContext('experimental-webgl');
- if (!gl) {
- // WebGL unavailable — fall back to a plain <img> overlay so the user
- // still sees something meaningful during generation.
- canvas.remove();
- const img = document.createElement('img');
- img.src = URL.createObjectURL(blob);
- img.id = PREFIX + '-shader';
- // Copy positioning via cssText. Object.assign across CSSStyleDeclaration
- // throws in modern Chromium because the source's indexed properties
- // (style[0], [1], ...) are read-only and the engine forbids writing
- // them on the destination.
- img.style.cssText = canvas.style.cssText;
- img.style.outline = '2px dashed ' + C.brand;
- img.style.outlineOffset = '-2px';
- document.body.appendChild(img);
- shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
- return;
- }
-
- let program, texture;
- try {
- const vs = compileShader(gl, gl.VERTEX_SHADER, SHADER_VS);
- const fs = compileShader(gl, gl.FRAGMENT_SHADER, SHADER_FS);
- program = gl.createProgram();
- gl.attachShader(program, vs);
- gl.attachShader(program, fs);
- gl.linkProgram(program);
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- throw new Error('program link failed: ' + gl.getProgramInfoLog(program));
- }
- // Full-screen quad
- const buf = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
- -1, -1, 0, 1,
- 1, -1, 1, 1,
- -1, 1, 0, 0,
- -1, 1, 0, 0,
- 1, -1, 1, 1,
- 1, 1, 1, 0,
- ]), gl.STATIC_DRAW);
- const posLoc = gl.getAttribLocation(program, 'a_position');
- const uvLoc = gl.getAttribLocation(program, 'a_uv');
- gl.enableVertexAttribArray(posLoc);
- gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 16, 0);
- gl.enableVertexAttribArray(uvLoc);
- gl.vertexAttribPointer(uvLoc, 2, gl.FLOAT, false, 16, 8);
- } catch (err) {
- console.warn('[impeccable] shader setup failed:', err);
- canvas.remove();
- return;
- }
-
- // Upload the screenshot as a texture
- let bitmap;
- try {
- bitmap = await createImageBitmap(blob);
- } catch {
- // Safari fallback: go via a regular Image
- const imgUrl = URL.createObjectURL(blob);
- const img = new Image();
- img.src = imgUrl;
- await new Promise((r, rej) => { img.onload = r; img.onerror = rej; });
- bitmap = img;
- URL.revokeObjectURL(imgUrl);
- }
- texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
- if (bitmap.close) bitmap.close();
-
- const uTime = gl.getUniformLocation(program, 'u_time');
- const uRes = gl.getUniformLocation(program, 'u_resolution');
- const uAccent = gl.getUniformLocation(program, 'u_accent');
- const uTex = gl.getUniformLocation(program, 'u_texture');
- const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-
- shaderState = { canvas, gl, program, texture, rafId: 0, startTime: performance.now(), reduced };
- function frame() {
- if (!shaderState) return;
- const elapsed = (performance.now() - shaderState.startTime) / 1000;
- const t = shaderState.reduced ? 0.0 : elapsed;
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.useProgram(program);
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.uniform1i(uTex, 0);
- gl.uniform1f(uTime, t);
- gl.uniform2f(uRes, canvas.width, canvas.height);
- gl.uniform3f(uAccent, SHADER_ACCENT[0], SHADER_ACCENT[1], SHADER_ACCENT[2]);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- shaderState.rafId = requestAnimationFrame(frame);
- }
- frame();
- }
-
- function handleAccept() {
- if (!currentSessionId || arrivedVariants === 0) return;
- const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);
- if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;
- const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };
- if (Object.keys(paramsCurrentValues).length > 0) {
- acceptPayload.paramValues = { ...paramsCurrentValues };
- }
- // The accepted variant is already the only visible child of the wrapper
- // (all other variants are display:none). HMR from the source rewrite will
- // replace the wrapper imminently. Don't eagerly replaceChild here — React
- // reconciliation races with our mutation and throws NotFoundError in Next
- // 16 / Turbopack. Schedule a fallback that runs the manual swap only if
- // HMR hasn't cleaned up by then (keeps static-server flows working).
- const acceptedSessionId = currentSessionId;
- const acceptedVariant = visibleVariant;
-
- state = 'SAVING';
- updateBarContent('saving');
-
- sendEvent(acceptPayload, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- confirmAcceptAfterReceipt();
- })
- .catch(() => {
- state = 'CYCLING';
- updateBarContent('cycling');
- showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);
- });
-
- function confirmAcceptAfterReceipt() {
- state = 'CONFIRMED';
- updateBarContent('confirmed');
- scheduleAcceptCleanup();
- }
-
- function scheduleAcceptCleanup() {
- setTimeout(function() {
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }, 1800);
-
- // Static-server / no-HMR fallback: if the wrapper is still around 2s after
- // the cleanup above, swap it out manually. By now React has either moved
- // on or the app isn't React at all. Preserve the `data-impeccable-variant="N"`
- // div (with display:contents) so @scope rules anchored to the variant
- // attribute keep matching until reload replaces it with the carbonize block.
- setTimeout(function() {
- const wrapper = document.querySelector('[data-impeccable-variants="' + acceptedSessionId + '"]');
- if (!wrapper) return;
- const accepted = wrapper.querySelector('[data-impeccable-variant="' + acceptedVariant + '"]');
- if (accepted && accepted.firstElementChild) {
- const parent = wrapper.parentElement;
- if (!parent) return;
- accepted.style.display = 'contents';
- parent.replaceChild(accepted, wrapper);
- }
- }, 2000);
- }
- }
-
- function handleDiscard() {
- if (!currentSessionId) return;
- sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- cleanup();
- })
- .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));
- }
-
- // ---------------------------------------------------------------------------
- // Session persistence via live-browser-session.js
- // ---------------------------------------------------------------------------
- // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
-
- function saveSession() {
- if (!currentSessionId) return;
- // NOTE: scrollY is stored under a separate key (writeScrollY). Storing
- // it here would overwrite the Go-time value every time state changes.
- sessionState.saveSession({
- id: currentSessionId,
- state,
- action: selectedAction,
- count: selectedCount,
- expected: expectedVariants,
- arrived: arrivedVariants,
- visible: visibleVariant,
- });
- }
-
- function loadSession() {
- return sessionState.loadSession();
- }
-
- function clearSession() {
- sessionState.clearSession();
- }
-
- /** Mark session as handled (accepted/discarded). The agent will clean up
- * the source, but until it does the wrapper is still in the HTML. This
- * prevents resumeSession from picking it up again after reload. */
- function markSessionHandled() {
- if (!currentSessionId) return;
- sessionState.markHandled(currentSessionId);
- }
-
- function isSessionHandled(id) {
- return sessionState.isHandled(id);
- }
-
- function clearHandled() {
- sessionState.clearHandled();
- }
-
- function cleanup() {
- // Hide the wrapper immediately so variants disappear. DON'T structurally
- // mutate the DOM yet — HMR from the agent's source rewrite is on its way,
- // and a manual replaceChild under React causes NotFoundError when the
- // reconciler later tries to remove a wrapper we already removed.
- // Schedule a 2s fallback that does the manual swap only if HMR hasn't
- // replaced the wrapper by then (keeps static-server / no-HMR flows alive).
- const cleanupSessionId = currentSessionId;
- if (cleanupSessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (wrapper) wrapper.style.display = 'none';
- }
- setTimeout(function() {
- if (!cleanupSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (!wrapper) return;
- const orig = wrapper.querySelector('[data-impeccable-variant="original"]');
- if (orig) {
- const content = orig.firstElementChild;
- if (content) {
- wrapper.parentElement.replaceChild(content, wrapper);
- return;
- }
- }
- wrapper.remove();
- }, 2000);
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }
-
- // ---------------------------------------------------------------------------
- // Toast
- // ---------------------------------------------------------------------------
-
- function showToast(message, duration) {
- if (toastEl) toastEl.remove();
- // Stack the toast above the global bar (which sits at bottom:14px) so
- // the two never overlap. Read the bar's actual rect — its height varies
- // with hover-expanded labels — and fall back to a sensible default
- // when the bar isn't mounted yet.
- const barRect = globalBarEl?.getBoundingClientRect();
- const barTopFromBottom = barRect && barRect.height > 0
- ? Math.max(16, window.innerHeight - barRect.top + 12)
- : 16;
- toastEl = el('div', {
- position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
- transform: 'translateX(-50%) translateY(8px)',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px',
- padding: '8px 16px', borderRadius: '8px',
- zIndex: Z.toast, opacity: '0',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
- pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
- });
- toastEl.id = PREFIX + '-toast';
- toastEl.textContent = message;
- document.body.appendChild(toastEl);
- requestAnimationFrame(() => {
- toastEl.style.opacity = '1';
- toastEl.style.transform = 'translateX(-50%) translateY(0)';
- });
- setTimeout(() => {
- if (toastEl) {
- toastEl.style.opacity = '0';
- toastEl.style.transform = 'translateX(-50%) translateY(8px)';
- setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
- }
- }, duration);
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- // Resume an active variant session after HMR/page reload.
- // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
- // variants before HMR fired. Pick up where we left off.
- function resumeSession() {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) { clearSession(); clearHandled(); return false; }
-
- const sessionId = wrapper.dataset.impeccableVariants;
-
- // Don't resume if this session was already accepted/discarded
- if (isSessionHandled(sessionId)) return false;
-
- currentSessionId = sessionId;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
-
- // Restore state from localStorage if available
- const saved = loadSession();
- if (saved && saved.id === sessionId) {
- visibleVariant = (saved.visible > 0 && saved.visible <= arrivedVariants) ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
- if (saved.action) selectedAction = saved.action;
- if (saved.count) selectedCount = saved.count;
- } else {
- visibleVariant = arrivedVariants > 0 ? 1 : 0;
- }
-
- // Find the visible variant's content element for highlight positioning.
- // Try the visible variant first, fall back to the original's content.
- const visEl = visibleVariant > 0 ? pickVariantContent(wrapper, visibleVariant) : null;
- const origEl = pickVariantContent(wrapper, 'original');
- selectedElement = visEl || origEl || wrapper.parentElement;
-
- // Set display state BEFORE starting observer (avoid triggering it)
- if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
-
- state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
- showBar(state === 'CYCLING' ? 'cycling' : 'generating');
- startScrollTracking();
- // Build the params panel for the restored visible variant. Previously
- // this was missed on page-reload resume: showVariantInDOM above fires
- // refreshParamsPanel, but state was still IDLE at that moment so it
- // hid. Now that state is CYCLING, re-fire.
- if (state === 'CYCLING') refreshParamsPanel();
- saveSession();
- queueCheckpoint('browser_resumed');
-
- // Start observing for more variants AFTER initial setup
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
-
- // Hold the target at its saved viewport top through any subsequent
- // HMR patches, variant inserts, or cycle swaps.
- startScrollLock(currentSessionId, readScrollY());
-
- // If we reloaded mid-generation (Bun's HTML HMR destroys the shader
- // canvas), re-capture the original's content and restart the shader so
- // the wait doesn't go dead.
- if (state === 'GENERATING' && origEl) {
- (async () => {
- try {
- const rect = origEl.getBoundingClientRect();
- if (rect.width === 0 || rect.height === 0) return;
- const blob = await captureElementToBlob(origEl, null, rect);
- if (blob && state === 'GENERATING') {
- showShaderOverlay(origEl, blob, rect);
- }
- } catch (err) {
- console.warn('[impeccable] shader resume failed:', err);
- }
- })();
- }
- return true;
- }
-
- // ---------------------------------------------------------------------------
- // Global bar (always visible at bottom)
- // ---------------------------------------------------------------------------
-
- let globalBarEl = null;
- let detectActive = false;
- let pickActive = true;
- let detectCount = 0;
- let detectScriptLoaded = false;
-
- // Theme-aware color palette for the global bar. We detect the page's
- // ambient background and invert — dark bar on light pages, light bar on
- // dark pages. This keeps the bar from fighting with the host design.
- function detectPageTheme() {
- try {
- // Dev override: set localStorage 'impeccable-dev-theme' to 'light' or
- // 'dark' to preview the opposite palette without actually changing the
- // page bg. Used for screenshots and theme QA.
- const override = localStorage.getItem('impeccable-dev-theme');
- if (override === 'light' || override === 'dark') return override;
-
- // Walk body → html, taking the first opaque background. The browser's
- // default body / html background is `rgba(0, 0, 0, 0)`, which a naive
- // regex would read as black and mislabel a perfectly white page as
- // dark. Honoring alpha avoids that — and falling through to <html>
- // catches the common pattern of a bg only on <html> (or only on body).
- function readOpaque(el) {
- if (!el) return null;
- const bg = getComputedStyle(el).backgroundColor;
- const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
- if (!m) return null;
- const alpha = m[4] == null ? 1 : parseFloat(m[4]);
- if (alpha < 0.5) return null; // transparent / nearly transparent → skip
- return [+m[1], +m[2], +m[3]];
- }
-
- const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
- // Both transparent → fall back to the browser's effective canvas color.
- // White is the universal default; only one in a thousand sites swaps it
- // via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
- // us catch that case.
- if (!rgb) {
- return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
- }
- const [r, g, b] = rgb;
- // Perceptual luminance (Rec. 709)
- const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
- return L > 0.55 ? 'light' : 'dark';
- } catch { return 'light'; }
- }
-
- function barPaletteForTheme(theme) {
- if (theme === 'dark') {
- // Light bar on dark page
- return {
- surface: 'oklch(98% 0 0 / 0.92)',
- surfaceDeep: 'oklch(92% 0.005 60 / 0.96)', // slightly deeper, faint warm
- hairline: 'oklch(70% 0 0 / 0.35)',
- text: 'oklch(15% 0 0)',
- textDim: 'oklch(45% 0 0)',
- accent: 'oklch(60% 0.25 350)',
- accentSoft: 'oklch(60% 0.25 350 / 0.18)',
- mark: 'oklch(98% 0 0)', // logo mark fill
- markText: 'oklch(15% 0 0)', // logo "/" color
- exitHover: 'oklch(85% 0 0 / 0.5)',
- };
- }
- // Dark bar on light page. Bar is a warm charcoal, logo slab is much
- // deeper so the rounded-right shape reads as a clear sculpted mark.
- return {
- surface: 'oklch(26% 0 0 / 0.94)',
- surfaceDeep: 'oklch(18% 0 0 / 0.96)', // darker sand for Tune popover
- hairline: 'oklch(42% 0 0 / 0.5)',
- text: 'oklch(96% 0 0)',
- textDim: 'oklch(72% 0 0)',
- accent: 'oklch(72% 0.22 350)',
- accentSoft: 'oklch(72% 0.22 350 / 0.22)',
- mark: 'oklch(8% 0 0)',
- markText: 'oklch(96% 0 0)',
- exitHover: 'oklch(36% 0 0 / 0.6)',
- };
- }
-
- // Impeccable logo mark — matches the site-header SVG (rounded square + "/").
- function brandMarkSvg(fill, ink, size = 18) {
- return `<svg width="${size}" height="${size}" viewBox="0 0 32 32" aria-hidden="true">
- <rect width="32" height="32" rx="7" fill="${fill}"/>
- <text x="16" y="24" font-family="system-ui, -apple-system, sans-serif" font-size="22" font-weight="500" fill="${ink}" text-anchor="middle">/</text>
- </svg>`;
- }
-
- function initGlobalBar() {
- const theme = detectPageTheme();
- const P = barPaletteForTheme(theme);
-
- // Custom focus-visible for bar buttons. Browser default is a heavy
- // blue ring that looks jarring on the dark capsule. Replace with a
- // soft accent-tinted inner ring that respects the bar's palette.
- if (!document.getElementById(PREFIX + '-bar-focus-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-bar-focus-style';
- s.textContent =
- '#' + PREFIX + '-global-bar button:focus { outline: none; }' +
- '#' + PREFIX + '-global-bar button:focus-visible {' +
- ' outline: none;' +
- ' box-shadow: 0 0 0 2px ' + P.accentSoft + ', 0 0 0 3px ' + P.accent + ';' +
- '}';
- document.head.appendChild(s);
- }
-
- globalBarEl = el('div', {
- position: 'fixed', bottom: '14px', left: '50%',
- transform: 'translateX(-50%) translateY(20px)',
- zIndex: Z.bar + 5,
- display: 'flex', alignItems: 'stretch',
- gap: '2px',
- background: P.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 4px 20px oklch(0% 0 0 / 0.12), 0 1px 3px oklch(0% 0 0 / 0.08)',
- fontFamily: FONT, fontSize: '12px', lineHeight: '1',
- opacity: '0',
- overflow: 'hidden', // clip the full-bleed brand mark to the bar radius
- transition: 'opacity 0.3s ' + EASE + ', transform 0.3s ' + EASE,
- });
- globalBarEl.id = PREFIX + '-global-bar';
- globalBarEl.dataset.theme = theme;
-
- // Brand mark — fills bar height on the left. Left side inherits the bar's
- // rounded corner via overflow:hidden; right side is a clean hard edge since
- // the near-black/charcoal contrast does the shape-defining work.
- const brand = el('span', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- alignSelf: 'stretch',
- padding: '0 12px 0 14px',
- background: P.mark,
- color: P.markText,
- fontFamily: 'system-ui, -apple-system, sans-serif',
- fontWeight: '500',
- fontSize: '18px', lineHeight: '1',
- });
- brand.textContent = '/';
- brand.title = 'Impeccable';
- globalBarEl.appendChild(brand);
-
- // Inner wrapper: holds the toggles with normal bar padding.
- const inner = el('div', {
- display: 'flex', alignItems: 'center',
- padding: '4px 5px', gap: '2px',
- });
- inner.id = PREFIX + '-global-bar-inner';
- globalBarEl.appendChild(inner);
-
- // --- button factory: icon-only at rest, label slides in on hover/active ---
- function makeIconBtn({ id, svg, label, ariaLabel, labelFont, onClick }) {
- const b = el('button', {
- position: 'relative',
- display: 'inline-flex', alignItems: 'center',
- padding: '6px 8px', borderRadius: '7px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '11.5px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.15s ease, color 0.15s ease',
- whiteSpace: 'nowrap', overflow: 'hidden',
- });
- b.id = id;
- b.title = ariaLabel || label || '';
- b.setAttribute('aria-label', ariaLabel || label || '');
- b.innerHTML = svg + (label
- ? `<span class="icon-btn-label" style="display:inline-block;max-width:0;opacity:0;margin-left:0;overflow:hidden;font-family:${labelFont || FONT};transition:max-width 0.25s ${EASE}, opacity 0.2s ease, margin-left 0.25s ${EASE};">${label}</span>`
- : '');
- const labelEl = b.querySelector('.icon-btn-label');
- const expand = () => {
- if (!labelEl) return;
- labelEl.style.maxWidth = '120px'; labelEl.style.opacity = '1'; labelEl.style.marginLeft = '6px';
- };
- const collapse = () => {
- if (!labelEl || b.dataset.active === 'true') return;
- labelEl.style.maxWidth = '0'; labelEl.style.opacity = '0'; labelEl.style.marginLeft = '0';
- };
- // Per-button hover only changes color (no layout). The label expand/
- // collapse is driven by the bar-level mouseenter/mouseleave so moving
- // the mouse between adjacent buttons doesn't trigger per-button width
- // thrashing — the whole bar grows once and shrinks once.
- b.addEventListener('mouseenter', () => { if (b.dataset.active !== 'true') b.style.color = P.text; });
- b.addEventListener('mouseleave', () => { if (b.dataset.active !== 'true') b.style.color = P.textDim; });
- b.addEventListener('click', onClick);
- b._expandLabel = expand;
- b._collapseLabel = collapse;
- return b;
- }
-
- // Pick toggle — starts active (primary intent when entering live mode).
- const pickBtn = makeIconBtn({
- id: PREFIX + '-pick-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',
- label: 'Pick',
- ariaLabel: 'Pick element',
- onClick: () => togglePick(),
- });
- pickBtn.style.background = P.accentSoft;
- pickBtn.style.color = P.accent;
- pickBtn.dataset.active = 'true';
- pickBtn._expandLabel();
- inner.appendChild(pickBtn);
-
- // Detect toggle
- const detectBtn = makeIconBtn({
- id: PREFIX + '-detect-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',
- label: 'Detect',
- ariaLabel: 'Detect anti-patterns',
- onClick: () => toggleDetect(),
- });
- const detectBadge = el('span', {
- fontSize: '10px', fontWeight: '600',
- padding: '0px 5px', borderRadius: '7px', lineHeight: '16px',
- background: P.accent, color: P.surface.includes('18%') ? 'oklch(18% 0 0)' : 'oklch(98% 0 0)',
- display: 'none', fontFamily: MONO, marginLeft: '4px',
- });
- detectBadge.id = PREFIX + '-detect-badge';
- detectBtn.appendChild(detectBadge);
- inner.appendChild(detectBtn);
-
- // DESIGN.md panel toggle — quartet of color squares as the mark.
- const designBtn = makeIconBtn({
- id: PREFIX + '-design-toggle',
- svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px ${P.hairline};flex-shrink:0">
- <span style="background:oklch(60% 0.25 350)"></span>
- <span style="background:oklch(60% 0.15 45)"></span>
- <span style="background:oklch(55% 0.12 250)"></span>
- <span style="background:oklch(30% 0 0)"></span>
- </span>`,
- label: 'DESIGN.md',
- ariaLabel: 'Toggle DESIGN.md panel',
- labelFont: MONO,
- onClick: () => toggleDesignPanel(),
- });
- inner.appendChild(designBtn);
-
- // Thin divider before the exit button
- const divider = el('span', {
- width: '1px', height: '18px',
- background: P.hairline,
- margin: '0 4px 0 2px',
- });
- inner.appendChild(divider);
-
- // Exit × on the right — intentionally subtle (textDim at rest, text on
- // hover) so it sits behind the active toggles in visual hierarchy.
- //
- // Explicit padding + box-sizing here is load-bearing: a host page like
- // `button { padding: 0.5rem 1rem; }` (very common in resets) would
- // otherwise inflate this 24x24 button into 56x40 and push the SVG out
- // of the visible bar — the X stays invisible even though the styles in
- // DevTools look fine. Every other chrome button sets padding inline;
- // this one needed it too.
- const exitBtn = el('button', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- padding: '0', boxSizing: 'border-box',
- width: '24px', height: '24px', borderRadius: '6px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
- cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
- });
- exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
- exitBtn.title = 'Exit live mode';
- exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
- exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
- exitBtn.addEventListener('click', () => { sendEvent({ type: 'exit' }); teardown(); });
- inner.appendChild(exitBtn);
-
- // Bar-level hover: expand every toggle's label at once; collapse on leave.
- // Buttons with dataset.active="true" ignore collapse (their label stays).
- const toggles = [pickBtn, detectBtn, designBtn];
- globalBarEl.addEventListener('mouseenter', () => {
- toggles.forEach((t) => t._expandLabel && t._expandLabel());
- });
- globalBarEl.addEventListener('mouseleave', () => {
- toggles.forEach((t) => t._collapseLabel && t._collapseLabel());
- });
-
- document.body.appendChild(globalBarEl);
- defangOutsideHandlers(globalBarEl);
-
- requestAnimationFrame(() => {
- globalBarEl.style.opacity = '1';
- globalBarEl.style.transform = 'translateX(-50%) translateY(0)';
- });
-
- // Listen for detection results AND ready signal
- window.addEventListener('message', onDetectMessage);
- }
-
- function updateGlobalBarState() {
- const detectToggle = document.getElementById(PREFIX + '-detect-toggle');
- const detectBadge = document.getElementById(PREFIX + '-detect-badge');
- const pickToggle = document.getElementById(PREFIX + '-pick-toggle');
- const designToggle = document.getElementById(PREFIX + '-design-toggle');
- const theme = globalBarEl?.dataset.theme || 'light';
- const P = barPaletteForTheme(theme);
-
- // Sync one toggle's active state, colors, and slide-label visibility.
- function sync(btn, active) {
- if (!btn) return;
- btn.style.background = active ? P.accentSoft : 'transparent';
- btn.style.color = active ? P.accent : P.textDim;
- btn.dataset.active = active ? 'true' : 'false';
- if (active && btn._expandLabel) btn._expandLabel();
- else if (!active && btn._collapseLabel) btn._collapseLabel();
- }
- sync(pickToggle, pickActive);
- sync(detectToggle, detectActive);
- sync(designToggle, designState.open);
-
- // If the bar is currently under the cursor, keep all labels expanded —
- // otherwise clicking a toggle that deactivates (e.g. closing DESIGN.md)
- // would collapse its label while the user's mouse is still on the bar.
- if (globalBarEl && globalBarEl.matches(':hover')) {
- [pickToggle, detectToggle, designToggle].forEach((t) => t?._expandLabel?.());
- }
-
- if (detectBadge) {
- detectBadge.style.display = (detectActive && detectCount > 0) ? 'inline' : 'none';
- detectBadge.textContent = detectCount;
- }
-
- // When pick is active, make detect overlays click-through so the picker works
- document.querySelectorAll('.impeccable-overlay').forEach(o => {
- o.style.pointerEvents = pickActive ? 'none' : '';
- });
- }
-
- let detectReady = false; // true once detect script posts 'impeccable-ready'
- let detectPendingScan = false; // scan requested before script was ready
-
- function toggleDetect() {
- detectActive = !detectActive;
- updateGlobalBarState();
-
- if (detectActive) {
- if (!detectScriptLoaded) {
- detectPendingScan = true;
- loadDetectScript();
- } else if (detectReady) {
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- } else {
- detectPendingScan = true;
- }
- } else {
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- detectCount = 0;
- updateGlobalBarState();
- }
- }
-
- function togglePick() {
- pickActive = !pickActive;
- updateGlobalBarState();
-
- if (!pickActive) {
- // Disabling pick clears any in-flight selection and UI: highlight,
- // contextual bar, selectedElement. Otherwise a stale selection sits
- // on screen with no obvious way to dismiss.
- hideHighlight();
- hideBar();
- hideActionPicker();
- selectedElement = null;
- if (state === 'PICKING' || state === 'CONFIGURING') state = 'IDLE';
- } else {
- if (state === 'IDLE') state = 'PICKING';
- }
- }
-
- function loadDetectScript() {
- if (detectScriptLoaded) return;
- detectScriptLoaded = true;
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/detect.js';
- s.dataset.impeccableExtension = 'true';
- document.head.appendChild(s);
- }
-
- function onDetectMessage(e) {
- if (!e.data || typeof e.data.source !== 'string') return;
- // Detection script is loaded and ready
- if (e.data.source === 'impeccable-ready') {
- detectReady = true;
- if (detectPendingScan && detectActive) {
- detectPendingScan = false;
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- }
- }
- // Scan results arrived
- if (e.data.source === 'impeccable-results') {
- detectCount = e.data.count || 0;
- updateGlobalBarState();
- }
- }
-
- /** Full teardown: remove all UI, disconnect SSE, clean up. */
- function teardown() {
- cleanup();
- hideBar();
- if (globalBarEl) {
- globalBarEl.style.transform = 'translateY(100%)';
- setTimeout(() => { if (globalBarEl) globalBarEl.remove(); globalBarEl = null; }, 300);
- }
- if (highlightEl) { highlightEl.remove(); highlightEl = null; }
- if (tooltipEl) { tooltipEl.remove(); tooltipEl = null; }
- if (barEl) { barEl.remove(); barEl = null; }
- if (pickerEl) { pickerEl.remove(); pickerEl = null; }
- if (paramsPanelEl) { paramsPanelEl.remove(); paramsPanelEl = null; paramsPanelInner = null; paramsPanelBody = null; }
- if (evtSource) { evtSource.close(); evtSource = null; }
- document.removeEventListener('mousemove', handleMouseMove, true);
- document.removeEventListener('click', handleClick, true);
- document.removeEventListener('keydown', handleKeyDown, true);
- window.removeEventListener('message', onDetectMessage);
- // Remove detection overlays
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- state = 'IDLE';
- window.__IMPECCABLE_LIVE_INIT__ = false;
- console.log('[impeccable] Live mode exited.');
- }
-
- // ---------------------------------------------------------------------------
- // Design System Panel — visualizes the project's .impeccable/design.json sidecar
- // ---------------------------------------------------------------------------
-
- const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';
- const DESIGN_PANEL_WIDTH = 440;
-
- let designHost = null;
- let designShadow = null;
- let designState = {
- open: false,
- tab: 'visual', // 'visual' | 'raw'
- parsed: null, // parseDesignMd output (frontmatter + body sections)
- sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)
- hasMd: false,
- hasSidecar: false,
- present: null, // true/false once fetch resolves
- raw: null, // raw DESIGN.md for the raw tab
- mdNewerThanJson: false, // stale-hint flag
- loading: false,
- error: null,
- collapsed: { // narrative-section accordion state
- rules: true, dosdonts: true, overview: true,
- },
- };
-
- function loadDesignPrefs() {
- // `open` is intentionally NOT persisted — the panel always starts closed
- // so live mode doesn't auto-slide a big panel over the page on startup.
- try {
- const raw = localStorage.getItem(DESIGN_PREFS_KEY);
- if (!raw) return;
- const prefs = JSON.parse(raw);
- if (prefs.tab === 'visual' || prefs.tab === 'raw') designState.tab = prefs.tab;
- if (prefs.collapsed && typeof prefs.collapsed === 'object') {
- Object.assign(designState.collapsed, prefs.collapsed);
- }
- } catch { /* ignore */ }
- }
-
- function saveDesignPrefs() {
- try {
- localStorage.setItem(DESIGN_PREFS_KEY, JSON.stringify({
- tab: designState.tab,
- collapsed: designState.collapsed,
- }));
- } catch { /* ignore */ }
- }
-
- function initDesignPanel() {
- designHost = document.createElement('div');
- designHost.id = PREFIX + '-design-host';
- Object.assign(designHost.style, {
- position: 'fixed', top: '0', left: '0',
- width: '0', height: '0',
- zIndex: String(Z.bar + 10),
- pointerEvents: 'none',
- });
- designShadow = designHost.attachShadow({ mode: 'open' });
-
- const style = document.createElement('style');
- // Theme-match the bar: dark chrome on light pages, light chrome on dark pages.
- const theme = detectPageTheme();
- style.textContent = designPanelCss(barPaletteForTheme(theme));
- designShadow.appendChild(style);
-
- const root = document.createElement('div');
- root.className = 'root';
- designShadow.appendChild(root);
-
- document.body.appendChild(designHost);
- // The host is pointer-events: none; the panel inside the shadow DOM
- // manages its own auto/none. Events bubble through the shadow boundary,
- // so attaching here silences host-page outside-interaction handlers
- // without touching the host's click-through behavior.
- defangOutsideHandlers(designHost, { setPointerEvents: false });
-
- loadDesignPrefs();
- renderDesignChrome();
- if (designState.open) {
- fetchDesignSystem();
- }
- }
-
- // Neutral panel palette — deliberately NOT Impeccable-branded. The panel is
- // a viewer of the project's design system, not an Impeccable surface.
- const DP = {
- canvas: 'oklch(94% 0 0)', // panel background
- tile: 'oklch(98.5% 0 0)', // card-on-canvas
- tileAlt: 'oklch(96% 0 0)', // subtler tile for inner surfaces
- ink: 'oklch(15% 0 0)',
- ink2: 'oklch(35% 0 0)',
- meta: 'oklch(55% 0 0)',
- hairline: 'oklch(88% 0 0)',
- hairlineSoft: 'oklch(92% 0 0)',
- amber: 'oklch(70% 0.13 65)', // stale-hint accent
- amberBg: 'oklch(95% 0.05 80)',
- };
-
- function designPanelCss(BP) {
- // BP = bar palette (theme-aware, matches the global bar).
- // DP = internal content palette (neutral, so tiles render colors true).
- return `
- :host, .root { all: initial; }
- .root {
- font-family: ${FONT};
- color: ${DP.ink};
- pointer-events: none;
- }
- .root * { box-sizing: border-box; }
- button { font: inherit; color: inherit; }
-
- /* --- Panel shell: chrome matches the bar; body canvas stays neutral --- */
- .panel {
- position: fixed; top: 12px; bottom: 72px; right: 12px;
- width: ${DESIGN_PANEL_WIDTH}px; max-width: calc(100vw - 24px);
- background: ${BP.surface};
- border: 1px solid ${BP.hairline};
- border-radius: 14px;
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- box-shadow: 0 20px 60px oklch(0% 0 0 / 0.18), 0 4px 12px oklch(0% 0 0 / 0.08);
- display: flex; flex-direction: column;
- transform: translateX(calc(100% + 24px));
- opacity: 0;
- transition: transform 0.35s ${EASE}, opacity 0.25s ${EASE};
- pointer-events: none;
- overflow: hidden;
- }
- .panel[data-open="true"] { transform: translateX(0); opacity: 1; pointer-events: auto; }
-
- .panel-header {
- display: flex; align-items: center; gap: 10px;
- padding: 10px 10px 10px 14px;
- background: transparent;
- border-bottom: 1px solid ${BP.hairline};
- }
- .panel-title {
- flex: 1; min-width: 0;
- font-family: ${MONO};
- font-size: 11.5px; font-weight: 600;
- letter-spacing: 0.02em;
- color: ${BP.text};
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
- }
- .panel-close {
- border: none; background: transparent; color: ${BP.textDim};
- width: 26px; height: 26px; border-radius: 7px;
- display: inline-flex; align-items: center; justify-content: center;
- cursor: pointer; transition: background 0.15s ease, color 0.15s ease;
- }
- .panel-close:hover { background: ${BP.hairline}; color: ${BP.text}; }
-
- .tabs {
- display: inline-flex; padding: 2px;
- background: ${BP.hairline};
- border-radius: 7px;
- gap: 2px;
- }
- .tab {
- border: none; background: transparent;
- padding: 4px 10px; border-radius: 5px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 600; letter-spacing: 0.08em;
- text-transform: uppercase;
- color: ${BP.textDim}; cursor: pointer;
- transition: background 0.15s ease, color 0.15s ease;
- }
- .tab[data-active="true"] { background: ${BP.surface}; color: ${BP.text}; }
-
- .panel-body {
- flex: 1; overflow-y: auto;
- padding: 12px 12px 20px;
- background: ${DP.canvas};
- scrollbar-width: thin;
- scrollbar-color: ${DP.hairline} transparent;
- }
- .panel-body::-webkit-scrollbar { width: 8px; }
- .panel-body::-webkit-scrollbar-thumb { background: ${DP.hairline}; border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
-
- /* --- States --- */
- .empty, .loading, .error {
- margin: 16px 4px;
- padding: 28px 20px; text-align: center;
- background: ${DP.tile}; border-radius: 14px;
- color: ${DP.ink2}; font-size: 13px; line-height: 1.55;
- }
- .empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
- .empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
- .error { color: oklch(45% 0.15 25); }
-
- /* --- Stale hint --- */
- .stale {
- display: flex; align-items: center; gap: 8px;
- margin: 8px 4px 12px;
- padding: 8px 12px;
- background: ${DP.amberBg};
- border-radius: 10px;
- font-size: 11.5px; color: ${DP.ink2};
- }
- .stale-dot { width: 8px; height: 8px; border-radius: 50%; background: ${DP.amber}; flex-shrink: 0; }
- .stale-text { flex: 1; min-width: 0; }
- .stale-text strong { color: ${DP.ink}; font-weight: 600; }
-
- /* --- Parsed-md fallback banner --- */
- .parsed-md-cta {
- margin: 8px 4px 14px;
- padding: 14px 16px;
- background: ${DP.tile};
- border: 1px dashed ${DP.hairline};
- border-radius: 12px;
- font-size: 12px; color: ${DP.ink2}; line-height: 1.55;
- }
- .parsed-md-cta strong { color: ${DP.ink}; display: block; margin-bottom: 4px; font-size: 13px; font-weight: 600; }
- .parsed-md-cta code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; font-size: 11.5px; color: ${DP.ink}; }
-
- /* --- Tile primitives --- */
- .tile {
- position: relative;
- background: ${DP.tile};
- border-radius: 16px;
- padding: 16px;
- margin: 0 4px 10px;
- }
- .tile-row { margin: 0 4px 10px; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
- .tile-row .tile { margin: 0; }
- .tile-meta {
- display: flex; align-items: baseline; justify-content: space-between;
- gap: 10px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase;
- color: ${DP.meta};
- }
- .tile-meta .name { color: ${DP.ink}; font-weight: 600; letter-spacing: 0.05em; text-transform: none; font-family: ${FONT}; font-size: 12.5px; }
-
- /* --- Color tile --- */
- .c-tile { cursor: pointer; transition: transform 0.2s ${EASE}; }
- .c-tile:hover { transform: translateY(-1px); }
- .c-hero {
- height: 72px; border-radius: 10px; margin-top: 10px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.05);
- }
- .c-ramp {
- display: flex; gap: 0; height: 14px; border-radius: 4px; overflow: hidden;
- margin-top: 8px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.04);
- }
- .c-ramp > span { flex: 1; }
- .c-desc { margin-top: 8px; font-size: 11.5px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Type tile --- */
- .t-tile { }
- .t-specimen {
- margin: 4px 0 6px;
- color: ${DP.ink};
- line-height: 0.9;
- }
- .t-family { margin-top: 4px; font-size: 12px; font-weight: 600; color: ${DP.ink}; }
- .t-purpose { margin-top: 4px; font-size: 11px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Shadow tile --- */
- .s-tile { }
- .s-surface {
- height: 60px; margin: 8px 2px 10px;
- background: ${DP.tile};
- border-radius: 10px;
- }
- .s-value { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; word-break: break-all; line-height: 1.4; }
- .s-purpose { margin-top: 4px; font-size: 11px; color: ${DP.ink2}; line-height: 1.45; }
-
- /* --- Radii strip --- */
- .r-strip { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
- .r-item { display: flex; flex-direction: column; align-items: center; gap: 4px; flex: 1; min-width: 60px; }
- .r-sample { width: 44px; height: 44px; background: ${DP.canvas}; box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.08); }
- .r-label { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; text-transform: uppercase; }
- .r-val { font-family: ${MONO}; font-size: 10px; color: ${DP.ink}; }
-
- /* --- Component tile (hosts live primitives) --- */
- .cmp-tile { }
- .cmp-stage {
- margin: 12px -4px 0;
- padding: 18px 16px 10px;
- border-top: 1px solid ${DP.hairlineSoft};
- display: flex; flex-direction: column; align-items: center; justify-content: center;
- gap: 14px;
- min-height: 68px;
- }
- .cmp-stage + .cmp-stage { border-top: 1px dashed ${DP.hairlineSoft}; }
- .cmp-sublabel { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.06em; }
- .cmp-kind { font-family: ${MONO}; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; }
-
- /* --- Collapsible --- */
- .coll {
- margin: 0 4px 8px;
- background: ${DP.tile};
- border-radius: 12px;
- overflow: hidden;
- }
- .coll-head {
- display: flex; align-items: center; gap: 10px;
- width: 100%;
- padding: 12px 14px;
- background: transparent; border: none;
- cursor: pointer; text-align: left;
- font-family: ${FONT}; font-size: 12.5px; font-weight: 600; color: ${DP.ink};
- transition: background 0.12s ease;
- }
- .coll-head:hover { background: ${DP.tileAlt}; }
- .coll-chev {
- width: 12px; height: 12px; flex-shrink: 0;
- color: ${DP.meta};
- transition: transform 0.2s ${EASE};
- }
- .coll[data-open="true"] .coll-chev { transform: rotate(90deg); }
- .coll-count { margin-left: auto; font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; }
- .coll-body { padding: 0 14px 14px; display: none; }
- .coll[data-open="true"] .coll-body { display: block; }
-
- .rule-card {
- padding: 10px 0;
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .rule-card:first-child { border-top: none; padding-top: 2px; }
- .rule-card .name { font-size: 11.5px; font-weight: 700; color: ${DP.ink}; margin-bottom: 3px; }
- .rule-card .name .section { font-family: ${MONO}; font-size: 9px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; margin-left: 8px; }
- .rule-card .body { font-size: 11.5px; color: ${DP.ink2}; line-height: 1.5; }
-
- .coll .dos { display: grid; gap: 0; margin-top: 2px; }
- .coll .do, .coll .dont {
- position: relative;
- padding: 8px 0 8px 22px;
- font-size: 11.5px; line-height: 1.5; color: ${DP.ink2};
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .coll .do:first-child, .coll .dont:first-child,
- .coll .do:first-of-type { border-top: none; }
- .coll .do + .dont { border-top: 1px solid ${DP.hairlineSoft}; }
- .coll .do::before, .coll .dont::before {
- content: ''; position: absolute; left: 4px; top: 13px;
- width: 8px; height: 8px; border-radius: 50%;
- }
- .coll .do::before { background: oklch(62% 0.16 145); }
- .coll .dont::before { background: oklch(58% 0.22 25); }
-
- .coll .overview-body {
- font-size: 12px; line-height: 1.55; color: ${DP.ink2};
- }
- .coll .overview-body .north-star {
- display: block; font-family: ${FONT}; font-style: italic;
- font-size: 15px; line-height: 1.3; color: ${DP.ink};
- margin-bottom: 8px;
- }
- .coll .overview-body p { margin: 0 0 8px; }
- .coll .overview-body ul { margin: 6px 0 0; padding-left: 16px; font-size: 11.5px; }
- .coll .overview-body li { margin-bottom: 3px; }
-
- /* --- raw tab markdown (unchanged layout, neutralized palette) --- */
- .md { padding: 4px 10px 20px; font-size: 13px; line-height: 1.6; color: ${DP.ink}; }
- .md h1, .md h2, .md h3, .md h4 { margin: 20px 0 8px; color: ${DP.ink}; font-weight: 600; }
- .md h1 { font-size: 18px; }
- .md h2 { font-size: 15px; padding-bottom: 4px; border-bottom: 1px solid ${DP.hairlineSoft}; }
- .md h3 { font-size: 13px; }
- .md h4 { font-size: 12px; color: ${DP.meta}; }
- .md p { margin: 0 0 10px; }
- .md ul, .md ol { margin: 0 0 10px; padding-left: 20px; }
- .md li { margin-bottom: 4px; }
- .md code { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; }
- .md pre { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 10px 12px; border-radius: 8px; overflow-x: auto; margin: 0 0 10px; }
- .md pre code { background: none; padding: 0; }
- .md strong { font-weight: 700; }
- .md em { font-style: italic; }
- .md a { color: ${DP.ink}; text-decoration: underline; }
- .md hr { border: none; border-top: 1px solid ${DP.hairlineSoft}; margin: 16px 0; }
- `;
- }
-
- function renderDesignChrome() {
- const root = designShadow.querySelector('.root');
- root.innerHTML = '';
-
- // (Panel toggle lives in the global bar — no floating FAB.)
- // Panel
- const panel = document.createElement('aside');
- panel.className = 'panel';
- panel.setAttribute('data-open', designState.open ? 'true' : 'false');
- panel.appendChild(buildDesignHeader());
- const body = document.createElement('div');
- body.className = 'panel-body';
- body.id = 'panel-body';
- panel.appendChild(body);
- root.appendChild(panel);
-
- renderDesignBody();
- }
-
- function buildDesignHeader() {
- const header = document.createElement('div');
- header.className = 'panel-header';
-
- const title = document.createElement('div');
- title.className = 'panel-title';
- title.textContent = 'DESIGN.md';
- header.appendChild(title);
-
- const tabs = document.createElement('div');
- tabs.className = 'tabs';
- for (const t of [['visual', 'Visual'], ['raw', 'Raw']]) {
- const btn = document.createElement('button');
- btn.className = 'tab';
- btn.textContent = t[1];
- btn.setAttribute('data-active', designState.tab === t[0] ? 'true' : 'false');
- btn.addEventListener('click', () => {
- if (designState.tab === t[0]) return;
- designState.tab = t[0];
- saveDesignPrefs();
- renderDesignChrome();
- if (t[0] === 'raw' && designState.raw === null && !designState.loading) {
- fetchDesignSystem(); // raw is part of the same fetch pair
- }
- });
- tabs.appendChild(btn);
- }
- header.appendChild(tabs);
-
- const close = document.createElement('button');
- close.className = 'panel-close';
- close.innerHTML = '✕';
- close.setAttribute('aria-label', 'Close panel');
- close.addEventListener('click', toggleDesignPanel);
- header.appendChild(close);
-
- return header;
- }
-
- function toggleDesignPanel() {
- designState.open = !designState.open;
- renderDesignChrome();
- updateGlobalBarState();
- if (designState.open && designState.present === null && !designState.loading) {
- fetchDesignSystem();
- }
- }
-
- async function fetchDesignSystem() {
- designState.loading = true;
- designState.error = null;
- renderDesignBody();
- try {
- const [jsonRes, rawRes] = await Promise.all([
- fetch(`http://localhost:${PORT}/design-system.json?token=${TOKEN}`, { cache: 'no-store' }),
- fetch(`http://localhost:${PORT}/design-system/raw?token=${TOKEN}`, { cache: 'no-store' }),
- ]);
- const jsonData = await jsonRes.json();
- designState.present = jsonData.present === true;
- designState.parsed = jsonData.parsed || null;
- designState.sidecar = jsonData.sidecar || null;
- designState.hasMd = !!jsonData.hasMd;
- designState.hasSidecar = !!jsonData.hasSidecar;
- designState.mdNewerThanJson = !!jsonData.mdNewerThanJson;
- designState.raw = designState.present && rawRes.ok ? await rawRes.text() : null;
- designState.error = jsonData.parseError || jsonData.sidecarError || null;
- } catch (err) {
- designState.error = err?.message || 'Failed to load design system.';
- } finally {
- designState.loading = false;
- renderDesignChrome(); // refresh title from data
- }
- }
-
- function renderDesignBody() {
- const body = designShadow.querySelector('#panel-body');
- if (!body) return;
- body.innerHTML = '';
-
- if (designState.loading) {
- body.appendChild(msgDiv('loading', 'Loading design system…'));
- return;
- }
- if (designState.error) {
- body.appendChild(msgDiv('error', designState.error));
- return;
- }
- if (designState.present === false) {
- const empty = document.createElement('div');
- empty.className = 'empty';
- empty.innerHTML = `<strong>No DESIGN.md yet</strong>Create one by running <code>/impeccable document</code> in your terminal, then re-open this panel.`;
- body.appendChild(empty);
- return;
- }
-
- if (designState.tab === 'raw') {
- renderRawTab(body, designState.raw || '');
- return;
- }
-
- // Visual tab — single unified render path.
- if (designState.mdNewerThanJson) body.appendChild(renderStaleHint());
- if (designState.hasMd && !designState.hasSidecar) {
- body.appendChild(renderParsedMdCta());
- }
- renderDesignVisual(body, designState.parsed, designState.sidecar);
- }
-
- function msgDiv(cls, text) {
- const d = document.createElement('div');
- d.className = cls;
- d.textContent = text;
- return d;
- }
-
- function renderStaleHint() {
- const box = document.createElement('div');
- box.className = 'stale';
- box.innerHTML = `
- <span class="stale-dot"></span>
- <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>
- `;
- return box;
- }
-
- function renderParsedMdCta() {
- const box = document.createElement('div');
- box.className = 'parsed-md-cta';
- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;
- return box;
- }
-
- // --- Unified render: merge parsed DESIGN.md frontmatter with sidecar v2 ---
-
- function renderDesignVisual(body, parsed, sidecar) {
- const frontmatter = parsed?.frontmatter || {};
- const extensions = sidecar?.extensions || {};
- const proseColors = parsed?.colors || null;
-
- const colors = buildColorModels(frontmatter.colors, extensions.colorMeta, proseColors);
- if (colors.length) renderColorTiles(body, colors);
-
- const types = buildTypographyModels(frontmatter.typography, extensions.typographyMeta);
- if (types.length) renderTypeTiles(body, types);
-
- const radii = buildRadiiModels(frontmatter.rounded);
- if (radii.length) renderRadiiTile(body, radii);
-
- if (extensions.shadows?.length) renderShadowTiles(body, extensions.shadows);
-
- const components = sidecar?.components || [];
- if (components.length) renderComponentTiles(body, components);
-
- // Narrative: sidecar wins if present (richer, agent-curated). Otherwise
- // synthesize from prose sections.
- const narrative = sidecar?.narrative || synthesizeNarrative(parsed);
- if (narrative.rules?.length) body.appendChild(renderRulesCollapsible(narrative.rules));
- if ((narrative.dos?.length || narrative.donts?.length)) body.appendChild(renderDosDontsCollapsible(narrative));
- if (narrative.overview || narrative.northStar || narrative.keyCharacteristics?.length) {
- body.appendChild(renderOverviewCollapsible(narrative));
- }
-
- if (body.childElementCount === 0) {
- body.appendChild(msgDiv('empty', 'No design system data available.'));
- }
- }
-
- // Frontmatter primitives + sidecar colorMeta → tile-ready color models.
- // A matching prose bullet (when the slug sits in the bullet text) supplies
- // description as a last-resort fallback.
- function buildColorModels(fmColors, colorMeta, proseColors) {
- if (!fmColors) return [];
- const meta = colorMeta || {};
- return Object.entries(fmColors).map(([key, value]) => {
- const m = meta[key] || {};
- return {
- role: m.role || humanizeKey(key),
- name: m.displayName || humanizeKey(key),
- value: value,
- canonical: m.canonical || null,
- description: m.description || findProseDescription(proseColors, key, m.displayName),
- tonalRamp: m.tonalRamp || null,
- };
- });
- }
-
- function buildTypographyModels(fmTypography, typographyMeta) {
- if (!fmTypography) return [];
- const meta = typographyMeta || {};
- return Object.entries(fmTypography).map(([key, spec]) => {
- const m = meta[key] || {};
- const { family, fallback } = splitFontFamily(spec?.fontFamily);
- return {
- role: key,
- name: m.displayName || humanizeKey(key),
- family,
- fallback,
- weight: spec?.fontWeight ?? 400,
- // fontStyle isn't in Stitch's frontmatter schema; the sidecar carries
- // it when a role is rendered in italic (e.g. display italic).
- style: m.style || 'normal',
- sampleSize: spec?.fontSize || '1rem',
- lineHeight: spec?.lineHeight != null ? String(spec.lineHeight) : '',
- letterSpacing: spec?.letterSpacing,
- purpose: m.purpose,
- };
- });
- }
-
- function buildRadiiModels(fmRounded) {
- if (!fmRounded) return [];
- return Object.entries(fmRounded).map(([name, value]) => ({ name, value }));
- }
-
- function splitFontFamily(stack) {
- if (!stack || typeof stack !== 'string') return { family: '', fallback: '' };
- const parts = stack.split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, ''));
- return { family: parts[0] || '', fallback: parts.slice(1).join(', ') };
- }
-
- function humanizeKey(k) {
- return String(k || '').replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
- }
-
- function findProseDescription(proseColors, key, displayName) {
- if (!proseColors || !proseColors.groups) return null;
- const needles = [key, displayName].filter(Boolean).map((s) => s.toLowerCase());
- for (const g of proseColors.groups) {
- for (const c of g.colors || []) {
- const hay = String(c.name || '').toLowerCase();
- if (hay && needles.some((n) => hay.includes(n) || n.includes(hay))) {
- return c.description || null;
- }
- }
- }
- return null;
- }
-
- function synthesizeNarrative(parsed) {
- if (!parsed) return {};
- const md = parsed;
- return {
- northStar: md.overview?.creativeNorthStar,
- overview: (md.overview?.philosophy || []).join(' '),
- keyCharacteristics: md.overview?.keyCharacteristics || [],
- rules: [
- ...(md.colors?.rules || []).map((r) => ({ ...r, section: 'colors' })),
- ...(md.typography?.rules || []).map((r) => ({ ...r, section: 'typography' })),
- ...(md.elevation?.rules || []).map((r) => ({ ...r, section: 'elevation' })),
- ],
- dos: md.dosDonts?.dos || [],
- donts: md.dosDonts?.donts || [],
- };
- }
-
- function renderColorTiles(body, colors) {
- for (const c of colors) {
- const tile = document.createElement('div');
- tile.className = 'tile c-tile';
- tile.title = 'Click to copy';
- tile.addEventListener('click', () => copyToClipboard(c.value));
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(c.name || c.role || 'Color')}</span><span>${escapeHtml(c.value || '')}</span>`;
- tile.appendChild(meta);
-
- const hero = document.createElement('div');
- hero.className = 'c-hero';
- hero.style.background = c.value;
- tile.appendChild(hero);
-
- const ramp = synthesizeRamp(c);
- if (ramp.length) {
- const r = document.createElement('div');
- r.className = 'c-ramp';
- r.innerHTML = ramp.map((v) => `<span style="background:${cssSafe(v)}"></span>`).join('');
- tile.appendChild(r);
- }
-
- if (c.description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = c.description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function synthesizeRamp(c) {
- if (c.tonalRamp?.length) return c.tonalRamp;
- // If base value is OKLCH, synthesize an 8-step ramp across lightness.
- const m = typeof c.value === 'string' && c.value.match(/^oklch\(\s*([\d.]+)%\s+([\d.]+)\s+([\d.]+)\s*(?:\/\s*([\d.]+))?\s*\)$/i);
- if (!m) return [];
- const [, , chroma, hue] = m;
- const steps = [20, 32, 44, 56, 68, 80, 90, 96];
- return steps.map((l) => `oklch(${l}% ${chroma} ${hue})`);
- }
-
- function renderTypeTiles(body, types) {
- for (const t of types) {
- const tile = document.createElement('div');
- tile.className = 'tile t-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span>${escapeHtml(t.role || '')}</span><span>${escapeHtml(t.weight || '')} ${escapeHtml(t.style === 'italic' ? 'italic' : '')}</span>`;
- tile.appendChild(meta);
-
- const specimen = document.createElement('div');
- specimen.className = 't-specimen';
- specimen.textContent = 'Aa';
- specimen.style.fontFamily = fontStack(t);
- specimen.style.fontWeight = String(t.weight || 400);
- specimen.style.fontStyle = t.style || 'normal';
- specimen.style.fontSize = '56px'; // Fixed specimen size — compare faces, not scales.
- specimen.style.letterSpacing = 'normal';
- specimen.style.textTransform = 'none';
- tile.appendChild(specimen);
-
- // The system's actual sample size for this role, shown as small mono meta below.
- if (t.sampleSize) {
- const scale = document.createElement('div');
- scale.style.cssText = 'font-family:' + MONO + '; font-size: 10px; color:' + DP.meta + '; margin-top: 2px;';
- scale.textContent = t.sampleSize;
- tile.appendChild(scale);
- }
-
- const family = document.createElement('div');
- family.className = 't-family';
- family.textContent = t.family || t.name || '';
- tile.appendChild(family);
-
- if (t.purpose) {
- const p = document.createElement('div');
- p.className = 't-purpose';
- p.textContent = t.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function fontStack(t) {
- const fam = t.family || '';
- const fb = t.fallback || '';
- if (fam && /[,\s]/.test(fam) && !fam.includes("'") && !fam.includes('"')) {
- return `"${fam}", ${fb}`;
- }
- return fam && fb ? `"${fam}", ${fb}` : (fam || fb);
- }
-
- function renderRadiiTile(body, radii) {
- const tile = document.createElement('div');
- tile.className = 'tile';
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">Corner Radii</span><span>${radii.length}</span>`;
- tile.appendChild(meta);
-
- const strip = document.createElement('div');
- strip.className = 'r-strip';
- for (const r of radii) {
- const item = document.createElement('div');
- item.className = 'r-item';
- const s = document.createElement('div');
- s.className = 'r-sample';
- s.style.borderRadius = r.value || '0';
- item.appendChild(s);
- const lbl = document.createElement('div');
- lbl.className = 'r-label';
- lbl.textContent = r.name || '';
- item.appendChild(lbl);
- const val = document.createElement('div');
- val.className = 'r-val';
- val.textContent = r.value || '';
- item.appendChild(val);
- strip.appendChild(item);
- }
- tile.appendChild(strip);
- body.appendChild(tile);
- }
-
- function renderShadowTiles(body, shadows) {
- for (const sh of shadows) {
- const tile = document.createElement('div');
- tile.className = 'tile s-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(sh.name || 'Shadow')}</span><span>Elevation</span>`;
- tile.appendChild(meta);
-
- const surface = document.createElement('div');
- surface.className = 's-surface';
- surface.style.boxShadow = sh.value || 'none';
- tile.appendChild(surface);
-
- const val = document.createElement('div');
- val.className = 's-value';
- val.textContent = sh.value || '';
- tile.appendChild(val);
-
- if (sh.purpose) {
- const p = document.createElement('div');
- p.className = 's-purpose';
- p.textContent = sh.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function renderComponentTiles(body, components) {
- // Group consecutive components that share a kind into one tile. This avoids
- // a pile of one-component tiles (e.g., three button variants = three tiles)
- // and reads more like a proper category.
- const groups = groupByKind(components);
-
- for (const group of groups) {
- const tile = document.createElement('div');
- tile.className = 'tile cmp-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- const groupTitle = group.length === 1
- ? (group[0].name || group[0].kind || 'Component')
- : titleForKind(group[0].kind, group.length);
- meta.innerHTML = `<span class="name">${escapeHtml(groupTitle)}</span><span class="cmp-kind">${escapeHtml(group[0].kind || '')}</span>`;
- tile.appendChild(meta);
-
- for (const c of group) {
- const stage = document.createElement('div');
- stage.className = 'cmp-stage';
-
- // Render the component in its own shadow root so its CSS can't bleed.
- const host = document.createElement('div');
- const sub = host.attachShadow({ mode: 'open' });
- const style = document.createElement('style');
- style.textContent = c.css || '';
- sub.appendChild(style);
- const container = document.createElement('div');
- container.innerHTML = c.html || '';
- sub.appendChild(container);
- stage.appendChild(host);
-
- // Show component name as a sublabel only when the tile groups >1 item,
- // or when the component's display name differs from its kind.
- const showSublabel = group.length > 1;
- if (showSublabel) {
- const lbl = document.createElement('div');
- lbl.className = 'cmp-sublabel';
- lbl.textContent = c.name || '';
- stage.appendChild(lbl);
- }
- tile.appendChild(stage);
- }
-
- // Single shared description if all items carry the same one; otherwise
- // skip — per-item descriptions clutter a grouped tile.
- if (group.length === 1 && group[0].description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = group[0].description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function groupByKind(components) {
- const groups = [];
- for (const c of components) {
- const last = groups[groups.length - 1];
- if (last && last[0].kind && c.kind === last[0].kind) {
- last.push(c);
- } else {
- groups.push([c]);
- }
- }
- return groups;
- }
-
- function titleForKind(kind, count) {
- const labels = {
- button: 'Buttons',
- input: 'Inputs',
- nav: 'Navigation',
- chip: 'Chips',
- card: 'Cards',
- custom: 'Components',
- };
- return labels[kind] || (kind ? kind.charAt(0).toUpperCase() + kind.slice(1) + 's' : 'Components');
- }
-
- // --- Collapsibles ---------------------------------------------------------
-
- function buildCollapsible(key, label, count) {
- const wrap = document.createElement('div');
- wrap.className = 'coll';
- wrap.setAttribute('data-open', designState.collapsed[key] ? 'false' : 'true');
-
- const head = document.createElement('button');
- head.className = 'coll-head';
- head.innerHTML = `
- <svg class="coll-chev" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 2.5L8 6 4 9.5"/></svg>
- <span>${escapeHtml(label)}</span>
- ${count != null ? `<span class="coll-count">${escapeHtml(String(count))}</span>` : ''}
- `;
- head.addEventListener('click', () => {
- designState.collapsed[key] = !designState.collapsed[key];
- saveDesignPrefs();
- renderDesignBody();
- });
- wrap.appendChild(head);
-
- const body = document.createElement('div');
- body.className = 'coll-body';
- wrap.appendChild(body);
- return { wrap, body };
- }
-
- function renderRulesCollapsible(rules) {
- const { wrap, body } = buildCollapsible('rules', 'Named Rules', rules.length);
- for (const r of rules) {
- const card = document.createElement('div');
- card.className = 'rule-card';
- const name = document.createElement('div');
- name.className = 'name';
- name.innerHTML = `${escapeHtml(r.name)}${r.section ? `<span class="section">${escapeHtml(r.section)}</span>` : ''}`;
- card.appendChild(name);
- const b = document.createElement('div');
- b.className = 'body';
- b.textContent = r.body || '';
- card.appendChild(b);
- body.appendChild(card);
- }
- return wrap;
- }
-
- function renderDosDontsCollapsible(n) {
- const total = (n.dos?.length || 0) + (n.donts?.length || 0);
- const { wrap, body } = buildCollapsible('dosdonts', "Do's and Don'ts", total);
- const grid = document.createElement('div');
- grid.className = 'dos';
- for (const d of n.dos || []) {
- const el = document.createElement('div');
- el.className = 'do';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- for (const d of n.donts || []) {
- const el = document.createElement('div');
- el.className = 'dont';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- body.appendChild(grid);
- return wrap;
- }
-
- function renderOverviewCollapsible(n) {
- const { wrap, body } = buildCollapsible('overview', 'Overview', null);
- const ov = document.createElement('div');
- ov.className = 'overview-body';
- if (n.northStar) {
- const star = document.createElement('span');
- star.className = 'north-star';
- star.textContent = '“' + n.northStar + '”';
- ov.appendChild(star);
- }
- if (n.overview) {
- const p = document.createElement('p');
- p.innerHTML = inlineMd(n.overview);
- ov.appendChild(p);
- }
- if (n.keyCharacteristics?.length) {
- const ul = document.createElement('ul');
- ul.innerHTML = n.keyCharacteristics.map((k) => `<li>${inlineMd(k)}</li>`).join('');
- ov.appendChild(ul);
- }
- body.appendChild(ov);
- return wrap;
- }
-
- function cssSafe(v) {
- // Strip anything outside valid CSS value chars to prevent injection via
- // .impeccable/design.json values rendered into inline style strings.
- return String(v).replace(/[<>"'`\n]/g, '');
- }
-
- // --- Raw tab: minimal markdown renderer (subset) --------------------------
-
- function renderRawTab(body, md) {
- const wrap = document.createElement('div');
- wrap.className = 'md';
- wrap.innerHTML = renderMarkdown(md);
- body.appendChild(wrap);
- }
-
- function renderMarkdown(md) {
- const lines = md.split(/\r?\n/);
- const out = [];
- let i = 0;
- let inCode = false;
- let codeBuf = [];
- let paraBuf = [];
- let listBuf = []; // array of { indent, html }
- let listType = null; // 'ul' | 'ol'
-
- const flushPara = () => {
- if (paraBuf.length) {
- out.push(`<p>${inlineMd(paraBuf.join(' '))}</p>`);
- paraBuf = [];
- }
- };
- const flushList = () => {
- if (listBuf.length) {
- out.push(buildListHtml(listBuf, listType));
- listBuf = [];
- listType = null;
- }
- };
- const flushAll = () => { flushPara(); flushList(); };
-
- for (; i < lines.length; i++) {
- const line = lines[i];
-
- // Code fence
- const fence = line.match(/^```(\w*)\s*$/);
- if (fence) {
- if (!inCode) { flushAll(); inCode = true; codeBuf = []; }
- else {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- inCode = false;
- }
- continue;
- }
- if (inCode) { codeBuf.push(line); continue; }
-
- if (line.trim() === '') { flushAll(); continue; }
-
- const hr = line.match(/^\s*(?:---+|\*\*\*+)\s*$/);
- if (hr) { flushAll(); out.push('<hr />'); continue; }
-
- const heading = line.match(/^(#{1,4})\s+(.+)$/);
- if (heading) {
- flushAll();
- const lvl = heading[1].length;
- out.push(`<h${lvl}>${inlineMd(heading[2])}</h${lvl}>`);
- continue;
- }
-
- const bullet = line.match(/^(\s*)([-*])\s+(.+)$/);
- const ordered = line.match(/^(\s*)(\d+)\.\s+(.+)$/);
- if (bullet || ordered) {
- flushPara();
- const m = bullet || ordered;
- const indent = Math.floor(m[1].length / 2);
- const t = bullet ? 'ul' : 'ol';
- if (listType && listType !== t) flushList();
- listType = t;
- listBuf.push({ indent, html: inlineMd(m[3]) });
- continue;
- }
-
- paraBuf.push(line);
- }
- flushAll();
- if (inCode && codeBuf.length) {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- }
- return out.join('\n');
- }
-
- function buildListHtml(items, type) {
- // Nest by indent (one level deep is plenty for DESIGN.md).
- let html = `<${type}>`;
- let lastIndent = 0;
- for (const it of items) {
- if (it.indent > lastIndent) html += `<${type}>`;
- else if (it.indent < lastIndent) html += `</${type}>`.repeat(lastIndent - it.indent);
- html += `<li>${it.html}</li>`;
- lastIndent = it.indent;
- }
- html += `</${type}>`.repeat(lastIndent + 1);
- return html;
- }
-
- function inlineMd(text) {
- // Order matters: escape first, then re-inject tags.
- let s = escapeHtml(text);
- // Code spans
- s = s.replace(/`([^`]+)`/g, (_, code) => `<code>${code}</code>`);
- // Links [text](url)
- s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, t, u) => `<a href="${u}" target="_blank" rel="noopener noreferrer">${t}</a>`);
- // Bold
- s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
- // Italic (only single *…*, skip if inside bold already handled)
- s = s.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em>$2</em>');
- return s;
- }
-
- function highlightBold(text) {
- return inlineMd(text);
- }
-
- function escapeHtml(s) {
- return String(s)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
-
- function copyToClipboard(text) {
- if (!text) return;
- try {
- navigator.clipboard.writeText(text);
- showToast('Copied: ' + text);
- } catch { /* ignore */ }
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- function init() {
- try { history.scrollRestoration = 'manual'; } catch {}
- initHighlight();
- initAnnotOverlay();
- initBar();
- initActionPicker();
- initParamsPanel();
- initGlobalBar();
- initDesignPanel();
- document.addEventListener('mousemove', handleMouseMove, true);
- document.addEventListener('click', handleClick, true);
- document.addEventListener('keydown', handleKeyDown, true);
- connectSSE();
-
- // Check for an active session to resume (variant wrapper already in DOM after HMR)
- if (!resumeSession()) {
- console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
- // SvelteKit (and any framework that hydrates after HTML parse) may add
- // the variant wrapper AFTER init runs. Watch for it and retry resume
- // once it appears. Disconnect on first hit.
- const scout = new MutationObserver(() => {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) return;
- scout.disconnect();
- if (resumeSession()) {
- console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
- }
- });
- scout.observe(document.body, { childList: true, subtree: true });
- } else {
- console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
- }
- }
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
- } else {
- init();
- }
-})();
@@ -1,75 +0,0 @@
-#!/usr/bin/env node
-/**
- * Canonical durable completion acknowledgement for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function parseArgs(argv) {
- const out = { status: 'complete' };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';
- else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }
- else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function completeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help || !args.id) {
- console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);
- process.exit(args.help ? 0 : 1);
- }
-
- const serverInfo = readServerInfo();
- const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;
- if (serverResult?.ok) {
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const snapshot = store.getSnapshot(args.id, { includeCompleted: true });
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const event = args.status === 'discarded'
- ? { type: 'discarded', id: args.id }
- : args.status === 'agent_error'
- ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }
- : { type: 'complete', id: args.id };
- const snapshot = store.appendEvent(event);
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));
-}
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function completeThroughServer(info, args) {
- const type = args.status === 'discarded'
- ? 'discarded'
- : args.status === 'agent_error'
- ? 'error'
- : 'complete';
- try {
- const res = await fetch(`http://localhost:${info.port}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),
- });
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {
- completeCli();
-}
@@ -1,18 +0,0 @@
-export function completionTypeForAcceptResult(eventType, acceptResult) {
- if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';
- if (acceptResult?.handled === true) return 'complete';
- if (acceptResult?.mode === 'error') return 'error';
- return 'agent_done';
-}
-
-export function completionAckForAcceptResult(eventId, completionType, acceptResult) {
- const ack = { ok: true, type: completionType };
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) {
- ack.final = false;
- ack.requiresComplete = true;
- ack.nextCommand = `live-complete.mjs --id ${eventId}`;
- ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';
- }
- return ack;
-}
@@ -1,446 +0,0 @@
-/**
- * CLI helper: insert/remove the live variant mode script tag in the project's
- * main HTML entry point.
- *
- * On first live run, the agent generates `.impeccable/live/config.json`
- * with the project's insertion target (framework-specific). On
- * every subsequent run, this script handles insert/remove deterministically
- * with zero LLM involvement.
- *
- * Usage:
- * node live-inject.mjs --port PORT # Insert the live script tag
- * node live-inject.mjs --remove # Remove the live script tag
- * node live-inject.mjs --check # Check whether live config exists
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { resolveLiveConfigPath } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });
-const MARKER_OPEN_TEXT = 'impeccable-live-start';
-const MARKER_CLOSE_TEXT = 'impeccable-live-end';
-
-/**
- * Hard-excluded directory patterns. These are NEVER user-facing pages and
- * matching them would silently inject tracking scripts into third-party
- * code. The user cannot turn these off via config — they are the floor.
- */
-const HARD_EXCLUDES = [
- '**/node_modules/**',
- '**/.git/**',
-];
-
-export async function injectCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-inject.mjs [options]
-
-Insert or remove the live mode script tag in the project's HTML entry point.
-Reads configuration from .impeccable/live/config.json.
-
-Modes:
- --port PORT Insert script tag pointing at http://localhost:PORT/live.js
- --remove Remove the script tag (if present)
- --check Print whether .impeccable/live/config.json exists and its content
-
-Output (JSON):
- { ok, file, inserted|removed, config? }`);
- process.exit(0);
- }
-
- if (args.includes('--check')) {
- if (!fs.existsSync(CONFIG_PATH)) {
- console.log(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(0);
- }
- let cfg;
- try {
- cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- try {
- validateConfig(cfg);
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- console.log(JSON.stringify({ ok: true, config: cfg, path: CONFIG_PATH }));
- return;
- }
-
- // Load config
- if (!fs.existsSync(CONFIG_PATH)) {
- console.error(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(1);
- }
- const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- validateConfig(config);
-
- const resolvedFiles = resolveFiles(process.cwd(), config);
-
- if (args.includes('--remove')) {
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const detagged = removeTag(content, config.commentSyntax);
- const updated = revertCspMeta(detagged);
- if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- removed: detagged !== content,
- cspReverted: updated !== detagged,
- };
- });
- console.log(JSON.stringify({ ok: true, results }));
- return;
- }
-
- // Insert mode — need --port
- const portIdx = args.indexOf('--port');
- const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : NaN;
- if (!Number.isFinite(port)) {
- console.error(JSON.stringify({ ok: false, error: 'missing_port' }));
- process.exit(1);
- }
-
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
- const withTag = insertTag(withoutOld, config, port);
- if (withTag === withoutOld) {
- return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
- }
- const updated = patchCspMeta(withTag, port);
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- inserted: true,
- cspPatched: updated !== withTag,
- };
- });
- const anyInserted = results.some((r) => r.inserted);
- console.log(JSON.stringify({ ok: anyInserted, port, results }));
- if (!anyInserted) process.exit(1);
-}
-
-/**
- * Expand config.files (which may contain glob patterns) into a literal list
- * of existing file paths relative to rootDir. Literal entries pass through;
- * glob patterns are expanded via fs.globSync. HARD_EXCLUDES and config.exclude
- * are applied as filters. Duplicates are removed. Order is preserved by
- * first appearance.
- */
-export function resolveFiles(rootDir, config) {
- const patterns = config.files;
- const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
- const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
- const excludeRegexes = allExcludes.map(globToRegex);
-
- const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
- const isGlob = (s) => /[*?[]/.test(s);
-
- const seen = new Set();
- const out = [];
- for (const pat of patterns) {
- if (!isGlob(pat)) {
- // Literal path — include even if it doesn't exist yet; the caller
- // reports file_not_found per-entry. Exclude list doesn't apply to
- // explicit literal entries (user named it on purpose).
- if (!seen.has(pat)) {
- seen.add(pat);
- out.push(pat);
- }
- continue;
- }
- let matches;
- try {
- matches = fs.globSync(pat, { cwd: rootDir, withFileTypes: true });
- } catch {
- continue;
- }
- for (const ent of matches) {
- if (!ent.isFile || !ent.isFile()) continue;
- const abs = path.join(ent.parentPath || ent.path || rootDir, ent.name);
- const rel = path.relative(rootDir, abs).split(path.sep).join('/');
- if (isExcluded(rel)) continue;
- if (seen.has(rel)) continue;
- seen.add(rel);
- out.push(rel);
- }
- }
- return out;
-}
-
-/**
- * Convert a glob pattern to a RegExp. Supports:
- * ** → any number of path segments (including zero)
- * * → any chars except `/`
- * ? → any single char except `/`
- * Paths are normalized to forward slashes before matching.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- // ** — any number of segments, including zero. Handle the common
- // **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
- if (pattern[i + 2] === '/') {
- re += '(?:.*/)?';
- i += 3;
- } else {
- re += '.*';
- i += 2;
- }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Core operations
-// ---------------------------------------------------------------------------
-
-function validateConfig(cfg) {
- if (!cfg || typeof cfg !== 'object') throw new Error('config.json must be an object');
- if (!Array.isArray(cfg.files) || cfg.files.length === 0) {
- throw new Error('config.files (non-empty string array) required');
- }
- if (!cfg.files.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.files must contain only non-empty strings');
- }
- if (cfg.exclude !== undefined) {
- if (!Array.isArray(cfg.exclude)) {
- throw new Error('config.exclude, if present, must be a string array');
- }
- if (!cfg.exclude.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.exclude must contain only non-empty strings');
- }
- }
- if (typeof cfg.insertBefore !== 'string' && typeof cfg.insertAfter !== 'string') {
- throw new Error('config.insertBefore or config.insertAfter (string) required');
- }
- if (cfg.commentSyntax !== 'html' && cfg.commentSyntax !== 'jsx') {
- throw new Error("config.commentSyntax must be 'html' or 'jsx'");
- }
- if (cfg.cspChecked !== undefined && typeof cfg.cspChecked !== 'boolean') {
- throw new Error("config.cspChecked, if present, must be a boolean");
- }
-}
-
-function commentOpen(syntax) { return syntax === 'jsx' ? '{/*' : '<!--'; }
-function commentClose(syntax) { return syntax === 'jsx' ? '*/}' : '-->'; }
-
-function buildTagBlock(syntax, port) {
- const open = commentOpen(syntax);
- const close = commentClose(syntax);
- return (
- open + ' ' + MARKER_OPEN_TEXT + ' ' + close + '\n' +
- '<script src="http://localhost:' + port + '/live.js"></script>\n' +
- open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n'
- );
-}
-
-function insertTag(content, config, port) {
- const block = buildTagBlock(config.commentSyntax, port);
- // insertBefore: match the LAST occurrence. Anchors like `</body>` naturally
- // belong at the end, and the same literal can appear earlier in code blocks
- // within rendered documentation pages.
- if (config.insertBefore) {
- const idx = content.lastIndexOf(config.insertBefore);
- if (idx === -1) return content;
- return content.slice(0, idx) + block + content.slice(idx);
- }
- // insertAfter: match the FIRST occurrence — typical anchors like `<head>` or
- // `<body>` open near the top of the document.
- const idx = content.indexOf(config.insertAfter);
- if (idx === -1) return content;
- const after = idx + config.insertAfter.length;
- // Preserve a single trailing newline if the anchor didn't end with one
- const prefix = content[after] === '\n' ? content.slice(0, after + 1) : content.slice(0, after) + '\n';
- return prefix + block + content.slice(prefix.length);
-}
-
-/**
- * Remove the live script block. Matches either HTML or JSX comment markers
- * regardless of config (so stale tags from a wrong config can still be cleaned).
- *
- * Indent-preserving: captures any whitespace immediately preceding the opener
- * marker and re-emits it in place of the removed block. `insertTag` inserted
- * the block *after* the original line's indent and *before* the anchor (e.g.
- * `</body>`), which moved the indent onto the opener line and left the anchor
- * unindented. Replacing the whole block (plus its trailing newline) with just
- * the captured indent hands the indent back to the anchor that follows.
- */
-function removeTag(content, _syntax) {
- const patterns = [
- /([ \t]*)<!--\s*impeccable-live-start\s*-->[\s\S]*?<!--\s*impeccable-live-end\s*-->[ \t]*\n/,
- /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}[ \t]*\n/,
- ];
- for (const pat of patterns) {
- const next = content.replace(pat, '$1');
- if (next !== content) return next;
- }
- return content;
-}
-
-// ---------------------------------------------------------------------------
-// Content-Security-Policy meta-tag patcher
-//
-// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
-// the cross-origin load of /live.js (and the SSE/POST connection back to
-// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
-//
-// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
-// and stash the original `content` value in a `data-impeccable-csp-original`
-// attribute (base64) so revert is exact.
-//
-// On remove: detect the marker attribute, decode it, restore the original
-// content value verbatim, drop the marker.
-//
-// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
-// shared helpers) is NOT patched here — those need framework-specific config
-// edits and are handled via the existing detect-csp.mjs reference output.
-// Only the in-source meta-tag form gets the auto-patch.
-// ---------------------------------------------------------------------------
-
-const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
-
-function findCspMetaTags(content) {
- const out = [];
- const tagRe = /<meta\s+([^>]*?)\/?>/gis;
- let m;
- while ((m = tagRe.exec(content)) !== null) {
- const attrs = m[1];
- if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
- out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
- }
- return out;
-}
-
-function getAttr(attrs, name) {
- const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
- const m = attrs.match(re);
- return m ? { quote: m[1], value: m[2], full: m[0] } : null;
-}
-
-function appendOriginToDirective(csp, directive, origin) {
- const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
- const m = csp.match(re);
- if (m) {
- const tokens = m[4].trim().split(/\s+/);
- if (tokens.includes(origin)) return csp;
- return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
- }
- // Directive missing — add it. Use 'self' + origin so we don't inadvertently
- // narrow the policy compared to the default-src fallback (most users with
- // an explicit CSP have 'self' there).
- return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
-}
-
-export function patchCspMeta(content, port) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
- const origin = `http://localhost:${port}`;
-
- // Walk last-to-first so prior splices don't invalidate later indices.
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const attrs = tag.attrs;
- if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
- const contentAttr = getAttr(attrs, 'content');
- if (!contentAttr) continue;
-
- const original = contentAttr.value;
- let patched = original;
- patched = appendOriginToDirective(patched, 'script-src', origin);
- patched = appendOriginToDirective(patched, 'connect-src', origin);
- // The shader overlay during 'generating' creates a screenshot via
- // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
- // those. Add `blob:` so the overlay doesn't throw a CSP violation.
- patched = appendOriginToDirective(patched, 'img-src', 'blob:');
- if (patched === original) continue;
-
- const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
- const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
- // The tagRe captures any whitespace between the last attribute and the
- // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
- // a replace would land it BEFORE that trailing space, leaving a double
- // space inside attrs and clobbering the space before `/>`. Split off
- // the trailing whitespace, splice the marker into the attribute body,
- // and re-append the original trailing whitespace so a self-closing
- // `<meta … />` round-trips byte-for-byte.
- const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
- const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
- const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
- const newTag = tag.full.replace(attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-export function revertCspMeta(content) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
-
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
- if (!origAttr) continue;
- const contentAttr = getAttr(tag.attrs, 'content');
- if (!contentAttr) continue;
-
- let originalValue;
- try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
- catch { continue; }
-
- const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
- let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
- // Drop the marker attribute and any single space immediately preceding it.
- newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
- const newTag = tag.full.replace(tag.attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
- injectCli();
-}
-
-export { insertTag, removeTag, validateConfig, buildTagBlock };
-// patchCspMeta + revertCspMeta are exported above where they're defined.
@@ -1,200 +0,0 @@
-/**
- * CLI client for the live variant mode poll/reply protocol.
- *
- * Usage:
- * npx impeccable poll # Block until browser event, print JSON
- * npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
- * npx impeccable poll --reply <id> done # Reply "done" to event <id>
- * npx impeccable poll --reply <id> error "msg" # Reply with error
- */
-
-import { execFileSync } from 'node:child_process';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-// Node's built-in fetch (undici under the hood) enforces a 300s headers
-// timeout that can't be lowered per-request. We cap each request below
-// that ceiling and loop in `pollOnce` to synthesize a long poll without
-// depending on the standalone undici package.
-const PER_REQUEST_TIMEOUT_MS = 270_000;
-
-function readServerInfo() {
- const record = readLiveServerInfo(process.cwd());
- if (!record) {
- console.error('No running live server found. Start one with: npx impeccable live');
- process.exit(1);
- }
- return record.info;
-}
-
-export function buildPollReplyPayload(token, { id, type, message, file, data }) {
- return { token, id, type, message, file, data };
-}
-
-async function postReply(base, token, reply) {
- const res = await fetch(`${base}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(buildPollReplyPayload(token, reply)),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error || res.statusText);
- }
-}
-
-export async function pollCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable poll [options]
-
-Wait for a browser event from the live variant server, or reply to one.
-
-Modes:
- poll Block until a browser event arrives, print JSON
- poll --reply <id> done Reply "done" to event <id>
- poll --reply <id> error "msg" Reply with an error message
-
-Options:
- --timeout=MS Long-poll timeout in ms (default: 600000). Use the default unless the user asked to pause live; never use a short timeout to end the chat turn
- --help Show this help message`);
- process.exit(0);
- }
-
- const info = readServerInfo();
- const base = `http://localhost:${info.port}`;
-
- // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
- const replyIdx = args.indexOf('--reply');
- if (replyIdx !== -1) {
- const id = args[replyIdx + 1];
- const status = args[replyIdx + 2] || 'done';
- const fileIdx = args.indexOf('--file');
- const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
- // Message is any remaining positional arg that isn't a flag
- const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
-
- if (!id) {
- console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
- process.exit(1);
- }
-
- try {
- await postReply(base, info.token, { id, type: status, message, file: filePath });
-
- // Success — silent exit (agent doesn't need output for replies)
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Reply failed:', err.message);
- }
- process.exit(1);
- }
- return;
- }
-
- // Poll mode: block until browser event. Default 10 min. Node's built-in
- // fetch enforces a 300s headers timeout, so we loop in slices under that
- // ceiling and keep re-polling until we get a real event or the user's
- // total timeout runs out.
- const timeoutArg = args.find(a => a.startsWith('--timeout='));
- const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600000;
-
- const deadline = Date.now() + totalTimeout;
- let event;
- try {
- while (true) {
- const remaining = deadline - Date.now();
- if (remaining <= 0) {
- event = { type: 'timeout' };
- break;
- }
- const slice = Math.min(remaining, PER_REQUEST_TIMEOUT_MS);
- const res = await fetch(`${base}/poll?token=${info.token}&timeout=${slice}`);
-
- if (res.status === 401) {
- console.error('Authentication failed. The server token may have changed.');
- console.error('Try restarting: npx impeccable live stop && npx impeccable live');
- process.exit(1);
- }
-
- if (!res.ok) {
- console.error(`Poll failed: ${res.status} ${res.statusText}`);
- process.exit(1);
- }
-
- const next = await res.json();
- // Server-side timeout means no browser event arrived in this slice.
- // Loop and re-poll until we get a real event or we hit the user's
- // total deadline.
- if (next?.type === 'timeout' && Date.now() < deadline) continue;
- event = next;
- break;
- }
-
- // Auto-handle accept/discard via deterministic script
- if (event.type === 'accept' || event.type === 'discard') {
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const acceptScript = path.join(__dirname, 'live-accept.mjs');
- const scriptArgs = event.type === 'discard'
- ? ['--id', event.id, '--discard']
- : ['--id', event.id, '--variant', event.variantId];
- if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
- scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
- }
- try {
- const out = execFileSync(
- 'node',
- [acceptScript, ...scriptArgs],
- { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 }
- );
- event._acceptResult = JSON.parse(out.trim());
- } catch (err) {
- event._acceptResult = { handled: false, mode: 'error', error: err.message };
- }
-
- const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
- try {
- await postReply(base, info.token, {
- id: event.id,
- type: completionType,
- message: event._acceptResult?.error,
- file: event._acceptResult?.file,
- data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
- });
- } catch (err) {
- event._completionAck = { ok: false, error: err.message };
- }
- if (!event._completionAck) {
- event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
- }
- }
-
- // Second signal path: stderr banner in case the agent parses stdout
- // JSON but skips nested fields. One line is enough — the full checklist
- // is in reference/live.md.
- if (event._acceptResult?.carbonize === true) {
- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
- }
-
- // Print the event as JSON — the agent reads this from stdout
- console.log(JSON.stringify(event));
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Poll failed:', err.message);
- }
- process.exit(1);
- }
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
- pollCli();
-}
@@ -1,48 +0,0 @@
-#!/usr/bin/env node
-/**
- * Recover the next agent action from the durable live-session journal.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-
-function parseArgs(argv) {
- const out = { id: null };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function resumeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help) {
- console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });
- const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;
- if (!snapshot) {
- console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));
- return;
- }
-
- const pending = snapshot.pendingEvent || null;
- const nextAction = pending
- ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`
- : snapshot.phase === 'carbonize_required'
- ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`
- : snapshot.phase === 'accept_requested'
- ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`
- : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;
-
- console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {
- resumeCli();
-}
@@ -1,838 +0,0 @@
-#!/usr/bin/env node
-/**
- * Live variant mode server (self-contained, zero dependencies).
- *
- * Serves the browser script (/live.js), the detection overlay (/detect.js),
- * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
- * browser→server events. Agent communicates via HTTP long-poll (/poll).
- *
- * Usage:
- * node <scripts_path>/live-server.mjs # start
- * node <scripts_path>/live-server.mjs stop # stop + remove injected live.js tag
- * node <scripts_path>/live-server.mjs stop --keep-inject # stop only
- * node <scripts_path>/live-server.mjs --help
- */
-
-import http from 'node:http';
-import { randomUUID } from 'node:crypto';
-import { spawn, execFileSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import net from 'node:net';
-import { fileURLToPath } from 'node:url';
-import { parseDesignMd } from './design-parser.mjs';
-import { resolveContextDir } from './load-context.mjs';
-import { createLiveSessionStore } from './live-session-store.mjs';
-import {
- getDesignSidecarPath,
- getLiveAnnotationsDir,
- readLiveServerInfo,
- removeLiveServerInfo,
- resolveDesignSidecarPath,
- writeLiveServerInfo,
-} from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated
-// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
-// DESIGN.json fallback for existing projects.
-const CONTEXT_DIR = resolveContextDir(process.cwd());
-const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anyway
-const SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s
-
-// ---------------------------------------------------------------------------
-// Port detection
-// ---------------------------------------------------------------------------
-
-async function findOpenPort(start = 8400) {
- return new Promise((resolve) => {
- const srv = net.createServer();
- srv.listen(start, '127.0.0.1', () => {
- const port = srv.address().port;
- srv.close(() => resolve(port));
- });
- srv.on('error', () => resolve(findOpenPort(start + 1)));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Session state
-// ---------------------------------------------------------------------------
-
-const state = {
- token: null,
- port: null,
- sseClients: new Set(), // SSE response objects (server→browser push)
- pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
- pendingPolls: [], // agent poll callbacks waiting for browser events
- exitTimer: null,
- sessionDir: null, // per-session tmp dir for annotation screenshots
- sessionStore: null,
- leaseTimer: null,
-};
-
-// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;
-// cap at 10 MB to guard against runaway writes from a misbehaving client.
-const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
-
-function enqueueEvent(event) {
- if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;
- state.pendingEvents.push({ event, leaseUntil: 0 });
- flushPendingPolls();
-}
-
-function restorePendingEventsFromStore() {
- if (!state.sessionStore) return;
- for (const snapshot of state.sessionStore.listActiveSessions()) {
- if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);
- }
-}
-
-function findAvailablePendingEvent(now = Date.now()) {
- return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);
-}
-
-function leaseEvent(entry, leaseMs) {
- if (!entry.event?.id) {
- const idx = state.pendingEvents.indexOf(entry);
- if (idx !== -1) state.pendingEvents.splice(idx, 1);
- return entry.event;
- }
- entry.leaseUntil = Date.now() + leaseMs;
- return entry.event;
-}
-
-function acknowledgePendingEvent(id) {
- if (!id) return false;
- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);
- if (idx === -1) return false;
- state.pendingEvents.splice(idx, 1);
- scheduleLeaseFlush();
- return true;
-}
-
-function scheduleLeaseFlush() {
- if (state.leaseTimer) {
- clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- }
- if (state.pendingPolls.length === 0) return;
- const now = Date.now();
- const nextLeaseUntil = state.pendingEvents
- .map((entry) => entry.leaseUntil || 0)
- .filter((leaseUntil) => leaseUntil > now)
- .sort((a, b) => a - b)[0];
- if (!nextLeaseUntil) return;
- state.leaseTimer = setTimeout(() => {
- state.leaseTimer = null;
- flushPendingPolls();
- }, Math.max(0, nextLeaseUntil - now));
-}
-
-function flushPendingPolls() {
- while (state.pendingPolls.length > 0) {
- const entry = findAvailablePendingEvent();
- if (!entry) {
- scheduleLeaseFlush();
- return;
- }
- const poll = state.pendingPolls.shift();
- poll.resolve(leaseEvent(entry, poll.leaseMs));
- }
- scheduleLeaseFlush();
-}
-
-/** Push a message to all connected SSE clients. */
-function broadcast(msg) {
- const data = 'data: ' + JSON.stringify(msg) + '\n\n';
- for (const res of state.sseClients) {
- try { res.write(data); } catch { /* client gone */ }
- }
-}
-
-// ---------------------------------------------------------------------------
-// Load scripts
-// ---------------------------------------------------------------------------
-
-function loadBrowserScripts() {
- // Detection script: prefer the skill-bundled detector, then fall back to
- // source/npm package locations for local development and older installs.
- // This one IS cached — detect.js rarely changes during a session.
- const detectPaths = [
- path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(process.cwd(), 'node_modules', 'impeccable', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- ];
- let detectScript = '';
- for (const p of detectPaths) {
- try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
- }
-
- // live-browser.js: DO NOT cache. Return the path so the /live.js handler
- // can re-read on every request. Editing the browser script during iteration
- // should land on the next tab reload, not require a server restart.
- const sessionPath = path.join(__dirname, 'live-browser-session.js');
- const livePath = path.join(__dirname, 'live-browser.js');
- for (const p of [sessionPath, livePath]) {
- if (!fs.existsSync(p)) {
- process.stderr.write('Error: live browser script not found at ' + p + '\n');
- process.exit(1);
- }
- }
-
- return { detectScript, sessionPath, livePath };
-}
-
-function hasProjectContext() {
- // PRODUCT.md carries brand voice / anti-references — that's what determines
- // whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
- // concern, surfaced by the design panel's own empty state. Legacy
- // .impeccable.md is auto-migrated to PRODUCT.md by load-context.mjs.
- try {
- fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
- return true;
- } catch { return false; }
-}
-
-function statOrNull(filePath) {
- try { return fs.statSync(filePath); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// Validation (inline — no external import needed for self-contained script)
-// ---------------------------------------------------------------------------
-
-const VISUAL_ACTIONS = [
- 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
- 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
-];
-
-// Browser generates ids via crypto.randomUUID().slice(0, 8) (8 hex chars)
-// and variantIds via String(small integer). Restrict to those shapes so
-// any value that reaches a downstream child_process or DOM selector is
-// inert by construction.
-const ID_PATTERN = /^[0-9a-f]{8}$/;
-const VARIANT_ID_PATTERN = /^[0-9]{1,3}$/;
-
-function isValidId(v) { return typeof v === 'string' && ID_PATTERN.test(v); }
-function isValidVariantId(v) { return typeof v === 'string' && VARIANT_ID_PATTERN.test(v); }
-
-function validateEvent(msg) {
- if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
- switch (msg.type) {
- case 'generate':
- if (!isValidId(msg.id)) return 'generate: missing or malformed id';
- if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
- if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
- if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
- // Optional annotation fields (all-or-nothing: if any present, all must be well-formed).
- if (msg.screenshotPath !== undefined && typeof msg.screenshotPath !== 'string') return 'generate: screenshotPath must be string';
- if (msg.comments !== undefined && !Array.isArray(msg.comments)) return 'generate: comments must be array';
- if (msg.strokes !== undefined && !Array.isArray(msg.strokes)) return 'generate: strokes must be array';
- return null;
- case 'accept':
- if (!isValidId(msg.id)) return 'accept: missing or malformed id';
- if (!isValidVariantId(msg.variantId)) return 'accept: missing or malformed variantId';
- if (msg.paramValues !== undefined) {
- if (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues)) {
- return 'accept: paramValues must be an object';
- }
- }
- return null;
- case 'discard':
- return isValidId(msg.id) ? null : 'discard: missing or malformed id';
- case 'checkpoint':
- if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';
- if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';
- if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {
- return 'checkpoint: paramValues must be an object';
- }
- return null;
- case 'exit':
- return null;
- case 'prefetch':
- if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return 'prefetch: missing pageUrl';
- return null;
- default:
- return 'Unknown event type: ' + msg.type;
- }
-}
-
-// ---------------------------------------------------------------------------
-// HTTP request handler
-// ---------------------------------------------------------------------------
-
-function createRequestHandler({ detectScript, sessionPath, livePath }) {
- return (req, res) => {
- const url = new URL(req.url, `http://localhost:${state.port}`);
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
- if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
-
- const p = url.pathname;
-
- // --- Scripts ---
- if (p === '/live.js') {
- // Re-read from disk each request so edits to live-browser.js land on
- // the next tab reload. No-store headers prevent browser caching across
- // sessions — during iteration, a cached old script silently breaks
- // every subsequent session.
- let sessionScript;
- let liveScript;
- try {
- sessionScript = fs.readFileSync(sessionPath, 'utf-8');
- liveScript = fs.readFileSync(livePath, 'utf-8');
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'text/plain' });
- res.end('Error reading live browser scripts: ' + err.message);
- return;
- }
- const body =
- `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
- `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
- sessionScript + '\n' +
- liveScript;
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
- 'Pragma': 'no-cache',
- });
- res.end(body);
- return;
- }
- if (p === '/detect.js' || p === '/') {
- if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
- res.writeHead(200, { 'Content-Type': 'application/javascript' });
- res.end(detectScript);
- return;
- }
-
- // --- Vendored modern-screenshot (UMD build) ---
- // Lazy-loaded by live.js when the user clicks Go; exposes
- // window.modernScreenshot.domToBlob(...) for capture.
- if (p === '/modern-screenshot.js') {
- const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
- try {
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'public, max-age=31536000, immutable',
- });
- res.end(fs.readFileSync(vendorPath));
- } catch {
- res.writeHead(404); res.end('Vendor script not found');
- }
- return;
- }
-
- // --- Annotation upload (browser → server, raw PNG body) ---
- // Client generates the eventId, POSTs the PNG, then POSTs the generate
- // event with screenshotPath already set. Keeps bytes out of the SSE/poll
- // bridge and preserves the "one shot from the user's POV" UX.
- if (p === '/annotation' && req.method === 'POST') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const eventId = url.searchParams.get('eventId');
- if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid eventId' }));
- return;
- }
- if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
- res.writeHead(415, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
- return;
- }
- if (!state.sessionDir) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Session dir unavailable' }));
- return;
- }
- const chunks = [];
- let total = 0;
- let aborted = false;
- req.on('data', (c) => {
- if (aborted) return;
- total += c.length;
- if (total > MAX_ANNOTATION_BYTES) {
- aborted = true;
- res.writeHead(413, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Payload too large' }));
- req.destroy();
- return;
- }
- chunks.push(c);
- });
- req.on('end', () => {
- if (aborted) return;
- const absPath = path.join(state.sessionDir, eventId + '.png');
- try {
- fs.writeFileSync(absPath, Buffer.concat(chunks));
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Write failed: ' + err.message }));
- return;
- }
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true, path: absPath }));
- });
- req.on('error', () => {
- if (!aborted) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Upload failed' }));
- }
- });
- return;
- }
-
- // --- Health ---
- if (p === '/status') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
- const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok',
- port: state.port,
- connectedClients: state.sseClients.size,
- pendingEvents: state.pendingEvents.map((entry) => ({
- id: entry.event?.id,
- type: entry.event?.type,
- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),
- leaseUntil: entry.leaseUntil || null,
- })),
- activeSessions: sessions,
- }));
- return;
- }
-
- if (p === '/health') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok', port: state.port, mode: 'variant',
- hasProjectContext: hasProjectContext(),
- connectedClients: state.sseClients.size,
- }));
- return;
- }
-
- // --- Design system (unified v2 response) + raw ---
- // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json
- // sidecar when present. Panel merges them:
- // { present, parsed, sidecar, hasMd, hasSidecar,
- // mdNewerThanJson, parseError?, sidecarError? }
- // - parsed: output of parseDesignMd (frontmatter
- // + six canonical sections) when DESIGN.md exists.
- // - sidecar: .impeccable/design.json contents when present.
- // Expected shape: schemaVersion 2, carrying
- // extensions + components + narrative.
- // /design-system/raw returns DESIGN.md markdown verbatim
- if (p === '/design-system.json' || p === '/design-system/raw') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
-
- const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
- const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
- const mdStat = statOrNull(mdPath);
- const jsonStat = statOrNull(jsonPath);
-
- if (p === '/design-system/raw') {
- if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
- res.end(fs.readFileSync(mdPath, 'utf-8'));
- return;
- }
-
- if (!mdStat && !jsonStat) {
- res.writeHead(404, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ present: false }));
- return;
- }
-
- const response = {
- present: true,
- hasMd: !!mdStat,
- hasSidecar: !!jsonStat,
- mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
- };
-
- if (mdStat) {
- try {
- response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
- } catch (err) {
- response.parseError = err.message;
- }
- }
-
- if (jsonStat) {
- try {
- response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
- } catch (err) {
- response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;
- }
- }
-
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(response));
- return;
- }
-
- // --- Source file (no-HMR fallback) ---
- if (p === '/source') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const filePath = url.searchParams.get('path');
- if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
- const absPath = path.resolve(process.cwd(), filePath);
- if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
- let content;
- try { content = fs.readFileSync(absPath, 'utf-8'); }
- catch { res.writeHead(404); res.end('File not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
- res.end(content);
- return;
- }
-
- // --- SSE: server→browser push (replaces WebSocket) ---
- if (p === '/events' && req.method === 'GET') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- 'Connection': 'keep-alive',
- });
- res.write('data: ' + JSON.stringify({
- type: 'connected',
- hasProjectContext: hasProjectContext(),
- }) + '\n\n');
-
- state.sseClients.add(res);
- clearTimeout(state.exitTimer);
-
- // Keepalive: SSE comment every 30s prevents silent connection drops.
- const heartbeat = setInterval(() => {
- try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
- }, SSE_HEARTBEAT_INTERVAL);
-
- req.on('close', () => {
- clearInterval(heartbeat);
- state.sseClients.delete(res);
- if (state.sseClients.size === 0) {
- clearTimeout(state.exitTimer);
- state.exitTimer = setTimeout(() => {
- if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
- }, 8000);
- }
- });
- return;
- }
-
- // --- Browser→server events (replaces WebSocket messages) ---
- if (p === '/events' && req.method === 'POST') {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const error = validateEvent(msg);
- if (error) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error }));
- return;
- }
- if (state.sessionStore && msg.id) {
- try {
- state.sessionStore.appendEvent(msg);
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
- return;
- }
- }
- if (msg.type !== 'checkpoint') enqueueEvent(msg);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
- return;
- }
-
- // --- Stop ---
- if (p === '/stop') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.end('stopping');
- shutdown();
- return;
- }
-
- // --- Agent poll ---
- if (p === '/poll' && req.method === 'GET') {
- handlePollGet(req, res, url);
- return;
- }
- if (p === '/poll' && req.method === 'POST') {
- handlePollPost(req, res);
- return;
- }
-
- res.writeHead(404); res.end('Not found');
- };
-}
-
-// ---------------------------------------------------------------------------
-// Agent poll endpoints (unchanged from WS version)
-// ---------------------------------------------------------------------------
-
-function handlePollGet(req, res, url) {
- const token = url.searchParams.get('token');
- if (token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
- const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
- const available = findAvailablePendingEvent();
- if (available) {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(leaseEvent(available, leaseMs)));
- return;
- }
- const poll = { resolve, leaseMs };
- const timer = setTimeout(() => {
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ type: 'timeout' }));
- }, timeout);
- function resolve(event) {
- clearTimeout(timer);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(event));
- }
- state.pendingPolls.push(poll);
- scheduleLeaseFlush();
- req.on('close', () => {
- clearTimeout(timer);
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- });
-}
-
-function handlePollPost(req, res) {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- acknowledgePendingEvent(msg.id);
- if (state.sessionStore && msg.id) {
- try {
- const eventType = msg.type === 'discard' || msg.type === 'discarded'
- ? 'discarded'
- : msg.type === 'complete'
- ? 'complete'
- : msg.type === 'error'
- ? 'agent_error'
- : 'agent_done';
- state.sessionStore.appendEvent({
- type: eventType,
- id: msg.id,
- file: msg.file,
- message: msg.message,
- carbonize: msg.data?.carbonize === true,
- });
- } catch { /* keep reply path best-effort; browser still needs SSE */ }
- }
- flushPendingPolls();
- // Forward the reply to the browser via SSE
- broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Lifecycle
-// ---------------------------------------------------------------------------
-
-let httpServer = null;
-
-function shutdown() {
- removeLiveServerInfo(process.cwd());
- if (state.leaseTimer) clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- if (state.sessionDir) {
- try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}
- }
- for (const res of state.sseClients) { try { res.end(); } catch {} }
- state.sseClients.clear();
- for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });
- state.pendingPolls.length = 0;
- if (httpServer) httpServer.close();
- process.exit(0);
-}
-
-// ---------------------------------------------------------------------------
-// Main
-// ---------------------------------------------------------------------------
-
-const args = process.argv.slice(2);
-
-if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-server.mjs [options]
-
-Start the live variant mode server (zero dependencies).
-
-Commands:
- (default) Start the server (foreground)
- stop Stop the server and remove the injected live.js script tag
- stop --keep-inject Stop the server only (leave the script tag in the HTML entry)
-
-Options:
- --background Start detached, print connection JSON to stdout, then exit
- --port=PORT Use a specific port (default: auto-detect starting at 8400)
- --keep-inject Only with stop: skip live-inject.mjs --remove
- --help Show this help
-
-Endpoints:
- /live.js Browser script (element picker + variant cycling)
- /detect.js Detection overlay (backwards compatible)
- /modern-screenshot.js Vendored modern-screenshot UMD build (lazy-loaded by live.js)
- /annotation POST raw image/png to stage a variant screenshot
- /events SSE stream (server→browser) + POST (browser→server)
- /poll Long-poll for agent CLI
- /source Raw source file reader (no-HMR fallback)
- /status Durable recovery status (token-protected)
- /health Health check`);
- process.exit(0);
-}
-
-if (args.includes('stop')) {
- const keepInject = args.includes('--keep-inject');
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);
- if (res.ok) console.log(`Stopped live server on port ${info.port}.`);
- } catch {
- console.log('No running live server found.');
- }
- if (!keepInject) {
- const injectPath = path.join(__dirname, 'live-inject.mjs');
- try {
- const out = execFileSync(process.execPath, [injectPath, '--remove'], {
- encoding: 'utf-8',
- cwd: process.cwd(),
- });
- const line = out.trim().split('\n').filter(Boolean).pop();
- if (line) {
- try {
- const j = JSON.parse(line);
- if (j.removed === true) {
- console.log(`Removed live script tag from ${j.file}.`);
- }
- } catch {
- /* ignore non-JSON lines */
- }
- }
- } catch (err) {
- const detail = err.stderr?.toString?.().trim?.()
- || err.stdout?.toString?.().trim?.()
- || err.message
- || String(err);
- console.warn(`Note: could not remove live script tag (${detail.split('\n')[0]})`);
- }
- }
- process.exit(0);
-}
-
-// --background: spawn a detached child server, wait for it to be ready,
-// print the connection JSON, then exit. This keeps the startup command
-// simple (no shell backgrounding or chained commands).
-if (args.includes('--background')) {
- const childArgs = args.filter(a => a !== '--background');
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), ...childArgs], {
- detached: true,
- stdio: 'ignore',
- cwd: process.cwd(),
- });
- child.unref();
-
- // Poll for the PID file (the child writes it once the HTTP server is listening).
- const deadline = Date.now() + 10_000;
- while (Date.now() < deadline) {
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- if (info.pid !== process.pid) {
- // Output JSON so the agent can read port + token from stdout.
- console.log(JSON.stringify(info));
- process.exit(0);
- }
- } catch { /* not ready yet */ }
- await new Promise(r => setTimeout(r, 200));
- }
- console.error('Timed out waiting for live server to start.');
- process.exit(1);
-}
-
-// Check for existing session
-const existingRecord = readLiveServerInfo(process.cwd());
-if (existingRecord?.info) {
- const existing = existingRecord.info;
- try {
- process.kill(existing.pid, 0);
- console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
- console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');
- process.exit(1);
- } catch {
- try { fs.unlinkSync(existingRecord.path); } catch {}
- }
-}
-
-state.token = randomUUID();
-state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });
-restorePendingEventsFromStore();
-const portArg = args.find(a => a.startsWith('--port='));
-state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
-// Annotation screenshots live in the project root so the agent's Read tool
-// doesn't trip a per-file permission prompt. Sessioned by token so concurrent
-// projects (or quick restarts) don't collide.
-const annotRoot = getLiveAnnotationsDir(process.cwd());
-fs.mkdirSync(annotRoot, { recursive: true });
-state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));
-
-const { detectScript, sessionPath, livePath } = loadBrowserScripts();
-httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));
-
-httpServer.listen(state.port, '127.0.0.1', () => {
- writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });
- const url = `http://localhost:${state.port}`;
- console.log(`\nImpeccable live server running on ${url}`);
- console.log(`Token: ${state.token}\n`);
- console.log(`Inject: <script src="${url}/live.js"><\/script>`);
- console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
-});
-
-process.on('SIGINT', shutdown);
-process.on('SIGTERM', shutdown);
@@ -1,254 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';
-
-const COMPLETED_PHASES = new Set(['completed', 'discarded']);
-
-export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {
- const rootDir = getLiveSessionsDir(cwd);
- const legacyRootDir = getLegacyLiveSessionsDir(cwd);
- fs.mkdirSync(rootDir, { recursive: true });
- const snapshotCache = new Map();
-
- function loadCachedOrRebuild(id) {
- const cached = snapshotCache.get(id);
- if (cached) return cached;
- const journalPath = getReadableJournalPath(id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- return rebuilt;
- }
-
- function getReadableJournalPath(id) {
- const primary = getJournalPath(rootDir, id);
- if (fs.existsSync(primary)) return primary;
- const legacy = getJournalPath(legacyRootDir, id);
- if (fs.existsSync(legacy)) return legacy;
- return primary;
- }
-
- return {
- rootDir,
- legacyRootDir,
- appendEvent(event) {
- const normalized = normalizeEvent(event, sessionId);
- const journalPath = getJournalPath(rootDir, normalized.id);
- const snapshotPath = getSnapshotPath(rootDir, normalized.id);
- const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);
- if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {
- fs.copyFileSync(legacyJournalPath, journalPath);
- }
- const prior = loadCachedOrRebuild(normalized.id);
- const seq = prior.nextSeq;
- const entry = {
- seq,
- id: normalized.id,
- type: normalized.type,
- ts: new Date().toISOString(),
- event: normalized,
- };
- fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');
- const next = applyEvent(prior.snapshot, entry, prior.diagnostics);
- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });
- writeSnapshot(snapshotPath, next);
- return next;
- },
- getSnapshot(id = sessionId, opts = {}) {
- if (!id) throw new Error('session id required');
- const journalPath = getReadableJournalPath(id);
- const snapshotPath = getSnapshotPath(rootDir, id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- writeSnapshot(snapshotPath, rebuilt.snapshot);
- if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;
- return rebuilt.snapshot;
- },
- listActiveSessions() {
- const ids = new Set();
- for (const dir of [legacyRootDir, rootDir]) {
- if (!fs.existsSync(dir)) continue;
- for (const name of fs.readdirSync(dir)) {
- if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));
- }
- }
- return [...ids]
- .sort()
- .map((id) => this.getSnapshot(id))
- .filter(Boolean);
- },
- };
-}
-
-function normalizeEvent(event, fallbackId) {
- if (!event || typeof event !== 'object') throw new Error('event object required');
- const id = event.id || fallbackId;
- if (!id || typeof id !== 'string') throw new Error('event id required');
- if (!event.type || typeof event.type !== 'string') throw new Error('event type required');
- return { ...event, id };
-}
-
-function getJournalPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.jsonl');
-}
-
-function getSnapshotPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.snapshot.json');
-}
-
-function safeSessionId(id) {
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);
- return id;
-}
-
-function baseSnapshot(id) {
- return {
- id,
- phase: 'new',
- pageUrl: null,
- sourceFile: null,
- expectedVariants: 0,
- arrivedVariants: 0,
- visibleVariant: null,
- paramValues: {},
- pendingEventSeq: null,
- pendingEvent: null,
- deliveryLease: null,
- checkpointRevision: 0,
- activeOwner: null,
- sourceMarkers: {},
- fallbackMode: null,
- annotationArtifacts: [],
- diagnostics: [],
- updatedAt: null,
- };
-}
-
-function rebuildSnapshotFromJournal(journalPath, id) {
- let snapshot = baseSnapshot(id);
- const diagnostics = [];
- let nextSeq = 1;
- if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };
-
- const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- if (!line.trim()) continue;
- try {
- const entry = JSON.parse(line);
- if (!entry || typeof entry !== 'object') throw new Error('entry is not object');
- if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);
- snapshot = applyEvent(snapshot, entry);
- } catch (err) {
- diagnostics.push({
- error: 'journal_parse_failed',
- line: i + 1,
- message: err.message,
- });
- }
- }
- snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];
- return { snapshot, diagnostics, nextSeq };
-}
-
-function applyEvent(snapshot, entry, inheritedDiagnostics = []) {
- const event = entry.event || entry;
- const next = {
- ...snapshot,
- paramValues: { ...(snapshot.paramValues || {}) },
- sourceMarkers: { ...(snapshot.sourceMarkers || {}) },
- annotationArtifacts: [...(snapshot.annotationArtifacts || [])],
- diagnostics: [...(snapshot.diagnostics || [])],
- updatedAt: entry.ts || new Date().toISOString(),
- };
-
- if (inheritedDiagnostics.length && next.diagnostics.length === 0) {
- next.diagnostics = [...inheritedDiagnostics];
- }
-
- switch (event.type) {
- case 'generate':
- next.phase = 'generate_requested';
- next.pageUrl = event.pageUrl ?? next.pageUrl;
- next.expectedVariants = event.count ?? next.expectedVariants;
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });
- break;
- case 'variants_ready':
- case 'agent_done':
- next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';
- next.sourceFile = event.file ?? next.sourceFile;
- next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- if (event.carbonize === true) {
- next.diagnostics.push({
- error: 'carbonize_cleanup_required',
- file: event.file || null,
- message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',
- });
- }
- break;
- case 'checkpoint':
- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {
- next.phase = event.phase ?? next.phase;
- next.checkpointRevision = event.revision ?? next.checkpointRevision;
- next.activeOwner = event.owner ?? next.activeOwner;
- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;
- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- } else {
- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });
- }
- break;
- case 'accept':
- case 'accept_intent':
- next.phase = 'accept_requested';
- next.visibleVariant = Number(event.variantId ?? next.visibleVariant);
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discard':
- next.phase = 'discard_requested';
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discarded':
- next.phase = 'discarded';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'complete':
- next.phase = 'completed';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'agent_error':
- next.phase = 'agent_error';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });
- break;
- default:
- next.diagnostics.push({ error: 'unknown_event_type', type: event.type });
- break;
- }
- return next;
-}
-
-function toPendingEvent(event) {
- const pending = { ...event };
- delete pending.token;
- return pending;
-}
-
-function upsertArtifact(artifacts, artifact) {
- if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {
- artifacts.push(artifact);
- }
-}
-
-function writeSnapshot(snapshotPath, snapshot) {
- fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');
-}
@@ -1,47 +0,0 @@
-#!/usr/bin/env node
-/**
- * Print durable recovery status for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function fetchServerStatus(info) {
- if (!info) return null;
- try {
- const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-export async function statusCli() {
- const info = readServerInfo();
- const server = await fetchServerStatus(info);
- const store = createLiveSessionStore({ cwd: process.cwd() });
- const activeSessions = store.listActiveSessions();
- const payload = {
- liveServer: server ? {
- status: server.status,
- port: server.port,
- connectedClients: server.connectedClients,
- pendingEvents: server.pendingEvents,
- } : null,
- activeSessions: server?.activeSessions || activeSessions,
- recoveryHint: server
- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'
- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',
- };
- console.log(JSON.stringify(payload, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {
- statusCli();
-}
@@ -1,632 +0,0 @@
-/**
- * CLI helper: find an element in source and wrap it in a variant container.
- *
- * Usage:
- * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
- *
- * Searches project files for the element matching the query (class name, ID, or
- * text snippet), wraps it with the variant scaffolding, and prints the file path
- * + line range where the agent should insert variant HTML.
- *
- * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-export async function wrapCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable wrap [options]
-
-Find an element in source and wrap it in a variant container.
-
-Required:
- --id ID Session ID for the variant wrapper
- --count N Number of expected variants (1-8)
-
-Element identification (at least one required):
- --element-id ID HTML id attribute of the element
- --classes A,B,C Comma-separated CSS class names
- --tag TAG Tag name (div, section, etc.)
- --query TEXT Fallback: raw text to search for
-
-Optional:
- --file PATH Source file to search in (skips auto-detection)
- --text TEXT Picked element's textContent. Used to disambiguate when
- classes/tag match multiple sibling elements (e.g. a list
- of <Card>s with the same className). Pass the first ~80
- chars of event.element.textContent.
- --help Show this help message
-
-Output (JSON):
- { file, startLine, endLine, insertLine, commentSyntax }
-
-The agent should insert variant HTML at insertLine.`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const count = parseInt(argVal(args, '--count') || '3');
- const elementId = argVal(args, '--element-id');
- const classes = argVal(args, '--classes');
- const tag = argVal(args, '--tag');
- const query = argVal(args, '--query');
- const filePath = argVal(args, '--file');
- const text = argVal(args, '--text');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!elementId && !classes && !query) {
- console.error('Need at least one of: --element-id, --classes, --query');
- process.exit(1);
- }
-
- // Build search queries in priority order (most specific first)
- const queries = buildSearchQueries(elementId, classes, tag, query);
-
- const genOpts = { cwd: process.cwd() };
-
- // Find the source file. Generated files are excluded from auto-search so we
- // don't silently write variants into a file the next build will wipe.
- let targetFile = filePath;
- let matchedQuery = null;
- if (!targetFile) {
- for (const q of queries) {
- targetFile = findFileWithQuery(q, process.cwd(), genOpts);
- if (targetFile) { matchedQuery = q; break; }
- }
- if (!targetFile) {
- // Nothing in source. Did the element show up in a generated file? That
- // tells the agent "fall back to the agent-driven flow" vs "element just
- // doesn't exist in this project."
- let generatedHit = null;
- for (const q of queries) {
- generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
- if (generatedHit) break;
- }
- if (generatedHit) {
- console.error(JSON.stringify({
- error: 'element_not_in_source',
- fallback: 'agent-driven',
- generatedMatch: path.relative(process.cwd(), generatedHit),
- hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
- }));
- } else {
- console.error(JSON.stringify({
- error: 'element_not_found',
- fallback: 'agent-driven',
- hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
- }));
- }
- process.exit(1);
- }
- } else {
- if (isGeneratedFile(targetFile, genOpts)) {
- console.error(JSON.stringify({
- error: 'file_is_generated',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
- hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- matchedQuery = queries[0];
- }
-
- const content = fs.readFileSync(targetFile, 'utf-8');
- const lines = content.split('\n');
-
- // Find the element, trying each query in priority order. When `--text` is
- // supplied, collect every candidate the queries surface and disambiguate
- // by the picked element's textContent. Without `--text`, fall back to the
- // legacy first-match behavior so unmodified callers keep working.
- let match = null;
- if (text) {
- const candidates = [];
- for (const q of queries) {
- const all = findAllElements(lines, q, tag);
- for (const c of all) {
- if (!candidates.some((x) => x.startLine === c.startLine)) {
- candidates.push(c);
- }
- }
- // Once a more-specific query (ID, full className combo) yielded a unique
- // result, stop — falling through to the loose tag+single-class query
- // would readmit the siblings we just disambiguated past.
- if (candidates.length === 1) break;
- }
- if (candidates.length === 0) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- if (candidates.length === 1) {
- match = candidates[0];
- } else {
- const filtered = filterByText(candidates, lines, text);
- if (filtered.length === 1) {
- match = filtered[0];
- } else if (filtered.length === 0) {
- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the
- // browser-side textContent doesn't appear literally in source. Fall
- // back to first-match rather than refusing — this is the same
- // behavior unmodified callers see, just preserved.
- match = candidates[0];
- } else {
- // Multiple candidates ALSO match the text. Truly ambiguous — refuse
- // rather than pick wrong, and hand the agent the candidate locations
- // so it can disambiguate by reading the file.
- console.error(JSON.stringify({
- error: 'element_ambiguous',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), targetFile),
- candidates: filtered.map((c) => ({
- startLine: c.startLine + 1,
- endLine: c.endLine + 1,
- })),
- hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- }
- } else {
- for (const q of queries) {
- match = findElement(lines, q, tag);
- if (match) break;
- }
- if (!match) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- }
-
- const { startLine, endLine } = match;
- const commentSyntax = detectCommentSyntax(targetFile);
- const styleMode = detectStyleMode(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- const indent = lines[startLine].match(/^(\s*)/)[1];
-
- // Extract the original element. Reindent under the wrapper while preserving
- // the relative depth between lines — `l.trimStart()` would strip ALL leading
- // whitespace and collapse e.g. `<aside>`/` <h1>`/`</aside>` (6/8/6 spaces)
- // to a single uniform indent, so on accept/discard the round-trip restores
- // the inner element at its parent's depth instead of nested inside it.
- // Strip only the COMMON minimum leading whitespace across the picked lines;
- // `deindentContent` on the accept side already mirrors this convention.
- const originalLines = lines.slice(startLine, endLine + 1);
- const originalBaseIndent = minLeadingSpaces(originalLines);
- const reindentOriginal = (extra) => originalLines
- .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
- .join('\n');
- const originalIndented = reindentOriginal(' ');
-
- // Wrapper attributes differ by syntax. HTML allows plain string attrs;
- // JSX requires object-literal style and parses string attrs as HTML (which
- // either type-errors or renders a literal CSS string).
- const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
-
- // JSX/TSX guard: the picked element occupies a single JSX child slot
- // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
- // any other expression position). Replacing it with `comment + <div> +
- // comment` yields three adjacent siblings — invalid JSX. We can't use a
- // Fragment `<></>` either: parents that clone children (Radix `asChild`,
- // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
- // they try to pass an `id` through.
- //
- // Solution: keep the wrapper `<div>` as the single JSX-slot child and
- // tuck both marker comments INSIDE it. accept/discard then expands its
- // replacement range to include the wrapper's `<div>` open / close lines
- // so the entire scaffold gets removed cleanly.
- const wrapperLines = isJsx ? [
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- reindentOriginal(' '),
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- indent + '</div>',
- ] : [
- indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- originalIndented,
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + '</div>',
- indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- ];
-
- // Replace the original element with the wrapper
- const newLines = [
- ...lines.slice(0, startLine),
- ...wrapperLines,
- ...lines.slice(endLine + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- // Calculate insert line (the "insert below this line" comment).
- // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
- // the insert marker (HTML: start-comment + outer-div + Original-comment +
- // original-div + content + close-original-div; JSX: outer-div +
- // start-comment + Original-comment + original-div + content +
- // close-original-div). Multi-line originals push the marker by their
- // extra line count.
- const insertLine = startLine + 6 + (originalLines.length - 1);
-
- console.log(JSON.stringify({
- file: path.relative(process.cwd(), targetFile),
- startLine: startLine + 1, // 1-indexed for the agent
- // wrapperLines is an array but one element (the original-content slot)
- // is a `\n`-joined multi-line string, so the actual file-row count is
- // wrapperLines.length + (originalLines.length - 1). Without the offset,
- // endLine pointed inside the wrapper for any picked element that
- // spanned more than one source line.
- endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexed
- insertLine: insertLine + 1, // 1-indexed: where variants go
- commentSyntax: commentSyntax,
- styleMode: styleMode.mode,
- styleTag: styleMode.styleTag,
- cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
- cssAuthoring: buildCssAuthoring(styleMode, count),
- originalLineCount: originalLines.length,
- }));
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-/**
- * Build search query strings in priority order (most specific first).
- * ID is most reliable, then specific class combos, then single classes, then raw query.
- */
-function buildSearchQueries(elementId, classes, tag, query) {
- const queries = [];
-
- // 1. ID is the most specific
- if (elementId) {
- queries.push('id="' + elementId + '"');
- }
-
- // 2. Full class attribute match (for elements with distinctive multi-class combos).
- // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
- // convention the file uses will match.
- if (classes) {
- const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
- if (classList.length > 1) {
- const joined = classList.join(' ');
- const sorted = [...classList].sort((a, b) => b.length - a.length);
- queries.push('class="' + joined + '"');
- queries.push('className="' + joined + '"');
- queries.push(sorted[0]); // most distinctive single class, fallback
- } else if (classList.length === 1) {
- queries.push(classList[0]);
- }
- }
-
- // 3. Tag + class combo (e.g., <section class="hero">).
- // Same dual-emit for JSX compatibility.
- if (tag && classes) {
- const firstClass = classes.split(',')[0].trim();
- queries.push('<' + tag + ' class="' + firstClass);
- queries.push('<' + tag + ' className="' + firstClass);
- }
-
- // 4. Raw fallback query
- if (query) {
- queries.push(query);
- }
-
- return queries;
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- // HTML, Vue, Svelte, Astro all use HTML comments
- return { open: '<!--', close: '-->' };
-}
-
-function detectStyleMode(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.astro') {
- return {
- mode: 'astro-global-prefixed',
- styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',
- };
- }
- return {
- mode: 'scoped',
- styleTag: '<style data-impeccable-css="SESSION_ID">',
- };
-}
-
-function buildCssSelectorPrefixExamples(styleMode, count) {
- if (styleMode !== 'astro-global-prefixed') return [];
- return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);
-}
-
-function buildCssAuthoring(styleMode, count) {
- const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
- if (styleMode.mode === 'astro-global-prefixed') {
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'global-prefixed',
- rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',
- selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),
- requirements: [
- 'Use the styleTag exactly; the is:inline attribute is required for this file.',
- 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',
- 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
- ],
- forbidden: [
- 'Do not use @scope for this styleMode.',
- ],
- };
- }
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'scope-rule',
- rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',
- selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),
- requirements: [
- 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',
- 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
- 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
- ],
- forbidden: [
- 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',
- 'Do not add is:inline to the style tag for this styleMode.',
- ],
- };
-}
-
-/**
- * Search project files for the query string (class name, ID, etc.)
- * Returns the first matching file path, or null.
- */
-function findFileWithQuery(query, cwd, genOpts = {}) {
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, query, seen, 0, genOpts);
- if (result) return result;
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth, genOpts) {
- if (depth > 5) return null; // don't go too deep
- const realDir = fs.realpathSync(dir);
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- // Check files first
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name).toLowerCase();
- if (!EXTENSIONS.includes(ext)) continue;
-
- const filePath = path.join(dir, entry.name);
- if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip unreadable files */ }
- }
-
- // Then recurse into directories. Always skip node_modules and .git (never
- // project content). dist/build/out are left to the isGeneratedFile guard so
- // the includeGenerated second-pass can still find the element there and
- // report `generatedMatch`.
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
- if (result) return result;
- }
-
- return null;
-}
-
-/**
- * Regex that matches a tag opener on a line. Allows the tag name to be
- * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
- * openers (e.g. `<section\n className="..."\n>`) are recognised.
- */
-const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
-
-/**
- * Find the element's start and end line in the file.
- *
- * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
- * `id="..."`), or a raw text snippet. Because a query can appear on a
- * continuation line of a multi-line tag (e.g. the `className="..."` row of a
- * `<section\n className="..."\n>` JSX tag), we walk backward from the match
- * line to find the actual tag opener. When `tag` is provided, opener candidates
- * must match that tag name.
- */
-/**
- * Return the smallest leading-whitespace count across a set of lines,
- * ignoring blank lines (whose indent isn't load-bearing). Used to compute
- * the common base indent of a multi-line picked element so reindenting
- * under the wrapper preserves the relative depth between lines.
- */
-function minLeadingSpaces(lines) {
- let min = Infinity;
- for (const l of lines) {
- if (l.trim() === '') continue;
- const m = l.match(/^(\s*)/);
- if (m && m[1].length < min) min = m[1].length;
- }
- return min === Infinity ? 0 : min;
-}
-
-function findElement(lines, query, tag = null) {
- // Iterate all matches — the first substring hit isn't always the right one.
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
-
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- // Skip lines already inside a variant wrapper
- if (lines[i].includes('data-impeccable-variant')) continue;
-
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
-
- const endLine = findClosingLine(lines, openerLine);
- return { startLine: openerLine, endLine };
- }
-
- return null;
-}
-
-/**
- * Like findElement, but returns every match. Used for ambiguity detection
- * when the agent passes --text: when the same className appears on multiple
- * sibling elements (a list of cards, repeated section variants, etc.),
- * first-match silently lands on the wrong branch. Returning all matches lets
- * the caller narrow by textContent or fail with a structured ambiguity error.
- */
-function findAllElements(lines, query, tag = null) {
- const out = [];
- const seen = new Set();
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- if (lines[i].includes('data-impeccable-variant')) continue;
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
- if (seen.has(openerLine)) continue; // multiple matches inside the same element
- seen.add(openerLine);
- const endLine = findClosingLine(lines, openerLine);
- out.push({ startLine: openerLine, endLine });
- }
- return out;
-}
-
-/**
- * Narrow a candidate set to those whose source body matches a meaningful
- * prefix of the picked element's textContent. The compare strips tags and
- * JSX expressions, then checks two whitespace normalizations side-by-side:
- *
- * - single-space ("hero two second card body")
- * - no-whitespace ("herotwosecondcardbody")
- *
- * Both are needed because `el.textContent` concatenates sibling text without
- * inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
- * `"Hero TwoSecond…"`), while the source has whitespace between tags. If
- * EITHER normalization matches, the candidate keeps. A snippet shorter than
- * 8 chars after stripping is too weak to disambiguate — the caller falls
- * back to first-match.
- */
-function filterByText(candidates, lines, text) {
- const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
- // Too short to disambiguate. Return [] so the caller's `filtered.length
- // === 0` branch fires (fall back to first-match) — the previous
- // `candidates.slice()` return forced `filtered.length > 1` and surfaced
- // a spurious `element_ambiguous` error on every short-text picker event
- // with multiple candidates.
- if (trimmed.length < 8) return [];
- const targetSpaced = trimmed;
- const targetCompact = trimmed.replace(/\s+/g, '');
-
- return candidates.filter((c) => {
- const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
- const inner = body
- .replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
- .replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
- .toLowerCase();
- const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
- const sourceCompact = inner.replace(/\s+/g, '');
- return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
- });
-}
-
-/**
- * Resolve a match line to the real tag opener. If the match line itself opens
- * a tag, return it. Otherwise walk up to 10 lines backward looking for the
- * first tag opener. If `tag` is specified, the opener must match that tag
- * name; an opener with a different tag name aborts the backward walk for this
- * match (we don't jump across element boundaries).
- *
- * Returns the line index of the opener, or -1 if none can be resolved.
- */
-function findOpenerLine(lines, matchLine, tag) {
- const self = lines[matchLine].match(OPENER_RE);
- if (self) {
- if (!tag || self[1] === tag) return matchLine;
- return -1;
- }
- const MAX_BACKWALK = 10;
- for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
- const opener = lines[i].match(OPENER_RE);
- if (!opener) continue;
- if (!tag || opener[1] === tag) return i;
- // Different tag name than requested — abort; we're inside a non-target opener.
- return -1;
- }
- return -1;
-}
-
-/**
- * Starting from a line with an opening tag, find the line with the matching
- * closing tag by counting tag nesting depth.
- */
-function findClosingLine(lines, start) {
- const openMatch = lines[start].match(OPENER_RE);
- if (!openMatch) return start; // caller passed a non-opener; nothing to span
-
- const tagName = openMatch[1];
- let depth = 0;
- const openRe = new RegExp('<' + tagName + '(?=[\\s/>]|$)', 'g');
- const selfCloseRe = new RegExp('<' + tagName + '[^>]*/>', 'g');
- const closeRe = new RegExp('</' + tagName + '\\s*>', 'g');
-
- for (let i = start; i < lines.length; i++) {
- const line = lines[i];
- const opens = (line.match(openRe) || []).length;
- const selfCloses = (line.match(selfCloseRe) || []).length;
- const closes = (line.match(closeRe) || []).length;
-
- depth += opens - selfCloses - closes;
-
- if (depth <= 0) return i;
- }
-
- // If we can't find the close, return a reasonable guess
- return Math.min(start + 50, lines.length - 1);
-}
-
-// Auto-execute when run directly (node live-wrap.mjs ...)
-const _running = process.argv[1];
-if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {
- wrapCli();
-}
-
-// Test exports (used by tests/live-wrap.test.mjs)
-export { buildSearchQueries, findElement, findClosingLine, detectCommentSyntax };
@@ -1,247 +0,0 @@
-/**
- * CLI entry point: prepare everything needed to enter the live variant poll loop.
- *
- * Does (all in one command):
- * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)
- * 2. Start the live server in the background (or reuse a running one)
- * 3. Inject the browser script tag into the project's entry file
- * 4. Read PRODUCT.md / DESIGN.md for project context
- * 5. Print a single JSON blob with everything the agent needs
- *
- * After this, the agent's only remaining steps are:
- * - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll
- * - Enter the poll loop: `node live-poll.mjs`
- *
- * Usage:
- * node live.mjs # Prepare everything, print JSON, exit
- * node live.mjs --help
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { loadContext } from './load-context.mjs';
-import { resolveFiles } from './live-inject.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-async function liveCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live.mjs
-
-Prepare everything for live variant mode in a single command:
- - Checks .impeccable/live/config.json (required, created once per project)
- - Starts (or reuses) the live server in the background
- - Injects the browser script tag
- - Reads PRODUCT.md / DESIGN.md for project context
-
-On success, prints a JSON blob with:
- { ok, serverPort, serverToken, pageFile, hasContext, context }
-
-On config_missing, prints:
- { ok: false, error: "config_missing", configPath, hint }
-
-The agent should then:
- 1. If config_missing, create the config and re-run this script
- 2. Optionally open the project's dev/preview URL in the browser (see reference/live.md—not serverPort)
- 3. Enter the poll loop: node live-poll.mjs`);
- process.exit(0);
- }
-
- // 1. Check config (fail fast if missing — no point starting anything else)
- const checkOut = runScript('live-inject.mjs', ['--check']);
- const checkResult = safeParse(checkOut);
- if (!checkResult || !checkResult.ok) {
- console.log(JSON.stringify(checkResult || { ok: false, error: 'check_failed', raw: checkOut }));
- process.exit(0);
- }
-
- // 2. Start server (or reuse existing)
- const serverInfo = ensureServerRunning();
- if (!serverInfo) {
- console.log(JSON.stringify({ ok: false, error: 'server_start_failed' }));
- process.exit(1);
- }
-
- // 3. Inject the script tag at the current port
- const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)]);
- const injectResult = safeParse(injectOut);
- if (!injectResult || !injectResult.ok) {
- console.log(JSON.stringify({
- ok: false,
- error: 'inject_failed',
- detail: injectResult || injectOut,
- serverPort: serverInfo.port,
- }));
- process.exit(1);
- }
-
- // 4. Load PRODUCT.md + DESIGN.md context (auto-migrates legacy .impeccable.md)
- const ctx = loadContext(process.cwd());
-
- // 5. Compute drift-heal: compare resolved inject targets against the
- // project's HTML files. Orphans are HTML files not covered by config.
- // Warning only — the agent decides whether to act.
- const resolvedFiles = resolveFiles(process.cwd(), checkResult.config);
- const drift = scanForDrift(process.cwd(), resolvedFiles, checkResult.config);
-
- // 6. Emit everything the agent needs
- console.log(JSON.stringify({
- ok: true,
- serverPort: serverInfo.port,
- serverToken: serverInfo.token,
- pageFiles: resolvedFiles,
- configDrift: drift,
- hasProduct: ctx.hasProduct,
- product: ctx.product,
- productPath: ctx.productPath,
- hasDesign: ctx.hasDesign,
- design: ctx.design,
- designPath: ctx.designPath,
- migrated: ctx.migrated,
- }, null, 2));
-}
-
-/**
- * Drift-heal scan. Walks the project for HTML files under common
- * page-source directories (public/, src/, app/, pages/) and reports any
- * that aren't covered by the resolved inject targets. This is purely
- * advisory — the agent can ignore it, or suggest the user add the
- * orphans to config.files.
- *
- * Skipped if config.files already contains at least one glob pattern
- * covering everything in practice (signaled by the orphan count being 0).
- */
-function scanForDrift(rootDir, resolvedFiles, config) {
- const SCAN_ROOTS = ['public', 'src', 'app', 'pages'];
- const IGNORE_DIRS = new Set([
- 'node_modules', '.git', '.next', '.nuxt', '.svelte-kit', '.astro',
- '.turbo', '.vercel', '.cache', 'coverage', 'dist', 'build',
- ]);
-
- const resolvedSet = new Set(resolvedFiles.map((f) => f.split(path.sep).join('/')));
-
- // Files matching the user's `exclude` globs are intentional omissions,
- // not drift. Compile them to regexes so the orphan list stays signal.
- const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
- .map((p) => globToRegex(p));
- const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
-
- const orphans = [];
-
- const walk = (dir, relBase) => {
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
- for (const e of entries) {
- const rel = relBase ? `${relBase}/${e.name}` : e.name;
- if (e.isDirectory()) {
- if (IGNORE_DIRS.has(e.name) || e.name.startsWith('.')) continue;
- walk(path.join(dir, e.name), rel);
- } else if (e.isFile() && e.name.endsWith('.html')) {
- if (resolvedSet.has(rel)) continue;
- if (isUserExcluded(rel)) continue;
- orphans.push(rel);
- }
- }
- };
-
- for (const root of SCAN_ROOTS) {
- const abs = path.join(rootDir, root);
- if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
- walk(abs, root);
- }
- }
-
- if (orphans.length === 0) return null;
- const capped = orphans.slice(0, 20);
- return {
- orphans: capped,
- orphanCount: orphans.length,
- hint: `${orphans.length} HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like "public/**/*.html".`,
- };
-}
-
-/**
- * Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
- * to avoid a circular import (live-inject.mjs already imports nothing
- * from live.mjs). The two must stay in sync.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
- else { re += '.*'; i += 2; }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function runScript(name, args) {
- const scriptPath = path.join(__dirname, name);
- const cmd = `node "${scriptPath}" ${args.map(a => `"${a}"`).join(' ')}`;
- try {
- return execSync(cmd, { encoding: 'utf-8', cwd: process.cwd(), timeout: 15_000 });
- } catch (err) {
- // execSync throws on non-zero exit; return stdout if any
- return err.stdout || err.message || '';
- }
-}
-
-function safeParse(out) {
- try { return JSON.parse(String(out).trim()); } catch { return null; }
-}
-
-/**
- * Return { pid, port, token } for the running live server, starting one if needed.
- */
-function ensureServerRunning() {
- // Try to reuse an existing server
- try {
- const existing = readLiveServerInfo(process.cwd())?.info;
- if (existing && existing.pid) {
- try {
- process.kill(existing.pid, 0); // throws if dead
- return existing;
- } catch { /* stale PID file — the server script will clean it up */ }
- }
- } catch { /* no PID file */ }
-
- // Start a new server
- const out = runScript('live-server.mjs', ['--background']);
- return safeParse(out);
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live.mjs') || _running?.endsWith('live.mjs/')) {
- liveCli();
-}
@@ -1,141 +0,0 @@
-/**
- * Shared context loader for every impeccable command that needs to know
- * "who is this for" and "what does this look like".
- *
- * Input: project root (process.cwd()).
- *
- * Output (JSON to stdout):
- * {
- * hasProduct: boolean, // PRODUCT.md found (or auto-migrated)
- * product: string | null, // PRODUCT.md contents
- * productPath: string | null, // relative path
- * hasDesign: boolean, // DESIGN.md found
- * design: string | null, // DESIGN.md contents
- * designPath: string | null,
- * migrated: boolean, // true if we auto-renamed .impeccable.md -> PRODUCT.md
- * contextDir: string, // absolute path of the directory the files were found in
- * }
- *
- * Filename matching is case-insensitive for PRODUCT.md and DESIGN.md. The
- * Google DESIGN.md convention is uppercase at repo root; Kiro-style and
- * lowercase variants are also matched so users don't get punished for case.
- *
- * Lookup directory resolution (first match wins):
- * 1. process.env.IMPECCABLE_CONTEXT_DIR (absolute or relative to cwd)
- * 2. cwd, if PRODUCT.md / DESIGN.md / .impeccable.md is there (back-compat)
- * 3. Auto-fallback subdirectories of cwd: .agents/context/, then docs/
- * 4. cwd as a default "no context found" location
- *
- * Legacy `.impeccable.md` -> PRODUCT.md migration only fires at cwd root;
- * fallback directories are read-only as far as auto-rename is concerned.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
-const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
-const LEGACY_NAMES = ['.impeccable.md'];
-const FALLBACK_DIRS = ['.agents/context', 'docs'];
-
-/**
- * Resolve the directory that holds PRODUCT.md / DESIGN.md for
- * this project. Exported so other scripts (e.g. live-server.mjs) can read the
- * design files from the same location the loader uses.
- */
-export function resolveContextDir(cwd = process.cwd()) {
- // 1. Explicit override
- const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
- if (envDir && envDir.trim()) {
- const trimmed = envDir.trim();
- return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- }
-
- // 2. cwd wins if any canonical or legacy file is there. We check legacy too
- // so the auto-migration path in loadContext stays predictable.
- if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES, ...LEGACY_NAMES])) {
- return cwd;
- }
-
- // 3. Auto-fallback subdirs. Match if PRODUCT.md or DESIGN.md is present;
- // legacy `.impeccable.md` does not pull the lookup into a fallback dir.
- for (const rel of FALLBACK_DIRS) {
- const candidate = path.resolve(cwd, rel);
- if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
- return candidate;
- }
- }
-
- // 4. Nothing found — keep the historical "default to cwd" behaviour so the
- // caller's `hasProduct === false` branch still fires the same way.
- return cwd;
-}
-
-export function loadContext(cwd = process.cwd()) {
- let migrated = false;
- const contextDir = resolveContextDir(cwd);
-
- // 1. Look for PRODUCT.md (case-insensitive) in the resolved dir
- let productPath = firstExisting(contextDir, PRODUCT_NAMES);
-
- // 2. Legacy: if no PRODUCT.md but .impeccable.md exists at cwd root, rename
- // it in place. We only migrate at the root — fallback dirs are read-only
- // so we don't surprise users by mutating files under docs/ or .agents/.
- if (!productPath && contextDir === cwd) {
- const legacyPath = firstExisting(cwd, LEGACY_NAMES);
- if (legacyPath) {
- const newPath = path.join(cwd, 'PRODUCT.md');
- try {
- fs.renameSync(legacyPath, newPath);
- productPath = newPath;
- migrated = true;
- } catch {
- // Rename failed (permissions, etc.) — fall back to reading legacy in place
- productPath = legacyPath;
- }
- }
- }
-
- // 3. DESIGN.md (case-insensitive)
- const designPath = firstExisting(contextDir, DESIGN_NAMES);
-
- const product = productPath ? safeRead(productPath) : null;
- const design = designPath ? safeRead(designPath) : null;
-
- return {
- hasProduct: !!product,
- product,
- productPath: productPath ? path.relative(cwd, productPath) : null,
- hasDesign: !!design,
- design,
- designPath: designPath ? path.relative(cwd, designPath) : null,
- migrated,
- contextDir,
- };
-}
-
-function firstExisting(dir, names) {
- for (const name of names) {
- const abs = path.join(dir, name);
- if (fs.existsSync(abs)) return abs;
- }
- return null;
-}
-
-function safeRead(p) {
- try { return fs.readFileSync(p, 'utf-8'); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// CLI mode — print the context as JSON
-// ---------------------------------------------------------------------------
-
-function cli() {
- const result = loadContext(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('load-context.mjs') || _running?.endsWith('load-context.mjs/')) {
- cli();
-}
@@ -1,14 +0,0 @@
@@ -1,214 +0,0 @@
-#!/usr/bin/env node
-/**
- * Pin/unpin sub-commands as standalone skill shortcuts.
- *
- * Usage:
- * node <scripts_path>/pin.mjs pin <command>
- * node <scripts_path>/pin.mjs unpin <command>
- *
- * `pin audit` creates a lightweight /audit skill that redirects to /impeccable audit.
- * `unpin audit` removes that shortcut.
- *
- * The script discovers harness directories (.claude/skills, .cursor/skills, etc.)
- * in the project root and creates/removes the pin in all of them.
- */
-
-import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
-import { join, resolve, dirname } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-// All known harness directories
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Valid sub-command names
-const VALID_COMMANDS = [
- 'craft', 'teach', 'extract', 'document', 'shape',
- 'critique', 'audit',
- 'polish', 'bolder', 'quieter', 'distill', 'harden', 'onboard', 'live',
- 'animate', 'colorize', 'typeset', 'layout', 'delight', 'overdrive',
- 'clarify', 'adapt', 'optimize',
-];
-
-// Marker to identify pinned skills (so unpin doesn't delete user skills)
-const PIN_MARKER = '<!-- impeccable-pinned-skill -->';
-
-/**
- * Walk up from startDir to find a project root.
- */
-function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- while (dir !== '/') {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Find harness skill directories that have an impeccable skill installed.
- */
-function findHarnessDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const skillsDir = join(projectRoot, harness, 'skills');
- // Only pin in harness dirs that already have impeccable installed
- const impeccableDir = join(skillsDir, 'impeccable');
- if (existsSync(impeccableDir) || existsSync(join(skillsDir, 'i-impeccable'))) {
- dirs.push(skillsDir);
- }
- }
- return dirs;
-}
-
-/**
- * Load command metadata (descriptions for pinned skills).
- */
-function loadCommandMetadata() {
- const metadataPath = join(__dirname, 'command-metadata.json');
- if (existsSync(metadataPath)) {
- return JSON.parse(readFileSync(metadataPath, 'utf-8'));
- }
- return {};
-}
-
-/**
- * Generate a pinned skill's SKILL.md content.
- */
-function generatePinnedSkill(command, metadata) {
- const desc = metadata[command]?.description || `Shortcut for /impeccable ${command}.`;
- const hint = metadata[command]?.argumentHint || '[target]';
-
- return `---
-name: ${command}
-description: "${desc}"
-argument-hint: "${hint}"
-user-invocable: true
----
-
-${PIN_MARKER}
-
-This is a pinned shortcut for \`{{command_prefix}}impeccable ${command}\`.
-
-Invoke {{command_prefix}}impeccable ${command}, passing along any arguments provided here, and follow its instructions.
-`;
-}
-
-/**
- * Pin a command: create shortcut skill in all harness dirs.
- */
-function pin(command, projectRoot) {
- const metadata = loadCommandMetadata();
- const harnessDirs = findHarnessDirs(projectRoot);
-
- if (harnessDirs.length === 0) {
- console.log('No harness directories with impeccable installed found.');
- return false;
- }
-
- const content = generatePinnedSkill(command, metadata);
- let created = 0;
-
- for (const skillsDir of harnessDirs) {
- // Check if skill already exists (and isn't a pin)
- const skillDir = join(skillsDir, command);
- if (existsSync(skillDir)) {
- const existingMd = join(skillDir, 'SKILL.md');
- if (existsSync(existingMd)) {
- const existing = readFileSync(existingMd, 'utf-8');
- if (!existing.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (non-pinned skill already exists)`);
- continue;
- }
- }
- }
-
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(join(skillDir, 'SKILL.md'), content, 'utf-8');
- console.log(` + ${skillDir}`);
- created++;
- }
-
- if (created > 0) {
- console.log(`\nPinned '${command}' as a standalone shortcut in ${created} location(s).`);
- console.log(`You can now use /${command} directly.`);
- }
-
- return created > 0;
-}
-
-/**
- * Unpin a command: remove shortcut skill from all harness dirs.
- */
-function unpin(command, projectRoot) {
- const harnessDirs = findHarnessDirs(projectRoot);
- let removed = 0;
-
- for (const skillsDir of harnessDirs) {
- const skillDir = join(skillsDir, command);
- if (!existsSync(skillDir)) continue;
-
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) continue;
-
- // Safety: only remove if it's a pinned skill
- const content = readFileSync(skillMd, 'utf-8');
- if (!content.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (not a pinned skill)`);
- continue;
- }
-
- rmSync(skillDir, { recursive: true, force: true });
- console.log(` - ${skillDir}`);
- removed++;
- }
-
- if (removed > 0) {
- console.log(`\nUnpinned '${command}' from ${removed} location(s).`);
- console.log(`Use /impeccable ${command} to access it.`);
- } else {
- console.log(`No pinned '${command}' shortcut found.`);
- }
-
- return removed > 0;
-}
-
-// --- CLI ---
-const [,, action, command] = process.argv;
-
-if (!action || !command) {
- console.log('Usage: node pin.mjs <pin|unpin> <command>');
- console.log(`\nAvailable commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-if (action !== 'pin' && action !== 'unpin') {
- console.error(`Unknown action: ${action}. Use 'pin' or 'unpin'.`);
- process.exit(1);
-}
-
-if (!VALID_COMMANDS.includes(command)) {
- console.error(`Unknown command: ${command}`);
- console.error(`Available commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-const root = findProjectRoot();
-
-if (action === 'pin') {
- pin(command, root);
-} else {
- unpin(command, root);
-}
@@ -1,169 +0,0 @@
----
-name: impeccable
-description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
-version: 3.1.1
-user-invocable: true
-argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · teach|document|extract|live] [target]"
-license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
-allowed-tools:
- - Bash(npx impeccable *)
----
-
-Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
-
-## Setup
-
-Before any design work or file edits:
-
-1. Load context (PRODUCT.md / DESIGN.md) via the loader script.
-2. Identify the register and load the matching register reference (brand.md or product.md).
-3. **If the user invoked a sub-command (e.g. `craft`, `shape`, `audit`), load its reference file too.** This is non-negotiable: `craft` without `craft.md` loaded means you'll skip the shape-and-confirm step the user expects.
-
-Skipping these produces generic output that ignores the project.
-
-### 1. Context gathering
-
-Two files, case-insensitive. The loader looks at the project root by default and falls back to `.agents/context/` and `docs/` if the root is clean. Override with `IMPECCABLE_CONTEXT_DIR=path/to/dir` (absolute or relative to cwd).
-
-- **PRODUCT.md**: required. Users, brand, tone, anti-references, strategic principles.
-- **DESIGN.md**: optional, strongly recommended. Colors, typography, elevation, components.
-
-Load both in one call:
-
-```bash
-node .rovodev/skills/impeccable/scripts/load-context.mjs
-```
-
-Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`. The output's `contextDir` field tells you where the files were resolved from.
-
-If the output is already in this session's conversation history, don't re-run. Exceptions requiring a fresh load: you just ran `/impeccable teach` or `/impeccable document` (they rewrite the files), or the user manually edited one.
-
-`/impeccable live` already warms context via `live.mjs`. If you've run `live.mjs`, don't also run `load-context.mjs` this session.
-
-If PRODUCT.md is missing, empty, or placeholder (`[TODO]` markers, <200 chars): run `/impeccable teach`, then resume the user's original task with the fresh context. If the original task was `/impeccable craft`, resume into `/impeccable shape` before any implementation work.
-
-If DESIGN.md is missing: nudge once per session (*"Run `/impeccable document` for more on-brand output"*), then proceed.
-
-### 2. Register
-
-Every design task is **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboard, tool: design SERVES the product).
-
-Identify before designing. Priority: (1) cue in the task itself ("landing page" vs "dashboard"); (2) the surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. First match wins.
-
-If PRODUCT.md lacks the `register` field (legacy), infer it once from its "Users" and "Product Purpose" sections, then cache the inferred value for the session. Suggest the user run `/impeccable teach` to add the field explicitly.
-
-Load the matching reference: [reference/brand.md](reference/brand.md) or [reference/product.md](reference/product.md). The shared design laws below apply to both.
-
-## Shared design laws
-
-Apply to every design, both registers. Match implementation complexity to the aesthetic vision: maximalism needs elaborate code, minimalism needs precision. Interpret creatively. Vary across projects; never converge on the same choices. Rovo Dev is capable of extraordinary work. Don't hold back.
-
-### Color
-
-- Use OKLCH. Reduce chroma as lightness approaches 0 or 100; high chroma at extremes looks garish.
-- Never use `#000` or `#fff`. Tint every neutral toward the brand hue (chroma 0.005–0.01 is enough).
-- Pick a **color strategy** before picking colors. Four steps on the commitment axis:
- - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism.
- - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages.
- - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz.
- - **Drenched**: the surface IS the color. Brand heroes, campaign pages.
-- The "one accent ≤10%" rule is Restrained only. Committed / Full palette / Drenched exceed it on purpose. Don't collapse every design to Restrained by reflex.
-
-### Theme
-
-Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe."
-
-Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does.
-
-"Observability dashboard" does not force an answer. "SRE glancing at incident severity on a 27-inch monitor at 2am in a dim room" does. Run the sentence, not the category.
-
-### Typography
-
-- Cap body line length at 65–75ch.
-- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales.
-
-### Layout
-
-- Vary spacing for rhythm. Same padding everywhere is monotony.
-- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
-- Don't wrap everything in a container. Most things don't need one.
-
-### Motion
-
-- Don't animate CSS layout properties.
-- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
-
-### Absolute bans
-
-Match-and-refuse. If you're about to write any of these, rewrite the element with different structure.
-
-- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing.
-- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size.
-- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing.
-- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché.
-- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly.
-- **Modal as first thought.** Modals are usually laziness. Exhaust inline / progressive alternatives first.
-
-### Copy
-
-- Every word earns its place. No restated headings, no intros that repeat the title.
-- **No em dashes.** Use commas, colons, semicolons, periods, or parentheses. Also not `--`.
-
-### The AI slop test
-
-If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference.
-
-**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses.
-
-- **First-order:** if someone could guess the theme + palette from the category alone ("observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black"), it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
-- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families.
-
-## Commands
-
-| Command | Category | Description | Reference |
-|---|---|---|---|
-| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) |
-| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) |
-| `teach` | Build | Set up PRODUCT.md and DESIGN.md context | [reference/teach.md](reference/teach.md) |
-| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) |
-| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) |
-| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) |
-| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) |
-| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) |
-| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) |
-| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) |
-| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) |
-| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) |
-| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) |
-| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) |
-| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) |
-| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) |
-| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) |
-| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) |
-| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) |
-| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) |
-| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) |
-| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
-| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
-
-### Routing rules
-
-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
-3. **First word doesn't match**: general design invocation. Apply the setup steps, shared design laws, and the loaded register reference, using the full argument as context.
-
-Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `/impeccable`.
-
-If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `teach` as a blocker, finish teach, refresh context, then resume the original command and target.
-
-## Pin / Unpin
-
-**Pin** creates a standalone shortcut so `/<command>` invokes `/impeccable <command>` directly. **Unpin** removes it. The script writes to every harness directory present in the project.
-
-```bash
-node .rovodev/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
-```
-
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
@@ -1,190 +0,0 @@
-> **Additional context needed**: target platforms/devices and usage contexts.
-
-Adapt an existing design to a different context: another screen size, device, platform, or use case. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context.
-
-
----
-
-## Assess Adaptation Challenge
-
-Understand what needs adaptation and why:
-
-1. **Identify the source context**:
- - What was it designed for originally? (Desktop web? Mobile app?)
- - What assumptions were made? (Large screen? Mouse input? Fast connection?)
- - What works well in current context?
-
-2. **Understand target context**:
- - **Device**: Mobile, tablet, desktop, TV, watch, print?
- - **Input method**: Touch, mouse, keyboard, voice, gamepad?
- - **Screen constraints**: Size, resolution, orientation?
- - **Connection**: Fast wifi, slow 3G, offline?
- - **Usage context**: On-the-go vs desk, quick glance vs focused reading?
- - **User expectations**: What do users expect on this platform?
-
-3. **Identify adaptation challenges**:
- - What won't fit? (Content, navigation, features)
- - What won't work? (Hover states on touch, tiny touch targets)
- - What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop)
-
-**CRITICAL**: Adaptation is rethinking the experience for the new context, not scaling pixels.
-
-## Plan Adaptation Strategy
-
-Create context-appropriate strategy:
-
-### Mobile Adaptation (Desktop → Mobile)
-
-**Layout Strategy**:
-- Single column instead of multi-column
-- Vertical stacking instead of side-by-side
-- Full-width components instead of fixed widths
-- Bottom navigation instead of top/side navigation
-
-**Interaction Strategy**:
-- Touch targets 44x44px minimum (not hover-dependent)
-- Swipe gestures where appropriate (lists, carousels)
-- Bottom sheets instead of dropdowns
-- Thumbs-first design (controls within thumb reach)
-- Larger tap areas with more spacing
-
-**Content Strategy**:
-- Progressive disclosure (don't show everything at once)
-- Prioritize primary content (secondary content in tabs/accordions)
-- Shorter text (more concise)
-- Larger text (16px minimum)
-
-**Navigation Strategy**:
-- Hamburger menu or bottom navigation
-- Reduce navigation complexity
-- Sticky headers for context
-- Back button in navigation flow
-
-### Tablet Adaptation (Hybrid Approach)
-
-**Layout Strategy**:
-- Two-column layouts (not single or three-column)
-- Side panels for secondary content
-- Master-detail views (list + detail)
-- Adaptive based on orientation (portrait vs landscape)
-
-**Interaction Strategy**:
-- Support both touch and pointer
-- Touch targets 44x44px but allow denser layouts than phone
-- Side navigation drawers
-- Multi-column forms where appropriate
-
-### Desktop Adaptation (Mobile → Desktop)
-
-**Layout Strategy**:
-- Multi-column layouts (use horizontal space)
-- Side navigation always visible
-- Multiple information panels simultaneously
-- Fixed widths with max-width constraints (don't stretch to 4K)
-
-**Interaction Strategy**:
-- Hover states for additional information
-- Keyboard shortcuts
-- Right-click context menus
-- Drag and drop where helpful
-- Multi-select with Shift/Cmd
-
-**Content Strategy**:
-- Show more information upfront (less progressive disclosure)
-- Data tables with many columns
-- Richer visualizations
-- More detailed descriptions
-
-### Print Adaptation (Screen → Print)
-
-**Layout Strategy**:
-- Page breaks at logical points
-- Remove navigation, footer, interactive elements
-- Black and white (or limited color)
-- Proper margins for binding
-
-**Content Strategy**:
-- Expand shortened content (show full URLs, hidden sections)
-- Add page numbers, headers, footers
-- Include metadata (print date, page title)
-- Convert charts to print-friendly versions
-
-### Email Adaptation (Web → Email)
-
-**Layout Strategy**:
-- Narrow width (600px max)
-- Single column only
-- Inline CSS (no external stylesheets)
-- Table-based layouts (for email client compatibility)
-
-**Interaction Strategy**:
-- Large, obvious CTAs (buttons not text links)
-- No hover states (not reliable)
-- Deep links to web app for complex interactions
-
-## Implement Adaptations
-
-Apply changes systematically:
-
-### Responsive Breakpoints
-
-Choose appropriate breakpoints:
-- Mobile: 320px-767px
-- Tablet: 768px-1023px
-- Desktop: 1024px+
-- Or content-driven breakpoints (where design breaks)
-
-### Layout Adaptation Techniques
-
-- **CSS Grid/Flexbox**: Reflow layouts automatically
-- **Container Queries**: Adapt based on container, not viewport
-- **`clamp()`**: Fluid sizing between min and max
-- **Media queries**: Different styles for different contexts
-- **Display properties**: Show/hide elements per context
-
-### Touch Adaptation
-
-- Increase touch target sizes (44x44px minimum)
-- Add more spacing between interactive elements
-- Remove hover-dependent interactions
-- Add touch feedback (ripples, highlights)
-- Consider thumb zones (easier to reach bottom than top)
-
-### Content Adaptation
-
-- Use `display: none` sparingly (still downloads)
-- Progressive enhancement (core content first, enhancements on larger screens)
-- Lazy loading for off-screen content
-- Responsive images (`srcset`, `picture` element)
-
-### Navigation Adaptation
-
-- Transform complex nav to hamburger/drawer on mobile
-- Bottom nav bar for mobile apps
-- Persistent side navigation on desktop
-- Breadcrumbs on smaller screens for context
-
-**IMPORTANT**: Test on real devices. Device emulation in DevTools is helpful but not perfect.
-
-**NEVER**:
-- Hide core functionality on mobile (if it matters, make it work)
-- Assume desktop = powerful device (consider accessibility, older machines)
-- Use different information architecture across contexts (confusing)
-- Break user expectations for platform (mobile users expect mobile patterns)
-- Forget landscape orientation on mobile/tablet
-- Use generic breakpoints blindly (use content-driven breakpoints)
-- Ignore touch on desktop (many desktop devices have touch)
-
-## Verify Adaptations
-
-Test thoroughly across contexts:
-
-- **Real devices**: Test on actual phones, tablets, desktops
-- **Different orientations**: Portrait and landscape
-- **Different browsers**: Safari, Chrome, Firefox, Edge
-- **Different OS**: iOS, Android, Windows, macOS
-- **Different input methods**: Touch, mouse, keyboard
-- **Edge cases**: Very small screens (320px), very large screens (4K)
-- **Slow connections**: Test on throttled network
-
-When the adaptation feels native to each context, hand off to `/impeccable polish` for the final pass.
@@ -1,175 +0,0 @@
-> **Additional context needed**: performance constraints.
-
-Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it.
-
----
-
-## Register
-
-Brand: orchestrated page-load sequences, staggered reveals, scroll-driven animation. Motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions.
-
-Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it.
-
----
-
-## Assess Animation Opportunities
-
-Analyze where motion would improve the experience:
-
-1. **Identify static areas**:
- - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.)
- - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes)
- - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious
- - **Lack of delight**: Functional but joyless interactions
- - **Missed guidance**: Opportunities to direct attention or explain behavior
-
-2. **Understand the context**:
- - What's the personality? (Playful vs serious, energetic vs calm)
- - What's the performance budget? (Mobile-first? Complex page?)
- - Who's the audience? (Motion-sensitive users? Power users who want speed?)
- - What matters most? (One hero animation vs many micro-interactions?)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them.
-
-## Plan Animation Strategy
-
-Create a purposeful animation plan:
-
-- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?)
-- **Feedback layer**: Which interactions need acknowledgment?
-- **Transition layer**: Which state changes need smoothing?
-- **Delight layer**: Where can we surprise and delight?
-
-**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments.
-
-## Implement Animations
-
-Add motion systematically across these categories:
-
-### Entrance Animations
-- **Page load choreography**: Stagger element reveals (100-150ms delays), fade + slide combinations
-- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects)
-- **Content reveals**: Scroll-triggered animations using intersection observer
-- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management
-
-### Micro-interactions
-- **Button feedback**:
- - Hover: Subtle scale (1.02-1.05), color shift, shadow increase
- - Click: Quick scale down then up (0.95 → 1), ripple effect
- - Loading: Spinner or pulse state
-- **Form interactions**:
- - Input focus: Border color transition, slight scale or glow
- - Validation: Shake on error, check mark on success, smooth color transitions
-- **Toggle switches**: Smooth slide + color transition (200-300ms)
-- **Checkboxes/radio**: Check mark animation, ripple effect
-- **Like/favorite**: Scale + rotation, particle effects, color transition
-
-### State Transitions
-- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms)
-- **Expand/collapse**: Height transition with overflow handling, icon rotation
-- **Loading states**: Skeleton screen fades, spinner animations, progress bars
-- **Success/error**: Color transitions, icon animations, gentle scale pulse
-- **Enable/disable**: Opacity transitions, cursor changes
-
-### Navigation & Flow
-- **Page transitions**: Crossfade between routes, shared element transitions
-- **Tab switching**: Slide indicator, content fade/slide
-- **Carousel/slider**: Smooth transforms, snap points, momentum
-- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators
-
-### Feedback & Guidance
-- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights
-- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning
-- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation
-- **Focus flow**: Highlight path through form or workflow
-
-### Delight Moments
-- **Empty states**: Subtle floating animations on illustrations
-- **Completed actions**: Confetti, check mark flourish, success celebrations
-- **Easter eggs**: Hidden interactions for discovery
-- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches
-
-## Technical Implementation
-
-Use appropriate techniques for each animation:
-
-### Timing & Easing
-
-**Durations by purpose:**
-- **100-150ms**: Instant feedback (button press, toggle)
-- **200-300ms**: State changes (hover, menu open)
-- **300-500ms**: Layout changes (accordion, modal)
-- **500-800ms**: Entrance animations (page load)
-
-**Easing curves (use these, not CSS defaults):**
-```css
-/* Recommended: natural deceleration */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */
-
-/* AVOID: feel dated and tacky */
-/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */
-/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */
-```
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-### CSS Animations
-```css
-/* Prefer for simple, declarative animations */
-- transitions for state changes
-- @keyframes for complex sequences
-- transform and opacity for reliable movement
-- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth
-```
-
-### JavaScript Animation
-```javascript
-/* Use for complex, interactive animations */
-- Web Animations API for programmatic control
-- Framer Motion for React
-- GSAP for complex sequences
-```
-
-### Performance
-- **Motion materials**: Use transform/opacity for reliable movement, but use blur, filters, masks, shadows, and color shifts when they materially improve the effect
-- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- **will-change**: Add sparingly for known expensive animations
-- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate
-- **Monitor FPS**: Ensure 60fps on target devices
-
-### Accessibility
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**NEVER**:
-- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself
-- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work
-- Use durations over 500ms for feedback (it feels laggy)
-- Animate without purpose (every animation needs a reason)
-- Ignore `prefers-reduced-motion` (this is an accessibility violation)
-- Animate everything (animation fatigue makes interfaces feel exhausting)
-- Block interaction during animations unless intentional
-
-## Verify Quality
-
-Test animations thoroughly:
-
-- **Smooth at 60fps**: No jank on target devices
-- **Feels natural**: Easing curves feel organic, not robotic
-- **Appropriate timing**: Not too fast (jarring) or too slow (laggy)
-- **Reduced motion works**: Animations disabled or simplified appropriately
-- **Doesn't block**: Users can interact during/after animations
-- **Adds value**: Makes interface clearer or more delightful
-
-When the motion clarifies state instead of decorating it, hand off to `/impeccable polish` for the final pass.
@@ -1,133 +0,0 @@
-Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues; document them for other commands to address.
-
-This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation.
-
-## Diagnostic Scan
-
-Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below.
-
-### 1. Accessibility (A11y)
-
-**Check for**:
-- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA)
-- **Missing ARIA**: Interactive elements without proper roles, labels, or states
-- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps
-- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons
-- **Alt text**: Missing or poor image descriptions
-- **Form issues**: Inputs without labels, poor error messaging, missing required indicators
-
-**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA)
-
-### 2. Performance
-
-**Check for**:
-- **Layout thrashing**: Reading/writing layout properties in loops
-- **Expensive animations**: Casual layout-property animation, unbounded blur/filter/shadow effects, or effects that visibly drop frames
-- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change
-- **Bundle size**: Unnecessary imports, unused dependencies
-- **Render performance**: Unnecessary re-renders, missing memoization
-
-**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized)
-
-### 3. Theming
-
-**Check for**:
-- **Hard-coded colors**: Colors not using design tokens
-- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme
-- **Inconsistent tokens**: Using wrong tokens, mixing token types
-- **Theme switching issues**: Values that don't update on theme change
-
-**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly)
-
-### 4. Responsive Design
-
-**Check for**:
-- **Fixed widths**: Hard-coded widths that break on mobile
-- **Touch targets**: Interactive elements < 44x44px
-- **Horizontal scroll**: Content overflow on narrow viewports
-- **Text scaling**: Layouts that break when text size increases
-- **Missing breakpoints**: No mobile/tablet variants
-
-**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets)
-
-### 5. Anti-Patterns (CRITICAL)
-
-Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy).
-
-**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design)
-
-## Generate Report
-
-### Audit Health Score
-
-| # | Dimension | Score | Key Finding |
-|---|-----------|-------|-------------|
-| 1 | Accessibility | ? | [most critical a11y issue or "--"] |
-| 2 | Performance | ? | |
-| 3 | Responsive Design | ? | |
-| 4 | Theming | ? | |
-| 5 | Anti-Patterns | ? | |
-| **Total** | | **??/20** | **[Rating band]** |
-
-**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues)
-
-### Anti-Patterns Verdict
-**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest.
-
-### Executive Summary
-- Audit Health Score: **??/20** ([rating band])
-- Total issues found (count by severity: P0/P1/P2/P3)
-- Top 3-5 critical issues
-- Recommended next steps
-
-### Detailed Findings by Severity
-
-Tag every issue with **P0-P3 severity**:
-- **P0 Blocking**: Prevents task completion. Fix immediately
-- **P1 Major**: Significant difficulty or WCAG AA violation. Fix before release
-- **P2 Minor**: Annoyance, workaround exists. Fix in next pass
-- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits
-
-For each issue, document:
-- **[P?] Issue name**
-- **Location**: Component, file, line
-- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern
-- **Impact**: How it affects users
-- **WCAG/Standard**: Which standard it violates (if applicable)
-- **Recommendation**: How to fix it
-- **Suggested command**: Which command to use (prefer: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-### Patterns & Systemic Issues
-
-Identify recurring problems that indicate systemic gaps rather than one-off mistakes:
-- "Hard-coded colors appear in 15+ components, should use design tokens"
-- "Touch targets consistently too small (<44px) throughout mobile experience"
-
-### Positive Findings
-
-Note what's working well: good practices to maintain and replicate.
-
-## Recommended Actions
-
-List recommended commands in priority order (P0 first, then P1, then P2):
-
-1. **[P?] `/command-name`**: Brief description (specific context from audit findings)
-2. **[P?] `/command-name`**: Brief description (specific context)
-
-**Rules**: Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset. Map findings to the most appropriate command. End with `/impeccable polish` as the final step if any fixes were recommended.
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable audit` after fixes to see your score improve.
-
-**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters.
-
-**NEVER**:
-- Report issues without explaining impact (why does this matter?)
-- Provide generic recommendations (be specific and actionable)
-- Skip positive findings (celebrate what works)
-- Forget to prioritize (everything can't be P0)
-- Report false positives without verification
-
@@ -1,113 +0,0 @@
-When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact and personality through stronger hierarchy, committed scale, and decisive type.
-
----
-
-## Register
-
-Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
-
-Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too safe or boring:
-
-1. **Identify weakness sources**:
- - **Generic choices**: System fonts, basic colors, standard layouts
- - **Timid scale**: Everything is medium-sized with no drama
- - **Low contrast**: Everything has similar visual weight
- - **Static**: No motion, no energy, no life
- - **Predictable**: Standard patterns with no surprises
- - **Flat hierarchy**: Nothing stands out or commands attention
-
-2. **Understand the context**:
- - What's the brand personality? (How far can we push?)
- - What's the purpose? (Marketing can be bolder than financial dashboards)
- - Who's the audience? (What will resonate?)
- - What are the constraints? (Brand guidelines, accessibility, performance)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
-
-**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
-
-## Plan Amplification
-
-Create a strategy to increase impact while maintaining coherence:
-
-- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
-- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
-- **Risk budget**: How experimental can we be? Push boundaries within constraints.
-- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
-
-**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration.
-
-## Amplify the Design
-
-Systematically increase impact across these dimensions:
-
-### Typography Amplification
-- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and [typography.md](typography.md) for inspiration)
-- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
-- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
-- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
-
-### Color Intensification
-- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
-- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop
-- **Dominant color strategy**: Let one bold color own 60% of the design
-- **Sharp accents**: High-contrast accent colors that pop
-- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
-- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
-
-### Spatial Drama
-- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
-- **Break the grid**: Let hero elements escape containers and cross boundaries
-- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
-- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
-- **Overlap**: Layer elements intentionally for depth
-
-### Visual Effects
-- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
-- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
-- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop)
-- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
-- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
-
-### Motion & Animation
-- **Entrance choreography**: Staggered, dramatic page load animations with 50-100ms delays
-- **Scroll effects**: Parallax, reveal animations, scroll-triggered sequences
-- **Micro-interactions**: Satisfying hover effects, click feedback, state changes
-- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect)
-
-### Composition Boldness
-- **Hero moments**: Create clear focal points with dramatic treatment
-- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
-- **Full-bleed elements**: Use full viewport width/height for impact
-- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
-
-**NEVER**:
-- Add effects randomly without purpose (chaos ≠ bold)
-- Sacrifice readability for aesthetics (body text must be readable)
-- Make everything bold (then nothing is bold; you need contrast)
-- Ignore accessibility (bold design must still meet WCAG standards)
-- Overwhelm with motion (animation fatigue is real)
-- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
-
-## Verify Quality
-
-Ensure amplification maintains usability and coherence:
-
-- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over.
-- **Still functional**: Can users accomplish tasks without distraction?
-- **Coherent**: Does everything feel intentional and unified?
-- **Memorable**: Will users remember this experience?
-- **Performant**: Do all these effects run smoothly?
-- **Accessible**: Does it still meet accessibility standards?
-
-**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects."
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,118 +0,0 @@
-# Brand register
-
-When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made.
-
-The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look.
-
-## The brand slop test
-
-If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?"
-
-Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home.
-
-**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register.
-
-Then the inverse test: in one sentence, describe what you're about to build the way a competitor would describe theirs. If that sentence fits the modal landing page in the category, restart.
-
-## Typography
-
-### Font selection procedure
-
-Every project. Never skip.
-
-1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words.
-2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture.
-3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy."
-4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over.
-
-### Reflex-reject list
-
-Training-data defaults. Ban list. Look further:
-
-Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif
-
-### Reflex-reject aesthetic lanes
-
-Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further.
-
-- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery.
-
-(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.)
-
-The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md).
-
-### Pairing and voice
-
-Distinctive + refined is the goal. The specific shape depends on the brand:
-
-- **Editorial / long-form / luxury**: display serif + sans body (a magazine shape).
-- **Tech / dev tools / fintech**: one committed sans, usually; custom-tight tracking, strong weight contrast inside a single family.
-- **Consumer / food / travel**: warmer pairings, often a humanist sans plus a script or display serif.
-- **Creative studios / agencies**: rule-breaking welcome. Mono-only, or display-only, or custom-drawn type as voice.
-
-Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair.
-
-Vary across projects. If the last brief was a serif-display landing page, this one isn't.
-
-### Scale
-
-Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted.
-
-Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room.
-
-## Color
-
-Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register.
-
-- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige.
-- Palette IS voice. A calm brand and a restless brand should not share palette mechanics.
-- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit.
-- Don't converge across projects. If the last brand surface was restrained-on-cream, this one is not.
-- When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette.
-
-## Layout
-
-- Asymmetric compositions are one option. Break the grid intentionally for emphasis.
-- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings.
-- Alternative: a strict, visible grid as the voice (brutalist / Swiss / tech-spec aesthetics). Either asymmetric or rigorously-gridded can be "designed"; the failure mode is splitting the difference into a generic centered stack.
-- Don't default to centering everything. Left-aligned with asymmetric layouts feels more designed; a strict grid reads as confident structure. A centered-stack hero with icon-title-subtitle cards reads as template.
-- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness.
-
-## Imagery
-
-Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo.
-
-**When the brief implies imagery (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product), you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy.
-
-- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `<div>` placeholders.
-- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel".
-- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one.
-- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish".
-
-"Imagery" here is broader than stock photography: product screenshots, custom data visualizations, generated SVG, and canvas/WebGL scenes are all imagery. Text-only pages where typography alone carries the entire visual weight are the failure mode.
-
-## Motion
-
-- One well-orchestrated page-load with staggered reveals beats scattered micro-interactions, when the brand invites it. Tech-minimal brands often skip entrance motion entirely; the restraint is the voice.
-- For collapsing/expanding sections, transition `grid-template-rows` rather than `height`.
-
-## Brand bans (on top of the shared absolute bans)
-
-- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume.
-- Large rounded-corner icons above every heading. Screams template.
-- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.)
-- All-caps body copy. Reserve caps for short labels and headings.
-- Timid palettes and average layouts. Safe = invisible.
-- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs.
-- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic.
-- Repeated tiny uppercase tracked labels above every section heading. A single strong kicker can be voice; repeating it as section grammar is AI scaffolding unless it's a deliberate, named brand system.
-
-## Brand permissions
-
-Brand can afford things product can't. Take them.
-
-- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography.
-- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing.
-- Typographic risk. Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines, a single oversize word as a hero.
-- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics.
-- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment.
@@ -1,174 +0,0 @@
-> **Additional context needed**: audience technical level and users' mental state in context.
-
-Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task.
-
-
----
-
-## Assess Current Copy
-
-Identify what makes the text unclear or ineffective:
-
-1. **Find clarity problems**:
- - **Jargon**: Technical terms users won't understand
- - **Ambiguity**: Multiple interpretations possible
- - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file"
- - **Length**: Too wordy or too terse
- - **Assumptions**: Assuming user knowledge they don't have
- - **Missing context**: Users don't know what to do or why
- - **Tone mismatch**: Too formal, too casual, or inappropriate for situation
-
-2. **Understand the context**:
- - Who's the audience? (Technical? General? First-time users?)
- - What's the user's mental state? (Stressed during error? Confident during success?)
- - What's the action? (What do we want users to do?)
- - What's the constraint? (Character limits? Space limitations?)
-
-**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets.
-
-## Plan Copy Improvements
-
-Create a strategy for clearer communication:
-
-- **Primary message**: What's the ONE thing users need to know?
-- **Action needed**: What should users do next (if anything)?
-- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?)
-- **Constraints**: Length limits, brand voice, localization considerations
-
-**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words.
-
-## Improve Copy Systematically
-
-Refine text across these common areas:
-
-### Error Messages
-**Bad**: "Error 403: Forbidden"
-**Good**: "You don't have permission to view this page. Contact your admin for access."
-
-**Bad**: "Invalid input"
-**Good**: "Email addresses need an @ symbol. Try: name@example.com"
-
-**Principles**:
-- Explain what went wrong in plain language
-- Suggest how to fix it
-- Don't blame the user
-- Include examples when helpful
-- Link to help/support if applicable
-
-### Form Labels & Instructions
-**Bad**: "DOB (MM/DD/YYYY)"
-**Good**: "Date of birth" (with placeholder showing format)
-
-**Bad**: "Enter value here"
-**Good**: "Your email address" or "Company name"
-
-**Principles**:
-- Use clear, specific labels (not generic placeholders)
-- Show format expectations with examples
-- Explain why you're asking (when not obvious)
-- Put instructions before the field, not after
-- Keep required field indicators clear
-
-### Button & CTA Text
-**Bad**: "Click here" | "Submit" | "OK"
-**Good**: "Create account" | "Save changes" | "Got it, thanks"
-
-**Principles**:
-- Describe the action specifically
-- Use active voice (verb + noun)
-- Match user's mental model
-- Be specific ("Save" is better than "OK")
-
-### Help Text & Tooltips
-**Bad**: "This is the username field"
-**Good**: "Choose a username. You can change this later in Settings."
-
-**Principles**:
-- Add value (don't just repeat the label)
-- Answer the implicit question ("What is this?" or "Why do you need this?")
-- Keep it brief but complete
-- Link to detailed docs if needed
-
-### Empty States
-**Bad**: "No items"
-**Good**: "No projects yet. Create your first project to get started."
-
-**Principles**:
-- Explain why it's empty (if not obvious)
-- Show next action clearly
-- Make it welcoming, not dead-end
-
-### Success Messages
-**Bad**: "Success"
-**Good**: "Settings saved! Your changes will take effect immediately."
-
-**Principles**:
-- Confirm what happened
-- Explain what happens next (if relevant)
-- Be brief but complete
-- Match the user's emotional moment (celebrate big wins)
-
-### Loading States
-**Bad**: "Loading..." (for 30+ seconds)
-**Good**: "Analyzing your data... this usually takes 30-60 seconds"
-
-**Principles**:
-- Set expectations (how long?)
-- Explain what's happening (when it's not obvious)
-- Show progress when possible
-- Offer escape hatch if appropriate ("Cancel")
-
-### Confirmation Dialogs
-**Bad**: "Are you sure?"
-**Good**: "Delete 'Project Alpha'? This can't be undone."
-
-**Principles**:
-- State the specific action
-- Explain consequences (especially for destructive actions)
-- Use clear button labels ("Delete project" not "Yes")
-- Don't overuse confirmations (only for risky actions)
-
-### Navigation & Wayfinding
-**Bad**: Generic labels like "Items" | "Things" | "Stuff"
-**Good**: Specific labels like "Your projects" | "Team members" | "Settings"
-
-**Principles**:
-- Be specific and descriptive
-- Use language users understand (not internal jargon)
-- Make hierarchy clear
-- Consider information scent (breadcrumbs, current location)
-
-## Apply Clarity Principles
-
-Every piece of copy should follow these rules:
-
-1. **Be specific**: "Enter email" not "Enter value"
-2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity)
-3. **Be active**: "Save changes" not "Changes will be saved"
-4. **Be human**: "Oops, something went wrong" not "System error encountered"
-5. **Tell users what to do**, not just what happened
-6. **Be consistent**: Use same terms throughout (don't vary for variety)
-
-**NEVER**:
-- Use jargon without explanation
-- Blame users ("You made an error" → "This field is required")
-- Be vague ("Something went wrong" without explanation)
-- Use passive voice unnecessarily
-- Write overly long explanations (be concise)
-- Use humor for errors (be empathetic instead)
-- Assume technical knowledge
-- Vary terminology (pick one term and stick with it)
-- Repeat information (headers restating intros, redundant explanations)
-- Use placeholders as the only labels (they disappear when users type)
-
-## Verify Improvements
-
-Test that copy improvements work:
-
-- **Comprehension**: Can users understand without context?
-- **Actionability**: Do users know what to do next?
-- **Brevity**: Is it as short as possible while remaining clear?
-- **Consistency**: Does it match terminology elsewhere?
-- **Tone**: Is it appropriate for the situation?
-
-When the copy reads cleanly, hand off to `/impeccable polish` for the final pass.
@@ -1,105 +0,0 @@
-# Codex: Visual Direction & Asset Production
-
-This file is loaded by `/impeccable craft` when the harness has native image generation (currently Codex via `image_gen`). Other harnesses skip it. It covers the two craft steps that depend on real image generation: landing the visual direction, and producing the raster assets the implementation will compose.
-
-Read this *before* generating any images. The order matters, and the per-step user pauses are what keep generated imagery from drifting away from the brief.
-
-### Four stop points before code
-
-Steps A through D each end with the user. Do not advance past any of them on your own read of the situation.
-
-1. **STOP after Step A questions.** Wait for answers.
-2. **STOP after Step B palette generation.** Wait for "confirm palette."
-3. **STOP after Step C mocks.** Wait for direction approval or delegation.
-4. **Only after Step D approves a direction** do you return to craft.md Step 4 and write code.
-
-Prior shape approval does **not** satisfy any of these. Shape's "confirm or override" advances you into Step A; it is not a substitute for it.
-
-## Step A: Explore Directions with the User
-
-Before generating anything, run a brief direction conversation grounded in the shape brief.
-
-**Step A is required even when shape just produced a confirmed brief.** The shape questions and Step A questions cover different ground: shape pins purpose, content, scope; Step A pins palette, atmosphere, and named visual references for the comps you're about to generate. The only time you can skip Step A is when the user has already answered these exact palette/atmosphere/reference questions in the same session.
-
-Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions:
-
-- "Brief says 'editorial restraint, Klim-adjacent.' Are we closer to a quiet specimen page or a magazine-spread feel with hero imagery?"
-- "Palette strategy from shape was 'Committed.' Want it warm-grounded (deep oxblood + cream) or cool-grounded (slate + paper white)?"
-
-**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded.
-
-## Step B: Generate the Brand Palette First
-
-Generate **one** palette artifact before any mocks. This is a small, focused image: typography pairing on the chosen background, primary + accent color swatches, one signature ornament or motif. Single image, single pass.
-
-Why palette first: mocks generated against a vague color sense produce noise that drowns out the structural decisions. A confirmed palette is the first concrete contract for everything downstream.
-
-Show the palette to the user. Ask one question: "This is the palette I'm locking in for the mocks. Confirm, or call out what to shift?"
-
-**STOP and wait for confirmation.** Do not generate mocks against an unconfirmed palette. "Probably good enough" is the wrong call here; the palette is the contract for everything downstream.
-
-## Step C: Generate 1-3 Visual Mocks Against the Palette
-
-Once the palette is confirmed, generate **1 to 3** high-fidelity north-star comps. Each mock must use the confirmed palette and typography. Mocks differ in *structural* direction (hierarchy, topology, density, composition), not in color or motif.
-
-- Brand work: push visual identity, composition, mood, and signature motifs.
-- Product work: push hierarchy, topology, density, tone, grounded in realistic product structure.
-- Landing pages and long-form brand surfaces: show enough of the second fold to establish the system beyond the hero.
-
-Use the `image_gen` tool directly (or via the imagegen skill when available). Don't ask the user to install anything.
-
-## Step D: Approval Loop
-
-Show the comps. Ask what carries forward. Iterate until **one direction is approved** or the user explicitly delegates.
-
-**STOP and wait for the approval or the delegation.** Do not begin Step E or return to craft.md Step 4 until a single direction is named. If the user delegates, pick the strongest direction and explain it from the brief, not personal taste.
-
-Before moving to assets, summarize what to carry into code and what *not* to literalize from the mock. This is the handoff between visual exploration and semantic implementation.
-
-## Step E: Mock Fidelity Inventory
-
-Inventory the approved mock's major visible ingredients. For each, decide implementation: semantic HTML/CSS/SVG, generated raster, sourced raster, icon library, canvas/WebGL, or accepted omission.
-
-Common ingredients to inventory:
-
-- Hero silhouette and dominant composition
-- Signature motifs (planets, devices, portraits, charts, route lines, insets, badges, etc.)
-- Nav and primary CTA treatment
-- Section sequence, especially the second fold
-- Image-native content the concept depends on
-- Typography, density, color/material treatment, motion cues
-
-Treat the mock as a north star, not a screenshot to trace. Don't rasterize core UI text. But if the live result lacks the mock's major ingredients, the implementation is wrong.
-
-If a photographic, architectural, product, or place-led mock becomes generic CSS scenery, decorative diagrams, bullets, or copy, stop and fix it. That's a broken implementation, not a harmless interpretation.
-
-Don't substitute a different hero composition or visual driver post-approval without user sign-off.
-
-## Step F: Asset Slicing via the Asset Producer
-
-Raster ingredients identified in Step E need clean production assets. Use the bundled `impeccable_asset_producer` subagent rather than producing inline.
-
-Spawn it as a scoped subagent. If you do not have explicit permission to use agents, stop and ask:
-
-```text
-Asset production will work better as a scoped subagent job. Should I spawn the Impeccable asset producer subagent for this step?
-```
-
-Pass to the agent:
-
-- Approved mock path or screenshot reference
-- Crop paths or a contact sheet with crop ids
-- Output directory
-- Required dimensions, format, transparency needs
-- Avoid list
-- Notes on what should remain semantic HTML/CSS/SVG instead of raster
-
-Attach image generation capability to the spawned agent when the harness supports it. Do **not** load image-generation reference material into the parent thread.
-
-Inline asset production is allowed only if the user declines subagents, the harness cannot spawn the authorized agent, or the user explicitly asks for single-thread mode.
-
-Prefer HTML/CSS/SVG/canvas when they can credibly reproduce an ingredient; reach for real, generated, or stock imagery when the mock or subject matter calls for actual visual content.
-
-## After This File
-
-Once Steps A through F are complete, return to `craft.md` Step 5 (Build to Production Quality). The implementation builds against the confirmed palette, approved mock, and the assets the producer wrote.
@@ -1,106 +0,0 @@
-# Cognitive Load Assessment
-
-Cognitive load is the total mental effort required to use an interface. Overloaded users make mistakes, get frustrated, and leave. This reference helps identify and fix cognitive overload.
-
----
-
-## Three Types of Cognitive Load
-
-### Intrinsic Load: The Task Itself
-Complexity inherent to what the user is trying to do. You can't eliminate this, but you can structure it.
-
-**Manage it by**:
-- Breaking complex tasks into discrete steps
-- Providing scaffolding (templates, defaults, examples)
-- Progressive disclosure: show what's needed now, hide the rest
-- Grouping related decisions together
-
-### Extraneous Load: Bad Design
-Mental effort caused by poor design choices. **Eliminate this ruthlessly.** It's pure waste.
-
-**Common sources**:
-- Confusing navigation that requires mental mapping
-- Unclear labels that force users to guess meaning
-- Visual clutter competing for attention
-- Inconsistent patterns that prevent learning
-- Unnecessary steps between user intent and result
-
-### Germane Load: Learning Effort
-Mental effort spent building understanding. This is *good* cognitive load; it leads to mastery.
-
-**Support it by**:
-- Progressive disclosure that reveals complexity gradually
-- Consistent patterns that reward learning
-- Feedback that confirms correct understanding
-- Onboarding that teaches through action, not walls of text
-
----
-
-## Cognitive Load Checklist
-
-Evaluate the interface against these 8 items:
-
-- [ ] **Single focus**: Can the user complete their primary task without distraction from competing elements?
-- [ ] **Chunking**: Is information presented in digestible groups (≤4 items per group)?
-- [ ] **Grouping**: Are related items visually grouped together (proximity, borders, shared background)?
-- [ ] **Visual hierarchy**: Is it immediately clear what's most important on the screen?
-- [ ] **One thing at a time**: Can the user focus on a single decision before moving to the next?
-- [ ] **Minimal choices**: Are decisions simplified (≤4 visible options at any decision point)?
-- [ ] **Working memory**: Does the user need to remember information from a previous screen to act on the current one?
-- [ ] **Progressive disclosure**: Is complexity revealed only when the user needs it?
-
-**Scoring**: Count the failed items. 0–1 failures = low cognitive load (good). 2–3 = moderate (address soon). 4+ = high cognitive load (critical fix needed).
-
----
-
-## The Working Memory Rule
-
-**Humans can hold ≤4 items in working memory at once** (Miller's Law revised by Cowan, 2001).
-
-At any decision point, count the number of distinct options, actions, or pieces of information a user must simultaneously consider:
-- **≤4 items**: Within working memory limits, manageable
-- **5–7 items**: Pushing the boundary; consider grouping or progressive disclosure
-- **8+ items**: Overloaded; users will skip, misclick, or abandon
-
-**Practical applications**:
-- Navigation menus: ≤5 top-level items (group the rest under clear categories)
-- Form sections: ≤4 fields visible per group before a visual break
-- Action buttons: 1 primary, 1–2 secondary, group the rest in a menu
-- Dashboard widgets: ≤4 key metrics visible without scrolling
-- Pricing tiers: ≤3 options (more causes analysis paralysis)
-
----
-
-## Common Cognitive Load Violations
-
-### 1. The Wall of Options
-**Problem**: Presenting 10+ choices at once with no hierarchy.
-**Fix**: Group into categories, highlight recommended, use progressive disclosure.
-
-### 2. The Memory Bridge
-**Problem**: User must remember info from step 1 to complete step 3.
-**Fix**: Keep relevant context visible, or repeat it where it's needed.
-
-### 3. The Hidden Navigation
-**Problem**: User must build a mental map of where things are.
-**Fix**: Always show current location (breadcrumbs, active states, progress indicators).
-
-### 4. The Jargon Barrier
-**Problem**: Technical or domain language forces translation effort.
-**Fix**: Use plain language. If domain terms are unavoidable, define them inline.
-
-### 5. The Visual Noise Floor
-**Problem**: Every element has the same visual weight; nothing stands out.
-**Fix**: Establish clear hierarchy: one primary element, 2–3 secondary, everything else muted.
-
-### 6. The Inconsistent Pattern
-**Problem**: Similar actions work differently in different places.
-**Fix**: Standardize interaction patterns. Same type of action = same type of UI.
-
-### 7. The Multi-Task Demand
-**Problem**: Interface requires processing multiple simultaneous inputs (reading + deciding + navigating).
-**Fix**: Sequence the steps. Let the user do one thing at a time.
-
-### 8. The Context Switch
-**Problem**: User must jump between screens/tabs/modals to gather info for a single decision.
-**Fix**: Co-locate the information needed for each decision. Reduce back-and-forth.
@@ -1,105 +0,0 @@
-# Color & Contrast
-
-## Color Spaces: Use OKLCH
-
-**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark.
-
-The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish.
-
-The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand.
-
-## Building Functional Palettes
-
-### Tinted Neutrals
-
-**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces.
-
-The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette.
-
-**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects.
-
-### Palette Structure
-
-A complete system needs:
-
-| Role | Purpose | Example |
-|------|---------|---------|
-| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades |
-| **Neutral** | Text, backgrounds, borders | 9-11 shade scale |
-| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each |
-| **Surface** | Cards, modals, overlays | 2-3 elevation levels |
-
-**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise.
-
-### The 60-30-10 Rule (Applied Correctly)
-
-This rule is about **visual weight**, not pixel count:
-
-- **60%**: Neutral backgrounds, white space, base surfaces
-- **30%**: Secondary colors: text, borders, inactive states
-- **10%**: Accent: CTAs, highlights, focus states
-
-The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power.
-
-## Contrast & Accessibility
-
-### WCAG Requirements
-
-| Content Type | AA Minimum | AAA Target |
-|--------------|------------|------------|
-| Body text | 4.5:1 | 7:1 |
-| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 |
-| UI components, icons | 3:1 | 4.5:1 |
-| Non-essential decorations | None | None |
-
-**The gotcha**: Placeholder text still needs 4.5:1. That light gray placeholder you see everywhere? Usually fails WCAG.
-
-### Dangerous Color Combinations
-
-These commonly fail contrast or cause readability issues:
-
-- Light gray text on white (the #1 accessibility fail)
-- **Gray text on any colored background**: gray looks washed out and dead on color. Use a darker shade of the background color, or transparency
-- Red text on green background (or vice versa): 8% of men can't distinguish these
-- Blue text on red background (vibrates visually)
-- Yellow text on white (almost always fails)
-- Thin light text on images (unpredictable contrast)
-
-### Never Use Pure Gray or Pure Black
-
-Pure gray (`oklch(50% 0 0)`) and pure black (`#000`) don't exist in nature; real shadows and surfaces always have a color cast. Even a chroma of 0.005-0.01 is enough to feel natural without being obviously tinted. (See tinted neutrals example above.)
-
-### Testing
-
-Don't trust your eyes. Use tools:
-
-- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/)
-- Browser DevTools → Rendering → Emulate vision deficiencies
-- [Polypane](https://polypane.app/) for real-time testing
-
-## Theming: Light & Dark Mode
-
-### Dark Mode Is Not Inverted Light Mode
-
-You can't just swap colors. Dark mode requires different design decisions:
-
-| Light Mode | Dark Mode |
-|------------|-----------|
-| Shadows for depth | Lighter surfaces for depth (no shadows) |
-| Dark text on light | Light text on dark (reduce font weight) |
-| Vibrant accents | Desaturate accents slightly |
-| White backgrounds | Never pure black; use dark gray (oklch 12-18%) |
-
-In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light.
-
-### Token Hierarchy
-
-Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same.
-
-## Alpha Is A Design Smell
-
-Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed.
-
----
-
-**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Using pure black (#000) for large areas. Skipping color blindness testing (8% of men affected).
@@ -1,154 +0,0 @@
-> **Additional context needed**: existing brand colors.
-
-Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit.
-
----
-
-## Register
-
-Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it.
-
-Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen.
-
----
-
-## Assess Color Opportunity
-
-Analyze the current state and identify opportunities:
-
-1. **Understand current state**:
- - **Color absence**: Pure grayscale? Limited neutrals? One timid accent?
- - **Missed opportunities**: Where could color add meaning, hierarchy, or delight?
- - **Context**: What's appropriate for this domain and audience?
- - **Brand**: Are there existing brand colors we should use?
-
-2. **Identify where color adds value**:
- - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue)
- - **Hierarchy**: Drawing attention to important elements
- - **Categorization**: Different sections, types, or states
- - **Emotional tone**: Warmth, energy, trust, creativity
- - **Wayfinding**: Helping users navigate and understand structure
- - **Delight**: Moments of visual interest and personality
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose.
-
-## Plan Color Strategy
-
-Create a purposeful color introduction plan:
-
-- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals)
-- **Dominant color**: Which color owns 60% of colored elements?
-- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%)
-- **Application strategy**: Where does each color appear and why?
-
-**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more.
-
-## Introduce Color Strategically
-
-Add color systematically across these dimensions:
-
-### Semantic Color
-- **State indicators**:
- - Success: Green tones (emerald, forest, mint)
- - Error: Red/pink tones (rose, crimson, coral)
- - Warning: Orange/amber tones
- - Info: Blue tones (sky, ocean, indigo)
- - Neutral: Gray/slate for inactive states
-
-- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.)
-- **Progress indicators**: Colored bars, rings, or charts showing completion or health
-
-### Accent Color Application
-- **Primary actions**: Color the most important buttons/CTAs
-- **Links**: Add color to clickable text (maintain accessibility)
-- **Icons**: Colorize key icons for recognition and personality
-- **Headers/titles**: Add color to section headers or key labels
-- **Hover states**: Introduce color on interaction
-
-### Background & Surfaces
-- **Tinted backgrounds**: Replace pure gray (`#f5f5f5`) with warm neutrals (`oklch(97% 0.01 60)`) or cool tints (`oklch(97% 0.01 250)`)
-- **Colored sections**: Use subtle background colors to separate areas
-- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue)
-- **Cards & surfaces**: Tint cards or surfaces slightly for warmth
-
-**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
-
-### Data Visualization
-- **Charts & graphs**: Use color to encode categories or values
-- **Heatmaps**: Color intensity shows density or importance
-- **Comparison**: Color coding for different datasets or timeframes
-
-### Borders & Accents
-- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`)
-- **Underlines**: Color underlines for emphasis or active states
-- **Dividers**: Subtle colored dividers instead of gray lines
-- **Focus rings**: Colored focus indicators matching brand
-- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe
-
-**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe.
-
-### Typography Color
-- **Colored headings**: Use brand colors for section headings (maintain contrast)
-- **Highlight text**: Color for emphasis or categories
-- **Labels & tags**: Small colored labels for metadata or categories
-
-### Decorative Elements
-- **Illustrations**: Add colored illustrations or icons
-- **Shapes**: Geometric shapes in brand colors as background elements
-- **Gradients**: Colorful gradient overlays or mesh backgrounds
-- **Blobs/organic shapes**: Soft colored shapes for visual interest
-
-## Balance & Refinement
-
-Ensure color addition improves rather than overwhelms:
-
-### Maintain Hierarchy
-- **Dominant color** (60%): Primary brand color or most used accent
-- **Secondary color** (30%): Supporting color for variety
-- **Accent color** (10%): High contrast for key moments
-- **Neutrals** (remaining): Gray/black/white for structure
-
-### Accessibility
-- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components)
-- **Don't rely on color alone**: Use icons, labels, or patterns alongside color
-- **Test for color blindness**: Verify red/green combinations work for all users
-
-### Cohesion
-- **Consistent palette**: Use colors from defined palette, not arbitrary choices
-- **Systematic application**: Same color meanings throughout (green always = success)
-- **Temperature consistency**: Warm palette stays warm, cool stays cool
-
-**NEVER**:
-- Use every color in the rainbow (choose 2-4 colors beyond neutrals)
-- Apply color randomly without semantic meaning
-- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead
-- Use pure gray for neutrals. Add subtle color tint (warm or cool) for depth
-- Use pure black (`#000`) or pure white (`#fff`) for large areas
-- Violate WCAG contrast requirements
-- Use color as the only indicator (accessibility issue)
-- Make everything colorful (defeats the purpose)
-- Default to purple-blue gradients (AI slop aesthetic)
-
-## Verify Color Addition
-
-Test that colorization improves the experience:
-
-- **Better hierarchy**: Does color guide attention appropriately?
-- **Clearer meaning**: Does color help users understand states/categories?
-- **More engaging**: Does the interface feel warmer and more inviting?
-- **Still accessible**: Do all color combinations meet WCAG standards?
-- **Not overwhelming**: Is color balanced and purposeful?
-
-When the palette earns its place, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage.
-
-```json
-{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"}
-```
-
-Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract.
@@ -1,123 +0,0 @@
-# Craft Flow
-
-Build a feature with impeccable UX and UI quality: shape the design, land the visual direction, build real production code, inspect and improve in-browser until it meets a high-end studio bar.
-
-Before writing code, you need: PRODUCT.md loaded, register identified and the matching reference loaded, and a confirmed design direction for this task (either from `shape` or supplied by the user). PRODUCT.md is project context, not a task-specific brief.
-
-Treat any approved visual direction (generated mock or stated reference) as a concrete contract for composition, hierarchy, density, atmosphere, signature motifs, and distinctive visual moves. Don't let mocks replace structure, copy, accessibility, or state design. But if the live result lacks the approved direction's major ingredients, the implementation is wrong.
-
-### Gates: do not compress
-
-Craft has **multiple user gates**, not one. When the harness has native image generation (Codex via `image_gen`), the gate sequence before code is:
-
-1. **Shape brief confirmed** (Step 1)
-2. **Direction questions answered** (codex.md Step A)
-3. **Palette confirmed** (codex.md Step B)
-4. **One mock direction approved or delegated** (codex.md Step D)
-
-You must stop at every gate. **Shape confirmation alone is NOT a green light to start coding.** It is the green light to begin codex.md Step A. Compressing gates 2 through 4 because the shape brief felt complete is the dominant failure mode of this flow.
-
-When the harness lacks native image generation, gates 2-4 collapse into the brief itself, and shape confirmation does advance straight to code.
-
-## Step 0: Project Foundation
-
-Before shape, before code: figure out what kind of project you're working in.
-
-Look at the working directory. Run `ls`. Check for:
-
-- An existing framework: `astro.config.mjs/ts`, `next.config.js/ts`, `nuxt.config.ts`, `svelte.config.js`, `vite.config.js/ts`, `package.json` with framework deps, `Cargo.toml` + Leptos/Yew, `Gemfile` + Rails. **If found, use it.** Do not start a parallel build, do not introduce a second framework, do not write to `dist/` or `build/` directly. Whatever pipeline the project has, respect it.
-- An existing component library or design system: `src/components/`, `app/components/`, a `tokens.css` / `theme.ts`, an `astro.config` `integrations`. Read what's there before adding to it.
-- An existing icon set: `lucide-react`, `@phosphor-icons/react`, `@iconify/*`, hand-rolled SVG sprites in `assets/icons/`. **Use what's already in the project**; don't introduce a second set.
-
-If the directory is empty (greenfield), don't pick a framework silently. Ask the user via the AskUserQuestion tool, with sensible defaults framed by the brief:
-
-```text
-What should this be built on?
- - Astro (default for content-led brand sites, landing pages, marketing surfaces)
- - SvelteKit / Next.js / Nuxt (when the brief implies an app surface or significant interactivity)
- - Single index.html (one-shot demo, prototype, or a deliberately framework-free experiment)
-```
-
-Default: Astro for brand briefs, the project's existing framework for product briefs. Ask once; don't re-ask mid-task.
-
-## Step 1: Shape the Design
-
-Run /impeccable shape, passing along whatever feature description the user provided. Shape is **required** for craft; it is what produces a confirmed direction.
-
-Present the shape output and stop. Wait for the user to confirm, override, or course-correct before writing code.
-
-If the user already supplied a confirmed brief or ran shape separately, use it and skip this step.
-
-When the original prompt + PRODUCT.md already answer scope, content, and visual direction with no real ambiguity, the shape output can be **compact** (3-5 bullets stating what you're building and the visual lane, ending with one or two specific questions or "confirm or override"). The full 10-section structured brief is reserved for genuinely ambiguous, multi-screen, or stakeholder-heavy tasks. Don't pad a clear brief into a long one to look thorough; equally, don't skip the pause to look efficient.
-
-If the harness has native image generation (Codex), a compact shape's "confirm or override" advances to **Step 3 and the codex.md flow**, not to Step 4. Phrase the closing line accordingly: "Confirm or override; once we lock direction, I'll run a couple of palette and reference questions before generating any mocks." This stops the model from reading shape confirmation as code-green.
-
-## Step 2: Load References
-
-Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult:
-
-- [spatial-design.md](spatial-design.md) for layout and spacing
-- [typography.md](typography.md) for type hierarchy
-
-Then add references based on the brief's needs:
-- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md)
-- Animation or transitions? Consult [motion-design.md](motion-design.md)
-- Color-heavy or themed? Consult [color-and-contrast.md](color-and-contrast.md)
-- Responsive requirements? Consult [responsive-design.md](responsive-design.md)
-- Heavy on copy, labels, or errors? Consult [ux-writing.md](ux-writing.md)
-
-## Step 3: Visual Direction & Assets (Harness-Gated)
-
-If the harness has **native image generation** (currently Codex via `image_gen`), this step is mandatory. **Stop and load [codex.md](codex.md)**. It covers palette generation, mock exploration, the approval loop, mock-fidelity inventory, and asset slicing via the `impeccable_asset_producer` subagent. Follow Steps A-F in that file, then return here for Step 4.
-
-If the harness lacks native image generation, **state in one line that the visual-direction-by-generation step is being skipped because the harness lacks native image generation, then proceed**. The one-line announcement is required; it forces a conscious decision instead of letting the step quietly evaporate. The brief is your only visual reference. Implement directly from it, treating any named anchor references and the brief's "Design Direction" as the contract.
-
-Whether you generated mocks or not: don't replace required imagery with generic cards, bullets, emoji, fake metrics, decorative CSS panels, or filler copy. Image-led briefs (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product) need real or sourced imagery in the build, not CSS scenery.
-
-## Step 4: Build to Production Quality
-
-**Precondition.** If Step 3 routed you to codex.md (native image generation available), Steps A through D in that file must be complete before any code: questions answered, palette confirmed, mocks generated, one direction approved or delegated. **Do not mention implementation, file paths, or patch plans until that's done.** A confirmed shape brief is not enough; the model that compressed those gates is the model that already failed this flow.
-
-Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration.
-
-### Production bar
-
-- **Real content.** No placeholder copy, placeholder images, dead links, fake controls, or unused scaffold at presentation time.
-- **Preserve the approved mock's major ingredients.** Missing hero objects, world/product imagery, section structure, CTA/nav treatment, or distinctive motifs are blocking defects unless the user accepted the change.
-- **Semantic first.** Real headings, landmarks, labels, form associations, button/link semantics, accessible names, state announcements where needed.
-- **Deliberate spacing and alignment.** No default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment.
-- **Intentional typography.** Chosen loading strategy, clear hierarchy, readable measure, stable line breaks, no overflow at any width.
-- **Realistic state coverage.** Default, hover, focus-visible, active, disabled, loading, error, success, empty, overflow, long/short text, first-run.
-- **Finished interaction quality.** Keyboard paths, touch targets, feedback timing, scroll behavior, state transitions, no hover-only functionality.
-- **Coherent icon set.** Use the project's established set; otherwise pick one library or use accessible text. Don't mix.
-- **Respect the build pipeline.** Edit source files and run the project's build (`npm run build` or equivalent). Don't write to `build/` / `dist/` / `.next/` with `cat`, heredoc, or Bash redirects; that skips asset hashing, image optimization, code splitting, and CSS extraction, and produces output the dev server won't serve.
-- **Verify image URLs before referencing them.** Use image-search MCP or web-fetch when available; guessed photo IDs ship as broken-image placeholders. Without verification, prefer fewer images you're confident about.
-- **Optimized imagery and media.** Correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset`/`picture` for raster, no project-referenced asset left outside the workspace.
-- **Premium motion.** Use atmospheric blur, filter, mask, shadow, reveal when they improve the experience. Avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion.
-- **Maintainable.** Reusable local patterns, clear component boundaries, project conventions. No rasterized UI text or one-off hacks when a local pattern exists.
-- **Technically clean.** Production build passes, no console errors, no avoidable layout shift, no needless dependencies, no broken asset paths.
-- **Ask when uncertain.** If a discovery materially changes the brief or approved direction, stop and ask. Don't guess.
-
-## Step 5: Iterate Visually
-
-Look at what you built like a designer would. Your eyes are whatever the harness gives you: a connected browser, a screenshotting tool, Playwright, or asking the user. Use them for responsive testing (mobile, tablet, desktop minimum) and general visual validation.
-
-If your tool returns a file path, read the PNG back into the conversation. A screenshot you didn't read doesn't count.
-
-For long-form brand surfaces, inspect major sections individually. Thumbnails hide spacing, clipping, and cascade defects.
-
-After the first pass, write an honest critique against the brief, the approved mock's major ingredients (hero silhouette, motifs, imagery, nav/CTA, density), and impeccable's DON'Ts. Patch material defects and re-inspect. **Don't invent defects to demonstrate iteration.** A confident "first pass clean, shipping" beats a fake fix.
-
-Actively check: responsive behavior (composes, not shrinks), every state (empty / error / loading / edge), craft details (spacing, alignment, hierarchy, contrast, motion timing, focus), performance basics. The exit bar: defensible in a high-end studio review.
-
-Detector or QA output is defect evidence only; never proof the work is finished.
-
-## Step 6: Present
-
-Present the result to the user:
-- Show the feature in its primary state
-- Summarize the browser/viewports checked and the most important fixes made after inspection
-- Walk through the key states (empty, error, responsive)
-- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients.
-- Note any remaining limitations or follow-up risks honestly
-- Ask: "What's working? What isn't?"
@@ -1,236 +0,0 @@
-### Purpose
-
-Resolve one stable target, run two independent assessments, synthesize a design critique, persist a snapshot, and ask the user what to improve next. The chat response is the primary deliverable; the snapshot is an archive/backlog for future commands.
-
-### Hard Invariants
-
-- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
-- Assessment A must finish before detector findings enter the parent synthesis context. Detector output is deterministic, but it still anchors judgment.
-- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize.
-- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
-- Viewable targets require browser inspection when available.
-- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
-- Do not claim a user-visible overlay exists unless script injection succeeded and the detector ran in the page.
-
-### Setup
-
-1. **Resolve the target** to a concrete file path or URL. Prefer a source path over a dev-server URL when both identify the same surface; ports drift, paths do not.
- - "the homepage" -> `site/pages/index.astro` or `index.html`
- - "the settings modal" -> the primary component file
- - "this page" -> the current URL or source file
-2. **Compute the slug**:
- ```bash
- node .rovodev/skills/impeccable/scripts/critique-storage.mjs slug "<resolved-path-or-url>"
- ```
- Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique.
-3. **Read `.impeccable/critique/ignore.md`** if it exists. Drop matching findings silently; it is the only prior-run input critique consumes.
-
-### Assessment Orchestration
-
-Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis.
-
-If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
-
-### Assessment A: Design Review
-
-Read relevant source files and visually inspect the live page when browser automation is available. Think like a design director.
-
-Evaluate:
-- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill.
-- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases.
-- **Cognitive load**: consult [cognitive-load](cognitive-load.md); report checklist failures and decision points with >4 visible options.
-- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments.
-- **Nielsen heuristics**: consult [heuristics-scoring](heuristics-scoring.md); score all 10 heuristics 0-4.
-
-Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions.
-
-### Assessment B: Detector + Browser Evidence
-
-Run the bundled detector and browser visualization evidence. Assessment B is mandatory and must remain isolated from Assessment A until both are complete.
-
-CLI scan:
-```bash
-node .rovodev/skills/impeccable/scripts/detect.mjs --json [--fast] [target]
-```
-
-- Pass markup files/directories as `[target]`; do not pass CSS-only files.
-- For URLs, skip CLI scan and use browser visualization.
-- For 200+ scannable files, use `--fast`; for 500+, narrow scope or ask.
-- Exit code 0 = clean; 2 = findings.
-- If the detector entrypoint is missing or fails to load, report deterministic scan unavailable and continue with browser/manual review.
-
-Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
-
-1. Create a fresh tab and navigate.
-2. Preflight mutable injection by setting `document.title` and appending a `<script>` tag. Read-only evaluate APIs do not count.
-3. If mutation is unavailable, skip live server, browser presentation, and injection; report fallback signal.
-4. If mutation is available, start `node .rovodev/skills/impeccable/scripts/live-server.mjs --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then stop the live server.
-5. For multi-view targets, inject on 3-5 representative pages.
-
-Return: CLI findings JSON/counts, browser console findings if applicable, false positives, and skipped/failed browser steps with concrete reasons.
-
-After Assessment B returns usable CLI findings, reuse them. Do not rerun `detect.mjs` in the parent unless Assessment B failed, was truncated, or omitted count, rule names, or file locations.
-
-### Generate Combined Critique Report
-
-Synthesize both assessments into a single report. Do NOT simply concatenate. Weave the findings together, noting where the LLM review and detector agree, where the detector caught issues the LLM missed, and where detector findings are false positives.
-
-The chat response is the primary user-facing deliverable. Present the full structured critique below in chat; do not replace it with a summary and a link. The persisted snapshot is only an archive/backlog for later commands.
-
-Structure your feedback as a design director would:
-
-#### Design Health Score
-> *Consult [heuristics-scoring](heuristics-scoring.md)*
-
-Present the Nielsen's 10 heuristics scores as a table:
-
-| # | Heuristic | Score | Key Issue |
-|---|-----------|-------|-----------|
-| 1 | Visibility of System Status | ? | [specific finding or "n/a" if solid] |
-| 2 | Match System / Real World | ? | |
-| 3 | User Control and Freedom | ? | |
-| 4 | Consistency and Standards | ? | |
-| 5 | Error Prevention | ? | |
-| 6 | Recognition Rather Than Recall | ? | |
-| 7 | Flexibility and Efficiency | ? | |
-| 8 | Aesthetic and Minimalist Design | ? | |
-| 9 | Error Recovery | ? | |
-| 10 | Help and Documentation | ? | |
-| **Total** | | **??/40** | **[Rating band]** |
-
-Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32.
-
-#### Anti-Patterns Verdict
-
-**Start here.** Does this look AI-generated?
-
-**LLM assessment**: Your own evaluation of AI slop tells. Cover overall aesthetic feel, layout sameness, generic composition, missed opportunities for personality.
-
-**Deterministic scan**: Summarize what the automated detector found, with counts and file locations. Note any additional issues the detector caught that you missed, and flag any false positives.
-
-**Visual overlays** (if injection succeeded): Tell the user that overlays are now visible in the **[Human]** tab in their browser, highlighting the detected issues. Summarize what the console output reported. If browser visualization was attempted but injection failed, say that no reliable user-visible overlay is available and report the fallback signal instead.
-
-#### Overall Impression
-A brief gut reaction: what works, what doesn't, and the single biggest opportunity.
-
-#### What's Working
-Highlight 2-3 things done well. Be specific about why they work.
-
-#### Priority Issues
-The 3-5 most impactful design problems, ordered by importance.
-
-For each issue, tag with **P0-P3 severity** (consult [heuristics-scoring](heuristics-scoring.md) for severity definitions):
-- **[P?] What**: Name the problem clearly
-- **Why it matters**: How this hurts users or undermines goals
-- **Fix**: What to do about it (be concrete)
-- **Suggested command**: Which command could address this (from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-#### Persona Red Flags
-> *Consult [personas](personas.md)*
-
-Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `AGENTS.md` contains a `## Design Context` section from `impeccable teach`, also generate 1-2 project-specific personas from the audience/brand info.
-
-For each selected persona, walk through the primary user action and list specific red flags found:
-
-**Alex (Power User)**: No keyboard shortcuts detected. Form requires 8 clicks for primary action. Forced modal onboarding. High abandonment risk.
-
-**Jordan (First-Timer)**: Icon-only nav in sidebar. Technical jargon in error messages ("404 Not Found"). No visible help. Will abandon at step 2.
-
-Be specific. Name the exact elements and interactions that fail each persona. Don't write generic persona descriptions; write what broke for them.
-
-#### Minor Observations
-Quick notes on smaller issues worth addressing.
-
-#### Questions to Consider
-Provocative questions that might unlock better solutions:
-- "What if the primary action were more prominent?"
-- "Does this need to feel this complex?"
-- "What would a confident version of this look like?"
-
-**Remember**:
-- Be direct. Vague feedback wastes everyone's time.
-- Be specific. "The submit button," not "some elements."
-- Say what's wrong AND why it matters to users.
-- Give concrete suggestions. Cut "consider exploring..." entirely.
-- Prioritize ruthlessly. If everything is important, nothing is.
-- Don't soften criticism. Developers need honest feedback to ship great design.
-
-### Persist the Snapshot
-
-Once the report above is finalized, write it to `.impeccable/critique/` so the user can refer back, and so `/impeccable polish` can pick up the priority issues without a copy-paste.
-
-Skip this step if the Setup slug was null (vague or root-level target).
-
-1. **Write the body to a temp file** so you can pipe it to the helper. Use the full critique report (heuristic table, anti-patterns verdict, priority issues, persona red flags, minor observations, and questions), but stop before the "Ask the User" / "Recommended Actions" sections that come later.
-
-2. **Pass the structured metadata** through `IMPECCABLE_CRITIQUE_META` (JSON), then run the write command:
- ```bash
- IMPECCABLE_CRITIQUE_META='{"target":"<user phrasing>","total_score":<n>,"p0_count":<n>,"p1_count":<n>}' \
- node .rovodev/skills/impeccable/scripts/critique-storage.mjs write <slug> <body-file>
- ```
- The helper prints the absolute path it wrote.
-
-3. **Delete the temp body file** after the write attempt completes, whether the write succeeded or failed. If deletion fails, mention `temp-file cleanup failed: <reason>` briefly in the final output, but do not block the critique.
-
-4. **Read the trend** for context:
- ```bash
- node .rovodev/skills/impeccable/scripts/critique-storage.mjs trend <slug> 5
- ```
- This returns a JSON array of the last 5 frontmatter entries (including the one you just wrote).
-
-5. **Append a single line to the user-visible output**, after the report and before the questions:
-
- > **Trend for `<slug>` (last 5 runs): 24 → 28 → 32 → 29 → 32**
- > Wrote `.impeccable/critique/<filename>`.
-
- If this is the first run for the slug, the trend is just one score; say so: "First run for this target, no trend yet."
-
-This is fire-and-forget. Do not show the user the helper's JSON output; only the human-readable trend line and the written path. Failures here should not block the rest of the flow; print the error and move on.
-
-### Ask the User
-
-**After presenting findings**, use targeted questions based on what was actually found. ask the user directly to clarify what you cannot infer. These answers will shape the action plan.
-
-Ask questions along these lines (adapt to the specific findings; do NOT ask generic questions):
-
-1. **Priority direction**: Based on the issues found, ask which category matters most to the user right now. For example: "I found problems with visual hierarchy, color usage, and information overload. Which area should we tackle first?" Offer the top 2-3 issue categories as options.
-
-2. **Design intent**: If the critique found a tonal mismatch, ask whether it was intentional. For example: "The interface feels clinical and corporate. Is that the intended tone, or should it feel warmer/bolder/more playful?" Offer 2-3 tonal directions as options based on what would fix the issues found.
-
-3. **Scope**: Ask how much the user wants to take on. For example: "I found N issues. Want to address everything, or focus on the top 3?" Offer scope options like "Top 3 only", "All issues", "Critical issues only".
-
-4. **Constraints** (optional; only ask if relevant): If the findings touch many areas, ask if anything is off-limits. For example: "Should any sections stay as-is?" This prevents the plan from touching things the user considers done.
-
-**Rules for questions**:
-- Every question must reference specific findings from the report. Never ask generic "who is your audience?" questions.
-- Keep it to 2-4 questions maximum. Respect the user's time.
-- Offer concrete options, not open-ended prompts.
-- If findings are straightforward (e.g., only 1-2 clear issues), skip questions and go directly to Recommended Actions.
-
-### Recommended Actions
-
-**After receiving the user's answers**, present a prioritized action summary reflecting the user's priorities and scope from Ask the User.
-
-#### Action Summary
-
-List recommended commands in priority order, based on the user's answers:
-
-1. **`/command-name`**: Brief description of what to fix (specific context from critique findings)
-2. **`/command-name`**: Brief description (specific context)
-...
-
-**Rules for recommendations**:
-- Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset
-- Order by the user's stated priorities first, then by impact
-- Each item's description should carry enough context that the command knows what to focus on
-- Map each Priority Issue to the appropriate command
-- Skip commands that would address zero issues
-- If the user chose a limited scope, only include items within that scope
-- If the user marked areas as off-limits, exclude commands that would touch those areas
-- End with `/impeccable polish` as the final step if any fixes were recommended
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable critique` after fixes to see your score improve.
@@ -1,302 +0,0 @@
-> **Additional context needed**: what's appropriate for the domain (playful vs professional vs quirky vs elegant).
-
-Find the moments where personality and unexpected polish would turn a functional interface into one users remember and tell other people about. Add only where the moment earns it; delight everywhere reads as noise.
-
----
-
-## Register
-
-Brand: delight can be distributed across copy voice, section transitions, discovery rewards, seasonal touches, personality across the whole surface.
-
-Product: delight at specific moments, not pages. Completion, first-time actions, error recovery, milestone crossings. Reliability and consistency carry the rest of the experience; delight pushed everywhere reads as noise.
-
----
-
-## Assess Delight Opportunities
-
-Identify where delight would enhance (not distract from) the experience:
-
-1. **Find natural delight moments**:
- - **Success states**: Completed actions (save, send, publish)
- - **Empty states**: First-time experiences, onboarding
- - **Loading states**: Waiting periods that could be entertaining
- - **Achievements**: Milestones, streaks, completions
- - **Interactions**: Hover states, clicks, drags
- - **Errors**: Softening frustrating moments
- - **Easter eggs**: Hidden discoveries for curious users
-
-2. **Understand the context**:
- - What's the brand personality? (Playful? Professional? Quirky? Elegant?)
- - Who's the audience? (Tech-savvy? Creative? Corporate?)
- - What's the emotional context? (Accomplishment? Exploration? Frustration?)
- - What's appropriate? (Banking app ≠ gaming app)
-
-3. **Define delight strategy**:
- - **Subtle sophistication**: Refined micro-interactions (luxury brands)
- - **Playful personality**: Whimsical illustrations and copy (consumer apps)
- - **Helpful surprises**: Anticipating needs before users ask (productivity tools)
- - **Sensory richness**: Satisfying sounds, smooth animations (creative tools)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Delight should enhance usability, never obscure it. If users notice the delight more than accomplishing their goal, you've gone too far.
-
-## Delight Principles
-
-Follow these guidelines:
-
-### Delight Amplifies, Never Blocks
-- Delight moments should be quick (< 1 second)
-- Never delay core functionality for delight
-- Make delight skippable or subtle
-- Respect user's time and task focus
-
-### Surprise and Discovery
-- Hide delightful details for users to discover
-- Reward exploration and curiosity
-- Don't announce every delight moment
-- Let users share discoveries with others
-
-### Appropriate to Context
-- Match delight to emotional moment (celebrate success, empathize with errors)
-- Respect the user's state (don't be playful during critical errors)
-- Match brand personality and audience expectations
-- Cultural sensitivity (what's delightful varies by culture)
-
-### Compound Over Time
-- Delight should remain fresh with repeated use
-- Vary responses (not same animation every time)
-- Reveal deeper layers with continued use
-- Build anticipation through patterns
-
-## Delight Techniques
-
-Add personality and joy through these methods:
-
-### Micro-interactions & Animation
-
-**Button delight**:
-```css
-/* Satisfying button press */
-.button {
- transition: transform 0.1s, box-shadow 0.1s;
-}
-.button:active {
- transform: translateY(2px);
- box-shadow: 0 2px 4px rgba(0,0,0,0.2);
-}
-
-/* Ripple effect on click */
-/* Smooth lift on hover */
-.button:hover {
- transform: translateY(-2px);
- transition: transform 0.2s cubic-bezier(0.25, 1, 0.5, 1); /* ease-out-quart */
-}
-```
-
-**Loading delight**:
-- Playful loading animations (not just spinners)
-- Personality in loading messages (write product-specific ones, not generic AI filler)
-- Progress indication with encouraging messages
-- Skeleton screens with subtle animations
-
-**Success animations**:
-- Checkmark draw animation
-- Confetti burst for major achievements
-- Gentle scale + fade for confirmation
-- Satisfying sound effects (subtle)
-
-**Hover surprises**:
-- Icons that animate on hover
-- Color shifts or glow effects
-- Tooltip reveals with personality
-- Cursor changes (custom cursors for branded experiences)
-
-### Personality in Copy
-
-**Playful error messages**:
-```
-"Error 404"
-"This page is playing hide and seek. (And winning)"
-
-"Connection failed"
-"Looks like the internet took a coffee break. Want to retry?"
-```
-
-**Encouraging empty states**:
-```
-"No projects"
-"Your canvas awaits. Create something amazing."
-
-"No messages"
-"Inbox zero! You're crushing it today."
-```
-
-**Playful labels & tooltips**:
-```
-"Delete"
-"Send to void" (for playful brand)
-
-"Help"
-"Rescue me" (tooltip)
-```
-
-**IMPORTANT**: Match copy personality to brand. Banks shouldn't be wacky, but they can be warm.
-
-### Illustrations & Visual Personality
-
-**Custom illustrations**:
-- Empty state illustrations (not stock icons)
-- Error state illustrations (friendly monsters, quirky characters)
-- Loading state illustrations (animated characters)
-- Success state illustrations (celebrations)
-
-**Icon personality**:
-- Custom icon set matching brand personality
-- Animated icons (subtle motion on hover/click)
-- Illustrative icons (more detailed than generic)
-- Consistent style across all icons
-
-**Background effects**:
-- Subtle particle effects
-- Gradient mesh backgrounds
-- Geometric patterns
-- Parallax depth
-- Time-of-day themes (morning vs night)
-
-### Satisfying Interactions
-
-**Drag and drop delight**:
-- Lift effect on drag (shadow, scale)
-- Snap animation when dropped
-- Satisfying placement sound
-- Undo toast ("Dropped in wrong place? [Undo]")
-
-**Toggle switches**:
-- Smooth slide with spring physics
-- Color transition
-- Haptic feedback on mobile
-- Optional sound effect
-
-**Progress & achievements**:
-- Streak counters with celebratory milestones
-- Progress bars that "celebrate" at 100%
-- Badge unlocks with animation
-- Playful stats ("You're on fire! 5 days in a row")
-
-**Form interactions**:
-- Input fields that animate on focus
-- Checkboxes with a satisfying scale pulse when checked
-- Success state that celebrates valid input
-- Auto-grow textareas
-
-### Sound Design
-
-**Subtle audio cues** (when appropriate):
-- Notification sounds (distinctive but not annoying)
-- Success sounds (satisfying "ding")
-- Error sounds (empathetic, not harsh)
-- Typing sounds for chat/messaging
-- Ambient background audio (very subtle)
-
-**IMPORTANT**:
-- Respect system sound settings
-- Provide mute option
-- Keep volumes quiet (subtle cues, not alarms)
-- Don't play on every interaction (sound fatigue is real)
-
-### Easter Eggs & Hidden Delights
-
-**Discovery rewards**:
-- Konami code unlocks special theme
-- Hidden keyboard shortcuts (Cmd+K for special features)
-- Hover reveals on logos or illustrations
-- Alt text jokes on images (for screen reader users too!)
-- Console messages for developers ("Like what you see? We're hiring!")
-
-**Seasonal touches**:
-- Holiday themes (subtle, tasteful)
-- Seasonal color shifts
-- Weather-based variations
-- Time-based changes (dark at night, light during day)
-
-**Contextual personality**:
-- Different messages based on time of day
-- Responses to specific user actions
-- Randomized variations (not same every time)
-- Progressive reveals with continued use
-
-### Loading & Waiting States
-
-**Make waiting engaging**:
-- Interesting loading messages that rotate
-- Progress bars with personality
-- Mini-games during long loads
-- Fun facts or tips while waiting
-- Countdown with encouraging messages
-
-```
-Loading messages: write ones specific to your product, not generic AI filler:
-- "Crunching your latest numbers..."
-- "Syncing with your team's changes..."
-- "Preparing your dashboard..."
-- "Checking for updates since yesterday..."
-```
-
-**WARNING**: Avoid cliched loading messages like "Herding pixels", "Teaching robots to dance", "Consulting the magic 8-ball", "Counting backwards from infinity". These are AI-slop copy, instantly recognizable as machine-generated. Write messages that are specific to what your product actually does.
-
-### Celebration Moments
-
-**Success celebrations**:
-- Confetti for major milestones
-- Animated checkmarks for completions
-- Progress bar celebrations at 100%
-- "Achievement unlocked" style notifications
-- Personalized messages ("You published your 10th article!")
-
-**Milestone recognition**:
-- First-time actions get special treatment
-- Streak tracking and celebration
-- Progress toward goals
-- Anniversary celebrations
-
-## Implementation Patterns
-
-**Animation libraries**:
-- Framer Motion (React)
-- GSAP (universal)
-- Lottie (After Effects animations)
-- Canvas confetti (party effects)
-
-**Sound libraries**:
-- Howler.js (audio management)
-- Use-sound (React hook)
-
-**Physics libraries**:
-- React Spring (spring physics)
-- Popmotion (animation primitives)
-
-**IMPORTANT**: File size matters. Compress images, optimize animations, lazy load delight features.
-
-**NEVER**:
-- Delay core functionality for delight
-- Force users through delightful moments (make skippable)
-- Use delight to hide poor UX
-- Overdo it (less is more)
-- Ignore accessibility (animate responsibly, provide alternatives)
-- Make every interaction delightful (special moments should be special)
-- Sacrifice performance for delight
-- Be inappropriate for context (read the room)
-
-## Verify Delight Quality
-
-Test that delight actually delights:
-
-- **User reactions**: Do users smile? Share screenshots?
-- **Doesn't annoy**: Still pleasant after 100th time?
-- **Doesn't block**: Can users opt out or skip?
-- **Performant**: No jank, no slowdown
-- **Appropriate**: Matches brand and context
-- **Accessible**: Works with reduced motion, screen readers
-
-When the moments feel earned, hand off to `/impeccable polish` for the final pass.
@@ -1,111 +0,0 @@
-Strip a design to its essence. Remove anything that doesn't earn its place: redundant elements, repeated information, decorative noise, cosmetic complexity.
-
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel complex or cluttered:
-
-1. **Identify complexity sources**:
- - **Too many elements**: Competing buttons, redundant information, visual clutter
- - **Excessive variation**: Too many colors, fonts, sizes, styles without purpose
- - **Information overload**: Everything visible at once, no progressive disclosure
- - **Visual noise**: Unnecessary borders, shadows, backgrounds, decorations
- - **Confusing hierarchy**: Unclear what matters most
- - **Feature creep**: Too many options, actions, or paths forward
-
-2. **Find the essence**:
- - What's the primary user goal? (There should be ONE)
- - What's actually necessary vs nice-to-have?
- - What can be removed, hidden, or combined?
- - What's the 20% that delivers 80% of value?
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Simplicity is not about removing features. It's about removing obstacles between users and their goals. Every element should justify its existence.
-
-## Plan Simplification
-
-Create a ruthless editing strategy:
-
-- **Core purpose**: What's the ONE thing this should accomplish?
-- **Essential elements**: What's truly necessary to achieve that purpose?
-- **Progressive disclosure**: What can be hidden until needed?
-- **Consolidation opportunities**: What can be combined or integrated?
-
-**IMPORTANT**: Simplification is hard. It requires saying no to good ideas to make room for great execution. Be ruthless.
-
-## Simplify the Design
-
-Systematically remove complexity across these dimensions:
-
-### Information Architecture
-- **Reduce scope**: Remove secondary actions, optional features, redundant information
-- **Progressive disclosure**: Hide complexity behind clear entry points (accordions, modals, step-through flows)
-- **Combine related actions**: Merge similar buttons, consolidate forms, group related content
-- **Clear hierarchy**: ONE primary action, few secondary actions, everything else tertiary or hidden
-- **Remove redundancy**: If it's said elsewhere, don't repeat it here
-
-### Visual Simplification
-- **Reduce color palette**: Use 1-2 colors plus neutrals, not 5-7 colors
-- **Limit typography**: One font family, 3-4 sizes maximum, 2-3 weights
-- **Remove decorations**: Eliminate borders, shadows, backgrounds that don't serve hierarchy or function
-- **Flatten structure**: Reduce nesting, remove unnecessary containers; never nest cards inside cards
-- **Remove unnecessary cards**: Cards aren't needed for basic layout; use spacing and alignment instead
-- **Consistent spacing**: Use one spacing scale, remove arbitrary gaps
-
-### Layout Simplification
-- **Linear flow**: Replace complex grids with simple vertical flow where possible
-- **Remove sidebars**: Move secondary content inline or hide it
-- **Full-width**: Use available space generously instead of complex multi-column layouts
-- **Consistent alignment**: Pick left or center, stick with it
-- **Generous white space**: Let content breathe, don't pack everything tight
-
-### Interaction Simplification
-- **Reduce choices**: Fewer buttons, fewer options, clearer path forward (paradox of choice is real)
-- **Smart defaults**: Make common choices automatic, only ask when necessary
-- **Inline actions**: Replace modal flows with inline editing where possible
-- **Remove steps**: Can signup be one step instead of three? Can checkout be simplified?
-- **Clear CTAs**: ONE obvious next step, not five competing actions
-
-### Content Simplification
-- **Shorter copy**: Cut every sentence in half, then do it again
-- **Active voice**: "Save changes" not "Changes will be saved"
-- **Remove jargon**: Plain language always wins
-- **Scannable structure**: Short paragraphs, bullet points, clear headings
-- **Essential information only**: Remove marketing fluff, legalese, hedging
-- **Remove redundant copy**: No headers restating intros, no repeated explanations, say it once
-
-### Code Simplification
-- **Remove unused code**: Dead CSS, unused components, orphaned files
-- **Flatten component trees**: Reduce nesting depth
-- **Consolidate styles**: Merge similar styles, use utilities consistently
-- **Reduce variants**: Does that component need 12 variations, or can 3 cover 90% of cases?
-
-**NEVER**:
-- Remove necessary functionality (simplicity ≠ feature-less)
-- Sacrifice accessibility for simplicity (clear labels and ARIA still required)
-- Make things so simple they're unclear (mystery ≠ minimalism)
-- Remove information users need to make decisions
-- Eliminate hierarchy completely (some things should stand out)
-- Oversimplify complex domains (match complexity to actual task complexity)
-
-## Verify Simplification
-
-Ensure simplification improves usability:
-
-- **Faster task completion**: Can users accomplish goals more quickly?
-- **Reduced cognitive load**: Is it easier to understand what to do?
-- **Still complete**: Are all necessary features still accessible?
-- **Clearer hierarchy**: Is it obvious what matters most?
-- **Better performance**: Does simpler design load faster?
-
-## Document Removed Complexity
-
-If you removed features or options:
-- Document why they were removed
-- Consider if they need alternative access points
-- Note any user feedback to monitor
-
-When the cuts feel right, hand off to `/impeccable polish` for the final pass. As Antoine de Saint-Exupéry put it: "Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away."
@@ -1,427 +0,0 @@
-Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
-
-DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
-
-## The frontmatter: token schema
-
-The YAML frontmatter is the machine-readable layer. It's what Stitch's linter validates and what the live panel renders tiles from. Keep it tight; every entry should correspond to a token the project actually uses.
-
-```yaml
----
-name: <project title>
-description: <one-line tagline>
-colors:
- primary: "#b8422e"
- neutral-bg: "#faf7f2"
- # ...one entry per extracted color; key = descriptive slug
-typography:
- display:
- fontFamily: "Cormorant Garamond, Georgia, serif"
- fontSize: "clamp(2.5rem, 7vw, 4.5rem)"
- fontWeight: 300
- lineHeight: 1
- letterSpacing: "normal"
- body:
- # ...
-rounded:
- sm: "4px"
- md: "8px"
-spacing:
- sm: "8px"
- md: "16px"
-components:
- button-primary:
- backgroundColor: "{colors.primary}"
- textColor: "{colors.neutral-bg}"
- rounded: "{rounded.sm}"
- padding: "16px 48px"
- button-primary-hover:
- backgroundColor: "{colors.primary-deep}"
----
-```
-
-Rules that matter:
-
-- **Token refs** use `{path.to.token}` (e.g. `{colors.primary}`, `{rounded.md}`). Components may reference primitives; primitives may not reference each other.
-- **Stitch validates colors as hex sRGB only** (`#RGB` / `#RGBA` / `#RRGGBB` / `#RRGGBBAA`); OKLCH/HSL/P3 trigger a linter warning, not a hard error. YAML accepts the string either way and our own parser is format-agnostic. Choose based on project posture: (a) if the project has an "OKLCH-only" doctrine or uses Display-P3 values that don't round-trip through sRGB, put OKLCH directly in the frontmatter and accept the Stitch linter warning; (b) if the project wants strict Stitch compliance or plans to use their Tailwind/DTCG export pipeline, put hex in the frontmatter and keep OKLCH in prose as the canonical reference. Never split the source of truth without explicit reason.
-- **Component sub-tokens** are limited to 8 props: `backgroundColor`, `textColor`, `typography`, `rounded`, `padding`, `size`, `height`, `width`. Shadows, motion, focus rings, backdrop-filter: none of those fit. Carry them in the sidecar (Step 4b).
-- **Scale keys are open-ended.** Use whatever names the project already uses (`warm-ash-cream`, `surface-container-low`). Don't rename to Material defaults.
-- **Variants are naming convention, not schema.** `button-primary` / `button-primary-hover` / `button-primary-active` as sibling keys.
-
-## The markdown body: six sections (exact order)
-
-1. `## Overview`
-2. `## Colors`
-3. `## Typography`
-4. `## Elevation`
-5. `## Components`
-6. `## Do's and Don'ts`
-
-Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] Palette` (Stitch's own outputs do this), but the literal word in each header (Overview, Colors, Typography, Elevation, Components, Do's and Don'ts) must be present. Do NOT add extra top-level sections (Layout Principles, Responsive Behavior, Motion, Agent Prompt Guide). Fold that content into the six spec sections where it naturally belongs.
-
-## When to run
-
-- The user just ran `/impeccable teach` and needs the visual side documented.
-- The skill noticed no `DESIGN.md` exists and nudged the user to create one.
-- An existing `DESIGN.md` is stale (the design has drifted).
-- Before a large redesign, to capture the current state as a reference.
-
-If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user the existing file and ask the user directly to clarify what you cannot infer. whether to refresh, overwrite, or merge.
-
-## Two paths
-
-- **Scan mode** (default): the project has design tokens, components, or rendered output. Extract, then confirm descriptive language. Use when there's code to analyze.
-- **Seed mode**: the project is pre-implementation (fresh teach, nothing built yet). Interview for five high-level answers, write a minimal DESIGN.md marked `<!-- SEED -->`. Re-run in scan mode once there's code.
-
-Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode; don't silently switch. `/impeccable document --seed` forces seed mode regardless of code presence.
-
-## Scan mode (approach C: auto-extract, then confirm descriptive language)
-
-### Step 1: Find the design assets
-
-Search the codebase in priority order:
-
-1. **CSS custom properties**: grep for `--color-`, `--font-`, `--spacing-`, `--radius-`, `--shadow-`, `--ease-`, `--duration-` declarations in CSS files (usually `src/styles/`, `public/css/`, `app/globals.css`, etc.). Record name, value, and the file it's defined in.
-2. **Tailwind config**: if `tailwind.config.{js,ts,mjs}` exists, read the `theme.extend` block for colors, fontFamily, spacing, borderRadius, boxShadow.
-3. **CSS-in-JS theme files**: styled-components, emotion, vanilla-extract, stitches; look for `theme.ts`, `tokens.ts`, or equivalent.
-4. **Design token files**: `tokens.json`, `design-tokens.json`, Style Dictionary output, W3C token community group format.
-5. **Component library**: scan the main button, card, input, navigation, dialog components. Note their variant APIs and default styles.
-6. **Global stylesheet**: the root CSS file usually has the base typography and color assignments.
-7. **Visible rendered output**: if browser automation tools are available, load the live site and sample computed styles from key elements (body, h1, a, button, .card). This catches values that tokens miss.
-
-### Step 2: Auto-extract what can be auto-extracted
-
-Build a structured draft from the discovered tokens. For each token class:
-
-- **Colors**: Group into Primary / Secondary / Tertiary / Neutral (the Material-derived roles Stitch uses). If the project only has one accent, express it as Primary + Neutral; omit Secondary and Tertiary rather than inventing them.
-- **Typography**: Map observed sizes and weights to the Material hierarchy (display / headline / title / body / label). Note font-family stacks and the scale ratio.
-- **Elevation**: Catalogue the shadow vocabulary. If the project is flat and uses tonal layering instead, that's a valid answer; state it explicitly.
-- **Components**: For each common component (button, card, input, chip, list item, tooltip, nav), extract shape (radius), color assignment, hover/focus treatment, internal padding.
-- **Spacing + layout**: Fold into Overview or relevant Components. The spec does NOT have a Layout section.
-
-### Step 2b: Stage the frontmatter
-
-From the auto-extracted tokens, draft the YAML frontmatter now (you'll write it at the top of DESIGN.md in Step 4). This is the machine-readable layer: what the live panel and Stitch's linter consume.
-
-- **Colors**: one entry per extracted color. Key = descriptive slug (`warm-ash-cream`, `editorial-magenta`, not `blue-800`). Value = whichever format the project treats as canonical (OKLCH or hex; see the frontmatter rules above). Don't split the source of truth: one format in the frontmatter, don't redefine the same token in prose with a different value.
-- **Typography**: one entry per role (`display`, `headline`, `title`, `body`, `label`). Typography is an object; include only the props that are real for the project (`fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `fontFeature`, `fontVariation`).
-- **Rounded / Spacing**: whatever scale steps the project actually uses, keyed by whatever scale name the project uses (`sm` / `md` / `lg`, or `surface-sm`, or numeric steps).
-- **Components**: one entry per variant (`button-primary`, `button-primary-hover`, `button-ghost`). Reference primitives via `{colors.X}`, `{rounded.Y}`. If a variant needs a property Stitch's 8-prop set doesn't cover (shadow, focus ring, backdrop-filter), carry the full snippet in the sidecar instead.
-
-Skip anything the project doesn't have. Empty scale keys or fabricated tokens pollute the spec.
-
-### Step 3: Ask the user for qualitative language
-
-The following require creative input that cannot be auto-extracted. Group them into one `AskUserQuestion` interaction:
-
-- **Creative North Star**: a single named metaphor for the whole system ("The Editorial Sanctuary", "The Golden State Curator", "The Lab Notebook"). Offer 2-3 options that honor PRODUCT.md's brand personality.
-- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, anti-references (what the system should not feel like).
-- **Color character** (for auto-extracted colors): descriptive names ("Deep Muted Teal-Navy", not "blue-800"). Suggest 2-3 options per key color based on hue/saturation.
-- **Elevation philosophy**: flat/layered/lifted. If shadows exist, is their role ambient or structural?
-- **Component philosophy**: the feel of buttons, cards, inputs in one phrase ("tactile and confident" vs. "refined and restrained").
-
-Quote a line from PRODUCT.md when possible so the user sees their own strategic language carry forward.
-
-### Step 4: Write DESIGN.md
-
-The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the structure below. Headers must match character-for-character. Optional evocative subtitles (e.g. `## 2. Colors: The Coastal Palette`) are allowed.
-
-```markdown
----
-name: [Project Title]
-description: [one-line tagline]
-colors:
- # ... staged frontmatter from Step 2b
----
-
-# Design System: [Project Title]
-
-## 1. Overview
-
-**Creative North Star: "[Named metaphor in quotes]"**
-
-[2-3 paragraph holistic description: personality, density, aesthetic philosophy. Start from the North Star and work outward. State what this system explicitly rejects (pulled from PRODUCT.md's anti-references). End with a short **Key Characteristics:** bullet list.]
-
-## 2. Colors
-
-[Describe the palette character in one sentence.]
-
-### Primary
-- **[Descriptive Name]** (#HEX / oklch(...)): [Where and why this color is used. Be specific about context, not just role.]
-
-### Secondary (optional; omit if the project has only one accent)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Tertiary (optional)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Neutral
-- **[Descriptive Name]** (#HEX): [Text / background / border / divider role.]
-- [...]
-
-### Named Rules (optional, powerful)
-**The [Rule Name] Rule.** [Short, forceful prohibition or doctrine, e.g. "The One Voice Rule. The primary accent is used on ≤10% of any given screen. Its rarity is the point."]
-
-## 3. Typography
-
-**Display Font:** [Family] (with [fallback])
-**Body Font:** [Family] (with [fallback])
-**Label/Mono Font:** [Family, if distinct]
-
-**Character:** [1-2 sentence personality description of the pairing.]
-
-### Hierarchy
-- **Display** ([weight], [size/clamp], [line-height]): [Purpose; where it appears.]
-- **Headline** ([weight], [size], [line-height]): [Purpose.]
-- **Title** ([weight], [size], [line-height]): [Purpose.]
-- **Body** ([weight], [size], [line-height]): [Purpose. Include max line length like 65–75ch if relevant.]
-- **Label** ([weight], [size], [letter-spacing], [case if uppercase]): [Purpose.]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [Short doctrine about type use.]
-
-## 4. Elevation
-
-[One paragraph: does this system use shadows, tonal layering, or a hybrid? If "no shadows", say so explicitly and describe how depth is conveyed instead.]
-
-### Shadow Vocabulary (if applicable)
-- **[Role name]** (`box-shadow: [exact value]`): [When to use it.]
-- [...]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [e.g. "The Flat-By-Default Rule. Surfaces are flat at rest. Shadows appear only as a response to state (hover, elevation, focus)."]
-
-## 5. Components
-
-For each component, lead with a short character line, then specify shape, color assignment, states, and any distinctive behavior.
-
-### Buttons
-- **Shape:** [radius described, exact value in parens]
-- **Primary:** [color assignment + padding, in semantic + exact terms]
-- **Hover / Focus:** [transitions, treatments]
-- **Secondary / Ghost / Tertiary (if applicable):** [brief description]
-
-### Chips (if used)
-- **Style:** [background, text color, border treatment]
-- **State:** [selected / unselected, filter / action variants]
-
-### Cards / Containers
-- **Corner Style:** [radius]
-- **Background:** [colors used]
-- **Shadow Strategy:** [reference Elevation section]
-- **Border:** [if any]
-- **Internal Padding:** [scale]
-
-### Inputs / Fields
-- **Style:** [stroke, background, radius]
-- **Focus:** [treatment, e.g. glow, border shift, etc.]
-- **Error / Disabled:** [if applicable]
-
-### Navigation
-- **Style, typography, default/hover/active states, mobile treatment.**
-
-### [Signature Component] (optional; if the project has a distinctive custom component worth documenting)
-[Description.]
-
-## 6. Do's and Don'ts
-
-Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: include exact colors, pixel values, and named anti-patterns the user mentioned in PRODUCT.md. **Every anti-reference in PRODUCT.md should show up here as a "Don't" with the same language**, so the visual spec carries the strategic line through. Quote PRODUCT.md directly where possible: if PRODUCT.md says *"avoid dark mode with purple gradients, neon accents, glassmorphism"*, the Don'ts here should repeat that by name.
-
-### Do:
-- **Do** [specific prescription with exact values / named rule].
-- **Do** [...]
-
-### Don't:
-- **Don't** [specific prohibition, e.g. "use border-left greater than 1px as a colored stripe"].
-- **Don't** [...]
-- **Don't** [...]
-```
-
-### Step 4b: Write .impeccable/design.json sidecar (extensions only)
-
-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.
-
-Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.
-
-#### Schema
-
-```json
-{
- "schemaVersion": 2,
- "generatedAt": "ISO-8601 string",
- "title": "Design System: [Project Title]",
- "extensions": {
- "colorMeta": {
- "primary": { "role": "primary", "displayName": "Editorial Magenta", "canonical": "oklch(60% 0.25 350)", "tonalRamp": ["...", "...", "..."] },
- "warm-ash-cream": { "role": "neutral", "displayName": "Warm Ash Cream", "canonical": "oklch(96% 0.005 350)", "tonalRamp": ["...", "...", "..."] }
- },
- "typographyMeta": {
- "display": { "displayName": "Display", "purpose": "Hero headlines only." }
- },
- "shadows": [
- { "name": "ambient-low", "value": "0 4px 24px rgba(0,0,0,0.12)", "purpose": "Diffuse hover glow under accent elements." }
- ],
- "motion": [
- { "name": "ease-standard", "value": "cubic-bezier(0.4, 0, 0.2, 1)", "purpose": "Default easing for state transitions." }
- ],
- "breakpoints": [
- { "name": "sm", "value": "640px" }
- ]
- },
- "components": [
- {
- "name": "Primary Button",
- "kind": "button | input | nav | chip | card | custom",
- "refersTo": "button-primary",
- "description": "One-line what and when.",
- "html": "<button class=\"ds-btn-primary\">GET STARTED</button>",
- "css": ".ds-btn-primary { background: #191c1d; color: #fff; padding: 16px 48px; letter-spacing: 0.05em; text-transform: uppercase; font-weight: 500; border: none; border-radius: 0; transition: background 0.2s, transform 0.2s; } .ds-btn-primary:hover { background: oklch(60% 0.25 350); transform: translateY(-2px); }"
- }
- ],
- "narrative": {
- "northStar": "The Editorial Sanctuary",
- "overview": "2-3 paragraphs of the philosophy, pulled from DESIGN.md Overview section.",
- "keyCharacteristics": ["...", "..."],
- "rules": [{ "name": "The One Voice Rule", "body": "...", "section": "colors|typography|elevation" }],
- "dos": ["Do use ..."],
- "donts": ["Don't use ..."]
- }
-}
-```
-
-**What changed from schemaVersion 1.** The old sidecar carried token primitive arrays (`tokens.colors[]`, `tokens.typography[]`, etc.). Those values now live in the frontmatter. The sidecar only carries metadata that can't live in the frontmatter (tonal ramps, canonical OKLCH when the hex is an approximation, display names, role hints), keyed by the frontmatter token name (`colorMeta.<token-name>`, `typographyMeta.<token-name>`). Components still carry full HTML/CSS because Stitch's 8-prop set can't hold them.
-
-#### Component translation rules
-
-The `html` and `css` fields must be **self-contained, drop-in snippets** that render correctly when injected into a shadow DOM. The panel applies them directly: no post-processing, no framework runtime.
-
-1. **Tailwind expansion.** If the source uses Tailwind (className="bg-primary text-white rounded-lg px-6 py-3"), expand every utility to literal CSS properties in the `css` string. Do **not** reference Tailwind classes; do **not** assume a Tailwind CSS bundle is loaded. Each component is self-contained.
-2. **Token resolution.** If the project exposes tokens as CSS custom properties on `:root` (e.g. `--color-primary`, `--radius-md`), reference them via `var(--color-primary)`; they inherit through the shadow DOM and stay live-bound. If tokens live only in JS theme objects (styled-components, CSS-in-JS), resolve to literal values at generation time.
-3. **Icons.** Inline as SVG. Do not reference Lucide/Heroicons packages, icon fonts, or `<img src="...">`. A typical icon is 16-24px; copy the SVG path data directly.
-4. **States.** Include `:hover`, `:focus-visible`, and (if meaningful) `:active` rules inline. A static default-only snapshot makes the panel feel dead. Hover + focus rules in the CSS make it feel alive.
-5. **Reset bloat.** Extract only the component's *distinctive* CSS (background, color, padding, border-radius, typography, transition). Skip universal resets (`box-sizing: border-box`, `line-height: inherit`, `-webkit-font-smoothing`). The panel already has a neutral canvas; don't re-ship resets.
-6. **Scoped class names.** Prefix every class with `ds-` (e.g. `ds-btn-primary`, `ds-input-search`) so component CSS doesn't collide with other components' CSS in the same shadow DOM.
-
-#### What to include
-
-Aim for a tight set of **5-10 components** that best represent the visual system:
-
-- **Canonical primitives (always include if the project has them):** button (each variant as a separate component entry), input/text field, navigation, chip/tag, card.
-- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.
-- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.
-
-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.
-
-#### Tonal ramps
-
-For each color token, generate an 8-step `tonalRamp` array: dark to light, same hue and chroma, stepped lightness from ~15% to ~95%. The panel renders this as a strip under the swatch. If the project already defines a tonal scale (Material `surface-container-low` family, Tailwind-style `blue-50..blue-900`), use those values. Otherwise synthesize in OKLCH.
-
-#### Narrative mapping
-
-Pull directly from the DESIGN.md you just wrote:
-
-- `narrative.northStar` → the `**Creative North Star: "..."**` line from Overview
-- `narrative.overview` → the philosophy paragraphs from Overview
-- `narrative.keyCharacteristics` → the bulleted `**Key Characteristics:**` list
-- `narrative.rules` → every `**The [Name] Rule.** [body]` across all sections, tagged with `section`
-- `narrative.dos` / `narrative.donts` → the bullet lists from Do's and Don'ts verbatim
-
-Do not reword. The panel shows these as secondary collapsible context; the same voice that's in the Markdown carries through.
-
-### Step 5: Confirm, refine, and refresh session cache
-
-1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).
-2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.
-3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"
-4. **Refresh the session cache.** Run `node .rovodev/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.
-
-## Seed mode
-
-For projects with no visual system to extract yet. Produces a minimal scaffold, not a full spec.
-
-### Step 1: Confirm seed mode
-
-Before interviewing: "There's no existing visual system to scan. I'll ask five quick questions to seed a starter DESIGN.md. You can re-run `/impeccable document` once there's code, to capture the real tokens and components. OK?"
-
-If the user prefers to skip, stop. No file.
-
-### Step 2: Five questions
-
-Group into one `AskUserQuestion` interaction. Options must be concrete.
-
-1. **Color strategy.** Pick one:
- - Restrained: tinted neutrals + one accent ≤10%
- - Committed: one saturated color carries 30–60% of the surface
- - Full palette: 3–4 named color roles, each deliberate
- - Drenched: the surface IS the color
-
- Then: one hue family or anchor reference ("deep teal", "mustard", "Klim #ff4500 orange").
-
-2. **Typography direction.** Pick one (specific fonts come later):
- - Serif display + sans body
- - Single sans (warm / technical / geometric / humanist; pick a feel)
- - Display + mono
- - Mono-forward
- - Editorial script + sans
-
-3. **Motion energy.** Pick one:
- - Restrained: state changes only
- - Responsive: feedback + transitions, no choreography
- - Choreographed: orchestrated entrances, scroll-driven sequences
-
-4. **Three named references.** Brands, products, printed objects. Not adjectives.
-
-5. **One anti-reference.** What it should NOT feel like. Also named.
-
-### Step 3: Write seed DESIGN.md
-
-Use the six-section spec from Scan mode. Populate what the interview answers; leave the rest as honest placeholders. The seed is a scaffold, not a fabricated spec.
-
-Lead the file with:
-
-```markdown
-<!-- SEED: re-run /impeccable document once there's code to capture the actual tokens and components. -->
-```
-
-Per-section guidance in seed mode:
-
-- **Overview**: Creative North Star and philosophy phrased from the answers (color strategy + motion energy + references). Reference the user's anti-reference directly.
-- **Colors**: Color strategy as a Named Rule (e.g. *"The Drenched Rule. The surface IS the color."*). Hue family or anchor reference. No hex values; mark as `[to be resolved during implementation]`.
-- **Typography**: the direction the user picked (e.g. "Serif display + sans body"). No font names yet: `[font pairing to be chosen at implementation]`.
-- **Elevation**: inferred from motion energy. Restrained/Responsive → flat by default; Choreographed → layered. One sentence.
-- **Components**: omit entirely; no components exist yet.
-- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.
-
-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.
-
-### Step 4: Confirm and refresh session cache
-
-1. Show the seed DESIGN.md. Call out that it is a seed (the marker is the literal commitment).
-2. Tell the user: "Re-run `/impeccable document` once you have some code. That pass will extract real tokens and generate the sidecar."
-3. Run `node .rovodev/skills/impeccable/scripts/load-context.mjs` once so the seed lands in conversation for the rest of the session.
-
-## Style guidelines
-
-- **Frontmatter first, prose second.** Tokens go in the YAML frontmatter; prose contextualizes them. Don't redefine a token value in two places; the frontmatter is normative.
-- **Cite PRODUCT.md anti-references by name** in the Do's and Don'ts section. If PRODUCT.md lists "SaaS landing-page clichés" or "generic AI tool marketing" as anti-references, the DESIGN.md Don'ts should repeat those phrases verbatim so the visual spec enforces the strategic line.
-- **Match the spec, don't invent new sections.** The six section names are fixed. If you have Layout/Motion/Responsive content to document, fold it into Overview (philosophy-level rules) or Components (per-component behavior).
-- **Descriptive > technical**: "Gently curved edges (8px radius)" > "rounded-lg". Include the technical value in parens, lead with the description.
-- **Functional > decorative**: for each token, explain WHERE and WHY it's used, not just WHAT it is.
-- **Exact values in parens**: hex codes, px/rem values, font weights; always the number in parens alongside the description.
-- **Use Named Rules**: `**The [Name] Rule.** [short doctrine]`. These are memorable, citable, and much stickier for AI consumers than bullet lists. Stitch's own outputs use them heavily ("The No-Line Rule", "The Ghost Border Fallback"). Aim for 1-3 per section.
-- **Be forceful**. The voice of a design director. "Prohibited", "forbidden", "never", "always", not "consider", "might", "prefer". Match PRODUCT.md's tone.
-- **Concrete anti-pattern tests**. Stitch writes things like *"If it looks like a 2014 app, the shadow is too dark and the blur is too small."* A one-sentence audit test beats a paragraph of principle.
-- **Reference PRODUCT.md**. The anti-references section of PRODUCT.md should directly inform the Do's and Don'ts section here. Quote or paraphrase.
-- **Group colors by role**, not by hex-order or hue-order. Primary / Secondary / Tertiary / Neutral is the spec ordering.
-
-## Pitfalls
-
-- Don't paste raw CSS class names. Translate to descriptive language.
-- Don't extract every token. Stop at what's actually reused; one-offs pollute the system.
-- Don't invent components that don't exist. If the project only has buttons and cards, only document those.
-- Don't overwrite an existing DESIGN.md without asking.
-- Don't duplicate content from PRODUCT.md. DESIGN.md is strictly visual.
-- Don't add a "Layout Principles" or "Motion" or "Responsive Behavior" top-level section. The spec has six, not nine. Fold that content where it belongs.
-- Don't rename sections even slightly. "Colors" not "Color Palette & Roles". "Typography" not "Typography Rules". Tooling parsing depends on exact headers.
-- Don't duplicate token values between frontmatter and prose. If a color is in `colors.primary` as hex, the prose can name it and describe its role but should not reassert a different hex. The frontmatter is normative.
-- Don't invent frontmatter token groups outside Stitch's schema (no `motion:`, `breakpoints:`, `shadows:` at the top level). Stitch's Zod schema only accepts `colors`, `typography`, `rounded`, `spacing`, `components`. Anything else belongs in the sidecar's `extensions`.
@@ -1,69 +0,0 @@
-# Extract Flow
-
-Identify reusable patterns, components, and design tokens, then extract and consolidate them into the design system for systematic reuse.
-
-## Step 1: Discover the Design System
-
-Find the design system, component library, or shared UI directory. Understand its structure: component organization, naming conventions, design token structure, import/export conventions.
-
-**CRITICAL**: If no design system exists, ask the user directly to clarify what you cannot infer. before creating one. Understand the preferred location and structure first.
-
-## Step 2: Identify Patterns
-
-Look for extraction opportunities in the target area:
-
-- **Repeated components**: Similar UI patterns used 3+ times (buttons, cards, inputs)
-- **Hard-coded values**: Colors, spacing, typography, shadows that should be tokens
-- **Inconsistent variations**: Multiple implementations of the same concept
-- **Composition patterns**: Layout or interaction patterns that repeat (form rows, toolbar groups, empty states)
-- **Type styles**: Repeated font-size + weight + line-height combinations
-- **Animation patterns**: Repeated easing, duration, or keyframe combinations
-
-Assess value: only extract things used 3+ times with the same intent. Premature abstraction is worse than duplication.
-
-## Step 3: Plan Extraction
-
-Create a systematic plan:
-
-- **Components to extract**: Which UI elements become reusable components?
-- **Tokens to create**: Which hard-coded values become design tokens?
-- **Variants to support**: What variations does each component need?
-- **Naming conventions**: Component names, token names, prop names that match existing patterns
-- **Migration path**: How to refactor existing uses to consume the new shared versions
-
-**IMPORTANT**: Design systems grow incrementally. Extract what is clearly reusable now, not everything that might someday be reusable.
-
-## Step 4: Extract & Enrich
-
-Build improved, reusable versions:
-
-- **Components**: Clear props API with sensible defaults, proper variants for different use cases, accessibility built in (ARIA, keyboard navigation, focus management), documentation and usage examples
-- **Design tokens**: Clear naming (primitive vs semantic), proper hierarchy and organization, documentation of when to use each token
-- **Patterns**: When to use this pattern, code examples, variations and combinations
-
-## Step 5: Migrate
-
-Replace existing uses with the new shared versions:
-
-- **Find all instances**: Search for the patterns you extracted
-- **Replace systematically**: Update each use to consume the shared version
-- **Test thoroughly**: Ensure visual and functional parity
-- **Delete dead code**: Remove the old implementations
-
-## Step 6: Document
-
-Update design system documentation:
-
-- Add new components to the component library
-- Document token usage and values
-- Add examples and guidelines
-- Update any Storybook or component catalog
-
-**NEVER**:
-- Extract one-off, context-specific implementations without generalization
-- Create components so generic they are useless
-- Extract without considering existing design system conventions
-- Skip proper TypeScript types or prop documentation
-- Create tokens for every single value (tokens should have semantic meaning)
-- Extract things that differ in intent (two buttons that look similar but serve different purposes should stay separate)
-
@@ -1,347 +0,0 @@
-Designs that only work with perfect data aren't production-ready. Harden the interface against the inputs, errors, languages, and network conditions that real users will throw at it.
-
-## Assess Hardening Needs
-
-Identify weaknesses and edge cases:
-
-1. **Test with extreme inputs**:
- - Very long text (names, descriptions, titles)
- - Very short text (empty, single character)
- - Special characters (emoji, RTL text, accents)
- - Large numbers (millions, billions)
- - Many items (1000+ list items, 50+ options)
- - No data (empty states)
-
-2. **Test error scenarios**:
- - Network failures (offline, slow, timeout)
- - API errors (400, 401, 403, 404, 500)
- - Validation errors
- - Permission errors
- - Rate limiting
- - Concurrent operations
-
-3. **Test internationalization**:
- - Long translations (German is often 30% longer than English)
- - RTL languages (Arabic, Hebrew)
- - Character sets (Chinese, Japanese, Korean, emoji)
- - Date/time formats
- - Number formats (1,000 vs 1.000)
- - Currency symbols
-
-**CRITICAL**: Designs that only work with perfect data aren't production-ready. Harden against reality.
-
-## Hardening Dimensions
-
-Systematically improve resilience:
-
-### Text Overflow & Wrapping
-
-**Long text handling**:
-```css
-/* Single line with ellipsis */
-.truncate {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* Multi-line with clamp */
-.line-clamp {
- display: -webkit-box;
- -webkit-line-clamp: 3;
- -webkit-box-orient: vertical;
- overflow: hidden;
-}
-
-/* Allow wrapping */
-.wrap {
- word-wrap: break-word;
- overflow-wrap: break-word;
- hyphens: auto;
-}
-```
-
-**Flex/Grid overflow**:
-```css
-/* Prevent flex items from overflowing */
-.flex-item {
- min-width: 0; /* Allow shrinking below content size */
- overflow: hidden;
-}
-
-/* Prevent grid items from overflowing */
-.grid-item {
- min-width: 0;
- min-height: 0;
-}
-```
-
-**Responsive text sizing**:
-- Use `clamp()` for fluid typography
-- Set minimum readable sizes (14px on mobile)
-- Test text scaling (zoom to 200%)
-- Ensure containers expand with text
-
-### Internationalization (i18n)
-
-**Text expansion**:
-- Add 30-40% space budget for translations
-- Use flexbox/grid that adapts to content
-- Test with longest language (usually German)
-- Avoid fixed widths on text containers
-
-```jsx
-// ❌ Bad: Assumes short English text
-<button className="w-24">Submit</button>
-
-// ✅ Good: Adapts to content
-<button className="px-4 py-2">Submit</button>
-```
-
-**RTL (Right-to-Left) support**:
-```css
-/* Use logical properties */
-margin-inline-start: 1rem; /* Not margin-left */
-padding-inline: 1rem; /* Not padding-left/right */
-border-inline-end: 1px solid; /* Not border-right */
-
-/* Or use dir attribute */
-[dir="rtl"] .arrow { transform: scaleX(-1); }
-```
-
-**Character set support**:
-- Use UTF-8 encoding everywhere
-- Test with Chinese/Japanese/Korean (CJK) characters
-- Test with emoji (they can be 2-4 bytes)
-- Handle different scripts (Latin, Cyrillic, Arabic, etc.)
-
-**Date/Time formatting**:
-```javascript
-// ✅ Use Intl API for proper formatting
-new Intl.DateTimeFormat('en-US').format(date); // 1/15/2024
-new Intl.DateTimeFormat('de-DE').format(date); // 15.1.2024
-
-new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: 'USD'
-}).format(1234.56); // $1,234.56
-```
-
-**Pluralization**:
-```javascript
-// ❌ Bad: Assumes English pluralization
-`${count} item${count !== 1 ? 's' : ''}`
-
-// ✅ Good: Use proper i18n library
-t('items', { count }) // Handles complex plural rules
-```
-
-### Error Handling
-
-**Network errors**:
-- Show clear error messages
-- Provide retry button
-- Explain what happened
-- Offer offline mode (if applicable)
-- Handle timeout scenarios
-
-```jsx
-// Error states with recovery
-{error && (
- <ErrorMessage>
- <p>Failed to load data. {error.message}</p>
- <button onClick={retry}>Try again</button>
- </ErrorMessage>
-)}
-```
-
-**Form validation errors**:
-- Inline errors near fields
-- Clear, specific messages
-- Suggest corrections
-- Don't block submission unnecessarily
-- Preserve user input on error
-
-**API errors**:
-- Handle each status code appropriately
- - 400: Show validation errors
- - 401: Redirect to login
- - 403: Show permission error
- - 404: Show not found state
- - 429: Show rate limit message
- - 500: Show generic error, offer support
-
-**Graceful degradation**:
-- Core functionality works without JavaScript
-- Images have alt text
-- Progressive enhancement
-- Fallbacks for unsupported features
-
-### Edge Cases & Boundary Conditions
-
-**Empty states**:
-- No items in list
-- No search results
-- No notifications
-- No data to display
-- Provide clear next action
-
-**Loading states**:
-- Initial load
-- Pagination load
-- Refresh
-- Show what's loading ("Loading your projects...")
-- Time estimates for long operations
-
-**Large datasets**:
-- Pagination or virtual scrolling
-- Search/filter capabilities
-- Performance optimization
-- Don't load all 10,000 items at once
-
-**Concurrent operations**:
-- Prevent double-submission (disable button while loading)
-- Handle race conditions
-- Optimistic updates with rollback
-- Conflict resolution
-
-**Permission states**:
-- No permission to view
-- No permission to edit
-- Read-only mode
-- Clear explanation of why
-
-**Browser compatibility**:
-- Polyfills for modern features
-- Fallbacks for unsupported CSS
-- Feature detection (not browser detection)
-- Test in target browsers
-
-### Input Validation & Sanitization
-
-**Client-side validation**:
-- Required fields
-- Format validation (email, phone, URL)
-- Length limits
-- Pattern matching
-- Custom validation rules
-
-**Server-side validation** (always):
-- Never trust client-side only
-- Validate and sanitize all inputs
-- Protect against injection attacks
-- Rate limiting
-
-**Constraint handling**:
-```html
-<!-- Set clear constraints -->
-<input
- type="text"
- maxlength="100"
- pattern="[A-Za-z0-9]+"
- required
- aria-describedby="username-hint"
-/>
-<small id="username-hint">
- Letters and numbers only, up to 100 characters
-</small>
-```
-
-### Accessibility Resilience
-
-**Keyboard navigation**:
-- All functionality accessible via keyboard
-- Logical tab order
-- Focus management in modals
-- Skip links for long content
-
-**Screen reader support**:
-- Proper ARIA labels
-- Announce dynamic changes (live regions)
-- Descriptive alt text
-- Semantic HTML
-
-**Motion sensitivity**:
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**High contrast mode**:
-- Test in Windows high contrast mode
-- Don't rely only on color
-- Provide alternative visual cues
-
-### Performance Resilience
-
-**Slow connections**:
-- Progressive image loading
-- Skeleton screens
-- Optimistic UI updates
-- Offline support (service workers)
-
-**Memory leaks**:
-- Clean up event listeners
-- Cancel subscriptions
-- Clear timers/intervals
-- Abort pending requests on unmount
-
-**Throttling & Debouncing**:
-```javascript
-// Debounce search input
-const debouncedSearch = debounce(handleSearch, 300);
-
-// Throttle scroll handler
-const throttledScroll = throttle(handleScroll, 100);
-```
-
-## Testing Strategies
-
-**Manual testing**:
-- Test with extreme data (very long, very short, empty)
-- Test in different languages
-- Test offline
-- Test slow connection (throttle to 3G)
-- Test with screen reader
-- Test keyboard-only navigation
-- Test on old browsers
-
-**Automated testing**:
-- Unit tests for edge cases
-- Integration tests for error scenarios
-- E2E tests for critical paths
-- Visual regression tests
-- Accessibility tests (axe, WAVE)
-
-**IMPORTANT**: Hardening is about expecting the unexpected. Real users will do things you never imagined.
-
-**NEVER**:
-- Assume perfect input (validate everything)
-- Ignore internationalization (design for global)
-- Leave error messages generic ("Error occurred")
-- Forget offline scenarios
-- Trust client-side validation alone
-- Use fixed widths for text
-- Assume English-length text
-- Block entire interface when one component errors
-
-## Verify Hardening
-
-Test thoroughly with edge cases:
-
-- **Long text**: Try names with 100+ characters
-- **Emoji**: Use emoji in all text fields
-- **RTL**: Test with Arabic or Hebrew
-- **CJK**: Test with Chinese/Japanese/Korean
-- **Network issues**: Disable internet, throttle connection
-- **Large datasets**: Test with 1000+ items
-- **Concurrent actions**: Click submit 10 times rapidly
-- **Errors**: Force API errors, test all error states
-- **Empty**: Remove all data, test empty states
-
-When edge cases are covered, hand off to `/impeccable polish` for the final pass.
@@ -1,234 +0,0 @@
-# Heuristics Scoring Guide
-
-Score each of Nielsen's 10 Usability Heuristics on a 0–4 scale. Be honest: a 4 means genuinely excellent, not "good enough."
-
-## Nielsen's 10 Heuristics
-
-### 1. Visibility of System Status
-
-Keep users informed about what's happening through timely, appropriate feedback.
-
-**Check for**:
-- Loading indicators during async operations
-- Confirmation of user actions (save, submit, delete)
-- Progress indicators for multi-step processes
-- Current location in navigation (breadcrumbs, active states)
-- Form validation feedback (inline, not just on submit)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No feedback; user is guessing what happened |
-| 1 | Rare feedback; most actions produce no visible response |
-| 2 | Partial; some states communicated, major gaps remain |
-| 3 | Good; most operations give clear feedback, minor gaps |
-| 4 | Excellent; every action confirms, progress is always visible |
-
-### 2. Match Between System and Real World
-
-Speak the user's language. Follow real-world conventions. Information appears in natural, logical order.
-
-**Check for**:
-- Familiar terminology (no unexplained jargon)
-- Logical information order matching user expectations
-- Recognizable icons and metaphors
-- Domain-appropriate language for the target audience
-- Natural reading flow (left-to-right, top-to-bottom priority)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Pure tech jargon, alien to users |
-| 1 | Mostly confusing; requires domain expertise to navigate |
-| 2 | Mixed; some plain language, some jargon leaks through |
-| 3 | Mostly natural; occasional term needs context |
-| 4 | Speaks the user's language fluently throughout |
-
-### 3. User Control and Freedom
-
-Users need a clear "emergency exit" from unwanted states without extended dialogue.
-
-**Check for**:
-- Undo/redo functionality
-- Cancel buttons on forms and modals
-- Clear navigation back to safety (home, previous)
-- Easy way to clear filters, search, selections
-- Escape from long or multi-step processes
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Users get trapped; no way out without refreshing |
-| 1 | Difficult exits; must find obscure paths to escape |
-| 2 | Some exits; main flows have escape, edge cases don't |
-| 3 | Good control; users can exit and undo most actions |
-| 4 | Full control; undo, cancel, back, and escape everywhere |
-
-### 4. Consistency and Standards
-
-Users shouldn't wonder whether different words, situations, or actions mean the same thing.
-
-**Check for**:
-- Consistent terminology throughout the interface
-- Same actions produce same results everywhere
-- Platform conventions followed (standard UI patterns)
-- Visual consistency (colors, typography, spacing, components)
-- Consistent interaction patterns (same gesture = same behavior)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Inconsistent everywhere; feels like different products stitched together |
-| 1 | Many inconsistencies; similar things look/behave differently |
-| 2 | Partially consistent; main flows match, details diverge |
-| 3 | Mostly consistent; occasional deviation, nothing confusing |
-| 4 | Fully consistent; cohesive system, predictable behavior |
-
-### 5. Error Prevention
-
-Better than good error messages is a design that prevents problems in the first place.
-
-**Check for**:
-- Confirmation before destructive actions (delete, overwrite)
-- Constraints preventing invalid input (date pickers, dropdowns)
-- Smart defaults that reduce errors
-- Clear labels that prevent misunderstanding
-- Autosave and draft recovery
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Errors easy to make; no guardrails anywhere |
-| 1 | Few safeguards; some inputs validated, most aren't |
-| 2 | Partial prevention; common errors caught, edge cases slip |
-| 3 | Good prevention; most error paths blocked proactively |
-| 4 | Excellent; errors nearly impossible through smart constraints |
-
-### 6. Recognition Rather Than Recall
-
-Minimize memory load. Make objects, actions, and options visible or easily retrievable.
-
-**Check for**:
-- Visible options (not buried in hidden menus)
-- Contextual help when needed (tooltips, inline hints)
-- Recent items and history
-- Autocomplete and suggestions
-- Labels on icons (not icon-only navigation)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Heavy memorization; users must remember paths and commands |
-| 1 | Mostly recall; many hidden features, few visible cues |
-| 2 | Some aids; main actions visible, secondary features hidden |
-| 3 | Good recognition; most things discoverable, few memory demands |
-| 4 | Everything discoverable; users never need to memorize |
-
-### 7. Flexibility and Efficiency of Use
-
-Accelerators, invisible to novices, speed up expert interaction.
-
-**Check for**:
-- Keyboard shortcuts for common actions
-- Customizable interface elements
-- Recent items and favorites
-- Bulk/batch actions
-- Power user features that don't complicate the basics
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | One rigid path; no shortcuts or alternatives |
-| 1 | Limited flexibility; few alternatives to the main path |
-| 2 | Some shortcuts; basic keyboard support, limited bulk actions |
-| 3 | Good accelerators; keyboard nav, some customization |
-| 4 | Highly flexible; multiple paths, power features, customizable |
-
-### 8. Aesthetic and Minimalist Design
-
-Interfaces should not contain irrelevant or rarely needed information. Every element should serve a purpose.
-
-**Check for**:
-- Only necessary information visible at each step
-- Clear visual hierarchy directing attention
-- Purposeful use of color and emphasis
-- No decorative clutter competing for attention
-- Focused, uncluttered layouts
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Overwhelming; everything competes for attention equally |
-| 1 | Cluttered; too much noise, hard to find what matters |
-| 2 | Some clutter; main content clear, periphery noisy |
-| 3 | Mostly clean; focused design, minor visual noise |
-| 4 | Perfectly minimal; every element earns its pixel |
-
-### 9. Help Users Recognize, Diagnose, and Recover from Errors
-
-Error messages should use plain language, precisely indicate the problem, and constructively suggest a solution.
-
-**Check for**:
-- Plain language error messages (no error codes for users)
-- Specific problem identification ("Email is missing @" not "Invalid input")
-- Actionable recovery suggestions
-- Errors displayed near the source of the problem
-- Non-blocking error handling (don't wipe the form)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Cryptic errors; codes, jargon, or no message at all |
-| 1 | Vague errors; "Something went wrong" with no guidance |
-| 2 | Clear but unhelpful; names the problem but not the fix |
-| 3 | Clear with suggestions; identifies problem and offers next steps |
-| 4 | Perfect recovery; pinpoints issue, suggests fix, preserves user work |
-
-### 10. Help and Documentation
-
-Even if the system is usable without docs, help should be easy to find, task-focused, and concise.
-
-**Check for**:
-- Searchable help or documentation
-- Contextual help (tooltips, inline hints, guided tours)
-- Task-focused organization (not feature-organized)
-- Concise, scannable content
-- Easy access without leaving current context
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No help available anywhere |
-| 1 | Help exists but hard to find or irrelevant |
-| 2 | Basic help; FAQ or docs exist, not contextual |
-| 3 | Good documentation; searchable, mostly task-focused |
-| 4 | Excellent contextual help; right info at the right moment |
-
----
-
-## Score Summary
-
-**Total possible**: 40 points (10 heuristics × 4 max)
-
-| Score Range | Rating | What It Means |
-|-------------|--------|---------------|
-| 36–40 | Excellent | Minor polish only; ship it |
-| 28–35 | Good | Address weak areas, solid foundation |
-| 20–27 | Acceptable | Significant improvements needed before users are happy |
-| 12–19 | Poor | Major UX overhaul required; core experience broken |
-| 0–11 | Critical | Redesign needed; unusable in current state |
-
----
-
-## Issue Severity (P0–P3)
-
-Tag each individual issue found during scoring with a priority level:
-
-| Priority | Name | Description | Action |
-|----------|------|-------------|--------|
-| **P0** | Blocking | Prevents task completion entirely | Fix immediately; this is a showstopper |
-| **P1** | Major | Causes significant difficulty or confusion | Fix before release |
-| **P2** | Minor | Annoyance, but workaround exists | Fix in next pass |
-| **P3** | Polish | Nice-to-fix, no real user impact | Fix if time permits |
-
-**Tip**: If you're unsure between two levels, ask: "Would a user contact support about this?" If yes, it's at least P1.
@@ -1,195 +0,0 @@
-# Interaction Design
-
-## The Eight Interactive States
-
-Every interactive element needs these states designed:
-
-| State | When | Visual Treatment |
-|-------|------|------------------|
-| **Default** | At rest | Base styling |
-| **Hover** | Pointer over (not touch) | Subtle lift, color shift |
-| **Focus** | Keyboard/programmatic focus | Visible ring (see below) |
-| **Active** | Being pressed | Pressed in, darker |
-| **Disabled** | Not interactive | Reduced opacity, no pointer |
-| **Loading** | Processing | Spinner, skeleton |
-| **Error** | Invalid state | Red border, icon, message |
-| **Success** | Completed | Green check, confirmation |
-
-**The common miss**: Designing hover without focus, or vice versa. They're different. Keyboard users never see hover states.
-
-## Focus Rings: Do Them Right
-
-**Never `outline: none` without replacement.** It's an accessibility violation. Instead, use `:focus-visible` to show focus only for keyboard users:
-
-```css
-/* Hide focus ring for mouse/touch */
-button:focus {
- outline: none;
-}
-
-/* Show focus ring for keyboard */
-button:focus-visible {
- outline: 2px solid var(--color-accent);
- outline-offset: 2px;
-}
-```
-
-**Focus ring design**:
-- High contrast (3:1 minimum against adjacent colors)
-- 2-3px thick
-- Offset from element (not inside it)
-- Consistent across all interactive elements
-
-## Form Design: The Non-Obvious
-
-**Placeholders aren't labels.** They disappear on input. Always use visible `<label>` elements. **Validate on blur**, not on every keystroke (exception: password strength). Place errors **below** fields with `aria-describedby` connecting them.
-
-## Loading States
-
-**Optimistic updates**: Show success immediately, rollback on failure. Use for low-stakes actions (likes, follows), not payments or destructive actions. **Skeleton screens > spinners**: they preview content shape and feel faster than generic spinners.
-
-## Modals: The Inert Approach
-
-Focus trapping in modals used to require complex JavaScript. Now use the `inert` attribute:
-
-```html
-<!-- When modal is open -->
-<main inert>
- <!-- Content behind modal can't be focused or clicked -->
-</main>
-<dialog open>
- <h2>Modal Title</h2>
- <!-- Focus stays inside modal -->
-</dialog>
-```
-
-Or use the native `<dialog>` element:
-
-```javascript
-const dialog = document.querySelector('dialog');
-dialog.showModal(); // Opens with focus trap, closes on Escape
-```
-
-## The Popover API
-
-For tooltips, dropdowns, and non-modal overlays, use native popovers:
-
-```html
-<button popovertarget="menu">Open menu</button>
-<div id="menu" popover>
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-**Benefits**: Light-dismiss (click outside closes), proper stacking, no z-index wars, accessible by default.
-
-## Dropdown & Overlay Positioning
-
-Dropdowns rendered with `position: absolute` inside a container that has `overflow: hidden` or `overflow: auto` will be clipped. This is the single most common dropdown bug in generated code.
-
-### CSS Anchor Positioning
-
-The modern solution uses the CSS Anchor Positioning API to tether an overlay to its trigger without JavaScript:
-
-```css
-.trigger {
- anchor-name: --menu-trigger;
-}
-
-.dropdown {
- position: fixed;
- position-anchor: --menu-trigger;
- position-area: block-end span-inline-end;
- margin-top: 4px;
-}
-
-/* Flip above if no room below */
-@position-try --flip-above {
- position-area: block-start span-inline-end;
- margin-bottom: 4px;
-}
-```
-
-Because the dropdown uses `position: fixed`, it escapes any `overflow` clipping on ancestor elements. The `@position-try` block handles viewport edges automatically. **Browser support**: Chrome 125+, Edge 125+. Not yet in Firefox or Safari - use a fallback for those browsers.
-
-### Popover + Anchor Combo
-
-Combining the Popover API with anchor positioning gives you stacking, light-dismiss, accessibility, and correct positioning in one pattern:
-
-```html
-<button popovertarget="menu" class="trigger">Open</button>
-<div id="menu" popover class="dropdown">
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-The `popover` attribute places the element in the **top layer**, which sits above all other content regardless of z-index or overflow. No portal needed.
-
-### Portal / Teleport Pattern
-
-In component frameworks, render the dropdown at the document root and position it with JavaScript:
-
-- **React**: `createPortal(dropdown, document.body)`
-- **Vue**: `<Teleport to="body">`
-- **Svelte**: Use a portal library or mount to `document.body`
-
-Calculate position from the trigger's `getBoundingClientRect()`, then apply `position: fixed` with `top` and `left` values. Recalculate on scroll and resize.
-
-### Fixed Positioning Fallback
-
-For browsers without anchor positioning support, `position: fixed` with manual coordinates avoids overflow clipping:
-
-```css
-.dropdown {
- position: fixed;
- /* top/left set via JS from trigger's getBoundingClientRect() */
-}
-```
-
-Check viewport boundaries before rendering. If the dropdown would overflow the bottom edge, flip it above the trigger. If it would overflow the right edge, align it to the trigger's right side instead.
-
-### Anti-Patterns
-
-- **`position: absolute` inside `overflow: hidden`** - The dropdown will be clipped. Use `position: fixed` or the top layer instead.
-- **Arbitrary z-index values** like `z-index: 9999` - Use a semantic z-index scale: `dropdown (100) -> sticky (200) -> modal-backdrop (300) -> modal (400) -> toast (500) -> tooltip (600)`.
-- **Rendering dropdown markup inline** without an escape hatch from the parent's stacking context. Either use `popover` (top layer), a portal, or `position: fixed`.
-
-## Destructive Actions: Undo > Confirm
-
-**Undo is better than confirmation dialogs.** Users click through confirmations mindlessly. Remove from UI immediately, show undo toast, actually delete after toast expires. Use confirmation only for truly irreversible actions (account deletion), high-cost actions, or batch operations.
-
-## Keyboard Navigation Patterns
-
-### Roving Tabindex
-
-For component groups (tabs, menu items, radio groups), one item is tabbable; arrow keys move within:
-
-```html
-<div role="tablist">
- <button role="tab" tabindex="0">Tab 1</button>
- <button role="tab" tabindex="-1">Tab 2</button>
- <button role="tab" tabindex="-1">Tab 3</button>
-</div>
-```
-
-Arrow keys move `tabindex="0"` between items. Tab moves to the next component entirely.
-
-### Skip Links
-
-Provide skip links (`<a href="#main-content">Skip to main content</a>`) for keyboard users to jump past navigation. Hide off-screen, show on focus.
-
-## Gesture Discoverability
-
-Swipe-to-delete and similar gestures are invisible. Hint at their existence:
-
-- **Partially reveal**: Show delete button peeking from edge
-- **Onboarding**: Coach marks on first use
-- **Alternative**: Always provide a visible fallback (menu with "Delete")
-
-Don't rely on gestures as the only way to perform actions.
-
----
-
-**Avoid**: Removing focus indicators without alternatives. Using placeholder text as labels. Touch targets <44x44px. Generic error messages. Custom controls without ARIA/keyboard support.
@@ -1,141 +0,0 @@
-Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids, the centered-stack default) and fix the structure, not the surface.
-
----
-
-## Register
-
-Brand: asymmetric compositions, fluid spacing with `clamp()`, intentional grid-breaking for emphasis. Rhythm through contrast: tight groupings paired with generous separations.
-
-Product: predictable grids, consistent densities, familiar navigation patterns. Responsive behavior is structural (collapse sidebar, responsive table), not fluid typography. Consistency IS an affordance.
-
----
-
-## Assess Current Layout
-
-Analyze what's weak about the current spatial design:
-
-1. **Spacing**:
- - Is spacing consistent or arbitrary? (Random padding/margin values)
- - Is all spacing the same? (Equal padding everywhere = no rhythm)
- - Are related elements grouped tightly, with generous space between groups?
-
-2. **Visual hierarchy**:
- - Apply the squint test: blur your (metaphorical) eyes. Can you still identify the most important element, second most important, and clear groupings?
- - Is hierarchy achieved effectively? (Space and weight alone can be enough; is the current approach working?)
- - Does whitespace guide the eye to what matters?
-
-3. **Grid & structure**:
- - Is there a clear underlying structure, or does the layout feel random?
- - Are identical card grids used everywhere? (Icon + heading + text, repeated endlessly)
- - Is everything centered? (Left-aligned with asymmetric layouts feels more designed, but not a hard and fast rule)
-
-4. **Rhythm & variety**:
- - Does the layout have visual rhythm? (Alternating tight/generous spacing)
- - Is every section structured the same way? (Monotonous repetition)
- - Are there intentional moments of surprise or emphasis?
-
-5. **Density**:
- - Is the layout too cramped? (Not enough breathing room)
- - Is the layout too sparse? (Excessive whitespace without purpose)
- - Does density match the content type? (Data-dense UIs need tighter spacing; marketing pages need more air)
-
-**CRITICAL**: Layout problems are often the root cause of interfaces feeling "off" even when colors and fonts are fine. Space is a design material; use it with intention.
-
-## Plan Layout Improvements
-
-Consult the [spatial design reference](spatial-design.md) for detailed guidance on grids, rhythm, and container queries.
-
-Create a systematic plan:
-
-- **Spacing system**: Use a consistent scale (a framework's built-in scale like Tailwind's, rem-based tokens, or a custom system). The specific values matter less than consistency.
-- **Hierarchy strategy**: How will space communicate importance?
-- **Layout approach**: What structure fits the content? Flex for 1D, Grid for 2D, named areas for complex page layouts.
-- **Rhythm**: Where should spacing be tight vs generous?
-
-## Improve Layout Systematically
-
-### Establish a Spacing System
-
-- Use a consistent spacing scale (framework scales like Tailwind, rem-based tokens, or a custom scale all work). What matters is that values come from a defined set, not arbitrary numbers.
-- Name tokens semantically if using custom properties: `--space-xs` through `--space-xl`, not `--spacing-8`
-- Use `gap` for sibling spacing instead of margins; eliminates margin collapse hacks
-- Apply `clamp()` for fluid spacing that breathes on larger screens
-
-### Create Visual Rhythm
-
-- **Tight grouping** for related elements (8-12px between siblings)
-- **Generous separation** between distinct sections (48-96px)
-- **Varied spacing** within sections (not every row needs the same gap)
-- **Asymmetric compositions**: break the predictable centered-content pattern when it makes sense
-
-### Choose the Right Layout Tool
-
-- **Use Flexbox for 1D layouts**: Rows of items, nav bars, button groups, card contents, most component internals. Flex is simpler and more appropriate for the majority of layout tasks.
-- **Use Grid for 2D layouts**: Page-level structure, dashboards, data-dense interfaces, anything where rows AND columns need coordinated control.
-- **Don't default to Grid** when Flexbox with `flex-wrap` would be simpler and more flexible.
-- Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints.
-- Use named grid areas (`grid-template-areas`) for complex page layouts; redefine at breakpoints.
-
-### Break Card Grid Monotony
-
-- Don't default to card grids for everything; spacing and alignment create visual grouping naturally
-- Use cards only when content is truly distinct and actionable. Never nest cards inside cards
-- Vary card sizes, span columns, or mix cards with non-card content to break repetition
-
-### Strengthen Visual Hierarchy
-
-- Use the fewest dimensions needed for clear hierarchy. Space alone can be enough; generous whitespace around an element draws the eye. Some of the most polished designs achieve rhythm with just space and weight. Add color or size contrast only when simpler means aren't sufficient.
-- Be aware of reading flow: in LTR languages, the eye naturally scans top-left to bottom-right, but primary action placement depends on context (e.g., bottom-right in dialogs, top in navigation).
-- Create clear content groupings through proximity and separation.
-
-### Manage Depth & Elevation
-
-- Create a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip)
-- Build a consistent shadow scale (sm → md → lg → xl); shadows should be subtle
-- Use elevation to reinforce hierarchy, not as decoration
-
-### Optical Adjustments
-
-- If an icon looks visually off-center despite being geometrically centered, nudge it. But only if you're confident it actually looks wrong. Don't adjust speculatively.
-
-**NEVER**:
-- Use arbitrary spacing values outside your scale
-- Make all spacing equal (variety creates hierarchy)
-- Wrap everything in cards (not everything needs a container)
-- Nest cards inside cards (use spacing and dividers for hierarchy within)
-- Use identical card grids everywhere (icon + heading + text, repeated)
-- Center everything (left-aligned with asymmetry feels more designed)
-- Default to the hero metric layout (big number, small label, stats, gradient) as a template. If showing real user data, a prominent metric can work, but it should display actual data, not decorative numbers.
-- Default to CSS Grid when Flexbox would be simpler; use the simplest tool for the job
-- Use arbitrary z-index values (999, 9999); build a semantic scale
-
-## Verify Layout Improvements
-
-- **Squint test**: Can you identify primary, secondary, and groupings with blurred vision?
-- **Rhythm**: Does the page have a satisfying beat of tight and generous spacing?
-- **Hierarchy**: Is the most important content obvious within 2 seconds?
-- **Breathing room**: Does the layout feel comfortable, not cramped or wasteful?
-- **Consistency**: Is the spacing system applied uniformly?
-- **Responsiveness**: Does the layout adapt gracefully across screen sizes?
-
-When the rhythm and hierarchy land, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `density` param. Drive all spacing tokens in the variant's scoped CSS through `calc(var(--p-density, 1) * <base>)`: paddings, gaps, column widths. Users slide from airy to packed and see layout re-breathe with no regeneration.
-
-```json
-{"id":"density","kind":"range","min":0.6,"max":1.4,"step":0.05,"default":1,"label":"Density"}
-```
-
-For variants whose topology genuinely changes (stacked vs. side-by-side, grid vs. bento), use a `steps` param whose scoped CSS branches via `:scope[data-p-structure="X"]`. One structure param + one density param is a powerful combo; resist adding a third.
-
-```json
-{"id":"structure","kind":"steps","default":"grid","label":"Structure","options":[
- {"value":"stacked","label":"Stacked"},
- {"value":"grid","label":"Grid"},
- {"value":"bento","label":"Bento"}
-]}
-```
-
-See `reference/live.md` for the full params contract.
@@ -1,622 +0,0 @@
-Interactive live variant mode: select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via the dev server's HMR.
-
-## Prerequisites
-
-A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR a static HTML file open in the browser.
-
-## The contract (read once)
-
-Execute in order. No step skipped, no step reordered.
-
-1. `live.mjs`: boot.
-2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.
-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.
-5. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
-6. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
-7. On `exit`: run the cleanup at the bottom.
-
-Harness policy:
-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.
-- **Cursor**: run the poll in the **foreground** (blocking shell; not a background terminal, not a subagent). Cursor background terminals and subagents do not reliably resume the chat with poll stdout.
-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.
-- **Other harnesses**: foreground unless you know stdout reliably returns to this session.
-
-Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.
-
-## Start
-
-```bash
-node .rovodev/skills/impeccable/scripts/live.mjs
-```
-
-Output JSON: `{ ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath, migrated }`. `pageFiles` is the list of HTML entries the live script was injected into. Keep PRODUCT.md and DESIGN.md in mind for variant generation; **DESIGN.md wins on visual decisions; PRODUCT.md wins on strategic/voice decisions.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt. If `migrated: true`, the loader auto-renamed legacy `.impeccable.md` to `PRODUCT.md`; mention this once and suggest `/impeccable document` for the matching DESIGN.md.
-
-`serverPort` and `serverToken` belong to the small **Impeccable live helper** HTTP server (serves `/live.js`, SSE, and `/poll`). That port is **not** your dev server and is usually not the URL you open to view the app. The browser page is whatever origin serves one of the `pageFiles` entries (Vite / Next / Bun / tunnel / LAN hostname).
-
-If output is `{ ok: false, error: "config_missing" | "config_invalid", path }`, this project hasn't been configured for live mode (or its config is stale). See **First-time setup** at the bottom.
-
-## Poll loop
-
-```
-LOOP:
- node .rovodev/skills/impeccable/scripts/live-poll.mjs # default long timeout; no --timeout=
- Read JSON; dispatch on "type"
-
- "generate" → Handle Generate; reply done; LOOP
- "accept" → Handle Accept; complete carbonize cleanup if required; LOOP
- "discard" → Handle Discard; LOOP
- "prefetch" → Handle Prefetch; LOOP
- "timeout" → LOOP
- "exit" → break → Cleanup
-```
-
-## Recovery commands
-
-The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.
-
-Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:
-
-```bash
-node .rovodev/skills/impeccable/scripts/live-status.mjs
-node .rovodev/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID
-node .rovodev/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID
-```
-
-- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.
-- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.
-- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.
-
-Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.
-
-## Handle `generate`
-
-Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.
-
-Speed matters; the user is watching a spinner. Minimize tool calls by using the `wrap` helper and writing all variants in a single edit.
-
-### 1. Read the screenshot (if present)
-
-`event.screenshotPath` is **only sent when the user placed at least one comment or stroke before Go.** When present, it's an absolute path to a PNG of the element as rendered with the annotations baked in. **Read it before planning**: annotations encode user intent not recoverable from `element.outerHTML` alone.
-
-When `screenshotPath` is absent, don't ask for one and don't go looking for the current rendering. The omission is deliberate: without annotations, a screenshot would anchor the model on the existing design and fight the three-distinct-directions brief. Work from `element.outerHTML`, the computed styles in `event.element`, and the freeform prompt if present.
-
-`event.comments` and `event.strokes` carry structured metadata alongside the visual. Treat the screenshot as primary; use the structured data for specifics worth quoting (e.g. the exact text of a comment).
-
-Reading annotations precisely:
-
-- **Comment position carries meaning.** Its `{x, y}` is element-local CSS px (same coord space as `element.boundingRect`). Find the child under that point and apply the comment text LOCALLY to that sub-element. A comment near the title is about the title, not a global description.
-- **Comments and strokes are independent annotations** unless clearly paired by overlap or tight proximity. Don't let the visual weight of a prominent stroke override the precise location of a textually-specific comment elsewhere.
-- **Strokes are gestures; read them by shape.** Closed loop = "this thing" (emphasis / focus); arrow = direction (move / point to); cross or slash = delete; free scribble = emphasis or delete depending on context. A loop around region X means "pay attention to X," not "only change pixels inside X."
-- **When a stroke's intent is ambiguous** (circle or arrow? emphasis or move?), state your reading in one sentence of rationale rather than silently guessing. If the uncertainty materially changes the brief, ask one short clarifying question before generating.
-
-### 2. Wrap the element
-
-```bash
-node .rovodev/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"
-```
-
-Flag mapping. Keep them separate, don't collapse into `--query`:
-
-- `--element-id` ← `event.element.id`
-- `--classes` ← `event.element.classes` joined with commas
-- `--tag` ← `event.element.tagName`
-- `--text` ← first ~80 chars of `event.element.textContent` (trim, single-line). **Pass this every call.** When the picked element shares classes + tag with sibling components (a list of `<Card>`s, repeating sections), this is what disambiguates which branch in source to wrap. Without it, wrap silently lands on the first match and may rewrite the wrong element.
-
-The helper searches ID first, then classes, then tag + class combo. If `event.pageUrl` implies the file (e.g. `/` is usually `index.html`), pass `--file PATH` to skip the search. `--query` is a fallback for raw text search only; do not use it for normal element lookups.
-
-If `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.
-
-Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.
-
-`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:
-
-- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.
-- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.
-
-Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.
-
-**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:
-
-- `{ error: "file_is_generated", file, hint }`: user-supplied `--file` points at a generated file.
-- `{ error: "element_not_in_source", generatedMatch, hint }`: element exists only in a generated file (the next build would wipe any edits).
-- `{ error: "element_not_found", hint }`: element isn't in any project file; likely runtime-injected (JS component, dynamic render from data).
-
-All three carry `fallback: "agent-driven"`. Follow **Handle fallback** below.
-
-### 3. Load the action's reference
-
-If `event.action` is `impeccable` (the default freeform action), use SKILL.md's shared laws plus the loaded register reference (`brand.md` or `product.md`). Do not load a sub-command reference. **Freeform is not a pass to skip parameters:** you still follow the composition budget and the freeform bias in **§7 Parameters** below. Sub-command files list MUST-have signature knobs; freeform has no such file, so sizing knobs from surface weight and primary axes is entirely on you.
-
-Any other `event.action` (`bolder`, `quieter`, `distill`, `polish`, `typeset`, `colorize`, `layout`, `adapt`, `animate`, `delight`, `overdrive`): Read `reference/<action>.md` before planning. Each sub-command encodes a specific discipline; skipping its reference produces generic output. Those files may require specific params; layer them on top of the §7 budget, not instead of it.
-
-### 4. Plan three variants: identity first, then mode, then axes
-
-The wrong frame for live mode is "show three different design directions." Live runs on an existing surface; the brand has already been chosen. The job is variation **within identity**, not selection between identities. Failure mode: three editorial-typographic variants on a brief that wasn't editorial. Bigger failure mode: three off-brand variants the user can't accept because they don't look like their product.
-
-Four phases. Do them in order.
-
-#### Phase A: Extract the identity (non-skippable)
-
-The existing surface has an identity already. Read it before planning anything. Sources, in priority order:
-
-1. **DESIGN.md** if loaded: read the visual system fields (palette, type pairing, motion, components). This is the authoritative answer.
-2. **CSS custom properties** in the page's stylesheets (`:root { --color-...; --font-...; ... }`): these are de-facto tokens.
-3. **Computed styles** on the picked element and its parent: colors, fonts, spacing scales, corner radii.
-4. **Sibling components on the page**: what visual rhetoric do existing components use? (Asymmetric or centered? Dense or airy? Bold or quiet?)
-
-Write down what you see in **one sentence**. The sentence describes the surface that's actually on screen; it is not aspirational, not opinionated, not edited toward what the brand "should" be. Capture, in roughly this order:
-
-- The dominant surface color and accent color, by hex or token name (use the actual values, not categories like "warm" or "neutral").
-- The type pairing: the actual font names loaded, primary first.
-- The layout topology: how the dominant elements are arranged (stacked / side-by-side / grid / asymmetric / overlay).
-- The surface treatment: corners, borders, shadows, density of decoration.
-- The voice tone you read off the copy itself, not off the aesthetic feel.
-
-Be specific. "Modern" is not a color, "elegant" is not a type pairing, "clean" is not a layout. If you can't extract a real value for an axis, skip it rather than fabricate. The point is to record what is, not to describe what you wish it were.
-
-Do not include adjectives that name an aesthetic family ("editorial-leaning", "terminal-flavored", "brutalist"); those are conclusions, not data. They belong to Phase C lane selection in departure mode, not to identity description. Letting them sneak into Phase A is how the identity-lock collapses into a self-fulfilling prophecy.
-
-This sentence is the **identity lock**. Every variant must be readable as the same brand if rendered side by side. Skipping this phase is the primary cause of off-brand variants. Absence of DESIGN.md is never an excuse; extract from CSS and computed styles instead.
-
-#### Phase B: Pick mode (default vs departure)
-
-**Default mode**: the existing identity is preserved. Variants vary expression axes within it. *This is the right mode for ~90% of live sessions.* The user picked an element on a real product they're shipping; they expect variants of *their* hero, not three different brands' heroes.
-
-**Departure mode**: the existing identity is rejected. Variants propose alternatives consistent with PRODUCT.md voice. Trigger only when at least one is true:
-
-- PRODUCT.md anti-references explicitly call out the current surface ("the current `index.html` is itself an example"; "diffuse away from this"; "the page on screen is the failure"). Generic anti-references that describe what to avoid in general do **not** trigger departure mode; only ones that point at *this* surface specifically.
-- The user's freeform prompt explicitly asks for departure ("rebuild this from scratch", "what if it weren't editorial at all", "show me something completely different").
-
-If you're unsure, you're in default mode. The cost of being wrong about default is "three on-brand variants with similar feel": recoverable, the user picks none. The cost of being wrong about departure is "three off-brand variants": unrecoverable, the user is annoyed.
-
-#### Phase C: Plan three variants
-
-**Default mode.** Each variant commits to a different **primary axis** of difference, while preserving the identity sentence. The six axes:
-
-1. **Hierarchy**: which element commands the eye?
-2. **Layout topology**: stacked / side-by-side / grid / asymmetric / overlay
-3. **Typographic system**: pairing logic, scale ratio, case/weight strategy *within the available faces*
-4. **Color strategy**: which existing palette role carries the surface (Restrained / Committed / Full palette / Drenched). Use the brand's existing palette tokens, not new colors.
-5. **Density**: minimal / comfortable / dense
-6. **Structural decomposition**: merge, split, progressive disclosure
-
-Three variants → three DIFFERENT axes. The trio reads as *the same brand at three angles*. Do not introduce new fonts, new palette hues, or new aesthetic-family signals; those belong to departure mode.
-
-**While planning each variant, also name its 2–3 parameter knobs** (per the §7 budget table). Parameters are part of the design, not a decoration added afterward. If the variant explores density, expose a density knob. If it explores color commitment, expose a color-amount range. Deciding "what's tunable" during planning produces better knobs than retrofitting them onto finished HTML.
-
-**Departure mode.** Each variant anchors to a different **aesthetic direction**, derived from the brand's stated voice and register in PRODUCT.md. Do NOT pick from a fixed catalog of lane categories. The right three directions for this brand are not the same as the right three for another brand, and picking from a list is itself the training-data reflex (the model selects "Swiss-grid, Terminal, Industrial-signage" every time because those are the furthest-from-editorial items in any enumerated list).
-
-Instead, work from the brand:
-
-1. Read PRODUCT.md's Brand Personality words. What physical, spatial, or material experiences would embody those words if design were not involved? (A personality described as "specific, earned, unmistakable" evokes a hand-stamped letter, a numbered print, a watchmaker's loupe. A personality described as "restless, loud, unfiltered" evokes a concert poster, a spray-painted wall, a megaphone.)
-2. From those physical experiences, derive three visual directions that are genuinely different from each other AND from the current surface you're departing.
-3. Avoid the **reflex-reject lanes** in [brand.md](brand.md). Don't trade one monoculture for another. If you find yourself reaching for "Swiss-grid" or "Terminal" or "Industrial-signage" by reflex, you are pattern-matching a catalog in your training data, not reading the brand. Start over from the personality words.
-4. Each direction must be expressible in one concrete sentence that names a real-world referent ("a museum exhibition label system for a contemporary art gallery" not "clean and minimal"). If your sentence contains only adjectives, it's not concrete enough.
-5. **While planning each direction, also name its 2–3 parameter knobs** (per the §7 budget table). The same principle as default mode: decide "what's tunable" during planning, not after writing the HTML. A departure-mode hero with 0 parameters is not "bold creative vision," it's a missed opportunity for the user to fine-tune the direction they pick.
-
-#### Phase D: Squint test
-
-**Default mode squint.** Read each variant's identity sentence and compare to the locked identity from Phase A. If any variant has drifted to a different palette, type voice, or visual rhetoric, it has crossed into departure mode by accident; rework. Then check that each variant commits to a different primary axis. Three "tighter density" variants is failure.
-
-**Departure mode squint.** Two passes, family before sentence:
-
-1. **Family pass.** Label each variant with one design-family word of your own choosing (any concrete noun: *exhibition, storefront, cockpit, recipe-card, playbill, field-manual*). If any two variants share a label, or if the label could apply to the other variants equally well, rework. Do not use a fixed vocabulary list for the labels. *This pass is non-negotiable in departure mode and catches the monoculture failure that the sentence pass misses.*
-2. **Sentence pass.** Write three one-sentence descriptions side by side. If two of them rhyme ("both feature big type" / "both are stacks of sections" / "both center the CTA"), rework the offender.
-
-**When the primary axis is color or theme, forbid the trio from sharing theme + dominant hue.** Two dark-plus-one-dark is not distinct. Aim for three color worlds, not three shades of the same.
-
-**For action-specific invocations**, each variant must vary along the dimension the action names:
-
-- `bolder`: amplify a different dimension per variant (scale / saturation / structural change). Not three "slightly bigger" variants.
-- `quieter`: pull back a different dimension (color / ornament / spacing).
-- `distill`: remove a different class of excess (visual noise / redundant content / nested structure).
-- `polish`: target a different refinement axis (rhythm / hierarchy / micro-details like corner radii, focus states, optical kerning).
-- `typeset`: different type pairing AND different scale ratio each. Not three riffs on one pairing.
-- `colorize`: different hue family each (not shades of one hue). Vary chroma and contrast strategy.
-- `layout`: different structural arrangement (stacked / side-by-side / grid / asymmetric). Not spacing tweaks.
-- `adapt`: different target context per variant (mobile-first / tablet / desktop / print or low-data). Don't make three mobile layouts.
-- `animate`: different motion vocabulary (cascade stagger / clip wipe / scale-and-focus / morph / parallax). Not three staggered fades.
-- `delight`: different flavor of personality (unexpected micro-interaction / typographic surprise / illustrated accent / sonic-or-haptic moment / easter-egg interaction).
-- `overdrive`: different convention broken (scale / structure / motion / input model / state transitions). Skip `overdrive.md`'s "propose and ask" step; live mode is non-interactive.
-
-### 5. Apply the freeform prompt (if present)
-
-`event.freeformPrompt` is the user's ceiling on direction (all variants must honor it), but still explore meaningfully different *interpretations*. The interpretations stay within whichever mode you picked in Phase B.
-
-In **default mode**, the prompt narrows the axes you choose, not the identity. *"Make it feel more confident"* → variant 1 amplifies hierarchy (one element commands the eye), variant 2 commits the existing accent color (Committed strategy on the brand's hue), variant 3 tightens density and removes decorative slack. Three different axes, same brand.
-
-In **departure mode**, the prompt narrows the lanes you draw from, not the families. *"Make it feel like a newspaper front page"* would itself be a departure-mode prompt; honor it but pick three meaningfully different newspaper-adjacent lanes (broadsheet vs. tabloid vs. trade journal), and run the family pass to confirm they don't collapse into one.
-
-When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.
-
-### 6. Write all variants in a single edit
-
-Complete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).
-
-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).
-
-Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:
-
-```html
-<!-- Variants: insert below this line -->
-<style data-impeccable-css="SESSION_ID">
- /* rules matching cssAuthoring.rulePattern */
-</style>
-<div data-impeccable-variant="1">
- <!-- variant 1: full element replacement (single top-level element) -->
-</div>
-<div data-impeccable-variant="2" style="display: none">
- <!-- variant 2: full element replacement -->
-</div>
-<div data-impeccable-variant="3" style="display: none">
- <!-- variant 3: full element replacement -->
-</div>
-```
-
-**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.
-
-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.
-
-One edit, all variants; the browser's MutationObserver picks everything up in one pass.
-
-For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.
-
-**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:
-
-```tsx
-<style data-impeccable-css="SESSION_ID">{`
- @scope ([data-impeccable-variant="1"]) { ... }
- @scope ([data-impeccable-variant="2"]) { ... }
-`}</style>
-<div data-impeccable-variant="1">
- {/* variant 1 */}
-</div>
-<div data-impeccable-variant="2" style={{ display: 'none' }}>
- {/* variant 2 */}
-</div>
-```
-
-The wrap script already gives you a single-rooted JSX wrapper: a `<div data-impeccable-variants="…">` outer element with the marker comments tucked inside. Drop the variants block above into the "Variants: insert below this line" comment and the source stays valid TSX.
-
-### 7. Parameters (composition-sized, 0–4 per variant)
-
-Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement. The browser docks a small panel to the right of the outline with one control per parameter. The user drags/clicks and sees instant feedback: there is zero regeneration cost because the knob toggles a CSS variable or data attribute that the variant's scoped CSS is already authored against.
-
-**What “optional” does not mean.** Parameters are not nice-to-have decoration on large work. The word meant “omit controls that are redundant or cosmetic,” not “default to zero because three variants were enough work.”
-
-**When to add.** As soon as the variant’s scoped CSS has a meaningful continuous or stepped axis: density, color amount, type scale, motion intensity, column weight, and so on. If you can imagine the user muttering “a bit tighter” or “a touch more accent” **without** wanting a full regeneration, wire that axis. **Not** micro-margins or one-off nudges; those are not parameters.
-
-**Freeform (`action` is `impeccable`) bias.** You did not load a sub-command reference, so you must **choose** signature axes yourself. Match the budget table: for a hero or large composition, that means **2–3 axes per variant**, not 1. Prefer knobs that sit on the dimensions where your three variants actually differ (if density varies, expose it as a `steps` knob; if color commitment varies, expose it as a `range`). A hero that ships with **0** params is almost always a mistake, not a judgment call. A hero with exactly **1** param is underweight unless the design is genuinely a fixed-point comparison. Start from the budget table, not from zero.
-
-**Budget scales with the element's visual weight, not token budget.** Knobs need real estate to read as tunable; three sliders on a single control are noise.
-
-- **Leaf / tiny**: a single button, icon, input, bare heading, solitary paragraph: **0 params.**
-- **Small composition**: labeled input, simple card, short callout (≤ ~5 visual children): **0–1** params when one dominant axis is obvious; otherwise **0.**
-- **Medium composition**: section component, nav cluster, dense card, short feature block (6–15 visual children): **target 2**; **1** is acceptable if the block is simple; **0** only when variants are truly fixed points.
-- **Large composition**: hero section, full page region, spread layout, strong internal structure (16+ visual children or multiple sub-sections): **target 2–3**; **up to 4** when several independent axes (e.g. structure `steps` + `density` + one accent) are all authored in scoped CSS.
-
-**When in doubt, ask whether a dial exists before defaulting to zero.** The user can always request more variants, but the point of live mode is instant tuning without another Go. Crowding the panel is bad; **under-shipping** knobs on a dense composition is the more common failure for freeform. Count by **visual** children, not DOM depth; a shallow-but-wide hero is still large.
-
-**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.
-
-**How to declare.** Put a JSON manifest on the variant wrapper:
-
-```html
-<div data-impeccable-variant="1" data-impeccable-params='[
- {"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"},
- {"id":"density","kind":"steps","default":"snug","label":"Density","options":[
- {"value":"airy","label":"Airy"},
- {"value":"snug","label":"Snug"},
- {"value":"packed","label":"Packed"}
- ]},
- {"id":"serif","kind":"toggle","default":false,"label":"Serif display"}
-]'>
- ...variant content...
-</div>
-```
-
-**Three kinds:**
-
-- `range`: smooth slider. Drives a CSS custom property `--p-<id>` on the variant wrapper. Author CSS with `var(--p-color-amount, 0.5)`. Fields: `min`, `max`, `step`, `default` (number), `label`.
-- `steps`: segmented radio. Drives a data attribute `data-p-<id>` on the variant wrapper. Author CSS with `:scope[data-p-density="airy"] .grid { ... }`. Fields: `options` (array of `{value, label}`), `default` (string), `label`.
-- `toggle`: on/off switch. Drives BOTH a CSS var (`--p-<id>: 0|1`) and a data attribute (present when on, absent when off). Use whichever is more convenient. Fields: `default` (boolean), `label`.
-
-**Signature params per action.** For named sub-commands, read that action’s `reference/<action>.md` for one or two **MUST** params (e.g. `layout` → `density`). Those are non-negotiable when the design can express them. **Freeform has no file-level MUST**; the **Freeform (`impeccable`) bias** in this section is the stand-in. If the user’s action is both stylized and sub-command (e.g. `colorize`), the sub-command’s MUST list takes precedence for its axes; still respect the **Hard cap** and add no redundant duplicate knobs.
-
-**Reset on variant switch.** User dials density on v1, flips to v2, v2 starts at v2's declared defaults. Known limitation; preservation across variants may land later.
-
-**On accept**, the browser sends the user's current values in the accept event. `live-accept.mjs` writes them as a sibling comment:
-
-```html
-<!-- impeccable-param-values SESSION_ID: {"color-amount":0.7,"density":"packed"} -->
-```
-
-The carbonize cleanup step (see below) reads that comment and bakes the chosen values into the final CSS. For `steps`/`toggle` attribute selectors: keep only the branch matching the chosen value, drop the others, collapse `:scope[data-p-density="packed"] .grid` to a semantic class rule. For `range` vars: either substitute the literal or keep the var with the chosen value as its new default.
-
-### 8. Signal done
-
-```bash
-node .rovodev/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
-```
-
-`RELATIVE_PATH` is relative to project root (`public/index.html`, `src/App.tsx`, etc.); the browser fetches source directly if the dev server lacks HMR.
-
-Then run `live-poll.mjs` again immediately.
-
-### Aborting an in-flight session
-
-If wrap or generation fails after the browser has flipped to GENERATING (e.g. wrap landed on the wrong source branch and you've already reverted it, or generation hit an unrecoverable error), tell the **browser** so its bar resets to PICKING:
-
-```bash
-node .rovodev/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID error "Short reason"
-```
-
-Don't run `live-accept --discard` for this; that's a pure file mutator, the browser doesn't see it, and the bar gets stuck on the GENERATING dots forever (the user has to refresh). `--discard` is only correct when the **browser** initiated the discard (user clicked ✕ during CYCLING) and the agent is just running source-side cleanup the browser already triggered.
-
-## Handle fallback
-
-When wrap returns `fallback: "agent-driven"`, the deterministic flow doesn't apply. Pick up here.
-
-The goal is the same: give the user three variants to choose from AND persist the accepted one in a place the next build won't wipe. The difference is that you have to pick the right source file yourself.
-
-### Step 1: Identify where the element actually lives
-
-Use the error payload:
-
-- `element_not_in_source` with `generatedMatch: "public/docs/foo.html"`: the served HTML is generated. Find the generator (grep for writers of that path, e.g. `scripts/build-sub-pages.js`, an Astro/Next template) and locate the template or partial that emits this element.
-- `element_not_found`: the element is runtime-injected. Look for the component that renders it (React/Vue/Svelte), the JS that assembles it, or the data source that feeds it.
-- `file_is_generated` with `file: "..."`: user pointed at a generated file explicitly. Same resolution as `element_not_in_source`.
-
-Read the candidate source until you're confident where a change to the element would belong. If the change is purely visual, that source might be a shared stylesheet, not the template.
-
-### Step 2: Show three variants in the DOM for preview
-
-The browser bar is waiting for variants. Even without a wrapper in source, you still need to show something:
-
-1. Manually write the wrapper scaffold into the **served** file (the one the browser actually loaded). Use the same structure `live-wrap.mjs` produces; `<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents">…</div><!-- end -->`.
-2. Insert your three variant divs inside it, same shape as the deterministic path.
-3. Signal done with `--reply EVENT_ID done --file <served file>`. The browser's no-HMR fallback will fetch and inject.
-
-This served-file edit is **temporary**: next regen wipes it, and that's fine. The real work happens on accept.
-
-### Step 3: On accept, write to true source
-
-When the accept event arrives (`_acceptResult.handled` will usually be `false` here because accept also refuses to persist into generated files; see Handle accept for the carbonize branch), extract the accepted variant's content and write it into the source you identified in Step 1:
-
-- Structural change → edit the template / component source.
-- Visual-only change → add or update rules in the appropriate stylesheet; remove the inline `<style>` scope.
-- Dynamic from data → update the data source or the render logic.
-
-Then remove the temporary wrapper from the served file if it's still there.
-
-### Step 4: On discard, clean up the served file
-
-Remove the wrapper you inserted in Step 2. Nothing else to do.
-
-## Handle `accept`
-
-Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.
-
-- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.
-- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.
-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.
-- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.
-- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.
-
-### Required after accept (carbonize)
-
-When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.
-
-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.
-
-1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.
-2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).
-3. **Bake in parameter values while rewriting selectors.** For `@scope ([data-impeccable-variant="N"])` wrappers: retarget to real, semantic classes on the accepted HTML (`.why-visual--v2 .v2-label { … }`). For `:scope[data-p-<id>="VALUE"]` selectors: keep only the branch matching the chosen value from the param-values comment; drop the others (they're dead after accept). For `var(--p-<id>, DEFAULT)` in the CSS: either substitute the literal value, or if the param is still useful as a knob going forward, leave the var and update its initial declaration to the chosen value.
-4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; those are live-mode plumbing, not source.
-5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.
-
-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.
-
-A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.
-
-## Handle `discard`
-
-Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.
-
-## Handle `prefetch`
-
-Event: `{pageUrl}`. The browser fires this the first time the user selects an element on a given route, as a latency shortcut; it signals the user is likely about to Go on a page you haven't read yet.
-
-Resolve `pageUrl` to the underlying file:
-
-- Root `/` → the `pageFile` returned by `live.mjs` (usually `public/index.html` or equivalent).
-- Sub-routes (e.g. `/docs`, `/docs/live`) → the generated or source file for that route. Use your knowledge of the project layout (multi-page static sites often resolve `/foo` → `public/foo/index.html`; SPAs may map all routes to a single entry).
-
-Read the file into context, then poll again. No `--reply`: this is speculative pre-work; Go will come later. If you can't confidently resolve the route to a file, skip and poll again.
-
-Dedupe is the browser's job (one prefetch per unique pathname per session); trust it. If the same file shows up twice from different routes mapping to the same file, the second Read is cached anyway.
-
-## Exit
-
-The user can stop live mode by:
-- Saying "stop live mode" / "exit live" in chat
-- Closing the browser tab (SSE drops, poll returns `exit` after 8s)
-- The browser's exit button
-
-When the poll returns `exit`, proceed to cleanup. If the poll is still running as a background task, kill it first.
-
-## Cleanup
-
-```bash
-node .rovodev/skills/impeccable/scripts/live-server.mjs stop
-```
-
-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.
-
-Then:
-- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).
-- Remove any leftover carbonize blocks (search for `impeccable-carbonize-start` markers).
-
-## First-time setup (config missing or invalid)
-
-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.
-
-Schema:
-
-```json
-{
- "files": ["<path-or-glob>", "<path-or-glob>", ...],
- "exclude": ["<optional-glob>", ...],
- "insertBefore": "</body>",
- "commentSyntax": "html",
- "cspChecked": true
-}
-```
-
-`files` is the inject target; **the HTML files the browser actually loads**, not necessarily source. Each entry is either a literal path (`"public/index.html"`) or a glob pattern (`"public/**/*.html"`). Tracked or generated doesn't matter here; wrap has its own generated-file guard and routes accepts through the fallback flow.
-
-`exclude` (optional) is a list of glob patterns matching files to skip, even if a `files` glob would have included them. Use for email templates, demo fixtures, or any HTML that isn't a live page.
-
-`cspChecked` tracks whether the CSP detection step below has already run. Absent on first setup; set to `true` after CSP is checked (whether patched, declined, or not needed).
-
-**Hard-excluded paths (cannot be overridden).** `**/node_modules/**` and `**/.git/**` are never matched regardless of what the user writes. These are vendor/metadata directories and injecting into them would silently instrument third-party code.
-
-**Glob syntax.** `**` matches any number of path segments (including zero), `*` matches any characters except `/`, `?` matches a single character except `/`. Paths are always relative to the project root with forward slashes.
-
-| Framework | `files` | `insertBefore` | `commentSyntax` |
-|-----------|---------|----------------|-----------------|
-| SPA with single shell (Vite / React / Plain HTML) | `["index.html"]` | `</body>` | `html` |
-| Next.js (App Router) | `["app/layout.tsx"]` | `</body>` | `jsx` |
-| Next.js (Pages) | `["pages/_document.tsx"]` | `</body>` | `jsx` |
-| Nuxt | `["app.vue"]` | `</body>` | `html` |
-| Svelte / SvelteKit | `["src/app.html"]` | `</body>` | `html` |
-| Astro | `[" <root layout .astro>"]` | `</body>` | `html` |
-| Multi-page (separate HTML per route) | `["public/**/*.html"]`: a glob covering the served directory | `</body>` | `html` |
-
-Pick an anchor that exists in every file (`</body>` almost always works). Use `insertAfter` if the anchor should match **after** a specific line.
-
-For multi-page sites, **prefer a glob over a literal file list**. New pages added later are picked up automatically on the next `live-inject.mjs` run; no config maintenance needed.
-
-For multi-page sites whose pages are *rebuilt* by a generator (Astro, static-site generators, custom scripts like `build-sub-pages.js`), the inject survives only until the next regeneration. Re-run `live.mjs` after each build. Accept is unaffected; it writes to true source via the fallback flow.
-
-### Drift-heal warning
-
-On every `live.mjs` boot, after inject, the project is scanned for HTML files under common page-source roots (`public/`, `src/`, `app/`, `pages/`). If any exist that aren't covered by the resolved `files` list, the output includes a `configDrift` field:
-
-```json
-{
- "ok": true,
- "serverPort": 8400,
- "pageFiles": [ "..." ],
- "configDrift": {
- "orphans": ["public/new-section/index.html", "public/docs/new-command.html"],
- "orphanCount": 2,
- "hint": "2 HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like \"public/**/*.html\"."
- }
-}
-```
-
-When `configDrift` is present, surface it to the user once per session before entering the poll loop:
-
-> Noticed N HTML file(s) in the project that aren't in `config.files`:
->
-> - `public/new-section/index.html`
-> - `public/docs/new-command.html`
->
-> Add them, or switch `files` to a glob like `["public/**/*.html"]` and let it track new pages automatically?
-
-Don't auto-update the config; let the user decide. `configDrift` is `null` when there's no drift.
-
-### CSP detection (first-time only)
-
-If `config.cspChecked === true`, skip this entire section. You already asked this user once; the answer sticks.
-
-Otherwise, run the detection helper:
-
-```bash
-node .rovodev/skills/impeccable/scripts/detect-csp.mjs
-```
-
-Output: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.
-
-- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.
-- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:
- - Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)
- - SvelteKit `kit.csp.directives`
- - Nuxt `nuxt-security` module's `contentSecurityPolicy`
-- **`append-string`**: CSP written as a literal value string. Auto-patchable. See *append-string* below. Covers:
- - Inline `next.config.*` `headers()` with a CSP literal
- - Nuxt `routeRules` / `nitro.routeRules` headers
-- **`middleware`** or **`meta-tag`**: rarer. Detected but not auto-patched in v1. Show the user the detected files and ask them to add `http://localhost:8400` to `script-src` and `connect-src` manually, then mark `cspChecked: true` and proceed.
-
-#### Consent prompt template
-
-Use this phrasing so the experience is consistent across agents:
-
-> **CSP patch needed.** I detected a Content Security Policy in your project that blocks `http://localhost:8400`: the live picker won't load without an allowance. Here's the change I'd make:
->
-> ```diff
-> [file: <patchTarget>]
-> [exact diff, 2–5 lines]
-> ```
->
-> It's guarded by `NODE_ENV === "development"` so the extra entry only appears in dev and never reaches production. You can remove it any time by reverting this file. Apply? [y/n]
-
-On "no": skip the patch, mention live won't work until the user adds the allowance manually, still write `cspChecked: true` (the question's been asked).
-
-On "yes": apply the Shape-specific patch below, then write `cspChecked: true`.
-
-#### append-arrays
-
-CSP expressed as structured directive arrays. Patch mechanism: declare a dev-only array, spread it into the script-src and connect-src arrays.
-
-**Declare near the top of the file that holds the CSP arrays:**
-
-```ts
-// Dev-only allowance so impeccable live mode can load. Guarded by NODE_ENV.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? ["http://localhost:8400"] : [];
-```
-
-**Append `...__impeccableLiveDev` to the script-src and connect-src directive arrays.** Per-framework specifics:
-
-- **Next.js + monorepo helper**: edit the *app's* `next.config.*` (not the shared helper), appending to `additionalScriptSrc` and `additionalConnectSrc` passed into `createBaseNextConfig` (or equivalent). Keeps the shared package clean.
-- **SvelteKit**: edit `svelte.config.js`, appending to `kit.csp.directives['script-src']` and `kit.csp.directives['connect-src']`.
-- **Nuxt + nuxt-security**: edit `nuxt.config.*`, appending to `security.headers.contentSecurityPolicy['script-src']` and `['connect-src']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-turborepo/expected-after-patch.ts` (Next.js)
-- `tests/framework-fixtures/sveltekit-csp/expected-after-patch.js` (SvelteKit)
-
-Idempotency: if `__impeccableLiveDev` already exists in the file, the patch is already applied; skip asking and just mark `cspChecked: true`.
-
-#### append-string
-
-CSP built as a literal value string. Two-point patch: declare a dev-only string near the top, interpolate it into the CSP at the `script-src` and `connect-src` directives.
-
-```ts
-// Dev-only allowance so impeccable live mode can load.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? " http://localhost:8400" : "";
-```
-
-Then in the CSP value string:
-- `script-src 'self' 'unsafe-inline'` → `` `script-src 'self' 'unsafe-inline'${__impeccableLiveDev}` ``
-- `connect-src 'self'` → `` `connect-src 'self'${__impeccableLiveDev}` ``
-
-(Leading space on the dev string so it concatenates cleanly into the existing value. Convert the literal CSP directives into template strings as part of the edit if they aren't already.)
-
-Per-framework specifics:
-- **Next.js inline `headers()`**: edit `next.config.*`, splicing the variable into the CSP value.
-- **Nuxt `routeRules`**: edit `nuxt.config.*`, splicing into the CSP in `routeRules['/**'].headers['Content-Security-Policy']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-inline-csp/expected-after-patch.js` (Next.js)
-- `tests/framework-fixtures/nuxt-csp/expected-after-patch.ts` (Nuxt)
-
-### Troubleshooting
-
-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.
-
-Then re-run `live.mjs`.
@@ -1,109 +0,0 @@
-# Motion Design
-
-## Duration: The 100/300/500 Rule
-
-Timing matters more than easing. These durations feel right for most UI:
-
-| Duration | Use Case | Examples |
-|----------|----------|----------|
-| **100-150ms** | Instant feedback | Button press, toggle, color change |
-| **200-300ms** | State changes | Menu open, tooltip, hover states |
-| **300-500ms** | Layout changes | Accordion, modal, drawer |
-| **500-800ms** | Entrance animations | Page load, hero reveals |
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-## Easing: Pick the Right Curve
-
-**Don't use `ease`.** It's a compromise that's rarely optimal. Instead:
-
-| Curve | Use For | CSS |
-|-------|---------|-----|
-| **ease-out** | Elements entering | `cubic-bezier(0.16, 1, 0.3, 1)` |
-| **ease-in** | Elements leaving | `cubic-bezier(0.7, 0, 0.84, 0)` |
-| **ease-in-out** | State toggles (there → back) | `cubic-bezier(0.65, 0, 0.35, 1)` |
-
-**For micro-interactions, use exponential curves.** They feel natural because they mimic real physics (friction, deceleration):
-
-```css
-/* Quart out - smooth, refined (recommended default) */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1);
-
-/* Quint out - slightly more dramatic */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1);
-
-/* Expo out - snappy, confident */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1);
-```
-
-**Avoid bounce and elastic curves.** They were trendy in 2015 but now feel tacky and amateurish. Real objects don't bounce when they stop; they decelerate smoothly. Overshoot effects draw attention to the animation itself rather than the content.
-
-## Premium Motion Materials
-
-Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties: blur reveals, backdrop-filter panels, saturation or brightness shifts, shadow bloom, SVG filters, masks, clip paths, gradient-position movement, and variable font or shader-driven effects.
-
-Use the right material for the effect:
-
-- **Transform / opacity**: movement, press feedback, simple reveals, list choreography.
-- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances, atmospheric transitions.
-- **Clip path / masks**: wipes, reveals, editorial cropping, product-like transitions.
-- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state.
-- **Grid-template rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly.
-
-The hard rule is not "transform and opacity only." The hard rule is: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify in-browser that the result is smooth on the target viewports. If blur/filter makes the interaction feel significantly more premium and remains smooth, use it.
-
-## Staggered Animations
-
-Use CSS custom properties for cleaner stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"` on each item. **Cap total stagger time**: 10 items at 50ms = 500ms total. For many items, reduce per-item delay or cap staggered count.
-
-## Reduced Motion
-
-This is not optional. Vestibular disorders affect ~35% of adults over 40.
-
-```css
-/* Define animations normally */
-.card {
- animation: slide-up 500ms ease-out;
-}
-
-/* Provide alternative for reduced motion */
-@media (prefers-reduced-motion: reduce) {
- .card {
- animation: fade-in 200ms ease-out; /* Crossfade instead of motion */
- }
-}
-
-/* Or disable entirely */
-@media (prefers-reduced-motion: reduce) {
- *, *::before, *::after {
- animation-duration: 0.01ms !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**What to preserve**: Functional animations like progress bars, loading spinners (slowed down), and focus indicators should still work, just without spatial movement.
-
-## Perceived Performance
-
-**Nobody cares how fast your site is, just how fast it feels.** Perception can be as effective as actual performance.
-
-**The 80ms threshold**: Our brains buffer sensory input for ~80ms to synchronize perception. Anything under 80ms feels instant and simultaneous. This is your target for micro-interactions.
-
-**Active vs passive time**: Passive waiting (staring at a spinner) feels longer than active engagement. Strategies to shift the balance:
-
-- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening.
-- **Early completion**: Show content progressively, don't wait for everything. Video buffering, progressive images, streaming HTML.
-- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Instagram likes work offline; the UI updates instantly, syncs later. Use for low-stakes actions; avoid for payments or destructive operations.
-
-**Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances, but ease-in toward a task's end compresses perceived time.
-
-**Caution**: Too-fast responses can decrease perceived value. Users may distrust instant results for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
-
-## Performance
-
-Don't use `will-change` preemptively, only when animation is imminent (`:hover`, `.animating`). For scroll-triggered animations, use Intersection Observer instead of scroll events; unobserve after animating once. Create motion tokens for consistency (durations, easings, common transitions).
-
----
-
-**Avoid**: Animating everything (animation fatigue is real). Using >500ms for UI feedback. Ignoring `prefers-reduced-motion`. Using animation to hide slow loading.
@@ -1,234 +0,0 @@
-> **Additional context needed**: the "aha moment" you want users to reach, and users' experience level.
-
-Get users to first value as fast as possible. Onboarding's job is not to teach the product. Its job is to get people to the moment that proves the product is worth their time.
-
-## Assess Onboarding Needs
-
-Understand what users need to learn and why:
-
-1. **Identify the challenge**:
- - What are users trying to accomplish?
- - What's confusing or unclear about current experience?
- - Where do users get stuck or drop off?
- - What's the "aha moment" we want users to reach?
-
-2. **Understand the users**:
- - What's their experience level? (Beginners, power users, mixed?)
- - What's their motivation? (Excited and exploring? Required by work?)
- - What's their time commitment? (5 minutes? 30 minutes?)
- - What alternatives do they know? (Coming from competitor? New to category?)
-
-3. **Define success**:
- - What's the minimum users need to learn to be successful?
- - What's the key action we want them to take? (First project? First invite?)
- - How do we know onboarding worked? (Completion rate? Time to value?)
-
-**CRITICAL**: Onboarding should get users to value as quickly as possible, not teach everything possible.
-
-## Onboarding Principles
-
-Follow these core principles:
-
-### Show, Don't Tell
-- Demonstrate with working examples, not just descriptions
-- Provide real functionality in onboarding, not separate tutorial mode
-- Use progressive disclosure, teach one thing at a time
-
-### Make It Optional (When Possible)
-- Let experienced users skip onboarding
-- Don't block access to product
-- Provide "Skip" or "I'll explore on my own" options
-
-### Time to Value
-- Get users to their "aha moment" ASAP
-- Front-load most important concepts
-- Teach 20% that delivers 80% of value
-- Save advanced features for contextual discovery
-
-### Context Over Ceremony
-- Teach features when users need them, not upfront
-- Empty states are onboarding opportunities
-- Tooltips and hints at point of use
-
-### Respect User Intelligence
-- Don't patronize or over-explain
-- Be concise and clear
-- Assume users can figure out standard patterns
-
-## Design Onboarding Experiences
-
-Create appropriate onboarding for the context:
-
-### Initial Product Onboarding
-
-**Welcome Screen**:
-- Clear value proposition (what is this product?)
-- What users will learn/accomplish
-- Time estimate (honest about commitment)
-- Option to skip (for experienced users)
-
-**Account Setup**:
-- Minimal required information (collect more later)
-- Explain why you're asking for each piece of information
-- Smart defaults where possible
-- Social login when appropriate
-
-**Core Concept Introduction**:
-- Introduce 1-3 core concepts (not everything)
-- Use simple language and examples
-- Interactive when possible (do, don't just read)
-- Progress indication (step 1 of 3)
-
-**First Success**:
-- Guide users to accomplish something real
-- Pre-populated examples or templates
-- Celebrate completion (but don't overdo it)
-- Clear next steps
-
-### Feature Discovery & Adoption
-
-**Empty States**:
-Instead of blank space, show:
-- What will appear here (description + screenshot/illustration)
-- Why it's valuable
-- Clear CTA to create first item
-- Example or template option
-
-Example:
-```
-No projects yet
-Projects help you organize your work and collaborate with your team.
-[Create your first project] or [Start from template]
-```
-
-**Contextual Tooltips**:
-- Appear at relevant moment (first time user sees feature)
-- Point directly at relevant UI element
-- Brief explanation + benefit
-- Dismissable (with "Don't show again" option)
-- Optional "Learn more" link
-
-**Feature Announcements**:
-- Highlight new features when they're released
-- Show what's new and why it matters
-- Let users try immediately
-- Dismissable
-
-**Progressive Onboarding**:
-- Teach features when users encounter them
-- Badges or indicators on new/unused features
-- Unlock complexity gradually (don't show all options immediately)
-
-### Guided Tours & Walkthroughs
-
-**When to use**:
-- Complex interfaces with many features
-- Significant changes to existing product
-- Industry-specific tools needing domain knowledge
-
-**How to design**:
-- Spotlight specific UI elements (dim rest of page)
-- Keep steps short (3-7 steps max per tour)
-- Allow users to click through tour freely
-- Include "Skip tour" option
-- Make replayable (help menu)
-
-**Best practices**:
-- Interactive over passive (let users click real buttons)
-- Focus on workflow, not features ("Create a project" not "This is the project button")
-- Provide sample data so actions work
-
-### Interactive Tutorials
-
-**When to use**:
-- Users need hands-on practice
-- Concepts are complex or unfamiliar
-- High stakes (better to practice in safe environment)
-
-**How to design**:
-- Sandbox environment with sample data
-- Clear objectives ("Create a chart showing sales by region")
-- Step-by-step guidance
-- Validation (confirm they did it right)
-- Graduation moment (you're ready!)
-
-### Documentation & Help
-
-**In-product help**:
-- Contextual help links throughout interface
-- Keyboard shortcut reference
-- Search-able help center
-- Video tutorials for complex workflows
-
-**Help patterns**:
-- `?` icon near complex features
-- "Learn more" links in tooltips
-- Keyboard shortcut hints (`⌘K` shown on search box)
-
-## Empty State Design
-
-Every empty state needs:
-
-### What Will Be Here
-"Your recent projects will appear here"
-
-### Why It Matters
-"Projects help you organize your work and collaborate with your team"
-
-### How to Get Started
-[Create project] or [Import from template]
-
-### Visual Interest
-Illustration or icon (not just text on blank page)
-
-### Contextual Help
-"Need help getting started? [Watch 2-min tutorial]"
-
-**Empty state types**:
-- **First use**: Never used this feature (emphasize value, provide template)
-- **User cleared**: Intentionally deleted everything (light touch, easy to recreate)
-- **No results**: Search or filter returned nothing (suggest different query, clear filters)
-- **No permissions**: Can't access (explain why, how to get access)
-- **Error state**: Failed to load (explain what happened, retry option)
-
-## Implementation Patterns
-
-### Technical approaches:
-
-**Tooltip libraries**: Tippy.js, Popper.js
-**Tour libraries**: Intro.js, Shepherd.js, React Joyride
-**Modal patterns**: Focus trap, backdrop, ESC to close
-**Progress tracking**: LocalStorage for "seen" states
-**Analytics**: Track completion, drop-off points
-
-**Storage patterns**:
-```javascript
-// Track which onboarding steps user has seen
-localStorage.setItem('onboarding-completed', 'true');
-localStorage.setItem('feature-tooltip-seen-reports', 'true');
-```
-
-**IMPORTANT**: Don't show same onboarding twice (annoying). Track completion and respect dismissals.
-
-**NEVER**:
-- Force users through long onboarding before they can use product
-- Patronize users with obvious explanations
-- Show same tooltip repeatedly (respect dismissals)
-- Block all UI during tour (let users explore)
-- Create separate tutorial mode disconnected from real product
-- Overwhelm with information upfront (progressive disclosure!)
-- Hide "Skip" or make it hard to find
-- Forget about returning users (don't show initial onboarding again)
-
-## Verify Onboarding Quality
-
-Test with real users:
-
-- **Time to completion**: Can users complete onboarding quickly?
-- **Comprehension**: Do users understand after completing?
-- **Action**: Do users take desired next step?
-- **Skip rate**: Are too many users skipping? (Maybe it's too long or not valuable)
-- **Completion rate**: Are users completing? (If low, simplify)
-- **Time to value**: How long until users get first value?
-
-When users hit the aha moment fast and don't drop off, hand off to `/impeccable polish` for the final pass.
@@ -1,258 +0,0 @@
-Performance is a feature. Identify the actual bottleneck for THIS interface, fix it, then measure. Don't optimize what isn't slow.
-
-## Assess Performance Issues
-
-Understand current performance and identify problems:
-
-1. **Measure current state**:
- - **Core Web Vitals**: LCP, FID/INP, CLS scores
- - **Load time**: Time to interactive, first contentful paint
- - **Bundle size**: JavaScript, CSS, image sizes
- - **Runtime performance**: Frame rate, memory usage, CPU usage
- - **Network**: Request count, payload sizes, waterfall
-
-2. **Identify bottlenecks**:
- - What's slow? (Initial load? Interactions? Animations?)
- - What's causing it? (Large images? Expensive JavaScript? Layout thrashing?)
- - How bad is it? (Perceivable? Annoying? Blocking?)
- - Who's affected? (All users? Mobile only? Slow connections?)
-
-**CRITICAL**: Measure before and after. Premature optimization wastes time. Optimize what actually matters.
-
-## Optimization Strategy
-
-Create systematic improvement plan:
-
-### Loading Performance
-
-**Optimize Images**:
-- Use modern formats (WebP, AVIF)
-- Proper sizing (don't load 3000px image for 300px display)
-- Lazy loading for below-fold images
-- Responsive images (`srcset`, `picture` element)
-- Compress images (80-85% quality is usually imperceptible)
-- Use CDN for faster delivery
-
-```html
-<img
- src="hero.webp"
- srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
- sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
- loading="lazy"
- alt="Hero image"
-/>
-```
-
-**Reduce JavaScript Bundle**:
-- Code splitting (route-based, component-based)
-- Tree shaking (remove unused code)
-- Remove unused dependencies
-- Lazy load non-critical code
-- Use dynamic imports for large components
-
-```javascript
-// Lazy load heavy component
-const HeavyChart = lazy(() => import('./HeavyChart'));
-```
-
-**Optimize CSS**:
-- Remove unused CSS
-- Critical CSS inline, rest async
-- Minimize CSS files
-- Use CSS containment for independent regions
-
-**Optimize Fonts**:
-- Use `font-display: swap` or `optional`
-- Subset fonts (only characters you need)
-- Preload critical fonts
-- Use system fonts when appropriate
-- Limit font weights loaded
-
-```css
-@font-face {
- font-family: 'CustomFont';
- src: url('/fonts/custom.woff2') format('woff2');
- font-display: swap; /* Show fallback immediately */
- unicode-range: U+0020-007F; /* Basic Latin only */
-}
-```
-
-**Optimize Loading Strategy**:
-- Critical resources first (async/defer non-critical)
-- Preload critical assets
-- Prefetch likely next pages
-- Service worker for offline/caching
-- HTTP/2 or HTTP/3 for multiplexing
-
-### Rendering Performance
-
-**Avoid Layout Thrashing**:
-```javascript
-// ❌ Bad: Alternating reads and writes (causes reflows)
-elements.forEach(el => {
- const height = el.offsetHeight; // Read (forces layout)
- el.style.height = height * 2; // Write
-});
-
-// ✅ Good: Batch reads, then batch writes
-const heights = elements.map(el => el.offsetHeight); // All reads
-elements.forEach((el, i) => {
- el.style.height = heights[i] * 2; // All writes
-});
-```
-
-**Optimize Rendering**:
-- Use CSS `contain` property for independent regions
-- Minimize DOM depth (flatter is faster)
-- Reduce DOM size (fewer elements)
-- Use `content-visibility: auto` for long lists
-- Virtual scrolling for very long lists (react-window, react-virtualized)
-
-**Reduce Paint & Composite**:
-- Use `transform` and `opacity` for reliable movement, but allow blur, filters, masks, clip paths, shadows, and color shifts when they create meaningful polish
-- Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- Use `will-change` sparingly for known expensive operations
-- Bound expensive paint areas for blur/filter/shadow effects (smaller and isolated is faster)
-
-### Animation Performance
-
-**GPU Acceleration**:
-```css
-/* ✅ GPU-accelerated (fast) */
-.animated {
- transform: translateX(100px);
- opacity: 0.5;
-}
-
-/* ❌ CPU-bound (slow) */
-.animated {
- left: 100px;
- width: 300px;
-}
-```
-
-**Smooth 60fps**:
-- Target 16ms per frame (60fps)
-- Use `requestAnimationFrame` for JS animations
-- Debounce/throttle scroll handlers
-- Use CSS animations when possible
-- Avoid long-running JavaScript during animations
-
-**Intersection Observer**:
-```javascript
-// Efficiently detect when elements enter viewport
-const observer = new IntersectionObserver((entries) => {
- entries.forEach(entry => {
- if (entry.isIntersecting) {
- // Element is visible, lazy load or animate
- }
- });
-});
-```
-
-### React/Framework Optimization
-
-**React-specific**:
-- Use `memo()` for expensive components
-- `useMemo()` and `useCallback()` for expensive computations
-- Virtualize long lists
-- Code split routes
-- Avoid inline function creation in render
-- Use React DevTools Profiler
-
-**Framework-agnostic**:
-- Minimize re-renders
-- Debounce expensive operations
-- Memoize computed values
-- Lazy load routes and components
-
-### Network Optimization
-
-**Reduce Requests**:
-- Combine small files
-- Use SVG sprites for icons
-- Inline small critical assets
-- Remove unused third-party scripts
-
-**Optimize APIs**:
-- Use pagination (don't load everything)
-- GraphQL to request only needed fields
-- Response compression (gzip, brotli)
-- HTTP caching headers
-- CDN for static assets
-
-**Optimize for Slow Connections**:
-- Adaptive loading based on connection (navigator.connection)
-- Optimistic UI updates
-- Request prioritization
-- Progressive enhancement
-
-## Core Web Vitals Optimization
-
-### Largest Contentful Paint (LCP < 2.5s)
-- Optimize hero images
-- Inline critical CSS
-- Preload key resources
-- Use CDN
-- Server-side rendering
-
-### First Input Delay (FID < 100ms) / INP (< 200ms)
-- Break up long tasks
-- Defer non-critical JavaScript
-- Use web workers for heavy computation
-- Reduce JavaScript execution time
-
-### Cumulative Layout Shift (CLS < 0.1)
-- Set dimensions on images and videos
-- Don't inject content above existing content
-- Use `aspect-ratio` CSS property
-- Reserve space for ads/embeds
-- Avoid animations that cause layout shifts
-
-```css
-/* Reserve space for image */
-.image-container {
- aspect-ratio: 16 / 9;
-}
-```
-
-## Performance Monitoring
-
-**Tools to use**:
-- Chrome DevTools (Lighthouse, Performance panel)
-- WebPageTest
-- Core Web Vitals (Chrome UX Report)
-- Bundle analyzers (webpack-bundle-analyzer)
-- Performance monitoring (Sentry, DataDog, New Relic)
-
-**Key metrics**:
-- LCP, FID/INP, CLS (Core Web Vitals)
-- Time to Interactive (TTI)
-- First Contentful Paint (FCP)
-- Total Blocking Time (TBT)
-- Bundle size
-- Request count
-
-**IMPORTANT**: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.
-
-**NEVER**:
-- Optimize without measuring (premature optimization)
-- Sacrifice accessibility for performance
-- Break functionality while optimizing
-- Use `will-change` everywhere (creates new layers, uses memory)
-- Lazy load above-fold content
-- Optimize micro-optimizations while ignoring major issues (optimize the biggest bottleneck first)
-- Forget about mobile performance (often slower devices, slower connections)
-
-## Verify Improvements
-
-Test that optimizations worked:
-
-- **Before/after metrics**: Compare Lighthouse scores
-- **Real user monitoring**: Track improvements for real users
-- **Different devices**: Test on low-end Android, not just flagship iPhone
-- **Slow connections**: Throttle to 3G, test experience
-- **No regressions**: Ensure functionality still works
-- **User perception**: Does it *feel* faster?
-
-When the user-facing numbers move, hand off to `/impeccable polish` for the final pass.
@@ -1,130 +0,0 @@
-Start your response with:
-
-```
-──────────── ⚡ OVERDRIVE ─────────────
-》》》 Entering overdrive mode...
-```
-
-Push an interface past conventional limits. This isn't just about visual effects. It's about using the full power of the browser to make any part of an interface feel extraordinary: a table that handles a million rows, a dialog that morphs from its trigger, a form that validates in real-time with streaming feedback, a page transition that feels cinematic.
-
-**EXTRA IMPORTANT FOR THIS COMMAND**: Context determines what "extraordinary" means. A particle system on a creative portfolio is impressive. The same particle system on a settings page is embarrassing. But a settings page with instant optimistic saves and animated state transitions? That's extraordinary too. Understand the project's personality and goals before deciding what's appropriate.
-
-### Propose Before Building
-
-This command has the highest potential to misfire. Do NOT jump straight into implementation. You MUST:
-
-1. **Think through 2-3 different directions**: consider different techniques, levels of ambition, and aesthetic approaches. For each direction, briefly describe what the result would look and feel like.
-2. **ask the user directly to clarify what you cannot infer.** to present these directions and get the user's pick before writing any code. Explain trade-offs (browser support, performance cost, complexity).
-3. Only proceed with the direction the user confirms.
-
-Skipping this step risks building something embarrassing that needs to be thrown away.
-
-### Iterate with Browser Automation
-
-Technically ambitious effects almost never work on the first try. You MUST actively use browser automation tools to preview your work, visually verify the result, and iterate. Do not assume the effect looks right, check it. Expect multiple rounds of refinement. The gap between "technically works" and "looks extraordinary" is closed through visual iteration, not code alone.
-
----
-
-## Assess What "Extraordinary" Means Here
-
-The right kind of technical ambition depends entirely on what you're working with. Before choosing a technique, ask: **what would make a user of THIS specific interface say "wow, that's nice"?**
-
-### For visual/marketing surfaces
-Pages, hero sections, landing pages, portfolios: the "wow" is often sensory: a scroll-driven reveal, a shader background, a cinematic page transition, generative art that responds to the cursor.
-
-### For functional UI
-Tables, forms, dialogs, navigation: the "wow" is in how it FEELS: a dialog that morphs from the button that triggered it via View Transitions, a data table that renders 100k rows at 60fps via virtual scrolling, a form with streaming validation that feels instant, drag-and-drop with spring physics.
-
-### For performance-critical UI
-The "wow" is invisible but felt: a search that filters 50k items without a flicker, a complex form that never blocks the main thread, an image editor that processes in near-real-time. The interface just never hesitates.
-
-### For data-heavy interfaces
-Charts and dashboards: the "wow" is in fluidity: GPU-accelerated rendering via Canvas/WebGL for massive datasets, animated transitions between data states, force-directed graph layouts that settle naturally.
-
-**The common thread**: something about the implementation goes beyond what users expect from a web interface. The technique serves the experience, not the other way around.
-
-## The Toolkit
-
-Organized by what you're trying to achieve, not by technology name.
-
-### Make transitions feel cinematic
-- **View Transitions API** (same-document: all browsers; cross-document: no Firefox): shared element morphing between states. A list item expanding into a detail page. A button morphing into a dialog. This is the closest thing to native FLIP animations.
-- **`@starting-style`** (all browsers): animate elements from `display: none` to visible with CSS only, including entry keyframes
-- **Spring physics**: natural motion with mass, tension, and damping instead of cubic-bezier. Libraries: motion (formerly Framer Motion), GSAP, or roll your own spring solver.
-
-### Tie animation to scroll position
-- **Scroll-driven animations** (`animation-timeline: scroll()`): CSS-only, no JS. Parallax, progress bars, reveal sequences all driven by scroll position. (Chrome/Edge/Safari; Firefox: flag only; always provide a static fallback)
-
-### Render beyond CSS
-- **WebGL** (all browsers): shader effects, post-processing, particle systems. Libraries: Three.js, OGL (lightweight), regl. Use for effects CSS can't express.
-- **WebGPU** (Chrome/Edge; Safari partial; Firefox: flag only): next-gen GPU compute. More powerful than WebGL but limited browser support. Always fall back to WebGL2.
-- **Canvas 2D / OffscreenCanvas**: custom rendering, pixel manipulation, or moving heavy rendering off the main thread entirely via Web Workers + OffscreenCanvas.
-- **SVG filter chains**: displacement maps, turbulence, morphology for organic distortion effects. CSS-animatable.
-
-### Make data feel alive
-- **Virtual scrolling**: render only visible rows for tables/lists with tens of thousands of items. No library required for simple cases; TanStack Virtual for complex ones.
-- **GPU-accelerated charts**: Canvas or WebGL-rendered data visualization for datasets too large for SVG/DOM. Libraries: deck.gl, regl-based custom renderers.
-- **Animated data transitions**: morph between chart states rather than replacing. D3's `transition()` or View Transitions for DOM-based charts.
-
-### Animate complex properties
-- **`@property`** (all browsers): register custom CSS properties with types, enabling animation of gradients, colors, and complex values that CSS can't normally interpolate.
-- **Web Animations API** (all browsers): JavaScript-driven animations with the performance of CSS. Composable, cancellable, reversible. The foundation for complex choreography.
-
-### Push performance boundaries
-- **Web Workers**: move computation off the main thread. Heavy data processing, image manipulation, search indexing: anything that would cause jank.
-- **OffscreenCanvas**: render in a Worker thread. The main thread stays free while complex visuals render in the background.
-- **WASM**: near-native performance for computation-heavy features. Image processing, physics simulations, codecs.
-
-### Interact with the device
-- **Web Audio API**: spatial audio, audio-reactive visualizations, sonic feedback. Requires user gesture to start.
-- **Device APIs**: orientation, ambient light, geolocation. Use sparingly and always with user permission.
-
-**NOTE**: This command is about enhancing how an interface FEELS, not changing what a product DOES. Adding real-time collaboration, offline support, or new backend capabilities are product decisions, not UI enhancements. Focus on making existing features feel extraordinary.
-
-## Implement with Discipline
-
-### Progressive enhancement is non-negotiable
-
-Every technique must degrade gracefully. The experience without the enhancement must still be good.
-
-```css
-@supports (animation-timeline: scroll()) {
- .hero { animation-timeline: scroll(); }
-}
-```
-
-```javascript
-if ('gpu' in navigator) { /* WebGPU */ }
-else if (canvas.getContext('webgl2')) { /* WebGL2 fallback */ }
-/* CSS-only fallback must still look good */
-```
-
-### Performance rules
-
-- Target 60fps. If dropping below 50, simplify.
-- Respect `prefers-reduced-motion`, always. Provide a beautiful static alternative.
-- Lazy-initialize heavy resources (WebGL contexts, WASM modules) only when near viewport.
-- Pause off-screen rendering. Kill what you can't see.
-- Test on real mid-range devices, not just your development machine.
-
-### Polish is the difference
-
-The gap between "cool" and "extraordinary" is in the last 20% of refinement: the easing curve on a spring animation, the timing offset in a staggered reveal, the subtle secondary motion that makes a transition feel physical. Don't ship the first version that works; ship the version that feels inevitable.
-
-**NEVER**:
-- Ignore `prefers-reduced-motion`. This is an accessibility requirement, not a suggestion
-- Ship effects that cause jank on mid-range devices
-- Use bleeding-edge APIs without a functional fallback
-- Add sound without explicit user opt-in
-- Use technical ambition to mask weak design fundamentals; fix those first with other commands
-- Layer multiple competing extraordinary moments. Focus creates impact, excess creates noise
-
-## Verify the Result
-
-- **The wow test**: Show it to someone who hasn't seen it. Do they react?
-- **The removal test**: Take it away. Does the experience feel diminished, or does nobody notice?
-- **The device test**: Run it on a phone, a tablet, a Chromebook. Still smooth?
-- **The accessibility test**: Enable reduced motion. Still beautiful?
-- **The context test**: Does this make sense for THIS brand and audience?
-
-"Technically extraordinary" isn't about using the newest API. It's about making an interface do something users didn't think a website could do.
@@ -1,179 +0,0 @@
-# Persona-Based Design Testing
-
-Test the interface through the eyes of 5 distinct user archetypes. Each persona exposes different failure modes that a single "design director" perspective would miss.
-
-**How to use**: Select 2–3 personas most relevant to the interface being critiqued. Walk through the primary user action as each persona. Report specific red flags, not generic concerns.
-
----
-
-## 1. Impatient Power User: "Alex"
-
-
-**Profile**: Expert with similar products. Expects efficiency, hates hand-holding. Will find shortcuts or leave.
-
-**Behaviors**:
-- Skips all onboarding and instructions
-- Looks for keyboard shortcuts immediately
-- Tries to bulk-select, batch-edit, and automate
-- Gets frustrated by required steps that feel unnecessary
-- Abandons if anything feels slow or patronizing
-
-**Test Questions**:
-- Can Alex complete the core task in under 60 seconds?
-- Are there keyboard shortcuts for common actions?
-- Can onboarding be skipped entirely?
-- Do modals have keyboard dismiss (Esc)?
-- Is there a "power user" path (shortcuts, bulk actions)?
-
-**Red Flags** (report these specifically):
-- Forced tutorials or unskippable onboarding
-- No keyboard navigation for primary actions
-- Slow animations that can't be skipped
-- One-item-at-a-time workflows where batch would be natural
-- Redundant confirmation steps for low-risk actions
-
----
-
-## 2. Confused First-Timer: "Jordan"
-
-**Profile**: Never used this type of product. Needs guidance at every step. Will abandon rather than figure it out.
-
-**Behaviors**:
-- Reads all instructions carefully
-- Hesitates before clicking anything unfamiliar
-- Looks for help or support constantly
-- Misunderstands jargon and abbreviations
-- Takes the most literal interpretation of any label
-
-**Test Questions**:
-- Is the first action obviously clear within 5 seconds?
-- Are all icons labeled with text?
-- Is there contextual help at decision points?
-- Does terminology assume prior knowledge?
-- Is there a clear "back" or "undo" at every step?
-
-**Red Flags** (report these specifically):
-- Icon-only navigation with no labels
-- Technical jargon without explanation
-- No visible help option or guidance
-- Ambiguous next steps after completing an action
-- No confirmation that an action succeeded
-
----
-
-## 3. Accessibility-Dependent User: "Sam"
-
-**Profile**: Uses screen reader (VoiceOver/NVDA), keyboard-only navigation. May have low vision, motor impairment, or cognitive differences.
-
-**Behaviors**:
-- Tabs through the interface linearly
-- Relies on ARIA labels and heading structure
-- Cannot see hover states or visual-only indicators
-- Needs adequate color contrast (4.5:1 minimum)
-- May use browser zoom up to 200%
-
-**Test Questions**:
-- Can the entire primary flow be completed keyboard-only?
-- Are all interactive elements focusable with visible focus indicators?
-- Do images have meaningful alt text?
-- Is color contrast WCAG AA compliant (4.5:1 for text)?
-- Does the screen reader announce state changes (loading, success, errors)?
-
-**Red Flags** (report these specifically):
-- Click-only interactions with no keyboard alternative
-- Missing or invisible focus indicators
-- Meaning conveyed by color alone (red = error, green = success)
-- Unlabeled form fields or buttons
-- Time-limited actions without extension option
-- Custom components that break screen reader flow
-
----
-
-## 4. Deliberate Stress Tester: "Riley"
-
-**Profile**: Methodical user who pushes interfaces beyond the happy path. Tests edge cases, tries unexpected inputs, and probes for gaps in the experience.
-
-**Behaviors**:
-- Tests edge cases intentionally (empty states, long strings, special characters)
-- Submits forms with unexpected data (emoji, RTL text, very long values)
-- Tries to break workflows by navigating backwards, refreshing mid-flow, or opening in multiple tabs
-- Looks for inconsistencies between what the UI promises and what actually happens
-- Documents problems methodically
-
-**Test Questions**:
-- What happens at the edges (0 items, 1000 items, very long text)?
-- Do error states recover gracefully or leave the UI in a broken state?
-- What happens on refresh mid-workflow? Is state preserved?
-- Are there features that appear to work but produce broken results?
-- How does the UI handle unexpected input (emoji, special chars, paste from Excel)?
-
-**Red Flags** (report these specifically):
-- Features that appear to work but silently fail or produce wrong results
-- Error handling that exposes technical details or leaves UI in a broken state
-- Empty states that show nothing useful ("No results" with no guidance)
-- Workflows that lose user data on refresh or navigation
-- Inconsistent behavior between similar interactions in different parts of the UI
-
----
-
-## 5. Distracted Mobile User: "Casey"
-
-**Profile**: Using phone one-handed on the go. Frequently interrupted. Possibly on a slow connection.
-
-**Behaviors**:
-- Uses thumb only; prefers bottom-of-screen actions
-- Gets interrupted mid-flow and returns later
-- Switches between apps frequently
-- Has limited attention span and low patience
-- Types as little as possible, prefers taps and selections
-
-**Test Questions**:
-- Are primary actions in the thumb zone (bottom half of screen)?
-- Is state preserved if the user leaves and returns?
-- Does it work on slow connections (3G)?
-- Can forms use autocomplete and smart defaults?
-- Are touch targets at least 44×44pt?
-
-**Red Flags** (report these specifically):
-- Important actions positioned at the top of the screen (unreachable by thumb)
-- No state persistence; progress lost on tab switch or interruption
-- Large text inputs required where selection would work
-- Heavy assets loading on every page (no lazy loading)
-- Tiny tap targets or targets too close together
-
----
-
-## Selecting Personas
-
-Choose personas based on the interface type:
-
-| Interface Type | Primary Personas | Why |
-|---------------|-----------------|-----|
-| Landing page / marketing | Jordan, Riley, Casey | First impressions, trust, mobile |
-| Dashboard / admin | Alex, Sam | Power users, accessibility |
-| E-commerce / checkout | Casey, Riley, Jordan | Mobile, edge cases, clarity |
-| Onboarding flow | Jordan, Casey | Confusion, interruption |
-| Data-heavy / analytics | Alex, Sam | Efficiency, keyboard nav |
-| Form-heavy / wizard | Jordan, Sam, Casey | Clarity, accessibility, mobile |
-
----
-
-## Project-Specific Personas
-
-If `AGENTS.md` contains a `## Design Context` section (generated by `impeccable teach`), derive 1–2 additional personas from the audience and brand information:
-
-1. Read the target audience description
-2. Identify the primary user archetype not covered by the 5 predefined personas
-3. Create a persona following this template:
-
-```
-### [Role]: "[Name]"
-
-**Profile**: [2-3 key characteristics derived from Design Context]
-
-**Behaviors**: [3-4 specific behaviors based on the described audience]
-
-**Red Flags**: [3-4 things that would alienate this specific user type]
-```
-
-Only generate project-specific personas when real Design Context data is available. Don't invent audience details; use the 5 predefined personas when no context exists.
@@ -1,242 +0,0 @@
-> **Additional context needed**: quality bar (MVP vs flagship).
-
-Perform a meticulous final pass to catch all the small details that separate good work from great work. The difference between shipped and polished.
-
-Detector and automated QA output are defect evidence only. A clean script result is never proof that the design is strong; gather browser evidence and inspect the real interaction path.
-
-## Design System Discovery
-
-Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
-
-1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
-2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
-3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category: patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
-
-If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask. Never guess at design system principles.**
-
-## Pre-Polish Assessment
-
-Understand the current state and goals before touching anything:
-
-1. **Review completeness**:
- - Is it functionally complete?
- - Are there known issues to preserve (mark with TODOs)?
- - What's the quality bar? (MVP vs flagship feature?)
- - When does it ship? (How much time for polish?)
-
-2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish; a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
-
-3. **Identify polish areas**:
- - Visual inconsistencies
- - Spacing and alignment issues
- - Interaction state gaps
- - Copy inconsistencies
- - Edge cases and error states
- - Loading and transition smoothness
- - Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
-
-4. **Pull in any prior critique** (optional signal): If `/impeccable critique` has been run on the same target, its priority issues are a useful prior for what to address first. Resolve the target to a file path or URL, then:
- ```bash
- slug=$(node .rovodev/skills/impeccable/scripts/critique-storage.mjs slug "<resolved>")
- node .rovodev/skills/impeccable/scripts/critique-storage.mjs latest "$slug"
- ```
- Exit 0 with body = found; fold the P0/P1 items into your polish list and mention the snapshot path so the user sees what you read. Exit 2 = no snapshot, continue without it. The critique is one input among many. Do your own pass either way.
-
-5. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent; never perfect one corner while leaving another rough.
-
-**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
-
-## Polish Systematically
-
-Work through these dimensions methodically:
-
-### Visual Alignment & Spacing
-
-- **Pixel-perfect alignment**: Everything lines up to grid
-- **Consistent spacing**: All gaps use spacing scale (no random 13px gaps)
-- **Optical alignment**: Adjust for visual weight (icons may need offset for optical centering)
-- **Responsive consistency**: Spacing and alignment work at all breakpoints
-- **Grid adherence**: Elements snap to baseline grid
-
-**Check**:
-- Enable grid overlay and verify alignment
-- Check spacing with browser inspector
-- Test at multiple viewport sizes
-- Look for elements that "feel" off
-
-### Information Architecture & Flow
-
-Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
-
-- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
-- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere: modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
-- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
-- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
-- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
-
-### Typography Refinement
-
-- **Hierarchy consistency**: Same elements use same sizes/weights throughout
-- **Line length**: 45-75 characters for body text
-- **Line height**: Appropriate for font size and context
-- **Widows & orphans**: No single words on last line
-- **Hyphenation**: Appropriate for language and column width
-- **Kerning**: Adjust letter spacing where needed (especially headlines)
-- **Font loading**: No FOUT/FOIT flashes
-
-### Color & Contrast
-
-- **Contrast ratios**: All text meets WCAG standards
-- **Consistent token usage**: No hard-coded colors, all use design tokens
-- **Theme consistency**: Works in all theme variants
-- **Color meaning**: Same colors mean same things throughout
-- **Accessible focus**: Focus indicators visible with sufficient contrast
-- **Tinted neutrals**: No pure gray or pure black; add subtle color tint (0.01 chroma)
-- **Gray on color**: Never put gray text on colored backgrounds; use a shade of that color or transparency
-
-### Interaction States
-
-Every interactive element needs all states:
-
-- **Default**: Resting state
-- **Hover**: Subtle feedback (color, scale, shadow)
-- **Focus**: Keyboard focus indicator (never remove without replacement)
-- **Active**: Click/tap feedback
-- **Disabled**: Clearly non-interactive
-- **Loading**: Async action feedback
-- **Error**: Validation or error state
-- **Success**: Successful completion
-
-**Missing states create confusion and broken experiences**.
-
-### Micro-interactions & Transitions
-
-- **Smooth transitions**: All state changes animated appropriately (150-300ms)
-- **Consistent easing**: Use ease-out-quart/quint/expo for natural deceleration. Never bounce or elastic; they feel dated.
-- **No jank**: Smooth animations; use atmospheric blur/filter/mask/shadow effects when they add polish, but bound expensive paint areas and avoid casual layout-property animation
-- **Appropriate motion**: Motion serves purpose, not decoration
-- **Reduced motion**: Respects `prefers-reduced-motion`
-
-### Content & Copy
-
-- **Consistent terminology**: Same things called same names throughout
-- **Consistent capitalization**: Title Case vs Sentence case applied consistently
-- **Grammar & spelling**: No typos
-- **Appropriate length**: Not too wordy, not too terse
-- **Punctuation consistency**: Periods on sentences, not on labels (unless all labels have them)
-
-### Icons & Images
-
-- **Consistent style**: All icons from same family or matching style
-- **Appropriate sizing**: Icons sized consistently for context
-- **Proper alignment**: Icons align with adjacent text optically
-- **Alt text**: All images have descriptive alt text
-- **Loading states**: Images don't cause layout shift, proper aspect ratios
-- **Retina support**: 2x assets for high-DPI screens
-
-### Forms & Inputs
-
-- **Label consistency**: All inputs properly labeled
-- **Required indicators**: Clear and consistent
-- **Error messages**: Helpful and consistent
-- **Tab order**: Logical keyboard navigation
-- **Auto-focus**: Appropriate (don't overuse)
-- **Validation timing**: Consistent (on blur vs on submit)
-
-### Edge Cases & Error States
-
-- **Loading states**: All async actions have loading feedback
-- **Empty states**: Helpful empty states, not just blank space
-- **Error states**: Clear error messages with recovery paths
-- **Success states**: Confirmation of successful actions
-- **Long content**: Handles very long names, descriptions, etc.
-- **No content**: Handles missing data gracefully
-- **Offline**: Appropriate offline handling (if applicable)
-
-### Responsiveness
-
-- **All breakpoints**: Test mobile, tablet, desktop
-- **Touch targets**: 44x44px minimum on touch devices
-- **Readable text**: No text smaller than 14px on mobile
-- **No horizontal scroll**: Content fits viewport
-- **Appropriate reflow**: Content adapts logically
-
-### Performance
-
-- **Fast initial load**: Optimize critical path
-- **No layout shift**: Elements don't jump after load (CLS)
-- **Smooth interactions**: No lag or jank
-- **Optimized images**: Appropriate formats and sizes
-- **Lazy loading**: Off-screen content loads lazily
-
-### Code Quality
-
-- **Remove console logs**: No debug logging in production
-- **Remove commented code**: Clean up dead code
-- **Remove unused imports**: Clean up unused dependencies
-- **Consistent naming**: Variables and functions follow conventions
-- **Type safety**: No TypeScript `any` or ignored errors
-- **Accessibility**: Proper ARIA labels and semantic HTML
-
-## Polish Checklist
-
-Go through systematically:
-
-- [ ] Aligned to the design system (drift named and resolved by root cause)
-- [ ] Information architecture and flow shape match neighboring features
-- [ ] Visual alignment perfect at all breakpoints
-- [ ] Spacing uses design tokens consistently
-- [ ] Typography hierarchy consistent
-- [ ] All interactive states implemented
-- [ ] All transitions smooth (60fps)
-- [ ] Copy is consistent and polished
-- [ ] Icons are consistent and properly sized
-- [ ] All forms properly labeled and validated
-- [ ] Error states are helpful
-- [ ] Loading states are clear
-- [ ] Empty states are welcoming
-- [ ] Touch targets are 44x44px minimum
-- [ ] Contrast ratios meet WCAG AA
-- [ ] Keyboard navigation works
-- [ ] Focus indicators visible
-- [ ] No console errors or warnings
-- [ ] No layout shift on load
-- [ ] Works in all supported browsers
-- [ ] Respects reduced motion preference
-- [ ] Code is clean (no TODOs, console.logs, commented code)
-
-**IMPORTANT**: Polish is about details. Zoom in. Squint at it. Use it yourself. The little things add up.
-
-Sweat the details. Zoom in until the alignment is right and the spacing reads as deliberate. Then ship.
-
-**NEVER**:
-- Polish before it's functionally complete
-- Polish without aligning to the design system; that's decoration on drift
-- Guess at design system principles instead of asking when something is ambiguous
-- Spend hours on polish if it ships in 30 minutes (triage)
-- Introduce bugs while polishing (test thoroughly)
-- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
-- Perfect one thing while leaving others rough (consistent quality level)
-- Create new one-off components when design system equivalents exist
-- Hard-code values that should use design tokens
-- Introduce new patterns or flows that diverge from established ones
-
-## Final Verification
-
-Before marking as done:
-
-- **Use it yourself**: Actually interact with the feature.
-- **Test on real devices**: Not just browser DevTools.
-- **Ask someone else to review**: Fresh eyes catch things.
-- **Compare to design**: Match intended design.
-- **Check all states**: Don't just test happy path.
-- **Treat automation carefully**: Run detector or QA commands when they are available and relevant, fix their defects, but never cite a clean result as proof that the work is polished.
-
-## Clean Up
-
-After polishing, ensure code quality:
-
-- **Replace custom implementations**: If the design system provides a component you reimplemented, switch to the shared version.
-- **Remove orphaned code**: Delete unused styles, components, or files made obsolete by polish.
-- **Consolidate tokens**: If you introduced new values, check whether they should be tokens.
-- **Verify DRYness**: Look for duplication introduced during polishing and consolidate.
@@ -1,62 +0,0 @@
-# Product register
-
-When design SERVES the product: app UIs, admin dashboards, settings panels, data tables, tools, authenticated surfaces, anything where the user is in a task.
-
-## The product slop test
-
-Not "would someone say AI made this." Familiarity is often a feature here. The test is: would a user fluent in the category's best tools (Linear, Figma, Notion, Raycast, Stripe come to mind) sit down and trust this interface, or pause at every subtly-off component?
-
-Product UI's failure mode isn't flatness, it's strangeness without purpose: over-decorated buttons, mismatched form controls, gratuitous motion, display fonts where labels should be, invented affordances for standard tasks. The bar is earned familiarity. The tool should disappear into the task.
-
-## Typography
-
-- **System fonts are legitimate.** `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` gives you native feel on every platform. Inter is the common cross-platform default for a reason.
-- **One family is often right.** Product UIs don't need display/body pairing. A well-tuned sans carries headings, buttons, labels, body, data.
-- **Fixed rem scale, not fluid.** Clamp-sized headings don't serve product UI. Users view at consistent DPI, and a fluid h1 that shrinks in a sidebar looks worse, not better.
-- **Tighter scale ratio.** 1.125–1.2 between steps is typical. More type elements here than on brand surfaces; exaggerated contrast creates noise.
-- **Line length still applies for prose** (65–75ch). Data and compact UI can run denser; tables at 120ch+ are fine.
-
-## Color
-
-Product defaults to Restrained. A single surface can earn Committed (a dashboard where one category color carries a report, an onboarding flow with a drenched welcome screen), but Restrained is the floor.
-
-- State-rich semantic vocabulary: hover, focus, active, disabled, selected, loading, error, warning, success, info. Standardize these.
-- Accent color used for primary actions, current selection, and state indicators only, not decoration.
-- A second neutral layer for sidebars, toolbars, and panels (slightly cooler or warmer than the content surface).
-
-## Layout
-
-- Predictable grids. Consistency IS an affordance; users navigate faster when the structure is expected.
-- Familiar patterns are features. Standard navigation (top bar, side nav), breadcrumbs, tabs, and form layouts have established user expectations. Don't reinvent for flavor.
-- Responsive behavior is structural (collapse sidebar, responsive table, breakpoint-driven columns), not fluid typography.
-
-## Components
-
-Every interactive component has: default, hover, focus, active, disabled, loading, error. Don't ship with half of these.
-
-- Skeleton states for loading, not spinners in the middle of content.
-- Empty states that teach the interface, not "nothing here."
-- Consistent affordances across the surface. Same button shape. Same form-control vocabulary. Same icon style.
-
-## Motion
-
-- 150–250 ms on most transitions. Users are in flow; don't make them wait for choreography.
-- Motion conveys state, not decoration. State change, feedback, loading, reveal: nothing else.
-- No orchestrated page-load sequences. Product loads into a task; users don't want to watch it load.
-
-## Product bans (on top of the shared absolute bans)
-
-- Decorative motion that doesn't convey state.
-- Inconsistent component vocabulary across screens. If the "save" button looks different in two places, one is wrong.
-- Display fonts in UI labels, buttons, data.
-- Reinventing standard affordances for flavor (custom scrollbars, weird form controls, non-standard modals).
-- Heavy color or full-saturation accents on inactive states.
-
-## Product permissions
-
-Product can afford things brand surfaces can't.
-
-- System fonts and familiar sans defaults (Inter, SF Pro, system-ui stacks).
-- Standard navigation patterns: top bar + side nav, breadcrumbs, tabs, command palettes.
-- Density. Tables with many rows, panels with many labels, dense information when users need it.
-- Consistency over surprise. The same visual vocabulary screen to screen is a virtue; delight is saved for moments, not pages.
@@ -1,99 +0,0 @@
-Quiet design is harder than bold design. Subtlety needs precision. Reduce visual intensity in designs that are too loud, aggressive, or overstimulating without losing personality or making the result generic.
-
----
-
-## Register
-
-Brand: "quieter" means more restrained palette, more whitespace, more typographic air. Drama is reduced, not eliminated; the POV stays intact.
-
-Product: "quieter" means reducing visual noise. Fewer background accents, flatter cards, less color, less motion. The tool should disappear more completely into the task.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too intense:
-
-1. **Identify intensity sources**:
- - **Color saturation**: Overly bright or saturated colors
- - **Contrast extremes**: Too much high-contrast juxtaposition
- - **Visual weight**: Too many bold, heavy elements competing
- - **Animation excess**: Too much motion or overly dramatic effects
- - **Complexity**: Too many visual elements, patterns, or decorations
- - **Scale**: Everything is large and loud with no hierarchy
-
-2. **Understand the context**:
- - What's the purpose? (Marketing vs tool vs reading experience)
- - Who's the audience? (Some contexts need energy)
- - What's working? (Don't throw away good ideas)
- - What's the core message? (Preserve what matters)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Quieter" doesn't mean boring or generic. It means refined and easier on the eyes. Think luxury, not laziness.
-
-## Plan Refinement
-
-Create a strategy to reduce intensity while maintaining impact:
-
-- **Color approach**: Desaturate or shift to more restrained tones?
-- **Hierarchy approach**: Which elements should stay bold (very few), which should recede?
-- **Simplification approach**: What can be removed entirely?
-- **Sophistication approach**: How can we signal quality through restraint?
-
-**IMPORTANT**: Subtlety requires precision. Quiet without intent collapses to generic.
-
-## Refine the Design
-
-Systematically reduce intensity across these dimensions:
-
-### Color Refinement
-- **Reduce saturation**: Shift from fully saturated to 70-85% saturation
-- **Soften palette**: Replace bright colors with muted tones
-- **Reduce color variety**: Use fewer colors more thoughtfully
-- **Neutral dominance**: Let neutrals do more work, use color as accent (10% rule)
-- **Gentler contrasts**: High contrast only where it matters most
-- **Tinted grays**: Use warm or cool tinted grays instead of pure gray. Adds depth without loudness
-- **Never gray on color**: If you have gray text on a colored background, use a darker shade of that color or transparency instead
-
-### Visual Weight Reduction
-- **Typography**: Reduce font weights (900 → 600, 700 → 500), decrease sizes where appropriate
-- **Hierarchy through subtlety**: Use weight, size, and space instead of color and boldness
-- **White space**: Increase breathing room, reduce density
-- **Borders & lines**: Reduce thickness, decrease opacity, or remove entirely
-
-### Simplification
-- **Remove decorative elements**: Gradients, shadows, patterns, textures that don't serve purpose
-- **Simplify shapes**: Reduce border radius extremes, simplify custom shapes
-- **Reduce layering**: Flatten visual hierarchy where possible
-- **Clean up effects**: Reduce or remove blur effects, glows, multiple shadows
-
-### Motion Reduction
-- **Reduce animation intensity**: Shorter distances (10-20px instead of 40px), gentler easing
-- **Remove decorative animations**: Keep functional motion, remove flourishes
-- **Subtle micro-interactions**: Replace dramatic effects with gentle feedback
-- **Refined easing**: Use ease-out-quart for smooth, understated motion. Never bounce or elastic
-- **Remove animations entirely** if they're not serving a clear purpose
-
-### Composition Refinement
-- **Reduce scale jumps**: Smaller contrast between sizes creates calmer feeling
-- **Align to grid**: Bring rogue elements back into systematic alignment
-- **Even out spacing**: Replace extreme spacing variations with consistent rhythm
-
-**NEVER**:
-- Make everything the same size/weight (hierarchy still matters)
-- Remove all color (quiet ≠ grayscale)
-- Eliminate all personality (maintain character through refinement)
-- Sacrifice usability for aesthetics (functional elements still need clear affordances)
-- Make everything small and light (some anchors needed)
-
-## Verify Quality
-
-Ensure refinement maintains quality:
-
-- **Still functional**: Can users still accomplish tasks easily?
-- **Still distinctive**: Does it have character, or is it generic now?
-- **Better reading**: Is text easier to read for extended periods?
-- **Restrained, not absent**: Does the POV survive the cuts?
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,114 +0,0 @@
-# Responsive Design
-
-## Mobile-First: Write It Right
-
-Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
-
-## Breakpoints: Content-Driven
-
-Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
-
-## Detect Input Method, Not Just Screen Size
-
-**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
-
-```css
-/* Fine pointer (mouse, trackpad) */
-@media (pointer: fine) {
- .button { padding: 8px 16px; }
-}
-
-/* Coarse pointer (touch, stylus) */
-@media (pointer: coarse) {
- .button { padding: 12px 20px; } /* Larger touch target */
-}
-
-/* Device supports hover */
-@media (hover: hover) {
- .card:hover { transform: translateY(-2px); }
-}
-
-/* Device doesn't support hover (touch) */
-@media (hover: none) {
- .card { /* No hover state - use active instead */ }
-}
-```
-
-**Critical**: Don't rely on hover for functionality. Touch users can't hover.
-
-## Safe Areas: Handle the Notch
-
-Modern phones have notches, rounded corners, and home indicators. Use `env()`:
-
-```css
-body {
- padding-top: env(safe-area-inset-top);
- padding-bottom: env(safe-area-inset-bottom);
- padding-left: env(safe-area-inset-left);
- padding-right: env(safe-area-inset-right);
-}
-
-/* With fallback */
-.footer {
- padding-bottom: max(1rem, env(safe-area-inset-bottom));
-}
-```
-
-**Enable viewport-fit** in your meta tag:
-```html
-<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
-```
-
-## Responsive Images: Get It Right
-
-### srcset with Width Descriptors
-
-```html
-<img
- src="hero-800.jpg"
- srcset="
- hero-400.jpg 400w,
- hero-800.jpg 800w,
- hero-1200.jpg 1200w
- "
- sizes="(max-width: 768px) 100vw, 50vw"
- alt="Hero image"
->
-```
-
-**How it works**:
-- `srcset` lists available images with their actual widths (`w` descriptors)
-- `sizes` tells the browser how wide the image will display
-- Browser picks the best file based on viewport width AND device pixel ratio
-
-### Picture Element for Art Direction
-
-When you need different crops/compositions (not just resolutions):
-
-```html
-<picture>
- <source media="(min-width: 768px)" srcset="wide.jpg">
- <source media="(max-width: 767px)" srcset="tall.jpg">
- <img src="fallback.jpg" alt="...">
-</picture>
-```
-
-## Layout Adaptation Patterns
-
-**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
-
-## Testing: Don't Trust DevTools Alone
-
-DevTools device emulation is useful for layout but misses:
-
-- Actual touch interactions
-- Real CPU/memory constraints
-- Network latency patterns
-- Font rendering differences
-- Browser chrome/keyboard appearances
-
-**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
-
----
-
-**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
@@ -1,165 +0,0 @@
-Shape the UX and UI for a feature before any code is written. This command produces a **design brief**: a structured artifact that guides implementation through discovery, not guesswork.
-
-**Scope**: Design planning only. This command does NOT write code. It produces the thinking that makes code good.
-
-**Output**: A design brief that can be handed off to /impeccable craft, or directly to /impeccable for freeform implementation. When visual direction probes are used, the images are supporting artifacts, not the primary output.
-
-## Philosophy
-
-Most AI-generated UIs fail not because of bad code, but because of skipped thinking. They jump to "here's a card grid" without asking "what is the user trying to accomplish?" This command inverts that: understand deeply first, so implementation is precise.
-
-## Phase 1: Discovery Interview
-
-**Do NOT write any code or make any design decisions during this phase.** Your only job is to understand the feature deeply enough to make excellent design decisions later.
-
-This is a required interaction, not optional guidance. Ask these questions in conversation, adapting based on answers. Don't dump them all at once; have a natural dialogue. ask the user directly to clarify what you cannot infer.
-
-### Interview cadence
-
-Discovery includes at least one user-answer round unless PRODUCT.md, DESIGN.md, or an already-confirmed brief directly answers the needed inputs. With a sparse prompt, do **not** synthesize a complete brief for confirmation on the first response.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Treat PRODUCT.md and DESIGN.md as anchors; they reduce repeated questions but do **not** replace shape for craft. Shape is task-specific.
-- One round is the default. Add a second only if the first answers leave material gaps. Don't run a second round just to feel thorough.
-- Round 1 should clarify purpose, audience/context, content/scope, and (for brand) visual direction.
-- Round 2, when needed, fills in whatever's still genuinely missing.
-
-**Assert-then-confirm, not menu-with-escape.** When PRODUCT.md and the user's prompt make one option obvious, name it and ask the user to confirm or override. Don't enumerate "Restrained / Committed / Or something else?" as a real choice; "This reads as Restrained, confirm?" beats a four-option menu when the answer is already clear.
-
-### Purpose & Context
-- What is this feature for? What problem does it solve?
-- Who specifically will use it? (Not "users"; be specific: role, context, frequency)
-- What does success look like? How will you know this feature is working?
-- What's the user's state of mind when they reach this feature? (Rushed? Exploring? Anxious? Focused?)
-
-### Content & Data
-- What content or data does this feature display or collect?
-- What are the realistic ranges? (Minimum, typical, maximum, e.g., 0 items, 5 items, 500 items)
-- What are the edge cases? (Empty state, error state, first-time use, power user)
-- Is any content dynamic? What changes and how often?
-- What visual assets are real content here? Note required images, product shots, illustrations, maps, textures, diagrams, generated objects, or existing project assets.
-
-### Design Direction
-
-Force a visual decision on three fronts. Skip anything PRODUCT.md or DESIGN.md already answers; ask only what's missing.
-
-- **Color strategy for this surface.** Pick one: Restrained / Committed / Full palette / Drenched. Can override the project default if the surface earns it (e.g. a drenched hero inside an otherwise Restrained product).
-- **Theme via scene sentence.** Write one sentence of physical context for this surface: who uses it, where, under what ambient light, in what mood. The sentence forces dark vs light. If it doesn't, add detail until it does.
-- **Two or three named anchor references.** Specific products, brands, objects. Not adjectives like "modern" or "clean."
-
-### Scope
-
-Always ask. Sketch quality and shipped quality are different outputs; don't guess between them.
-
-- **Fidelity.** Sketch / mid-fi / high-fi / production-ready?
-- **Breadth.** One screen / a flow / a whole surface?
-- **Interactivity.** Static visual / interactive prototype / shipped-quality component?
-- **Time intent.** Quick exploration, or polish until it ships?
-
-Scope answers are task-scoped. Don't write them to PRODUCT.md or DESIGN.md; carry them through the design brief only.
-
-### Constraints
-- Are there technical constraints? (Framework, performance budget, browser support)
-- Are there content constraints? (Localization, dynamic text length, user-generated content)
-- Mobile/responsive requirements?
-- Accessibility requirements beyond WCAG AA?
-
-### Anti-Goals
-- What should this NOT be? What would be a wrong direction?
-- What's the biggest risk of getting this wrong?
-
-## Phase 1.5: Visual Direction Probe (Capability-Gated)
-
-After the discovery interview, generate a small set of visual direction probes **before** writing the final brief when all of these are true:
-
-- The work is **net-new** or directionally ambiguous enough that visual exploration will clarify the brief.
-- The requested fidelity is **mid-fi, high-fi, or production-ready**. Skip for sketch-only planning.
-- The current harness gives you native image generation (Codex's `image_gen`, an equivalent MCP tool, or similar). Don't ask the user to install APIs or tooling.
-
-When those conditions are met, this step is mandatory. If image generation isn't natively available, do not ask the user to install APIs or tooling. State in one line that the image step is skipped because the harness lacks native image generation, then proceed. The one-line announcement is required, not optional; it forces a conscious decision instead of letting the step quietly evaporate.
-
-Use probes to explore visual lanes, not to replace the brief.
-
-Do not skip probes because the final UI will be semantic, editable, code-native, responsive, or accessible. Those are implementation requirements, not reasons to avoid visual exploration.
-
-### What to generate
-
-Generate **2 to 4** distinct direction probes based on the discovery answers, especially:
-
-- Color strategy
-- Theme scene sentence
-- Named anchor references
-- Scope and fidelity
-
-The probes should differ in primary visual direction (hierarchy, topology, density, typographic voice, or color strategy), not just palette tweaks.
-
-### How to use the probes
-
-- Treat them as **direction tests**, not final designs.
-- Use them to pressure-test whether the brief is pointing at the right lane.
-- Ask the user which direction feels closest, what feels off, and what should carry forward.
-- If the probes reveal a mismatch, revise the brief inputs before finalizing the brief.
-
-### Important limits
-
-- Do **not** skip discovery because image generation is available.
-- Do **not** treat generated imagery as final UX specification, final copy, or final accessibility behavior.
-- Do **not** use this step for minor refinements of existing work. It's for shaping a new surface or clarifying a big directional choice.
-
-If image generation isn't natively available, announce the skip in one line and proceed to the design brief.
-
-## Phase 2: Design Brief
-
-After the interview and any required probes, present a brief and **end your response**. The user must confirm before any implementation runs. Do not present a brief and then continue to code in the same response, even if the brief feels obvious to you. The user's confirmation is the gate.
-
-**Choose the brief shape based on how clear the answers are:**
-
-- **Compact form (3-5 bullets)** when discovery was crisp and the original prompt + PRODUCT.md already pinned scope, content, and direction. State what you're building, the visual lane, and end with one or two specific questions or a clear "confirm or override?" prompt. This is the default for typical craft requests with a clear prompt.
-- **Full structured form (sections below)** when the task is genuinely ambiguous, multi-screen, or when the user asked for shape as a standalone step. Use this when the discipline of structure earns its weight.
-
-Don't pad a clear brief into a long one to look thorough. A 70-line brief restating answers the user just gave is noise, not rigor. Equally, don't skip the confirmation pause to look efficient: the pause is the point.
-
-Present the brief, then **stop and wait for explicit confirmation**. You are not the judge of whether the user already approved. Even when the brief feels obviously right, ask once and wait. The pause is what separates shape from premature implementation.
-
-### Brief Structure
-
-**1. Feature Summary** (2-3 sentences)
-What this is, who it's for, what it needs to accomplish.
-
-**2. Primary User Action**
-The single most important thing a user should do or understand here.
-
-**3. Design Direction**
-Color strategy (Restrained / Committed / Full palette / Drenched) + the theme scene sentence + 2–3 named anchor references. Reference PRODUCT.md and DESIGN.md where they already answer, and note any per-surface overrides.
-
-If you ran the Visual Direction Probe step, name which probe direction won and what changed in the brief because of it.
-
-**4. Scope**
-Fidelity, breadth, interactivity, and time intent from the Scope section of the interview. Task-scoped; these don't persist beyond the brief.
-
-**5. Layout Strategy**
-High-level spatial approach: what gets emphasis, what's secondary, how information flows. Describe the visual hierarchy and rhythm, not specific CSS.
-
-**6. Key States**
-List every state the feature needs: default, empty, loading, error, success, edge cases. For each, note what the user needs to see and feel.
-
-**7. Interaction Model**
-How users interact with this feature. What happens on click, hover, scroll? What feedback do they get? What's the flow from entry to completion?
-
-**8. Content Requirements**
-What copy, labels, empty state messages, error messages, and microcopy are needed. Note any dynamic content and its realistic ranges. For image-led surfaces, also list the required image/media roles and their likely source (project asset, generated raster, semantic SVG/CSS, canvas/WebGL, icon library, or accepted omission).
-
-**9. Recommended References**
-Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., spatial-design.md for complex layouts, motion-design.md for animated features, interaction-design.md for form-heavy features).
-
-**10. Open Questions**
-Anything genuinely unresolved. Don't list "open questions" you've already recommended a default for; assert the default and move on. If you'd write `Recommend: X` next to a question, just decide X.
-
----
-
-ask the user directly to clarify what you cannot infer. Ask for explicit confirmation of the brief before finishing.
-
-If the user disagrees with any part, revisit the relevant discovery questions. A shape run is incomplete until the user confirms direction.
-
-Once confirmed, the brief is complete. The user can now hand it to /impeccable, or use it to guide any other implementation approach. (If the user wants the full discovery-then-build flow in one step, they should use /impeccable craft instead, which runs this command internally.)
@@ -1,100 +0,0 @@
-# Spatial Design
-
-## Spacing Systems
-
-### Use 4pt Base, Not 8pt
-
-8pt systems are too coarse; you'll frequently need 12px (between 8 and 16). Use 4pt for granularity: 4, 8, 12, 16, 24, 32, 48, 64, 96px.
-
-### Name Tokens Semantically
-
-Name by relationship (`--space-sm`, `--space-lg`), not value (`--spacing-8`). Use `gap` instead of margins for sibling spacing; it eliminates margin collapse and cleanup hacks.
-
-## Grid Systems
-
-### The Self-Adjusting Grid
-
-Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Columns are at least 280px, as many as fit per row, leftovers stretch. For complex layouts, use named grid areas (`grid-template-areas`) and redefine them at breakpoints.
-
-## Visual Hierarchy
-
-### The Squint Test
-
-Blur your eyes (or screenshot and blur). Can you still identify:
-- The most important element?
-- The second most important?
-- Clear groupings?
-
-If everything looks the same weight blurred, you have a hierarchy problem.
-
-### Hierarchy Through Multiple Dimensions
-
-Don't rely on size alone. Combine:
-
-| Tool | Strong Hierarchy | Weak Hierarchy |
-|------|------------------|----------------|
-| **Size** | 3:1 ratio or more | <2:1 ratio |
-| **Weight** | Bold vs Regular | Medium vs Regular |
-| **Color** | High contrast | Similar tones |
-| **Position** | Top/left (primary) | Bottom/right |
-| **Space** | Surrounded by white space | Crowded |
-
-**The best hierarchy uses 2-3 dimensions at once**: A heading that's larger, bolder, AND has more space above it.
-
-### Cards Are Not Required
-
-Cards are overused. Spacing and alignment create visual grouping naturally. Use cards only when content is truly distinct and actionable, items need visual comparison in a grid, or content needs clear interaction boundaries. **Never nest cards inside cards.** Use spacing, typography, and subtle dividers for hierarchy within a card.
-
-## Container Queries
-
-Viewport queries are for page layouts. **Container queries are for components**:
-
-```css
-.card-container {
- container-type: inline-size;
-}
-
-.card {
- display: grid;
- gap: var(--space-md);
-}
-
-/* Card layout changes based on its container, not viewport */
-@container (min-width: 400px) {
- .card {
- grid-template-columns: 120px 1fr;
- }
-}
-```
-
-**Why this matters**: A card in a narrow sidebar stays compact, while the same card in a main content area expands automatically, without viewport hacks.
-
-## Optical Adjustments
-
-Text at `margin-left: 0` looks indented due to letterform whitespace; use negative margin (`-0.05em`) to optically align. Geometrically centered icons often look off-center; play icons need to shift right, arrows shift toward their direction.
-
-### Touch Targets vs Visual Size
-
-Buttons can look small but need large touch targets (44px minimum). Use padding or pseudo-elements:
-
-```css
-.icon-button {
- width: 24px; /* Visual size */
- height: 24px;
- position: relative;
-}
-
-.icon-button::before {
- content: '';
- position: absolute;
- inset: -10px; /* Expand tap target to 44px */
-}
-```
-
-## Depth & Elevation
-
-Create semantic z-index scales (dropdown → sticky → modal-backdrop → modal → toast → tooltip) instead of arbitrary numbers. For shadows, create a consistent elevation scale (sm → md → lg → xl). **Key insight**: Shadows should be subtle. If you can clearly see it, it's probably too strong.
-
----
-
-**Avoid**: Arbitrary spacing values outside your scale. Making all spacing equal (variety creates hierarchy). Creating hierarchy through size alone - combine size, weight, color, and space.
@@ -1,156 +0,0 @@
-# Teach Flow
-
-Gathers design context for a project and writes two complementary files at the project root:
-
-- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
-- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
-
-Every other impeccable command reads these files before doing any work.
-
-## Step 1: Load current state
-
-Run the shared loader first so you know what already exists:
-
-```bash
-node .rovodev/skills/impeccable/scripts/load-context.mjs
-```
-
-The output tells you whether PRODUCT.md and/or DESIGN.md already exist. If `migrated: true`, legacy `.impeccable.md` was auto-renamed to `PRODUCT.md`. Mention this once to the user.
-
-Decision tree:
-- **Neither file exists (empty project or no context yet)**: do Steps 2-4 (write PRODUCT.md), then decide on DESIGN.md based on whether there's code to analyze.
-- **PRODUCT.md exists, DESIGN.md missing**: skip to Step 5 and offer to run `/impeccable document` for DESIGN.md.
-- **PRODUCT.md exists but has no `## Register` section (legacy)**: add it. Infer a hypothesis from the codebase (see Step 2), confirm with the user, write the field.
-- **Both exist**: ask the user directly to clarify what you cannot infer. Ask which file to refresh. Skip the one the user doesn't want changed.
-- **Just DESIGN.md exists (unusual)**: do Steps 2-4 to produce PRODUCT.md.
-
-Never silently overwrite an existing file. Always confirm first.
-
-If teach was invoked as a setup blocker by another command, such as `/impeccable craft landing page`, pause that command here. Complete teach, re-run the loader, then resume the original command with the freshly loaded context. For craft, resume into shape next; teach creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
-
-## Step 2: Explore the codebase
-
-Before asking questions, thoroughly scan the project to discover what you can:
-
-- **README and docs**: Project purpose, target audience, any stated goals
-- **Package.json / config files**: Tech stack, dependencies, existing design libraries
-- **Existing components**: Current design patterns, spacing, typography in use
-- **Brand assets**: Logos, favicons, color values already defined
-- **Design tokens / CSS variables**: Existing color palettes, font stacks, spacing scales
-- **Any style guides or brand documentation**
-
-Also form a **register hypothesis** from what you find:
-
-- Brand signals: `/`, `/about`, `/pricing`, `/blog/*`, `/docs/*`, hero sections, big typography, scroll-driven sections, landing-page-shaped content.
-- Product signals: `/app/*`, `/dashboard`, `/settings`, `/(auth)`, forms, data tables, side/top nav, app-shell components.
-
-Register is a hypothesis at this point, not a decision; Step 3 confirms it.
-
-Note what you've learned and what remains unclear. This exploration feeds both PRODUCT.md and DESIGN.md.
-
-## Step 3: Ask strategic questions (for PRODUCT.md)
-
-ask the user directly to clarify what you cannot infer. Ask only about what you couldn't infer from the codebase.
-
-### Interview mode, not confirmation mode
-
-If the repo is empty or the user's brief is sparse, run a short interview before proposing PRODUCT.md. Do **not** turn a one-sentence request into a complete inferred PRODUCT.md and ask for blanket confirmation.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Use inferred answers as hypotheses or options, not as finished facts.
-- Complete at least one real user-answer round before drafting PRODUCT.md, unless every required answer is directly discoverable from repo docs.
-- Round 1 should establish register, users/purpose, and desired outcome.
-- Round 2 should establish brand personality or references, anti-references, and accessibility needs.
-
-### Minimum viable interview
-
-Ask enough to complete PRODUCT.md. At minimum, cover register confirmation, users and purpose, brand personality, anti-references, and accessibility needs unless each answer is directly discoverable from repo context. After at least one interview round, you may propose inferred answers, but the user must confirm them before you write PRODUCT.md. Never synthesize PRODUCT.md from the original task prompt alone.
-
-### Register (ask first; it shapes everything below)
-
-Every design task is either **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboards, tools: design SERVES the product).
-
-If Step 2 produced a clear hypothesis, lead with it: *"From the codebase, this looks like a [brand / product] surface. Does that match your intent, or should we treat it differently?"*
-
-If the signal is genuinely split (e.g. a product with a big marketing landing), ask the user directly to clarify what you cannot infer. Ask which register describes the **primary** surface. The register can be overridden per task later, but PRODUCT.md carries one default.
-
-### Users & Purpose
-- Who uses this? What's their context when using it?
-- What job are they trying to get done?
-- For brand: what emotions should the interface evoke? (confidence, delight, calm, urgency)
-- For product: what workflow are they in? What's the primary task on any given screen?
-
-### Brand & Personality
-- How would you describe the brand personality in 3 words?
-- Reference sites or apps that capture the right feel? What specifically about them?
- - For brand, push for real-world references in the right lane (tech-minimal, editorial-magazine, consumer-warm, brutalist-grid, etc.), not generic "modern" adjectives.
- - For product, push for category best-tool references (Linear, Figma, Notion, Raycast, Stripe).
-- What should this explicitly NOT look like? Any anti-references?
-
-### Accessibility & Inclusion
-- Specific accessibility requirements? (WCAG level, known user needs)
-- Considerations for reduced motion, color blindness, or other accommodations?
-
-Skip questions where the answer is already clear. **Do NOT ask about colors, fonts, radii, or visual styling here.** Those belong in DESIGN.md, not PRODUCT.md.
-
-## Step 4: Write PRODUCT.md
-
-Write PRODUCT.md only after the user has confirmed the strategic answers from Step 3. If an inferred answer is uncertain or unconfirmed, ask before writing.
-
-Synthesize into a strategic document:
-
-```markdown
-# Product
-
-## Register
-
-product
-
-## Users
-[Who they are, their context, the job to be done]
-
-## Product Purpose
-[What this product does, why it exists, what success looks like]
-
-## Brand Personality
-[Voice, tone, 3-word personality, emotional goals]
-
-## Anti-references
-[What this should NOT look like. Specific bad-example sites or patterns to avoid.]
-
-## Design Principles
-[3-5 strategic principles derived from the conversation. Principles like "practice what you preach", "show, don't tell", "expert confidence". NOT visual rules like "use OKLCH" or "magenta accent".]
-
-## Accessibility & Inclusion
-[WCAG level, known user needs, considerations]
-```
-
-Register is either `brand` or `product` as a bare value. No prose, no commentary.
-
-Write to `PROJECT_ROOT/PRODUCT.md`. If `.impeccable.md` existed, the loader already renamed it; merge into that content rather than starting from scratch.
-
-## Step 5: Decide on DESIGN.md
-
-Offer `/impeccable document` either way. Two paths:
-
-- **Code exists** (CSS tokens, components, a running site): "I can generate a DESIGN.md that captures your visual system (colors, typography, components) so variants stay on-brand. Want to do that now?"
-- **Pre-implementation** (empty project): "I can seed a starter DESIGN.md from five quick questions about color strategy, type direction, motion energy, and references. You can re-run once there's code, to capture the real tokens. Want to do that now?"
-
-If the user agrees, delegate to `/impeccable document` (it auto-detects scan vs seed). Load its reference and follow that flow.
-
-If the user prefers to skip, mention they can run `/impeccable document` any time later.
-
-## Step 6: Confirm and wrap up
-
-Summarize:
-- Register captured (brand / product)
-- What was written (PRODUCT.md, DESIGN.md, or both)
-- The 3-5 strategic principles from PRODUCT.md that will guide future work
-- If DESIGN.md is pending, remind the user how to generate it later
-
-**Critical: re-run the loader to refresh session context.** After writing PRODUCT.md, run `node .rovodev/skills/impeccable/scripts/load-context.mjs` one final time and let its full JSON output land in conversation. This ensures subsequent commands in this session use the freshly-written PRODUCT.md, not a stale earlier version.
-
-If teach was invoked as a blocker by another impeccable command (e.g. the user ran `/impeccable polish` with no PRODUCT.md), resume that original task now with the fresh context.
-
-Optionally ask the user directly to clarify what you cannot infer. Ask whether they'd like a brief summary of PRODUCT.md appended to AGENTS.md for easier agent reference. If yes, append a short **Design Context** pointer section there.
@@ -1,124 +0,0 @@
-Typography carries most of the information on the page. Replace generic defaults (Inter, Roboto, system fallback at flat scale) with type that reflects the brand and scales with intentional contrast.
-
----
-
-## Register
-
-Brand: run the font selection procedure in [brand.md](brand.md). Pairing follows the brand's lane (display serif + sans body for editorial/luxury, one committed sans for tech, etc.). Fluid `clamp()` scale, ≥1.25 ratio between steps.
-
-Product: system fonts and familiar sans stacks are legitimate here. One well-tuned family typically carries the whole UI. Fixed `rem` scale, 1.125–1.2 ratio between more closely-spaced steps.
-
----
-
-## Assess Current Typography
-
-Analyze what's weak or generic about the current type:
-
-1. **Font choices**:
- - Are we using invisible defaults? (Inter, Roboto, Arial, Open Sans, system defaults)
- - Does the font match the brand personality? (A playful brand shouldn't use a corporate typeface)
- - Are there too many font families? (More than 2-3 is almost always a mess)
-
-2. **Hierarchy**:
- - Can you tell headings from body from captions at a glance?
- - Are font sizes too close together? (14px, 15px, 16px = muddy hierarchy)
- - Are weight contrasts strong enough? (Medium vs Regular is barely visible)
-
-3. **Sizing & scale**:
- - Is there a consistent type scale, or are sizes arbitrary?
- - Does body text meet minimum readability? (16px+)
- - Is the sizing strategy appropriate for the context? (Fixed `rem` scales for app UIs; fluid `clamp()` for marketing/content page headings)
-
-4. **Readability**:
- - Are line lengths comfortable? (45-75 characters ideal)
- - Is line-height appropriate for the font and context?
- - Is there enough contrast between text and background?
-
-5. **Consistency**:
- - Are the same elements styled the same way throughout?
- - Are font weights used consistently? (Not bold in one section, semibold in another for the same role)
- - Is letter-spacing intentional or default everywhere?
-
-**CRITICAL**: The goal isn't to make text "fancier." It's to make it clearer, more readable, and more intentional. Good typography is invisible; bad typography is distracting.
-
-## Plan Typography Improvements
-
-Consult the [typography reference](typography.md) for detailed guidance on scales, pairing, and loading strategies.
-
-Create a systematic plan:
-
-- **Font selection**: Do fonts need replacing? What fits the brand/context?
-- **Type scale**: Establish a modular scale (e.g., 1.25 ratio) with clear hierarchy
-- **Weight strategy**: Which weights serve which roles? (Regular for body, Semibold for labels, Bold for headings, or whatever fits)
-- **Spacing**: Line-heights, letter-spacing, and margins between typographic elements
-
-## Improve Typography Systematically
-
-### Font Selection
-
-If fonts need replacing:
-- Choose fonts that reflect the brand personality
-- Pair with genuine contrast (serif + sans, geometric + humanist), or use a single family in multiple weights
-- Ensure web font loading doesn't cause layout shift (`font-display: swap`, metric-matched fallbacks)
-
-### Establish Hierarchy
-
-Build a clear type scale:
-- **5 sizes cover most needs**: caption, secondary, body, subheading, heading
-- **Use a consistent ratio** between levels (1.25, 1.333, or 1.5)
-- **Combine dimensions**: Size + weight + color + space for strong hierarchy. Don't rely on size alone
-- **App UIs**: Use a fixed `rem`-based type scale, optionally adjusted at 1-2 breakpoints. Fluid sizing undermines the spatial predictability that dense, container-based layouts need
-- **Marketing / content pages**: Use fluid sizing via `clamp(min, preferred, max)` for headings and display text. Keep body text fixed
-
-### Fix Readability
-
-- Set `max-width` on text containers using `ch` units (`max-width: 65ch`)
-- Adjust line-height per context: tighter for headings (1.1-1.2), looser for body (1.5-1.7)
-- Increase line-height slightly for light-on-dark text
-- Ensure body text is at least 16px / 1rem
-
-### Refine Details
-
-- Use `tabular-nums` for data tables and numbers that should align
-- Apply proper `letter-spacing`: slightly open for small caps and uppercase, default or tight for large display text
-- Use semantic token names (`--text-body`, `--text-heading`), not value names (`--font-16`)
-- Set `font-kerning: normal` and consider OpenType features where appropriate
-
-### Weight Consistency
-
-- Define clear roles for each weight and stick to them
-- Don't use more than 3-4 weights (Regular, Medium, Semibold, Bold is plenty)
-- Load only the weights you actually use (each weight adds to page load)
-
-**NEVER**:
-- Use more than 2-3 font families
-- Pick sizes arbitrarily; commit to a scale
-- Set body text below 16px
-- Use decorative/display fonts for body text
-- Disable browser zoom (`user-scalable=no`)
-- Use `px` for font sizes; use `rem` to respect user settings
-- Default to Inter/Roboto/Open Sans when personality matters
-- Pair fonts that are similar but not identical (two geometric sans-serifs)
-
-## Verify Typography Improvements
-
-- **Hierarchy**: Can you identify heading vs body vs caption instantly?
-- **Readability**: Is body text comfortable to read in long passages?
-- **Consistency**: Are same-role elements styled identically throughout?
-- **Personality**: Does the typography reflect the brand?
-- **Performance**: Are web fonts loading efficiently without layout shift?
-- **Accessibility**: Does text meet WCAG contrast ratios? Is it zoomable to 200%?
-
-When the type carries the hierarchy on its own, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `scale` param controlling the hierarchy ratio. Express all font sizes in the variant's scoped CSS through `calc(var(--p-scale, 1) * <base>)` or, better, scale the type ramp via `clamp(min, calc(var(--p-scale, 1) * Npx), max)`. Users slide from subdued to commanding.
-
-```json
-{"id":"scale","kind":"range","min":0.85,"max":1.3,"step":0.05,"default":1,"label":"Scale"}
-```
-
-Where the variant riffs on a specific pairing, expose the pairing choice as a `steps` param (e.g. "serif display + sans body" vs. "mono display + sans body" vs. "all-sans"). Each branch routes through `:scope[data-p-pairing="X"]` selectors in scoped CSS.
-
-See `reference/live.md` for the full params contract.
@@ -1,159 +0,0 @@
-# Typography
-
-## Classic Typography Principles
-
-### Vertical Rhythm
-
-Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
-
-### Modular Scale & Hierarchy
-
-The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
-
-**Use fewer sizes with more contrast.** A 5-size system covers most needs:
-
-| Role | Typical Ratio | Use Case |
-|------|---------------|----------|
-| xs | 0.75rem | Captions, legal |
-| sm | 0.875rem | Secondary UI, metadata |
-| base | 1rem | Body text |
-| lg | 1.25-1.5rem | Subheadings, lead text |
-| xl+ | 2-4rem | Headlines, hero text |
-
-Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
-
-### Readability & Measure
-
-Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
-
-**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
-
-**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
-
-## Font Selection & Pairing
-
-The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
-
-### Anti-reflexes worth defending against
-
-- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
-- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
-- A children's product does NOT need a rounded display font. Kids' books use real type.
-- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
-
-**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
-
-### Pairing Principles
-
-**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
-
-When pairing, contrast on multiple axes:
-- Serif + Sans (structure contrast)
-- Geometric + Humanist (personality contrast)
-- Condensed display + Wide body (proportion contrast)
-
-**Never pair fonts that are similar but not identical** (e.g., two geometric sans-serifs). They create visual tension without clear hierarchy.
-
-### Web Font Loading
-
-The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
-
-```css
-/* 1. Use font-display: swap for visibility */
-@font-face {
- font-family: 'CustomFont';
- src: url('font.woff2') format('woff2');
- font-display: swap;
-}
-
-/* 2. Match fallback metrics to minimize shift */
-@font-face {
- font-family: 'CustomFont-Fallback';
- src: local('Arial');
- size-adjust: 105%; /* Scale to match x-height */
- ascent-override: 90%; /* Match ascender height */
- descent-override: 20%; /* Match descender depth */
- line-gap-override: 10%; /* Match line spacing */
-}
-
-body {
- font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
-}
-```
-
-Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
-
-**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
-
-**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
-
-**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
-
-## Modern Web Typography
-
-### Fluid Type
-
-Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
-
-**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
-
-**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
-
-**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
-
-**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
-
-### OpenType Features
-
-Most developers don't know these exist. Use them for polish:
-
-```css
-/* Tabular numbers for data alignment */
-.data-table { font-variant-numeric: tabular-nums; }
-
-/* Proper fractions */
-.recipe-amount { font-variant-numeric: diagonal-fractions; }
-
-/* Small caps for abbreviations */
-abbr { font-variant-caps: all-small-caps; }
-
-/* Disable ligatures in code */
-code { font-variant-ligatures: none; }
-
-/* Enable kerning (usually on by default, but be explicit) */
-body { font-kerning: normal; }
-```
-
-Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
-
-### Rendering polish
-
-```css
-/* Even out heading line lengths (browser picks better break points) */
-h1, h2, h3 { text-wrap: balance; }
-
-/* Reduce orphans and ragged endings in long prose */
-article p { text-wrap: pretty; }
-
-/* Variable fonts: pick the right optical-size master automatically */
-body { font-optical-sizing: auto; }
-```
-
-**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
-
-## Typography System Architecture
-
-Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
-
-## Accessibility Considerations
-
-Beyond contrast ratios (which are well-documented), consider:
-
-- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
-- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
-- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
-- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
-
----
-
-**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
@@ -1,107 +0,0 @@
-# UX Writing
-
-## The Button Label Problem
-
-**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
-
-| Bad | Good | Why |
-|-----|------|-----|
-| OK | Save changes | Says what will happen |
-| Submit | Create account | Outcome-focused |
-| Yes | Delete message | Confirms the action |
-| Cancel | Keep editing | Clarifies what "cancel" means |
-| Click here | Download PDF | Describes the destination |
-
-**For destructive actions**, name the destruction:
-- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
-- "Delete 5 items" not "Delete selected" (show the count)
-
-## Error Messages: The Formula
-
-Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
-
-### Error Message Templates
-
-| Situation | Template |
-|-----------|----------|
-| **Format error** | "[Field] needs to be [format]. Example: [example]" |
-| **Missing required** | "Please enter [what's missing]" |
-| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
-| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
-| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
-
-### Don't Blame the User
-
-Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
-
-## Empty States Are Opportunities
-
-Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
-
-## Voice vs Tone
-
-**Voice** is your brand's personality, consistent everywhere.
-**Tone** adapts to the moment.
-
-| Moment | Tone Shift |
-|--------|------------|
-| Success | Celebratory, brief: "Done! Your changes are live." |
-| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
-| Loading | Reassuring: "Saving your work..." |
-| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
-
-**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
-
-## Writing for Accessibility
-
-**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
-
-## Writing for Translation
-
-### Plan for Expansion
-
-German text is ~30% longer than English. Allocate space:
-
-| Language | Expansion |
-|----------|-----------|
-| German | +30% |
-| French | +20% |
-| Finnish | +30-40% |
-| Chinese | -30% (fewer chars, but same width) |
-
-### Translation-Friendly Patterns
-
-Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
-
-## Consistency: The Terminology Problem
-
-Pick one term and stick with it:
-
-| Inconsistent | Consistent |
-|--------------|------------|
-| Delete / Remove / Trash | Delete |
-| Settings / Preferences / Options | Settings |
-| Sign in / Log in / Enter | Sign in |
-| Create / Add / New | Create |
-
-Build a terminology glossary and enforce it. Variety creates confusion.
-
-## Avoid Redundant Copy
-
-If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
-
-## Loading States
-
-Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
-
-## Confirmation Dialogs: Use Sparingly
-
-Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
-
-## Form Instructions
-
-Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
-
----
-
-**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
@@ -1,284 +0,0 @@
-#!/usr/bin/env node
-/**
- * Cleans up deprecated Impeccable skill files, symlinks, and
- * skills-lock.json entries left over from previous versions.
- *
- * Safe to run repeatedly -- it is a no-op when nothing needs cleaning.
- *
- * Usage (from the project root):
- * node {{scripts_path}}/cleanup-deprecated.mjs
- *
- * What it does:
- * 1. Finds every harness-specific skills directory (.claude/skills,
- * .cursor/skills, .agents/skills, etc.).
- * 2. For each deprecated skill name (with and without i- prefix),
- * checks if the directory exists and its SKILL.md mentions
- * "impeccable" (to avoid deleting unrelated user skills).
- * 3. Deletes confirmed matches (files, directories, or symlinks).
- * 4. Removes the corresponding entries from skills-lock.json.
- */
-
-import { existsSync, readFileSync, writeFileSync, rmSync, readdirSync, statSync, lstatSync, unlinkSync } from 'node:fs';
-import { join, resolve } from 'node:path';
-
-// Skills that were renamed, merged, or folded in v2.0, v2.1, and v3.0.
-const DEPRECATED_NAMES = [
- // v2.0 renames
- 'frontend-design', // renamed to impeccable
- 'teach-impeccable', // folded into /impeccable teach
- // v2.1 merges
- 'arrange', // renamed to layout
- 'normalize', // merged into polish
- 'onboard', // merged into harden
- 'extract', // merged into /impeccable extract
- // v3.0 consolidation: all standalone skills -> /impeccable sub-commands
- 'adapt',
- 'animate',
- 'audit',
- 'bolder',
- 'clarify',
- 'colorize',
- 'critique',
- 'delight',
- 'distill',
- 'harden',
- 'layout',
- 'optimize',
- 'overdrive',
- 'polish',
- 'quieter',
- 'shape',
- 'typeset',
-];
-
-// All known harness directories that may contain a skills/ subfolder.
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Per-skill fingerprints for SKILL.md bodies that never mentioned
-// "impeccable" in their v2.x source. Used as a last-resort match
-// when no skills-lock.json exists and the word heuristic fails.
-// The strings are lifted verbatim from the v2.x frontmatter
-// descriptions, so collisions with hand-written user skills are
-// vanishingly unlikely.
-const SKILL_FINGERPRINTS = {
- harden: 'Make interfaces production-ready: error handling, empty states',
- optimize: 'Diagnoses and fixes UI performance across loading speed',
-};
-
-/**
- * Walk up from startDir until we find a directory that looks like a
- * project root (has package.json, .git, or skills-lock.json).
- */
-export function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- const { root } = { root: '/' };
- while (dir !== root) {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Load skills-lock.json from the project root, or null if missing/unreadable.
- */
-export function loadLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return null;
- try {
- return JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return null;
- }
-}
-
-/**
- * Check whether a skill directory belongs to Impeccable. Three layered
- * signals, in order of reliability:
- * 1. Lock source equals "pbakaus/impeccable" (authoritative).
- * 2. SKILL.md body contains the word "impeccable".
- * 3. SKILL.md body contains a per-skill fingerprint (for harden and
- * optimize, whose v2.x SKILL.md never mentioned the pack name).
- */
-export function isImpeccableSkill(skillDir, { skillName, lock } = {}) {
- // 1. Authoritative: the lock file claims this skill is ours.
- if (skillName && lock?.skills?.[skillName]?.source === 'pbakaus/impeccable') {
- return true;
- }
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) return false;
- let content;
- try {
- content = readFileSync(skillMd, 'utf-8');
- } catch {
- return false;
- }
- // 2. Word-level content heuristic.
- if (/impeccable/i.test(content)) return true;
- // 3. Per-skill fingerprint for old skills that never mentioned the pack.
- // Strip the i- prefix so both `harden` and `i-harden` resolve to the
- // same fingerprint entry.
- const unprefixed = skillName?.startsWith('i-') ? skillName.slice(2) : skillName;
- const fingerprint = unprefixed && SKILL_FINGERPRINTS[unprefixed];
- if (fingerprint && content.includes(fingerprint)) return true;
- return false;
-}
-
-/**
- * Build the full list of names to check: each deprecated name, plus
- * its i-prefixed variant.
- */
-export function buildTargetNames() {
- const names = [];
- for (const name of DEPRECATED_NAMES) {
- names.push(name);
- names.push(`i-${name}`);
- }
- return names;
-}
-
-/**
- * Find every skills directory across all harness dirs in the project.
- * Returns absolute paths that exist on disk.
- */
-export function findSkillsDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const candidate = join(projectRoot, harness, 'skills');
- if (existsSync(candidate)) {
- dirs.push(candidate);
- }
- }
- return dirs;
-}
-
-/**
- * Remove deprecated skill directories/symlinks from all harness dirs.
- * Reads skills-lock.json so the authoritative "source" field can
- * drive deletion even when SKILL.md never mentions impeccable.
- * Returns an array of paths that were deleted.
- */
-export function removeDeprecatedSkills(projectRoot, lock) {
- if (lock === undefined) lock = loadLock(projectRoot);
- const targets = buildTargetNames();
- const skillsDirs = findSkillsDirs(projectRoot);
- const deleted = [];
-
- for (const skillsDir of skillsDirs) {
- for (const name of targets) {
- const skillPath = join(skillsDir, name);
-
- // Use lstat to detect symlinks (existsSync follows symlinks and
- // returns false for dangling ones).
- let stat;
- try {
- stat = lstatSync(skillPath);
- } catch {
- continue; // does not exist at all
- }
-
- if (stat.isSymbolicLink()) {
- // Symlink: check the target if it's alive, otherwise treat
- // dangling symlinks to deprecated names as safe to remove.
- const targetAlive = existsSync(skillPath);
- const isMatch = targetAlive
- ? isImpeccableSkill(skillPath, { skillName: name, lock })
- : true;
- if (isMatch) {
- unlinkSync(skillPath);
- deleted.push(skillPath);
- }
- continue;
- }
-
- // Regular directory -- verify it belongs to impeccable
- if (isImpeccableSkill(skillPath, { skillName: name, lock })) {
- rmSync(skillPath, { recursive: true, force: true });
- deleted.push(skillPath);
- }
- }
- }
-
- return deleted;
-}
-
-/**
- * Remove deprecated entries from skills-lock.json.
- * Only removes entries whose source is "pbakaus/impeccable".
- * Returns the list of removed skill names.
- */
-export function cleanSkillsLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return [];
-
- let lock;
- try {
- lock = JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return [];
- }
-
- if (!lock.skills || typeof lock.skills !== 'object') return [];
-
- const targets = buildTargetNames();
- const removed = [];
-
- for (const name of targets) {
- const entry = lock.skills[name];
- if (!entry) continue;
- // Only remove if it belongs to impeccable
- if (entry.source === 'pbakaus/impeccable') {
- delete lock.skills[name];
- removed.push(name);
- }
- }
-
- if (removed.length > 0) {
- writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\n', 'utf-8');
- }
-
- return removed;
-}
-
-/**
- * Run the full cleanup. Returns a summary object.
- *
- * Order matters: read the lock and delete directories first, then
- * strip lock entries. Otherwise the authoritative signal is gone by
- * the time directory deletion runs.
- */
-export function cleanup(projectRoot) {
- const root = projectRoot || findProjectRoot();
- const lock = loadLock(root);
- const deletedPaths = removeDeprecatedSkills(root, lock);
- const removedLockEntries = cleanSkillsLock(root);
- return { deletedPaths, removedLockEntries, projectRoot: root };
-}
-
-// CLI entry point
-if (process.argv[1] && resolve(process.argv[1]) === resolve(new URL(import.meta.url).pathname)) {
- const result = cleanup();
- if (result.deletedPaths.length === 0 && result.removedLockEntries.length === 0) {
- console.log('No deprecated Impeccable skills found. Nothing to clean up.');
- } else {
- if (result.deletedPaths.length > 0) {
- console.log(`Removed ${result.deletedPaths.length} deprecated skill(s):`);
- for (const p of result.deletedPaths) console.log(` - ${p}`);
- }
- if (result.removedLockEntries.length > 0) {
- console.log(`Cleaned ${result.removedLockEntries.length} entry/entries from skills-lock.json:`);
- for (const name of result.removedLockEntries) console.log(` - ${name}`);
- }
- }
-}
@@ -1,94 +0,0 @@
-{
- "craft": {
- "description": "Full confirmed-brief-then-build flow. Runs multi-round shape discovery first, resolves visual probe and north-star mock gates when available, then builds and visually iterates. Use when building a new feature end-to-end.",
- "argumentHint": "[feature description]"
- },
- "teach": {
- "description": "Gathers design context for a project. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles) and, when code exists to analyze, DESIGN.md (visual: colors, typography, components). Every other command reads these files before doing work. Use once per project.",
- "argumentHint": ""
- },
- "document": {
- "description": "Generate a DESIGN.md file that captures the current visual design system. Auto-extracts colors, typography, spacing, radii, and component patterns from the codebase, then asks the user to confirm descriptive language for atmosphere and color character. Follows the Google Stitch DESIGN.md format so the file is tool-compatible. Use when you need a visual design spec an AI agent can follow to stay on-brand.",
- "argumentHint": ""
- },
- "extract": {
- "description": "Pull reusable patterns, components, and design tokens into the design system. Identifies repeated patterns and consolidates them. Use when you have drift across the codebase and want to bring things back to a consistent system.",
- "argumentHint": "[target]"
- },
- "live": {
- "description": "Interactive live variant mode. Select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via HMR. Requires a running dev server. Use when you want to visually experiment with design alternatives in real time.",
- "argumentHint": ""
- },
- "adapt": {
- "description": "Adapt designs to work across different screen sizes, devices, contexts, or platforms. Implements breakpoints, fluid layouts, and touch targets. Use when the user mentions responsive design, mobile layouts, breakpoints, viewport adaptation, or cross-device compatibility.",
- "argumentHint": "[target] [context (mobile, tablet, print...)]"
- },
- "animate": {
- "description": "Review a feature and enhance it with purposeful animations, micro-interactions, and motion effects that improve usability and delight. Use when the user mentions adding animation, transitions, micro-interactions, motion design, hover effects, or making the UI feel more alive.",
- "argumentHint": "[target]"
- },
- "audit": {
- "description": "Run technical quality checks across accessibility, performance, theming, responsive design, and anti-patterns. Generates a scored report with P0-P3 severity ratings and actionable plan. Use when the user wants an accessibility check, performance audit, or technical quality review.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "bolder": {
- "description": "Amplify safe or boring designs to make them more visually interesting and stimulating. Increases impact while maintaining usability. Use when the user says the design looks bland, generic, too safe, lacks personality, or wants more visual impact and character.",
- "argumentHint": "[target]"
- },
- "clarify": {
- "description": "Improve unclear UX copy, error messages, microcopy, labels, and instructions to make interfaces easier to understand. Use when the user mentions confusing text, unclear labels, bad error messages, hard-to-follow instructions, or wanting better UX writing.",
- "argumentHint": "[target]"
- },
- "colorize": {
- "description": "Add strategic color to features that are too monochromatic or lack visual interest, making interfaces more engaging and expressive. Use when the user mentions the design looking gray, dull, lacking warmth, needing more color, or wanting a more vibrant or expressive palette.",
- "argumentHint": "[target]"
- },
- "critique": {
- "description": "Evaluate design from a UX perspective, assessing visual hierarchy, information architecture, emotional resonance, cognitive load, and overall quality with quantitative scoring, persona-based testing, automated anti-pattern detection, and actionable feedback. Use when the user asks to review, critique, evaluate, or give feedback on a design or component.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "delight": {
- "description": "Add moments of joy, personality, and unexpected touches that make interfaces memorable and enjoyable to use. Elevates functional to delightful. Use when the user asks to add polish, personality, animations, micro-interactions, delight, or make an interface feel fun or memorable.",
- "argumentHint": "[target]"
- },
- "distill": {
- "description": "Strip designs to their essence by removing unnecessary complexity. Great design is simple, powerful, and clean. Use when the user asks to simplify, declutter, reduce noise, remove elements, or make a UI cleaner and more focused.",
- "argumentHint": "[target]"
- },
- "harden": {
- "description": "Make interfaces production-ready: error handling, i18n, text overflow, edge case management, and resilience under real-world data. Use when the user asks to harden, make production-ready, handle edge cases, add error states, or fix overflow and i18n issues.",
- "argumentHint": "[target]"
- },
- "onboard": {
- "description": "Design onboarding flows, first-run experiences, and empty states that guide new users to value. Covers welcome screens, account setup, progressive disclosure, contextual tooltips, feature announcements, and activation moments. Use when the user mentions onboarding, first-time users, empty states, activation, getting started, new user flows, or the aha moment.",
- "argumentHint": "[target]"
- },
- "layout": {
- "description": "Improve layout, spacing, and visual rhythm. Fixes monotonous grids, inconsistent spacing, and weak visual hierarchy. Use when the user mentions layout feeling off, spacing issues, visual hierarchy, crowded UI, alignment problems, or wanting better composition.",
- "argumentHint": "[target]"
- },
- "optimize": {
- "description": "Diagnoses and fixes UI performance across loading speed, rendering, animations, images, and bundle size. Use when the user mentions slow, laggy, janky, performance, bundle size, load time, or wants a faster, smoother experience.",
- "argumentHint": "[target]"
- },
- "overdrive": {
- "description": "Pushes interfaces past conventional limits with technically ambitious implementations — shaders, spring physics, scroll-driven reveals, 60fps animations. Use when the user wants to wow, impress, go all-out, or make something that feels extraordinary.",
- "argumentHint": "[target]"
- },
- "polish": {
- "description": "Performs a final quality pass fixing alignment, spacing, consistency, and micro-detail issues before shipping. Use when the user mentions polish, finishing touches, pre-launch review, something looks off, or wants to go from good to great.",
- "argumentHint": "[target]"
- },
- "quieter": {
- "description": "Tones down visually aggressive or overstimulating designs, reducing intensity while preserving quality. Use when the user mentions too bold, too loud, overwhelming, aggressive, garish, or wants a calmer, more refined aesthetic.",
- "argumentHint": "[target]"
- },
- "shape": {
- "description": "Plan UX and UI before code. Runs a required multi-round discovery interview, uses visual probes when available, and produces a user-confirmed design brief for implementation.",
- "argumentHint": "[feature to shape]"
- },
- "typeset": {
- "description": "Improves typography by fixing font choices, hierarchy, sizing, weight, and readability so text feels intentional. Use when the user mentions fonts, type, readability, text hierarchy, sizing looks off, or wants more polished, intentional typography.",
- "argumentHint": "[target]"
- }
-}
@@ -1,242 +0,0 @@
-#!/usr/bin/env node
-/**
- * Critique persistence helper.
- *
- * Each run of /impeccable critique writes a per-target snapshot to
- * .impeccable/critique/<timestamp>__<slug>.md
- * with a small YAML frontmatter carrying the score + P0/P1 counts.
- *
- * /impeccable polish reads the latest matching snapshot at start as its
- * fix backlog. No other skill auto-reads critique output.
- *
- * The slug is derived mechanically from the *resolved* primary artifact
- * (file path or URL), never from the user's natural-language phrasing.
- * Slug stability across runs is what lets the trend display work.
- *
- * CLI entry points (called from skill instructions):
- * node critique-storage.mjs slug <resolved-target>
- * node critique-storage.mjs write <slug> <snapshot-body-file>
- * node critique-storage.mjs latest <slug>
- * node critique-storage.mjs trend <slug> [limit]
- *
- * Note: there is intentionally no `ignore` subcommand. ignore.md is a plain
- * markdown file; the model reads it directly with its file-read tool. This
- * helper only exists for operations the model can't trivially do inline
- * (normalizing paths, generating filenames, globbing + parsing frontmatter).
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath, pathToFileURL } from 'node:url';
-import { getCritiqueDir } from './impeccable-paths.mjs';
-
-const SLUG_MAX = 50;
-
-/**
- * Mechanically derive a slug from a resolved target. Returns null if the
- * input doesn't look like a stable identifier (empty, project root, etc).
- *
- * Accepts file paths and URLs. The model resolves "the homepage" to a
- * concrete artifact before calling this — we never slug a natural-language
- * phrase.
- */
-export function slugFromTarget(resolved, { cwd = process.cwd() } = {}) {
- if (!resolved || typeof resolved !== 'string') return null;
- const trimmed = resolved.trim();
- if (!trimmed) return null;
-
- // URL
- if (/^https?:\/\//i.test(trimmed)) {
- let url;
- try { url = new URL(trimmed); } catch { return null; }
- const hostPath = `${url.hostname}${url.pathname}`;
- return kebab(hostPath);
- }
-
- // File path. Make it project-relative so two devs critiquing the same
- // checkout get the same slug regardless of where their repo is cloned.
- const abs = path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- let rel = path.relative(cwd, abs);
- // If the target is outside cwd, fall back to the basename so we still
- // produce a stable slug (vs the absolute path, which would include
- // home dirs / usernames).
- if (rel.startsWith('..') || path.isAbsolute(rel)) {
- rel = path.basename(abs);
- }
- if (!rel || rel === '.' || rel === '') return null;
- return kebab(rel);
-}
-
-function kebab(s) {
- const slug = s
- .toLowerCase()
- .replace(/[/\\.]+/g, '-')
- .replace(/[^a-z0-9-]+/g, '-')
- .replace(/-+/g, '-')
- .replace(/^-|-$/g, '');
- if (!slug) return null;
- // Cap from the tail — the tail (filename) is more identifying than the
- // top-level directory.
- return slug.length <= SLUG_MAX ? slug : slug.slice(slug.length - SLUG_MAX).replace(/^-/, '');
-}
-
-/**
- * Filename-safe UTC ISO timestamp: hyphens for separators, trailing Z.
- * Plain colons aren't allowed on Windows filesystems.
- */
-export function nowFilenameStamp(date = new Date()) {
- const iso = date.toISOString(); // 2026-05-12T18:30:00.123Z
- return iso.replace(/[:.]/g, '-').replace(/-\d+Z$/, 'Z');
-}
-
-/**
- * Write a snapshot for `slug`. `meta` carries the small structured frontmatter
- * keys read back by readTrend(). `body` is the human-readable critique
- * report (everything below the frontmatter).
- *
- * Returns the absolute path written.
- */
-export function writeSnapshot({ slug, meta, body, cwd = process.cwd(), now = new Date() }) {
- if (!slug) throw new Error('writeSnapshot requires a slug');
- const dir = getCritiqueDir(cwd);
- fs.mkdirSync(dir, { recursive: true });
- const timestamp = nowFilenameStamp(now);
- const filePath = path.join(dir, `${timestamp}__${slug}.md`);
- // Spread `meta` first so internally computed `timestamp` and `slug`
- // always win. Otherwise a caller-supplied meta blob (parsed from the
- // IMPECCABLE_CRITIQUE_META env var) could clobber them, leaving the
- // filename in disagreement with its frontmatter and corrupting trends.
- const front = serializeFrontmatter({ ...meta, timestamp, slug });
- fs.writeFileSync(filePath, `${front}\n${body.trim()}\n`, 'utf-8');
- return filePath;
-}
-
-function serializeFrontmatter(obj) {
- const lines = ['---'];
- for (const [key, value] of Object.entries(obj)) {
- if (value === undefined || value === null) continue;
- const str = typeof value === 'string' ? value : String(value);
- // Quote strings that contain : or # to keep parsing simple.
- const needsQuotes = typeof value === 'string' && /[:#]/.test(str);
- lines.push(`${key}: ${needsQuotes ? JSON.stringify(str) : str}`);
- }
- lines.push('---');
- return lines.join('\n');
-}
-
-function parseFrontmatter(text) {
- const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
- if (!match) return {};
- const out = {};
- for (const line of match[1].split(/\r?\n/)) {
- const colon = line.indexOf(':');
- if (colon < 0) continue;
- const key = line.slice(0, colon).trim();
- let value = line.slice(colon + 1).trim();
- if (/^".*"$/.test(value)) {
- try { value = JSON.parse(value); } catch { /* leave as-is */ }
- } else if (/^-?\d+$/.test(value)) {
- value = Number(value);
- }
- out[key] = value;
- }
- return out;
-}
-
-/**
- * Return all snapshot files for `slug`, sorted oldest → newest.
- */
-function listSnapshotsForSlug(slug, cwd) {
- const dir = getCritiqueDir(cwd);
- if (!fs.existsSync(dir)) return [];
- const suffix = `__${slug}.md`;
- return fs.readdirSync(dir)
- .filter((f) => f.endsWith(suffix))
- .sort()
- .map((f) => path.join(dir, f));
-}
-
-/**
- * Return the most recent snapshot for `slug`, or null. Polish reads this
- * to find its fix backlog when the slug matches.
- */
-export function readLatestSnapshot(slug, { cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- if (!all.length) return null;
- const latest = all[all.length - 1];
- const body = fs.readFileSync(latest, 'utf-8');
- return { path: latest, body, meta: parseFrontmatter(body) };
-}
-
-/**
- * Return the last `limit` snapshots' frontmatter, oldest → newest.
- * Critique appends a one-line trend to its output using this.
- */
-export function readTrend(slug, { limit = 5, cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- const slice = all.slice(-limit);
- return slice.map((file) => parseFrontmatter(fs.readFileSync(file, 'utf-8')));
-}
-
-// ---- CLI ---------------------------------------------------------------
-
-function main(argv) {
- const [cmd, ...args] = argv;
- switch (cmd) {
- case 'slug': {
- const slug = slugFromTarget(args[0]);
- if (!slug) { process.stderr.write('no stable slug for input\n'); process.exit(1); }
- process.stdout.write(`${slug}\n`);
- return;
- }
- case 'write': {
- const [slug, bodyFile] = args;
- if (!slug || !bodyFile) { process.stderr.write('usage: write <slug> <body-file>\n'); process.exit(1); }
- const raw = fs.readFileSync(bodyFile, 'utf-8');
- // The body file may be a full report. The caller passes the meta as
- // a JSON object on stdin if it wants structured frontmatter; otherwise
- // we write with minimal metadata.
- let meta = {};
- const metaArg = process.env.IMPECCABLE_CRITIQUE_META;
- if (metaArg) {
- try { meta = JSON.parse(metaArg); } catch { /* ignore */ }
- }
- const out = writeSnapshot({ slug, meta, body: raw });
- process.stdout.write(`${out}\n`);
- return;
- }
- case 'latest': {
- const latest = readLatestSnapshot(args[0]);
- if (!latest) { process.exit(2); }
- process.stdout.write(latest.body);
- return;
- }
- case 'trend': {
- const rows = readTrend(args[0], { limit: args[1] ? Number(args[1]) : 5 });
- process.stdout.write(JSON.stringify(rows, null, 2) + '\n');
- return;
- }
- default:
- process.stderr.write('usage: critique-storage.mjs <slug|write|latest|trend> [args]\n');
- process.exit(1);
- }
-}
-
-function isMainModule() {
- if (!process.argv[1]) return false;
- try {
- return fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1]);
- } catch {
- // pathToFileURL normalizes Windows paths; keep it as a fallback for any
- // environment where realpath is unavailable.
- return import.meta.url === pathToFileURL(process.argv[1]).href;
- }
-}
-
-// Why the realpath check: generated skills are often reached through symlinked
-// harness directories (for example a demo repo's `.agents` -> source `.agents`).
-// Node resolves import.meta.url to the real file, while process.argv[1] keeps
-// the symlink path. Comparing canonical paths prevents a silent exit-0 no-op.
-if (isMainModule()) {
- main(process.argv.slice(2));
-}
@@ -1,820 +0,0 @@
-// Parse a DESIGN.md (Stitch-spec format) into a structured JSON model that
-// the live-mode design-system panel can render. Deterministic, dependency-free.
-//
-// Two-layer: YAML frontmatter (machine-readable tokens) + markdown body
-// (prose with six canonical H2 sections). When frontmatter is present, it's
-// exposed on `model.frontmatter` alongside the prose-scraped sections;
-// consumers can prefer frontmatter values and fall back to prose.
-
-const CANONICAL_SECTIONS = [
- 'Overview',
- 'Colors',
- 'Typography',
- 'Elevation',
- 'Components',
- "Do's and Don'ts",
-];
-
-// ---------- Frontmatter (Stitch YAML subset) ----------
-
-function parseFrontmatter(md) {
- const lines = md.split(/\r?\n/);
- if (lines[0]?.trim() !== '---') return { frontmatter: null, body: md };
-
- let end = -1;
- for (let i = 1; i < lines.length; i++) {
- if (lines[i].trim() === '---') { end = i; break; }
- }
- if (end === -1) return { frontmatter: null, body: md };
-
- const yaml = lines.slice(1, end).join('\n');
- const body = lines.slice(end + 1).join('\n');
- try {
- return { frontmatter: parseYamlSubset(yaml), body };
- } catch {
- return { frontmatter: null, body: md };
- }
-}
-
-// Minimal YAML reader for the Stitch frontmatter subset: scalar maps with
-// one level of nested objects (typography roles, components). Indent-based,
-// 2-space convention. No arrays, no anchors, no multi-line scalars — Stitch's
-// schema doesn't need them and accepting them would require a real YAML
-// dependency we don't want to vendor.
-function parseYamlSubset(yaml) {
- const lines = yaml.split(/\r?\n/);
- const root = {};
- const stack = [{ indent: -1, obj: root }];
-
- for (const raw of lines) {
- // Skip blanks and line-only comments. Don't strip inline comments:
- // unquoted hex values start with `#` and can't be safely distinguished
- // from a comment after whitespace.
- if (!raw.trim() || /^\s*#/.test(raw)) continue;
-
- const indent = raw.match(/^\s*/)[0].length;
- const content = raw.slice(indent);
-
- const colonIdx = findTopLevelColon(content);
- if (colonIdx === -1) continue;
-
- while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
- stack.pop();
- }
-
- const key = content.slice(0, colonIdx).trim();
- const rest = content.slice(colonIdx + 1).trim();
- const parent = stack[stack.length - 1].obj;
-
- if (rest === '') {
- const obj = {};
- parent[key] = obj;
- stack.push({ indent, obj });
- } else {
- parent[key] = parseScalar(rest);
- }
- }
-
- return root;
-}
-
-function findTopLevelColon(s) {
- let inQuote = null;
- for (let i = 0; i < s.length; i++) {
- const ch = s[i];
- if (inQuote) {
- if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
- } else if (ch === '"' || ch === "'") {
- inQuote = ch;
- } else if (ch === ':') {
- return i;
- }
- }
- return -1;
-}
-
-function parseScalar(raw) {
- const s = raw.trim();
- if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
- return s.slice(1, -1);
- }
- if (s === 'true') return true;
- if (s === 'false') return false;
- if (s === 'null' || s === '~') return null;
- if (/^-?\d+$/.test(s)) return Number(s);
- if (/^-?\d*\.\d+$/.test(s)) return Number(s);
- return s;
-}
-
-const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
-const OKLCH_RE = /oklch\([^)]+\)/gi;
-const RGBA_RE = /rgba?\([^)]+\)/gi;
-const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
-const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
-
-// ---------- Section splitting ----------
-
-function splitSections(md) {
- const lines = md.split(/\r?\n/);
- let title = null;
- const sections = {};
- let current = null;
-
- for (const raw of lines) {
- const line = raw.trimEnd();
-
- if (!title && line.startsWith('# ') && !line.startsWith('## ')) {
- title = line.replace(/^#\s+/, '').trim();
- continue;
- }
-
- const h2 = line.match(/^##\s+(?:\d+\.\s*)?([^:\n]+?)(?::\s*(.+))?$/);
- if (h2) {
- const rawName = normalizeApostrophes(h2[1].trim());
- const subtitle = h2[2] ? h2[2].trim() : null;
- const canonical = matchCanonicalSection(rawName);
- if (canonical) {
- current = { name: canonical, subtitle, lines: [] };
- sections[canonical] = current;
- continue;
- }
- // non-canonical H2 — ignore but stop feeding into current
- current = null;
- continue;
- }
-
- if (current) current.lines.push(raw);
- }
-
- return { title, sections };
-}
-
-function normalizeApostrophes(s) {
- return s.replace(/[\u2018\u2019]/g, "'");
-}
-
-function matchCanonicalSection(name) {
- const normalized = normalizeApostrophes(name).toLowerCase();
- // Exact match first
- for (const c of CANONICAL_SECTIONS) {
- if (normalizeApostrophes(c).toLowerCase() === normalized) return c;
- }
- // Keyword-contained match: "Overview & Creative North Star" -> "Overview",
- // "Elevation & Depth" -> "Elevation", etc.
- for (const c of CANONICAL_SECTIONS) {
- const key = normalizeApostrophes(c).toLowerCase();
- const pattern = new RegExp(`\\b${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
- if (pattern.test(normalized)) return c;
- }
- return null;
-}
-
-// ---------- Subsection splitting (inside a canonical section) ----------
-
-function splitSubsections(lines) {
- const subs = [];
- let current = { name: null, lines: [] };
- subs.push(current);
-
- for (const raw of lines) {
- const h3 = raw.match(/^###\s+(.+?)\s*$/);
- if (h3) {
- current = { name: h3[1].trim(), lines: [] };
- subs.push(current);
- continue;
- }
- current.lines.push(raw);
- }
-
- return subs;
-}
-
-// ---------- Generic helpers ----------
-
-function collectParagraphs(lines) {
- const paragraphs = [];
- let buf = [];
- const flush = () => {
- if (buf.length) {
- paragraphs.push(buf.join(' ').trim());
- buf = [];
- }
- };
- for (const raw of lines) {
- const trimmed = raw.trim();
- if (trimmed === '') { flush(); continue; }
- // Horizontal rules (---, ***) and headings/bullets end a paragraph.
- if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { flush(); continue; }
- if (raw.startsWith('#') || raw.match(/^[-*]\s/)) { flush(); continue; }
- buf.push(trimmed);
- }
- flush();
- return paragraphs.filter(Boolean);
-}
-
-function collectBullets(lines) {
- const bullets = [];
- let current = null;
- for (const raw of lines) {
- const m = raw.match(/^\s*[-*]\s+(.+)$/);
- if (m) {
- if (current) bullets.push(current);
- current = m[1];
- continue;
- }
- // continuation of a bullet (indented line)
- if (current && raw.match(/^\s{2,}\S/)) {
- current += ' ' + raw.trim();
- continue;
- }
- // blank line ends a bullet
- if (raw.trim() === '' && current) {
- bullets.push(current);
- current = null;
- }
- }
- if (current) bullets.push(current);
- return bullets;
-}
-
-function stripBold(s) {
- return s.replace(/\*\*(.+?)\*\*/g, '$1');
-}
-
-function extractNamedRules(lines) {
- const rules = [];
- const seen = new Set();
-
- // Style A (Impeccable): "**The X Rule.** body body body" — can span lines.
- const joined = lines.join('\n');
- const inlineStart = /\*\*(The [^*]+?Rule)\.\*\*/g;
- const inlineMatches = [];
- let m;
- while ((m = inlineStart.exec(joined)) !== null) {
- inlineMatches.push({ name: m[1], start: m.index, end: inlineStart.lastIndex });
- }
- for (let i = 0; i < inlineMatches.length; i++) {
- const mm = inlineMatches[i];
- const bodyEnd = i + 1 < inlineMatches.length ? inlineMatches[i + 1].start : joined.length;
- const body = joined
- .slice(mm.end, bodyEnd)
- .replace(/\n##[^\n]*$/s, '')
- .replace(/\n###[^\n]*$/s, '')
- .trim();
- const name = stripBold(mm.name).trim();
- seen.add(name.toLowerCase());
- rules.push({ name, body: stripBold(body) });
- }
-
- // Style B (Stitch): `### The "X" Rule` or `### The X Fallback`, body is the
- // bullets/paragraphs until the next heading. Accept Rule / Fallback / Principle.
- for (let i = 0; i < lines.length; i++) {
- const h3 = lines[i].match(/^###\s+(.+?)\s*$/);
- if (!h3) continue;
- const headerName = stripBold(h3[1]).replace(/["“”]/g, '').trim();
- if (!/^The\b.*\b(Rule|Fallback|Principle)\b/i.test(headerName)) continue;
- if (seen.has(headerName.toLowerCase())) continue;
-
- const bodyLines = [];
- for (let j = i + 1; j < lines.length; j++) {
- if (/^##\s|^###\s/.test(lines[j])) break;
- bodyLines.push(lines[j]);
- }
- const body = stripBold(bodyLines.join('\n').replace(/\n+/g, ' ')).trim();
- if (body) {
- seen.add(headerName.toLowerCase());
- rules.push({ name: headerName, body });
- }
- }
-
- // Style C (Stitch bullet form): "* **The Layering Principle:** body"
- // Colon/period lives inside the bold, so match "**...**" then inspect.
- for (const b of collectBullets(lines)) {
- const mm = b.match(/^\*\*([^*]+?)\*\*\s*(.+)$/);
- if (!mm) continue;
- const nameRaw = mm[1].replace(/[.:]\s*$/, '').replace(/["“”]/g, '').trim();
- if (!/^The\b.+\b(Rule|Fallback|Principle)$/i.test(nameRaw)) continue;
- if (seen.has(nameRaw.toLowerCase())) continue;
- seen.add(nameRaw.toLowerCase());
- rules.push({ name: nameRaw, body: stripBold(mm[2]).trim() });
- }
-
- return rules;
-}
-
-// ---------- Per-section extractors ----------
-
-function extractOverview(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
- const northStar = text.match(/\*\*Creative North Star:\s*"([^"]+)"\*\*/);
- const keyChars = [];
- const keyCharMatch = text.match(/\*\*Key Characteristics:\*\*\s*\n([\s\S]+?)(?:\n##|\n###|$)/);
- if (keyCharMatch) {
- for (const line of keyCharMatch[1].split('\n')) {
- const m = line.match(/^\s*[-*]\s+(.+)$/);
- if (m) keyChars.push(stripBold(m[1].trim()));
- }
- }
-
- // Philosophy paragraphs: everything that isn't a rule header or key-char block
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) =>
- !p.startsWith('**Creative North Star') &&
- !p.startsWith('**Key Characteristics')
- );
-
- return {
- subtitle: section.subtitle,
- creativeNorthStar: northStar ? northStar[1] : null,
- philosophy: paragraphs,
- keyCharacteristics: keyChars,
- };
-}
-
-function extractColors(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ');
- const groups = [];
- const ROLE_KEYWORDS = /^(primary|secondary|tertiary|neutral|accent)\b/i;
-
- for (const sub of subs.slice(1)) {
- if (!sub.name || /Named Rules?/i.test(sub.name) || /^The\s/i.test(sub.name)) continue;
-
- const bullets = collectBullets(sub.lines);
- const parsed = bullets.map((b) => parseColorBullet(b)).filter(Boolean);
- if (parsed.length === 0) continue;
-
- // If every bullet starts with a role keyword (Primary/Secondary/...), promote
- // each bullet to its own group. Otherwise keep the subsection as the group.
- const allRoleBullets =
- parsed.length > 0 && parsed.every((p) => p.name && ROLE_KEYWORDS.test(p.name));
-
- if (allRoleBullets) {
- for (const p of parsed) {
- groups.push({ role: p.name, colors: [p] });
- }
- } else {
- groups.push({ role: sub.name, colors: parsed });
- }
- }
-
- // If the Colors section has no subsections at all (unlikely), fall back to
- // scanning the whole section as a flat bullet list.
- if (groups.length === 0) {
- const flat = collectBullets(section.lines)
- .map((b) => parseColorBullet(b))
- .filter(Boolean);
- if (flat.length) {
- for (const p of flat) {
- if (p.name && ROLE_KEYWORDS.test(p.name)) {
- groups.push({ role: p.name, colors: [p] });
- } else {
- const fallback = groups.find((g) => g.role === 'Palette');
- if (fallback) fallback.colors.push(p);
- else groups.push({ role: 'Palette', colors: [p] });
- }
- }
- }
- }
-
- return {
- subtitle: section.subtitle,
- description: description || null,
- groups,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function parseColorBullet(bullet) {
- const text = bullet.trim();
-
- // Case 1 (Impeccable): **Name** (value-with-maybe-nested-parens): description
- const bold = text.match(/^\*\*(.+?)\*\*\s*(.*)$/);
- if (bold && bold[2].startsWith('(')) {
- const value = extractParenGroup(bold[2]);
- if (value !== null) {
- const after = bold[2].slice(value.length + 2).trimStart();
- if (after.startsWith(':')) {
- return buildColor(bold[1], value, after.slice(1).trim());
- }
- }
- }
-
- // Case 2 (Stitch): **Name (values):** description — value embedded in bold.
- const stitch = text.match(/^\*\*([^*]+?)\s*\(([^)]+)\):\*\*\s*(.*)$/);
- if (stitch) {
- return buildColor(stitch[1].trim(), stitch[2], stitch[3]);
- }
-
- // Case 3: bullet without bold, just hex/oklch inside.
- const values = collectColorValues(text);
- if (values.length) {
- return buildColor(null, values.join(' to '), text);
- }
- return null;
-}
-
-function extractParenGroup(s) {
- if (s[0] !== '(') return null;
- let depth = 0;
- for (let i = 0; i < s.length; i++) {
- if (s[i] === '(') depth++;
- else if (s[i] === ')') {
- depth--;
- if (depth === 0) return s.slice(1, i);
- }
- }
- return null;
-}
-
-function buildColor(name, rawValue, description) {
- const values = collectColorValues(rawValue);
- const primary = values[0] ?? rawValue.trim();
- return {
- name: name ? stripBold(name).trim() : null,
- value: primary,
- valueRange: values.length > 1 ? values : null,
- format: detectFormat(primary),
- description: stripBold(description || '').trim() || null,
- };
-}
-
-function collectColorValues(s) {
- const out = [];
- s.replace(HEX_RE, (v) => {
- out.push(v);
- return v;
- });
- s.replace(OKLCH_RE, (v) => {
- out.push(v);
- return v;
- });
- return out;
-}
-
-function detectFormat(v) {
- if (!v) return 'unknown';
- if (v.startsWith('#')) return 'hex';
- if (/^oklch/i.test(v)) return 'oklch';
- if (/^rgb/i.test(v)) return 'rgb';
- return 'unknown';
-}
-
-function scanInlineColors(lines) {
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '');
- const color = parseColorBullet(trimmed);
- if (color) out.push(color);
- }
- return out;
-}
-
-function parseStitchInlineGroups(lines) {
- // Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
- // Each bullet IS its own role. Group them under the spoken role name.
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
- const m = trimmed.match(
- /^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
- );
- if (m) {
- const role = m[1];
- const color = buildColor(role, m[2], m[3]);
- out.push({ role, colors: [color] });
- }
- }
- return out;
-}
-
-function extractTypography(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
-
- const fonts = {};
- // Pattern A: **Display Font:** Family (with fallback)
- const fontLineRe = /\*\*([\w\s/]+?)Font:\*\*\s*([^\n(]+?)(?:\s*\(with\s+([^)]+)\))?\s*$/gm;
- let fm;
- while ((fm = fontLineRe.exec(text)) !== null) {
- const rawRole = fm[1].trim().toLowerCase().replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || 'display';
- fonts[role] = {
- family: fm[2].trim(),
- fallback: fm[3] ? fm[3].trim() : null,
- };
- }
-
- // Pattern B (Stitch): * **Display & Headlines (Noto Serif):** description
- if (Object.keys(fonts).length === 0) {
- const stitchRe = /\*\*([\w\s&/]+?)\s*\(([^)]+)\):\*\*\s*(.+)/g;
- let sm;
- while ((sm = stitchRe.exec(text)) !== null) {
- const rawRole = sm[1]
- .trim()
- .toLowerCase()
- .replace(/\s*&\s*/g, '-')
- .replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || rawRole;
- fonts[role] = { family: sm[2].trim(), fallback: null, purpose: sm[3].trim() };
- }
- }
-
- // Character paragraph — either a **Character:** label, or fall back to the
- // first free paragraph under the section header (Stitch style).
- const characterMatch = text.match(/\*\*Character:\*\*\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\n|\n###|\n##|$)/);
- let character = characterMatch ? characterMatch[1].replace(/\n/g, ' ').trim() : null;
- if (!character) {
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) => !/^\*\*[\w\s/&]+Font/i.test(p) && !/^\*\*[\w\s/&]+\([^)]+\)/.test(p)
- );
- if (paragraphs.length) character = paragraphs[0];
- }
-
- // Hierarchy bullets under ### Hierarchy
- const subs = splitSubsections(section.lines);
- let hierarchy = [];
- const hierSub = subs.find((s) => s.name && /hierarch/i.test(s.name));
- if (hierSub) {
- const bullets = collectBullets(hierSub.lines);
- hierarchy = bullets.map(parseTypeBullet).filter(Boolean);
- }
-
- return {
- subtitle: section.subtitle,
- fonts,
- character,
- hierarchy,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function normalizeFontRole(raw) {
- // Canonical roles the panel cares about: display, body, label, mono.
- // Stitch often writes compound roles like "display-&-headlines" or "ui-&-body"
- // — collapse them to the first canonical role present.
- const tokens = raw.split(/[-/&\s]+/).filter(Boolean);
- const priority = ['display', 'headline', 'body', 'ui', 'label', 'mono'];
- const canonical = { headline: 'display', ui: 'body' };
- for (const p of priority) {
- if (tokens.includes(p)) return canonical[p] || p;
- }
- return null;
-}
-
-function parseTypeBullet(bullet) {
- // - **Display** (family, weight 300, italic, clamp(...), line-height 1): purpose
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(([^)]+)\):\s*(.*)$/);
- if (!m) return null;
- const name = m[1].trim();
- const specs = m[2].split(',').map((s) => s.trim());
- return {
- name,
- specs,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractElevation(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ') || null;
-
- const shadows = [];
- const seen = new Set();
- const dedupe = (entry) => {
- const key = (entry.name || '') + '::' + entry.value;
- if (seen.has(key)) return;
- seen.add(key);
- shadows.push(entry);
- };
-
- for (const b of collectBullets(section.lines)) {
- const parsed = parseShadowBullet(b);
- if (parsed) dedupe(parsed);
- }
-
- // Fallback: extract shadows written inline in prose. Stitch style is
- // "...use an extra-diffused shadow: `box-shadow: 0 12px 40px rgba(...)`."
- for (const p of collectParagraphs(section.lines)) {
- for (const inline of extractInlineShadows(p)) dedupe(inline);
- }
- for (const b of collectBullets(section.lines)) {
- for (const inline of extractInlineShadows(b)) dedupe(inline);
- }
-
- return {
- subtitle: section.subtitle,
- description,
- shadows,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function extractInlineShadows(text) {
- // Find `box-shadow: ...` anywhere in prose and capture the value. Work on the
- // raw string so it handles both backtick-fenced and unfenced variants.
- const out = [];
- const re = /box-shadow\s*:\s*([^`;\n]+)/gi;
- let m;
- while ((m = re.exec(text)) !== null) {
- const value = m[1].replace(/[`.)]+$/, '').trim();
- if (!value) continue;
- // Name heuristic: the noun immediately before the shadow phrase.
- // e.g. "an extra-diffused shadow: ..." -> "extra-diffused shadow"
- const before = text.slice(0, m.index);
- const nameMatch = before.match(/\b([A-Za-z][A-Za-z\- ]{2,40})\s+shadow\b[^A-Za-z0-9]*$/i);
- let name = null;
- if (nameMatch) {
- const stripped = nameMatch[1]
- .replace(/^(?:use|using|apply|applying|is|are|looks? like)\s+/i, '')
- .replace(/^(?:a|an|the)\s+/i, '')
- .trim();
- if (stripped) {
- name =
- stripped.charAt(0).toUpperCase() + stripped.slice(1) + ' shadow';
- }
- }
- out.push({
- name,
- value,
- purpose: null,
- });
- }
- return out;
-}
-
-function parseShadowBullet(bullet) {
- // - **Name** (`box-shadow: value`): purpose
- // - **Name** (`value`): purpose
- // Only accept if the paren content looks like a shadow value (contains px,
- // rem, rgba, or box-shadow). This filters out `**Rule Name:**` bullets.
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(`?([^`]+?)`?\):\s*(.*)$/);
- if (!m) return null;
- const rawValue = m[2].replace(/^box-shadow:\s*/i, '').trim();
- const looksLikeShadow =
- /box-shadow|rgba?\(|\bpx\b|\brem\b|^-?\d+\s/i.test(rawValue) &&
- /\d/.test(rawValue);
- if (!looksLikeShadow) return null;
- const name = stripBold(m[1]).trim();
- return {
- name,
- value: rawValue,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractComponents(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const components = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
-
- const bullets = collectBullets(sub.lines);
- const paragraphs = collectParagraphs(sub.lines);
-
- const variants = [];
- const properties = {};
-
- for (const b of bullets) {
- // - **Key:** value
- const m = b.match(/^\*\*(.+?):?\*\*:?\s*(.+)$/);
- if (m) {
- const key = stripBold(m[1]).trim();
- const value = stripBold(m[2]).trim();
- // Heuristic: "Primary", "Secondary", "Hover", "Focus" etc are variants;
- // "Shape", "Background", "Padding" are properties.
- if (/^(primary|secondary|tertiary|ghost|hover|focus|active|disabled|default|error|selected|unselected|state)$/i.test(key.split(/[\s/]/)[0])) {
- variants.push({ name: key, description: value });
- } else {
- properties[key.toLowerCase()] = value;
- }
- }
- }
-
- components.push({
- name: sub.name,
- description: paragraphs.join(' ') || null,
- properties,
- variants,
- });
- }
-
- return {
- subtitle: section.subtitle,
- components,
- };
-}
-
-function extractDosDonts(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const dos = [];
- const donts = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
- const subName = normalizeApostrophes(sub.name);
- const bullets = collectBullets(sub.lines).map((b) => stripBold(b).trim());
- if (/^do'?t?:?$/i.test(subName) || /^do:?$/i.test(subName)) {
- dos.push(...bullets);
- } else if (/^don'?t:?$/i.test(subName)) {
- donts.push(...bullets);
- }
- }
-
- // Classify by bullet prefix as a backup (catches loose bullets outside H3 wrappers)
- for (const b of collectBullets(section.lines)) {
- const stripped = normalizeApostrophes(stripBold(b).trim());
- if (/^don'?t\b/i.test(stripped)) {
- if (!donts.some((d) => normalizeApostrophes(d) === stripped)) donts.push(stripped);
- } else if (/^do\b/i.test(stripped)) {
- if (!dos.some((d) => normalizeApostrophes(d) === stripped)) dos.push(stripped);
- }
- }
-
- return { dos, donts };
-}
-
-// ---------- Coverage assessment ----------
-
-function assessCoverage(model) {
- const report = {};
-
- report.overview = model.overview
- ? {
- northStar: Boolean(model.overview.creativeNorthStar),
- philosophy: model.overview.philosophy.length > 0,
- keyCharacteristics: model.overview.keyCharacteristics.length,
- }
- : 'missing';
-
- report.colors = model.colors
- ? {
- groups: model.colors.groups.length,
- totalColors: model.colors.groups.reduce((n, g) => n + g.colors.length, 0),
- rules: model.colors.rules.length,
- }
- : 'missing';
-
- report.typography = model.typography
- ? {
- fonts: Object.keys(model.typography.fonts).length,
- hierarchyEntries: model.typography.hierarchy.length,
- character: Boolean(model.typography.character),
- rules: model.typography.rules.length,
- }
- : 'missing';
-
- report.elevation = model.elevation
- ? {
- shadows: model.elevation.shadows.length,
- rules: model.elevation.rules.length,
- description: Boolean(model.elevation.description),
- }
- : 'missing';
-
- report.components = model.components
- ? {
- count: model.components.components.length,
- variantTotal: model.components.components.reduce((n, c) => n + c.variants.length, 0),
- }
- : 'missing';
-
- report.dosDonts = model.dosDonts
- ? {
- dos: model.dosDonts.dos.length,
- donts: model.dosDonts.donts.length,
- }
- : 'missing';
-
- return report;
-}
-
-// ---------- Main ----------
-
-export function parseDesignMd(md) {
- const { frontmatter, body } = parseFrontmatter(md);
- const { title, sections } = splitSections(body);
- return {
- schemaVersion: 2,
- title,
- frontmatter,
- overview: extractOverview(sections['Overview']),
- colors: extractColors(sections['Colors']),
- typography: extractTypography(sections['Typography']),
- elevation: extractElevation(sections['Elevation']),
- components: extractComponents(sections['Components']),
- dosDonts: extractDosDonts(sections["Do's and Don'ts"]),
- };
-}
-
-export { assessCoverage };
@@ -1,198 +0,0 @@
-/**
- * Scan a project tree for Content-Security-Policy signals and classify the
- * shape so the agent knows which patch template to propose.
- *
- * Used at first-time `live.mjs` setup. Mechanical (grep-based) — no network,
- * no dev server, no JS evaluation. The classification drives a user-facing
- * consent prompt; the agent does the actual patch writing.
- *
- * Shapes are named by patch mechanism, not framework origin:
- * - "append-arrays": CSP defined as structured directive arrays. Patch
- * appends a dev-only localhost entry. Covers:
- * - Monorepo helpers with additional*Src options
- * (e.g. createBaseNextConfig for Next)
- * - SvelteKit kit.csp.directives
- * - nuxt-security module's contentSecurityPolicy
- * - "append-string": CSP built as a literal value string. Patch splices
- * a dev-only token into script-src and connect-src.
- * Covers:
- * - Inline Next.js headers() with CSP string
- * - Nuxt routeRules / nitro.routeRules CSP headers
- * - "middleware": CSP set dynamically in middleware.{ts,js}.
- * Detected but not auto-patched in v1.
- * - "meta-tag": <meta http-equiv="Content-Security-Policy"> in
- * layout files. Detected but not auto-patched in v1.
- * - null: no CSP signals found; no patch needed.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const SKIP_DIRS = new Set([
- 'node_modules',
- '.git',
- '.next',
- '.turbo',
- '.svelte-kit',
- '.nuxt',
- '.astro',
- 'dist',
- 'build',
- 'out',
- '.vercel',
-]);
-
-const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.tsx', '.jsx']);
-const LAYOUT_EXTS = new Set(['.tsx', '.jsx', '.astro', '.vue', '.svelte', '.html']);
-const MAX_DEPTH = 6;
-const MAX_READ_BYTES = 64 * 1024;
-
-// append-arrays signals: CSP expressed as structured directive arrays
-const MONOREPO_HELPER_SIGNALS = [
- /\bbuildCSPConfig\b/,
- /\bbuildSecurityHeaders\b/,
- /\badditionalScriptSrc\b/,
- /\badditionalConnectSrc\b/,
- /\bcreateBaseNextConfig\b/,
-];
-const SVELTEKIT_CSP_SIGNALS = [
- /\bkit\s*:/,
- /\bcsp\s*:/,
- /\bdirectives\s*:/,
-];
-const NUXT_SECURITY_SIGNALS = [
- /['"]nuxt-security['"]/,
- /\bcontentSecurityPolicy\b/,
-];
-
-// append-string signals: CSP written as a literal value string
-const INLINE_HEADER_SIGNALS = [
- /["']Content-Security-Policy["']/i,
- /\bscript-src\b/,
- /\bconnect-src\b/,
-];
-const NUXT_ROUTE_RULES_SIGNALS = [
- /\brouteRules\b/,
- /Content-Security-Policy/i,
- /\bscript-src\b/,
-];
-
-const MIDDLEWARE_HINT = /headers\.set\(\s*["']Content-Security-Policy["']/i;
-const META_TAG_HINT = /http-equiv\s*=\s*["']Content-Security-Policy["']/i;
-
-/**
- * @param {string} cwd Project root.
- * @returns {{ shape: string|null, signals: string[] }}
- */
-export function detectCsp(cwd = process.cwd()) {
- const hits = { appendArrays: [], appendString: [], middleware: [], metaTag: [] };
-
- walk(cwd, cwd, 0, (absPath, relPath, body) => {
- const ext = path.extname(absPath);
- const base = path.basename(absPath).toLowerCase();
- const isConfig = (name) =>
- new RegExp('(^|/)' + name + '\\.config\\.').test(relPath);
-
- // === append-arrays candidates ===
-
- // Monorepo CSP helper: packages/*/src/.../(config|security)/*
- if (SCAN_EXTS.has(ext) &&
- /packages\/[^/]+\/src\/.*(config|next-config|security)/.test(relPath) &&
- MONOREPO_HELPER_SIGNALS.some((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // SvelteKit kit.csp.directives
- if (SCAN_EXTS.has(ext) && isConfig('svelte') &&
- SVELTEKIT_CSP_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // Nuxt nuxt-security module
- if (SCAN_EXTS.has(ext) && isConfig('nuxt') &&
- NUXT_SECURITY_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // === append-string candidates ===
-
- // Inline headers in Next/Nuxt/SvelteKit/Astro/Vite config
- if (SCAN_EXTS.has(ext) &&
- /(^|\/)(next|nuxt|vite|astro|svelte)\.config\./.test(relPath) &&
- INLINE_HEADER_SIGNALS.every((re) => re.test(body))) {
- // Nuxt routeRules is a sub-shape of append-string; we already covered
- // nuxt-security above via return, so any remaining Nuxt CSP match here
- // is a route-rules / inline-headers case. Either way, same patch
- // mechanism.
- hits.appendString.push(relPath);
- return;
- }
-
- // === detect-only shapes ===
-
- if ((base === 'middleware.ts' || base === 'middleware.js' || base === 'middleware.mjs') &&
- MIDDLEWARE_HINT.test(body)) {
- hits.middleware.push(relPath);
- }
-
- if (LAYOUT_EXTS.has(ext) && META_TAG_HINT.test(body)) {
- hits.metaTag.push(relPath);
- }
- });
-
- // Priority: append-arrays > append-string > middleware > meta-tag.
- // Structured patches are safer than string splices; runtime and HTML
- // injection patches are less reliable and v1 doesn't auto-apply them.
- if (hits.appendArrays.length > 0) {
- return { shape: 'append-arrays', signals: hits.appendArrays };
- }
- if (hits.appendString.length > 0) {
- return { shape: 'append-string', signals: hits.appendString };
- }
- if (hits.middleware.length > 0) {
- return { shape: 'middleware', signals: hits.middleware };
- }
- if (hits.metaTag.length > 0) {
- return { shape: 'meta-tag', signals: hits.metaTag };
- }
- return { shape: null, signals: [] };
-}
-
-function walk(root, dir, depth, visit) {
- if (depth > MAX_DEPTH) return;
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
-
- for (const entry of entries) {
- const abs = path.join(dir, entry.name);
- if (entry.isDirectory()) {
- if (SKIP_DIRS.has(entry.name)) continue;
- walk(root, abs, depth + 1, visit);
- continue;
- }
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name);
- if (!SCAN_EXTS.has(ext) && !LAYOUT_EXTS.has(ext)) continue;
- let body;
- try {
- const fd = fs.openSync(abs, 'r');
- try {
- const buf = Buffer.alloc(MAX_READ_BYTES);
- const n = fs.readSync(fd, buf, 0, MAX_READ_BYTES, 0);
- body = buf.slice(0, n).toString('utf-8');
- } finally { fs.closeSync(fd); }
- } catch { continue; }
- visit(abs, path.relative(root, abs), body);
- }
-}
-
-// CLI mode
-const _running = process.argv[1];
-if (_running?.endsWith('detect-csp.mjs') || _running?.endsWith('detect-csp.mjs/')) {
- const result = detectCsp(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
@@ -1,21 +0,0 @@
-#!/usr/bin/env node
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { pathToFileURL, fileURLToPath } from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const candidates = [
- path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
-];
-const detectorPath = candidates.find(p => fs.existsSync(p));
-
-if (!detectorPath) {
- process.stderr.write('Error: bundled detector not found.\n');
- process.exit(1);
-}
-
-const { detectCli } = await import(pathToFileURL(detectorPath));
-
-await detectCli();
@@ -1,1688 +0,0 @@
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
@@ -1,232 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
-import { detectHtml } from '../engines/static-html/detect-html.mjs';
-import { detectText } from '../engines/regex/detect-text.mjs';
-import {
- HTML_EXTENSIONS,
- buildImportGraph,
- detectFrameworkConfig,
- isPortListening,
- walkDir,
-} from '../node/file-system.mjs';
-
-// ---------------------------------------------------------------------------
-// Output formatting
-// ---------------------------------------------------------------------------
-
-function formatFindings(findings, jsonMode) {
- if (jsonMode) return JSON.stringify(findings, null, 2);
-
- const grouped = {};
- for (const f of findings) {
- if (!grouped[f.file]) grouped[f.file] = [];
- grouped[f.file].push(f);
- }
- const out = [];
- for (const [file, items] of Object.entries(grouped)) {
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
- out.push(`\n${file}${importNote}`);
- for (const item of items) {
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
- out.push(` → ${item.description}`);
- }
- }
- out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
- return out.join('\n');
-}
-
-// ---------------------------------------------------------------------------
-// Stdin handling
-// ---------------------------------------------------------------------------
-
-async function handleStdin() {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- const input = Buffer.concat(chunks).toString('utf-8');
- try {
- const parsed = JSON.parse(input);
- const fp = parsed?.tool_input?.file_path;
- if (fp && fs.existsSync(fp)) {
- return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
- ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
- }
- } catch { /* not JSON */ }
- return detectText(input, '<stdin>');
-}
-
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-async function confirm(question) {
- const rl = (await import('node:readline')).default.createInterface({
- input: process.stdin, output: process.stderr,
- });
- return new Promise((resolve) => {
- rl.question(`${question} [Y/n] `, (answer) => {
- rl.close();
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
- });
- });
-}
-
-function printUsage() {
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
-
-Scan files or URLs for UI anti-patterns and design quality issues.
-
-Options:
- --fast Regex-only mode (skip static HTML/CSS analysis, faster but misses linked stylesheets)
- --json Output results as JSON
- --help Show this help message
-
-Detection modes:
- HTML files Static HTML/CSS analysis (default, catches linked CSS)
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
- URLs Puppeteer full browser rendering (auto-detected)
- --fast Forces regex for all files
-
-Examples:
- impeccable detect src/
- impeccable detect index.html
- impeccable detect https://example.com
- impeccable detect --fast --json .`);
-}
-
-async function detectCli() {
- let args = process.argv.slice(2).map(arg => {
- if (arg === '-json') return '--json';
- if (arg === '-fast') return '--fast';
- return arg;
- });
- if (args[0] === 'detect') args = args.slice(1);
- const jsonMode = args.includes('--json');
- const helpMode = args.includes('--help');
- const fastMode = args.includes('--fast');
- const targets = args.filter(a => !a.startsWith('--'));
-
- if (helpMode) { printUsage(); process.exit(0); }
-
- let allFindings = [];
-
- if (!process.stdin.isTTY && targets.length === 0) {
- allFindings = await handleStdin();
- } else {
- const paths = targets.length > 0 ? targets : [process.cwd()];
- const urlTargetCount = paths.filter(target => /^https?:\/\//i.test(target)).length;
- const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
-
- try {
- for (const target of paths) {
- if (/^https?:\/\//i.test(target)) {
- try {
- const scanner = browserDetector
- ? (url) => browserDetector.detectUrl(url)
- : (url) => detectUrl(url);
- allFindings.push(...await scanner(target));
- } catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
- continue;
- }
-
- const resolved = path.resolve(target);
- let stat;
- try { stat = fs.statSync(resolved); }
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
-
- if (stat.isDirectory()) {
- // Check for framework dev server config (skip in JSON mode to avoid polluting output)
- if (!jsonMode) {
- const fwConfig = detectFrameworkConfig(resolved);
- if (fwConfig) {
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
- if (probe.listening && probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
- `For more accurate results, scan the running site:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- } else if (probe.listening && !probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
- );
- } else {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Start the dev server and scan via URL for best results:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- }
- }
- }
-
- const files = walkDir(resolved);
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
-
- // Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
- if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
- process.stderr.write(
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
- `Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
- `Use --fast to skip static HTML/CSS analysis, or target a specific subdirectory.\n`
- );
- const ok = await confirm('Continue?');
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
- }
-
- // Build import graph for multi-file awareness
- const graph = buildImportGraph(files);
- // Build reverse map: file -> set of files that import it
- const importedByMap = new Map();
- for (const [importer, imports] of graph) {
- for (const imported of imports) {
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
- importedByMap.get(imported).add(importer);
- }
- }
-
- for (const file of files) {
- const ext = path.extname(file).toLowerCase();
- let fileFindings;
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- fileFindings = await detectHtml(file);
- } else {
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
- }
- // Annotate findings with import context
- const importers = importedByMap.get(file);
- if (importers && importers.size > 0) {
- const importerNames = [...importers].map(f => path.basename(f));
- for (const f of fileFindings) {
- f.importedBy = importerNames;
- }
- }
- allFindings.push(...fileFindings);
- }
- } else if (stat.isFile()) {
- const ext = path.extname(resolved).toLowerCase();
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- allFindings.push(...await detectHtml(resolved));
- } else {
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
- }
- }
- }
- } finally {
- if (browserDetector) await browserDetector.close();
- }
- }
-
- if (allFindings.length > 0) {
- if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
- else process.stderr.write(formatFindings(allFindings, false) + '\n');
- process.exit(2);
- }
- if (jsonMode) process.stdout.write('[]\n');
- process.exit(0);
-}
-
-export { formatFindings, handleStdin, confirm, printUsage, detectCli };
@@ -1,4030 +0,0 @@
-/**
- * Anti-Pattern Browser Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * GENERATED -- do not edit. Source: cli/engine/browser/injected/index.mjs
- * Rebuild: node scripts/build-browser-detector.js
- *
- * Usage: <script src="detect-antipatterns-browser.js"></script>
- * Re-scan: window.impeccableScan()
- */
-(function () {
-if (typeof window === 'undefined') return;
-// --- cli/engine/shared/constants.mjs ---
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-// --- cli/engine/registry/antipatterns.mjs ---
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-// --- cli/engine/shared/color.mjs ---
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-// --- cli/engine/rules/checks.mjs ---
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-// --- cli/engine/browser/injected/index.mjs ---
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
-
-})();
@@ -1,43 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Anti-Pattern Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * Public API facade. Runtime engines live under cli/engine/engines/.
- */
-
-import { detectCli } from './cli/main.mjs';
-
-export { ANTIPATTERNS, RULE_ENGINE_SUPPORT, getAntipattern, getRulesForCategory, getRuleEngineSupport } from './registry/antipatterns.mjs';
-export { SAFE_TAGS, BORDER_SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS, KNOWN_SERIF_FONTS } from './shared/constants.mjs';
-export { isNeutralColor, parseRgb, relativeLuminance, contrastRatio, parseGradientColors, hasChroma, getHue, colorToHex } from './shared/color.mjs';
-export { isFullPage } from './shared/page.mjs';
-export {
- checkElementBorders,
- checkElementMotion,
- checkElementGlow,
- checkPageTypography,
- checkPageLayout,
- checkHtmlPatterns,
-} from './rules/checks.mjs';
-export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
-export { detectHtml } from './engines/static-html/detect-html.mjs';
-export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
-export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
-export {
- walkDir,
- SCANNABLE_EXTENSIONS,
- SKIP_DIRS,
- buildImportGraph,
- resolveImport,
- detectFrameworkConfig,
- isPortListening,
- FRAMEWORK_CONFIGS,
-} from './node/file-system.mjs';
-export { formatFindings, detectCli } from './cli/main.mjs';
-
-const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
-if (isMainModule) detectCli();
@@ -1,251 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { finding } from '../../findings.mjs';
-import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
-
-async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
- if (options?.visualContrast === false) return [];
- const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : 12;
- const scrollOffscreen = options?.visualContrastScrollOffscreen !== false;
- const existingLowContrastSelectors = new Set(
- serializedGroups
- .filter(group => group.findings?.some(f => f.type === 'low-contrast'))
- .map(group => group.selector)
- .filter(Boolean)
- );
-
- let browserAnalyses = [];
- const findings = [];
- if (options?.visualContrastBrowser !== false) {
- const browserFindings = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'browser-fallback',
- target,
- }, async () => {
- browserAnalyses = await page.evaluate(async ({ maxCandidates, scrollOffscreen }) => {
- if (typeof window.impeccableAnalyzeVisualContrast !== 'function') return [];
- return window.impeccableAnalyzeVisualContrast({ maxCandidates, scrollOffscreen });
- }, { maxCandidates, scrollOffscreen });
- return browserAnalyses
- .filter(result => result.finding && !existingLowContrastSelectors.has(result.selector))
- .map(result => result.finding);
- });
- findings.push(...browserFindings);
- }
-
- let candidates = browserAnalyses.length > 0 ? browserAnalyses : [];
- if (candidates.length === 0) {
- candidates = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'collect-candidates',
- target,
- }, () => page.evaluate(({ maxCandidates }) => {
- if (typeof window.impeccableCollectVisualContrastCandidates !== 'function') return [];
- return window.impeccableCollectVisualContrastCandidates({ maxCandidates });
- }, { maxCandidates }));
- }
-
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const browserResolvedSelectors = new Set(
- browserAnalyses
- .filter(result => result.status === 'fail' || result.status === 'pass')
- .map(result => result.selector)
- .filter(Boolean)
- );
- const filtered = candidates.filter(candidate =>
- !existingLowContrastSelectors.has(candidate.selector) &&
- !browserResolvedSelectors.has(candidate.selector)
- );
- if (options?.visualContrastPixel === false) return findings;
- for (const candidate of filtered) {
- const result = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'pixel-diff',
- target,
- }, async () => {
- const finding = await captureVisualContrastCandidate(page, candidate, viewport);
- return finding ? [finding] : [];
- });
- findings.push(...result);
- }
- return findings;
-}
-
-// ---------------------------------------------------------------------------
-// Puppeteer detection (for URLs)
-// ---------------------------------------------------------------------------
-
-async function detectUrl(url, options = {}) {
- const profile = options?.profile;
- const waitUntil = options?.waitUntil || 'networkidle0';
- const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const externalBrowser = options?.browser || null;
- let puppeteer;
- if (!externalBrowser) {
- try {
- puppeteer = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'import-puppeteer',
- target: url,
- }, () => import('puppeteer'));
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- }
-
- // Read the browser detection script — reuse it instead of reimplementing
- const browserScriptPath = path.resolve(
- path.dirname(fileURLToPath(import.meta.url)),
- '..',
- '..',
- 'detect-antipatterns-browser.js'
- );
- let browserScript;
- try {
- browserScript = profileStep(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'read-browser-script',
- target: url,
- }, () => fs.readFileSync(browserScriptPath, 'utf-8'));
- } catch {
- throw new Error(`Browser script not found at ${browserScriptPath}`);
- }
-
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
- // running in CI; local users keep the default hardened launch.
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
- const browser = externalBrowser || await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'launch-browser',
- target: url,
- }, () => puppeteer.default.launch({ headless: true, args: launchArgs }));
- const page = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'new-page',
- target: url,
- }, () => browser.newPage());
- let results = [];
- try {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'set-viewport',
- target: url,
- }, () => page.setViewport(viewport));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: `goto:${waitUntil}`,
- target: url,
- }, () => page.goto(url, { waitUntil, timeout: 30000 }));
- if (settleMs > 0) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'settle',
- target: url,
- }, () => new Promise(resolve => setTimeout(resolve, settleMs)));
- }
-
- // Inject the browser detection script and collect results
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'configure-pure-detect',
- target: url,
- }, () => page.evaluate(() => {
- window.__IMPECCABLE_CONFIG__ = {
- ...(window.__IMPECCABLE_CONFIG__ || {}),
- autoScan: false,
- };
- }));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'inject-browser-script',
- target: url,
- }, () => page.evaluate(browserScript));
- let serializedGroups = [];
- results = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'browser-scan',
- target: url,
- }, async () => {
- serializedGroups = await page.evaluate(() => {
- if (!window.impeccableDetect) return [];
- return window.impeccableDetect({ decorate: false, serialize: true });
- });
- return serializedGroups.flatMap(({ findings }) =>
- findings.map(f => ({ id: f.type, snippet: f.detail }))
- );
- });
- const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
- results.push(...visualFindings);
- } finally {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-page',
- target: url,
- }, () => page.close().catch(() => {}));
- if (!externalBrowser) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-browser',
- target: url,
- }, () => browser.close());
- }
- }
- return results.map(f => finding(f.id, url, f.snippet));
-}
-
-async function createBrowserDetector(options = {}) {
- let puppeteer;
- try {
- puppeteer = await import('puppeteer');
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- const launchArgs = options.launchArgs || (process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : []);
- const browser = options.browser || await puppeteer.default.launch({
- headless: options.headless ?? true,
- args: launchArgs,
- });
- const ownsBrowser = !options.browser;
- const defaults = {
- waitUntil: options.waitUntil || 'load',
- settleMs: Number.isFinite(options.settleMs) ? options.settleMs : 100,
- viewport: options.viewport || { width: 1280, height: 800 },
- };
- return {
- browser,
- async detectUrl(url, scanOptions = {}) {
- return detectUrl(url, {
- ...defaults,
- ...scanOptions,
- browser,
- });
- },
- async close() {
- if (ownsBrowser) await browser.close().catch(() => {});
- },
- };
-}
-
-export { runVisualContrastFallback, detectUrl, createBrowserDetector };
@@ -1,420 +0,0 @@
-import { GENERIC_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep } from '../../profile/profiler.mjs';
-
-// ---------------------------------------------------------------------------
-// Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
-// ---------------------------------------------------------------------------
-
-const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
-const hasBorderRadius = (line) => /border-radius/i.test(line);
-const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
-
-function isNeutralBorderColor(str) {
- const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
- if (!m) return false;
- const c = m[1].toLowerCase();
- if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
- const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
- if (hex) {
- const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
- if (shex) {
- const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- return false;
-}
-
-const REGEX_MATCHERS = [
- // --- Side-tab ---
- { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
- test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
- test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
- fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
- { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
- test: (m) => +m[1] >= 3,
- fmt: (m) => m[0] },
- // --- Border accent on rounded ---
- { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
- test: (m, line) => hasRounded(line) && +m[1] >= 1,
- fmt: (m) => m[0] },
- { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
- fmt: (m) => m[0] },
- // --- Overused font ---
- { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
- test: () => true,
- fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
- // --- Pure black background ---
- { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Gradient text ---
- { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
- test: (m, line) => /gradient/i.test(line),
- fmt: () => 'background-clip: text + gradient' },
- // --- Gradient text (Tailwind) ---
- { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
- test: (m, line) => /\bbg-gradient-to-/i.test(line),
- fmt: () => 'bg-clip-text + bg-gradient' },
- // --- Tailwind pure black background ---
- { id: 'pure-black-white', regex: /\bbg-black\b/g,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Tailwind gray on colored bg ---
- { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
- test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
- fmt: (m, line) => { const bg = line.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/); return `${m[0]} on ${bg?.[0] || '?'}`; } },
- // --- Tailwind AI palette ---
- { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
- fmt: (m) => `${m[0]} on heading` },
- { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
- fmt: (m) => `${m[0]} gradient` },
- // --- Bounce/elastic easing ---
- { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
- test: () => true,
- fmt: () => 'animate-bounce (Tailwind)' },
- { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
- test: (m) => {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
- },
- fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
- // --- Layout property transition ---
- { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition: ${found ? found.join(', ') : m[1].trim()}`;
- } },
- { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
- } },
-];
-
-const REGEX_ANALYZERS = [
- // Single font
- (content, filePath) => {
- const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
- const fonts = new Set();
- let m;
- while ((m = fontFamilyRe.exec(content)) !== null) {
- for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
- }
- }
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- while ((m = gfRe.exec(content)) !== null) {
- for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
- }
- if (fonts.size !== 1 || content.split('\n').length < 20) return [];
- const name = [...fonts][0];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
- return [finding('single-font', filePath, `only font used is ${name}`, line)];
- },
- // Flat type hierarchy
- (content, filePath) => {
- const sizes = new Set();
- const REM = 16;
- let m;
- const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
- while ((m = sizeRe.exec(content)) !== null) {
- const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
- if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
- }
- const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
- while ((m = clampRe.exec(content)) !== null) {
- sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
- sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
- }
- const TW = { 'text-xs': 12, 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24, 'text-3xl': 30, 'text-4xl': 36, 'text-5xl': 48, 'text-6xl': 60, 'text-7xl': 72, 'text-8xl': 96, 'text-9xl': 128 };
- for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
- if (sizes.size < 3) return [];
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio >= 2.0) return [];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (/font-size/i.test(lines[i]) || /\btext-(?:xs|sm|base|lg|xl|\d)/i.test(lines[i])) { line = i + 1; break; } }
- return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
- },
- // Monotonous spacing (regex)
- (content, filePath) => {
- const vals = [];
- let m;
- const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
- const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
- const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
- const rounded = vals.map(v => Math.round(v / 4) * 4);
- if (rounded.length < 10) return [];
- const counts = {};
- for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const pct = maxCount / rounded.length;
- const unique = [...new Set(rounded)].filter(v => v > 0);
- if (pct <= 0.6 || unique.length > 3) return [];
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
- },
- // Everything centered (regex)
- (content, filePath) => {
- const lines = content.split('\n');
- let centered = 0, total = 0;
- for (const line of lines) {
- if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
- total++;
- if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
- }
- }
- if (total < 5 || centered / total <= 0.7) return [];
- return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
- },
- // Dark glow (page-level: dark bg + colored box-shadow with blur)
- (content, filePath) => {
- // Check if page has a dark background
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
- if (!hasDarkBg) return [];
-
- // Check for colored box-shadow with blur > 4px
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let m;
- while ((m = shadowRe.exec(content)) !== null) {
- const val = m[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
- // Check blur: look for pattern like "0 0 20px" (third number > 4)
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- const lines = content.substring(0, m.index).split('\n');
- return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
- }
- }
- return [];
- },
-];
-
-// ---------------------------------------------------------------------------
-// Style block extraction (Vue/Svelte <style> blocks)
-// ---------------------------------------------------------------------------
-
-function extractStyleBlocks(content, ext) {
- ext = ext.toLowerCase();
- if (ext !== '.vue' && ext !== '.svelte') return [];
- const blocks = [];
- const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length + 1;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-// ---------------------------------------------------------------------------
-// CSS-in-JS extraction (styled-components, emotion)
-// ---------------------------------------------------------------------------
-
-const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
-
-function extractCSSinJS(content, ext) {
- ext = ext.toLowerCase();
- if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
- const blocks = [];
- const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null, options = {}) {
- const { profile, phase = 'regex-matchers' } = options || {};
- const findings = [];
- if (!profile) {
- for (const matcher of REGEX_MATCHERS) {
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- }
- return findings;
- }
-
- for (const matcher of REGEX_MATCHERS) {
- const matcherFindings = profileFindings(profile, {
- engine: 'regex',
- phase,
- ruleId: matcher.id,
- target: filePath,
- }, () => {
- const matches = [];
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- matches.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- return matches;
- });
- findings.push(...matcherFindings);
- }
- return findings;
-}
-
-function detectText(content, filePath, options = {}) {
- const profile = options?.profile;
- const findings = [];
- const lines = content.split('\n');
- const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
-
- // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
- // Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
- findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
- profile,
- phase: 'source',
- }));
-
- // Extract and scan <style> blocks from Vue/Svelte SFCs
- const styleBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'style-blocks',
- target: filePath,
- }, () => extractStyleBlocks(content, ext))
- : extractStyleBlocks(content, ext);
- for (const block of styleBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'style-block',
- }));
- }
-
- // Extract and scan CSS-in-JS template literals
- const cssJsBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'css-in-js',
- target: filePath,
- }, () => extractCSSinJS(content, ext))
- : extractCSSinJS(content, ext);
- for (const block of cssJsBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'css-in-js',
- }));
- }
-
- // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
- const deduped = [];
- for (const f of findings) {
- const isDupe = deduped.some(d =>
- d.antipattern === f.antipattern &&
- d.snippet === f.snippet &&
- Math.abs(d.line - f.line) <= 2
- );
- if (!isDupe) deduped.push(f);
- }
-
- // Page-level analyzers only run on full pages
- if (isFullPage(content)) {
- const analyzerIds = [
- 'single-font',
- 'flat-type-hierarchy',
- 'monotonous-spacing',
- 'everything-centered',
- 'dark-glow',
- ];
- for (let i = 0; i < REGEX_ANALYZERS.length; i++) {
- const analyzer = REGEX_ANALYZERS[i];
- deduped.push(...profileFindings(profile, {
- engine: 'regex',
- phase: 'page-analyzer',
- ruleId: analyzerIds[i] || `analyzer-${i + 1}`,
- target: filePath,
- }, () => analyzer(content, filePath)));
- }
- }
-
- return deduped;
-}
-
-export {
- REGEX_MATCHERS,
- REGEX_ANALYZERS,
- extractStyleBlocks,
- extractCSSinJS,
- runRegexMatchers,
- detectText,
-};
@@ -1,954 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { profileStep, recordProfileEvent } from '../../profile/profiler.mjs';
-import { parseAnyColor, resolveLengthPx, resolveVarRefs } from '../../rules/checks.mjs';
-
-// ---------------------------------------------------------------------------
-// jsdom CSS-variable border override map
-// ---------------------------------------------------------------------------
-//
-// jsdom's CSSOM silently drops any border shorthand that contains a var()
-// reference — the computed style for the element then shows empty width,
-// empty style, and a default black color. That's enough to hide the most
-// common real-world side-tab pattern in AI-generated pages:
-//
-// :root { --brand: #87a8ff; }
-// .card { border-left: 5px solid var(--brand); border-radius: 4px; }
-//
-// Real browsers (and therefore the browser detector path) resolve var()
-// natively, so this only affects the Node jsdom path.
-//
-// This pre-pass walks the stylesheets, finds any rule whose per-side or
-// all-sides border property contains var(), resolves the var() against
-// :root-level custom properties (read from the documentElement's computed
-// style, which jsdom DOES handle correctly), and attaches the resolved
-// width+color to every element that matches the rule's selector. The
-// Node-side `checkElementBorders` adapter consumes that map as a fallback
-// whenever jsdom's computed style came back empty.
-//
-// Limitations (intentional, to keep the pass simple):
-// * Only :root-level custom properties are resolved. Scoped overrides on
-// descendants are not tracked — uncommon in practice and would require
-// a per-element cascade walk.
-// * @media / @supports wrapped rules are ignored (jsdom often mishandles
-// these anyway).
-// * The fallback only fills sides that jsdom left empty, so any rule
-// whose border parses normally still wins via the computed style.
-
-const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
-
-// isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
-// CSS variables typically hold hex or named colors, so normalize those to
-// rgb() before handing the value off to the shared check. Anything we don't
-// recognise is passed through unchanged — isNeutralColor then treats it as
-// non-neutral, which is the safer default (matches the oklch-era bugfix).
-const NAMED_COLORS = {
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
-};
-
-function normalizeColorForCheck(value) {
- if (!value) return value;
- const v = value.trim();
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
- if (hex6) {
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
- if (hex3) {
- const [r, g, b] = [
- parseInt(hex3[1] + hex3[1], 16),
- parseInt(hex3[2] + hex3[2], 16),
- parseInt(hex3[3] + hex3[3], 16),
- ];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const named = NAMED_COLORS[v.toLowerCase()];
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
- return v;
-}
-
-function buildBorderOverrideMap(document, window) {
- const map = new Map();
- const rootStyle = window.getComputedStyle(document.documentElement);
-
- function resolveVar(value, depth = 0) {
- if (!value || depth > 10 || !value.includes('var(')) return value;
- return value.replace(
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
- (_, name, fallback) => {
- const v = rootStyle.getPropertyValue(name).trim();
- if (v) return resolveVar(v, depth + 1);
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
- return '';
- }
- );
- }
-
- function parseShorthand(text) {
- const m = text.trim().match(BORDER_SHORTHAND_RE);
- if (!m) return null;
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
- }
-
- // Read from the per-property accessors on rule.style. jsdom preserves
- // each border-* shorthand it parsed, even when the overall cssText has
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
- // `border-left: ...` loses the first declaration but keeps the second).
- const SIDE_PROPS = [
- ['borderLeft', 'Left'],
- ['borderRight', 'Right'],
- ['borderTop', 'Top'],
- ['borderBottom', 'Bottom'],
- ['borderInlineStart', 'Left'],
- ['borderInlineEnd', 'Right'],
- ];
-
- for (const sheet of document.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || []; } catch { continue; }
- for (const rule of rules) {
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
-
- const perSide = {};
-
- for (const [prop, side] of SIDE_PROPS) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const parsed = parseShorthand(resolveVar(val));
- if (parsed && parsed.color) perSide[side] = parsed;
- }
-
- // Uniform `border: <w> <style> var(...)` applies to every side the
- // per-side map didn't already claim.
- const borderAll = rule.style.border;
- if (borderAll && borderAll.includes('var(')) {
- const parsed = parseShorthand(resolveVar(borderAll));
- if (parsed && parsed.color) {
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
- if (!perSide[s]) perSide[s] = parsed;
- }
- }
- }
-
- // Longhand `border-*-color: var(...)` with width/style in separate
- // declarations. Rare in AI-generated pages, but cheap to cover.
- for (const [prop, side] of [
- ['borderLeftColor', 'Left'],
- ['borderRightColor', 'Right'],
- ['borderTopColor', 'Top'],
- ['borderBottomColor', 'Bottom'],
- ]) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const resolved = resolveVar(val).trim();
- if (!resolved) continue;
- // Width may or may not come from this rule — that's fine; the
- // adapter only substitutes the color when jsdom left it as a
- // literal var() string.
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
- }
-
- if (Object.keys(perSide).length === 0) continue;
-
- let matched;
- try { matched = document.querySelectorAll(rule.selectorText); }
- catch { continue; }
-
- for (const el of matched) {
- const existing = map.get(el);
- if (existing) {
- // Later rules overwrite earlier ones — approximates source-order
- // cascade for equal-specificity rules and is good enough for the
- // uncontested var()-dropped sides we're trying to recover.
- Object.assign(existing, perSide);
- } else {
- map.set(el, { ...perSide });
- }
- }
- }
- }
-
- return map;
-}
-
-// Strip `@layer NAME { … }` wrappers from a CSS / HTML source, leaving
-// the inner rules as flat CSS. jsdom doesn't implement CSS @layer, so
-// any rule inside a layer block becomes invisible to getComputedStyle.
-// Tailwind v4 makes this ubiquitous: every utility class lives in
-// `@layer utilities`, and Preflight lives in `@layer base`. Without
-// unwrapping, every Tailwind-styled element returns empty computed
-// styles. We walk the source character-by-character, balancing braces
-// so we correctly handle nested style rules inside the layer block.
-function unwrapCssAtLayer(source) {
- if (!source || !source.includes('@layer')) return source;
- // Find `@layer <name>? {` openers. The match starts at the @, and
- // we then balance braces from the opening { onward.
- const re = /@layer\b[^{;]*\{/g;
- let out = '';
- let lastIdx = 0;
- let m;
- while ((m = re.exec(source)) !== null) {
- const openStart = m.index;
- const openEnd = m.index + m[0].length; // position right after `{`
- let depth = 1;
- let i = openEnd;
- while (i < source.length && depth > 0) {
- const c = source.charCodeAt(i);
- if (c === 0x7b /* { */) depth++;
- else if (c === 0x7d /* } */) depth--;
- i++;
- }
- if (depth !== 0) {
- // Unbalanced — bail and return source unchanged.
- return source;
- }
- // Emit everything before the @layer, then the inner contents
- // (between the opening { and the matched closing }), then advance.
- out += source.slice(lastIdx, openStart);
- out += source.slice(openEnd, i - 1); // i-1 = position of the closing }
- lastIdx = i;
- re.lastIndex = i;
- }
- out += source.slice(lastIdx);
- return out;
-}
-
-// ---------------------------------------------------------------------------
-// Static HTML/CSS detection (default for local HTML files)
-// ---------------------------------------------------------------------------
-
-const STATIC_INHERITED_PROPS = new Set([
- 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight',
- 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'hyphens',
- 'webkitHyphens',
-]);
-
-const STATIC_DEFAULT_STYLE = {
- color: 'rgb(0, 0, 0)',
- backgroundColor: 'rgba(0, 0, 0, 0)',
- backgroundImage: 'none',
- borderTopWidth: '0px',
- borderRightWidth: '0px',
- borderBottomWidth: '0px',
- borderLeftWidth: '0px',
- borderTopColor: 'rgb(0, 0, 0)',
- borderRightColor: 'rgb(0, 0, 0)',
- borderBottomColor: 'rgb(0, 0, 0)',
- borderLeftColor: 'rgb(0, 0, 0)',
- borderRadius: '0px',
- boxShadow: 'none',
- fontFamily: '',
- fontSize: '16px',
- fontStyle: 'normal',
- fontWeight: '400',
- lineHeight: 'normal',
- letterSpacing: 'normal',
- textTransform: 'none',
- textAlign: 'start',
- hyphens: 'manual',
- webkitHyphens: 'manual',
- transitionProperty: '',
- transitionTimingFunction: '',
- animationName: '',
- animationTimingFunction: '',
- webkitBackgroundClip: '',
- backgroundClip: '',
- width: '',
- height: '',
- paddingTop: '0px',
- paddingRight: '0px',
- paddingBottom: '0px',
- paddingLeft: '0px',
- position: 'static',
- display: '',
-};
-
-const STATIC_PROP_MAP = {
- 'background-color': 'backgroundColor',
- 'background-image': 'backgroundImage',
- 'background-clip': 'backgroundClip',
- '-webkit-background-clip': 'webkitBackgroundClip',
- 'border-radius': 'borderRadius',
- 'border-top-width': 'borderTopWidth',
- 'border-right-width': 'borderRightWidth',
- 'border-bottom-width': 'borderBottomWidth',
- 'border-left-width': 'borderLeftWidth',
- 'border-top-color': 'borderTopColor',
- 'border-right-color': 'borderRightColor',
- 'border-bottom-color': 'borderBottomColor',
- 'border-left-color': 'borderLeftColor',
- 'box-shadow': 'boxShadow',
- 'font-family': 'fontFamily',
- 'font-size': 'fontSize',
- 'font-style': 'fontStyle',
- 'font-weight': 'fontWeight',
- 'line-height': 'lineHeight',
- 'letter-spacing': 'letterSpacing',
- 'text-transform': 'textTransform',
- 'text-align': 'textAlign',
- 'hyphens': 'hyphens',
- '-webkit-hyphens': 'webkitHyphens',
- 'transition-property': 'transitionProperty',
- 'transition-timing-function': 'transitionTimingFunction',
- 'animation-name': 'animationName',
- 'animation-timing-function': 'animationTimingFunction',
- 'width': 'width',
- 'height': 'height',
- 'padding-top': 'paddingTop',
- 'padding-right': 'paddingRight',
- 'padding-bottom': 'paddingBottom',
- 'padding-left': 'paddingLeft',
- 'position': 'position',
- 'display': 'display',
-};
-
-const STATIC_NAMED_COLORS = {
- black: { r: 0, g: 0, b: 0, a: 1 },
- white: { r: 255, g: 255, b: 255, a: 1 },
- transparent: { r: 0, g: 0, b: 0, a: 0 },
- gray: { r: 128, g: 128, b: 128, a: 1 },
- grey: { r: 128, g: 128, b: 128, a: 1 },
- silver: { r: 192, g: 192, b: 192, a: 1 },
- red: { r: 255, g: 0, b: 0, a: 1 },
- green: { r: 0, g: 128, b: 0, a: 1 },
- blue: { r: 0, g: 0, b: 255, a: 1 },
-};
-
-function splitCssList(value) {
- const parts = [];
- let depth = 0, quote = '', start = 0;
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; continue; }
- if (ch === '(' || ch === '[') depth++;
- else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);
- else if (ch === ',' && depth === 0) {
- parts.push(value.slice(start, i).trim());
- start = i + 1;
- }
- }
- const tail = value.slice(start).trim();
- if (tail) parts.push(tail);
- return parts;
-}
-
-function splitCssTokens(value) {
- const tokens = [];
- let depth = 0, quote = '', current = '';
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- current += ch;
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
- if (ch === '(') { depth++; current += ch; continue; }
- if (ch === ')') { depth = Math.max(0, depth - 1); current += ch; continue; }
- if (/\s/.test(ch) && depth === 0) {
- if (current) { tokens.push(current); current = ''; }
- continue;
- }
- current += ch;
- }
- if (current) tokens.push(current);
- return tokens;
-}
-
-function cssPropToCamel(prop) {
- if (!prop) return prop;
- const mapped = STATIC_PROP_MAP[prop];
- if (mapped) return mapped;
- return prop.replace(/-([a-z])/g, (_m, ch) => ch.toUpperCase());
-}
-
-function staticColorToCss(c) {
- if (!c) return '';
- if (c.a != null && c.a < 1) return `rgba(${c.r}, ${c.g}, ${c.b}, ${Number(c.a.toFixed(3))})`;
- return `rgb(${c.r}, ${c.g}, ${c.b})`;
-}
-
-function parseStaticColor(value) {
- const parsed = parseAnyColor(value);
- if (parsed) return parsed;
- const named = STATIC_NAMED_COLORS[String(value || '').trim().toLowerCase()];
- return named ? { ...named } : null;
-}
-
-function extractStaticColor(value) {
- if (!value) return '';
- const raw = String(value).trim();
- if (/^var\(/i.test(raw)) return raw;
- const colorLike = raw.match(/(?:rgba?\([^)]+\)|oklch\([^)]+\)|oklab\([^)]+\)|lch\([^)]+\)|lab\([^)]+\)|hsla?\([^)]+\)|hwb\([^)]+\)|#[0-9a-f]{3,8}\b|\b(?:black|white|gray|grey|silver|red|green|blue|transparent)\b)/i);
- if (!colorLike) return '';
- return colorLike[0];
-}
-
-function normalizeStaticCssValue(prop, value, customProps, parentStyle, currentStyle = null) {
- let resolved = resolveVarRefs(String(value || '').trim(), customProps);
- if (resolved === 'inherit') return parentStyle?.[prop] || STATIC_DEFAULT_STYLE[prop] || '';
- const isModernBorderColor = /^border[A-Z][a-z]+Color$/.test(prop) && /^(?:oklch|oklab|lch|lab|hsl|hwb)\(/i.test(resolved);
- if (!isModernBorderColor && (/color$/i.test(prop) || prop === 'color' || prop === 'backgroundColor')) {
- const parsed = parseStaticColor(resolved);
- if (parsed) resolved = staticColorToCss(parsed);
- }
- if (prop === 'fontSize') {
- const base = parseFloat(parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'letterSpacing') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'lineHeight' && resolved !== 'normal') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- return resolved;
-}
-
-function expandStaticBoxValues(tokens) {
- if (tokens.length === 0) return ['0px', '0px', '0px', '0px'];
- if (tokens.length === 1) return [tokens[0], tokens[0], tokens[0], tokens[0]];
- if (tokens.length === 2) return [tokens[0], tokens[1], tokens[0], tokens[1]];
- if (tokens.length === 3) return [tokens[0], tokens[1], tokens[2], tokens[1]];
- return [tokens[0], tokens[1], tokens[2], tokens[3]];
-}
-
-function parseStaticBorder(value) {
- const tokens = splitCssTokens(value);
- let width = '', color = '';
- for (const token of tokens) {
- if (!width && /^-?[\d.]+(?:px|rem|em|%)$/.test(token)) width = token;
- if (!color) color = extractStaticColor(token);
- }
- return { width, color };
-}
-
-function parseStaticFont(value) {
- const out = [];
- const slashParts = value.match(/(?:^|\s)([\d.]+(?:px|rem|em|%))(?:\/([^\s]+))?/);
- if (/\bitalic\b/i.test(value)) out.push(['fontStyle', 'italic']);
- const weight = value.match(/\b([1-9]00|bold|normal|lighter|bolder)\b/i);
- if (weight) out.push(['fontWeight', weight[1]]);
- if (slashParts) {
- out.push(['fontSize', slashParts[1]]);
- if (slashParts[2]) out.push(['lineHeight', slashParts[2]]);
- const familyStart = value.indexOf(slashParts[0]) + slashParts[0].length;
- const family = value.slice(familyStart).trim();
- if (family) out.push(['fontFamily', family]);
- }
- return out;
-}
-
-function parseStaticTransition(value) {
- const props = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const prop = tokens.find(token => /^[a-z-]+$/i.test(token) && !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none)$/.test(token) && !/s$/.test(token));
- if (prop) props.push(prop);
- }
- return {
- property: props.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function parseStaticAnimation(value) {
- const names = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const name = tokens.find(token =>
- /^[a-z_-][\w-]*$/i.test(token) &&
- !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none|running|paused)$/.test(token)
- );
- if (name) names.push(name);
- }
- return {
- name: names.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function expandStaticDeclaration(prop, value) {
- const p = prop.toLowerCase();
- const v = String(value || '').trim();
- if (!v) return [];
- if (p.startsWith('--')) return [[p, v]];
- if (p === 'background') {
- const out = [];
- const hasImage = /gradient|url\(/i.test(v);
- if (hasImage) out.push(['backgroundImage', v]);
- const beforeImage = hasImage ? v.split(/(?:repeating-)?(?:linear|radial|conic)-gradient\(|url\(/i)[0] : v;
- const color = extractStaticColor(hasImage ? beforeImage : v);
- if (color) out.push(['backgroundColor', color]);
- return out;
- }
- if (p === 'border') {
- const parsed = parseStaticBorder(v);
- const out = [];
- for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
- if (parsed.width) out.push([`border${side}Width`, parsed.width]);
- if (parsed.color) out.push([`border${side}Color`, parsed.color]);
- }
- return out;
- }
- const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
- if (sideMatch) {
- const parsed = parseStaticBorder(v);
- const side = sideMatch[1][0].toUpperCase() + sideMatch[1].slice(1);
- return [
- ...(parsed.width ? [[`border${side}Width`, parsed.width]] : []),
- ...(parsed.color ? [[`border${side}Color`, parsed.color]] : []),
- ];
- }
- if (p === 'border-width') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopWidth', vals[0]],
- ['borderRightWidth', vals[1]],
- ['borderBottomWidth', vals[2]],
- ['borderLeftWidth', vals[3]],
- ];
- }
- if (p === 'border-color') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopColor', vals[0]],
- ['borderRightColor', vals[1]],
- ['borderBottomColor', vals[2]],
- ['borderLeftColor', vals[3]],
- ];
- }
- if (p === 'padding') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['paddingTop', vals[0]],
- ['paddingRight', vals[1]],
- ['paddingBottom', vals[2]],
- ['paddingLeft', vals[3]],
- ];
- }
- if (p === 'font') return parseStaticFont(v);
- if (p === 'transition') {
- const parsed = parseStaticTransition(v);
- return [
- ...(parsed.property ? [['transitionProperty', parsed.property]] : []),
- ...(parsed.timing ? [['transitionTimingFunction', parsed.timing]] : []),
- ];
- }
- if (p === 'animation') {
- const parsed = parseStaticAnimation(v);
- return [
- ...(parsed.name ? [['animationName', parsed.name]] : []),
- ...(parsed.timing ? [['animationTimingFunction', parsed.timing]] : []),
- ];
- }
- const mapped = cssPropToCamel(p);
- if (STATIC_DEFAULT_STYLE[mapped] != null || STATIC_INHERITED_PROPS.has(mapped)) {
- return [[mapped, v]];
- }
- return [];
-}
-
-function compareStaticPriority(a, b) {
- if (!a) return true;
- if (!!b.important !== !!a.important) return !!b.important;
- if (!!b.inline !== !!a.inline) return !!b.inline;
- for (let i = 0; i < 3; i++) {
- if ((b.specificity[i] || 0) !== (a.specificity[i] || 0)) {
- return (b.specificity[i] || 0) > (a.specificity[i] || 0);
- }
- }
- return b.order >= a.order;
-}
-
-function staticSpecificity(selector) {
- const noWhere = selector.replace(/:where\([^)]*\)/g, '');
- const ids = (noWhere.match(/#[\w-]+/g) || []).length;
- const classes = (noWhere.match(/\.[\w-]+|\[[^\]]+\]|:(?!:)[\w-]+(?:\([^)]*\))?/g) || []).length;
- const stripped = noWhere
- .replace(/#[\w-]+/g, ' ')
- .replace(/\.[\w-]+|\[[^\]]+\]|:{1,2}[\w-]+(?:\([^)]*\))?/g, ' ')
- .replace(/[*>+~(),]/g, ' ');
- const types = (stripped.match(/\b[a-zA-Z][\w-]*\b/g) || []).length;
- return [ids, classes, types];
-}
-
-function applyStaticDeclaration(specified, node, prop, value, meta) {
- let map = specified.get(node);
- if (!map) { map = new Map(); specified.set(node, map); }
- for (const [expandedProp, expandedValue] of expandStaticDeclaration(prop, value)) {
- const existing = map.get(expandedProp);
- const next = { ...meta, prop: expandedProp, value: expandedValue };
- if (compareStaticPriority(existing, next)) map.set(expandedProp, next);
- }
-}
-
-function parseStaticStyleAttribute(styleText, orderBase = 0) {
- const decls = [];
- for (const part of String(styleText || '').split(';')) {
- const idx = part.indexOf(':');
- if (idx <= 0) continue;
- const prop = part.slice(0, idx).trim();
- let value = part.slice(idx + 1).trim();
- const important = /!important\s*$/i.test(value);
- value = value.replace(/\s*!important\s*$/i, '').trim();
- decls.push({ prop, value, important, order: orderBase + decls.length });
- }
- return decls;
-}
-
-function collectStaticCssRules(cssText, csstree) {
- const rules = [];
- let ast;
- try {
- ast = csstree.parse(cssText, { positions: false, parseValue: true, parseCustomProperty: false });
- } catch {
- return rules;
- }
- let order = 0;
- const walkList = (list, atRuleStack = []) => {
- list?.forEach?.(node => {
- if (node.type === 'Rule' && node.block) {
- if (atRuleStack.some(name => /keyframes$/i.test(name))) return;
- const selectorText = csstree.generate(node.prelude).trim();
- const declarations = [];
- node.block.children?.forEach?.(child => {
- if (child.type !== 'Declaration') return;
- declarations.push({
- prop: child.property,
- value: csstree.generate(child.value).trim(),
- important: !!child.important,
- });
- });
- for (const selector of splitCssList(selectorText)) {
- if (selector) rules.push({ selector, declarations, specificity: staticSpecificity(selector), order: order++ });
- }
- return;
- }
- if (node.type === 'Atrule' && node.block) {
- const name = String(node.name || '').toLowerCase();
- if (name === 'media' || name === 'supports' || name === 'layer') {
- walkList(node.block.children, [...atRuleStack, name]);
- }
- }
- });
- };
- walkList(ast.children);
- return rules;
-}
-
-class StaticElement {
- constructor(node, doc) {
- this.node = node;
- this._doc = doc;
- this.nodeType = 1;
- this.tagName = String(node.name || '').toUpperCase();
- this.nodeName = this.tagName;
- }
- get parentElement() {
- let cur = this.node.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- return cur ? this._doc.wrap(cur) : null;
- }
- get previousElementSibling() {
- let cur = this.node.prev;
- while (cur && cur.type !== 'tag') cur = cur.prev;
- return cur ? this._doc.wrap(cur) : null;
- }
- get children() {
- return (this.node.children || []).filter(child => child.type === 'tag').map(child => this._doc.wrap(child));
- }
- get childNodes() {
- return (this.node.children || []).map(child => {
- if (child.type === 'text') return { nodeType: 3, textContent: child.data || '' };
- if (child.type === 'tag') return this._doc.wrap(child);
- return { nodeType: 8, textContent: child.data || '' };
- });
- }
- get textContent() {
- return this._doc.domutils.textContent(this.node);
- }
- get className() {
- return this.getAttribute('class') || '';
- }
- get id() {
- return this.getAttribute('id') || '';
- }
- getAttribute(name) {
- return this.node.attribs?.[name] ?? null;
- }
- querySelector(selector) {
- try {
- const found = this._doc.selectOne(selector, this.node.children || []);
- return found ? this._doc.wrap(found) : null;
- } catch {
- return null;
- }
- }
- querySelectorAll(selector) {
- try {
- return this._doc.selectAll(selector, this.node.children || []).map(node => this._doc.wrap(node));
- } catch {
- return [];
- }
- }
- closest(selector) {
- let cur = this.node;
- while (cur && cur.type === 'tag') {
- try {
- if (this._doc.is(cur, selector)) return this._doc.wrap(cur);
- } catch {
- return null;
- }
- cur = cur.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- }
- return null;
- }
- contains(other) {
- let cur = other?.node || null;
- while (cur) {
- if (cur === this.node) return true;
- cur = cur.parent;
- }
- return false;
- }
-}
-
-class StaticDocument {
- constructor(root, modules) {
- this.root = root;
- this.selectAll = modules.selectAll;
- this.selectOne = modules.selectOne;
- this.is = modules.is;
- this.domutils = modules.domutils;
- this._wrappers = new WeakMap();
- this._styleMap = new WeakMap();
- }
- wrap(node) {
- let wrapped = this._wrappers.get(node);
- if (!wrapped) {
- wrapped = new StaticElement(node, this);
- this._wrappers.set(node, wrapped);
- }
- return wrapped;
- }
- querySelectorAll(selector) {
- try {
- return this.selectAll(selector, this.root.children || []).map(node => this.wrap(node));
- } catch {
- return [];
- }
- }
- querySelector(selector) {
- try {
- const found = this.selectOne(selector, this.root.children || []);
- return found ? this.wrap(found) : null;
- } catch {
- return null;
- }
- }
- get documentElement() {
- return this.querySelector('html');
- }
- get body() {
- return this.querySelector('body');
- }
- setStyle(node, style) {
- this._styleMap.set(node, style);
- }
- getStyle(el) {
- return this._styleMap.get(el.node) || makeStaticStyle();
- }
-}
-
-function makeStaticStyle(values = {}) {
- const style = { ...STATIC_DEFAULT_STYLE, ...values };
- style.getPropertyValue = (prop) => {
- const key = cssPropToCamel(prop);
- return style[key] || style[prop] || '';
- };
- return style;
-}
-
-function buildStaticWindow(staticDoc) {
- return {
- document: staticDoc,
- getComputedStyle: (el) => staticDoc.getStyle(el),
- };
-}
-
-function collectStaticCssText(root, fileDir, profile, filePath, modules) {
- const styleTexts = [];
- for (const styleEl of modules.selectAll('style', root.children || [])) {
- styleTexts.push(modules.domutils.textContent(styleEl));
- }
- const links = modules.selectAll('link', root.children || []);
- for (const link of links) {
- const rel = link.attribs?.rel || '';
- const href = link.attribs?.href || '';
- if (!/\bstylesheet\b/i.test(rel) || !href || /^(https?:)?\/\//i.test(href)) continue;
- const cssPath = path.resolve(fileDir, href);
- try {
- const css = profileStep(profile, {
- engine: 'static-html',
- phase: 'preprocess',
- ruleId: 'inline-linked-stylesheet',
- target: filePath,
- detail: href,
- }, () => fs.readFileSync(cssPath, 'utf-8'));
- styleTexts.push(css);
- } catch { /* skip unreadable */ }
- }
- return styleTexts.join('\n');
-}
-
-function buildStaticStyleMap(root, staticDoc, cssText, modules, profile, filePath) {
- const specified = new Map();
- const allNodes = modules.selectAll('*', root.children || []);
- const rules = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-css',
- ruleId: 'css-rules',
- target: filePath,
- }, () => collectStaticCssRules(cssText, modules.csstree));
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'css-selectors',
- target: filePath,
- }, () => {
- for (const rule of rules) {
- let matched;
- try {
- matched = modules.selectAll(rule.selector, root.children || []);
- } catch {
- recordProfileEvent(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'unsupported-selector',
- target: filePath,
- ms: 0,
- findings: 0,
- detail: rule.selector,
- });
- continue;
- }
- for (const node of matched) {
- for (const decl of rule.declarations) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: rule.specificity,
- order: rule.order,
- inline: false,
- });
- }
- }
- }
-
- let inlineOrder = rules.length + 1;
- for (const node of allNodes) {
- const styleText = node.attribs?.style;
- if (!styleText) continue;
- for (const decl of parseStaticStyleAttribute(styleText, inlineOrder)) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: [1, 0, 0],
- order: decl.order,
- inline: true,
- });
- }
- inlineOrder += 1000;
- }
- });
-
- const computeNode = (node, parentStyle = null, parentCustom = new Map()) => {
- const specifiedMap = specified.get(node) || new Map();
- const customProps = new Map(parentCustom);
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) customProps.set(prop, resolveVarRefs(decl.value, customProps));
- }
- const values = {};
- for (const prop of Object.keys(STATIC_DEFAULT_STYLE)) {
- if (STATIC_INHERITED_PROPS.has(prop) && parentStyle?.[prop] != null) values[prop] = parentStyle[prop];
- else values[prop] = STATIC_DEFAULT_STYLE[prop];
- }
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) continue;
- values[prop] = normalizeStaticCssValue(prop, decl.value, customProps, parentStyle, values);
- }
- const style = makeStaticStyle(values);
- staticDoc.setStyle(node, style);
- for (const child of node.children || []) {
- if (child.type === 'tag') computeNode(child, style, customProps);
- }
- };
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'cascade',
- ruleId: 'compute-styles',
- target: filePath,
- }, () => {
- for (const child of root.children || []) {
- if (child.type === 'tag') computeNode(child);
- }
- });
-}
-
-export {
- BORDER_SHORTHAND_RE,
- NAMED_COLORS,
- normalizeColorForCheck,
- buildBorderOverrideMap,
- unwrapCssAtLayer,
- STATIC_INHERITED_PROPS,
- STATIC_DEFAULT_STYLE,
- STATIC_PROP_MAP,
- STATIC_NAMED_COLORS,
- splitCssList,
- splitCssTokens,
- cssPropToCamel,
- staticColorToCss,
- parseStaticColor,
- extractStaticColor,
- normalizeStaticCssValue,
- expandStaticBoxValues,
- parseStaticBorder,
- parseStaticFont,
- parseStaticTransition,
- parseStaticAnimation,
- expandStaticDeclaration,
- compareStaticPriority,
- staticSpecificity,
- applyStaticDeclaration,
- parseStaticStyleAttribute,
- collectStaticCssRules,
- StaticElement,
- StaticDocument,
- makeStaticStyle,
- buildStaticWindow,
- collectStaticCssText,
- buildStaticStyleMap,
-};
@@ -1,174 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import {
- checkElementBorders,
- checkElementColors,
- checkElementGlow,
- checkElementHeroEyebrow,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementMotion,
- checkElementQuality,
- checkHtmlPatterns,
- checkPageLayout,
- checkPageQualityFromDoc,
- checkRepeatedSectionKickersFromDoc,
- resolveBackground,
- resolveBorderRadiusPx,
-} from '../../rules/checks.mjs';
-import { detectText } from '../regex/detect-text.mjs';
-import {
- StaticDocument,
- buildStaticStyleMap,
- buildStaticWindow,
- collectStaticCssText,
-} from './css-cascade.mjs';
-
-function checkStaticPageTypography(document, window) {
- const findings = [];
- const fonts = new Set();
- const overusedFound = new Set();
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span, div')) {
- const hasText = el.childNodes.some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const ff = window.getComputedStyle(el).fontFamily || '';
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
- if (fonts.size === 1 && document.querySelectorAll('*').length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div')) {
- const fontSize = parseFloat(window.getComputedStyle(el).fontSize);
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
- return findings;
-}
-
-const STATIC_ELEMENT_RULES = [
- { id: 'border-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementBorders(tag, style, null, resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window)) },
- { id: 'color-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementColors(el, style, tag, window, customPropMap, false) },
- { id: 'dark-glow', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window, customPropMap)) },
- { id: 'motion-rules', selector: '*', run: (el, tag, style) => checkElementMotion(tag, style) },
- { id: 'icon-tile-stack', selector: 'h1,h2,h3,h4,h5,h6', run: (el, tag, _style, window) => checkElementIconTile(el, tag, window) },
- { id: 'italic-serif-display', selector: 'h1,h2', run: (el, tag, style) => checkElementItalicSerif(el, style, tag) },
- { id: 'hero-eyebrow-chip', selector: 'h1', run: (el, tag, style, window, customPropMap) => checkElementHeroEyebrow(el, style, tag, window, customPropMap) },
- { id: 'quality-rules', selector: '*', run: (el, tag, style, window) => checkElementQuality(el, style, tag, window) },
-];
-
-async function detectHtml(filePath, options = {}) {
- const profile = options?.profile;
- const html = profileStep(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'read-html',
- target: filePath,
- }, () => fs.readFileSync(filePath, 'utf-8'));
-
- let modules;
- try {
- modules = await profileStepAsync(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'import-static-parser',
- target: filePath,
- }, async () => {
- const [htmlparser2, cssSelect, csstree, domutils] = await Promise.all([
- import('htmlparser2'),
- import('css-select'),
- import('css-tree'),
- import('domutils'),
- ]);
- return {
- parseDocument: htmlparser2.parseDocument,
- selectAll: cssSelect.selectAll,
- selectOne: cssSelect.selectOne,
- is: cssSelect.is,
- csstree,
- domutils,
- };
- });
- } catch {
- return detectText(html, filePath, options);
- }
-
- const resolvedPath = path.resolve(filePath);
- const fileDir = path.dirname(resolvedPath);
- const root = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-html',
- ruleId: 'parse-document',
- target: filePath,
- }, () => modules.parseDocument(html, { lowerCaseAttributeNames: false, lowerCaseTags: true }));
-
- const cssText = collectStaticCssText(root, fileDir, profile, filePath, modules);
- const document = new StaticDocument(root, modules);
- buildStaticStyleMap(root, document, cssText, modules, profile, filePath);
- const window = buildStaticWindow(document);
-
- const customPropMap = null;
-
- const findings = [];
- const runElementCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'element', ruleId, target: filePath }, callback)
- : callback();
-
- const visitedByRule = new Map();
- for (const rule of STATIC_ELEMENT_RULES) {
- const elements = document.querySelectorAll(rule.selector);
- visitedByRule.set(rule.id, elements.length);
- for (const el of elements) {
- const tag = el.tagName.toLowerCase();
- const style = window.getComputedStyle(el);
- for (const f of runElementCheck(rule.id, () => rule.run(el, tag, style, window, customPropMap))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
- }
-
- if (isFullPage(html)) {
- const runPageCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
- : callback();
- for (const f of runPageCheck('typography-rules', () => checkStaticPageTypography(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('repeated-section-kickers', () => checkRepeatedSectionKickersFromDoc(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('layout-rules', () => checkPageLayout(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('skipped-heading', () => checkPageQualityFromDoc(document))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('html-patterns', () => checkHtmlPatterns(html).filter(item =>
- item.id !== 'bounce-easing' && item.id !== 'layout-transition'
- ))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
-
- return findings;
-}
-
-export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -1,189 +0,0 @@
-function sanitizeScreenshotClip(clip, viewport) {
- if (!clip) return null;
- const x = Math.max(0, Math.floor(clip.x || 0));
- const y = Math.max(0, Math.floor(clip.y || 0));
- const width = Math.min(
- Math.max(1, Math.ceil(clip.width || 0)),
- Math.max(1, viewport?.width || 1600),
- );
- const height = Math.min(
- Math.max(1, Math.ceil(clip.height || 0)),
- 320,
- );
- if (width < 1 || height < 1) return null;
- return { x, y, width, height };
-}
-
-async function compareScreenshotContrast(page, beforeBase64, afterBase64, candidate) {
- return page.evaluate(async ({ beforeBase64, afterBase64, candidate }) => {
- const loadImage = (base64) => new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = () => reject(new Error('Could not decode contrast screenshot'));
- img.src = `data:image/png;base64,${base64}`;
- });
- const [before, after] = await Promise.all([loadImage(beforeBase64), loadImage(afterBase64)]);
- const width = Math.min(before.width, after.width);
- const height = Math.min(before.height, after.height);
- if (width < 1 || height < 1) return null;
-
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return null;
-
- ctx.drawImage(before, 0, 0, width, height);
- const beforePixels = ctx.getImageData(0, 0, width, height).data;
- ctx.clearRect(0, 0, width, height);
- ctx.drawImage(after, 0, 0, width, height);
- const afterPixels = ctx.getImageData(0, 0, width, height).data;
-
- const luminance = ({ r, g, b }) => {
- const convert = c => {
- const v = c / 255;
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
- };
- return 0.2126 * convert(r) + 0.7152 * convert(g) + 0.0722 * convert(b);
- };
- const ratio = (a, b) => {
- const l1 = luminance(a);
- const l2 = luminance(b);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
- };
-
- const cssTextColor = candidate.textColor && !candidate.preferRenderedForeground
- ? {
- r: candidate.textColor.r,
- g: candidate.textColor.g,
- b: candidate.textColor.b,
- }
- : null;
- const ratios = [];
- let glyphPixels = 0;
- let strongestDelta = 0;
- for (let i = 0; i < beforePixels.length; i += 4) {
- const delta = Math.abs(beforePixels[i] - afterPixels[i])
- + Math.abs(beforePixels[i + 1] - afterPixels[i + 1])
- + Math.abs(beforePixels[i + 2] - afterPixels[i + 2])
- + Math.abs(beforePixels[i + 3] - afterPixels[i + 3]);
- strongestDelta = Math.max(strongestDelta, delta);
- if (delta < 10) continue;
- glyphPixels++;
- const fg = cssTextColor || {
- r: beforePixels[i],
- g: beforePixels[i + 1],
- b: beforePixels[i + 2],
- };
- const bg = {
- r: afterPixels[i],
- g: afterPixels[i + 1],
- b: afterPixels[i + 2],
- };
- ratios.push(ratio(fg, bg));
- }
-
- if (ratios.length < 8) {
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: null,
- p10Ratio: null,
- medianRatio: null,
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: ratios[0],
- p10Ratio: pick(10),
- medianRatio: pick(50),
- };
- }, { beforeBase64, afterBase64, candidate });
-}
-
-async function captureVisualContrastCandidate(page, candidate, viewport) {
- const clip = sanitizeScreenshotClip(candidate.clip, viewport);
- if (!clip) return null;
-
- const beforeBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- const token = `impeccable-contrast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- const applied = await page.evaluate(({ selector, token, backgroundClipText }) => {
- let el;
- try {
- el = document.querySelector(selector);
- } catch {
- return false;
- }
- if (!el) return false;
- let style = document.getElementById('impeccable-visual-contrast-hide-style');
- if (!style) {
- style = document.createElement('style');
- style.id = 'impeccable-visual-contrast-hide-style';
- style.textContent = [
- '[data-impeccable-visual-contrast-target] {',
- ' color: transparent !important;',
- ' -webkit-text-fill-color: transparent !important;',
- ' text-shadow: none !important;',
- '}',
- '[data-impeccable-visual-contrast-target][data-impeccable-bgclip-text="true"] {',
- ' background-image: none !important;',
- '}',
- ].join('\n');
- document.head.appendChild(style);
- }
- el.setAttribute('data-impeccable-visual-contrast-target', token);
- if (backgroundClipText) el.setAttribute('data-impeccable-bgclip-text', 'true');
- return true;
- }, {
- selector: candidate.selector,
- token,
- backgroundClipText: candidate.backgroundClipText,
- });
- if (!applied) return null;
-
- let afterBase64;
- try {
- afterBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- } finally {
- await page.evaluate(({ selector }) => {
- try {
- const el = document.querySelector(selector);
- if (el) {
- el.removeAttribute('data-impeccable-visual-contrast-target');
- el.removeAttribute('data-impeccable-bgclip-text');
- }
- } catch {
- // Ignore invalid or stale selectors during cleanup.
- }
- }, { selector: candidate.selector }).catch(() => {});
- }
-
- const metrics = await compareScreenshotContrast(page, beforeBase64, afterBase64, candidate);
- if (!metrics || !Number.isFinite(metrics.p10Ratio) || metrics.glyphPixels < 8) return null;
- const measuredRatio = metrics.p10Ratio;
- if (measuredRatio >= candidate.threshold) return null;
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const reasonLabel = (candidate.reasons || []).slice(0, 3).join(', ') || 'visual background';
- return {
- id: 'low-contrast',
- snippet: `pixel contrast ${measuredRatio.toFixed(1)}:1 median ${metrics.medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) on ${reasonLabel}${textLabel}`,
- };
-}
-
-export {
- sanitizeScreenshotClip,
- compareScreenshotContrast,
- captureVisualContrastCandidate,
-};
@@ -1,12 +0,0 @@
-import { getAntipattern } from './registry/antipatterns.mjs';
-
-function getAP(id) {
- return getAntipattern(id);
-}
-
-function finding(id, filePath, snippet, line = 0) {
- const ap = getAP(id);
- return { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', file: filePath, line, snippet };
-}
-
-export { getAP, finding };
@@ -1,198 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-// ---------------------------------------------------------------------------
-// File walker
-// ---------------------------------------------------------------------------
-
-const SKIP_DIRS = new Set([
- 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
- '.svelte-kit', '__pycache__', '.turbo', '.vercel',
-]);
-
-const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
- '.jsx', '.tsx', '.js', '.ts',
- '.vue', '.svelte', '.astro',
-]);
-
-const HTML_EXTENSIONS = new Set(['.html', '.htm']);
-
-function walkDir(dir) {
- const files = [];
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
- for (const entry of entries) {
- if (SKIP_DIRS.has(entry.name)) continue;
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) files.push(...walkDir(full));
- else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
- }
- return files;
-}
-
-
-// ---------------------------------------------------------------------------
-// Import graph (multi-file awareness)
-// ---------------------------------------------------------------------------
-
-function resolveImport(specifier, fromDir, fileSet) {
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
- const base = path.resolve(fromDir, specifier);
- if (fileSet.has(base)) return base;
- for (const ext of SCANNABLE_EXTENSIONS) {
- const withExt = base + ext;
- if (fileSet.has(withExt)) return withExt;
- }
- // index file convention
- for (const ext of SCANNABLE_EXTENSIONS) {
- const indexFile = path.join(base, 'index' + ext);
- if (fileSet.has(indexFile)) return indexFile;
- }
- return null;
-}
-
-function buildImportGraph(files) {
- const fileSet = new Set(files);
- const graph = new Map();
-
- for (const file of files) {
- const content = fs.readFileSync(file, 'utf-8');
- const dir = path.dirname(file);
- const imports = new Set();
-
- // ES imports: import ... from '...' and import '...'
- const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
- let m;
- while ((m = esRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // CSS @import
- const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
- while ((m = cssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // SCSS @use / @forward
- const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
- while ((m = scssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- graph.set(file, imports);
- }
- return graph;
-}
-
-// ---------------------------------------------------------------------------
-// Framework dev server detection
-// ---------------------------------------------------------------------------
-
-const FRAMEWORK_CONFIGS = [
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /next/i } },
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-sveltekit-page', value: null } },
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /@vite\/client/ } },
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /astro/i } },
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
- portRe: /"port"\s*:\s*(\d+)/,
- fingerprint: { body: /ng-version/i } },
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
-];
-
-function detectFrameworkConfig(dir) {
- let entries;
- try { entries = fs.readdirSync(dir); } catch { return null; }
- const entrySet = new Set(entries);
-
- for (const cfg of FRAMEWORK_CONFIGS) {
- const match = cfg.files.find(f => entrySet.has(f));
- if (!match) continue;
-
- const configPath = path.join(dir, match);
- let port = cfg.defaultPort;
- try {
- const content = fs.readFileSync(configPath, 'utf-8');
- const portMatch = content.match(cfg.portRe);
- if (portMatch) port = parseInt(portMatch[1], 10);
- } catch { /* use default */ }
-
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
- }
- return null;
-}
-
-/**
- * Check if a port is listening and optionally verify it matches the expected framework.
- * Returns { listening: true, matched: true/false } or { listening: false }.
- */
-async function isPortListening(port, fingerprint = null) {
- if (!fingerprint) {
- // Simple TCP probe fallback
- const net = await import('node:net');
- return new Promise((resolve) => {
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
- sock.setTimeout(500);
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
- sock.on('error', () => resolve({ listening: false }));
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
- });
- }
-
- // HTTP probe with fingerprint matching
- try {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 2000);
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
- clearTimeout(timeout);
-
- // Check header fingerprint
- if (fingerprint.header) {
- const val = res.headers.get(fingerprint.header);
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
- return { listening: true, matched: true };
- }
- }
-
- // Check body fingerprint
- if (fingerprint.body) {
- const body = await res.text();
- if (fingerprint.body.test(body)) {
- return { listening: true, matched: true };
- }
- }
-
- // Port is listening but doesn't match the expected framework
- return { listening: true, matched: false };
- } catch {
- return { listening: false };
- }
-}
-
-export {
- SKIP_DIRS,
- SCANNABLE_EXTENSIONS,
- HTML_EXTENSIONS,
- walkDir,
- resolveImport,
- buildImportGraph,
- FRAMEWORK_CONFIGS,
- detectFrameworkConfig,
- isPortListening,
-};
@@ -1,166 +0,0 @@
-function profileNow() {
- return typeof performance !== 'undefined' && performance.now
- ? performance.now()
- : Date.now();
-}
-
-function createDetectorProfile() {
- return { events: [] };
-}
-
-function recordProfileEvent(profile, event) {
- if (!profile) return;
- const normalized = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- ms: Number.isFinite(event.ms) ? event.ms : 0,
- findings: Number.isFinite(event.findings) ? event.findings : 0,
- };
- if (event.detail) normalized.detail = event.detail;
- if (Array.isArray(event.findingIds) && event.findingIds.length) {
- normalized.findingIds = event.findingIds;
- }
- if (typeof profile === 'function') {
- profile(normalized);
- } else if (typeof profile.record === 'function') {
- profile.record(normalized);
- } else if (Array.isArray(profile.events)) {
- profile.events.push(normalized);
- } else if (Array.isArray(profile)) {
- profile.push(normalized);
- }
-}
-
-function extractFindingIds(findings) {
- if (!Array.isArray(findings) || findings.length === 0) return [];
- return [...new Set(findings.map(f => f?.id || f?.type || f?.antipattern).filter(Boolean))];
-}
-
-function profileFindings(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-function profileStep(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-async function profileFindingsAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = await callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-async function profileStepAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return await callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-function percentile(sortedValues, pct) {
- if (!sortedValues.length) return 0;
- const idx = Math.min(
- sortedValues.length - 1,
- Math.max(0, Math.ceil((pct / 100) * sortedValues.length) - 1),
- );
- return sortedValues[idx];
-}
-
-function summarizeDetectorProfile(profile) {
- const events = Array.isArray(profile)
- ? profile
- : (Array.isArray(profile?.events) ? profile.events : []);
- const groups = new Map();
- for (const event of events) {
- const key = [
- event.engine || 'unknown',
- event.phase || 'unknown',
- event.ruleId || 'unknown',
- event.target || '',
- ].join('\u0000');
- let group = groups.get(key);
- if (!group) {
- group = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- calls: 0,
- totalMs: 0,
- findings: 0,
- samples: [],
- };
- groups.set(key, group);
- }
- const ms = Number.isFinite(event.ms) ? event.ms : 0;
- group.calls += 1;
- group.totalMs += ms;
- group.findings += Number.isFinite(event.findings) ? event.findings : 0;
- group.samples.push(ms);
- }
- return [...groups.values()]
- .map(group => {
- const samples = group.samples.sort((a, b) => a - b);
- return {
- engine: group.engine,
- phase: group.phase,
- ruleId: group.ruleId,
- target: group.target,
- calls: group.calls,
- totalMs: Number(group.totalMs.toFixed(3)),
- avgMs: Number((group.totalMs / group.calls).toFixed(3)),
- p50: Number(percentile(samples, 50).toFixed(3)),
- p95: Number(percentile(samples, 95).toFixed(3)),
- findings: group.findings,
- };
- })
- .sort((a, b) => b.totalMs - a.totalMs);
-}
-
-export {
- profileNow,
- createDetectorProfile,
- recordProfileEvent,
- extractFindingIds,
- profileFindings,
- profileStep,
- profileFindingsAsync,
- profileStepAsync,
- percentile,
- summarizeDetectorProfile,
-};
@@ -1,278 +0,0 @@
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-const RULE_ENGINE_SUPPORT = {
- regex: new Set(['source', 'page-analyzer']),
- 'static-html': new Set(['element', 'page']),
- browser: new Set(['element', 'page', 'layout']),
- visual: new Set(['visual-contrast']),
-};
-
-function getAntipattern(id) {
- return ANTIPATTERNS.find(rule => rule.id === id);
-}
-
-function getRulesForCategory(category) {
- return ANTIPATTERNS.filter(rule => rule.category === category);
-}
-
-function getRuleEngineSupport(engine) {
- return RULE_ENGINE_SUPPORT[engine] || new Set();
-}
-
-export {
- ANTIPATTERNS,
- RULE_ENGINE_SUPPORT,
- getAntipattern,
- getRulesForCategory,
- getRuleEngineSupport,
-};
@@ -1,1948 +0,0 @@
-import {
- BORDER_SAFE_TAGS,
- GENERIC_FONTS,
- KNOWN_SERIF_FONTS,
- OVERUSED_FONTS,
- SAFE_TAGS,
- WCAG_LARGE_BOLD_TEXT_PX,
- WCAG_LARGE_TEXT_PX,
- isBrandFontOnOwnDomain,
-} from '../shared/constants.mjs';
-import {
- colorToHex,
- contrastRatio,
- getHue,
- hasChroma,
- isNeutralColor,
- parseGradientColors,
- parseRgb,
- relativeLuminance,
-} from '../shared/color.mjs';
-
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-export {
- checkBorders,
- isEmojiOnlyText,
- checkColors,
- isCardLikeFromProps,
- checkIconTile,
- resolveSerif,
- checkItalicSerif,
- isAccentColor,
- checkHeroEyebrow,
- checkRepeatedSectionKickers,
- checkMotion,
- checkGlow,
- checkHtmlPatterns,
- readOwnBackgroundColor,
- resolveBackground,
- resolveGradientStops,
- parseRadiusToPx,
- resolveBorderRadiusPx,
- checkElementBordersDOM,
- checkElementColorsDOM,
- checkElementIconTileDOM,
- checkElementItalicSerifDOM,
- checkElementHeroEyebrowDOM,
- buildCustomPropMap,
- resolveVarRefs,
- oklchToRgb,
- parseAnyColor,
- parseColorResolved,
- cleanInlineText,
- isRepeatedKickerCandidate,
- collectRepeatedSectionKickerCandidates,
- checkRepeatedSectionKickersDOM,
- checkElementMotionDOM,
- checkElementGlowDOM,
- checkElementAIPaletteDOM,
- resolveFontSizePx,
- resolveLengthPx,
- checkQuality,
- checkElementQualityDOM,
- checkPageQualityFromDoc,
- checkPageQualityDOM,
- checkElementQuality,
- checkElementBorders,
- checkElementColors,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementHeroEyebrow,
- checkRepeatedSectionKickersFromDoc,
- checkElementMotion,
- checkElementGlow,
- checkTypography,
- isCardLikeDOM,
- checkLayout,
- checkPageTypography,
- isCardLike,
- checkPageLayout,
-};
@@ -1,124 +0,0 @@
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-export {
- isNeutralColor,
- parseRgb,
- relativeLuminance,
- contrastRatio,
- parseGradientColors,
- hasChroma,
- getHue,
- colorToHex,
-};
@@ -1,101 +0,0 @@
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-export {
- SAFE_TAGS,
- BORDER_SAFE_TAGS,
- OVERUSED_FONTS,
- GOOGLE_DOMAINS,
- VERCEL_DOMAINS,
- GITHUB_DOMAINS,
- BRAND_FONT_DOMAINS,
- isBrandFontOnOwnDomain,
- GENERIC_FONTS,
- WCAG_LARGE_TEXT_PX,
- WCAG_LARGE_BOLD_TEXT_PX,
- KNOWN_SERIF_FONTS,
-};
@@ -1,7 +0,0 @@
-/** Check if content looks like a full page (not a component/partial) */
-function isFullPage(content) {
- const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
- return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
-}
-
-export { isFullPage };
@@ -1,110 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-export const IMPECCABLE_DIR = '.impeccable';
-export const LIVE_DIR = 'live';
-export const CRITIQUE_DIR = 'critique';
-
-export function getImpeccableDir(cwd = process.cwd()) {
- return path.join(cwd, IMPECCABLE_DIR);
-}
-
-export function getDesignSidecarPath(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), 'design.json');
-}
-
-export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {
- const candidates = [
- getDesignSidecarPath(cwd),
- path.join(cwd, 'DESIGN.json'),
- ];
- const contextLegacy = path.join(contextDir, 'DESIGN.json');
- if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
- return candidates;
-}
-
-export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
- return firstExisting(getDesignSidecarCandidates(cwd, contextDir));
-}
-
-export function getLiveDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), LIVE_DIR);
-}
-
-export function getLiveConfigPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'config.json');
-}
-
-export function getLegacyLiveConfigPath(scriptsDir) {
- return path.join(scriptsDir, 'config.json');
-}
-
-export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {
- if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
- const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
- return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
- }
- const primary = getLiveConfigPath(cwd);
- if (fs.existsSync(primary)) return primary;
- if (scriptsDir) {
- const legacy = getLegacyLiveConfigPath(scriptsDir);
- if (fs.existsSync(legacy)) return legacy;
- }
- return primary;
-}
-
-export function getLiveServerPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'server.json');
-}
-
-export function getLegacyLiveServerPath(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live.json');
-}
-
-export function readLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try {
- return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };
- } catch {
- /* try next */
- }
- }
- return null;
-}
-
-export function writeLiveServerInfo(cwd = process.cwd(), info) {
- const filePath = getLiveServerPath(cwd);
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- fs.writeFileSync(filePath, JSON.stringify(info));
- return filePath;
-}
-
-export function removeLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try { fs.unlinkSync(filePath); } catch {}
- }
-}
-
-export function getLiveSessionsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'sessions');
-}
-
-export function getLegacyLiveSessionsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'sessions');
-}
-
-export function getLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'annotations');
-}
-
-export function getCritiqueDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), CRITIQUE_DIR);
-}
-
-export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'annotations');
-}
-
-function firstExisting(paths) {
- return paths.find((filePath) => fs.existsSync(filePath)) || null;
-}
@@ -1,69 +0,0 @@
-/**
- * Decide whether a given file is "generated" (regenerated by a build step,
- * unsafe to write variants into) or "source" (safe to edit, changes persist).
- *
- * Why this matters: when the user picks an element on a page whose underlying
- * file is regenerated by a build step (e.g. `scripts/build-sub-pages.js`
- * rewriting `public/docs/*.html`), writing variants or accepted changes into
- * that file is silent data loss — the next build wipes them.
- *
- * Signals, in order of reliability:
- * 1. Git check-ignore: gitignored files are assumed generated.
- * 2. File-header markers ("GENERATED", "DO NOT EDIT", "AUTO-GENERATED")
- * within the first ~300 characters — catches non-git projects.
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-
-const HEADER_SCAN_BYTES = 300;
-const HEADER_MARKERS = [
- /@generated\b/i,
- /\bGENERATED\s+FILE\b/,
- /\bAUTO-?GENERATED\b/i,
- /\bDO\s+NOT\s+EDIT\b/i,
-];
-
-/**
- * @param {string} filePath - absolute or cwd-relative path
- * @param {object} [options]
- * @param {string} [options.cwd] - project root (defaults to process.cwd())
- */
-export function isGeneratedFile(filePath, options = {}) {
- const cwd = options.cwd || process.cwd();
- const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
-
- if (isGitIgnored(absPath, cwd)) return true;
- if (hasGeneratedHeader(absPath)) return true;
- return false;
-}
-
-function isGitIgnored(absPath, cwd) {
- try {
- execSync(`git check-ignore --quiet ${JSON.stringify(absPath)}`, {
- cwd,
- stdio: 'ignore',
- });
- return true; // exit 0 = ignored
- } catch (err) {
- // Exit code 1 = not ignored. Exit code 128 = not a git repo or other error.
- // In both cases, treat as "not known to be ignored."
- return false;
- }
-}
-
-function hasGeneratedHeader(absPath) {
- let fd;
- try {
- fd = fs.openSync(absPath, 'r');
- const buf = Buffer.alloc(HEADER_SCAN_BYTES);
- const bytesRead = fs.readSync(fd, buf, 0, HEADER_SCAN_BYTES, 0);
- const head = buf.slice(0, bytesRead).toString('utf-8');
- return HEADER_MARKERS.some((re) => re.test(head));
- } catch {
- return false;
- } finally {
- if (fd !== undefined) { try { fs.closeSync(fd); } catch {} }
- }
-}
@@ -1,595 +0,0 @@
-/**
- * CLI helper: deterministic accept/discard of variant sessions.
- *
- * Usage:
- * node live-accept.mjs --id SESSION_ID --discard
- * node live-accept.mjs --id SESSION_ID --variant N
- *
- * For discard: removes the entire variant wrapper and restores the original.
- * For accept: replaces the wrapper with the chosen variant's content. If the
- * session had a colocated <style> block, it's preserved with carbonize markers
- * for a background agent to integrate into the project's CSS.
- *
- * Output: JSON to stdout.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-export async function acceptCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-accept.mjs [options]
-
-Deterministic accept/discard for live variant sessions.
-
-Modes:
- --discard Remove variants, restore original
- --variant N Accept variant N, discard the rest
-
-Required:
- --id SESSION_ID Session ID of the variant wrapper
-
-Output (JSON):
- { handled, file, carbonize }`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const variantNum = argVal(args, '--variant');
- const paramValuesRaw = argVal(args, '--param-values');
- const isDiscard = args.includes('--discard');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }
-
- let paramValues = null;
- if (paramValuesRaw) {
- try { paramValues = JSON.parse(paramValuesRaw); }
- catch { paramValues = null; } // malformed blob: skip the comment rather than failing the accept
- }
-
- // Find the file containing this session's markers
- const found = findSessionFile(id, process.cwd());
- if (!found) {
- console.log(JSON.stringify({ handled: false, error: 'Session markers not found for id: ' + id }));
- process.exit(0);
- }
-
- const { file: targetFile, content, lines } = found;
- const relFile = path.relative(process.cwd(), targetFile);
-
- // Bail if the session lives in a generated file. The agent manually wrote
- // the wrapper there for preview, and is responsible for writing the
- // accepted variant to true source (or cleaning up on discard). See
- // "Handle fallback" in live.md.
- if (isGeneratedFile(targetFile, { cwd: process.cwd() })) {
- console.log(JSON.stringify({
- handled: false,
- mode: 'fallback',
- file: relFile,
- hint: 'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.',
- }));
- process.exit(0);
- }
-
- if (isDiscard) {
- const result = handleDiscard(id, lines, targetFile);
- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));
- } else {
- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);
- // Single-line attention-grabber when cleanup is required. The full
- // five-step checklist lives in reference/live.md (loaded once per
- // session); repeating it per-event would waste tokens.
- if (result.carbonize) {
- result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + relFile + '. See reference/live.md "Required after accept".';
- }
- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));
- }
-}
-
-// ---------------------------------------------------------------------------
-// Discard
-// ---------------------------------------------------------------------------
-
-function handleDiscard(id, lines, targetFile) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const original = extractOriginal(lines, block);
- const isJsx = detectCommentSyntax(targetFile).open === '{/*';
- const replaceRange = expandReplaceRange(block, lines, isJsx);
-
- // Restore at the line we're actually replacing FROM, not the marker line.
- // For JSX wrappers the marker comments live INSIDE the outer `<div>`, so
- // `block.start` sits 2 spaces deeper than the original element. Using that
- // as the deindent base would push the restored content 2 spaces too far
- // right on every JSX/TSX session. `replaceRange.start` is the outer wrapper
- // line, which is at the original element's indent for both HTML and JSX.
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
- const restored = deindentContent(original, indent);
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...restored,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
- return {};
-}
-
-// ---------------------------------------------------------------------------
-// Accept
-// ---------------------------------------------------------------------------
-
-function handleAccept(id, variantNum, lines, targetFile, paramValues) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const commentSyntax = detectCommentSyntax(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- // Anchor indent on the line we're replacing FROM (the outer wrapper),
- // not on `block.start` — for JSX that's the marker comment 2 spaces
- // deeper than the original element. See handleDiscard for the full
- // rationale.
- const replaceRange = expandReplaceRange(block, lines, isJsx);
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
-
- // Extract the chosen variant's inner content
- const variantContent = extractVariant(lines, block, variantNum);
- if (!variantContent) return { handled: false, error: 'Variant ' + variantNum + ' not found' };
-
- // Extract CSS block if present
- const cssContent = extractCss(lines, block, id);
-
- // Check if carbonizing is needed:
- // - CSS block exists, OR
- // - variant HTML contains helper classes/attributes that need cleanup
- const variantText = variantContent.join('\n');
- const hasHelperAttrs = variantText.includes('data-impeccable-variant');
- const needsCarbonize = !!(cssContent || hasHelperAttrs);
-
- // Build the replacement
- const restored = deindentContent(variantContent, indent);
- const replacement = [];
-
- if (cssContent) {
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
- // JSX targets need the CSS body wrapped in a template literal so that the
- // `{` and `}` in CSS rules don't get parsed as JSX expressions.
- replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
- // Re-indent CSS content to match
- for (const cssLine of cssContent) {
- replacement.push(indent + cssLine.trimStart());
- }
- replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
- if (paramValues && Object.keys(paramValues).length > 0) {
- // Preserve the user's knob positions for the carbonize-cleanup agent
- // to bake into the final CSS when it collapses scoped rules.
- replacement.push(indent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close);
- }
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close);
- }
-
- // Keep the `@scope ([data-impeccable-variant="N"])` selectors in the
- // carbonize CSS block working visually by re-wrapping the accepted content
- // in a data-impeccable-variant="N" div with `display: contents` (so layout
- // isn't affected). The carbonize agent strips this attribute + wrapper when
- // it moves the CSS to a proper stylesheet.
- //
- // Style attribute syntax has to follow the host file's flavor — JSX files
- // need the object form, otherwise React 19 throws "Failed to set indexed
- // property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
- if (cssContent) {
- const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
- replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
- replacement.push(...restored);
- replacement.push(indent + '</div>');
- } else {
- replacement.push(...restored);
- }
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...replacement,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- return { carbonize: needsCarbonize };
-}
-
-// ---------------------------------------------------------------------------
-// Parsing helpers
-// ---------------------------------------------------------------------------
-
-/**
- * Find the start/end marker lines for a session.
- * Returns { start, end } (0-indexed line numbers) or null.
- */
-function findMarkerBlock(id, lines) {
- let start = -1;
- let end = -1;
- const startPattern = 'impeccable-variants-start ' + id;
- const endPattern = 'impeccable-variants-end ' + id;
-
- for (let i = 0; i < lines.length; i++) {
- if (start === -1 && lines[i].includes(startPattern)) start = i;
- if (lines[i].includes(endPattern)) { end = i; break; }
- }
-
- return (start !== -1 && end !== -1) ? { start, end } : null;
-}
-
-/**
- * Compute the line range to REPLACE (vs. just the marker range to extract
- * from). For JSX/TSX wrappers, live-wrap places the marker comments INSIDE
- * the `<div data-impeccable-variants="ID">` outer wrapper so the picked
- * element's JSX slot keeps a single child — a Fragment `<></>` would have
- * solved the multi-sibling case but failed inside `asChild` / cloneElement
- * parents with "Invalid prop supplied to React.Fragment".
- *
- * That means the marker block is enclosed by the wrapper `<div>` opener
- * (with `data-impeccable-variants="ID"`) and its matching `</div>`. We
- * walk back to the opener and forward to the closer so accept/discard
- * remove the entire scaffold, not just the inner markers.
- *
- * Marker lines themselves stay where they were so extractOriginal /
- * extractVariant / extractCss continue to walk the same range.
- */
-function expandReplaceRange(block, lines, isJsx) {
- if (!isJsx) return { start: block.start, end: block.end };
-
- let { start, end } = block;
-
- // Walk back for the wrapper `<div data-impeccable-variants="..."` opener.
- // The attr may sit on a continuation line of a multi-line opening tag, so
- // also walk to the line that actually contains `<div`.
- for (let i = start - 1; i >= Math.max(0, start - 12); i--) {
- if (/data-impeccable-variants=/.test(lines[i])) {
- let opener = i;
- while (opener > 0 && !/<div\b/.test(lines[opener])) opener--;
- start = opener;
- break;
- }
- }
-
- // Walk forward to the matching `</div>` by div-depth tracking from the
- // wrapper opener. Operate on JOINED text instead of per-line: a
- // multi-line self-closing JSX `<div\n className="spacer"\n/>` would
- // fool per-line regex tracking (the `<div` line matches openRe but the
- // `/>` line never matches selfCloseRe since it needs `<div` on the same
- // line). That left depth permanently over-counted and the wrapper's
- // outer `</div>` orphaned after accept/discard. Single regex with
- // `[^>]*?` (which spans newlines in JS) handles either form correctly.
- const joined = lines.slice(start).join('\n');
- // Match either `<div … />` (self-close, group 1 is `/`), `<div … >`
- // (open, group 1 is empty), or `</div>`.
- const tagRe = /<div\b[^>]*?(\/?)>|<\/div\s*>/g;
- let depth = 0;
- let m;
- while ((m = tagRe.exec(joined)) !== null) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && m[1] === '/';
- if (isClose) depth--;
- else if (!isSelfClose) depth++;
- if (depth <= 0) {
- // m.index is offset within `joined`; convert back to a file line.
- const linesBefore = joined.slice(0, m.index + m[0].length).split('\n').length - 1;
- const candidateEnd = start + linesBefore;
- if (candidateEnd >= end) {
- end = candidateEnd;
- break;
- }
- }
- }
-
- return { start, end };
-}
-
-/**
- * Join wrapper lines into a single string with `<style>` elements removed so
- * marker matching and div-depth tracking aren't confused by:
- * - CSS `@scope ([data-impeccable-variant="N"])` strings that look like the
- * HTML marker we're searching for
- * - JSX self-closing `<style ... />` (no separate `</style>` to close on)
- * - Same-line `<style>…</style>` blocks
- * - Multi-line `<style>\n…\n</style>` blocks
- */
-function stripStyleAndJoin(lines, block) {
- const out = [];
- let inStyle = false;
- for (let i = block.start; i <= block.end; i++) {
- let line = lines[i];
-
- if (!inStyle) {
- // Strip any complete <style> elements on this line (self-closed or
- // same-line-closed), including their body content.
- line = line
- .replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/g, '')
- .replace(/<style\b[^>]*\/\s*>/g, '');
-
- // If a <style> opener remains (multi-line body starts here), strip from
- // the opener to end-of-line and flip into skip mode.
- const openerIdx = line.search(/<style\b/);
- if (openerIdx !== -1) {
- line = line.slice(0, openerIdx);
- inStyle = true;
- }
- out.push(line);
- } else {
- // In multi-line style body; drop everything until we see </style>.
- const closeIdx = line.search(/<\/style\s*>/);
- if (closeIdx !== -1) {
- inStyle = false;
- out.push(line.slice(closeIdx).replace(/<\/style\s*>/, ''));
- }
- // else: skip line entirely
- }
- }
- return out.join('\n');
-}
-
-/**
- * Find the inner content of `<TAG ...attrMatch...>…</TAG>` inside `text`,
- * handling nested same-tag elements via depth counting. `attrMatch` is a
- * regex source fragment that must appear inside the opener tag.
- * Returns the inner string (may be empty), or null if not found.
- */
-function extractInnerByAttr(text, attrMatch) {
- const openerRe = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*' + attrMatch + '[^>]*>');
- const openMatch = text.match(openerRe);
- if (!openMatch) return null;
-
- const tagName = openMatch[1];
- const innerStart = openMatch.index + openMatch[0].length;
-
- // Match any opener or closer of this tag name after innerStart.
- // (Does not match self-closing <TAG … />, which doesn't contribute to depth.)
- const tagRe = new RegExp('<(?:/)?' + tagName + '\\b[^>]*>', 'g');
- tagRe.lastIndex = innerStart;
-
- let depth = 1;
- let m;
- while ((m = tagRe.exec(text))) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && /\/\s*>$/.test(m[0]);
- if (isClose) {
- depth--;
- if (depth === 0) return text.slice(innerStart, m.index);
- } else if (!isSelfClose) {
- depth++;
- }
- }
- return null;
-}
-
-/**
- * Extract the original element content from within the variant wrapper.
- * Returns an array of lines.
- */
-function extractOriginal(lines, block) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="original"');
- if (inner === null) return [];
- return inner.split('\n');
-}
-
-/**
- * Extract a specific variant's inner content (stripping the wrapper div).
- * Returns an array of lines, or null if not found.
- */
-function extractVariant(lines, block, variantNum) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + variantNum + '"');
- if (inner === null) return null;
- const result = inner.split('\n');
- // Collapse a lone empty leading/trailing line (common after string splice).
- while (result.length > 1 && result[0].trim() === '') result.shift();
- while (result.length > 1 && result[result.length - 1].trim() === '') result.pop();
- return result.length > 0 ? result : null;
-}
-
-/**
- * Extract the colocated <style> block content (between the style tags).
- * Returns an array of CSS lines, or null if no style block found.
- *
- * Handles three shapes of `<style data-impeccable-css="ID" ...>`:
- * 1. Self-closing: `<style ... />` — no body; return null (nothing to carbonize).
- * 2. Same-line open+close: `<style>...</style>` — return the inner content.
- * 3. Multi-line: `<style>` on one line, `</style>` on a later line — return
- * the lines between them.
- */
-function extractCss(lines, block, id) {
- const styleAttr = 'data-impeccable-css="' + id + '"';
- let inStyle = false;
- const content = [];
-
- for (let i = block.start; i <= block.end; i++) {
- const line = lines[i];
-
- if (!inStyle && line.includes(styleAttr)) {
- // Self-closing: nothing to carbonize.
- if (/<style\b[^>]*\/\s*>/.test(line)) return null;
- // Same-line open + close: extract inner text.
- const sameLine = line.match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/);
- if (sameLine) {
- const inner = stripJsxTemplateWrap(sameLine[1]);
- return inner.length > 0 ? inner.split('\n') : null;
- }
- inStyle = true;
- continue; // skip the <style> opening tag
- }
-
- if (inStyle) {
- // Detect </style> anywhere on the line — JSX template-literal closes
- // (`}</style>`) put the close mid-line, and we don't want to absorb the
- // template-literal punctuation as CSS content.
- const closeIdx = line.indexOf('</style>');
- if (closeIdx !== -1) break;
- content.push(line);
- }
- }
-
- if (content.length === 0) return null;
- return stripJsxTemplateLines(content);
-}
-
-/**
- * Strip a JSX template-literal wrap (`{` … `}`) from CSS extracted out of a
- * `<style>` element in a JSX/TSX file. The agent may write the wrap with
- * `{` and `}` directly attached to the `<style>` tags, on their own lines,
- * or attached to the first/last CSS lines — all three are JSX-legal.
- *
- * Stripping is required because handleAccept re-wraps the CSS itself when
- * carbonizing. Without this, two consecutive accepts (or a previously-
- * accepted variants block being carbonized) would produce nested
- * `{` `{` … `}` `}`, which oxc rejects with "Expected `}` but found `@`".
- */
-function stripJsxTemplateLines(content) {
- const out = content.slice();
-
- // Drop any leading blank lines so we don't miss a `{` line buried below
- // them; same for trailing.
- while (out.length > 0 && out[0].trim() === '') out.shift();
- while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
- if (out.length === 0) return null;
-
- // Leading `{`: own line, or attached to the first CSS line.
- const firstTrim = out[0].trimStart();
- if (firstTrim === '{`') {
- out.shift();
- } else if (firstTrim.startsWith('{`')) {
- const idx = out[0].indexOf('{`');
- out[0] = out[0].slice(0, idx) + out[0].slice(idx + 2);
- if (out[0].trim() === '') out.shift();
- }
- if (out.length === 0) return null;
-
- // Trailing `` ` `` `}`: own line, or attached to the last CSS line.
- const lastIdx = out.length - 1;
- const lastTrim = out[lastIdx].trimEnd();
- if (lastTrim === '`}') {
- out.pop();
- } else if (lastTrim.endsWith('`}')) {
- const text = out[lastIdx];
- const idx = text.lastIndexOf('`}');
- out[lastIdx] = text.slice(0, idx) + text.slice(idx + 2);
- if (out[lastIdx].trim() === '') out.pop();
- }
-
- return out.length > 0 ? out : null;
-}
-
-function stripJsxTemplateWrap(text) {
- const lines = text.split('\n');
- const stripped = stripJsxTemplateLines(lines);
- return stripped ? stripped.join('\n') : '';
-}
-
-/**
- * De-indent content that was indented by live-wrap.mjs.
- * The wrap script adds `indent + ' '` (4 extra spaces) to each line.
- * We restore to just `indent` level.
- */
-function deindentContent(contentLines, baseIndent) {
- // Find the minimum indentation in the content to determine how much was added
- let minIndent = Infinity;
- for (const line of contentLines) {
- if (line.trim() === '') continue;
- const leadingSpaces = line.match(/^(\s*)/)[1].length;
- minIndent = Math.min(minIndent, leadingSpaces);
- }
- if (minIndent === Infinity) minIndent = 0;
-
- // Strip the extra indentation and re-add base indent
- return contentLines.map(line => {
- if (line.trim() === '') return '';
- return baseIndent + line.slice(minIndent);
- });
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- return { open: '<!--', close: '-->' };
-}
-
-// ---------------------------------------------------------------------------
-// File search (find the file containing session markers)
-// ---------------------------------------------------------------------------
-
-function findSessionFile(id, cwd) {
- const marker = 'impeccable-variants-start ' + id;
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, marker, seen, 0);
- if (result) {
- const content = fs.readFileSync(result, 'utf-8');
- return { file: result, content, lines: content.split('\n') };
- }
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth) {
- if (depth > 5) return null;
- let realDir;
- try { realDir = fs.realpathSync(dir); } catch { return null; }
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- if (!EXTENSIONS.includes(path.extname(entry.name).toLowerCase())) continue;
- const filePath = path.join(dir, entry.name);
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip */ }
- }
-
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
- if (result) return result;
- }
-
- return null;
-}
-
-// ---------------------------------------------------------------------------
-// Utilities
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-accept.mjs') || _running?.endsWith('live-accept.mjs/')) {
- acceptCli();
-}
-
-export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax };
@@ -1,123 +0,0 @@
-/**
- * Browser-side durable session helpers for Impeccable live mode.
- *
- * Kept separate from live-browser.js so recovery state can be tested without
- * booting the full overlay UI. Served before live-browser.js and attached to
- * window.__IMPECCABLE_LIVE_SESSION__.
- */
-(function (root) {
- 'use strict';
-
- function createLiveBrowserSessionState({ prefix, storage, idFactory }) {
- if (!prefix) throw new Error('prefix required');
- const store = storage || root.localStorage;
- const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };
- const sessionKey = prefix + '-session';
- const handledKey = sessionKey + '-handled';
- const scrollKey = sessionKey + '-scroll';
- let checkpointRevision = 0;
- const owner = makeId();
-
- function safeRead(key) {
- try { return store.getItem(key); } catch { return null; }
- }
-
- function safeWrite(key, value) {
- try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }
- }
-
- function safeRemove(key) {
- try { store.removeItem(key); } catch { /* unavailable storage */ }
- }
-
- function loadSession() {
- try {
- const raw = safeRead(sessionKey);
- if (!raw) return null;
- const parsed = JSON.parse(raw);
- if (Number.isInteger(parsed.checkpointRevision)) {
- checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);
- }
- return parsed;
- } catch { return null; }
- }
-
- function saveSession(session) {
- if (!session || !session.id) return;
- const payload = {
- ...session,
- checkpointRevision,
- };
- safeWrite(sessionKey, JSON.stringify(payload));
- }
-
- function clearSession() {
- safeRemove(sessionKey);
- }
-
- function nextCheckpointRevision() {
- checkpointRevision += 1;
- const existing = loadSession();
- if (existing?.id) saveSession(existing);
- return checkpointRevision;
- }
-
- function seedCheckpointRevision(value) {
- if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);
- return checkpointRevision;
- }
-
- function currentCheckpointRevision() {
- return checkpointRevision;
- }
-
- function markHandled(id) {
- if (!id) return;
- safeWrite(handledKey, id);
- }
-
- function isHandled(id) {
- return !!id && safeRead(handledKey) === id;
- }
-
- function clearHandled() {
- safeRemove(handledKey);
- }
-
- function writeScrollY(y) {
- safeWrite(scrollKey, String(y));
- }
-
- function readScrollY() {
- const raw = safeRead(scrollKey);
- if (raw == null) return null;
- const n = parseFloat(raw);
- return isFinite(n) ? n : null;
- }
-
- function clearScrollY() {
- safeRemove(scrollKey);
- }
-
- return {
- owner,
- sessionKey,
- handledKey,
- scrollKey,
- saveSession,
- loadSession,
- clearSession,
- nextCheckpointRevision,
- seedCheckpointRevision,
- currentCheckpointRevision,
- markHandled,
- isHandled,
- clearHandled,
- writeScrollY,
- readScrollY,
- clearScrollY,
- };
- }
-
- root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };
-})(typeof window !== 'undefined' ? window : globalThis);
@@ -1,4860 +0,0 @@
-/**
- * Impeccable Live Variant Mode — Browser Script
- *
- * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
- * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
- * before this code.
- *
- * UI: a single floating bar that morphs between three states —
- * configure (pick action + go), generating (progressive dots), and cycling
- * (prev/next + accept/discard). Feels like Spotlight, not a modal.
- */
-(function () {
- 'use strict';
- if (typeof window === 'undefined') return;
-
- // Guard against double-init. Bun's HTML loader may process the <script> tag
- // and create a bundled copy alongside the external load, or HMR may re-execute.
- // Check BEFORE reading token/port to catch all cases.
- if (window.__IMPECCABLE_LIVE_INIT__) return;
- window.__IMPECCABLE_LIVE_INIT__ = true;
-
- const TOKEN = window.__IMPECCABLE_TOKEN__;
- const PORT = window.__IMPECCABLE_PORT__;
- if (!TOKEN || !PORT) {
- window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
- return;
- }
-
- // ---------------------------------------------------------------------------
- // Design tokens
- // ---------------------------------------------------------------------------
-
- // Brand magenta is pinned to the site token (--color-accent in main.css)
- // so Accept / knobs / cycle-dots match the site's accent, not a washed
- // theme-adjusted one.
- const C = {
- brand: 'oklch(60% 0.25 350)',
- brandHov: 'oklch(52% 0.25 350)',
- brandSoft: 'oklch(60% 0.25 350 / 0.15)',
- ink: 'oklch(15% 0.01 350)',
- ash: 'oklch(55% 0 0)',
- paper: 'oklch(98% 0.005 350 / 0.92)',
- paperSolid:'oklch(98% 0.005 350)',
- mist: 'oklch(90% 0.01 350 / 0.6)',
- white: 'oklch(99% 0 0)',
- };
- const FONT = 'system-ui, -apple-system, sans-serif';
- const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
- // z-index: detect overlays use 99999, so our UI must be above them
- const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };
- const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
- const PREFIX = 'impeccable-live';
- const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
- prefix: PREFIX,
- storage: localStorage,
- idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),
- });
- if (!sessionState) {
- console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');
- window.__IMPECCABLE_LIVE_INIT__ = false;
- return;
- }
- const HIGHLIGHT_TRANSITION =
- 'top 140ms ' + EASE +
- ', left 140ms ' + EASE +
- ', width 140ms ' + EASE +
- ', height 140ms ' + EASE +
- ', opacity 150ms ease';
- const TOOLTIP_TRANSITION =
- 'top 140ms ' + EASE + ', left 140ms ' + EASE + ', opacity 150ms ease';
-
- const SKIP_TAGS = new Set([
- 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
- ]);
-
- // SVG icons stack above each chip label. All strokes use currentColor so the
- // icon recolors to C.brand when its chip is selected. 20x20 render, 24-viewBox,
- // 1.5 stroke — visually consistent with the Foundation grid on the homepage.
- const ICON_ATTRS = 'width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block"';
- const ICONS = {
- impeccable: `<svg ${ICON_ATTRS}><path d="M4 20l4-1L18 9l-3-3L5 16z"/><path d="M14 7l3 3"/></svg>`,
- bolder: `<svg ${ICON_ATTRS}><rect x="6" y="12" width="4" height="7" rx="0.5"/><rect x="14" y="5" width="4" height="14" rx="0.5"/></svg>`,
- quieter: `<svg ${ICON_ATTRS}><rect x="6" y="5" width="4" height="14" rx="0.5"/><rect x="14" y="12" width="4" height="7" rx="0.5"/></svg>`,
- distill: `<svg ${ICON_ATTRS}><path d="M4 5h16l-6 8v7l-4-2v-5z"/></svg>`,
- polish: `<svg ${ICON_ATTRS}><path d="M15 3l1 3 3 1-3 1-1 3-1-3-3-1 3-1z"/><path d="M7 13l0.6 1.8 1.8 0.6-1.8 0.6-0.6 1.8-0.6-1.8-1.8-0.6 1.8-0.6z"/></svg>`,
- typeset: `<svg ${ICON_ATTRS}><path d="M5 6h14" stroke-width="2.6"/><path d="M5 12h9" stroke-width="1.9"/><path d="M5 18h5" stroke-width="1.3"/></svg>`,
- colorize: `<svg ${ICON_ATTRS}><circle cx="9" cy="10" r="5"/><circle cx="15" cy="10" r="5"/><circle cx="12" cy="15" r="5"/></svg>`,
- layout: `<svg ${ICON_ATTRS}><rect x="3" y="4" width="8" height="16" rx="0.5"/><rect x="13" y="4" width="8" height="7" rx="0.5"/><rect x="13" y="13" width="8" height="7" rx="0.5"/></svg>`,
- adapt: `<svg ${ICON_ATTRS}><rect x="2.5" y="5" width="12" height="11" rx="1"/><line x1="2.5" y1="19" x2="14.5" y2="19"/><rect x="16.5" y="8" width="5" height="11" rx="1"/></svg>`,
- animate: `<svg ${ICON_ATTRS}><path d="M3 18c4-4 6-10 10-10"/><path d="M13 8c3 0 5 5 8 10"/><circle cx="13" cy="8" r="1.6" fill="currentColor" stroke="none"/></svg>`,
- delight: `<svg ${ICON_ATTRS}><path d="M12 3l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>`,
- overdrive: `<svg ${ICON_ATTRS}><path d="M13 3L5 13h5l-1 8 9-12h-6z"/></svg>`,
- };
-
- const ACTIONS = [
- { value: 'impeccable', label: 'Freeform' },
- { value: 'bolder', label: 'Bolder' },
- { value: 'quieter', label: 'Quieter' },
- { value: 'distill', label: 'Distill' },
- { value: 'polish', label: 'Polish' },
- { value: 'typeset', label: 'Typeset' },
- { value: 'colorize', label: 'Colorize' },
- { value: 'layout', label: 'Layout' },
- { value: 'adapt', label: 'Adapt' },
- { value: 'animate', label: 'Animate' },
- { value: 'delight', label: 'Delight' },
- { value: 'overdrive', label: 'Overdrive' },
- ];
-
- // ---------------------------------------------------------------------------
- // State
- // ---------------------------------------------------------------------------
-
- let state = 'IDLE';
- let hoveredElement = null;
- let selectedElement = null;
- let currentSessionId = null;
- let expectedVariants = 0;
- let arrivedVariants = 0;
- let visibleVariant = 0;
- let variantObserver = null;
- let hasProjectContext = false;
- let selectedAction = 'impeccable';
- let selectedCount = 3;
- const browserOwner = sessionState.owner;
- let checkpointTimer = null;
-
- // Scroll lock — holds window.scrollY at a fixed value while the session is
- // active, so HMR DOM patches and variant swaps can't drift the page. See
- // startScrollLock / stopScrollLock below.
- let scrollLockObserver = null;
- let scrollLockTargetY = null;
- let scrollLockRaf = null;
- let scrollLockAbort = null;
-
- // Dedicated key for scroll position — SEPARATE from LS_KEY so that
- // saveSession's state updates don't clobber a carefully-captured scrollY.
- // (Previously: saveSession wrote scrollY alongside state, so every call
- // during resume overwrote the pre-reload value with whatever the browser
- // had landed on, typically 0.)
- function writeScrollY(y) { sessionState.writeScrollY(y); }
- function readScrollY() { return sessionState.readScrollY(); }
- function clearScrollY() { sessionState.clearScrollY(); }
-
- // Pre-empt the browser: apply manual scroll restoration and jump to the
- // saved scrollY at script-parse time. Retries on fonts.ready and load
- // are essential: scrollTo(y) clamps to the current document.scrollHeight,
- // which is often hundreds of pixels short of the final value until
- // async-loaded fonts swap in and reflow.
- try {
- history.scrollRestoration = 'manual';
- const savedY = readScrollY();
- if (savedY != null) {
- const apply = () => {
- if (Math.abs(window.scrollY - savedY) > 0.5) {
- console.log('[impeccable.scroll] early restore', { from: window.scrollY, to: savedY });
- window.scrollTo(0, savedY);
- }
- };
- apply();
- if (document.fonts?.ready) document.fonts.ready.then(apply).catch(() => {});
- window.addEventListener('load', apply, { once: true });
- }
- } catch {}
-
- // UI refs
- let highlightEl = null;
- let tooltipEl = null;
- let barEl = null;
- let pickerEl = null;
- let toastEl = null;
- let scrollRaf = null;
-
- // ---------------------------------------------------------------------------
- // Helpers
- // ---------------------------------------------------------------------------
-
- function own(el) {
- return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
- }
-
- function pickable(el) {
- if (!el || el.nodeType !== 1) return false;
- if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
- if (own(el)) return false;
- const r = el.getBoundingClientRect();
- return r.width >= 20 && r.height >= 20;
- }
-
- function desc(el) {
- if (!el) return '';
- let s = el.tagName.toLowerCase();
- if (el.id) s += '#' + el.id;
- else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
- return s;
- }
-
- function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
-
- // Modal-aware chrome: keep our floating UI clickable inside Radix /
- // Headless UI / vaul portals.
- //
- // Two host-page behaviors break us when the picked element lives inside a
- // modal dialog:
- //
- // 1. Modal scroll-lock disables outside pointer events. Radix's
- // `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
- // while a modal is open and only restores `auto` on the layer. Our
- // chrome inherits `none` from <body> and becomes unclickable.
- // 2. The dialog's outside-interaction handler (Radix's
- // `usePointerDownOutside`) listens at document level and dismisses
- // the dialog whenever a `pointerdown` lands outside the layer node.
- // Our chrome is a sibling of <body>, so Radix classifies our clicks
- // as outside and tears the dialog down mid-task.
- //
- // We can't reliably re-parent our chrome into the dialog subtree (z-index
- // stacking, scroll containers, theming all become host-page concerns), so
- // we defang both behaviors at our root:
- //
- // - `pointer-events: auto !important` overrides the inherited `none`.
- // - Stop `pointerdown` / `mousedown` propagation so the document-level
- // dismiss listener never fires for our clicks.
- // - Stop `focusin` propagation so any focus shifts inside our chrome
- // don't read as "focus moved outside the dialog" to focus traps.
- //
- // Click events still bubble normally — only the early pointer/focus
- // signals that drive outside-interaction detection are silenced.
- function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
- if (!rootEl) return;
- if (setPointerEvents) {
- rootEl.style.setProperty('pointer-events', 'auto', 'important');
- }
- const stop = (e) => e.stopPropagation();
- rootEl.addEventListener('pointerdown', stop);
- rootEl.addEventListener('mousedown', stop);
- rootEl.addEventListener('focusin', stop);
- }
-
- // ---------------------------------------------------------------------------
- // Highlight overlay
- // ---------------------------------------------------------------------------
-
- function initHighlight() {
- highlightEl = document.createElement('div');
- highlightEl.id = PREFIX + '-highlight';
- Object.assign(highlightEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- border: '2px solid ' + C.brand, borderRadius: '3px',
- pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
- transition: HIGHLIGHT_TRANSITION,
- display: 'none', opacity: '0',
- });
- document.body.appendChild(highlightEl);
-
- tooltipEl = document.createElement('div');
- tooltipEl.id = PREFIX + '-tooltip';
- Object.assign(tooltipEl.style, {
- position: 'fixed',
- background: C.ink, color: C.white,
- fontFamily: MONO, fontSize: '10px', fontWeight: '500',
- padding: '2px 6px', borderRadius: '3px',
- zIndex: Z.highlight + 1, pointerEvents: 'none',
- whiteSpace: 'nowrap', display: 'none',
- letterSpacing: '0.02em',
- transition: TOOLTIP_TRANSITION,
- });
- document.body.appendChild(tooltipEl);
- }
-
- function showHighlight(el) {
- if (!el || !highlightEl) return;
- const r = el.getBoundingClientRect();
- const top = (r.top - 2) + 'px', left = (r.left - 2) + 'px';
- const width = (r.width + 4) + 'px', height = (r.height + 4) + 'px';
- const tipTop = r.top - 20;
- const tipY = (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px';
- const tipX = Math.max(4, r.left) + 'px';
- tooltipEl.textContent = desc(el);
-
- const hiWasHidden = highlightEl.style.display === 'none' || highlightEl.style.opacity === '0';
- if (hiWasHidden) {
- // Snap to first target without animating from (0,0), then fade in.
- highlightEl.style.transition = 'none';
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block' });
- tooltipEl.style.transition = 'none';
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block' });
- void highlightEl.offsetWidth;
- highlightEl.style.transition = HIGHLIGHT_TRANSITION;
- highlightEl.style.opacity = '1';
- tooltipEl.style.transition = TOOLTIP_TRANSITION;
- tooltipEl.style.opacity = '1';
- } else {
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block', opacity: '1' });
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block', opacity: '1' });
- }
- }
-
- function hideHighlight() {
- if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
- if (tooltipEl) { tooltipEl.style.opacity = '0'; tooltipEl.style.display = 'none'; }
- }
-
- // ---------------------------------------------------------------------------
- // Annotation overlay (comment pins + magenta strokes)
- //
- // Active while state === 'CONFIGURING'. The overlay is a fixed-positioned
- // sibling of <body> mirroring selectedElement's bounding rect. Click (no
- // drag) drops a comment pin; drag paints a magenta SVG stroke. All coords
- // are stored in element-local CSS px so they survive scroll / resize and
- // correlate directly with the captured PNG.
- // ---------------------------------------------------------------------------
-
- const DRAG_THRESHOLD = 5; // px — below this, treat pointerup as a click
- const PIN_DBL_CLICK_MS = 300; // two clicks on the same pin within this delete it
- let annotOverlayEl = null;
- let annotSvgEl = null;
- let annotPinsEl = null;
- let annotClearChipEl = null;
- let annotState = { comments: [], strokes: [] };
- let annotActive = false;
- // `annotPointer` is either:
- // { kind: 'new', x0, y0, moved, strokeEl, strokePoints } creating a stroke/pin
- // { kind: 'pin', idx, startPointer, startPin, moved } dragging an existing pin
- let annotPointer = null;
- let annotEditing = null; // { idx, input, wrapEl }
- let annotLastPinClick = { idx: -1, time: 0 }; // for click-click-to-delete
-
- function initAnnotOverlay() {
- annotOverlayEl = document.createElement('div');
- annotOverlayEl.id = PREFIX + '-annot';
- Object.assign(annotOverlayEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- pointerEvents: 'auto', zIndex: Z.highlight + 2,
- display: 'none', overflow: 'visible',
- cursor: 'crosshair', touchAction: 'none',
- });
-
- annotSvgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- annotSvgEl.id = PREFIX + '-annot-svg';
- Object.assign(annotSvgEl.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%',
- // The SVG itself doesn't absorb clicks; individual hit-paths opt-in via
- // pointer-events=stroke so gaps still fall through to the overlay.
- pointerEvents: 'none', overflow: 'visible',
- });
- annotOverlayEl.appendChild(annotSvgEl);
-
- annotPinsEl = document.createElement('div');
- annotPinsEl.id = PREFIX + '-annot-pins';
- Object.assign(annotPinsEl.style, {
- position: 'absolute', inset: '0',
- pointerEvents: 'none',
- });
- annotOverlayEl.appendChild(annotPinsEl);
-
- annotClearChipEl = document.createElement('div');
- annotClearChipEl.id = PREFIX + '-annot-clear';
- annotClearChipEl.dataset.annotClear = 'true';
- annotClearChipEl.textContent = 'Clear';
- Object.assign(annotClearChipEl.style, {
- position: 'absolute', top: '8px', right: '8px',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '10px', fontWeight: '500',
- letterSpacing: '0.08em', textTransform: 'uppercase',
- padding: '5px 12px', borderRadius: '999px',
- cursor: 'pointer', pointerEvents: 'auto',
- display: 'none', userSelect: 'none',
- boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
- });
- annotOverlayEl.appendChild(annotClearChipEl);
-
- annotOverlayEl.addEventListener('pointerdown', onAnnotDown);
- annotOverlayEl.addEventListener('pointermove', onAnnotMove);
- annotOverlayEl.addEventListener('pointerup', onAnnotUp);
- annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
- document.body.appendChild(annotOverlayEl);
- // Modal-host friendliness: pointer-events is already 'auto' on this
- // overlay; we only need to silence the host's outside-interaction
- // listeners. Don't override pointer-events here (the overlay toggles
- // visibility via display:none, which is fine).
- defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
- }
-
- function updateClearChip() {
- if (!annotClearChipEl) return;
- const hasAny = annotState.comments.length > 0 || annotState.strokes.length > 0;
- annotClearChipEl.style.display = hasAny ? 'block' : 'none';
- }
-
- function showAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- annotActive = true;
- positionAnnotOverlay(el);
- annotOverlayEl.style.display = 'block';
- }
-
- function hideAnnotOverlay() {
- annotActive = false;
- if (annotOverlayEl) annotOverlayEl.style.display = 'none';
- // Drop any in-progress edit without touching annotState — clearAnnotations
- // (if the caller is exiting configure mode) handles state reset.
- annotEditing = null;
- }
-
- function positionAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- const r = el.getBoundingClientRect();
- Object.assign(annotOverlayEl.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- annotSvgEl.setAttribute('viewBox', '0 0 ' + r.width + ' ' + r.height);
- }
-
- function clearAnnotations() {
- annotState.comments = [];
- annotState.strokes = [];
- if (annotSvgEl) while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- if (annotPinsEl) annotPinsEl.innerHTML = '';
- annotPointer = null;
- annotEditing = null;
- annotLastPinClick = { idx: -1, time: 0 };
- updateClearChip();
- }
-
- // Rebuild the SVG layer. Each stroke gets a wider invisible hit path
- // beneath the visible magenta path so clicks register on thin lines.
- function redrawStrokes() {
- while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- annotState.strokes.forEach((s, idx) => {
- const d = pointsToPath(s.points);
- const hit = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- hit.setAttribute('d', d);
- hit.setAttribute('stroke', 'transparent');
- hit.setAttribute('stroke-width', '16');
- hit.setAttribute('stroke-linecap', 'round');
- hit.setAttribute('stroke-linejoin', 'round');
- hit.setAttribute('fill', 'none');
- hit.setAttribute('pointer-events', 'stroke');
- hit.style.cursor = 'pointer';
- hit.dataset.annotStroke = String(idx);
- annotSvgEl.appendChild(hit);
- const visible = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- visible.setAttribute('d', d);
- visible.setAttribute('stroke', C.brand);
- visible.setAttribute('stroke-width', '3');
- visible.setAttribute('stroke-linecap', 'round');
- visible.setAttribute('stroke-linejoin', 'round');
- visible.setAttribute('fill', 'none');
- visible.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(visible);
- });
- updateClearChip();
- }
-
- function localCoords(e) {
- const rect = annotOverlayEl.getBoundingClientRect();
- return { x: e.clientX - rect.left, y: e.clientY - rect.top };
- }
-
- function onAnnotDown(e) {
- if (!annotActive) return;
-
- // 1) Clear chip → wipe all annotations
- if (e.target.closest?.('[data-annot-clear]')) {
- if (annotEditing) annotEditing = null;
- clearAnnotations();
- renderAllPins();
- redrawStrokes();
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 2) Stroke hit path → delete that stroke
- const strokeHit = e.target.closest?.('[data-annot-stroke]');
- if (strokeHit) {
- const idx = parseInt(strokeHit.dataset.annotStroke, 10);
- if (Number.isInteger(idx)) {
- annotState.strokes.splice(idx, 1);
- redrawStrokes();
- }
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 3) Pin → drag, edit, or delete-on-double-click
- const pinWrap = e.target.closest?.('[data-annot-pin]');
- if (pinWrap) {
- const idx = parseInt(pinWrap.dataset.annotPin, 10);
- if (!Number.isInteger(idx)) return;
- // Double-click (two pointerdowns on the same pin within window) → delete.
- const now = Date.now();
- if (annotLastPinClick.idx === idx && now - annotLastPinClick.time < PIN_DBL_CLICK_MS) {
- if (annotEditing && annotEditing.idx === idx) annotEditing = null;
- annotState.comments.splice(idx, 1);
- annotLastPinClick = { idx: -1, time: 0 };
- renderAllPins();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- annotLastPinClick = { idx, time: now };
- // If editing a different pin, commit that edit before starting here.
- if (annotEditing && annotEditing.idx !== idx) finalizeEditingPin();
- // If already editing THIS pin and the user clicked the dot, let the
- // input keep focus (don't start a drag — the click wasn't meant as one).
- if (annotEditing && annotEditing.idx === idx) return;
- const p = localCoords(e);
- const pin = annotState.comments[idx];
- annotPointer = {
- kind: 'pin', idx,
- startPointer: p,
- startPin: { x: pin.x, y: pin.y },
- moved: false,
- };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 4) Empty area → commit any open edit, then start new annotation
- if (annotEditing) {
- finalizeEditingPin();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- const p = localCoords(e);
- annotPointer = { kind: 'new', x0: p.x, y0: p.y, moved: false, strokeEl: null, strokePoints: null };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- }
-
- function onAnnotMove(e) {
- if (!annotActive || !annotPointer) return;
- const p = localCoords(e);
-
- if (annotPointer.kind === 'pin') {
- const dx = p.x - annotPointer.startPointer.x;
- const dy = p.y - annotPointer.startPointer.y;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- }
- const pin = annotState.comments[annotPointer.idx];
- if (!pin) { annotPointer = null; return; }
- pin.x = annotPointer.startPin.x + dx;
- pin.y = annotPointer.startPin.y + dy;
- renderAllPins();
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const dx = p.x - annotPointer.x0, dy = p.y - annotPointer.y0;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- const strokeEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- strokeEl.setAttribute('stroke', C.brand);
- strokeEl.setAttribute('stroke-width', '3');
- strokeEl.setAttribute('stroke-linecap', 'round');
- strokeEl.setAttribute('stroke-linejoin', 'round');
- strokeEl.setAttribute('fill', 'none');
- strokeEl.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(strokeEl);
- annotPointer.strokeEl = strokeEl;
- annotPointer.strokePoints = [[annotPointer.x0, annotPointer.y0]];
- }
- annotPointer.strokePoints.push([p.x, p.y]);
- annotPointer.strokeEl.setAttribute('d', pointsToPath(annotPointer.strokePoints));
- e.stopPropagation();
- }
-
- function onAnnotUp(e) {
- if (!annotActive || !annotPointer) return;
-
- if (annotPointer.kind === 'pin') {
- const wasDrag = annotPointer.moved;
- const idx = annotPointer.idx;
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- if (wasDrag) {
- // A drag is an intentional reposition; a follow-up click shouldn't be
- // interpreted as a double-click-to-delete.
- annotLastPinClick = { idx: -1, time: 0 };
- } else {
- beginEditPin(idx);
- }
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const wasDrag = annotPointer.moved;
- if (wasDrag) {
- annotState.strokes.push({ points: annotPointer.strokePoints });
- // Swap the temporary preview SVG path for the full render with hit paths.
- redrawStrokes();
- } else {
- const idx = annotState.comments.length;
- annotState.comments.push({ x: annotPointer.x0, y: annotPointer.y0, text: '' });
- renderAllPins();
- beginEditPin(idx);
- }
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- e.stopPropagation();
- }
-
- function pointsToPath(points) {
- if (!points || points.length === 0) return '';
- let d = 'M' + points[0][0].toFixed(1) + ' ' + points[0][1].toFixed(1);
- for (let i = 1; i < points.length; i++) {
- d += ' L' + points[i][0].toFixed(1) + ' ' + points[i][1].toFixed(1);
- }
- return d;
- }
-
- function renderAllPins() {
- annotPinsEl.innerHTML = '';
- annotState.comments.forEach((c, idx) => {
- annotPinsEl.appendChild(buildPinElement(c, idx));
- });
- updateClearChip();
- }
-
- function buildPinElement(comment, idx) {
- const interactive = idx >= 0;
- const wrap = document.createElement('div');
- if (interactive) wrap.dataset.annotPin = String(idx);
- Object.assign(wrap.style, {
- position: 'absolute',
- left: (comment.x - 7) + 'px', top: (comment.y - 7) + 'px',
- pointerEvents: interactive ? 'auto' : 'none',
- display: 'flex', alignItems: 'flex-start', gap: '6px',
- cursor: interactive ? 'grab' : 'default',
- touchAction: 'none',
- });
- const dot = document.createElement('div');
- Object.assign(dot.style, {
- width: '14px', height: '14px', borderRadius: '50%',
- background: C.brand, border: '2px solid ' + C.white,
- boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
- flexShrink: '0',
- });
- wrap.appendChild(dot);
-
- if (comment.text) {
- const bubble = document.createElement('div');
- bubble.textContent = comment.text;
- Object.assign(bubble.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- marginTop: '-2px', maxWidth: '220px',
- pointerEvents: 'none', whiteSpace: 'pre-wrap',
- wordBreak: 'break-word',
- });
- wrap.appendChild(bubble);
- }
- return wrap;
- }
-
- function beginEditPin(idx) {
- const wrapEl = annotPinsEl.querySelector('[data-annot-pin="' + idx + '"]');
- if (!wrapEl) return;
- // Strip any existing bubble (but keep the dot)
- wrapEl.querySelectorAll('div:not(:first-child)').forEach(n => n.remove());
- const input = document.createElement('input');
- input.type = 'text';
- input.placeholder = 'Note…';
- Object.assign(input.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- border: '1px solid ' + C.brand,
- outline: 'none', marginTop: '-2px',
- width: '220px', pointerEvents: 'auto',
- });
- const originalText = annotState.comments[idx].text || '';
- input.value = originalText;
- wrapEl.appendChild(input);
- annotEditing = { idx, input, wrapEl, originalText };
- input.addEventListener('keydown', onAnnotInputKey, true);
- input.addEventListener('blur', () => {
- // Fires on both focus-loss and programmatic blur; commit unless we
- // already handled it.
- if (annotEditing && annotEditing.input === input) finalizeEditingPin();
- });
- // Stop clicks/pointerdowns inside the input from bubbling to the overlay
- ['pointerdown', 'click'].forEach(ev => {
- input.addEventListener(ev, e => e.stopPropagation());
- });
- setTimeout(() => input.focus(), 0);
- }
-
- function onAnnotInputKey(e) {
- if (e.key === 'Enter') {
- e.preventDefault(); e.stopPropagation();
- finalizeEditingPin();
- } else if (e.key === 'Escape') {
- e.preventDefault(); e.stopPropagation();
- cancelEditingPin();
- } else {
- // Keep arrows / backspace from hitting global handlers
- e.stopPropagation();
- }
- }
-
- function finalizeEditingPin() {
- if (!annotEditing) return;
- const { idx, input } = annotEditing;
- const text = input.value.trim();
- annotEditing = null;
- if (text) annotState.comments[idx].text = text;
- else annotState.comments.splice(idx, 1);
- renderAllPins();
- }
-
- function cancelEditingPin() {
- if (!annotEditing) return;
- const { idx, originalText } = annotEditing;
- annotEditing = null;
- // If the pin had text before this edit, revert to it. If it was a
- // just-created empty pin, Escape removes it.
- if (originalText) {
- annotState.comments[idx].text = originalText;
- } else {
- annotState.comments.splice(idx, 1);
- }
- renderAllPins();
- }
-
- // Build a detached annotation subtree suitable for injection into the clone
- // modern-screenshot creates. Coordinates are element-local so this slots
- // straight into an element that's been made position:relative. Takes an
- // explicit snapshot so it works after annotState has been cleared.
- function buildAnnotationsForCapture(rect, snapshot) {
- const comments = snapshot ? snapshot.comments : annotState.comments;
- const strokes = snapshot ? snapshot.strokes : annotState.strokes;
- if (comments.length === 0 && strokes.length === 0) return null;
- const wrap = document.createElement('div');
- Object.assign(wrap.style, {
- position: 'absolute', top: '0', left: '0',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none', overflow: 'visible',
- });
- if (strokes.length > 0) {
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- svg.setAttribute('viewBox', '0 0 ' + rect.width + ' ' + rect.height);
- Object.assign(svg.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%', overflow: 'visible',
- });
- for (const s of strokes) {
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- path.setAttribute('stroke', C.brand);
- path.setAttribute('stroke-width', '3');
- path.setAttribute('stroke-linecap', 'round');
- path.setAttribute('stroke-linejoin', 'round');
- path.setAttribute('fill', 'none');
- path.setAttribute('d', pointsToPath(s.points));
- svg.appendChild(path);
- }
- wrap.appendChild(svg);
- }
- for (const c of comments) {
- // idx=-1 means non-interactive; pointerEvents stay off in the clone
- wrap.appendChild(buildPinElement(c, -1));
- }
- return wrap;
- }
-
- // ---------------------------------------------------------------------------
- // Element context extraction
- // ---------------------------------------------------------------------------
-
- function extractContext(el) {
- const cs = getComputedStyle(el);
- const r = el.getBoundingClientRect();
- const props = {};
- for (const sheet of document.styleSheets) {
- try {
- for (const rule of sheet.cssRules) {
- if (rule.style) for (let i = 0; i < rule.style.length; i++) {
- const p = rule.style[i];
- if (p.startsWith('--') && !props[p]) {
- const v = cs.getPropertyValue(p).trim();
- if (v) props[p] = v;
- }
- }
- }
- } catch { /* cross-origin */ }
- }
- return {
- tagName: el.tagName.toLowerCase(), id: el.id || null,
- classes: [...el.classList],
- textContent: (el.textContent || '').slice(0, 500),
- outerHTML: el.outerHTML.slice(0, 10000),
- computedStyles: {
- 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
- 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
- 'color': cs.color, 'background': cs.background,
- 'background-color': cs.backgroundColor,
- 'padding': cs.padding, 'margin': cs.margin,
- 'display': cs.display, 'position': cs.position,
- 'gap': cs.gap, 'border-radius': cs.borderRadius,
- 'box-shadow': cs.boxShadow,
- },
- cssCustomProperties: props,
- parentContext: el.parentElement
- ? '<' + el.parentElement.tagName.toLowerCase()
- + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
- + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
- + '>'
- : null,
- boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
- };
- }
-
- // ---------------------------------------------------------------------------
- // The Bar — one floating element, three modes
- // ---------------------------------------------------------------------------
-
- // Contextual-bar palette. Cached at init so every build*Row reads a
- // consistent set of colors; detectPageTheme runs once rather than on every
- // phase transition.
- let BP = null;
-
- // Bar shadow variants. The default projects down + subtle around. When
- // the Tune popover opens below the bar, a downward shadow lands on the
- // dark popover and reads as a bright ghost line. We swap to UP-only while
- // tune is open below so the popover's top edge is clean.
- const BAR_SHADOW_DEFAULT = '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_UP = '0 -4px 20px oklch(0% 0 0 / 0.08), 0 -1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_DOWN = BAR_SHADOW_DEFAULT;
-
- function initBar() {
- BP = barPaletteForTheme(detectPageTheme());
- barEl = document.createElement('div');
- barEl.id = PREFIX + '-bar';
- Object.assign(barEl.style, {
- position: 'fixed', zIndex: Z.bar,
- display: 'none', opacity: '0',
- transform: 'translateY(6px)',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- background: BP.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + BP.hairline,
- borderRadius: '10px',
- boxShadow: BAR_SHADOW_DEFAULT,
- transition: 'box-shadow 0.2s ease, opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- fontFamily: FONT, fontSize: '13px', color: BP.text,
- padding: '6px',
- maxWidth: '520px', minWidth: '320px',
- });
- document.body.appendChild(barEl);
- defangOutsideHandlers(barEl);
- }
-
- function positionBar() {
- if (!barEl || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- const barH = barEl.offsetHeight || 44;
- const barW = barEl.offsetWidth || 380;
- const GLOBAL_BAR_RESERVE = 64; // global bar height + bottom margin + breathing room
- const GAP = 8;
-
- // Prefer below the element; fall back to above; if neither fits (element
- // taller than viewport), pin to a stable viewport anchor so the bar
- // doesn't teleport between top and bottom as the user scrolls.
- let top;
- const belowTop = r.bottom + GAP;
- const aboveTop = r.top - barH - GAP;
- if (belowTop + barH + GAP <= window.innerHeight - GLOBAL_BAR_RESERVE) {
- top = belowTop;
- } else if (aboveTop >= GAP) {
- top = aboveTop;
- } else {
- top = window.innerHeight - barH - GLOBAL_BAR_RESERVE;
- }
-
- let left = r.left + (r.width - barW) / 2;
- if (left < GAP) left = GAP;
- if (left + barW > window.innerWidth - GAP) left = window.innerWidth - barW - GAP;
- Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
- }
-
- function showBar(mode) {
- barEl.innerHTML = '';
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- barEl.style.display = 'block';
- positionBar();
- requestAnimationFrame(() => {
- barEl.style.opacity = '1';
- barEl.style.transform = 'translateY(0)';
- });
- }
-
- function hideBar() {
- if (!barEl) return;
- barEl.style.opacity = '0';
- barEl.style.transform = 'translateY(6px)';
- setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
- hideActionPicker();
- closeTunePopover();
- }
-
- function updateBarContent(mode) {
- if (!barEl || barEl.style.display === 'none') return;
- barEl.innerHTML = '';
- // Reset bar styling to the theme-aware palette
- barEl.style.background = BP.surface;
- barEl.style.border = '1px solid ' + BP.hairline;
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- else if (mode === 'saving') barEl.appendChild(buildSavingRow());
- else if (mode === 'confirmed') {
- barEl.appendChild(buildConfirmedRow());
- barEl.style.background = 'oklch(95% 0.05 145)';
- barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
- }
- }
-
- // --- Configure row ---
-
- function buildConfigureRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
-
- // Action pill
- const pill = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '4px',
- padding: '5px 10px', borderRadius: '6px',
- background: BP.mark, color: BP.markText,
- fontFamily: FONT, fontSize: '12px', fontWeight: '500',
- border: 'none', cursor: 'pointer',
- transition: 'background 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap', flexShrink: '0',
- });
- pill.textContent = actionLabel() + ' \u25BE';
- pill.addEventListener('mouseenter', () => pill.style.background = BP.accent);
- pill.addEventListener('mouseleave', () => pill.style.background = BP.mark);
- pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
- pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
- pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
- row.appendChild(pill);
-
- // Freeform input. Focus state shows an accent-colored border only —
- // an earlier version tinted the background with `BP.accentSoft`, which
- // composited against the dark bar surface to a murky purple where the
- // browser's default placeholder gray was unreadable. Placeholder color
- // is set explicitly via a one-shot stylesheet keyed off this input's id
- // so it picks up the bar's `textDim` token in both themes.
- const input = document.createElement('input');
- input.id = PREFIX + '-input';
- input.type = 'text';
- input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
- Object.assign(input.style, {
- flex: '1', minWidth: '0',
- padding: '5px 8px', borderRadius: '6px',
- border: '1px solid transparent', background: 'transparent',
- fontFamily: FONT, fontSize: '12px', color: BP.text,
- outline: 'none',
- transition: 'border-color 0.15s ease',
- });
- if (!document.getElementById(PREFIX + '-input-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-input-style';
- s.textContent =
- '#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
- document.head.appendChild(s);
- }
- input.addEventListener('focus', () => {
- input.style.borderColor = BP.accent;
- });
- input.addEventListener('blur', () => {
- input.style.borderColor = 'transparent';
- });
- input.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
- if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; return; }
- // Let arrow keys pass through to the element picker when the input is empty
- if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && !input.value) return;
- e.stopPropagation();
- });
- row.appendChild(input);
-
- // Variant count toggle
- const count = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: MONO, fontSize: '11px', fontWeight: '600',
- color: BP.textDim, cursor: 'pointer',
- transition: 'color 0.12s ease, border-color 0.12s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- count.textContent = '\u00D7' + selectedCount;
- count.title = 'Variants: click to change';
- count.addEventListener('mouseenter', () => { count.style.color = BP.text; count.style.borderColor = BP.text; });
- count.addEventListener('mouseleave', () => { count.style.color = BP.textDim; count.style.borderColor = BP.hairline; });
- count.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
- count.textContent = '\u00D7' + selectedCount;
- });
- row.appendChild(count);
-
- // Go button
- const go = el('button', {
- padding: '5px 12px', borderRadius: '6px',
- border: 'none', background: BP.accent, color: BP.mark,
- fontFamily: FONT, fontSize: '12px', fontWeight: '600',
- cursor: 'pointer',
- transition: 'filter 0.12s ease, transform 0.1s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- go.textContent = 'Go \u2192';
- go.addEventListener('mouseenter', () => go.style.filter = 'brightness(1.1)');
- go.addEventListener('mouseleave', () => go.style.filter = 'none');
- go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
- go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
- go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
- row.appendChild(go);
-
- // Auto-focus input after a beat
- setTimeout(() => input.focus(), 60);
- return row;
- }
-
- // --- Generating row ---
-
- function buildGeneratingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 4px',
- });
-
- // Action label
- const label = el('span', {
- fontWeight: '600', fontSize: '12px', color: BP.text,
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- label.textContent = actionLabel();
- row.appendChild(label);
-
- // Dots
- row.appendChild(buildDots(false));
-
- // Status
- const status = el('span', {
- fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',
- marginLeft: 'auto',
- });
- // Variants currently arrive atomically in a single file edit, so a
- // per-variant counter would lie. Say what's true.
- status.textContent = arrivedVariants < expectedVariants
- ? 'Generating ' + expectedVariants + ' variants...'
- : 'Done';
- row.appendChild(status);
-
- return row;
- }
-
- // --- Cycling row ---
-
- const TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';
-
- function buildCyclingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '6px',
- padding: '1px 2px',
- });
-
- // Prev
- const prev = navBtn('\u2190');
- prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
- if (visibleVariant <= 1) prev.style.opacity = '0.3';
- row.appendChild(prev);
-
- // Dots (clickable)
- row.appendChild(buildDots(true));
-
- // Counter
- const counter = el('span', {
- fontFamily: MONO, fontSize: '11px', fontWeight: '500',
- color: BP.textDim, minWidth: '24px', textAlign: 'center',
- });
- counter.textContent = visibleVariant + '/' + arrivedVariants;
- row.appendChild(counter);
-
- // Next
- const next = navBtn('\u2192');
- next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
- if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
- row.appendChild(next);
-
- // Tune chip — only when the visible variant exposes params
- const visParams = parseVariantParams(getVisibleVariantEl());
- const hasParams = visParams.length > 0;
- if (hasParams) {
- const tune = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '6px',
- padding: '4px 10px', borderRadius: '5px',
- border: '1px solid transparent',
- background: tuneOpen ? BP.accentSoft : 'transparent',
- color: tuneOpen ? BP.accent : BP.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'color 0.12s ease, background 0.12s ease',
- whiteSpace: 'nowrap',
- });
- tune.innerHTML = TUNE_ICON_SVG;
- const tuneLabel = document.createElement('span');
- tuneLabel.textContent = 'Tune';
- tune.appendChild(tuneLabel);
- const tuneBadge = document.createElement('span');
- Object.assign(tuneBadge.style, {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- minWidth: '16px', height: '16px', padding: '0 4px',
- borderRadius: '999px',
- background: tuneOpen ? C.brand : BP.hairline,
- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',
- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',
- lineHeight: '1',
- boxSizing: 'border-box',
- });
- tuneBadge.textContent = String(visParams.length);
- tune.appendChild(tuneBadge);
- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';
- tune.addEventListener('mouseenter', () => {
- if (!tuneOpen) tune.style.background = BP.accentSoft;
- });
- tune.addEventListener('mouseleave', () => {
- if (!tuneOpen) tune.style.background = 'transparent';
- });
- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });
- tune.dataset.iceqTune = '1';
- row.appendChild(tune);
- }
-
- // Spacer
- row.appendChild(el('div', { flex: '1' }));
-
- // Accept — primary action, uses the site's saturated brand magenta
- // with paper-white text, not the theme-muted BP.accent.
- const accept = el('button', {
- padding: '5px 14px', borderRadius: '5px',
- border: 'none', background: C.brand, color: 'oklch(98% 0 0)',
- fontFamily: FONT, fontSize: '11px', fontWeight: '600',
- cursor: 'pointer', transition: 'filter 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap',
- });
- accept.textContent = '\u2713 Accept';
- accept.addEventListener('mouseenter', () => accept.style.filter = 'brightness(1.08)');
- accept.addEventListener('mouseleave', () => accept.style.filter = 'none');
- accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');
- accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');
- accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
- row.appendChild(accept);
-
- // Discard
- const discard = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: FONT, fontSize: '11px', color: BP.textDim,
- cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
- });
- discard.textContent = '\u2715';
- discard.title = 'Discard all variants';
- discard.addEventListener('mouseenter', () => { discard.style.color = BP.text; discard.style.borderColor = BP.text; });
- discard.addEventListener('mouseleave', () => { discard.style.color = BP.textDim; discard.style.borderColor = BP.hairline; });
- discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
- row.appendChild(discard);
-
- return row;
- }
-
- // --- Shared UI builders ---
-
- // --- Saving row (waiting for agent to process accept/discard) ---
-
- function buildSavingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const spinner = el('div', {
- width: '14px', height: '14px', borderRadius: '50%',
- border: '2px solid ' + BP.hairline,
- borderTopColor: BP.accent,
- animation: 'impeccable-spin 0.6s linear infinite',
- flexShrink: '0',
- });
- row.appendChild(spinner);
- const label = el('span', {
- fontSize: '12px', color: BP.textDim, fontWeight: '500',
- });
- label.textContent = 'Applying variant...';
- row.appendChild(label);
-
- // Inject the keyframes if not already present
- if (!document.getElementById(PREFIX + '-keyframes')) {
- const style = document.createElement('style');
- style.id = PREFIX + '-keyframes';
- style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
- document.head.appendChild(style);
- }
- return row;
- }
-
- // --- Confirmed row (green success, auto-dismisses) ---
-
- function buildConfirmedRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const check = el('span', {
- fontSize: '15px', lineHeight: '1', flexShrink: '0',
- color: 'oklch(45% 0.15 145)',
- });
- check.textContent = '\u2713';
- row.appendChild(check);
- const label = el('span', {
- fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
- });
- label.textContent = 'Variant applied';
- row.appendChild(label);
- return row;
- }
-
- // --- Shared UI builders ---
-
- function buildDots(clickable) {
- const container = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
- for (let i = 1; i <= expectedVariants; i++) {
- const arrived = i <= arrivedVariants;
- const active = i === visibleVariant;
- // active: solid site-brand magenta dot. arrived+inactive: muted neutral.
- // pending (not yet arrived): faint outline ring. No borders on arrived
- // dots — the previous "accent ring + ash fill" combo read as noisy
- // magenta chips, especially when all variants had arrived and every
- // dot wore an accent ring.
- const dotBg = active ? C.brand
- : arrived ? BP.textDim
- : 'transparent';
- const dotBorder = arrived ? 'none' : '1.5px solid ' + BP.hairline;
- const dot = el('div', {
- width: active ? '8px' : '6px',
- height: active ? '8px' : '6px',
- borderRadius: '50%',
- background: dotBg,
- border: dotBorder,
- boxSizing: 'border-box',
- transition: 'all 0.2s ' + EASE,
- cursor: (clickable && arrived) ? 'pointer' : 'default',
- transform: arrived ? 'scale(1)' : 'scale(0.85)',
- opacity: arrived ? (active ? '1' : '0.6') : '0.4',
- });
- if (clickable && arrived) {
- const idx = i;
- dot.addEventListener('click', (e) => {
- e.stopPropagation();
- visibleVariant = idx;
- showVariantInDOM(currentSessionId, idx);
- updateSelectedElement();
- updateBarContent('cycling');
- });
- }
- container.appendChild(dot);
- }
- return container;
- }
-
- function navBtn(text) {
- const b = el('button', {
- width: '26px', height: '26px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- color: BP.text, fontFamily: FONT, fontSize: '13px',
- cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
- transition: 'border-color 0.12s ease, background 0.12s ease',
- padding: '0', lineHeight: '1',
- });
- b.textContent = text;
- b.addEventListener('mouseenter', () => { b.style.borderColor = BP.text; });
- b.addEventListener('mouseleave', () => { b.style.borderColor = BP.hairline; });
- return b;
- }
-
- function actionLabel() {
- const a = ACTIONS.find(a => a.value === selectedAction);
- return a ? a.label : 'Freeform';
- }
-
- function el(tag, styles) {
- const e = document.createElement(tag);
- if (styles) Object.assign(e.style, styles);
- return e;
- }
-
- // ---------------------------------------------------------------------------
- // Action picker popover
- // ---------------------------------------------------------------------------
-
- function initActionPicker() {
- const P = barPaletteForTheme(detectPageTheme());
- pickerEl = document.createElement('div');
- pickerEl.id = PREFIX + '-picker';
- Object.assign(pickerEl.style, {
- position: 'fixed', zIndex: Z.picker,
- display: 'none', opacity: '0',
- transform: 'scale(0.96) translateY(4px)',
- transformOrigin: 'bottom left',
- transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
- background: P.surface,
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
- padding: '6px',
- fontFamily: FONT,
- backdropFilter: 'blur(10px)',
- WebkitBackdropFilter: 'blur(10px)',
- });
-
- // Build the chip grid
- const grid = el('div', {
- display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
- });
-
- ACTIONS.forEach(action => {
- const chip = el('button', {
- display: 'flex', flexDirection: 'column', alignItems: 'center',
- gap: '4px',
- padding: '8px 6px', borderRadius: '6px',
- border: 'none',
- background: action.value === selectedAction ? P.accentSoft : 'transparent',
- color: action.value === selectedAction ? P.accent : P.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.1s ease, color 0.1s ease',
- textAlign: 'center', whiteSpace: 'nowrap',
- });
- const iconWrap = el('span', {
- display: 'flex', alignItems: 'center', justifyContent: 'center',
- height: '20px', opacity: '0.9',
- });
- iconWrap.innerHTML = ICONS[action.value] || '';
- const labelEl = el('span', { lineHeight: '1' });
- labelEl.textContent = action.label;
- chip.appendChild(iconWrap);
- chip.appendChild(labelEl);
- chip.dataset.action = action.value;
- chip.addEventListener('mouseenter', () => {
- if (action.value !== selectedAction) chip.style.background = P.accentSoft;
- });
- chip.addEventListener('mouseleave', () => {
- chip.style.background = action.value === selectedAction ? P.accentSoft : 'transparent';
- });
- chip.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedAction = action.value;
- hideActionPicker();
- updateBarContent('configure');
- });
- grid.appendChild(chip);
- });
-
- pickerEl.appendChild(grid);
- document.body.appendChild(pickerEl);
- defangOutsideHandlers(pickerEl);
-
- // Cache the palette on the picker so toggleActionPicker's state refresh
- // uses the same theme-aware colors when it repaints chips.
- pickerEl.__iceq_palette = P;
- }
-
- function toggleActionPicker() {
- if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
- // Rebuild chips to reflect current selection
- const P = pickerEl.__iceq_palette || barPaletteForTheme(detectPageTheme());
- pickerEl.querySelectorAll('button').forEach(chip => {
- const isActive = chip.dataset.action === selectedAction;
- chip.style.background = isActive ? P.accentSoft : 'transparent';
- chip.style.color = isActive ? P.accent : P.text;
- });
- // Position above the bar
- const barRect = barEl.getBoundingClientRect();
- const pickerH = 170; // approximate; grows with icon + label rows
- let top = barRect.top - pickerH - 6;
- if (top < 8) top = barRect.bottom + 6;
- Object.assign(pickerEl.style, {
- top: top + 'px', left: barRect.left + 'px',
- display: 'block',
- });
- requestAnimationFrame(() => {
- pickerEl.style.opacity = '1';
- pickerEl.style.transform = 'scale(1) translateY(0)';
- });
- }
-
- function hideActionPicker() {
- if (!pickerEl) return;
- pickerEl.style.opacity = '0';
- pickerEl.style.transform = 'scale(0.96) translateY(4px)';
- setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
- }
-
- // ---------------------------------------------------------------------------
- // Params panel (per-variant coarse controls)
- //
- // Variants may declare a parameter manifest via a JSON attribute on the
- // variant wrapper:
- //
- // <div data-impeccable-variant="1"
- // data-impeccable-params='[{"id":"density","kind":"steps",...}]'>
- //
- // The panel docks to the right edge of the outline during CYCLING and
- // exposes 2-5 coarse knobs. Values apply to the variant wrapper so scoped
- // CSS can respond instantly without regeneration:
- //
- // range / numeric toggle → CSS var (`--p-<id>`) used via var(--p-foo, N)
- // steps / boolean toggle → data-p-<id> attribute used via :scope[data-p-foo="..."]
- //
- // On variant switch, values reset to that variant's declared defaults.
- // On accept, current values are sent in the event payload so the agent
- // can bake them into the source-file write.
- // ---------------------------------------------------------------------------
-
- let paramsPanelEl = null; // outer wrapper (overflow:hidden, clips the slide)
- let paramsPanelInner = null; // translating content (carries bg, padding, knobs)
- let paramsPanelBody = null; // grid holding the knob cells
- let paramsCurrentValues = {}; // {paramId: value} — mirror of the visible variant's live values
- let tuneOpen = false; // whether the Tune popover is open right now
-
- // Theme-aware Tune popover. Appears as a drawer that slides out from the
- // contextual bar's bar-facing edge (below if the bar sits below the
- // element, above otherwise). Same width as the bar. Auto-wraps to extra
- // rows when the knobs exceed one row. The bar's border-radius on the
- // popover side goes flat while open so the two shapes read as one.
- let paramsPanelPalette = null;
-
- function initParamsPanel() {
- paramsPanelPalette = barPaletteForTheme(detectPageTheme());
- const P = paramsPanelPalette;
-
- // Single element, always in the DOM. The slide animation is a CSS mask
- // with mask-size growing from 0% to 100% along the bar-facing axis — no
- // display toggle, no opacity toggle, no transform trickery. The mask
- // hides everything initially; as it grows, content is revealed from
- // the bar edge outward.
- paramsPanelEl = document.createElement('div');
- paramsPanelEl.id = PREFIX + '-params-panel';
- Object.assign(paramsPanelEl.style, {
- position: 'fixed', zIndex: String(Z.bar - 1),
- background: P.surfaceDeep,
- color: P.text,
- fontFamily: FONT,
- padding: '14px 18px',
- boxSizing: 'border-box',
- borderRadius: '0 0 10px 10px',
- pointerEvents: 'none',
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
-
- // clip-path is the same conceptual reveal as mask but with rock-solid
- // transition support across engines. Closed state clips from the far
- // edge; open = inset(0) shows everything.
- clipPath: 'inset(0 0 100% 0)',
- transition: 'clip-path 0.44s ' + EASE,
-
- // Park off-screen until positionParamsPanel places it. These are NOT
- // in the transition list, so they snap instantly — no fly-in from the
- // top-left when first shown.
- top: '-9999px', left: '-9999px', width: '0',
- });
-
- paramsPanelBody = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
- gap: '12px 16px',
- });
-
- paramsPanelEl.appendChild(paramsPanelBody);
- document.body.appendChild(paramsPanelEl);
- // Don't override pointer-events: the panel toggles between 'none' (closed,
- // click-through) and 'auto' (open) on its own. Just silence the host's
- // outside-interaction listeners while the panel is open.
- defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
- paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
- }
-
- function getVisibleVariantEl() {
- if (!currentSessionId) return null;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return null;
- return wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"]');
- }
-
- function parseVariantParams(variantEl) {
- if (!variantEl) return [];
- const raw = variantEl.getAttribute('data-impeccable-params');
- if (!raw) return [];
- try {
- const parsed = JSON.parse(raw);
- return Array.isArray(parsed) ? parsed : [];
- } catch (err) {
- console.warn('[impeccable] Invalid data-impeccable-params JSON:', err.message);
- return [];
- }
- }
-
- function applyParamValue(variantEl, param, value) {
- if (!variantEl) return;
- const attr = 'data-p-' + param.id;
- if (param.kind === 'range') {
- variantEl.style.setProperty('--p-' + param.id, String(value));
- } else if (param.kind === 'toggle') {
- const on = !!value;
- variantEl.style.setProperty('--p-' + param.id, on ? '1' : '0');
- if (on) variantEl.setAttribute(attr, 'on');
- else variantEl.removeAttribute(attr);
- } else if (param.kind === 'steps') {
- variantEl.setAttribute(attr, String(value));
- }
- }
-
- function applyParamDefaults(variantEl, params) {
- paramsCurrentValues = {};
- for (const p of params) {
- paramsCurrentValues[p.id] = p.default;
- applyParamValue(variantEl, p, p.default);
- }
- }
-
- function formatRangeValue(input) {
- const max = parseFloat(input.max), min = parseFloat(input.min);
- const v = parseFloat(input.value);
- if (!isFinite(v)) return input.value;
- return (max - min) <= 2 ? v.toFixed(2) : String(Math.round(v));
- }
-
- function buildParamsPanel(variantEl, params) {
- const P = paramsPanelPalette || barPaletteForTheme(detectPageTheme());
- paramsPanelBody.innerHTML = '';
- for (const p of params) {
- const row = el('div', { display: 'flex', flexDirection: 'column', gap: '6px' });
- const labelRow = el('div', {
- display: 'flex', justifyContent: 'space-between',
- alignItems: 'baseline', gap: '8px',
- });
- const lbl = el('span', {
- fontSize: '10.5px', fontWeight: '600', color: P.text,
- letterSpacing: '0.03em',
- });
- lbl.textContent = p.label || p.id;
- labelRow.appendChild(lbl);
- const readout = el('span', {
- fontSize: '10.5px', color: P.textDim,
- fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
- });
- labelRow.appendChild(readout);
- row.appendChild(labelRow);
-
- if (p.kind === 'range') {
- const input = document.createElement('input');
- input.type = 'range';
- input.min = String(p.min != null ? p.min : 0);
- input.max = String(p.max != null ? p.max : 1);
- input.step = String(p.step != null ? p.step : 0.05);
- input.value = String(p.default);
- Object.assign(input.style, {
- width: '100%', accentColor: C.brand, cursor: 'pointer',
- });
- readout.textContent = formatRangeValue(input);
- input.addEventListener('input', (e) => {
- e.stopPropagation();
- const v = parseFloat(input.value);
- paramsCurrentValues[p.id] = v;
- readout.textContent = formatRangeValue(input);
- applyParamValue(variantEl, p, v);
- queueCheckpoint('param_changed');
- });
- row.appendChild(input);
- } else if (p.kind === 'toggle') {
- const initial = !!p.default;
- readout.textContent = initial ? 'On' : 'Off';
- const track = el('button', {
- position: 'relative', width: '36px', height: '20px',
- borderRadius: '10px', border: 'none', padding: '0',
- cursor: 'pointer',
- background: initial ? C.brand : P.hairline,
- transition: 'background 0.15s ease',
- alignSelf: 'flex-start',
- });
- const knob = el('span', {
- position: 'absolute', top: '2px',
- left: initial ? '18px' : '2px',
- width: '16px', height: '16px', borderRadius: '50%',
- background: 'oklch(98% 0 0)',
- transition: 'left 0.18s ' + EASE,
- boxShadow: '0 1px 2px oklch(0% 0 0 / 0.2)',
- });
- track.appendChild(knob);
- track.addEventListener('click', (e) => {
- e.stopPropagation();
- const next = !paramsCurrentValues[p.id];
- paramsCurrentValues[p.id] = next;
- track.style.background = next ? C.brand : P.hairline;
- knob.style.left = next ? '18px' : '2px';
- readout.textContent = next ? 'On' : 'Off';
- applyParamValue(variantEl, p, next);
- queueCheckpoint('param_changed');
- });
- row.appendChild(track);
- } else if (p.kind === 'steps') {
- const opts = (p.options || []).map(o =>
- typeof o === 'string' ? { value: o, label: o } : o
- );
- const activeOpt = opts.find(o => o.value === p.default) || opts[0];
- readout.textContent = activeOpt ? activeOpt.label : String(p.default);
- const segRow = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(' + opts.length + ', 1fr)',
- gap: '1px', padding: '2px',
- background: P.hairline, borderRadius: '5px',
- });
- const segBtns = [];
- opts.forEach(o => {
- const active = o.value === p.default;
- const b = el('button', {
- padding: '5px 4px', border: 'none', borderRadius: '3px',
- background: active ? C.brand : 'transparent',
- color: active ? 'oklch(98% 0 0)' : P.text,
- fontFamily: FONT, fontSize: '10.5px', fontWeight: '500',
- cursor: 'pointer', whiteSpace: 'nowrap',
- transition: 'background 0.1s ease, color 0.1s ease',
- });
- b.textContent = o.label;
- b.addEventListener('click', (e) => {
- e.stopPropagation();
- paramsCurrentValues[p.id] = o.value;
- readout.textContent = o.label;
- segBtns.forEach(({ btn, val }) => {
- const on = val === o.value;
- btn.style.background = on ? C.brand : 'transparent';
- btn.style.color = on ? 'oklch(98% 0 0)' : P.text;
- });
- applyParamValue(variantEl, p, o.value);
- queueCheckpoint('param_changed');
- });
- segRow.appendChild(b);
- segBtns.push({ btn: b, val: o.value });
- });
- row.appendChild(segRow);
- }
-
- paramsPanelBody.appendChild(row);
- }
- }
-
- // Decide which way the popover opens: away from the picked element. If the
- // bar landed below the element, popover slides DOWN from the bar's bottom.
- // If the bar landed above, popover slides UP from the bar's top.
- function popoverDirection() {
- if (!barEl || !selectedElement) return 'below';
- const br = barEl.getBoundingClientRect();
- const er = selectedElement.getBoundingClientRect();
- return br.top >= er.bottom - 4 ? 'below' : 'above';
- }
-
- // The popover overlaps the bar by OVERLAP px on the bar-facing side. With
- // popover z-index below bar, that overlap sits behind bar (invisible) and
- // reinforces the "tucked behind" feel. Padding compensates so the real
- // content starts flush with bar's outer edge.
- const TUNE_OVERLAP = 6;
-
- // Closed clip-path depends on direction: for 'below' clip from the far
- // (bottom) edge so the reveal grows downward from the bar; for 'above'
- // clip from the top edge so the reveal grows upward from the bar.
- function closedClipPath(direction) {
- return direction === 'below' ? 'inset(0 0 100% 0)' : 'inset(100% 0 0 0)';
- }
-
- function setClipPath(value, withTransition) {
- const saved = paramsPanelEl.style.transition;
- if (!withTransition) paramsPanelEl.style.transition = 'none';
- paramsPanelEl.style.clipPath = value;
- if (!withTransition) {
- void paramsPanelEl.offsetHeight;
- paramsPanelEl.style.transition = saved;
- }
- }
-
- function positionParamsPanel() {
- if (!paramsPanelEl || !barEl || barEl.style.display === 'none') return;
- const br = barEl.getBoundingClientRect();
- const direction = popoverDirection();
- const prevDirection = paramsPanelEl.dataset.tuneDirection;
-
- // top/left/width are NOT in the transition list, so they snap instantly.
- paramsPanelEl.style.left = br.left + 'px';
- paramsPanelEl.style.width = br.width + 'px';
-
- if (direction === 'below') {
- paramsPanelEl.style.top = (br.bottom - TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '0 0 10px 10px';
- paramsPanelEl.style.paddingTop = (14 + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.paddingBottom = '14px';
- } else {
- const ih = paramsPanelEl.offsetHeight || 80;
- paramsPanelEl.style.top = (br.top - ih + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '10px 10px 0 0';
- paramsPanelEl.style.paddingTop = '14px';
- paramsPanelEl.style.paddingBottom = (14 + TUNE_OVERLAP) + 'px';
- }
- paramsPanelEl.dataset.tuneDirection = direction;
-
- // If currently closed and direction flipped (or first-time setup),
- // snap the clip-path to the new direction's closed pose without
- // transitioning (so the clip doesn't slide across the element).
- if (!tuneOpen && (!prevDirection || prevDirection !== direction)) {
- setClipPath(closedClipPath(direction), false);
- }
- }
-
- function showParamsPanel() {
- if (!paramsPanelEl) return;
- positionParamsPanel();
- paramsPanelEl.style.pointerEvents = 'auto';
- // rAF so the positioning paint commits before the transition fires.
- requestAnimationFrame(() => {
- setClipPath('inset(0 0 0 0)', true);
- });
- }
-
- function hideParamsPanel() {
- if (!paramsPanelEl) return;
- paramsPanelEl.style.pointerEvents = 'none';
- const direction = paramsPanelEl.dataset.tuneDirection || 'below';
- setClipPath(closedClipPath(direction), true);
- }
-
- // Build/rebuild the panel's contents for the current variant AND apply
- // its defaults to the variant wrapper (so scoped CSS responds even before
- // the user opens the popover). Visibility is governed by tuneOpen.
- function refreshParamsPanel() {
- if (state !== 'CYCLING') {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- if (tuneOpen) {
- // If already visible (variant cycled while open), refresh in place
- // instead of re-running the clip-path animation.
- const alreadyVisible = paramsPanelEl.style.display === 'block'
- && paramsPanelEl.style.opacity === '1';
- if (alreadyVisible) positionParamsPanel();
- else showParamsPanel();
- } else {
- hideParamsPanel();
- }
- }
-
- function toggleTunePopover() {
- if (tuneOpen) { closeTunePopover(); return; }
- openTunePopover();
- }
-
- function openTunePopover() {
- if (state !== 'CYCLING') return;
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) return;
- // Build fresh to ensure the current variant's controls are shown.
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- tuneOpen = true;
- showParamsPanel();
- // Kill the bar's shadow on the popover-facing side so the dark popover
- // doesn't pick up a bright glow line.
- if (barEl) {
- const direction = paramsPanelEl?.dataset.tuneDirection || 'below';
- barEl.style.boxShadow = direction === 'below' ? BAR_SHADOW_UP : BAR_SHADOW_DOWN;
- }
- // Re-render the bar so the Tune chip picks up the active styling.
- updateBarContent('cycling');
- }
-
- function closeTunePopover() {
- tuneOpen = false;
- hideParamsPanel();
- if (barEl) barEl.style.boxShadow = BAR_SHADOW_DEFAULT;
- if (barEl && barEl.style.display !== 'none' && state === 'CYCLING') {
- updateBarContent('cycling');
- }
- }
-
- // ---------------------------------------------------------------------------
- // Variant cycling in DOM
- // ---------------------------------------------------------------------------
-
- function showVariantInDOM(sessionId, num) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
- for (const child of wrapper.children) {
- const v = child.dataset ? child.dataset.impeccableVariant : null;
- if (!v) continue;
- child.style.display = (v === String(num)) ? '' : 'none';
- }
- // Unconditional refresh — covers first-reveal (no-op if state isn't
- // CYCLING yet, the subsequent CYCLING transition triggers its own
- // refresh) and every cycle step.
- refreshParamsPanel();
- }
-
- /**
- * No-HMR fallback: fetch the raw source file from the live server,
- * parse it, extract the variant wrapper, and inject it into the live DOM.
- * This works even when the dev server caches HTML (Bun, static servers).
- */
- function injectVariantsFromSource(filePath, sessionId) {
- const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
- fetch(url)
- .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
- .then(html => {
- // Parse the raw source HTML
- const parser = new DOMParser();
- const doc = parser.parseFromString(html, 'text/html');
- const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!srcWrapper) {
- console.error('[impeccable] Variant wrapper not found in source file.');
- return;
- }
-
- // Find the original element in the live DOM.
- // The original is inside the wrapper in the source. We find the
- // corresponding element in the live DOM by matching the first child's
- // tag + classes from the original snapshot.
- const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
- if (!origContent) return;
-
- const tag = origContent.tagName.toLowerCase();
- const cls = origContent.className;
- let liveEl = null;
- if (origContent.id) {
- liveEl = document.getElementById(origContent.id);
- } else if (cls) {
- // Find by tag + exact class match
- const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
- for (const c of candidates) {
- if (c.className === cls && !own(c)) { liveEl = c; break; }
- }
- }
-
- if (!liveEl) {
- console.error('[impeccable] Could not find original element in live DOM.');
- return;
- }
-
- const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;
-
- // Replace the live element with the full wrapper from source
- const wrapper = srcWrapper.cloneNode(true);
- liveEl.parentElement.replaceChild(wrapper, liveEl);
-
- // Update state: count variants, preserving the user's current variant
- // when a late HMR/source reinjection lands after they have cycled.
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants
- ? previousVisibleVariant
- : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);
- showVariantInDOM(sessionId, visibleVariant);
-
- // Update selectedElement to the visible variant's content
- selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;
-
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- saveSession();
- console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
- })
- .catch(err => {
- console.error('[impeccable] Failed to fetch source:', err);
- showToast('Could not load variants. Try refreshing the page.', 5000);
- });
- }
-
- function cycleVariant(dir) {
- const next = visibleVariant + dir;
- if (next < 1 || next > arrivedVariants) return;
- visibleVariant = next;
- showVariantInDOM(currentSessionId, next); // calls refreshParamsPanel itself
- updateSelectedElement();
- updateBarContent('cycling');
- saveSession();
- queueCheckpoint('variant_changed');
- }
-
- function updateSelectedElement() {
- if (!currentSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return;
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- function readVisibleVariantFromDOM(sessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return 0;
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- for (const variant of variants) {
- if (variant.style.display === 'none') continue;
- const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);
- if (idx > 0) return idx;
- }
- return 0;
- }
-
- // Resolve the element that represents the variant's visible content.
- // Contract: each variant div should contain exactly one top-level element
- // (the full replacement). In practice a model may ship loose siblings or
- // lead with <style>/<script>. Be defensive: skip non-visual elements, and
- // if the variant has multiple element children, use the variant div itself
- // (it wraps all of them and gets correct bounds).
- function pickVariantContent(wrapper, index) {
- if (!wrapper) return null;
- const variantDiv = wrapper.querySelector('[data-impeccable-variant="' + index + '"]');
- if (!variantDiv) return null;
- const NON_VISUAL = new Set(['STYLE', 'SCRIPT', 'LINK', 'META', 'TEMPLATE']);
- const visual = [];
- for (const child of variantDiv.children) {
- if (!NON_VISUAL.has(child.tagName)) visual.push(child);
- }
- if (visual.length === 1) return visual[0];
- return variantDiv;
- }
-
- // Hold window.scrollY at a fixed value across DOM mutations inside the
- // session's wrapper (HMR patches, variant inserts, cycle swaps).
- function startScrollLock(sessionId, initialTargetY) {
- stopScrollLock();
- scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)
- ? initialTargetY
- : window.scrollY;
- console.log('[impeccable.scroll] startScrollLock', { sessionId, scrollY: window.scrollY, targetY: scrollLockTargetY, initialOverride: initialTargetY });
-
- try { history.scrollRestoration = 'manual'; } catch {}
-
- const prevHtmlAnchor = document.documentElement.style.overflowAnchor;
- const prevBodyAnchor = document.body.style.overflowAnchor;
- document.documentElement.style.overflowAnchor = 'none';
- document.body.style.overflowAnchor = 'none';
-
- const correct = (why) => {
- scrollLockRaf = null;
- if (scrollLockTargetY == null) return;
- const before = window.scrollY;
- const delta = before - scrollLockTargetY;
- if (Math.abs(delta) < 0.5) {
- console.log('[impeccable.scroll] correct noop', { why, scrollY: before, targetY: scrollLockTargetY });
- return;
- }
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] corrected', { why, from: before, to: scrollLockTargetY, delta, nowAt: window.scrollY });
- };
- const schedule = (why) => {
- if (scrollLockRaf != null) return;
- scrollLockRaf = requestAnimationFrame(() => correct(why));
- };
-
- scrollLockObserver = new MutationObserver((mutations) => {
- for (const m of mutations) {
- if (m.target?.closest?.('[data-impeccable-variants="' + sessionId + '"]')) {
- const childAdds = Array.from(m.addedNodes).map(n => n.nodeType === 1 ? (n.tagName + (n.dataset?.impeccableVariant ? ('[variant=' + n.dataset.impeccableVariant + ']') : '')) : n.nodeType).join(',');
- console.log('[impeccable.scroll] mutation inside wrapper', { type: m.type, target: m.target?.tagName, adds: childAdds, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('mutation-in-wrapper');
- return;
- }
- for (const n of m.addedNodes) {
- if (n.nodeType === 1 && (n.matches?.('[data-impeccable-variants="' + sessionId + '"]') || n.querySelector?.('[data-impeccable-variants="' + sessionId + '"]'))) {
- console.log('[impeccable.scroll] wrapper node added', { tag: n.tagName, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('wrapper-added');
- return;
- }
- }
- }
- });
- scrollLockObserver.observe(document.body, { childList: true, subtree: true });
-
- scrollLockAbort = new AbortController();
- scrollLockAbort.signal.addEventListener('abort', () => {
- document.documentElement.style.overflowAnchor = prevHtmlAnchor;
- document.body.style.overflowAnchor = prevBodyAnchor;
- }, { once: true });
- const sig = { signal: scrollLockAbort.signal };
- // Track whether the most recent scroll came from a user gesture. We
- // gate user-scroll re-anchoring on this flag so programmatic smooth
- // scrolls (browser reload-restore, scrollIntoView from other scripts)
- // don't accidentally update our target.
- let userGestureAt = 0;
- const USER_GESTURE_WINDOW_MS = 250;
-
- const reanchor = (why) => {
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- const prevTarget = scrollLockTargetY;
- scrollLockTargetY = window.scrollY;
- writeScrollY(scrollLockTargetY);
- console.log('[impeccable.scroll] reanchor', { why, prevTarget, newTarget: scrollLockTargetY });
- };
- const markGesture = (why) => {
- userGestureAt = performance.now();
- reanchor(why);
- };
- window.addEventListener('wheel', () => markGesture('wheel'), { passive: true, ...sig });
- window.addEventListener('touchstart', () => markGesture('touchstart'), { passive: true, ...sig });
- window.addEventListener('touchmove', () => markGesture('touchmove'), { passive: true, ...sig });
- window.addEventListener('keydown', (e) => {
- if (['PageDown', 'PageUp', ' ', 'End', 'Home', 'ArrowDown', 'ArrowUp'].includes(e.key)) markGesture('key:' + e.key);
- }, sig);
-
- // Correct on EVERY scroll event: whether it's the browser's
- // post-reload animated restore or some other script calling
- // scrollIntoView, we want to snap back immediately. Only skip if a
- // user gesture fired in the last 250ms.
- let lastLoggedScrollY = window.scrollY;
- window.addEventListener('scroll', () => {
- const now = window.scrollY;
- if (Math.abs(now - lastLoggedScrollY) > 5) {
- console.log('[impeccable.scroll] scroll event', { from: lastLoggedScrollY, to: now, targetY: scrollLockTargetY });
- lastLoggedScrollY = now;
- }
- if (scrollLockTargetY == null) return;
- if (performance.now() - userGestureAt < USER_GESTURE_WINDOW_MS) return;
- if (Math.abs(now - scrollLockTargetY) < 0.5) return;
- console.log('[impeccable.scroll] scroll-event snap', { from: now, to: scrollLockTargetY });
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- }, { passive: true, ...sig });
-
- // Apply target synchronously, not via rAF — racing the browser's
- // restore or a smooth-scroll animation means we want to win now.
- if (Math.abs(window.scrollY - scrollLockTargetY) > 0.5) {
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] startScrollLock initial apply', { to: scrollLockTargetY });
- }
- }
-
- function stopScrollLock() {
- if (scrollLockObserver) { scrollLockObserver.disconnect(); scrollLockObserver = null; }
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }
- scrollLockTargetY = null;
- // NOTE: do NOT clear the persistent scroll key here. startScrollLock
- // calls us as a reset, and clearing the key would nuke the Go-time
- // scrollY that the next resume needs to read.
- }
-
- // ---------------------------------------------------------------------------
- // MutationObserver for progressive variant reveal
- // ---------------------------------------------------------------------------
-
- function startVariantObserver(sessionId) {
- let updating = false; // re-entrancy guard
-
- const obs = new MutationObserver((mutations) => {
- if (updating) return;
-
- // Only react to mutations that add nodes with data-impeccable-variant,
- // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
- let dominated = false;
- for (const m of mutations) {
- if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
- for (const n of m.addedNodes) {
- if (n.nodeType !== 1) continue;
- // Direct hit: the added node itself is the wrapper or a variant.
- if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
- dominated = true; break;
- }
- // Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
- // a whole subtree where the wrapper is a descendant of the added
- // node. Without this check, the observer ignores those mutations
- // and the session stays in GENERATING forever.
- if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
- dominated = true; break;
- }
- }
- if (dominated) break;
- }
- if (!dominated) return;
-
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
-
- // Re-anchor selectedElement if it was detached by live-wrap's HMR swap.
- // Without this, the shader / highlight / bar track a zero-rect phantom
- // and the overlay appears frozen.
- if (selectedElement && !document.body.contains(selectedElement)) {
- selectedElement = pickVariantContent(wrapper, 'original') || wrapper;
- }
-
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- const count = variants.length;
-
- // Nothing new
- if (count <= arrivedVariants) return;
-
- updating = true;
- arrivedVariants = count;
- if (visibleVariant === 0 && arrivedVariants > 0) {
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;
- showVariantInDOM(sessionId, visibleVariant);
- // showVariantInDOM hid the original (display:none); if we were still
- // anchored to the original's content, its boundingRect is now zero
- // and the bar snaps to (0,0). Re-point at the visible variant instead.
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- if (expected > 0) expectedVariants = expected;
-
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- } else if (state === 'GENERATING') {
- updateBarContent('generating');
- }
- saveSession();
- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');
- updating = false;
- });
-
- obs.observe(document.body, { childList: true, subtree: true });
- return obs;
- }
-
- // ---------------------------------------------------------------------------
- // Bar scroll tracking
- // ---------------------------------------------------------------------------
-
- function startScrollTracking() {
- function tick() {
- if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
- positionBar();
- showHighlight(selectedElement);
- if (tuneOpen) positionParamsPanel();
- }
- if (annotActive) positionAnnotOverlay(selectedElement);
- // Shader overlay (via debug P toggle or generation) is repositioned
- // by its own branch below; debug no longer has a separate overlay.
- if (shaderState) positionShaderOverlay();
- scrollRaf = requestAnimationFrame(tick);
- }
- scrollRaf = requestAnimationFrame(tick);
- }
-
- function stopScrollTracking() {
- if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
- }
-
- // ---------------------------------------------------------------------------
- // SSE (server→browser) + fetch POST (browser→server)
- // Zero-dependency replacement for WebSocket.
- // ---------------------------------------------------------------------------
-
- let evtSource = null;
- let sseRetries = 0;
- const SSE_MAX_RETRIES = 20; // generous: heartbeats keep the connection alive, so retries mean real trouble
-
- function connectSSE() {
- evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
-
- evtSource.onopen = () => {
- sseRetries = 0; // reset on successful (re)connect
- };
-
- evtSource.onmessage = (e) => {
- sseRetries = 0; // reset on any successful message
- let msg; try { msg = JSON.parse(e.data); } catch { return; }
- switch (msg.type) {
- case 'connected':
- hasProjectContext = !!msg.hasProjectContext;
- if (!hasProjectContext) showToast('No PRODUCT.md found. Variants will be brand-agnostic. Run /impeccable teach to generate one.', 7000);
- console.log('[impeccable] Live mode connected.');
- if (state === 'IDLE') state = 'PICKING';
- break;
- case 'done':
- // Variants already arrived via HMR → normal transition.
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- if (state === 'GENERATING') {
- state = 'CYCLING';
- updateBarContent('cycling');
- refreshParamsPanel();
- }
- break;
- }
- // Variants are in source but not in the DOM yet. Common when the
- // picked element lived inside conditional render (closed modal,
- // hidden tab, a route the user navigated away from). The variant
- // MutationObserver stays armed and auto-transitions to CYCLING
- // the moment the wrapper actually mounts. Nudge the user toward
- // that path with a toast — better than the prior force-reload
- // which reset framework state and left the session stuck.
- setTimeout(() => {
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
- if (state !== 'GENERATING') return;
- showToast(
- "Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
- 15000,
- );
- }, 2000);
- break;
- case 'error':
- console.error('[impeccable] Error:', msg.message);
- showToast('Error: ' + msg.message, 5000);
- hideBar();
- state = 'PICKING';
- break;
- }
- };
-
- evtSource.onerror = () => {
- sseRetries++;
- if (sseRetries <= SSE_MAX_RETRIES) {
- console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
- return; // EventSource auto-reconnects
- }
- // Server is gone. Clean up gracefully.
- console.log('[impeccable] Live server unreachable. Cleaning up UI.');
- evtSource.close();
- evtSource = null;
- handleServerLost();
- };
- }
-
- /** Server died or became unreachable. Reset UI to a clean state. */
- function handleServerLost() {
- const recoveryState = currentSessionId ? state : 'IDLE';
- if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
- showToast('Live server disconnected. Session ended.', 5000);
- }
- hideBar();
- hideHighlight();
- hideShaderOverlay();
- hideAnnotOverlay();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- // Preserve local session state on server loss. The durable journal is the
- // source of truth, but localStorage plus the variant wrapper lets the UI
- // resume after a helper restart or page reload instead of treating a
- // transient disconnect as an explicit discard.
- selectedElement = null;
- selectedAction = 'impeccable';
- state = recoveryState;
- if (currentSessionId) saveSession();
- }
-
- function sendEvent(msg, opts) {
- msg.token = TOKEN;
- function handleFailure(err) {
- console.error('[impeccable] Failed to send event:', err);
- if (opts && opts.throwOnError) throw err;
- return null;
- }
- return fetch('http://localhost:' + PORT + '/events', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(msg),
- }).then(res => {
- if (res.ok) return res;
- return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));
- }).catch(handleFailure);
- }
-
- function checkpointPayload(reason) {
- return {
- type: 'checkpoint',
- id: currentSessionId,
- revision: sessionState.nextCheckpointRevision(),
- owner: browserOwner,
- phase: String(state || '').toLowerCase(),
- reason,
- pageUrl: location.pathname,
- expectedVariants,
- arrivedVariants,
- visibleVariant,
- paramValues: { ...paramsCurrentValues },
- };
- }
-
- function sendCheckpoint(reason) {
- if (!currentSessionId) return Promise.resolve(null);
- return sendEvent(checkpointPayload(reason)).catch(() => null);
- }
-
- function queueCheckpoint(reason) {
- if (!currentSessionId) return;
- if (checkpointTimer) clearTimeout(checkpointTimer);
- checkpointTimer = setTimeout(() => {
- checkpointTimer = null;
- sendCheckpoint(reason);
- }, 120);
- }
-
- // ---------------------------------------------------------------------------
- // Event handlers
- // ---------------------------------------------------------------------------
-
- function handleMouseMove(e) {
- if (state !== 'PICKING' || !pickActive) return;
- const target = document.elementFromPoint(e.clientX, e.clientY);
- if (!target || !pickable(target) || target === hoveredElement) return;
- hoveredElement = target;
- showHighlight(target);
- }
-
- function handleClick(e) {
- // Close action picker on any outside click
- if (pickerEl?.style.display !== 'none' && !own(e.target)) {
- hideActionPicker();
- }
- // Close Tune popover on outside click (anything outside panel + bar)
- if (tuneOpen && paramsPanelEl && !paramsPanelEl.contains(e.target) && barEl && !barEl.contains(e.target)) {
- closeTunePopover();
- }
- // In CONFIGURING: click outside the bar and selected element returns to PICKING
- if (state === 'CONFIGURING' && !own(e.target) && selectedElement && !selectedElement.contains(e.target)) {
- hideBar();
- stopScrollTracking();
- hideAnnotOverlay();
- clearAnnotations();
- state = 'PICKING';
- hoveredElement = null;
- hideHighlight();
- return;
- }
- if (state !== 'PICKING' || !pickActive) return;
- if (own(e.target)) return;
- if (!hoveredElement || !pickable(hoveredElement)) return;
- e.preventDefault();
- e.stopPropagation();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- maybePrefetchPage();
- maybeWarnConditionalAncestor(selectedElement);
- }
-
- /**
- * Surface a brief, non-blocking heads-up when the picked element lives
- * inside a container whose visibility is gated by ephemeral state — modals,
- * collapsible panels, popovers, off-screen tab panels. If HMR remounts the
- * parent during generation (Vite Fast Refresh, SvelteKit page reload), the
- * variants land in source but stay invisible until the user re-opens the
- * container. Telling the user upfront is much friendlier than the silent
- * timeout-then-toast that they'd otherwise hit.
- *
- * Heuristic, intentionally narrow — only fires for unambiguous cases so
- * we don't cry wolf on every nested element.
- */
- function maybeWarnConditionalAncestor(el) {
- let node = el?.parentElement;
- let depth = 0;
- while (node && depth < 12) {
- // 1. Active dialog / modal
- if (node.getAttribute && node.getAttribute('role') === 'dialog'
- && node.getAttribute('aria-modal') === 'true') {
- showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 2. Common Radix / shadcn / headless-ui open-state attribute
- if (node.dataset && node.dataset.state === 'open') {
- showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 3. Tab panel — only meaningful when the page also shows ANOTHER
- // tab as selected. A single tabpanel with no tablist is just a static
- // section in disguise and isn't conditional.
- if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
- const list = document.querySelector('[role="tablist"]');
- if (list) {
- const tabs = list.querySelectorAll('[role="tab"]');
- if (tabs.length > 1) {
- showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
- return;
- }
- }
- }
- // 4. Collapsible: aria-expanded sibling. Look for the trigger button.
- if (node.id) {
- const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
- if (trigger) {
- showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
- return;
- }
- }
- node = node.parentElement;
- depth++;
- }
- }
-
- // Fire a lightweight prefetch event the first time the user selects an
- // element on a given route. The agent uses this to Read the underlying file
- // into context before Go is hit, shaving the read off the critical path.
- // Dedupe per session by pathname — clicking around on the same page doesn't
- // re-fire.
- //
- // DISABLED: quick-Go workflows pay an extra harness round trip because
- // prefetch + generate arrive as two events instead of one. Re-enable with
- // a browser-side debounce (~800–1000ms, cancelled on Go) if we want to
- // resurrect this. Server validator and skill dispatch remain in place so
- // flipping this flag is the only change needed.
- const PREFETCH_ENABLED = false;
- const prefetchedPaths = new Set();
- function maybePrefetchPage() {
- if (!PREFETCH_ENABLED) return;
- const path = location.pathname;
- if (prefetchedPaths.has(path)) return;
- prefetchedPaths.add(path);
- sendEvent({ type: 'prefetch', pageUrl: path });
- }
-
- function handleKeyDown(e) {
- // When the annotation input is focused, let it handle its own keys.
- if (annotEditing && annotEditing.input && e.target === annotEditing.input) return;
- if (e.key === 'Escape') {
- e.preventDefault();
- if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
- if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); hideAnnotOverlay(); clearAnnotations(); state = 'PICKING'; return; }
- if (state === 'CYCLING') { handleDiscard(); return; }
- if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
- if (state === 'PICKING') {
- // Use togglePick so the "Pick" button in the global bar also flips
- // off, otherwise the bar stays lit while nothing else is active.
- if (pickActive) togglePick();
- else { hideHighlight(); state = 'IDLE'; }
- return;
- }
- }
-
- // Arrow/Enter nav works in PICKING (hover) and CONFIGURING (selected, input empty)
- var navEl = (state === 'PICKING') ? hoveredElement : (state === 'CONFIGURING') ? selectedElement : null;
- if (navEl && (e.key === 'ArrowUp' || e.key === 'ArrowDown' || (e.key === 'Enter' && state === 'PICKING'))) {
- let next = null;
- if (e.key === 'ArrowDown' && !e.shiftKey) {
- next = navEl.nextElementSibling;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'ArrowUp' && !e.shiftKey) {
- next = navEl.previousElementSibling;
- while (next && !pickable(next)) next = next.previousElementSibling;
- } else if (e.key === 'ArrowUp' && e.shiftKey) {
- next = navEl.parentElement;
- if (next && !pickable(next)) next = null;
- } else if (e.key === 'ArrowDown' && e.shiftKey) {
- next = navEl.firstElementChild;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'Enter') {
- e.preventDefault();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- return;
- }
- if (next) {
- e.preventDefault();
- if (state === 'PICKING') {
- hoveredElement = next;
- } else {
- // CONFIGURING: re-select the new element and refresh the bar
- selectedElement = next;
- clearAnnotations();
- showAnnotOverlay(next);
- showBar('configure');
- startScrollTracking();
- }
- showHighlight(next);
- next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
- }
- return;
- }
-
- if (state === 'CYCLING') {
- if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
- if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
- if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
- }
- }
-
- function handleGo() {
- if (!selectedElement || state !== 'CONFIGURING') return;
- const input = document.getElementById(PREFIX + '-input');
- const prompt = input ? input.value.trim() : '';
-
- // Commit any pending pin edit BEFORE we snapshot annotations.
- if (annotEditing) finalizeEditingPin();
-
- currentSessionId = id8();
- expectedVariants = selectedCount;
- arrivedVariants = 0;
- visibleVariant = 0;
-
- // Flip to GENERATING immediately so the bar morphs without waiting on
- // capture + upload. The event is emitted from captureAndEmit() once the
- // screenshot is uploaded (or capture fails — we still emit, just without
- // screenshotPath).
- const elForCapture = selectedElement;
- const captureRect = elForCapture.getBoundingClientRect();
- const snapshot = {
- comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),
- strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),
- };
- const basePayload = {
- type: 'generate', id: currentSessionId,
- action: selectedAction,
- freeformPrompt: prompt || undefined,
- count: selectedCount,
- pageUrl: location.pathname,
- element: extractContext(elForCapture),
- };
- if (snapshot.comments.length > 0) basePayload.comments = snapshot.comments;
- if (snapshot.strokes.length > 0) basePayload.strokes = snapshot.strokes;
-
- // Hide the interactive overlay so it doesn't linger during generation.
- hideAnnotOverlay();
- clearAnnotations();
-
- state = 'GENERATING';
- showBar('generating');
- saveSession();
- sendCheckpoint('generate_started');
- writeScrollY(window.scrollY);
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
- console.log('[impeccable.scroll] Go pressed', { scrollY: window.scrollY, sessionId: currentSessionId });
- startScrollLock(currentSessionId);
-
- captureAndEmit(elForCapture, basePayload, snapshot, captureRect);
- }
-
- // ---------------------------------------------------------------------------
- // Screenshot capture + upload
- // ---------------------------------------------------------------------------
-
- let msLoadPromise = null;
- function loadModernScreenshot() {
- if (window.modernScreenshot) return Promise.resolve(window.modernScreenshot);
- if (msLoadPromise) return msLoadPromise;
- msLoadPromise = new Promise((resolve, reject) => {
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/modern-screenshot.js';
- s.onload = () => resolve(window.modernScreenshot);
- s.onerror = () => { msLoadPromise = null; reject(new Error('modern-screenshot failed to load')); };
- document.head.appendChild(s);
- });
- return msLoadPromise;
- }
-
- // Collect @font-face rules from every stylesheet on the page. Cross-origin
- // sheets (Google Fonts, Typekit, etc.) throw SecurityError on .cssRules
- // access, so modern-screenshot can't embed them on its own — the resulting
- // SVG falls back to system fonts and text re-wraps + renders with different
- // weight. We fetch the raw CSS text (CORS-permitted for these providers),
- // extract @font-face blocks, inline the referenced font files as base64
- // data URIs (SVGs rasterized via canvas can't fetch external resources,
- // so URLs inside the SVG silently fail without this), and pass the result
- // to modern-screenshot as font.cssText.
- const FONT_EXT_RE = /\.(woff2?|ttf|otf|eot)(\?.*)?$/i;
- const FONT_MIME = {
- woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', eot: 'application/vnd.ms-fontobject',
- };
- function bufferToBase64(buf) {
- const bytes = new Uint8Array(buf);
- let binary = '';
- const CHUNK = 0x8000;
- for (let i = 0; i < bytes.length; i += CHUNK) {
- binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
- }
- return btoa(binary);
- }
- async function inlineFontUrls(cssText) {
- const urlRe = /url\((['"]?)(https?:\/\/[^'")\s]+)\1\)/g;
- const urls = new Set();
- let m;
- while ((m = urlRe.exec(cssText))) {
- if (FONT_EXT_RE.test(m[2])) urls.add(m[2]);
- }
- const map = new Map();
- await Promise.all([...urls].map(async (url) => {
- try {
- const res = await fetch(url);
- if (!res.ok) return;
- const buf = await res.arrayBuffer();
- const ext = url.toLowerCase().match(FONT_EXT_RE)?.[1] || 'woff2';
- const mime = FONT_MIME[ext] || 'application/octet-stream';
- map.set(url, 'data:' + mime + ';base64,' + bufferToBase64(buf));
- } catch { /* skip; fall through to URL */ }
- }));
- return cssText.replace(urlRe, (orig, q, url) => {
- const data = map.get(url);
- return data ? 'url(' + q + data + q + ')' : orig;
- });
- }
- async function collectFontCssText() {
- const chunks = [];
- const fontFaceRe = /@font-face\s*\{[^}]*\}/g;
- for (const sheet of document.styleSheets) {
- try {
- const rules = sheet.cssRules;
- for (const rule of rules) {
- if (rule.constructor.name === 'CSSFontFaceRule' || rule.cssText?.startsWith('@font-face')) {
- chunks.push(rule.cssText);
- }
- }
- } catch {
- if (!sheet.href) continue;
- try {
- const res = await fetch(sheet.href);
- if (!res.ok) continue;
- const text = await res.text();
- let m2;
- while ((m2 = fontFaceRe.exec(text))) chunks.push(m2[0]);
- } catch { /* ignore; capture is best-effort */ }
- }
- }
- if (chunks.length === 0) return '';
- return inlineFontUrls(chunks.join('\n'));
- }
-
- // True if `s` is a computed color string that renders as nothing
- // (explicit `transparent`, or `rgba(...)` with alpha 0).
- function isTransparentColor(s) {
- if (!s) return true;
- if (s === 'transparent') return true;
- const m = /rgba?\(([^)]+)\)/.exec(s);
- if (!m) return false;
- const parts = m[1].split(',').map((p) => p.trim());
- if (parts.length === 4) return parseFloat(parts[3]) === 0;
- return false;
- }
-
- // modern-screenshot force-sets `background-color: X !important` on the
- // cloned root whenever `backgroundColor` is passed, clobbering the
- // element's own background. So we only pass it when the element is
- // genuinely transparent (no own color, no own image) — in that case
- // we resolve up the DOM to the nearest opaque ancestor so the capture
- // sits on the page's real background instead of rendering black.
- function resolveCanvasBackground(el) {
- const own = getComputedStyle(el);
- if (!isTransparentColor(own.backgroundColor)) return null;
- if (own.backgroundImage && own.backgroundImage !== 'none') return null;
- let node = el.parentElement;
- while (node) {
- const cs = getComputedStyle(node);
- if (!isTransparentColor(cs.backgroundColor)) return cs.backgroundColor;
- node = node.parentElement;
- }
- // The walk already passed through <body> and <html>; if they had been
- // opaque we would have returned. Falling through with the previous
- // `getComputedStyle(body).backgroundColor || …` chain is a trap: that
- // call returns the literal string `"rgba(0, 0, 0, 0)"` for a page that
- // never set its own bg, which is truthy and short-circuits the chain to
- // transparent-black — modern-screenshot then renders the capture on a
- // black canvas and the shader overlay flashes solid black during load.
- // The browser canvas defaults to white, so we do too.
- return '#ffffff';
- }
-
- // Capture the element (with current annotations baked in) and return a PNG
- // Blob. Shared between the Go flow (uploads it to the server) and the
- // debug toggle (displays it as an overlay for side-by-side comparison).
- async function captureElementToBlob(el, snapshot, rect) {
- try { if (document.fonts?.ready) await document.fonts.ready; } catch {}
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- let annotNode = null;
- let savedPosition = null;
- if (hasAnnotations) {
- const pos = getComputedStyle(el).position;
- if (pos === 'static') {
- savedPosition = el.style.position;
- el.style.position = 'relative';
- }
- annotNode = buildAnnotationsForCapture(rect, snapshot);
- el.appendChild(annotNode);
- }
- try {
- const ms = await loadModernScreenshot();
- const fontCssText = await collectFontCssText();
- const backgroundColor = resolveCanvasBackground(el);
- return await ms.domToBlob(el, {
- scale: Math.min(window.devicePixelRatio || 1, 2),
- font: fontCssText ? { cssText: fontCssText } : undefined,
- ...(backgroundColor ? { backgroundColor } : {}),
- });
- } finally {
- if (annotNode) annotNode.remove();
- if (savedPosition !== null) el.style.position = savedPosition;
- }
- }
-
- async function captureAndEmit(el, basePayload, snapshot, rect) {
- let screenshotPath;
- let blob;
- try {
- blob = await captureElementToBlob(el, snapshot, rect);
- } catch (err) {
- console.warn('[impeccable] capture failed, proceeding without screenshot:', err);
- }
- // Light up the shader overlay the moment capture is ready — no reason to
- // wait for the upload to complete before the user sees something alive.
- if (blob && state === 'GENERATING') {
- showShaderOverlay(el, blob, rect);
- }
- // Only upload + forward the screenshot when annotations (comments/strokes)
- // are present. Without annotations the image is pure visual anchoring —
- // it biases the model toward the current rendering and works against the
- // three-distinct-directions brief.
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- if (blob && hasAnnotations) {
- try {
- const uploadRes = await fetch(
- 'http://localhost:' + PORT + '/annotation?token=' + encodeURIComponent(TOKEN) +
- '&eventId=' + encodeURIComponent(basePayload.id),
- { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: blob },
- );
- if (uploadRes.ok) {
- const { path: p } = await uploadRes.json();
- screenshotPath = p;
- } else {
- console.warn('[impeccable] annotation upload failed:', uploadRes.status);
- }
- } catch (err) {
- console.warn('[impeccable] annotation upload failed:', err);
- }
- }
- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);
- }
-
- // ---------------------------------------------------------------------------
- // Shader overlay — renders the captured screenshot as a WebGL texture and
- // runs an editorial "ink-wash" fragment shader over it during generation.
- // A single rolling band sweeps top-to-bottom, desaturating + tinting magenta
- // and leaving a soft trail. Makes the wait feel like a letterpress scan
- // instead of a dead spinner.
- // ---------------------------------------------------------------------------
-
- const SHADER_VS = `attribute vec2 a_position;
-attribute vec2 a_uv;
-varying vec2 v_uv;
-void main() {
- v_uv = a_uv;
- gl_Position = vec4(a_position, 0.0, 1.0);
-}`;
-
- const SHADER_FS = `precision highp float;
-uniform sampler2D u_texture;
-uniform float u_time;
-uniform vec2 u_resolution;
-uniform vec3 u_accent;
-varying vec2 v_uv;
-
-// Asymmetric roller band. Product of two one-sided smoothsteps — peaks at
-// d=0 with a short sharp leading ramp and a longer soft trailing tail. Clean
-// outside the [-leadW, trailW] range (no rogue "trail=1 everywhere below"
-// failure that reversed-edge smoothstep would give).
-float bandAt(float d, float leadW, float trailW) {
- float above = smoothstep(-leadW, 0.0, d);
- float below = 1.0 - smoothstep(0.0, trailW, d);
- return above * below;
-}
-
-void main() {
- vec2 uv = v_uv;
- // Roller sweeps top-to-bottom with small overshoot so each cycle enters
- // and exits the element cleanly.
- float phase = fract(u_time / 3.4);
- float y = phase * 1.25 - 0.12;
- float band = bandAt(uv.y - y, 0.05, 0.32);
-
- // Halftone cell grid (fixed ~10 px pitch).
- float cellPx = 10.0;
- vec2 gridUv = uv * u_resolution / cellPx;
- vec2 cellId = floor(gridUv);
- vec2 cellUv = fract(gridUv) - 0.5;
- vec2 sampleCenter = (cellId + 0.5) * cellPx / u_resolution;
- vec3 cellImg = texture2D(u_texture, sampleCenter).rgb;
- float luma = dot(cellImg, vec3(0.299, 0.587, 0.114));
- // Darker cells → bigger magenta dots (classic risograph halftone curve).
- float radius = sqrt(clamp(1.0 - luma, 0.0, 1.0)) * 0.56;
- float dotMask = smoothstep(radius + 0.06, radius, length(cellUv));
- vec3 paper = vec3(0.975, 0.965, 0.955);
- vec3 dotLayer = mix(paper, u_accent, dotMask);
-
- // Blend the halftone layer in where the roller is passing; leave the
- // element pristine elsewhere.
- vec3 base = texture2D(u_texture, uv).rgb;
- gl_FragColor = vec4(mix(base, dotLayer, band), 1.0);
-}`;
-
- // Editorial Magenta converted to approximate sRGB 0-1 (matches oklch(60% 0.25 350))
- const SHADER_ACCENT = [0.82, 0.16, 0.47];
- let shaderState = null; // { canvas, gl, program, texture, rafId, startTime }
-
- function compileShader(gl, type, source) {
- const sh = gl.createShader(type);
- gl.shaderSource(sh, source);
- gl.compileShader(sh);
- if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
- const info = gl.getShaderInfoLog(sh);
- gl.deleteShader(sh);
- throw new Error('shader compile failed: ' + info);
- }
- return sh;
- }
-
- function positionShaderOverlay() {
- if (!shaderState || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- Object.assign(shaderState.canvas.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- }
-
- function hideShaderOverlay() {
- if (!shaderState) return;
- if (shaderState.rafId) cancelAnimationFrame(shaderState.rafId);
- if (shaderState.canvas) shaderState.canvas.remove();
- const lose = shaderState.gl?.getExtension?.('WEBGL_lose_context');
- try { lose?.loseContext(); } catch {}
- shaderState = null;
- }
-
- async function showShaderOverlay(el, blob, rect) {
- hideShaderOverlay();
- if (!blob || !el) return;
- const canvas = document.createElement('canvas');
- canvas.id = PREFIX + '-shader';
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
- canvas.width = Math.max(1, Math.floor(rect.width * dpr));
- canvas.height = Math.max(1, Math.floor(rect.height * dpr));
- Object.assign(canvas.style, {
- position: 'fixed',
- top: rect.top + 'px', left: rect.left + 'px',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none',
- zIndex: Z.bar - 1,
- });
- document.body.appendChild(canvas);
-
- const gl = canvas.getContext('webgl', { premultipliedAlpha: false, preserveDrawingBuffer: false })
- || canvas.getContext('experimental-webgl');
- if (!gl) {
- // WebGL unavailable — fall back to a plain <img> overlay so the user
- // still sees something meaningful during generation.
- canvas.remove();
- const img = document.createElement('img');
- img.src = URL.createObjectURL(blob);
- img.id = PREFIX + '-shader';
- // Copy positioning via cssText. Object.assign across CSSStyleDeclaration
- // throws in modern Chromium because the source's indexed properties
- // (style[0], [1], ...) are read-only and the engine forbids writing
- // them on the destination.
- img.style.cssText = canvas.style.cssText;
- img.style.outline = '2px dashed ' + C.brand;
- img.style.outlineOffset = '-2px';
- document.body.appendChild(img);
- shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
- return;
- }
-
- let program, texture;
- try {
- const vs = compileShader(gl, gl.VERTEX_SHADER, SHADER_VS);
- const fs = compileShader(gl, gl.FRAGMENT_SHADER, SHADER_FS);
- program = gl.createProgram();
- gl.attachShader(program, vs);
- gl.attachShader(program, fs);
- gl.linkProgram(program);
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- throw new Error('program link failed: ' + gl.getProgramInfoLog(program));
- }
- // Full-screen quad
- const buf = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
- -1, -1, 0, 1,
- 1, -1, 1, 1,
- -1, 1, 0, 0,
- -1, 1, 0, 0,
- 1, -1, 1, 1,
- 1, 1, 1, 0,
- ]), gl.STATIC_DRAW);
- const posLoc = gl.getAttribLocation(program, 'a_position');
- const uvLoc = gl.getAttribLocation(program, 'a_uv');
- gl.enableVertexAttribArray(posLoc);
- gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 16, 0);
- gl.enableVertexAttribArray(uvLoc);
- gl.vertexAttribPointer(uvLoc, 2, gl.FLOAT, false, 16, 8);
- } catch (err) {
- console.warn('[impeccable] shader setup failed:', err);
- canvas.remove();
- return;
- }
-
- // Upload the screenshot as a texture
- let bitmap;
- try {
- bitmap = await createImageBitmap(blob);
- } catch {
- // Safari fallback: go via a regular Image
- const imgUrl = URL.createObjectURL(blob);
- const img = new Image();
- img.src = imgUrl;
- await new Promise((r, rej) => { img.onload = r; img.onerror = rej; });
- bitmap = img;
- URL.revokeObjectURL(imgUrl);
- }
- texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
- if (bitmap.close) bitmap.close();
-
- const uTime = gl.getUniformLocation(program, 'u_time');
- const uRes = gl.getUniformLocation(program, 'u_resolution');
- const uAccent = gl.getUniformLocation(program, 'u_accent');
- const uTex = gl.getUniformLocation(program, 'u_texture');
- const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-
- shaderState = { canvas, gl, program, texture, rafId: 0, startTime: performance.now(), reduced };
- function frame() {
- if (!shaderState) return;
- const elapsed = (performance.now() - shaderState.startTime) / 1000;
- const t = shaderState.reduced ? 0.0 : elapsed;
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.useProgram(program);
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.uniform1i(uTex, 0);
- gl.uniform1f(uTime, t);
- gl.uniform2f(uRes, canvas.width, canvas.height);
- gl.uniform3f(uAccent, SHADER_ACCENT[0], SHADER_ACCENT[1], SHADER_ACCENT[2]);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- shaderState.rafId = requestAnimationFrame(frame);
- }
- frame();
- }
-
- function handleAccept() {
- if (!currentSessionId || arrivedVariants === 0) return;
- const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);
- if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;
- const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };
- if (Object.keys(paramsCurrentValues).length > 0) {
- acceptPayload.paramValues = { ...paramsCurrentValues };
- }
- // The accepted variant is already the only visible child of the wrapper
- // (all other variants are display:none). HMR from the source rewrite will
- // replace the wrapper imminently. Don't eagerly replaceChild here — React
- // reconciliation races with our mutation and throws NotFoundError in Next
- // 16 / Turbopack. Schedule a fallback that runs the manual swap only if
- // HMR hasn't cleaned up by then (keeps static-server flows working).
- const acceptedSessionId = currentSessionId;
- const acceptedVariant = visibleVariant;
-
- state = 'SAVING';
- updateBarContent('saving');
-
- sendEvent(acceptPayload, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- confirmAcceptAfterReceipt();
- })
- .catch(() => {
- state = 'CYCLING';
- updateBarContent('cycling');
- showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);
- });
-
- function confirmAcceptAfterReceipt() {
- state = 'CONFIRMED';
- updateBarContent('confirmed');
- scheduleAcceptCleanup();
- }
-
- function scheduleAcceptCleanup() {
- setTimeout(function() {
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }, 1800);
-
- // Static-server / no-HMR fallback: if the wrapper is still around 2s after
- // the cleanup above, swap it out manually. By now React has either moved
- // on or the app isn't React at all. Preserve the `data-impeccable-variant="N"`
- // div (with display:contents) so @scope rules anchored to the variant
- // attribute keep matching until reload replaces it with the carbonize block.
- setTimeout(function() {
- const wrapper = document.querySelector('[data-impeccable-variants="' + acceptedSessionId + '"]');
- if (!wrapper) return;
- const accepted = wrapper.querySelector('[data-impeccable-variant="' + acceptedVariant + '"]');
- if (accepted && accepted.firstElementChild) {
- const parent = wrapper.parentElement;
- if (!parent) return;
- accepted.style.display = 'contents';
- parent.replaceChild(accepted, wrapper);
- }
- }, 2000);
- }
- }
-
- function handleDiscard() {
- if (!currentSessionId) return;
- sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- cleanup();
- })
- .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));
- }
-
- // ---------------------------------------------------------------------------
- // Session persistence via live-browser-session.js
- // ---------------------------------------------------------------------------
- // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
-
- function saveSession() {
- if (!currentSessionId) return;
- // NOTE: scrollY is stored under a separate key (writeScrollY). Storing
- // it here would overwrite the Go-time value every time state changes.
- sessionState.saveSession({
- id: currentSessionId,
- state,
- action: selectedAction,
- count: selectedCount,
- expected: expectedVariants,
- arrived: arrivedVariants,
- visible: visibleVariant,
- });
- }
-
- function loadSession() {
- return sessionState.loadSession();
- }
-
- function clearSession() {
- sessionState.clearSession();
- }
-
- /** Mark session as handled (accepted/discarded). The agent will clean up
- * the source, but until it does the wrapper is still in the HTML. This
- * prevents resumeSession from picking it up again after reload. */
- function markSessionHandled() {
- if (!currentSessionId) return;
- sessionState.markHandled(currentSessionId);
- }
-
- function isSessionHandled(id) {
- return sessionState.isHandled(id);
- }
-
- function clearHandled() {
- sessionState.clearHandled();
- }
-
- function cleanup() {
- // Hide the wrapper immediately so variants disappear. DON'T structurally
- // mutate the DOM yet — HMR from the agent's source rewrite is on its way,
- // and a manual replaceChild under React causes NotFoundError when the
- // reconciler later tries to remove a wrapper we already removed.
- // Schedule a 2s fallback that does the manual swap only if HMR hasn't
- // replaced the wrapper by then (keeps static-server / no-HMR flows alive).
- const cleanupSessionId = currentSessionId;
- if (cleanupSessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (wrapper) wrapper.style.display = 'none';
- }
- setTimeout(function() {
- if (!cleanupSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (!wrapper) return;
- const orig = wrapper.querySelector('[data-impeccable-variant="original"]');
- if (orig) {
- const content = orig.firstElementChild;
- if (content) {
- wrapper.parentElement.replaceChild(content, wrapper);
- return;
- }
- }
- wrapper.remove();
- }, 2000);
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }
-
- // ---------------------------------------------------------------------------
- // Toast
- // ---------------------------------------------------------------------------
-
- function showToast(message, duration) {
- if (toastEl) toastEl.remove();
- // Stack the toast above the global bar (which sits at bottom:14px) so
- // the two never overlap. Read the bar's actual rect — its height varies
- // with hover-expanded labels — and fall back to a sensible default
- // when the bar isn't mounted yet.
- const barRect = globalBarEl?.getBoundingClientRect();
- const barTopFromBottom = barRect && barRect.height > 0
- ? Math.max(16, window.innerHeight - barRect.top + 12)
- : 16;
- toastEl = el('div', {
- position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
- transform: 'translateX(-50%) translateY(8px)',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px',
- padding: '8px 16px', borderRadius: '8px',
- zIndex: Z.toast, opacity: '0',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
- pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
- });
- toastEl.id = PREFIX + '-toast';
- toastEl.textContent = message;
- document.body.appendChild(toastEl);
- requestAnimationFrame(() => {
- toastEl.style.opacity = '1';
- toastEl.style.transform = 'translateX(-50%) translateY(0)';
- });
- setTimeout(() => {
- if (toastEl) {
- toastEl.style.opacity = '0';
- toastEl.style.transform = 'translateX(-50%) translateY(8px)';
- setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
- }
- }, duration);
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- // Resume an active variant session after HMR/page reload.
- // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
- // variants before HMR fired. Pick up where we left off.
- function resumeSession() {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) { clearSession(); clearHandled(); return false; }
-
- const sessionId = wrapper.dataset.impeccableVariants;
-
- // Don't resume if this session was already accepted/discarded
- if (isSessionHandled(sessionId)) return false;
-
- currentSessionId = sessionId;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
-
- // Restore state from localStorage if available
- const saved = loadSession();
- if (saved && saved.id === sessionId) {
- visibleVariant = (saved.visible > 0 && saved.visible <= arrivedVariants) ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
- if (saved.action) selectedAction = saved.action;
- if (saved.count) selectedCount = saved.count;
- } else {
- visibleVariant = arrivedVariants > 0 ? 1 : 0;
- }
-
- // Find the visible variant's content element for highlight positioning.
- // Try the visible variant first, fall back to the original's content.
- const visEl = visibleVariant > 0 ? pickVariantContent(wrapper, visibleVariant) : null;
- const origEl = pickVariantContent(wrapper, 'original');
- selectedElement = visEl || origEl || wrapper.parentElement;
-
- // Set display state BEFORE starting observer (avoid triggering it)
- if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
-
- state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
- showBar(state === 'CYCLING' ? 'cycling' : 'generating');
- startScrollTracking();
- // Build the params panel for the restored visible variant. Previously
- // this was missed on page-reload resume: showVariantInDOM above fires
- // refreshParamsPanel, but state was still IDLE at that moment so it
- // hid. Now that state is CYCLING, re-fire.
- if (state === 'CYCLING') refreshParamsPanel();
- saveSession();
- queueCheckpoint('browser_resumed');
-
- // Start observing for more variants AFTER initial setup
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
-
- // Hold the target at its saved viewport top through any subsequent
- // HMR patches, variant inserts, or cycle swaps.
- startScrollLock(currentSessionId, readScrollY());
-
- // If we reloaded mid-generation (Bun's HTML HMR destroys the shader
- // canvas), re-capture the original's content and restart the shader so
- // the wait doesn't go dead.
- if (state === 'GENERATING' && origEl) {
- (async () => {
- try {
- const rect = origEl.getBoundingClientRect();
- if (rect.width === 0 || rect.height === 0) return;
- const blob = await captureElementToBlob(origEl, null, rect);
- if (blob && state === 'GENERATING') {
- showShaderOverlay(origEl, blob, rect);
- }
- } catch (err) {
- console.warn('[impeccable] shader resume failed:', err);
- }
- })();
- }
- return true;
- }
-
- // ---------------------------------------------------------------------------
- // Global bar (always visible at bottom)
- // ---------------------------------------------------------------------------
-
- let globalBarEl = null;
- let detectActive = false;
- let pickActive = true;
- let detectCount = 0;
- let detectScriptLoaded = false;
-
- // Theme-aware color palette for the global bar. We detect the page's
- // ambient background and invert — dark bar on light pages, light bar on
- // dark pages. This keeps the bar from fighting with the host design.
- function detectPageTheme() {
- try {
- // Dev override: set localStorage 'impeccable-dev-theme' to 'light' or
- // 'dark' to preview the opposite palette without actually changing the
- // page bg. Used for screenshots and theme QA.
- const override = localStorage.getItem('impeccable-dev-theme');
- if (override === 'light' || override === 'dark') return override;
-
- // Walk body → html, taking the first opaque background. The browser's
- // default body / html background is `rgba(0, 0, 0, 0)`, which a naive
- // regex would read as black and mislabel a perfectly white page as
- // dark. Honoring alpha avoids that — and falling through to <html>
- // catches the common pattern of a bg only on <html> (or only on body).
- function readOpaque(el) {
- if (!el) return null;
- const bg = getComputedStyle(el).backgroundColor;
- const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
- if (!m) return null;
- const alpha = m[4] == null ? 1 : parseFloat(m[4]);
- if (alpha < 0.5) return null; // transparent / nearly transparent → skip
- return [+m[1], +m[2], +m[3]];
- }
-
- const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
- // Both transparent → fall back to the browser's effective canvas color.
- // White is the universal default; only one in a thousand sites swaps it
- // via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
- // us catch that case.
- if (!rgb) {
- return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
- }
- const [r, g, b] = rgb;
- // Perceptual luminance (Rec. 709)
- const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
- return L > 0.55 ? 'light' : 'dark';
- } catch { return 'light'; }
- }
-
- function barPaletteForTheme(theme) {
- if (theme === 'dark') {
- // Light bar on dark page
- return {
- surface: 'oklch(98% 0 0 / 0.92)',
- surfaceDeep: 'oklch(92% 0.005 60 / 0.96)', // slightly deeper, faint warm
- hairline: 'oklch(70% 0 0 / 0.35)',
- text: 'oklch(15% 0 0)',
- textDim: 'oklch(45% 0 0)',
- accent: 'oklch(60% 0.25 350)',
- accentSoft: 'oklch(60% 0.25 350 / 0.18)',
- mark: 'oklch(98% 0 0)', // logo mark fill
- markText: 'oklch(15% 0 0)', // logo "/" color
- exitHover: 'oklch(85% 0 0 / 0.5)',
- };
- }
- // Dark bar on light page. Bar is a warm charcoal, logo slab is much
- // deeper so the rounded-right shape reads as a clear sculpted mark.
- return {
- surface: 'oklch(26% 0 0 / 0.94)',
- surfaceDeep: 'oklch(18% 0 0 / 0.96)', // darker sand for Tune popover
- hairline: 'oklch(42% 0 0 / 0.5)',
- text: 'oklch(96% 0 0)',
- textDim: 'oklch(72% 0 0)',
- accent: 'oklch(72% 0.22 350)',
- accentSoft: 'oklch(72% 0.22 350 / 0.22)',
- mark: 'oklch(8% 0 0)',
- markText: 'oklch(96% 0 0)',
- exitHover: 'oklch(36% 0 0 / 0.6)',
- };
- }
-
- // Impeccable logo mark — matches the site-header SVG (rounded square + "/").
- function brandMarkSvg(fill, ink, size = 18) {
- return `<svg width="${size}" height="${size}" viewBox="0 0 32 32" aria-hidden="true">
- <rect width="32" height="32" rx="7" fill="${fill}"/>
- <text x="16" y="24" font-family="system-ui, -apple-system, sans-serif" font-size="22" font-weight="500" fill="${ink}" text-anchor="middle">/</text>
- </svg>`;
- }
-
- function initGlobalBar() {
- const theme = detectPageTheme();
- const P = barPaletteForTheme(theme);
-
- // Custom focus-visible for bar buttons. Browser default is a heavy
- // blue ring that looks jarring on the dark capsule. Replace with a
- // soft accent-tinted inner ring that respects the bar's palette.
- if (!document.getElementById(PREFIX + '-bar-focus-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-bar-focus-style';
- s.textContent =
- '#' + PREFIX + '-global-bar button:focus { outline: none; }' +
- '#' + PREFIX + '-global-bar button:focus-visible {' +
- ' outline: none;' +
- ' box-shadow: 0 0 0 2px ' + P.accentSoft + ', 0 0 0 3px ' + P.accent + ';' +
- '}';
- document.head.appendChild(s);
- }
-
- globalBarEl = el('div', {
- position: 'fixed', bottom: '14px', left: '50%',
- transform: 'translateX(-50%) translateY(20px)',
- zIndex: Z.bar + 5,
- display: 'flex', alignItems: 'stretch',
- gap: '2px',
- background: P.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 4px 20px oklch(0% 0 0 / 0.12), 0 1px 3px oklch(0% 0 0 / 0.08)',
- fontFamily: FONT, fontSize: '12px', lineHeight: '1',
- opacity: '0',
- overflow: 'hidden', // clip the full-bleed brand mark to the bar radius
- transition: 'opacity 0.3s ' + EASE + ', transform 0.3s ' + EASE,
- });
- globalBarEl.id = PREFIX + '-global-bar';
- globalBarEl.dataset.theme = theme;
-
- // Brand mark — fills bar height on the left. Left side inherits the bar's
- // rounded corner via overflow:hidden; right side is a clean hard edge since
- // the near-black/charcoal contrast does the shape-defining work.
- const brand = el('span', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- alignSelf: 'stretch',
- padding: '0 12px 0 14px',
- background: P.mark,
- color: P.markText,
- fontFamily: 'system-ui, -apple-system, sans-serif',
- fontWeight: '500',
- fontSize: '18px', lineHeight: '1',
- });
- brand.textContent = '/';
- brand.title = 'Impeccable';
- globalBarEl.appendChild(brand);
-
- // Inner wrapper: holds the toggles with normal bar padding.
- const inner = el('div', {
- display: 'flex', alignItems: 'center',
- padding: '4px 5px', gap: '2px',
- });
- inner.id = PREFIX + '-global-bar-inner';
- globalBarEl.appendChild(inner);
-
- // --- button factory: icon-only at rest, label slides in on hover/active ---
- function makeIconBtn({ id, svg, label, ariaLabel, labelFont, onClick }) {
- const b = el('button', {
- position: 'relative',
- display: 'inline-flex', alignItems: 'center',
- padding: '6px 8px', borderRadius: '7px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '11.5px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.15s ease, color 0.15s ease',
- whiteSpace: 'nowrap', overflow: 'hidden',
- });
- b.id = id;
- b.title = ariaLabel || label || '';
- b.setAttribute('aria-label', ariaLabel || label || '');
- b.innerHTML = svg + (label
- ? `<span class="icon-btn-label" style="display:inline-block;max-width:0;opacity:0;margin-left:0;overflow:hidden;font-family:${labelFont || FONT};transition:max-width 0.25s ${EASE}, opacity 0.2s ease, margin-left 0.25s ${EASE};">${label}</span>`
- : '');
- const labelEl = b.querySelector('.icon-btn-label');
- const expand = () => {
- if (!labelEl) return;
- labelEl.style.maxWidth = '120px'; labelEl.style.opacity = '1'; labelEl.style.marginLeft = '6px';
- };
- const collapse = () => {
- if (!labelEl || b.dataset.active === 'true') return;
- labelEl.style.maxWidth = '0'; labelEl.style.opacity = '0'; labelEl.style.marginLeft = '0';
- };
- // Per-button hover only changes color (no layout). The label expand/
- // collapse is driven by the bar-level mouseenter/mouseleave so moving
- // the mouse between adjacent buttons doesn't trigger per-button width
- // thrashing — the whole bar grows once and shrinks once.
- b.addEventListener('mouseenter', () => { if (b.dataset.active !== 'true') b.style.color = P.text; });
- b.addEventListener('mouseleave', () => { if (b.dataset.active !== 'true') b.style.color = P.textDim; });
- b.addEventListener('click', onClick);
- b._expandLabel = expand;
- b._collapseLabel = collapse;
- return b;
- }
-
- // Pick toggle — starts active (primary intent when entering live mode).
- const pickBtn = makeIconBtn({
- id: PREFIX + '-pick-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',
- label: 'Pick',
- ariaLabel: 'Pick element',
- onClick: () => togglePick(),
- });
- pickBtn.style.background = P.accentSoft;
- pickBtn.style.color = P.accent;
- pickBtn.dataset.active = 'true';
- pickBtn._expandLabel();
- inner.appendChild(pickBtn);
-
- // Detect toggle
- const detectBtn = makeIconBtn({
- id: PREFIX + '-detect-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',
- label: 'Detect',
- ariaLabel: 'Detect anti-patterns',
- onClick: () => toggleDetect(),
- });
- const detectBadge = el('span', {
- fontSize: '10px', fontWeight: '600',
- padding: '0px 5px', borderRadius: '7px', lineHeight: '16px',
- background: P.accent, color: P.surface.includes('18%') ? 'oklch(18% 0 0)' : 'oklch(98% 0 0)',
- display: 'none', fontFamily: MONO, marginLeft: '4px',
- });
- detectBadge.id = PREFIX + '-detect-badge';
- detectBtn.appendChild(detectBadge);
- inner.appendChild(detectBtn);
-
- // DESIGN.md panel toggle — quartet of color squares as the mark.
- const designBtn = makeIconBtn({
- id: PREFIX + '-design-toggle',
- svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px ${P.hairline};flex-shrink:0">
- <span style="background:oklch(60% 0.25 350)"></span>
- <span style="background:oklch(60% 0.15 45)"></span>
- <span style="background:oklch(55% 0.12 250)"></span>
- <span style="background:oklch(30% 0 0)"></span>
- </span>`,
- label: 'DESIGN.md',
- ariaLabel: 'Toggle DESIGN.md panel',
- labelFont: MONO,
- onClick: () => toggleDesignPanel(),
- });
- inner.appendChild(designBtn);
-
- // Thin divider before the exit button
- const divider = el('span', {
- width: '1px', height: '18px',
- background: P.hairline,
- margin: '0 4px 0 2px',
- });
- inner.appendChild(divider);
-
- // Exit × on the right — intentionally subtle (textDim at rest, text on
- // hover) so it sits behind the active toggles in visual hierarchy.
- //
- // Explicit padding + box-sizing here is load-bearing: a host page like
- // `button { padding: 0.5rem 1rem; }` (very common in resets) would
- // otherwise inflate this 24x24 button into 56x40 and push the SVG out
- // of the visible bar — the X stays invisible even though the styles in
- // DevTools look fine. Every other chrome button sets padding inline;
- // this one needed it too.
- const exitBtn = el('button', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- padding: '0', boxSizing: 'border-box',
- width: '24px', height: '24px', borderRadius: '6px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
- cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
- });
- exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
- exitBtn.title = 'Exit live mode';
- exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
- exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
- exitBtn.addEventListener('click', () => { sendEvent({ type: 'exit' }); teardown(); });
- inner.appendChild(exitBtn);
-
- // Bar-level hover: expand every toggle's label at once; collapse on leave.
- // Buttons with dataset.active="true" ignore collapse (their label stays).
- const toggles = [pickBtn, detectBtn, designBtn];
- globalBarEl.addEventListener('mouseenter', () => {
- toggles.forEach((t) => t._expandLabel && t._expandLabel());
- });
- globalBarEl.addEventListener('mouseleave', () => {
- toggles.forEach((t) => t._collapseLabel && t._collapseLabel());
- });
-
- document.body.appendChild(globalBarEl);
- defangOutsideHandlers(globalBarEl);
-
- requestAnimationFrame(() => {
- globalBarEl.style.opacity = '1';
- globalBarEl.style.transform = 'translateX(-50%) translateY(0)';
- });
-
- // Listen for detection results AND ready signal
- window.addEventListener('message', onDetectMessage);
- }
-
- function updateGlobalBarState() {
- const detectToggle = document.getElementById(PREFIX + '-detect-toggle');
- const detectBadge = document.getElementById(PREFIX + '-detect-badge');
- const pickToggle = document.getElementById(PREFIX + '-pick-toggle');
- const designToggle = document.getElementById(PREFIX + '-design-toggle');
- const theme = globalBarEl?.dataset.theme || 'light';
- const P = barPaletteForTheme(theme);
-
- // Sync one toggle's active state, colors, and slide-label visibility.
- function sync(btn, active) {
- if (!btn) return;
- btn.style.background = active ? P.accentSoft : 'transparent';
- btn.style.color = active ? P.accent : P.textDim;
- btn.dataset.active = active ? 'true' : 'false';
- if (active && btn._expandLabel) btn._expandLabel();
- else if (!active && btn._collapseLabel) btn._collapseLabel();
- }
- sync(pickToggle, pickActive);
- sync(detectToggle, detectActive);
- sync(designToggle, designState.open);
-
- // If the bar is currently under the cursor, keep all labels expanded —
- // otherwise clicking a toggle that deactivates (e.g. closing DESIGN.md)
- // would collapse its label while the user's mouse is still on the bar.
- if (globalBarEl && globalBarEl.matches(':hover')) {
- [pickToggle, detectToggle, designToggle].forEach((t) => t?._expandLabel?.());
- }
-
- if (detectBadge) {
- detectBadge.style.display = (detectActive && detectCount > 0) ? 'inline' : 'none';
- detectBadge.textContent = detectCount;
- }
-
- // When pick is active, make detect overlays click-through so the picker works
- document.querySelectorAll('.impeccable-overlay').forEach(o => {
- o.style.pointerEvents = pickActive ? 'none' : '';
- });
- }
-
- let detectReady = false; // true once detect script posts 'impeccable-ready'
- let detectPendingScan = false; // scan requested before script was ready
-
- function toggleDetect() {
- detectActive = !detectActive;
- updateGlobalBarState();
-
- if (detectActive) {
- if (!detectScriptLoaded) {
- detectPendingScan = true;
- loadDetectScript();
- } else if (detectReady) {
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- } else {
- detectPendingScan = true;
- }
- } else {
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- detectCount = 0;
- updateGlobalBarState();
- }
- }
-
- function togglePick() {
- pickActive = !pickActive;
- updateGlobalBarState();
-
- if (!pickActive) {
- // Disabling pick clears any in-flight selection and UI: highlight,
- // contextual bar, selectedElement. Otherwise a stale selection sits
- // on screen with no obvious way to dismiss.
- hideHighlight();
- hideBar();
- hideActionPicker();
- selectedElement = null;
- if (state === 'PICKING' || state === 'CONFIGURING') state = 'IDLE';
- } else {
- if (state === 'IDLE') state = 'PICKING';
- }
- }
-
- function loadDetectScript() {
- if (detectScriptLoaded) return;
- detectScriptLoaded = true;
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/detect.js';
- s.dataset.impeccableExtension = 'true';
- document.head.appendChild(s);
- }
-
- function onDetectMessage(e) {
- if (!e.data || typeof e.data.source !== 'string') return;
- // Detection script is loaded and ready
- if (e.data.source === 'impeccable-ready') {
- detectReady = true;
- if (detectPendingScan && detectActive) {
- detectPendingScan = false;
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- }
- }
- // Scan results arrived
- if (e.data.source === 'impeccable-results') {
- detectCount = e.data.count || 0;
- updateGlobalBarState();
- }
- }
-
- /** Full teardown: remove all UI, disconnect SSE, clean up. */
- function teardown() {
- cleanup();
- hideBar();
- if (globalBarEl) {
- globalBarEl.style.transform = 'translateY(100%)';
- setTimeout(() => { if (globalBarEl) globalBarEl.remove(); globalBarEl = null; }, 300);
- }
- if (highlightEl) { highlightEl.remove(); highlightEl = null; }
- if (tooltipEl) { tooltipEl.remove(); tooltipEl = null; }
- if (barEl) { barEl.remove(); barEl = null; }
- if (pickerEl) { pickerEl.remove(); pickerEl = null; }
- if (paramsPanelEl) { paramsPanelEl.remove(); paramsPanelEl = null; paramsPanelInner = null; paramsPanelBody = null; }
- if (evtSource) { evtSource.close(); evtSource = null; }
- document.removeEventListener('mousemove', handleMouseMove, true);
- document.removeEventListener('click', handleClick, true);
- document.removeEventListener('keydown', handleKeyDown, true);
- window.removeEventListener('message', onDetectMessage);
- // Remove detection overlays
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- state = 'IDLE';
- window.__IMPECCABLE_LIVE_INIT__ = false;
- console.log('[impeccable] Live mode exited.');
- }
-
- // ---------------------------------------------------------------------------
- // Design System Panel — visualizes the project's .impeccable/design.json sidecar
- // ---------------------------------------------------------------------------
-
- const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';
- const DESIGN_PANEL_WIDTH = 440;
-
- let designHost = null;
- let designShadow = null;
- let designState = {
- open: false,
- tab: 'visual', // 'visual' | 'raw'
- parsed: null, // parseDesignMd output (frontmatter + body sections)
- sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)
- hasMd: false,
- hasSidecar: false,
- present: null, // true/false once fetch resolves
- raw: null, // raw DESIGN.md for the raw tab
- mdNewerThanJson: false, // stale-hint flag
- loading: false,
- error: null,
- collapsed: { // narrative-section accordion state
- rules: true, dosdonts: true, overview: true,
- },
- };
-
- function loadDesignPrefs() {
- // `open` is intentionally NOT persisted — the panel always starts closed
- // so live mode doesn't auto-slide a big panel over the page on startup.
- try {
- const raw = localStorage.getItem(DESIGN_PREFS_KEY);
- if (!raw) return;
- const prefs = JSON.parse(raw);
- if (prefs.tab === 'visual' || prefs.tab === 'raw') designState.tab = prefs.tab;
- if (prefs.collapsed && typeof prefs.collapsed === 'object') {
- Object.assign(designState.collapsed, prefs.collapsed);
- }
- } catch { /* ignore */ }
- }
-
- function saveDesignPrefs() {
- try {
- localStorage.setItem(DESIGN_PREFS_KEY, JSON.stringify({
- tab: designState.tab,
- collapsed: designState.collapsed,
- }));
- } catch { /* ignore */ }
- }
-
- function initDesignPanel() {
- designHost = document.createElement('div');
- designHost.id = PREFIX + '-design-host';
- Object.assign(designHost.style, {
- position: 'fixed', top: '0', left: '0',
- width: '0', height: '0',
- zIndex: String(Z.bar + 10),
- pointerEvents: 'none',
- });
- designShadow = designHost.attachShadow({ mode: 'open' });
-
- const style = document.createElement('style');
- // Theme-match the bar: dark chrome on light pages, light chrome on dark pages.
- const theme = detectPageTheme();
- style.textContent = designPanelCss(barPaletteForTheme(theme));
- designShadow.appendChild(style);
-
- const root = document.createElement('div');
- root.className = 'root';
- designShadow.appendChild(root);
-
- document.body.appendChild(designHost);
- // The host is pointer-events: none; the panel inside the shadow DOM
- // manages its own auto/none. Events bubble through the shadow boundary,
- // so attaching here silences host-page outside-interaction handlers
- // without touching the host's click-through behavior.
- defangOutsideHandlers(designHost, { setPointerEvents: false });
-
- loadDesignPrefs();
- renderDesignChrome();
- if (designState.open) {
- fetchDesignSystem();
- }
- }
-
- // Neutral panel palette — deliberately NOT Impeccable-branded. The panel is
- // a viewer of the project's design system, not an Impeccable surface.
- const DP = {
- canvas: 'oklch(94% 0 0)', // panel background
- tile: 'oklch(98.5% 0 0)', // card-on-canvas
- tileAlt: 'oklch(96% 0 0)', // subtler tile for inner surfaces
- ink: 'oklch(15% 0 0)',
- ink2: 'oklch(35% 0 0)',
- meta: 'oklch(55% 0 0)',
- hairline: 'oklch(88% 0 0)',
- hairlineSoft: 'oklch(92% 0 0)',
- amber: 'oklch(70% 0.13 65)', // stale-hint accent
- amberBg: 'oklch(95% 0.05 80)',
- };
-
- function designPanelCss(BP) {
- // BP = bar palette (theme-aware, matches the global bar).
- // DP = internal content palette (neutral, so tiles render colors true).
- return `
- :host, .root { all: initial; }
- .root {
- font-family: ${FONT};
- color: ${DP.ink};
- pointer-events: none;
- }
- .root * { box-sizing: border-box; }
- button { font: inherit; color: inherit; }
-
- /* --- Panel shell: chrome matches the bar; body canvas stays neutral --- */
- .panel {
- position: fixed; top: 12px; bottom: 72px; right: 12px;
- width: ${DESIGN_PANEL_WIDTH}px; max-width: calc(100vw - 24px);
- background: ${BP.surface};
- border: 1px solid ${BP.hairline};
- border-radius: 14px;
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- box-shadow: 0 20px 60px oklch(0% 0 0 / 0.18), 0 4px 12px oklch(0% 0 0 / 0.08);
- display: flex; flex-direction: column;
- transform: translateX(calc(100% + 24px));
- opacity: 0;
- transition: transform 0.35s ${EASE}, opacity 0.25s ${EASE};
- pointer-events: none;
- overflow: hidden;
- }
- .panel[data-open="true"] { transform: translateX(0); opacity: 1; pointer-events: auto; }
-
- .panel-header {
- display: flex; align-items: center; gap: 10px;
- padding: 10px 10px 10px 14px;
- background: transparent;
- border-bottom: 1px solid ${BP.hairline};
- }
- .panel-title {
- flex: 1; min-width: 0;
- font-family: ${MONO};
- font-size: 11.5px; font-weight: 600;
- letter-spacing: 0.02em;
- color: ${BP.text};
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
- }
- .panel-close {
- border: none; background: transparent; color: ${BP.textDim};
- width: 26px; height: 26px; border-radius: 7px;
- display: inline-flex; align-items: center; justify-content: center;
- cursor: pointer; transition: background 0.15s ease, color 0.15s ease;
- }
- .panel-close:hover { background: ${BP.hairline}; color: ${BP.text}; }
-
- .tabs {
- display: inline-flex; padding: 2px;
- background: ${BP.hairline};
- border-radius: 7px;
- gap: 2px;
- }
- .tab {
- border: none; background: transparent;
- padding: 4px 10px; border-radius: 5px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 600; letter-spacing: 0.08em;
- text-transform: uppercase;
- color: ${BP.textDim}; cursor: pointer;
- transition: background 0.15s ease, color 0.15s ease;
- }
- .tab[data-active="true"] { background: ${BP.surface}; color: ${BP.text}; }
-
- .panel-body {
- flex: 1; overflow-y: auto;
- padding: 12px 12px 20px;
- background: ${DP.canvas};
- scrollbar-width: thin;
- scrollbar-color: ${DP.hairline} transparent;
- }
- .panel-body::-webkit-scrollbar { width: 8px; }
- .panel-body::-webkit-scrollbar-thumb { background: ${DP.hairline}; border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
-
- /* --- States --- */
- .empty, .loading, .error {
- margin: 16px 4px;
- padding: 28px 20px; text-align: center;
- background: ${DP.tile}; border-radius: 14px;
- color: ${DP.ink2}; font-size: 13px; line-height: 1.55;
- }
- .empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
- .empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
- .error { color: oklch(45% 0.15 25); }
-
- /* --- Stale hint --- */
- .stale {
- display: flex; align-items: center; gap: 8px;
- margin: 8px 4px 12px;
- padding: 8px 12px;
- background: ${DP.amberBg};
- border-radius: 10px;
- font-size: 11.5px; color: ${DP.ink2};
- }
- .stale-dot { width: 8px; height: 8px; border-radius: 50%; background: ${DP.amber}; flex-shrink: 0; }
- .stale-text { flex: 1; min-width: 0; }
- .stale-text strong { color: ${DP.ink}; font-weight: 600; }
-
- /* --- Parsed-md fallback banner --- */
- .parsed-md-cta {
- margin: 8px 4px 14px;
- padding: 14px 16px;
- background: ${DP.tile};
- border: 1px dashed ${DP.hairline};
- border-radius: 12px;
- font-size: 12px; color: ${DP.ink2}; line-height: 1.55;
- }
- .parsed-md-cta strong { color: ${DP.ink}; display: block; margin-bottom: 4px; font-size: 13px; font-weight: 600; }
- .parsed-md-cta code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; font-size: 11.5px; color: ${DP.ink}; }
-
- /* --- Tile primitives --- */
- .tile {
- position: relative;
- background: ${DP.tile};
- border-radius: 16px;
- padding: 16px;
- margin: 0 4px 10px;
- }
- .tile-row { margin: 0 4px 10px; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
- .tile-row .tile { margin: 0; }
- .tile-meta {
- display: flex; align-items: baseline; justify-content: space-between;
- gap: 10px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase;
- color: ${DP.meta};
- }
- .tile-meta .name { color: ${DP.ink}; font-weight: 600; letter-spacing: 0.05em; text-transform: none; font-family: ${FONT}; font-size: 12.5px; }
-
- /* --- Color tile --- */
- .c-tile { cursor: pointer; transition: transform 0.2s ${EASE}; }
- .c-tile:hover { transform: translateY(-1px); }
- .c-hero {
- height: 72px; border-radius: 10px; margin-top: 10px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.05);
- }
- .c-ramp {
- display: flex; gap: 0; height: 14px; border-radius: 4px; overflow: hidden;
- margin-top: 8px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.04);
- }
- .c-ramp > span { flex: 1; }
- .c-desc { margin-top: 8px; font-size: 11.5px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Type tile --- */
- .t-tile { }
- .t-specimen {
- margin: 4px 0 6px;
- color: ${DP.ink};
- line-height: 0.9;
- }
- .t-family { margin-top: 4px; font-size: 12px; font-weight: 600; color: ${DP.ink}; }
- .t-purpose { margin-top: 4px; font-size: 11px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Shadow tile --- */
- .s-tile { }
- .s-surface {
- height: 60px; margin: 8px 2px 10px;
- background: ${DP.tile};
- border-radius: 10px;
- }
- .s-value { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; word-break: break-all; line-height: 1.4; }
- .s-purpose { margin-top: 4px; font-size: 11px; color: ${DP.ink2}; line-height: 1.45; }
-
- /* --- Radii strip --- */
- .r-strip { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
- .r-item { display: flex; flex-direction: column; align-items: center; gap: 4px; flex: 1; min-width: 60px; }
- .r-sample { width: 44px; height: 44px; background: ${DP.canvas}; box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.08); }
- .r-label { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; text-transform: uppercase; }
- .r-val { font-family: ${MONO}; font-size: 10px; color: ${DP.ink}; }
-
- /* --- Component tile (hosts live primitives) --- */
- .cmp-tile { }
- .cmp-stage {
- margin: 12px -4px 0;
- padding: 18px 16px 10px;
- border-top: 1px solid ${DP.hairlineSoft};
- display: flex; flex-direction: column; align-items: center; justify-content: center;
- gap: 14px;
- min-height: 68px;
- }
- .cmp-stage + .cmp-stage { border-top: 1px dashed ${DP.hairlineSoft}; }
- .cmp-sublabel { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.06em; }
- .cmp-kind { font-family: ${MONO}; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; }
-
- /* --- Collapsible --- */
- .coll {
- margin: 0 4px 8px;
- background: ${DP.tile};
- border-radius: 12px;
- overflow: hidden;
- }
- .coll-head {
- display: flex; align-items: center; gap: 10px;
- width: 100%;
- padding: 12px 14px;
- background: transparent; border: none;
- cursor: pointer; text-align: left;
- font-family: ${FONT}; font-size: 12.5px; font-weight: 600; color: ${DP.ink};
- transition: background 0.12s ease;
- }
- .coll-head:hover { background: ${DP.tileAlt}; }
- .coll-chev {
- width: 12px; height: 12px; flex-shrink: 0;
- color: ${DP.meta};
- transition: transform 0.2s ${EASE};
- }
- .coll[data-open="true"] .coll-chev { transform: rotate(90deg); }
- .coll-count { margin-left: auto; font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; }
- .coll-body { padding: 0 14px 14px; display: none; }
- .coll[data-open="true"] .coll-body { display: block; }
-
- .rule-card {
- padding: 10px 0;
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .rule-card:first-child { border-top: none; padding-top: 2px; }
- .rule-card .name { font-size: 11.5px; font-weight: 700; color: ${DP.ink}; margin-bottom: 3px; }
- .rule-card .name .section { font-family: ${MONO}; font-size: 9px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; margin-left: 8px; }
- .rule-card .body { font-size: 11.5px; color: ${DP.ink2}; line-height: 1.5; }
-
- .coll .dos { display: grid; gap: 0; margin-top: 2px; }
- .coll .do, .coll .dont {
- position: relative;
- padding: 8px 0 8px 22px;
- font-size: 11.5px; line-height: 1.5; color: ${DP.ink2};
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .coll .do:first-child, .coll .dont:first-child,
- .coll .do:first-of-type { border-top: none; }
- .coll .do + .dont { border-top: 1px solid ${DP.hairlineSoft}; }
- .coll .do::before, .coll .dont::before {
- content: ''; position: absolute; left: 4px; top: 13px;
- width: 8px; height: 8px; border-radius: 50%;
- }
- .coll .do::before { background: oklch(62% 0.16 145); }
- .coll .dont::before { background: oklch(58% 0.22 25); }
-
- .coll .overview-body {
- font-size: 12px; line-height: 1.55; color: ${DP.ink2};
- }
- .coll .overview-body .north-star {
- display: block; font-family: ${FONT}; font-style: italic;
- font-size: 15px; line-height: 1.3; color: ${DP.ink};
- margin-bottom: 8px;
- }
- .coll .overview-body p { margin: 0 0 8px; }
- .coll .overview-body ul { margin: 6px 0 0; padding-left: 16px; font-size: 11.5px; }
- .coll .overview-body li { margin-bottom: 3px; }
-
- /* --- raw tab markdown (unchanged layout, neutralized palette) --- */
- .md { padding: 4px 10px 20px; font-size: 13px; line-height: 1.6; color: ${DP.ink}; }
- .md h1, .md h2, .md h3, .md h4 { margin: 20px 0 8px; color: ${DP.ink}; font-weight: 600; }
- .md h1 { font-size: 18px; }
- .md h2 { font-size: 15px; padding-bottom: 4px; border-bottom: 1px solid ${DP.hairlineSoft}; }
- .md h3 { font-size: 13px; }
- .md h4 { font-size: 12px; color: ${DP.meta}; }
- .md p { margin: 0 0 10px; }
- .md ul, .md ol { margin: 0 0 10px; padding-left: 20px; }
- .md li { margin-bottom: 4px; }
- .md code { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; }
- .md pre { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 10px 12px; border-radius: 8px; overflow-x: auto; margin: 0 0 10px; }
- .md pre code { background: none; padding: 0; }
- .md strong { font-weight: 700; }
- .md em { font-style: italic; }
- .md a { color: ${DP.ink}; text-decoration: underline; }
- .md hr { border: none; border-top: 1px solid ${DP.hairlineSoft}; margin: 16px 0; }
- `;
- }
-
- function renderDesignChrome() {
- const root = designShadow.querySelector('.root');
- root.innerHTML = '';
-
- // (Panel toggle lives in the global bar — no floating FAB.)
- // Panel
- const panel = document.createElement('aside');
- panel.className = 'panel';
- panel.setAttribute('data-open', designState.open ? 'true' : 'false');
- panel.appendChild(buildDesignHeader());
- const body = document.createElement('div');
- body.className = 'panel-body';
- body.id = 'panel-body';
- panel.appendChild(body);
- root.appendChild(panel);
-
- renderDesignBody();
- }
-
- function buildDesignHeader() {
- const header = document.createElement('div');
- header.className = 'panel-header';
-
- const title = document.createElement('div');
- title.className = 'panel-title';
- title.textContent = 'DESIGN.md';
- header.appendChild(title);
-
- const tabs = document.createElement('div');
- tabs.className = 'tabs';
- for (const t of [['visual', 'Visual'], ['raw', 'Raw']]) {
- const btn = document.createElement('button');
- btn.className = 'tab';
- btn.textContent = t[1];
- btn.setAttribute('data-active', designState.tab === t[0] ? 'true' : 'false');
- btn.addEventListener('click', () => {
- if (designState.tab === t[0]) return;
- designState.tab = t[0];
- saveDesignPrefs();
- renderDesignChrome();
- if (t[0] === 'raw' && designState.raw === null && !designState.loading) {
- fetchDesignSystem(); // raw is part of the same fetch pair
- }
- });
- tabs.appendChild(btn);
- }
- header.appendChild(tabs);
-
- const close = document.createElement('button');
- close.className = 'panel-close';
- close.innerHTML = '✕';
- close.setAttribute('aria-label', 'Close panel');
- close.addEventListener('click', toggleDesignPanel);
- header.appendChild(close);
-
- return header;
- }
-
- function toggleDesignPanel() {
- designState.open = !designState.open;
- renderDesignChrome();
- updateGlobalBarState();
- if (designState.open && designState.present === null && !designState.loading) {
- fetchDesignSystem();
- }
- }
-
- async function fetchDesignSystem() {
- designState.loading = true;
- designState.error = null;
- renderDesignBody();
- try {
- const [jsonRes, rawRes] = await Promise.all([
- fetch(`http://localhost:${PORT}/design-system.json?token=${TOKEN}`, { cache: 'no-store' }),
- fetch(`http://localhost:${PORT}/design-system/raw?token=${TOKEN}`, { cache: 'no-store' }),
- ]);
- const jsonData = await jsonRes.json();
- designState.present = jsonData.present === true;
- designState.parsed = jsonData.parsed || null;
- designState.sidecar = jsonData.sidecar || null;
- designState.hasMd = !!jsonData.hasMd;
- designState.hasSidecar = !!jsonData.hasSidecar;
- designState.mdNewerThanJson = !!jsonData.mdNewerThanJson;
- designState.raw = designState.present && rawRes.ok ? await rawRes.text() : null;
- designState.error = jsonData.parseError || jsonData.sidecarError || null;
- } catch (err) {
- designState.error = err?.message || 'Failed to load design system.';
- } finally {
- designState.loading = false;
- renderDesignChrome(); // refresh title from data
- }
- }
-
- function renderDesignBody() {
- const body = designShadow.querySelector('#panel-body');
- if (!body) return;
- body.innerHTML = '';
-
- if (designState.loading) {
- body.appendChild(msgDiv('loading', 'Loading design system…'));
- return;
- }
- if (designState.error) {
- body.appendChild(msgDiv('error', designState.error));
- return;
- }
- if (designState.present === false) {
- const empty = document.createElement('div');
- empty.className = 'empty';
- empty.innerHTML = `<strong>No DESIGN.md yet</strong>Create one by running <code>/impeccable document</code> in your terminal, then re-open this panel.`;
- body.appendChild(empty);
- return;
- }
-
- if (designState.tab === 'raw') {
- renderRawTab(body, designState.raw || '');
- return;
- }
-
- // Visual tab — single unified render path.
- if (designState.mdNewerThanJson) body.appendChild(renderStaleHint());
- if (designState.hasMd && !designState.hasSidecar) {
- body.appendChild(renderParsedMdCta());
- }
- renderDesignVisual(body, designState.parsed, designState.sidecar);
- }
-
- function msgDiv(cls, text) {
- const d = document.createElement('div');
- d.className = cls;
- d.textContent = text;
- return d;
- }
-
- function renderStaleHint() {
- const box = document.createElement('div');
- box.className = 'stale';
- box.innerHTML = `
- <span class="stale-dot"></span>
- <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>
- `;
- return box;
- }
-
- function renderParsedMdCta() {
- const box = document.createElement('div');
- box.className = 'parsed-md-cta';
- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;
- return box;
- }
-
- // --- Unified render: merge parsed DESIGN.md frontmatter with sidecar v2 ---
-
- function renderDesignVisual(body, parsed, sidecar) {
- const frontmatter = parsed?.frontmatter || {};
- const extensions = sidecar?.extensions || {};
- const proseColors = parsed?.colors || null;
-
- const colors = buildColorModels(frontmatter.colors, extensions.colorMeta, proseColors);
- if (colors.length) renderColorTiles(body, colors);
-
- const types = buildTypographyModels(frontmatter.typography, extensions.typographyMeta);
- if (types.length) renderTypeTiles(body, types);
-
- const radii = buildRadiiModels(frontmatter.rounded);
- if (radii.length) renderRadiiTile(body, radii);
-
- if (extensions.shadows?.length) renderShadowTiles(body, extensions.shadows);
-
- const components = sidecar?.components || [];
- if (components.length) renderComponentTiles(body, components);
-
- // Narrative: sidecar wins if present (richer, agent-curated). Otherwise
- // synthesize from prose sections.
- const narrative = sidecar?.narrative || synthesizeNarrative(parsed);
- if (narrative.rules?.length) body.appendChild(renderRulesCollapsible(narrative.rules));
- if ((narrative.dos?.length || narrative.donts?.length)) body.appendChild(renderDosDontsCollapsible(narrative));
- if (narrative.overview || narrative.northStar || narrative.keyCharacteristics?.length) {
- body.appendChild(renderOverviewCollapsible(narrative));
- }
-
- if (body.childElementCount === 0) {
- body.appendChild(msgDiv('empty', 'No design system data available.'));
- }
- }
-
- // Frontmatter primitives + sidecar colorMeta → tile-ready color models.
- // A matching prose bullet (when the slug sits in the bullet text) supplies
- // description as a last-resort fallback.
- function buildColorModels(fmColors, colorMeta, proseColors) {
- if (!fmColors) return [];
- const meta = colorMeta || {};
- return Object.entries(fmColors).map(([key, value]) => {
- const m = meta[key] || {};
- return {
- role: m.role || humanizeKey(key),
- name: m.displayName || humanizeKey(key),
- value: value,
- canonical: m.canonical || null,
- description: m.description || findProseDescription(proseColors, key, m.displayName),
- tonalRamp: m.tonalRamp || null,
- };
- });
- }
-
- function buildTypographyModels(fmTypography, typographyMeta) {
- if (!fmTypography) return [];
- const meta = typographyMeta || {};
- return Object.entries(fmTypography).map(([key, spec]) => {
- const m = meta[key] || {};
- const { family, fallback } = splitFontFamily(spec?.fontFamily);
- return {
- role: key,
- name: m.displayName || humanizeKey(key),
- family,
- fallback,
- weight: spec?.fontWeight ?? 400,
- // fontStyle isn't in Stitch's frontmatter schema; the sidecar carries
- // it when a role is rendered in italic (e.g. display italic).
- style: m.style || 'normal',
- sampleSize: spec?.fontSize || '1rem',
- lineHeight: spec?.lineHeight != null ? String(spec.lineHeight) : '',
- letterSpacing: spec?.letterSpacing,
- purpose: m.purpose,
- };
- });
- }
-
- function buildRadiiModels(fmRounded) {
- if (!fmRounded) return [];
- return Object.entries(fmRounded).map(([name, value]) => ({ name, value }));
- }
-
- function splitFontFamily(stack) {
- if (!stack || typeof stack !== 'string') return { family: '', fallback: '' };
- const parts = stack.split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, ''));
- return { family: parts[0] || '', fallback: parts.slice(1).join(', ') };
- }
-
- function humanizeKey(k) {
- return String(k || '').replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
- }
-
- function findProseDescription(proseColors, key, displayName) {
- if (!proseColors || !proseColors.groups) return null;
- const needles = [key, displayName].filter(Boolean).map((s) => s.toLowerCase());
- for (const g of proseColors.groups) {
- for (const c of g.colors || []) {
- const hay = String(c.name || '').toLowerCase();
- if (hay && needles.some((n) => hay.includes(n) || n.includes(hay))) {
- return c.description || null;
- }
- }
- }
- return null;
- }
-
- function synthesizeNarrative(parsed) {
- if (!parsed) return {};
- const md = parsed;
- return {
- northStar: md.overview?.creativeNorthStar,
- overview: (md.overview?.philosophy || []).join(' '),
- keyCharacteristics: md.overview?.keyCharacteristics || [],
- rules: [
- ...(md.colors?.rules || []).map((r) => ({ ...r, section: 'colors' })),
- ...(md.typography?.rules || []).map((r) => ({ ...r, section: 'typography' })),
- ...(md.elevation?.rules || []).map((r) => ({ ...r, section: 'elevation' })),
- ],
- dos: md.dosDonts?.dos || [],
- donts: md.dosDonts?.donts || [],
- };
- }
-
- function renderColorTiles(body, colors) {
- for (const c of colors) {
- const tile = document.createElement('div');
- tile.className = 'tile c-tile';
- tile.title = 'Click to copy';
- tile.addEventListener('click', () => copyToClipboard(c.value));
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(c.name || c.role || 'Color')}</span><span>${escapeHtml(c.value || '')}</span>`;
- tile.appendChild(meta);
-
- const hero = document.createElement('div');
- hero.className = 'c-hero';
- hero.style.background = c.value;
- tile.appendChild(hero);
-
- const ramp = synthesizeRamp(c);
- if (ramp.length) {
- const r = document.createElement('div');
- r.className = 'c-ramp';
- r.innerHTML = ramp.map((v) => `<span style="background:${cssSafe(v)}"></span>`).join('');
- tile.appendChild(r);
- }
-
- if (c.description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = c.description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function synthesizeRamp(c) {
- if (c.tonalRamp?.length) return c.tonalRamp;
- // If base value is OKLCH, synthesize an 8-step ramp across lightness.
- const m = typeof c.value === 'string' && c.value.match(/^oklch\(\s*([\d.]+)%\s+([\d.]+)\s+([\d.]+)\s*(?:\/\s*([\d.]+))?\s*\)$/i);
- if (!m) return [];
- const [, , chroma, hue] = m;
- const steps = [20, 32, 44, 56, 68, 80, 90, 96];
- return steps.map((l) => `oklch(${l}% ${chroma} ${hue})`);
- }
-
- function renderTypeTiles(body, types) {
- for (const t of types) {
- const tile = document.createElement('div');
- tile.className = 'tile t-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span>${escapeHtml(t.role || '')}</span><span>${escapeHtml(t.weight || '')} ${escapeHtml(t.style === 'italic' ? 'italic' : '')}</span>`;
- tile.appendChild(meta);
-
- const specimen = document.createElement('div');
- specimen.className = 't-specimen';
- specimen.textContent = 'Aa';
- specimen.style.fontFamily = fontStack(t);
- specimen.style.fontWeight = String(t.weight || 400);
- specimen.style.fontStyle = t.style || 'normal';
- specimen.style.fontSize = '56px'; // Fixed specimen size — compare faces, not scales.
- specimen.style.letterSpacing = 'normal';
- specimen.style.textTransform = 'none';
- tile.appendChild(specimen);
-
- // The system's actual sample size for this role, shown as small mono meta below.
- if (t.sampleSize) {
- const scale = document.createElement('div');
- scale.style.cssText = 'font-family:' + MONO + '; font-size: 10px; color:' + DP.meta + '; margin-top: 2px;';
- scale.textContent = t.sampleSize;
- tile.appendChild(scale);
- }
-
- const family = document.createElement('div');
- family.className = 't-family';
- family.textContent = t.family || t.name || '';
- tile.appendChild(family);
-
- if (t.purpose) {
- const p = document.createElement('div');
- p.className = 't-purpose';
- p.textContent = t.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function fontStack(t) {
- const fam = t.family || '';
- const fb = t.fallback || '';
- if (fam && /[,\s]/.test(fam) && !fam.includes("'") && !fam.includes('"')) {
- return `"${fam}", ${fb}`;
- }
- return fam && fb ? `"${fam}", ${fb}` : (fam || fb);
- }
-
- function renderRadiiTile(body, radii) {
- const tile = document.createElement('div');
- tile.className = 'tile';
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">Corner Radii</span><span>${radii.length}</span>`;
- tile.appendChild(meta);
-
- const strip = document.createElement('div');
- strip.className = 'r-strip';
- for (const r of radii) {
- const item = document.createElement('div');
- item.className = 'r-item';
- const s = document.createElement('div');
- s.className = 'r-sample';
- s.style.borderRadius = r.value || '0';
- item.appendChild(s);
- const lbl = document.createElement('div');
- lbl.className = 'r-label';
- lbl.textContent = r.name || '';
- item.appendChild(lbl);
- const val = document.createElement('div');
- val.className = 'r-val';
- val.textContent = r.value || '';
- item.appendChild(val);
- strip.appendChild(item);
- }
- tile.appendChild(strip);
- body.appendChild(tile);
- }
-
- function renderShadowTiles(body, shadows) {
- for (const sh of shadows) {
- const tile = document.createElement('div');
- tile.className = 'tile s-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(sh.name || 'Shadow')}</span><span>Elevation</span>`;
- tile.appendChild(meta);
-
- const surface = document.createElement('div');
- surface.className = 's-surface';
- surface.style.boxShadow = sh.value || 'none';
- tile.appendChild(surface);
-
- const val = document.createElement('div');
- val.className = 's-value';
- val.textContent = sh.value || '';
- tile.appendChild(val);
-
- if (sh.purpose) {
- const p = document.createElement('div');
- p.className = 's-purpose';
- p.textContent = sh.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function renderComponentTiles(body, components) {
- // Group consecutive components that share a kind into one tile. This avoids
- // a pile of one-component tiles (e.g., three button variants = three tiles)
- // and reads more like a proper category.
- const groups = groupByKind(components);
-
- for (const group of groups) {
- const tile = document.createElement('div');
- tile.className = 'tile cmp-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- const groupTitle = group.length === 1
- ? (group[0].name || group[0].kind || 'Component')
- : titleForKind(group[0].kind, group.length);
- meta.innerHTML = `<span class="name">${escapeHtml(groupTitle)}</span><span class="cmp-kind">${escapeHtml(group[0].kind || '')}</span>`;
- tile.appendChild(meta);
-
- for (const c of group) {
- const stage = document.createElement('div');
- stage.className = 'cmp-stage';
-
- // Render the component in its own shadow root so its CSS can't bleed.
- const host = document.createElement('div');
- const sub = host.attachShadow({ mode: 'open' });
- const style = document.createElement('style');
- style.textContent = c.css || '';
- sub.appendChild(style);
- const container = document.createElement('div');
- container.innerHTML = c.html || '';
- sub.appendChild(container);
- stage.appendChild(host);
-
- // Show component name as a sublabel only when the tile groups >1 item,
- // or when the component's display name differs from its kind.
- const showSublabel = group.length > 1;
- if (showSublabel) {
- const lbl = document.createElement('div');
- lbl.className = 'cmp-sublabel';
- lbl.textContent = c.name || '';
- stage.appendChild(lbl);
- }
- tile.appendChild(stage);
- }
-
- // Single shared description if all items carry the same one; otherwise
- // skip — per-item descriptions clutter a grouped tile.
- if (group.length === 1 && group[0].description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = group[0].description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function groupByKind(components) {
- const groups = [];
- for (const c of components) {
- const last = groups[groups.length - 1];
- if (last && last[0].kind && c.kind === last[0].kind) {
- last.push(c);
- } else {
- groups.push([c]);
- }
- }
- return groups;
- }
-
- function titleForKind(kind, count) {
- const labels = {
- button: 'Buttons',
- input: 'Inputs',
- nav: 'Navigation',
- chip: 'Chips',
- card: 'Cards',
- custom: 'Components',
- };
- return labels[kind] || (kind ? kind.charAt(0).toUpperCase() + kind.slice(1) + 's' : 'Components');
- }
-
- // --- Collapsibles ---------------------------------------------------------
-
- function buildCollapsible(key, label, count) {
- const wrap = document.createElement('div');
- wrap.className = 'coll';
- wrap.setAttribute('data-open', designState.collapsed[key] ? 'false' : 'true');
-
- const head = document.createElement('button');
- head.className = 'coll-head';
- head.innerHTML = `
- <svg class="coll-chev" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 2.5L8 6 4 9.5"/></svg>
- <span>${escapeHtml(label)}</span>
- ${count != null ? `<span class="coll-count">${escapeHtml(String(count))}</span>` : ''}
- `;
- head.addEventListener('click', () => {
- designState.collapsed[key] = !designState.collapsed[key];
- saveDesignPrefs();
- renderDesignBody();
- });
- wrap.appendChild(head);
-
- const body = document.createElement('div');
- body.className = 'coll-body';
- wrap.appendChild(body);
- return { wrap, body };
- }
-
- function renderRulesCollapsible(rules) {
- const { wrap, body } = buildCollapsible('rules', 'Named Rules', rules.length);
- for (const r of rules) {
- const card = document.createElement('div');
- card.className = 'rule-card';
- const name = document.createElement('div');
- name.className = 'name';
- name.innerHTML = `${escapeHtml(r.name)}${r.section ? `<span class="section">${escapeHtml(r.section)}</span>` : ''}`;
- card.appendChild(name);
- const b = document.createElement('div');
- b.className = 'body';
- b.textContent = r.body || '';
- card.appendChild(b);
- body.appendChild(card);
- }
- return wrap;
- }
-
- function renderDosDontsCollapsible(n) {
- const total = (n.dos?.length || 0) + (n.donts?.length || 0);
- const { wrap, body } = buildCollapsible('dosdonts', "Do's and Don'ts", total);
- const grid = document.createElement('div');
- grid.className = 'dos';
- for (const d of n.dos || []) {
- const el = document.createElement('div');
- el.className = 'do';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- for (const d of n.donts || []) {
- const el = document.createElement('div');
- el.className = 'dont';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- body.appendChild(grid);
- return wrap;
- }
-
- function renderOverviewCollapsible(n) {
- const { wrap, body } = buildCollapsible('overview', 'Overview', null);
- const ov = document.createElement('div');
- ov.className = 'overview-body';
- if (n.northStar) {
- const star = document.createElement('span');
- star.className = 'north-star';
- star.textContent = '“' + n.northStar + '”';
- ov.appendChild(star);
- }
- if (n.overview) {
- const p = document.createElement('p');
- p.innerHTML = inlineMd(n.overview);
- ov.appendChild(p);
- }
- if (n.keyCharacteristics?.length) {
- const ul = document.createElement('ul');
- ul.innerHTML = n.keyCharacteristics.map((k) => `<li>${inlineMd(k)}</li>`).join('');
- ov.appendChild(ul);
- }
- body.appendChild(ov);
- return wrap;
- }
-
- function cssSafe(v) {
- // Strip anything outside valid CSS value chars to prevent injection via
- // .impeccable/design.json values rendered into inline style strings.
- return String(v).replace(/[<>"'`\n]/g, '');
- }
-
- // --- Raw tab: minimal markdown renderer (subset) --------------------------
-
- function renderRawTab(body, md) {
- const wrap = document.createElement('div');
- wrap.className = 'md';
- wrap.innerHTML = renderMarkdown(md);
- body.appendChild(wrap);
- }
-
- function renderMarkdown(md) {
- const lines = md.split(/\r?\n/);
- const out = [];
- let i = 0;
- let inCode = false;
- let codeBuf = [];
- let paraBuf = [];
- let listBuf = []; // array of { indent, html }
- let listType = null; // 'ul' | 'ol'
-
- const flushPara = () => {
- if (paraBuf.length) {
- out.push(`<p>${inlineMd(paraBuf.join(' '))}</p>`);
- paraBuf = [];
- }
- };
- const flushList = () => {
- if (listBuf.length) {
- out.push(buildListHtml(listBuf, listType));
- listBuf = [];
- listType = null;
- }
- };
- const flushAll = () => { flushPara(); flushList(); };
-
- for (; i < lines.length; i++) {
- const line = lines[i];
-
- // Code fence
- const fence = line.match(/^```(\w*)\s*$/);
- if (fence) {
- if (!inCode) { flushAll(); inCode = true; codeBuf = []; }
- else {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- inCode = false;
- }
- continue;
- }
- if (inCode) { codeBuf.push(line); continue; }
-
- if (line.trim() === '') { flushAll(); continue; }
-
- const hr = line.match(/^\s*(?:---+|\*\*\*+)\s*$/);
- if (hr) { flushAll(); out.push('<hr />'); continue; }
-
- const heading = line.match(/^(#{1,4})\s+(.+)$/);
- if (heading) {
- flushAll();
- const lvl = heading[1].length;
- out.push(`<h${lvl}>${inlineMd(heading[2])}</h${lvl}>`);
- continue;
- }
-
- const bullet = line.match(/^(\s*)([-*])\s+(.+)$/);
- const ordered = line.match(/^(\s*)(\d+)\.\s+(.+)$/);
- if (bullet || ordered) {
- flushPara();
- const m = bullet || ordered;
- const indent = Math.floor(m[1].length / 2);
- const t = bullet ? 'ul' : 'ol';
- if (listType && listType !== t) flushList();
- listType = t;
- listBuf.push({ indent, html: inlineMd(m[3]) });
- continue;
- }
-
- paraBuf.push(line);
- }
- flushAll();
- if (inCode && codeBuf.length) {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- }
- return out.join('\n');
- }
-
- function buildListHtml(items, type) {
- // Nest by indent (one level deep is plenty for DESIGN.md).
- let html = `<${type}>`;
- let lastIndent = 0;
- for (const it of items) {
- if (it.indent > lastIndent) html += `<${type}>`;
- else if (it.indent < lastIndent) html += `</${type}>`.repeat(lastIndent - it.indent);
- html += `<li>${it.html}</li>`;
- lastIndent = it.indent;
- }
- html += `</${type}>`.repeat(lastIndent + 1);
- return html;
- }
-
- function inlineMd(text) {
- // Order matters: escape first, then re-inject tags.
- let s = escapeHtml(text);
- // Code spans
- s = s.replace(/`([^`]+)`/g, (_, code) => `<code>${code}</code>`);
- // Links [text](url)
- s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, t, u) => `<a href="${u}" target="_blank" rel="noopener noreferrer">${t}</a>`);
- // Bold
- s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
- // Italic (only single *…*, skip if inside bold already handled)
- s = s.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em>$2</em>');
- return s;
- }
-
- function highlightBold(text) {
- return inlineMd(text);
- }
-
- function escapeHtml(s) {
- return String(s)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
-
- function copyToClipboard(text) {
- if (!text) return;
- try {
- navigator.clipboard.writeText(text);
- showToast('Copied: ' + text);
- } catch { /* ignore */ }
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- function init() {
- try { history.scrollRestoration = 'manual'; } catch {}
- initHighlight();
- initAnnotOverlay();
- initBar();
- initActionPicker();
- initParamsPanel();
- initGlobalBar();
- initDesignPanel();
- document.addEventListener('mousemove', handleMouseMove, true);
- document.addEventListener('click', handleClick, true);
- document.addEventListener('keydown', handleKeyDown, true);
- connectSSE();
-
- // Check for an active session to resume (variant wrapper already in DOM after HMR)
- if (!resumeSession()) {
- console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
- // SvelteKit (and any framework that hydrates after HTML parse) may add
- // the variant wrapper AFTER init runs. Watch for it and retry resume
- // once it appears. Disconnect on first hit.
- const scout = new MutationObserver(() => {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) return;
- scout.disconnect();
- if (resumeSession()) {
- console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
- }
- });
- scout.observe(document.body, { childList: true, subtree: true });
- } else {
- console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
- }
- }
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
- } else {
- init();
- }
-})();
@@ -1,75 +0,0 @@
-#!/usr/bin/env node
-/**
- * Canonical durable completion acknowledgement for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function parseArgs(argv) {
- const out = { status: 'complete' };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';
- else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }
- else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function completeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help || !args.id) {
- console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);
- process.exit(args.help ? 0 : 1);
- }
-
- const serverInfo = readServerInfo();
- const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;
- if (serverResult?.ok) {
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const snapshot = store.getSnapshot(args.id, { includeCompleted: true });
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const event = args.status === 'discarded'
- ? { type: 'discarded', id: args.id }
- : args.status === 'agent_error'
- ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }
- : { type: 'complete', id: args.id };
- const snapshot = store.appendEvent(event);
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));
-}
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function completeThroughServer(info, args) {
- const type = args.status === 'discarded'
- ? 'discarded'
- : args.status === 'agent_error'
- ? 'error'
- : 'complete';
- try {
- const res = await fetch(`http://localhost:${info.port}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),
- });
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {
- completeCli();
-}
@@ -1,18 +0,0 @@
-export function completionTypeForAcceptResult(eventType, acceptResult) {
- if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';
- if (acceptResult?.handled === true) return 'complete';
- if (acceptResult?.mode === 'error') return 'error';
- return 'agent_done';
-}
-
-export function completionAckForAcceptResult(eventId, completionType, acceptResult) {
- const ack = { ok: true, type: completionType };
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) {
- ack.final = false;
- ack.requiresComplete = true;
- ack.nextCommand = `live-complete.mjs --id ${eventId}`;
- ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';
- }
- return ack;
-}
@@ -1,446 +0,0 @@
-/**
- * CLI helper: insert/remove the live variant mode script tag in the project's
- * main HTML entry point.
- *
- * On first live run, the agent generates `.impeccable/live/config.json`
- * with the project's insertion target (framework-specific). On
- * every subsequent run, this script handles insert/remove deterministically
- * with zero LLM involvement.
- *
- * Usage:
- * node live-inject.mjs --port PORT # Insert the live script tag
- * node live-inject.mjs --remove # Remove the live script tag
- * node live-inject.mjs --check # Check whether live config exists
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { resolveLiveConfigPath } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });
-const MARKER_OPEN_TEXT = 'impeccable-live-start';
-const MARKER_CLOSE_TEXT = 'impeccable-live-end';
-
-/**
- * Hard-excluded directory patterns. These are NEVER user-facing pages and
- * matching them would silently inject tracking scripts into third-party
- * code. The user cannot turn these off via config — they are the floor.
- */
-const HARD_EXCLUDES = [
- '**/node_modules/**',
- '**/.git/**',
-];
-
-export async function injectCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-inject.mjs [options]
-
-Insert or remove the live mode script tag in the project's HTML entry point.
-Reads configuration from .impeccable/live/config.json.
-
-Modes:
- --port PORT Insert script tag pointing at http://localhost:PORT/live.js
- --remove Remove the script tag (if present)
- --check Print whether .impeccable/live/config.json exists and its content
-
-Output (JSON):
- { ok, file, inserted|removed, config? }`);
- process.exit(0);
- }
-
- if (args.includes('--check')) {
- if (!fs.existsSync(CONFIG_PATH)) {
- console.log(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(0);
- }
- let cfg;
- try {
- cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- try {
- validateConfig(cfg);
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- console.log(JSON.stringify({ ok: true, config: cfg, path: CONFIG_PATH }));
- return;
- }
-
- // Load config
- if (!fs.existsSync(CONFIG_PATH)) {
- console.error(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(1);
- }
- const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- validateConfig(config);
-
- const resolvedFiles = resolveFiles(process.cwd(), config);
-
- if (args.includes('--remove')) {
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const detagged = removeTag(content, config.commentSyntax);
- const updated = revertCspMeta(detagged);
- if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- removed: detagged !== content,
- cspReverted: updated !== detagged,
- };
- });
- console.log(JSON.stringify({ ok: true, results }));
- return;
- }
-
- // Insert mode — need --port
- const portIdx = args.indexOf('--port');
- const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : NaN;
- if (!Number.isFinite(port)) {
- console.error(JSON.stringify({ ok: false, error: 'missing_port' }));
- process.exit(1);
- }
-
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
- const withTag = insertTag(withoutOld, config, port);
- if (withTag === withoutOld) {
- return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
- }
- const updated = patchCspMeta(withTag, port);
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- inserted: true,
- cspPatched: updated !== withTag,
- };
- });
- const anyInserted = results.some((r) => r.inserted);
- console.log(JSON.stringify({ ok: anyInserted, port, results }));
- if (!anyInserted) process.exit(1);
-}
-
-/**
- * Expand config.files (which may contain glob patterns) into a literal list
- * of existing file paths relative to rootDir. Literal entries pass through;
- * glob patterns are expanded via fs.globSync. HARD_EXCLUDES and config.exclude
- * are applied as filters. Duplicates are removed. Order is preserved by
- * first appearance.
- */
-export function resolveFiles(rootDir, config) {
- const patterns = config.files;
- const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
- const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
- const excludeRegexes = allExcludes.map(globToRegex);
-
- const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
- const isGlob = (s) => /[*?[]/.test(s);
-
- const seen = new Set();
- const out = [];
- for (const pat of patterns) {
- if (!isGlob(pat)) {
- // Literal path — include even if it doesn't exist yet; the caller
- // reports file_not_found per-entry. Exclude list doesn't apply to
- // explicit literal entries (user named it on purpose).
- if (!seen.has(pat)) {
- seen.add(pat);
- out.push(pat);
- }
- continue;
- }
- let matches;
- try {
- matches = fs.globSync(pat, { cwd: rootDir, withFileTypes: true });
- } catch {
- continue;
- }
- for (const ent of matches) {
- if (!ent.isFile || !ent.isFile()) continue;
- const abs = path.join(ent.parentPath || ent.path || rootDir, ent.name);
- const rel = path.relative(rootDir, abs).split(path.sep).join('/');
- if (isExcluded(rel)) continue;
- if (seen.has(rel)) continue;
- seen.add(rel);
- out.push(rel);
- }
- }
- return out;
-}
-
-/**
- * Convert a glob pattern to a RegExp. Supports:
- * ** → any number of path segments (including zero)
- * * → any chars except `/`
- * ? → any single char except `/`
- * Paths are normalized to forward slashes before matching.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- // ** — any number of segments, including zero. Handle the common
- // **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
- if (pattern[i + 2] === '/') {
- re += '(?:.*/)?';
- i += 3;
- } else {
- re += '.*';
- i += 2;
- }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Core operations
-// ---------------------------------------------------------------------------
-
-function validateConfig(cfg) {
- if (!cfg || typeof cfg !== 'object') throw new Error('config.json must be an object');
- if (!Array.isArray(cfg.files) || cfg.files.length === 0) {
- throw new Error('config.files (non-empty string array) required');
- }
- if (!cfg.files.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.files must contain only non-empty strings');
- }
- if (cfg.exclude !== undefined) {
- if (!Array.isArray(cfg.exclude)) {
- throw new Error('config.exclude, if present, must be a string array');
- }
- if (!cfg.exclude.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.exclude must contain only non-empty strings');
- }
- }
- if (typeof cfg.insertBefore !== 'string' && typeof cfg.insertAfter !== 'string') {
- throw new Error('config.insertBefore or config.insertAfter (string) required');
- }
- if (cfg.commentSyntax !== 'html' && cfg.commentSyntax !== 'jsx') {
- throw new Error("config.commentSyntax must be 'html' or 'jsx'");
- }
- if (cfg.cspChecked !== undefined && typeof cfg.cspChecked !== 'boolean') {
- throw new Error("config.cspChecked, if present, must be a boolean");
- }
-}
-
-function commentOpen(syntax) { return syntax === 'jsx' ? '{/*' : '<!--'; }
-function commentClose(syntax) { return syntax === 'jsx' ? '*/}' : '-->'; }
-
-function buildTagBlock(syntax, port) {
- const open = commentOpen(syntax);
- const close = commentClose(syntax);
- return (
- open + ' ' + MARKER_OPEN_TEXT + ' ' + close + '\n' +
- '<script src="http://localhost:' + port + '/live.js"></script>\n' +
- open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n'
- );
-}
-
-function insertTag(content, config, port) {
- const block = buildTagBlock(config.commentSyntax, port);
- // insertBefore: match the LAST occurrence. Anchors like `</body>` naturally
- // belong at the end, and the same literal can appear earlier in code blocks
- // within rendered documentation pages.
- if (config.insertBefore) {
- const idx = content.lastIndexOf(config.insertBefore);
- if (idx === -1) return content;
- return content.slice(0, idx) + block + content.slice(idx);
- }
- // insertAfter: match the FIRST occurrence — typical anchors like `<head>` or
- // `<body>` open near the top of the document.
- const idx = content.indexOf(config.insertAfter);
- if (idx === -1) return content;
- const after = idx + config.insertAfter.length;
- // Preserve a single trailing newline if the anchor didn't end with one
- const prefix = content[after] === '\n' ? content.slice(0, after + 1) : content.slice(0, after) + '\n';
- return prefix + block + content.slice(prefix.length);
-}
-
-/**
- * Remove the live script block. Matches either HTML or JSX comment markers
- * regardless of config (so stale tags from a wrong config can still be cleaned).
- *
- * Indent-preserving: captures any whitespace immediately preceding the opener
- * marker and re-emits it in place of the removed block. `insertTag` inserted
- * the block *after* the original line's indent and *before* the anchor (e.g.
- * `</body>`), which moved the indent onto the opener line and left the anchor
- * unindented. Replacing the whole block (plus its trailing newline) with just
- * the captured indent hands the indent back to the anchor that follows.
- */
-function removeTag(content, _syntax) {
- const patterns = [
- /([ \t]*)<!--\s*impeccable-live-start\s*-->[\s\S]*?<!--\s*impeccable-live-end\s*-->[ \t]*\n/,
- /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}[ \t]*\n/,
- ];
- for (const pat of patterns) {
- const next = content.replace(pat, '$1');
- if (next !== content) return next;
- }
- return content;
-}
-
-// ---------------------------------------------------------------------------
-// Content-Security-Policy meta-tag patcher
-//
-// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
-// the cross-origin load of /live.js (and the SSE/POST connection back to
-// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
-//
-// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
-// and stash the original `content` value in a `data-impeccable-csp-original`
-// attribute (base64) so revert is exact.
-//
-// On remove: detect the marker attribute, decode it, restore the original
-// content value verbatim, drop the marker.
-//
-// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
-// shared helpers) is NOT patched here — those need framework-specific config
-// edits and are handled via the existing detect-csp.mjs reference output.
-// Only the in-source meta-tag form gets the auto-patch.
-// ---------------------------------------------------------------------------
-
-const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
-
-function findCspMetaTags(content) {
- const out = [];
- const tagRe = /<meta\s+([^>]*?)\/?>/gis;
- let m;
- while ((m = tagRe.exec(content)) !== null) {
- const attrs = m[1];
- if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
- out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
- }
- return out;
-}
-
-function getAttr(attrs, name) {
- const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
- const m = attrs.match(re);
- return m ? { quote: m[1], value: m[2], full: m[0] } : null;
-}
-
-function appendOriginToDirective(csp, directive, origin) {
- const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
- const m = csp.match(re);
- if (m) {
- const tokens = m[4].trim().split(/\s+/);
- if (tokens.includes(origin)) return csp;
- return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
- }
- // Directive missing — add it. Use 'self' + origin so we don't inadvertently
- // narrow the policy compared to the default-src fallback (most users with
- // an explicit CSP have 'self' there).
- return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
-}
-
-export function patchCspMeta(content, port) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
- const origin = `http://localhost:${port}`;
-
- // Walk last-to-first so prior splices don't invalidate later indices.
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const attrs = tag.attrs;
- if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
- const contentAttr = getAttr(attrs, 'content');
- if (!contentAttr) continue;
-
- const original = contentAttr.value;
- let patched = original;
- patched = appendOriginToDirective(patched, 'script-src', origin);
- patched = appendOriginToDirective(patched, 'connect-src', origin);
- // The shader overlay during 'generating' creates a screenshot via
- // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
- // those. Add `blob:` so the overlay doesn't throw a CSP violation.
- patched = appendOriginToDirective(patched, 'img-src', 'blob:');
- if (patched === original) continue;
-
- const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
- const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
- // The tagRe captures any whitespace between the last attribute and the
- // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
- // a replace would land it BEFORE that trailing space, leaving a double
- // space inside attrs and clobbering the space before `/>`. Split off
- // the trailing whitespace, splice the marker into the attribute body,
- // and re-append the original trailing whitespace so a self-closing
- // `<meta … />` round-trips byte-for-byte.
- const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
- const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
- const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
- const newTag = tag.full.replace(attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-export function revertCspMeta(content) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
-
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
- if (!origAttr) continue;
- const contentAttr = getAttr(tag.attrs, 'content');
- if (!contentAttr) continue;
-
- let originalValue;
- try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
- catch { continue; }
-
- const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
- let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
- // Drop the marker attribute and any single space immediately preceding it.
- newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
- const newTag = tag.full.replace(tag.attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
- injectCli();
-}
-
-export { insertTag, removeTag, validateConfig, buildTagBlock };
-// patchCspMeta + revertCspMeta are exported above where they're defined.
@@ -1,200 +0,0 @@
-/**
- * CLI client for the live variant mode poll/reply protocol.
- *
- * Usage:
- * npx impeccable poll # Block until browser event, print JSON
- * npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
- * npx impeccable poll --reply <id> done # Reply "done" to event <id>
- * npx impeccable poll --reply <id> error "msg" # Reply with error
- */
-
-import { execFileSync } from 'node:child_process';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-// Node's built-in fetch (undici under the hood) enforces a 300s headers
-// timeout that can't be lowered per-request. We cap each request below
-// that ceiling and loop in `pollOnce` to synthesize a long poll without
-// depending on the standalone undici package.
-const PER_REQUEST_TIMEOUT_MS = 270_000;
-
-function readServerInfo() {
- const record = readLiveServerInfo(process.cwd());
- if (!record) {
- console.error('No running live server found. Start one with: npx impeccable live');
- process.exit(1);
- }
- return record.info;
-}
-
-export function buildPollReplyPayload(token, { id, type, message, file, data }) {
- return { token, id, type, message, file, data };
-}
-
-async function postReply(base, token, reply) {
- const res = await fetch(`${base}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(buildPollReplyPayload(token, reply)),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error || res.statusText);
- }
-}
-
-export async function pollCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable poll [options]
-
-Wait for a browser event from the live variant server, or reply to one.
-
-Modes:
- poll Block until a browser event arrives, print JSON
- poll --reply <id> done Reply "done" to event <id>
- poll --reply <id> error "msg" Reply with an error message
-
-Options:
- --timeout=MS Long-poll timeout in ms (default: 600000). Use the default unless the user asked to pause live; never use a short timeout to end the chat turn
- --help Show this help message`);
- process.exit(0);
- }
-
- const info = readServerInfo();
- const base = `http://localhost:${info.port}`;
-
- // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
- const replyIdx = args.indexOf('--reply');
- if (replyIdx !== -1) {
- const id = args[replyIdx + 1];
- const status = args[replyIdx + 2] || 'done';
- const fileIdx = args.indexOf('--file');
- const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
- // Message is any remaining positional arg that isn't a flag
- const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
-
- if (!id) {
- console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
- process.exit(1);
- }
-
- try {
- await postReply(base, info.token, { id, type: status, message, file: filePath });
-
- // Success — silent exit (agent doesn't need output for replies)
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Reply failed:', err.message);
- }
- process.exit(1);
- }
- return;
- }
-
- // Poll mode: block until browser event. Default 10 min. Node's built-in
- // fetch enforces a 300s headers timeout, so we loop in slices under that
- // ceiling and keep re-polling until we get a real event or the user's
- // total timeout runs out.
- const timeoutArg = args.find(a => a.startsWith('--timeout='));
- const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600000;
-
- const deadline = Date.now() + totalTimeout;
- let event;
- try {
- while (true) {
- const remaining = deadline - Date.now();
- if (remaining <= 0) {
- event = { type: 'timeout' };
- break;
- }
- const slice = Math.min(remaining, PER_REQUEST_TIMEOUT_MS);
- const res = await fetch(`${base}/poll?token=${info.token}&timeout=${slice}`);
-
- if (res.status === 401) {
- console.error('Authentication failed. The server token may have changed.');
- console.error('Try restarting: npx impeccable live stop && npx impeccable live');
- process.exit(1);
- }
-
- if (!res.ok) {
- console.error(`Poll failed: ${res.status} ${res.statusText}`);
- process.exit(1);
- }
-
- const next = await res.json();
- // Server-side timeout means no browser event arrived in this slice.
- // Loop and re-poll until we get a real event or we hit the user's
- // total deadline.
- if (next?.type === 'timeout' && Date.now() < deadline) continue;
- event = next;
- break;
- }
-
- // Auto-handle accept/discard via deterministic script
- if (event.type === 'accept' || event.type === 'discard') {
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const acceptScript = path.join(__dirname, 'live-accept.mjs');
- const scriptArgs = event.type === 'discard'
- ? ['--id', event.id, '--discard']
- : ['--id', event.id, '--variant', event.variantId];
- if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
- scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
- }
- try {
- const out = execFileSync(
- 'node',
- [acceptScript, ...scriptArgs],
- { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 }
- );
- event._acceptResult = JSON.parse(out.trim());
- } catch (err) {
- event._acceptResult = { handled: false, mode: 'error', error: err.message };
- }
-
- const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
- try {
- await postReply(base, info.token, {
- id: event.id,
- type: completionType,
- message: event._acceptResult?.error,
- file: event._acceptResult?.file,
- data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
- });
- } catch (err) {
- event._completionAck = { ok: false, error: err.message };
- }
- if (!event._completionAck) {
- event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
- }
- }
-
- // Second signal path: stderr banner in case the agent parses stdout
- // JSON but skips nested fields. One line is enough — the full checklist
- // is in reference/live.md.
- if (event._acceptResult?.carbonize === true) {
- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
- }
-
- // Print the event as JSON — the agent reads this from stdout
- console.log(JSON.stringify(event));
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Poll failed:', err.message);
- }
- process.exit(1);
- }
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
- pollCli();
-}
@@ -1,48 +0,0 @@
-#!/usr/bin/env node
-/**
- * Recover the next agent action from the durable live-session journal.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-
-function parseArgs(argv) {
- const out = { id: null };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function resumeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help) {
- console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });
- const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;
- if (!snapshot) {
- console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));
- return;
- }
-
- const pending = snapshot.pendingEvent || null;
- const nextAction = pending
- ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`
- : snapshot.phase === 'carbonize_required'
- ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`
- : snapshot.phase === 'accept_requested'
- ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`
- : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;
-
- console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {
- resumeCli();
-}
@@ -1,838 +0,0 @@
-#!/usr/bin/env node
-/**
- * Live variant mode server (self-contained, zero dependencies).
- *
- * Serves the browser script (/live.js), the detection overlay (/detect.js),
- * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
- * browser→server events. Agent communicates via HTTP long-poll (/poll).
- *
- * Usage:
- * node <scripts_path>/live-server.mjs # start
- * node <scripts_path>/live-server.mjs stop # stop + remove injected live.js tag
- * node <scripts_path>/live-server.mjs stop --keep-inject # stop only
- * node <scripts_path>/live-server.mjs --help
- */
-
-import http from 'node:http';
-import { randomUUID } from 'node:crypto';
-import { spawn, execFileSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import net from 'node:net';
-import { fileURLToPath } from 'node:url';
-import { parseDesignMd } from './design-parser.mjs';
-import { resolveContextDir } from './load-context.mjs';
-import { createLiveSessionStore } from './live-session-store.mjs';
-import {
- getDesignSidecarPath,
- getLiveAnnotationsDir,
- readLiveServerInfo,
- removeLiveServerInfo,
- resolveDesignSidecarPath,
- writeLiveServerInfo,
-} from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated
-// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
-// DESIGN.json fallback for existing projects.
-const CONTEXT_DIR = resolveContextDir(process.cwd());
-const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anyway
-const SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s
-
-// ---------------------------------------------------------------------------
-// Port detection
-// ---------------------------------------------------------------------------
-
-async function findOpenPort(start = 8400) {
- return new Promise((resolve) => {
- const srv = net.createServer();
- srv.listen(start, '127.0.0.1', () => {
- const port = srv.address().port;
- srv.close(() => resolve(port));
- });
- srv.on('error', () => resolve(findOpenPort(start + 1)));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Session state
-// ---------------------------------------------------------------------------
-
-const state = {
- token: null,
- port: null,
- sseClients: new Set(), // SSE response objects (server→browser push)
- pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
- pendingPolls: [], // agent poll callbacks waiting for browser events
- exitTimer: null,
- sessionDir: null, // per-session tmp dir for annotation screenshots
- sessionStore: null,
- leaseTimer: null,
-};
-
-// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;
-// cap at 10 MB to guard against runaway writes from a misbehaving client.
-const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
-
-function enqueueEvent(event) {
- if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;
- state.pendingEvents.push({ event, leaseUntil: 0 });
- flushPendingPolls();
-}
-
-function restorePendingEventsFromStore() {
- if (!state.sessionStore) return;
- for (const snapshot of state.sessionStore.listActiveSessions()) {
- if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);
- }
-}
-
-function findAvailablePendingEvent(now = Date.now()) {
- return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);
-}
-
-function leaseEvent(entry, leaseMs) {
- if (!entry.event?.id) {
- const idx = state.pendingEvents.indexOf(entry);
- if (idx !== -1) state.pendingEvents.splice(idx, 1);
- return entry.event;
- }
- entry.leaseUntil = Date.now() + leaseMs;
- return entry.event;
-}
-
-function acknowledgePendingEvent(id) {
- if (!id) return false;
- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);
- if (idx === -1) return false;
- state.pendingEvents.splice(idx, 1);
- scheduleLeaseFlush();
- return true;
-}
-
-function scheduleLeaseFlush() {
- if (state.leaseTimer) {
- clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- }
- if (state.pendingPolls.length === 0) return;
- const now = Date.now();
- const nextLeaseUntil = state.pendingEvents
- .map((entry) => entry.leaseUntil || 0)
- .filter((leaseUntil) => leaseUntil > now)
- .sort((a, b) => a - b)[0];
- if (!nextLeaseUntil) return;
- state.leaseTimer = setTimeout(() => {
- state.leaseTimer = null;
- flushPendingPolls();
- }, Math.max(0, nextLeaseUntil - now));
-}
-
-function flushPendingPolls() {
- while (state.pendingPolls.length > 0) {
- const entry = findAvailablePendingEvent();
- if (!entry) {
- scheduleLeaseFlush();
- return;
- }
- const poll = state.pendingPolls.shift();
- poll.resolve(leaseEvent(entry, poll.leaseMs));
- }
- scheduleLeaseFlush();
-}
-
-/** Push a message to all connected SSE clients. */
-function broadcast(msg) {
- const data = 'data: ' + JSON.stringify(msg) + '\n\n';
- for (const res of state.sseClients) {
- try { res.write(data); } catch { /* client gone */ }
- }
-}
-
-// ---------------------------------------------------------------------------
-// Load scripts
-// ---------------------------------------------------------------------------
-
-function loadBrowserScripts() {
- // Detection script: prefer the skill-bundled detector, then fall back to
- // source/npm package locations for local development and older installs.
- // This one IS cached — detect.js rarely changes during a session.
- const detectPaths = [
- path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(process.cwd(), 'node_modules', 'impeccable', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- ];
- let detectScript = '';
- for (const p of detectPaths) {
- try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
- }
-
- // live-browser.js: DO NOT cache. Return the path so the /live.js handler
- // can re-read on every request. Editing the browser script during iteration
- // should land on the next tab reload, not require a server restart.
- const sessionPath = path.join(__dirname, 'live-browser-session.js');
- const livePath = path.join(__dirname, 'live-browser.js');
- for (const p of [sessionPath, livePath]) {
- if (!fs.existsSync(p)) {
- process.stderr.write('Error: live browser script not found at ' + p + '\n');
- process.exit(1);
- }
- }
-
- return { detectScript, sessionPath, livePath };
-}
-
-function hasProjectContext() {
- // PRODUCT.md carries brand voice / anti-references — that's what determines
- // whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
- // concern, surfaced by the design panel's own empty state. Legacy
- // .impeccable.md is auto-migrated to PRODUCT.md by load-context.mjs.
- try {
- fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
- return true;
- } catch { return false; }
-}
-
-function statOrNull(filePath) {
- try { return fs.statSync(filePath); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// Validation (inline — no external import needed for self-contained script)
-// ---------------------------------------------------------------------------
-
-const VISUAL_ACTIONS = [
- 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
- 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
-];
-
-// Browser generates ids via crypto.randomUUID().slice(0, 8) (8 hex chars)
-// and variantIds via String(small integer). Restrict to those shapes so
-// any value that reaches a downstream child_process or DOM selector is
-// inert by construction.
-const ID_PATTERN = /^[0-9a-f]{8}$/;
-const VARIANT_ID_PATTERN = /^[0-9]{1,3}$/;
-
-function isValidId(v) { return typeof v === 'string' && ID_PATTERN.test(v); }
-function isValidVariantId(v) { return typeof v === 'string' && VARIANT_ID_PATTERN.test(v); }
-
-function validateEvent(msg) {
- if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
- switch (msg.type) {
- case 'generate':
- if (!isValidId(msg.id)) return 'generate: missing or malformed id';
- if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
- if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
- if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
- // Optional annotation fields (all-or-nothing: if any present, all must be well-formed).
- if (msg.screenshotPath !== undefined && typeof msg.screenshotPath !== 'string') return 'generate: screenshotPath must be string';
- if (msg.comments !== undefined && !Array.isArray(msg.comments)) return 'generate: comments must be array';
- if (msg.strokes !== undefined && !Array.isArray(msg.strokes)) return 'generate: strokes must be array';
- return null;
- case 'accept':
- if (!isValidId(msg.id)) return 'accept: missing or malformed id';
- if (!isValidVariantId(msg.variantId)) return 'accept: missing or malformed variantId';
- if (msg.paramValues !== undefined) {
- if (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues)) {
- return 'accept: paramValues must be an object';
- }
- }
- return null;
- case 'discard':
- return isValidId(msg.id) ? null : 'discard: missing or malformed id';
- case 'checkpoint':
- if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';
- if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';
- if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {
- return 'checkpoint: paramValues must be an object';
- }
- return null;
- case 'exit':
- return null;
- case 'prefetch':
- if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return 'prefetch: missing pageUrl';
- return null;
- default:
- return 'Unknown event type: ' + msg.type;
- }
-}
-
-// ---------------------------------------------------------------------------
-// HTTP request handler
-// ---------------------------------------------------------------------------
-
-function createRequestHandler({ detectScript, sessionPath, livePath }) {
- return (req, res) => {
- const url = new URL(req.url, `http://localhost:${state.port}`);
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
- if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
-
- const p = url.pathname;
-
- // --- Scripts ---
- if (p === '/live.js') {
- // Re-read from disk each request so edits to live-browser.js land on
- // the next tab reload. No-store headers prevent browser caching across
- // sessions — during iteration, a cached old script silently breaks
- // every subsequent session.
- let sessionScript;
- let liveScript;
- try {
- sessionScript = fs.readFileSync(sessionPath, 'utf-8');
- liveScript = fs.readFileSync(livePath, 'utf-8');
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'text/plain' });
- res.end('Error reading live browser scripts: ' + err.message);
- return;
- }
- const body =
- `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
- `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
- sessionScript + '\n' +
- liveScript;
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
- 'Pragma': 'no-cache',
- });
- res.end(body);
- return;
- }
- if (p === '/detect.js' || p === '/') {
- if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
- res.writeHead(200, { 'Content-Type': 'application/javascript' });
- res.end(detectScript);
- return;
- }
-
- // --- Vendored modern-screenshot (UMD build) ---
- // Lazy-loaded by live.js when the user clicks Go; exposes
- // window.modernScreenshot.domToBlob(...) for capture.
- if (p === '/modern-screenshot.js') {
- const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
- try {
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'public, max-age=31536000, immutable',
- });
- res.end(fs.readFileSync(vendorPath));
- } catch {
- res.writeHead(404); res.end('Vendor script not found');
- }
- return;
- }
-
- // --- Annotation upload (browser → server, raw PNG body) ---
- // Client generates the eventId, POSTs the PNG, then POSTs the generate
- // event with screenshotPath already set. Keeps bytes out of the SSE/poll
- // bridge and preserves the "one shot from the user's POV" UX.
- if (p === '/annotation' && req.method === 'POST') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const eventId = url.searchParams.get('eventId');
- if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid eventId' }));
- return;
- }
- if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
- res.writeHead(415, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
- return;
- }
- if (!state.sessionDir) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Session dir unavailable' }));
- return;
- }
- const chunks = [];
- let total = 0;
- let aborted = false;
- req.on('data', (c) => {
- if (aborted) return;
- total += c.length;
- if (total > MAX_ANNOTATION_BYTES) {
- aborted = true;
- res.writeHead(413, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Payload too large' }));
- req.destroy();
- return;
- }
- chunks.push(c);
- });
- req.on('end', () => {
- if (aborted) return;
- const absPath = path.join(state.sessionDir, eventId + '.png');
- try {
- fs.writeFileSync(absPath, Buffer.concat(chunks));
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Write failed: ' + err.message }));
- return;
- }
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true, path: absPath }));
- });
- req.on('error', () => {
- if (!aborted) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Upload failed' }));
- }
- });
- return;
- }
-
- // --- Health ---
- if (p === '/status') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
- const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok',
- port: state.port,
- connectedClients: state.sseClients.size,
- pendingEvents: state.pendingEvents.map((entry) => ({
- id: entry.event?.id,
- type: entry.event?.type,
- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),
- leaseUntil: entry.leaseUntil || null,
- })),
- activeSessions: sessions,
- }));
- return;
- }
-
- if (p === '/health') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok', port: state.port, mode: 'variant',
- hasProjectContext: hasProjectContext(),
- connectedClients: state.sseClients.size,
- }));
- return;
- }
-
- // --- Design system (unified v2 response) + raw ---
- // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json
- // sidecar when present. Panel merges them:
- // { present, parsed, sidecar, hasMd, hasSidecar,
- // mdNewerThanJson, parseError?, sidecarError? }
- // - parsed: output of parseDesignMd (frontmatter
- // + six canonical sections) when DESIGN.md exists.
- // - sidecar: .impeccable/design.json contents when present.
- // Expected shape: schemaVersion 2, carrying
- // extensions + components + narrative.
- // /design-system/raw returns DESIGN.md markdown verbatim
- if (p === '/design-system.json' || p === '/design-system/raw') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
-
- const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
- const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
- const mdStat = statOrNull(mdPath);
- const jsonStat = statOrNull(jsonPath);
-
- if (p === '/design-system/raw') {
- if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
- res.end(fs.readFileSync(mdPath, 'utf-8'));
- return;
- }
-
- if (!mdStat && !jsonStat) {
- res.writeHead(404, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ present: false }));
- return;
- }
-
- const response = {
- present: true,
- hasMd: !!mdStat,
- hasSidecar: !!jsonStat,
- mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
- };
-
- if (mdStat) {
- try {
- response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
- } catch (err) {
- response.parseError = err.message;
- }
- }
-
- if (jsonStat) {
- try {
- response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
- } catch (err) {
- response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;
- }
- }
-
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(response));
- return;
- }
-
- // --- Source file (no-HMR fallback) ---
- if (p === '/source') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const filePath = url.searchParams.get('path');
- if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
- const absPath = path.resolve(process.cwd(), filePath);
- if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
- let content;
- try { content = fs.readFileSync(absPath, 'utf-8'); }
- catch { res.writeHead(404); res.end('File not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
- res.end(content);
- return;
- }
-
- // --- SSE: server→browser push (replaces WebSocket) ---
- if (p === '/events' && req.method === 'GET') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- 'Connection': 'keep-alive',
- });
- res.write('data: ' + JSON.stringify({
- type: 'connected',
- hasProjectContext: hasProjectContext(),
- }) + '\n\n');
-
- state.sseClients.add(res);
- clearTimeout(state.exitTimer);
-
- // Keepalive: SSE comment every 30s prevents silent connection drops.
- const heartbeat = setInterval(() => {
- try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
- }, SSE_HEARTBEAT_INTERVAL);
-
- req.on('close', () => {
- clearInterval(heartbeat);
- state.sseClients.delete(res);
- if (state.sseClients.size === 0) {
- clearTimeout(state.exitTimer);
- state.exitTimer = setTimeout(() => {
- if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
- }, 8000);
- }
- });
- return;
- }
-
- // --- Browser→server events (replaces WebSocket messages) ---
- if (p === '/events' && req.method === 'POST') {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const error = validateEvent(msg);
- if (error) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error }));
- return;
- }
- if (state.sessionStore && msg.id) {
- try {
- state.sessionStore.appendEvent(msg);
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
- return;
- }
- }
- if (msg.type !== 'checkpoint') enqueueEvent(msg);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
- return;
- }
-
- // --- Stop ---
- if (p === '/stop') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.end('stopping');
- shutdown();
- return;
- }
-
- // --- Agent poll ---
- if (p === '/poll' && req.method === 'GET') {
- handlePollGet(req, res, url);
- return;
- }
- if (p === '/poll' && req.method === 'POST') {
- handlePollPost(req, res);
- return;
- }
-
- res.writeHead(404); res.end('Not found');
- };
-}
-
-// ---------------------------------------------------------------------------
-// Agent poll endpoints (unchanged from WS version)
-// ---------------------------------------------------------------------------
-
-function handlePollGet(req, res, url) {
- const token = url.searchParams.get('token');
- if (token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
- const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
- const available = findAvailablePendingEvent();
- if (available) {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(leaseEvent(available, leaseMs)));
- return;
- }
- const poll = { resolve, leaseMs };
- const timer = setTimeout(() => {
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ type: 'timeout' }));
- }, timeout);
- function resolve(event) {
- clearTimeout(timer);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(event));
- }
- state.pendingPolls.push(poll);
- scheduleLeaseFlush();
- req.on('close', () => {
- clearTimeout(timer);
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- });
-}
-
-function handlePollPost(req, res) {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- acknowledgePendingEvent(msg.id);
- if (state.sessionStore && msg.id) {
- try {
- const eventType = msg.type === 'discard' || msg.type === 'discarded'
- ? 'discarded'
- : msg.type === 'complete'
- ? 'complete'
- : msg.type === 'error'
- ? 'agent_error'
- : 'agent_done';
- state.sessionStore.appendEvent({
- type: eventType,
- id: msg.id,
- file: msg.file,
- message: msg.message,
- carbonize: msg.data?.carbonize === true,
- });
- } catch { /* keep reply path best-effort; browser still needs SSE */ }
- }
- flushPendingPolls();
- // Forward the reply to the browser via SSE
- broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Lifecycle
-// ---------------------------------------------------------------------------
-
-let httpServer = null;
-
-function shutdown() {
- removeLiveServerInfo(process.cwd());
- if (state.leaseTimer) clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- if (state.sessionDir) {
- try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}
- }
- for (const res of state.sseClients) { try { res.end(); } catch {} }
- state.sseClients.clear();
- for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });
- state.pendingPolls.length = 0;
- if (httpServer) httpServer.close();
- process.exit(0);
-}
-
-// ---------------------------------------------------------------------------
-// Main
-// ---------------------------------------------------------------------------
-
-const args = process.argv.slice(2);
-
-if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-server.mjs [options]
-
-Start the live variant mode server (zero dependencies).
-
-Commands:
- (default) Start the server (foreground)
- stop Stop the server and remove the injected live.js script tag
- stop --keep-inject Stop the server only (leave the script tag in the HTML entry)
-
-Options:
- --background Start detached, print connection JSON to stdout, then exit
- --port=PORT Use a specific port (default: auto-detect starting at 8400)
- --keep-inject Only with stop: skip live-inject.mjs --remove
- --help Show this help
-
-Endpoints:
- /live.js Browser script (element picker + variant cycling)
- /detect.js Detection overlay (backwards compatible)
- /modern-screenshot.js Vendored modern-screenshot UMD build (lazy-loaded by live.js)
- /annotation POST raw image/png to stage a variant screenshot
- /events SSE stream (server→browser) + POST (browser→server)
- /poll Long-poll for agent CLI
- /source Raw source file reader (no-HMR fallback)
- /status Durable recovery status (token-protected)
- /health Health check`);
- process.exit(0);
-}
-
-if (args.includes('stop')) {
- const keepInject = args.includes('--keep-inject');
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);
- if (res.ok) console.log(`Stopped live server on port ${info.port}.`);
- } catch {
- console.log('No running live server found.');
- }
- if (!keepInject) {
- const injectPath = path.join(__dirname, 'live-inject.mjs');
- try {
- const out = execFileSync(process.execPath, [injectPath, '--remove'], {
- encoding: 'utf-8',
- cwd: process.cwd(),
- });
- const line = out.trim().split('\n').filter(Boolean).pop();
- if (line) {
- try {
- const j = JSON.parse(line);
- if (j.removed === true) {
- console.log(`Removed live script tag from ${j.file}.`);
- }
- } catch {
- /* ignore non-JSON lines */
- }
- }
- } catch (err) {
- const detail = err.stderr?.toString?.().trim?.()
- || err.stdout?.toString?.().trim?.()
- || err.message
- || String(err);
- console.warn(`Note: could not remove live script tag (${detail.split('\n')[0]})`);
- }
- }
- process.exit(0);
-}
-
-// --background: spawn a detached child server, wait for it to be ready,
-// print the connection JSON, then exit. This keeps the startup command
-// simple (no shell backgrounding or chained commands).
-if (args.includes('--background')) {
- const childArgs = args.filter(a => a !== '--background');
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), ...childArgs], {
- detached: true,
- stdio: 'ignore',
- cwd: process.cwd(),
- });
- child.unref();
-
- // Poll for the PID file (the child writes it once the HTTP server is listening).
- const deadline = Date.now() + 10_000;
- while (Date.now() < deadline) {
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- if (info.pid !== process.pid) {
- // Output JSON so the agent can read port + token from stdout.
- console.log(JSON.stringify(info));
- process.exit(0);
- }
- } catch { /* not ready yet */ }
- await new Promise(r => setTimeout(r, 200));
- }
- console.error('Timed out waiting for live server to start.');
- process.exit(1);
-}
-
-// Check for existing session
-const existingRecord = readLiveServerInfo(process.cwd());
-if (existingRecord?.info) {
- const existing = existingRecord.info;
- try {
- process.kill(existing.pid, 0);
- console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
- console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');
- process.exit(1);
- } catch {
- try { fs.unlinkSync(existingRecord.path); } catch {}
- }
-}
-
-state.token = randomUUID();
-state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });
-restorePendingEventsFromStore();
-const portArg = args.find(a => a.startsWith('--port='));
-state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
-// Annotation screenshots live in the project root so the agent's Read tool
-// doesn't trip a per-file permission prompt. Sessioned by token so concurrent
-// projects (or quick restarts) don't collide.
-const annotRoot = getLiveAnnotationsDir(process.cwd());
-fs.mkdirSync(annotRoot, { recursive: true });
-state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));
-
-const { detectScript, sessionPath, livePath } = loadBrowserScripts();
-httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));
-
-httpServer.listen(state.port, '127.0.0.1', () => {
- writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });
- const url = `http://localhost:${state.port}`;
- console.log(`\nImpeccable live server running on ${url}`);
- console.log(`Token: ${state.token}\n`);
- console.log(`Inject: <script src="${url}/live.js"><\/script>`);
- console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
-});
-
-process.on('SIGINT', shutdown);
-process.on('SIGTERM', shutdown);
@@ -1,254 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';
-
-const COMPLETED_PHASES = new Set(['completed', 'discarded']);
-
-export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {
- const rootDir = getLiveSessionsDir(cwd);
- const legacyRootDir = getLegacyLiveSessionsDir(cwd);
- fs.mkdirSync(rootDir, { recursive: true });
- const snapshotCache = new Map();
-
- function loadCachedOrRebuild(id) {
- const cached = snapshotCache.get(id);
- if (cached) return cached;
- const journalPath = getReadableJournalPath(id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- return rebuilt;
- }
-
- function getReadableJournalPath(id) {
- const primary = getJournalPath(rootDir, id);
- if (fs.existsSync(primary)) return primary;
- const legacy = getJournalPath(legacyRootDir, id);
- if (fs.existsSync(legacy)) return legacy;
- return primary;
- }
-
- return {
- rootDir,
- legacyRootDir,
- appendEvent(event) {
- const normalized = normalizeEvent(event, sessionId);
- const journalPath = getJournalPath(rootDir, normalized.id);
- const snapshotPath = getSnapshotPath(rootDir, normalized.id);
- const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);
- if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {
- fs.copyFileSync(legacyJournalPath, journalPath);
- }
- const prior = loadCachedOrRebuild(normalized.id);
- const seq = prior.nextSeq;
- const entry = {
- seq,
- id: normalized.id,
- type: normalized.type,
- ts: new Date().toISOString(),
- event: normalized,
- };
- fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');
- const next = applyEvent(prior.snapshot, entry, prior.diagnostics);
- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });
- writeSnapshot(snapshotPath, next);
- return next;
- },
- getSnapshot(id = sessionId, opts = {}) {
- if (!id) throw new Error('session id required');
- const journalPath = getReadableJournalPath(id);
- const snapshotPath = getSnapshotPath(rootDir, id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- writeSnapshot(snapshotPath, rebuilt.snapshot);
- if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;
- return rebuilt.snapshot;
- },
- listActiveSessions() {
- const ids = new Set();
- for (const dir of [legacyRootDir, rootDir]) {
- if (!fs.existsSync(dir)) continue;
- for (const name of fs.readdirSync(dir)) {
- if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));
- }
- }
- return [...ids]
- .sort()
- .map((id) => this.getSnapshot(id))
- .filter(Boolean);
- },
- };
-}
-
-function normalizeEvent(event, fallbackId) {
- if (!event || typeof event !== 'object') throw new Error('event object required');
- const id = event.id || fallbackId;
- if (!id || typeof id !== 'string') throw new Error('event id required');
- if (!event.type || typeof event.type !== 'string') throw new Error('event type required');
- return { ...event, id };
-}
-
-function getJournalPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.jsonl');
-}
-
-function getSnapshotPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.snapshot.json');
-}
-
-function safeSessionId(id) {
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);
- return id;
-}
-
-function baseSnapshot(id) {
- return {
- id,
- phase: 'new',
- pageUrl: null,
- sourceFile: null,
- expectedVariants: 0,
- arrivedVariants: 0,
- visibleVariant: null,
- paramValues: {},
- pendingEventSeq: null,
- pendingEvent: null,
- deliveryLease: null,
- checkpointRevision: 0,
- activeOwner: null,
- sourceMarkers: {},
- fallbackMode: null,
- annotationArtifacts: [],
- diagnostics: [],
- updatedAt: null,
- };
-}
-
-function rebuildSnapshotFromJournal(journalPath, id) {
- let snapshot = baseSnapshot(id);
- const diagnostics = [];
- let nextSeq = 1;
- if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };
-
- const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- if (!line.trim()) continue;
- try {
- const entry = JSON.parse(line);
- if (!entry || typeof entry !== 'object') throw new Error('entry is not object');
- if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);
- snapshot = applyEvent(snapshot, entry);
- } catch (err) {
- diagnostics.push({
- error: 'journal_parse_failed',
- line: i + 1,
- message: err.message,
- });
- }
- }
- snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];
- return { snapshot, diagnostics, nextSeq };
-}
-
-function applyEvent(snapshot, entry, inheritedDiagnostics = []) {
- const event = entry.event || entry;
- const next = {
- ...snapshot,
- paramValues: { ...(snapshot.paramValues || {}) },
- sourceMarkers: { ...(snapshot.sourceMarkers || {}) },
- annotationArtifacts: [...(snapshot.annotationArtifacts || [])],
- diagnostics: [...(snapshot.diagnostics || [])],
- updatedAt: entry.ts || new Date().toISOString(),
- };
-
- if (inheritedDiagnostics.length && next.diagnostics.length === 0) {
- next.diagnostics = [...inheritedDiagnostics];
- }
-
- switch (event.type) {
- case 'generate':
- next.phase = 'generate_requested';
- next.pageUrl = event.pageUrl ?? next.pageUrl;
- next.expectedVariants = event.count ?? next.expectedVariants;
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });
- break;
- case 'variants_ready':
- case 'agent_done':
- next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';
- next.sourceFile = event.file ?? next.sourceFile;
- next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- if (event.carbonize === true) {
- next.diagnostics.push({
- error: 'carbonize_cleanup_required',
- file: event.file || null,
- message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',
- });
- }
- break;
- case 'checkpoint':
- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {
- next.phase = event.phase ?? next.phase;
- next.checkpointRevision = event.revision ?? next.checkpointRevision;
- next.activeOwner = event.owner ?? next.activeOwner;
- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;
- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- } else {
- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });
- }
- break;
- case 'accept':
- case 'accept_intent':
- next.phase = 'accept_requested';
- next.visibleVariant = Number(event.variantId ?? next.visibleVariant);
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discard':
- next.phase = 'discard_requested';
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discarded':
- next.phase = 'discarded';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'complete':
- next.phase = 'completed';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'agent_error':
- next.phase = 'agent_error';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });
- break;
- default:
- next.diagnostics.push({ error: 'unknown_event_type', type: event.type });
- break;
- }
- return next;
-}
-
-function toPendingEvent(event) {
- const pending = { ...event };
- delete pending.token;
- return pending;
-}
-
-function upsertArtifact(artifacts, artifact) {
- if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {
- artifacts.push(artifact);
- }
-}
-
-function writeSnapshot(snapshotPath, snapshot) {
- fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');
-}
@@ -1,47 +0,0 @@
-#!/usr/bin/env node
-/**
- * Print durable recovery status for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function fetchServerStatus(info) {
- if (!info) return null;
- try {
- const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-export async function statusCli() {
- const info = readServerInfo();
- const server = await fetchServerStatus(info);
- const store = createLiveSessionStore({ cwd: process.cwd() });
- const activeSessions = store.listActiveSessions();
- const payload = {
- liveServer: server ? {
- status: server.status,
- port: server.port,
- connectedClients: server.connectedClients,
- pendingEvents: server.pendingEvents,
- } : null,
- activeSessions: server?.activeSessions || activeSessions,
- recoveryHint: server
- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'
- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',
- };
- console.log(JSON.stringify(payload, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {
- statusCli();
-}
@@ -1,632 +0,0 @@
-/**
- * CLI helper: find an element in source and wrap it in a variant container.
- *
- * Usage:
- * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
- *
- * Searches project files for the element matching the query (class name, ID, or
- * text snippet), wraps it with the variant scaffolding, and prints the file path
- * + line range where the agent should insert variant HTML.
- *
- * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-export async function wrapCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable wrap [options]
-
-Find an element in source and wrap it in a variant container.
-
-Required:
- --id ID Session ID for the variant wrapper
- --count N Number of expected variants (1-8)
-
-Element identification (at least one required):
- --element-id ID HTML id attribute of the element
- --classes A,B,C Comma-separated CSS class names
- --tag TAG Tag name (div, section, etc.)
- --query TEXT Fallback: raw text to search for
-
-Optional:
- --file PATH Source file to search in (skips auto-detection)
- --text TEXT Picked element's textContent. Used to disambiguate when
- classes/tag match multiple sibling elements (e.g. a list
- of <Card>s with the same className). Pass the first ~80
- chars of event.element.textContent.
- --help Show this help message
-
-Output (JSON):
- { file, startLine, endLine, insertLine, commentSyntax }
-
-The agent should insert variant HTML at insertLine.`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const count = parseInt(argVal(args, '--count') || '3');
- const elementId = argVal(args, '--element-id');
- const classes = argVal(args, '--classes');
- const tag = argVal(args, '--tag');
- const query = argVal(args, '--query');
- const filePath = argVal(args, '--file');
- const text = argVal(args, '--text');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!elementId && !classes && !query) {
- console.error('Need at least one of: --element-id, --classes, --query');
- process.exit(1);
- }
-
- // Build search queries in priority order (most specific first)
- const queries = buildSearchQueries(elementId, classes, tag, query);
-
- const genOpts = { cwd: process.cwd() };
-
- // Find the source file. Generated files are excluded from auto-search so we
- // don't silently write variants into a file the next build will wipe.
- let targetFile = filePath;
- let matchedQuery = null;
- if (!targetFile) {
- for (const q of queries) {
- targetFile = findFileWithQuery(q, process.cwd(), genOpts);
- if (targetFile) { matchedQuery = q; break; }
- }
- if (!targetFile) {
- // Nothing in source. Did the element show up in a generated file? That
- // tells the agent "fall back to the agent-driven flow" vs "element just
- // doesn't exist in this project."
- let generatedHit = null;
- for (const q of queries) {
- generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
- if (generatedHit) break;
- }
- if (generatedHit) {
- console.error(JSON.stringify({
- error: 'element_not_in_source',
- fallback: 'agent-driven',
- generatedMatch: path.relative(process.cwd(), generatedHit),
- hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
- }));
- } else {
- console.error(JSON.stringify({
- error: 'element_not_found',
- fallback: 'agent-driven',
- hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
- }));
- }
- process.exit(1);
- }
- } else {
- if (isGeneratedFile(targetFile, genOpts)) {
- console.error(JSON.stringify({
- error: 'file_is_generated',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
- hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- matchedQuery = queries[0];
- }
-
- const content = fs.readFileSync(targetFile, 'utf-8');
- const lines = content.split('\n');
-
- // Find the element, trying each query in priority order. When `--text` is
- // supplied, collect every candidate the queries surface and disambiguate
- // by the picked element's textContent. Without `--text`, fall back to the
- // legacy first-match behavior so unmodified callers keep working.
- let match = null;
- if (text) {
- const candidates = [];
- for (const q of queries) {
- const all = findAllElements(lines, q, tag);
- for (const c of all) {
- if (!candidates.some((x) => x.startLine === c.startLine)) {
- candidates.push(c);
- }
- }
- // Once a more-specific query (ID, full className combo) yielded a unique
- // result, stop — falling through to the loose tag+single-class query
- // would readmit the siblings we just disambiguated past.
- if (candidates.length === 1) break;
- }
- if (candidates.length === 0) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- if (candidates.length === 1) {
- match = candidates[0];
- } else {
- const filtered = filterByText(candidates, lines, text);
- if (filtered.length === 1) {
- match = filtered[0];
- } else if (filtered.length === 0) {
- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the
- // browser-side textContent doesn't appear literally in source. Fall
- // back to first-match rather than refusing — this is the same
- // behavior unmodified callers see, just preserved.
- match = candidates[0];
- } else {
- // Multiple candidates ALSO match the text. Truly ambiguous — refuse
- // rather than pick wrong, and hand the agent the candidate locations
- // so it can disambiguate by reading the file.
- console.error(JSON.stringify({
- error: 'element_ambiguous',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), targetFile),
- candidates: filtered.map((c) => ({
- startLine: c.startLine + 1,
- endLine: c.endLine + 1,
- })),
- hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- }
- } else {
- for (const q of queries) {
- match = findElement(lines, q, tag);
- if (match) break;
- }
- if (!match) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- }
-
- const { startLine, endLine } = match;
- const commentSyntax = detectCommentSyntax(targetFile);
- const styleMode = detectStyleMode(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- const indent = lines[startLine].match(/^(\s*)/)[1];
-
- // Extract the original element. Reindent under the wrapper while preserving
- // the relative depth between lines — `l.trimStart()` would strip ALL leading
- // whitespace and collapse e.g. `<aside>`/` <h1>`/`</aside>` (6/8/6 spaces)
- // to a single uniform indent, so on accept/discard the round-trip restores
- // the inner element at its parent's depth instead of nested inside it.
- // Strip only the COMMON minimum leading whitespace across the picked lines;
- // `deindentContent` on the accept side already mirrors this convention.
- const originalLines = lines.slice(startLine, endLine + 1);
- const originalBaseIndent = minLeadingSpaces(originalLines);
- const reindentOriginal = (extra) => originalLines
- .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
- .join('\n');
- const originalIndented = reindentOriginal(' ');
-
- // Wrapper attributes differ by syntax. HTML allows plain string attrs;
- // JSX requires object-literal style and parses string attrs as HTML (which
- // either type-errors or renders a literal CSS string).
- const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
-
- // JSX/TSX guard: the picked element occupies a single JSX child slot
- // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
- // any other expression position). Replacing it with `comment + <div> +
- // comment` yields three adjacent siblings — invalid JSX. We can't use a
- // Fragment `<></>` either: parents that clone children (Radix `asChild`,
- // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
- // they try to pass an `id` through.
- //
- // Solution: keep the wrapper `<div>` as the single JSX-slot child and
- // tuck both marker comments INSIDE it. accept/discard then expands its
- // replacement range to include the wrapper's `<div>` open / close lines
- // so the entire scaffold gets removed cleanly.
- const wrapperLines = isJsx ? [
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- reindentOriginal(' '),
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- indent + '</div>',
- ] : [
- indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- originalIndented,
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + '</div>',
- indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- ];
-
- // Replace the original element with the wrapper
- const newLines = [
- ...lines.slice(0, startLine),
- ...wrapperLines,
- ...lines.slice(endLine + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- // Calculate insert line (the "insert below this line" comment).
- // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
- // the insert marker (HTML: start-comment + outer-div + Original-comment +
- // original-div + content + close-original-div; JSX: outer-div +
- // start-comment + Original-comment + original-div + content +
- // close-original-div). Multi-line originals push the marker by their
- // extra line count.
- const insertLine = startLine + 6 + (originalLines.length - 1);
-
- console.log(JSON.stringify({
- file: path.relative(process.cwd(), targetFile),
- startLine: startLine + 1, // 1-indexed for the agent
- // wrapperLines is an array but one element (the original-content slot)
- // is a `\n`-joined multi-line string, so the actual file-row count is
- // wrapperLines.length + (originalLines.length - 1). Without the offset,
- // endLine pointed inside the wrapper for any picked element that
- // spanned more than one source line.
- endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexed
- insertLine: insertLine + 1, // 1-indexed: where variants go
- commentSyntax: commentSyntax,
- styleMode: styleMode.mode,
- styleTag: styleMode.styleTag,
- cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
- cssAuthoring: buildCssAuthoring(styleMode, count),
- originalLineCount: originalLines.length,
- }));
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-/**
- * Build search query strings in priority order (most specific first).
- * ID is most reliable, then specific class combos, then single classes, then raw query.
- */
-function buildSearchQueries(elementId, classes, tag, query) {
- const queries = [];
-
- // 1. ID is the most specific
- if (elementId) {
- queries.push('id="' + elementId + '"');
- }
-
- // 2. Full class attribute match (for elements with distinctive multi-class combos).
- // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
- // convention the file uses will match.
- if (classes) {
- const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
- if (classList.length > 1) {
- const joined = classList.join(' ');
- const sorted = [...classList].sort((a, b) => b.length - a.length);
- queries.push('class="' + joined + '"');
- queries.push('className="' + joined + '"');
- queries.push(sorted[0]); // most distinctive single class, fallback
- } else if (classList.length === 1) {
- queries.push(classList[0]);
- }
- }
-
- // 3. Tag + class combo (e.g., <section class="hero">).
- // Same dual-emit for JSX compatibility.
- if (tag && classes) {
- const firstClass = classes.split(',')[0].trim();
- queries.push('<' + tag + ' class="' + firstClass);
- queries.push('<' + tag + ' className="' + firstClass);
- }
-
- // 4. Raw fallback query
- if (query) {
- queries.push(query);
- }
-
- return queries;
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- // HTML, Vue, Svelte, Astro all use HTML comments
- return { open: '<!--', close: '-->' };
-}
-
-function detectStyleMode(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.astro') {
- return {
- mode: 'astro-global-prefixed',
- styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',
- };
- }
- return {
- mode: 'scoped',
- styleTag: '<style data-impeccable-css="SESSION_ID">',
- };
-}
-
-function buildCssSelectorPrefixExamples(styleMode, count) {
- if (styleMode !== 'astro-global-prefixed') return [];
- return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);
-}
-
-function buildCssAuthoring(styleMode, count) {
- const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
- if (styleMode.mode === 'astro-global-prefixed') {
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'global-prefixed',
- rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',
- selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),
- requirements: [
- 'Use the styleTag exactly; the is:inline attribute is required for this file.',
- 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',
- 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
- ],
- forbidden: [
- 'Do not use @scope for this styleMode.',
- ],
- };
- }
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'scope-rule',
- rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',
- selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),
- requirements: [
- 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',
- 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
- 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
- ],
- forbidden: [
- 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',
- 'Do not add is:inline to the style tag for this styleMode.',
- ],
- };
-}
-
-/**
- * Search project files for the query string (class name, ID, etc.)
- * Returns the first matching file path, or null.
- */
-function findFileWithQuery(query, cwd, genOpts = {}) {
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, query, seen, 0, genOpts);
- if (result) return result;
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth, genOpts) {
- if (depth > 5) return null; // don't go too deep
- const realDir = fs.realpathSync(dir);
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- // Check files first
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name).toLowerCase();
- if (!EXTENSIONS.includes(ext)) continue;
-
- const filePath = path.join(dir, entry.name);
- if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip unreadable files */ }
- }
-
- // Then recurse into directories. Always skip node_modules and .git (never
- // project content). dist/build/out are left to the isGeneratedFile guard so
- // the includeGenerated second-pass can still find the element there and
- // report `generatedMatch`.
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
- if (result) return result;
- }
-
- return null;
-}
-
-/**
- * Regex that matches a tag opener on a line. Allows the tag name to be
- * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
- * openers (e.g. `<section\n className="..."\n>`) are recognised.
- */
-const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
-
-/**
- * Find the element's start and end line in the file.
- *
- * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
- * `id="..."`), or a raw text snippet. Because a query can appear on a
- * continuation line of a multi-line tag (e.g. the `className="..."` row of a
- * `<section\n className="..."\n>` JSX tag), we walk backward from the match
- * line to find the actual tag opener. When `tag` is provided, opener candidates
- * must match that tag name.
- */
-/**
- * Return the smallest leading-whitespace count across a set of lines,
- * ignoring blank lines (whose indent isn't load-bearing). Used to compute
- * the common base indent of a multi-line picked element so reindenting
- * under the wrapper preserves the relative depth between lines.
- */
-function minLeadingSpaces(lines) {
- let min = Infinity;
- for (const l of lines) {
- if (l.trim() === '') continue;
- const m = l.match(/^(\s*)/);
- if (m && m[1].length < min) min = m[1].length;
- }
- return min === Infinity ? 0 : min;
-}
-
-function findElement(lines, query, tag = null) {
- // Iterate all matches — the first substring hit isn't always the right one.
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
-
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- // Skip lines already inside a variant wrapper
- if (lines[i].includes('data-impeccable-variant')) continue;
-
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
-
- const endLine = findClosingLine(lines, openerLine);
- return { startLine: openerLine, endLine };
- }
-
- return null;
-}
-
-/**
- * Like findElement, but returns every match. Used for ambiguity detection
- * when the agent passes --text: when the same className appears on multiple
- * sibling elements (a list of cards, repeated section variants, etc.),
- * first-match silently lands on the wrong branch. Returning all matches lets
- * the caller narrow by textContent or fail with a structured ambiguity error.
- */
-function findAllElements(lines, query, tag = null) {
- const out = [];
- const seen = new Set();
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- if (lines[i].includes('data-impeccable-variant')) continue;
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
- if (seen.has(openerLine)) continue; // multiple matches inside the same element
- seen.add(openerLine);
- const endLine = findClosingLine(lines, openerLine);
- out.push({ startLine: openerLine, endLine });
- }
- return out;
-}
-
-/**
- * Narrow a candidate set to those whose source body matches a meaningful
- * prefix of the picked element's textContent. The compare strips tags and
- * JSX expressions, then checks two whitespace normalizations side-by-side:
- *
- * - single-space ("hero two second card body")
- * - no-whitespace ("herotwosecondcardbody")
- *
- * Both are needed because `el.textContent` concatenates sibling text without
- * inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
- * `"Hero TwoSecond…"`), while the source has whitespace between tags. If
- * EITHER normalization matches, the candidate keeps. A snippet shorter than
- * 8 chars after stripping is too weak to disambiguate — the caller falls
- * back to first-match.
- */
-function filterByText(candidates, lines, text) {
- const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
- // Too short to disambiguate. Return [] so the caller's `filtered.length
- // === 0` branch fires (fall back to first-match) — the previous
- // `candidates.slice()` return forced `filtered.length > 1` and surfaced
- // a spurious `element_ambiguous` error on every short-text picker event
- // with multiple candidates.
- if (trimmed.length < 8) return [];
- const targetSpaced = trimmed;
- const targetCompact = trimmed.replace(/\s+/g, '');
-
- return candidates.filter((c) => {
- const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
- const inner = body
- .replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
- .replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
- .toLowerCase();
- const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
- const sourceCompact = inner.replace(/\s+/g, '');
- return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
- });
-}
-
-/**
- * Resolve a match line to the real tag opener. If the match line itself opens
- * a tag, return it. Otherwise walk up to 10 lines backward looking for the
- * first tag opener. If `tag` is specified, the opener must match that tag
- * name; an opener with a different tag name aborts the backward walk for this
- * match (we don't jump across element boundaries).
- *
- * Returns the line index of the opener, or -1 if none can be resolved.
- */
-function findOpenerLine(lines, matchLine, tag) {
- const self = lines[matchLine].match(OPENER_RE);
- if (self) {
- if (!tag || self[1] === tag) return matchLine;
- return -1;
- }
- const MAX_BACKWALK = 10;
- for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
- const opener = lines[i].match(OPENER_RE);
- if (!opener) continue;
- if (!tag || opener[1] === tag) return i;
- // Different tag name than requested — abort; we're inside a non-target opener.
- return -1;
- }
- return -1;
-}
-
-/**
- * Starting from a line with an opening tag, find the line with the matching
- * closing tag by counting tag nesting depth.
- */
-function findClosingLine(lines, start) {
- const openMatch = lines[start].match(OPENER_RE);
- if (!openMatch) return start; // caller passed a non-opener; nothing to span
-
- const tagName = openMatch[1];
- let depth = 0;
- const openRe = new RegExp('<' + tagName + '(?=[\\s/>]|$)', 'g');
- const selfCloseRe = new RegExp('<' + tagName + '[^>]*/>', 'g');
- const closeRe = new RegExp('</' + tagName + '\\s*>', 'g');
-
- for (let i = start; i < lines.length; i++) {
- const line = lines[i];
- const opens = (line.match(openRe) || []).length;
- const selfCloses = (line.match(selfCloseRe) || []).length;
- const closes = (line.match(closeRe) || []).length;
-
- depth += opens - selfCloses - closes;
-
- if (depth <= 0) return i;
- }
-
- // If we can't find the close, return a reasonable guess
- return Math.min(start + 50, lines.length - 1);
-}
-
-// Auto-execute when run directly (node live-wrap.mjs ...)
-const _running = process.argv[1];
-if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {
- wrapCli();
-}
-
-// Test exports (used by tests/live-wrap.test.mjs)
-export { buildSearchQueries, findElement, findClosingLine, detectCommentSyntax };
@@ -1,247 +0,0 @@
-/**
- * CLI entry point: prepare everything needed to enter the live variant poll loop.
- *
- * Does (all in one command):
- * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)
- * 2. Start the live server in the background (or reuse a running one)
- * 3. Inject the browser script tag into the project's entry file
- * 4. Read PRODUCT.md / DESIGN.md for project context
- * 5. Print a single JSON blob with everything the agent needs
- *
- * After this, the agent's only remaining steps are:
- * - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll
- * - Enter the poll loop: `node live-poll.mjs`
- *
- * Usage:
- * node live.mjs # Prepare everything, print JSON, exit
- * node live.mjs --help
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { loadContext } from './load-context.mjs';
-import { resolveFiles } from './live-inject.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-async function liveCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live.mjs
-
-Prepare everything for live variant mode in a single command:
- - Checks .impeccable/live/config.json (required, created once per project)
- - Starts (or reuses) the live server in the background
- - Injects the browser script tag
- - Reads PRODUCT.md / DESIGN.md for project context
-
-On success, prints a JSON blob with:
- { ok, serverPort, serverToken, pageFile, hasContext, context }
-
-On config_missing, prints:
- { ok: false, error: "config_missing", configPath, hint }
-
-The agent should then:
- 1. If config_missing, create the config and re-run this script
- 2. Optionally open the project's dev/preview URL in the browser (see reference/live.md—not serverPort)
- 3. Enter the poll loop: node live-poll.mjs`);
- process.exit(0);
- }
-
- // 1. Check config (fail fast if missing — no point starting anything else)
- const checkOut = runScript('live-inject.mjs', ['--check']);
- const checkResult = safeParse(checkOut);
- if (!checkResult || !checkResult.ok) {
- console.log(JSON.stringify(checkResult || { ok: false, error: 'check_failed', raw: checkOut }));
- process.exit(0);
- }
-
- // 2. Start server (or reuse existing)
- const serverInfo = ensureServerRunning();
- if (!serverInfo) {
- console.log(JSON.stringify({ ok: false, error: 'server_start_failed' }));
- process.exit(1);
- }
-
- // 3. Inject the script tag at the current port
- const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)]);
- const injectResult = safeParse(injectOut);
- if (!injectResult || !injectResult.ok) {
- console.log(JSON.stringify({
- ok: false,
- error: 'inject_failed',
- detail: injectResult || injectOut,
- serverPort: serverInfo.port,
- }));
- process.exit(1);
- }
-
- // 4. Load PRODUCT.md + DESIGN.md context (auto-migrates legacy .impeccable.md)
- const ctx = loadContext(process.cwd());
-
- // 5. Compute drift-heal: compare resolved inject targets against the
- // project's HTML files. Orphans are HTML files not covered by config.
- // Warning only — the agent decides whether to act.
- const resolvedFiles = resolveFiles(process.cwd(), checkResult.config);
- const drift = scanForDrift(process.cwd(), resolvedFiles, checkResult.config);
-
- // 6. Emit everything the agent needs
- console.log(JSON.stringify({
- ok: true,
- serverPort: serverInfo.port,
- serverToken: serverInfo.token,
- pageFiles: resolvedFiles,
- configDrift: drift,
- hasProduct: ctx.hasProduct,
- product: ctx.product,
- productPath: ctx.productPath,
- hasDesign: ctx.hasDesign,
- design: ctx.design,
- designPath: ctx.designPath,
- migrated: ctx.migrated,
- }, null, 2));
-}
-
-/**
- * Drift-heal scan. Walks the project for HTML files under common
- * page-source directories (public/, src/, app/, pages/) and reports any
- * that aren't covered by the resolved inject targets. This is purely
- * advisory — the agent can ignore it, or suggest the user add the
- * orphans to config.files.
- *
- * Skipped if config.files already contains at least one glob pattern
- * covering everything in practice (signaled by the orphan count being 0).
- */
-function scanForDrift(rootDir, resolvedFiles, config) {
- const SCAN_ROOTS = ['public', 'src', 'app', 'pages'];
- const IGNORE_DIRS = new Set([
- 'node_modules', '.git', '.next', '.nuxt', '.svelte-kit', '.astro',
- '.turbo', '.vercel', '.cache', 'coverage', 'dist', 'build',
- ]);
-
- const resolvedSet = new Set(resolvedFiles.map((f) => f.split(path.sep).join('/')));
-
- // Files matching the user's `exclude` globs are intentional omissions,
- // not drift. Compile them to regexes so the orphan list stays signal.
- const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
- .map((p) => globToRegex(p));
- const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
-
- const orphans = [];
-
- const walk = (dir, relBase) => {
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
- for (const e of entries) {
- const rel = relBase ? `${relBase}/${e.name}` : e.name;
- if (e.isDirectory()) {
- if (IGNORE_DIRS.has(e.name) || e.name.startsWith('.')) continue;
- walk(path.join(dir, e.name), rel);
- } else if (e.isFile() && e.name.endsWith('.html')) {
- if (resolvedSet.has(rel)) continue;
- if (isUserExcluded(rel)) continue;
- orphans.push(rel);
- }
- }
- };
-
- for (const root of SCAN_ROOTS) {
- const abs = path.join(rootDir, root);
- if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
- walk(abs, root);
- }
- }
-
- if (orphans.length === 0) return null;
- const capped = orphans.slice(0, 20);
- return {
- orphans: capped,
- orphanCount: orphans.length,
- hint: `${orphans.length} HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like "public/**/*.html".`,
- };
-}
-
-/**
- * Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
- * to avoid a circular import (live-inject.mjs already imports nothing
- * from live.mjs). The two must stay in sync.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
- else { re += '.*'; i += 2; }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function runScript(name, args) {
- const scriptPath = path.join(__dirname, name);
- const cmd = `node "${scriptPath}" ${args.map(a => `"${a}"`).join(' ')}`;
- try {
- return execSync(cmd, { encoding: 'utf-8', cwd: process.cwd(), timeout: 15_000 });
- } catch (err) {
- // execSync throws on non-zero exit; return stdout if any
- return err.stdout || err.message || '';
- }
-}
-
-function safeParse(out) {
- try { return JSON.parse(String(out).trim()); } catch { return null; }
-}
-
-/**
- * Return { pid, port, token } for the running live server, starting one if needed.
- */
-function ensureServerRunning() {
- // Try to reuse an existing server
- try {
- const existing = readLiveServerInfo(process.cwd())?.info;
- if (existing && existing.pid) {
- try {
- process.kill(existing.pid, 0); // throws if dead
- return existing;
- } catch { /* stale PID file — the server script will clean it up */ }
- }
- } catch { /* no PID file */ }
-
- // Start a new server
- const out = runScript('live-server.mjs', ['--background']);
- return safeParse(out);
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live.mjs') || _running?.endsWith('live.mjs/')) {
- liveCli();
-}
@@ -1,141 +0,0 @@
-/**
- * Shared context loader for every impeccable command that needs to know
- * "who is this for" and "what does this look like".
- *
- * Input: project root (process.cwd()).
- *
- * Output (JSON to stdout):
- * {
- * hasProduct: boolean, // PRODUCT.md found (or auto-migrated)
- * product: string | null, // PRODUCT.md contents
- * productPath: string | null, // relative path
- * hasDesign: boolean, // DESIGN.md found
- * design: string | null, // DESIGN.md contents
- * designPath: string | null,
- * migrated: boolean, // true if we auto-renamed .impeccable.md -> PRODUCT.md
- * contextDir: string, // absolute path of the directory the files were found in
- * }
- *
- * Filename matching is case-insensitive for PRODUCT.md and DESIGN.md. The
- * Google DESIGN.md convention is uppercase at repo root; Kiro-style and
- * lowercase variants are also matched so users don't get punished for case.
- *
- * Lookup directory resolution (first match wins):
- * 1. process.env.IMPECCABLE_CONTEXT_DIR (absolute or relative to cwd)
- * 2. cwd, if PRODUCT.md / DESIGN.md / .impeccable.md is there (back-compat)
- * 3. Auto-fallback subdirectories of cwd: .agents/context/, then docs/
- * 4. cwd as a default "no context found" location
- *
- * Legacy `.impeccable.md` -> PRODUCT.md migration only fires at cwd root;
- * fallback directories are read-only as far as auto-rename is concerned.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
-const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
-const LEGACY_NAMES = ['.impeccable.md'];
-const FALLBACK_DIRS = ['.agents/context', 'docs'];
-
-/**
- * Resolve the directory that holds PRODUCT.md / DESIGN.md for
- * this project. Exported so other scripts (e.g. live-server.mjs) can read the
- * design files from the same location the loader uses.
- */
-export function resolveContextDir(cwd = process.cwd()) {
- // 1. Explicit override
- const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
- if (envDir && envDir.trim()) {
- const trimmed = envDir.trim();
- return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- }
-
- // 2. cwd wins if any canonical or legacy file is there. We check legacy too
- // so the auto-migration path in loadContext stays predictable.
- if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES, ...LEGACY_NAMES])) {
- return cwd;
- }
-
- // 3. Auto-fallback subdirs. Match if PRODUCT.md or DESIGN.md is present;
- // legacy `.impeccable.md` does not pull the lookup into a fallback dir.
- for (const rel of FALLBACK_DIRS) {
- const candidate = path.resolve(cwd, rel);
- if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
- return candidate;
- }
- }
-
- // 4. Nothing found — keep the historical "default to cwd" behaviour so the
- // caller's `hasProduct === false` branch still fires the same way.
- return cwd;
-}
-
-export function loadContext(cwd = process.cwd()) {
- let migrated = false;
- const contextDir = resolveContextDir(cwd);
-
- // 1. Look for PRODUCT.md (case-insensitive) in the resolved dir
- let productPath = firstExisting(contextDir, PRODUCT_NAMES);
-
- // 2. Legacy: if no PRODUCT.md but .impeccable.md exists at cwd root, rename
- // it in place. We only migrate at the root — fallback dirs are read-only
- // so we don't surprise users by mutating files under docs/ or .agents/.
- if (!productPath && contextDir === cwd) {
- const legacyPath = firstExisting(cwd, LEGACY_NAMES);
- if (legacyPath) {
- const newPath = path.join(cwd, 'PRODUCT.md');
- try {
- fs.renameSync(legacyPath, newPath);
- productPath = newPath;
- migrated = true;
- } catch {
- // Rename failed (permissions, etc.) — fall back to reading legacy in place
- productPath = legacyPath;
- }
- }
- }
-
- // 3. DESIGN.md (case-insensitive)
- const designPath = firstExisting(contextDir, DESIGN_NAMES);
-
- const product = productPath ? safeRead(productPath) : null;
- const design = designPath ? safeRead(designPath) : null;
-
- return {
- hasProduct: !!product,
- product,
- productPath: productPath ? path.relative(cwd, productPath) : null,
- hasDesign: !!design,
- design,
- designPath: designPath ? path.relative(cwd, designPath) : null,
- migrated,
- contextDir,
- };
-}
-
-function firstExisting(dir, names) {
- for (const name of names) {
- const abs = path.join(dir, name);
- if (fs.existsSync(abs)) return abs;
- }
- return null;
-}
-
-function safeRead(p) {
- try { return fs.readFileSync(p, 'utf-8'); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// CLI mode — print the context as JSON
-// ---------------------------------------------------------------------------
-
-function cli() {
- const result = loadContext(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('load-context.mjs') || _running?.endsWith('load-context.mjs/')) {
- cli();
-}
@@ -1,14 +0,0 @@
@@ -1,214 +0,0 @@
-#!/usr/bin/env node
-/**
- * Pin/unpin sub-commands as standalone skill shortcuts.
- *
- * Usage:
- * node <scripts_path>/pin.mjs pin <command>
- * node <scripts_path>/pin.mjs unpin <command>
- *
- * `pin audit` creates a lightweight /audit skill that redirects to /impeccable audit.
- * `unpin audit` removes that shortcut.
- *
- * The script discovers harness directories (.claude/skills, .cursor/skills, etc.)
- * in the project root and creates/removes the pin in all of them.
- */
-
-import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
-import { join, resolve, dirname } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-// All known harness directories
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Valid sub-command names
-const VALID_COMMANDS = [
- 'craft', 'teach', 'extract', 'document', 'shape',
- 'critique', 'audit',
- 'polish', 'bolder', 'quieter', 'distill', 'harden', 'onboard', 'live',
- 'animate', 'colorize', 'typeset', 'layout', 'delight', 'overdrive',
- 'clarify', 'adapt', 'optimize',
-];
-
-// Marker to identify pinned skills (so unpin doesn't delete user skills)
-const PIN_MARKER = '<!-- impeccable-pinned-skill -->';
-
-/**
- * Walk up from startDir to find a project root.
- */
-function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- while (dir !== '/') {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Find harness skill directories that have an impeccable skill installed.
- */
-function findHarnessDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const skillsDir = join(projectRoot, harness, 'skills');
- // Only pin in harness dirs that already have impeccable installed
- const impeccableDir = join(skillsDir, 'impeccable');
- if (existsSync(impeccableDir) || existsSync(join(skillsDir, 'i-impeccable'))) {
- dirs.push(skillsDir);
- }
- }
- return dirs;
-}
-
-/**
- * Load command metadata (descriptions for pinned skills).
- */
-function loadCommandMetadata() {
- const metadataPath = join(__dirname, 'command-metadata.json');
- if (existsSync(metadataPath)) {
- return JSON.parse(readFileSync(metadataPath, 'utf-8'));
- }
- return {};
-}
-
-/**
- * Generate a pinned skill's SKILL.md content.
- */
-function generatePinnedSkill(command, metadata) {
- const desc = metadata[command]?.description || `Shortcut for /impeccable ${command}.`;
- const hint = metadata[command]?.argumentHint || '[target]';
-
- return `---
-name: ${command}
-description: "${desc}"
-argument-hint: "${hint}"
-user-invocable: true
----
-
-${PIN_MARKER}
-
-This is a pinned shortcut for \`{{command_prefix}}impeccable ${command}\`.
-
-Invoke {{command_prefix}}impeccable ${command}, passing along any arguments provided here, and follow its instructions.
-`;
-}
-
-/**
- * Pin a command: create shortcut skill in all harness dirs.
- */
-function pin(command, projectRoot) {
- const metadata = loadCommandMetadata();
- const harnessDirs = findHarnessDirs(projectRoot);
-
- if (harnessDirs.length === 0) {
- console.log('No harness directories with impeccable installed found.');
- return false;
- }
-
- const content = generatePinnedSkill(command, metadata);
- let created = 0;
-
- for (const skillsDir of harnessDirs) {
- // Check if skill already exists (and isn't a pin)
- const skillDir = join(skillsDir, command);
- if (existsSync(skillDir)) {
- const existingMd = join(skillDir, 'SKILL.md');
- if (existsSync(existingMd)) {
- const existing = readFileSync(existingMd, 'utf-8');
- if (!existing.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (non-pinned skill already exists)`);
- continue;
- }
- }
- }
-
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(join(skillDir, 'SKILL.md'), content, 'utf-8');
- console.log(` + ${skillDir}`);
- created++;
- }
-
- if (created > 0) {
- console.log(`\nPinned '${command}' as a standalone shortcut in ${created} location(s).`);
- console.log(`You can now use /${command} directly.`);
- }
-
- return created > 0;
-}
-
-/**
- * Unpin a command: remove shortcut skill from all harness dirs.
- */
-function unpin(command, projectRoot) {
- const harnessDirs = findHarnessDirs(projectRoot);
- let removed = 0;
-
- for (const skillsDir of harnessDirs) {
- const skillDir = join(skillsDir, command);
- if (!existsSync(skillDir)) continue;
-
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) continue;
-
- // Safety: only remove if it's a pinned skill
- const content = readFileSync(skillMd, 'utf-8');
- if (!content.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (not a pinned skill)`);
- continue;
- }
-
- rmSync(skillDir, { recursive: true, force: true });
- console.log(` - ${skillDir}`);
- removed++;
- }
-
- if (removed > 0) {
- console.log(`\nUnpinned '${command}' from ${removed} location(s).`);
- console.log(`Use /impeccable ${command} to access it.`);
- } else {
- console.log(`No pinned '${command}' shortcut found.`);
- }
-
- return removed > 0;
-}
-
-// --- CLI ---
-const [,, action, command] = process.argv;
-
-if (!action || !command) {
- console.log('Usage: node pin.mjs <pin|unpin> <command>');
- console.log(`\nAvailable commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-if (action !== 'pin' && action !== 'unpin') {
- console.error(`Unknown action: ${action}. Use 'pin' or 'unpin'.`);
- process.exit(1);
-}
-
-if (!VALID_COMMANDS.includes(command)) {
- console.error(`Unknown command: ${command}`);
- console.error(`Available commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-const root = findProjectRoot();
-
-if (action === 'pin') {
- pin(command, root);
-} else {
- unpin(command, root);
-}
@@ -1,167 +0,0 @@
----
-name: impeccable
-description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
-version: 3.1.1
-user-invocable: true
-argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · teach|document|extract|live] [target]"
-license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
----
-
-Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
-
-## Setup
-
-Before any design work or file edits:
-
-1. Load context (PRODUCT.md / DESIGN.md) via the loader script.
-2. Identify the register and load the matching register reference (brand.md or product.md).
-3. **If the user invoked a sub-command (e.g. `craft`, `shape`, `audit`), load its reference file too.** This is non-negotiable: `craft` without `craft.md` loaded means you'll skip the shape-and-confirm step the user expects.
-
-Skipping these produces generic output that ignores the project.
-
-### 1. Context gathering
-
-Two files, case-insensitive. The loader looks at the project root by default and falls back to `.agents/context/` and `docs/` if the root is clean. Override with `IMPECCABLE_CONTEXT_DIR=path/to/dir` (absolute or relative to cwd).
-
-- **PRODUCT.md**: required. Users, brand, tone, anti-references, strategic principles.
-- **DESIGN.md**: optional, strongly recommended. Colors, typography, elevation, components.
-
-Load both in one call:
-
-```bash
-node .trae-cn/skills/impeccable/scripts/load-context.mjs
-```
-
-Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`. The output's `contextDir` field tells you where the files were resolved from.
-
-If the output is already in this session's conversation history, don't re-run. Exceptions requiring a fresh load: you just ran `/impeccable teach` or `/impeccable document` (they rewrite the files), or the user manually edited one.
-
-`/impeccable live` already warms context via `live.mjs`. If you've run `live.mjs`, don't also run `load-context.mjs` this session.
-
-If PRODUCT.md is missing, empty, or placeholder (`[TODO]` markers, <200 chars): run `/impeccable teach`, then resume the user's original task with the fresh context. If the original task was `/impeccable craft`, resume into `/impeccable shape` before any implementation work.
-
-If DESIGN.md is missing: nudge once per session (*"Run `/impeccable document` for more on-brand output"*), then proceed.
-
-### 2. Register
-
-Every design task is **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboard, tool: design SERVES the product).
-
-Identify before designing. Priority: (1) cue in the task itself ("landing page" vs "dashboard"); (2) the surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. First match wins.
-
-If PRODUCT.md lacks the `register` field (legacy), infer it once from its "Users" and "Product Purpose" sections, then cache the inferred value for the session. Suggest the user run `/impeccable teach` to add the field explicitly.
-
-Load the matching reference: [reference/brand.md](reference/brand.md) or [reference/product.md](reference/product.md). The shared design laws below apply to both.
-
-## Shared design laws
-
-Apply to every design, both registers. Match implementation complexity to the aesthetic vision: maximalism needs elaborate code, minimalism needs precision. Interpret creatively. Vary across projects; never converge on the same choices. the model is capable of extraordinary work. Don't hold back.
-
-### Color
-
-- Use OKLCH. Reduce chroma as lightness approaches 0 or 100; high chroma at extremes looks garish.
-- Never use `#000` or `#fff`. Tint every neutral toward the brand hue (chroma 0.005–0.01 is enough).
-- Pick a **color strategy** before picking colors. Four steps on the commitment axis:
- - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism.
- - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages.
- - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz.
- - **Drenched**: the surface IS the color. Brand heroes, campaign pages.
-- The "one accent ≤10%" rule is Restrained only. Committed / Full palette / Drenched exceed it on purpose. Don't collapse every design to Restrained by reflex.
-
-### Theme
-
-Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe."
-
-Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does.
-
-"Observability dashboard" does not force an answer. "SRE glancing at incident severity on a 27-inch monitor at 2am in a dim room" does. Run the sentence, not the category.
-
-### Typography
-
-- Cap body line length at 65–75ch.
-- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales.
-
-### Layout
-
-- Vary spacing for rhythm. Same padding everywhere is monotony.
-- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
-- Don't wrap everything in a container. Most things don't need one.
-
-### Motion
-
-- Don't animate CSS layout properties.
-- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
-
-### Absolute bans
-
-Match-and-refuse. If you're about to write any of these, rewrite the element with different structure.
-
-- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing.
-- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size.
-- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing.
-- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché.
-- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly.
-- **Modal as first thought.** Modals are usually laziness. Exhaust inline / progressive alternatives first.
-
-### Copy
-
-- Every word earns its place. No restated headings, no intros that repeat the title.
-- **No em dashes.** Use commas, colons, semicolons, periods, or parentheses. Also not `--`.
-
-### The AI slop test
-
-If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference.
-
-**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses.
-
-- **First-order:** if someone could guess the theme + palette from the category alone ("observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black"), it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
-- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families.
-
-## Commands
-
-| Command | Category | Description | Reference |
-|---|---|---|---|
-| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) |
-| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) |
-| `teach` | Build | Set up PRODUCT.md and DESIGN.md context | [reference/teach.md](reference/teach.md) |
-| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) |
-| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) |
-| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) |
-| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) |
-| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) |
-| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) |
-| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) |
-| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) |
-| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) |
-| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) |
-| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) |
-| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) |
-| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) |
-| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) |
-| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) |
-| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) |
-| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) |
-| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) |
-| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
-| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
-
-### Routing rules
-
-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
-3. **First word doesn't match**: general design invocation. Apply the setup steps, shared design laws, and the loaded register reference, using the full argument as context.
-
-Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `/impeccable`.
-
-If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `teach` as a blocker, finish teach, refresh context, then resume the original command and target.
-
-## Pin / Unpin
-
-**Pin** creates a standalone shortcut so `/<command>` invokes `/impeccable <command>` directly. **Unpin** removes it. The script writes to every harness directory present in the project.
-
-```bash
-node .trae-cn/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
-```
-
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
@@ -1,190 +0,0 @@
-> **Additional context needed**: target platforms/devices and usage contexts.
-
-Adapt an existing design to a different context: another screen size, device, platform, or use case. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context.
-
-
----
-
-## Assess Adaptation Challenge
-
-Understand what needs adaptation and why:
-
-1. **Identify the source context**:
- - What was it designed for originally? (Desktop web? Mobile app?)
- - What assumptions were made? (Large screen? Mouse input? Fast connection?)
- - What works well in current context?
-
-2. **Understand target context**:
- - **Device**: Mobile, tablet, desktop, TV, watch, print?
- - **Input method**: Touch, mouse, keyboard, voice, gamepad?
- - **Screen constraints**: Size, resolution, orientation?
- - **Connection**: Fast wifi, slow 3G, offline?
- - **Usage context**: On-the-go vs desk, quick glance vs focused reading?
- - **User expectations**: What do users expect on this platform?
-
-3. **Identify adaptation challenges**:
- - What won't fit? (Content, navigation, features)
- - What won't work? (Hover states on touch, tiny touch targets)
- - What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop)
-
-**CRITICAL**: Adaptation is rethinking the experience for the new context, not scaling pixels.
-
-## Plan Adaptation Strategy
-
-Create context-appropriate strategy:
-
-### Mobile Adaptation (Desktop → Mobile)
-
-**Layout Strategy**:
-- Single column instead of multi-column
-- Vertical stacking instead of side-by-side
-- Full-width components instead of fixed widths
-- Bottom navigation instead of top/side navigation
-
-**Interaction Strategy**:
-- Touch targets 44x44px minimum (not hover-dependent)
-- Swipe gestures where appropriate (lists, carousels)
-- Bottom sheets instead of dropdowns
-- Thumbs-first design (controls within thumb reach)
-- Larger tap areas with more spacing
-
-**Content Strategy**:
-- Progressive disclosure (don't show everything at once)
-- Prioritize primary content (secondary content in tabs/accordions)
-- Shorter text (more concise)
-- Larger text (16px minimum)
-
-**Navigation Strategy**:
-- Hamburger menu or bottom navigation
-- Reduce navigation complexity
-- Sticky headers for context
-- Back button in navigation flow
-
-### Tablet Adaptation (Hybrid Approach)
-
-**Layout Strategy**:
-- Two-column layouts (not single or three-column)
-- Side panels for secondary content
-- Master-detail views (list + detail)
-- Adaptive based on orientation (portrait vs landscape)
-
-**Interaction Strategy**:
-- Support both touch and pointer
-- Touch targets 44x44px but allow denser layouts than phone
-- Side navigation drawers
-- Multi-column forms where appropriate
-
-### Desktop Adaptation (Mobile → Desktop)
-
-**Layout Strategy**:
-- Multi-column layouts (use horizontal space)
-- Side navigation always visible
-- Multiple information panels simultaneously
-- Fixed widths with max-width constraints (don't stretch to 4K)
-
-**Interaction Strategy**:
-- Hover states for additional information
-- Keyboard shortcuts
-- Right-click context menus
-- Drag and drop where helpful
-- Multi-select with Shift/Cmd
-
-**Content Strategy**:
-- Show more information upfront (less progressive disclosure)
-- Data tables with many columns
-- Richer visualizations
-- More detailed descriptions
-
-### Print Adaptation (Screen → Print)
-
-**Layout Strategy**:
-- Page breaks at logical points
-- Remove navigation, footer, interactive elements
-- Black and white (or limited color)
-- Proper margins for binding
-
-**Content Strategy**:
-- Expand shortened content (show full URLs, hidden sections)
-- Add page numbers, headers, footers
-- Include metadata (print date, page title)
-- Convert charts to print-friendly versions
-
-### Email Adaptation (Web → Email)
-
-**Layout Strategy**:
-- Narrow width (600px max)
-- Single column only
-- Inline CSS (no external stylesheets)
-- Table-based layouts (for email client compatibility)
-
-**Interaction Strategy**:
-- Large, obvious CTAs (buttons not text links)
-- No hover states (not reliable)
-- Deep links to web app for complex interactions
-
-## Implement Adaptations
-
-Apply changes systematically:
-
-### Responsive Breakpoints
-
-Choose appropriate breakpoints:
-- Mobile: 320px-767px
-- Tablet: 768px-1023px
-- Desktop: 1024px+
-- Or content-driven breakpoints (where design breaks)
-
-### Layout Adaptation Techniques
-
-- **CSS Grid/Flexbox**: Reflow layouts automatically
-- **Container Queries**: Adapt based on container, not viewport
-- **`clamp()`**: Fluid sizing between min and max
-- **Media queries**: Different styles for different contexts
-- **Display properties**: Show/hide elements per context
-
-### Touch Adaptation
-
-- Increase touch target sizes (44x44px minimum)
-- Add more spacing between interactive elements
-- Remove hover-dependent interactions
-- Add touch feedback (ripples, highlights)
-- Consider thumb zones (easier to reach bottom than top)
-
-### Content Adaptation
-
-- Use `display: none` sparingly (still downloads)
-- Progressive enhancement (core content first, enhancements on larger screens)
-- Lazy loading for off-screen content
-- Responsive images (`srcset`, `picture` element)
-
-### Navigation Adaptation
-
-- Transform complex nav to hamburger/drawer on mobile
-- Bottom nav bar for mobile apps
-- Persistent side navigation on desktop
-- Breadcrumbs on smaller screens for context
-
-**IMPORTANT**: Test on real devices. Device emulation in DevTools is helpful but not perfect.
-
-**NEVER**:
-- Hide core functionality on mobile (if it matters, make it work)
-- Assume desktop = powerful device (consider accessibility, older machines)
-- Use different information architecture across contexts (confusing)
-- Break user expectations for platform (mobile users expect mobile patterns)
-- Forget landscape orientation on mobile/tablet
-- Use generic breakpoints blindly (use content-driven breakpoints)
-- Ignore touch on desktop (many desktop devices have touch)
-
-## Verify Adaptations
-
-Test thoroughly across contexts:
-
-- **Real devices**: Test on actual phones, tablets, desktops
-- **Different orientations**: Portrait and landscape
-- **Different browsers**: Safari, Chrome, Firefox, Edge
-- **Different OS**: iOS, Android, Windows, macOS
-- **Different input methods**: Touch, mouse, keyboard
-- **Edge cases**: Very small screens (320px), very large screens (4K)
-- **Slow connections**: Test on throttled network
-
-When the adaptation feels native to each context, hand off to `/impeccable polish` for the final pass.
@@ -1,175 +0,0 @@
-> **Additional context needed**: performance constraints.
-
-Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it.
-
----
-
-## Register
-
-Brand: orchestrated page-load sequences, staggered reveals, scroll-driven animation. Motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions.
-
-Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it.
-
----
-
-## Assess Animation Opportunities
-
-Analyze where motion would improve the experience:
-
-1. **Identify static areas**:
- - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.)
- - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes)
- - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious
- - **Lack of delight**: Functional but joyless interactions
- - **Missed guidance**: Opportunities to direct attention or explain behavior
-
-2. **Understand the context**:
- - What's the personality? (Playful vs serious, energetic vs calm)
- - What's the performance budget? (Mobile-first? Complex page?)
- - Who's the audience? (Motion-sensitive users? Power users who want speed?)
- - What matters most? (One hero animation vs many micro-interactions?)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them.
-
-## Plan Animation Strategy
-
-Create a purposeful animation plan:
-
-- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?)
-- **Feedback layer**: Which interactions need acknowledgment?
-- **Transition layer**: Which state changes need smoothing?
-- **Delight layer**: Where can we surprise and delight?
-
-**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments.
-
-## Implement Animations
-
-Add motion systematically across these categories:
-
-### Entrance Animations
-- **Page load choreography**: Stagger element reveals (100-150ms delays), fade + slide combinations
-- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects)
-- **Content reveals**: Scroll-triggered animations using intersection observer
-- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management
-
-### Micro-interactions
-- **Button feedback**:
- - Hover: Subtle scale (1.02-1.05), color shift, shadow increase
- - Click: Quick scale down then up (0.95 → 1), ripple effect
- - Loading: Spinner or pulse state
-- **Form interactions**:
- - Input focus: Border color transition, slight scale or glow
- - Validation: Shake on error, check mark on success, smooth color transitions
-- **Toggle switches**: Smooth slide + color transition (200-300ms)
-- **Checkboxes/radio**: Check mark animation, ripple effect
-- **Like/favorite**: Scale + rotation, particle effects, color transition
-
-### State Transitions
-- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms)
-- **Expand/collapse**: Height transition with overflow handling, icon rotation
-- **Loading states**: Skeleton screen fades, spinner animations, progress bars
-- **Success/error**: Color transitions, icon animations, gentle scale pulse
-- **Enable/disable**: Opacity transitions, cursor changes
-
-### Navigation & Flow
-- **Page transitions**: Crossfade between routes, shared element transitions
-- **Tab switching**: Slide indicator, content fade/slide
-- **Carousel/slider**: Smooth transforms, snap points, momentum
-- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators
-
-### Feedback & Guidance
-- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights
-- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning
-- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation
-- **Focus flow**: Highlight path through form or workflow
-
-### Delight Moments
-- **Empty states**: Subtle floating animations on illustrations
-- **Completed actions**: Confetti, check mark flourish, success celebrations
-- **Easter eggs**: Hidden interactions for discovery
-- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches
-
-## Technical Implementation
-
-Use appropriate techniques for each animation:
-
-### Timing & Easing
-
-**Durations by purpose:**
-- **100-150ms**: Instant feedback (button press, toggle)
-- **200-300ms**: State changes (hover, menu open)
-- **300-500ms**: Layout changes (accordion, modal)
-- **500-800ms**: Entrance animations (page load)
-
-**Easing curves (use these, not CSS defaults):**
-```css
-/* Recommended: natural deceleration */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */
-
-/* AVOID: feel dated and tacky */
-/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */
-/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */
-```
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-### CSS Animations
-```css
-/* Prefer for simple, declarative animations */
-- transitions for state changes
-- @keyframes for complex sequences
-- transform and opacity for reliable movement
-- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth
-```
-
-### JavaScript Animation
-```javascript
-/* Use for complex, interactive animations */
-- Web Animations API for programmatic control
-- Framer Motion for React
-- GSAP for complex sequences
-```
-
-### Performance
-- **Motion materials**: Use transform/opacity for reliable movement, but use blur, filters, masks, shadows, and color shifts when they materially improve the effect
-- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- **will-change**: Add sparingly for known expensive animations
-- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate
-- **Monitor FPS**: Ensure 60fps on target devices
-
-### Accessibility
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**NEVER**:
-- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself
-- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work
-- Use durations over 500ms for feedback (it feels laggy)
-- Animate without purpose (every animation needs a reason)
-- Ignore `prefers-reduced-motion` (this is an accessibility violation)
-- Animate everything (animation fatigue makes interfaces feel exhausting)
-- Block interaction during animations unless intentional
-
-## Verify Quality
-
-Test animations thoroughly:
-
-- **Smooth at 60fps**: No jank on target devices
-- **Feels natural**: Easing curves feel organic, not robotic
-- **Appropriate timing**: Not too fast (jarring) or too slow (laggy)
-- **Reduced motion works**: Animations disabled or simplified appropriately
-- **Doesn't block**: Users can interact during/after animations
-- **Adds value**: Makes interface clearer or more delightful
-
-When the motion clarifies state instead of decorating it, hand off to `/impeccable polish` for the final pass.
@@ -1,133 +0,0 @@
-Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues; document them for other commands to address.
-
-This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation.
-
-## Diagnostic Scan
-
-Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below.
-
-### 1. Accessibility (A11y)
-
-**Check for**:
-- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA)
-- **Missing ARIA**: Interactive elements without proper roles, labels, or states
-- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps
-- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons
-- **Alt text**: Missing or poor image descriptions
-- **Form issues**: Inputs without labels, poor error messaging, missing required indicators
-
-**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA)
-
-### 2. Performance
-
-**Check for**:
-- **Layout thrashing**: Reading/writing layout properties in loops
-- **Expensive animations**: Casual layout-property animation, unbounded blur/filter/shadow effects, or effects that visibly drop frames
-- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change
-- **Bundle size**: Unnecessary imports, unused dependencies
-- **Render performance**: Unnecessary re-renders, missing memoization
-
-**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized)
-
-### 3. Theming
-
-**Check for**:
-- **Hard-coded colors**: Colors not using design tokens
-- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme
-- **Inconsistent tokens**: Using wrong tokens, mixing token types
-- **Theme switching issues**: Values that don't update on theme change
-
-**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly)
-
-### 4. Responsive Design
-
-**Check for**:
-- **Fixed widths**: Hard-coded widths that break on mobile
-- **Touch targets**: Interactive elements < 44x44px
-- **Horizontal scroll**: Content overflow on narrow viewports
-- **Text scaling**: Layouts that break when text size increases
-- **Missing breakpoints**: No mobile/tablet variants
-
-**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets)
-
-### 5. Anti-Patterns (CRITICAL)
-
-Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy).
-
-**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design)
-
-## Generate Report
-
-### Audit Health Score
-
-| # | Dimension | Score | Key Finding |
-|---|-----------|-------|-------------|
-| 1 | Accessibility | ? | [most critical a11y issue or "--"] |
-| 2 | Performance | ? | |
-| 3 | Responsive Design | ? | |
-| 4 | Theming | ? | |
-| 5 | Anti-Patterns | ? | |
-| **Total** | | **??/20** | **[Rating band]** |
-
-**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues)
-
-### Anti-Patterns Verdict
-**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest.
-
-### Executive Summary
-- Audit Health Score: **??/20** ([rating band])
-- Total issues found (count by severity: P0/P1/P2/P3)
-- Top 3-5 critical issues
-- Recommended next steps
-
-### Detailed Findings by Severity
-
-Tag every issue with **P0-P3 severity**:
-- **P0 Blocking**: Prevents task completion. Fix immediately
-- **P1 Major**: Significant difficulty or WCAG AA violation. Fix before release
-- **P2 Minor**: Annoyance, workaround exists. Fix in next pass
-- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits
-
-For each issue, document:
-- **[P?] Issue name**
-- **Location**: Component, file, line
-- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern
-- **Impact**: How it affects users
-- **WCAG/Standard**: Which standard it violates (if applicable)
-- **Recommendation**: How to fix it
-- **Suggested command**: Which command to use (prefer: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-### Patterns & Systemic Issues
-
-Identify recurring problems that indicate systemic gaps rather than one-off mistakes:
-- "Hard-coded colors appear in 15+ components, should use design tokens"
-- "Touch targets consistently too small (<44px) throughout mobile experience"
-
-### Positive Findings
-
-Note what's working well: good practices to maintain and replicate.
-
-## Recommended Actions
-
-List recommended commands in priority order (P0 first, then P1, then P2):
-
-1. **[P?] `/command-name`**: Brief description (specific context from audit findings)
-2. **[P?] `/command-name`**: Brief description (specific context)
-
-**Rules**: Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset. Map findings to the most appropriate command. End with `/impeccable polish` as the final step if any fixes were recommended.
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable audit` after fixes to see your score improve.
-
-**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters.
-
-**NEVER**:
-- Report issues without explaining impact (why does this matter?)
-- Provide generic recommendations (be specific and actionable)
-- Skip positive findings (celebrate what works)
-- Forget to prioritize (everything can't be P0)
-- Report false positives without verification
-
@@ -1,113 +0,0 @@
-When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact and personality through stronger hierarchy, committed scale, and decisive type.
-
----
-
-## Register
-
-Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
-
-Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too safe or boring:
-
-1. **Identify weakness sources**:
- - **Generic choices**: System fonts, basic colors, standard layouts
- - **Timid scale**: Everything is medium-sized with no drama
- - **Low contrast**: Everything has similar visual weight
- - **Static**: No motion, no energy, no life
- - **Predictable**: Standard patterns with no surprises
- - **Flat hierarchy**: Nothing stands out or commands attention
-
-2. **Understand the context**:
- - What's the brand personality? (How far can we push?)
- - What's the purpose? (Marketing can be bolder than financial dashboards)
- - Who's the audience? (What will resonate?)
- - What are the constraints? (Brand guidelines, accessibility, performance)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
-
-**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
-
-## Plan Amplification
-
-Create a strategy to increase impact while maintaining coherence:
-
-- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
-- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
-- **Risk budget**: How experimental can we be? Push boundaries within constraints.
-- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
-
-**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration.
-
-## Amplify the Design
-
-Systematically increase impact across these dimensions:
-
-### Typography Amplification
-- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and [typography.md](typography.md) for inspiration)
-- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
-- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
-- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
-
-### Color Intensification
-- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
-- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop
-- **Dominant color strategy**: Let one bold color own 60% of the design
-- **Sharp accents**: High-contrast accent colors that pop
-- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
-- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
-
-### Spatial Drama
-- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
-- **Break the grid**: Let hero elements escape containers and cross boundaries
-- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
-- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
-- **Overlap**: Layer elements intentionally for depth
-
-### Visual Effects
-- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
-- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
-- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop)
-- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
-- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
-
-### Motion & Animation
-- **Entrance choreography**: Staggered, dramatic page load animations with 50-100ms delays
-- **Scroll effects**: Parallax, reveal animations, scroll-triggered sequences
-- **Micro-interactions**: Satisfying hover effects, click feedback, state changes
-- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect)
-
-### Composition Boldness
-- **Hero moments**: Create clear focal points with dramatic treatment
-- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
-- **Full-bleed elements**: Use full viewport width/height for impact
-- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
-
-**NEVER**:
-- Add effects randomly without purpose (chaos ≠ bold)
-- Sacrifice readability for aesthetics (body text must be readable)
-- Make everything bold (then nothing is bold; you need contrast)
-- Ignore accessibility (bold design must still meet WCAG standards)
-- Overwhelm with motion (animation fatigue is real)
-- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
-
-## Verify Quality
-
-Ensure amplification maintains usability and coherence:
-
-- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over.
-- **Still functional**: Can users accomplish tasks without distraction?
-- **Coherent**: Does everything feel intentional and unified?
-- **Memorable**: Will users remember this experience?
-- **Performant**: Do all these effects run smoothly?
-- **Accessible**: Does it still meet accessibility standards?
-
-**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects."
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,118 +0,0 @@
-# Brand register
-
-When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made.
-
-The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look.
-
-## The brand slop test
-
-If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?"
-
-Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home.
-
-**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register.
-
-Then the inverse test: in one sentence, describe what you're about to build the way a competitor would describe theirs. If that sentence fits the modal landing page in the category, restart.
-
-## Typography
-
-### Font selection procedure
-
-Every project. Never skip.
-
-1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words.
-2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture.
-3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy."
-4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over.
-
-### Reflex-reject list
-
-Training-data defaults. Ban list. Look further:
-
-Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif
-
-### Reflex-reject aesthetic lanes
-
-Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further.
-
-- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery.
-
-(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.)
-
-The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md).
-
-### Pairing and voice
-
-Distinctive + refined is the goal. The specific shape depends on the brand:
-
-- **Editorial / long-form / luxury**: display serif + sans body (a magazine shape).
-- **Tech / dev tools / fintech**: one committed sans, usually; custom-tight tracking, strong weight contrast inside a single family.
-- **Consumer / food / travel**: warmer pairings, often a humanist sans plus a script or display serif.
-- **Creative studios / agencies**: rule-breaking welcome. Mono-only, or display-only, or custom-drawn type as voice.
-
-Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair.
-
-Vary across projects. If the last brief was a serif-display landing page, this one isn't.
-
-### Scale
-
-Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted.
-
-Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room.
-
-## Color
-
-Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register.
-
-- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige.
-- Palette IS voice. A calm brand and a restless brand should not share palette mechanics.
-- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit.
-- Don't converge across projects. If the last brand surface was restrained-on-cream, this one is not.
-- When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette.
-
-## Layout
-
-- Asymmetric compositions are one option. Break the grid intentionally for emphasis.
-- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings.
-- Alternative: a strict, visible grid as the voice (brutalist / Swiss / tech-spec aesthetics). Either asymmetric or rigorously-gridded can be "designed"; the failure mode is splitting the difference into a generic centered stack.
-- Don't default to centering everything. Left-aligned with asymmetric layouts feels more designed; a strict grid reads as confident structure. A centered-stack hero with icon-title-subtitle cards reads as template.
-- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness.
-
-## Imagery
-
-Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo.
-
-**When the brief implies imagery (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product), you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy.
-
-- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `<div>` placeholders.
-- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel".
-- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one.
-- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish".
-
-"Imagery" here is broader than stock photography: product screenshots, custom data visualizations, generated SVG, and canvas/WebGL scenes are all imagery. Text-only pages where typography alone carries the entire visual weight are the failure mode.
-
-## Motion
-
-- One well-orchestrated page-load with staggered reveals beats scattered micro-interactions, when the brand invites it. Tech-minimal brands often skip entrance motion entirely; the restraint is the voice.
-- For collapsing/expanding sections, transition `grid-template-rows` rather than `height`.
-
-## Brand bans (on top of the shared absolute bans)
-
-- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume.
-- Large rounded-corner icons above every heading. Screams template.
-- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.)
-- All-caps body copy. Reserve caps for short labels and headings.
-- Timid palettes and average layouts. Safe = invisible.
-- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs.
-- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic.
-- Repeated tiny uppercase tracked labels above every section heading. A single strong kicker can be voice; repeating it as section grammar is AI scaffolding unless it's a deliberate, named brand system.
-
-## Brand permissions
-
-Brand can afford things product can't. Take them.
-
-- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography.
-- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing.
-- Typographic risk. Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines, a single oversize word as a hero.
-- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics.
-- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment.
@@ -1,174 +0,0 @@
-> **Additional context needed**: audience technical level and users' mental state in context.
-
-Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task.
-
-
----
-
-## Assess Current Copy
-
-Identify what makes the text unclear or ineffective:
-
-1. **Find clarity problems**:
- - **Jargon**: Technical terms users won't understand
- - **Ambiguity**: Multiple interpretations possible
- - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file"
- - **Length**: Too wordy or too terse
- - **Assumptions**: Assuming user knowledge they don't have
- - **Missing context**: Users don't know what to do or why
- - **Tone mismatch**: Too formal, too casual, or inappropriate for situation
-
-2. **Understand the context**:
- - Who's the audience? (Technical? General? First-time users?)
- - What's the user's mental state? (Stressed during error? Confident during success?)
- - What's the action? (What do we want users to do?)
- - What's the constraint? (Character limits? Space limitations?)
-
-**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets.
-
-## Plan Copy Improvements
-
-Create a strategy for clearer communication:
-
-- **Primary message**: What's the ONE thing users need to know?
-- **Action needed**: What should users do next (if anything)?
-- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?)
-- **Constraints**: Length limits, brand voice, localization considerations
-
-**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words.
-
-## Improve Copy Systematically
-
-Refine text across these common areas:
-
-### Error Messages
-**Bad**: "Error 403: Forbidden"
-**Good**: "You don't have permission to view this page. Contact your admin for access."
-
-**Bad**: "Invalid input"
-**Good**: "Email addresses need an @ symbol. Try: name@example.com"
-
-**Principles**:
-- Explain what went wrong in plain language
-- Suggest how to fix it
-- Don't blame the user
-- Include examples when helpful
-- Link to help/support if applicable
-
-### Form Labels & Instructions
-**Bad**: "DOB (MM/DD/YYYY)"
-**Good**: "Date of birth" (with placeholder showing format)
-
-**Bad**: "Enter value here"
-**Good**: "Your email address" or "Company name"
-
-**Principles**:
-- Use clear, specific labels (not generic placeholders)
-- Show format expectations with examples
-- Explain why you're asking (when not obvious)
-- Put instructions before the field, not after
-- Keep required field indicators clear
-
-### Button & CTA Text
-**Bad**: "Click here" | "Submit" | "OK"
-**Good**: "Create account" | "Save changes" | "Got it, thanks"
-
-**Principles**:
-- Describe the action specifically
-- Use active voice (verb + noun)
-- Match user's mental model
-- Be specific ("Save" is better than "OK")
-
-### Help Text & Tooltips
-**Bad**: "This is the username field"
-**Good**: "Choose a username. You can change this later in Settings."
-
-**Principles**:
-- Add value (don't just repeat the label)
-- Answer the implicit question ("What is this?" or "Why do you need this?")
-- Keep it brief but complete
-- Link to detailed docs if needed
-
-### Empty States
-**Bad**: "No items"
-**Good**: "No projects yet. Create your first project to get started."
-
-**Principles**:
-- Explain why it's empty (if not obvious)
-- Show next action clearly
-- Make it welcoming, not dead-end
-
-### Success Messages
-**Bad**: "Success"
-**Good**: "Settings saved! Your changes will take effect immediately."
-
-**Principles**:
-- Confirm what happened
-- Explain what happens next (if relevant)
-- Be brief but complete
-- Match the user's emotional moment (celebrate big wins)
-
-### Loading States
-**Bad**: "Loading..." (for 30+ seconds)
-**Good**: "Analyzing your data... this usually takes 30-60 seconds"
-
-**Principles**:
-- Set expectations (how long?)
-- Explain what's happening (when it's not obvious)
-- Show progress when possible
-- Offer escape hatch if appropriate ("Cancel")
-
-### Confirmation Dialogs
-**Bad**: "Are you sure?"
-**Good**: "Delete 'Project Alpha'? This can't be undone."
-
-**Principles**:
-- State the specific action
-- Explain consequences (especially for destructive actions)
-- Use clear button labels ("Delete project" not "Yes")
-- Don't overuse confirmations (only for risky actions)
-
-### Navigation & Wayfinding
-**Bad**: Generic labels like "Items" | "Things" | "Stuff"
-**Good**: Specific labels like "Your projects" | "Team members" | "Settings"
-
-**Principles**:
-- Be specific and descriptive
-- Use language users understand (not internal jargon)
-- Make hierarchy clear
-- Consider information scent (breadcrumbs, current location)
-
-## Apply Clarity Principles
-
-Every piece of copy should follow these rules:
-
-1. **Be specific**: "Enter email" not "Enter value"
-2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity)
-3. **Be active**: "Save changes" not "Changes will be saved"
-4. **Be human**: "Oops, something went wrong" not "System error encountered"
-5. **Tell users what to do**, not just what happened
-6. **Be consistent**: Use same terms throughout (don't vary for variety)
-
-**NEVER**:
-- Use jargon without explanation
-- Blame users ("You made an error" → "This field is required")
-- Be vague ("Something went wrong" without explanation)
-- Use passive voice unnecessarily
-- Write overly long explanations (be concise)
-- Use humor for errors (be empathetic instead)
-- Assume technical knowledge
-- Vary terminology (pick one term and stick with it)
-- Repeat information (headers restating intros, redundant explanations)
-- Use placeholders as the only labels (they disappear when users type)
-
-## Verify Improvements
-
-Test that copy improvements work:
-
-- **Comprehension**: Can users understand without context?
-- **Actionability**: Do users know what to do next?
-- **Brevity**: Is it as short as possible while remaining clear?
-- **Consistency**: Does it match terminology elsewhere?
-- **Tone**: Is it appropriate for the situation?
-
-When the copy reads cleanly, hand off to `/impeccable polish` for the final pass.
@@ -1,105 +0,0 @@
-# Codex: Visual Direction & Asset Production
-
-This file is loaded by `/impeccable craft` when the harness has native image generation (currently Codex via `image_gen`). Other harnesses skip it. It covers the two craft steps that depend on real image generation: landing the visual direction, and producing the raster assets the implementation will compose.
-
-Read this *before* generating any images. The order matters, and the per-step user pauses are what keep generated imagery from drifting away from the brief.
-
-### Four stop points before code
-
-Steps A through D each end with the user. Do not advance past any of them on your own read of the situation.
-
-1. **STOP after Step A questions.** Wait for answers.
-2. **STOP after Step B palette generation.** Wait for "confirm palette."
-3. **STOP after Step C mocks.** Wait for direction approval or delegation.
-4. **Only after Step D approves a direction** do you return to craft.md Step 4 and write code.
-
-Prior shape approval does **not** satisfy any of these. Shape's "confirm or override" advances you into Step A; it is not a substitute for it.
-
-## Step A: Explore Directions with the User
-
-Before generating anything, run a brief direction conversation grounded in the shape brief.
-
-**Step A is required even when shape just produced a confirmed brief.** The shape questions and Step A questions cover different ground: shape pins purpose, content, scope; Step A pins palette, atmosphere, and named visual references for the comps you're about to generate. The only time you can skip Step A is when the user has already answered these exact palette/atmosphere/reference questions in the same session.
-
-Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions:
-
-- "Brief says 'editorial restraint, Klim-adjacent.' Are we closer to a quiet specimen page or a magazine-spread feel with hero imagery?"
-- "Palette strategy from shape was 'Committed.' Want it warm-grounded (deep oxblood + cream) or cool-grounded (slate + paper white)?"
-
-**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded.
-
-## Step B: Generate the Brand Palette First
-
-Generate **one** palette artifact before any mocks. This is a small, focused image: typography pairing on the chosen background, primary + accent color swatches, one signature ornament or motif. Single image, single pass.
-
-Why palette first: mocks generated against a vague color sense produce noise that drowns out the structural decisions. A confirmed palette is the first concrete contract for everything downstream.
-
-Show the palette to the user. Ask one question: "This is the palette I'm locking in for the mocks. Confirm, or call out what to shift?"
-
-**STOP and wait for confirmation.** Do not generate mocks against an unconfirmed palette. "Probably good enough" is the wrong call here; the palette is the contract for everything downstream.
-
-## Step C: Generate 1-3 Visual Mocks Against the Palette
-
-Once the palette is confirmed, generate **1 to 3** high-fidelity north-star comps. Each mock must use the confirmed palette and typography. Mocks differ in *structural* direction (hierarchy, topology, density, composition), not in color or motif.
-
-- Brand work: push visual identity, composition, mood, and signature motifs.
-- Product work: push hierarchy, topology, density, tone, grounded in realistic product structure.
-- Landing pages and long-form brand surfaces: show enough of the second fold to establish the system beyond the hero.
-
-Use the `image_gen` tool directly (or via the imagegen skill when available). Don't ask the user to install anything.
-
-## Step D: Approval Loop
-
-Show the comps. Ask what carries forward. Iterate until **one direction is approved** or the user explicitly delegates.
-
-**STOP and wait for the approval or the delegation.** Do not begin Step E or return to craft.md Step 4 until a single direction is named. If the user delegates, pick the strongest direction and explain it from the brief, not personal taste.
-
-Before moving to assets, summarize what to carry into code and what *not* to literalize from the mock. This is the handoff between visual exploration and semantic implementation.
-
-## Step E: Mock Fidelity Inventory
-
-Inventory the approved mock's major visible ingredients. For each, decide implementation: semantic HTML/CSS/SVG, generated raster, sourced raster, icon library, canvas/WebGL, or accepted omission.
-
-Common ingredients to inventory:
-
-- Hero silhouette and dominant composition
-- Signature motifs (planets, devices, portraits, charts, route lines, insets, badges, etc.)
-- Nav and primary CTA treatment
-- Section sequence, especially the second fold
-- Image-native content the concept depends on
-- Typography, density, color/material treatment, motion cues
-
-Treat the mock as a north star, not a screenshot to trace. Don't rasterize core UI text. But if the live result lacks the mock's major ingredients, the implementation is wrong.
-
-If a photographic, architectural, product, or place-led mock becomes generic CSS scenery, decorative diagrams, bullets, or copy, stop and fix it. That's a broken implementation, not a harmless interpretation.
-
-Don't substitute a different hero composition or visual driver post-approval without user sign-off.
-
-## Step F: Asset Slicing via the Asset Producer
-
-Raster ingredients identified in Step E need clean production assets. Use the bundled `impeccable_asset_producer` subagent rather than producing inline.
-
-Spawn it as a scoped subagent. If you do not have explicit permission to use agents, stop and ask:
-
-```text
-Asset production will work better as a scoped subagent job. Should I spawn the Impeccable asset producer subagent for this step?
-```
-
-Pass to the agent:
-
-- Approved mock path or screenshot reference
-- Crop paths or a contact sheet with crop ids
-- Output directory
-- Required dimensions, format, transparency needs
-- Avoid list
-- Notes on what should remain semantic HTML/CSS/SVG instead of raster
-
-Attach image generation capability to the spawned agent when the harness supports it. Do **not** load image-generation reference material into the parent thread.
-
-Inline asset production is allowed only if the user declines subagents, the harness cannot spawn the authorized agent, or the user explicitly asks for single-thread mode.
-
-Prefer HTML/CSS/SVG/canvas when they can credibly reproduce an ingredient; reach for real, generated, or stock imagery when the mock or subject matter calls for actual visual content.
-
-## After This File
-
-Once Steps A through F are complete, return to `craft.md` Step 5 (Build to Production Quality). The implementation builds against the confirmed palette, approved mock, and the assets the producer wrote.
@@ -1,106 +0,0 @@
-# Cognitive Load Assessment
-
-Cognitive load is the total mental effort required to use an interface. Overloaded users make mistakes, get frustrated, and leave. This reference helps identify and fix cognitive overload.
-
----
-
-## Three Types of Cognitive Load
-
-### Intrinsic Load: The Task Itself
-Complexity inherent to what the user is trying to do. You can't eliminate this, but you can structure it.
-
-**Manage it by**:
-- Breaking complex tasks into discrete steps
-- Providing scaffolding (templates, defaults, examples)
-- Progressive disclosure: show what's needed now, hide the rest
-- Grouping related decisions together
-
-### Extraneous Load: Bad Design
-Mental effort caused by poor design choices. **Eliminate this ruthlessly.** It's pure waste.
-
-**Common sources**:
-- Confusing navigation that requires mental mapping
-- Unclear labels that force users to guess meaning
-- Visual clutter competing for attention
-- Inconsistent patterns that prevent learning
-- Unnecessary steps between user intent and result
-
-### Germane Load: Learning Effort
-Mental effort spent building understanding. This is *good* cognitive load; it leads to mastery.
-
-**Support it by**:
-- Progressive disclosure that reveals complexity gradually
-- Consistent patterns that reward learning
-- Feedback that confirms correct understanding
-- Onboarding that teaches through action, not walls of text
-
----
-
-## Cognitive Load Checklist
-
-Evaluate the interface against these 8 items:
-
-- [ ] **Single focus**: Can the user complete their primary task without distraction from competing elements?
-- [ ] **Chunking**: Is information presented in digestible groups (≤4 items per group)?
-- [ ] **Grouping**: Are related items visually grouped together (proximity, borders, shared background)?
-- [ ] **Visual hierarchy**: Is it immediately clear what's most important on the screen?
-- [ ] **One thing at a time**: Can the user focus on a single decision before moving to the next?
-- [ ] **Minimal choices**: Are decisions simplified (≤4 visible options at any decision point)?
-- [ ] **Working memory**: Does the user need to remember information from a previous screen to act on the current one?
-- [ ] **Progressive disclosure**: Is complexity revealed only when the user needs it?
-
-**Scoring**: Count the failed items. 0–1 failures = low cognitive load (good). 2–3 = moderate (address soon). 4+ = high cognitive load (critical fix needed).
-
----
-
-## The Working Memory Rule
-
-**Humans can hold ≤4 items in working memory at once** (Miller's Law revised by Cowan, 2001).
-
-At any decision point, count the number of distinct options, actions, or pieces of information a user must simultaneously consider:
-- **≤4 items**: Within working memory limits, manageable
-- **5–7 items**: Pushing the boundary; consider grouping or progressive disclosure
-- **8+ items**: Overloaded; users will skip, misclick, or abandon
-
-**Practical applications**:
-- Navigation menus: ≤5 top-level items (group the rest under clear categories)
-- Form sections: ≤4 fields visible per group before a visual break
-- Action buttons: 1 primary, 1–2 secondary, group the rest in a menu
-- Dashboard widgets: ≤4 key metrics visible without scrolling
-- Pricing tiers: ≤3 options (more causes analysis paralysis)
-
----
-
-## Common Cognitive Load Violations
-
-### 1. The Wall of Options
-**Problem**: Presenting 10+ choices at once with no hierarchy.
-**Fix**: Group into categories, highlight recommended, use progressive disclosure.
-
-### 2. The Memory Bridge
-**Problem**: User must remember info from step 1 to complete step 3.
-**Fix**: Keep relevant context visible, or repeat it where it's needed.
-
-### 3. The Hidden Navigation
-**Problem**: User must build a mental map of where things are.
-**Fix**: Always show current location (breadcrumbs, active states, progress indicators).
-
-### 4. The Jargon Barrier
-**Problem**: Technical or domain language forces translation effort.
-**Fix**: Use plain language. If domain terms are unavoidable, define them inline.
-
-### 5. The Visual Noise Floor
-**Problem**: Every element has the same visual weight; nothing stands out.
-**Fix**: Establish clear hierarchy: one primary element, 2–3 secondary, everything else muted.
-
-### 6. The Inconsistent Pattern
-**Problem**: Similar actions work differently in different places.
-**Fix**: Standardize interaction patterns. Same type of action = same type of UI.
-
-### 7. The Multi-Task Demand
-**Problem**: Interface requires processing multiple simultaneous inputs (reading + deciding + navigating).
-**Fix**: Sequence the steps. Let the user do one thing at a time.
-
-### 8. The Context Switch
-**Problem**: User must jump between screens/tabs/modals to gather info for a single decision.
-**Fix**: Co-locate the information needed for each decision. Reduce back-and-forth.
@@ -1,105 +0,0 @@
-# Color & Contrast
-
-## Color Spaces: Use OKLCH
-
-**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark.
-
-The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish.
-
-The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand.
-
-## Building Functional Palettes
-
-### Tinted Neutrals
-
-**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces.
-
-The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette.
-
-**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects.
-
-### Palette Structure
-
-A complete system needs:
-
-| Role | Purpose | Example |
-|------|---------|---------|
-| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades |
-| **Neutral** | Text, backgrounds, borders | 9-11 shade scale |
-| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each |
-| **Surface** | Cards, modals, overlays | 2-3 elevation levels |
-
-**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise.
-
-### The 60-30-10 Rule (Applied Correctly)
-
-This rule is about **visual weight**, not pixel count:
-
-- **60%**: Neutral backgrounds, white space, base surfaces
-- **30%**: Secondary colors: text, borders, inactive states
-- **10%**: Accent: CTAs, highlights, focus states
-
-The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power.
-
-## Contrast & Accessibility
-
-### WCAG Requirements
-
-| Content Type | AA Minimum | AAA Target |
-|--------------|------------|------------|
-| Body text | 4.5:1 | 7:1 |
-| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 |
-| UI components, icons | 3:1 | 4.5:1 |
-| Non-essential decorations | None | None |
-
-**The gotcha**: Placeholder text still needs 4.5:1. That light gray placeholder you see everywhere? Usually fails WCAG.
-
-### Dangerous Color Combinations
-
-These commonly fail contrast or cause readability issues:
-
-- Light gray text on white (the #1 accessibility fail)
-- **Gray text on any colored background**: gray looks washed out and dead on color. Use a darker shade of the background color, or transparency
-- Red text on green background (or vice versa): 8% of men can't distinguish these
-- Blue text on red background (vibrates visually)
-- Yellow text on white (almost always fails)
-- Thin light text on images (unpredictable contrast)
-
-### Never Use Pure Gray or Pure Black
-
-Pure gray (`oklch(50% 0 0)`) and pure black (`#000`) don't exist in nature; real shadows and surfaces always have a color cast. Even a chroma of 0.005-0.01 is enough to feel natural without being obviously tinted. (See tinted neutrals example above.)
-
-### Testing
-
-Don't trust your eyes. Use tools:
-
-- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/)
-- Browser DevTools → Rendering → Emulate vision deficiencies
-- [Polypane](https://polypane.app/) for real-time testing
-
-## Theming: Light & Dark Mode
-
-### Dark Mode Is Not Inverted Light Mode
-
-You can't just swap colors. Dark mode requires different design decisions:
-
-| Light Mode | Dark Mode |
-|------------|-----------|
-| Shadows for depth | Lighter surfaces for depth (no shadows) |
-| Dark text on light | Light text on dark (reduce font weight) |
-| Vibrant accents | Desaturate accents slightly |
-| White backgrounds | Never pure black; use dark gray (oklch 12-18%) |
-
-In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light.
-
-### Token Hierarchy
-
-Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same.
-
-## Alpha Is A Design Smell
-
-Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed.
-
----
-
-**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Using pure black (#000) for large areas. Skipping color blindness testing (8% of men affected).
@@ -1,154 +0,0 @@
-> **Additional context needed**: existing brand colors.
-
-Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit.
-
----
-
-## Register
-
-Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it.
-
-Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen.
-
----
-
-## Assess Color Opportunity
-
-Analyze the current state and identify opportunities:
-
-1. **Understand current state**:
- - **Color absence**: Pure grayscale? Limited neutrals? One timid accent?
- - **Missed opportunities**: Where could color add meaning, hierarchy, or delight?
- - **Context**: What's appropriate for this domain and audience?
- - **Brand**: Are there existing brand colors we should use?
-
-2. **Identify where color adds value**:
- - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue)
- - **Hierarchy**: Drawing attention to important elements
- - **Categorization**: Different sections, types, or states
- - **Emotional tone**: Warmth, energy, trust, creativity
- - **Wayfinding**: Helping users navigate and understand structure
- - **Delight**: Moments of visual interest and personality
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose.
-
-## Plan Color Strategy
-
-Create a purposeful color introduction plan:
-
-- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals)
-- **Dominant color**: Which color owns 60% of colored elements?
-- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%)
-- **Application strategy**: Where does each color appear and why?
-
-**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more.
-
-## Introduce Color Strategically
-
-Add color systematically across these dimensions:
-
-### Semantic Color
-- **State indicators**:
- - Success: Green tones (emerald, forest, mint)
- - Error: Red/pink tones (rose, crimson, coral)
- - Warning: Orange/amber tones
- - Info: Blue tones (sky, ocean, indigo)
- - Neutral: Gray/slate for inactive states
-
-- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.)
-- **Progress indicators**: Colored bars, rings, or charts showing completion or health
-
-### Accent Color Application
-- **Primary actions**: Color the most important buttons/CTAs
-- **Links**: Add color to clickable text (maintain accessibility)
-- **Icons**: Colorize key icons for recognition and personality
-- **Headers/titles**: Add color to section headers or key labels
-- **Hover states**: Introduce color on interaction
-
-### Background & Surfaces
-- **Tinted backgrounds**: Replace pure gray (`#f5f5f5`) with warm neutrals (`oklch(97% 0.01 60)`) or cool tints (`oklch(97% 0.01 250)`)
-- **Colored sections**: Use subtle background colors to separate areas
-- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue)
-- **Cards & surfaces**: Tint cards or surfaces slightly for warmth
-
-**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
-
-### Data Visualization
-- **Charts & graphs**: Use color to encode categories or values
-- **Heatmaps**: Color intensity shows density or importance
-- **Comparison**: Color coding for different datasets or timeframes
-
-### Borders & Accents
-- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`)
-- **Underlines**: Color underlines for emphasis or active states
-- **Dividers**: Subtle colored dividers instead of gray lines
-- **Focus rings**: Colored focus indicators matching brand
-- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe
-
-**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe.
-
-### Typography Color
-- **Colored headings**: Use brand colors for section headings (maintain contrast)
-- **Highlight text**: Color for emphasis or categories
-- **Labels & tags**: Small colored labels for metadata or categories
-
-### Decorative Elements
-- **Illustrations**: Add colored illustrations or icons
-- **Shapes**: Geometric shapes in brand colors as background elements
-- **Gradients**: Colorful gradient overlays or mesh backgrounds
-- **Blobs/organic shapes**: Soft colored shapes for visual interest
-
-## Balance & Refinement
-
-Ensure color addition improves rather than overwhelms:
-
-### Maintain Hierarchy
-- **Dominant color** (60%): Primary brand color or most used accent
-- **Secondary color** (30%): Supporting color for variety
-- **Accent color** (10%): High contrast for key moments
-- **Neutrals** (remaining): Gray/black/white for structure
-
-### Accessibility
-- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components)
-- **Don't rely on color alone**: Use icons, labels, or patterns alongside color
-- **Test for color blindness**: Verify red/green combinations work for all users
-
-### Cohesion
-- **Consistent palette**: Use colors from defined palette, not arbitrary choices
-- **Systematic application**: Same color meanings throughout (green always = success)
-- **Temperature consistency**: Warm palette stays warm, cool stays cool
-
-**NEVER**:
-- Use every color in the rainbow (choose 2-4 colors beyond neutrals)
-- Apply color randomly without semantic meaning
-- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead
-- Use pure gray for neutrals. Add subtle color tint (warm or cool) for depth
-- Use pure black (`#000`) or pure white (`#fff`) for large areas
-- Violate WCAG contrast requirements
-- Use color as the only indicator (accessibility issue)
-- Make everything colorful (defeats the purpose)
-- Default to purple-blue gradients (AI slop aesthetic)
-
-## Verify Color Addition
-
-Test that colorization improves the experience:
-
-- **Better hierarchy**: Does color guide attention appropriately?
-- **Clearer meaning**: Does color help users understand states/categories?
-- **More engaging**: Does the interface feel warmer and more inviting?
-- **Still accessible**: Do all color combinations meet WCAG standards?
-- **Not overwhelming**: Is color balanced and purposeful?
-
-When the palette earns its place, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage.
-
-```json
-{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"}
-```
-
-Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract.
@@ -1,123 +0,0 @@
-# Craft Flow
-
-Build a feature with impeccable UX and UI quality: shape the design, land the visual direction, build real production code, inspect and improve in-browser until it meets a high-end studio bar.
-
-Before writing code, you need: PRODUCT.md loaded, register identified and the matching reference loaded, and a confirmed design direction for this task (either from `shape` or supplied by the user). PRODUCT.md is project context, not a task-specific brief.
-
-Treat any approved visual direction (generated mock or stated reference) as a concrete contract for composition, hierarchy, density, atmosphere, signature motifs, and distinctive visual moves. Don't let mocks replace structure, copy, accessibility, or state design. But if the live result lacks the approved direction's major ingredients, the implementation is wrong.
-
-### Gates: do not compress
-
-Craft has **multiple user gates**, not one. When the harness has native image generation (Codex via `image_gen`), the gate sequence before code is:
-
-1. **Shape brief confirmed** (Step 1)
-2. **Direction questions answered** (codex.md Step A)
-3. **Palette confirmed** (codex.md Step B)
-4. **One mock direction approved or delegated** (codex.md Step D)
-
-You must stop at every gate. **Shape confirmation alone is NOT a green light to start coding.** It is the green light to begin codex.md Step A. Compressing gates 2 through 4 because the shape brief felt complete is the dominant failure mode of this flow.
-
-When the harness lacks native image generation, gates 2-4 collapse into the brief itself, and shape confirmation does advance straight to code.
-
-## Step 0: Project Foundation
-
-Before shape, before code: figure out what kind of project you're working in.
-
-Look at the working directory. Run `ls`. Check for:
-
-- An existing framework: `astro.config.mjs/ts`, `next.config.js/ts`, `nuxt.config.ts`, `svelte.config.js`, `vite.config.js/ts`, `package.json` with framework deps, `Cargo.toml` + Leptos/Yew, `Gemfile` + Rails. **If found, use it.** Do not start a parallel build, do not introduce a second framework, do not write to `dist/` or `build/` directly. Whatever pipeline the project has, respect it.
-- An existing component library or design system: `src/components/`, `app/components/`, a `tokens.css` / `theme.ts`, an `astro.config` `integrations`. Read what's there before adding to it.
-- An existing icon set: `lucide-react`, `@phosphor-icons/react`, `@iconify/*`, hand-rolled SVG sprites in `assets/icons/`. **Use what's already in the project**; don't introduce a second set.
-
-If the directory is empty (greenfield), don't pick a framework silently. Ask the user via the AskUserQuestion tool, with sensible defaults framed by the brief:
-
-```text
-What should this be built on?
- - Astro (default for content-led brand sites, landing pages, marketing surfaces)
- - SvelteKit / Next.js / Nuxt (when the brief implies an app surface or significant interactivity)
- - Single index.html (one-shot demo, prototype, or a deliberately framework-free experiment)
-```
-
-Default: Astro for brand briefs, the project's existing framework for product briefs. Ask once; don't re-ask mid-task.
-
-## Step 1: Shape the Design
-
-Run /impeccable shape, passing along whatever feature description the user provided. Shape is **required** for craft; it is what produces a confirmed direction.
-
-Present the shape output and stop. Wait for the user to confirm, override, or course-correct before writing code.
-
-If the user already supplied a confirmed brief or ran shape separately, use it and skip this step.
-
-When the original prompt + PRODUCT.md already answer scope, content, and visual direction with no real ambiguity, the shape output can be **compact** (3-5 bullets stating what you're building and the visual lane, ending with one or two specific questions or "confirm or override"). The full 10-section structured brief is reserved for genuinely ambiguous, multi-screen, or stakeholder-heavy tasks. Don't pad a clear brief into a long one to look thorough; equally, don't skip the pause to look efficient.
-
-If the harness has native image generation (Codex), a compact shape's "confirm or override" advances to **Step 3 and the codex.md flow**, not to Step 4. Phrase the closing line accordingly: "Confirm or override; once we lock direction, I'll run a couple of palette and reference questions before generating any mocks." This stops the model from reading shape confirmation as code-green.
-
-## Step 2: Load References
-
-Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult:
-
-- [spatial-design.md](spatial-design.md) for layout and spacing
-- [typography.md](typography.md) for type hierarchy
-
-Then add references based on the brief's needs:
-- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md)
-- Animation or transitions? Consult [motion-design.md](motion-design.md)
-- Color-heavy or themed? Consult [color-and-contrast.md](color-and-contrast.md)
-- Responsive requirements? Consult [responsive-design.md](responsive-design.md)
-- Heavy on copy, labels, or errors? Consult [ux-writing.md](ux-writing.md)
-
-## Step 3: Visual Direction & Assets (Harness-Gated)
-
-If the harness has **native image generation** (currently Codex via `image_gen`), this step is mandatory. **Stop and load [codex.md](codex.md)**. It covers palette generation, mock exploration, the approval loop, mock-fidelity inventory, and asset slicing via the `impeccable_asset_producer` subagent. Follow Steps A-F in that file, then return here for Step 4.
-
-If the harness lacks native image generation, **state in one line that the visual-direction-by-generation step is being skipped because the harness lacks native image generation, then proceed**. The one-line announcement is required; it forces a conscious decision instead of letting the step quietly evaporate. The brief is your only visual reference. Implement directly from it, treating any named anchor references and the brief's "Design Direction" as the contract.
-
-Whether you generated mocks or not: don't replace required imagery with generic cards, bullets, emoji, fake metrics, decorative CSS panels, or filler copy. Image-led briefs (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product) need real or sourced imagery in the build, not CSS scenery.
-
-## Step 4: Build to Production Quality
-
-**Precondition.** If Step 3 routed you to codex.md (native image generation available), Steps A through D in that file must be complete before any code: questions answered, palette confirmed, mocks generated, one direction approved or delegated. **Do not mention implementation, file paths, or patch plans until that's done.** A confirmed shape brief is not enough; the model that compressed those gates is the model that already failed this flow.
-
-Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration.
-
-### Production bar
-
-- **Real content.** No placeholder copy, placeholder images, dead links, fake controls, or unused scaffold at presentation time.
-- **Preserve the approved mock's major ingredients.** Missing hero objects, world/product imagery, section structure, CTA/nav treatment, or distinctive motifs are blocking defects unless the user accepted the change.
-- **Semantic first.** Real headings, landmarks, labels, form associations, button/link semantics, accessible names, state announcements where needed.
-- **Deliberate spacing and alignment.** No default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment.
-- **Intentional typography.** Chosen loading strategy, clear hierarchy, readable measure, stable line breaks, no overflow at any width.
-- **Realistic state coverage.** Default, hover, focus-visible, active, disabled, loading, error, success, empty, overflow, long/short text, first-run.
-- **Finished interaction quality.** Keyboard paths, touch targets, feedback timing, scroll behavior, state transitions, no hover-only functionality.
-- **Coherent icon set.** Use the project's established set; otherwise pick one library or use accessible text. Don't mix.
-- **Respect the build pipeline.** Edit source files and run the project's build (`npm run build` or equivalent). Don't write to `build/` / `dist/` / `.next/` with `cat`, heredoc, or Bash redirects; that skips asset hashing, image optimization, code splitting, and CSS extraction, and produces output the dev server won't serve.
-- **Verify image URLs before referencing them.** Use image-search MCP or web-fetch when available; guessed photo IDs ship as broken-image placeholders. Without verification, prefer fewer images you're confident about.
-- **Optimized imagery and media.** Correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset`/`picture` for raster, no project-referenced asset left outside the workspace.
-- **Premium motion.** Use atmospheric blur, filter, mask, shadow, reveal when they improve the experience. Avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion.
-- **Maintainable.** Reusable local patterns, clear component boundaries, project conventions. No rasterized UI text or one-off hacks when a local pattern exists.
-- **Technically clean.** Production build passes, no console errors, no avoidable layout shift, no needless dependencies, no broken asset paths.
-- **Ask when uncertain.** If a discovery materially changes the brief or approved direction, stop and ask. Don't guess.
-
-## Step 5: Iterate Visually
-
-Look at what you built like a designer would. Your eyes are whatever the harness gives you: a connected browser, a screenshotting tool, Playwright, or asking the user. Use them for responsive testing (mobile, tablet, desktop minimum) and general visual validation.
-
-If your tool returns a file path, read the PNG back into the conversation. A screenshot you didn't read doesn't count.
-
-For long-form brand surfaces, inspect major sections individually. Thumbnails hide spacing, clipping, and cascade defects.
-
-After the first pass, write an honest critique against the brief, the approved mock's major ingredients (hero silhouette, motifs, imagery, nav/CTA, density), and impeccable's DON'Ts. Patch material defects and re-inspect. **Don't invent defects to demonstrate iteration.** A confident "first pass clean, shipping" beats a fake fix.
-
-Actively check: responsive behavior (composes, not shrinks), every state (empty / error / loading / edge), craft details (spacing, alignment, hierarchy, contrast, motion timing, focus), performance basics. The exit bar: defensible in a high-end studio review.
-
-Detector or QA output is defect evidence only; never proof the work is finished.
-
-## Step 6: Present
-
-Present the result to the user:
-- Show the feature in its primary state
-- Summarize the browser/viewports checked and the most important fixes made after inspection
-- Walk through the key states (empty, error, responsive)
-- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients.
-- Note any remaining limitations or follow-up risks honestly
-- Ask: "What's working? What isn't?"
@@ -1,236 +0,0 @@
-### Purpose
-
-Resolve one stable target, run two independent assessments, synthesize a design critique, persist a snapshot, and ask the user what to improve next. The chat response is the primary deliverable; the snapshot is an archive/backlog for future commands.
-
-### Hard Invariants
-
-- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
-- Assessment A must finish before detector findings enter the parent synthesis context. Detector output is deterministic, but it still anchors judgment.
-- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize.
-- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
-- Viewable targets require browser inspection when available.
-- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
-- Do not claim a user-visible overlay exists unless script injection succeeded and the detector ran in the page.
-
-### Setup
-
-1. **Resolve the target** to a concrete file path or URL. Prefer a source path over a dev-server URL when both identify the same surface; ports drift, paths do not.
- - "the homepage" -> `site/pages/index.astro` or `index.html`
- - "the settings modal" -> the primary component file
- - "this page" -> the current URL or source file
-2. **Compute the slug**:
- ```bash
- node .trae-cn/skills/impeccable/scripts/critique-storage.mjs slug "<resolved-path-or-url>"
- ```
- Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique.
-3. **Read `.impeccable/critique/ignore.md`** if it exists. Drop matching findings silently; it is the only prior-run input critique consumes.
-
-### Assessment Orchestration
-
-Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis.
-
-If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
-
-### Assessment A: Design Review
-
-Read relevant source files and visually inspect the live page when browser automation is available. Think like a design director.
-
-Evaluate:
-- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill.
-- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases.
-- **Cognitive load**: consult [cognitive-load](cognitive-load.md); report checklist failures and decision points with >4 visible options.
-- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments.
-- **Nielsen heuristics**: consult [heuristics-scoring](heuristics-scoring.md); score all 10 heuristics 0-4.
-
-Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions.
-
-### Assessment B: Detector + Browser Evidence
-
-Run the bundled detector and browser visualization evidence. Assessment B is mandatory and must remain isolated from Assessment A until both are complete.
-
-CLI scan:
-```bash
-node .trae-cn/skills/impeccable/scripts/detect.mjs --json [--fast] [target]
-```
-
-- Pass markup files/directories as `[target]`; do not pass CSS-only files.
-- For URLs, skip CLI scan and use browser visualization.
-- For 200+ scannable files, use `--fast`; for 500+, narrow scope or ask.
-- Exit code 0 = clean; 2 = findings.
-- If the detector entrypoint is missing or fails to load, report deterministic scan unavailable and continue with browser/manual review.
-
-Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
-
-1. Create a fresh tab and navigate.
-2. Preflight mutable injection by setting `document.title` and appending a `<script>` tag. Read-only evaluate APIs do not count.
-3. If mutation is unavailable, skip live server, browser presentation, and injection; report fallback signal.
-4. If mutation is available, start `node .trae-cn/skills/impeccable/scripts/live-server.mjs --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then stop the live server.
-5. For multi-view targets, inject on 3-5 representative pages.
-
-Return: CLI findings JSON/counts, browser console findings if applicable, false positives, and skipped/failed browser steps with concrete reasons.
-
-After Assessment B returns usable CLI findings, reuse them. Do not rerun `detect.mjs` in the parent unless Assessment B failed, was truncated, or omitted count, rule names, or file locations.
-
-### Generate Combined Critique Report
-
-Synthesize both assessments into a single report. Do NOT simply concatenate. Weave the findings together, noting where the LLM review and detector agree, where the detector caught issues the LLM missed, and where detector findings are false positives.
-
-The chat response is the primary user-facing deliverable. Present the full structured critique below in chat; do not replace it with a summary and a link. The persisted snapshot is only an archive/backlog for later commands.
-
-Structure your feedback as a design director would:
-
-#### Design Health Score
-> *Consult [heuristics-scoring](heuristics-scoring.md)*
-
-Present the Nielsen's 10 heuristics scores as a table:
-
-| # | Heuristic | Score | Key Issue |
-|---|-----------|-------|-----------|
-| 1 | Visibility of System Status | ? | [specific finding or "n/a" if solid] |
-| 2 | Match System / Real World | ? | |
-| 3 | User Control and Freedom | ? | |
-| 4 | Consistency and Standards | ? | |
-| 5 | Error Prevention | ? | |
-| 6 | Recognition Rather Than Recall | ? | |
-| 7 | Flexibility and Efficiency | ? | |
-| 8 | Aesthetic and Minimalist Design | ? | |
-| 9 | Error Recovery | ? | |
-| 10 | Help and Documentation | ? | |
-| **Total** | | **??/40** | **[Rating band]** |
-
-Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32.
-
-#### Anti-Patterns Verdict
-
-**Start here.** Does this look AI-generated?
-
-**LLM assessment**: Your own evaluation of AI slop tells. Cover overall aesthetic feel, layout sameness, generic composition, missed opportunities for personality.
-
-**Deterministic scan**: Summarize what the automated detector found, with counts and file locations. Note any additional issues the detector caught that you missed, and flag any false positives.
-
-**Visual overlays** (if injection succeeded): Tell the user that overlays are now visible in the **[Human]** tab in their browser, highlighting the detected issues. Summarize what the console output reported. If browser visualization was attempted but injection failed, say that no reliable user-visible overlay is available and report the fallback signal instead.
-
-#### Overall Impression
-A brief gut reaction: what works, what doesn't, and the single biggest opportunity.
-
-#### What's Working
-Highlight 2-3 things done well. Be specific about why they work.
-
-#### Priority Issues
-The 3-5 most impactful design problems, ordered by importance.
-
-For each issue, tag with **P0-P3 severity** (consult [heuristics-scoring](heuristics-scoring.md) for severity definitions):
-- **[P?] What**: Name the problem clearly
-- **Why it matters**: How this hurts users or undermines goals
-- **Fix**: What to do about it (be concrete)
-- **Suggested command**: Which command could address this (from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-#### Persona Red Flags
-> *Consult [personas](personas.md)*
-
-Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `RULES.md` contains a `## Design Context` section from `impeccable teach`, also generate 1-2 project-specific personas from the audience/brand info.
-
-For each selected persona, walk through the primary user action and list specific red flags found:
-
-**Alex (Power User)**: No keyboard shortcuts detected. Form requires 8 clicks for primary action. Forced modal onboarding. High abandonment risk.
-
-**Jordan (First-Timer)**: Icon-only nav in sidebar. Technical jargon in error messages ("404 Not Found"). No visible help. Will abandon at step 2.
-
-Be specific. Name the exact elements and interactions that fail each persona. Don't write generic persona descriptions; write what broke for them.
-
-#### Minor Observations
-Quick notes on smaller issues worth addressing.
-
-#### Questions to Consider
-Provocative questions that might unlock better solutions:
-- "What if the primary action were more prominent?"
-- "Does this need to feel this complex?"
-- "What would a confident version of this look like?"
-
-**Remember**:
-- Be direct. Vague feedback wastes everyone's time.
-- Be specific. "The submit button," not "some elements."
-- Say what's wrong AND why it matters to users.
-- Give concrete suggestions. Cut "consider exploring..." entirely.
-- Prioritize ruthlessly. If everything is important, nothing is.
-- Don't soften criticism. Developers need honest feedback to ship great design.
-
-### Persist the Snapshot
-
-Once the report above is finalized, write it to `.impeccable/critique/` so the user can refer back, and so `/impeccable polish` can pick up the priority issues without a copy-paste.
-
-Skip this step if the Setup slug was null (vague or root-level target).
-
-1. **Write the body to a temp file** so you can pipe it to the helper. Use the full critique report (heuristic table, anti-patterns verdict, priority issues, persona red flags, minor observations, and questions), but stop before the "Ask the User" / "Recommended Actions" sections that come later.
-
-2. **Pass the structured metadata** through `IMPECCABLE_CRITIQUE_META` (JSON), then run the write command:
- ```bash
- IMPECCABLE_CRITIQUE_META='{"target":"<user phrasing>","total_score":<n>,"p0_count":<n>,"p1_count":<n>}' \
- node .trae-cn/skills/impeccable/scripts/critique-storage.mjs write <slug> <body-file>
- ```
- The helper prints the absolute path it wrote.
-
-3. **Delete the temp body file** after the write attempt completes, whether the write succeeded or failed. If deletion fails, mention `temp-file cleanup failed: <reason>` briefly in the final output, but do not block the critique.
-
-4. **Read the trend** for context:
- ```bash
- node .trae-cn/skills/impeccable/scripts/critique-storage.mjs trend <slug> 5
- ```
- This returns a JSON array of the last 5 frontmatter entries (including the one you just wrote).
-
-5. **Append a single line to the user-visible output**, after the report and before the questions:
-
- > **Trend for `<slug>` (last 5 runs): 24 → 28 → 32 → 29 → 32**
- > Wrote `.impeccable/critique/<filename>`.
-
- If this is the first run for the slug, the trend is just one score; say so: "First run for this target, no trend yet."
-
-This is fire-and-forget. Do not show the user the helper's JSON output; only the human-readable trend line and the written path. Failures here should not block the rest of the flow; print the error and move on.
-
-### Ask the User
-
-**After presenting findings**, use targeted questions based on what was actually found. ask the user directly to clarify what you cannot infer. These answers will shape the action plan.
-
-Ask questions along these lines (adapt to the specific findings; do NOT ask generic questions):
-
-1. **Priority direction**: Based on the issues found, ask which category matters most to the user right now. For example: "I found problems with visual hierarchy, color usage, and information overload. Which area should we tackle first?" Offer the top 2-3 issue categories as options.
-
-2. **Design intent**: If the critique found a tonal mismatch, ask whether it was intentional. For example: "The interface feels clinical and corporate. Is that the intended tone, or should it feel warmer/bolder/more playful?" Offer 2-3 tonal directions as options based on what would fix the issues found.
-
-3. **Scope**: Ask how much the user wants to take on. For example: "I found N issues. Want to address everything, or focus on the top 3?" Offer scope options like "Top 3 only", "All issues", "Critical issues only".
-
-4. **Constraints** (optional; only ask if relevant): If the findings touch many areas, ask if anything is off-limits. For example: "Should any sections stay as-is?" This prevents the plan from touching things the user considers done.
-
-**Rules for questions**:
-- Every question must reference specific findings from the report. Never ask generic "who is your audience?" questions.
-- Keep it to 2-4 questions maximum. Respect the user's time.
-- Offer concrete options, not open-ended prompts.
-- If findings are straightforward (e.g., only 1-2 clear issues), skip questions and go directly to Recommended Actions.
-
-### Recommended Actions
-
-**After receiving the user's answers**, present a prioritized action summary reflecting the user's priorities and scope from Ask the User.
-
-#### Action Summary
-
-List recommended commands in priority order, based on the user's answers:
-
-1. **`/command-name`**: Brief description of what to fix (specific context from critique findings)
-2. **`/command-name`**: Brief description (specific context)
-...
-
-**Rules for recommendations**:
-- Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset
-- Order by the user's stated priorities first, then by impact
-- Each item's description should carry enough context that the command knows what to focus on
-- Map each Priority Issue to the appropriate command
-- Skip commands that would address zero issues
-- If the user chose a limited scope, only include items within that scope
-- If the user marked areas as off-limits, exclude commands that would touch those areas
-- End with `/impeccable polish` as the final step if any fixes were recommended
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable critique` after fixes to see your score improve.
@@ -1,302 +0,0 @@
-> **Additional context needed**: what's appropriate for the domain (playful vs professional vs quirky vs elegant).
-
-Find the moments where personality and unexpected polish would turn a functional interface into one users remember and tell other people about. Add only where the moment earns it; delight everywhere reads as noise.
-
----
-
-## Register
-
-Brand: delight can be distributed across copy voice, section transitions, discovery rewards, seasonal touches, personality across the whole surface.
-
-Product: delight at specific moments, not pages. Completion, first-time actions, error recovery, milestone crossings. Reliability and consistency carry the rest of the experience; delight pushed everywhere reads as noise.
-
----
-
-## Assess Delight Opportunities
-
-Identify where delight would enhance (not distract from) the experience:
-
-1. **Find natural delight moments**:
- - **Success states**: Completed actions (save, send, publish)
- - **Empty states**: First-time experiences, onboarding
- - **Loading states**: Waiting periods that could be entertaining
- - **Achievements**: Milestones, streaks, completions
- - **Interactions**: Hover states, clicks, drags
- - **Errors**: Softening frustrating moments
- - **Easter eggs**: Hidden discoveries for curious users
-
-2. **Understand the context**:
- - What's the brand personality? (Playful? Professional? Quirky? Elegant?)
- - Who's the audience? (Tech-savvy? Creative? Corporate?)
- - What's the emotional context? (Accomplishment? Exploration? Frustration?)
- - What's appropriate? (Banking app ≠ gaming app)
-
-3. **Define delight strategy**:
- - **Subtle sophistication**: Refined micro-interactions (luxury brands)
- - **Playful personality**: Whimsical illustrations and copy (consumer apps)
- - **Helpful surprises**: Anticipating needs before users ask (productivity tools)
- - **Sensory richness**: Satisfying sounds, smooth animations (creative tools)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Delight should enhance usability, never obscure it. If users notice the delight more than accomplishing their goal, you've gone too far.
-
-## Delight Principles
-
-Follow these guidelines:
-
-### Delight Amplifies, Never Blocks
-- Delight moments should be quick (< 1 second)
-- Never delay core functionality for delight
-- Make delight skippable or subtle
-- Respect user's time and task focus
-
-### Surprise and Discovery
-- Hide delightful details for users to discover
-- Reward exploration and curiosity
-- Don't announce every delight moment
-- Let users share discoveries with others
-
-### Appropriate to Context
-- Match delight to emotional moment (celebrate success, empathize with errors)
-- Respect the user's state (don't be playful during critical errors)
-- Match brand personality and audience expectations
-- Cultural sensitivity (what's delightful varies by culture)
-
-### Compound Over Time
-- Delight should remain fresh with repeated use
-- Vary responses (not same animation every time)
-- Reveal deeper layers with continued use
-- Build anticipation through patterns
-
-## Delight Techniques
-
-Add personality and joy through these methods:
-
-### Micro-interactions & Animation
-
-**Button delight**:
-```css
-/* Satisfying button press */
-.button {
- transition: transform 0.1s, box-shadow 0.1s;
-}
-.button:active {
- transform: translateY(2px);
- box-shadow: 0 2px 4px rgba(0,0,0,0.2);
-}
-
-/* Ripple effect on click */
-/* Smooth lift on hover */
-.button:hover {
- transform: translateY(-2px);
- transition: transform 0.2s cubic-bezier(0.25, 1, 0.5, 1); /* ease-out-quart */
-}
-```
-
-**Loading delight**:
-- Playful loading animations (not just spinners)
-- Personality in loading messages (write product-specific ones, not generic AI filler)
-- Progress indication with encouraging messages
-- Skeleton screens with subtle animations
-
-**Success animations**:
-- Checkmark draw animation
-- Confetti burst for major achievements
-- Gentle scale + fade for confirmation
-- Satisfying sound effects (subtle)
-
-**Hover surprises**:
-- Icons that animate on hover
-- Color shifts or glow effects
-- Tooltip reveals with personality
-- Cursor changes (custom cursors for branded experiences)
-
-### Personality in Copy
-
-**Playful error messages**:
-```
-"Error 404"
-"This page is playing hide and seek. (And winning)"
-
-"Connection failed"
-"Looks like the internet took a coffee break. Want to retry?"
-```
-
-**Encouraging empty states**:
-```
-"No projects"
-"Your canvas awaits. Create something amazing."
-
-"No messages"
-"Inbox zero! You're crushing it today."
-```
-
-**Playful labels & tooltips**:
-```
-"Delete"
-"Send to void" (for playful brand)
-
-"Help"
-"Rescue me" (tooltip)
-```
-
-**IMPORTANT**: Match copy personality to brand. Banks shouldn't be wacky, but they can be warm.
-
-### Illustrations & Visual Personality
-
-**Custom illustrations**:
-- Empty state illustrations (not stock icons)
-- Error state illustrations (friendly monsters, quirky characters)
-- Loading state illustrations (animated characters)
-- Success state illustrations (celebrations)
-
-**Icon personality**:
-- Custom icon set matching brand personality
-- Animated icons (subtle motion on hover/click)
-- Illustrative icons (more detailed than generic)
-- Consistent style across all icons
-
-**Background effects**:
-- Subtle particle effects
-- Gradient mesh backgrounds
-- Geometric patterns
-- Parallax depth
-- Time-of-day themes (morning vs night)
-
-### Satisfying Interactions
-
-**Drag and drop delight**:
-- Lift effect on drag (shadow, scale)
-- Snap animation when dropped
-- Satisfying placement sound
-- Undo toast ("Dropped in wrong place? [Undo]")
-
-**Toggle switches**:
-- Smooth slide with spring physics
-- Color transition
-- Haptic feedback on mobile
-- Optional sound effect
-
-**Progress & achievements**:
-- Streak counters with celebratory milestones
-- Progress bars that "celebrate" at 100%
-- Badge unlocks with animation
-- Playful stats ("You're on fire! 5 days in a row")
-
-**Form interactions**:
-- Input fields that animate on focus
-- Checkboxes with a satisfying scale pulse when checked
-- Success state that celebrates valid input
-- Auto-grow textareas
-
-### Sound Design
-
-**Subtle audio cues** (when appropriate):
-- Notification sounds (distinctive but not annoying)
-- Success sounds (satisfying "ding")
-- Error sounds (empathetic, not harsh)
-- Typing sounds for chat/messaging
-- Ambient background audio (very subtle)
-
-**IMPORTANT**:
-- Respect system sound settings
-- Provide mute option
-- Keep volumes quiet (subtle cues, not alarms)
-- Don't play on every interaction (sound fatigue is real)
-
-### Easter Eggs & Hidden Delights
-
-**Discovery rewards**:
-- Konami code unlocks special theme
-- Hidden keyboard shortcuts (Cmd+K for special features)
-- Hover reveals on logos or illustrations
-- Alt text jokes on images (for screen reader users too!)
-- Console messages for developers ("Like what you see? We're hiring!")
-
-**Seasonal touches**:
-- Holiday themes (subtle, tasteful)
-- Seasonal color shifts
-- Weather-based variations
-- Time-based changes (dark at night, light during day)
-
-**Contextual personality**:
-- Different messages based on time of day
-- Responses to specific user actions
-- Randomized variations (not same every time)
-- Progressive reveals with continued use
-
-### Loading & Waiting States
-
-**Make waiting engaging**:
-- Interesting loading messages that rotate
-- Progress bars with personality
-- Mini-games during long loads
-- Fun facts or tips while waiting
-- Countdown with encouraging messages
-
-```
-Loading messages: write ones specific to your product, not generic AI filler:
-- "Crunching your latest numbers..."
-- "Syncing with your team's changes..."
-- "Preparing your dashboard..."
-- "Checking for updates since yesterday..."
-```
-
-**WARNING**: Avoid cliched loading messages like "Herding pixels", "Teaching robots to dance", "Consulting the magic 8-ball", "Counting backwards from infinity". These are AI-slop copy, instantly recognizable as machine-generated. Write messages that are specific to what your product actually does.
-
-### Celebration Moments
-
-**Success celebrations**:
-- Confetti for major milestones
-- Animated checkmarks for completions
-- Progress bar celebrations at 100%
-- "Achievement unlocked" style notifications
-- Personalized messages ("You published your 10th article!")
-
-**Milestone recognition**:
-- First-time actions get special treatment
-- Streak tracking and celebration
-- Progress toward goals
-- Anniversary celebrations
-
-## Implementation Patterns
-
-**Animation libraries**:
-- Framer Motion (React)
-- GSAP (universal)
-- Lottie (After Effects animations)
-- Canvas confetti (party effects)
-
-**Sound libraries**:
-- Howler.js (audio management)
-- Use-sound (React hook)
-
-**Physics libraries**:
-- React Spring (spring physics)
-- Popmotion (animation primitives)
-
-**IMPORTANT**: File size matters. Compress images, optimize animations, lazy load delight features.
-
-**NEVER**:
-- Delay core functionality for delight
-- Force users through delightful moments (make skippable)
-- Use delight to hide poor UX
-- Overdo it (less is more)
-- Ignore accessibility (animate responsibly, provide alternatives)
-- Make every interaction delightful (special moments should be special)
-- Sacrifice performance for delight
-- Be inappropriate for context (read the room)
-
-## Verify Delight Quality
-
-Test that delight actually delights:
-
-- **User reactions**: Do users smile? Share screenshots?
-- **Doesn't annoy**: Still pleasant after 100th time?
-- **Doesn't block**: Can users opt out or skip?
-- **Performant**: No jank, no slowdown
-- **Appropriate**: Matches brand and context
-- **Accessible**: Works with reduced motion, screen readers
-
-When the moments feel earned, hand off to `/impeccable polish` for the final pass.
@@ -1,111 +0,0 @@
-Strip a design to its essence. Remove anything that doesn't earn its place: redundant elements, repeated information, decorative noise, cosmetic complexity.
-
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel complex or cluttered:
-
-1. **Identify complexity sources**:
- - **Too many elements**: Competing buttons, redundant information, visual clutter
- - **Excessive variation**: Too many colors, fonts, sizes, styles without purpose
- - **Information overload**: Everything visible at once, no progressive disclosure
- - **Visual noise**: Unnecessary borders, shadows, backgrounds, decorations
- - **Confusing hierarchy**: Unclear what matters most
- - **Feature creep**: Too many options, actions, or paths forward
-
-2. **Find the essence**:
- - What's the primary user goal? (There should be ONE)
- - What's actually necessary vs nice-to-have?
- - What can be removed, hidden, or combined?
- - What's the 20% that delivers 80% of value?
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Simplicity is not about removing features. It's about removing obstacles between users and their goals. Every element should justify its existence.
-
-## Plan Simplification
-
-Create a ruthless editing strategy:
-
-- **Core purpose**: What's the ONE thing this should accomplish?
-- **Essential elements**: What's truly necessary to achieve that purpose?
-- **Progressive disclosure**: What can be hidden until needed?
-- **Consolidation opportunities**: What can be combined or integrated?
-
-**IMPORTANT**: Simplification is hard. It requires saying no to good ideas to make room for great execution. Be ruthless.
-
-## Simplify the Design
-
-Systematically remove complexity across these dimensions:
-
-### Information Architecture
-- **Reduce scope**: Remove secondary actions, optional features, redundant information
-- **Progressive disclosure**: Hide complexity behind clear entry points (accordions, modals, step-through flows)
-- **Combine related actions**: Merge similar buttons, consolidate forms, group related content
-- **Clear hierarchy**: ONE primary action, few secondary actions, everything else tertiary or hidden
-- **Remove redundancy**: If it's said elsewhere, don't repeat it here
-
-### Visual Simplification
-- **Reduce color palette**: Use 1-2 colors plus neutrals, not 5-7 colors
-- **Limit typography**: One font family, 3-4 sizes maximum, 2-3 weights
-- **Remove decorations**: Eliminate borders, shadows, backgrounds that don't serve hierarchy or function
-- **Flatten structure**: Reduce nesting, remove unnecessary containers; never nest cards inside cards
-- **Remove unnecessary cards**: Cards aren't needed for basic layout; use spacing and alignment instead
-- **Consistent spacing**: Use one spacing scale, remove arbitrary gaps
-
-### Layout Simplification
-- **Linear flow**: Replace complex grids with simple vertical flow where possible
-- **Remove sidebars**: Move secondary content inline or hide it
-- **Full-width**: Use available space generously instead of complex multi-column layouts
-- **Consistent alignment**: Pick left or center, stick with it
-- **Generous white space**: Let content breathe, don't pack everything tight
-
-### Interaction Simplification
-- **Reduce choices**: Fewer buttons, fewer options, clearer path forward (paradox of choice is real)
-- **Smart defaults**: Make common choices automatic, only ask when necessary
-- **Inline actions**: Replace modal flows with inline editing where possible
-- **Remove steps**: Can signup be one step instead of three? Can checkout be simplified?
-- **Clear CTAs**: ONE obvious next step, not five competing actions
-
-### Content Simplification
-- **Shorter copy**: Cut every sentence in half, then do it again
-- **Active voice**: "Save changes" not "Changes will be saved"
-- **Remove jargon**: Plain language always wins
-- **Scannable structure**: Short paragraphs, bullet points, clear headings
-- **Essential information only**: Remove marketing fluff, legalese, hedging
-- **Remove redundant copy**: No headers restating intros, no repeated explanations, say it once
-
-### Code Simplification
-- **Remove unused code**: Dead CSS, unused components, orphaned files
-- **Flatten component trees**: Reduce nesting depth
-- **Consolidate styles**: Merge similar styles, use utilities consistently
-- **Reduce variants**: Does that component need 12 variations, or can 3 cover 90% of cases?
-
-**NEVER**:
-- Remove necessary functionality (simplicity ≠ feature-less)
-- Sacrifice accessibility for simplicity (clear labels and ARIA still required)
-- Make things so simple they're unclear (mystery ≠ minimalism)
-- Remove information users need to make decisions
-- Eliminate hierarchy completely (some things should stand out)
-- Oversimplify complex domains (match complexity to actual task complexity)
-
-## Verify Simplification
-
-Ensure simplification improves usability:
-
-- **Faster task completion**: Can users accomplish goals more quickly?
-- **Reduced cognitive load**: Is it easier to understand what to do?
-- **Still complete**: Are all necessary features still accessible?
-- **Clearer hierarchy**: Is it obvious what matters most?
-- **Better performance**: Does simpler design load faster?
-
-## Document Removed Complexity
-
-If you removed features or options:
-- Document why they were removed
-- Consider if they need alternative access points
-- Note any user feedback to monitor
-
-When the cuts feel right, hand off to `/impeccable polish` for the final pass. As Antoine de Saint-Exupéry put it: "Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away."
@@ -1,427 +0,0 @@
-Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
-
-DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
-
-## The frontmatter: token schema
-
-The YAML frontmatter is the machine-readable layer. It's what Stitch's linter validates and what the live panel renders tiles from. Keep it tight; every entry should correspond to a token the project actually uses.
-
-```yaml
----
-name: <project title>
-description: <one-line tagline>
-colors:
- primary: "#b8422e"
- neutral-bg: "#faf7f2"
- # ...one entry per extracted color; key = descriptive slug
-typography:
- display:
- fontFamily: "Cormorant Garamond, Georgia, serif"
- fontSize: "clamp(2.5rem, 7vw, 4.5rem)"
- fontWeight: 300
- lineHeight: 1
- letterSpacing: "normal"
- body:
- # ...
-rounded:
- sm: "4px"
- md: "8px"
-spacing:
- sm: "8px"
- md: "16px"
-components:
- button-primary:
- backgroundColor: "{colors.primary}"
- textColor: "{colors.neutral-bg}"
- rounded: "{rounded.sm}"
- padding: "16px 48px"
- button-primary-hover:
- backgroundColor: "{colors.primary-deep}"
----
-```
-
-Rules that matter:
-
-- **Token refs** use `{path.to.token}` (e.g. `{colors.primary}`, `{rounded.md}`). Components may reference primitives; primitives may not reference each other.
-- **Stitch validates colors as hex sRGB only** (`#RGB` / `#RGBA` / `#RRGGBB` / `#RRGGBBAA`); OKLCH/HSL/P3 trigger a linter warning, not a hard error. YAML accepts the string either way and our own parser is format-agnostic. Choose based on project posture: (a) if the project has an "OKLCH-only" doctrine or uses Display-P3 values that don't round-trip through sRGB, put OKLCH directly in the frontmatter and accept the Stitch linter warning; (b) if the project wants strict Stitch compliance or plans to use their Tailwind/DTCG export pipeline, put hex in the frontmatter and keep OKLCH in prose as the canonical reference. Never split the source of truth without explicit reason.
-- **Component sub-tokens** are limited to 8 props: `backgroundColor`, `textColor`, `typography`, `rounded`, `padding`, `size`, `height`, `width`. Shadows, motion, focus rings, backdrop-filter: none of those fit. Carry them in the sidecar (Step 4b).
-- **Scale keys are open-ended.** Use whatever names the project already uses (`warm-ash-cream`, `surface-container-low`). Don't rename to Material defaults.
-- **Variants are naming convention, not schema.** `button-primary` / `button-primary-hover` / `button-primary-active` as sibling keys.
-
-## The markdown body: six sections (exact order)
-
-1. `## Overview`
-2. `## Colors`
-3. `## Typography`
-4. `## Elevation`
-5. `## Components`
-6. `## Do's and Don'ts`
-
-Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] Palette` (Stitch's own outputs do this), but the literal word in each header (Overview, Colors, Typography, Elevation, Components, Do's and Don'ts) must be present. Do NOT add extra top-level sections (Layout Principles, Responsive Behavior, Motion, Agent Prompt Guide). Fold that content into the six spec sections where it naturally belongs.
-
-## When to run
-
-- The user just ran `/impeccable teach` and needs the visual side documented.
-- The skill noticed no `DESIGN.md` exists and nudged the user to create one.
-- An existing `DESIGN.md` is stale (the design has drifted).
-- Before a large redesign, to capture the current state as a reference.
-
-If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user the existing file and ask the user directly to clarify what you cannot infer. whether to refresh, overwrite, or merge.
-
-## Two paths
-
-- **Scan mode** (default): the project has design tokens, components, or rendered output. Extract, then confirm descriptive language. Use when there's code to analyze.
-- **Seed mode**: the project is pre-implementation (fresh teach, nothing built yet). Interview for five high-level answers, write a minimal DESIGN.md marked `<!-- SEED -->`. Re-run in scan mode once there's code.
-
-Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode; don't silently switch. `/impeccable document --seed` forces seed mode regardless of code presence.
-
-## Scan mode (approach C: auto-extract, then confirm descriptive language)
-
-### Step 1: Find the design assets
-
-Search the codebase in priority order:
-
-1. **CSS custom properties**: grep for `--color-`, `--font-`, `--spacing-`, `--radius-`, `--shadow-`, `--ease-`, `--duration-` declarations in CSS files (usually `src/styles/`, `public/css/`, `app/globals.css`, etc.). Record name, value, and the file it's defined in.
-2. **Tailwind config**: if `tailwind.config.{js,ts,mjs}` exists, read the `theme.extend` block for colors, fontFamily, spacing, borderRadius, boxShadow.
-3. **CSS-in-JS theme files**: styled-components, emotion, vanilla-extract, stitches; look for `theme.ts`, `tokens.ts`, or equivalent.
-4. **Design token files**: `tokens.json`, `design-tokens.json`, Style Dictionary output, W3C token community group format.
-5. **Component library**: scan the main button, card, input, navigation, dialog components. Note their variant APIs and default styles.
-6. **Global stylesheet**: the root CSS file usually has the base typography and color assignments.
-7. **Visible rendered output**: if browser automation tools are available, load the live site and sample computed styles from key elements (body, h1, a, button, .card). This catches values that tokens miss.
-
-### Step 2: Auto-extract what can be auto-extracted
-
-Build a structured draft from the discovered tokens. For each token class:
-
-- **Colors**: Group into Primary / Secondary / Tertiary / Neutral (the Material-derived roles Stitch uses). If the project only has one accent, express it as Primary + Neutral; omit Secondary and Tertiary rather than inventing them.
-- **Typography**: Map observed sizes and weights to the Material hierarchy (display / headline / title / body / label). Note font-family stacks and the scale ratio.
-- **Elevation**: Catalogue the shadow vocabulary. If the project is flat and uses tonal layering instead, that's a valid answer; state it explicitly.
-- **Components**: For each common component (button, card, input, chip, list item, tooltip, nav), extract shape (radius), color assignment, hover/focus treatment, internal padding.
-- **Spacing + layout**: Fold into Overview or relevant Components. The spec does NOT have a Layout section.
-
-### Step 2b: Stage the frontmatter
-
-From the auto-extracted tokens, draft the YAML frontmatter now (you'll write it at the top of DESIGN.md in Step 4). This is the machine-readable layer: what the live panel and Stitch's linter consume.
-
-- **Colors**: one entry per extracted color. Key = descriptive slug (`warm-ash-cream`, `editorial-magenta`, not `blue-800`). Value = whichever format the project treats as canonical (OKLCH or hex; see the frontmatter rules above). Don't split the source of truth: one format in the frontmatter, don't redefine the same token in prose with a different value.
-- **Typography**: one entry per role (`display`, `headline`, `title`, `body`, `label`). Typography is an object; include only the props that are real for the project (`fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `fontFeature`, `fontVariation`).
-- **Rounded / Spacing**: whatever scale steps the project actually uses, keyed by whatever scale name the project uses (`sm` / `md` / `lg`, or `surface-sm`, or numeric steps).
-- **Components**: one entry per variant (`button-primary`, `button-primary-hover`, `button-ghost`). Reference primitives via `{colors.X}`, `{rounded.Y}`. If a variant needs a property Stitch's 8-prop set doesn't cover (shadow, focus ring, backdrop-filter), carry the full snippet in the sidecar instead.
-
-Skip anything the project doesn't have. Empty scale keys or fabricated tokens pollute the spec.
-
-### Step 3: Ask the user for qualitative language
-
-The following require creative input that cannot be auto-extracted. Group them into one `AskUserQuestion` interaction:
-
-- **Creative North Star**: a single named metaphor for the whole system ("The Editorial Sanctuary", "The Golden State Curator", "The Lab Notebook"). Offer 2-3 options that honor PRODUCT.md's brand personality.
-- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, anti-references (what the system should not feel like).
-- **Color character** (for auto-extracted colors): descriptive names ("Deep Muted Teal-Navy", not "blue-800"). Suggest 2-3 options per key color based on hue/saturation.
-- **Elevation philosophy**: flat/layered/lifted. If shadows exist, is their role ambient or structural?
-- **Component philosophy**: the feel of buttons, cards, inputs in one phrase ("tactile and confident" vs. "refined and restrained").
-
-Quote a line from PRODUCT.md when possible so the user sees their own strategic language carry forward.
-
-### Step 4: Write DESIGN.md
-
-The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the structure below. Headers must match character-for-character. Optional evocative subtitles (e.g. `## 2. Colors: The Coastal Palette`) are allowed.
-
-```markdown
----
-name: [Project Title]
-description: [one-line tagline]
-colors:
- # ... staged frontmatter from Step 2b
----
-
-# Design System: [Project Title]
-
-## 1. Overview
-
-**Creative North Star: "[Named metaphor in quotes]"**
-
-[2-3 paragraph holistic description: personality, density, aesthetic philosophy. Start from the North Star and work outward. State what this system explicitly rejects (pulled from PRODUCT.md's anti-references). End with a short **Key Characteristics:** bullet list.]
-
-## 2. Colors
-
-[Describe the palette character in one sentence.]
-
-### Primary
-- **[Descriptive Name]** (#HEX / oklch(...)): [Where and why this color is used. Be specific about context, not just role.]
-
-### Secondary (optional; omit if the project has only one accent)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Tertiary (optional)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Neutral
-- **[Descriptive Name]** (#HEX): [Text / background / border / divider role.]
-- [...]
-
-### Named Rules (optional, powerful)
-**The [Rule Name] Rule.** [Short, forceful prohibition or doctrine, e.g. "The One Voice Rule. The primary accent is used on ≤10% of any given screen. Its rarity is the point."]
-
-## 3. Typography
-
-**Display Font:** [Family] (with [fallback])
-**Body Font:** [Family] (with [fallback])
-**Label/Mono Font:** [Family, if distinct]
-
-**Character:** [1-2 sentence personality description of the pairing.]
-
-### Hierarchy
-- **Display** ([weight], [size/clamp], [line-height]): [Purpose; where it appears.]
-- **Headline** ([weight], [size], [line-height]): [Purpose.]
-- **Title** ([weight], [size], [line-height]): [Purpose.]
-- **Body** ([weight], [size], [line-height]): [Purpose. Include max line length like 65–75ch if relevant.]
-- **Label** ([weight], [size], [letter-spacing], [case if uppercase]): [Purpose.]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [Short doctrine about type use.]
-
-## 4. Elevation
-
-[One paragraph: does this system use shadows, tonal layering, or a hybrid? If "no shadows", say so explicitly and describe how depth is conveyed instead.]
-
-### Shadow Vocabulary (if applicable)
-- **[Role name]** (`box-shadow: [exact value]`): [When to use it.]
-- [...]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [e.g. "The Flat-By-Default Rule. Surfaces are flat at rest. Shadows appear only as a response to state (hover, elevation, focus)."]
-
-## 5. Components
-
-For each component, lead with a short character line, then specify shape, color assignment, states, and any distinctive behavior.
-
-### Buttons
-- **Shape:** [radius described, exact value in parens]
-- **Primary:** [color assignment + padding, in semantic + exact terms]
-- **Hover / Focus:** [transitions, treatments]
-- **Secondary / Ghost / Tertiary (if applicable):** [brief description]
-
-### Chips (if used)
-- **Style:** [background, text color, border treatment]
-- **State:** [selected / unselected, filter / action variants]
-
-### Cards / Containers
-- **Corner Style:** [radius]
-- **Background:** [colors used]
-- **Shadow Strategy:** [reference Elevation section]
-- **Border:** [if any]
-- **Internal Padding:** [scale]
-
-### Inputs / Fields
-- **Style:** [stroke, background, radius]
-- **Focus:** [treatment, e.g. glow, border shift, etc.]
-- **Error / Disabled:** [if applicable]
-
-### Navigation
-- **Style, typography, default/hover/active states, mobile treatment.**
-
-### [Signature Component] (optional; if the project has a distinctive custom component worth documenting)
-[Description.]
-
-## 6. Do's and Don'ts
-
-Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: include exact colors, pixel values, and named anti-patterns the user mentioned in PRODUCT.md. **Every anti-reference in PRODUCT.md should show up here as a "Don't" with the same language**, so the visual spec carries the strategic line through. Quote PRODUCT.md directly where possible: if PRODUCT.md says *"avoid dark mode with purple gradients, neon accents, glassmorphism"*, the Don'ts here should repeat that by name.
-
-### Do:
-- **Do** [specific prescription with exact values / named rule].
-- **Do** [...]
-
-### Don't:
-- **Don't** [specific prohibition, e.g. "use border-left greater than 1px as a colored stripe"].
-- **Don't** [...]
-- **Don't** [...]
-```
-
-### Step 4b: Write .impeccable/design.json sidecar (extensions only)
-
-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.
-
-Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.
-
-#### Schema
-
-```json
-{
- "schemaVersion": 2,
- "generatedAt": "ISO-8601 string",
- "title": "Design System: [Project Title]",
- "extensions": {
- "colorMeta": {
- "primary": { "role": "primary", "displayName": "Editorial Magenta", "canonical": "oklch(60% 0.25 350)", "tonalRamp": ["...", "...", "..."] },
- "warm-ash-cream": { "role": "neutral", "displayName": "Warm Ash Cream", "canonical": "oklch(96% 0.005 350)", "tonalRamp": ["...", "...", "..."] }
- },
- "typographyMeta": {
- "display": { "displayName": "Display", "purpose": "Hero headlines only." }
- },
- "shadows": [
- { "name": "ambient-low", "value": "0 4px 24px rgba(0,0,0,0.12)", "purpose": "Diffuse hover glow under accent elements." }
- ],
- "motion": [
- { "name": "ease-standard", "value": "cubic-bezier(0.4, 0, 0.2, 1)", "purpose": "Default easing for state transitions." }
- ],
- "breakpoints": [
- { "name": "sm", "value": "640px" }
- ]
- },
- "components": [
- {
- "name": "Primary Button",
- "kind": "button | input | nav | chip | card | custom",
- "refersTo": "button-primary",
- "description": "One-line what and when.",
- "html": "<button class=\"ds-btn-primary\">GET STARTED</button>",
- "css": ".ds-btn-primary { background: #191c1d; color: #fff; padding: 16px 48px; letter-spacing: 0.05em; text-transform: uppercase; font-weight: 500; border: none; border-radius: 0; transition: background 0.2s, transform 0.2s; } .ds-btn-primary:hover { background: oklch(60% 0.25 350); transform: translateY(-2px); }"
- }
- ],
- "narrative": {
- "northStar": "The Editorial Sanctuary",
- "overview": "2-3 paragraphs of the philosophy, pulled from DESIGN.md Overview section.",
- "keyCharacteristics": ["...", "..."],
- "rules": [{ "name": "The One Voice Rule", "body": "...", "section": "colors|typography|elevation" }],
- "dos": ["Do use ..."],
- "donts": ["Don't use ..."]
- }
-}
-```
-
-**What changed from schemaVersion 1.** The old sidecar carried token primitive arrays (`tokens.colors[]`, `tokens.typography[]`, etc.). Those values now live in the frontmatter. The sidecar only carries metadata that can't live in the frontmatter (tonal ramps, canonical OKLCH when the hex is an approximation, display names, role hints), keyed by the frontmatter token name (`colorMeta.<token-name>`, `typographyMeta.<token-name>`). Components still carry full HTML/CSS because Stitch's 8-prop set can't hold them.
-
-#### Component translation rules
-
-The `html` and `css` fields must be **self-contained, drop-in snippets** that render correctly when injected into a shadow DOM. The panel applies them directly: no post-processing, no framework runtime.
-
-1. **Tailwind expansion.** If the source uses Tailwind (className="bg-primary text-white rounded-lg px-6 py-3"), expand every utility to literal CSS properties in the `css` string. Do **not** reference Tailwind classes; do **not** assume a Tailwind CSS bundle is loaded. Each component is self-contained.
-2. **Token resolution.** If the project exposes tokens as CSS custom properties on `:root` (e.g. `--color-primary`, `--radius-md`), reference them via `var(--color-primary)`; they inherit through the shadow DOM and stay live-bound. If tokens live only in JS theme objects (styled-components, CSS-in-JS), resolve to literal values at generation time.
-3. **Icons.** Inline as SVG. Do not reference Lucide/Heroicons packages, icon fonts, or `<img src="...">`. A typical icon is 16-24px; copy the SVG path data directly.
-4. **States.** Include `:hover`, `:focus-visible`, and (if meaningful) `:active` rules inline. A static default-only snapshot makes the panel feel dead. Hover + focus rules in the CSS make it feel alive.
-5. **Reset bloat.** Extract only the component's *distinctive* CSS (background, color, padding, border-radius, typography, transition). Skip universal resets (`box-sizing: border-box`, `line-height: inherit`, `-webkit-font-smoothing`). The panel already has a neutral canvas; don't re-ship resets.
-6. **Scoped class names.** Prefix every class with `ds-` (e.g. `ds-btn-primary`, `ds-input-search`) so component CSS doesn't collide with other components' CSS in the same shadow DOM.
-
-#### What to include
-
-Aim for a tight set of **5-10 components** that best represent the visual system:
-
-- **Canonical primitives (always include if the project has them):** button (each variant as a separate component entry), input/text field, navigation, chip/tag, card.
-- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.
-- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.
-
-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.
-
-#### Tonal ramps
-
-For each color token, generate an 8-step `tonalRamp` array: dark to light, same hue and chroma, stepped lightness from ~15% to ~95%. The panel renders this as a strip under the swatch. If the project already defines a tonal scale (Material `surface-container-low` family, Tailwind-style `blue-50..blue-900`), use those values. Otherwise synthesize in OKLCH.
-
-#### Narrative mapping
-
-Pull directly from the DESIGN.md you just wrote:
-
-- `narrative.northStar` → the `**Creative North Star: "..."**` line from Overview
-- `narrative.overview` → the philosophy paragraphs from Overview
-- `narrative.keyCharacteristics` → the bulleted `**Key Characteristics:**` list
-- `narrative.rules` → every `**The [Name] Rule.** [body]` across all sections, tagged with `section`
-- `narrative.dos` / `narrative.donts` → the bullet lists from Do's and Don'ts verbatim
-
-Do not reword. The panel shows these as secondary collapsible context; the same voice that's in the Markdown carries through.
-
-### Step 5: Confirm, refine, and refresh session cache
-
-1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).
-2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.
-3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"
-4. **Refresh the session cache.** Run `node .trae-cn/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.
-
-## Seed mode
-
-For projects with no visual system to extract yet. Produces a minimal scaffold, not a full spec.
-
-### Step 1: Confirm seed mode
-
-Before interviewing: "There's no existing visual system to scan. I'll ask five quick questions to seed a starter DESIGN.md. You can re-run `/impeccable document` once there's code, to capture the real tokens and components. OK?"
-
-If the user prefers to skip, stop. No file.
-
-### Step 2: Five questions
-
-Group into one `AskUserQuestion` interaction. Options must be concrete.
-
-1. **Color strategy.** Pick one:
- - Restrained: tinted neutrals + one accent ≤10%
- - Committed: one saturated color carries 30–60% of the surface
- - Full palette: 3–4 named color roles, each deliberate
- - Drenched: the surface IS the color
-
- Then: one hue family or anchor reference ("deep teal", "mustard", "Klim #ff4500 orange").
-
-2. **Typography direction.** Pick one (specific fonts come later):
- - Serif display + sans body
- - Single sans (warm / technical / geometric / humanist; pick a feel)
- - Display + mono
- - Mono-forward
- - Editorial script + sans
-
-3. **Motion energy.** Pick one:
- - Restrained: state changes only
- - Responsive: feedback + transitions, no choreography
- - Choreographed: orchestrated entrances, scroll-driven sequences
-
-4. **Three named references.** Brands, products, printed objects. Not adjectives.
-
-5. **One anti-reference.** What it should NOT feel like. Also named.
-
-### Step 3: Write seed DESIGN.md
-
-Use the six-section spec from Scan mode. Populate what the interview answers; leave the rest as honest placeholders. The seed is a scaffold, not a fabricated spec.
-
-Lead the file with:
-
-```markdown
-<!-- SEED: re-run /impeccable document once there's code to capture the actual tokens and components. -->
-```
-
-Per-section guidance in seed mode:
-
-- **Overview**: Creative North Star and philosophy phrased from the answers (color strategy + motion energy + references). Reference the user's anti-reference directly.
-- **Colors**: Color strategy as a Named Rule (e.g. *"The Drenched Rule. The surface IS the color."*). Hue family or anchor reference. No hex values; mark as `[to be resolved during implementation]`.
-- **Typography**: the direction the user picked (e.g. "Serif display + sans body"). No font names yet: `[font pairing to be chosen at implementation]`.
-- **Elevation**: inferred from motion energy. Restrained/Responsive → flat by default; Choreographed → layered. One sentence.
-- **Components**: omit entirely; no components exist yet.
-- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.
-
-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.
-
-### Step 4: Confirm and refresh session cache
-
-1. Show the seed DESIGN.md. Call out that it is a seed (the marker is the literal commitment).
-2. Tell the user: "Re-run `/impeccable document` once you have some code. That pass will extract real tokens and generate the sidecar."
-3. Run `node .trae-cn/skills/impeccable/scripts/load-context.mjs` once so the seed lands in conversation for the rest of the session.
-
-## Style guidelines
-
-- **Frontmatter first, prose second.** Tokens go in the YAML frontmatter; prose contextualizes them. Don't redefine a token value in two places; the frontmatter is normative.
-- **Cite PRODUCT.md anti-references by name** in the Do's and Don'ts section. If PRODUCT.md lists "SaaS landing-page clichés" or "generic AI tool marketing" as anti-references, the DESIGN.md Don'ts should repeat those phrases verbatim so the visual spec enforces the strategic line.
-- **Match the spec, don't invent new sections.** The six section names are fixed. If you have Layout/Motion/Responsive content to document, fold it into Overview (philosophy-level rules) or Components (per-component behavior).
-- **Descriptive > technical**: "Gently curved edges (8px radius)" > "rounded-lg". Include the technical value in parens, lead with the description.
-- **Functional > decorative**: for each token, explain WHERE and WHY it's used, not just WHAT it is.
-- **Exact values in parens**: hex codes, px/rem values, font weights; always the number in parens alongside the description.
-- **Use Named Rules**: `**The [Name] Rule.** [short doctrine]`. These are memorable, citable, and much stickier for AI consumers than bullet lists. Stitch's own outputs use them heavily ("The No-Line Rule", "The Ghost Border Fallback"). Aim for 1-3 per section.
-- **Be forceful**. The voice of a design director. "Prohibited", "forbidden", "never", "always", not "consider", "might", "prefer". Match PRODUCT.md's tone.
-- **Concrete anti-pattern tests**. Stitch writes things like *"If it looks like a 2014 app, the shadow is too dark and the blur is too small."* A one-sentence audit test beats a paragraph of principle.
-- **Reference PRODUCT.md**. The anti-references section of PRODUCT.md should directly inform the Do's and Don'ts section here. Quote or paraphrase.
-- **Group colors by role**, not by hex-order or hue-order. Primary / Secondary / Tertiary / Neutral is the spec ordering.
-
-## Pitfalls
-
-- Don't paste raw CSS class names. Translate to descriptive language.
-- Don't extract every token. Stop at what's actually reused; one-offs pollute the system.
-- Don't invent components that don't exist. If the project only has buttons and cards, only document those.
-- Don't overwrite an existing DESIGN.md without asking.
-- Don't duplicate content from PRODUCT.md. DESIGN.md is strictly visual.
-- Don't add a "Layout Principles" or "Motion" or "Responsive Behavior" top-level section. The spec has six, not nine. Fold that content where it belongs.
-- Don't rename sections even slightly. "Colors" not "Color Palette & Roles". "Typography" not "Typography Rules". Tooling parsing depends on exact headers.
-- Don't duplicate token values between frontmatter and prose. If a color is in `colors.primary` as hex, the prose can name it and describe its role but should not reassert a different hex. The frontmatter is normative.
-- Don't invent frontmatter token groups outside Stitch's schema (no `motion:`, `breakpoints:`, `shadows:` at the top level). Stitch's Zod schema only accepts `colors`, `typography`, `rounded`, `spacing`, `components`. Anything else belongs in the sidecar's `extensions`.
@@ -1,69 +0,0 @@
-# Extract Flow
-
-Identify reusable patterns, components, and design tokens, then extract and consolidate them into the design system for systematic reuse.
-
-## Step 1: Discover the Design System
-
-Find the design system, component library, or shared UI directory. Understand its structure: component organization, naming conventions, design token structure, import/export conventions.
-
-**CRITICAL**: If no design system exists, ask the user directly to clarify what you cannot infer. before creating one. Understand the preferred location and structure first.
-
-## Step 2: Identify Patterns
-
-Look for extraction opportunities in the target area:
-
-- **Repeated components**: Similar UI patterns used 3+ times (buttons, cards, inputs)
-- **Hard-coded values**: Colors, spacing, typography, shadows that should be tokens
-- **Inconsistent variations**: Multiple implementations of the same concept
-- **Composition patterns**: Layout or interaction patterns that repeat (form rows, toolbar groups, empty states)
-- **Type styles**: Repeated font-size + weight + line-height combinations
-- **Animation patterns**: Repeated easing, duration, or keyframe combinations
-
-Assess value: only extract things used 3+ times with the same intent. Premature abstraction is worse than duplication.
-
-## Step 3: Plan Extraction
-
-Create a systematic plan:
-
-- **Components to extract**: Which UI elements become reusable components?
-- **Tokens to create**: Which hard-coded values become design tokens?
-- **Variants to support**: What variations does each component need?
-- **Naming conventions**: Component names, token names, prop names that match existing patterns
-- **Migration path**: How to refactor existing uses to consume the new shared versions
-
-**IMPORTANT**: Design systems grow incrementally. Extract what is clearly reusable now, not everything that might someday be reusable.
-
-## Step 4: Extract & Enrich
-
-Build improved, reusable versions:
-
-- **Components**: Clear props API with sensible defaults, proper variants for different use cases, accessibility built in (ARIA, keyboard navigation, focus management), documentation and usage examples
-- **Design tokens**: Clear naming (primitive vs semantic), proper hierarchy and organization, documentation of when to use each token
-- **Patterns**: When to use this pattern, code examples, variations and combinations
-
-## Step 5: Migrate
-
-Replace existing uses with the new shared versions:
-
-- **Find all instances**: Search for the patterns you extracted
-- **Replace systematically**: Update each use to consume the shared version
-- **Test thoroughly**: Ensure visual and functional parity
-- **Delete dead code**: Remove the old implementations
-
-## Step 6: Document
-
-Update design system documentation:
-
-- Add new components to the component library
-- Document token usage and values
-- Add examples and guidelines
-- Update any Storybook or component catalog
-
-**NEVER**:
-- Extract one-off, context-specific implementations without generalization
-- Create components so generic they are useless
-- Extract without considering existing design system conventions
-- Skip proper TypeScript types or prop documentation
-- Create tokens for every single value (tokens should have semantic meaning)
-- Extract things that differ in intent (two buttons that look similar but serve different purposes should stay separate)
-
@@ -1,347 +0,0 @@
-Designs that only work with perfect data aren't production-ready. Harden the interface against the inputs, errors, languages, and network conditions that real users will throw at it.
-
-## Assess Hardening Needs
-
-Identify weaknesses and edge cases:
-
-1. **Test with extreme inputs**:
- - Very long text (names, descriptions, titles)
- - Very short text (empty, single character)
- - Special characters (emoji, RTL text, accents)
- - Large numbers (millions, billions)
- - Many items (1000+ list items, 50+ options)
- - No data (empty states)
-
-2. **Test error scenarios**:
- - Network failures (offline, slow, timeout)
- - API errors (400, 401, 403, 404, 500)
- - Validation errors
- - Permission errors
- - Rate limiting
- - Concurrent operations
-
-3. **Test internationalization**:
- - Long translations (German is often 30% longer than English)
- - RTL languages (Arabic, Hebrew)
- - Character sets (Chinese, Japanese, Korean, emoji)
- - Date/time formats
- - Number formats (1,000 vs 1.000)
- - Currency symbols
-
-**CRITICAL**: Designs that only work with perfect data aren't production-ready. Harden against reality.
-
-## Hardening Dimensions
-
-Systematically improve resilience:
-
-### Text Overflow & Wrapping
-
-**Long text handling**:
-```css
-/* Single line with ellipsis */
-.truncate {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* Multi-line with clamp */
-.line-clamp {
- display: -webkit-box;
- -webkit-line-clamp: 3;
- -webkit-box-orient: vertical;
- overflow: hidden;
-}
-
-/* Allow wrapping */
-.wrap {
- word-wrap: break-word;
- overflow-wrap: break-word;
- hyphens: auto;
-}
-```
-
-**Flex/Grid overflow**:
-```css
-/* Prevent flex items from overflowing */
-.flex-item {
- min-width: 0; /* Allow shrinking below content size */
- overflow: hidden;
-}
-
-/* Prevent grid items from overflowing */
-.grid-item {
- min-width: 0;
- min-height: 0;
-}
-```
-
-**Responsive text sizing**:
-- Use `clamp()` for fluid typography
-- Set minimum readable sizes (14px on mobile)
-- Test text scaling (zoom to 200%)
-- Ensure containers expand with text
-
-### Internationalization (i18n)
-
-**Text expansion**:
-- Add 30-40% space budget for translations
-- Use flexbox/grid that adapts to content
-- Test with longest language (usually German)
-- Avoid fixed widths on text containers
-
-```jsx
-// ❌ Bad: Assumes short English text
-<button className="w-24">Submit</button>
-
-// ✅ Good: Adapts to content
-<button className="px-4 py-2">Submit</button>
-```
-
-**RTL (Right-to-Left) support**:
-```css
-/* Use logical properties */
-margin-inline-start: 1rem; /* Not margin-left */
-padding-inline: 1rem; /* Not padding-left/right */
-border-inline-end: 1px solid; /* Not border-right */
-
-/* Or use dir attribute */
-[dir="rtl"] .arrow { transform: scaleX(-1); }
-```
-
-**Character set support**:
-- Use UTF-8 encoding everywhere
-- Test with Chinese/Japanese/Korean (CJK) characters
-- Test with emoji (they can be 2-4 bytes)
-- Handle different scripts (Latin, Cyrillic, Arabic, etc.)
-
-**Date/Time formatting**:
-```javascript
-// ✅ Use Intl API for proper formatting
-new Intl.DateTimeFormat('en-US').format(date); // 1/15/2024
-new Intl.DateTimeFormat('de-DE').format(date); // 15.1.2024
-
-new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: 'USD'
-}).format(1234.56); // $1,234.56
-```
-
-**Pluralization**:
-```javascript
-// ❌ Bad: Assumes English pluralization
-`${count} item${count !== 1 ? 's' : ''}`
-
-// ✅ Good: Use proper i18n library
-t('items', { count }) // Handles complex plural rules
-```
-
-### Error Handling
-
-**Network errors**:
-- Show clear error messages
-- Provide retry button
-- Explain what happened
-- Offer offline mode (if applicable)
-- Handle timeout scenarios
-
-```jsx
-// Error states with recovery
-{error && (
- <ErrorMessage>
- <p>Failed to load data. {error.message}</p>
- <button onClick={retry}>Try again</button>
- </ErrorMessage>
-)}
-```
-
-**Form validation errors**:
-- Inline errors near fields
-- Clear, specific messages
-- Suggest corrections
-- Don't block submission unnecessarily
-- Preserve user input on error
-
-**API errors**:
-- Handle each status code appropriately
- - 400: Show validation errors
- - 401: Redirect to login
- - 403: Show permission error
- - 404: Show not found state
- - 429: Show rate limit message
- - 500: Show generic error, offer support
-
-**Graceful degradation**:
-- Core functionality works without JavaScript
-- Images have alt text
-- Progressive enhancement
-- Fallbacks for unsupported features
-
-### Edge Cases & Boundary Conditions
-
-**Empty states**:
-- No items in list
-- No search results
-- No notifications
-- No data to display
-- Provide clear next action
-
-**Loading states**:
-- Initial load
-- Pagination load
-- Refresh
-- Show what's loading ("Loading your projects...")
-- Time estimates for long operations
-
-**Large datasets**:
-- Pagination or virtual scrolling
-- Search/filter capabilities
-- Performance optimization
-- Don't load all 10,000 items at once
-
-**Concurrent operations**:
-- Prevent double-submission (disable button while loading)
-- Handle race conditions
-- Optimistic updates with rollback
-- Conflict resolution
-
-**Permission states**:
-- No permission to view
-- No permission to edit
-- Read-only mode
-- Clear explanation of why
-
-**Browser compatibility**:
-- Polyfills for modern features
-- Fallbacks for unsupported CSS
-- Feature detection (not browser detection)
-- Test in target browsers
-
-### Input Validation & Sanitization
-
-**Client-side validation**:
-- Required fields
-- Format validation (email, phone, URL)
-- Length limits
-- Pattern matching
-- Custom validation rules
-
-**Server-side validation** (always):
-- Never trust client-side only
-- Validate and sanitize all inputs
-- Protect against injection attacks
-- Rate limiting
-
-**Constraint handling**:
-```html
-<!-- Set clear constraints -->
-<input
- type="text"
- maxlength="100"
- pattern="[A-Za-z0-9]+"
- required
- aria-describedby="username-hint"
-/>
-<small id="username-hint">
- Letters and numbers only, up to 100 characters
-</small>
-```
-
-### Accessibility Resilience
-
-**Keyboard navigation**:
-- All functionality accessible via keyboard
-- Logical tab order
-- Focus management in modals
-- Skip links for long content
-
-**Screen reader support**:
-- Proper ARIA labels
-- Announce dynamic changes (live regions)
-- Descriptive alt text
-- Semantic HTML
-
-**Motion sensitivity**:
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**High contrast mode**:
-- Test in Windows high contrast mode
-- Don't rely only on color
-- Provide alternative visual cues
-
-### Performance Resilience
-
-**Slow connections**:
-- Progressive image loading
-- Skeleton screens
-- Optimistic UI updates
-- Offline support (service workers)
-
-**Memory leaks**:
-- Clean up event listeners
-- Cancel subscriptions
-- Clear timers/intervals
-- Abort pending requests on unmount
-
-**Throttling & Debouncing**:
-```javascript
-// Debounce search input
-const debouncedSearch = debounce(handleSearch, 300);
-
-// Throttle scroll handler
-const throttledScroll = throttle(handleScroll, 100);
-```
-
-## Testing Strategies
-
-**Manual testing**:
-- Test with extreme data (very long, very short, empty)
-- Test in different languages
-- Test offline
-- Test slow connection (throttle to 3G)
-- Test with screen reader
-- Test keyboard-only navigation
-- Test on old browsers
-
-**Automated testing**:
-- Unit tests for edge cases
-- Integration tests for error scenarios
-- E2E tests for critical paths
-- Visual regression tests
-- Accessibility tests (axe, WAVE)
-
-**IMPORTANT**: Hardening is about expecting the unexpected. Real users will do things you never imagined.
-
-**NEVER**:
-- Assume perfect input (validate everything)
-- Ignore internationalization (design for global)
-- Leave error messages generic ("Error occurred")
-- Forget offline scenarios
-- Trust client-side validation alone
-- Use fixed widths for text
-- Assume English-length text
-- Block entire interface when one component errors
-
-## Verify Hardening
-
-Test thoroughly with edge cases:
-
-- **Long text**: Try names with 100+ characters
-- **Emoji**: Use emoji in all text fields
-- **RTL**: Test with Arabic or Hebrew
-- **CJK**: Test with Chinese/Japanese/Korean
-- **Network issues**: Disable internet, throttle connection
-- **Large datasets**: Test with 1000+ items
-- **Concurrent actions**: Click submit 10 times rapidly
-- **Errors**: Force API errors, test all error states
-- **Empty**: Remove all data, test empty states
-
-When edge cases are covered, hand off to `/impeccable polish` for the final pass.
@@ -1,234 +0,0 @@
-# Heuristics Scoring Guide
-
-Score each of Nielsen's 10 Usability Heuristics on a 0–4 scale. Be honest: a 4 means genuinely excellent, not "good enough."
-
-## Nielsen's 10 Heuristics
-
-### 1. Visibility of System Status
-
-Keep users informed about what's happening through timely, appropriate feedback.
-
-**Check for**:
-- Loading indicators during async operations
-- Confirmation of user actions (save, submit, delete)
-- Progress indicators for multi-step processes
-- Current location in navigation (breadcrumbs, active states)
-- Form validation feedback (inline, not just on submit)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No feedback; user is guessing what happened |
-| 1 | Rare feedback; most actions produce no visible response |
-| 2 | Partial; some states communicated, major gaps remain |
-| 3 | Good; most operations give clear feedback, minor gaps |
-| 4 | Excellent; every action confirms, progress is always visible |
-
-### 2. Match Between System and Real World
-
-Speak the user's language. Follow real-world conventions. Information appears in natural, logical order.
-
-**Check for**:
-- Familiar terminology (no unexplained jargon)
-- Logical information order matching user expectations
-- Recognizable icons and metaphors
-- Domain-appropriate language for the target audience
-- Natural reading flow (left-to-right, top-to-bottom priority)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Pure tech jargon, alien to users |
-| 1 | Mostly confusing; requires domain expertise to navigate |
-| 2 | Mixed; some plain language, some jargon leaks through |
-| 3 | Mostly natural; occasional term needs context |
-| 4 | Speaks the user's language fluently throughout |
-
-### 3. User Control and Freedom
-
-Users need a clear "emergency exit" from unwanted states without extended dialogue.
-
-**Check for**:
-- Undo/redo functionality
-- Cancel buttons on forms and modals
-- Clear navigation back to safety (home, previous)
-- Easy way to clear filters, search, selections
-- Escape from long or multi-step processes
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Users get trapped; no way out without refreshing |
-| 1 | Difficult exits; must find obscure paths to escape |
-| 2 | Some exits; main flows have escape, edge cases don't |
-| 3 | Good control; users can exit and undo most actions |
-| 4 | Full control; undo, cancel, back, and escape everywhere |
-
-### 4. Consistency and Standards
-
-Users shouldn't wonder whether different words, situations, or actions mean the same thing.
-
-**Check for**:
-- Consistent terminology throughout the interface
-- Same actions produce same results everywhere
-- Platform conventions followed (standard UI patterns)
-- Visual consistency (colors, typography, spacing, components)
-- Consistent interaction patterns (same gesture = same behavior)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Inconsistent everywhere; feels like different products stitched together |
-| 1 | Many inconsistencies; similar things look/behave differently |
-| 2 | Partially consistent; main flows match, details diverge |
-| 3 | Mostly consistent; occasional deviation, nothing confusing |
-| 4 | Fully consistent; cohesive system, predictable behavior |
-
-### 5. Error Prevention
-
-Better than good error messages is a design that prevents problems in the first place.
-
-**Check for**:
-- Confirmation before destructive actions (delete, overwrite)
-- Constraints preventing invalid input (date pickers, dropdowns)
-- Smart defaults that reduce errors
-- Clear labels that prevent misunderstanding
-- Autosave and draft recovery
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Errors easy to make; no guardrails anywhere |
-| 1 | Few safeguards; some inputs validated, most aren't |
-| 2 | Partial prevention; common errors caught, edge cases slip |
-| 3 | Good prevention; most error paths blocked proactively |
-| 4 | Excellent; errors nearly impossible through smart constraints |
-
-### 6. Recognition Rather Than Recall
-
-Minimize memory load. Make objects, actions, and options visible or easily retrievable.
-
-**Check for**:
-- Visible options (not buried in hidden menus)
-- Contextual help when needed (tooltips, inline hints)
-- Recent items and history
-- Autocomplete and suggestions
-- Labels on icons (not icon-only navigation)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Heavy memorization; users must remember paths and commands |
-| 1 | Mostly recall; many hidden features, few visible cues |
-| 2 | Some aids; main actions visible, secondary features hidden |
-| 3 | Good recognition; most things discoverable, few memory demands |
-| 4 | Everything discoverable; users never need to memorize |
-
-### 7. Flexibility and Efficiency of Use
-
-Accelerators, invisible to novices, speed up expert interaction.
-
-**Check for**:
-- Keyboard shortcuts for common actions
-- Customizable interface elements
-- Recent items and favorites
-- Bulk/batch actions
-- Power user features that don't complicate the basics
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | One rigid path; no shortcuts or alternatives |
-| 1 | Limited flexibility; few alternatives to the main path |
-| 2 | Some shortcuts; basic keyboard support, limited bulk actions |
-| 3 | Good accelerators; keyboard nav, some customization |
-| 4 | Highly flexible; multiple paths, power features, customizable |
-
-### 8. Aesthetic and Minimalist Design
-
-Interfaces should not contain irrelevant or rarely needed information. Every element should serve a purpose.
-
-**Check for**:
-- Only necessary information visible at each step
-- Clear visual hierarchy directing attention
-- Purposeful use of color and emphasis
-- No decorative clutter competing for attention
-- Focused, uncluttered layouts
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Overwhelming; everything competes for attention equally |
-| 1 | Cluttered; too much noise, hard to find what matters |
-| 2 | Some clutter; main content clear, periphery noisy |
-| 3 | Mostly clean; focused design, minor visual noise |
-| 4 | Perfectly minimal; every element earns its pixel |
-
-### 9. Help Users Recognize, Diagnose, and Recover from Errors
-
-Error messages should use plain language, precisely indicate the problem, and constructively suggest a solution.
-
-**Check for**:
-- Plain language error messages (no error codes for users)
-- Specific problem identification ("Email is missing @" not "Invalid input")
-- Actionable recovery suggestions
-- Errors displayed near the source of the problem
-- Non-blocking error handling (don't wipe the form)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Cryptic errors; codes, jargon, or no message at all |
-| 1 | Vague errors; "Something went wrong" with no guidance |
-| 2 | Clear but unhelpful; names the problem but not the fix |
-| 3 | Clear with suggestions; identifies problem and offers next steps |
-| 4 | Perfect recovery; pinpoints issue, suggests fix, preserves user work |
-
-### 10. Help and Documentation
-
-Even if the system is usable without docs, help should be easy to find, task-focused, and concise.
-
-**Check for**:
-- Searchable help or documentation
-- Contextual help (tooltips, inline hints, guided tours)
-- Task-focused organization (not feature-organized)
-- Concise, scannable content
-- Easy access without leaving current context
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No help available anywhere |
-| 1 | Help exists but hard to find or irrelevant |
-| 2 | Basic help; FAQ or docs exist, not contextual |
-| 3 | Good documentation; searchable, mostly task-focused |
-| 4 | Excellent contextual help; right info at the right moment |
-
----
-
-## Score Summary
-
-**Total possible**: 40 points (10 heuristics × 4 max)
-
-| Score Range | Rating | What It Means |
-|-------------|--------|---------------|
-| 36–40 | Excellent | Minor polish only; ship it |
-| 28–35 | Good | Address weak areas, solid foundation |
-| 20–27 | Acceptable | Significant improvements needed before users are happy |
-| 12–19 | Poor | Major UX overhaul required; core experience broken |
-| 0–11 | Critical | Redesign needed; unusable in current state |
-
----
-
-## Issue Severity (P0–P3)
-
-Tag each individual issue found during scoring with a priority level:
-
-| Priority | Name | Description | Action |
-|----------|------|-------------|--------|
-| **P0** | Blocking | Prevents task completion entirely | Fix immediately; this is a showstopper |
-| **P1** | Major | Causes significant difficulty or confusion | Fix before release |
-| **P2** | Minor | Annoyance, but workaround exists | Fix in next pass |
-| **P3** | Polish | Nice-to-fix, no real user impact | Fix if time permits |
-
-**Tip**: If you're unsure between two levels, ask: "Would a user contact support about this?" If yes, it's at least P1.
@@ -1,195 +0,0 @@
-# Interaction Design
-
-## The Eight Interactive States
-
-Every interactive element needs these states designed:
-
-| State | When | Visual Treatment |
-|-------|------|------------------|
-| **Default** | At rest | Base styling |
-| **Hover** | Pointer over (not touch) | Subtle lift, color shift |
-| **Focus** | Keyboard/programmatic focus | Visible ring (see below) |
-| **Active** | Being pressed | Pressed in, darker |
-| **Disabled** | Not interactive | Reduced opacity, no pointer |
-| **Loading** | Processing | Spinner, skeleton |
-| **Error** | Invalid state | Red border, icon, message |
-| **Success** | Completed | Green check, confirmation |
-
-**The common miss**: Designing hover without focus, or vice versa. They're different. Keyboard users never see hover states.
-
-## Focus Rings: Do Them Right
-
-**Never `outline: none` without replacement.** It's an accessibility violation. Instead, use `:focus-visible` to show focus only for keyboard users:
-
-```css
-/* Hide focus ring for mouse/touch */
-button:focus {
- outline: none;
-}
-
-/* Show focus ring for keyboard */
-button:focus-visible {
- outline: 2px solid var(--color-accent);
- outline-offset: 2px;
-}
-```
-
-**Focus ring design**:
-- High contrast (3:1 minimum against adjacent colors)
-- 2-3px thick
-- Offset from element (not inside it)
-- Consistent across all interactive elements
-
-## Form Design: The Non-Obvious
-
-**Placeholders aren't labels.** They disappear on input. Always use visible `<label>` elements. **Validate on blur**, not on every keystroke (exception: password strength). Place errors **below** fields with `aria-describedby` connecting them.
-
-## Loading States
-
-**Optimistic updates**: Show success immediately, rollback on failure. Use for low-stakes actions (likes, follows), not payments or destructive actions. **Skeleton screens > spinners**: they preview content shape and feel faster than generic spinners.
-
-## Modals: The Inert Approach
-
-Focus trapping in modals used to require complex JavaScript. Now use the `inert` attribute:
-
-```html
-<!-- When modal is open -->
-<main inert>
- <!-- Content behind modal can't be focused or clicked -->
-</main>
-<dialog open>
- <h2>Modal Title</h2>
- <!-- Focus stays inside modal -->
-</dialog>
-```
-
-Or use the native `<dialog>` element:
-
-```javascript
-const dialog = document.querySelector('dialog');
-dialog.showModal(); // Opens with focus trap, closes on Escape
-```
-
-## The Popover API
-
-For tooltips, dropdowns, and non-modal overlays, use native popovers:
-
-```html
-<button popovertarget="menu">Open menu</button>
-<div id="menu" popover>
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-**Benefits**: Light-dismiss (click outside closes), proper stacking, no z-index wars, accessible by default.
-
-## Dropdown & Overlay Positioning
-
-Dropdowns rendered with `position: absolute` inside a container that has `overflow: hidden` or `overflow: auto` will be clipped. This is the single most common dropdown bug in generated code.
-
-### CSS Anchor Positioning
-
-The modern solution uses the CSS Anchor Positioning API to tether an overlay to its trigger without JavaScript:
-
-```css
-.trigger {
- anchor-name: --menu-trigger;
-}
-
-.dropdown {
- position: fixed;
- position-anchor: --menu-trigger;
- position-area: block-end span-inline-end;
- margin-top: 4px;
-}
-
-/* Flip above if no room below */
-@position-try --flip-above {
- position-area: block-start span-inline-end;
- margin-bottom: 4px;
-}
-```
-
-Because the dropdown uses `position: fixed`, it escapes any `overflow` clipping on ancestor elements. The `@position-try` block handles viewport edges automatically. **Browser support**: Chrome 125+, Edge 125+. Not yet in Firefox or Safari - use a fallback for those browsers.
-
-### Popover + Anchor Combo
-
-Combining the Popover API with anchor positioning gives you stacking, light-dismiss, accessibility, and correct positioning in one pattern:
-
-```html
-<button popovertarget="menu" class="trigger">Open</button>
-<div id="menu" popover class="dropdown">
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-The `popover` attribute places the element in the **top layer**, which sits above all other content regardless of z-index or overflow. No portal needed.
-
-### Portal / Teleport Pattern
-
-In component frameworks, render the dropdown at the document root and position it with JavaScript:
-
-- **React**: `createPortal(dropdown, document.body)`
-- **Vue**: `<Teleport to="body">`
-- **Svelte**: Use a portal library or mount to `document.body`
-
-Calculate position from the trigger's `getBoundingClientRect()`, then apply `position: fixed` with `top` and `left` values. Recalculate on scroll and resize.
-
-### Fixed Positioning Fallback
-
-For browsers without anchor positioning support, `position: fixed` with manual coordinates avoids overflow clipping:
-
-```css
-.dropdown {
- position: fixed;
- /* top/left set via JS from trigger's getBoundingClientRect() */
-}
-```
-
-Check viewport boundaries before rendering. If the dropdown would overflow the bottom edge, flip it above the trigger. If it would overflow the right edge, align it to the trigger's right side instead.
-
-### Anti-Patterns
-
-- **`position: absolute` inside `overflow: hidden`** - The dropdown will be clipped. Use `position: fixed` or the top layer instead.
-- **Arbitrary z-index values** like `z-index: 9999` - Use a semantic z-index scale: `dropdown (100) -> sticky (200) -> modal-backdrop (300) -> modal (400) -> toast (500) -> tooltip (600)`.
-- **Rendering dropdown markup inline** without an escape hatch from the parent's stacking context. Either use `popover` (top layer), a portal, or `position: fixed`.
-
-## Destructive Actions: Undo > Confirm
-
-**Undo is better than confirmation dialogs.** Users click through confirmations mindlessly. Remove from UI immediately, show undo toast, actually delete after toast expires. Use confirmation only for truly irreversible actions (account deletion), high-cost actions, or batch operations.
-
-## Keyboard Navigation Patterns
-
-### Roving Tabindex
-
-For component groups (tabs, menu items, radio groups), one item is tabbable; arrow keys move within:
-
-```html
-<div role="tablist">
- <button role="tab" tabindex="0">Tab 1</button>
- <button role="tab" tabindex="-1">Tab 2</button>
- <button role="tab" tabindex="-1">Tab 3</button>
-</div>
-```
-
-Arrow keys move `tabindex="0"` between items. Tab moves to the next component entirely.
-
-### Skip Links
-
-Provide skip links (`<a href="#main-content">Skip to main content</a>`) for keyboard users to jump past navigation. Hide off-screen, show on focus.
-
-## Gesture Discoverability
-
-Swipe-to-delete and similar gestures are invisible. Hint at their existence:
-
-- **Partially reveal**: Show delete button peeking from edge
-- **Onboarding**: Coach marks on first use
-- **Alternative**: Always provide a visible fallback (menu with "Delete")
-
-Don't rely on gestures as the only way to perform actions.
-
----
-
-**Avoid**: Removing focus indicators without alternatives. Using placeholder text as labels. Touch targets <44x44px. Generic error messages. Custom controls without ARIA/keyboard support.
@@ -1,141 +0,0 @@
-Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids, the centered-stack default) and fix the structure, not the surface.
-
----
-
-## Register
-
-Brand: asymmetric compositions, fluid spacing with `clamp()`, intentional grid-breaking for emphasis. Rhythm through contrast: tight groupings paired with generous separations.
-
-Product: predictable grids, consistent densities, familiar navigation patterns. Responsive behavior is structural (collapse sidebar, responsive table), not fluid typography. Consistency IS an affordance.
-
----
-
-## Assess Current Layout
-
-Analyze what's weak about the current spatial design:
-
-1. **Spacing**:
- - Is spacing consistent or arbitrary? (Random padding/margin values)
- - Is all spacing the same? (Equal padding everywhere = no rhythm)
- - Are related elements grouped tightly, with generous space between groups?
-
-2. **Visual hierarchy**:
- - Apply the squint test: blur your (metaphorical) eyes. Can you still identify the most important element, second most important, and clear groupings?
- - Is hierarchy achieved effectively? (Space and weight alone can be enough; is the current approach working?)
- - Does whitespace guide the eye to what matters?
-
-3. **Grid & structure**:
- - Is there a clear underlying structure, or does the layout feel random?
- - Are identical card grids used everywhere? (Icon + heading + text, repeated endlessly)
- - Is everything centered? (Left-aligned with asymmetric layouts feels more designed, but not a hard and fast rule)
-
-4. **Rhythm & variety**:
- - Does the layout have visual rhythm? (Alternating tight/generous spacing)
- - Is every section structured the same way? (Monotonous repetition)
- - Are there intentional moments of surprise or emphasis?
-
-5. **Density**:
- - Is the layout too cramped? (Not enough breathing room)
- - Is the layout too sparse? (Excessive whitespace without purpose)
- - Does density match the content type? (Data-dense UIs need tighter spacing; marketing pages need more air)
-
-**CRITICAL**: Layout problems are often the root cause of interfaces feeling "off" even when colors and fonts are fine. Space is a design material; use it with intention.
-
-## Plan Layout Improvements
-
-Consult the [spatial design reference](spatial-design.md) for detailed guidance on grids, rhythm, and container queries.
-
-Create a systematic plan:
-
-- **Spacing system**: Use a consistent scale (a framework's built-in scale like Tailwind's, rem-based tokens, or a custom system). The specific values matter less than consistency.
-- **Hierarchy strategy**: How will space communicate importance?
-- **Layout approach**: What structure fits the content? Flex for 1D, Grid for 2D, named areas for complex page layouts.
-- **Rhythm**: Where should spacing be tight vs generous?
-
-## Improve Layout Systematically
-
-### Establish a Spacing System
-
-- Use a consistent spacing scale (framework scales like Tailwind, rem-based tokens, or a custom scale all work). What matters is that values come from a defined set, not arbitrary numbers.
-- Name tokens semantically if using custom properties: `--space-xs` through `--space-xl`, not `--spacing-8`
-- Use `gap` for sibling spacing instead of margins; eliminates margin collapse hacks
-- Apply `clamp()` for fluid spacing that breathes on larger screens
-
-### Create Visual Rhythm
-
-- **Tight grouping** for related elements (8-12px between siblings)
-- **Generous separation** between distinct sections (48-96px)
-- **Varied spacing** within sections (not every row needs the same gap)
-- **Asymmetric compositions**: break the predictable centered-content pattern when it makes sense
-
-### Choose the Right Layout Tool
-
-- **Use Flexbox for 1D layouts**: Rows of items, nav bars, button groups, card contents, most component internals. Flex is simpler and more appropriate for the majority of layout tasks.
-- **Use Grid for 2D layouts**: Page-level structure, dashboards, data-dense interfaces, anything where rows AND columns need coordinated control.
-- **Don't default to Grid** when Flexbox with `flex-wrap` would be simpler and more flexible.
-- Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints.
-- Use named grid areas (`grid-template-areas`) for complex page layouts; redefine at breakpoints.
-
-### Break Card Grid Monotony
-
-- Don't default to card grids for everything; spacing and alignment create visual grouping naturally
-- Use cards only when content is truly distinct and actionable. Never nest cards inside cards
-- Vary card sizes, span columns, or mix cards with non-card content to break repetition
-
-### Strengthen Visual Hierarchy
-
-- Use the fewest dimensions needed for clear hierarchy. Space alone can be enough; generous whitespace around an element draws the eye. Some of the most polished designs achieve rhythm with just space and weight. Add color or size contrast only when simpler means aren't sufficient.
-- Be aware of reading flow: in LTR languages, the eye naturally scans top-left to bottom-right, but primary action placement depends on context (e.g., bottom-right in dialogs, top in navigation).
-- Create clear content groupings through proximity and separation.
-
-### Manage Depth & Elevation
-
-- Create a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip)
-- Build a consistent shadow scale (sm → md → lg → xl); shadows should be subtle
-- Use elevation to reinforce hierarchy, not as decoration
-
-### Optical Adjustments
-
-- If an icon looks visually off-center despite being geometrically centered, nudge it. But only if you're confident it actually looks wrong. Don't adjust speculatively.
-
-**NEVER**:
-- Use arbitrary spacing values outside your scale
-- Make all spacing equal (variety creates hierarchy)
-- Wrap everything in cards (not everything needs a container)
-- Nest cards inside cards (use spacing and dividers for hierarchy within)
-- Use identical card grids everywhere (icon + heading + text, repeated)
-- Center everything (left-aligned with asymmetry feels more designed)
-- Default to the hero metric layout (big number, small label, stats, gradient) as a template. If showing real user data, a prominent metric can work, but it should display actual data, not decorative numbers.
-- Default to CSS Grid when Flexbox would be simpler; use the simplest tool for the job
-- Use arbitrary z-index values (999, 9999); build a semantic scale
-
-## Verify Layout Improvements
-
-- **Squint test**: Can you identify primary, secondary, and groupings with blurred vision?
-- **Rhythm**: Does the page have a satisfying beat of tight and generous spacing?
-- **Hierarchy**: Is the most important content obvious within 2 seconds?
-- **Breathing room**: Does the layout feel comfortable, not cramped or wasteful?
-- **Consistency**: Is the spacing system applied uniformly?
-- **Responsiveness**: Does the layout adapt gracefully across screen sizes?
-
-When the rhythm and hierarchy land, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `density` param. Drive all spacing tokens in the variant's scoped CSS through `calc(var(--p-density, 1) * <base>)`: paddings, gaps, column widths. Users slide from airy to packed and see layout re-breathe with no regeneration.
-
-```json
-{"id":"density","kind":"range","min":0.6,"max":1.4,"step":0.05,"default":1,"label":"Density"}
-```
-
-For variants whose topology genuinely changes (stacked vs. side-by-side, grid vs. bento), use a `steps` param whose scoped CSS branches via `:scope[data-p-structure="X"]`. One structure param + one density param is a powerful combo; resist adding a third.
-
-```json
-{"id":"structure","kind":"steps","default":"grid","label":"Structure","options":[
- {"value":"stacked","label":"Stacked"},
- {"value":"grid","label":"Grid"},
- {"value":"bento","label":"Bento"}
-]}
-```
-
-See `reference/live.md` for the full params contract.
@@ -1,622 +0,0 @@
-Interactive live variant mode: select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via the dev server's HMR.
-
-## Prerequisites
-
-A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR a static HTML file open in the browser.
-
-## The contract (read once)
-
-Execute in order. No step skipped, no step reordered.
-
-1. `live.mjs`: boot.
-2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.
-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.
-5. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
-6. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
-7. On `exit`: run the cleanup at the bottom.
-
-Harness policy:
-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.
-- **Cursor**: run the poll in the **foreground** (blocking shell; not a background terminal, not a subagent). Cursor background terminals and subagents do not reliably resume the chat with poll stdout.
-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.
-- **Other harnesses**: foreground unless you know stdout reliably returns to this session.
-
-Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.
-
-## Start
-
-```bash
-node .trae-cn/skills/impeccable/scripts/live.mjs
-```
-
-Output JSON: `{ ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath, migrated }`. `pageFiles` is the list of HTML entries the live script was injected into. Keep PRODUCT.md and DESIGN.md in mind for variant generation; **DESIGN.md wins on visual decisions; PRODUCT.md wins on strategic/voice decisions.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt. If `migrated: true`, the loader auto-renamed legacy `.impeccable.md` to `PRODUCT.md`; mention this once and suggest `/impeccable document` for the matching DESIGN.md.
-
-`serverPort` and `serverToken` belong to the small **Impeccable live helper** HTTP server (serves `/live.js`, SSE, and `/poll`). That port is **not** your dev server and is usually not the URL you open to view the app. The browser page is whatever origin serves one of the `pageFiles` entries (Vite / Next / Bun / tunnel / LAN hostname).
-
-If output is `{ ok: false, error: "config_missing" | "config_invalid", path }`, this project hasn't been configured for live mode (or its config is stale). See **First-time setup** at the bottom.
-
-## Poll loop
-
-```
-LOOP:
- node .trae-cn/skills/impeccable/scripts/live-poll.mjs # default long timeout; no --timeout=
- Read JSON; dispatch on "type"
-
- "generate" → Handle Generate; reply done; LOOP
- "accept" → Handle Accept; complete carbonize cleanup if required; LOOP
- "discard" → Handle Discard; LOOP
- "prefetch" → Handle Prefetch; LOOP
- "timeout" → LOOP
- "exit" → break → Cleanup
-```
-
-## Recovery commands
-
-The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.
-
-Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:
-
-```bash
-node .trae-cn/skills/impeccable/scripts/live-status.mjs
-node .trae-cn/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID
-node .trae-cn/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID
-```
-
-- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.
-- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.
-- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.
-
-Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.
-
-## Handle `generate`
-
-Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.
-
-Speed matters; the user is watching a spinner. Minimize tool calls by using the `wrap` helper and writing all variants in a single edit.
-
-### 1. Read the screenshot (if present)
-
-`event.screenshotPath` is **only sent when the user placed at least one comment or stroke before Go.** When present, it's an absolute path to a PNG of the element as rendered with the annotations baked in. **Read it before planning**: annotations encode user intent not recoverable from `element.outerHTML` alone.
-
-When `screenshotPath` is absent, don't ask for one and don't go looking for the current rendering. The omission is deliberate: without annotations, a screenshot would anchor the model on the existing design and fight the three-distinct-directions brief. Work from `element.outerHTML`, the computed styles in `event.element`, and the freeform prompt if present.
-
-`event.comments` and `event.strokes` carry structured metadata alongside the visual. Treat the screenshot as primary; use the structured data for specifics worth quoting (e.g. the exact text of a comment).
-
-Reading annotations precisely:
-
-- **Comment position carries meaning.** Its `{x, y}` is element-local CSS px (same coord space as `element.boundingRect`). Find the child under that point and apply the comment text LOCALLY to that sub-element. A comment near the title is about the title, not a global description.
-- **Comments and strokes are independent annotations** unless clearly paired by overlap or tight proximity. Don't let the visual weight of a prominent stroke override the precise location of a textually-specific comment elsewhere.
-- **Strokes are gestures; read them by shape.** Closed loop = "this thing" (emphasis / focus); arrow = direction (move / point to); cross or slash = delete; free scribble = emphasis or delete depending on context. A loop around region X means "pay attention to X," not "only change pixels inside X."
-- **When a stroke's intent is ambiguous** (circle or arrow? emphasis or move?), state your reading in one sentence of rationale rather than silently guessing. If the uncertainty materially changes the brief, ask one short clarifying question before generating.
-
-### 2. Wrap the element
-
-```bash
-node .trae-cn/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"
-```
-
-Flag mapping. Keep them separate, don't collapse into `--query`:
-
-- `--element-id` ← `event.element.id`
-- `--classes` ← `event.element.classes` joined with commas
-- `--tag` ← `event.element.tagName`
-- `--text` ← first ~80 chars of `event.element.textContent` (trim, single-line). **Pass this every call.** When the picked element shares classes + tag with sibling components (a list of `<Card>`s, repeating sections), this is what disambiguates which branch in source to wrap. Without it, wrap silently lands on the first match and may rewrite the wrong element.
-
-The helper searches ID first, then classes, then tag + class combo. If `event.pageUrl` implies the file (e.g. `/` is usually `index.html`), pass `--file PATH` to skip the search. `--query` is a fallback for raw text search only; do not use it for normal element lookups.
-
-If `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.
-
-Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.
-
-`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:
-
-- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.
-- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.
-
-Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.
-
-**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:
-
-- `{ error: "file_is_generated", file, hint }`: user-supplied `--file` points at a generated file.
-- `{ error: "element_not_in_source", generatedMatch, hint }`: element exists only in a generated file (the next build would wipe any edits).
-- `{ error: "element_not_found", hint }`: element isn't in any project file; likely runtime-injected (JS component, dynamic render from data).
-
-All three carry `fallback: "agent-driven"`. Follow **Handle fallback** below.
-
-### 3. Load the action's reference
-
-If `event.action` is `impeccable` (the default freeform action), use SKILL.md's shared laws plus the loaded register reference (`brand.md` or `product.md`). Do not load a sub-command reference. **Freeform is not a pass to skip parameters:** you still follow the composition budget and the freeform bias in **§7 Parameters** below. Sub-command files list MUST-have signature knobs; freeform has no such file, so sizing knobs from surface weight and primary axes is entirely on you.
-
-Any other `event.action` (`bolder`, `quieter`, `distill`, `polish`, `typeset`, `colorize`, `layout`, `adapt`, `animate`, `delight`, `overdrive`): Read `reference/<action>.md` before planning. Each sub-command encodes a specific discipline; skipping its reference produces generic output. Those files may require specific params; layer them on top of the §7 budget, not instead of it.
-
-### 4. Plan three variants: identity first, then mode, then axes
-
-The wrong frame for live mode is "show three different design directions." Live runs on an existing surface; the brand has already been chosen. The job is variation **within identity**, not selection between identities. Failure mode: three editorial-typographic variants on a brief that wasn't editorial. Bigger failure mode: three off-brand variants the user can't accept because they don't look like their product.
-
-Four phases. Do them in order.
-
-#### Phase A: Extract the identity (non-skippable)
-
-The existing surface has an identity already. Read it before planning anything. Sources, in priority order:
-
-1. **DESIGN.md** if loaded: read the visual system fields (palette, type pairing, motion, components). This is the authoritative answer.
-2. **CSS custom properties** in the page's stylesheets (`:root { --color-...; --font-...; ... }`): these are de-facto tokens.
-3. **Computed styles** on the picked element and its parent: colors, fonts, spacing scales, corner radii.
-4. **Sibling components on the page**: what visual rhetoric do existing components use? (Asymmetric or centered? Dense or airy? Bold or quiet?)
-
-Write down what you see in **one sentence**. The sentence describes the surface that's actually on screen; it is not aspirational, not opinionated, not edited toward what the brand "should" be. Capture, in roughly this order:
-
-- The dominant surface color and accent color, by hex or token name (use the actual values, not categories like "warm" or "neutral").
-- The type pairing: the actual font names loaded, primary first.
-- The layout topology: how the dominant elements are arranged (stacked / side-by-side / grid / asymmetric / overlay).
-- The surface treatment: corners, borders, shadows, density of decoration.
-- The voice tone you read off the copy itself, not off the aesthetic feel.
-
-Be specific. "Modern" is not a color, "elegant" is not a type pairing, "clean" is not a layout. If you can't extract a real value for an axis, skip it rather than fabricate. The point is to record what is, not to describe what you wish it were.
-
-Do not include adjectives that name an aesthetic family ("editorial-leaning", "terminal-flavored", "brutalist"); those are conclusions, not data. They belong to Phase C lane selection in departure mode, not to identity description. Letting them sneak into Phase A is how the identity-lock collapses into a self-fulfilling prophecy.
-
-This sentence is the **identity lock**. Every variant must be readable as the same brand if rendered side by side. Skipping this phase is the primary cause of off-brand variants. Absence of DESIGN.md is never an excuse; extract from CSS and computed styles instead.
-
-#### Phase B: Pick mode (default vs departure)
-
-**Default mode**: the existing identity is preserved. Variants vary expression axes within it. *This is the right mode for ~90% of live sessions.* The user picked an element on a real product they're shipping; they expect variants of *their* hero, not three different brands' heroes.
-
-**Departure mode**: the existing identity is rejected. Variants propose alternatives consistent with PRODUCT.md voice. Trigger only when at least one is true:
-
-- PRODUCT.md anti-references explicitly call out the current surface ("the current `index.html` is itself an example"; "diffuse away from this"; "the page on screen is the failure"). Generic anti-references that describe what to avoid in general do **not** trigger departure mode; only ones that point at *this* surface specifically.
-- The user's freeform prompt explicitly asks for departure ("rebuild this from scratch", "what if it weren't editorial at all", "show me something completely different").
-
-If you're unsure, you're in default mode. The cost of being wrong about default is "three on-brand variants with similar feel": recoverable, the user picks none. The cost of being wrong about departure is "three off-brand variants": unrecoverable, the user is annoyed.
-
-#### Phase C: Plan three variants
-
-**Default mode.** Each variant commits to a different **primary axis** of difference, while preserving the identity sentence. The six axes:
-
-1. **Hierarchy**: which element commands the eye?
-2. **Layout topology**: stacked / side-by-side / grid / asymmetric / overlay
-3. **Typographic system**: pairing logic, scale ratio, case/weight strategy *within the available faces*
-4. **Color strategy**: which existing palette role carries the surface (Restrained / Committed / Full palette / Drenched). Use the brand's existing palette tokens, not new colors.
-5. **Density**: minimal / comfortable / dense
-6. **Structural decomposition**: merge, split, progressive disclosure
-
-Three variants → three DIFFERENT axes. The trio reads as *the same brand at three angles*. Do not introduce new fonts, new palette hues, or new aesthetic-family signals; those belong to departure mode.
-
-**While planning each variant, also name its 2–3 parameter knobs** (per the §7 budget table). Parameters are part of the design, not a decoration added afterward. If the variant explores density, expose a density knob. If it explores color commitment, expose a color-amount range. Deciding "what's tunable" during planning produces better knobs than retrofitting them onto finished HTML.
-
-**Departure mode.** Each variant anchors to a different **aesthetic direction**, derived from the brand's stated voice and register in PRODUCT.md. Do NOT pick from a fixed catalog of lane categories. The right three directions for this brand are not the same as the right three for another brand, and picking from a list is itself the training-data reflex (the model selects "Swiss-grid, Terminal, Industrial-signage" every time because those are the furthest-from-editorial items in any enumerated list).
-
-Instead, work from the brand:
-
-1. Read PRODUCT.md's Brand Personality words. What physical, spatial, or material experiences would embody those words if design were not involved? (A personality described as "specific, earned, unmistakable" evokes a hand-stamped letter, a numbered print, a watchmaker's loupe. A personality described as "restless, loud, unfiltered" evokes a concert poster, a spray-painted wall, a megaphone.)
-2. From those physical experiences, derive three visual directions that are genuinely different from each other AND from the current surface you're departing.
-3. Avoid the **reflex-reject lanes** in [brand.md](brand.md). Don't trade one monoculture for another. If you find yourself reaching for "Swiss-grid" or "Terminal" or "Industrial-signage" by reflex, you are pattern-matching a catalog in your training data, not reading the brand. Start over from the personality words.
-4. Each direction must be expressible in one concrete sentence that names a real-world referent ("a museum exhibition label system for a contemporary art gallery" not "clean and minimal"). If your sentence contains only adjectives, it's not concrete enough.
-5. **While planning each direction, also name its 2–3 parameter knobs** (per the §7 budget table). The same principle as default mode: decide "what's tunable" during planning, not after writing the HTML. A departure-mode hero with 0 parameters is not "bold creative vision," it's a missed opportunity for the user to fine-tune the direction they pick.
-
-#### Phase D: Squint test
-
-**Default mode squint.** Read each variant's identity sentence and compare to the locked identity from Phase A. If any variant has drifted to a different palette, type voice, or visual rhetoric, it has crossed into departure mode by accident; rework. Then check that each variant commits to a different primary axis. Three "tighter density" variants is failure.
-
-**Departure mode squint.** Two passes, family before sentence:
-
-1. **Family pass.** Label each variant with one design-family word of your own choosing (any concrete noun: *exhibition, storefront, cockpit, recipe-card, playbill, field-manual*). If any two variants share a label, or if the label could apply to the other variants equally well, rework. Do not use a fixed vocabulary list for the labels. *This pass is non-negotiable in departure mode and catches the monoculture failure that the sentence pass misses.*
-2. **Sentence pass.** Write three one-sentence descriptions side by side. If two of them rhyme ("both feature big type" / "both are stacks of sections" / "both center the CTA"), rework the offender.
-
-**When the primary axis is color or theme, forbid the trio from sharing theme + dominant hue.** Two dark-plus-one-dark is not distinct. Aim for three color worlds, not three shades of the same.
-
-**For action-specific invocations**, each variant must vary along the dimension the action names:
-
-- `bolder`: amplify a different dimension per variant (scale / saturation / structural change). Not three "slightly bigger" variants.
-- `quieter`: pull back a different dimension (color / ornament / spacing).
-- `distill`: remove a different class of excess (visual noise / redundant content / nested structure).
-- `polish`: target a different refinement axis (rhythm / hierarchy / micro-details like corner radii, focus states, optical kerning).
-- `typeset`: different type pairing AND different scale ratio each. Not three riffs on one pairing.
-- `colorize`: different hue family each (not shades of one hue). Vary chroma and contrast strategy.
-- `layout`: different structural arrangement (stacked / side-by-side / grid / asymmetric). Not spacing tweaks.
-- `adapt`: different target context per variant (mobile-first / tablet / desktop / print or low-data). Don't make three mobile layouts.
-- `animate`: different motion vocabulary (cascade stagger / clip wipe / scale-and-focus / morph / parallax). Not three staggered fades.
-- `delight`: different flavor of personality (unexpected micro-interaction / typographic surprise / illustrated accent / sonic-or-haptic moment / easter-egg interaction).
-- `overdrive`: different convention broken (scale / structure / motion / input model / state transitions). Skip `overdrive.md`'s "propose and ask" step; live mode is non-interactive.
-
-### 5. Apply the freeform prompt (if present)
-
-`event.freeformPrompt` is the user's ceiling on direction (all variants must honor it), but still explore meaningfully different *interpretations*. The interpretations stay within whichever mode you picked in Phase B.
-
-In **default mode**, the prompt narrows the axes you choose, not the identity. *"Make it feel more confident"* → variant 1 amplifies hierarchy (one element commands the eye), variant 2 commits the existing accent color (Committed strategy on the brand's hue), variant 3 tightens density and removes decorative slack. Three different axes, same brand.
-
-In **departure mode**, the prompt narrows the lanes you draw from, not the families. *"Make it feel like a newspaper front page"* would itself be a departure-mode prompt; honor it but pick three meaningfully different newspaper-adjacent lanes (broadsheet vs. tabloid vs. trade journal), and run the family pass to confirm they don't collapse into one.
-
-When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.
-
-### 6. Write all variants in a single edit
-
-Complete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).
-
-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).
-
-Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:
-
-```html
-<!-- Variants: insert below this line -->
-<style data-impeccable-css="SESSION_ID">
- /* rules matching cssAuthoring.rulePattern */
-</style>
-<div data-impeccable-variant="1">
- <!-- variant 1: full element replacement (single top-level element) -->
-</div>
-<div data-impeccable-variant="2" style="display: none">
- <!-- variant 2: full element replacement -->
-</div>
-<div data-impeccable-variant="3" style="display: none">
- <!-- variant 3: full element replacement -->
-</div>
-```
-
-**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.
-
-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.
-
-One edit, all variants; the browser's MutationObserver picks everything up in one pass.
-
-For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.
-
-**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:
-
-```tsx
-<style data-impeccable-css="SESSION_ID">{`
- @scope ([data-impeccable-variant="1"]) { ... }
- @scope ([data-impeccable-variant="2"]) { ... }
-`}</style>
-<div data-impeccable-variant="1">
- {/* variant 1 */}
-</div>
-<div data-impeccable-variant="2" style={{ display: 'none' }}>
- {/* variant 2 */}
-</div>
-```
-
-The wrap script already gives you a single-rooted JSX wrapper: a `<div data-impeccable-variants="…">` outer element with the marker comments tucked inside. Drop the variants block above into the "Variants: insert below this line" comment and the source stays valid TSX.
-
-### 7. Parameters (composition-sized, 0–4 per variant)
-
-Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement. The browser docks a small panel to the right of the outline with one control per parameter. The user drags/clicks and sees instant feedback: there is zero regeneration cost because the knob toggles a CSS variable or data attribute that the variant's scoped CSS is already authored against.
-
-**What “optional” does not mean.** Parameters are not nice-to-have decoration on large work. The word meant “omit controls that are redundant or cosmetic,” not “default to zero because three variants were enough work.”
-
-**When to add.** As soon as the variant’s scoped CSS has a meaningful continuous or stepped axis: density, color amount, type scale, motion intensity, column weight, and so on. If you can imagine the user muttering “a bit tighter” or “a touch more accent” **without** wanting a full regeneration, wire that axis. **Not** micro-margins or one-off nudges; those are not parameters.
-
-**Freeform (`action` is `impeccable`) bias.** You did not load a sub-command reference, so you must **choose** signature axes yourself. Match the budget table: for a hero or large composition, that means **2–3 axes per variant**, not 1. Prefer knobs that sit on the dimensions where your three variants actually differ (if density varies, expose it as a `steps` knob; if color commitment varies, expose it as a `range`). A hero that ships with **0** params is almost always a mistake, not a judgment call. A hero with exactly **1** param is underweight unless the design is genuinely a fixed-point comparison. Start from the budget table, not from zero.
-
-**Budget scales with the element's visual weight, not token budget.** Knobs need real estate to read as tunable; three sliders on a single control are noise.
-
-- **Leaf / tiny**: a single button, icon, input, bare heading, solitary paragraph: **0 params.**
-- **Small composition**: labeled input, simple card, short callout (≤ ~5 visual children): **0–1** params when one dominant axis is obvious; otherwise **0.**
-- **Medium composition**: section component, nav cluster, dense card, short feature block (6–15 visual children): **target 2**; **1** is acceptable if the block is simple; **0** only when variants are truly fixed points.
-- **Large composition**: hero section, full page region, spread layout, strong internal structure (16+ visual children or multiple sub-sections): **target 2–3**; **up to 4** when several independent axes (e.g. structure `steps` + `density` + one accent) are all authored in scoped CSS.
-
-**When in doubt, ask whether a dial exists before defaulting to zero.** The user can always request more variants, but the point of live mode is instant tuning without another Go. Crowding the panel is bad; **under-shipping** knobs on a dense composition is the more common failure for freeform. Count by **visual** children, not DOM depth; a shallow-but-wide hero is still large.
-
-**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.
-
-**How to declare.** Put a JSON manifest on the variant wrapper:
-
-```html
-<div data-impeccable-variant="1" data-impeccable-params='[
- {"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"},
- {"id":"density","kind":"steps","default":"snug","label":"Density","options":[
- {"value":"airy","label":"Airy"},
- {"value":"snug","label":"Snug"},
- {"value":"packed","label":"Packed"}
- ]},
- {"id":"serif","kind":"toggle","default":false,"label":"Serif display"}
-]'>
- ...variant content...
-</div>
-```
-
-**Three kinds:**
-
-- `range`: smooth slider. Drives a CSS custom property `--p-<id>` on the variant wrapper. Author CSS with `var(--p-color-amount, 0.5)`. Fields: `min`, `max`, `step`, `default` (number), `label`.
-- `steps`: segmented radio. Drives a data attribute `data-p-<id>` on the variant wrapper. Author CSS with `:scope[data-p-density="airy"] .grid { ... }`. Fields: `options` (array of `{value, label}`), `default` (string), `label`.
-- `toggle`: on/off switch. Drives BOTH a CSS var (`--p-<id>: 0|1`) and a data attribute (present when on, absent when off). Use whichever is more convenient. Fields: `default` (boolean), `label`.
-
-**Signature params per action.** For named sub-commands, read that action’s `reference/<action>.md` for one or two **MUST** params (e.g. `layout` → `density`). Those are non-negotiable when the design can express them. **Freeform has no file-level MUST**; the **Freeform (`impeccable`) bias** in this section is the stand-in. If the user’s action is both stylized and sub-command (e.g. `colorize`), the sub-command’s MUST list takes precedence for its axes; still respect the **Hard cap** and add no redundant duplicate knobs.
-
-**Reset on variant switch.** User dials density on v1, flips to v2, v2 starts at v2's declared defaults. Known limitation; preservation across variants may land later.
-
-**On accept**, the browser sends the user's current values in the accept event. `live-accept.mjs` writes them as a sibling comment:
-
-```html
-<!-- impeccable-param-values SESSION_ID: {"color-amount":0.7,"density":"packed"} -->
-```
-
-The carbonize cleanup step (see below) reads that comment and bakes the chosen values into the final CSS. For `steps`/`toggle` attribute selectors: keep only the branch matching the chosen value, drop the others, collapse `:scope[data-p-density="packed"] .grid` to a semantic class rule. For `range` vars: either substitute the literal or keep the var with the chosen value as its new default.
-
-### 8. Signal done
-
-```bash
-node .trae-cn/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
-```
-
-`RELATIVE_PATH` is relative to project root (`public/index.html`, `src/App.tsx`, etc.); the browser fetches source directly if the dev server lacks HMR.
-
-Then run `live-poll.mjs` again immediately.
-
-### Aborting an in-flight session
-
-If wrap or generation fails after the browser has flipped to GENERATING (e.g. wrap landed on the wrong source branch and you've already reverted it, or generation hit an unrecoverable error), tell the **browser** so its bar resets to PICKING:
-
-```bash
-node .trae-cn/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID error "Short reason"
-```
-
-Don't run `live-accept --discard` for this; that's a pure file mutator, the browser doesn't see it, and the bar gets stuck on the GENERATING dots forever (the user has to refresh). `--discard` is only correct when the **browser** initiated the discard (user clicked ✕ during CYCLING) and the agent is just running source-side cleanup the browser already triggered.
-
-## Handle fallback
-
-When wrap returns `fallback: "agent-driven"`, the deterministic flow doesn't apply. Pick up here.
-
-The goal is the same: give the user three variants to choose from AND persist the accepted one in a place the next build won't wipe. The difference is that you have to pick the right source file yourself.
-
-### Step 1: Identify where the element actually lives
-
-Use the error payload:
-
-- `element_not_in_source` with `generatedMatch: "public/docs/foo.html"`: the served HTML is generated. Find the generator (grep for writers of that path, e.g. `scripts/build-sub-pages.js`, an Astro/Next template) and locate the template or partial that emits this element.
-- `element_not_found`: the element is runtime-injected. Look for the component that renders it (React/Vue/Svelte), the JS that assembles it, or the data source that feeds it.
-- `file_is_generated` with `file: "..."`: user pointed at a generated file explicitly. Same resolution as `element_not_in_source`.
-
-Read the candidate source until you're confident where a change to the element would belong. If the change is purely visual, that source might be a shared stylesheet, not the template.
-
-### Step 2: Show three variants in the DOM for preview
-
-The browser bar is waiting for variants. Even without a wrapper in source, you still need to show something:
-
-1. Manually write the wrapper scaffold into the **served** file (the one the browser actually loaded). Use the same structure `live-wrap.mjs` produces; `<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents">…</div><!-- end -->`.
-2. Insert your three variant divs inside it, same shape as the deterministic path.
-3. Signal done with `--reply EVENT_ID done --file <served file>`. The browser's no-HMR fallback will fetch and inject.
-
-This served-file edit is **temporary**: next regen wipes it, and that's fine. The real work happens on accept.
-
-### Step 3: On accept, write to true source
-
-When the accept event arrives (`_acceptResult.handled` will usually be `false` here because accept also refuses to persist into generated files; see Handle accept for the carbonize branch), extract the accepted variant's content and write it into the source you identified in Step 1:
-
-- Structural change → edit the template / component source.
-- Visual-only change → add or update rules in the appropriate stylesheet; remove the inline `<style>` scope.
-- Dynamic from data → update the data source or the render logic.
-
-Then remove the temporary wrapper from the served file if it's still there.
-
-### Step 4: On discard, clean up the served file
-
-Remove the wrapper you inserted in Step 2. Nothing else to do.
-
-## Handle `accept`
-
-Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.
-
-- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.
-- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.
-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.
-- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.
-- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.
-
-### Required after accept (carbonize)
-
-When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.
-
-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.
-
-1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.
-2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).
-3. **Bake in parameter values while rewriting selectors.** For `@scope ([data-impeccable-variant="N"])` wrappers: retarget to real, semantic classes on the accepted HTML (`.why-visual--v2 .v2-label { … }`). For `:scope[data-p-<id>="VALUE"]` selectors: keep only the branch matching the chosen value from the param-values comment; drop the others (they're dead after accept). For `var(--p-<id>, DEFAULT)` in the CSS: either substitute the literal value, or if the param is still useful as a knob going forward, leave the var and update its initial declaration to the chosen value.
-4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; those are live-mode plumbing, not source.
-5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.
-
-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.
-
-A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.
-
-## Handle `discard`
-
-Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.
-
-## Handle `prefetch`
-
-Event: `{pageUrl}`. The browser fires this the first time the user selects an element on a given route, as a latency shortcut; it signals the user is likely about to Go on a page you haven't read yet.
-
-Resolve `pageUrl` to the underlying file:
-
-- Root `/` → the `pageFile` returned by `live.mjs` (usually `public/index.html` or equivalent).
-- Sub-routes (e.g. `/docs`, `/docs/live`) → the generated or source file for that route. Use your knowledge of the project layout (multi-page static sites often resolve `/foo` → `public/foo/index.html`; SPAs may map all routes to a single entry).
-
-Read the file into context, then poll again. No `--reply`: this is speculative pre-work; Go will come later. If you can't confidently resolve the route to a file, skip and poll again.
-
-Dedupe is the browser's job (one prefetch per unique pathname per session); trust it. If the same file shows up twice from different routes mapping to the same file, the second Read is cached anyway.
-
-## Exit
-
-The user can stop live mode by:
-- Saying "stop live mode" / "exit live" in chat
-- Closing the browser tab (SSE drops, poll returns `exit` after 8s)
-- The browser's exit button
-
-When the poll returns `exit`, proceed to cleanup. If the poll is still running as a background task, kill it first.
-
-## Cleanup
-
-```bash
-node .trae-cn/skills/impeccable/scripts/live-server.mjs stop
-```
-
-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.
-
-Then:
-- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).
-- Remove any leftover carbonize blocks (search for `impeccable-carbonize-start` markers).
-
-## First-time setup (config missing or invalid)
-
-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.
-
-Schema:
-
-```json
-{
- "files": ["<path-or-glob>", "<path-or-glob>", ...],
- "exclude": ["<optional-glob>", ...],
- "insertBefore": "</body>",
- "commentSyntax": "html",
- "cspChecked": true
-}
-```
-
-`files` is the inject target; **the HTML files the browser actually loads**, not necessarily source. Each entry is either a literal path (`"public/index.html"`) or a glob pattern (`"public/**/*.html"`). Tracked or generated doesn't matter here; wrap has its own generated-file guard and routes accepts through the fallback flow.
-
-`exclude` (optional) is a list of glob patterns matching files to skip, even if a `files` glob would have included them. Use for email templates, demo fixtures, or any HTML that isn't a live page.
-
-`cspChecked` tracks whether the CSP detection step below has already run. Absent on first setup; set to `true` after CSP is checked (whether patched, declined, or not needed).
-
-**Hard-excluded paths (cannot be overridden).** `**/node_modules/**` and `**/.git/**` are never matched regardless of what the user writes. These are vendor/metadata directories and injecting into them would silently instrument third-party code.
-
-**Glob syntax.** `**` matches any number of path segments (including zero), `*` matches any characters except `/`, `?` matches a single character except `/`. Paths are always relative to the project root with forward slashes.
-
-| Framework | `files` | `insertBefore` | `commentSyntax` |
-|-----------|---------|----------------|-----------------|
-| SPA with single shell (Vite / React / Plain HTML) | `["index.html"]` | `</body>` | `html` |
-| Next.js (App Router) | `["app/layout.tsx"]` | `</body>` | `jsx` |
-| Next.js (Pages) | `["pages/_document.tsx"]` | `</body>` | `jsx` |
-| Nuxt | `["app.vue"]` | `</body>` | `html` |
-| Svelte / SvelteKit | `["src/app.html"]` | `</body>` | `html` |
-| Astro | `[" <root layout .astro>"]` | `</body>` | `html` |
-| Multi-page (separate HTML per route) | `["public/**/*.html"]`: a glob covering the served directory | `</body>` | `html` |
-
-Pick an anchor that exists in every file (`</body>` almost always works). Use `insertAfter` if the anchor should match **after** a specific line.
-
-For multi-page sites, **prefer a glob over a literal file list**. New pages added later are picked up automatically on the next `live-inject.mjs` run; no config maintenance needed.
-
-For multi-page sites whose pages are *rebuilt* by a generator (Astro, static-site generators, custom scripts like `build-sub-pages.js`), the inject survives only until the next regeneration. Re-run `live.mjs` after each build. Accept is unaffected; it writes to true source via the fallback flow.
-
-### Drift-heal warning
-
-On every `live.mjs` boot, after inject, the project is scanned for HTML files under common page-source roots (`public/`, `src/`, `app/`, `pages/`). If any exist that aren't covered by the resolved `files` list, the output includes a `configDrift` field:
-
-```json
-{
- "ok": true,
- "serverPort": 8400,
- "pageFiles": [ "..." ],
- "configDrift": {
- "orphans": ["public/new-section/index.html", "public/docs/new-command.html"],
- "orphanCount": 2,
- "hint": "2 HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like \"public/**/*.html\"."
- }
-}
-```
-
-When `configDrift` is present, surface it to the user once per session before entering the poll loop:
-
-> Noticed N HTML file(s) in the project that aren't in `config.files`:
->
-> - `public/new-section/index.html`
-> - `public/docs/new-command.html`
->
-> Add them, or switch `files` to a glob like `["public/**/*.html"]` and let it track new pages automatically?
-
-Don't auto-update the config; let the user decide. `configDrift` is `null` when there's no drift.
-
-### CSP detection (first-time only)
-
-If `config.cspChecked === true`, skip this entire section. You already asked this user once; the answer sticks.
-
-Otherwise, run the detection helper:
-
-```bash
-node .trae-cn/skills/impeccable/scripts/detect-csp.mjs
-```
-
-Output: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.
-
-- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.
-- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:
- - Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)
- - SvelteKit `kit.csp.directives`
- - Nuxt `nuxt-security` module's `contentSecurityPolicy`
-- **`append-string`**: CSP written as a literal value string. Auto-patchable. See *append-string* below. Covers:
- - Inline `next.config.*` `headers()` with a CSP literal
- - Nuxt `routeRules` / `nitro.routeRules` headers
-- **`middleware`** or **`meta-tag`**: rarer. Detected but not auto-patched in v1. Show the user the detected files and ask them to add `http://localhost:8400` to `script-src` and `connect-src` manually, then mark `cspChecked: true` and proceed.
-
-#### Consent prompt template
-
-Use this phrasing so the experience is consistent across agents:
-
-> **CSP patch needed.** I detected a Content Security Policy in your project that blocks `http://localhost:8400`: the live picker won't load without an allowance. Here's the change I'd make:
->
-> ```diff
-> [file: <patchTarget>]
-> [exact diff, 2–5 lines]
-> ```
->
-> It's guarded by `NODE_ENV === "development"` so the extra entry only appears in dev and never reaches production. You can remove it any time by reverting this file. Apply? [y/n]
-
-On "no": skip the patch, mention live won't work until the user adds the allowance manually, still write `cspChecked: true` (the question's been asked).
-
-On "yes": apply the Shape-specific patch below, then write `cspChecked: true`.
-
-#### append-arrays
-
-CSP expressed as structured directive arrays. Patch mechanism: declare a dev-only array, spread it into the script-src and connect-src arrays.
-
-**Declare near the top of the file that holds the CSP arrays:**
-
-```ts
-// Dev-only allowance so impeccable live mode can load. Guarded by NODE_ENV.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? ["http://localhost:8400"] : [];
-```
-
-**Append `...__impeccableLiveDev` to the script-src and connect-src directive arrays.** Per-framework specifics:
-
-- **Next.js + monorepo helper**: edit the *app's* `next.config.*` (not the shared helper), appending to `additionalScriptSrc` and `additionalConnectSrc` passed into `createBaseNextConfig` (or equivalent). Keeps the shared package clean.
-- **SvelteKit**: edit `svelte.config.js`, appending to `kit.csp.directives['script-src']` and `kit.csp.directives['connect-src']`.
-- **Nuxt + nuxt-security**: edit `nuxt.config.*`, appending to `security.headers.contentSecurityPolicy['script-src']` and `['connect-src']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-turborepo/expected-after-patch.ts` (Next.js)
-- `tests/framework-fixtures/sveltekit-csp/expected-after-patch.js` (SvelteKit)
-
-Idempotency: if `__impeccableLiveDev` already exists in the file, the patch is already applied; skip asking and just mark `cspChecked: true`.
-
-#### append-string
-
-CSP built as a literal value string. Two-point patch: declare a dev-only string near the top, interpolate it into the CSP at the `script-src` and `connect-src` directives.
-
-```ts
-// Dev-only allowance so impeccable live mode can load.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? " http://localhost:8400" : "";
-```
-
-Then in the CSP value string:
-- `script-src 'self' 'unsafe-inline'` → `` `script-src 'self' 'unsafe-inline'${__impeccableLiveDev}` ``
-- `connect-src 'self'` → `` `connect-src 'self'${__impeccableLiveDev}` ``
-
-(Leading space on the dev string so it concatenates cleanly into the existing value. Convert the literal CSP directives into template strings as part of the edit if they aren't already.)
-
-Per-framework specifics:
-- **Next.js inline `headers()`**: edit `next.config.*`, splicing the variable into the CSP value.
-- **Nuxt `routeRules`**: edit `nuxt.config.*`, splicing into the CSP in `routeRules['/**'].headers['Content-Security-Policy']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-inline-csp/expected-after-patch.js` (Next.js)
-- `tests/framework-fixtures/nuxt-csp/expected-after-patch.ts` (Nuxt)
-
-### Troubleshooting
-
-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.
-
-Then re-run `live.mjs`.
@@ -1,109 +0,0 @@
-# Motion Design
-
-## Duration: The 100/300/500 Rule
-
-Timing matters more than easing. These durations feel right for most UI:
-
-| Duration | Use Case | Examples |
-|----------|----------|----------|
-| **100-150ms** | Instant feedback | Button press, toggle, color change |
-| **200-300ms** | State changes | Menu open, tooltip, hover states |
-| **300-500ms** | Layout changes | Accordion, modal, drawer |
-| **500-800ms** | Entrance animations | Page load, hero reveals |
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-## Easing: Pick the Right Curve
-
-**Don't use `ease`.** It's a compromise that's rarely optimal. Instead:
-
-| Curve | Use For | CSS |
-|-------|---------|-----|
-| **ease-out** | Elements entering | `cubic-bezier(0.16, 1, 0.3, 1)` |
-| **ease-in** | Elements leaving | `cubic-bezier(0.7, 0, 0.84, 0)` |
-| **ease-in-out** | State toggles (there → back) | `cubic-bezier(0.65, 0, 0.35, 1)` |
-
-**For micro-interactions, use exponential curves.** They feel natural because they mimic real physics (friction, deceleration):
-
-```css
-/* Quart out - smooth, refined (recommended default) */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1);
-
-/* Quint out - slightly more dramatic */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1);
-
-/* Expo out - snappy, confident */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1);
-```
-
-**Avoid bounce and elastic curves.** They were trendy in 2015 but now feel tacky and amateurish. Real objects don't bounce when they stop; they decelerate smoothly. Overshoot effects draw attention to the animation itself rather than the content.
-
-## Premium Motion Materials
-
-Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties: blur reveals, backdrop-filter panels, saturation or brightness shifts, shadow bloom, SVG filters, masks, clip paths, gradient-position movement, and variable font or shader-driven effects.
-
-Use the right material for the effect:
-
-- **Transform / opacity**: movement, press feedback, simple reveals, list choreography.
-- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances, atmospheric transitions.
-- **Clip path / masks**: wipes, reveals, editorial cropping, product-like transitions.
-- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state.
-- **Grid-template rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly.
-
-The hard rule is not "transform and opacity only." The hard rule is: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify in-browser that the result is smooth on the target viewports. If blur/filter makes the interaction feel significantly more premium and remains smooth, use it.
-
-## Staggered Animations
-
-Use CSS custom properties for cleaner stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"` on each item. **Cap total stagger time**: 10 items at 50ms = 500ms total. For many items, reduce per-item delay or cap staggered count.
-
-## Reduced Motion
-
-This is not optional. Vestibular disorders affect ~35% of adults over 40.
-
-```css
-/* Define animations normally */
-.card {
- animation: slide-up 500ms ease-out;
-}
-
-/* Provide alternative for reduced motion */
-@media (prefers-reduced-motion: reduce) {
- .card {
- animation: fade-in 200ms ease-out; /* Crossfade instead of motion */
- }
-}
-
-/* Or disable entirely */
-@media (prefers-reduced-motion: reduce) {
- *, *::before, *::after {
- animation-duration: 0.01ms !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**What to preserve**: Functional animations like progress bars, loading spinners (slowed down), and focus indicators should still work, just without spatial movement.
-
-## Perceived Performance
-
-**Nobody cares how fast your site is, just how fast it feels.** Perception can be as effective as actual performance.
-
-**The 80ms threshold**: Our brains buffer sensory input for ~80ms to synchronize perception. Anything under 80ms feels instant and simultaneous. This is your target for micro-interactions.
-
-**Active vs passive time**: Passive waiting (staring at a spinner) feels longer than active engagement. Strategies to shift the balance:
-
-- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening.
-- **Early completion**: Show content progressively, don't wait for everything. Video buffering, progressive images, streaming HTML.
-- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Instagram likes work offline; the UI updates instantly, syncs later. Use for low-stakes actions; avoid for payments or destructive operations.
-
-**Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances, but ease-in toward a task's end compresses perceived time.
-
-**Caution**: Too-fast responses can decrease perceived value. Users may distrust instant results for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
-
-## Performance
-
-Don't use `will-change` preemptively, only when animation is imminent (`:hover`, `.animating`). For scroll-triggered animations, use Intersection Observer instead of scroll events; unobserve after animating once. Create motion tokens for consistency (durations, easings, common transitions).
-
----
-
-**Avoid**: Animating everything (animation fatigue is real). Using >500ms for UI feedback. Ignoring `prefers-reduced-motion`. Using animation to hide slow loading.
@@ -1,234 +0,0 @@
-> **Additional context needed**: the "aha moment" you want users to reach, and users' experience level.
-
-Get users to first value as fast as possible. Onboarding's job is not to teach the product. Its job is to get people to the moment that proves the product is worth their time.
-
-## Assess Onboarding Needs
-
-Understand what users need to learn and why:
-
-1. **Identify the challenge**:
- - What are users trying to accomplish?
- - What's confusing or unclear about current experience?
- - Where do users get stuck or drop off?
- - What's the "aha moment" we want users to reach?
-
-2. **Understand the users**:
- - What's their experience level? (Beginners, power users, mixed?)
- - What's their motivation? (Excited and exploring? Required by work?)
- - What's their time commitment? (5 minutes? 30 minutes?)
- - What alternatives do they know? (Coming from competitor? New to category?)
-
-3. **Define success**:
- - What's the minimum users need to learn to be successful?
- - What's the key action we want them to take? (First project? First invite?)
- - How do we know onboarding worked? (Completion rate? Time to value?)
-
-**CRITICAL**: Onboarding should get users to value as quickly as possible, not teach everything possible.
-
-## Onboarding Principles
-
-Follow these core principles:
-
-### Show, Don't Tell
-- Demonstrate with working examples, not just descriptions
-- Provide real functionality in onboarding, not separate tutorial mode
-- Use progressive disclosure, teach one thing at a time
-
-### Make It Optional (When Possible)
-- Let experienced users skip onboarding
-- Don't block access to product
-- Provide "Skip" or "I'll explore on my own" options
-
-### Time to Value
-- Get users to their "aha moment" ASAP
-- Front-load most important concepts
-- Teach 20% that delivers 80% of value
-- Save advanced features for contextual discovery
-
-### Context Over Ceremony
-- Teach features when users need them, not upfront
-- Empty states are onboarding opportunities
-- Tooltips and hints at point of use
-
-### Respect User Intelligence
-- Don't patronize or over-explain
-- Be concise and clear
-- Assume users can figure out standard patterns
-
-## Design Onboarding Experiences
-
-Create appropriate onboarding for the context:
-
-### Initial Product Onboarding
-
-**Welcome Screen**:
-- Clear value proposition (what is this product?)
-- What users will learn/accomplish
-- Time estimate (honest about commitment)
-- Option to skip (for experienced users)
-
-**Account Setup**:
-- Minimal required information (collect more later)
-- Explain why you're asking for each piece of information
-- Smart defaults where possible
-- Social login when appropriate
-
-**Core Concept Introduction**:
-- Introduce 1-3 core concepts (not everything)
-- Use simple language and examples
-- Interactive when possible (do, don't just read)
-- Progress indication (step 1 of 3)
-
-**First Success**:
-- Guide users to accomplish something real
-- Pre-populated examples or templates
-- Celebrate completion (but don't overdo it)
-- Clear next steps
-
-### Feature Discovery & Adoption
-
-**Empty States**:
-Instead of blank space, show:
-- What will appear here (description + screenshot/illustration)
-- Why it's valuable
-- Clear CTA to create first item
-- Example or template option
-
-Example:
-```
-No projects yet
-Projects help you organize your work and collaborate with your team.
-[Create your first project] or [Start from template]
-```
-
-**Contextual Tooltips**:
-- Appear at relevant moment (first time user sees feature)
-- Point directly at relevant UI element
-- Brief explanation + benefit
-- Dismissable (with "Don't show again" option)
-- Optional "Learn more" link
-
-**Feature Announcements**:
-- Highlight new features when they're released
-- Show what's new and why it matters
-- Let users try immediately
-- Dismissable
-
-**Progressive Onboarding**:
-- Teach features when users encounter them
-- Badges or indicators on new/unused features
-- Unlock complexity gradually (don't show all options immediately)
-
-### Guided Tours & Walkthroughs
-
-**When to use**:
-- Complex interfaces with many features
-- Significant changes to existing product
-- Industry-specific tools needing domain knowledge
-
-**How to design**:
-- Spotlight specific UI elements (dim rest of page)
-- Keep steps short (3-7 steps max per tour)
-- Allow users to click through tour freely
-- Include "Skip tour" option
-- Make replayable (help menu)
-
-**Best practices**:
-- Interactive over passive (let users click real buttons)
-- Focus on workflow, not features ("Create a project" not "This is the project button")
-- Provide sample data so actions work
-
-### Interactive Tutorials
-
-**When to use**:
-- Users need hands-on practice
-- Concepts are complex or unfamiliar
-- High stakes (better to practice in safe environment)
-
-**How to design**:
-- Sandbox environment with sample data
-- Clear objectives ("Create a chart showing sales by region")
-- Step-by-step guidance
-- Validation (confirm they did it right)
-- Graduation moment (you're ready!)
-
-### Documentation & Help
-
-**In-product help**:
-- Contextual help links throughout interface
-- Keyboard shortcut reference
-- Search-able help center
-- Video tutorials for complex workflows
-
-**Help patterns**:
-- `?` icon near complex features
-- "Learn more" links in tooltips
-- Keyboard shortcut hints (`⌘K` shown on search box)
-
-## Empty State Design
-
-Every empty state needs:
-
-### What Will Be Here
-"Your recent projects will appear here"
-
-### Why It Matters
-"Projects help you organize your work and collaborate with your team"
-
-### How to Get Started
-[Create project] or [Import from template]
-
-### Visual Interest
-Illustration or icon (not just text on blank page)
-
-### Contextual Help
-"Need help getting started? [Watch 2-min tutorial]"
-
-**Empty state types**:
-- **First use**: Never used this feature (emphasize value, provide template)
-- **User cleared**: Intentionally deleted everything (light touch, easy to recreate)
-- **No results**: Search or filter returned nothing (suggest different query, clear filters)
-- **No permissions**: Can't access (explain why, how to get access)
-- **Error state**: Failed to load (explain what happened, retry option)
-
-## Implementation Patterns
-
-### Technical approaches:
-
-**Tooltip libraries**: Tippy.js, Popper.js
-**Tour libraries**: Intro.js, Shepherd.js, React Joyride
-**Modal patterns**: Focus trap, backdrop, ESC to close
-**Progress tracking**: LocalStorage for "seen" states
-**Analytics**: Track completion, drop-off points
-
-**Storage patterns**:
-```javascript
-// Track which onboarding steps user has seen
-localStorage.setItem('onboarding-completed', 'true');
-localStorage.setItem('feature-tooltip-seen-reports', 'true');
-```
-
-**IMPORTANT**: Don't show same onboarding twice (annoying). Track completion and respect dismissals.
-
-**NEVER**:
-- Force users through long onboarding before they can use product
-- Patronize users with obvious explanations
-- Show same tooltip repeatedly (respect dismissals)
-- Block all UI during tour (let users explore)
-- Create separate tutorial mode disconnected from real product
-- Overwhelm with information upfront (progressive disclosure!)
-- Hide "Skip" or make it hard to find
-- Forget about returning users (don't show initial onboarding again)
-
-## Verify Onboarding Quality
-
-Test with real users:
-
-- **Time to completion**: Can users complete onboarding quickly?
-- **Comprehension**: Do users understand after completing?
-- **Action**: Do users take desired next step?
-- **Skip rate**: Are too many users skipping? (Maybe it's too long or not valuable)
-- **Completion rate**: Are users completing? (If low, simplify)
-- **Time to value**: How long until users get first value?
-
-When users hit the aha moment fast and don't drop off, hand off to `/impeccable polish` for the final pass.
@@ -1,258 +0,0 @@
-Performance is a feature. Identify the actual bottleneck for THIS interface, fix it, then measure. Don't optimize what isn't slow.
-
-## Assess Performance Issues
-
-Understand current performance and identify problems:
-
-1. **Measure current state**:
- - **Core Web Vitals**: LCP, FID/INP, CLS scores
- - **Load time**: Time to interactive, first contentful paint
- - **Bundle size**: JavaScript, CSS, image sizes
- - **Runtime performance**: Frame rate, memory usage, CPU usage
- - **Network**: Request count, payload sizes, waterfall
-
-2. **Identify bottlenecks**:
- - What's slow? (Initial load? Interactions? Animations?)
- - What's causing it? (Large images? Expensive JavaScript? Layout thrashing?)
- - How bad is it? (Perceivable? Annoying? Blocking?)
- - Who's affected? (All users? Mobile only? Slow connections?)
-
-**CRITICAL**: Measure before and after. Premature optimization wastes time. Optimize what actually matters.
-
-## Optimization Strategy
-
-Create systematic improvement plan:
-
-### Loading Performance
-
-**Optimize Images**:
-- Use modern formats (WebP, AVIF)
-- Proper sizing (don't load 3000px image for 300px display)
-- Lazy loading for below-fold images
-- Responsive images (`srcset`, `picture` element)
-- Compress images (80-85% quality is usually imperceptible)
-- Use CDN for faster delivery
-
-```html
-<img
- src="hero.webp"
- srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
- sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
- loading="lazy"
- alt="Hero image"
-/>
-```
-
-**Reduce JavaScript Bundle**:
-- Code splitting (route-based, component-based)
-- Tree shaking (remove unused code)
-- Remove unused dependencies
-- Lazy load non-critical code
-- Use dynamic imports for large components
-
-```javascript
-// Lazy load heavy component
-const HeavyChart = lazy(() => import('./HeavyChart'));
-```
-
-**Optimize CSS**:
-- Remove unused CSS
-- Critical CSS inline, rest async
-- Minimize CSS files
-- Use CSS containment for independent regions
-
-**Optimize Fonts**:
-- Use `font-display: swap` or `optional`
-- Subset fonts (only characters you need)
-- Preload critical fonts
-- Use system fonts when appropriate
-- Limit font weights loaded
-
-```css
-@font-face {
- font-family: 'CustomFont';
- src: url('/fonts/custom.woff2') format('woff2');
- font-display: swap; /* Show fallback immediately */
- unicode-range: U+0020-007F; /* Basic Latin only */
-}
-```
-
-**Optimize Loading Strategy**:
-- Critical resources first (async/defer non-critical)
-- Preload critical assets
-- Prefetch likely next pages
-- Service worker for offline/caching
-- HTTP/2 or HTTP/3 for multiplexing
-
-### Rendering Performance
-
-**Avoid Layout Thrashing**:
-```javascript
-// ❌ Bad: Alternating reads and writes (causes reflows)
-elements.forEach(el => {
- const height = el.offsetHeight; // Read (forces layout)
- el.style.height = height * 2; // Write
-});
-
-// ✅ Good: Batch reads, then batch writes
-const heights = elements.map(el => el.offsetHeight); // All reads
-elements.forEach((el, i) => {
- el.style.height = heights[i] * 2; // All writes
-});
-```
-
-**Optimize Rendering**:
-- Use CSS `contain` property for independent regions
-- Minimize DOM depth (flatter is faster)
-- Reduce DOM size (fewer elements)
-- Use `content-visibility: auto` for long lists
-- Virtual scrolling for very long lists (react-window, react-virtualized)
-
-**Reduce Paint & Composite**:
-- Use `transform` and `opacity` for reliable movement, but allow blur, filters, masks, clip paths, shadows, and color shifts when they create meaningful polish
-- Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- Use `will-change` sparingly for known expensive operations
-- Bound expensive paint areas for blur/filter/shadow effects (smaller and isolated is faster)
-
-### Animation Performance
-
-**GPU Acceleration**:
-```css
-/* ✅ GPU-accelerated (fast) */
-.animated {
- transform: translateX(100px);
- opacity: 0.5;
-}
-
-/* ❌ CPU-bound (slow) */
-.animated {
- left: 100px;
- width: 300px;
-}
-```
-
-**Smooth 60fps**:
-- Target 16ms per frame (60fps)
-- Use `requestAnimationFrame` for JS animations
-- Debounce/throttle scroll handlers
-- Use CSS animations when possible
-- Avoid long-running JavaScript during animations
-
-**Intersection Observer**:
-```javascript
-// Efficiently detect when elements enter viewport
-const observer = new IntersectionObserver((entries) => {
- entries.forEach(entry => {
- if (entry.isIntersecting) {
- // Element is visible, lazy load or animate
- }
- });
-});
-```
-
-### React/Framework Optimization
-
-**React-specific**:
-- Use `memo()` for expensive components
-- `useMemo()` and `useCallback()` for expensive computations
-- Virtualize long lists
-- Code split routes
-- Avoid inline function creation in render
-- Use React DevTools Profiler
-
-**Framework-agnostic**:
-- Minimize re-renders
-- Debounce expensive operations
-- Memoize computed values
-- Lazy load routes and components
-
-### Network Optimization
-
-**Reduce Requests**:
-- Combine small files
-- Use SVG sprites for icons
-- Inline small critical assets
-- Remove unused third-party scripts
-
-**Optimize APIs**:
-- Use pagination (don't load everything)
-- GraphQL to request only needed fields
-- Response compression (gzip, brotli)
-- HTTP caching headers
-- CDN for static assets
-
-**Optimize for Slow Connections**:
-- Adaptive loading based on connection (navigator.connection)
-- Optimistic UI updates
-- Request prioritization
-- Progressive enhancement
-
-## Core Web Vitals Optimization
-
-### Largest Contentful Paint (LCP < 2.5s)
-- Optimize hero images
-- Inline critical CSS
-- Preload key resources
-- Use CDN
-- Server-side rendering
-
-### First Input Delay (FID < 100ms) / INP (< 200ms)
-- Break up long tasks
-- Defer non-critical JavaScript
-- Use web workers for heavy computation
-- Reduce JavaScript execution time
-
-### Cumulative Layout Shift (CLS < 0.1)
-- Set dimensions on images and videos
-- Don't inject content above existing content
-- Use `aspect-ratio` CSS property
-- Reserve space for ads/embeds
-- Avoid animations that cause layout shifts
-
-```css
-/* Reserve space for image */
-.image-container {
- aspect-ratio: 16 / 9;
-}
-```
-
-## Performance Monitoring
-
-**Tools to use**:
-- Chrome DevTools (Lighthouse, Performance panel)
-- WebPageTest
-- Core Web Vitals (Chrome UX Report)
-- Bundle analyzers (webpack-bundle-analyzer)
-- Performance monitoring (Sentry, DataDog, New Relic)
-
-**Key metrics**:
-- LCP, FID/INP, CLS (Core Web Vitals)
-- Time to Interactive (TTI)
-- First Contentful Paint (FCP)
-- Total Blocking Time (TBT)
-- Bundle size
-- Request count
-
-**IMPORTANT**: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.
-
-**NEVER**:
-- Optimize without measuring (premature optimization)
-- Sacrifice accessibility for performance
-- Break functionality while optimizing
-- Use `will-change` everywhere (creates new layers, uses memory)
-- Lazy load above-fold content
-- Optimize micro-optimizations while ignoring major issues (optimize the biggest bottleneck first)
-- Forget about mobile performance (often slower devices, slower connections)
-
-## Verify Improvements
-
-Test that optimizations worked:
-
-- **Before/after metrics**: Compare Lighthouse scores
-- **Real user monitoring**: Track improvements for real users
-- **Different devices**: Test on low-end Android, not just flagship iPhone
-- **Slow connections**: Throttle to 3G, test experience
-- **No regressions**: Ensure functionality still works
-- **User perception**: Does it *feel* faster?
-
-When the user-facing numbers move, hand off to `/impeccable polish` for the final pass.
@@ -1,130 +0,0 @@
-Start your response with:
-
-```
-──────────── ⚡ OVERDRIVE ─────────────
-》》》 Entering overdrive mode...
-```
-
-Push an interface past conventional limits. This isn't just about visual effects. It's about using the full power of the browser to make any part of an interface feel extraordinary: a table that handles a million rows, a dialog that morphs from its trigger, a form that validates in real-time with streaming feedback, a page transition that feels cinematic.
-
-**EXTRA IMPORTANT FOR THIS COMMAND**: Context determines what "extraordinary" means. A particle system on a creative portfolio is impressive. The same particle system on a settings page is embarrassing. But a settings page with instant optimistic saves and animated state transitions? That's extraordinary too. Understand the project's personality and goals before deciding what's appropriate.
-
-### Propose Before Building
-
-This command has the highest potential to misfire. Do NOT jump straight into implementation. You MUST:
-
-1. **Think through 2-3 different directions**: consider different techniques, levels of ambition, and aesthetic approaches. For each direction, briefly describe what the result would look and feel like.
-2. **ask the user directly to clarify what you cannot infer.** to present these directions and get the user's pick before writing any code. Explain trade-offs (browser support, performance cost, complexity).
-3. Only proceed with the direction the user confirms.
-
-Skipping this step risks building something embarrassing that needs to be thrown away.
-
-### Iterate with Browser Automation
-
-Technically ambitious effects almost never work on the first try. You MUST actively use browser automation tools to preview your work, visually verify the result, and iterate. Do not assume the effect looks right, check it. Expect multiple rounds of refinement. The gap between "technically works" and "looks extraordinary" is closed through visual iteration, not code alone.
-
----
-
-## Assess What "Extraordinary" Means Here
-
-The right kind of technical ambition depends entirely on what you're working with. Before choosing a technique, ask: **what would make a user of THIS specific interface say "wow, that's nice"?**
-
-### For visual/marketing surfaces
-Pages, hero sections, landing pages, portfolios: the "wow" is often sensory: a scroll-driven reveal, a shader background, a cinematic page transition, generative art that responds to the cursor.
-
-### For functional UI
-Tables, forms, dialogs, navigation: the "wow" is in how it FEELS: a dialog that morphs from the button that triggered it via View Transitions, a data table that renders 100k rows at 60fps via virtual scrolling, a form with streaming validation that feels instant, drag-and-drop with spring physics.
-
-### For performance-critical UI
-The "wow" is invisible but felt: a search that filters 50k items without a flicker, a complex form that never blocks the main thread, an image editor that processes in near-real-time. The interface just never hesitates.
-
-### For data-heavy interfaces
-Charts and dashboards: the "wow" is in fluidity: GPU-accelerated rendering via Canvas/WebGL for massive datasets, animated transitions between data states, force-directed graph layouts that settle naturally.
-
-**The common thread**: something about the implementation goes beyond what users expect from a web interface. The technique serves the experience, not the other way around.
-
-## The Toolkit
-
-Organized by what you're trying to achieve, not by technology name.
-
-### Make transitions feel cinematic
-- **View Transitions API** (same-document: all browsers; cross-document: no Firefox): shared element morphing between states. A list item expanding into a detail page. A button morphing into a dialog. This is the closest thing to native FLIP animations.
-- **`@starting-style`** (all browsers): animate elements from `display: none` to visible with CSS only, including entry keyframes
-- **Spring physics**: natural motion with mass, tension, and damping instead of cubic-bezier. Libraries: motion (formerly Framer Motion), GSAP, or roll your own spring solver.
-
-### Tie animation to scroll position
-- **Scroll-driven animations** (`animation-timeline: scroll()`): CSS-only, no JS. Parallax, progress bars, reveal sequences all driven by scroll position. (Chrome/Edge/Safari; Firefox: flag only; always provide a static fallback)
-
-### Render beyond CSS
-- **WebGL** (all browsers): shader effects, post-processing, particle systems. Libraries: Three.js, OGL (lightweight), regl. Use for effects CSS can't express.
-- **WebGPU** (Chrome/Edge; Safari partial; Firefox: flag only): next-gen GPU compute. More powerful than WebGL but limited browser support. Always fall back to WebGL2.
-- **Canvas 2D / OffscreenCanvas**: custom rendering, pixel manipulation, or moving heavy rendering off the main thread entirely via Web Workers + OffscreenCanvas.
-- **SVG filter chains**: displacement maps, turbulence, morphology for organic distortion effects. CSS-animatable.
-
-### Make data feel alive
-- **Virtual scrolling**: render only visible rows for tables/lists with tens of thousands of items. No library required for simple cases; TanStack Virtual for complex ones.
-- **GPU-accelerated charts**: Canvas or WebGL-rendered data visualization for datasets too large for SVG/DOM. Libraries: deck.gl, regl-based custom renderers.
-- **Animated data transitions**: morph between chart states rather than replacing. D3's `transition()` or View Transitions for DOM-based charts.
-
-### Animate complex properties
-- **`@property`** (all browsers): register custom CSS properties with types, enabling animation of gradients, colors, and complex values that CSS can't normally interpolate.
-- **Web Animations API** (all browsers): JavaScript-driven animations with the performance of CSS. Composable, cancellable, reversible. The foundation for complex choreography.
-
-### Push performance boundaries
-- **Web Workers**: move computation off the main thread. Heavy data processing, image manipulation, search indexing: anything that would cause jank.
-- **OffscreenCanvas**: render in a Worker thread. The main thread stays free while complex visuals render in the background.
-- **WASM**: near-native performance for computation-heavy features. Image processing, physics simulations, codecs.
-
-### Interact with the device
-- **Web Audio API**: spatial audio, audio-reactive visualizations, sonic feedback. Requires user gesture to start.
-- **Device APIs**: orientation, ambient light, geolocation. Use sparingly and always with user permission.
-
-**NOTE**: This command is about enhancing how an interface FEELS, not changing what a product DOES. Adding real-time collaboration, offline support, or new backend capabilities are product decisions, not UI enhancements. Focus on making existing features feel extraordinary.
-
-## Implement with Discipline
-
-### Progressive enhancement is non-negotiable
-
-Every technique must degrade gracefully. The experience without the enhancement must still be good.
-
-```css
-@supports (animation-timeline: scroll()) {
- .hero { animation-timeline: scroll(); }
-}
-```
-
-```javascript
-if ('gpu' in navigator) { /* WebGPU */ }
-else if (canvas.getContext('webgl2')) { /* WebGL2 fallback */ }
-/* CSS-only fallback must still look good */
-```
-
-### Performance rules
-
-- Target 60fps. If dropping below 50, simplify.
-- Respect `prefers-reduced-motion`, always. Provide a beautiful static alternative.
-- Lazy-initialize heavy resources (WebGL contexts, WASM modules) only when near viewport.
-- Pause off-screen rendering. Kill what you can't see.
-- Test on real mid-range devices, not just your development machine.
-
-### Polish is the difference
-
-The gap between "cool" and "extraordinary" is in the last 20% of refinement: the easing curve on a spring animation, the timing offset in a staggered reveal, the subtle secondary motion that makes a transition feel physical. Don't ship the first version that works; ship the version that feels inevitable.
-
-**NEVER**:
-- Ignore `prefers-reduced-motion`. This is an accessibility requirement, not a suggestion
-- Ship effects that cause jank on mid-range devices
-- Use bleeding-edge APIs without a functional fallback
-- Add sound without explicit user opt-in
-- Use technical ambition to mask weak design fundamentals; fix those first with other commands
-- Layer multiple competing extraordinary moments. Focus creates impact, excess creates noise
-
-## Verify the Result
-
-- **The wow test**: Show it to someone who hasn't seen it. Do they react?
-- **The removal test**: Take it away. Does the experience feel diminished, or does nobody notice?
-- **The device test**: Run it on a phone, a tablet, a Chromebook. Still smooth?
-- **The accessibility test**: Enable reduced motion. Still beautiful?
-- **The context test**: Does this make sense for THIS brand and audience?
-
-"Technically extraordinary" isn't about using the newest API. It's about making an interface do something users didn't think a website could do.
@@ -1,179 +0,0 @@
-# Persona-Based Design Testing
-
-Test the interface through the eyes of 5 distinct user archetypes. Each persona exposes different failure modes that a single "design director" perspective would miss.
-
-**How to use**: Select 2–3 personas most relevant to the interface being critiqued. Walk through the primary user action as each persona. Report specific red flags, not generic concerns.
-
----
-
-## 1. Impatient Power User: "Alex"
-
-
-**Profile**: Expert with similar products. Expects efficiency, hates hand-holding. Will find shortcuts or leave.
-
-**Behaviors**:
-- Skips all onboarding and instructions
-- Looks for keyboard shortcuts immediately
-- Tries to bulk-select, batch-edit, and automate
-- Gets frustrated by required steps that feel unnecessary
-- Abandons if anything feels slow or patronizing
-
-**Test Questions**:
-- Can Alex complete the core task in under 60 seconds?
-- Are there keyboard shortcuts for common actions?
-- Can onboarding be skipped entirely?
-- Do modals have keyboard dismiss (Esc)?
-- Is there a "power user" path (shortcuts, bulk actions)?
-
-**Red Flags** (report these specifically):
-- Forced tutorials or unskippable onboarding
-- No keyboard navigation for primary actions
-- Slow animations that can't be skipped
-- One-item-at-a-time workflows where batch would be natural
-- Redundant confirmation steps for low-risk actions
-
----
-
-## 2. Confused First-Timer: "Jordan"
-
-**Profile**: Never used this type of product. Needs guidance at every step. Will abandon rather than figure it out.
-
-**Behaviors**:
-- Reads all instructions carefully
-- Hesitates before clicking anything unfamiliar
-- Looks for help or support constantly
-- Misunderstands jargon and abbreviations
-- Takes the most literal interpretation of any label
-
-**Test Questions**:
-- Is the first action obviously clear within 5 seconds?
-- Are all icons labeled with text?
-- Is there contextual help at decision points?
-- Does terminology assume prior knowledge?
-- Is there a clear "back" or "undo" at every step?
-
-**Red Flags** (report these specifically):
-- Icon-only navigation with no labels
-- Technical jargon without explanation
-- No visible help option or guidance
-- Ambiguous next steps after completing an action
-- No confirmation that an action succeeded
-
----
-
-## 3. Accessibility-Dependent User: "Sam"
-
-**Profile**: Uses screen reader (VoiceOver/NVDA), keyboard-only navigation. May have low vision, motor impairment, or cognitive differences.
-
-**Behaviors**:
-- Tabs through the interface linearly
-- Relies on ARIA labels and heading structure
-- Cannot see hover states or visual-only indicators
-- Needs adequate color contrast (4.5:1 minimum)
-- May use browser zoom up to 200%
-
-**Test Questions**:
-- Can the entire primary flow be completed keyboard-only?
-- Are all interactive elements focusable with visible focus indicators?
-- Do images have meaningful alt text?
-- Is color contrast WCAG AA compliant (4.5:1 for text)?
-- Does the screen reader announce state changes (loading, success, errors)?
-
-**Red Flags** (report these specifically):
-- Click-only interactions with no keyboard alternative
-- Missing or invisible focus indicators
-- Meaning conveyed by color alone (red = error, green = success)
-- Unlabeled form fields or buttons
-- Time-limited actions without extension option
-- Custom components that break screen reader flow
-
----
-
-## 4. Deliberate Stress Tester: "Riley"
-
-**Profile**: Methodical user who pushes interfaces beyond the happy path. Tests edge cases, tries unexpected inputs, and probes for gaps in the experience.
-
-**Behaviors**:
-- Tests edge cases intentionally (empty states, long strings, special characters)
-- Submits forms with unexpected data (emoji, RTL text, very long values)
-- Tries to break workflows by navigating backwards, refreshing mid-flow, or opening in multiple tabs
-- Looks for inconsistencies between what the UI promises and what actually happens
-- Documents problems methodically
-
-**Test Questions**:
-- What happens at the edges (0 items, 1000 items, very long text)?
-- Do error states recover gracefully or leave the UI in a broken state?
-- What happens on refresh mid-workflow? Is state preserved?
-- Are there features that appear to work but produce broken results?
-- How does the UI handle unexpected input (emoji, special chars, paste from Excel)?
-
-**Red Flags** (report these specifically):
-- Features that appear to work but silently fail or produce wrong results
-- Error handling that exposes technical details or leaves UI in a broken state
-- Empty states that show nothing useful ("No results" with no guidance)
-- Workflows that lose user data on refresh or navigation
-- Inconsistent behavior between similar interactions in different parts of the UI
-
----
-
-## 5. Distracted Mobile User: "Casey"
-
-**Profile**: Using phone one-handed on the go. Frequently interrupted. Possibly on a slow connection.
-
-**Behaviors**:
-- Uses thumb only; prefers bottom-of-screen actions
-- Gets interrupted mid-flow and returns later
-- Switches between apps frequently
-- Has limited attention span and low patience
-- Types as little as possible, prefers taps and selections
-
-**Test Questions**:
-- Are primary actions in the thumb zone (bottom half of screen)?
-- Is state preserved if the user leaves and returns?
-- Does it work on slow connections (3G)?
-- Can forms use autocomplete and smart defaults?
-- Are touch targets at least 44×44pt?
-
-**Red Flags** (report these specifically):
-- Important actions positioned at the top of the screen (unreachable by thumb)
-- No state persistence; progress lost on tab switch or interruption
-- Large text inputs required where selection would work
-- Heavy assets loading on every page (no lazy loading)
-- Tiny tap targets or targets too close together
-
----
-
-## Selecting Personas
-
-Choose personas based on the interface type:
-
-| Interface Type | Primary Personas | Why |
-|---------------|-----------------|-----|
-| Landing page / marketing | Jordan, Riley, Casey | First impressions, trust, mobile |
-| Dashboard / admin | Alex, Sam | Power users, accessibility |
-| E-commerce / checkout | Casey, Riley, Jordan | Mobile, edge cases, clarity |
-| Onboarding flow | Jordan, Casey | Confusion, interruption |
-| Data-heavy / analytics | Alex, Sam | Efficiency, keyboard nav |
-| Form-heavy / wizard | Jordan, Sam, Casey | Clarity, accessibility, mobile |
-
----
-
-## Project-Specific Personas
-
-If `RULES.md` contains a `## Design Context` section (generated by `impeccable teach`), derive 1–2 additional personas from the audience and brand information:
-
-1. Read the target audience description
-2. Identify the primary user archetype not covered by the 5 predefined personas
-3. Create a persona following this template:
-
-```
-### [Role]: "[Name]"
-
-**Profile**: [2-3 key characteristics derived from Design Context]
-
-**Behaviors**: [3-4 specific behaviors based on the described audience]
-
-**Red Flags**: [3-4 things that would alienate this specific user type]
-```
-
-Only generate project-specific personas when real Design Context data is available. Don't invent audience details; use the 5 predefined personas when no context exists.
@@ -1,242 +0,0 @@
-> **Additional context needed**: quality bar (MVP vs flagship).
-
-Perform a meticulous final pass to catch all the small details that separate good work from great work. The difference between shipped and polished.
-
-Detector and automated QA output are defect evidence only. A clean script result is never proof that the design is strong; gather browser evidence and inspect the real interaction path.
-
-## Design System Discovery
-
-Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
-
-1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
-2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
-3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category: patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
-
-If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask. Never guess at design system principles.**
-
-## Pre-Polish Assessment
-
-Understand the current state and goals before touching anything:
-
-1. **Review completeness**:
- - Is it functionally complete?
- - Are there known issues to preserve (mark with TODOs)?
- - What's the quality bar? (MVP vs flagship feature?)
- - When does it ship? (How much time for polish?)
-
-2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish; a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
-
-3. **Identify polish areas**:
- - Visual inconsistencies
- - Spacing and alignment issues
- - Interaction state gaps
- - Copy inconsistencies
- - Edge cases and error states
- - Loading and transition smoothness
- - Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
-
-4. **Pull in any prior critique** (optional signal): If `/impeccable critique` has been run on the same target, its priority issues are a useful prior for what to address first. Resolve the target to a file path or URL, then:
- ```bash
- slug=$(node .trae-cn/skills/impeccable/scripts/critique-storage.mjs slug "<resolved>")
- node .trae-cn/skills/impeccable/scripts/critique-storage.mjs latest "$slug"
- ```
- Exit 0 with body = found; fold the P0/P1 items into your polish list and mention the snapshot path so the user sees what you read. Exit 2 = no snapshot, continue without it. The critique is one input among many. Do your own pass either way.
-
-5. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent; never perfect one corner while leaving another rough.
-
-**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
-
-## Polish Systematically
-
-Work through these dimensions methodically:
-
-### Visual Alignment & Spacing
-
-- **Pixel-perfect alignment**: Everything lines up to grid
-- **Consistent spacing**: All gaps use spacing scale (no random 13px gaps)
-- **Optical alignment**: Adjust for visual weight (icons may need offset for optical centering)
-- **Responsive consistency**: Spacing and alignment work at all breakpoints
-- **Grid adherence**: Elements snap to baseline grid
-
-**Check**:
-- Enable grid overlay and verify alignment
-- Check spacing with browser inspector
-- Test at multiple viewport sizes
-- Look for elements that "feel" off
-
-### Information Architecture & Flow
-
-Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
-
-- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
-- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere: modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
-- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
-- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
-- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
-
-### Typography Refinement
-
-- **Hierarchy consistency**: Same elements use same sizes/weights throughout
-- **Line length**: 45-75 characters for body text
-- **Line height**: Appropriate for font size and context
-- **Widows & orphans**: No single words on last line
-- **Hyphenation**: Appropriate for language and column width
-- **Kerning**: Adjust letter spacing where needed (especially headlines)
-- **Font loading**: No FOUT/FOIT flashes
-
-### Color & Contrast
-
-- **Contrast ratios**: All text meets WCAG standards
-- **Consistent token usage**: No hard-coded colors, all use design tokens
-- **Theme consistency**: Works in all theme variants
-- **Color meaning**: Same colors mean same things throughout
-- **Accessible focus**: Focus indicators visible with sufficient contrast
-- **Tinted neutrals**: No pure gray or pure black; add subtle color tint (0.01 chroma)
-- **Gray on color**: Never put gray text on colored backgrounds; use a shade of that color or transparency
-
-### Interaction States
-
-Every interactive element needs all states:
-
-- **Default**: Resting state
-- **Hover**: Subtle feedback (color, scale, shadow)
-- **Focus**: Keyboard focus indicator (never remove without replacement)
-- **Active**: Click/tap feedback
-- **Disabled**: Clearly non-interactive
-- **Loading**: Async action feedback
-- **Error**: Validation or error state
-- **Success**: Successful completion
-
-**Missing states create confusion and broken experiences**.
-
-### Micro-interactions & Transitions
-
-- **Smooth transitions**: All state changes animated appropriately (150-300ms)
-- **Consistent easing**: Use ease-out-quart/quint/expo for natural deceleration. Never bounce or elastic; they feel dated.
-- **No jank**: Smooth animations; use atmospheric blur/filter/mask/shadow effects when they add polish, but bound expensive paint areas and avoid casual layout-property animation
-- **Appropriate motion**: Motion serves purpose, not decoration
-- **Reduced motion**: Respects `prefers-reduced-motion`
-
-### Content & Copy
-
-- **Consistent terminology**: Same things called same names throughout
-- **Consistent capitalization**: Title Case vs Sentence case applied consistently
-- **Grammar & spelling**: No typos
-- **Appropriate length**: Not too wordy, not too terse
-- **Punctuation consistency**: Periods on sentences, not on labels (unless all labels have them)
-
-### Icons & Images
-
-- **Consistent style**: All icons from same family or matching style
-- **Appropriate sizing**: Icons sized consistently for context
-- **Proper alignment**: Icons align with adjacent text optically
-- **Alt text**: All images have descriptive alt text
-- **Loading states**: Images don't cause layout shift, proper aspect ratios
-- **Retina support**: 2x assets for high-DPI screens
-
-### Forms & Inputs
-
-- **Label consistency**: All inputs properly labeled
-- **Required indicators**: Clear and consistent
-- **Error messages**: Helpful and consistent
-- **Tab order**: Logical keyboard navigation
-- **Auto-focus**: Appropriate (don't overuse)
-- **Validation timing**: Consistent (on blur vs on submit)
-
-### Edge Cases & Error States
-
-- **Loading states**: All async actions have loading feedback
-- **Empty states**: Helpful empty states, not just blank space
-- **Error states**: Clear error messages with recovery paths
-- **Success states**: Confirmation of successful actions
-- **Long content**: Handles very long names, descriptions, etc.
-- **No content**: Handles missing data gracefully
-- **Offline**: Appropriate offline handling (if applicable)
-
-### Responsiveness
-
-- **All breakpoints**: Test mobile, tablet, desktop
-- **Touch targets**: 44x44px minimum on touch devices
-- **Readable text**: No text smaller than 14px on mobile
-- **No horizontal scroll**: Content fits viewport
-- **Appropriate reflow**: Content adapts logically
-
-### Performance
-
-- **Fast initial load**: Optimize critical path
-- **No layout shift**: Elements don't jump after load (CLS)
-- **Smooth interactions**: No lag or jank
-- **Optimized images**: Appropriate formats and sizes
-- **Lazy loading**: Off-screen content loads lazily
-
-### Code Quality
-
-- **Remove console logs**: No debug logging in production
-- **Remove commented code**: Clean up dead code
-- **Remove unused imports**: Clean up unused dependencies
-- **Consistent naming**: Variables and functions follow conventions
-- **Type safety**: No TypeScript `any` or ignored errors
-- **Accessibility**: Proper ARIA labels and semantic HTML
-
-## Polish Checklist
-
-Go through systematically:
-
-- [ ] Aligned to the design system (drift named and resolved by root cause)
-- [ ] Information architecture and flow shape match neighboring features
-- [ ] Visual alignment perfect at all breakpoints
-- [ ] Spacing uses design tokens consistently
-- [ ] Typography hierarchy consistent
-- [ ] All interactive states implemented
-- [ ] All transitions smooth (60fps)
-- [ ] Copy is consistent and polished
-- [ ] Icons are consistent and properly sized
-- [ ] All forms properly labeled and validated
-- [ ] Error states are helpful
-- [ ] Loading states are clear
-- [ ] Empty states are welcoming
-- [ ] Touch targets are 44x44px minimum
-- [ ] Contrast ratios meet WCAG AA
-- [ ] Keyboard navigation works
-- [ ] Focus indicators visible
-- [ ] No console errors or warnings
-- [ ] No layout shift on load
-- [ ] Works in all supported browsers
-- [ ] Respects reduced motion preference
-- [ ] Code is clean (no TODOs, console.logs, commented code)
-
-**IMPORTANT**: Polish is about details. Zoom in. Squint at it. Use it yourself. The little things add up.
-
-Sweat the details. Zoom in until the alignment is right and the spacing reads as deliberate. Then ship.
-
-**NEVER**:
-- Polish before it's functionally complete
-- Polish without aligning to the design system; that's decoration on drift
-- Guess at design system principles instead of asking when something is ambiguous
-- Spend hours on polish if it ships in 30 minutes (triage)
-- Introduce bugs while polishing (test thoroughly)
-- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
-- Perfect one thing while leaving others rough (consistent quality level)
-- Create new one-off components when design system equivalents exist
-- Hard-code values that should use design tokens
-- Introduce new patterns or flows that diverge from established ones
-
-## Final Verification
-
-Before marking as done:
-
-- **Use it yourself**: Actually interact with the feature.
-- **Test on real devices**: Not just browser DevTools.
-- **Ask someone else to review**: Fresh eyes catch things.
-- **Compare to design**: Match intended design.
-- **Check all states**: Don't just test happy path.
-- **Treat automation carefully**: Run detector or QA commands when they are available and relevant, fix their defects, but never cite a clean result as proof that the work is polished.
-
-## Clean Up
-
-After polishing, ensure code quality:
-
-- **Replace custom implementations**: If the design system provides a component you reimplemented, switch to the shared version.
-- **Remove orphaned code**: Delete unused styles, components, or files made obsolete by polish.
-- **Consolidate tokens**: If you introduced new values, check whether they should be tokens.
-- **Verify DRYness**: Look for duplication introduced during polishing and consolidate.
@@ -1,62 +0,0 @@
-# Product register
-
-When design SERVES the product: app UIs, admin dashboards, settings panels, data tables, tools, authenticated surfaces, anything where the user is in a task.
-
-## The product slop test
-
-Not "would someone say AI made this." Familiarity is often a feature here. The test is: would a user fluent in the category's best tools (Linear, Figma, Notion, Raycast, Stripe come to mind) sit down and trust this interface, or pause at every subtly-off component?
-
-Product UI's failure mode isn't flatness, it's strangeness without purpose: over-decorated buttons, mismatched form controls, gratuitous motion, display fonts where labels should be, invented affordances for standard tasks. The bar is earned familiarity. The tool should disappear into the task.
-
-## Typography
-
-- **System fonts are legitimate.** `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` gives you native feel on every platform. Inter is the common cross-platform default for a reason.
-- **One family is often right.** Product UIs don't need display/body pairing. A well-tuned sans carries headings, buttons, labels, body, data.
-- **Fixed rem scale, not fluid.** Clamp-sized headings don't serve product UI. Users view at consistent DPI, and a fluid h1 that shrinks in a sidebar looks worse, not better.
-- **Tighter scale ratio.** 1.125–1.2 between steps is typical. More type elements here than on brand surfaces; exaggerated contrast creates noise.
-- **Line length still applies for prose** (65–75ch). Data and compact UI can run denser; tables at 120ch+ are fine.
-
-## Color
-
-Product defaults to Restrained. A single surface can earn Committed (a dashboard where one category color carries a report, an onboarding flow with a drenched welcome screen), but Restrained is the floor.
-
-- State-rich semantic vocabulary: hover, focus, active, disabled, selected, loading, error, warning, success, info. Standardize these.
-- Accent color used for primary actions, current selection, and state indicators only, not decoration.
-- A second neutral layer for sidebars, toolbars, and panels (slightly cooler or warmer than the content surface).
-
-## Layout
-
-- Predictable grids. Consistency IS an affordance; users navigate faster when the structure is expected.
-- Familiar patterns are features. Standard navigation (top bar, side nav), breadcrumbs, tabs, and form layouts have established user expectations. Don't reinvent for flavor.
-- Responsive behavior is structural (collapse sidebar, responsive table, breakpoint-driven columns), not fluid typography.
-
-## Components
-
-Every interactive component has: default, hover, focus, active, disabled, loading, error. Don't ship with half of these.
-
-- Skeleton states for loading, not spinners in the middle of content.
-- Empty states that teach the interface, not "nothing here."
-- Consistent affordances across the surface. Same button shape. Same form-control vocabulary. Same icon style.
-
-## Motion
-
-- 150–250 ms on most transitions. Users are in flow; don't make them wait for choreography.
-- Motion conveys state, not decoration. State change, feedback, loading, reveal: nothing else.
-- No orchestrated page-load sequences. Product loads into a task; users don't want to watch it load.
-
-## Product bans (on top of the shared absolute bans)
-
-- Decorative motion that doesn't convey state.
-- Inconsistent component vocabulary across screens. If the "save" button looks different in two places, one is wrong.
-- Display fonts in UI labels, buttons, data.
-- Reinventing standard affordances for flavor (custom scrollbars, weird form controls, non-standard modals).
-- Heavy color or full-saturation accents on inactive states.
-
-## Product permissions
-
-Product can afford things brand surfaces can't.
-
-- System fonts and familiar sans defaults (Inter, SF Pro, system-ui stacks).
-- Standard navigation patterns: top bar + side nav, breadcrumbs, tabs, command palettes.
-- Density. Tables with many rows, panels with many labels, dense information when users need it.
-- Consistency over surprise. The same visual vocabulary screen to screen is a virtue; delight is saved for moments, not pages.
@@ -1,99 +0,0 @@
-Quiet design is harder than bold design. Subtlety needs precision. Reduce visual intensity in designs that are too loud, aggressive, or overstimulating without losing personality or making the result generic.
-
----
-
-## Register
-
-Brand: "quieter" means more restrained palette, more whitespace, more typographic air. Drama is reduced, not eliminated; the POV stays intact.
-
-Product: "quieter" means reducing visual noise. Fewer background accents, flatter cards, less color, less motion. The tool should disappear more completely into the task.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too intense:
-
-1. **Identify intensity sources**:
- - **Color saturation**: Overly bright or saturated colors
- - **Contrast extremes**: Too much high-contrast juxtaposition
- - **Visual weight**: Too many bold, heavy elements competing
- - **Animation excess**: Too much motion or overly dramatic effects
- - **Complexity**: Too many visual elements, patterns, or decorations
- - **Scale**: Everything is large and loud with no hierarchy
-
-2. **Understand the context**:
- - What's the purpose? (Marketing vs tool vs reading experience)
- - Who's the audience? (Some contexts need energy)
- - What's working? (Don't throw away good ideas)
- - What's the core message? (Preserve what matters)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Quieter" doesn't mean boring or generic. It means refined and easier on the eyes. Think luxury, not laziness.
-
-## Plan Refinement
-
-Create a strategy to reduce intensity while maintaining impact:
-
-- **Color approach**: Desaturate or shift to more restrained tones?
-- **Hierarchy approach**: Which elements should stay bold (very few), which should recede?
-- **Simplification approach**: What can be removed entirely?
-- **Sophistication approach**: How can we signal quality through restraint?
-
-**IMPORTANT**: Subtlety requires precision. Quiet without intent collapses to generic.
-
-## Refine the Design
-
-Systematically reduce intensity across these dimensions:
-
-### Color Refinement
-- **Reduce saturation**: Shift from fully saturated to 70-85% saturation
-- **Soften palette**: Replace bright colors with muted tones
-- **Reduce color variety**: Use fewer colors more thoughtfully
-- **Neutral dominance**: Let neutrals do more work, use color as accent (10% rule)
-- **Gentler contrasts**: High contrast only where it matters most
-- **Tinted grays**: Use warm or cool tinted grays instead of pure gray. Adds depth without loudness
-- **Never gray on color**: If you have gray text on a colored background, use a darker shade of that color or transparency instead
-
-### Visual Weight Reduction
-- **Typography**: Reduce font weights (900 → 600, 700 → 500), decrease sizes where appropriate
-- **Hierarchy through subtlety**: Use weight, size, and space instead of color and boldness
-- **White space**: Increase breathing room, reduce density
-- **Borders & lines**: Reduce thickness, decrease opacity, or remove entirely
-
-### Simplification
-- **Remove decorative elements**: Gradients, shadows, patterns, textures that don't serve purpose
-- **Simplify shapes**: Reduce border radius extremes, simplify custom shapes
-- **Reduce layering**: Flatten visual hierarchy where possible
-- **Clean up effects**: Reduce or remove blur effects, glows, multiple shadows
-
-### Motion Reduction
-- **Reduce animation intensity**: Shorter distances (10-20px instead of 40px), gentler easing
-- **Remove decorative animations**: Keep functional motion, remove flourishes
-- **Subtle micro-interactions**: Replace dramatic effects with gentle feedback
-- **Refined easing**: Use ease-out-quart for smooth, understated motion. Never bounce or elastic
-- **Remove animations entirely** if they're not serving a clear purpose
-
-### Composition Refinement
-- **Reduce scale jumps**: Smaller contrast between sizes creates calmer feeling
-- **Align to grid**: Bring rogue elements back into systematic alignment
-- **Even out spacing**: Replace extreme spacing variations with consistent rhythm
-
-**NEVER**:
-- Make everything the same size/weight (hierarchy still matters)
-- Remove all color (quiet ≠ grayscale)
-- Eliminate all personality (maintain character through refinement)
-- Sacrifice usability for aesthetics (functional elements still need clear affordances)
-- Make everything small and light (some anchors needed)
-
-## Verify Quality
-
-Ensure refinement maintains quality:
-
-- **Still functional**: Can users still accomplish tasks easily?
-- **Still distinctive**: Does it have character, or is it generic now?
-- **Better reading**: Is text easier to read for extended periods?
-- **Restrained, not absent**: Does the POV survive the cuts?
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,114 +0,0 @@
-# Responsive Design
-
-## Mobile-First: Write It Right
-
-Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
-
-## Breakpoints: Content-Driven
-
-Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
-
-## Detect Input Method, Not Just Screen Size
-
-**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
-
-```css
-/* Fine pointer (mouse, trackpad) */
-@media (pointer: fine) {
- .button { padding: 8px 16px; }
-}
-
-/* Coarse pointer (touch, stylus) */
-@media (pointer: coarse) {
- .button { padding: 12px 20px; } /* Larger touch target */
-}
-
-/* Device supports hover */
-@media (hover: hover) {
- .card:hover { transform: translateY(-2px); }
-}
-
-/* Device doesn't support hover (touch) */
-@media (hover: none) {
- .card { /* No hover state - use active instead */ }
-}
-```
-
-**Critical**: Don't rely on hover for functionality. Touch users can't hover.
-
-## Safe Areas: Handle the Notch
-
-Modern phones have notches, rounded corners, and home indicators. Use `env()`:
-
-```css
-body {
- padding-top: env(safe-area-inset-top);
- padding-bottom: env(safe-area-inset-bottom);
- padding-left: env(safe-area-inset-left);
- padding-right: env(safe-area-inset-right);
-}
-
-/* With fallback */
-.footer {
- padding-bottom: max(1rem, env(safe-area-inset-bottom));
-}
-```
-
-**Enable viewport-fit** in your meta tag:
-```html
-<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
-```
-
-## Responsive Images: Get It Right
-
-### srcset with Width Descriptors
-
-```html
-<img
- src="hero-800.jpg"
- srcset="
- hero-400.jpg 400w,
- hero-800.jpg 800w,
- hero-1200.jpg 1200w
- "
- sizes="(max-width: 768px) 100vw, 50vw"
- alt="Hero image"
->
-```
-
-**How it works**:
-- `srcset` lists available images with their actual widths (`w` descriptors)
-- `sizes` tells the browser how wide the image will display
-- Browser picks the best file based on viewport width AND device pixel ratio
-
-### Picture Element for Art Direction
-
-When you need different crops/compositions (not just resolutions):
-
-```html
-<picture>
- <source media="(min-width: 768px)" srcset="wide.jpg">
- <source media="(max-width: 767px)" srcset="tall.jpg">
- <img src="fallback.jpg" alt="...">
-</picture>
-```
-
-## Layout Adaptation Patterns
-
-**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
-
-## Testing: Don't Trust DevTools Alone
-
-DevTools device emulation is useful for layout but misses:
-
-- Actual touch interactions
-- Real CPU/memory constraints
-- Network latency patterns
-- Font rendering differences
-- Browser chrome/keyboard appearances
-
-**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
-
----
-
-**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
@@ -1,165 +0,0 @@
-Shape the UX and UI for a feature before any code is written. This command produces a **design brief**: a structured artifact that guides implementation through discovery, not guesswork.
-
-**Scope**: Design planning only. This command does NOT write code. It produces the thinking that makes code good.
-
-**Output**: A design brief that can be handed off to /impeccable craft, or directly to /impeccable for freeform implementation. When visual direction probes are used, the images are supporting artifacts, not the primary output.
-
-## Philosophy
-
-Most AI-generated UIs fail not because of bad code, but because of skipped thinking. They jump to "here's a card grid" without asking "what is the user trying to accomplish?" This command inverts that: understand deeply first, so implementation is precise.
-
-## Phase 1: Discovery Interview
-
-**Do NOT write any code or make any design decisions during this phase.** Your only job is to understand the feature deeply enough to make excellent design decisions later.
-
-This is a required interaction, not optional guidance. Ask these questions in conversation, adapting based on answers. Don't dump them all at once; have a natural dialogue. ask the user directly to clarify what you cannot infer.
-
-### Interview cadence
-
-Discovery includes at least one user-answer round unless PRODUCT.md, DESIGN.md, or an already-confirmed brief directly answers the needed inputs. With a sparse prompt, do **not** synthesize a complete brief for confirmation on the first response.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Treat PRODUCT.md and DESIGN.md as anchors; they reduce repeated questions but do **not** replace shape for craft. Shape is task-specific.
-- One round is the default. Add a second only if the first answers leave material gaps. Don't run a second round just to feel thorough.
-- Round 1 should clarify purpose, audience/context, content/scope, and (for brand) visual direction.
-- Round 2, when needed, fills in whatever's still genuinely missing.
-
-**Assert-then-confirm, not menu-with-escape.** When PRODUCT.md and the user's prompt make one option obvious, name it and ask the user to confirm or override. Don't enumerate "Restrained / Committed / Or something else?" as a real choice; "This reads as Restrained, confirm?" beats a four-option menu when the answer is already clear.
-
-### Purpose & Context
-- What is this feature for? What problem does it solve?
-- Who specifically will use it? (Not "users"; be specific: role, context, frequency)
-- What does success look like? How will you know this feature is working?
-- What's the user's state of mind when they reach this feature? (Rushed? Exploring? Anxious? Focused?)
-
-### Content & Data
-- What content or data does this feature display or collect?
-- What are the realistic ranges? (Minimum, typical, maximum, e.g., 0 items, 5 items, 500 items)
-- What are the edge cases? (Empty state, error state, first-time use, power user)
-- Is any content dynamic? What changes and how often?
-- What visual assets are real content here? Note required images, product shots, illustrations, maps, textures, diagrams, generated objects, or existing project assets.
-
-### Design Direction
-
-Force a visual decision on three fronts. Skip anything PRODUCT.md or DESIGN.md already answers; ask only what's missing.
-
-- **Color strategy for this surface.** Pick one: Restrained / Committed / Full palette / Drenched. Can override the project default if the surface earns it (e.g. a drenched hero inside an otherwise Restrained product).
-- **Theme via scene sentence.** Write one sentence of physical context for this surface: who uses it, where, under what ambient light, in what mood. The sentence forces dark vs light. If it doesn't, add detail until it does.
-- **Two or three named anchor references.** Specific products, brands, objects. Not adjectives like "modern" or "clean."
-
-### Scope
-
-Always ask. Sketch quality and shipped quality are different outputs; don't guess between them.
-
-- **Fidelity.** Sketch / mid-fi / high-fi / production-ready?
-- **Breadth.** One screen / a flow / a whole surface?
-- **Interactivity.** Static visual / interactive prototype / shipped-quality component?
-- **Time intent.** Quick exploration, or polish until it ships?
-
-Scope answers are task-scoped. Don't write them to PRODUCT.md or DESIGN.md; carry them through the design brief only.
-
-### Constraints
-- Are there technical constraints? (Framework, performance budget, browser support)
-- Are there content constraints? (Localization, dynamic text length, user-generated content)
-- Mobile/responsive requirements?
-- Accessibility requirements beyond WCAG AA?
-
-### Anti-Goals
-- What should this NOT be? What would be a wrong direction?
-- What's the biggest risk of getting this wrong?
-
-## Phase 1.5: Visual Direction Probe (Capability-Gated)
-
-After the discovery interview, generate a small set of visual direction probes **before** writing the final brief when all of these are true:
-
-- The work is **net-new** or directionally ambiguous enough that visual exploration will clarify the brief.
-- The requested fidelity is **mid-fi, high-fi, or production-ready**. Skip for sketch-only planning.
-- The current harness gives you native image generation (Codex's `image_gen`, an equivalent MCP tool, or similar). Don't ask the user to install APIs or tooling.
-
-When those conditions are met, this step is mandatory. If image generation isn't natively available, do not ask the user to install APIs or tooling. State in one line that the image step is skipped because the harness lacks native image generation, then proceed. The one-line announcement is required, not optional; it forces a conscious decision instead of letting the step quietly evaporate.
-
-Use probes to explore visual lanes, not to replace the brief.
-
-Do not skip probes because the final UI will be semantic, editable, code-native, responsive, or accessible. Those are implementation requirements, not reasons to avoid visual exploration.
-
-### What to generate
-
-Generate **2 to 4** distinct direction probes based on the discovery answers, especially:
-
-- Color strategy
-- Theme scene sentence
-- Named anchor references
-- Scope and fidelity
-
-The probes should differ in primary visual direction (hierarchy, topology, density, typographic voice, or color strategy), not just palette tweaks.
-
-### How to use the probes
-
-- Treat them as **direction tests**, not final designs.
-- Use them to pressure-test whether the brief is pointing at the right lane.
-- Ask the user which direction feels closest, what feels off, and what should carry forward.
-- If the probes reveal a mismatch, revise the brief inputs before finalizing the brief.
-
-### Important limits
-
-- Do **not** skip discovery because image generation is available.
-- Do **not** treat generated imagery as final UX specification, final copy, or final accessibility behavior.
-- Do **not** use this step for minor refinements of existing work. It's for shaping a new surface or clarifying a big directional choice.
-
-If image generation isn't natively available, announce the skip in one line and proceed to the design brief.
-
-## Phase 2: Design Brief
-
-After the interview and any required probes, present a brief and **end your response**. The user must confirm before any implementation runs. Do not present a brief and then continue to code in the same response, even if the brief feels obvious to you. The user's confirmation is the gate.
-
-**Choose the brief shape based on how clear the answers are:**
-
-- **Compact form (3-5 bullets)** when discovery was crisp and the original prompt + PRODUCT.md already pinned scope, content, and direction. State what you're building, the visual lane, and end with one or two specific questions or a clear "confirm or override?" prompt. This is the default for typical craft requests with a clear prompt.
-- **Full structured form (sections below)** when the task is genuinely ambiguous, multi-screen, or when the user asked for shape as a standalone step. Use this when the discipline of structure earns its weight.
-
-Don't pad a clear brief into a long one to look thorough. A 70-line brief restating answers the user just gave is noise, not rigor. Equally, don't skip the confirmation pause to look efficient: the pause is the point.
-
-Present the brief, then **stop and wait for explicit confirmation**. You are not the judge of whether the user already approved. Even when the brief feels obviously right, ask once and wait. The pause is what separates shape from premature implementation.
-
-### Brief Structure
-
-**1. Feature Summary** (2-3 sentences)
-What this is, who it's for, what it needs to accomplish.
-
-**2. Primary User Action**
-The single most important thing a user should do or understand here.
-
-**3. Design Direction**
-Color strategy (Restrained / Committed / Full palette / Drenched) + the theme scene sentence + 2–3 named anchor references. Reference PRODUCT.md and DESIGN.md where they already answer, and note any per-surface overrides.
-
-If you ran the Visual Direction Probe step, name which probe direction won and what changed in the brief because of it.
-
-**4. Scope**
-Fidelity, breadth, interactivity, and time intent from the Scope section of the interview. Task-scoped; these don't persist beyond the brief.
-
-**5. Layout Strategy**
-High-level spatial approach: what gets emphasis, what's secondary, how information flows. Describe the visual hierarchy and rhythm, not specific CSS.
-
-**6. Key States**
-List every state the feature needs: default, empty, loading, error, success, edge cases. For each, note what the user needs to see and feel.
-
-**7. Interaction Model**
-How users interact with this feature. What happens on click, hover, scroll? What feedback do they get? What's the flow from entry to completion?
-
-**8. Content Requirements**
-What copy, labels, empty state messages, error messages, and microcopy are needed. Note any dynamic content and its realistic ranges. For image-led surfaces, also list the required image/media roles and their likely source (project asset, generated raster, semantic SVG/CSS, canvas/WebGL, icon library, or accepted omission).
-
-**9. Recommended References**
-Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., spatial-design.md for complex layouts, motion-design.md for animated features, interaction-design.md for form-heavy features).
-
-**10. Open Questions**
-Anything genuinely unresolved. Don't list "open questions" you've already recommended a default for; assert the default and move on. If you'd write `Recommend: X` next to a question, just decide X.
-
----
-
-ask the user directly to clarify what you cannot infer. Ask for explicit confirmation of the brief before finishing.
-
-If the user disagrees with any part, revisit the relevant discovery questions. A shape run is incomplete until the user confirms direction.
-
-Once confirmed, the brief is complete. The user can now hand it to /impeccable, or use it to guide any other implementation approach. (If the user wants the full discovery-then-build flow in one step, they should use /impeccable craft instead, which runs this command internally.)
@@ -1,100 +0,0 @@
-# Spatial Design
-
-## Spacing Systems
-
-### Use 4pt Base, Not 8pt
-
-8pt systems are too coarse; you'll frequently need 12px (between 8 and 16). Use 4pt for granularity: 4, 8, 12, 16, 24, 32, 48, 64, 96px.
-
-### Name Tokens Semantically
-
-Name by relationship (`--space-sm`, `--space-lg`), not value (`--spacing-8`). Use `gap` instead of margins for sibling spacing; it eliminates margin collapse and cleanup hacks.
-
-## Grid Systems
-
-### The Self-Adjusting Grid
-
-Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Columns are at least 280px, as many as fit per row, leftovers stretch. For complex layouts, use named grid areas (`grid-template-areas`) and redefine them at breakpoints.
-
-## Visual Hierarchy
-
-### The Squint Test
-
-Blur your eyes (or screenshot and blur). Can you still identify:
-- The most important element?
-- The second most important?
-- Clear groupings?
-
-If everything looks the same weight blurred, you have a hierarchy problem.
-
-### Hierarchy Through Multiple Dimensions
-
-Don't rely on size alone. Combine:
-
-| Tool | Strong Hierarchy | Weak Hierarchy |
-|------|------------------|----------------|
-| **Size** | 3:1 ratio or more | <2:1 ratio |
-| **Weight** | Bold vs Regular | Medium vs Regular |
-| **Color** | High contrast | Similar tones |
-| **Position** | Top/left (primary) | Bottom/right |
-| **Space** | Surrounded by white space | Crowded |
-
-**The best hierarchy uses 2-3 dimensions at once**: A heading that's larger, bolder, AND has more space above it.
-
-### Cards Are Not Required
-
-Cards are overused. Spacing and alignment create visual grouping naturally. Use cards only when content is truly distinct and actionable, items need visual comparison in a grid, or content needs clear interaction boundaries. **Never nest cards inside cards.** Use spacing, typography, and subtle dividers for hierarchy within a card.
-
-## Container Queries
-
-Viewport queries are for page layouts. **Container queries are for components**:
-
-```css
-.card-container {
- container-type: inline-size;
-}
-
-.card {
- display: grid;
- gap: var(--space-md);
-}
-
-/* Card layout changes based on its container, not viewport */
-@container (min-width: 400px) {
- .card {
- grid-template-columns: 120px 1fr;
- }
-}
-```
-
-**Why this matters**: A card in a narrow sidebar stays compact, while the same card in a main content area expands automatically, without viewport hacks.
-
-## Optical Adjustments
-
-Text at `margin-left: 0` looks indented due to letterform whitespace; use negative margin (`-0.05em`) to optically align. Geometrically centered icons often look off-center; play icons need to shift right, arrows shift toward their direction.
-
-### Touch Targets vs Visual Size
-
-Buttons can look small but need large touch targets (44px minimum). Use padding or pseudo-elements:
-
-```css
-.icon-button {
- width: 24px; /* Visual size */
- height: 24px;
- position: relative;
-}
-
-.icon-button::before {
- content: '';
- position: absolute;
- inset: -10px; /* Expand tap target to 44px */
-}
-```
-
-## Depth & Elevation
-
-Create semantic z-index scales (dropdown → sticky → modal-backdrop → modal → toast → tooltip) instead of arbitrary numbers. For shadows, create a consistent elevation scale (sm → md → lg → xl). **Key insight**: Shadows should be subtle. If you can clearly see it, it's probably too strong.
-
----
-
-**Avoid**: Arbitrary spacing values outside your scale. Making all spacing equal (variety creates hierarchy). Creating hierarchy through size alone - combine size, weight, color, and space.
@@ -1,156 +0,0 @@
-# Teach Flow
-
-Gathers design context for a project and writes two complementary files at the project root:
-
-- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
-- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
-
-Every other impeccable command reads these files before doing any work.
-
-## Step 1: Load current state
-
-Run the shared loader first so you know what already exists:
-
-```bash
-node .trae-cn/skills/impeccable/scripts/load-context.mjs
-```
-
-The output tells you whether PRODUCT.md and/or DESIGN.md already exist. If `migrated: true`, legacy `.impeccable.md` was auto-renamed to `PRODUCT.md`. Mention this once to the user.
-
-Decision tree:
-- **Neither file exists (empty project or no context yet)**: do Steps 2-4 (write PRODUCT.md), then decide on DESIGN.md based on whether there's code to analyze.
-- **PRODUCT.md exists, DESIGN.md missing**: skip to Step 5 and offer to run `/impeccable document` for DESIGN.md.
-- **PRODUCT.md exists but has no `## Register` section (legacy)**: add it. Infer a hypothesis from the codebase (see Step 2), confirm with the user, write the field.
-- **Both exist**: ask the user directly to clarify what you cannot infer. Ask which file to refresh. Skip the one the user doesn't want changed.
-- **Just DESIGN.md exists (unusual)**: do Steps 2-4 to produce PRODUCT.md.
-
-Never silently overwrite an existing file. Always confirm first.
-
-If teach was invoked as a setup blocker by another command, such as `/impeccable craft landing page`, pause that command here. Complete teach, re-run the loader, then resume the original command with the freshly loaded context. For craft, resume into shape next; teach creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
-
-## Step 2: Explore the codebase
-
-Before asking questions, thoroughly scan the project to discover what you can:
-
-- **README and docs**: Project purpose, target audience, any stated goals
-- **Package.json / config files**: Tech stack, dependencies, existing design libraries
-- **Existing components**: Current design patterns, spacing, typography in use
-- **Brand assets**: Logos, favicons, color values already defined
-- **Design tokens / CSS variables**: Existing color palettes, font stacks, spacing scales
-- **Any style guides or brand documentation**
-
-Also form a **register hypothesis** from what you find:
-
-- Brand signals: `/`, `/about`, `/pricing`, `/blog/*`, `/docs/*`, hero sections, big typography, scroll-driven sections, landing-page-shaped content.
-- Product signals: `/app/*`, `/dashboard`, `/settings`, `/(auth)`, forms, data tables, side/top nav, app-shell components.
-
-Register is a hypothesis at this point, not a decision; Step 3 confirms it.
-
-Note what you've learned and what remains unclear. This exploration feeds both PRODUCT.md and DESIGN.md.
-
-## Step 3: Ask strategic questions (for PRODUCT.md)
-
-ask the user directly to clarify what you cannot infer. Ask only about what you couldn't infer from the codebase.
-
-### Interview mode, not confirmation mode
-
-If the repo is empty or the user's brief is sparse, run a short interview before proposing PRODUCT.md. Do **not** turn a one-sentence request into a complete inferred PRODUCT.md and ask for blanket confirmation.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Use inferred answers as hypotheses or options, not as finished facts.
-- Complete at least one real user-answer round before drafting PRODUCT.md, unless every required answer is directly discoverable from repo docs.
-- Round 1 should establish register, users/purpose, and desired outcome.
-- Round 2 should establish brand personality or references, anti-references, and accessibility needs.
-
-### Minimum viable interview
-
-Ask enough to complete PRODUCT.md. At minimum, cover register confirmation, users and purpose, brand personality, anti-references, and accessibility needs unless each answer is directly discoverable from repo context. After at least one interview round, you may propose inferred answers, but the user must confirm them before you write PRODUCT.md. Never synthesize PRODUCT.md from the original task prompt alone.
-
-### Register (ask first; it shapes everything below)
-
-Every design task is either **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboards, tools: design SERVES the product).
-
-If Step 2 produced a clear hypothesis, lead with it: *"From the codebase, this looks like a [brand / product] surface. Does that match your intent, or should we treat it differently?"*
-
-If the signal is genuinely split (e.g. a product with a big marketing landing), ask the user directly to clarify what you cannot infer. Ask which register describes the **primary** surface. The register can be overridden per task later, but PRODUCT.md carries one default.
-
-### Users & Purpose
-- Who uses this? What's their context when using it?
-- What job are they trying to get done?
-- For brand: what emotions should the interface evoke? (confidence, delight, calm, urgency)
-- For product: what workflow are they in? What's the primary task on any given screen?
-
-### Brand & Personality
-- How would you describe the brand personality in 3 words?
-- Reference sites or apps that capture the right feel? What specifically about them?
- - For brand, push for real-world references in the right lane (tech-minimal, editorial-magazine, consumer-warm, brutalist-grid, etc.), not generic "modern" adjectives.
- - For product, push for category best-tool references (Linear, Figma, Notion, Raycast, Stripe).
-- What should this explicitly NOT look like? Any anti-references?
-
-### Accessibility & Inclusion
-- Specific accessibility requirements? (WCAG level, known user needs)
-- Considerations for reduced motion, color blindness, or other accommodations?
-
-Skip questions where the answer is already clear. **Do NOT ask about colors, fonts, radii, or visual styling here.** Those belong in DESIGN.md, not PRODUCT.md.
-
-## Step 4: Write PRODUCT.md
-
-Write PRODUCT.md only after the user has confirmed the strategic answers from Step 3. If an inferred answer is uncertain or unconfirmed, ask before writing.
-
-Synthesize into a strategic document:
-
-```markdown
-# Product
-
-## Register
-
-product
-
-## Users
-[Who they are, their context, the job to be done]
-
-## Product Purpose
-[What this product does, why it exists, what success looks like]
-
-## Brand Personality
-[Voice, tone, 3-word personality, emotional goals]
-
-## Anti-references
-[What this should NOT look like. Specific bad-example sites or patterns to avoid.]
-
-## Design Principles
-[3-5 strategic principles derived from the conversation. Principles like "practice what you preach", "show, don't tell", "expert confidence". NOT visual rules like "use OKLCH" or "magenta accent".]
-
-## Accessibility & Inclusion
-[WCAG level, known user needs, considerations]
-```
-
-Register is either `brand` or `product` as a bare value. No prose, no commentary.
-
-Write to `PROJECT_ROOT/PRODUCT.md`. If `.impeccable.md` existed, the loader already renamed it; merge into that content rather than starting from scratch.
-
-## Step 5: Decide on DESIGN.md
-
-Offer `/impeccable document` either way. Two paths:
-
-- **Code exists** (CSS tokens, components, a running site): "I can generate a DESIGN.md that captures your visual system (colors, typography, components) so variants stay on-brand. Want to do that now?"
-- **Pre-implementation** (empty project): "I can seed a starter DESIGN.md from five quick questions about color strategy, type direction, motion energy, and references. You can re-run once there's code, to capture the real tokens. Want to do that now?"
-
-If the user agrees, delegate to `/impeccable document` (it auto-detects scan vs seed). Load its reference and follow that flow.
-
-If the user prefers to skip, mention they can run `/impeccable document` any time later.
-
-## Step 6: Confirm and wrap up
-
-Summarize:
-- Register captured (brand / product)
-- What was written (PRODUCT.md, DESIGN.md, or both)
-- The 3-5 strategic principles from PRODUCT.md that will guide future work
-- If DESIGN.md is pending, remind the user how to generate it later
-
-**Critical: re-run the loader to refresh session context.** After writing PRODUCT.md, run `node .trae-cn/skills/impeccable/scripts/load-context.mjs` one final time and let its full JSON output land in conversation. This ensures subsequent commands in this session use the freshly-written PRODUCT.md, not a stale earlier version.
-
-If teach was invoked as a blocker by another impeccable command (e.g. the user ran `/impeccable polish` with no PRODUCT.md), resume that original task now with the fresh context.
-
-Optionally ask the user directly to clarify what you cannot infer. Ask whether they'd like a brief summary of PRODUCT.md appended to RULES.md for easier agent reference. If yes, append a short **Design Context** pointer section there.
@@ -1,124 +0,0 @@
-Typography carries most of the information on the page. Replace generic defaults (Inter, Roboto, system fallback at flat scale) with type that reflects the brand and scales with intentional contrast.
-
----
-
-## Register
-
-Brand: run the font selection procedure in [brand.md](brand.md). Pairing follows the brand's lane (display serif + sans body for editorial/luxury, one committed sans for tech, etc.). Fluid `clamp()` scale, ≥1.25 ratio between steps.
-
-Product: system fonts and familiar sans stacks are legitimate here. One well-tuned family typically carries the whole UI. Fixed `rem` scale, 1.125–1.2 ratio between more closely-spaced steps.
-
----
-
-## Assess Current Typography
-
-Analyze what's weak or generic about the current type:
-
-1. **Font choices**:
- - Are we using invisible defaults? (Inter, Roboto, Arial, Open Sans, system defaults)
- - Does the font match the brand personality? (A playful brand shouldn't use a corporate typeface)
- - Are there too many font families? (More than 2-3 is almost always a mess)
-
-2. **Hierarchy**:
- - Can you tell headings from body from captions at a glance?
- - Are font sizes too close together? (14px, 15px, 16px = muddy hierarchy)
- - Are weight contrasts strong enough? (Medium vs Regular is barely visible)
-
-3. **Sizing & scale**:
- - Is there a consistent type scale, or are sizes arbitrary?
- - Does body text meet minimum readability? (16px+)
- - Is the sizing strategy appropriate for the context? (Fixed `rem` scales for app UIs; fluid `clamp()` for marketing/content page headings)
-
-4. **Readability**:
- - Are line lengths comfortable? (45-75 characters ideal)
- - Is line-height appropriate for the font and context?
- - Is there enough contrast between text and background?
-
-5. **Consistency**:
- - Are the same elements styled the same way throughout?
- - Are font weights used consistently? (Not bold in one section, semibold in another for the same role)
- - Is letter-spacing intentional or default everywhere?
-
-**CRITICAL**: The goal isn't to make text "fancier." It's to make it clearer, more readable, and more intentional. Good typography is invisible; bad typography is distracting.
-
-## Plan Typography Improvements
-
-Consult the [typography reference](typography.md) for detailed guidance on scales, pairing, and loading strategies.
-
-Create a systematic plan:
-
-- **Font selection**: Do fonts need replacing? What fits the brand/context?
-- **Type scale**: Establish a modular scale (e.g., 1.25 ratio) with clear hierarchy
-- **Weight strategy**: Which weights serve which roles? (Regular for body, Semibold for labels, Bold for headings, or whatever fits)
-- **Spacing**: Line-heights, letter-spacing, and margins between typographic elements
-
-## Improve Typography Systematically
-
-### Font Selection
-
-If fonts need replacing:
-- Choose fonts that reflect the brand personality
-- Pair with genuine contrast (serif + sans, geometric + humanist), or use a single family in multiple weights
-- Ensure web font loading doesn't cause layout shift (`font-display: swap`, metric-matched fallbacks)
-
-### Establish Hierarchy
-
-Build a clear type scale:
-- **5 sizes cover most needs**: caption, secondary, body, subheading, heading
-- **Use a consistent ratio** between levels (1.25, 1.333, or 1.5)
-- **Combine dimensions**: Size + weight + color + space for strong hierarchy. Don't rely on size alone
-- **App UIs**: Use a fixed `rem`-based type scale, optionally adjusted at 1-2 breakpoints. Fluid sizing undermines the spatial predictability that dense, container-based layouts need
-- **Marketing / content pages**: Use fluid sizing via `clamp(min, preferred, max)` for headings and display text. Keep body text fixed
-
-### Fix Readability
-
-- Set `max-width` on text containers using `ch` units (`max-width: 65ch`)
-- Adjust line-height per context: tighter for headings (1.1-1.2), looser for body (1.5-1.7)
-- Increase line-height slightly for light-on-dark text
-- Ensure body text is at least 16px / 1rem
-
-### Refine Details
-
-- Use `tabular-nums` for data tables and numbers that should align
-- Apply proper `letter-spacing`: slightly open for small caps and uppercase, default or tight for large display text
-- Use semantic token names (`--text-body`, `--text-heading`), not value names (`--font-16`)
-- Set `font-kerning: normal` and consider OpenType features where appropriate
-
-### Weight Consistency
-
-- Define clear roles for each weight and stick to them
-- Don't use more than 3-4 weights (Regular, Medium, Semibold, Bold is plenty)
-- Load only the weights you actually use (each weight adds to page load)
-
-**NEVER**:
-- Use more than 2-3 font families
-- Pick sizes arbitrarily; commit to a scale
-- Set body text below 16px
-- Use decorative/display fonts for body text
-- Disable browser zoom (`user-scalable=no`)
-- Use `px` for font sizes; use `rem` to respect user settings
-- Default to Inter/Roboto/Open Sans when personality matters
-- Pair fonts that are similar but not identical (two geometric sans-serifs)
-
-## Verify Typography Improvements
-
-- **Hierarchy**: Can you identify heading vs body vs caption instantly?
-- **Readability**: Is body text comfortable to read in long passages?
-- **Consistency**: Are same-role elements styled identically throughout?
-- **Personality**: Does the typography reflect the brand?
-- **Performance**: Are web fonts loading efficiently without layout shift?
-- **Accessibility**: Does text meet WCAG contrast ratios? Is it zoomable to 200%?
-
-When the type carries the hierarchy on its own, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `scale` param controlling the hierarchy ratio. Express all font sizes in the variant's scoped CSS through `calc(var(--p-scale, 1) * <base>)` or, better, scale the type ramp via `clamp(min, calc(var(--p-scale, 1) * Npx), max)`. Users slide from subdued to commanding.
-
-```json
-{"id":"scale","kind":"range","min":0.85,"max":1.3,"step":0.05,"default":1,"label":"Scale"}
-```
-
-Where the variant riffs on a specific pairing, expose the pairing choice as a `steps` param (e.g. "serif display + sans body" vs. "mono display + sans body" vs. "all-sans"). Each branch routes through `:scope[data-p-pairing="X"]` selectors in scoped CSS.
-
-See `reference/live.md` for the full params contract.
@@ -1,159 +0,0 @@
-# Typography
-
-## Classic Typography Principles
-
-### Vertical Rhythm
-
-Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
-
-### Modular Scale & Hierarchy
-
-The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
-
-**Use fewer sizes with more contrast.** A 5-size system covers most needs:
-
-| Role | Typical Ratio | Use Case |
-|------|---------------|----------|
-| xs | 0.75rem | Captions, legal |
-| sm | 0.875rem | Secondary UI, metadata |
-| base | 1rem | Body text |
-| lg | 1.25-1.5rem | Subheadings, lead text |
-| xl+ | 2-4rem | Headlines, hero text |
-
-Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
-
-### Readability & Measure
-
-Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
-
-**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
-
-**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
-
-## Font Selection & Pairing
-
-The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
-
-### Anti-reflexes worth defending against
-
-- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
-- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
-- A children's product does NOT need a rounded display font. Kids' books use real type.
-- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
-
-**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
-
-### Pairing Principles
-
-**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
-
-When pairing, contrast on multiple axes:
-- Serif + Sans (structure contrast)
-- Geometric + Humanist (personality contrast)
-- Condensed display + Wide body (proportion contrast)
-
-**Never pair fonts that are similar but not identical** (e.g., two geometric sans-serifs). They create visual tension without clear hierarchy.
-
-### Web Font Loading
-
-The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
-
-```css
-/* 1. Use font-display: swap for visibility */
-@font-face {
- font-family: 'CustomFont';
- src: url('font.woff2') format('woff2');
- font-display: swap;
-}
-
-/* 2. Match fallback metrics to minimize shift */
-@font-face {
- font-family: 'CustomFont-Fallback';
- src: local('Arial');
- size-adjust: 105%; /* Scale to match x-height */
- ascent-override: 90%; /* Match ascender height */
- descent-override: 20%; /* Match descender depth */
- line-gap-override: 10%; /* Match line spacing */
-}
-
-body {
- font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
-}
-```
-
-Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
-
-**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
-
-**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
-
-**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
-
-## Modern Web Typography
-
-### Fluid Type
-
-Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
-
-**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
-
-**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
-
-**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
-
-**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
-
-### OpenType Features
-
-Most developers don't know these exist. Use them for polish:
-
-```css
-/* Tabular numbers for data alignment */
-.data-table { font-variant-numeric: tabular-nums; }
-
-/* Proper fractions */
-.recipe-amount { font-variant-numeric: diagonal-fractions; }
-
-/* Small caps for abbreviations */
-abbr { font-variant-caps: all-small-caps; }
-
-/* Disable ligatures in code */
-code { font-variant-ligatures: none; }
-
-/* Enable kerning (usually on by default, but be explicit) */
-body { font-kerning: normal; }
-```
-
-Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
-
-### Rendering polish
-
-```css
-/* Even out heading line lengths (browser picks better break points) */
-h1, h2, h3 { text-wrap: balance; }
-
-/* Reduce orphans and ragged endings in long prose */
-article p { text-wrap: pretty; }
-
-/* Variable fonts: pick the right optical-size master automatically */
-body { font-optical-sizing: auto; }
-```
-
-**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
-
-## Typography System Architecture
-
-Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
-
-## Accessibility Considerations
-
-Beyond contrast ratios (which are well-documented), consider:
-
-- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
-- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
-- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
-- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
-
----
-
-**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
@@ -1,107 +0,0 @@
-# UX Writing
-
-## The Button Label Problem
-
-**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
-
-| Bad | Good | Why |
-|-----|------|-----|
-| OK | Save changes | Says what will happen |
-| Submit | Create account | Outcome-focused |
-| Yes | Delete message | Confirms the action |
-| Cancel | Keep editing | Clarifies what "cancel" means |
-| Click here | Download PDF | Describes the destination |
-
-**For destructive actions**, name the destruction:
-- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
-- "Delete 5 items" not "Delete selected" (show the count)
-
-## Error Messages: The Formula
-
-Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
-
-### Error Message Templates
-
-| Situation | Template |
-|-----------|----------|
-| **Format error** | "[Field] needs to be [format]. Example: [example]" |
-| **Missing required** | "Please enter [what's missing]" |
-| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
-| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
-| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
-
-### Don't Blame the User
-
-Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
-
-## Empty States Are Opportunities
-
-Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
-
-## Voice vs Tone
-
-**Voice** is your brand's personality, consistent everywhere.
-**Tone** adapts to the moment.
-
-| Moment | Tone Shift |
-|--------|------------|
-| Success | Celebratory, brief: "Done! Your changes are live." |
-| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
-| Loading | Reassuring: "Saving your work..." |
-| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
-
-**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
-
-## Writing for Accessibility
-
-**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
-
-## Writing for Translation
-
-### Plan for Expansion
-
-German text is ~30% longer than English. Allocate space:
-
-| Language | Expansion |
-|----------|-----------|
-| German | +30% |
-| French | +20% |
-| Finnish | +30-40% |
-| Chinese | -30% (fewer chars, but same width) |
-
-### Translation-Friendly Patterns
-
-Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
-
-## Consistency: The Terminology Problem
-
-Pick one term and stick with it:
-
-| Inconsistent | Consistent |
-|--------------|------------|
-| Delete / Remove / Trash | Delete |
-| Settings / Preferences / Options | Settings |
-| Sign in / Log in / Enter | Sign in |
-| Create / Add / New | Create |
-
-Build a terminology glossary and enforce it. Variety creates confusion.
-
-## Avoid Redundant Copy
-
-If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
-
-## Loading States
-
-Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
-
-## Confirmation Dialogs: Use Sparingly
-
-Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
-
-## Form Instructions
-
-Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
-
----
-
-**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
@@ -1,284 +0,0 @@
-#!/usr/bin/env node
-/**
- * Cleans up deprecated Impeccable skill files, symlinks, and
- * skills-lock.json entries left over from previous versions.
- *
- * Safe to run repeatedly -- it is a no-op when nothing needs cleaning.
- *
- * Usage (from the project root):
- * node {{scripts_path}}/cleanup-deprecated.mjs
- *
- * What it does:
- * 1. Finds every harness-specific skills directory (.claude/skills,
- * .cursor/skills, .agents/skills, etc.).
- * 2. For each deprecated skill name (with and without i- prefix),
- * checks if the directory exists and its SKILL.md mentions
- * "impeccable" (to avoid deleting unrelated user skills).
- * 3. Deletes confirmed matches (files, directories, or symlinks).
- * 4. Removes the corresponding entries from skills-lock.json.
- */
-
-import { existsSync, readFileSync, writeFileSync, rmSync, readdirSync, statSync, lstatSync, unlinkSync } from 'node:fs';
-import { join, resolve } from 'node:path';
-
-// Skills that were renamed, merged, or folded in v2.0, v2.1, and v3.0.
-const DEPRECATED_NAMES = [
- // v2.0 renames
- 'frontend-design', // renamed to impeccable
- 'teach-impeccable', // folded into /impeccable teach
- // v2.1 merges
- 'arrange', // renamed to layout
- 'normalize', // merged into polish
- 'onboard', // merged into harden
- 'extract', // merged into /impeccable extract
- // v3.0 consolidation: all standalone skills -> /impeccable sub-commands
- 'adapt',
- 'animate',
- 'audit',
- 'bolder',
- 'clarify',
- 'colorize',
- 'critique',
- 'delight',
- 'distill',
- 'harden',
- 'layout',
- 'optimize',
- 'overdrive',
- 'polish',
- 'quieter',
- 'shape',
- 'typeset',
-];
-
-// All known harness directories that may contain a skills/ subfolder.
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Per-skill fingerprints for SKILL.md bodies that never mentioned
-// "impeccable" in their v2.x source. Used as a last-resort match
-// when no skills-lock.json exists and the word heuristic fails.
-// The strings are lifted verbatim from the v2.x frontmatter
-// descriptions, so collisions with hand-written user skills are
-// vanishingly unlikely.
-const SKILL_FINGERPRINTS = {
- harden: 'Make interfaces production-ready: error handling, empty states',
- optimize: 'Diagnoses and fixes UI performance across loading speed',
-};
-
-/**
- * Walk up from startDir until we find a directory that looks like a
- * project root (has package.json, .git, or skills-lock.json).
- */
-export function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- const { root } = { root: '/' };
- while (dir !== root) {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Load skills-lock.json from the project root, or null if missing/unreadable.
- */
-export function loadLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return null;
- try {
- return JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return null;
- }
-}
-
-/**
- * Check whether a skill directory belongs to Impeccable. Three layered
- * signals, in order of reliability:
- * 1. Lock source equals "pbakaus/impeccable" (authoritative).
- * 2. SKILL.md body contains the word "impeccable".
- * 3. SKILL.md body contains a per-skill fingerprint (for harden and
- * optimize, whose v2.x SKILL.md never mentioned the pack name).
- */
-export function isImpeccableSkill(skillDir, { skillName, lock } = {}) {
- // 1. Authoritative: the lock file claims this skill is ours.
- if (skillName && lock?.skills?.[skillName]?.source === 'pbakaus/impeccable') {
- return true;
- }
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) return false;
- let content;
- try {
- content = readFileSync(skillMd, 'utf-8');
- } catch {
- return false;
- }
- // 2. Word-level content heuristic.
- if (/impeccable/i.test(content)) return true;
- // 3. Per-skill fingerprint for old skills that never mentioned the pack.
- // Strip the i- prefix so both `harden` and `i-harden` resolve to the
- // same fingerprint entry.
- const unprefixed = skillName?.startsWith('i-') ? skillName.slice(2) : skillName;
- const fingerprint = unprefixed && SKILL_FINGERPRINTS[unprefixed];
- if (fingerprint && content.includes(fingerprint)) return true;
- return false;
-}
-
-/**
- * Build the full list of names to check: each deprecated name, plus
- * its i-prefixed variant.
- */
-export function buildTargetNames() {
- const names = [];
- for (const name of DEPRECATED_NAMES) {
- names.push(name);
- names.push(`i-${name}`);
- }
- return names;
-}
-
-/**
- * Find every skills directory across all harness dirs in the project.
- * Returns absolute paths that exist on disk.
- */
-export function findSkillsDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const candidate = join(projectRoot, harness, 'skills');
- if (existsSync(candidate)) {
- dirs.push(candidate);
- }
- }
- return dirs;
-}
-
-/**
- * Remove deprecated skill directories/symlinks from all harness dirs.
- * Reads skills-lock.json so the authoritative "source" field can
- * drive deletion even when SKILL.md never mentions impeccable.
- * Returns an array of paths that were deleted.
- */
-export function removeDeprecatedSkills(projectRoot, lock) {
- if (lock === undefined) lock = loadLock(projectRoot);
- const targets = buildTargetNames();
- const skillsDirs = findSkillsDirs(projectRoot);
- const deleted = [];
-
- for (const skillsDir of skillsDirs) {
- for (const name of targets) {
- const skillPath = join(skillsDir, name);
-
- // Use lstat to detect symlinks (existsSync follows symlinks and
- // returns false for dangling ones).
- let stat;
- try {
- stat = lstatSync(skillPath);
- } catch {
- continue; // does not exist at all
- }
-
- if (stat.isSymbolicLink()) {
- // Symlink: check the target if it's alive, otherwise treat
- // dangling symlinks to deprecated names as safe to remove.
- const targetAlive = existsSync(skillPath);
- const isMatch = targetAlive
- ? isImpeccableSkill(skillPath, { skillName: name, lock })
- : true;
- if (isMatch) {
- unlinkSync(skillPath);
- deleted.push(skillPath);
- }
- continue;
- }
-
- // Regular directory -- verify it belongs to impeccable
- if (isImpeccableSkill(skillPath, { skillName: name, lock })) {
- rmSync(skillPath, { recursive: true, force: true });
- deleted.push(skillPath);
- }
- }
- }
-
- return deleted;
-}
-
-/**
- * Remove deprecated entries from skills-lock.json.
- * Only removes entries whose source is "pbakaus/impeccable".
- * Returns the list of removed skill names.
- */
-export function cleanSkillsLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return [];
-
- let lock;
- try {
- lock = JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return [];
- }
-
- if (!lock.skills || typeof lock.skills !== 'object') return [];
-
- const targets = buildTargetNames();
- const removed = [];
-
- for (const name of targets) {
- const entry = lock.skills[name];
- if (!entry) continue;
- // Only remove if it belongs to impeccable
- if (entry.source === 'pbakaus/impeccable') {
- delete lock.skills[name];
- removed.push(name);
- }
- }
-
- if (removed.length > 0) {
- writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\n', 'utf-8');
- }
-
- return removed;
-}
-
-/**
- * Run the full cleanup. Returns a summary object.
- *
- * Order matters: read the lock and delete directories first, then
- * strip lock entries. Otherwise the authoritative signal is gone by
- * the time directory deletion runs.
- */
-export function cleanup(projectRoot) {
- const root = projectRoot || findProjectRoot();
- const lock = loadLock(root);
- const deletedPaths = removeDeprecatedSkills(root, lock);
- const removedLockEntries = cleanSkillsLock(root);
- return { deletedPaths, removedLockEntries, projectRoot: root };
-}
-
-// CLI entry point
-if (process.argv[1] && resolve(process.argv[1]) === resolve(new URL(import.meta.url).pathname)) {
- const result = cleanup();
- if (result.deletedPaths.length === 0 && result.removedLockEntries.length === 0) {
- console.log('No deprecated Impeccable skills found. Nothing to clean up.');
- } else {
- if (result.deletedPaths.length > 0) {
- console.log(`Removed ${result.deletedPaths.length} deprecated skill(s):`);
- for (const p of result.deletedPaths) console.log(` - ${p}`);
- }
- if (result.removedLockEntries.length > 0) {
- console.log(`Cleaned ${result.removedLockEntries.length} entry/entries from skills-lock.json:`);
- for (const name of result.removedLockEntries) console.log(` - ${name}`);
- }
- }
-}
@@ -1,94 +0,0 @@
-{
- "craft": {
- "description": "Full confirmed-brief-then-build flow. Runs multi-round shape discovery first, resolves visual probe and north-star mock gates when available, then builds and visually iterates. Use when building a new feature end-to-end.",
- "argumentHint": "[feature description]"
- },
- "teach": {
- "description": "Gathers design context for a project. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles) and, when code exists to analyze, DESIGN.md (visual: colors, typography, components). Every other command reads these files before doing work. Use once per project.",
- "argumentHint": ""
- },
- "document": {
- "description": "Generate a DESIGN.md file that captures the current visual design system. Auto-extracts colors, typography, spacing, radii, and component patterns from the codebase, then asks the user to confirm descriptive language for atmosphere and color character. Follows the Google Stitch DESIGN.md format so the file is tool-compatible. Use when you need a visual design spec an AI agent can follow to stay on-brand.",
- "argumentHint": ""
- },
- "extract": {
- "description": "Pull reusable patterns, components, and design tokens into the design system. Identifies repeated patterns and consolidates them. Use when you have drift across the codebase and want to bring things back to a consistent system.",
- "argumentHint": "[target]"
- },
- "live": {
- "description": "Interactive live variant mode. Select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via HMR. Requires a running dev server. Use when you want to visually experiment with design alternatives in real time.",
- "argumentHint": ""
- },
- "adapt": {
- "description": "Adapt designs to work across different screen sizes, devices, contexts, or platforms. Implements breakpoints, fluid layouts, and touch targets. Use when the user mentions responsive design, mobile layouts, breakpoints, viewport adaptation, or cross-device compatibility.",
- "argumentHint": "[target] [context (mobile, tablet, print...)]"
- },
- "animate": {
- "description": "Review a feature and enhance it with purposeful animations, micro-interactions, and motion effects that improve usability and delight. Use when the user mentions adding animation, transitions, micro-interactions, motion design, hover effects, or making the UI feel more alive.",
- "argumentHint": "[target]"
- },
- "audit": {
- "description": "Run technical quality checks across accessibility, performance, theming, responsive design, and anti-patterns. Generates a scored report with P0-P3 severity ratings and actionable plan. Use when the user wants an accessibility check, performance audit, or technical quality review.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "bolder": {
- "description": "Amplify safe or boring designs to make them more visually interesting and stimulating. Increases impact while maintaining usability. Use when the user says the design looks bland, generic, too safe, lacks personality, or wants more visual impact and character.",
- "argumentHint": "[target]"
- },
- "clarify": {
- "description": "Improve unclear UX copy, error messages, microcopy, labels, and instructions to make interfaces easier to understand. Use when the user mentions confusing text, unclear labels, bad error messages, hard-to-follow instructions, or wanting better UX writing.",
- "argumentHint": "[target]"
- },
- "colorize": {
- "description": "Add strategic color to features that are too monochromatic or lack visual interest, making interfaces more engaging and expressive. Use when the user mentions the design looking gray, dull, lacking warmth, needing more color, or wanting a more vibrant or expressive palette.",
- "argumentHint": "[target]"
- },
- "critique": {
- "description": "Evaluate design from a UX perspective, assessing visual hierarchy, information architecture, emotional resonance, cognitive load, and overall quality with quantitative scoring, persona-based testing, automated anti-pattern detection, and actionable feedback. Use when the user asks to review, critique, evaluate, or give feedback on a design or component.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "delight": {
- "description": "Add moments of joy, personality, and unexpected touches that make interfaces memorable and enjoyable to use. Elevates functional to delightful. Use when the user asks to add polish, personality, animations, micro-interactions, delight, or make an interface feel fun or memorable.",
- "argumentHint": "[target]"
- },
- "distill": {
- "description": "Strip designs to their essence by removing unnecessary complexity. Great design is simple, powerful, and clean. Use when the user asks to simplify, declutter, reduce noise, remove elements, or make a UI cleaner and more focused.",
- "argumentHint": "[target]"
- },
- "harden": {
- "description": "Make interfaces production-ready: error handling, i18n, text overflow, edge case management, and resilience under real-world data. Use when the user asks to harden, make production-ready, handle edge cases, add error states, or fix overflow and i18n issues.",
- "argumentHint": "[target]"
- },
- "onboard": {
- "description": "Design onboarding flows, first-run experiences, and empty states that guide new users to value. Covers welcome screens, account setup, progressive disclosure, contextual tooltips, feature announcements, and activation moments. Use when the user mentions onboarding, first-time users, empty states, activation, getting started, new user flows, or the aha moment.",
- "argumentHint": "[target]"
- },
- "layout": {
- "description": "Improve layout, spacing, and visual rhythm. Fixes monotonous grids, inconsistent spacing, and weak visual hierarchy. Use when the user mentions layout feeling off, spacing issues, visual hierarchy, crowded UI, alignment problems, or wanting better composition.",
- "argumentHint": "[target]"
- },
- "optimize": {
- "description": "Diagnoses and fixes UI performance across loading speed, rendering, animations, images, and bundle size. Use when the user mentions slow, laggy, janky, performance, bundle size, load time, or wants a faster, smoother experience.",
- "argumentHint": "[target]"
- },
- "overdrive": {
- "description": "Pushes interfaces past conventional limits with technically ambitious implementations — shaders, spring physics, scroll-driven reveals, 60fps animations. Use when the user wants to wow, impress, go all-out, or make something that feels extraordinary.",
- "argumentHint": "[target]"
- },
- "polish": {
- "description": "Performs a final quality pass fixing alignment, spacing, consistency, and micro-detail issues before shipping. Use when the user mentions polish, finishing touches, pre-launch review, something looks off, or wants to go from good to great.",
- "argumentHint": "[target]"
- },
- "quieter": {
- "description": "Tones down visually aggressive or overstimulating designs, reducing intensity while preserving quality. Use when the user mentions too bold, too loud, overwhelming, aggressive, garish, or wants a calmer, more refined aesthetic.",
- "argumentHint": "[target]"
- },
- "shape": {
- "description": "Plan UX and UI before code. Runs a required multi-round discovery interview, uses visual probes when available, and produces a user-confirmed design brief for implementation.",
- "argumentHint": "[feature to shape]"
- },
- "typeset": {
- "description": "Improves typography by fixing font choices, hierarchy, sizing, weight, and readability so text feels intentional. Use when the user mentions fonts, type, readability, text hierarchy, sizing looks off, or wants more polished, intentional typography.",
- "argumentHint": "[target]"
- }
-}
@@ -1,242 +0,0 @@
-#!/usr/bin/env node
-/**
- * Critique persistence helper.
- *
- * Each run of /impeccable critique writes a per-target snapshot to
- * .impeccable/critique/<timestamp>__<slug>.md
- * with a small YAML frontmatter carrying the score + P0/P1 counts.
- *
- * /impeccable polish reads the latest matching snapshot at start as its
- * fix backlog. No other skill auto-reads critique output.
- *
- * The slug is derived mechanically from the *resolved* primary artifact
- * (file path or URL), never from the user's natural-language phrasing.
- * Slug stability across runs is what lets the trend display work.
- *
- * CLI entry points (called from skill instructions):
- * node critique-storage.mjs slug <resolved-target>
- * node critique-storage.mjs write <slug> <snapshot-body-file>
- * node critique-storage.mjs latest <slug>
- * node critique-storage.mjs trend <slug> [limit]
- *
- * Note: there is intentionally no `ignore` subcommand. ignore.md is a plain
- * markdown file; the model reads it directly with its file-read tool. This
- * helper only exists for operations the model can't trivially do inline
- * (normalizing paths, generating filenames, globbing + parsing frontmatter).
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath, pathToFileURL } from 'node:url';
-import { getCritiqueDir } from './impeccable-paths.mjs';
-
-const SLUG_MAX = 50;
-
-/**
- * Mechanically derive a slug from a resolved target. Returns null if the
- * input doesn't look like a stable identifier (empty, project root, etc).
- *
- * Accepts file paths and URLs. The model resolves "the homepage" to a
- * concrete artifact before calling this — we never slug a natural-language
- * phrase.
- */
-export function slugFromTarget(resolved, { cwd = process.cwd() } = {}) {
- if (!resolved || typeof resolved !== 'string') return null;
- const trimmed = resolved.trim();
- if (!trimmed) return null;
-
- // URL
- if (/^https?:\/\//i.test(trimmed)) {
- let url;
- try { url = new URL(trimmed); } catch { return null; }
- const hostPath = `${url.hostname}${url.pathname}`;
- return kebab(hostPath);
- }
-
- // File path. Make it project-relative so two devs critiquing the same
- // checkout get the same slug regardless of where their repo is cloned.
- const abs = path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- let rel = path.relative(cwd, abs);
- // If the target is outside cwd, fall back to the basename so we still
- // produce a stable slug (vs the absolute path, which would include
- // home dirs / usernames).
- if (rel.startsWith('..') || path.isAbsolute(rel)) {
- rel = path.basename(abs);
- }
- if (!rel || rel === '.' || rel === '') return null;
- return kebab(rel);
-}
-
-function kebab(s) {
- const slug = s
- .toLowerCase()
- .replace(/[/\\.]+/g, '-')
- .replace(/[^a-z0-9-]+/g, '-')
- .replace(/-+/g, '-')
- .replace(/^-|-$/g, '');
- if (!slug) return null;
- // Cap from the tail — the tail (filename) is more identifying than the
- // top-level directory.
- return slug.length <= SLUG_MAX ? slug : slug.slice(slug.length - SLUG_MAX).replace(/^-/, '');
-}
-
-/**
- * Filename-safe UTC ISO timestamp: hyphens for separators, trailing Z.
- * Plain colons aren't allowed on Windows filesystems.
- */
-export function nowFilenameStamp(date = new Date()) {
- const iso = date.toISOString(); // 2026-05-12T18:30:00.123Z
- return iso.replace(/[:.]/g, '-').replace(/-\d+Z$/, 'Z');
-}
-
-/**
- * Write a snapshot for `slug`. `meta` carries the small structured frontmatter
- * keys read back by readTrend(). `body` is the human-readable critique
- * report (everything below the frontmatter).
- *
- * Returns the absolute path written.
- */
-export function writeSnapshot({ slug, meta, body, cwd = process.cwd(), now = new Date() }) {
- if (!slug) throw new Error('writeSnapshot requires a slug');
- const dir = getCritiqueDir(cwd);
- fs.mkdirSync(dir, { recursive: true });
- const timestamp = nowFilenameStamp(now);
- const filePath = path.join(dir, `${timestamp}__${slug}.md`);
- // Spread `meta` first so internally computed `timestamp` and `slug`
- // always win. Otherwise a caller-supplied meta blob (parsed from the
- // IMPECCABLE_CRITIQUE_META env var) could clobber them, leaving the
- // filename in disagreement with its frontmatter and corrupting trends.
- const front = serializeFrontmatter({ ...meta, timestamp, slug });
- fs.writeFileSync(filePath, `${front}\n${body.trim()}\n`, 'utf-8');
- return filePath;
-}
-
-function serializeFrontmatter(obj) {
- const lines = ['---'];
- for (const [key, value] of Object.entries(obj)) {
- if (value === undefined || value === null) continue;
- const str = typeof value === 'string' ? value : String(value);
- // Quote strings that contain : or # to keep parsing simple.
- const needsQuotes = typeof value === 'string' && /[:#]/.test(str);
- lines.push(`${key}: ${needsQuotes ? JSON.stringify(str) : str}`);
- }
- lines.push('---');
- return lines.join('\n');
-}
-
-function parseFrontmatter(text) {
- const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
- if (!match) return {};
- const out = {};
- for (const line of match[1].split(/\r?\n/)) {
- const colon = line.indexOf(':');
- if (colon < 0) continue;
- const key = line.slice(0, colon).trim();
- let value = line.slice(colon + 1).trim();
- if (/^".*"$/.test(value)) {
- try { value = JSON.parse(value); } catch { /* leave as-is */ }
- } else if (/^-?\d+$/.test(value)) {
- value = Number(value);
- }
- out[key] = value;
- }
- return out;
-}
-
-/**
- * Return all snapshot files for `slug`, sorted oldest → newest.
- */
-function listSnapshotsForSlug(slug, cwd) {
- const dir = getCritiqueDir(cwd);
- if (!fs.existsSync(dir)) return [];
- const suffix = `__${slug}.md`;
- return fs.readdirSync(dir)
- .filter((f) => f.endsWith(suffix))
- .sort()
- .map((f) => path.join(dir, f));
-}
-
-/**
- * Return the most recent snapshot for `slug`, or null. Polish reads this
- * to find its fix backlog when the slug matches.
- */
-export function readLatestSnapshot(slug, { cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- if (!all.length) return null;
- const latest = all[all.length - 1];
- const body = fs.readFileSync(latest, 'utf-8');
- return { path: latest, body, meta: parseFrontmatter(body) };
-}
-
-/**
- * Return the last `limit` snapshots' frontmatter, oldest → newest.
- * Critique appends a one-line trend to its output using this.
- */
-export function readTrend(slug, { limit = 5, cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- const slice = all.slice(-limit);
- return slice.map((file) => parseFrontmatter(fs.readFileSync(file, 'utf-8')));
-}
-
-// ---- CLI ---------------------------------------------------------------
-
-function main(argv) {
- const [cmd, ...args] = argv;
- switch (cmd) {
- case 'slug': {
- const slug = slugFromTarget(args[0]);
- if (!slug) { process.stderr.write('no stable slug for input\n'); process.exit(1); }
- process.stdout.write(`${slug}\n`);
- return;
- }
- case 'write': {
- const [slug, bodyFile] = args;
- if (!slug || !bodyFile) { process.stderr.write('usage: write <slug> <body-file>\n'); process.exit(1); }
- const raw = fs.readFileSync(bodyFile, 'utf-8');
- // The body file may be a full report. The caller passes the meta as
- // a JSON object on stdin if it wants structured frontmatter; otherwise
- // we write with minimal metadata.
- let meta = {};
- const metaArg = process.env.IMPECCABLE_CRITIQUE_META;
- if (metaArg) {
- try { meta = JSON.parse(metaArg); } catch { /* ignore */ }
- }
- const out = writeSnapshot({ slug, meta, body: raw });
- process.stdout.write(`${out}\n`);
- return;
- }
- case 'latest': {
- const latest = readLatestSnapshot(args[0]);
- if (!latest) { process.exit(2); }
- process.stdout.write(latest.body);
- return;
- }
- case 'trend': {
- const rows = readTrend(args[0], { limit: args[1] ? Number(args[1]) : 5 });
- process.stdout.write(JSON.stringify(rows, null, 2) + '\n');
- return;
- }
- default:
- process.stderr.write('usage: critique-storage.mjs <slug|write|latest|trend> [args]\n');
- process.exit(1);
- }
-}
-
-function isMainModule() {
- if (!process.argv[1]) return false;
- try {
- return fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1]);
- } catch {
- // pathToFileURL normalizes Windows paths; keep it as a fallback for any
- // environment where realpath is unavailable.
- return import.meta.url === pathToFileURL(process.argv[1]).href;
- }
-}
-
-// Why the realpath check: generated skills are often reached through symlinked
-// harness directories (for example a demo repo's `.agents` -> source `.agents`).
-// Node resolves import.meta.url to the real file, while process.argv[1] keeps
-// the symlink path. Comparing canonical paths prevents a silent exit-0 no-op.
-if (isMainModule()) {
- main(process.argv.slice(2));
-}
@@ -1,820 +0,0 @@
-// Parse a DESIGN.md (Stitch-spec format) into a structured JSON model that
-// the live-mode design-system panel can render. Deterministic, dependency-free.
-//
-// Two-layer: YAML frontmatter (machine-readable tokens) + markdown body
-// (prose with six canonical H2 sections). When frontmatter is present, it's
-// exposed on `model.frontmatter` alongside the prose-scraped sections;
-// consumers can prefer frontmatter values and fall back to prose.
-
-const CANONICAL_SECTIONS = [
- 'Overview',
- 'Colors',
- 'Typography',
- 'Elevation',
- 'Components',
- "Do's and Don'ts",
-];
-
-// ---------- Frontmatter (Stitch YAML subset) ----------
-
-function parseFrontmatter(md) {
- const lines = md.split(/\r?\n/);
- if (lines[0]?.trim() !== '---') return { frontmatter: null, body: md };
-
- let end = -1;
- for (let i = 1; i < lines.length; i++) {
- if (lines[i].trim() === '---') { end = i; break; }
- }
- if (end === -1) return { frontmatter: null, body: md };
-
- const yaml = lines.slice(1, end).join('\n');
- const body = lines.slice(end + 1).join('\n');
- try {
- return { frontmatter: parseYamlSubset(yaml), body };
- } catch {
- return { frontmatter: null, body: md };
- }
-}
-
-// Minimal YAML reader for the Stitch frontmatter subset: scalar maps with
-// one level of nested objects (typography roles, components). Indent-based,
-// 2-space convention. No arrays, no anchors, no multi-line scalars — Stitch's
-// schema doesn't need them and accepting them would require a real YAML
-// dependency we don't want to vendor.
-function parseYamlSubset(yaml) {
- const lines = yaml.split(/\r?\n/);
- const root = {};
- const stack = [{ indent: -1, obj: root }];
-
- for (const raw of lines) {
- // Skip blanks and line-only comments. Don't strip inline comments:
- // unquoted hex values start with `#` and can't be safely distinguished
- // from a comment after whitespace.
- if (!raw.trim() || /^\s*#/.test(raw)) continue;
-
- const indent = raw.match(/^\s*/)[0].length;
- const content = raw.slice(indent);
-
- const colonIdx = findTopLevelColon(content);
- if (colonIdx === -1) continue;
-
- while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
- stack.pop();
- }
-
- const key = content.slice(0, colonIdx).trim();
- const rest = content.slice(colonIdx + 1).trim();
- const parent = stack[stack.length - 1].obj;
-
- if (rest === '') {
- const obj = {};
- parent[key] = obj;
- stack.push({ indent, obj });
- } else {
- parent[key] = parseScalar(rest);
- }
- }
-
- return root;
-}
-
-function findTopLevelColon(s) {
- let inQuote = null;
- for (let i = 0; i < s.length; i++) {
- const ch = s[i];
- if (inQuote) {
- if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
- } else if (ch === '"' || ch === "'") {
- inQuote = ch;
- } else if (ch === ':') {
- return i;
- }
- }
- return -1;
-}
-
-function parseScalar(raw) {
- const s = raw.trim();
- if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
- return s.slice(1, -1);
- }
- if (s === 'true') return true;
- if (s === 'false') return false;
- if (s === 'null' || s === '~') return null;
- if (/^-?\d+$/.test(s)) return Number(s);
- if (/^-?\d*\.\d+$/.test(s)) return Number(s);
- return s;
-}
-
-const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
-const OKLCH_RE = /oklch\([^)]+\)/gi;
-const RGBA_RE = /rgba?\([^)]+\)/gi;
-const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
-const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
-
-// ---------- Section splitting ----------
-
-function splitSections(md) {
- const lines = md.split(/\r?\n/);
- let title = null;
- const sections = {};
- let current = null;
-
- for (const raw of lines) {
- const line = raw.trimEnd();
-
- if (!title && line.startsWith('# ') && !line.startsWith('## ')) {
- title = line.replace(/^#\s+/, '').trim();
- continue;
- }
-
- const h2 = line.match(/^##\s+(?:\d+\.\s*)?([^:\n]+?)(?::\s*(.+))?$/);
- if (h2) {
- const rawName = normalizeApostrophes(h2[1].trim());
- const subtitle = h2[2] ? h2[2].trim() : null;
- const canonical = matchCanonicalSection(rawName);
- if (canonical) {
- current = { name: canonical, subtitle, lines: [] };
- sections[canonical] = current;
- continue;
- }
- // non-canonical H2 — ignore but stop feeding into current
- current = null;
- continue;
- }
-
- if (current) current.lines.push(raw);
- }
-
- return { title, sections };
-}
-
-function normalizeApostrophes(s) {
- return s.replace(/[\u2018\u2019]/g, "'");
-}
-
-function matchCanonicalSection(name) {
- const normalized = normalizeApostrophes(name).toLowerCase();
- // Exact match first
- for (const c of CANONICAL_SECTIONS) {
- if (normalizeApostrophes(c).toLowerCase() === normalized) return c;
- }
- // Keyword-contained match: "Overview & Creative North Star" -> "Overview",
- // "Elevation & Depth" -> "Elevation", etc.
- for (const c of CANONICAL_SECTIONS) {
- const key = normalizeApostrophes(c).toLowerCase();
- const pattern = new RegExp(`\\b${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
- if (pattern.test(normalized)) return c;
- }
- return null;
-}
-
-// ---------- Subsection splitting (inside a canonical section) ----------
-
-function splitSubsections(lines) {
- const subs = [];
- let current = { name: null, lines: [] };
- subs.push(current);
-
- for (const raw of lines) {
- const h3 = raw.match(/^###\s+(.+?)\s*$/);
- if (h3) {
- current = { name: h3[1].trim(), lines: [] };
- subs.push(current);
- continue;
- }
- current.lines.push(raw);
- }
-
- return subs;
-}
-
-// ---------- Generic helpers ----------
-
-function collectParagraphs(lines) {
- const paragraphs = [];
- let buf = [];
- const flush = () => {
- if (buf.length) {
- paragraphs.push(buf.join(' ').trim());
- buf = [];
- }
- };
- for (const raw of lines) {
- const trimmed = raw.trim();
- if (trimmed === '') { flush(); continue; }
- // Horizontal rules (---, ***) and headings/bullets end a paragraph.
- if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { flush(); continue; }
- if (raw.startsWith('#') || raw.match(/^[-*]\s/)) { flush(); continue; }
- buf.push(trimmed);
- }
- flush();
- return paragraphs.filter(Boolean);
-}
-
-function collectBullets(lines) {
- const bullets = [];
- let current = null;
- for (const raw of lines) {
- const m = raw.match(/^\s*[-*]\s+(.+)$/);
- if (m) {
- if (current) bullets.push(current);
- current = m[1];
- continue;
- }
- // continuation of a bullet (indented line)
- if (current && raw.match(/^\s{2,}\S/)) {
- current += ' ' + raw.trim();
- continue;
- }
- // blank line ends a bullet
- if (raw.trim() === '' && current) {
- bullets.push(current);
- current = null;
- }
- }
- if (current) bullets.push(current);
- return bullets;
-}
-
-function stripBold(s) {
- return s.replace(/\*\*(.+?)\*\*/g, '$1');
-}
-
-function extractNamedRules(lines) {
- const rules = [];
- const seen = new Set();
-
- // Style A (Impeccable): "**The X Rule.** body body body" — can span lines.
- const joined = lines.join('\n');
- const inlineStart = /\*\*(The [^*]+?Rule)\.\*\*/g;
- const inlineMatches = [];
- let m;
- while ((m = inlineStart.exec(joined)) !== null) {
- inlineMatches.push({ name: m[1], start: m.index, end: inlineStart.lastIndex });
- }
- for (let i = 0; i < inlineMatches.length; i++) {
- const mm = inlineMatches[i];
- const bodyEnd = i + 1 < inlineMatches.length ? inlineMatches[i + 1].start : joined.length;
- const body = joined
- .slice(mm.end, bodyEnd)
- .replace(/\n##[^\n]*$/s, '')
- .replace(/\n###[^\n]*$/s, '')
- .trim();
- const name = stripBold(mm.name).trim();
- seen.add(name.toLowerCase());
- rules.push({ name, body: stripBold(body) });
- }
-
- // Style B (Stitch): `### The "X" Rule` or `### The X Fallback`, body is the
- // bullets/paragraphs until the next heading. Accept Rule / Fallback / Principle.
- for (let i = 0; i < lines.length; i++) {
- const h3 = lines[i].match(/^###\s+(.+?)\s*$/);
- if (!h3) continue;
- const headerName = stripBold(h3[1]).replace(/["“”]/g, '').trim();
- if (!/^The\b.*\b(Rule|Fallback|Principle)\b/i.test(headerName)) continue;
- if (seen.has(headerName.toLowerCase())) continue;
-
- const bodyLines = [];
- for (let j = i + 1; j < lines.length; j++) {
- if (/^##\s|^###\s/.test(lines[j])) break;
- bodyLines.push(lines[j]);
- }
- const body = stripBold(bodyLines.join('\n').replace(/\n+/g, ' ')).trim();
- if (body) {
- seen.add(headerName.toLowerCase());
- rules.push({ name: headerName, body });
- }
- }
-
- // Style C (Stitch bullet form): "* **The Layering Principle:** body"
- // Colon/period lives inside the bold, so match "**...**" then inspect.
- for (const b of collectBullets(lines)) {
- const mm = b.match(/^\*\*([^*]+?)\*\*\s*(.+)$/);
- if (!mm) continue;
- const nameRaw = mm[1].replace(/[.:]\s*$/, '').replace(/["“”]/g, '').trim();
- if (!/^The\b.+\b(Rule|Fallback|Principle)$/i.test(nameRaw)) continue;
- if (seen.has(nameRaw.toLowerCase())) continue;
- seen.add(nameRaw.toLowerCase());
- rules.push({ name: nameRaw, body: stripBold(mm[2]).trim() });
- }
-
- return rules;
-}
-
-// ---------- Per-section extractors ----------
-
-function extractOverview(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
- const northStar = text.match(/\*\*Creative North Star:\s*"([^"]+)"\*\*/);
- const keyChars = [];
- const keyCharMatch = text.match(/\*\*Key Characteristics:\*\*\s*\n([\s\S]+?)(?:\n##|\n###|$)/);
- if (keyCharMatch) {
- for (const line of keyCharMatch[1].split('\n')) {
- const m = line.match(/^\s*[-*]\s+(.+)$/);
- if (m) keyChars.push(stripBold(m[1].trim()));
- }
- }
-
- // Philosophy paragraphs: everything that isn't a rule header or key-char block
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) =>
- !p.startsWith('**Creative North Star') &&
- !p.startsWith('**Key Characteristics')
- );
-
- return {
- subtitle: section.subtitle,
- creativeNorthStar: northStar ? northStar[1] : null,
- philosophy: paragraphs,
- keyCharacteristics: keyChars,
- };
-}
-
-function extractColors(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ');
- const groups = [];
- const ROLE_KEYWORDS = /^(primary|secondary|tertiary|neutral|accent)\b/i;
-
- for (const sub of subs.slice(1)) {
- if (!sub.name || /Named Rules?/i.test(sub.name) || /^The\s/i.test(sub.name)) continue;
-
- const bullets = collectBullets(sub.lines);
- const parsed = bullets.map((b) => parseColorBullet(b)).filter(Boolean);
- if (parsed.length === 0) continue;
-
- // If every bullet starts with a role keyword (Primary/Secondary/...), promote
- // each bullet to its own group. Otherwise keep the subsection as the group.
- const allRoleBullets =
- parsed.length > 0 && parsed.every((p) => p.name && ROLE_KEYWORDS.test(p.name));
-
- if (allRoleBullets) {
- for (const p of parsed) {
- groups.push({ role: p.name, colors: [p] });
- }
- } else {
- groups.push({ role: sub.name, colors: parsed });
- }
- }
-
- // If the Colors section has no subsections at all (unlikely), fall back to
- // scanning the whole section as a flat bullet list.
- if (groups.length === 0) {
- const flat = collectBullets(section.lines)
- .map((b) => parseColorBullet(b))
- .filter(Boolean);
- if (flat.length) {
- for (const p of flat) {
- if (p.name && ROLE_KEYWORDS.test(p.name)) {
- groups.push({ role: p.name, colors: [p] });
- } else {
- const fallback = groups.find((g) => g.role === 'Palette');
- if (fallback) fallback.colors.push(p);
- else groups.push({ role: 'Palette', colors: [p] });
- }
- }
- }
- }
-
- return {
- subtitle: section.subtitle,
- description: description || null,
- groups,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function parseColorBullet(bullet) {
- const text = bullet.trim();
-
- // Case 1 (Impeccable): **Name** (value-with-maybe-nested-parens): description
- const bold = text.match(/^\*\*(.+?)\*\*\s*(.*)$/);
- if (bold && bold[2].startsWith('(')) {
- const value = extractParenGroup(bold[2]);
- if (value !== null) {
- const after = bold[2].slice(value.length + 2).trimStart();
- if (after.startsWith(':')) {
- return buildColor(bold[1], value, after.slice(1).trim());
- }
- }
- }
-
- // Case 2 (Stitch): **Name (values):** description — value embedded in bold.
- const stitch = text.match(/^\*\*([^*]+?)\s*\(([^)]+)\):\*\*\s*(.*)$/);
- if (stitch) {
- return buildColor(stitch[1].trim(), stitch[2], stitch[3]);
- }
-
- // Case 3: bullet without bold, just hex/oklch inside.
- const values = collectColorValues(text);
- if (values.length) {
- return buildColor(null, values.join(' to '), text);
- }
- return null;
-}
-
-function extractParenGroup(s) {
- if (s[0] !== '(') return null;
- let depth = 0;
- for (let i = 0; i < s.length; i++) {
- if (s[i] === '(') depth++;
- else if (s[i] === ')') {
- depth--;
- if (depth === 0) return s.slice(1, i);
- }
- }
- return null;
-}
-
-function buildColor(name, rawValue, description) {
- const values = collectColorValues(rawValue);
- const primary = values[0] ?? rawValue.trim();
- return {
- name: name ? stripBold(name).trim() : null,
- value: primary,
- valueRange: values.length > 1 ? values : null,
- format: detectFormat(primary),
- description: stripBold(description || '').trim() || null,
- };
-}
-
-function collectColorValues(s) {
- const out = [];
- s.replace(HEX_RE, (v) => {
- out.push(v);
- return v;
- });
- s.replace(OKLCH_RE, (v) => {
- out.push(v);
- return v;
- });
- return out;
-}
-
-function detectFormat(v) {
- if (!v) return 'unknown';
- if (v.startsWith('#')) return 'hex';
- if (/^oklch/i.test(v)) return 'oklch';
- if (/^rgb/i.test(v)) return 'rgb';
- return 'unknown';
-}
-
-function scanInlineColors(lines) {
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '');
- const color = parseColorBullet(trimmed);
- if (color) out.push(color);
- }
- return out;
-}
-
-function parseStitchInlineGroups(lines) {
- // Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
- // Each bullet IS its own role. Group them under the spoken role name.
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
- const m = trimmed.match(
- /^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
- );
- if (m) {
- const role = m[1];
- const color = buildColor(role, m[2], m[3]);
- out.push({ role, colors: [color] });
- }
- }
- return out;
-}
-
-function extractTypography(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
-
- const fonts = {};
- // Pattern A: **Display Font:** Family (with fallback)
- const fontLineRe = /\*\*([\w\s/]+?)Font:\*\*\s*([^\n(]+?)(?:\s*\(with\s+([^)]+)\))?\s*$/gm;
- let fm;
- while ((fm = fontLineRe.exec(text)) !== null) {
- const rawRole = fm[1].trim().toLowerCase().replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || 'display';
- fonts[role] = {
- family: fm[2].trim(),
- fallback: fm[3] ? fm[3].trim() : null,
- };
- }
-
- // Pattern B (Stitch): * **Display & Headlines (Noto Serif):** description
- if (Object.keys(fonts).length === 0) {
- const stitchRe = /\*\*([\w\s&/]+?)\s*\(([^)]+)\):\*\*\s*(.+)/g;
- let sm;
- while ((sm = stitchRe.exec(text)) !== null) {
- const rawRole = sm[1]
- .trim()
- .toLowerCase()
- .replace(/\s*&\s*/g, '-')
- .replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || rawRole;
- fonts[role] = { family: sm[2].trim(), fallback: null, purpose: sm[3].trim() };
- }
- }
-
- // Character paragraph — either a **Character:** label, or fall back to the
- // first free paragraph under the section header (Stitch style).
- const characterMatch = text.match(/\*\*Character:\*\*\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\n|\n###|\n##|$)/);
- let character = characterMatch ? characterMatch[1].replace(/\n/g, ' ').trim() : null;
- if (!character) {
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) => !/^\*\*[\w\s/&]+Font/i.test(p) && !/^\*\*[\w\s/&]+\([^)]+\)/.test(p)
- );
- if (paragraphs.length) character = paragraphs[0];
- }
-
- // Hierarchy bullets under ### Hierarchy
- const subs = splitSubsections(section.lines);
- let hierarchy = [];
- const hierSub = subs.find((s) => s.name && /hierarch/i.test(s.name));
- if (hierSub) {
- const bullets = collectBullets(hierSub.lines);
- hierarchy = bullets.map(parseTypeBullet).filter(Boolean);
- }
-
- return {
- subtitle: section.subtitle,
- fonts,
- character,
- hierarchy,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function normalizeFontRole(raw) {
- // Canonical roles the panel cares about: display, body, label, mono.
- // Stitch often writes compound roles like "display-&-headlines" or "ui-&-body"
- // — collapse them to the first canonical role present.
- const tokens = raw.split(/[-/&\s]+/).filter(Boolean);
- const priority = ['display', 'headline', 'body', 'ui', 'label', 'mono'];
- const canonical = { headline: 'display', ui: 'body' };
- for (const p of priority) {
- if (tokens.includes(p)) return canonical[p] || p;
- }
- return null;
-}
-
-function parseTypeBullet(bullet) {
- // - **Display** (family, weight 300, italic, clamp(...), line-height 1): purpose
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(([^)]+)\):\s*(.*)$/);
- if (!m) return null;
- const name = m[1].trim();
- const specs = m[2].split(',').map((s) => s.trim());
- return {
- name,
- specs,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractElevation(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ') || null;
-
- const shadows = [];
- const seen = new Set();
- const dedupe = (entry) => {
- const key = (entry.name || '') + '::' + entry.value;
- if (seen.has(key)) return;
- seen.add(key);
- shadows.push(entry);
- };
-
- for (const b of collectBullets(section.lines)) {
- const parsed = parseShadowBullet(b);
- if (parsed) dedupe(parsed);
- }
-
- // Fallback: extract shadows written inline in prose. Stitch style is
- // "...use an extra-diffused shadow: `box-shadow: 0 12px 40px rgba(...)`."
- for (const p of collectParagraphs(section.lines)) {
- for (const inline of extractInlineShadows(p)) dedupe(inline);
- }
- for (const b of collectBullets(section.lines)) {
- for (const inline of extractInlineShadows(b)) dedupe(inline);
- }
-
- return {
- subtitle: section.subtitle,
- description,
- shadows,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function extractInlineShadows(text) {
- // Find `box-shadow: ...` anywhere in prose and capture the value. Work on the
- // raw string so it handles both backtick-fenced and unfenced variants.
- const out = [];
- const re = /box-shadow\s*:\s*([^`;\n]+)/gi;
- let m;
- while ((m = re.exec(text)) !== null) {
- const value = m[1].replace(/[`.)]+$/, '').trim();
- if (!value) continue;
- // Name heuristic: the noun immediately before the shadow phrase.
- // e.g. "an extra-diffused shadow: ..." -> "extra-diffused shadow"
- const before = text.slice(0, m.index);
- const nameMatch = before.match(/\b([A-Za-z][A-Za-z\- ]{2,40})\s+shadow\b[^A-Za-z0-9]*$/i);
- let name = null;
- if (nameMatch) {
- const stripped = nameMatch[1]
- .replace(/^(?:use|using|apply|applying|is|are|looks? like)\s+/i, '')
- .replace(/^(?:a|an|the)\s+/i, '')
- .trim();
- if (stripped) {
- name =
- stripped.charAt(0).toUpperCase() + stripped.slice(1) + ' shadow';
- }
- }
- out.push({
- name,
- value,
- purpose: null,
- });
- }
- return out;
-}
-
-function parseShadowBullet(bullet) {
- // - **Name** (`box-shadow: value`): purpose
- // - **Name** (`value`): purpose
- // Only accept if the paren content looks like a shadow value (contains px,
- // rem, rgba, or box-shadow). This filters out `**Rule Name:**` bullets.
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(`?([^`]+?)`?\):\s*(.*)$/);
- if (!m) return null;
- const rawValue = m[2].replace(/^box-shadow:\s*/i, '').trim();
- const looksLikeShadow =
- /box-shadow|rgba?\(|\bpx\b|\brem\b|^-?\d+\s/i.test(rawValue) &&
- /\d/.test(rawValue);
- if (!looksLikeShadow) return null;
- const name = stripBold(m[1]).trim();
- return {
- name,
- value: rawValue,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractComponents(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const components = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
-
- const bullets = collectBullets(sub.lines);
- const paragraphs = collectParagraphs(sub.lines);
-
- const variants = [];
- const properties = {};
-
- for (const b of bullets) {
- // - **Key:** value
- const m = b.match(/^\*\*(.+?):?\*\*:?\s*(.+)$/);
- if (m) {
- const key = stripBold(m[1]).trim();
- const value = stripBold(m[2]).trim();
- // Heuristic: "Primary", "Secondary", "Hover", "Focus" etc are variants;
- // "Shape", "Background", "Padding" are properties.
- if (/^(primary|secondary|tertiary|ghost|hover|focus|active|disabled|default|error|selected|unselected|state)$/i.test(key.split(/[\s/]/)[0])) {
- variants.push({ name: key, description: value });
- } else {
- properties[key.toLowerCase()] = value;
- }
- }
- }
-
- components.push({
- name: sub.name,
- description: paragraphs.join(' ') || null,
- properties,
- variants,
- });
- }
-
- return {
- subtitle: section.subtitle,
- components,
- };
-}
-
-function extractDosDonts(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const dos = [];
- const donts = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
- const subName = normalizeApostrophes(sub.name);
- const bullets = collectBullets(sub.lines).map((b) => stripBold(b).trim());
- if (/^do'?t?:?$/i.test(subName) || /^do:?$/i.test(subName)) {
- dos.push(...bullets);
- } else if (/^don'?t:?$/i.test(subName)) {
- donts.push(...bullets);
- }
- }
-
- // Classify by bullet prefix as a backup (catches loose bullets outside H3 wrappers)
- for (const b of collectBullets(section.lines)) {
- const stripped = normalizeApostrophes(stripBold(b).trim());
- if (/^don'?t\b/i.test(stripped)) {
- if (!donts.some((d) => normalizeApostrophes(d) === stripped)) donts.push(stripped);
- } else if (/^do\b/i.test(stripped)) {
- if (!dos.some((d) => normalizeApostrophes(d) === stripped)) dos.push(stripped);
- }
- }
-
- return { dos, donts };
-}
-
-// ---------- Coverage assessment ----------
-
-function assessCoverage(model) {
- const report = {};
-
- report.overview = model.overview
- ? {
- northStar: Boolean(model.overview.creativeNorthStar),
- philosophy: model.overview.philosophy.length > 0,
- keyCharacteristics: model.overview.keyCharacteristics.length,
- }
- : 'missing';
-
- report.colors = model.colors
- ? {
- groups: model.colors.groups.length,
- totalColors: model.colors.groups.reduce((n, g) => n + g.colors.length, 0),
- rules: model.colors.rules.length,
- }
- : 'missing';
-
- report.typography = model.typography
- ? {
- fonts: Object.keys(model.typography.fonts).length,
- hierarchyEntries: model.typography.hierarchy.length,
- character: Boolean(model.typography.character),
- rules: model.typography.rules.length,
- }
- : 'missing';
-
- report.elevation = model.elevation
- ? {
- shadows: model.elevation.shadows.length,
- rules: model.elevation.rules.length,
- description: Boolean(model.elevation.description),
- }
- : 'missing';
-
- report.components = model.components
- ? {
- count: model.components.components.length,
- variantTotal: model.components.components.reduce((n, c) => n + c.variants.length, 0),
- }
- : 'missing';
-
- report.dosDonts = model.dosDonts
- ? {
- dos: model.dosDonts.dos.length,
- donts: model.dosDonts.donts.length,
- }
- : 'missing';
-
- return report;
-}
-
-// ---------- Main ----------
-
-export function parseDesignMd(md) {
- const { frontmatter, body } = parseFrontmatter(md);
- const { title, sections } = splitSections(body);
- return {
- schemaVersion: 2,
- title,
- frontmatter,
- overview: extractOverview(sections['Overview']),
- colors: extractColors(sections['Colors']),
- typography: extractTypography(sections['Typography']),
- elevation: extractElevation(sections['Elevation']),
- components: extractComponents(sections['Components']),
- dosDonts: extractDosDonts(sections["Do's and Don'ts"]),
- };
-}
-
-export { assessCoverage };
@@ -1,198 +0,0 @@
-/**
- * Scan a project tree for Content-Security-Policy signals and classify the
- * shape so the agent knows which patch template to propose.
- *
- * Used at first-time `live.mjs` setup. Mechanical (grep-based) — no network,
- * no dev server, no JS evaluation. The classification drives a user-facing
- * consent prompt; the agent does the actual patch writing.
- *
- * Shapes are named by patch mechanism, not framework origin:
- * - "append-arrays": CSP defined as structured directive arrays. Patch
- * appends a dev-only localhost entry. Covers:
- * - Monorepo helpers with additional*Src options
- * (e.g. createBaseNextConfig for Next)
- * - SvelteKit kit.csp.directives
- * - nuxt-security module's contentSecurityPolicy
- * - "append-string": CSP built as a literal value string. Patch splices
- * a dev-only token into script-src and connect-src.
- * Covers:
- * - Inline Next.js headers() with CSP string
- * - Nuxt routeRules / nitro.routeRules CSP headers
- * - "middleware": CSP set dynamically in middleware.{ts,js}.
- * Detected but not auto-patched in v1.
- * - "meta-tag": <meta http-equiv="Content-Security-Policy"> in
- * layout files. Detected but not auto-patched in v1.
- * - null: no CSP signals found; no patch needed.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const SKIP_DIRS = new Set([
- 'node_modules',
- '.git',
- '.next',
- '.turbo',
- '.svelte-kit',
- '.nuxt',
- '.astro',
- 'dist',
- 'build',
- 'out',
- '.vercel',
-]);
-
-const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.tsx', '.jsx']);
-const LAYOUT_EXTS = new Set(['.tsx', '.jsx', '.astro', '.vue', '.svelte', '.html']);
-const MAX_DEPTH = 6;
-const MAX_READ_BYTES = 64 * 1024;
-
-// append-arrays signals: CSP expressed as structured directive arrays
-const MONOREPO_HELPER_SIGNALS = [
- /\bbuildCSPConfig\b/,
- /\bbuildSecurityHeaders\b/,
- /\badditionalScriptSrc\b/,
- /\badditionalConnectSrc\b/,
- /\bcreateBaseNextConfig\b/,
-];
-const SVELTEKIT_CSP_SIGNALS = [
- /\bkit\s*:/,
- /\bcsp\s*:/,
- /\bdirectives\s*:/,
-];
-const NUXT_SECURITY_SIGNALS = [
- /['"]nuxt-security['"]/,
- /\bcontentSecurityPolicy\b/,
-];
-
-// append-string signals: CSP written as a literal value string
-const INLINE_HEADER_SIGNALS = [
- /["']Content-Security-Policy["']/i,
- /\bscript-src\b/,
- /\bconnect-src\b/,
-];
-const NUXT_ROUTE_RULES_SIGNALS = [
- /\brouteRules\b/,
- /Content-Security-Policy/i,
- /\bscript-src\b/,
-];
-
-const MIDDLEWARE_HINT = /headers\.set\(\s*["']Content-Security-Policy["']/i;
-const META_TAG_HINT = /http-equiv\s*=\s*["']Content-Security-Policy["']/i;
-
-/**
- * @param {string} cwd Project root.
- * @returns {{ shape: string|null, signals: string[] }}
- */
-export function detectCsp(cwd = process.cwd()) {
- const hits = { appendArrays: [], appendString: [], middleware: [], metaTag: [] };
-
- walk(cwd, cwd, 0, (absPath, relPath, body) => {
- const ext = path.extname(absPath);
- const base = path.basename(absPath).toLowerCase();
- const isConfig = (name) =>
- new RegExp('(^|/)' + name + '\\.config\\.').test(relPath);
-
- // === append-arrays candidates ===
-
- // Monorepo CSP helper: packages/*/src/.../(config|security)/*
- if (SCAN_EXTS.has(ext) &&
- /packages\/[^/]+\/src\/.*(config|next-config|security)/.test(relPath) &&
- MONOREPO_HELPER_SIGNALS.some((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // SvelteKit kit.csp.directives
- if (SCAN_EXTS.has(ext) && isConfig('svelte') &&
- SVELTEKIT_CSP_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // Nuxt nuxt-security module
- if (SCAN_EXTS.has(ext) && isConfig('nuxt') &&
- NUXT_SECURITY_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // === append-string candidates ===
-
- // Inline headers in Next/Nuxt/SvelteKit/Astro/Vite config
- if (SCAN_EXTS.has(ext) &&
- /(^|\/)(next|nuxt|vite|astro|svelte)\.config\./.test(relPath) &&
- INLINE_HEADER_SIGNALS.every((re) => re.test(body))) {
- // Nuxt routeRules is a sub-shape of append-string; we already covered
- // nuxt-security above via return, so any remaining Nuxt CSP match here
- // is a route-rules / inline-headers case. Either way, same patch
- // mechanism.
- hits.appendString.push(relPath);
- return;
- }
-
- // === detect-only shapes ===
-
- if ((base === 'middleware.ts' || base === 'middleware.js' || base === 'middleware.mjs') &&
- MIDDLEWARE_HINT.test(body)) {
- hits.middleware.push(relPath);
- }
-
- if (LAYOUT_EXTS.has(ext) && META_TAG_HINT.test(body)) {
- hits.metaTag.push(relPath);
- }
- });
-
- // Priority: append-arrays > append-string > middleware > meta-tag.
- // Structured patches are safer than string splices; runtime and HTML
- // injection patches are less reliable and v1 doesn't auto-apply them.
- if (hits.appendArrays.length > 0) {
- return { shape: 'append-arrays', signals: hits.appendArrays };
- }
- if (hits.appendString.length > 0) {
- return { shape: 'append-string', signals: hits.appendString };
- }
- if (hits.middleware.length > 0) {
- return { shape: 'middleware', signals: hits.middleware };
- }
- if (hits.metaTag.length > 0) {
- return { shape: 'meta-tag', signals: hits.metaTag };
- }
- return { shape: null, signals: [] };
-}
-
-function walk(root, dir, depth, visit) {
- if (depth > MAX_DEPTH) return;
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
-
- for (const entry of entries) {
- const abs = path.join(dir, entry.name);
- if (entry.isDirectory()) {
- if (SKIP_DIRS.has(entry.name)) continue;
- walk(root, abs, depth + 1, visit);
- continue;
- }
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name);
- if (!SCAN_EXTS.has(ext) && !LAYOUT_EXTS.has(ext)) continue;
- let body;
- try {
- const fd = fs.openSync(abs, 'r');
- try {
- const buf = Buffer.alloc(MAX_READ_BYTES);
- const n = fs.readSync(fd, buf, 0, MAX_READ_BYTES, 0);
- body = buf.slice(0, n).toString('utf-8');
- } finally { fs.closeSync(fd); }
- } catch { continue; }
- visit(abs, path.relative(root, abs), body);
- }
-}
-
-// CLI mode
-const _running = process.argv[1];
-if (_running?.endsWith('detect-csp.mjs') || _running?.endsWith('detect-csp.mjs/')) {
- const result = detectCsp(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
@@ -1,21 +0,0 @@
-#!/usr/bin/env node
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { pathToFileURL, fileURLToPath } from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const candidates = [
- path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
-];
-const detectorPath = candidates.find(p => fs.existsSync(p));
-
-if (!detectorPath) {
- process.stderr.write('Error: bundled detector not found.\n');
- process.exit(1);
-}
-
-const { detectCli } = await import(pathToFileURL(detectorPath));
-
-await detectCli();
@@ -1,1688 +0,0 @@
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
@@ -1,232 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
-import { detectHtml } from '../engines/static-html/detect-html.mjs';
-import { detectText } from '../engines/regex/detect-text.mjs';
-import {
- HTML_EXTENSIONS,
- buildImportGraph,
- detectFrameworkConfig,
- isPortListening,
- walkDir,
-} from '../node/file-system.mjs';
-
-// ---------------------------------------------------------------------------
-// Output formatting
-// ---------------------------------------------------------------------------
-
-function formatFindings(findings, jsonMode) {
- if (jsonMode) return JSON.stringify(findings, null, 2);
-
- const grouped = {};
- for (const f of findings) {
- if (!grouped[f.file]) grouped[f.file] = [];
- grouped[f.file].push(f);
- }
- const out = [];
- for (const [file, items] of Object.entries(grouped)) {
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
- out.push(`\n${file}${importNote}`);
- for (const item of items) {
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
- out.push(` → ${item.description}`);
- }
- }
- out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
- return out.join('\n');
-}
-
-// ---------------------------------------------------------------------------
-// Stdin handling
-// ---------------------------------------------------------------------------
-
-async function handleStdin() {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- const input = Buffer.concat(chunks).toString('utf-8');
- try {
- const parsed = JSON.parse(input);
- const fp = parsed?.tool_input?.file_path;
- if (fp && fs.existsSync(fp)) {
- return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
- ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
- }
- } catch { /* not JSON */ }
- return detectText(input, '<stdin>');
-}
-
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-async function confirm(question) {
- const rl = (await import('node:readline')).default.createInterface({
- input: process.stdin, output: process.stderr,
- });
- return new Promise((resolve) => {
- rl.question(`${question} [Y/n] `, (answer) => {
- rl.close();
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
- });
- });
-}
-
-function printUsage() {
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
-
-Scan files or URLs for UI anti-patterns and design quality issues.
-
-Options:
- --fast Regex-only mode (skip static HTML/CSS analysis, faster but misses linked stylesheets)
- --json Output results as JSON
- --help Show this help message
-
-Detection modes:
- HTML files Static HTML/CSS analysis (default, catches linked CSS)
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
- URLs Puppeteer full browser rendering (auto-detected)
- --fast Forces regex for all files
-
-Examples:
- impeccable detect src/
- impeccable detect index.html
- impeccable detect https://example.com
- impeccable detect --fast --json .`);
-}
-
-async function detectCli() {
- let args = process.argv.slice(2).map(arg => {
- if (arg === '-json') return '--json';
- if (arg === '-fast') return '--fast';
- return arg;
- });
- if (args[0] === 'detect') args = args.slice(1);
- const jsonMode = args.includes('--json');
- const helpMode = args.includes('--help');
- const fastMode = args.includes('--fast');
- const targets = args.filter(a => !a.startsWith('--'));
-
- if (helpMode) { printUsage(); process.exit(0); }
-
- let allFindings = [];
-
- if (!process.stdin.isTTY && targets.length === 0) {
- allFindings = await handleStdin();
- } else {
- const paths = targets.length > 0 ? targets : [process.cwd()];
- const urlTargetCount = paths.filter(target => /^https?:\/\//i.test(target)).length;
- const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
-
- try {
- for (const target of paths) {
- if (/^https?:\/\//i.test(target)) {
- try {
- const scanner = browserDetector
- ? (url) => browserDetector.detectUrl(url)
- : (url) => detectUrl(url);
- allFindings.push(...await scanner(target));
- } catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
- continue;
- }
-
- const resolved = path.resolve(target);
- let stat;
- try { stat = fs.statSync(resolved); }
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
-
- if (stat.isDirectory()) {
- // Check for framework dev server config (skip in JSON mode to avoid polluting output)
- if (!jsonMode) {
- const fwConfig = detectFrameworkConfig(resolved);
- if (fwConfig) {
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
- if (probe.listening && probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
- `For more accurate results, scan the running site:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- } else if (probe.listening && !probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
- );
- } else {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Start the dev server and scan via URL for best results:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- }
- }
- }
-
- const files = walkDir(resolved);
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
-
- // Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
- if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
- process.stderr.write(
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
- `Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
- `Use --fast to skip static HTML/CSS analysis, or target a specific subdirectory.\n`
- );
- const ok = await confirm('Continue?');
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
- }
-
- // Build import graph for multi-file awareness
- const graph = buildImportGraph(files);
- // Build reverse map: file -> set of files that import it
- const importedByMap = new Map();
- for (const [importer, imports] of graph) {
- for (const imported of imports) {
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
- importedByMap.get(imported).add(importer);
- }
- }
-
- for (const file of files) {
- const ext = path.extname(file).toLowerCase();
- let fileFindings;
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- fileFindings = await detectHtml(file);
- } else {
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
- }
- // Annotate findings with import context
- const importers = importedByMap.get(file);
- if (importers && importers.size > 0) {
- const importerNames = [...importers].map(f => path.basename(f));
- for (const f of fileFindings) {
- f.importedBy = importerNames;
- }
- }
- allFindings.push(...fileFindings);
- }
- } else if (stat.isFile()) {
- const ext = path.extname(resolved).toLowerCase();
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- allFindings.push(...await detectHtml(resolved));
- } else {
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
- }
- }
- }
- } finally {
- if (browserDetector) await browserDetector.close();
- }
- }
-
- if (allFindings.length > 0) {
- if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
- else process.stderr.write(formatFindings(allFindings, false) + '\n');
- process.exit(2);
- }
- if (jsonMode) process.stdout.write('[]\n');
- process.exit(0);
-}
-
-export { formatFindings, handleStdin, confirm, printUsage, detectCli };
@@ -1,4030 +0,0 @@
-/**
- * Anti-Pattern Browser Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * GENERATED -- do not edit. Source: cli/engine/browser/injected/index.mjs
- * Rebuild: node scripts/build-browser-detector.js
- *
- * Usage: <script src="detect-antipatterns-browser.js"></script>
- * Re-scan: window.impeccableScan()
- */
-(function () {
-if (typeof window === 'undefined') return;
-// --- cli/engine/shared/constants.mjs ---
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-// --- cli/engine/registry/antipatterns.mjs ---
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-// --- cli/engine/shared/color.mjs ---
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-// --- cli/engine/rules/checks.mjs ---
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-// --- cli/engine/browser/injected/index.mjs ---
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
-
-})();
@@ -1,43 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Anti-Pattern Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * Public API facade. Runtime engines live under cli/engine/engines/.
- */
-
-import { detectCli } from './cli/main.mjs';
-
-export { ANTIPATTERNS, RULE_ENGINE_SUPPORT, getAntipattern, getRulesForCategory, getRuleEngineSupport } from './registry/antipatterns.mjs';
-export { SAFE_TAGS, BORDER_SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS, KNOWN_SERIF_FONTS } from './shared/constants.mjs';
-export { isNeutralColor, parseRgb, relativeLuminance, contrastRatio, parseGradientColors, hasChroma, getHue, colorToHex } from './shared/color.mjs';
-export { isFullPage } from './shared/page.mjs';
-export {
- checkElementBorders,
- checkElementMotion,
- checkElementGlow,
- checkPageTypography,
- checkPageLayout,
- checkHtmlPatterns,
-} from './rules/checks.mjs';
-export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
-export { detectHtml } from './engines/static-html/detect-html.mjs';
-export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
-export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
-export {
- walkDir,
- SCANNABLE_EXTENSIONS,
- SKIP_DIRS,
- buildImportGraph,
- resolveImport,
- detectFrameworkConfig,
- isPortListening,
- FRAMEWORK_CONFIGS,
-} from './node/file-system.mjs';
-export { formatFindings, detectCli } from './cli/main.mjs';
-
-const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
-if (isMainModule) detectCli();
@@ -1,251 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { finding } from '../../findings.mjs';
-import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
-
-async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
- if (options?.visualContrast === false) return [];
- const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : 12;
- const scrollOffscreen = options?.visualContrastScrollOffscreen !== false;
- const existingLowContrastSelectors = new Set(
- serializedGroups
- .filter(group => group.findings?.some(f => f.type === 'low-contrast'))
- .map(group => group.selector)
- .filter(Boolean)
- );
-
- let browserAnalyses = [];
- const findings = [];
- if (options?.visualContrastBrowser !== false) {
- const browserFindings = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'browser-fallback',
- target,
- }, async () => {
- browserAnalyses = await page.evaluate(async ({ maxCandidates, scrollOffscreen }) => {
- if (typeof window.impeccableAnalyzeVisualContrast !== 'function') return [];
- return window.impeccableAnalyzeVisualContrast({ maxCandidates, scrollOffscreen });
- }, { maxCandidates, scrollOffscreen });
- return browserAnalyses
- .filter(result => result.finding && !existingLowContrastSelectors.has(result.selector))
- .map(result => result.finding);
- });
- findings.push(...browserFindings);
- }
-
- let candidates = browserAnalyses.length > 0 ? browserAnalyses : [];
- if (candidates.length === 0) {
- candidates = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'collect-candidates',
- target,
- }, () => page.evaluate(({ maxCandidates }) => {
- if (typeof window.impeccableCollectVisualContrastCandidates !== 'function') return [];
- return window.impeccableCollectVisualContrastCandidates({ maxCandidates });
- }, { maxCandidates }));
- }
-
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const browserResolvedSelectors = new Set(
- browserAnalyses
- .filter(result => result.status === 'fail' || result.status === 'pass')
- .map(result => result.selector)
- .filter(Boolean)
- );
- const filtered = candidates.filter(candidate =>
- !existingLowContrastSelectors.has(candidate.selector) &&
- !browserResolvedSelectors.has(candidate.selector)
- );
- if (options?.visualContrastPixel === false) return findings;
- for (const candidate of filtered) {
- const result = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'pixel-diff',
- target,
- }, async () => {
- const finding = await captureVisualContrastCandidate(page, candidate, viewport);
- return finding ? [finding] : [];
- });
- findings.push(...result);
- }
- return findings;
-}
-
-// ---------------------------------------------------------------------------
-// Puppeteer detection (for URLs)
-// ---------------------------------------------------------------------------
-
-async function detectUrl(url, options = {}) {
- const profile = options?.profile;
- const waitUntil = options?.waitUntil || 'networkidle0';
- const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const externalBrowser = options?.browser || null;
- let puppeteer;
- if (!externalBrowser) {
- try {
- puppeteer = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'import-puppeteer',
- target: url,
- }, () => import('puppeteer'));
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- }
-
- // Read the browser detection script — reuse it instead of reimplementing
- const browserScriptPath = path.resolve(
- path.dirname(fileURLToPath(import.meta.url)),
- '..',
- '..',
- 'detect-antipatterns-browser.js'
- );
- let browserScript;
- try {
- browserScript = profileStep(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'read-browser-script',
- target: url,
- }, () => fs.readFileSync(browserScriptPath, 'utf-8'));
- } catch {
- throw new Error(`Browser script not found at ${browserScriptPath}`);
- }
-
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
- // running in CI; local users keep the default hardened launch.
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
- const browser = externalBrowser || await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'launch-browser',
- target: url,
- }, () => puppeteer.default.launch({ headless: true, args: launchArgs }));
- const page = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'new-page',
- target: url,
- }, () => browser.newPage());
- let results = [];
- try {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'set-viewport',
- target: url,
- }, () => page.setViewport(viewport));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: `goto:${waitUntil}`,
- target: url,
- }, () => page.goto(url, { waitUntil, timeout: 30000 }));
- if (settleMs > 0) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'settle',
- target: url,
- }, () => new Promise(resolve => setTimeout(resolve, settleMs)));
- }
-
- // Inject the browser detection script and collect results
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'configure-pure-detect',
- target: url,
- }, () => page.evaluate(() => {
- window.__IMPECCABLE_CONFIG__ = {
- ...(window.__IMPECCABLE_CONFIG__ || {}),
- autoScan: false,
- };
- }));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'inject-browser-script',
- target: url,
- }, () => page.evaluate(browserScript));
- let serializedGroups = [];
- results = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'browser-scan',
- target: url,
- }, async () => {
- serializedGroups = await page.evaluate(() => {
- if (!window.impeccableDetect) return [];
- return window.impeccableDetect({ decorate: false, serialize: true });
- });
- return serializedGroups.flatMap(({ findings }) =>
- findings.map(f => ({ id: f.type, snippet: f.detail }))
- );
- });
- const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
- results.push(...visualFindings);
- } finally {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-page',
- target: url,
- }, () => page.close().catch(() => {}));
- if (!externalBrowser) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-browser',
- target: url,
- }, () => browser.close());
- }
- }
- return results.map(f => finding(f.id, url, f.snippet));
-}
-
-async function createBrowserDetector(options = {}) {
- let puppeteer;
- try {
- puppeteer = await import('puppeteer');
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- const launchArgs = options.launchArgs || (process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : []);
- const browser = options.browser || await puppeteer.default.launch({
- headless: options.headless ?? true,
- args: launchArgs,
- });
- const ownsBrowser = !options.browser;
- const defaults = {
- waitUntil: options.waitUntil || 'load',
- settleMs: Number.isFinite(options.settleMs) ? options.settleMs : 100,
- viewport: options.viewport || { width: 1280, height: 800 },
- };
- return {
- browser,
- async detectUrl(url, scanOptions = {}) {
- return detectUrl(url, {
- ...defaults,
- ...scanOptions,
- browser,
- });
- },
- async close() {
- if (ownsBrowser) await browser.close().catch(() => {});
- },
- };
-}
-
-export { runVisualContrastFallback, detectUrl, createBrowserDetector };
@@ -1,420 +0,0 @@
-import { GENERIC_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep } from '../../profile/profiler.mjs';
-
-// ---------------------------------------------------------------------------
-// Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
-// ---------------------------------------------------------------------------
-
-const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
-const hasBorderRadius = (line) => /border-radius/i.test(line);
-const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
-
-function isNeutralBorderColor(str) {
- const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
- if (!m) return false;
- const c = m[1].toLowerCase();
- if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
- const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
- if (hex) {
- const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
- if (shex) {
- const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- return false;
-}
-
-const REGEX_MATCHERS = [
- // --- Side-tab ---
- { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
- test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
- test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
- fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
- { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
- test: (m) => +m[1] >= 3,
- fmt: (m) => m[0] },
- // --- Border accent on rounded ---
- { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
- test: (m, line) => hasRounded(line) && +m[1] >= 1,
- fmt: (m) => m[0] },
- { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
- fmt: (m) => m[0] },
- // --- Overused font ---
- { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
- test: () => true,
- fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
- // --- Pure black background ---
- { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Gradient text ---
- { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
- test: (m, line) => /gradient/i.test(line),
- fmt: () => 'background-clip: text + gradient' },
- // --- Gradient text (Tailwind) ---
- { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
- test: (m, line) => /\bbg-gradient-to-/i.test(line),
- fmt: () => 'bg-clip-text + bg-gradient' },
- // --- Tailwind pure black background ---
- { id: 'pure-black-white', regex: /\bbg-black\b/g,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Tailwind gray on colored bg ---
- { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
- test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
- fmt: (m, line) => { const bg = line.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/); return `${m[0]} on ${bg?.[0] || '?'}`; } },
- // --- Tailwind AI palette ---
- { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
- fmt: (m) => `${m[0]} on heading` },
- { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
- fmt: (m) => `${m[0]} gradient` },
- // --- Bounce/elastic easing ---
- { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
- test: () => true,
- fmt: () => 'animate-bounce (Tailwind)' },
- { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
- test: (m) => {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
- },
- fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
- // --- Layout property transition ---
- { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition: ${found ? found.join(', ') : m[1].trim()}`;
- } },
- { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
- } },
-];
-
-const REGEX_ANALYZERS = [
- // Single font
- (content, filePath) => {
- const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
- const fonts = new Set();
- let m;
- while ((m = fontFamilyRe.exec(content)) !== null) {
- for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
- }
- }
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- while ((m = gfRe.exec(content)) !== null) {
- for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
- }
- if (fonts.size !== 1 || content.split('\n').length < 20) return [];
- const name = [...fonts][0];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
- return [finding('single-font', filePath, `only font used is ${name}`, line)];
- },
- // Flat type hierarchy
- (content, filePath) => {
- const sizes = new Set();
- const REM = 16;
- let m;
- const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
- while ((m = sizeRe.exec(content)) !== null) {
- const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
- if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
- }
- const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
- while ((m = clampRe.exec(content)) !== null) {
- sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
- sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
- }
- const TW = { 'text-xs': 12, 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24, 'text-3xl': 30, 'text-4xl': 36, 'text-5xl': 48, 'text-6xl': 60, 'text-7xl': 72, 'text-8xl': 96, 'text-9xl': 128 };
- for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
- if (sizes.size < 3) return [];
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio >= 2.0) return [];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (/font-size/i.test(lines[i]) || /\btext-(?:xs|sm|base|lg|xl|\d)/i.test(lines[i])) { line = i + 1; break; } }
- return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
- },
- // Monotonous spacing (regex)
- (content, filePath) => {
- const vals = [];
- let m;
- const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
- const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
- const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
- const rounded = vals.map(v => Math.round(v / 4) * 4);
- if (rounded.length < 10) return [];
- const counts = {};
- for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const pct = maxCount / rounded.length;
- const unique = [...new Set(rounded)].filter(v => v > 0);
- if (pct <= 0.6 || unique.length > 3) return [];
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
- },
- // Everything centered (regex)
- (content, filePath) => {
- const lines = content.split('\n');
- let centered = 0, total = 0;
- for (const line of lines) {
- if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
- total++;
- if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
- }
- }
- if (total < 5 || centered / total <= 0.7) return [];
- return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
- },
- // Dark glow (page-level: dark bg + colored box-shadow with blur)
- (content, filePath) => {
- // Check if page has a dark background
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
- if (!hasDarkBg) return [];
-
- // Check for colored box-shadow with blur > 4px
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let m;
- while ((m = shadowRe.exec(content)) !== null) {
- const val = m[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
- // Check blur: look for pattern like "0 0 20px" (third number > 4)
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- const lines = content.substring(0, m.index).split('\n');
- return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
- }
- }
- return [];
- },
-];
-
-// ---------------------------------------------------------------------------
-// Style block extraction (Vue/Svelte <style> blocks)
-// ---------------------------------------------------------------------------
-
-function extractStyleBlocks(content, ext) {
- ext = ext.toLowerCase();
- if (ext !== '.vue' && ext !== '.svelte') return [];
- const blocks = [];
- const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length + 1;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-// ---------------------------------------------------------------------------
-// CSS-in-JS extraction (styled-components, emotion)
-// ---------------------------------------------------------------------------
-
-const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
-
-function extractCSSinJS(content, ext) {
- ext = ext.toLowerCase();
- if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
- const blocks = [];
- const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null, options = {}) {
- const { profile, phase = 'regex-matchers' } = options || {};
- const findings = [];
- if (!profile) {
- for (const matcher of REGEX_MATCHERS) {
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- }
- return findings;
- }
-
- for (const matcher of REGEX_MATCHERS) {
- const matcherFindings = profileFindings(profile, {
- engine: 'regex',
- phase,
- ruleId: matcher.id,
- target: filePath,
- }, () => {
- const matches = [];
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- matches.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- return matches;
- });
- findings.push(...matcherFindings);
- }
- return findings;
-}
-
-function detectText(content, filePath, options = {}) {
- const profile = options?.profile;
- const findings = [];
- const lines = content.split('\n');
- const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
-
- // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
- // Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
- findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
- profile,
- phase: 'source',
- }));
-
- // Extract and scan <style> blocks from Vue/Svelte SFCs
- const styleBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'style-blocks',
- target: filePath,
- }, () => extractStyleBlocks(content, ext))
- : extractStyleBlocks(content, ext);
- for (const block of styleBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'style-block',
- }));
- }
-
- // Extract and scan CSS-in-JS template literals
- const cssJsBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'css-in-js',
- target: filePath,
- }, () => extractCSSinJS(content, ext))
- : extractCSSinJS(content, ext);
- for (const block of cssJsBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'css-in-js',
- }));
- }
-
- // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
- const deduped = [];
- for (const f of findings) {
- const isDupe = deduped.some(d =>
- d.antipattern === f.antipattern &&
- d.snippet === f.snippet &&
- Math.abs(d.line - f.line) <= 2
- );
- if (!isDupe) deduped.push(f);
- }
-
- // Page-level analyzers only run on full pages
- if (isFullPage(content)) {
- const analyzerIds = [
- 'single-font',
- 'flat-type-hierarchy',
- 'monotonous-spacing',
- 'everything-centered',
- 'dark-glow',
- ];
- for (let i = 0; i < REGEX_ANALYZERS.length; i++) {
- const analyzer = REGEX_ANALYZERS[i];
- deduped.push(...profileFindings(profile, {
- engine: 'regex',
- phase: 'page-analyzer',
- ruleId: analyzerIds[i] || `analyzer-${i + 1}`,
- target: filePath,
- }, () => analyzer(content, filePath)));
- }
- }
-
- return deduped;
-}
-
-export {
- REGEX_MATCHERS,
- REGEX_ANALYZERS,
- extractStyleBlocks,
- extractCSSinJS,
- runRegexMatchers,
- detectText,
-};
@@ -1,954 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { profileStep, recordProfileEvent } from '../../profile/profiler.mjs';
-import { parseAnyColor, resolveLengthPx, resolveVarRefs } from '../../rules/checks.mjs';
-
-// ---------------------------------------------------------------------------
-// jsdom CSS-variable border override map
-// ---------------------------------------------------------------------------
-//
-// jsdom's CSSOM silently drops any border shorthand that contains a var()
-// reference — the computed style for the element then shows empty width,
-// empty style, and a default black color. That's enough to hide the most
-// common real-world side-tab pattern in AI-generated pages:
-//
-// :root { --brand: #87a8ff; }
-// .card { border-left: 5px solid var(--brand); border-radius: 4px; }
-//
-// Real browsers (and therefore the browser detector path) resolve var()
-// natively, so this only affects the Node jsdom path.
-//
-// This pre-pass walks the stylesheets, finds any rule whose per-side or
-// all-sides border property contains var(), resolves the var() against
-// :root-level custom properties (read from the documentElement's computed
-// style, which jsdom DOES handle correctly), and attaches the resolved
-// width+color to every element that matches the rule's selector. The
-// Node-side `checkElementBorders` adapter consumes that map as a fallback
-// whenever jsdom's computed style came back empty.
-//
-// Limitations (intentional, to keep the pass simple):
-// * Only :root-level custom properties are resolved. Scoped overrides on
-// descendants are not tracked — uncommon in practice and would require
-// a per-element cascade walk.
-// * @media / @supports wrapped rules are ignored (jsdom often mishandles
-// these anyway).
-// * The fallback only fills sides that jsdom left empty, so any rule
-// whose border parses normally still wins via the computed style.
-
-const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
-
-// isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
-// CSS variables typically hold hex or named colors, so normalize those to
-// rgb() before handing the value off to the shared check. Anything we don't
-// recognise is passed through unchanged — isNeutralColor then treats it as
-// non-neutral, which is the safer default (matches the oklch-era bugfix).
-const NAMED_COLORS = {
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
-};
-
-function normalizeColorForCheck(value) {
- if (!value) return value;
- const v = value.trim();
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
- if (hex6) {
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
- if (hex3) {
- const [r, g, b] = [
- parseInt(hex3[1] + hex3[1], 16),
- parseInt(hex3[2] + hex3[2], 16),
- parseInt(hex3[3] + hex3[3], 16),
- ];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const named = NAMED_COLORS[v.toLowerCase()];
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
- return v;
-}
-
-function buildBorderOverrideMap(document, window) {
- const map = new Map();
- const rootStyle = window.getComputedStyle(document.documentElement);
-
- function resolveVar(value, depth = 0) {
- if (!value || depth > 10 || !value.includes('var(')) return value;
- return value.replace(
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
- (_, name, fallback) => {
- const v = rootStyle.getPropertyValue(name).trim();
- if (v) return resolveVar(v, depth + 1);
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
- return '';
- }
- );
- }
-
- function parseShorthand(text) {
- const m = text.trim().match(BORDER_SHORTHAND_RE);
- if (!m) return null;
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
- }
-
- // Read from the per-property accessors on rule.style. jsdom preserves
- // each border-* shorthand it parsed, even when the overall cssText has
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
- // `border-left: ...` loses the first declaration but keeps the second).
- const SIDE_PROPS = [
- ['borderLeft', 'Left'],
- ['borderRight', 'Right'],
- ['borderTop', 'Top'],
- ['borderBottom', 'Bottom'],
- ['borderInlineStart', 'Left'],
- ['borderInlineEnd', 'Right'],
- ];
-
- for (const sheet of document.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || []; } catch { continue; }
- for (const rule of rules) {
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
-
- const perSide = {};
-
- for (const [prop, side] of SIDE_PROPS) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const parsed = parseShorthand(resolveVar(val));
- if (parsed && parsed.color) perSide[side] = parsed;
- }
-
- // Uniform `border: <w> <style> var(...)` applies to every side the
- // per-side map didn't already claim.
- const borderAll = rule.style.border;
- if (borderAll && borderAll.includes('var(')) {
- const parsed = parseShorthand(resolveVar(borderAll));
- if (parsed && parsed.color) {
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
- if (!perSide[s]) perSide[s] = parsed;
- }
- }
- }
-
- // Longhand `border-*-color: var(...)` with width/style in separate
- // declarations. Rare in AI-generated pages, but cheap to cover.
- for (const [prop, side] of [
- ['borderLeftColor', 'Left'],
- ['borderRightColor', 'Right'],
- ['borderTopColor', 'Top'],
- ['borderBottomColor', 'Bottom'],
- ]) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const resolved = resolveVar(val).trim();
- if (!resolved) continue;
- // Width may or may not come from this rule — that's fine; the
- // adapter only substitutes the color when jsdom left it as a
- // literal var() string.
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
- }
-
- if (Object.keys(perSide).length === 0) continue;
-
- let matched;
- try { matched = document.querySelectorAll(rule.selectorText); }
- catch { continue; }
-
- for (const el of matched) {
- const existing = map.get(el);
- if (existing) {
- // Later rules overwrite earlier ones — approximates source-order
- // cascade for equal-specificity rules and is good enough for the
- // uncontested var()-dropped sides we're trying to recover.
- Object.assign(existing, perSide);
- } else {
- map.set(el, { ...perSide });
- }
- }
- }
- }
-
- return map;
-}
-
-// Strip `@layer NAME { … }` wrappers from a CSS / HTML source, leaving
-// the inner rules as flat CSS. jsdom doesn't implement CSS @layer, so
-// any rule inside a layer block becomes invisible to getComputedStyle.
-// Tailwind v4 makes this ubiquitous: every utility class lives in
-// `@layer utilities`, and Preflight lives in `@layer base`. Without
-// unwrapping, every Tailwind-styled element returns empty computed
-// styles. We walk the source character-by-character, balancing braces
-// so we correctly handle nested style rules inside the layer block.
-function unwrapCssAtLayer(source) {
- if (!source || !source.includes('@layer')) return source;
- // Find `@layer <name>? {` openers. The match starts at the @, and
- // we then balance braces from the opening { onward.
- const re = /@layer\b[^{;]*\{/g;
- let out = '';
- let lastIdx = 0;
- let m;
- while ((m = re.exec(source)) !== null) {
- const openStart = m.index;
- const openEnd = m.index + m[0].length; // position right after `{`
- let depth = 1;
- let i = openEnd;
- while (i < source.length && depth > 0) {
- const c = source.charCodeAt(i);
- if (c === 0x7b /* { */) depth++;
- else if (c === 0x7d /* } */) depth--;
- i++;
- }
- if (depth !== 0) {
- // Unbalanced — bail and return source unchanged.
- return source;
- }
- // Emit everything before the @layer, then the inner contents
- // (between the opening { and the matched closing }), then advance.
- out += source.slice(lastIdx, openStart);
- out += source.slice(openEnd, i - 1); // i-1 = position of the closing }
- lastIdx = i;
- re.lastIndex = i;
- }
- out += source.slice(lastIdx);
- return out;
-}
-
-// ---------------------------------------------------------------------------
-// Static HTML/CSS detection (default for local HTML files)
-// ---------------------------------------------------------------------------
-
-const STATIC_INHERITED_PROPS = new Set([
- 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight',
- 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'hyphens',
- 'webkitHyphens',
-]);
-
-const STATIC_DEFAULT_STYLE = {
- color: 'rgb(0, 0, 0)',
- backgroundColor: 'rgba(0, 0, 0, 0)',
- backgroundImage: 'none',
- borderTopWidth: '0px',
- borderRightWidth: '0px',
- borderBottomWidth: '0px',
- borderLeftWidth: '0px',
- borderTopColor: 'rgb(0, 0, 0)',
- borderRightColor: 'rgb(0, 0, 0)',
- borderBottomColor: 'rgb(0, 0, 0)',
- borderLeftColor: 'rgb(0, 0, 0)',
- borderRadius: '0px',
- boxShadow: 'none',
- fontFamily: '',
- fontSize: '16px',
- fontStyle: 'normal',
- fontWeight: '400',
- lineHeight: 'normal',
- letterSpacing: 'normal',
- textTransform: 'none',
- textAlign: 'start',
- hyphens: 'manual',
- webkitHyphens: 'manual',
- transitionProperty: '',
- transitionTimingFunction: '',
- animationName: '',
- animationTimingFunction: '',
- webkitBackgroundClip: '',
- backgroundClip: '',
- width: '',
- height: '',
- paddingTop: '0px',
- paddingRight: '0px',
- paddingBottom: '0px',
- paddingLeft: '0px',
- position: 'static',
- display: '',
-};
-
-const STATIC_PROP_MAP = {
- 'background-color': 'backgroundColor',
- 'background-image': 'backgroundImage',
- 'background-clip': 'backgroundClip',
- '-webkit-background-clip': 'webkitBackgroundClip',
- 'border-radius': 'borderRadius',
- 'border-top-width': 'borderTopWidth',
- 'border-right-width': 'borderRightWidth',
- 'border-bottom-width': 'borderBottomWidth',
- 'border-left-width': 'borderLeftWidth',
- 'border-top-color': 'borderTopColor',
- 'border-right-color': 'borderRightColor',
- 'border-bottom-color': 'borderBottomColor',
- 'border-left-color': 'borderLeftColor',
- 'box-shadow': 'boxShadow',
- 'font-family': 'fontFamily',
- 'font-size': 'fontSize',
- 'font-style': 'fontStyle',
- 'font-weight': 'fontWeight',
- 'line-height': 'lineHeight',
- 'letter-spacing': 'letterSpacing',
- 'text-transform': 'textTransform',
- 'text-align': 'textAlign',
- 'hyphens': 'hyphens',
- '-webkit-hyphens': 'webkitHyphens',
- 'transition-property': 'transitionProperty',
- 'transition-timing-function': 'transitionTimingFunction',
- 'animation-name': 'animationName',
- 'animation-timing-function': 'animationTimingFunction',
- 'width': 'width',
- 'height': 'height',
- 'padding-top': 'paddingTop',
- 'padding-right': 'paddingRight',
- 'padding-bottom': 'paddingBottom',
- 'padding-left': 'paddingLeft',
- 'position': 'position',
- 'display': 'display',
-};
-
-const STATIC_NAMED_COLORS = {
- black: { r: 0, g: 0, b: 0, a: 1 },
- white: { r: 255, g: 255, b: 255, a: 1 },
- transparent: { r: 0, g: 0, b: 0, a: 0 },
- gray: { r: 128, g: 128, b: 128, a: 1 },
- grey: { r: 128, g: 128, b: 128, a: 1 },
- silver: { r: 192, g: 192, b: 192, a: 1 },
- red: { r: 255, g: 0, b: 0, a: 1 },
- green: { r: 0, g: 128, b: 0, a: 1 },
- blue: { r: 0, g: 0, b: 255, a: 1 },
-};
-
-function splitCssList(value) {
- const parts = [];
- let depth = 0, quote = '', start = 0;
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; continue; }
- if (ch === '(' || ch === '[') depth++;
- else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);
- else if (ch === ',' && depth === 0) {
- parts.push(value.slice(start, i).trim());
- start = i + 1;
- }
- }
- const tail = value.slice(start).trim();
- if (tail) parts.push(tail);
- return parts;
-}
-
-function splitCssTokens(value) {
- const tokens = [];
- let depth = 0, quote = '', current = '';
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- current += ch;
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
- if (ch === '(') { depth++; current += ch; continue; }
- if (ch === ')') { depth = Math.max(0, depth - 1); current += ch; continue; }
- if (/\s/.test(ch) && depth === 0) {
- if (current) { tokens.push(current); current = ''; }
- continue;
- }
- current += ch;
- }
- if (current) tokens.push(current);
- return tokens;
-}
-
-function cssPropToCamel(prop) {
- if (!prop) return prop;
- const mapped = STATIC_PROP_MAP[prop];
- if (mapped) return mapped;
- return prop.replace(/-([a-z])/g, (_m, ch) => ch.toUpperCase());
-}
-
-function staticColorToCss(c) {
- if (!c) return '';
- if (c.a != null && c.a < 1) return `rgba(${c.r}, ${c.g}, ${c.b}, ${Number(c.a.toFixed(3))})`;
- return `rgb(${c.r}, ${c.g}, ${c.b})`;
-}
-
-function parseStaticColor(value) {
- const parsed = parseAnyColor(value);
- if (parsed) return parsed;
- const named = STATIC_NAMED_COLORS[String(value || '').trim().toLowerCase()];
- return named ? { ...named } : null;
-}
-
-function extractStaticColor(value) {
- if (!value) return '';
- const raw = String(value).trim();
- if (/^var\(/i.test(raw)) return raw;
- const colorLike = raw.match(/(?:rgba?\([^)]+\)|oklch\([^)]+\)|oklab\([^)]+\)|lch\([^)]+\)|lab\([^)]+\)|hsla?\([^)]+\)|hwb\([^)]+\)|#[0-9a-f]{3,8}\b|\b(?:black|white|gray|grey|silver|red|green|blue|transparent)\b)/i);
- if (!colorLike) return '';
- return colorLike[0];
-}
-
-function normalizeStaticCssValue(prop, value, customProps, parentStyle, currentStyle = null) {
- let resolved = resolveVarRefs(String(value || '').trim(), customProps);
- if (resolved === 'inherit') return parentStyle?.[prop] || STATIC_DEFAULT_STYLE[prop] || '';
- const isModernBorderColor = /^border[A-Z][a-z]+Color$/.test(prop) && /^(?:oklch|oklab|lch|lab|hsl|hwb)\(/i.test(resolved);
- if (!isModernBorderColor && (/color$/i.test(prop) || prop === 'color' || prop === 'backgroundColor')) {
- const parsed = parseStaticColor(resolved);
- if (parsed) resolved = staticColorToCss(parsed);
- }
- if (prop === 'fontSize') {
- const base = parseFloat(parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'letterSpacing') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'lineHeight' && resolved !== 'normal') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- return resolved;
-}
-
-function expandStaticBoxValues(tokens) {
- if (tokens.length === 0) return ['0px', '0px', '0px', '0px'];
- if (tokens.length === 1) return [tokens[0], tokens[0], tokens[0], tokens[0]];
- if (tokens.length === 2) return [tokens[0], tokens[1], tokens[0], tokens[1]];
- if (tokens.length === 3) return [tokens[0], tokens[1], tokens[2], tokens[1]];
- return [tokens[0], tokens[1], tokens[2], tokens[3]];
-}
-
-function parseStaticBorder(value) {
- const tokens = splitCssTokens(value);
- let width = '', color = '';
- for (const token of tokens) {
- if (!width && /^-?[\d.]+(?:px|rem|em|%)$/.test(token)) width = token;
- if (!color) color = extractStaticColor(token);
- }
- return { width, color };
-}
-
-function parseStaticFont(value) {
- const out = [];
- const slashParts = value.match(/(?:^|\s)([\d.]+(?:px|rem|em|%))(?:\/([^\s]+))?/);
- if (/\bitalic\b/i.test(value)) out.push(['fontStyle', 'italic']);
- const weight = value.match(/\b([1-9]00|bold|normal|lighter|bolder)\b/i);
- if (weight) out.push(['fontWeight', weight[1]]);
- if (slashParts) {
- out.push(['fontSize', slashParts[1]]);
- if (slashParts[2]) out.push(['lineHeight', slashParts[2]]);
- const familyStart = value.indexOf(slashParts[0]) + slashParts[0].length;
- const family = value.slice(familyStart).trim();
- if (family) out.push(['fontFamily', family]);
- }
- return out;
-}
-
-function parseStaticTransition(value) {
- const props = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const prop = tokens.find(token => /^[a-z-]+$/i.test(token) && !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none)$/.test(token) && !/s$/.test(token));
- if (prop) props.push(prop);
- }
- return {
- property: props.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function parseStaticAnimation(value) {
- const names = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const name = tokens.find(token =>
- /^[a-z_-][\w-]*$/i.test(token) &&
- !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none|running|paused)$/.test(token)
- );
- if (name) names.push(name);
- }
- return {
- name: names.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function expandStaticDeclaration(prop, value) {
- const p = prop.toLowerCase();
- const v = String(value || '').trim();
- if (!v) return [];
- if (p.startsWith('--')) return [[p, v]];
- if (p === 'background') {
- const out = [];
- const hasImage = /gradient|url\(/i.test(v);
- if (hasImage) out.push(['backgroundImage', v]);
- const beforeImage = hasImage ? v.split(/(?:repeating-)?(?:linear|radial|conic)-gradient\(|url\(/i)[0] : v;
- const color = extractStaticColor(hasImage ? beforeImage : v);
- if (color) out.push(['backgroundColor', color]);
- return out;
- }
- if (p === 'border') {
- const parsed = parseStaticBorder(v);
- const out = [];
- for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
- if (parsed.width) out.push([`border${side}Width`, parsed.width]);
- if (parsed.color) out.push([`border${side}Color`, parsed.color]);
- }
- return out;
- }
- const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
- if (sideMatch) {
- const parsed = parseStaticBorder(v);
- const side = sideMatch[1][0].toUpperCase() + sideMatch[1].slice(1);
- return [
- ...(parsed.width ? [[`border${side}Width`, parsed.width]] : []),
- ...(parsed.color ? [[`border${side}Color`, parsed.color]] : []),
- ];
- }
- if (p === 'border-width') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopWidth', vals[0]],
- ['borderRightWidth', vals[1]],
- ['borderBottomWidth', vals[2]],
- ['borderLeftWidth', vals[3]],
- ];
- }
- if (p === 'border-color') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopColor', vals[0]],
- ['borderRightColor', vals[1]],
- ['borderBottomColor', vals[2]],
- ['borderLeftColor', vals[3]],
- ];
- }
- if (p === 'padding') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['paddingTop', vals[0]],
- ['paddingRight', vals[1]],
- ['paddingBottom', vals[2]],
- ['paddingLeft', vals[3]],
- ];
- }
- if (p === 'font') return parseStaticFont(v);
- if (p === 'transition') {
- const parsed = parseStaticTransition(v);
- return [
- ...(parsed.property ? [['transitionProperty', parsed.property]] : []),
- ...(parsed.timing ? [['transitionTimingFunction', parsed.timing]] : []),
- ];
- }
- if (p === 'animation') {
- const parsed = parseStaticAnimation(v);
- return [
- ...(parsed.name ? [['animationName', parsed.name]] : []),
- ...(parsed.timing ? [['animationTimingFunction', parsed.timing]] : []),
- ];
- }
- const mapped = cssPropToCamel(p);
- if (STATIC_DEFAULT_STYLE[mapped] != null || STATIC_INHERITED_PROPS.has(mapped)) {
- return [[mapped, v]];
- }
- return [];
-}
-
-function compareStaticPriority(a, b) {
- if (!a) return true;
- if (!!b.important !== !!a.important) return !!b.important;
- if (!!b.inline !== !!a.inline) return !!b.inline;
- for (let i = 0; i < 3; i++) {
- if ((b.specificity[i] || 0) !== (a.specificity[i] || 0)) {
- return (b.specificity[i] || 0) > (a.specificity[i] || 0);
- }
- }
- return b.order >= a.order;
-}
-
-function staticSpecificity(selector) {
- const noWhere = selector.replace(/:where\([^)]*\)/g, '');
- const ids = (noWhere.match(/#[\w-]+/g) || []).length;
- const classes = (noWhere.match(/\.[\w-]+|\[[^\]]+\]|:(?!:)[\w-]+(?:\([^)]*\))?/g) || []).length;
- const stripped = noWhere
- .replace(/#[\w-]+/g, ' ')
- .replace(/\.[\w-]+|\[[^\]]+\]|:{1,2}[\w-]+(?:\([^)]*\))?/g, ' ')
- .replace(/[*>+~(),]/g, ' ');
- const types = (stripped.match(/\b[a-zA-Z][\w-]*\b/g) || []).length;
- return [ids, classes, types];
-}
-
-function applyStaticDeclaration(specified, node, prop, value, meta) {
- let map = specified.get(node);
- if (!map) { map = new Map(); specified.set(node, map); }
- for (const [expandedProp, expandedValue] of expandStaticDeclaration(prop, value)) {
- const existing = map.get(expandedProp);
- const next = { ...meta, prop: expandedProp, value: expandedValue };
- if (compareStaticPriority(existing, next)) map.set(expandedProp, next);
- }
-}
-
-function parseStaticStyleAttribute(styleText, orderBase = 0) {
- const decls = [];
- for (const part of String(styleText || '').split(';')) {
- const idx = part.indexOf(':');
- if (idx <= 0) continue;
- const prop = part.slice(0, idx).trim();
- let value = part.slice(idx + 1).trim();
- const important = /!important\s*$/i.test(value);
- value = value.replace(/\s*!important\s*$/i, '').trim();
- decls.push({ prop, value, important, order: orderBase + decls.length });
- }
- return decls;
-}
-
-function collectStaticCssRules(cssText, csstree) {
- const rules = [];
- let ast;
- try {
- ast = csstree.parse(cssText, { positions: false, parseValue: true, parseCustomProperty: false });
- } catch {
- return rules;
- }
- let order = 0;
- const walkList = (list, atRuleStack = []) => {
- list?.forEach?.(node => {
- if (node.type === 'Rule' && node.block) {
- if (atRuleStack.some(name => /keyframes$/i.test(name))) return;
- const selectorText = csstree.generate(node.prelude).trim();
- const declarations = [];
- node.block.children?.forEach?.(child => {
- if (child.type !== 'Declaration') return;
- declarations.push({
- prop: child.property,
- value: csstree.generate(child.value).trim(),
- important: !!child.important,
- });
- });
- for (const selector of splitCssList(selectorText)) {
- if (selector) rules.push({ selector, declarations, specificity: staticSpecificity(selector), order: order++ });
- }
- return;
- }
- if (node.type === 'Atrule' && node.block) {
- const name = String(node.name || '').toLowerCase();
- if (name === 'media' || name === 'supports' || name === 'layer') {
- walkList(node.block.children, [...atRuleStack, name]);
- }
- }
- });
- };
- walkList(ast.children);
- return rules;
-}
-
-class StaticElement {
- constructor(node, doc) {
- this.node = node;
- this._doc = doc;
- this.nodeType = 1;
- this.tagName = String(node.name || '').toUpperCase();
- this.nodeName = this.tagName;
- }
- get parentElement() {
- let cur = this.node.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- return cur ? this._doc.wrap(cur) : null;
- }
- get previousElementSibling() {
- let cur = this.node.prev;
- while (cur && cur.type !== 'tag') cur = cur.prev;
- return cur ? this._doc.wrap(cur) : null;
- }
- get children() {
- return (this.node.children || []).filter(child => child.type === 'tag').map(child => this._doc.wrap(child));
- }
- get childNodes() {
- return (this.node.children || []).map(child => {
- if (child.type === 'text') return { nodeType: 3, textContent: child.data || '' };
- if (child.type === 'tag') return this._doc.wrap(child);
- return { nodeType: 8, textContent: child.data || '' };
- });
- }
- get textContent() {
- return this._doc.domutils.textContent(this.node);
- }
- get className() {
- return this.getAttribute('class') || '';
- }
- get id() {
- return this.getAttribute('id') || '';
- }
- getAttribute(name) {
- return this.node.attribs?.[name] ?? null;
- }
- querySelector(selector) {
- try {
- const found = this._doc.selectOne(selector, this.node.children || []);
- return found ? this._doc.wrap(found) : null;
- } catch {
- return null;
- }
- }
- querySelectorAll(selector) {
- try {
- return this._doc.selectAll(selector, this.node.children || []).map(node => this._doc.wrap(node));
- } catch {
- return [];
- }
- }
- closest(selector) {
- let cur = this.node;
- while (cur && cur.type === 'tag') {
- try {
- if (this._doc.is(cur, selector)) return this._doc.wrap(cur);
- } catch {
- return null;
- }
- cur = cur.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- }
- return null;
- }
- contains(other) {
- let cur = other?.node || null;
- while (cur) {
- if (cur === this.node) return true;
- cur = cur.parent;
- }
- return false;
- }
-}
-
-class StaticDocument {
- constructor(root, modules) {
- this.root = root;
- this.selectAll = modules.selectAll;
- this.selectOne = modules.selectOne;
- this.is = modules.is;
- this.domutils = modules.domutils;
- this._wrappers = new WeakMap();
- this._styleMap = new WeakMap();
- }
- wrap(node) {
- let wrapped = this._wrappers.get(node);
- if (!wrapped) {
- wrapped = new StaticElement(node, this);
- this._wrappers.set(node, wrapped);
- }
- return wrapped;
- }
- querySelectorAll(selector) {
- try {
- return this.selectAll(selector, this.root.children || []).map(node => this.wrap(node));
- } catch {
- return [];
- }
- }
- querySelector(selector) {
- try {
- const found = this.selectOne(selector, this.root.children || []);
- return found ? this.wrap(found) : null;
- } catch {
- return null;
- }
- }
- get documentElement() {
- return this.querySelector('html');
- }
- get body() {
- return this.querySelector('body');
- }
- setStyle(node, style) {
- this._styleMap.set(node, style);
- }
- getStyle(el) {
- return this._styleMap.get(el.node) || makeStaticStyle();
- }
-}
-
-function makeStaticStyle(values = {}) {
- const style = { ...STATIC_DEFAULT_STYLE, ...values };
- style.getPropertyValue = (prop) => {
- const key = cssPropToCamel(prop);
- return style[key] || style[prop] || '';
- };
- return style;
-}
-
-function buildStaticWindow(staticDoc) {
- return {
- document: staticDoc,
- getComputedStyle: (el) => staticDoc.getStyle(el),
- };
-}
-
-function collectStaticCssText(root, fileDir, profile, filePath, modules) {
- const styleTexts = [];
- for (const styleEl of modules.selectAll('style', root.children || [])) {
- styleTexts.push(modules.domutils.textContent(styleEl));
- }
- const links = modules.selectAll('link', root.children || []);
- for (const link of links) {
- const rel = link.attribs?.rel || '';
- const href = link.attribs?.href || '';
- if (!/\bstylesheet\b/i.test(rel) || !href || /^(https?:)?\/\//i.test(href)) continue;
- const cssPath = path.resolve(fileDir, href);
- try {
- const css = profileStep(profile, {
- engine: 'static-html',
- phase: 'preprocess',
- ruleId: 'inline-linked-stylesheet',
- target: filePath,
- detail: href,
- }, () => fs.readFileSync(cssPath, 'utf-8'));
- styleTexts.push(css);
- } catch { /* skip unreadable */ }
- }
- return styleTexts.join('\n');
-}
-
-function buildStaticStyleMap(root, staticDoc, cssText, modules, profile, filePath) {
- const specified = new Map();
- const allNodes = modules.selectAll('*', root.children || []);
- const rules = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-css',
- ruleId: 'css-rules',
- target: filePath,
- }, () => collectStaticCssRules(cssText, modules.csstree));
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'css-selectors',
- target: filePath,
- }, () => {
- for (const rule of rules) {
- let matched;
- try {
- matched = modules.selectAll(rule.selector, root.children || []);
- } catch {
- recordProfileEvent(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'unsupported-selector',
- target: filePath,
- ms: 0,
- findings: 0,
- detail: rule.selector,
- });
- continue;
- }
- for (const node of matched) {
- for (const decl of rule.declarations) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: rule.specificity,
- order: rule.order,
- inline: false,
- });
- }
- }
- }
-
- let inlineOrder = rules.length + 1;
- for (const node of allNodes) {
- const styleText = node.attribs?.style;
- if (!styleText) continue;
- for (const decl of parseStaticStyleAttribute(styleText, inlineOrder)) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: [1, 0, 0],
- order: decl.order,
- inline: true,
- });
- }
- inlineOrder += 1000;
- }
- });
-
- const computeNode = (node, parentStyle = null, parentCustom = new Map()) => {
- const specifiedMap = specified.get(node) || new Map();
- const customProps = new Map(parentCustom);
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) customProps.set(prop, resolveVarRefs(decl.value, customProps));
- }
- const values = {};
- for (const prop of Object.keys(STATIC_DEFAULT_STYLE)) {
- if (STATIC_INHERITED_PROPS.has(prop) && parentStyle?.[prop] != null) values[prop] = parentStyle[prop];
- else values[prop] = STATIC_DEFAULT_STYLE[prop];
- }
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) continue;
- values[prop] = normalizeStaticCssValue(prop, decl.value, customProps, parentStyle, values);
- }
- const style = makeStaticStyle(values);
- staticDoc.setStyle(node, style);
- for (const child of node.children || []) {
- if (child.type === 'tag') computeNode(child, style, customProps);
- }
- };
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'cascade',
- ruleId: 'compute-styles',
- target: filePath,
- }, () => {
- for (const child of root.children || []) {
- if (child.type === 'tag') computeNode(child);
- }
- });
-}
-
-export {
- BORDER_SHORTHAND_RE,
- NAMED_COLORS,
- normalizeColorForCheck,
- buildBorderOverrideMap,
- unwrapCssAtLayer,
- STATIC_INHERITED_PROPS,
- STATIC_DEFAULT_STYLE,
- STATIC_PROP_MAP,
- STATIC_NAMED_COLORS,
- splitCssList,
- splitCssTokens,
- cssPropToCamel,
- staticColorToCss,
- parseStaticColor,
- extractStaticColor,
- normalizeStaticCssValue,
- expandStaticBoxValues,
- parseStaticBorder,
- parseStaticFont,
- parseStaticTransition,
- parseStaticAnimation,
- expandStaticDeclaration,
- compareStaticPriority,
- staticSpecificity,
- applyStaticDeclaration,
- parseStaticStyleAttribute,
- collectStaticCssRules,
- StaticElement,
- StaticDocument,
- makeStaticStyle,
- buildStaticWindow,
- collectStaticCssText,
- buildStaticStyleMap,
-};
@@ -1,174 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import {
- checkElementBorders,
- checkElementColors,
- checkElementGlow,
- checkElementHeroEyebrow,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementMotion,
- checkElementQuality,
- checkHtmlPatterns,
- checkPageLayout,
- checkPageQualityFromDoc,
- checkRepeatedSectionKickersFromDoc,
- resolveBackground,
- resolveBorderRadiusPx,
-} from '../../rules/checks.mjs';
-import { detectText } from '../regex/detect-text.mjs';
-import {
- StaticDocument,
- buildStaticStyleMap,
- buildStaticWindow,
- collectStaticCssText,
-} from './css-cascade.mjs';
-
-function checkStaticPageTypography(document, window) {
- const findings = [];
- const fonts = new Set();
- const overusedFound = new Set();
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span, div')) {
- const hasText = el.childNodes.some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const ff = window.getComputedStyle(el).fontFamily || '';
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
- if (fonts.size === 1 && document.querySelectorAll('*').length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div')) {
- const fontSize = parseFloat(window.getComputedStyle(el).fontSize);
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
- return findings;
-}
-
-const STATIC_ELEMENT_RULES = [
- { id: 'border-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementBorders(tag, style, null, resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window)) },
- { id: 'color-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementColors(el, style, tag, window, customPropMap, false) },
- { id: 'dark-glow', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window, customPropMap)) },
- { id: 'motion-rules', selector: '*', run: (el, tag, style) => checkElementMotion(tag, style) },
- { id: 'icon-tile-stack', selector: 'h1,h2,h3,h4,h5,h6', run: (el, tag, _style, window) => checkElementIconTile(el, tag, window) },
- { id: 'italic-serif-display', selector: 'h1,h2', run: (el, tag, style) => checkElementItalicSerif(el, style, tag) },
- { id: 'hero-eyebrow-chip', selector: 'h1', run: (el, tag, style, window, customPropMap) => checkElementHeroEyebrow(el, style, tag, window, customPropMap) },
- { id: 'quality-rules', selector: '*', run: (el, tag, style, window) => checkElementQuality(el, style, tag, window) },
-];
-
-async function detectHtml(filePath, options = {}) {
- const profile = options?.profile;
- const html = profileStep(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'read-html',
- target: filePath,
- }, () => fs.readFileSync(filePath, 'utf-8'));
-
- let modules;
- try {
- modules = await profileStepAsync(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'import-static-parser',
- target: filePath,
- }, async () => {
- const [htmlparser2, cssSelect, csstree, domutils] = await Promise.all([
- import('htmlparser2'),
- import('css-select'),
- import('css-tree'),
- import('domutils'),
- ]);
- return {
- parseDocument: htmlparser2.parseDocument,
- selectAll: cssSelect.selectAll,
- selectOne: cssSelect.selectOne,
- is: cssSelect.is,
- csstree,
- domutils,
- };
- });
- } catch {
- return detectText(html, filePath, options);
- }
-
- const resolvedPath = path.resolve(filePath);
- const fileDir = path.dirname(resolvedPath);
- const root = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-html',
- ruleId: 'parse-document',
- target: filePath,
- }, () => modules.parseDocument(html, { lowerCaseAttributeNames: false, lowerCaseTags: true }));
-
- const cssText = collectStaticCssText(root, fileDir, profile, filePath, modules);
- const document = new StaticDocument(root, modules);
- buildStaticStyleMap(root, document, cssText, modules, profile, filePath);
- const window = buildStaticWindow(document);
-
- const customPropMap = null;
-
- const findings = [];
- const runElementCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'element', ruleId, target: filePath }, callback)
- : callback();
-
- const visitedByRule = new Map();
- for (const rule of STATIC_ELEMENT_RULES) {
- const elements = document.querySelectorAll(rule.selector);
- visitedByRule.set(rule.id, elements.length);
- for (const el of elements) {
- const tag = el.tagName.toLowerCase();
- const style = window.getComputedStyle(el);
- for (const f of runElementCheck(rule.id, () => rule.run(el, tag, style, window, customPropMap))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
- }
-
- if (isFullPage(html)) {
- const runPageCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
- : callback();
- for (const f of runPageCheck('typography-rules', () => checkStaticPageTypography(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('repeated-section-kickers', () => checkRepeatedSectionKickersFromDoc(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('layout-rules', () => checkPageLayout(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('skipped-heading', () => checkPageQualityFromDoc(document))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('html-patterns', () => checkHtmlPatterns(html).filter(item =>
- item.id !== 'bounce-easing' && item.id !== 'layout-transition'
- ))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
-
- return findings;
-}
-
-export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -1,189 +0,0 @@
-function sanitizeScreenshotClip(clip, viewport) {
- if (!clip) return null;
- const x = Math.max(0, Math.floor(clip.x || 0));
- const y = Math.max(0, Math.floor(clip.y || 0));
- const width = Math.min(
- Math.max(1, Math.ceil(clip.width || 0)),
- Math.max(1, viewport?.width || 1600),
- );
- const height = Math.min(
- Math.max(1, Math.ceil(clip.height || 0)),
- 320,
- );
- if (width < 1 || height < 1) return null;
- return { x, y, width, height };
-}
-
-async function compareScreenshotContrast(page, beforeBase64, afterBase64, candidate) {
- return page.evaluate(async ({ beforeBase64, afterBase64, candidate }) => {
- const loadImage = (base64) => new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = () => reject(new Error('Could not decode contrast screenshot'));
- img.src = `data:image/png;base64,${base64}`;
- });
- const [before, after] = await Promise.all([loadImage(beforeBase64), loadImage(afterBase64)]);
- const width = Math.min(before.width, after.width);
- const height = Math.min(before.height, after.height);
- if (width < 1 || height < 1) return null;
-
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return null;
-
- ctx.drawImage(before, 0, 0, width, height);
- const beforePixels = ctx.getImageData(0, 0, width, height).data;
- ctx.clearRect(0, 0, width, height);
- ctx.drawImage(after, 0, 0, width, height);
- const afterPixels = ctx.getImageData(0, 0, width, height).data;
-
- const luminance = ({ r, g, b }) => {
- const convert = c => {
- const v = c / 255;
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
- };
- return 0.2126 * convert(r) + 0.7152 * convert(g) + 0.0722 * convert(b);
- };
- const ratio = (a, b) => {
- const l1 = luminance(a);
- const l2 = luminance(b);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
- };
-
- const cssTextColor = candidate.textColor && !candidate.preferRenderedForeground
- ? {
- r: candidate.textColor.r,
- g: candidate.textColor.g,
- b: candidate.textColor.b,
- }
- : null;
- const ratios = [];
- let glyphPixels = 0;
- let strongestDelta = 0;
- for (let i = 0; i < beforePixels.length; i += 4) {
- const delta = Math.abs(beforePixels[i] - afterPixels[i])
- + Math.abs(beforePixels[i + 1] - afterPixels[i + 1])
- + Math.abs(beforePixels[i + 2] - afterPixels[i + 2])
- + Math.abs(beforePixels[i + 3] - afterPixels[i + 3]);
- strongestDelta = Math.max(strongestDelta, delta);
- if (delta < 10) continue;
- glyphPixels++;
- const fg = cssTextColor || {
- r: beforePixels[i],
- g: beforePixels[i + 1],
- b: beforePixels[i + 2],
- };
- const bg = {
- r: afterPixels[i],
- g: afterPixels[i + 1],
- b: afterPixels[i + 2],
- };
- ratios.push(ratio(fg, bg));
- }
-
- if (ratios.length < 8) {
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: null,
- p10Ratio: null,
- medianRatio: null,
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: ratios[0],
- p10Ratio: pick(10),
- medianRatio: pick(50),
- };
- }, { beforeBase64, afterBase64, candidate });
-}
-
-async function captureVisualContrastCandidate(page, candidate, viewport) {
- const clip = sanitizeScreenshotClip(candidate.clip, viewport);
- if (!clip) return null;
-
- const beforeBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- const token = `impeccable-contrast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- const applied = await page.evaluate(({ selector, token, backgroundClipText }) => {
- let el;
- try {
- el = document.querySelector(selector);
- } catch {
- return false;
- }
- if (!el) return false;
- let style = document.getElementById('impeccable-visual-contrast-hide-style');
- if (!style) {
- style = document.createElement('style');
- style.id = 'impeccable-visual-contrast-hide-style';
- style.textContent = [
- '[data-impeccable-visual-contrast-target] {',
- ' color: transparent !important;',
- ' -webkit-text-fill-color: transparent !important;',
- ' text-shadow: none !important;',
- '}',
- '[data-impeccable-visual-contrast-target][data-impeccable-bgclip-text="true"] {',
- ' background-image: none !important;',
- '}',
- ].join('\n');
- document.head.appendChild(style);
- }
- el.setAttribute('data-impeccable-visual-contrast-target', token);
- if (backgroundClipText) el.setAttribute('data-impeccable-bgclip-text', 'true');
- return true;
- }, {
- selector: candidate.selector,
- token,
- backgroundClipText: candidate.backgroundClipText,
- });
- if (!applied) return null;
-
- let afterBase64;
- try {
- afterBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- } finally {
- await page.evaluate(({ selector }) => {
- try {
- const el = document.querySelector(selector);
- if (el) {
- el.removeAttribute('data-impeccable-visual-contrast-target');
- el.removeAttribute('data-impeccable-bgclip-text');
- }
- } catch {
- // Ignore invalid or stale selectors during cleanup.
- }
- }, { selector: candidate.selector }).catch(() => {});
- }
-
- const metrics = await compareScreenshotContrast(page, beforeBase64, afterBase64, candidate);
- if (!metrics || !Number.isFinite(metrics.p10Ratio) || metrics.glyphPixels < 8) return null;
- const measuredRatio = metrics.p10Ratio;
- if (measuredRatio >= candidate.threshold) return null;
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const reasonLabel = (candidate.reasons || []).slice(0, 3).join(', ') || 'visual background';
- return {
- id: 'low-contrast',
- snippet: `pixel contrast ${measuredRatio.toFixed(1)}:1 median ${metrics.medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) on ${reasonLabel}${textLabel}`,
- };
-}
-
-export {
- sanitizeScreenshotClip,
- compareScreenshotContrast,
- captureVisualContrastCandidate,
-};
@@ -1,12 +0,0 @@
-import { getAntipattern } from './registry/antipatterns.mjs';
-
-function getAP(id) {
- return getAntipattern(id);
-}
-
-function finding(id, filePath, snippet, line = 0) {
- const ap = getAP(id);
- return { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', file: filePath, line, snippet };
-}
-
-export { getAP, finding };
@@ -1,198 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-// ---------------------------------------------------------------------------
-// File walker
-// ---------------------------------------------------------------------------
-
-const SKIP_DIRS = new Set([
- 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
- '.svelte-kit', '__pycache__', '.turbo', '.vercel',
-]);
-
-const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
- '.jsx', '.tsx', '.js', '.ts',
- '.vue', '.svelte', '.astro',
-]);
-
-const HTML_EXTENSIONS = new Set(['.html', '.htm']);
-
-function walkDir(dir) {
- const files = [];
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
- for (const entry of entries) {
- if (SKIP_DIRS.has(entry.name)) continue;
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) files.push(...walkDir(full));
- else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
- }
- return files;
-}
-
-
-// ---------------------------------------------------------------------------
-// Import graph (multi-file awareness)
-// ---------------------------------------------------------------------------
-
-function resolveImport(specifier, fromDir, fileSet) {
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
- const base = path.resolve(fromDir, specifier);
- if (fileSet.has(base)) return base;
- for (const ext of SCANNABLE_EXTENSIONS) {
- const withExt = base + ext;
- if (fileSet.has(withExt)) return withExt;
- }
- // index file convention
- for (const ext of SCANNABLE_EXTENSIONS) {
- const indexFile = path.join(base, 'index' + ext);
- if (fileSet.has(indexFile)) return indexFile;
- }
- return null;
-}
-
-function buildImportGraph(files) {
- const fileSet = new Set(files);
- const graph = new Map();
-
- for (const file of files) {
- const content = fs.readFileSync(file, 'utf-8');
- const dir = path.dirname(file);
- const imports = new Set();
-
- // ES imports: import ... from '...' and import '...'
- const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
- let m;
- while ((m = esRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // CSS @import
- const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
- while ((m = cssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // SCSS @use / @forward
- const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
- while ((m = scssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- graph.set(file, imports);
- }
- return graph;
-}
-
-// ---------------------------------------------------------------------------
-// Framework dev server detection
-// ---------------------------------------------------------------------------
-
-const FRAMEWORK_CONFIGS = [
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /next/i } },
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-sveltekit-page', value: null } },
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /@vite\/client/ } },
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /astro/i } },
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
- portRe: /"port"\s*:\s*(\d+)/,
- fingerprint: { body: /ng-version/i } },
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
-];
-
-function detectFrameworkConfig(dir) {
- let entries;
- try { entries = fs.readdirSync(dir); } catch { return null; }
- const entrySet = new Set(entries);
-
- for (const cfg of FRAMEWORK_CONFIGS) {
- const match = cfg.files.find(f => entrySet.has(f));
- if (!match) continue;
-
- const configPath = path.join(dir, match);
- let port = cfg.defaultPort;
- try {
- const content = fs.readFileSync(configPath, 'utf-8');
- const portMatch = content.match(cfg.portRe);
- if (portMatch) port = parseInt(portMatch[1], 10);
- } catch { /* use default */ }
-
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
- }
- return null;
-}
-
-/**
- * Check if a port is listening and optionally verify it matches the expected framework.
- * Returns { listening: true, matched: true/false } or { listening: false }.
- */
-async function isPortListening(port, fingerprint = null) {
- if (!fingerprint) {
- // Simple TCP probe fallback
- const net = await import('node:net');
- return new Promise((resolve) => {
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
- sock.setTimeout(500);
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
- sock.on('error', () => resolve({ listening: false }));
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
- });
- }
-
- // HTTP probe with fingerprint matching
- try {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 2000);
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
- clearTimeout(timeout);
-
- // Check header fingerprint
- if (fingerprint.header) {
- const val = res.headers.get(fingerprint.header);
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
- return { listening: true, matched: true };
- }
- }
-
- // Check body fingerprint
- if (fingerprint.body) {
- const body = await res.text();
- if (fingerprint.body.test(body)) {
- return { listening: true, matched: true };
- }
- }
-
- // Port is listening but doesn't match the expected framework
- return { listening: true, matched: false };
- } catch {
- return { listening: false };
- }
-}
-
-export {
- SKIP_DIRS,
- SCANNABLE_EXTENSIONS,
- HTML_EXTENSIONS,
- walkDir,
- resolveImport,
- buildImportGraph,
- FRAMEWORK_CONFIGS,
- detectFrameworkConfig,
- isPortListening,
-};
@@ -1,166 +0,0 @@
-function profileNow() {
- return typeof performance !== 'undefined' && performance.now
- ? performance.now()
- : Date.now();
-}
-
-function createDetectorProfile() {
- return { events: [] };
-}
-
-function recordProfileEvent(profile, event) {
- if (!profile) return;
- const normalized = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- ms: Number.isFinite(event.ms) ? event.ms : 0,
- findings: Number.isFinite(event.findings) ? event.findings : 0,
- };
- if (event.detail) normalized.detail = event.detail;
- if (Array.isArray(event.findingIds) && event.findingIds.length) {
- normalized.findingIds = event.findingIds;
- }
- if (typeof profile === 'function') {
- profile(normalized);
- } else if (typeof profile.record === 'function') {
- profile.record(normalized);
- } else if (Array.isArray(profile.events)) {
- profile.events.push(normalized);
- } else if (Array.isArray(profile)) {
- profile.push(normalized);
- }
-}
-
-function extractFindingIds(findings) {
- if (!Array.isArray(findings) || findings.length === 0) return [];
- return [...new Set(findings.map(f => f?.id || f?.type || f?.antipattern).filter(Boolean))];
-}
-
-function profileFindings(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-function profileStep(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-async function profileFindingsAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = await callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-async function profileStepAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return await callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-function percentile(sortedValues, pct) {
- if (!sortedValues.length) return 0;
- const idx = Math.min(
- sortedValues.length - 1,
- Math.max(0, Math.ceil((pct / 100) * sortedValues.length) - 1),
- );
- return sortedValues[idx];
-}
-
-function summarizeDetectorProfile(profile) {
- const events = Array.isArray(profile)
- ? profile
- : (Array.isArray(profile?.events) ? profile.events : []);
- const groups = new Map();
- for (const event of events) {
- const key = [
- event.engine || 'unknown',
- event.phase || 'unknown',
- event.ruleId || 'unknown',
- event.target || '',
- ].join('\u0000');
- let group = groups.get(key);
- if (!group) {
- group = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- calls: 0,
- totalMs: 0,
- findings: 0,
- samples: [],
- };
- groups.set(key, group);
- }
- const ms = Number.isFinite(event.ms) ? event.ms : 0;
- group.calls += 1;
- group.totalMs += ms;
- group.findings += Number.isFinite(event.findings) ? event.findings : 0;
- group.samples.push(ms);
- }
- return [...groups.values()]
- .map(group => {
- const samples = group.samples.sort((a, b) => a - b);
- return {
- engine: group.engine,
- phase: group.phase,
- ruleId: group.ruleId,
- target: group.target,
- calls: group.calls,
- totalMs: Number(group.totalMs.toFixed(3)),
- avgMs: Number((group.totalMs / group.calls).toFixed(3)),
- p50: Number(percentile(samples, 50).toFixed(3)),
- p95: Number(percentile(samples, 95).toFixed(3)),
- findings: group.findings,
- };
- })
- .sort((a, b) => b.totalMs - a.totalMs);
-}
-
-export {
- profileNow,
- createDetectorProfile,
- recordProfileEvent,
- extractFindingIds,
- profileFindings,
- profileStep,
- profileFindingsAsync,
- profileStepAsync,
- percentile,
- summarizeDetectorProfile,
-};
@@ -1,278 +0,0 @@
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-const RULE_ENGINE_SUPPORT = {
- regex: new Set(['source', 'page-analyzer']),
- 'static-html': new Set(['element', 'page']),
- browser: new Set(['element', 'page', 'layout']),
- visual: new Set(['visual-contrast']),
-};
-
-function getAntipattern(id) {
- return ANTIPATTERNS.find(rule => rule.id === id);
-}
-
-function getRulesForCategory(category) {
- return ANTIPATTERNS.filter(rule => rule.category === category);
-}
-
-function getRuleEngineSupport(engine) {
- return RULE_ENGINE_SUPPORT[engine] || new Set();
-}
-
-export {
- ANTIPATTERNS,
- RULE_ENGINE_SUPPORT,
- getAntipattern,
- getRulesForCategory,
- getRuleEngineSupport,
-};
@@ -1,1948 +0,0 @@
-import {
- BORDER_SAFE_TAGS,
- GENERIC_FONTS,
- KNOWN_SERIF_FONTS,
- OVERUSED_FONTS,
- SAFE_TAGS,
- WCAG_LARGE_BOLD_TEXT_PX,
- WCAG_LARGE_TEXT_PX,
- isBrandFontOnOwnDomain,
-} from '../shared/constants.mjs';
-import {
- colorToHex,
- contrastRatio,
- getHue,
- hasChroma,
- isNeutralColor,
- parseGradientColors,
- parseRgb,
- relativeLuminance,
-} from '../shared/color.mjs';
-
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-export {
- checkBorders,
- isEmojiOnlyText,
- checkColors,
- isCardLikeFromProps,
- checkIconTile,
- resolveSerif,
- checkItalicSerif,
- isAccentColor,
- checkHeroEyebrow,
- checkRepeatedSectionKickers,
- checkMotion,
- checkGlow,
- checkHtmlPatterns,
- readOwnBackgroundColor,
- resolveBackground,
- resolveGradientStops,
- parseRadiusToPx,
- resolveBorderRadiusPx,
- checkElementBordersDOM,
- checkElementColorsDOM,
- checkElementIconTileDOM,
- checkElementItalicSerifDOM,
- checkElementHeroEyebrowDOM,
- buildCustomPropMap,
- resolveVarRefs,
- oklchToRgb,
- parseAnyColor,
- parseColorResolved,
- cleanInlineText,
- isRepeatedKickerCandidate,
- collectRepeatedSectionKickerCandidates,
- checkRepeatedSectionKickersDOM,
- checkElementMotionDOM,
- checkElementGlowDOM,
- checkElementAIPaletteDOM,
- resolveFontSizePx,
- resolveLengthPx,
- checkQuality,
- checkElementQualityDOM,
- checkPageQualityFromDoc,
- checkPageQualityDOM,
- checkElementQuality,
- checkElementBorders,
- checkElementColors,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementHeroEyebrow,
- checkRepeatedSectionKickersFromDoc,
- checkElementMotion,
- checkElementGlow,
- checkTypography,
- isCardLikeDOM,
- checkLayout,
- checkPageTypography,
- isCardLike,
- checkPageLayout,
-};
@@ -1,124 +0,0 @@
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-export {
- isNeutralColor,
- parseRgb,
- relativeLuminance,
- contrastRatio,
- parseGradientColors,
- hasChroma,
- getHue,
- colorToHex,
-};
@@ -1,101 +0,0 @@
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-export {
- SAFE_TAGS,
- BORDER_SAFE_TAGS,
- OVERUSED_FONTS,
- GOOGLE_DOMAINS,
- VERCEL_DOMAINS,
- GITHUB_DOMAINS,
- BRAND_FONT_DOMAINS,
- isBrandFontOnOwnDomain,
- GENERIC_FONTS,
- WCAG_LARGE_TEXT_PX,
- WCAG_LARGE_BOLD_TEXT_PX,
- KNOWN_SERIF_FONTS,
-};
@@ -1,7 +0,0 @@
-/** Check if content looks like a full page (not a component/partial) */
-function isFullPage(content) {
- const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
- return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
-}
-
-export { isFullPage };
@@ -1,110 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-export const IMPECCABLE_DIR = '.impeccable';
-export const LIVE_DIR = 'live';
-export const CRITIQUE_DIR = 'critique';
-
-export function getImpeccableDir(cwd = process.cwd()) {
- return path.join(cwd, IMPECCABLE_DIR);
-}
-
-export function getDesignSidecarPath(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), 'design.json');
-}
-
-export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {
- const candidates = [
- getDesignSidecarPath(cwd),
- path.join(cwd, 'DESIGN.json'),
- ];
- const contextLegacy = path.join(contextDir, 'DESIGN.json');
- if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
- return candidates;
-}
-
-export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
- return firstExisting(getDesignSidecarCandidates(cwd, contextDir));
-}
-
-export function getLiveDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), LIVE_DIR);
-}
-
-export function getLiveConfigPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'config.json');
-}
-
-export function getLegacyLiveConfigPath(scriptsDir) {
- return path.join(scriptsDir, 'config.json');
-}
-
-export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {
- if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
- const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
- return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
- }
- const primary = getLiveConfigPath(cwd);
- if (fs.existsSync(primary)) return primary;
- if (scriptsDir) {
- const legacy = getLegacyLiveConfigPath(scriptsDir);
- if (fs.existsSync(legacy)) return legacy;
- }
- return primary;
-}
-
-export function getLiveServerPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'server.json');
-}
-
-export function getLegacyLiveServerPath(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live.json');
-}
-
-export function readLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try {
- return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };
- } catch {
- /* try next */
- }
- }
- return null;
-}
-
-export function writeLiveServerInfo(cwd = process.cwd(), info) {
- const filePath = getLiveServerPath(cwd);
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- fs.writeFileSync(filePath, JSON.stringify(info));
- return filePath;
-}
-
-export function removeLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try { fs.unlinkSync(filePath); } catch {}
- }
-}
-
-export function getLiveSessionsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'sessions');
-}
-
-export function getLegacyLiveSessionsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'sessions');
-}
-
-export function getLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'annotations');
-}
-
-export function getCritiqueDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), CRITIQUE_DIR);
-}
-
-export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'annotations');
-}
-
-function firstExisting(paths) {
- return paths.find((filePath) => fs.existsSync(filePath)) || null;
-}
@@ -1,69 +0,0 @@
-/**
- * Decide whether a given file is "generated" (regenerated by a build step,
- * unsafe to write variants into) or "source" (safe to edit, changes persist).
- *
- * Why this matters: when the user picks an element on a page whose underlying
- * file is regenerated by a build step (e.g. `scripts/build-sub-pages.js`
- * rewriting `public/docs/*.html`), writing variants or accepted changes into
- * that file is silent data loss — the next build wipes them.
- *
- * Signals, in order of reliability:
- * 1. Git check-ignore: gitignored files are assumed generated.
- * 2. File-header markers ("GENERATED", "DO NOT EDIT", "AUTO-GENERATED")
- * within the first ~300 characters — catches non-git projects.
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-
-const HEADER_SCAN_BYTES = 300;
-const HEADER_MARKERS = [
- /@generated\b/i,
- /\bGENERATED\s+FILE\b/,
- /\bAUTO-?GENERATED\b/i,
- /\bDO\s+NOT\s+EDIT\b/i,
-];
-
-/**
- * @param {string} filePath - absolute or cwd-relative path
- * @param {object} [options]
- * @param {string} [options.cwd] - project root (defaults to process.cwd())
- */
-export function isGeneratedFile(filePath, options = {}) {
- const cwd = options.cwd || process.cwd();
- const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
-
- if (isGitIgnored(absPath, cwd)) return true;
- if (hasGeneratedHeader(absPath)) return true;
- return false;
-}
-
-function isGitIgnored(absPath, cwd) {
- try {
- execSync(`git check-ignore --quiet ${JSON.stringify(absPath)}`, {
- cwd,
- stdio: 'ignore',
- });
- return true; // exit 0 = ignored
- } catch (err) {
- // Exit code 1 = not ignored. Exit code 128 = not a git repo or other error.
- // In both cases, treat as "not known to be ignored."
- return false;
- }
-}
-
-function hasGeneratedHeader(absPath) {
- let fd;
- try {
- fd = fs.openSync(absPath, 'r');
- const buf = Buffer.alloc(HEADER_SCAN_BYTES);
- const bytesRead = fs.readSync(fd, buf, 0, HEADER_SCAN_BYTES, 0);
- const head = buf.slice(0, bytesRead).toString('utf-8');
- return HEADER_MARKERS.some((re) => re.test(head));
- } catch {
- return false;
- } finally {
- if (fd !== undefined) { try { fs.closeSync(fd); } catch {} }
- }
-}
@@ -1,595 +0,0 @@
-/**
- * CLI helper: deterministic accept/discard of variant sessions.
- *
- * Usage:
- * node live-accept.mjs --id SESSION_ID --discard
- * node live-accept.mjs --id SESSION_ID --variant N
- *
- * For discard: removes the entire variant wrapper and restores the original.
- * For accept: replaces the wrapper with the chosen variant's content. If the
- * session had a colocated <style> block, it's preserved with carbonize markers
- * for a background agent to integrate into the project's CSS.
- *
- * Output: JSON to stdout.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-export async function acceptCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-accept.mjs [options]
-
-Deterministic accept/discard for live variant sessions.
-
-Modes:
- --discard Remove variants, restore original
- --variant N Accept variant N, discard the rest
-
-Required:
- --id SESSION_ID Session ID of the variant wrapper
-
-Output (JSON):
- { handled, file, carbonize }`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const variantNum = argVal(args, '--variant');
- const paramValuesRaw = argVal(args, '--param-values');
- const isDiscard = args.includes('--discard');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }
-
- let paramValues = null;
- if (paramValuesRaw) {
- try { paramValues = JSON.parse(paramValuesRaw); }
- catch { paramValues = null; } // malformed blob: skip the comment rather than failing the accept
- }
-
- // Find the file containing this session's markers
- const found = findSessionFile(id, process.cwd());
- if (!found) {
- console.log(JSON.stringify({ handled: false, error: 'Session markers not found for id: ' + id }));
- process.exit(0);
- }
-
- const { file: targetFile, content, lines } = found;
- const relFile = path.relative(process.cwd(), targetFile);
-
- // Bail if the session lives in a generated file. The agent manually wrote
- // the wrapper there for preview, and is responsible for writing the
- // accepted variant to true source (or cleaning up on discard). See
- // "Handle fallback" in live.md.
- if (isGeneratedFile(targetFile, { cwd: process.cwd() })) {
- console.log(JSON.stringify({
- handled: false,
- mode: 'fallback',
- file: relFile,
- hint: 'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.',
- }));
- process.exit(0);
- }
-
- if (isDiscard) {
- const result = handleDiscard(id, lines, targetFile);
- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));
- } else {
- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);
- // Single-line attention-grabber when cleanup is required. The full
- // five-step checklist lives in reference/live.md (loaded once per
- // session); repeating it per-event would waste tokens.
- if (result.carbonize) {
- result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + relFile + '. See reference/live.md "Required after accept".';
- }
- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));
- }
-}
-
-// ---------------------------------------------------------------------------
-// Discard
-// ---------------------------------------------------------------------------
-
-function handleDiscard(id, lines, targetFile) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const original = extractOriginal(lines, block);
- const isJsx = detectCommentSyntax(targetFile).open === '{/*';
- const replaceRange = expandReplaceRange(block, lines, isJsx);
-
- // Restore at the line we're actually replacing FROM, not the marker line.
- // For JSX wrappers the marker comments live INSIDE the outer `<div>`, so
- // `block.start` sits 2 spaces deeper than the original element. Using that
- // as the deindent base would push the restored content 2 spaces too far
- // right on every JSX/TSX session. `replaceRange.start` is the outer wrapper
- // line, which is at the original element's indent for both HTML and JSX.
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
- const restored = deindentContent(original, indent);
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...restored,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
- return {};
-}
-
-// ---------------------------------------------------------------------------
-// Accept
-// ---------------------------------------------------------------------------
-
-function handleAccept(id, variantNum, lines, targetFile, paramValues) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const commentSyntax = detectCommentSyntax(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- // Anchor indent on the line we're replacing FROM (the outer wrapper),
- // not on `block.start` — for JSX that's the marker comment 2 spaces
- // deeper than the original element. See handleDiscard for the full
- // rationale.
- const replaceRange = expandReplaceRange(block, lines, isJsx);
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
-
- // Extract the chosen variant's inner content
- const variantContent = extractVariant(lines, block, variantNum);
- if (!variantContent) return { handled: false, error: 'Variant ' + variantNum + ' not found' };
-
- // Extract CSS block if present
- const cssContent = extractCss(lines, block, id);
-
- // Check if carbonizing is needed:
- // - CSS block exists, OR
- // - variant HTML contains helper classes/attributes that need cleanup
- const variantText = variantContent.join('\n');
- const hasHelperAttrs = variantText.includes('data-impeccable-variant');
- const needsCarbonize = !!(cssContent || hasHelperAttrs);
-
- // Build the replacement
- const restored = deindentContent(variantContent, indent);
- const replacement = [];
-
- if (cssContent) {
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
- // JSX targets need the CSS body wrapped in a template literal so that the
- // `{` and `}` in CSS rules don't get parsed as JSX expressions.
- replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
- // Re-indent CSS content to match
- for (const cssLine of cssContent) {
- replacement.push(indent + cssLine.trimStart());
- }
- replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
- if (paramValues && Object.keys(paramValues).length > 0) {
- // Preserve the user's knob positions for the carbonize-cleanup agent
- // to bake into the final CSS when it collapses scoped rules.
- replacement.push(indent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close);
- }
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close);
- }
-
- // Keep the `@scope ([data-impeccable-variant="N"])` selectors in the
- // carbonize CSS block working visually by re-wrapping the accepted content
- // in a data-impeccable-variant="N" div with `display: contents` (so layout
- // isn't affected). The carbonize agent strips this attribute + wrapper when
- // it moves the CSS to a proper stylesheet.
- //
- // Style attribute syntax has to follow the host file's flavor — JSX files
- // need the object form, otherwise React 19 throws "Failed to set indexed
- // property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
- if (cssContent) {
- const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
- replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
- replacement.push(...restored);
- replacement.push(indent + '</div>');
- } else {
- replacement.push(...restored);
- }
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...replacement,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- return { carbonize: needsCarbonize };
-}
-
-// ---------------------------------------------------------------------------
-// Parsing helpers
-// ---------------------------------------------------------------------------
-
-/**
- * Find the start/end marker lines for a session.
- * Returns { start, end } (0-indexed line numbers) or null.
- */
-function findMarkerBlock(id, lines) {
- let start = -1;
- let end = -1;
- const startPattern = 'impeccable-variants-start ' + id;
- const endPattern = 'impeccable-variants-end ' + id;
-
- for (let i = 0; i < lines.length; i++) {
- if (start === -1 && lines[i].includes(startPattern)) start = i;
- if (lines[i].includes(endPattern)) { end = i; break; }
- }
-
- return (start !== -1 && end !== -1) ? { start, end } : null;
-}
-
-/**
- * Compute the line range to REPLACE (vs. just the marker range to extract
- * from). For JSX/TSX wrappers, live-wrap places the marker comments INSIDE
- * the `<div data-impeccable-variants="ID">` outer wrapper so the picked
- * element's JSX slot keeps a single child — a Fragment `<></>` would have
- * solved the multi-sibling case but failed inside `asChild` / cloneElement
- * parents with "Invalid prop supplied to React.Fragment".
- *
- * That means the marker block is enclosed by the wrapper `<div>` opener
- * (with `data-impeccable-variants="ID"`) and its matching `</div>`. We
- * walk back to the opener and forward to the closer so accept/discard
- * remove the entire scaffold, not just the inner markers.
- *
- * Marker lines themselves stay where they were so extractOriginal /
- * extractVariant / extractCss continue to walk the same range.
- */
-function expandReplaceRange(block, lines, isJsx) {
- if (!isJsx) return { start: block.start, end: block.end };
-
- let { start, end } = block;
-
- // Walk back for the wrapper `<div data-impeccable-variants="..."` opener.
- // The attr may sit on a continuation line of a multi-line opening tag, so
- // also walk to the line that actually contains `<div`.
- for (let i = start - 1; i >= Math.max(0, start - 12); i--) {
- if (/data-impeccable-variants=/.test(lines[i])) {
- let opener = i;
- while (opener > 0 && !/<div\b/.test(lines[opener])) opener--;
- start = opener;
- break;
- }
- }
-
- // Walk forward to the matching `</div>` by div-depth tracking from the
- // wrapper opener. Operate on JOINED text instead of per-line: a
- // multi-line self-closing JSX `<div\n className="spacer"\n/>` would
- // fool per-line regex tracking (the `<div` line matches openRe but the
- // `/>` line never matches selfCloseRe since it needs `<div` on the same
- // line). That left depth permanently over-counted and the wrapper's
- // outer `</div>` orphaned after accept/discard. Single regex with
- // `[^>]*?` (which spans newlines in JS) handles either form correctly.
- const joined = lines.slice(start).join('\n');
- // Match either `<div … />` (self-close, group 1 is `/`), `<div … >`
- // (open, group 1 is empty), or `</div>`.
- const tagRe = /<div\b[^>]*?(\/?)>|<\/div\s*>/g;
- let depth = 0;
- let m;
- while ((m = tagRe.exec(joined)) !== null) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && m[1] === '/';
- if (isClose) depth--;
- else if (!isSelfClose) depth++;
- if (depth <= 0) {
- // m.index is offset within `joined`; convert back to a file line.
- const linesBefore = joined.slice(0, m.index + m[0].length).split('\n').length - 1;
- const candidateEnd = start + linesBefore;
- if (candidateEnd >= end) {
- end = candidateEnd;
- break;
- }
- }
- }
-
- return { start, end };
-}
-
-/**
- * Join wrapper lines into a single string with `<style>` elements removed so
- * marker matching and div-depth tracking aren't confused by:
- * - CSS `@scope ([data-impeccable-variant="N"])` strings that look like the
- * HTML marker we're searching for
- * - JSX self-closing `<style ... />` (no separate `</style>` to close on)
- * - Same-line `<style>…</style>` blocks
- * - Multi-line `<style>\n…\n</style>` blocks
- */
-function stripStyleAndJoin(lines, block) {
- const out = [];
- let inStyle = false;
- for (let i = block.start; i <= block.end; i++) {
- let line = lines[i];
-
- if (!inStyle) {
- // Strip any complete <style> elements on this line (self-closed or
- // same-line-closed), including their body content.
- line = line
- .replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/g, '')
- .replace(/<style\b[^>]*\/\s*>/g, '');
-
- // If a <style> opener remains (multi-line body starts here), strip from
- // the opener to end-of-line and flip into skip mode.
- const openerIdx = line.search(/<style\b/);
- if (openerIdx !== -1) {
- line = line.slice(0, openerIdx);
- inStyle = true;
- }
- out.push(line);
- } else {
- // In multi-line style body; drop everything until we see </style>.
- const closeIdx = line.search(/<\/style\s*>/);
- if (closeIdx !== -1) {
- inStyle = false;
- out.push(line.slice(closeIdx).replace(/<\/style\s*>/, ''));
- }
- // else: skip line entirely
- }
- }
- return out.join('\n');
-}
-
-/**
- * Find the inner content of `<TAG ...attrMatch...>…</TAG>` inside `text`,
- * handling nested same-tag elements via depth counting. `attrMatch` is a
- * regex source fragment that must appear inside the opener tag.
- * Returns the inner string (may be empty), or null if not found.
- */
-function extractInnerByAttr(text, attrMatch) {
- const openerRe = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*' + attrMatch + '[^>]*>');
- const openMatch = text.match(openerRe);
- if (!openMatch) return null;
-
- const tagName = openMatch[1];
- const innerStart = openMatch.index + openMatch[0].length;
-
- // Match any opener or closer of this tag name after innerStart.
- // (Does not match self-closing <TAG … />, which doesn't contribute to depth.)
- const tagRe = new RegExp('<(?:/)?' + tagName + '\\b[^>]*>', 'g');
- tagRe.lastIndex = innerStart;
-
- let depth = 1;
- let m;
- while ((m = tagRe.exec(text))) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && /\/\s*>$/.test(m[0]);
- if (isClose) {
- depth--;
- if (depth === 0) return text.slice(innerStart, m.index);
- } else if (!isSelfClose) {
- depth++;
- }
- }
- return null;
-}
-
-/**
- * Extract the original element content from within the variant wrapper.
- * Returns an array of lines.
- */
-function extractOriginal(lines, block) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="original"');
- if (inner === null) return [];
- return inner.split('\n');
-}
-
-/**
- * Extract a specific variant's inner content (stripping the wrapper div).
- * Returns an array of lines, or null if not found.
- */
-function extractVariant(lines, block, variantNum) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + variantNum + '"');
- if (inner === null) return null;
- const result = inner.split('\n');
- // Collapse a lone empty leading/trailing line (common after string splice).
- while (result.length > 1 && result[0].trim() === '') result.shift();
- while (result.length > 1 && result[result.length - 1].trim() === '') result.pop();
- return result.length > 0 ? result : null;
-}
-
-/**
- * Extract the colocated <style> block content (between the style tags).
- * Returns an array of CSS lines, or null if no style block found.
- *
- * Handles three shapes of `<style data-impeccable-css="ID" ...>`:
- * 1. Self-closing: `<style ... />` — no body; return null (nothing to carbonize).
- * 2. Same-line open+close: `<style>...</style>` — return the inner content.
- * 3. Multi-line: `<style>` on one line, `</style>` on a later line — return
- * the lines between them.
- */
-function extractCss(lines, block, id) {
- const styleAttr = 'data-impeccable-css="' + id + '"';
- let inStyle = false;
- const content = [];
-
- for (let i = block.start; i <= block.end; i++) {
- const line = lines[i];
-
- if (!inStyle && line.includes(styleAttr)) {
- // Self-closing: nothing to carbonize.
- if (/<style\b[^>]*\/\s*>/.test(line)) return null;
- // Same-line open + close: extract inner text.
- const sameLine = line.match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/);
- if (sameLine) {
- const inner = stripJsxTemplateWrap(sameLine[1]);
- return inner.length > 0 ? inner.split('\n') : null;
- }
- inStyle = true;
- continue; // skip the <style> opening tag
- }
-
- if (inStyle) {
- // Detect </style> anywhere on the line — JSX template-literal closes
- // (`}</style>`) put the close mid-line, and we don't want to absorb the
- // template-literal punctuation as CSS content.
- const closeIdx = line.indexOf('</style>');
- if (closeIdx !== -1) break;
- content.push(line);
- }
- }
-
- if (content.length === 0) return null;
- return stripJsxTemplateLines(content);
-}
-
-/**
- * Strip a JSX template-literal wrap (`{` … `}`) from CSS extracted out of a
- * `<style>` element in a JSX/TSX file. The agent may write the wrap with
- * `{` and `}` directly attached to the `<style>` tags, on their own lines,
- * or attached to the first/last CSS lines — all three are JSX-legal.
- *
- * Stripping is required because handleAccept re-wraps the CSS itself when
- * carbonizing. Without this, two consecutive accepts (or a previously-
- * accepted variants block being carbonized) would produce nested
- * `{` `{` … `}` `}`, which oxc rejects with "Expected `}` but found `@`".
- */
-function stripJsxTemplateLines(content) {
- const out = content.slice();
-
- // Drop any leading blank lines so we don't miss a `{` line buried below
- // them; same for trailing.
- while (out.length > 0 && out[0].trim() === '') out.shift();
- while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
- if (out.length === 0) return null;
-
- // Leading `{`: own line, or attached to the first CSS line.
- const firstTrim = out[0].trimStart();
- if (firstTrim === '{`') {
- out.shift();
- } else if (firstTrim.startsWith('{`')) {
- const idx = out[0].indexOf('{`');
- out[0] = out[0].slice(0, idx) + out[0].slice(idx + 2);
- if (out[0].trim() === '') out.shift();
- }
- if (out.length === 0) return null;
-
- // Trailing `` ` `` `}`: own line, or attached to the last CSS line.
- const lastIdx = out.length - 1;
- const lastTrim = out[lastIdx].trimEnd();
- if (lastTrim === '`}') {
- out.pop();
- } else if (lastTrim.endsWith('`}')) {
- const text = out[lastIdx];
- const idx = text.lastIndexOf('`}');
- out[lastIdx] = text.slice(0, idx) + text.slice(idx + 2);
- if (out[lastIdx].trim() === '') out.pop();
- }
-
- return out.length > 0 ? out : null;
-}
-
-function stripJsxTemplateWrap(text) {
- const lines = text.split('\n');
- const stripped = stripJsxTemplateLines(lines);
- return stripped ? stripped.join('\n') : '';
-}
-
-/**
- * De-indent content that was indented by live-wrap.mjs.
- * The wrap script adds `indent + ' '` (4 extra spaces) to each line.
- * We restore to just `indent` level.
- */
-function deindentContent(contentLines, baseIndent) {
- // Find the minimum indentation in the content to determine how much was added
- let minIndent = Infinity;
- for (const line of contentLines) {
- if (line.trim() === '') continue;
- const leadingSpaces = line.match(/^(\s*)/)[1].length;
- minIndent = Math.min(minIndent, leadingSpaces);
- }
- if (minIndent === Infinity) minIndent = 0;
-
- // Strip the extra indentation and re-add base indent
- return contentLines.map(line => {
- if (line.trim() === '') return '';
- return baseIndent + line.slice(minIndent);
- });
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- return { open: '<!--', close: '-->' };
-}
-
-// ---------------------------------------------------------------------------
-// File search (find the file containing session markers)
-// ---------------------------------------------------------------------------
-
-function findSessionFile(id, cwd) {
- const marker = 'impeccable-variants-start ' + id;
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, marker, seen, 0);
- if (result) {
- const content = fs.readFileSync(result, 'utf-8');
- return { file: result, content, lines: content.split('\n') };
- }
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth) {
- if (depth > 5) return null;
- let realDir;
- try { realDir = fs.realpathSync(dir); } catch { return null; }
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- if (!EXTENSIONS.includes(path.extname(entry.name).toLowerCase())) continue;
- const filePath = path.join(dir, entry.name);
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip */ }
- }
-
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
- if (result) return result;
- }
-
- return null;
-}
-
-// ---------------------------------------------------------------------------
-// Utilities
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-accept.mjs') || _running?.endsWith('live-accept.mjs/')) {
- acceptCli();
-}
-
-export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax };
@@ -1,123 +0,0 @@
-/**
- * Browser-side durable session helpers for Impeccable live mode.
- *
- * Kept separate from live-browser.js so recovery state can be tested without
- * booting the full overlay UI. Served before live-browser.js and attached to
- * window.__IMPECCABLE_LIVE_SESSION__.
- */
-(function (root) {
- 'use strict';
-
- function createLiveBrowserSessionState({ prefix, storage, idFactory }) {
- if (!prefix) throw new Error('prefix required');
- const store = storage || root.localStorage;
- const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };
- const sessionKey = prefix + '-session';
- const handledKey = sessionKey + '-handled';
- const scrollKey = sessionKey + '-scroll';
- let checkpointRevision = 0;
- const owner = makeId();
-
- function safeRead(key) {
- try { return store.getItem(key); } catch { return null; }
- }
-
- function safeWrite(key, value) {
- try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }
- }
-
- function safeRemove(key) {
- try { store.removeItem(key); } catch { /* unavailable storage */ }
- }
-
- function loadSession() {
- try {
- const raw = safeRead(sessionKey);
- if (!raw) return null;
- const parsed = JSON.parse(raw);
- if (Number.isInteger(parsed.checkpointRevision)) {
- checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);
- }
- return parsed;
- } catch { return null; }
- }
-
- function saveSession(session) {
- if (!session || !session.id) return;
- const payload = {
- ...session,
- checkpointRevision,
- };
- safeWrite(sessionKey, JSON.stringify(payload));
- }
-
- function clearSession() {
- safeRemove(sessionKey);
- }
-
- function nextCheckpointRevision() {
- checkpointRevision += 1;
- const existing = loadSession();
- if (existing?.id) saveSession(existing);
- return checkpointRevision;
- }
-
- function seedCheckpointRevision(value) {
- if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);
- return checkpointRevision;
- }
-
- function currentCheckpointRevision() {
- return checkpointRevision;
- }
-
- function markHandled(id) {
- if (!id) return;
- safeWrite(handledKey, id);
- }
-
- function isHandled(id) {
- return !!id && safeRead(handledKey) === id;
- }
-
- function clearHandled() {
- safeRemove(handledKey);
- }
-
- function writeScrollY(y) {
- safeWrite(scrollKey, String(y));
- }
-
- function readScrollY() {
- const raw = safeRead(scrollKey);
- if (raw == null) return null;
- const n = parseFloat(raw);
- return isFinite(n) ? n : null;
- }
-
- function clearScrollY() {
- safeRemove(scrollKey);
- }
-
- return {
- owner,
- sessionKey,
- handledKey,
- scrollKey,
- saveSession,
- loadSession,
- clearSession,
- nextCheckpointRevision,
- seedCheckpointRevision,
- currentCheckpointRevision,
- markHandled,
- isHandled,
- clearHandled,
- writeScrollY,
- readScrollY,
- clearScrollY,
- };
- }
-
- root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };
-})(typeof window !== 'undefined' ? window : globalThis);
@@ -1,4860 +0,0 @@
-/**
- * Impeccable Live Variant Mode — Browser Script
- *
- * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
- * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
- * before this code.
- *
- * UI: a single floating bar that morphs between three states —
- * configure (pick action + go), generating (progressive dots), and cycling
- * (prev/next + accept/discard). Feels like Spotlight, not a modal.
- */
-(function () {
- 'use strict';
- if (typeof window === 'undefined') return;
-
- // Guard against double-init. Bun's HTML loader may process the <script> tag
- // and create a bundled copy alongside the external load, or HMR may re-execute.
- // Check BEFORE reading token/port to catch all cases.
- if (window.__IMPECCABLE_LIVE_INIT__) return;
- window.__IMPECCABLE_LIVE_INIT__ = true;
-
- const TOKEN = window.__IMPECCABLE_TOKEN__;
- const PORT = window.__IMPECCABLE_PORT__;
- if (!TOKEN || !PORT) {
- window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
- return;
- }
-
- // ---------------------------------------------------------------------------
- // Design tokens
- // ---------------------------------------------------------------------------
-
- // Brand magenta is pinned to the site token (--color-accent in main.css)
- // so Accept / knobs / cycle-dots match the site's accent, not a washed
- // theme-adjusted one.
- const C = {
- brand: 'oklch(60% 0.25 350)',
- brandHov: 'oklch(52% 0.25 350)',
- brandSoft: 'oklch(60% 0.25 350 / 0.15)',
- ink: 'oklch(15% 0.01 350)',
- ash: 'oklch(55% 0 0)',
- paper: 'oklch(98% 0.005 350 / 0.92)',
- paperSolid:'oklch(98% 0.005 350)',
- mist: 'oklch(90% 0.01 350 / 0.6)',
- white: 'oklch(99% 0 0)',
- };
- const FONT = 'system-ui, -apple-system, sans-serif';
- const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
- // z-index: detect overlays use 99999, so our UI must be above them
- const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };
- const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
- const PREFIX = 'impeccable-live';
- const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
- prefix: PREFIX,
- storage: localStorage,
- idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),
- });
- if (!sessionState) {
- console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');
- window.__IMPECCABLE_LIVE_INIT__ = false;
- return;
- }
- const HIGHLIGHT_TRANSITION =
- 'top 140ms ' + EASE +
- ', left 140ms ' + EASE +
- ', width 140ms ' + EASE +
- ', height 140ms ' + EASE +
- ', opacity 150ms ease';
- const TOOLTIP_TRANSITION =
- 'top 140ms ' + EASE + ', left 140ms ' + EASE + ', opacity 150ms ease';
-
- const SKIP_TAGS = new Set([
- 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
- ]);
-
- // SVG icons stack above each chip label. All strokes use currentColor so the
- // icon recolors to C.brand when its chip is selected. 20x20 render, 24-viewBox,
- // 1.5 stroke — visually consistent with the Foundation grid on the homepage.
- const ICON_ATTRS = 'width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block"';
- const ICONS = {
- impeccable: `<svg ${ICON_ATTRS}><path d="M4 20l4-1L18 9l-3-3L5 16z"/><path d="M14 7l3 3"/></svg>`,
- bolder: `<svg ${ICON_ATTRS}><rect x="6" y="12" width="4" height="7" rx="0.5"/><rect x="14" y="5" width="4" height="14" rx="0.5"/></svg>`,
- quieter: `<svg ${ICON_ATTRS}><rect x="6" y="5" width="4" height="14" rx="0.5"/><rect x="14" y="12" width="4" height="7" rx="0.5"/></svg>`,
- distill: `<svg ${ICON_ATTRS}><path d="M4 5h16l-6 8v7l-4-2v-5z"/></svg>`,
- polish: `<svg ${ICON_ATTRS}><path d="M15 3l1 3 3 1-3 1-1 3-1-3-3-1 3-1z"/><path d="M7 13l0.6 1.8 1.8 0.6-1.8 0.6-0.6 1.8-0.6-1.8-1.8-0.6 1.8-0.6z"/></svg>`,
- typeset: `<svg ${ICON_ATTRS}><path d="M5 6h14" stroke-width="2.6"/><path d="M5 12h9" stroke-width="1.9"/><path d="M5 18h5" stroke-width="1.3"/></svg>`,
- colorize: `<svg ${ICON_ATTRS}><circle cx="9" cy="10" r="5"/><circle cx="15" cy="10" r="5"/><circle cx="12" cy="15" r="5"/></svg>`,
- layout: `<svg ${ICON_ATTRS}><rect x="3" y="4" width="8" height="16" rx="0.5"/><rect x="13" y="4" width="8" height="7" rx="0.5"/><rect x="13" y="13" width="8" height="7" rx="0.5"/></svg>`,
- adapt: `<svg ${ICON_ATTRS}><rect x="2.5" y="5" width="12" height="11" rx="1"/><line x1="2.5" y1="19" x2="14.5" y2="19"/><rect x="16.5" y="8" width="5" height="11" rx="1"/></svg>`,
- animate: `<svg ${ICON_ATTRS}><path d="M3 18c4-4 6-10 10-10"/><path d="M13 8c3 0 5 5 8 10"/><circle cx="13" cy="8" r="1.6" fill="currentColor" stroke="none"/></svg>`,
- delight: `<svg ${ICON_ATTRS}><path d="M12 3l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>`,
- overdrive: `<svg ${ICON_ATTRS}><path d="M13 3L5 13h5l-1 8 9-12h-6z"/></svg>`,
- };
-
- const ACTIONS = [
- { value: 'impeccable', label: 'Freeform' },
- { value: 'bolder', label: 'Bolder' },
- { value: 'quieter', label: 'Quieter' },
- { value: 'distill', label: 'Distill' },
- { value: 'polish', label: 'Polish' },
- { value: 'typeset', label: 'Typeset' },
- { value: 'colorize', label: 'Colorize' },
- { value: 'layout', label: 'Layout' },
- { value: 'adapt', label: 'Adapt' },
- { value: 'animate', label: 'Animate' },
- { value: 'delight', label: 'Delight' },
- { value: 'overdrive', label: 'Overdrive' },
- ];
-
- // ---------------------------------------------------------------------------
- // State
- // ---------------------------------------------------------------------------
-
- let state = 'IDLE';
- let hoveredElement = null;
- let selectedElement = null;
- let currentSessionId = null;
- let expectedVariants = 0;
- let arrivedVariants = 0;
- let visibleVariant = 0;
- let variantObserver = null;
- let hasProjectContext = false;
- let selectedAction = 'impeccable';
- let selectedCount = 3;
- const browserOwner = sessionState.owner;
- let checkpointTimer = null;
-
- // Scroll lock — holds window.scrollY at a fixed value while the session is
- // active, so HMR DOM patches and variant swaps can't drift the page. See
- // startScrollLock / stopScrollLock below.
- let scrollLockObserver = null;
- let scrollLockTargetY = null;
- let scrollLockRaf = null;
- let scrollLockAbort = null;
-
- // Dedicated key for scroll position — SEPARATE from LS_KEY so that
- // saveSession's state updates don't clobber a carefully-captured scrollY.
- // (Previously: saveSession wrote scrollY alongside state, so every call
- // during resume overwrote the pre-reload value with whatever the browser
- // had landed on, typically 0.)
- function writeScrollY(y) { sessionState.writeScrollY(y); }
- function readScrollY() { return sessionState.readScrollY(); }
- function clearScrollY() { sessionState.clearScrollY(); }
-
- // Pre-empt the browser: apply manual scroll restoration and jump to the
- // saved scrollY at script-parse time. Retries on fonts.ready and load
- // are essential: scrollTo(y) clamps to the current document.scrollHeight,
- // which is often hundreds of pixels short of the final value until
- // async-loaded fonts swap in and reflow.
- try {
- history.scrollRestoration = 'manual';
- const savedY = readScrollY();
- if (savedY != null) {
- const apply = () => {
- if (Math.abs(window.scrollY - savedY) > 0.5) {
- console.log('[impeccable.scroll] early restore', { from: window.scrollY, to: savedY });
- window.scrollTo(0, savedY);
- }
- };
- apply();
- if (document.fonts?.ready) document.fonts.ready.then(apply).catch(() => {});
- window.addEventListener('load', apply, { once: true });
- }
- } catch {}
-
- // UI refs
- let highlightEl = null;
- let tooltipEl = null;
- let barEl = null;
- let pickerEl = null;
- let toastEl = null;
- let scrollRaf = null;
-
- // ---------------------------------------------------------------------------
- // Helpers
- // ---------------------------------------------------------------------------
-
- function own(el) {
- return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
- }
-
- function pickable(el) {
- if (!el || el.nodeType !== 1) return false;
- if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
- if (own(el)) return false;
- const r = el.getBoundingClientRect();
- return r.width >= 20 && r.height >= 20;
- }
-
- function desc(el) {
- if (!el) return '';
- let s = el.tagName.toLowerCase();
- if (el.id) s += '#' + el.id;
- else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
- return s;
- }
-
- function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
-
- // Modal-aware chrome: keep our floating UI clickable inside Radix /
- // Headless UI / vaul portals.
- //
- // Two host-page behaviors break us when the picked element lives inside a
- // modal dialog:
- //
- // 1. Modal scroll-lock disables outside pointer events. Radix's
- // `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
- // while a modal is open and only restores `auto` on the layer. Our
- // chrome inherits `none` from <body> and becomes unclickable.
- // 2. The dialog's outside-interaction handler (Radix's
- // `usePointerDownOutside`) listens at document level and dismisses
- // the dialog whenever a `pointerdown` lands outside the layer node.
- // Our chrome is a sibling of <body>, so Radix classifies our clicks
- // as outside and tears the dialog down mid-task.
- //
- // We can't reliably re-parent our chrome into the dialog subtree (z-index
- // stacking, scroll containers, theming all become host-page concerns), so
- // we defang both behaviors at our root:
- //
- // - `pointer-events: auto !important` overrides the inherited `none`.
- // - Stop `pointerdown` / `mousedown` propagation so the document-level
- // dismiss listener never fires for our clicks.
- // - Stop `focusin` propagation so any focus shifts inside our chrome
- // don't read as "focus moved outside the dialog" to focus traps.
- //
- // Click events still bubble normally — only the early pointer/focus
- // signals that drive outside-interaction detection are silenced.
- function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
- if (!rootEl) return;
- if (setPointerEvents) {
- rootEl.style.setProperty('pointer-events', 'auto', 'important');
- }
- const stop = (e) => e.stopPropagation();
- rootEl.addEventListener('pointerdown', stop);
- rootEl.addEventListener('mousedown', stop);
- rootEl.addEventListener('focusin', stop);
- }
-
- // ---------------------------------------------------------------------------
- // Highlight overlay
- // ---------------------------------------------------------------------------
-
- function initHighlight() {
- highlightEl = document.createElement('div');
- highlightEl.id = PREFIX + '-highlight';
- Object.assign(highlightEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- border: '2px solid ' + C.brand, borderRadius: '3px',
- pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
- transition: HIGHLIGHT_TRANSITION,
- display: 'none', opacity: '0',
- });
- document.body.appendChild(highlightEl);
-
- tooltipEl = document.createElement('div');
- tooltipEl.id = PREFIX + '-tooltip';
- Object.assign(tooltipEl.style, {
- position: 'fixed',
- background: C.ink, color: C.white,
- fontFamily: MONO, fontSize: '10px', fontWeight: '500',
- padding: '2px 6px', borderRadius: '3px',
- zIndex: Z.highlight + 1, pointerEvents: 'none',
- whiteSpace: 'nowrap', display: 'none',
- letterSpacing: '0.02em',
- transition: TOOLTIP_TRANSITION,
- });
- document.body.appendChild(tooltipEl);
- }
-
- function showHighlight(el) {
- if (!el || !highlightEl) return;
- const r = el.getBoundingClientRect();
- const top = (r.top - 2) + 'px', left = (r.left - 2) + 'px';
- const width = (r.width + 4) + 'px', height = (r.height + 4) + 'px';
- const tipTop = r.top - 20;
- const tipY = (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px';
- const tipX = Math.max(4, r.left) + 'px';
- tooltipEl.textContent = desc(el);
-
- const hiWasHidden = highlightEl.style.display === 'none' || highlightEl.style.opacity === '0';
- if (hiWasHidden) {
- // Snap to first target without animating from (0,0), then fade in.
- highlightEl.style.transition = 'none';
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block' });
- tooltipEl.style.transition = 'none';
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block' });
- void highlightEl.offsetWidth;
- highlightEl.style.transition = HIGHLIGHT_TRANSITION;
- highlightEl.style.opacity = '1';
- tooltipEl.style.transition = TOOLTIP_TRANSITION;
- tooltipEl.style.opacity = '1';
- } else {
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block', opacity: '1' });
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block', opacity: '1' });
- }
- }
-
- function hideHighlight() {
- if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
- if (tooltipEl) { tooltipEl.style.opacity = '0'; tooltipEl.style.display = 'none'; }
- }
-
- // ---------------------------------------------------------------------------
- // Annotation overlay (comment pins + magenta strokes)
- //
- // Active while state === 'CONFIGURING'. The overlay is a fixed-positioned
- // sibling of <body> mirroring selectedElement's bounding rect. Click (no
- // drag) drops a comment pin; drag paints a magenta SVG stroke. All coords
- // are stored in element-local CSS px so they survive scroll / resize and
- // correlate directly with the captured PNG.
- // ---------------------------------------------------------------------------
-
- const DRAG_THRESHOLD = 5; // px — below this, treat pointerup as a click
- const PIN_DBL_CLICK_MS = 300; // two clicks on the same pin within this delete it
- let annotOverlayEl = null;
- let annotSvgEl = null;
- let annotPinsEl = null;
- let annotClearChipEl = null;
- let annotState = { comments: [], strokes: [] };
- let annotActive = false;
- // `annotPointer` is either:
- // { kind: 'new', x0, y0, moved, strokeEl, strokePoints } creating a stroke/pin
- // { kind: 'pin', idx, startPointer, startPin, moved } dragging an existing pin
- let annotPointer = null;
- let annotEditing = null; // { idx, input, wrapEl }
- let annotLastPinClick = { idx: -1, time: 0 }; // for click-click-to-delete
-
- function initAnnotOverlay() {
- annotOverlayEl = document.createElement('div');
- annotOverlayEl.id = PREFIX + '-annot';
- Object.assign(annotOverlayEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- pointerEvents: 'auto', zIndex: Z.highlight + 2,
- display: 'none', overflow: 'visible',
- cursor: 'crosshair', touchAction: 'none',
- });
-
- annotSvgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- annotSvgEl.id = PREFIX + '-annot-svg';
- Object.assign(annotSvgEl.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%',
- // The SVG itself doesn't absorb clicks; individual hit-paths opt-in via
- // pointer-events=stroke so gaps still fall through to the overlay.
- pointerEvents: 'none', overflow: 'visible',
- });
- annotOverlayEl.appendChild(annotSvgEl);
-
- annotPinsEl = document.createElement('div');
- annotPinsEl.id = PREFIX + '-annot-pins';
- Object.assign(annotPinsEl.style, {
- position: 'absolute', inset: '0',
- pointerEvents: 'none',
- });
- annotOverlayEl.appendChild(annotPinsEl);
-
- annotClearChipEl = document.createElement('div');
- annotClearChipEl.id = PREFIX + '-annot-clear';
- annotClearChipEl.dataset.annotClear = 'true';
- annotClearChipEl.textContent = 'Clear';
- Object.assign(annotClearChipEl.style, {
- position: 'absolute', top: '8px', right: '8px',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '10px', fontWeight: '500',
- letterSpacing: '0.08em', textTransform: 'uppercase',
- padding: '5px 12px', borderRadius: '999px',
- cursor: 'pointer', pointerEvents: 'auto',
- display: 'none', userSelect: 'none',
- boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
- });
- annotOverlayEl.appendChild(annotClearChipEl);
-
- annotOverlayEl.addEventListener('pointerdown', onAnnotDown);
- annotOverlayEl.addEventListener('pointermove', onAnnotMove);
- annotOverlayEl.addEventListener('pointerup', onAnnotUp);
- annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
- document.body.appendChild(annotOverlayEl);
- // Modal-host friendliness: pointer-events is already 'auto' on this
- // overlay; we only need to silence the host's outside-interaction
- // listeners. Don't override pointer-events here (the overlay toggles
- // visibility via display:none, which is fine).
- defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
- }
-
- function updateClearChip() {
- if (!annotClearChipEl) return;
- const hasAny = annotState.comments.length > 0 || annotState.strokes.length > 0;
- annotClearChipEl.style.display = hasAny ? 'block' : 'none';
- }
-
- function showAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- annotActive = true;
- positionAnnotOverlay(el);
- annotOverlayEl.style.display = 'block';
- }
-
- function hideAnnotOverlay() {
- annotActive = false;
- if (annotOverlayEl) annotOverlayEl.style.display = 'none';
- // Drop any in-progress edit without touching annotState — clearAnnotations
- // (if the caller is exiting configure mode) handles state reset.
- annotEditing = null;
- }
-
- function positionAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- const r = el.getBoundingClientRect();
- Object.assign(annotOverlayEl.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- annotSvgEl.setAttribute('viewBox', '0 0 ' + r.width + ' ' + r.height);
- }
-
- function clearAnnotations() {
- annotState.comments = [];
- annotState.strokes = [];
- if (annotSvgEl) while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- if (annotPinsEl) annotPinsEl.innerHTML = '';
- annotPointer = null;
- annotEditing = null;
- annotLastPinClick = { idx: -1, time: 0 };
- updateClearChip();
- }
-
- // Rebuild the SVG layer. Each stroke gets a wider invisible hit path
- // beneath the visible magenta path so clicks register on thin lines.
- function redrawStrokes() {
- while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- annotState.strokes.forEach((s, idx) => {
- const d = pointsToPath(s.points);
- const hit = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- hit.setAttribute('d', d);
- hit.setAttribute('stroke', 'transparent');
- hit.setAttribute('stroke-width', '16');
- hit.setAttribute('stroke-linecap', 'round');
- hit.setAttribute('stroke-linejoin', 'round');
- hit.setAttribute('fill', 'none');
- hit.setAttribute('pointer-events', 'stroke');
- hit.style.cursor = 'pointer';
- hit.dataset.annotStroke = String(idx);
- annotSvgEl.appendChild(hit);
- const visible = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- visible.setAttribute('d', d);
- visible.setAttribute('stroke', C.brand);
- visible.setAttribute('stroke-width', '3');
- visible.setAttribute('stroke-linecap', 'round');
- visible.setAttribute('stroke-linejoin', 'round');
- visible.setAttribute('fill', 'none');
- visible.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(visible);
- });
- updateClearChip();
- }
-
- function localCoords(e) {
- const rect = annotOverlayEl.getBoundingClientRect();
- return { x: e.clientX - rect.left, y: e.clientY - rect.top };
- }
-
- function onAnnotDown(e) {
- if (!annotActive) return;
-
- // 1) Clear chip → wipe all annotations
- if (e.target.closest?.('[data-annot-clear]')) {
- if (annotEditing) annotEditing = null;
- clearAnnotations();
- renderAllPins();
- redrawStrokes();
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 2) Stroke hit path → delete that stroke
- const strokeHit = e.target.closest?.('[data-annot-stroke]');
- if (strokeHit) {
- const idx = parseInt(strokeHit.dataset.annotStroke, 10);
- if (Number.isInteger(idx)) {
- annotState.strokes.splice(idx, 1);
- redrawStrokes();
- }
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 3) Pin → drag, edit, or delete-on-double-click
- const pinWrap = e.target.closest?.('[data-annot-pin]');
- if (pinWrap) {
- const idx = parseInt(pinWrap.dataset.annotPin, 10);
- if (!Number.isInteger(idx)) return;
- // Double-click (two pointerdowns on the same pin within window) → delete.
- const now = Date.now();
- if (annotLastPinClick.idx === idx && now - annotLastPinClick.time < PIN_DBL_CLICK_MS) {
- if (annotEditing && annotEditing.idx === idx) annotEditing = null;
- annotState.comments.splice(idx, 1);
- annotLastPinClick = { idx: -1, time: 0 };
- renderAllPins();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- annotLastPinClick = { idx, time: now };
- // If editing a different pin, commit that edit before starting here.
- if (annotEditing && annotEditing.idx !== idx) finalizeEditingPin();
- // If already editing THIS pin and the user clicked the dot, let the
- // input keep focus (don't start a drag — the click wasn't meant as one).
- if (annotEditing && annotEditing.idx === idx) return;
- const p = localCoords(e);
- const pin = annotState.comments[idx];
- annotPointer = {
- kind: 'pin', idx,
- startPointer: p,
- startPin: { x: pin.x, y: pin.y },
- moved: false,
- };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 4) Empty area → commit any open edit, then start new annotation
- if (annotEditing) {
- finalizeEditingPin();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- const p = localCoords(e);
- annotPointer = { kind: 'new', x0: p.x, y0: p.y, moved: false, strokeEl: null, strokePoints: null };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- }
-
- function onAnnotMove(e) {
- if (!annotActive || !annotPointer) return;
- const p = localCoords(e);
-
- if (annotPointer.kind === 'pin') {
- const dx = p.x - annotPointer.startPointer.x;
- const dy = p.y - annotPointer.startPointer.y;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- }
- const pin = annotState.comments[annotPointer.idx];
- if (!pin) { annotPointer = null; return; }
- pin.x = annotPointer.startPin.x + dx;
- pin.y = annotPointer.startPin.y + dy;
- renderAllPins();
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const dx = p.x - annotPointer.x0, dy = p.y - annotPointer.y0;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- const strokeEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- strokeEl.setAttribute('stroke', C.brand);
- strokeEl.setAttribute('stroke-width', '3');
- strokeEl.setAttribute('stroke-linecap', 'round');
- strokeEl.setAttribute('stroke-linejoin', 'round');
- strokeEl.setAttribute('fill', 'none');
- strokeEl.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(strokeEl);
- annotPointer.strokeEl = strokeEl;
- annotPointer.strokePoints = [[annotPointer.x0, annotPointer.y0]];
- }
- annotPointer.strokePoints.push([p.x, p.y]);
- annotPointer.strokeEl.setAttribute('d', pointsToPath(annotPointer.strokePoints));
- e.stopPropagation();
- }
-
- function onAnnotUp(e) {
- if (!annotActive || !annotPointer) return;
-
- if (annotPointer.kind === 'pin') {
- const wasDrag = annotPointer.moved;
- const idx = annotPointer.idx;
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- if (wasDrag) {
- // A drag is an intentional reposition; a follow-up click shouldn't be
- // interpreted as a double-click-to-delete.
- annotLastPinClick = { idx: -1, time: 0 };
- } else {
- beginEditPin(idx);
- }
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const wasDrag = annotPointer.moved;
- if (wasDrag) {
- annotState.strokes.push({ points: annotPointer.strokePoints });
- // Swap the temporary preview SVG path for the full render with hit paths.
- redrawStrokes();
- } else {
- const idx = annotState.comments.length;
- annotState.comments.push({ x: annotPointer.x0, y: annotPointer.y0, text: '' });
- renderAllPins();
- beginEditPin(idx);
- }
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- e.stopPropagation();
- }
-
- function pointsToPath(points) {
- if (!points || points.length === 0) return '';
- let d = 'M' + points[0][0].toFixed(1) + ' ' + points[0][1].toFixed(1);
- for (let i = 1; i < points.length; i++) {
- d += ' L' + points[i][0].toFixed(1) + ' ' + points[i][1].toFixed(1);
- }
- return d;
- }
-
- function renderAllPins() {
- annotPinsEl.innerHTML = '';
- annotState.comments.forEach((c, idx) => {
- annotPinsEl.appendChild(buildPinElement(c, idx));
- });
- updateClearChip();
- }
-
- function buildPinElement(comment, idx) {
- const interactive = idx >= 0;
- const wrap = document.createElement('div');
- if (interactive) wrap.dataset.annotPin = String(idx);
- Object.assign(wrap.style, {
- position: 'absolute',
- left: (comment.x - 7) + 'px', top: (comment.y - 7) + 'px',
- pointerEvents: interactive ? 'auto' : 'none',
- display: 'flex', alignItems: 'flex-start', gap: '6px',
- cursor: interactive ? 'grab' : 'default',
- touchAction: 'none',
- });
- const dot = document.createElement('div');
- Object.assign(dot.style, {
- width: '14px', height: '14px', borderRadius: '50%',
- background: C.brand, border: '2px solid ' + C.white,
- boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
- flexShrink: '0',
- });
- wrap.appendChild(dot);
-
- if (comment.text) {
- const bubble = document.createElement('div');
- bubble.textContent = comment.text;
- Object.assign(bubble.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- marginTop: '-2px', maxWidth: '220px',
- pointerEvents: 'none', whiteSpace: 'pre-wrap',
- wordBreak: 'break-word',
- });
- wrap.appendChild(bubble);
- }
- return wrap;
- }
-
- function beginEditPin(idx) {
- const wrapEl = annotPinsEl.querySelector('[data-annot-pin="' + idx + '"]');
- if (!wrapEl) return;
- // Strip any existing bubble (but keep the dot)
- wrapEl.querySelectorAll('div:not(:first-child)').forEach(n => n.remove());
- const input = document.createElement('input');
- input.type = 'text';
- input.placeholder = 'Note…';
- Object.assign(input.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- border: '1px solid ' + C.brand,
- outline: 'none', marginTop: '-2px',
- width: '220px', pointerEvents: 'auto',
- });
- const originalText = annotState.comments[idx].text || '';
- input.value = originalText;
- wrapEl.appendChild(input);
- annotEditing = { idx, input, wrapEl, originalText };
- input.addEventListener('keydown', onAnnotInputKey, true);
- input.addEventListener('blur', () => {
- // Fires on both focus-loss and programmatic blur; commit unless we
- // already handled it.
- if (annotEditing && annotEditing.input === input) finalizeEditingPin();
- });
- // Stop clicks/pointerdowns inside the input from bubbling to the overlay
- ['pointerdown', 'click'].forEach(ev => {
- input.addEventListener(ev, e => e.stopPropagation());
- });
- setTimeout(() => input.focus(), 0);
- }
-
- function onAnnotInputKey(e) {
- if (e.key === 'Enter') {
- e.preventDefault(); e.stopPropagation();
- finalizeEditingPin();
- } else if (e.key === 'Escape') {
- e.preventDefault(); e.stopPropagation();
- cancelEditingPin();
- } else {
- // Keep arrows / backspace from hitting global handlers
- e.stopPropagation();
- }
- }
-
- function finalizeEditingPin() {
- if (!annotEditing) return;
- const { idx, input } = annotEditing;
- const text = input.value.trim();
- annotEditing = null;
- if (text) annotState.comments[idx].text = text;
- else annotState.comments.splice(idx, 1);
- renderAllPins();
- }
-
- function cancelEditingPin() {
- if (!annotEditing) return;
- const { idx, originalText } = annotEditing;
- annotEditing = null;
- // If the pin had text before this edit, revert to it. If it was a
- // just-created empty pin, Escape removes it.
- if (originalText) {
- annotState.comments[idx].text = originalText;
- } else {
- annotState.comments.splice(idx, 1);
- }
- renderAllPins();
- }
-
- // Build a detached annotation subtree suitable for injection into the clone
- // modern-screenshot creates. Coordinates are element-local so this slots
- // straight into an element that's been made position:relative. Takes an
- // explicit snapshot so it works after annotState has been cleared.
- function buildAnnotationsForCapture(rect, snapshot) {
- const comments = snapshot ? snapshot.comments : annotState.comments;
- const strokes = snapshot ? snapshot.strokes : annotState.strokes;
- if (comments.length === 0 && strokes.length === 0) return null;
- const wrap = document.createElement('div');
- Object.assign(wrap.style, {
- position: 'absolute', top: '0', left: '0',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none', overflow: 'visible',
- });
- if (strokes.length > 0) {
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- svg.setAttribute('viewBox', '0 0 ' + rect.width + ' ' + rect.height);
- Object.assign(svg.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%', overflow: 'visible',
- });
- for (const s of strokes) {
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- path.setAttribute('stroke', C.brand);
- path.setAttribute('stroke-width', '3');
- path.setAttribute('stroke-linecap', 'round');
- path.setAttribute('stroke-linejoin', 'round');
- path.setAttribute('fill', 'none');
- path.setAttribute('d', pointsToPath(s.points));
- svg.appendChild(path);
- }
- wrap.appendChild(svg);
- }
- for (const c of comments) {
- // idx=-1 means non-interactive; pointerEvents stay off in the clone
- wrap.appendChild(buildPinElement(c, -1));
- }
- return wrap;
- }
-
- // ---------------------------------------------------------------------------
- // Element context extraction
- // ---------------------------------------------------------------------------
-
- function extractContext(el) {
- const cs = getComputedStyle(el);
- const r = el.getBoundingClientRect();
- const props = {};
- for (const sheet of document.styleSheets) {
- try {
- for (const rule of sheet.cssRules) {
- if (rule.style) for (let i = 0; i < rule.style.length; i++) {
- const p = rule.style[i];
- if (p.startsWith('--') && !props[p]) {
- const v = cs.getPropertyValue(p).trim();
- if (v) props[p] = v;
- }
- }
- }
- } catch { /* cross-origin */ }
- }
- return {
- tagName: el.tagName.toLowerCase(), id: el.id || null,
- classes: [...el.classList],
- textContent: (el.textContent || '').slice(0, 500),
- outerHTML: el.outerHTML.slice(0, 10000),
- computedStyles: {
- 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
- 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
- 'color': cs.color, 'background': cs.background,
- 'background-color': cs.backgroundColor,
- 'padding': cs.padding, 'margin': cs.margin,
- 'display': cs.display, 'position': cs.position,
- 'gap': cs.gap, 'border-radius': cs.borderRadius,
- 'box-shadow': cs.boxShadow,
- },
- cssCustomProperties: props,
- parentContext: el.parentElement
- ? '<' + el.parentElement.tagName.toLowerCase()
- + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
- + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
- + '>'
- : null,
- boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
- };
- }
-
- // ---------------------------------------------------------------------------
- // The Bar — one floating element, three modes
- // ---------------------------------------------------------------------------
-
- // Contextual-bar palette. Cached at init so every build*Row reads a
- // consistent set of colors; detectPageTheme runs once rather than on every
- // phase transition.
- let BP = null;
-
- // Bar shadow variants. The default projects down + subtle around. When
- // the Tune popover opens below the bar, a downward shadow lands on the
- // dark popover and reads as a bright ghost line. We swap to UP-only while
- // tune is open below so the popover's top edge is clean.
- const BAR_SHADOW_DEFAULT = '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_UP = '0 -4px 20px oklch(0% 0 0 / 0.08), 0 -1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_DOWN = BAR_SHADOW_DEFAULT;
-
- function initBar() {
- BP = barPaletteForTheme(detectPageTheme());
- barEl = document.createElement('div');
- barEl.id = PREFIX + '-bar';
- Object.assign(barEl.style, {
- position: 'fixed', zIndex: Z.bar,
- display: 'none', opacity: '0',
- transform: 'translateY(6px)',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- background: BP.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + BP.hairline,
- borderRadius: '10px',
- boxShadow: BAR_SHADOW_DEFAULT,
- transition: 'box-shadow 0.2s ease, opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- fontFamily: FONT, fontSize: '13px', color: BP.text,
- padding: '6px',
- maxWidth: '520px', minWidth: '320px',
- });
- document.body.appendChild(barEl);
- defangOutsideHandlers(barEl);
- }
-
- function positionBar() {
- if (!barEl || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- const barH = barEl.offsetHeight || 44;
- const barW = barEl.offsetWidth || 380;
- const GLOBAL_BAR_RESERVE = 64; // global bar height + bottom margin + breathing room
- const GAP = 8;
-
- // Prefer below the element; fall back to above; if neither fits (element
- // taller than viewport), pin to a stable viewport anchor so the bar
- // doesn't teleport between top and bottom as the user scrolls.
- let top;
- const belowTop = r.bottom + GAP;
- const aboveTop = r.top - barH - GAP;
- if (belowTop + barH + GAP <= window.innerHeight - GLOBAL_BAR_RESERVE) {
- top = belowTop;
- } else if (aboveTop >= GAP) {
- top = aboveTop;
- } else {
- top = window.innerHeight - barH - GLOBAL_BAR_RESERVE;
- }
-
- let left = r.left + (r.width - barW) / 2;
- if (left < GAP) left = GAP;
- if (left + barW > window.innerWidth - GAP) left = window.innerWidth - barW - GAP;
- Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
- }
-
- function showBar(mode) {
- barEl.innerHTML = '';
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- barEl.style.display = 'block';
- positionBar();
- requestAnimationFrame(() => {
- barEl.style.opacity = '1';
- barEl.style.transform = 'translateY(0)';
- });
- }
-
- function hideBar() {
- if (!barEl) return;
- barEl.style.opacity = '0';
- barEl.style.transform = 'translateY(6px)';
- setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
- hideActionPicker();
- closeTunePopover();
- }
-
- function updateBarContent(mode) {
- if (!barEl || barEl.style.display === 'none') return;
- barEl.innerHTML = '';
- // Reset bar styling to the theme-aware palette
- barEl.style.background = BP.surface;
- barEl.style.border = '1px solid ' + BP.hairline;
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- else if (mode === 'saving') barEl.appendChild(buildSavingRow());
- else if (mode === 'confirmed') {
- barEl.appendChild(buildConfirmedRow());
- barEl.style.background = 'oklch(95% 0.05 145)';
- barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
- }
- }
-
- // --- Configure row ---
-
- function buildConfigureRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
-
- // Action pill
- const pill = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '4px',
- padding: '5px 10px', borderRadius: '6px',
- background: BP.mark, color: BP.markText,
- fontFamily: FONT, fontSize: '12px', fontWeight: '500',
- border: 'none', cursor: 'pointer',
- transition: 'background 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap', flexShrink: '0',
- });
- pill.textContent = actionLabel() + ' \u25BE';
- pill.addEventListener('mouseenter', () => pill.style.background = BP.accent);
- pill.addEventListener('mouseleave', () => pill.style.background = BP.mark);
- pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
- pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
- pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
- row.appendChild(pill);
-
- // Freeform input. Focus state shows an accent-colored border only —
- // an earlier version tinted the background with `BP.accentSoft`, which
- // composited against the dark bar surface to a murky purple where the
- // browser's default placeholder gray was unreadable. Placeholder color
- // is set explicitly via a one-shot stylesheet keyed off this input's id
- // so it picks up the bar's `textDim` token in both themes.
- const input = document.createElement('input');
- input.id = PREFIX + '-input';
- input.type = 'text';
- input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
- Object.assign(input.style, {
- flex: '1', minWidth: '0',
- padding: '5px 8px', borderRadius: '6px',
- border: '1px solid transparent', background: 'transparent',
- fontFamily: FONT, fontSize: '12px', color: BP.text,
- outline: 'none',
- transition: 'border-color 0.15s ease',
- });
- if (!document.getElementById(PREFIX + '-input-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-input-style';
- s.textContent =
- '#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
- document.head.appendChild(s);
- }
- input.addEventListener('focus', () => {
- input.style.borderColor = BP.accent;
- });
- input.addEventListener('blur', () => {
- input.style.borderColor = 'transparent';
- });
- input.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
- if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; return; }
- // Let arrow keys pass through to the element picker when the input is empty
- if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && !input.value) return;
- e.stopPropagation();
- });
- row.appendChild(input);
-
- // Variant count toggle
- const count = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: MONO, fontSize: '11px', fontWeight: '600',
- color: BP.textDim, cursor: 'pointer',
- transition: 'color 0.12s ease, border-color 0.12s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- count.textContent = '\u00D7' + selectedCount;
- count.title = 'Variants: click to change';
- count.addEventListener('mouseenter', () => { count.style.color = BP.text; count.style.borderColor = BP.text; });
- count.addEventListener('mouseleave', () => { count.style.color = BP.textDim; count.style.borderColor = BP.hairline; });
- count.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
- count.textContent = '\u00D7' + selectedCount;
- });
- row.appendChild(count);
-
- // Go button
- const go = el('button', {
- padding: '5px 12px', borderRadius: '6px',
- border: 'none', background: BP.accent, color: BP.mark,
- fontFamily: FONT, fontSize: '12px', fontWeight: '600',
- cursor: 'pointer',
- transition: 'filter 0.12s ease, transform 0.1s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- go.textContent = 'Go \u2192';
- go.addEventListener('mouseenter', () => go.style.filter = 'brightness(1.1)');
- go.addEventListener('mouseleave', () => go.style.filter = 'none');
- go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
- go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
- go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
- row.appendChild(go);
-
- // Auto-focus input after a beat
- setTimeout(() => input.focus(), 60);
- return row;
- }
-
- // --- Generating row ---
-
- function buildGeneratingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 4px',
- });
-
- // Action label
- const label = el('span', {
- fontWeight: '600', fontSize: '12px', color: BP.text,
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- label.textContent = actionLabel();
- row.appendChild(label);
-
- // Dots
- row.appendChild(buildDots(false));
-
- // Status
- const status = el('span', {
- fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',
- marginLeft: 'auto',
- });
- // Variants currently arrive atomically in a single file edit, so a
- // per-variant counter would lie. Say what's true.
- status.textContent = arrivedVariants < expectedVariants
- ? 'Generating ' + expectedVariants + ' variants...'
- : 'Done';
- row.appendChild(status);
-
- return row;
- }
-
- // --- Cycling row ---
-
- const TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';
-
- function buildCyclingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '6px',
- padding: '1px 2px',
- });
-
- // Prev
- const prev = navBtn('\u2190');
- prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
- if (visibleVariant <= 1) prev.style.opacity = '0.3';
- row.appendChild(prev);
-
- // Dots (clickable)
- row.appendChild(buildDots(true));
-
- // Counter
- const counter = el('span', {
- fontFamily: MONO, fontSize: '11px', fontWeight: '500',
- color: BP.textDim, minWidth: '24px', textAlign: 'center',
- });
- counter.textContent = visibleVariant + '/' + arrivedVariants;
- row.appendChild(counter);
-
- // Next
- const next = navBtn('\u2192');
- next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
- if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
- row.appendChild(next);
-
- // Tune chip — only when the visible variant exposes params
- const visParams = parseVariantParams(getVisibleVariantEl());
- const hasParams = visParams.length > 0;
- if (hasParams) {
- const tune = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '6px',
- padding: '4px 10px', borderRadius: '5px',
- border: '1px solid transparent',
- background: tuneOpen ? BP.accentSoft : 'transparent',
- color: tuneOpen ? BP.accent : BP.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'color 0.12s ease, background 0.12s ease',
- whiteSpace: 'nowrap',
- });
- tune.innerHTML = TUNE_ICON_SVG;
- const tuneLabel = document.createElement('span');
- tuneLabel.textContent = 'Tune';
- tune.appendChild(tuneLabel);
- const tuneBadge = document.createElement('span');
- Object.assign(tuneBadge.style, {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- minWidth: '16px', height: '16px', padding: '0 4px',
- borderRadius: '999px',
- background: tuneOpen ? C.brand : BP.hairline,
- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',
- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',
- lineHeight: '1',
- boxSizing: 'border-box',
- });
- tuneBadge.textContent = String(visParams.length);
- tune.appendChild(tuneBadge);
- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';
- tune.addEventListener('mouseenter', () => {
- if (!tuneOpen) tune.style.background = BP.accentSoft;
- });
- tune.addEventListener('mouseleave', () => {
- if (!tuneOpen) tune.style.background = 'transparent';
- });
- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });
- tune.dataset.iceqTune = '1';
- row.appendChild(tune);
- }
-
- // Spacer
- row.appendChild(el('div', { flex: '1' }));
-
- // Accept — primary action, uses the site's saturated brand magenta
- // with paper-white text, not the theme-muted BP.accent.
- const accept = el('button', {
- padding: '5px 14px', borderRadius: '5px',
- border: 'none', background: C.brand, color: 'oklch(98% 0 0)',
- fontFamily: FONT, fontSize: '11px', fontWeight: '600',
- cursor: 'pointer', transition: 'filter 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap',
- });
- accept.textContent = '\u2713 Accept';
- accept.addEventListener('mouseenter', () => accept.style.filter = 'brightness(1.08)');
- accept.addEventListener('mouseleave', () => accept.style.filter = 'none');
- accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');
- accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');
- accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
- row.appendChild(accept);
-
- // Discard
- const discard = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: FONT, fontSize: '11px', color: BP.textDim,
- cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
- });
- discard.textContent = '\u2715';
- discard.title = 'Discard all variants';
- discard.addEventListener('mouseenter', () => { discard.style.color = BP.text; discard.style.borderColor = BP.text; });
- discard.addEventListener('mouseleave', () => { discard.style.color = BP.textDim; discard.style.borderColor = BP.hairline; });
- discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
- row.appendChild(discard);
-
- return row;
- }
-
- // --- Shared UI builders ---
-
- // --- Saving row (waiting for agent to process accept/discard) ---
-
- function buildSavingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const spinner = el('div', {
- width: '14px', height: '14px', borderRadius: '50%',
- border: '2px solid ' + BP.hairline,
- borderTopColor: BP.accent,
- animation: 'impeccable-spin 0.6s linear infinite',
- flexShrink: '0',
- });
- row.appendChild(spinner);
- const label = el('span', {
- fontSize: '12px', color: BP.textDim, fontWeight: '500',
- });
- label.textContent = 'Applying variant...';
- row.appendChild(label);
-
- // Inject the keyframes if not already present
- if (!document.getElementById(PREFIX + '-keyframes')) {
- const style = document.createElement('style');
- style.id = PREFIX + '-keyframes';
- style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
- document.head.appendChild(style);
- }
- return row;
- }
-
- // --- Confirmed row (green success, auto-dismisses) ---
-
- function buildConfirmedRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const check = el('span', {
- fontSize: '15px', lineHeight: '1', flexShrink: '0',
- color: 'oklch(45% 0.15 145)',
- });
- check.textContent = '\u2713';
- row.appendChild(check);
- const label = el('span', {
- fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
- });
- label.textContent = 'Variant applied';
- row.appendChild(label);
- return row;
- }
-
- // --- Shared UI builders ---
-
- function buildDots(clickable) {
- const container = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
- for (let i = 1; i <= expectedVariants; i++) {
- const arrived = i <= arrivedVariants;
- const active = i === visibleVariant;
- // active: solid site-brand magenta dot. arrived+inactive: muted neutral.
- // pending (not yet arrived): faint outline ring. No borders on arrived
- // dots — the previous "accent ring + ash fill" combo read as noisy
- // magenta chips, especially when all variants had arrived and every
- // dot wore an accent ring.
- const dotBg = active ? C.brand
- : arrived ? BP.textDim
- : 'transparent';
- const dotBorder = arrived ? 'none' : '1.5px solid ' + BP.hairline;
- const dot = el('div', {
- width: active ? '8px' : '6px',
- height: active ? '8px' : '6px',
- borderRadius: '50%',
- background: dotBg,
- border: dotBorder,
- boxSizing: 'border-box',
- transition: 'all 0.2s ' + EASE,
- cursor: (clickable && arrived) ? 'pointer' : 'default',
- transform: arrived ? 'scale(1)' : 'scale(0.85)',
- opacity: arrived ? (active ? '1' : '0.6') : '0.4',
- });
- if (clickable && arrived) {
- const idx = i;
- dot.addEventListener('click', (e) => {
- e.stopPropagation();
- visibleVariant = idx;
- showVariantInDOM(currentSessionId, idx);
- updateSelectedElement();
- updateBarContent('cycling');
- });
- }
- container.appendChild(dot);
- }
- return container;
- }
-
- function navBtn(text) {
- const b = el('button', {
- width: '26px', height: '26px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- color: BP.text, fontFamily: FONT, fontSize: '13px',
- cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
- transition: 'border-color 0.12s ease, background 0.12s ease',
- padding: '0', lineHeight: '1',
- });
- b.textContent = text;
- b.addEventListener('mouseenter', () => { b.style.borderColor = BP.text; });
- b.addEventListener('mouseleave', () => { b.style.borderColor = BP.hairline; });
- return b;
- }
-
- function actionLabel() {
- const a = ACTIONS.find(a => a.value === selectedAction);
- return a ? a.label : 'Freeform';
- }
-
- function el(tag, styles) {
- const e = document.createElement(tag);
- if (styles) Object.assign(e.style, styles);
- return e;
- }
-
- // ---------------------------------------------------------------------------
- // Action picker popover
- // ---------------------------------------------------------------------------
-
- function initActionPicker() {
- const P = barPaletteForTheme(detectPageTheme());
- pickerEl = document.createElement('div');
- pickerEl.id = PREFIX + '-picker';
- Object.assign(pickerEl.style, {
- position: 'fixed', zIndex: Z.picker,
- display: 'none', opacity: '0',
- transform: 'scale(0.96) translateY(4px)',
- transformOrigin: 'bottom left',
- transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
- background: P.surface,
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
- padding: '6px',
- fontFamily: FONT,
- backdropFilter: 'blur(10px)',
- WebkitBackdropFilter: 'blur(10px)',
- });
-
- // Build the chip grid
- const grid = el('div', {
- display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
- });
-
- ACTIONS.forEach(action => {
- const chip = el('button', {
- display: 'flex', flexDirection: 'column', alignItems: 'center',
- gap: '4px',
- padding: '8px 6px', borderRadius: '6px',
- border: 'none',
- background: action.value === selectedAction ? P.accentSoft : 'transparent',
- color: action.value === selectedAction ? P.accent : P.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.1s ease, color 0.1s ease',
- textAlign: 'center', whiteSpace: 'nowrap',
- });
- const iconWrap = el('span', {
- display: 'flex', alignItems: 'center', justifyContent: 'center',
- height: '20px', opacity: '0.9',
- });
- iconWrap.innerHTML = ICONS[action.value] || '';
- const labelEl = el('span', { lineHeight: '1' });
- labelEl.textContent = action.label;
- chip.appendChild(iconWrap);
- chip.appendChild(labelEl);
- chip.dataset.action = action.value;
- chip.addEventListener('mouseenter', () => {
- if (action.value !== selectedAction) chip.style.background = P.accentSoft;
- });
- chip.addEventListener('mouseleave', () => {
- chip.style.background = action.value === selectedAction ? P.accentSoft : 'transparent';
- });
- chip.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedAction = action.value;
- hideActionPicker();
- updateBarContent('configure');
- });
- grid.appendChild(chip);
- });
-
- pickerEl.appendChild(grid);
- document.body.appendChild(pickerEl);
- defangOutsideHandlers(pickerEl);
-
- // Cache the palette on the picker so toggleActionPicker's state refresh
- // uses the same theme-aware colors when it repaints chips.
- pickerEl.__iceq_palette = P;
- }
-
- function toggleActionPicker() {
- if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
- // Rebuild chips to reflect current selection
- const P = pickerEl.__iceq_palette || barPaletteForTheme(detectPageTheme());
- pickerEl.querySelectorAll('button').forEach(chip => {
- const isActive = chip.dataset.action === selectedAction;
- chip.style.background = isActive ? P.accentSoft : 'transparent';
- chip.style.color = isActive ? P.accent : P.text;
- });
- // Position above the bar
- const barRect = barEl.getBoundingClientRect();
- const pickerH = 170; // approximate; grows with icon + label rows
- let top = barRect.top - pickerH - 6;
- if (top < 8) top = barRect.bottom + 6;
- Object.assign(pickerEl.style, {
- top: top + 'px', left: barRect.left + 'px',
- display: 'block',
- });
- requestAnimationFrame(() => {
- pickerEl.style.opacity = '1';
- pickerEl.style.transform = 'scale(1) translateY(0)';
- });
- }
-
- function hideActionPicker() {
- if (!pickerEl) return;
- pickerEl.style.opacity = '0';
- pickerEl.style.transform = 'scale(0.96) translateY(4px)';
- setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
- }
-
- // ---------------------------------------------------------------------------
- // Params panel (per-variant coarse controls)
- //
- // Variants may declare a parameter manifest via a JSON attribute on the
- // variant wrapper:
- //
- // <div data-impeccable-variant="1"
- // data-impeccable-params='[{"id":"density","kind":"steps",...}]'>
- //
- // The panel docks to the right edge of the outline during CYCLING and
- // exposes 2-5 coarse knobs. Values apply to the variant wrapper so scoped
- // CSS can respond instantly without regeneration:
- //
- // range / numeric toggle → CSS var (`--p-<id>`) used via var(--p-foo, N)
- // steps / boolean toggle → data-p-<id> attribute used via :scope[data-p-foo="..."]
- //
- // On variant switch, values reset to that variant's declared defaults.
- // On accept, current values are sent in the event payload so the agent
- // can bake them into the source-file write.
- // ---------------------------------------------------------------------------
-
- let paramsPanelEl = null; // outer wrapper (overflow:hidden, clips the slide)
- let paramsPanelInner = null; // translating content (carries bg, padding, knobs)
- let paramsPanelBody = null; // grid holding the knob cells
- let paramsCurrentValues = {}; // {paramId: value} — mirror of the visible variant's live values
- let tuneOpen = false; // whether the Tune popover is open right now
-
- // Theme-aware Tune popover. Appears as a drawer that slides out from the
- // contextual bar's bar-facing edge (below if the bar sits below the
- // element, above otherwise). Same width as the bar. Auto-wraps to extra
- // rows when the knobs exceed one row. The bar's border-radius on the
- // popover side goes flat while open so the two shapes read as one.
- let paramsPanelPalette = null;
-
- function initParamsPanel() {
- paramsPanelPalette = barPaletteForTheme(detectPageTheme());
- const P = paramsPanelPalette;
-
- // Single element, always in the DOM. The slide animation is a CSS mask
- // with mask-size growing from 0% to 100% along the bar-facing axis — no
- // display toggle, no opacity toggle, no transform trickery. The mask
- // hides everything initially; as it grows, content is revealed from
- // the bar edge outward.
- paramsPanelEl = document.createElement('div');
- paramsPanelEl.id = PREFIX + '-params-panel';
- Object.assign(paramsPanelEl.style, {
- position: 'fixed', zIndex: String(Z.bar - 1),
- background: P.surfaceDeep,
- color: P.text,
- fontFamily: FONT,
- padding: '14px 18px',
- boxSizing: 'border-box',
- borderRadius: '0 0 10px 10px',
- pointerEvents: 'none',
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
-
- // clip-path is the same conceptual reveal as mask but with rock-solid
- // transition support across engines. Closed state clips from the far
- // edge; open = inset(0) shows everything.
- clipPath: 'inset(0 0 100% 0)',
- transition: 'clip-path 0.44s ' + EASE,
-
- // Park off-screen until positionParamsPanel places it. These are NOT
- // in the transition list, so they snap instantly — no fly-in from the
- // top-left when first shown.
- top: '-9999px', left: '-9999px', width: '0',
- });
-
- paramsPanelBody = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
- gap: '12px 16px',
- });
-
- paramsPanelEl.appendChild(paramsPanelBody);
- document.body.appendChild(paramsPanelEl);
- // Don't override pointer-events: the panel toggles between 'none' (closed,
- // click-through) and 'auto' (open) on its own. Just silence the host's
- // outside-interaction listeners while the panel is open.
- defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
- paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
- }
-
- function getVisibleVariantEl() {
- if (!currentSessionId) return null;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return null;
- return wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"]');
- }
-
- function parseVariantParams(variantEl) {
- if (!variantEl) return [];
- const raw = variantEl.getAttribute('data-impeccable-params');
- if (!raw) return [];
- try {
- const parsed = JSON.parse(raw);
- return Array.isArray(parsed) ? parsed : [];
- } catch (err) {
- console.warn('[impeccable] Invalid data-impeccable-params JSON:', err.message);
- return [];
- }
- }
-
- function applyParamValue(variantEl, param, value) {
- if (!variantEl) return;
- const attr = 'data-p-' + param.id;
- if (param.kind === 'range') {
- variantEl.style.setProperty('--p-' + param.id, String(value));
- } else if (param.kind === 'toggle') {
- const on = !!value;
- variantEl.style.setProperty('--p-' + param.id, on ? '1' : '0');
- if (on) variantEl.setAttribute(attr, 'on');
- else variantEl.removeAttribute(attr);
- } else if (param.kind === 'steps') {
- variantEl.setAttribute(attr, String(value));
- }
- }
-
- function applyParamDefaults(variantEl, params) {
- paramsCurrentValues = {};
- for (const p of params) {
- paramsCurrentValues[p.id] = p.default;
- applyParamValue(variantEl, p, p.default);
- }
- }
-
- function formatRangeValue(input) {
- const max = parseFloat(input.max), min = parseFloat(input.min);
- const v = parseFloat(input.value);
- if (!isFinite(v)) return input.value;
- return (max - min) <= 2 ? v.toFixed(2) : String(Math.round(v));
- }
-
- function buildParamsPanel(variantEl, params) {
- const P = paramsPanelPalette || barPaletteForTheme(detectPageTheme());
- paramsPanelBody.innerHTML = '';
- for (const p of params) {
- const row = el('div', { display: 'flex', flexDirection: 'column', gap: '6px' });
- const labelRow = el('div', {
- display: 'flex', justifyContent: 'space-between',
- alignItems: 'baseline', gap: '8px',
- });
- const lbl = el('span', {
- fontSize: '10.5px', fontWeight: '600', color: P.text,
- letterSpacing: '0.03em',
- });
- lbl.textContent = p.label || p.id;
- labelRow.appendChild(lbl);
- const readout = el('span', {
- fontSize: '10.5px', color: P.textDim,
- fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
- });
- labelRow.appendChild(readout);
- row.appendChild(labelRow);
-
- if (p.kind === 'range') {
- const input = document.createElement('input');
- input.type = 'range';
- input.min = String(p.min != null ? p.min : 0);
- input.max = String(p.max != null ? p.max : 1);
- input.step = String(p.step != null ? p.step : 0.05);
- input.value = String(p.default);
- Object.assign(input.style, {
- width: '100%', accentColor: C.brand, cursor: 'pointer',
- });
- readout.textContent = formatRangeValue(input);
- input.addEventListener('input', (e) => {
- e.stopPropagation();
- const v = parseFloat(input.value);
- paramsCurrentValues[p.id] = v;
- readout.textContent = formatRangeValue(input);
- applyParamValue(variantEl, p, v);
- queueCheckpoint('param_changed');
- });
- row.appendChild(input);
- } else if (p.kind === 'toggle') {
- const initial = !!p.default;
- readout.textContent = initial ? 'On' : 'Off';
- const track = el('button', {
- position: 'relative', width: '36px', height: '20px',
- borderRadius: '10px', border: 'none', padding: '0',
- cursor: 'pointer',
- background: initial ? C.brand : P.hairline,
- transition: 'background 0.15s ease',
- alignSelf: 'flex-start',
- });
- const knob = el('span', {
- position: 'absolute', top: '2px',
- left: initial ? '18px' : '2px',
- width: '16px', height: '16px', borderRadius: '50%',
- background: 'oklch(98% 0 0)',
- transition: 'left 0.18s ' + EASE,
- boxShadow: '0 1px 2px oklch(0% 0 0 / 0.2)',
- });
- track.appendChild(knob);
- track.addEventListener('click', (e) => {
- e.stopPropagation();
- const next = !paramsCurrentValues[p.id];
- paramsCurrentValues[p.id] = next;
- track.style.background = next ? C.brand : P.hairline;
- knob.style.left = next ? '18px' : '2px';
- readout.textContent = next ? 'On' : 'Off';
- applyParamValue(variantEl, p, next);
- queueCheckpoint('param_changed');
- });
- row.appendChild(track);
- } else if (p.kind === 'steps') {
- const opts = (p.options || []).map(o =>
- typeof o === 'string' ? { value: o, label: o } : o
- );
- const activeOpt = opts.find(o => o.value === p.default) || opts[0];
- readout.textContent = activeOpt ? activeOpt.label : String(p.default);
- const segRow = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(' + opts.length + ', 1fr)',
- gap: '1px', padding: '2px',
- background: P.hairline, borderRadius: '5px',
- });
- const segBtns = [];
- opts.forEach(o => {
- const active = o.value === p.default;
- const b = el('button', {
- padding: '5px 4px', border: 'none', borderRadius: '3px',
- background: active ? C.brand : 'transparent',
- color: active ? 'oklch(98% 0 0)' : P.text,
- fontFamily: FONT, fontSize: '10.5px', fontWeight: '500',
- cursor: 'pointer', whiteSpace: 'nowrap',
- transition: 'background 0.1s ease, color 0.1s ease',
- });
- b.textContent = o.label;
- b.addEventListener('click', (e) => {
- e.stopPropagation();
- paramsCurrentValues[p.id] = o.value;
- readout.textContent = o.label;
- segBtns.forEach(({ btn, val }) => {
- const on = val === o.value;
- btn.style.background = on ? C.brand : 'transparent';
- btn.style.color = on ? 'oklch(98% 0 0)' : P.text;
- });
- applyParamValue(variantEl, p, o.value);
- queueCheckpoint('param_changed');
- });
- segRow.appendChild(b);
- segBtns.push({ btn: b, val: o.value });
- });
- row.appendChild(segRow);
- }
-
- paramsPanelBody.appendChild(row);
- }
- }
-
- // Decide which way the popover opens: away from the picked element. If the
- // bar landed below the element, popover slides DOWN from the bar's bottom.
- // If the bar landed above, popover slides UP from the bar's top.
- function popoverDirection() {
- if (!barEl || !selectedElement) return 'below';
- const br = barEl.getBoundingClientRect();
- const er = selectedElement.getBoundingClientRect();
- return br.top >= er.bottom - 4 ? 'below' : 'above';
- }
-
- // The popover overlaps the bar by OVERLAP px on the bar-facing side. With
- // popover z-index below bar, that overlap sits behind bar (invisible) and
- // reinforces the "tucked behind" feel. Padding compensates so the real
- // content starts flush with bar's outer edge.
- const TUNE_OVERLAP = 6;
-
- // Closed clip-path depends on direction: for 'below' clip from the far
- // (bottom) edge so the reveal grows downward from the bar; for 'above'
- // clip from the top edge so the reveal grows upward from the bar.
- function closedClipPath(direction) {
- return direction === 'below' ? 'inset(0 0 100% 0)' : 'inset(100% 0 0 0)';
- }
-
- function setClipPath(value, withTransition) {
- const saved = paramsPanelEl.style.transition;
- if (!withTransition) paramsPanelEl.style.transition = 'none';
- paramsPanelEl.style.clipPath = value;
- if (!withTransition) {
- void paramsPanelEl.offsetHeight;
- paramsPanelEl.style.transition = saved;
- }
- }
-
- function positionParamsPanel() {
- if (!paramsPanelEl || !barEl || barEl.style.display === 'none') return;
- const br = barEl.getBoundingClientRect();
- const direction = popoverDirection();
- const prevDirection = paramsPanelEl.dataset.tuneDirection;
-
- // top/left/width are NOT in the transition list, so they snap instantly.
- paramsPanelEl.style.left = br.left + 'px';
- paramsPanelEl.style.width = br.width + 'px';
-
- if (direction === 'below') {
- paramsPanelEl.style.top = (br.bottom - TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '0 0 10px 10px';
- paramsPanelEl.style.paddingTop = (14 + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.paddingBottom = '14px';
- } else {
- const ih = paramsPanelEl.offsetHeight || 80;
- paramsPanelEl.style.top = (br.top - ih + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '10px 10px 0 0';
- paramsPanelEl.style.paddingTop = '14px';
- paramsPanelEl.style.paddingBottom = (14 + TUNE_OVERLAP) + 'px';
- }
- paramsPanelEl.dataset.tuneDirection = direction;
-
- // If currently closed and direction flipped (or first-time setup),
- // snap the clip-path to the new direction's closed pose without
- // transitioning (so the clip doesn't slide across the element).
- if (!tuneOpen && (!prevDirection || prevDirection !== direction)) {
- setClipPath(closedClipPath(direction), false);
- }
- }
-
- function showParamsPanel() {
- if (!paramsPanelEl) return;
- positionParamsPanel();
- paramsPanelEl.style.pointerEvents = 'auto';
- // rAF so the positioning paint commits before the transition fires.
- requestAnimationFrame(() => {
- setClipPath('inset(0 0 0 0)', true);
- });
- }
-
- function hideParamsPanel() {
- if (!paramsPanelEl) return;
- paramsPanelEl.style.pointerEvents = 'none';
- const direction = paramsPanelEl.dataset.tuneDirection || 'below';
- setClipPath(closedClipPath(direction), true);
- }
-
- // Build/rebuild the panel's contents for the current variant AND apply
- // its defaults to the variant wrapper (so scoped CSS responds even before
- // the user opens the popover). Visibility is governed by tuneOpen.
- function refreshParamsPanel() {
- if (state !== 'CYCLING') {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- if (tuneOpen) {
- // If already visible (variant cycled while open), refresh in place
- // instead of re-running the clip-path animation.
- const alreadyVisible = paramsPanelEl.style.display === 'block'
- && paramsPanelEl.style.opacity === '1';
- if (alreadyVisible) positionParamsPanel();
- else showParamsPanel();
- } else {
- hideParamsPanel();
- }
- }
-
- function toggleTunePopover() {
- if (tuneOpen) { closeTunePopover(); return; }
- openTunePopover();
- }
-
- function openTunePopover() {
- if (state !== 'CYCLING') return;
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) return;
- // Build fresh to ensure the current variant's controls are shown.
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- tuneOpen = true;
- showParamsPanel();
- // Kill the bar's shadow on the popover-facing side so the dark popover
- // doesn't pick up a bright glow line.
- if (barEl) {
- const direction = paramsPanelEl?.dataset.tuneDirection || 'below';
- barEl.style.boxShadow = direction === 'below' ? BAR_SHADOW_UP : BAR_SHADOW_DOWN;
- }
- // Re-render the bar so the Tune chip picks up the active styling.
- updateBarContent('cycling');
- }
-
- function closeTunePopover() {
- tuneOpen = false;
- hideParamsPanel();
- if (barEl) barEl.style.boxShadow = BAR_SHADOW_DEFAULT;
- if (barEl && barEl.style.display !== 'none' && state === 'CYCLING') {
- updateBarContent('cycling');
- }
- }
-
- // ---------------------------------------------------------------------------
- // Variant cycling in DOM
- // ---------------------------------------------------------------------------
-
- function showVariantInDOM(sessionId, num) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
- for (const child of wrapper.children) {
- const v = child.dataset ? child.dataset.impeccableVariant : null;
- if (!v) continue;
- child.style.display = (v === String(num)) ? '' : 'none';
- }
- // Unconditional refresh — covers first-reveal (no-op if state isn't
- // CYCLING yet, the subsequent CYCLING transition triggers its own
- // refresh) and every cycle step.
- refreshParamsPanel();
- }
-
- /**
- * No-HMR fallback: fetch the raw source file from the live server,
- * parse it, extract the variant wrapper, and inject it into the live DOM.
- * This works even when the dev server caches HTML (Bun, static servers).
- */
- function injectVariantsFromSource(filePath, sessionId) {
- const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
- fetch(url)
- .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
- .then(html => {
- // Parse the raw source HTML
- const parser = new DOMParser();
- const doc = parser.parseFromString(html, 'text/html');
- const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!srcWrapper) {
- console.error('[impeccable] Variant wrapper not found in source file.');
- return;
- }
-
- // Find the original element in the live DOM.
- // The original is inside the wrapper in the source. We find the
- // corresponding element in the live DOM by matching the first child's
- // tag + classes from the original snapshot.
- const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
- if (!origContent) return;
-
- const tag = origContent.tagName.toLowerCase();
- const cls = origContent.className;
- let liveEl = null;
- if (origContent.id) {
- liveEl = document.getElementById(origContent.id);
- } else if (cls) {
- // Find by tag + exact class match
- const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
- for (const c of candidates) {
- if (c.className === cls && !own(c)) { liveEl = c; break; }
- }
- }
-
- if (!liveEl) {
- console.error('[impeccable] Could not find original element in live DOM.');
- return;
- }
-
- const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;
-
- // Replace the live element with the full wrapper from source
- const wrapper = srcWrapper.cloneNode(true);
- liveEl.parentElement.replaceChild(wrapper, liveEl);
-
- // Update state: count variants, preserving the user's current variant
- // when a late HMR/source reinjection lands after they have cycled.
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants
- ? previousVisibleVariant
- : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);
- showVariantInDOM(sessionId, visibleVariant);
-
- // Update selectedElement to the visible variant's content
- selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;
-
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- saveSession();
- console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
- })
- .catch(err => {
- console.error('[impeccable] Failed to fetch source:', err);
- showToast('Could not load variants. Try refreshing the page.', 5000);
- });
- }
-
- function cycleVariant(dir) {
- const next = visibleVariant + dir;
- if (next < 1 || next > arrivedVariants) return;
- visibleVariant = next;
- showVariantInDOM(currentSessionId, next); // calls refreshParamsPanel itself
- updateSelectedElement();
- updateBarContent('cycling');
- saveSession();
- queueCheckpoint('variant_changed');
- }
-
- function updateSelectedElement() {
- if (!currentSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return;
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- function readVisibleVariantFromDOM(sessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return 0;
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- for (const variant of variants) {
- if (variant.style.display === 'none') continue;
- const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);
- if (idx > 0) return idx;
- }
- return 0;
- }
-
- // Resolve the element that represents the variant's visible content.
- // Contract: each variant div should contain exactly one top-level element
- // (the full replacement). In practice a model may ship loose siblings or
- // lead with <style>/<script>. Be defensive: skip non-visual elements, and
- // if the variant has multiple element children, use the variant div itself
- // (it wraps all of them and gets correct bounds).
- function pickVariantContent(wrapper, index) {
- if (!wrapper) return null;
- const variantDiv = wrapper.querySelector('[data-impeccable-variant="' + index + '"]');
- if (!variantDiv) return null;
- const NON_VISUAL = new Set(['STYLE', 'SCRIPT', 'LINK', 'META', 'TEMPLATE']);
- const visual = [];
- for (const child of variantDiv.children) {
- if (!NON_VISUAL.has(child.tagName)) visual.push(child);
- }
- if (visual.length === 1) return visual[0];
- return variantDiv;
- }
-
- // Hold window.scrollY at a fixed value across DOM mutations inside the
- // session's wrapper (HMR patches, variant inserts, cycle swaps).
- function startScrollLock(sessionId, initialTargetY) {
- stopScrollLock();
- scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)
- ? initialTargetY
- : window.scrollY;
- console.log('[impeccable.scroll] startScrollLock', { sessionId, scrollY: window.scrollY, targetY: scrollLockTargetY, initialOverride: initialTargetY });
-
- try { history.scrollRestoration = 'manual'; } catch {}
-
- const prevHtmlAnchor = document.documentElement.style.overflowAnchor;
- const prevBodyAnchor = document.body.style.overflowAnchor;
- document.documentElement.style.overflowAnchor = 'none';
- document.body.style.overflowAnchor = 'none';
-
- const correct = (why) => {
- scrollLockRaf = null;
- if (scrollLockTargetY == null) return;
- const before = window.scrollY;
- const delta = before - scrollLockTargetY;
- if (Math.abs(delta) < 0.5) {
- console.log('[impeccable.scroll] correct noop', { why, scrollY: before, targetY: scrollLockTargetY });
- return;
- }
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] corrected', { why, from: before, to: scrollLockTargetY, delta, nowAt: window.scrollY });
- };
- const schedule = (why) => {
- if (scrollLockRaf != null) return;
- scrollLockRaf = requestAnimationFrame(() => correct(why));
- };
-
- scrollLockObserver = new MutationObserver((mutations) => {
- for (const m of mutations) {
- if (m.target?.closest?.('[data-impeccable-variants="' + sessionId + '"]')) {
- const childAdds = Array.from(m.addedNodes).map(n => n.nodeType === 1 ? (n.tagName + (n.dataset?.impeccableVariant ? ('[variant=' + n.dataset.impeccableVariant + ']') : '')) : n.nodeType).join(',');
- console.log('[impeccable.scroll] mutation inside wrapper', { type: m.type, target: m.target?.tagName, adds: childAdds, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('mutation-in-wrapper');
- return;
- }
- for (const n of m.addedNodes) {
- if (n.nodeType === 1 && (n.matches?.('[data-impeccable-variants="' + sessionId + '"]') || n.querySelector?.('[data-impeccable-variants="' + sessionId + '"]'))) {
- console.log('[impeccable.scroll] wrapper node added', { tag: n.tagName, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('wrapper-added');
- return;
- }
- }
- }
- });
- scrollLockObserver.observe(document.body, { childList: true, subtree: true });
-
- scrollLockAbort = new AbortController();
- scrollLockAbort.signal.addEventListener('abort', () => {
- document.documentElement.style.overflowAnchor = prevHtmlAnchor;
- document.body.style.overflowAnchor = prevBodyAnchor;
- }, { once: true });
- const sig = { signal: scrollLockAbort.signal };
- // Track whether the most recent scroll came from a user gesture. We
- // gate user-scroll re-anchoring on this flag so programmatic smooth
- // scrolls (browser reload-restore, scrollIntoView from other scripts)
- // don't accidentally update our target.
- let userGestureAt = 0;
- const USER_GESTURE_WINDOW_MS = 250;
-
- const reanchor = (why) => {
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- const prevTarget = scrollLockTargetY;
- scrollLockTargetY = window.scrollY;
- writeScrollY(scrollLockTargetY);
- console.log('[impeccable.scroll] reanchor', { why, prevTarget, newTarget: scrollLockTargetY });
- };
- const markGesture = (why) => {
- userGestureAt = performance.now();
- reanchor(why);
- };
- window.addEventListener('wheel', () => markGesture('wheel'), { passive: true, ...sig });
- window.addEventListener('touchstart', () => markGesture('touchstart'), { passive: true, ...sig });
- window.addEventListener('touchmove', () => markGesture('touchmove'), { passive: true, ...sig });
- window.addEventListener('keydown', (e) => {
- if (['PageDown', 'PageUp', ' ', 'End', 'Home', 'ArrowDown', 'ArrowUp'].includes(e.key)) markGesture('key:' + e.key);
- }, sig);
-
- // Correct on EVERY scroll event: whether it's the browser's
- // post-reload animated restore or some other script calling
- // scrollIntoView, we want to snap back immediately. Only skip if a
- // user gesture fired in the last 250ms.
- let lastLoggedScrollY = window.scrollY;
- window.addEventListener('scroll', () => {
- const now = window.scrollY;
- if (Math.abs(now - lastLoggedScrollY) > 5) {
- console.log('[impeccable.scroll] scroll event', { from: lastLoggedScrollY, to: now, targetY: scrollLockTargetY });
- lastLoggedScrollY = now;
- }
- if (scrollLockTargetY == null) return;
- if (performance.now() - userGestureAt < USER_GESTURE_WINDOW_MS) return;
- if (Math.abs(now - scrollLockTargetY) < 0.5) return;
- console.log('[impeccable.scroll] scroll-event snap', { from: now, to: scrollLockTargetY });
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- }, { passive: true, ...sig });
-
- // Apply target synchronously, not via rAF — racing the browser's
- // restore or a smooth-scroll animation means we want to win now.
- if (Math.abs(window.scrollY - scrollLockTargetY) > 0.5) {
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] startScrollLock initial apply', { to: scrollLockTargetY });
- }
- }
-
- function stopScrollLock() {
- if (scrollLockObserver) { scrollLockObserver.disconnect(); scrollLockObserver = null; }
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }
- scrollLockTargetY = null;
- // NOTE: do NOT clear the persistent scroll key here. startScrollLock
- // calls us as a reset, and clearing the key would nuke the Go-time
- // scrollY that the next resume needs to read.
- }
-
- // ---------------------------------------------------------------------------
- // MutationObserver for progressive variant reveal
- // ---------------------------------------------------------------------------
-
- function startVariantObserver(sessionId) {
- let updating = false; // re-entrancy guard
-
- const obs = new MutationObserver((mutations) => {
- if (updating) return;
-
- // Only react to mutations that add nodes with data-impeccable-variant,
- // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
- let dominated = false;
- for (const m of mutations) {
- if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
- for (const n of m.addedNodes) {
- if (n.nodeType !== 1) continue;
- // Direct hit: the added node itself is the wrapper or a variant.
- if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
- dominated = true; break;
- }
- // Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
- // a whole subtree where the wrapper is a descendant of the added
- // node. Without this check, the observer ignores those mutations
- // and the session stays in GENERATING forever.
- if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
- dominated = true; break;
- }
- }
- if (dominated) break;
- }
- if (!dominated) return;
-
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
-
- // Re-anchor selectedElement if it was detached by live-wrap's HMR swap.
- // Without this, the shader / highlight / bar track a zero-rect phantom
- // and the overlay appears frozen.
- if (selectedElement && !document.body.contains(selectedElement)) {
- selectedElement = pickVariantContent(wrapper, 'original') || wrapper;
- }
-
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- const count = variants.length;
-
- // Nothing new
- if (count <= arrivedVariants) return;
-
- updating = true;
- arrivedVariants = count;
- if (visibleVariant === 0 && arrivedVariants > 0) {
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;
- showVariantInDOM(sessionId, visibleVariant);
- // showVariantInDOM hid the original (display:none); if we were still
- // anchored to the original's content, its boundingRect is now zero
- // and the bar snaps to (0,0). Re-point at the visible variant instead.
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- if (expected > 0) expectedVariants = expected;
-
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- } else if (state === 'GENERATING') {
- updateBarContent('generating');
- }
- saveSession();
- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');
- updating = false;
- });
-
- obs.observe(document.body, { childList: true, subtree: true });
- return obs;
- }
-
- // ---------------------------------------------------------------------------
- // Bar scroll tracking
- // ---------------------------------------------------------------------------
-
- function startScrollTracking() {
- function tick() {
- if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
- positionBar();
- showHighlight(selectedElement);
- if (tuneOpen) positionParamsPanel();
- }
- if (annotActive) positionAnnotOverlay(selectedElement);
- // Shader overlay (via debug P toggle or generation) is repositioned
- // by its own branch below; debug no longer has a separate overlay.
- if (shaderState) positionShaderOverlay();
- scrollRaf = requestAnimationFrame(tick);
- }
- scrollRaf = requestAnimationFrame(tick);
- }
-
- function stopScrollTracking() {
- if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
- }
-
- // ---------------------------------------------------------------------------
- // SSE (server→browser) + fetch POST (browser→server)
- // Zero-dependency replacement for WebSocket.
- // ---------------------------------------------------------------------------
-
- let evtSource = null;
- let sseRetries = 0;
- const SSE_MAX_RETRIES = 20; // generous: heartbeats keep the connection alive, so retries mean real trouble
-
- function connectSSE() {
- evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
-
- evtSource.onopen = () => {
- sseRetries = 0; // reset on successful (re)connect
- };
-
- evtSource.onmessage = (e) => {
- sseRetries = 0; // reset on any successful message
- let msg; try { msg = JSON.parse(e.data); } catch { return; }
- switch (msg.type) {
- case 'connected':
- hasProjectContext = !!msg.hasProjectContext;
- if (!hasProjectContext) showToast('No PRODUCT.md found. Variants will be brand-agnostic. Run /impeccable teach to generate one.', 7000);
- console.log('[impeccable] Live mode connected.');
- if (state === 'IDLE') state = 'PICKING';
- break;
- case 'done':
- // Variants already arrived via HMR → normal transition.
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- if (state === 'GENERATING') {
- state = 'CYCLING';
- updateBarContent('cycling');
- refreshParamsPanel();
- }
- break;
- }
- // Variants are in source but not in the DOM yet. Common when the
- // picked element lived inside conditional render (closed modal,
- // hidden tab, a route the user navigated away from). The variant
- // MutationObserver stays armed and auto-transitions to CYCLING
- // the moment the wrapper actually mounts. Nudge the user toward
- // that path with a toast — better than the prior force-reload
- // which reset framework state and left the session stuck.
- setTimeout(() => {
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
- if (state !== 'GENERATING') return;
- showToast(
- "Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
- 15000,
- );
- }, 2000);
- break;
- case 'error':
- console.error('[impeccable] Error:', msg.message);
- showToast('Error: ' + msg.message, 5000);
- hideBar();
- state = 'PICKING';
- break;
- }
- };
-
- evtSource.onerror = () => {
- sseRetries++;
- if (sseRetries <= SSE_MAX_RETRIES) {
- console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
- return; // EventSource auto-reconnects
- }
- // Server is gone. Clean up gracefully.
- console.log('[impeccable] Live server unreachable. Cleaning up UI.');
- evtSource.close();
- evtSource = null;
- handleServerLost();
- };
- }
-
- /** Server died or became unreachable. Reset UI to a clean state. */
- function handleServerLost() {
- const recoveryState = currentSessionId ? state : 'IDLE';
- if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
- showToast('Live server disconnected. Session ended.', 5000);
- }
- hideBar();
- hideHighlight();
- hideShaderOverlay();
- hideAnnotOverlay();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- // Preserve local session state on server loss. The durable journal is the
- // source of truth, but localStorage plus the variant wrapper lets the UI
- // resume after a helper restart or page reload instead of treating a
- // transient disconnect as an explicit discard.
- selectedElement = null;
- selectedAction = 'impeccable';
- state = recoveryState;
- if (currentSessionId) saveSession();
- }
-
- function sendEvent(msg, opts) {
- msg.token = TOKEN;
- function handleFailure(err) {
- console.error('[impeccable] Failed to send event:', err);
- if (opts && opts.throwOnError) throw err;
- return null;
- }
- return fetch('http://localhost:' + PORT + '/events', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(msg),
- }).then(res => {
- if (res.ok) return res;
- return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));
- }).catch(handleFailure);
- }
-
- function checkpointPayload(reason) {
- return {
- type: 'checkpoint',
- id: currentSessionId,
- revision: sessionState.nextCheckpointRevision(),
- owner: browserOwner,
- phase: String(state || '').toLowerCase(),
- reason,
- pageUrl: location.pathname,
- expectedVariants,
- arrivedVariants,
- visibleVariant,
- paramValues: { ...paramsCurrentValues },
- };
- }
-
- function sendCheckpoint(reason) {
- if (!currentSessionId) return Promise.resolve(null);
- return sendEvent(checkpointPayload(reason)).catch(() => null);
- }
-
- function queueCheckpoint(reason) {
- if (!currentSessionId) return;
- if (checkpointTimer) clearTimeout(checkpointTimer);
- checkpointTimer = setTimeout(() => {
- checkpointTimer = null;
- sendCheckpoint(reason);
- }, 120);
- }
-
- // ---------------------------------------------------------------------------
- // Event handlers
- // ---------------------------------------------------------------------------
-
- function handleMouseMove(e) {
- if (state !== 'PICKING' || !pickActive) return;
- const target = document.elementFromPoint(e.clientX, e.clientY);
- if (!target || !pickable(target) || target === hoveredElement) return;
- hoveredElement = target;
- showHighlight(target);
- }
-
- function handleClick(e) {
- // Close action picker on any outside click
- if (pickerEl?.style.display !== 'none' && !own(e.target)) {
- hideActionPicker();
- }
- // Close Tune popover on outside click (anything outside panel + bar)
- if (tuneOpen && paramsPanelEl && !paramsPanelEl.contains(e.target) && barEl && !barEl.contains(e.target)) {
- closeTunePopover();
- }
- // In CONFIGURING: click outside the bar and selected element returns to PICKING
- if (state === 'CONFIGURING' && !own(e.target) && selectedElement && !selectedElement.contains(e.target)) {
- hideBar();
- stopScrollTracking();
- hideAnnotOverlay();
- clearAnnotations();
- state = 'PICKING';
- hoveredElement = null;
- hideHighlight();
- return;
- }
- if (state !== 'PICKING' || !pickActive) return;
- if (own(e.target)) return;
- if (!hoveredElement || !pickable(hoveredElement)) return;
- e.preventDefault();
- e.stopPropagation();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- maybePrefetchPage();
- maybeWarnConditionalAncestor(selectedElement);
- }
-
- /**
- * Surface a brief, non-blocking heads-up when the picked element lives
- * inside a container whose visibility is gated by ephemeral state — modals,
- * collapsible panels, popovers, off-screen tab panels. If HMR remounts the
- * parent during generation (Vite Fast Refresh, SvelteKit page reload), the
- * variants land in source but stay invisible until the user re-opens the
- * container. Telling the user upfront is much friendlier than the silent
- * timeout-then-toast that they'd otherwise hit.
- *
- * Heuristic, intentionally narrow — only fires for unambiguous cases so
- * we don't cry wolf on every nested element.
- */
- function maybeWarnConditionalAncestor(el) {
- let node = el?.parentElement;
- let depth = 0;
- while (node && depth < 12) {
- // 1. Active dialog / modal
- if (node.getAttribute && node.getAttribute('role') === 'dialog'
- && node.getAttribute('aria-modal') === 'true') {
- showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 2. Common Radix / shadcn / headless-ui open-state attribute
- if (node.dataset && node.dataset.state === 'open') {
- showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 3. Tab panel — only meaningful when the page also shows ANOTHER
- // tab as selected. A single tabpanel with no tablist is just a static
- // section in disguise and isn't conditional.
- if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
- const list = document.querySelector('[role="tablist"]');
- if (list) {
- const tabs = list.querySelectorAll('[role="tab"]');
- if (tabs.length > 1) {
- showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
- return;
- }
- }
- }
- // 4. Collapsible: aria-expanded sibling. Look for the trigger button.
- if (node.id) {
- const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
- if (trigger) {
- showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
- return;
- }
- }
- node = node.parentElement;
- depth++;
- }
- }
-
- // Fire a lightweight prefetch event the first time the user selects an
- // element on a given route. The agent uses this to Read the underlying file
- // into context before Go is hit, shaving the read off the critical path.
- // Dedupe per session by pathname — clicking around on the same page doesn't
- // re-fire.
- //
- // DISABLED: quick-Go workflows pay an extra harness round trip because
- // prefetch + generate arrive as two events instead of one. Re-enable with
- // a browser-side debounce (~800–1000ms, cancelled on Go) if we want to
- // resurrect this. Server validator and skill dispatch remain in place so
- // flipping this flag is the only change needed.
- const PREFETCH_ENABLED = false;
- const prefetchedPaths = new Set();
- function maybePrefetchPage() {
- if (!PREFETCH_ENABLED) return;
- const path = location.pathname;
- if (prefetchedPaths.has(path)) return;
- prefetchedPaths.add(path);
- sendEvent({ type: 'prefetch', pageUrl: path });
- }
-
- function handleKeyDown(e) {
- // When the annotation input is focused, let it handle its own keys.
- if (annotEditing && annotEditing.input && e.target === annotEditing.input) return;
- if (e.key === 'Escape') {
- e.preventDefault();
- if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
- if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); hideAnnotOverlay(); clearAnnotations(); state = 'PICKING'; return; }
- if (state === 'CYCLING') { handleDiscard(); return; }
- if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
- if (state === 'PICKING') {
- // Use togglePick so the "Pick" button in the global bar also flips
- // off, otherwise the bar stays lit while nothing else is active.
- if (pickActive) togglePick();
- else { hideHighlight(); state = 'IDLE'; }
- return;
- }
- }
-
- // Arrow/Enter nav works in PICKING (hover) and CONFIGURING (selected, input empty)
- var navEl = (state === 'PICKING') ? hoveredElement : (state === 'CONFIGURING') ? selectedElement : null;
- if (navEl && (e.key === 'ArrowUp' || e.key === 'ArrowDown' || (e.key === 'Enter' && state === 'PICKING'))) {
- let next = null;
- if (e.key === 'ArrowDown' && !e.shiftKey) {
- next = navEl.nextElementSibling;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'ArrowUp' && !e.shiftKey) {
- next = navEl.previousElementSibling;
- while (next && !pickable(next)) next = next.previousElementSibling;
- } else if (e.key === 'ArrowUp' && e.shiftKey) {
- next = navEl.parentElement;
- if (next && !pickable(next)) next = null;
- } else if (e.key === 'ArrowDown' && e.shiftKey) {
- next = navEl.firstElementChild;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'Enter') {
- e.preventDefault();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- return;
- }
- if (next) {
- e.preventDefault();
- if (state === 'PICKING') {
- hoveredElement = next;
- } else {
- // CONFIGURING: re-select the new element and refresh the bar
- selectedElement = next;
- clearAnnotations();
- showAnnotOverlay(next);
- showBar('configure');
- startScrollTracking();
- }
- showHighlight(next);
- next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
- }
- return;
- }
-
- if (state === 'CYCLING') {
- if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
- if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
- if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
- }
- }
-
- function handleGo() {
- if (!selectedElement || state !== 'CONFIGURING') return;
- const input = document.getElementById(PREFIX + '-input');
- const prompt = input ? input.value.trim() : '';
-
- // Commit any pending pin edit BEFORE we snapshot annotations.
- if (annotEditing) finalizeEditingPin();
-
- currentSessionId = id8();
- expectedVariants = selectedCount;
- arrivedVariants = 0;
- visibleVariant = 0;
-
- // Flip to GENERATING immediately so the bar morphs without waiting on
- // capture + upload. The event is emitted from captureAndEmit() once the
- // screenshot is uploaded (or capture fails — we still emit, just without
- // screenshotPath).
- const elForCapture = selectedElement;
- const captureRect = elForCapture.getBoundingClientRect();
- const snapshot = {
- comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),
- strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),
- };
- const basePayload = {
- type: 'generate', id: currentSessionId,
- action: selectedAction,
- freeformPrompt: prompt || undefined,
- count: selectedCount,
- pageUrl: location.pathname,
- element: extractContext(elForCapture),
- };
- if (snapshot.comments.length > 0) basePayload.comments = snapshot.comments;
- if (snapshot.strokes.length > 0) basePayload.strokes = snapshot.strokes;
-
- // Hide the interactive overlay so it doesn't linger during generation.
- hideAnnotOverlay();
- clearAnnotations();
-
- state = 'GENERATING';
- showBar('generating');
- saveSession();
- sendCheckpoint('generate_started');
- writeScrollY(window.scrollY);
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
- console.log('[impeccable.scroll] Go pressed', { scrollY: window.scrollY, sessionId: currentSessionId });
- startScrollLock(currentSessionId);
-
- captureAndEmit(elForCapture, basePayload, snapshot, captureRect);
- }
-
- // ---------------------------------------------------------------------------
- // Screenshot capture + upload
- // ---------------------------------------------------------------------------
-
- let msLoadPromise = null;
- function loadModernScreenshot() {
- if (window.modernScreenshot) return Promise.resolve(window.modernScreenshot);
- if (msLoadPromise) return msLoadPromise;
- msLoadPromise = new Promise((resolve, reject) => {
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/modern-screenshot.js';
- s.onload = () => resolve(window.modernScreenshot);
- s.onerror = () => { msLoadPromise = null; reject(new Error('modern-screenshot failed to load')); };
- document.head.appendChild(s);
- });
- return msLoadPromise;
- }
-
- // Collect @font-face rules from every stylesheet on the page. Cross-origin
- // sheets (Google Fonts, Typekit, etc.) throw SecurityError on .cssRules
- // access, so modern-screenshot can't embed them on its own — the resulting
- // SVG falls back to system fonts and text re-wraps + renders with different
- // weight. We fetch the raw CSS text (CORS-permitted for these providers),
- // extract @font-face blocks, inline the referenced font files as base64
- // data URIs (SVGs rasterized via canvas can't fetch external resources,
- // so URLs inside the SVG silently fail without this), and pass the result
- // to modern-screenshot as font.cssText.
- const FONT_EXT_RE = /\.(woff2?|ttf|otf|eot)(\?.*)?$/i;
- const FONT_MIME = {
- woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', eot: 'application/vnd.ms-fontobject',
- };
- function bufferToBase64(buf) {
- const bytes = new Uint8Array(buf);
- let binary = '';
- const CHUNK = 0x8000;
- for (let i = 0; i < bytes.length; i += CHUNK) {
- binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
- }
- return btoa(binary);
- }
- async function inlineFontUrls(cssText) {
- const urlRe = /url\((['"]?)(https?:\/\/[^'")\s]+)\1\)/g;
- const urls = new Set();
- let m;
- while ((m = urlRe.exec(cssText))) {
- if (FONT_EXT_RE.test(m[2])) urls.add(m[2]);
- }
- const map = new Map();
- await Promise.all([...urls].map(async (url) => {
- try {
- const res = await fetch(url);
- if (!res.ok) return;
- const buf = await res.arrayBuffer();
- const ext = url.toLowerCase().match(FONT_EXT_RE)?.[1] || 'woff2';
- const mime = FONT_MIME[ext] || 'application/octet-stream';
- map.set(url, 'data:' + mime + ';base64,' + bufferToBase64(buf));
- } catch { /* skip; fall through to URL */ }
- }));
- return cssText.replace(urlRe, (orig, q, url) => {
- const data = map.get(url);
- return data ? 'url(' + q + data + q + ')' : orig;
- });
- }
- async function collectFontCssText() {
- const chunks = [];
- const fontFaceRe = /@font-face\s*\{[^}]*\}/g;
- for (const sheet of document.styleSheets) {
- try {
- const rules = sheet.cssRules;
- for (const rule of rules) {
- if (rule.constructor.name === 'CSSFontFaceRule' || rule.cssText?.startsWith('@font-face')) {
- chunks.push(rule.cssText);
- }
- }
- } catch {
- if (!sheet.href) continue;
- try {
- const res = await fetch(sheet.href);
- if (!res.ok) continue;
- const text = await res.text();
- let m2;
- while ((m2 = fontFaceRe.exec(text))) chunks.push(m2[0]);
- } catch { /* ignore; capture is best-effort */ }
- }
- }
- if (chunks.length === 0) return '';
- return inlineFontUrls(chunks.join('\n'));
- }
-
- // True if `s` is a computed color string that renders as nothing
- // (explicit `transparent`, or `rgba(...)` with alpha 0).
- function isTransparentColor(s) {
- if (!s) return true;
- if (s === 'transparent') return true;
- const m = /rgba?\(([^)]+)\)/.exec(s);
- if (!m) return false;
- const parts = m[1].split(',').map((p) => p.trim());
- if (parts.length === 4) return parseFloat(parts[3]) === 0;
- return false;
- }
-
- // modern-screenshot force-sets `background-color: X !important` on the
- // cloned root whenever `backgroundColor` is passed, clobbering the
- // element's own background. So we only pass it when the element is
- // genuinely transparent (no own color, no own image) — in that case
- // we resolve up the DOM to the nearest opaque ancestor so the capture
- // sits on the page's real background instead of rendering black.
- function resolveCanvasBackground(el) {
- const own = getComputedStyle(el);
- if (!isTransparentColor(own.backgroundColor)) return null;
- if (own.backgroundImage && own.backgroundImage !== 'none') return null;
- let node = el.parentElement;
- while (node) {
- const cs = getComputedStyle(node);
- if (!isTransparentColor(cs.backgroundColor)) return cs.backgroundColor;
- node = node.parentElement;
- }
- // The walk already passed through <body> and <html>; if they had been
- // opaque we would have returned. Falling through with the previous
- // `getComputedStyle(body).backgroundColor || …` chain is a trap: that
- // call returns the literal string `"rgba(0, 0, 0, 0)"` for a page that
- // never set its own bg, which is truthy and short-circuits the chain to
- // transparent-black — modern-screenshot then renders the capture on a
- // black canvas and the shader overlay flashes solid black during load.
- // The browser canvas defaults to white, so we do too.
- return '#ffffff';
- }
-
- // Capture the element (with current annotations baked in) and return a PNG
- // Blob. Shared between the Go flow (uploads it to the server) and the
- // debug toggle (displays it as an overlay for side-by-side comparison).
- async function captureElementToBlob(el, snapshot, rect) {
- try { if (document.fonts?.ready) await document.fonts.ready; } catch {}
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- let annotNode = null;
- let savedPosition = null;
- if (hasAnnotations) {
- const pos = getComputedStyle(el).position;
- if (pos === 'static') {
- savedPosition = el.style.position;
- el.style.position = 'relative';
- }
- annotNode = buildAnnotationsForCapture(rect, snapshot);
- el.appendChild(annotNode);
- }
- try {
- const ms = await loadModernScreenshot();
- const fontCssText = await collectFontCssText();
- const backgroundColor = resolveCanvasBackground(el);
- return await ms.domToBlob(el, {
- scale: Math.min(window.devicePixelRatio || 1, 2),
- font: fontCssText ? { cssText: fontCssText } : undefined,
- ...(backgroundColor ? { backgroundColor } : {}),
- });
- } finally {
- if (annotNode) annotNode.remove();
- if (savedPosition !== null) el.style.position = savedPosition;
- }
- }
-
- async function captureAndEmit(el, basePayload, snapshot, rect) {
- let screenshotPath;
- let blob;
- try {
- blob = await captureElementToBlob(el, snapshot, rect);
- } catch (err) {
- console.warn('[impeccable] capture failed, proceeding without screenshot:', err);
- }
- // Light up the shader overlay the moment capture is ready — no reason to
- // wait for the upload to complete before the user sees something alive.
- if (blob && state === 'GENERATING') {
- showShaderOverlay(el, blob, rect);
- }
- // Only upload + forward the screenshot when annotations (comments/strokes)
- // are present. Without annotations the image is pure visual anchoring —
- // it biases the model toward the current rendering and works against the
- // three-distinct-directions brief.
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- if (blob && hasAnnotations) {
- try {
- const uploadRes = await fetch(
- 'http://localhost:' + PORT + '/annotation?token=' + encodeURIComponent(TOKEN) +
- '&eventId=' + encodeURIComponent(basePayload.id),
- { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: blob },
- );
- if (uploadRes.ok) {
- const { path: p } = await uploadRes.json();
- screenshotPath = p;
- } else {
- console.warn('[impeccable] annotation upload failed:', uploadRes.status);
- }
- } catch (err) {
- console.warn('[impeccable] annotation upload failed:', err);
- }
- }
- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);
- }
-
- // ---------------------------------------------------------------------------
- // Shader overlay — renders the captured screenshot as a WebGL texture and
- // runs an editorial "ink-wash" fragment shader over it during generation.
- // A single rolling band sweeps top-to-bottom, desaturating + tinting magenta
- // and leaving a soft trail. Makes the wait feel like a letterpress scan
- // instead of a dead spinner.
- // ---------------------------------------------------------------------------
-
- const SHADER_VS = `attribute vec2 a_position;
-attribute vec2 a_uv;
-varying vec2 v_uv;
-void main() {
- v_uv = a_uv;
- gl_Position = vec4(a_position, 0.0, 1.0);
-}`;
-
- const SHADER_FS = `precision highp float;
-uniform sampler2D u_texture;
-uniform float u_time;
-uniform vec2 u_resolution;
-uniform vec3 u_accent;
-varying vec2 v_uv;
-
-// Asymmetric roller band. Product of two one-sided smoothsteps — peaks at
-// d=0 with a short sharp leading ramp and a longer soft trailing tail. Clean
-// outside the [-leadW, trailW] range (no rogue "trail=1 everywhere below"
-// failure that reversed-edge smoothstep would give).
-float bandAt(float d, float leadW, float trailW) {
- float above = smoothstep(-leadW, 0.0, d);
- float below = 1.0 - smoothstep(0.0, trailW, d);
- return above * below;
-}
-
-void main() {
- vec2 uv = v_uv;
- // Roller sweeps top-to-bottom with small overshoot so each cycle enters
- // and exits the element cleanly.
- float phase = fract(u_time / 3.4);
- float y = phase * 1.25 - 0.12;
- float band = bandAt(uv.y - y, 0.05, 0.32);
-
- // Halftone cell grid (fixed ~10 px pitch).
- float cellPx = 10.0;
- vec2 gridUv = uv * u_resolution / cellPx;
- vec2 cellId = floor(gridUv);
- vec2 cellUv = fract(gridUv) - 0.5;
- vec2 sampleCenter = (cellId + 0.5) * cellPx / u_resolution;
- vec3 cellImg = texture2D(u_texture, sampleCenter).rgb;
- float luma = dot(cellImg, vec3(0.299, 0.587, 0.114));
- // Darker cells → bigger magenta dots (classic risograph halftone curve).
- float radius = sqrt(clamp(1.0 - luma, 0.0, 1.0)) * 0.56;
- float dotMask = smoothstep(radius + 0.06, radius, length(cellUv));
- vec3 paper = vec3(0.975, 0.965, 0.955);
- vec3 dotLayer = mix(paper, u_accent, dotMask);
-
- // Blend the halftone layer in where the roller is passing; leave the
- // element pristine elsewhere.
- vec3 base = texture2D(u_texture, uv).rgb;
- gl_FragColor = vec4(mix(base, dotLayer, band), 1.0);
-}`;
-
- // Editorial Magenta converted to approximate sRGB 0-1 (matches oklch(60% 0.25 350))
- const SHADER_ACCENT = [0.82, 0.16, 0.47];
- let shaderState = null; // { canvas, gl, program, texture, rafId, startTime }
-
- function compileShader(gl, type, source) {
- const sh = gl.createShader(type);
- gl.shaderSource(sh, source);
- gl.compileShader(sh);
- if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
- const info = gl.getShaderInfoLog(sh);
- gl.deleteShader(sh);
- throw new Error('shader compile failed: ' + info);
- }
- return sh;
- }
-
- function positionShaderOverlay() {
- if (!shaderState || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- Object.assign(shaderState.canvas.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- }
-
- function hideShaderOverlay() {
- if (!shaderState) return;
- if (shaderState.rafId) cancelAnimationFrame(shaderState.rafId);
- if (shaderState.canvas) shaderState.canvas.remove();
- const lose = shaderState.gl?.getExtension?.('WEBGL_lose_context');
- try { lose?.loseContext(); } catch {}
- shaderState = null;
- }
-
- async function showShaderOverlay(el, blob, rect) {
- hideShaderOverlay();
- if (!blob || !el) return;
- const canvas = document.createElement('canvas');
- canvas.id = PREFIX + '-shader';
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
- canvas.width = Math.max(1, Math.floor(rect.width * dpr));
- canvas.height = Math.max(1, Math.floor(rect.height * dpr));
- Object.assign(canvas.style, {
- position: 'fixed',
- top: rect.top + 'px', left: rect.left + 'px',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none',
- zIndex: Z.bar - 1,
- });
- document.body.appendChild(canvas);
-
- const gl = canvas.getContext('webgl', { premultipliedAlpha: false, preserveDrawingBuffer: false })
- || canvas.getContext('experimental-webgl');
- if (!gl) {
- // WebGL unavailable — fall back to a plain <img> overlay so the user
- // still sees something meaningful during generation.
- canvas.remove();
- const img = document.createElement('img');
- img.src = URL.createObjectURL(blob);
- img.id = PREFIX + '-shader';
- // Copy positioning via cssText. Object.assign across CSSStyleDeclaration
- // throws in modern Chromium because the source's indexed properties
- // (style[0], [1], ...) are read-only and the engine forbids writing
- // them on the destination.
- img.style.cssText = canvas.style.cssText;
- img.style.outline = '2px dashed ' + C.brand;
- img.style.outlineOffset = '-2px';
- document.body.appendChild(img);
- shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
- return;
- }
-
- let program, texture;
- try {
- const vs = compileShader(gl, gl.VERTEX_SHADER, SHADER_VS);
- const fs = compileShader(gl, gl.FRAGMENT_SHADER, SHADER_FS);
- program = gl.createProgram();
- gl.attachShader(program, vs);
- gl.attachShader(program, fs);
- gl.linkProgram(program);
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- throw new Error('program link failed: ' + gl.getProgramInfoLog(program));
- }
- // Full-screen quad
- const buf = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
- -1, -1, 0, 1,
- 1, -1, 1, 1,
- -1, 1, 0, 0,
- -1, 1, 0, 0,
- 1, -1, 1, 1,
- 1, 1, 1, 0,
- ]), gl.STATIC_DRAW);
- const posLoc = gl.getAttribLocation(program, 'a_position');
- const uvLoc = gl.getAttribLocation(program, 'a_uv');
- gl.enableVertexAttribArray(posLoc);
- gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 16, 0);
- gl.enableVertexAttribArray(uvLoc);
- gl.vertexAttribPointer(uvLoc, 2, gl.FLOAT, false, 16, 8);
- } catch (err) {
- console.warn('[impeccable] shader setup failed:', err);
- canvas.remove();
- return;
- }
-
- // Upload the screenshot as a texture
- let bitmap;
- try {
- bitmap = await createImageBitmap(blob);
- } catch {
- // Safari fallback: go via a regular Image
- const imgUrl = URL.createObjectURL(blob);
- const img = new Image();
- img.src = imgUrl;
- await new Promise((r, rej) => { img.onload = r; img.onerror = rej; });
- bitmap = img;
- URL.revokeObjectURL(imgUrl);
- }
- texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
- if (bitmap.close) bitmap.close();
-
- const uTime = gl.getUniformLocation(program, 'u_time');
- const uRes = gl.getUniformLocation(program, 'u_resolution');
- const uAccent = gl.getUniformLocation(program, 'u_accent');
- const uTex = gl.getUniformLocation(program, 'u_texture');
- const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-
- shaderState = { canvas, gl, program, texture, rafId: 0, startTime: performance.now(), reduced };
- function frame() {
- if (!shaderState) return;
- const elapsed = (performance.now() - shaderState.startTime) / 1000;
- const t = shaderState.reduced ? 0.0 : elapsed;
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.useProgram(program);
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.uniform1i(uTex, 0);
- gl.uniform1f(uTime, t);
- gl.uniform2f(uRes, canvas.width, canvas.height);
- gl.uniform3f(uAccent, SHADER_ACCENT[0], SHADER_ACCENT[1], SHADER_ACCENT[2]);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- shaderState.rafId = requestAnimationFrame(frame);
- }
- frame();
- }
-
- function handleAccept() {
- if (!currentSessionId || arrivedVariants === 0) return;
- const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);
- if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;
- const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };
- if (Object.keys(paramsCurrentValues).length > 0) {
- acceptPayload.paramValues = { ...paramsCurrentValues };
- }
- // The accepted variant is already the only visible child of the wrapper
- // (all other variants are display:none). HMR from the source rewrite will
- // replace the wrapper imminently. Don't eagerly replaceChild here — React
- // reconciliation races with our mutation and throws NotFoundError in Next
- // 16 / Turbopack. Schedule a fallback that runs the manual swap only if
- // HMR hasn't cleaned up by then (keeps static-server flows working).
- const acceptedSessionId = currentSessionId;
- const acceptedVariant = visibleVariant;
-
- state = 'SAVING';
- updateBarContent('saving');
-
- sendEvent(acceptPayload, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- confirmAcceptAfterReceipt();
- })
- .catch(() => {
- state = 'CYCLING';
- updateBarContent('cycling');
- showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);
- });
-
- function confirmAcceptAfterReceipt() {
- state = 'CONFIRMED';
- updateBarContent('confirmed');
- scheduleAcceptCleanup();
- }
-
- function scheduleAcceptCleanup() {
- setTimeout(function() {
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }, 1800);
-
- // Static-server / no-HMR fallback: if the wrapper is still around 2s after
- // the cleanup above, swap it out manually. By now React has either moved
- // on or the app isn't React at all. Preserve the `data-impeccable-variant="N"`
- // div (with display:contents) so @scope rules anchored to the variant
- // attribute keep matching until reload replaces it with the carbonize block.
- setTimeout(function() {
- const wrapper = document.querySelector('[data-impeccable-variants="' + acceptedSessionId + '"]');
- if (!wrapper) return;
- const accepted = wrapper.querySelector('[data-impeccable-variant="' + acceptedVariant + '"]');
- if (accepted && accepted.firstElementChild) {
- const parent = wrapper.parentElement;
- if (!parent) return;
- accepted.style.display = 'contents';
- parent.replaceChild(accepted, wrapper);
- }
- }, 2000);
- }
- }
-
- function handleDiscard() {
- if (!currentSessionId) return;
- sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- cleanup();
- })
- .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));
- }
-
- // ---------------------------------------------------------------------------
- // Session persistence via live-browser-session.js
- // ---------------------------------------------------------------------------
- // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
-
- function saveSession() {
- if (!currentSessionId) return;
- // NOTE: scrollY is stored under a separate key (writeScrollY). Storing
- // it here would overwrite the Go-time value every time state changes.
- sessionState.saveSession({
- id: currentSessionId,
- state,
- action: selectedAction,
- count: selectedCount,
- expected: expectedVariants,
- arrived: arrivedVariants,
- visible: visibleVariant,
- });
- }
-
- function loadSession() {
- return sessionState.loadSession();
- }
-
- function clearSession() {
- sessionState.clearSession();
- }
-
- /** Mark session as handled (accepted/discarded). The agent will clean up
- * the source, but until it does the wrapper is still in the HTML. This
- * prevents resumeSession from picking it up again after reload. */
- function markSessionHandled() {
- if (!currentSessionId) return;
- sessionState.markHandled(currentSessionId);
- }
-
- function isSessionHandled(id) {
- return sessionState.isHandled(id);
- }
-
- function clearHandled() {
- sessionState.clearHandled();
- }
-
- function cleanup() {
- // Hide the wrapper immediately so variants disappear. DON'T structurally
- // mutate the DOM yet — HMR from the agent's source rewrite is on its way,
- // and a manual replaceChild under React causes NotFoundError when the
- // reconciler later tries to remove a wrapper we already removed.
- // Schedule a 2s fallback that does the manual swap only if HMR hasn't
- // replaced the wrapper by then (keeps static-server / no-HMR flows alive).
- const cleanupSessionId = currentSessionId;
- if (cleanupSessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (wrapper) wrapper.style.display = 'none';
- }
- setTimeout(function() {
- if (!cleanupSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (!wrapper) return;
- const orig = wrapper.querySelector('[data-impeccable-variant="original"]');
- if (orig) {
- const content = orig.firstElementChild;
- if (content) {
- wrapper.parentElement.replaceChild(content, wrapper);
- return;
- }
- }
- wrapper.remove();
- }, 2000);
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }
-
- // ---------------------------------------------------------------------------
- // Toast
- // ---------------------------------------------------------------------------
-
- function showToast(message, duration) {
- if (toastEl) toastEl.remove();
- // Stack the toast above the global bar (which sits at bottom:14px) so
- // the two never overlap. Read the bar's actual rect — its height varies
- // with hover-expanded labels — and fall back to a sensible default
- // when the bar isn't mounted yet.
- const barRect = globalBarEl?.getBoundingClientRect();
- const barTopFromBottom = barRect && barRect.height > 0
- ? Math.max(16, window.innerHeight - barRect.top + 12)
- : 16;
- toastEl = el('div', {
- position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
- transform: 'translateX(-50%) translateY(8px)',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px',
- padding: '8px 16px', borderRadius: '8px',
- zIndex: Z.toast, opacity: '0',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
- pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
- });
- toastEl.id = PREFIX + '-toast';
- toastEl.textContent = message;
- document.body.appendChild(toastEl);
- requestAnimationFrame(() => {
- toastEl.style.opacity = '1';
- toastEl.style.transform = 'translateX(-50%) translateY(0)';
- });
- setTimeout(() => {
- if (toastEl) {
- toastEl.style.opacity = '0';
- toastEl.style.transform = 'translateX(-50%) translateY(8px)';
- setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
- }
- }, duration);
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- // Resume an active variant session after HMR/page reload.
- // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
- // variants before HMR fired. Pick up where we left off.
- function resumeSession() {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) { clearSession(); clearHandled(); return false; }
-
- const sessionId = wrapper.dataset.impeccableVariants;
-
- // Don't resume if this session was already accepted/discarded
- if (isSessionHandled(sessionId)) return false;
-
- currentSessionId = sessionId;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
-
- // Restore state from localStorage if available
- const saved = loadSession();
- if (saved && saved.id === sessionId) {
- visibleVariant = (saved.visible > 0 && saved.visible <= arrivedVariants) ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
- if (saved.action) selectedAction = saved.action;
- if (saved.count) selectedCount = saved.count;
- } else {
- visibleVariant = arrivedVariants > 0 ? 1 : 0;
- }
-
- // Find the visible variant's content element for highlight positioning.
- // Try the visible variant first, fall back to the original's content.
- const visEl = visibleVariant > 0 ? pickVariantContent(wrapper, visibleVariant) : null;
- const origEl = pickVariantContent(wrapper, 'original');
- selectedElement = visEl || origEl || wrapper.parentElement;
-
- // Set display state BEFORE starting observer (avoid triggering it)
- if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
-
- state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
- showBar(state === 'CYCLING' ? 'cycling' : 'generating');
- startScrollTracking();
- // Build the params panel for the restored visible variant. Previously
- // this was missed on page-reload resume: showVariantInDOM above fires
- // refreshParamsPanel, but state was still IDLE at that moment so it
- // hid. Now that state is CYCLING, re-fire.
- if (state === 'CYCLING') refreshParamsPanel();
- saveSession();
- queueCheckpoint('browser_resumed');
-
- // Start observing for more variants AFTER initial setup
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
-
- // Hold the target at its saved viewport top through any subsequent
- // HMR patches, variant inserts, or cycle swaps.
- startScrollLock(currentSessionId, readScrollY());
-
- // If we reloaded mid-generation (Bun's HTML HMR destroys the shader
- // canvas), re-capture the original's content and restart the shader so
- // the wait doesn't go dead.
- if (state === 'GENERATING' && origEl) {
- (async () => {
- try {
- const rect = origEl.getBoundingClientRect();
- if (rect.width === 0 || rect.height === 0) return;
- const blob = await captureElementToBlob(origEl, null, rect);
- if (blob && state === 'GENERATING') {
- showShaderOverlay(origEl, blob, rect);
- }
- } catch (err) {
- console.warn('[impeccable] shader resume failed:', err);
- }
- })();
- }
- return true;
- }
-
- // ---------------------------------------------------------------------------
- // Global bar (always visible at bottom)
- // ---------------------------------------------------------------------------
-
- let globalBarEl = null;
- let detectActive = false;
- let pickActive = true;
- let detectCount = 0;
- let detectScriptLoaded = false;
-
- // Theme-aware color palette for the global bar. We detect the page's
- // ambient background and invert — dark bar on light pages, light bar on
- // dark pages. This keeps the bar from fighting with the host design.
- function detectPageTheme() {
- try {
- // Dev override: set localStorage 'impeccable-dev-theme' to 'light' or
- // 'dark' to preview the opposite palette without actually changing the
- // page bg. Used for screenshots and theme QA.
- const override = localStorage.getItem('impeccable-dev-theme');
- if (override === 'light' || override === 'dark') return override;
-
- // Walk body → html, taking the first opaque background. The browser's
- // default body / html background is `rgba(0, 0, 0, 0)`, which a naive
- // regex would read as black and mislabel a perfectly white page as
- // dark. Honoring alpha avoids that — and falling through to <html>
- // catches the common pattern of a bg only on <html> (or only on body).
- function readOpaque(el) {
- if (!el) return null;
- const bg = getComputedStyle(el).backgroundColor;
- const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
- if (!m) return null;
- const alpha = m[4] == null ? 1 : parseFloat(m[4]);
- if (alpha < 0.5) return null; // transparent / nearly transparent → skip
- return [+m[1], +m[2], +m[3]];
- }
-
- const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
- // Both transparent → fall back to the browser's effective canvas color.
- // White is the universal default; only one in a thousand sites swaps it
- // via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
- // us catch that case.
- if (!rgb) {
- return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
- }
- const [r, g, b] = rgb;
- // Perceptual luminance (Rec. 709)
- const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
- return L > 0.55 ? 'light' : 'dark';
- } catch { return 'light'; }
- }
-
- function barPaletteForTheme(theme) {
- if (theme === 'dark') {
- // Light bar on dark page
- return {
- surface: 'oklch(98% 0 0 / 0.92)',
- surfaceDeep: 'oklch(92% 0.005 60 / 0.96)', // slightly deeper, faint warm
- hairline: 'oklch(70% 0 0 / 0.35)',
- text: 'oklch(15% 0 0)',
- textDim: 'oklch(45% 0 0)',
- accent: 'oklch(60% 0.25 350)',
- accentSoft: 'oklch(60% 0.25 350 / 0.18)',
- mark: 'oklch(98% 0 0)', // logo mark fill
- markText: 'oklch(15% 0 0)', // logo "/" color
- exitHover: 'oklch(85% 0 0 / 0.5)',
- };
- }
- // Dark bar on light page. Bar is a warm charcoal, logo slab is much
- // deeper so the rounded-right shape reads as a clear sculpted mark.
- return {
- surface: 'oklch(26% 0 0 / 0.94)',
- surfaceDeep: 'oklch(18% 0 0 / 0.96)', // darker sand for Tune popover
- hairline: 'oklch(42% 0 0 / 0.5)',
- text: 'oklch(96% 0 0)',
- textDim: 'oklch(72% 0 0)',
- accent: 'oklch(72% 0.22 350)',
- accentSoft: 'oklch(72% 0.22 350 / 0.22)',
- mark: 'oklch(8% 0 0)',
- markText: 'oklch(96% 0 0)',
- exitHover: 'oklch(36% 0 0 / 0.6)',
- };
- }
-
- // Impeccable logo mark — matches the site-header SVG (rounded square + "/").
- function brandMarkSvg(fill, ink, size = 18) {
- return `<svg width="${size}" height="${size}" viewBox="0 0 32 32" aria-hidden="true">
- <rect width="32" height="32" rx="7" fill="${fill}"/>
- <text x="16" y="24" font-family="system-ui, -apple-system, sans-serif" font-size="22" font-weight="500" fill="${ink}" text-anchor="middle">/</text>
- </svg>`;
- }
-
- function initGlobalBar() {
- const theme = detectPageTheme();
- const P = barPaletteForTheme(theme);
-
- // Custom focus-visible for bar buttons. Browser default is a heavy
- // blue ring that looks jarring on the dark capsule. Replace with a
- // soft accent-tinted inner ring that respects the bar's palette.
- if (!document.getElementById(PREFIX + '-bar-focus-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-bar-focus-style';
- s.textContent =
- '#' + PREFIX + '-global-bar button:focus { outline: none; }' +
- '#' + PREFIX + '-global-bar button:focus-visible {' +
- ' outline: none;' +
- ' box-shadow: 0 0 0 2px ' + P.accentSoft + ', 0 0 0 3px ' + P.accent + ';' +
- '}';
- document.head.appendChild(s);
- }
-
- globalBarEl = el('div', {
- position: 'fixed', bottom: '14px', left: '50%',
- transform: 'translateX(-50%) translateY(20px)',
- zIndex: Z.bar + 5,
- display: 'flex', alignItems: 'stretch',
- gap: '2px',
- background: P.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 4px 20px oklch(0% 0 0 / 0.12), 0 1px 3px oklch(0% 0 0 / 0.08)',
- fontFamily: FONT, fontSize: '12px', lineHeight: '1',
- opacity: '0',
- overflow: 'hidden', // clip the full-bleed brand mark to the bar radius
- transition: 'opacity 0.3s ' + EASE + ', transform 0.3s ' + EASE,
- });
- globalBarEl.id = PREFIX + '-global-bar';
- globalBarEl.dataset.theme = theme;
-
- // Brand mark — fills bar height on the left. Left side inherits the bar's
- // rounded corner via overflow:hidden; right side is a clean hard edge since
- // the near-black/charcoal contrast does the shape-defining work.
- const brand = el('span', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- alignSelf: 'stretch',
- padding: '0 12px 0 14px',
- background: P.mark,
- color: P.markText,
- fontFamily: 'system-ui, -apple-system, sans-serif',
- fontWeight: '500',
- fontSize: '18px', lineHeight: '1',
- });
- brand.textContent = '/';
- brand.title = 'Impeccable';
- globalBarEl.appendChild(brand);
-
- // Inner wrapper: holds the toggles with normal bar padding.
- const inner = el('div', {
- display: 'flex', alignItems: 'center',
- padding: '4px 5px', gap: '2px',
- });
- inner.id = PREFIX + '-global-bar-inner';
- globalBarEl.appendChild(inner);
-
- // --- button factory: icon-only at rest, label slides in on hover/active ---
- function makeIconBtn({ id, svg, label, ariaLabel, labelFont, onClick }) {
- const b = el('button', {
- position: 'relative',
- display: 'inline-flex', alignItems: 'center',
- padding: '6px 8px', borderRadius: '7px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '11.5px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.15s ease, color 0.15s ease',
- whiteSpace: 'nowrap', overflow: 'hidden',
- });
- b.id = id;
- b.title = ariaLabel || label || '';
- b.setAttribute('aria-label', ariaLabel || label || '');
- b.innerHTML = svg + (label
- ? `<span class="icon-btn-label" style="display:inline-block;max-width:0;opacity:0;margin-left:0;overflow:hidden;font-family:${labelFont || FONT};transition:max-width 0.25s ${EASE}, opacity 0.2s ease, margin-left 0.25s ${EASE};">${label}</span>`
- : '');
- const labelEl = b.querySelector('.icon-btn-label');
- const expand = () => {
- if (!labelEl) return;
- labelEl.style.maxWidth = '120px'; labelEl.style.opacity = '1'; labelEl.style.marginLeft = '6px';
- };
- const collapse = () => {
- if (!labelEl || b.dataset.active === 'true') return;
- labelEl.style.maxWidth = '0'; labelEl.style.opacity = '0'; labelEl.style.marginLeft = '0';
- };
- // Per-button hover only changes color (no layout). The label expand/
- // collapse is driven by the bar-level mouseenter/mouseleave so moving
- // the mouse between adjacent buttons doesn't trigger per-button width
- // thrashing — the whole bar grows once and shrinks once.
- b.addEventListener('mouseenter', () => { if (b.dataset.active !== 'true') b.style.color = P.text; });
- b.addEventListener('mouseleave', () => { if (b.dataset.active !== 'true') b.style.color = P.textDim; });
- b.addEventListener('click', onClick);
- b._expandLabel = expand;
- b._collapseLabel = collapse;
- return b;
- }
-
- // Pick toggle — starts active (primary intent when entering live mode).
- const pickBtn = makeIconBtn({
- id: PREFIX + '-pick-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',
- label: 'Pick',
- ariaLabel: 'Pick element',
- onClick: () => togglePick(),
- });
- pickBtn.style.background = P.accentSoft;
- pickBtn.style.color = P.accent;
- pickBtn.dataset.active = 'true';
- pickBtn._expandLabel();
- inner.appendChild(pickBtn);
-
- // Detect toggle
- const detectBtn = makeIconBtn({
- id: PREFIX + '-detect-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',
- label: 'Detect',
- ariaLabel: 'Detect anti-patterns',
- onClick: () => toggleDetect(),
- });
- const detectBadge = el('span', {
- fontSize: '10px', fontWeight: '600',
- padding: '0px 5px', borderRadius: '7px', lineHeight: '16px',
- background: P.accent, color: P.surface.includes('18%') ? 'oklch(18% 0 0)' : 'oklch(98% 0 0)',
- display: 'none', fontFamily: MONO, marginLeft: '4px',
- });
- detectBadge.id = PREFIX + '-detect-badge';
- detectBtn.appendChild(detectBadge);
- inner.appendChild(detectBtn);
-
- // DESIGN.md panel toggle — quartet of color squares as the mark.
- const designBtn = makeIconBtn({
- id: PREFIX + '-design-toggle',
- svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px ${P.hairline};flex-shrink:0">
- <span style="background:oklch(60% 0.25 350)"></span>
- <span style="background:oklch(60% 0.15 45)"></span>
- <span style="background:oklch(55% 0.12 250)"></span>
- <span style="background:oklch(30% 0 0)"></span>
- </span>`,
- label: 'DESIGN.md',
- ariaLabel: 'Toggle DESIGN.md panel',
- labelFont: MONO,
- onClick: () => toggleDesignPanel(),
- });
- inner.appendChild(designBtn);
-
- // Thin divider before the exit button
- const divider = el('span', {
- width: '1px', height: '18px',
- background: P.hairline,
- margin: '0 4px 0 2px',
- });
- inner.appendChild(divider);
-
- // Exit × on the right — intentionally subtle (textDim at rest, text on
- // hover) so it sits behind the active toggles in visual hierarchy.
- //
- // Explicit padding + box-sizing here is load-bearing: a host page like
- // `button { padding: 0.5rem 1rem; }` (very common in resets) would
- // otherwise inflate this 24x24 button into 56x40 and push the SVG out
- // of the visible bar — the X stays invisible even though the styles in
- // DevTools look fine. Every other chrome button sets padding inline;
- // this one needed it too.
- const exitBtn = el('button', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- padding: '0', boxSizing: 'border-box',
- width: '24px', height: '24px', borderRadius: '6px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
- cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
- });
- exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
- exitBtn.title = 'Exit live mode';
- exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
- exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
- exitBtn.addEventListener('click', () => { sendEvent({ type: 'exit' }); teardown(); });
- inner.appendChild(exitBtn);
-
- // Bar-level hover: expand every toggle's label at once; collapse on leave.
- // Buttons with dataset.active="true" ignore collapse (their label stays).
- const toggles = [pickBtn, detectBtn, designBtn];
- globalBarEl.addEventListener('mouseenter', () => {
- toggles.forEach((t) => t._expandLabel && t._expandLabel());
- });
- globalBarEl.addEventListener('mouseleave', () => {
- toggles.forEach((t) => t._collapseLabel && t._collapseLabel());
- });
-
- document.body.appendChild(globalBarEl);
- defangOutsideHandlers(globalBarEl);
-
- requestAnimationFrame(() => {
- globalBarEl.style.opacity = '1';
- globalBarEl.style.transform = 'translateX(-50%) translateY(0)';
- });
-
- // Listen for detection results AND ready signal
- window.addEventListener('message', onDetectMessage);
- }
-
- function updateGlobalBarState() {
- const detectToggle = document.getElementById(PREFIX + '-detect-toggle');
- const detectBadge = document.getElementById(PREFIX + '-detect-badge');
- const pickToggle = document.getElementById(PREFIX + '-pick-toggle');
- const designToggle = document.getElementById(PREFIX + '-design-toggle');
- const theme = globalBarEl?.dataset.theme || 'light';
- const P = barPaletteForTheme(theme);
-
- // Sync one toggle's active state, colors, and slide-label visibility.
- function sync(btn, active) {
- if (!btn) return;
- btn.style.background = active ? P.accentSoft : 'transparent';
- btn.style.color = active ? P.accent : P.textDim;
- btn.dataset.active = active ? 'true' : 'false';
- if (active && btn._expandLabel) btn._expandLabel();
- else if (!active && btn._collapseLabel) btn._collapseLabel();
- }
- sync(pickToggle, pickActive);
- sync(detectToggle, detectActive);
- sync(designToggle, designState.open);
-
- // If the bar is currently under the cursor, keep all labels expanded —
- // otherwise clicking a toggle that deactivates (e.g. closing DESIGN.md)
- // would collapse its label while the user's mouse is still on the bar.
- if (globalBarEl && globalBarEl.matches(':hover')) {
- [pickToggle, detectToggle, designToggle].forEach((t) => t?._expandLabel?.());
- }
-
- if (detectBadge) {
- detectBadge.style.display = (detectActive && detectCount > 0) ? 'inline' : 'none';
- detectBadge.textContent = detectCount;
- }
-
- // When pick is active, make detect overlays click-through so the picker works
- document.querySelectorAll('.impeccable-overlay').forEach(o => {
- o.style.pointerEvents = pickActive ? 'none' : '';
- });
- }
-
- let detectReady = false; // true once detect script posts 'impeccable-ready'
- let detectPendingScan = false; // scan requested before script was ready
-
- function toggleDetect() {
- detectActive = !detectActive;
- updateGlobalBarState();
-
- if (detectActive) {
- if (!detectScriptLoaded) {
- detectPendingScan = true;
- loadDetectScript();
- } else if (detectReady) {
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- } else {
- detectPendingScan = true;
- }
- } else {
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- detectCount = 0;
- updateGlobalBarState();
- }
- }
-
- function togglePick() {
- pickActive = !pickActive;
- updateGlobalBarState();
-
- if (!pickActive) {
- // Disabling pick clears any in-flight selection and UI: highlight,
- // contextual bar, selectedElement. Otherwise a stale selection sits
- // on screen with no obvious way to dismiss.
- hideHighlight();
- hideBar();
- hideActionPicker();
- selectedElement = null;
- if (state === 'PICKING' || state === 'CONFIGURING') state = 'IDLE';
- } else {
- if (state === 'IDLE') state = 'PICKING';
- }
- }
-
- function loadDetectScript() {
- if (detectScriptLoaded) return;
- detectScriptLoaded = true;
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/detect.js';
- s.dataset.impeccableExtension = 'true';
- document.head.appendChild(s);
- }
-
- function onDetectMessage(e) {
- if (!e.data || typeof e.data.source !== 'string') return;
- // Detection script is loaded and ready
- if (e.data.source === 'impeccable-ready') {
- detectReady = true;
- if (detectPendingScan && detectActive) {
- detectPendingScan = false;
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- }
- }
- // Scan results arrived
- if (e.data.source === 'impeccable-results') {
- detectCount = e.data.count || 0;
- updateGlobalBarState();
- }
- }
-
- /** Full teardown: remove all UI, disconnect SSE, clean up. */
- function teardown() {
- cleanup();
- hideBar();
- if (globalBarEl) {
- globalBarEl.style.transform = 'translateY(100%)';
- setTimeout(() => { if (globalBarEl) globalBarEl.remove(); globalBarEl = null; }, 300);
- }
- if (highlightEl) { highlightEl.remove(); highlightEl = null; }
- if (tooltipEl) { tooltipEl.remove(); tooltipEl = null; }
- if (barEl) { barEl.remove(); barEl = null; }
- if (pickerEl) { pickerEl.remove(); pickerEl = null; }
- if (paramsPanelEl) { paramsPanelEl.remove(); paramsPanelEl = null; paramsPanelInner = null; paramsPanelBody = null; }
- if (evtSource) { evtSource.close(); evtSource = null; }
- document.removeEventListener('mousemove', handleMouseMove, true);
- document.removeEventListener('click', handleClick, true);
- document.removeEventListener('keydown', handleKeyDown, true);
- window.removeEventListener('message', onDetectMessage);
- // Remove detection overlays
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- state = 'IDLE';
- window.__IMPECCABLE_LIVE_INIT__ = false;
- console.log('[impeccable] Live mode exited.');
- }
-
- // ---------------------------------------------------------------------------
- // Design System Panel — visualizes the project's .impeccable/design.json sidecar
- // ---------------------------------------------------------------------------
-
- const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';
- const DESIGN_PANEL_WIDTH = 440;
-
- let designHost = null;
- let designShadow = null;
- let designState = {
- open: false,
- tab: 'visual', // 'visual' | 'raw'
- parsed: null, // parseDesignMd output (frontmatter + body sections)
- sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)
- hasMd: false,
- hasSidecar: false,
- present: null, // true/false once fetch resolves
- raw: null, // raw DESIGN.md for the raw tab
- mdNewerThanJson: false, // stale-hint flag
- loading: false,
- error: null,
- collapsed: { // narrative-section accordion state
- rules: true, dosdonts: true, overview: true,
- },
- };
-
- function loadDesignPrefs() {
- // `open` is intentionally NOT persisted — the panel always starts closed
- // so live mode doesn't auto-slide a big panel over the page on startup.
- try {
- const raw = localStorage.getItem(DESIGN_PREFS_KEY);
- if (!raw) return;
- const prefs = JSON.parse(raw);
- if (prefs.tab === 'visual' || prefs.tab === 'raw') designState.tab = prefs.tab;
- if (prefs.collapsed && typeof prefs.collapsed === 'object') {
- Object.assign(designState.collapsed, prefs.collapsed);
- }
- } catch { /* ignore */ }
- }
-
- function saveDesignPrefs() {
- try {
- localStorage.setItem(DESIGN_PREFS_KEY, JSON.stringify({
- tab: designState.tab,
- collapsed: designState.collapsed,
- }));
- } catch { /* ignore */ }
- }
-
- function initDesignPanel() {
- designHost = document.createElement('div');
- designHost.id = PREFIX + '-design-host';
- Object.assign(designHost.style, {
- position: 'fixed', top: '0', left: '0',
- width: '0', height: '0',
- zIndex: String(Z.bar + 10),
- pointerEvents: 'none',
- });
- designShadow = designHost.attachShadow({ mode: 'open' });
-
- const style = document.createElement('style');
- // Theme-match the bar: dark chrome on light pages, light chrome on dark pages.
- const theme = detectPageTheme();
- style.textContent = designPanelCss(barPaletteForTheme(theme));
- designShadow.appendChild(style);
-
- const root = document.createElement('div');
- root.className = 'root';
- designShadow.appendChild(root);
-
- document.body.appendChild(designHost);
- // The host is pointer-events: none; the panel inside the shadow DOM
- // manages its own auto/none. Events bubble through the shadow boundary,
- // so attaching here silences host-page outside-interaction handlers
- // without touching the host's click-through behavior.
- defangOutsideHandlers(designHost, { setPointerEvents: false });
-
- loadDesignPrefs();
- renderDesignChrome();
- if (designState.open) {
- fetchDesignSystem();
- }
- }
-
- // Neutral panel palette — deliberately NOT Impeccable-branded. The panel is
- // a viewer of the project's design system, not an Impeccable surface.
- const DP = {
- canvas: 'oklch(94% 0 0)', // panel background
- tile: 'oklch(98.5% 0 0)', // card-on-canvas
- tileAlt: 'oklch(96% 0 0)', // subtler tile for inner surfaces
- ink: 'oklch(15% 0 0)',
- ink2: 'oklch(35% 0 0)',
- meta: 'oklch(55% 0 0)',
- hairline: 'oklch(88% 0 0)',
- hairlineSoft: 'oklch(92% 0 0)',
- amber: 'oklch(70% 0.13 65)', // stale-hint accent
- amberBg: 'oklch(95% 0.05 80)',
- };
-
- function designPanelCss(BP) {
- // BP = bar palette (theme-aware, matches the global bar).
- // DP = internal content palette (neutral, so tiles render colors true).
- return `
- :host, .root { all: initial; }
- .root {
- font-family: ${FONT};
- color: ${DP.ink};
- pointer-events: none;
- }
- .root * { box-sizing: border-box; }
- button { font: inherit; color: inherit; }
-
- /* --- Panel shell: chrome matches the bar; body canvas stays neutral --- */
- .panel {
- position: fixed; top: 12px; bottom: 72px; right: 12px;
- width: ${DESIGN_PANEL_WIDTH}px; max-width: calc(100vw - 24px);
- background: ${BP.surface};
- border: 1px solid ${BP.hairline};
- border-radius: 14px;
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- box-shadow: 0 20px 60px oklch(0% 0 0 / 0.18), 0 4px 12px oklch(0% 0 0 / 0.08);
- display: flex; flex-direction: column;
- transform: translateX(calc(100% + 24px));
- opacity: 0;
- transition: transform 0.35s ${EASE}, opacity 0.25s ${EASE};
- pointer-events: none;
- overflow: hidden;
- }
- .panel[data-open="true"] { transform: translateX(0); opacity: 1; pointer-events: auto; }
-
- .panel-header {
- display: flex; align-items: center; gap: 10px;
- padding: 10px 10px 10px 14px;
- background: transparent;
- border-bottom: 1px solid ${BP.hairline};
- }
- .panel-title {
- flex: 1; min-width: 0;
- font-family: ${MONO};
- font-size: 11.5px; font-weight: 600;
- letter-spacing: 0.02em;
- color: ${BP.text};
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
- }
- .panel-close {
- border: none; background: transparent; color: ${BP.textDim};
- width: 26px; height: 26px; border-radius: 7px;
- display: inline-flex; align-items: center; justify-content: center;
- cursor: pointer; transition: background 0.15s ease, color 0.15s ease;
- }
- .panel-close:hover { background: ${BP.hairline}; color: ${BP.text}; }
-
- .tabs {
- display: inline-flex; padding: 2px;
- background: ${BP.hairline};
- border-radius: 7px;
- gap: 2px;
- }
- .tab {
- border: none; background: transparent;
- padding: 4px 10px; border-radius: 5px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 600; letter-spacing: 0.08em;
- text-transform: uppercase;
- color: ${BP.textDim}; cursor: pointer;
- transition: background 0.15s ease, color 0.15s ease;
- }
- .tab[data-active="true"] { background: ${BP.surface}; color: ${BP.text}; }
-
- .panel-body {
- flex: 1; overflow-y: auto;
- padding: 12px 12px 20px;
- background: ${DP.canvas};
- scrollbar-width: thin;
- scrollbar-color: ${DP.hairline} transparent;
- }
- .panel-body::-webkit-scrollbar { width: 8px; }
- .panel-body::-webkit-scrollbar-thumb { background: ${DP.hairline}; border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
-
- /* --- States --- */
- .empty, .loading, .error {
- margin: 16px 4px;
- padding: 28px 20px; text-align: center;
- background: ${DP.tile}; border-radius: 14px;
- color: ${DP.ink2}; font-size: 13px; line-height: 1.55;
- }
- .empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
- .empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
- .error { color: oklch(45% 0.15 25); }
-
- /* --- Stale hint --- */
- .stale {
- display: flex; align-items: center; gap: 8px;
- margin: 8px 4px 12px;
- padding: 8px 12px;
- background: ${DP.amberBg};
- border-radius: 10px;
- font-size: 11.5px; color: ${DP.ink2};
- }
- .stale-dot { width: 8px; height: 8px; border-radius: 50%; background: ${DP.amber}; flex-shrink: 0; }
- .stale-text { flex: 1; min-width: 0; }
- .stale-text strong { color: ${DP.ink}; font-weight: 600; }
-
- /* --- Parsed-md fallback banner --- */
- .parsed-md-cta {
- margin: 8px 4px 14px;
- padding: 14px 16px;
- background: ${DP.tile};
- border: 1px dashed ${DP.hairline};
- border-radius: 12px;
- font-size: 12px; color: ${DP.ink2}; line-height: 1.55;
- }
- .parsed-md-cta strong { color: ${DP.ink}; display: block; margin-bottom: 4px; font-size: 13px; font-weight: 600; }
- .parsed-md-cta code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; font-size: 11.5px; color: ${DP.ink}; }
-
- /* --- Tile primitives --- */
- .tile {
- position: relative;
- background: ${DP.tile};
- border-radius: 16px;
- padding: 16px;
- margin: 0 4px 10px;
- }
- .tile-row { margin: 0 4px 10px; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
- .tile-row .tile { margin: 0; }
- .tile-meta {
- display: flex; align-items: baseline; justify-content: space-between;
- gap: 10px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase;
- color: ${DP.meta};
- }
- .tile-meta .name { color: ${DP.ink}; font-weight: 600; letter-spacing: 0.05em; text-transform: none; font-family: ${FONT}; font-size: 12.5px; }
-
- /* --- Color tile --- */
- .c-tile { cursor: pointer; transition: transform 0.2s ${EASE}; }
- .c-tile:hover { transform: translateY(-1px); }
- .c-hero {
- height: 72px; border-radius: 10px; margin-top: 10px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.05);
- }
- .c-ramp {
- display: flex; gap: 0; height: 14px; border-radius: 4px; overflow: hidden;
- margin-top: 8px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.04);
- }
- .c-ramp > span { flex: 1; }
- .c-desc { margin-top: 8px; font-size: 11.5px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Type tile --- */
- .t-tile { }
- .t-specimen {
- margin: 4px 0 6px;
- color: ${DP.ink};
- line-height: 0.9;
- }
- .t-family { margin-top: 4px; font-size: 12px; font-weight: 600; color: ${DP.ink}; }
- .t-purpose { margin-top: 4px; font-size: 11px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Shadow tile --- */
- .s-tile { }
- .s-surface {
- height: 60px; margin: 8px 2px 10px;
- background: ${DP.tile};
- border-radius: 10px;
- }
- .s-value { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; word-break: break-all; line-height: 1.4; }
- .s-purpose { margin-top: 4px; font-size: 11px; color: ${DP.ink2}; line-height: 1.45; }
-
- /* --- Radii strip --- */
- .r-strip { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
- .r-item { display: flex; flex-direction: column; align-items: center; gap: 4px; flex: 1; min-width: 60px; }
- .r-sample { width: 44px; height: 44px; background: ${DP.canvas}; box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.08); }
- .r-label { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; text-transform: uppercase; }
- .r-val { font-family: ${MONO}; font-size: 10px; color: ${DP.ink}; }
-
- /* --- Component tile (hosts live primitives) --- */
- .cmp-tile { }
- .cmp-stage {
- margin: 12px -4px 0;
- padding: 18px 16px 10px;
- border-top: 1px solid ${DP.hairlineSoft};
- display: flex; flex-direction: column; align-items: center; justify-content: center;
- gap: 14px;
- min-height: 68px;
- }
- .cmp-stage + .cmp-stage { border-top: 1px dashed ${DP.hairlineSoft}; }
- .cmp-sublabel { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.06em; }
- .cmp-kind { font-family: ${MONO}; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; }
-
- /* --- Collapsible --- */
- .coll {
- margin: 0 4px 8px;
- background: ${DP.tile};
- border-radius: 12px;
- overflow: hidden;
- }
- .coll-head {
- display: flex; align-items: center; gap: 10px;
- width: 100%;
- padding: 12px 14px;
- background: transparent; border: none;
- cursor: pointer; text-align: left;
- font-family: ${FONT}; font-size: 12.5px; font-weight: 600; color: ${DP.ink};
- transition: background 0.12s ease;
- }
- .coll-head:hover { background: ${DP.tileAlt}; }
- .coll-chev {
- width: 12px; height: 12px; flex-shrink: 0;
- color: ${DP.meta};
- transition: transform 0.2s ${EASE};
- }
- .coll[data-open="true"] .coll-chev { transform: rotate(90deg); }
- .coll-count { margin-left: auto; font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; }
- .coll-body { padding: 0 14px 14px; display: none; }
- .coll[data-open="true"] .coll-body { display: block; }
-
- .rule-card {
- padding: 10px 0;
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .rule-card:first-child { border-top: none; padding-top: 2px; }
- .rule-card .name { font-size: 11.5px; font-weight: 700; color: ${DP.ink}; margin-bottom: 3px; }
- .rule-card .name .section { font-family: ${MONO}; font-size: 9px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; margin-left: 8px; }
- .rule-card .body { font-size: 11.5px; color: ${DP.ink2}; line-height: 1.5; }
-
- .coll .dos { display: grid; gap: 0; margin-top: 2px; }
- .coll .do, .coll .dont {
- position: relative;
- padding: 8px 0 8px 22px;
- font-size: 11.5px; line-height: 1.5; color: ${DP.ink2};
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .coll .do:first-child, .coll .dont:first-child,
- .coll .do:first-of-type { border-top: none; }
- .coll .do + .dont { border-top: 1px solid ${DP.hairlineSoft}; }
- .coll .do::before, .coll .dont::before {
- content: ''; position: absolute; left: 4px; top: 13px;
- width: 8px; height: 8px; border-radius: 50%;
- }
- .coll .do::before { background: oklch(62% 0.16 145); }
- .coll .dont::before { background: oklch(58% 0.22 25); }
-
- .coll .overview-body {
- font-size: 12px; line-height: 1.55; color: ${DP.ink2};
- }
- .coll .overview-body .north-star {
- display: block; font-family: ${FONT}; font-style: italic;
- font-size: 15px; line-height: 1.3; color: ${DP.ink};
- margin-bottom: 8px;
- }
- .coll .overview-body p { margin: 0 0 8px; }
- .coll .overview-body ul { margin: 6px 0 0; padding-left: 16px; font-size: 11.5px; }
- .coll .overview-body li { margin-bottom: 3px; }
-
- /* --- raw tab markdown (unchanged layout, neutralized palette) --- */
- .md { padding: 4px 10px 20px; font-size: 13px; line-height: 1.6; color: ${DP.ink}; }
- .md h1, .md h2, .md h3, .md h4 { margin: 20px 0 8px; color: ${DP.ink}; font-weight: 600; }
- .md h1 { font-size: 18px; }
- .md h2 { font-size: 15px; padding-bottom: 4px; border-bottom: 1px solid ${DP.hairlineSoft}; }
- .md h3 { font-size: 13px; }
- .md h4 { font-size: 12px; color: ${DP.meta}; }
- .md p { margin: 0 0 10px; }
- .md ul, .md ol { margin: 0 0 10px; padding-left: 20px; }
- .md li { margin-bottom: 4px; }
- .md code { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; }
- .md pre { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 10px 12px; border-radius: 8px; overflow-x: auto; margin: 0 0 10px; }
- .md pre code { background: none; padding: 0; }
- .md strong { font-weight: 700; }
- .md em { font-style: italic; }
- .md a { color: ${DP.ink}; text-decoration: underline; }
- .md hr { border: none; border-top: 1px solid ${DP.hairlineSoft}; margin: 16px 0; }
- `;
- }
-
- function renderDesignChrome() {
- const root = designShadow.querySelector('.root');
- root.innerHTML = '';
-
- // (Panel toggle lives in the global bar — no floating FAB.)
- // Panel
- const panel = document.createElement('aside');
- panel.className = 'panel';
- panel.setAttribute('data-open', designState.open ? 'true' : 'false');
- panel.appendChild(buildDesignHeader());
- const body = document.createElement('div');
- body.className = 'panel-body';
- body.id = 'panel-body';
- panel.appendChild(body);
- root.appendChild(panel);
-
- renderDesignBody();
- }
-
- function buildDesignHeader() {
- const header = document.createElement('div');
- header.className = 'panel-header';
-
- const title = document.createElement('div');
- title.className = 'panel-title';
- title.textContent = 'DESIGN.md';
- header.appendChild(title);
-
- const tabs = document.createElement('div');
- tabs.className = 'tabs';
- for (const t of [['visual', 'Visual'], ['raw', 'Raw']]) {
- const btn = document.createElement('button');
- btn.className = 'tab';
- btn.textContent = t[1];
- btn.setAttribute('data-active', designState.tab === t[0] ? 'true' : 'false');
- btn.addEventListener('click', () => {
- if (designState.tab === t[0]) return;
- designState.tab = t[0];
- saveDesignPrefs();
- renderDesignChrome();
- if (t[0] === 'raw' && designState.raw === null && !designState.loading) {
- fetchDesignSystem(); // raw is part of the same fetch pair
- }
- });
- tabs.appendChild(btn);
- }
- header.appendChild(tabs);
-
- const close = document.createElement('button');
- close.className = 'panel-close';
- close.innerHTML = '✕';
- close.setAttribute('aria-label', 'Close panel');
- close.addEventListener('click', toggleDesignPanel);
- header.appendChild(close);
-
- return header;
- }
-
- function toggleDesignPanel() {
- designState.open = !designState.open;
- renderDesignChrome();
- updateGlobalBarState();
- if (designState.open && designState.present === null && !designState.loading) {
- fetchDesignSystem();
- }
- }
-
- async function fetchDesignSystem() {
- designState.loading = true;
- designState.error = null;
- renderDesignBody();
- try {
- const [jsonRes, rawRes] = await Promise.all([
- fetch(`http://localhost:${PORT}/design-system.json?token=${TOKEN}`, { cache: 'no-store' }),
- fetch(`http://localhost:${PORT}/design-system/raw?token=${TOKEN}`, { cache: 'no-store' }),
- ]);
- const jsonData = await jsonRes.json();
- designState.present = jsonData.present === true;
- designState.parsed = jsonData.parsed || null;
- designState.sidecar = jsonData.sidecar || null;
- designState.hasMd = !!jsonData.hasMd;
- designState.hasSidecar = !!jsonData.hasSidecar;
- designState.mdNewerThanJson = !!jsonData.mdNewerThanJson;
- designState.raw = designState.present && rawRes.ok ? await rawRes.text() : null;
- designState.error = jsonData.parseError || jsonData.sidecarError || null;
- } catch (err) {
- designState.error = err?.message || 'Failed to load design system.';
- } finally {
- designState.loading = false;
- renderDesignChrome(); // refresh title from data
- }
- }
-
- function renderDesignBody() {
- const body = designShadow.querySelector('#panel-body');
- if (!body) return;
- body.innerHTML = '';
-
- if (designState.loading) {
- body.appendChild(msgDiv('loading', 'Loading design system…'));
- return;
- }
- if (designState.error) {
- body.appendChild(msgDiv('error', designState.error));
- return;
- }
- if (designState.present === false) {
- const empty = document.createElement('div');
- empty.className = 'empty';
- empty.innerHTML = `<strong>No DESIGN.md yet</strong>Create one by running <code>/impeccable document</code> in your terminal, then re-open this panel.`;
- body.appendChild(empty);
- return;
- }
-
- if (designState.tab === 'raw') {
- renderRawTab(body, designState.raw || '');
- return;
- }
-
- // Visual tab — single unified render path.
- if (designState.mdNewerThanJson) body.appendChild(renderStaleHint());
- if (designState.hasMd && !designState.hasSidecar) {
- body.appendChild(renderParsedMdCta());
- }
- renderDesignVisual(body, designState.parsed, designState.sidecar);
- }
-
- function msgDiv(cls, text) {
- const d = document.createElement('div');
- d.className = cls;
- d.textContent = text;
- return d;
- }
-
- function renderStaleHint() {
- const box = document.createElement('div');
- box.className = 'stale';
- box.innerHTML = `
- <span class="stale-dot"></span>
- <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>
- `;
- return box;
- }
-
- function renderParsedMdCta() {
- const box = document.createElement('div');
- box.className = 'parsed-md-cta';
- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;
- return box;
- }
-
- // --- Unified render: merge parsed DESIGN.md frontmatter with sidecar v2 ---
-
- function renderDesignVisual(body, parsed, sidecar) {
- const frontmatter = parsed?.frontmatter || {};
- const extensions = sidecar?.extensions || {};
- const proseColors = parsed?.colors || null;
-
- const colors = buildColorModels(frontmatter.colors, extensions.colorMeta, proseColors);
- if (colors.length) renderColorTiles(body, colors);
-
- const types = buildTypographyModels(frontmatter.typography, extensions.typographyMeta);
- if (types.length) renderTypeTiles(body, types);
-
- const radii = buildRadiiModels(frontmatter.rounded);
- if (radii.length) renderRadiiTile(body, radii);
-
- if (extensions.shadows?.length) renderShadowTiles(body, extensions.shadows);
-
- const components = sidecar?.components || [];
- if (components.length) renderComponentTiles(body, components);
-
- // Narrative: sidecar wins if present (richer, agent-curated). Otherwise
- // synthesize from prose sections.
- const narrative = sidecar?.narrative || synthesizeNarrative(parsed);
- if (narrative.rules?.length) body.appendChild(renderRulesCollapsible(narrative.rules));
- if ((narrative.dos?.length || narrative.donts?.length)) body.appendChild(renderDosDontsCollapsible(narrative));
- if (narrative.overview || narrative.northStar || narrative.keyCharacteristics?.length) {
- body.appendChild(renderOverviewCollapsible(narrative));
- }
-
- if (body.childElementCount === 0) {
- body.appendChild(msgDiv('empty', 'No design system data available.'));
- }
- }
-
- // Frontmatter primitives + sidecar colorMeta → tile-ready color models.
- // A matching prose bullet (when the slug sits in the bullet text) supplies
- // description as a last-resort fallback.
- function buildColorModels(fmColors, colorMeta, proseColors) {
- if (!fmColors) return [];
- const meta = colorMeta || {};
- return Object.entries(fmColors).map(([key, value]) => {
- const m = meta[key] || {};
- return {
- role: m.role || humanizeKey(key),
- name: m.displayName || humanizeKey(key),
- value: value,
- canonical: m.canonical || null,
- description: m.description || findProseDescription(proseColors, key, m.displayName),
- tonalRamp: m.tonalRamp || null,
- };
- });
- }
-
- function buildTypographyModels(fmTypography, typographyMeta) {
- if (!fmTypography) return [];
- const meta = typographyMeta || {};
- return Object.entries(fmTypography).map(([key, spec]) => {
- const m = meta[key] || {};
- const { family, fallback } = splitFontFamily(spec?.fontFamily);
- return {
- role: key,
- name: m.displayName || humanizeKey(key),
- family,
- fallback,
- weight: spec?.fontWeight ?? 400,
- // fontStyle isn't in Stitch's frontmatter schema; the sidecar carries
- // it when a role is rendered in italic (e.g. display italic).
- style: m.style || 'normal',
- sampleSize: spec?.fontSize || '1rem',
- lineHeight: spec?.lineHeight != null ? String(spec.lineHeight) : '',
- letterSpacing: spec?.letterSpacing,
- purpose: m.purpose,
- };
- });
- }
-
- function buildRadiiModels(fmRounded) {
- if (!fmRounded) return [];
- return Object.entries(fmRounded).map(([name, value]) => ({ name, value }));
- }
-
- function splitFontFamily(stack) {
- if (!stack || typeof stack !== 'string') return { family: '', fallback: '' };
- const parts = stack.split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, ''));
- return { family: parts[0] || '', fallback: parts.slice(1).join(', ') };
- }
-
- function humanizeKey(k) {
- return String(k || '').replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
- }
-
- function findProseDescription(proseColors, key, displayName) {
- if (!proseColors || !proseColors.groups) return null;
- const needles = [key, displayName].filter(Boolean).map((s) => s.toLowerCase());
- for (const g of proseColors.groups) {
- for (const c of g.colors || []) {
- const hay = String(c.name || '').toLowerCase();
- if (hay && needles.some((n) => hay.includes(n) || n.includes(hay))) {
- return c.description || null;
- }
- }
- }
- return null;
- }
-
- function synthesizeNarrative(parsed) {
- if (!parsed) return {};
- const md = parsed;
- return {
- northStar: md.overview?.creativeNorthStar,
- overview: (md.overview?.philosophy || []).join(' '),
- keyCharacteristics: md.overview?.keyCharacteristics || [],
- rules: [
- ...(md.colors?.rules || []).map((r) => ({ ...r, section: 'colors' })),
- ...(md.typography?.rules || []).map((r) => ({ ...r, section: 'typography' })),
- ...(md.elevation?.rules || []).map((r) => ({ ...r, section: 'elevation' })),
- ],
- dos: md.dosDonts?.dos || [],
- donts: md.dosDonts?.donts || [],
- };
- }
-
- function renderColorTiles(body, colors) {
- for (const c of colors) {
- const tile = document.createElement('div');
- tile.className = 'tile c-tile';
- tile.title = 'Click to copy';
- tile.addEventListener('click', () => copyToClipboard(c.value));
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(c.name || c.role || 'Color')}</span><span>${escapeHtml(c.value || '')}</span>`;
- tile.appendChild(meta);
-
- const hero = document.createElement('div');
- hero.className = 'c-hero';
- hero.style.background = c.value;
- tile.appendChild(hero);
-
- const ramp = synthesizeRamp(c);
- if (ramp.length) {
- const r = document.createElement('div');
- r.className = 'c-ramp';
- r.innerHTML = ramp.map((v) => `<span style="background:${cssSafe(v)}"></span>`).join('');
- tile.appendChild(r);
- }
-
- if (c.description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = c.description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function synthesizeRamp(c) {
- if (c.tonalRamp?.length) return c.tonalRamp;
- // If base value is OKLCH, synthesize an 8-step ramp across lightness.
- const m = typeof c.value === 'string' && c.value.match(/^oklch\(\s*([\d.]+)%\s+([\d.]+)\s+([\d.]+)\s*(?:\/\s*([\d.]+))?\s*\)$/i);
- if (!m) return [];
- const [, , chroma, hue] = m;
- const steps = [20, 32, 44, 56, 68, 80, 90, 96];
- return steps.map((l) => `oklch(${l}% ${chroma} ${hue})`);
- }
-
- function renderTypeTiles(body, types) {
- for (const t of types) {
- const tile = document.createElement('div');
- tile.className = 'tile t-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span>${escapeHtml(t.role || '')}</span><span>${escapeHtml(t.weight || '')} ${escapeHtml(t.style === 'italic' ? 'italic' : '')}</span>`;
- tile.appendChild(meta);
-
- const specimen = document.createElement('div');
- specimen.className = 't-specimen';
- specimen.textContent = 'Aa';
- specimen.style.fontFamily = fontStack(t);
- specimen.style.fontWeight = String(t.weight || 400);
- specimen.style.fontStyle = t.style || 'normal';
- specimen.style.fontSize = '56px'; // Fixed specimen size — compare faces, not scales.
- specimen.style.letterSpacing = 'normal';
- specimen.style.textTransform = 'none';
- tile.appendChild(specimen);
-
- // The system's actual sample size for this role, shown as small mono meta below.
- if (t.sampleSize) {
- const scale = document.createElement('div');
- scale.style.cssText = 'font-family:' + MONO + '; font-size: 10px; color:' + DP.meta + '; margin-top: 2px;';
- scale.textContent = t.sampleSize;
- tile.appendChild(scale);
- }
-
- const family = document.createElement('div');
- family.className = 't-family';
- family.textContent = t.family || t.name || '';
- tile.appendChild(family);
-
- if (t.purpose) {
- const p = document.createElement('div');
- p.className = 't-purpose';
- p.textContent = t.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function fontStack(t) {
- const fam = t.family || '';
- const fb = t.fallback || '';
- if (fam && /[,\s]/.test(fam) && !fam.includes("'") && !fam.includes('"')) {
- return `"${fam}", ${fb}`;
- }
- return fam && fb ? `"${fam}", ${fb}` : (fam || fb);
- }
-
- function renderRadiiTile(body, radii) {
- const tile = document.createElement('div');
- tile.className = 'tile';
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">Corner Radii</span><span>${radii.length}</span>`;
- tile.appendChild(meta);
-
- const strip = document.createElement('div');
- strip.className = 'r-strip';
- for (const r of radii) {
- const item = document.createElement('div');
- item.className = 'r-item';
- const s = document.createElement('div');
- s.className = 'r-sample';
- s.style.borderRadius = r.value || '0';
- item.appendChild(s);
- const lbl = document.createElement('div');
- lbl.className = 'r-label';
- lbl.textContent = r.name || '';
- item.appendChild(lbl);
- const val = document.createElement('div');
- val.className = 'r-val';
- val.textContent = r.value || '';
- item.appendChild(val);
- strip.appendChild(item);
- }
- tile.appendChild(strip);
- body.appendChild(tile);
- }
-
- function renderShadowTiles(body, shadows) {
- for (const sh of shadows) {
- const tile = document.createElement('div');
- tile.className = 'tile s-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(sh.name || 'Shadow')}</span><span>Elevation</span>`;
- tile.appendChild(meta);
-
- const surface = document.createElement('div');
- surface.className = 's-surface';
- surface.style.boxShadow = sh.value || 'none';
- tile.appendChild(surface);
-
- const val = document.createElement('div');
- val.className = 's-value';
- val.textContent = sh.value || '';
- tile.appendChild(val);
-
- if (sh.purpose) {
- const p = document.createElement('div');
- p.className = 's-purpose';
- p.textContent = sh.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function renderComponentTiles(body, components) {
- // Group consecutive components that share a kind into one tile. This avoids
- // a pile of one-component tiles (e.g., three button variants = three tiles)
- // and reads more like a proper category.
- const groups = groupByKind(components);
-
- for (const group of groups) {
- const tile = document.createElement('div');
- tile.className = 'tile cmp-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- const groupTitle = group.length === 1
- ? (group[0].name || group[0].kind || 'Component')
- : titleForKind(group[0].kind, group.length);
- meta.innerHTML = `<span class="name">${escapeHtml(groupTitle)}</span><span class="cmp-kind">${escapeHtml(group[0].kind || '')}</span>`;
- tile.appendChild(meta);
-
- for (const c of group) {
- const stage = document.createElement('div');
- stage.className = 'cmp-stage';
-
- // Render the component in its own shadow root so its CSS can't bleed.
- const host = document.createElement('div');
- const sub = host.attachShadow({ mode: 'open' });
- const style = document.createElement('style');
- style.textContent = c.css || '';
- sub.appendChild(style);
- const container = document.createElement('div');
- container.innerHTML = c.html || '';
- sub.appendChild(container);
- stage.appendChild(host);
-
- // Show component name as a sublabel only when the tile groups >1 item,
- // or when the component's display name differs from its kind.
- const showSublabel = group.length > 1;
- if (showSublabel) {
- const lbl = document.createElement('div');
- lbl.className = 'cmp-sublabel';
- lbl.textContent = c.name || '';
- stage.appendChild(lbl);
- }
- tile.appendChild(stage);
- }
-
- // Single shared description if all items carry the same one; otherwise
- // skip — per-item descriptions clutter a grouped tile.
- if (group.length === 1 && group[0].description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = group[0].description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function groupByKind(components) {
- const groups = [];
- for (const c of components) {
- const last = groups[groups.length - 1];
- if (last && last[0].kind && c.kind === last[0].kind) {
- last.push(c);
- } else {
- groups.push([c]);
- }
- }
- return groups;
- }
-
- function titleForKind(kind, count) {
- const labels = {
- button: 'Buttons',
- input: 'Inputs',
- nav: 'Navigation',
- chip: 'Chips',
- card: 'Cards',
- custom: 'Components',
- };
- return labels[kind] || (kind ? kind.charAt(0).toUpperCase() + kind.slice(1) + 's' : 'Components');
- }
-
- // --- Collapsibles ---------------------------------------------------------
-
- function buildCollapsible(key, label, count) {
- const wrap = document.createElement('div');
- wrap.className = 'coll';
- wrap.setAttribute('data-open', designState.collapsed[key] ? 'false' : 'true');
-
- const head = document.createElement('button');
- head.className = 'coll-head';
- head.innerHTML = `
- <svg class="coll-chev" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 2.5L8 6 4 9.5"/></svg>
- <span>${escapeHtml(label)}</span>
- ${count != null ? `<span class="coll-count">${escapeHtml(String(count))}</span>` : ''}
- `;
- head.addEventListener('click', () => {
- designState.collapsed[key] = !designState.collapsed[key];
- saveDesignPrefs();
- renderDesignBody();
- });
- wrap.appendChild(head);
-
- const body = document.createElement('div');
- body.className = 'coll-body';
- wrap.appendChild(body);
- return { wrap, body };
- }
-
- function renderRulesCollapsible(rules) {
- const { wrap, body } = buildCollapsible('rules', 'Named Rules', rules.length);
- for (const r of rules) {
- const card = document.createElement('div');
- card.className = 'rule-card';
- const name = document.createElement('div');
- name.className = 'name';
- name.innerHTML = `${escapeHtml(r.name)}${r.section ? `<span class="section">${escapeHtml(r.section)}</span>` : ''}`;
- card.appendChild(name);
- const b = document.createElement('div');
- b.className = 'body';
- b.textContent = r.body || '';
- card.appendChild(b);
- body.appendChild(card);
- }
- return wrap;
- }
-
- function renderDosDontsCollapsible(n) {
- const total = (n.dos?.length || 0) + (n.donts?.length || 0);
- const { wrap, body } = buildCollapsible('dosdonts', "Do's and Don'ts", total);
- const grid = document.createElement('div');
- grid.className = 'dos';
- for (const d of n.dos || []) {
- const el = document.createElement('div');
- el.className = 'do';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- for (const d of n.donts || []) {
- const el = document.createElement('div');
- el.className = 'dont';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- body.appendChild(grid);
- return wrap;
- }
-
- function renderOverviewCollapsible(n) {
- const { wrap, body } = buildCollapsible('overview', 'Overview', null);
- const ov = document.createElement('div');
- ov.className = 'overview-body';
- if (n.northStar) {
- const star = document.createElement('span');
- star.className = 'north-star';
- star.textContent = '“' + n.northStar + '”';
- ov.appendChild(star);
- }
- if (n.overview) {
- const p = document.createElement('p');
- p.innerHTML = inlineMd(n.overview);
- ov.appendChild(p);
- }
- if (n.keyCharacteristics?.length) {
- const ul = document.createElement('ul');
- ul.innerHTML = n.keyCharacteristics.map((k) => `<li>${inlineMd(k)}</li>`).join('');
- ov.appendChild(ul);
- }
- body.appendChild(ov);
- return wrap;
- }
-
- function cssSafe(v) {
- // Strip anything outside valid CSS value chars to prevent injection via
- // .impeccable/design.json values rendered into inline style strings.
- return String(v).replace(/[<>"'`\n]/g, '');
- }
-
- // --- Raw tab: minimal markdown renderer (subset) --------------------------
-
- function renderRawTab(body, md) {
- const wrap = document.createElement('div');
- wrap.className = 'md';
- wrap.innerHTML = renderMarkdown(md);
- body.appendChild(wrap);
- }
-
- function renderMarkdown(md) {
- const lines = md.split(/\r?\n/);
- const out = [];
- let i = 0;
- let inCode = false;
- let codeBuf = [];
- let paraBuf = [];
- let listBuf = []; // array of { indent, html }
- let listType = null; // 'ul' | 'ol'
-
- const flushPara = () => {
- if (paraBuf.length) {
- out.push(`<p>${inlineMd(paraBuf.join(' '))}</p>`);
- paraBuf = [];
- }
- };
- const flushList = () => {
- if (listBuf.length) {
- out.push(buildListHtml(listBuf, listType));
- listBuf = [];
- listType = null;
- }
- };
- const flushAll = () => { flushPara(); flushList(); };
-
- for (; i < lines.length; i++) {
- const line = lines[i];
-
- // Code fence
- const fence = line.match(/^```(\w*)\s*$/);
- if (fence) {
- if (!inCode) { flushAll(); inCode = true; codeBuf = []; }
- else {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- inCode = false;
- }
- continue;
- }
- if (inCode) { codeBuf.push(line); continue; }
-
- if (line.trim() === '') { flushAll(); continue; }
-
- const hr = line.match(/^\s*(?:---+|\*\*\*+)\s*$/);
- if (hr) { flushAll(); out.push('<hr />'); continue; }
-
- const heading = line.match(/^(#{1,4})\s+(.+)$/);
- if (heading) {
- flushAll();
- const lvl = heading[1].length;
- out.push(`<h${lvl}>${inlineMd(heading[2])}</h${lvl}>`);
- continue;
- }
-
- const bullet = line.match(/^(\s*)([-*])\s+(.+)$/);
- const ordered = line.match(/^(\s*)(\d+)\.\s+(.+)$/);
- if (bullet || ordered) {
- flushPara();
- const m = bullet || ordered;
- const indent = Math.floor(m[1].length / 2);
- const t = bullet ? 'ul' : 'ol';
- if (listType && listType !== t) flushList();
- listType = t;
- listBuf.push({ indent, html: inlineMd(m[3]) });
- continue;
- }
-
- paraBuf.push(line);
- }
- flushAll();
- if (inCode && codeBuf.length) {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- }
- return out.join('\n');
- }
-
- function buildListHtml(items, type) {
- // Nest by indent (one level deep is plenty for DESIGN.md).
- let html = `<${type}>`;
- let lastIndent = 0;
- for (const it of items) {
- if (it.indent > lastIndent) html += `<${type}>`;
- else if (it.indent < lastIndent) html += `</${type}>`.repeat(lastIndent - it.indent);
- html += `<li>${it.html}</li>`;
- lastIndent = it.indent;
- }
- html += `</${type}>`.repeat(lastIndent + 1);
- return html;
- }
-
- function inlineMd(text) {
- // Order matters: escape first, then re-inject tags.
- let s = escapeHtml(text);
- // Code spans
- s = s.replace(/`([^`]+)`/g, (_, code) => `<code>${code}</code>`);
- // Links [text](url)
- s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, t, u) => `<a href="${u}" target="_blank" rel="noopener noreferrer">${t}</a>`);
- // Bold
- s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
- // Italic (only single *…*, skip if inside bold already handled)
- s = s.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em>$2</em>');
- return s;
- }
-
- function highlightBold(text) {
- return inlineMd(text);
- }
-
- function escapeHtml(s) {
- return String(s)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
-
- function copyToClipboard(text) {
- if (!text) return;
- try {
- navigator.clipboard.writeText(text);
- showToast('Copied: ' + text);
- } catch { /* ignore */ }
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- function init() {
- try { history.scrollRestoration = 'manual'; } catch {}
- initHighlight();
- initAnnotOverlay();
- initBar();
- initActionPicker();
- initParamsPanel();
- initGlobalBar();
- initDesignPanel();
- document.addEventListener('mousemove', handleMouseMove, true);
- document.addEventListener('click', handleClick, true);
- document.addEventListener('keydown', handleKeyDown, true);
- connectSSE();
-
- // Check for an active session to resume (variant wrapper already in DOM after HMR)
- if (!resumeSession()) {
- console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
- // SvelteKit (and any framework that hydrates after HTML parse) may add
- // the variant wrapper AFTER init runs. Watch for it and retry resume
- // once it appears. Disconnect on first hit.
- const scout = new MutationObserver(() => {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) return;
- scout.disconnect();
- if (resumeSession()) {
- console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
- }
- });
- scout.observe(document.body, { childList: true, subtree: true });
- } else {
- console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
- }
- }
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
- } else {
- init();
- }
-})();
@@ -1,75 +0,0 @@
-#!/usr/bin/env node
-/**
- * Canonical durable completion acknowledgement for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function parseArgs(argv) {
- const out = { status: 'complete' };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';
- else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }
- else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function completeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help || !args.id) {
- console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);
- process.exit(args.help ? 0 : 1);
- }
-
- const serverInfo = readServerInfo();
- const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;
- if (serverResult?.ok) {
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const snapshot = store.getSnapshot(args.id, { includeCompleted: true });
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const event = args.status === 'discarded'
- ? { type: 'discarded', id: args.id }
- : args.status === 'agent_error'
- ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }
- : { type: 'complete', id: args.id };
- const snapshot = store.appendEvent(event);
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));
-}
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function completeThroughServer(info, args) {
- const type = args.status === 'discarded'
- ? 'discarded'
- : args.status === 'agent_error'
- ? 'error'
- : 'complete';
- try {
- const res = await fetch(`http://localhost:${info.port}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),
- });
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {
- completeCli();
-}
@@ -1,18 +0,0 @@
-export function completionTypeForAcceptResult(eventType, acceptResult) {
- if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';
- if (acceptResult?.handled === true) return 'complete';
- if (acceptResult?.mode === 'error') return 'error';
- return 'agent_done';
-}
-
-export function completionAckForAcceptResult(eventId, completionType, acceptResult) {
- const ack = { ok: true, type: completionType };
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) {
- ack.final = false;
- ack.requiresComplete = true;
- ack.nextCommand = `live-complete.mjs --id ${eventId}`;
- ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';
- }
- return ack;
-}
@@ -1,446 +0,0 @@
-/**
- * CLI helper: insert/remove the live variant mode script tag in the project's
- * main HTML entry point.
- *
- * On first live run, the agent generates `.impeccable/live/config.json`
- * with the project's insertion target (framework-specific). On
- * every subsequent run, this script handles insert/remove deterministically
- * with zero LLM involvement.
- *
- * Usage:
- * node live-inject.mjs --port PORT # Insert the live script tag
- * node live-inject.mjs --remove # Remove the live script tag
- * node live-inject.mjs --check # Check whether live config exists
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { resolveLiveConfigPath } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });
-const MARKER_OPEN_TEXT = 'impeccable-live-start';
-const MARKER_CLOSE_TEXT = 'impeccable-live-end';
-
-/**
- * Hard-excluded directory patterns. These are NEVER user-facing pages and
- * matching them would silently inject tracking scripts into third-party
- * code. The user cannot turn these off via config — they are the floor.
- */
-const HARD_EXCLUDES = [
- '**/node_modules/**',
- '**/.git/**',
-];
-
-export async function injectCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-inject.mjs [options]
-
-Insert or remove the live mode script tag in the project's HTML entry point.
-Reads configuration from .impeccable/live/config.json.
-
-Modes:
- --port PORT Insert script tag pointing at http://localhost:PORT/live.js
- --remove Remove the script tag (if present)
- --check Print whether .impeccable/live/config.json exists and its content
-
-Output (JSON):
- { ok, file, inserted|removed, config? }`);
- process.exit(0);
- }
-
- if (args.includes('--check')) {
- if (!fs.existsSync(CONFIG_PATH)) {
- console.log(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(0);
- }
- let cfg;
- try {
- cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- try {
- validateConfig(cfg);
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- console.log(JSON.stringify({ ok: true, config: cfg, path: CONFIG_PATH }));
- return;
- }
-
- // Load config
- if (!fs.existsSync(CONFIG_PATH)) {
- console.error(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(1);
- }
- const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- validateConfig(config);
-
- const resolvedFiles = resolveFiles(process.cwd(), config);
-
- if (args.includes('--remove')) {
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const detagged = removeTag(content, config.commentSyntax);
- const updated = revertCspMeta(detagged);
- if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- removed: detagged !== content,
- cspReverted: updated !== detagged,
- };
- });
- console.log(JSON.stringify({ ok: true, results }));
- return;
- }
-
- // Insert mode — need --port
- const portIdx = args.indexOf('--port');
- const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : NaN;
- if (!Number.isFinite(port)) {
- console.error(JSON.stringify({ ok: false, error: 'missing_port' }));
- process.exit(1);
- }
-
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
- const withTag = insertTag(withoutOld, config, port);
- if (withTag === withoutOld) {
- return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
- }
- const updated = patchCspMeta(withTag, port);
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- inserted: true,
- cspPatched: updated !== withTag,
- };
- });
- const anyInserted = results.some((r) => r.inserted);
- console.log(JSON.stringify({ ok: anyInserted, port, results }));
- if (!anyInserted) process.exit(1);
-}
-
-/**
- * Expand config.files (which may contain glob patterns) into a literal list
- * of existing file paths relative to rootDir. Literal entries pass through;
- * glob patterns are expanded via fs.globSync. HARD_EXCLUDES and config.exclude
- * are applied as filters. Duplicates are removed. Order is preserved by
- * first appearance.
- */
-export function resolveFiles(rootDir, config) {
- const patterns = config.files;
- const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
- const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
- const excludeRegexes = allExcludes.map(globToRegex);
-
- const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
- const isGlob = (s) => /[*?[]/.test(s);
-
- const seen = new Set();
- const out = [];
- for (const pat of patterns) {
- if (!isGlob(pat)) {
- // Literal path — include even if it doesn't exist yet; the caller
- // reports file_not_found per-entry. Exclude list doesn't apply to
- // explicit literal entries (user named it on purpose).
- if (!seen.has(pat)) {
- seen.add(pat);
- out.push(pat);
- }
- continue;
- }
- let matches;
- try {
- matches = fs.globSync(pat, { cwd: rootDir, withFileTypes: true });
- } catch {
- continue;
- }
- for (const ent of matches) {
- if (!ent.isFile || !ent.isFile()) continue;
- const abs = path.join(ent.parentPath || ent.path || rootDir, ent.name);
- const rel = path.relative(rootDir, abs).split(path.sep).join('/');
- if (isExcluded(rel)) continue;
- if (seen.has(rel)) continue;
- seen.add(rel);
- out.push(rel);
- }
- }
- return out;
-}
-
-/**
- * Convert a glob pattern to a RegExp. Supports:
- * ** → any number of path segments (including zero)
- * * → any chars except `/`
- * ? → any single char except `/`
- * Paths are normalized to forward slashes before matching.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- // ** — any number of segments, including zero. Handle the common
- // **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
- if (pattern[i + 2] === '/') {
- re += '(?:.*/)?';
- i += 3;
- } else {
- re += '.*';
- i += 2;
- }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Core operations
-// ---------------------------------------------------------------------------
-
-function validateConfig(cfg) {
- if (!cfg || typeof cfg !== 'object') throw new Error('config.json must be an object');
- if (!Array.isArray(cfg.files) || cfg.files.length === 0) {
- throw new Error('config.files (non-empty string array) required');
- }
- if (!cfg.files.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.files must contain only non-empty strings');
- }
- if (cfg.exclude !== undefined) {
- if (!Array.isArray(cfg.exclude)) {
- throw new Error('config.exclude, if present, must be a string array');
- }
- if (!cfg.exclude.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.exclude must contain only non-empty strings');
- }
- }
- if (typeof cfg.insertBefore !== 'string' && typeof cfg.insertAfter !== 'string') {
- throw new Error('config.insertBefore or config.insertAfter (string) required');
- }
- if (cfg.commentSyntax !== 'html' && cfg.commentSyntax !== 'jsx') {
- throw new Error("config.commentSyntax must be 'html' or 'jsx'");
- }
- if (cfg.cspChecked !== undefined && typeof cfg.cspChecked !== 'boolean') {
- throw new Error("config.cspChecked, if present, must be a boolean");
- }
-}
-
-function commentOpen(syntax) { return syntax === 'jsx' ? '{/*' : '<!--'; }
-function commentClose(syntax) { return syntax === 'jsx' ? '*/}' : '-->'; }
-
-function buildTagBlock(syntax, port) {
- const open = commentOpen(syntax);
- const close = commentClose(syntax);
- return (
- open + ' ' + MARKER_OPEN_TEXT + ' ' + close + '\n' +
- '<script src="http://localhost:' + port + '/live.js"></script>\n' +
- open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n'
- );
-}
-
-function insertTag(content, config, port) {
- const block = buildTagBlock(config.commentSyntax, port);
- // insertBefore: match the LAST occurrence. Anchors like `</body>` naturally
- // belong at the end, and the same literal can appear earlier in code blocks
- // within rendered documentation pages.
- if (config.insertBefore) {
- const idx = content.lastIndexOf(config.insertBefore);
- if (idx === -1) return content;
- return content.slice(0, idx) + block + content.slice(idx);
- }
- // insertAfter: match the FIRST occurrence — typical anchors like `<head>` or
- // `<body>` open near the top of the document.
- const idx = content.indexOf(config.insertAfter);
- if (idx === -1) return content;
- const after = idx + config.insertAfter.length;
- // Preserve a single trailing newline if the anchor didn't end with one
- const prefix = content[after] === '\n' ? content.slice(0, after + 1) : content.slice(0, after) + '\n';
- return prefix + block + content.slice(prefix.length);
-}
-
-/**
- * Remove the live script block. Matches either HTML or JSX comment markers
- * regardless of config (so stale tags from a wrong config can still be cleaned).
- *
- * Indent-preserving: captures any whitespace immediately preceding the opener
- * marker and re-emits it in place of the removed block. `insertTag` inserted
- * the block *after* the original line's indent and *before* the anchor (e.g.
- * `</body>`), which moved the indent onto the opener line and left the anchor
- * unindented. Replacing the whole block (plus its trailing newline) with just
- * the captured indent hands the indent back to the anchor that follows.
- */
-function removeTag(content, _syntax) {
- const patterns = [
- /([ \t]*)<!--\s*impeccable-live-start\s*-->[\s\S]*?<!--\s*impeccable-live-end\s*-->[ \t]*\n/,
- /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}[ \t]*\n/,
- ];
- for (const pat of patterns) {
- const next = content.replace(pat, '$1');
- if (next !== content) return next;
- }
- return content;
-}
-
-// ---------------------------------------------------------------------------
-// Content-Security-Policy meta-tag patcher
-//
-// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
-// the cross-origin load of /live.js (and the SSE/POST connection back to
-// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
-//
-// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
-// and stash the original `content` value in a `data-impeccable-csp-original`
-// attribute (base64) so revert is exact.
-//
-// On remove: detect the marker attribute, decode it, restore the original
-// content value verbatim, drop the marker.
-//
-// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
-// shared helpers) is NOT patched here — those need framework-specific config
-// edits and are handled via the existing detect-csp.mjs reference output.
-// Only the in-source meta-tag form gets the auto-patch.
-// ---------------------------------------------------------------------------
-
-const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
-
-function findCspMetaTags(content) {
- const out = [];
- const tagRe = /<meta\s+([^>]*?)\/?>/gis;
- let m;
- while ((m = tagRe.exec(content)) !== null) {
- const attrs = m[1];
- if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
- out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
- }
- return out;
-}
-
-function getAttr(attrs, name) {
- const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
- const m = attrs.match(re);
- return m ? { quote: m[1], value: m[2], full: m[0] } : null;
-}
-
-function appendOriginToDirective(csp, directive, origin) {
- const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
- const m = csp.match(re);
- if (m) {
- const tokens = m[4].trim().split(/\s+/);
- if (tokens.includes(origin)) return csp;
- return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
- }
- // Directive missing — add it. Use 'self' + origin so we don't inadvertently
- // narrow the policy compared to the default-src fallback (most users with
- // an explicit CSP have 'self' there).
- return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
-}
-
-export function patchCspMeta(content, port) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
- const origin = `http://localhost:${port}`;
-
- // Walk last-to-first so prior splices don't invalidate later indices.
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const attrs = tag.attrs;
- if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
- const contentAttr = getAttr(attrs, 'content');
- if (!contentAttr) continue;
-
- const original = contentAttr.value;
- let patched = original;
- patched = appendOriginToDirective(patched, 'script-src', origin);
- patched = appendOriginToDirective(patched, 'connect-src', origin);
- // The shader overlay during 'generating' creates a screenshot via
- // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
- // those. Add `blob:` so the overlay doesn't throw a CSP violation.
- patched = appendOriginToDirective(patched, 'img-src', 'blob:');
- if (patched === original) continue;
-
- const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
- const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
- // The tagRe captures any whitespace between the last attribute and the
- // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
- // a replace would land it BEFORE that trailing space, leaving a double
- // space inside attrs and clobbering the space before `/>`. Split off
- // the trailing whitespace, splice the marker into the attribute body,
- // and re-append the original trailing whitespace so a self-closing
- // `<meta … />` round-trips byte-for-byte.
- const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
- const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
- const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
- const newTag = tag.full.replace(attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-export function revertCspMeta(content) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
-
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
- if (!origAttr) continue;
- const contentAttr = getAttr(tag.attrs, 'content');
- if (!contentAttr) continue;
-
- let originalValue;
- try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
- catch { continue; }
-
- const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
- let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
- // Drop the marker attribute and any single space immediately preceding it.
- newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
- const newTag = tag.full.replace(tag.attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
- injectCli();
-}
-
-export { insertTag, removeTag, validateConfig, buildTagBlock };
-// patchCspMeta + revertCspMeta are exported above where they're defined.
@@ -1,200 +0,0 @@
-/**
- * CLI client for the live variant mode poll/reply protocol.
- *
- * Usage:
- * npx impeccable poll # Block until browser event, print JSON
- * npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
- * npx impeccable poll --reply <id> done # Reply "done" to event <id>
- * npx impeccable poll --reply <id> error "msg" # Reply with error
- */
-
-import { execFileSync } from 'node:child_process';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-// Node's built-in fetch (undici under the hood) enforces a 300s headers
-// timeout that can't be lowered per-request. We cap each request below
-// that ceiling and loop in `pollOnce` to synthesize a long poll without
-// depending on the standalone undici package.
-const PER_REQUEST_TIMEOUT_MS = 270_000;
-
-function readServerInfo() {
- const record = readLiveServerInfo(process.cwd());
- if (!record) {
- console.error('No running live server found. Start one with: npx impeccable live');
- process.exit(1);
- }
- return record.info;
-}
-
-export function buildPollReplyPayload(token, { id, type, message, file, data }) {
- return { token, id, type, message, file, data };
-}
-
-async function postReply(base, token, reply) {
- const res = await fetch(`${base}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(buildPollReplyPayload(token, reply)),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error || res.statusText);
- }
-}
-
-export async function pollCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable poll [options]
-
-Wait for a browser event from the live variant server, or reply to one.
-
-Modes:
- poll Block until a browser event arrives, print JSON
- poll --reply <id> done Reply "done" to event <id>
- poll --reply <id> error "msg" Reply with an error message
-
-Options:
- --timeout=MS Long-poll timeout in ms (default: 600000). Use the default unless the user asked to pause live; never use a short timeout to end the chat turn
- --help Show this help message`);
- process.exit(0);
- }
-
- const info = readServerInfo();
- const base = `http://localhost:${info.port}`;
-
- // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
- const replyIdx = args.indexOf('--reply');
- if (replyIdx !== -1) {
- const id = args[replyIdx + 1];
- const status = args[replyIdx + 2] || 'done';
- const fileIdx = args.indexOf('--file');
- const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
- // Message is any remaining positional arg that isn't a flag
- const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
-
- if (!id) {
- console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
- process.exit(1);
- }
-
- try {
- await postReply(base, info.token, { id, type: status, message, file: filePath });
-
- // Success — silent exit (agent doesn't need output for replies)
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Reply failed:', err.message);
- }
- process.exit(1);
- }
- return;
- }
-
- // Poll mode: block until browser event. Default 10 min. Node's built-in
- // fetch enforces a 300s headers timeout, so we loop in slices under that
- // ceiling and keep re-polling until we get a real event or the user's
- // total timeout runs out.
- const timeoutArg = args.find(a => a.startsWith('--timeout='));
- const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600000;
-
- const deadline = Date.now() + totalTimeout;
- let event;
- try {
- while (true) {
- const remaining = deadline - Date.now();
- if (remaining <= 0) {
- event = { type: 'timeout' };
- break;
- }
- const slice = Math.min(remaining, PER_REQUEST_TIMEOUT_MS);
- const res = await fetch(`${base}/poll?token=${info.token}&timeout=${slice}`);
-
- if (res.status === 401) {
- console.error('Authentication failed. The server token may have changed.');
- console.error('Try restarting: npx impeccable live stop && npx impeccable live');
- process.exit(1);
- }
-
- if (!res.ok) {
- console.error(`Poll failed: ${res.status} ${res.statusText}`);
- process.exit(1);
- }
-
- const next = await res.json();
- // Server-side timeout means no browser event arrived in this slice.
- // Loop and re-poll until we get a real event or we hit the user's
- // total deadline.
- if (next?.type === 'timeout' && Date.now() < deadline) continue;
- event = next;
- break;
- }
-
- // Auto-handle accept/discard via deterministic script
- if (event.type === 'accept' || event.type === 'discard') {
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const acceptScript = path.join(__dirname, 'live-accept.mjs');
- const scriptArgs = event.type === 'discard'
- ? ['--id', event.id, '--discard']
- : ['--id', event.id, '--variant', event.variantId];
- if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
- scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
- }
- try {
- const out = execFileSync(
- 'node',
- [acceptScript, ...scriptArgs],
- { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 }
- );
- event._acceptResult = JSON.parse(out.trim());
- } catch (err) {
- event._acceptResult = { handled: false, mode: 'error', error: err.message };
- }
-
- const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
- try {
- await postReply(base, info.token, {
- id: event.id,
- type: completionType,
- message: event._acceptResult?.error,
- file: event._acceptResult?.file,
- data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
- });
- } catch (err) {
- event._completionAck = { ok: false, error: err.message };
- }
- if (!event._completionAck) {
- event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
- }
- }
-
- // Second signal path: stderr banner in case the agent parses stdout
- // JSON but skips nested fields. One line is enough — the full checklist
- // is in reference/live.md.
- if (event._acceptResult?.carbonize === true) {
- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
- }
-
- // Print the event as JSON — the agent reads this from stdout
- console.log(JSON.stringify(event));
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Poll failed:', err.message);
- }
- process.exit(1);
- }
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
- pollCli();
-}
@@ -1,48 +0,0 @@
-#!/usr/bin/env node
-/**
- * Recover the next agent action from the durable live-session journal.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-
-function parseArgs(argv) {
- const out = { id: null };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function resumeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help) {
- console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });
- const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;
- if (!snapshot) {
- console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));
- return;
- }
-
- const pending = snapshot.pendingEvent || null;
- const nextAction = pending
- ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`
- : snapshot.phase === 'carbonize_required'
- ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`
- : snapshot.phase === 'accept_requested'
- ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`
- : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;
-
- console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {
- resumeCli();
-}
@@ -1,838 +0,0 @@
-#!/usr/bin/env node
-/**
- * Live variant mode server (self-contained, zero dependencies).
- *
- * Serves the browser script (/live.js), the detection overlay (/detect.js),
- * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
- * browser→server events. Agent communicates via HTTP long-poll (/poll).
- *
- * Usage:
- * node <scripts_path>/live-server.mjs # start
- * node <scripts_path>/live-server.mjs stop # stop + remove injected live.js tag
- * node <scripts_path>/live-server.mjs stop --keep-inject # stop only
- * node <scripts_path>/live-server.mjs --help
- */
-
-import http from 'node:http';
-import { randomUUID } from 'node:crypto';
-import { spawn, execFileSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import net from 'node:net';
-import { fileURLToPath } from 'node:url';
-import { parseDesignMd } from './design-parser.mjs';
-import { resolveContextDir } from './load-context.mjs';
-import { createLiveSessionStore } from './live-session-store.mjs';
-import {
- getDesignSidecarPath,
- getLiveAnnotationsDir,
- readLiveServerInfo,
- removeLiveServerInfo,
- resolveDesignSidecarPath,
- writeLiveServerInfo,
-} from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated
-// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
-// DESIGN.json fallback for existing projects.
-const CONTEXT_DIR = resolveContextDir(process.cwd());
-const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anyway
-const SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s
-
-// ---------------------------------------------------------------------------
-// Port detection
-// ---------------------------------------------------------------------------
-
-async function findOpenPort(start = 8400) {
- return new Promise((resolve) => {
- const srv = net.createServer();
- srv.listen(start, '127.0.0.1', () => {
- const port = srv.address().port;
- srv.close(() => resolve(port));
- });
- srv.on('error', () => resolve(findOpenPort(start + 1)));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Session state
-// ---------------------------------------------------------------------------
-
-const state = {
- token: null,
- port: null,
- sseClients: new Set(), // SSE response objects (server→browser push)
- pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
- pendingPolls: [], // agent poll callbacks waiting for browser events
- exitTimer: null,
- sessionDir: null, // per-session tmp dir for annotation screenshots
- sessionStore: null,
- leaseTimer: null,
-};
-
-// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;
-// cap at 10 MB to guard against runaway writes from a misbehaving client.
-const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
-
-function enqueueEvent(event) {
- if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;
- state.pendingEvents.push({ event, leaseUntil: 0 });
- flushPendingPolls();
-}
-
-function restorePendingEventsFromStore() {
- if (!state.sessionStore) return;
- for (const snapshot of state.sessionStore.listActiveSessions()) {
- if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);
- }
-}
-
-function findAvailablePendingEvent(now = Date.now()) {
- return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);
-}
-
-function leaseEvent(entry, leaseMs) {
- if (!entry.event?.id) {
- const idx = state.pendingEvents.indexOf(entry);
- if (idx !== -1) state.pendingEvents.splice(idx, 1);
- return entry.event;
- }
- entry.leaseUntil = Date.now() + leaseMs;
- return entry.event;
-}
-
-function acknowledgePendingEvent(id) {
- if (!id) return false;
- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);
- if (idx === -1) return false;
- state.pendingEvents.splice(idx, 1);
- scheduleLeaseFlush();
- return true;
-}
-
-function scheduleLeaseFlush() {
- if (state.leaseTimer) {
- clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- }
- if (state.pendingPolls.length === 0) return;
- const now = Date.now();
- const nextLeaseUntil = state.pendingEvents
- .map((entry) => entry.leaseUntil || 0)
- .filter((leaseUntil) => leaseUntil > now)
- .sort((a, b) => a - b)[0];
- if (!nextLeaseUntil) return;
- state.leaseTimer = setTimeout(() => {
- state.leaseTimer = null;
- flushPendingPolls();
- }, Math.max(0, nextLeaseUntil - now));
-}
-
-function flushPendingPolls() {
- while (state.pendingPolls.length > 0) {
- const entry = findAvailablePendingEvent();
- if (!entry) {
- scheduleLeaseFlush();
- return;
- }
- const poll = state.pendingPolls.shift();
- poll.resolve(leaseEvent(entry, poll.leaseMs));
- }
- scheduleLeaseFlush();
-}
-
-/** Push a message to all connected SSE clients. */
-function broadcast(msg) {
- const data = 'data: ' + JSON.stringify(msg) + '\n\n';
- for (const res of state.sseClients) {
- try { res.write(data); } catch { /* client gone */ }
- }
-}
-
-// ---------------------------------------------------------------------------
-// Load scripts
-// ---------------------------------------------------------------------------
-
-function loadBrowserScripts() {
- // Detection script: prefer the skill-bundled detector, then fall back to
- // source/npm package locations for local development and older installs.
- // This one IS cached — detect.js rarely changes during a session.
- const detectPaths = [
- path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(process.cwd(), 'node_modules', 'impeccable', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- ];
- let detectScript = '';
- for (const p of detectPaths) {
- try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
- }
-
- // live-browser.js: DO NOT cache. Return the path so the /live.js handler
- // can re-read on every request. Editing the browser script during iteration
- // should land on the next tab reload, not require a server restart.
- const sessionPath = path.join(__dirname, 'live-browser-session.js');
- const livePath = path.join(__dirname, 'live-browser.js');
- for (const p of [sessionPath, livePath]) {
- if (!fs.existsSync(p)) {
- process.stderr.write('Error: live browser script not found at ' + p + '\n');
- process.exit(1);
- }
- }
-
- return { detectScript, sessionPath, livePath };
-}
-
-function hasProjectContext() {
- // PRODUCT.md carries brand voice / anti-references — that's what determines
- // whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
- // concern, surfaced by the design panel's own empty state. Legacy
- // .impeccable.md is auto-migrated to PRODUCT.md by load-context.mjs.
- try {
- fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
- return true;
- } catch { return false; }
-}
-
-function statOrNull(filePath) {
- try { return fs.statSync(filePath); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// Validation (inline — no external import needed for self-contained script)
-// ---------------------------------------------------------------------------
-
-const VISUAL_ACTIONS = [
- 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
- 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
-];
-
-// Browser generates ids via crypto.randomUUID().slice(0, 8) (8 hex chars)
-// and variantIds via String(small integer). Restrict to those shapes so
-// any value that reaches a downstream child_process or DOM selector is
-// inert by construction.
-const ID_PATTERN = /^[0-9a-f]{8}$/;
-const VARIANT_ID_PATTERN = /^[0-9]{1,3}$/;
-
-function isValidId(v) { return typeof v === 'string' && ID_PATTERN.test(v); }
-function isValidVariantId(v) { return typeof v === 'string' && VARIANT_ID_PATTERN.test(v); }
-
-function validateEvent(msg) {
- if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
- switch (msg.type) {
- case 'generate':
- if (!isValidId(msg.id)) return 'generate: missing or malformed id';
- if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
- if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
- if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
- // Optional annotation fields (all-or-nothing: if any present, all must be well-formed).
- if (msg.screenshotPath !== undefined && typeof msg.screenshotPath !== 'string') return 'generate: screenshotPath must be string';
- if (msg.comments !== undefined && !Array.isArray(msg.comments)) return 'generate: comments must be array';
- if (msg.strokes !== undefined && !Array.isArray(msg.strokes)) return 'generate: strokes must be array';
- return null;
- case 'accept':
- if (!isValidId(msg.id)) return 'accept: missing or malformed id';
- if (!isValidVariantId(msg.variantId)) return 'accept: missing or malformed variantId';
- if (msg.paramValues !== undefined) {
- if (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues)) {
- return 'accept: paramValues must be an object';
- }
- }
- return null;
- case 'discard':
- return isValidId(msg.id) ? null : 'discard: missing or malformed id';
- case 'checkpoint':
- if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';
- if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';
- if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {
- return 'checkpoint: paramValues must be an object';
- }
- return null;
- case 'exit':
- return null;
- case 'prefetch':
- if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return 'prefetch: missing pageUrl';
- return null;
- default:
- return 'Unknown event type: ' + msg.type;
- }
-}
-
-// ---------------------------------------------------------------------------
-// HTTP request handler
-// ---------------------------------------------------------------------------
-
-function createRequestHandler({ detectScript, sessionPath, livePath }) {
- return (req, res) => {
- const url = new URL(req.url, `http://localhost:${state.port}`);
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
- if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
-
- const p = url.pathname;
-
- // --- Scripts ---
- if (p === '/live.js') {
- // Re-read from disk each request so edits to live-browser.js land on
- // the next tab reload. No-store headers prevent browser caching across
- // sessions — during iteration, a cached old script silently breaks
- // every subsequent session.
- let sessionScript;
- let liveScript;
- try {
- sessionScript = fs.readFileSync(sessionPath, 'utf-8');
- liveScript = fs.readFileSync(livePath, 'utf-8');
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'text/plain' });
- res.end('Error reading live browser scripts: ' + err.message);
- return;
- }
- const body =
- `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
- `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
- sessionScript + '\n' +
- liveScript;
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
- 'Pragma': 'no-cache',
- });
- res.end(body);
- return;
- }
- if (p === '/detect.js' || p === '/') {
- if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
- res.writeHead(200, { 'Content-Type': 'application/javascript' });
- res.end(detectScript);
- return;
- }
-
- // --- Vendored modern-screenshot (UMD build) ---
- // Lazy-loaded by live.js when the user clicks Go; exposes
- // window.modernScreenshot.domToBlob(...) for capture.
- if (p === '/modern-screenshot.js') {
- const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
- try {
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'public, max-age=31536000, immutable',
- });
- res.end(fs.readFileSync(vendorPath));
- } catch {
- res.writeHead(404); res.end('Vendor script not found');
- }
- return;
- }
-
- // --- Annotation upload (browser → server, raw PNG body) ---
- // Client generates the eventId, POSTs the PNG, then POSTs the generate
- // event with screenshotPath already set. Keeps bytes out of the SSE/poll
- // bridge and preserves the "one shot from the user's POV" UX.
- if (p === '/annotation' && req.method === 'POST') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const eventId = url.searchParams.get('eventId');
- if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid eventId' }));
- return;
- }
- if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
- res.writeHead(415, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
- return;
- }
- if (!state.sessionDir) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Session dir unavailable' }));
- return;
- }
- const chunks = [];
- let total = 0;
- let aborted = false;
- req.on('data', (c) => {
- if (aborted) return;
- total += c.length;
- if (total > MAX_ANNOTATION_BYTES) {
- aborted = true;
- res.writeHead(413, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Payload too large' }));
- req.destroy();
- return;
- }
- chunks.push(c);
- });
- req.on('end', () => {
- if (aborted) return;
- const absPath = path.join(state.sessionDir, eventId + '.png');
- try {
- fs.writeFileSync(absPath, Buffer.concat(chunks));
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Write failed: ' + err.message }));
- return;
- }
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true, path: absPath }));
- });
- req.on('error', () => {
- if (!aborted) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Upload failed' }));
- }
- });
- return;
- }
-
- // --- Health ---
- if (p === '/status') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
- const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok',
- port: state.port,
- connectedClients: state.sseClients.size,
- pendingEvents: state.pendingEvents.map((entry) => ({
- id: entry.event?.id,
- type: entry.event?.type,
- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),
- leaseUntil: entry.leaseUntil || null,
- })),
- activeSessions: sessions,
- }));
- return;
- }
-
- if (p === '/health') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok', port: state.port, mode: 'variant',
- hasProjectContext: hasProjectContext(),
- connectedClients: state.sseClients.size,
- }));
- return;
- }
-
- // --- Design system (unified v2 response) + raw ---
- // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json
- // sidecar when present. Panel merges them:
- // { present, parsed, sidecar, hasMd, hasSidecar,
- // mdNewerThanJson, parseError?, sidecarError? }
- // - parsed: output of parseDesignMd (frontmatter
- // + six canonical sections) when DESIGN.md exists.
- // - sidecar: .impeccable/design.json contents when present.
- // Expected shape: schemaVersion 2, carrying
- // extensions + components + narrative.
- // /design-system/raw returns DESIGN.md markdown verbatim
- if (p === '/design-system.json' || p === '/design-system/raw') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
-
- const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
- const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
- const mdStat = statOrNull(mdPath);
- const jsonStat = statOrNull(jsonPath);
-
- if (p === '/design-system/raw') {
- if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
- res.end(fs.readFileSync(mdPath, 'utf-8'));
- return;
- }
-
- if (!mdStat && !jsonStat) {
- res.writeHead(404, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ present: false }));
- return;
- }
-
- const response = {
- present: true,
- hasMd: !!mdStat,
- hasSidecar: !!jsonStat,
- mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
- };
-
- if (mdStat) {
- try {
- response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
- } catch (err) {
- response.parseError = err.message;
- }
- }
-
- if (jsonStat) {
- try {
- response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
- } catch (err) {
- response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;
- }
- }
-
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(response));
- return;
- }
-
- // --- Source file (no-HMR fallback) ---
- if (p === '/source') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const filePath = url.searchParams.get('path');
- if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
- const absPath = path.resolve(process.cwd(), filePath);
- if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
- let content;
- try { content = fs.readFileSync(absPath, 'utf-8'); }
- catch { res.writeHead(404); res.end('File not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
- res.end(content);
- return;
- }
-
- // --- SSE: server→browser push (replaces WebSocket) ---
- if (p === '/events' && req.method === 'GET') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- 'Connection': 'keep-alive',
- });
- res.write('data: ' + JSON.stringify({
- type: 'connected',
- hasProjectContext: hasProjectContext(),
- }) + '\n\n');
-
- state.sseClients.add(res);
- clearTimeout(state.exitTimer);
-
- // Keepalive: SSE comment every 30s prevents silent connection drops.
- const heartbeat = setInterval(() => {
- try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
- }, SSE_HEARTBEAT_INTERVAL);
-
- req.on('close', () => {
- clearInterval(heartbeat);
- state.sseClients.delete(res);
- if (state.sseClients.size === 0) {
- clearTimeout(state.exitTimer);
- state.exitTimer = setTimeout(() => {
- if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
- }, 8000);
- }
- });
- return;
- }
-
- // --- Browser→server events (replaces WebSocket messages) ---
- if (p === '/events' && req.method === 'POST') {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const error = validateEvent(msg);
- if (error) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error }));
- return;
- }
- if (state.sessionStore && msg.id) {
- try {
- state.sessionStore.appendEvent(msg);
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
- return;
- }
- }
- if (msg.type !== 'checkpoint') enqueueEvent(msg);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
- return;
- }
-
- // --- Stop ---
- if (p === '/stop') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.end('stopping');
- shutdown();
- return;
- }
-
- // --- Agent poll ---
- if (p === '/poll' && req.method === 'GET') {
- handlePollGet(req, res, url);
- return;
- }
- if (p === '/poll' && req.method === 'POST') {
- handlePollPost(req, res);
- return;
- }
-
- res.writeHead(404); res.end('Not found');
- };
-}
-
-// ---------------------------------------------------------------------------
-// Agent poll endpoints (unchanged from WS version)
-// ---------------------------------------------------------------------------
-
-function handlePollGet(req, res, url) {
- const token = url.searchParams.get('token');
- if (token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
- const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
- const available = findAvailablePendingEvent();
- if (available) {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(leaseEvent(available, leaseMs)));
- return;
- }
- const poll = { resolve, leaseMs };
- const timer = setTimeout(() => {
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ type: 'timeout' }));
- }, timeout);
- function resolve(event) {
- clearTimeout(timer);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(event));
- }
- state.pendingPolls.push(poll);
- scheduleLeaseFlush();
- req.on('close', () => {
- clearTimeout(timer);
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- });
-}
-
-function handlePollPost(req, res) {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- acknowledgePendingEvent(msg.id);
- if (state.sessionStore && msg.id) {
- try {
- const eventType = msg.type === 'discard' || msg.type === 'discarded'
- ? 'discarded'
- : msg.type === 'complete'
- ? 'complete'
- : msg.type === 'error'
- ? 'agent_error'
- : 'agent_done';
- state.sessionStore.appendEvent({
- type: eventType,
- id: msg.id,
- file: msg.file,
- message: msg.message,
- carbonize: msg.data?.carbonize === true,
- });
- } catch { /* keep reply path best-effort; browser still needs SSE */ }
- }
- flushPendingPolls();
- // Forward the reply to the browser via SSE
- broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Lifecycle
-// ---------------------------------------------------------------------------
-
-let httpServer = null;
-
-function shutdown() {
- removeLiveServerInfo(process.cwd());
- if (state.leaseTimer) clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- if (state.sessionDir) {
- try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}
- }
- for (const res of state.sseClients) { try { res.end(); } catch {} }
- state.sseClients.clear();
- for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });
- state.pendingPolls.length = 0;
- if (httpServer) httpServer.close();
- process.exit(0);
-}
-
-// ---------------------------------------------------------------------------
-// Main
-// ---------------------------------------------------------------------------
-
-const args = process.argv.slice(2);
-
-if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-server.mjs [options]
-
-Start the live variant mode server (zero dependencies).
-
-Commands:
- (default) Start the server (foreground)
- stop Stop the server and remove the injected live.js script tag
- stop --keep-inject Stop the server only (leave the script tag in the HTML entry)
-
-Options:
- --background Start detached, print connection JSON to stdout, then exit
- --port=PORT Use a specific port (default: auto-detect starting at 8400)
- --keep-inject Only with stop: skip live-inject.mjs --remove
- --help Show this help
-
-Endpoints:
- /live.js Browser script (element picker + variant cycling)
- /detect.js Detection overlay (backwards compatible)
- /modern-screenshot.js Vendored modern-screenshot UMD build (lazy-loaded by live.js)
- /annotation POST raw image/png to stage a variant screenshot
- /events SSE stream (server→browser) + POST (browser→server)
- /poll Long-poll for agent CLI
- /source Raw source file reader (no-HMR fallback)
- /status Durable recovery status (token-protected)
- /health Health check`);
- process.exit(0);
-}
-
-if (args.includes('stop')) {
- const keepInject = args.includes('--keep-inject');
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);
- if (res.ok) console.log(`Stopped live server on port ${info.port}.`);
- } catch {
- console.log('No running live server found.');
- }
- if (!keepInject) {
- const injectPath = path.join(__dirname, 'live-inject.mjs');
- try {
- const out = execFileSync(process.execPath, [injectPath, '--remove'], {
- encoding: 'utf-8',
- cwd: process.cwd(),
- });
- const line = out.trim().split('\n').filter(Boolean).pop();
- if (line) {
- try {
- const j = JSON.parse(line);
- if (j.removed === true) {
- console.log(`Removed live script tag from ${j.file}.`);
- }
- } catch {
- /* ignore non-JSON lines */
- }
- }
- } catch (err) {
- const detail = err.stderr?.toString?.().trim?.()
- || err.stdout?.toString?.().trim?.()
- || err.message
- || String(err);
- console.warn(`Note: could not remove live script tag (${detail.split('\n')[0]})`);
- }
- }
- process.exit(0);
-}
-
-// --background: spawn a detached child server, wait for it to be ready,
-// print the connection JSON, then exit. This keeps the startup command
-// simple (no shell backgrounding or chained commands).
-if (args.includes('--background')) {
- const childArgs = args.filter(a => a !== '--background');
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), ...childArgs], {
- detached: true,
- stdio: 'ignore',
- cwd: process.cwd(),
- });
- child.unref();
-
- // Poll for the PID file (the child writes it once the HTTP server is listening).
- const deadline = Date.now() + 10_000;
- while (Date.now() < deadline) {
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- if (info.pid !== process.pid) {
- // Output JSON so the agent can read port + token from stdout.
- console.log(JSON.stringify(info));
- process.exit(0);
- }
- } catch { /* not ready yet */ }
- await new Promise(r => setTimeout(r, 200));
- }
- console.error('Timed out waiting for live server to start.');
- process.exit(1);
-}
-
-// Check for existing session
-const existingRecord = readLiveServerInfo(process.cwd());
-if (existingRecord?.info) {
- const existing = existingRecord.info;
- try {
- process.kill(existing.pid, 0);
- console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
- console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');
- process.exit(1);
- } catch {
- try { fs.unlinkSync(existingRecord.path); } catch {}
- }
-}
-
-state.token = randomUUID();
-state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });
-restorePendingEventsFromStore();
-const portArg = args.find(a => a.startsWith('--port='));
-state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
-// Annotation screenshots live in the project root so the agent's Read tool
-// doesn't trip a per-file permission prompt. Sessioned by token so concurrent
-// projects (or quick restarts) don't collide.
-const annotRoot = getLiveAnnotationsDir(process.cwd());
-fs.mkdirSync(annotRoot, { recursive: true });
-state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));
-
-const { detectScript, sessionPath, livePath } = loadBrowserScripts();
-httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));
-
-httpServer.listen(state.port, '127.0.0.1', () => {
- writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });
- const url = `http://localhost:${state.port}`;
- console.log(`\nImpeccable live server running on ${url}`);
- console.log(`Token: ${state.token}\n`);
- console.log(`Inject: <script src="${url}/live.js"><\/script>`);
- console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
-});
-
-process.on('SIGINT', shutdown);
-process.on('SIGTERM', shutdown);
@@ -1,254 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';
-
-const COMPLETED_PHASES = new Set(['completed', 'discarded']);
-
-export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {
- const rootDir = getLiveSessionsDir(cwd);
- const legacyRootDir = getLegacyLiveSessionsDir(cwd);
- fs.mkdirSync(rootDir, { recursive: true });
- const snapshotCache = new Map();
-
- function loadCachedOrRebuild(id) {
- const cached = snapshotCache.get(id);
- if (cached) return cached;
- const journalPath = getReadableJournalPath(id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- return rebuilt;
- }
-
- function getReadableJournalPath(id) {
- const primary = getJournalPath(rootDir, id);
- if (fs.existsSync(primary)) return primary;
- const legacy = getJournalPath(legacyRootDir, id);
- if (fs.existsSync(legacy)) return legacy;
- return primary;
- }
-
- return {
- rootDir,
- legacyRootDir,
- appendEvent(event) {
- const normalized = normalizeEvent(event, sessionId);
- const journalPath = getJournalPath(rootDir, normalized.id);
- const snapshotPath = getSnapshotPath(rootDir, normalized.id);
- const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);
- if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {
- fs.copyFileSync(legacyJournalPath, journalPath);
- }
- const prior = loadCachedOrRebuild(normalized.id);
- const seq = prior.nextSeq;
- const entry = {
- seq,
- id: normalized.id,
- type: normalized.type,
- ts: new Date().toISOString(),
- event: normalized,
- };
- fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');
- const next = applyEvent(prior.snapshot, entry, prior.diagnostics);
- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });
- writeSnapshot(snapshotPath, next);
- return next;
- },
- getSnapshot(id = sessionId, opts = {}) {
- if (!id) throw new Error('session id required');
- const journalPath = getReadableJournalPath(id);
- const snapshotPath = getSnapshotPath(rootDir, id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- writeSnapshot(snapshotPath, rebuilt.snapshot);
- if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;
- return rebuilt.snapshot;
- },
- listActiveSessions() {
- const ids = new Set();
- for (const dir of [legacyRootDir, rootDir]) {
- if (!fs.existsSync(dir)) continue;
- for (const name of fs.readdirSync(dir)) {
- if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));
- }
- }
- return [...ids]
- .sort()
- .map((id) => this.getSnapshot(id))
- .filter(Boolean);
- },
- };
-}
-
-function normalizeEvent(event, fallbackId) {
- if (!event || typeof event !== 'object') throw new Error('event object required');
- const id = event.id || fallbackId;
- if (!id || typeof id !== 'string') throw new Error('event id required');
- if (!event.type || typeof event.type !== 'string') throw new Error('event type required');
- return { ...event, id };
-}
-
-function getJournalPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.jsonl');
-}
-
-function getSnapshotPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.snapshot.json');
-}
-
-function safeSessionId(id) {
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);
- return id;
-}
-
-function baseSnapshot(id) {
- return {
- id,
- phase: 'new',
- pageUrl: null,
- sourceFile: null,
- expectedVariants: 0,
- arrivedVariants: 0,
- visibleVariant: null,
- paramValues: {},
- pendingEventSeq: null,
- pendingEvent: null,
- deliveryLease: null,
- checkpointRevision: 0,
- activeOwner: null,
- sourceMarkers: {},
- fallbackMode: null,
- annotationArtifacts: [],
- diagnostics: [],
- updatedAt: null,
- };
-}
-
-function rebuildSnapshotFromJournal(journalPath, id) {
- let snapshot = baseSnapshot(id);
- const diagnostics = [];
- let nextSeq = 1;
- if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };
-
- const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- if (!line.trim()) continue;
- try {
- const entry = JSON.parse(line);
- if (!entry || typeof entry !== 'object') throw new Error('entry is not object');
- if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);
- snapshot = applyEvent(snapshot, entry);
- } catch (err) {
- diagnostics.push({
- error: 'journal_parse_failed',
- line: i + 1,
- message: err.message,
- });
- }
- }
- snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];
- return { snapshot, diagnostics, nextSeq };
-}
-
-function applyEvent(snapshot, entry, inheritedDiagnostics = []) {
- const event = entry.event || entry;
- const next = {
- ...snapshot,
- paramValues: { ...(snapshot.paramValues || {}) },
- sourceMarkers: { ...(snapshot.sourceMarkers || {}) },
- annotationArtifacts: [...(snapshot.annotationArtifacts || [])],
- diagnostics: [...(snapshot.diagnostics || [])],
- updatedAt: entry.ts || new Date().toISOString(),
- };
-
- if (inheritedDiagnostics.length && next.diagnostics.length === 0) {
- next.diagnostics = [...inheritedDiagnostics];
- }
-
- switch (event.type) {
- case 'generate':
- next.phase = 'generate_requested';
- next.pageUrl = event.pageUrl ?? next.pageUrl;
- next.expectedVariants = event.count ?? next.expectedVariants;
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });
- break;
- case 'variants_ready':
- case 'agent_done':
- next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';
- next.sourceFile = event.file ?? next.sourceFile;
- next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- if (event.carbonize === true) {
- next.diagnostics.push({
- error: 'carbonize_cleanup_required',
- file: event.file || null,
- message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',
- });
- }
- break;
- case 'checkpoint':
- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {
- next.phase = event.phase ?? next.phase;
- next.checkpointRevision = event.revision ?? next.checkpointRevision;
- next.activeOwner = event.owner ?? next.activeOwner;
- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;
- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- } else {
- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });
- }
- break;
- case 'accept':
- case 'accept_intent':
- next.phase = 'accept_requested';
- next.visibleVariant = Number(event.variantId ?? next.visibleVariant);
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discard':
- next.phase = 'discard_requested';
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discarded':
- next.phase = 'discarded';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'complete':
- next.phase = 'completed';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'agent_error':
- next.phase = 'agent_error';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });
- break;
- default:
- next.diagnostics.push({ error: 'unknown_event_type', type: event.type });
- break;
- }
- return next;
-}
-
-function toPendingEvent(event) {
- const pending = { ...event };
- delete pending.token;
- return pending;
-}
-
-function upsertArtifact(artifacts, artifact) {
- if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {
- artifacts.push(artifact);
- }
-}
-
-function writeSnapshot(snapshotPath, snapshot) {
- fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');
-}
@@ -1,47 +0,0 @@
-#!/usr/bin/env node
-/**
- * Print durable recovery status for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function fetchServerStatus(info) {
- if (!info) return null;
- try {
- const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-export async function statusCli() {
- const info = readServerInfo();
- const server = await fetchServerStatus(info);
- const store = createLiveSessionStore({ cwd: process.cwd() });
- const activeSessions = store.listActiveSessions();
- const payload = {
- liveServer: server ? {
- status: server.status,
- port: server.port,
- connectedClients: server.connectedClients,
- pendingEvents: server.pendingEvents,
- } : null,
- activeSessions: server?.activeSessions || activeSessions,
- recoveryHint: server
- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'
- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',
- };
- console.log(JSON.stringify(payload, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {
- statusCli();
-}
@@ -1,632 +0,0 @@
-/**
- * CLI helper: find an element in source and wrap it in a variant container.
- *
- * Usage:
- * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
- *
- * Searches project files for the element matching the query (class name, ID, or
- * text snippet), wraps it with the variant scaffolding, and prints the file path
- * + line range where the agent should insert variant HTML.
- *
- * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-export async function wrapCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable wrap [options]
-
-Find an element in source and wrap it in a variant container.
-
-Required:
- --id ID Session ID for the variant wrapper
- --count N Number of expected variants (1-8)
-
-Element identification (at least one required):
- --element-id ID HTML id attribute of the element
- --classes A,B,C Comma-separated CSS class names
- --tag TAG Tag name (div, section, etc.)
- --query TEXT Fallback: raw text to search for
-
-Optional:
- --file PATH Source file to search in (skips auto-detection)
- --text TEXT Picked element's textContent. Used to disambiguate when
- classes/tag match multiple sibling elements (e.g. a list
- of <Card>s with the same className). Pass the first ~80
- chars of event.element.textContent.
- --help Show this help message
-
-Output (JSON):
- { file, startLine, endLine, insertLine, commentSyntax }
-
-The agent should insert variant HTML at insertLine.`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const count = parseInt(argVal(args, '--count') || '3');
- const elementId = argVal(args, '--element-id');
- const classes = argVal(args, '--classes');
- const tag = argVal(args, '--tag');
- const query = argVal(args, '--query');
- const filePath = argVal(args, '--file');
- const text = argVal(args, '--text');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!elementId && !classes && !query) {
- console.error('Need at least one of: --element-id, --classes, --query');
- process.exit(1);
- }
-
- // Build search queries in priority order (most specific first)
- const queries = buildSearchQueries(elementId, classes, tag, query);
-
- const genOpts = { cwd: process.cwd() };
-
- // Find the source file. Generated files are excluded from auto-search so we
- // don't silently write variants into a file the next build will wipe.
- let targetFile = filePath;
- let matchedQuery = null;
- if (!targetFile) {
- for (const q of queries) {
- targetFile = findFileWithQuery(q, process.cwd(), genOpts);
- if (targetFile) { matchedQuery = q; break; }
- }
- if (!targetFile) {
- // Nothing in source. Did the element show up in a generated file? That
- // tells the agent "fall back to the agent-driven flow" vs "element just
- // doesn't exist in this project."
- let generatedHit = null;
- for (const q of queries) {
- generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
- if (generatedHit) break;
- }
- if (generatedHit) {
- console.error(JSON.stringify({
- error: 'element_not_in_source',
- fallback: 'agent-driven',
- generatedMatch: path.relative(process.cwd(), generatedHit),
- hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
- }));
- } else {
- console.error(JSON.stringify({
- error: 'element_not_found',
- fallback: 'agent-driven',
- hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
- }));
- }
- process.exit(1);
- }
- } else {
- if (isGeneratedFile(targetFile, genOpts)) {
- console.error(JSON.stringify({
- error: 'file_is_generated',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
- hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- matchedQuery = queries[0];
- }
-
- const content = fs.readFileSync(targetFile, 'utf-8');
- const lines = content.split('\n');
-
- // Find the element, trying each query in priority order. When `--text` is
- // supplied, collect every candidate the queries surface and disambiguate
- // by the picked element's textContent. Without `--text`, fall back to the
- // legacy first-match behavior so unmodified callers keep working.
- let match = null;
- if (text) {
- const candidates = [];
- for (const q of queries) {
- const all = findAllElements(lines, q, tag);
- for (const c of all) {
- if (!candidates.some((x) => x.startLine === c.startLine)) {
- candidates.push(c);
- }
- }
- // Once a more-specific query (ID, full className combo) yielded a unique
- // result, stop — falling through to the loose tag+single-class query
- // would readmit the siblings we just disambiguated past.
- if (candidates.length === 1) break;
- }
- if (candidates.length === 0) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- if (candidates.length === 1) {
- match = candidates[0];
- } else {
- const filtered = filterByText(candidates, lines, text);
- if (filtered.length === 1) {
- match = filtered[0];
- } else if (filtered.length === 0) {
- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the
- // browser-side textContent doesn't appear literally in source. Fall
- // back to first-match rather than refusing — this is the same
- // behavior unmodified callers see, just preserved.
- match = candidates[0];
- } else {
- // Multiple candidates ALSO match the text. Truly ambiguous — refuse
- // rather than pick wrong, and hand the agent the candidate locations
- // so it can disambiguate by reading the file.
- console.error(JSON.stringify({
- error: 'element_ambiguous',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), targetFile),
- candidates: filtered.map((c) => ({
- startLine: c.startLine + 1,
- endLine: c.endLine + 1,
- })),
- hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- }
- } else {
- for (const q of queries) {
- match = findElement(lines, q, tag);
- if (match) break;
- }
- if (!match) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- }
-
- const { startLine, endLine } = match;
- const commentSyntax = detectCommentSyntax(targetFile);
- const styleMode = detectStyleMode(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- const indent = lines[startLine].match(/^(\s*)/)[1];
-
- // Extract the original element. Reindent under the wrapper while preserving
- // the relative depth between lines — `l.trimStart()` would strip ALL leading
- // whitespace and collapse e.g. `<aside>`/` <h1>`/`</aside>` (6/8/6 spaces)
- // to a single uniform indent, so on accept/discard the round-trip restores
- // the inner element at its parent's depth instead of nested inside it.
- // Strip only the COMMON minimum leading whitespace across the picked lines;
- // `deindentContent` on the accept side already mirrors this convention.
- const originalLines = lines.slice(startLine, endLine + 1);
- const originalBaseIndent = minLeadingSpaces(originalLines);
- const reindentOriginal = (extra) => originalLines
- .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
- .join('\n');
- const originalIndented = reindentOriginal(' ');
-
- // Wrapper attributes differ by syntax. HTML allows plain string attrs;
- // JSX requires object-literal style and parses string attrs as HTML (which
- // either type-errors or renders a literal CSS string).
- const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
-
- // JSX/TSX guard: the picked element occupies a single JSX child slot
- // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
- // any other expression position). Replacing it with `comment + <div> +
- // comment` yields three adjacent siblings — invalid JSX. We can't use a
- // Fragment `<></>` either: parents that clone children (Radix `asChild`,
- // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
- // they try to pass an `id` through.
- //
- // Solution: keep the wrapper `<div>` as the single JSX-slot child and
- // tuck both marker comments INSIDE it. accept/discard then expands its
- // replacement range to include the wrapper's `<div>` open / close lines
- // so the entire scaffold gets removed cleanly.
- const wrapperLines = isJsx ? [
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- reindentOriginal(' '),
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- indent + '</div>',
- ] : [
- indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- originalIndented,
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + '</div>',
- indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- ];
-
- // Replace the original element with the wrapper
- const newLines = [
- ...lines.slice(0, startLine),
- ...wrapperLines,
- ...lines.slice(endLine + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- // Calculate insert line (the "insert below this line" comment).
- // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
- // the insert marker (HTML: start-comment + outer-div + Original-comment +
- // original-div + content + close-original-div; JSX: outer-div +
- // start-comment + Original-comment + original-div + content +
- // close-original-div). Multi-line originals push the marker by their
- // extra line count.
- const insertLine = startLine + 6 + (originalLines.length - 1);
-
- console.log(JSON.stringify({
- file: path.relative(process.cwd(), targetFile),
- startLine: startLine + 1, // 1-indexed for the agent
- // wrapperLines is an array but one element (the original-content slot)
- // is a `\n`-joined multi-line string, so the actual file-row count is
- // wrapperLines.length + (originalLines.length - 1). Without the offset,
- // endLine pointed inside the wrapper for any picked element that
- // spanned more than one source line.
- endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexed
- insertLine: insertLine + 1, // 1-indexed: where variants go
- commentSyntax: commentSyntax,
- styleMode: styleMode.mode,
- styleTag: styleMode.styleTag,
- cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
- cssAuthoring: buildCssAuthoring(styleMode, count),
- originalLineCount: originalLines.length,
- }));
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-/**
- * Build search query strings in priority order (most specific first).
- * ID is most reliable, then specific class combos, then single classes, then raw query.
- */
-function buildSearchQueries(elementId, classes, tag, query) {
- const queries = [];
-
- // 1. ID is the most specific
- if (elementId) {
- queries.push('id="' + elementId + '"');
- }
-
- // 2. Full class attribute match (for elements with distinctive multi-class combos).
- // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
- // convention the file uses will match.
- if (classes) {
- const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
- if (classList.length > 1) {
- const joined = classList.join(' ');
- const sorted = [...classList].sort((a, b) => b.length - a.length);
- queries.push('class="' + joined + '"');
- queries.push('className="' + joined + '"');
- queries.push(sorted[0]); // most distinctive single class, fallback
- } else if (classList.length === 1) {
- queries.push(classList[0]);
- }
- }
-
- // 3. Tag + class combo (e.g., <section class="hero">).
- // Same dual-emit for JSX compatibility.
- if (tag && classes) {
- const firstClass = classes.split(',')[0].trim();
- queries.push('<' + tag + ' class="' + firstClass);
- queries.push('<' + tag + ' className="' + firstClass);
- }
-
- // 4. Raw fallback query
- if (query) {
- queries.push(query);
- }
-
- return queries;
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- // HTML, Vue, Svelte, Astro all use HTML comments
- return { open: '<!--', close: '-->' };
-}
-
-function detectStyleMode(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.astro') {
- return {
- mode: 'astro-global-prefixed',
- styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',
- };
- }
- return {
- mode: 'scoped',
- styleTag: '<style data-impeccable-css="SESSION_ID">',
- };
-}
-
-function buildCssSelectorPrefixExamples(styleMode, count) {
- if (styleMode !== 'astro-global-prefixed') return [];
- return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);
-}
-
-function buildCssAuthoring(styleMode, count) {
- const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
- if (styleMode.mode === 'astro-global-prefixed') {
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'global-prefixed',
- rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',
- selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),
- requirements: [
- 'Use the styleTag exactly; the is:inline attribute is required for this file.',
- 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',
- 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
- ],
- forbidden: [
- 'Do not use @scope for this styleMode.',
- ],
- };
- }
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'scope-rule',
- rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',
- selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),
- requirements: [
- 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',
- 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
- 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
- ],
- forbidden: [
- 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',
- 'Do not add is:inline to the style tag for this styleMode.',
- ],
- };
-}
-
-/**
- * Search project files for the query string (class name, ID, etc.)
- * Returns the first matching file path, or null.
- */
-function findFileWithQuery(query, cwd, genOpts = {}) {
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, query, seen, 0, genOpts);
- if (result) return result;
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth, genOpts) {
- if (depth > 5) return null; // don't go too deep
- const realDir = fs.realpathSync(dir);
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- // Check files first
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name).toLowerCase();
- if (!EXTENSIONS.includes(ext)) continue;
-
- const filePath = path.join(dir, entry.name);
- if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip unreadable files */ }
- }
-
- // Then recurse into directories. Always skip node_modules and .git (never
- // project content). dist/build/out are left to the isGeneratedFile guard so
- // the includeGenerated second-pass can still find the element there and
- // report `generatedMatch`.
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
- if (result) return result;
- }
-
- return null;
-}
-
-/**
- * Regex that matches a tag opener on a line. Allows the tag name to be
- * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
- * openers (e.g. `<section\n className="..."\n>`) are recognised.
- */
-const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
-
-/**
- * Find the element's start and end line in the file.
- *
- * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
- * `id="..."`), or a raw text snippet. Because a query can appear on a
- * continuation line of a multi-line tag (e.g. the `className="..."` row of a
- * `<section\n className="..."\n>` JSX tag), we walk backward from the match
- * line to find the actual tag opener. When `tag` is provided, opener candidates
- * must match that tag name.
- */
-/**
- * Return the smallest leading-whitespace count across a set of lines,
- * ignoring blank lines (whose indent isn't load-bearing). Used to compute
- * the common base indent of a multi-line picked element so reindenting
- * under the wrapper preserves the relative depth between lines.
- */
-function minLeadingSpaces(lines) {
- let min = Infinity;
- for (const l of lines) {
- if (l.trim() === '') continue;
- const m = l.match(/^(\s*)/);
- if (m && m[1].length < min) min = m[1].length;
- }
- return min === Infinity ? 0 : min;
-}
-
-function findElement(lines, query, tag = null) {
- // Iterate all matches — the first substring hit isn't always the right one.
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
-
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- // Skip lines already inside a variant wrapper
- if (lines[i].includes('data-impeccable-variant')) continue;
-
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
-
- const endLine = findClosingLine(lines, openerLine);
- return { startLine: openerLine, endLine };
- }
-
- return null;
-}
-
-/**
- * Like findElement, but returns every match. Used for ambiguity detection
- * when the agent passes --text: when the same className appears on multiple
- * sibling elements (a list of cards, repeated section variants, etc.),
- * first-match silently lands on the wrong branch. Returning all matches lets
- * the caller narrow by textContent or fail with a structured ambiguity error.
- */
-function findAllElements(lines, query, tag = null) {
- const out = [];
- const seen = new Set();
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- if (lines[i].includes('data-impeccable-variant')) continue;
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
- if (seen.has(openerLine)) continue; // multiple matches inside the same element
- seen.add(openerLine);
- const endLine = findClosingLine(lines, openerLine);
- out.push({ startLine: openerLine, endLine });
- }
- return out;
-}
-
-/**
- * Narrow a candidate set to those whose source body matches a meaningful
- * prefix of the picked element's textContent. The compare strips tags and
- * JSX expressions, then checks two whitespace normalizations side-by-side:
- *
- * - single-space ("hero two second card body")
- * - no-whitespace ("herotwosecondcardbody")
- *
- * Both are needed because `el.textContent` concatenates sibling text without
- * inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
- * `"Hero TwoSecond…"`), while the source has whitespace between tags. If
- * EITHER normalization matches, the candidate keeps. A snippet shorter than
- * 8 chars after stripping is too weak to disambiguate — the caller falls
- * back to first-match.
- */
-function filterByText(candidates, lines, text) {
- const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
- // Too short to disambiguate. Return [] so the caller's `filtered.length
- // === 0` branch fires (fall back to first-match) — the previous
- // `candidates.slice()` return forced `filtered.length > 1` and surfaced
- // a spurious `element_ambiguous` error on every short-text picker event
- // with multiple candidates.
- if (trimmed.length < 8) return [];
- const targetSpaced = trimmed;
- const targetCompact = trimmed.replace(/\s+/g, '');
-
- return candidates.filter((c) => {
- const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
- const inner = body
- .replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
- .replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
- .toLowerCase();
- const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
- const sourceCompact = inner.replace(/\s+/g, '');
- return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
- });
-}
-
-/**
- * Resolve a match line to the real tag opener. If the match line itself opens
- * a tag, return it. Otherwise walk up to 10 lines backward looking for the
- * first tag opener. If `tag` is specified, the opener must match that tag
- * name; an opener with a different tag name aborts the backward walk for this
- * match (we don't jump across element boundaries).
- *
- * Returns the line index of the opener, or -1 if none can be resolved.
- */
-function findOpenerLine(lines, matchLine, tag) {
- const self = lines[matchLine].match(OPENER_RE);
- if (self) {
- if (!tag || self[1] === tag) return matchLine;
- return -1;
- }
- const MAX_BACKWALK = 10;
- for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
- const opener = lines[i].match(OPENER_RE);
- if (!opener) continue;
- if (!tag || opener[1] === tag) return i;
- // Different tag name than requested — abort; we're inside a non-target opener.
- return -1;
- }
- return -1;
-}
-
-/**
- * Starting from a line with an opening tag, find the line with the matching
- * closing tag by counting tag nesting depth.
- */
-function findClosingLine(lines, start) {
- const openMatch = lines[start].match(OPENER_RE);
- if (!openMatch) return start; // caller passed a non-opener; nothing to span
-
- const tagName = openMatch[1];
- let depth = 0;
- const openRe = new RegExp('<' + tagName + '(?=[\\s/>]|$)', 'g');
- const selfCloseRe = new RegExp('<' + tagName + '[^>]*/>', 'g');
- const closeRe = new RegExp('</' + tagName + '\\s*>', 'g');
-
- for (let i = start; i < lines.length; i++) {
- const line = lines[i];
- const opens = (line.match(openRe) || []).length;
- const selfCloses = (line.match(selfCloseRe) || []).length;
- const closes = (line.match(closeRe) || []).length;
-
- depth += opens - selfCloses - closes;
-
- if (depth <= 0) return i;
- }
-
- // If we can't find the close, return a reasonable guess
- return Math.min(start + 50, lines.length - 1);
-}
-
-// Auto-execute when run directly (node live-wrap.mjs ...)
-const _running = process.argv[1];
-if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {
- wrapCli();
-}
-
-// Test exports (used by tests/live-wrap.test.mjs)
-export { buildSearchQueries, findElement, findClosingLine, detectCommentSyntax };
@@ -1,247 +0,0 @@
-/**
- * CLI entry point: prepare everything needed to enter the live variant poll loop.
- *
- * Does (all in one command):
- * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)
- * 2. Start the live server in the background (or reuse a running one)
- * 3. Inject the browser script tag into the project's entry file
- * 4. Read PRODUCT.md / DESIGN.md for project context
- * 5. Print a single JSON blob with everything the agent needs
- *
- * After this, the agent's only remaining steps are:
- * - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll
- * - Enter the poll loop: `node live-poll.mjs`
- *
- * Usage:
- * node live.mjs # Prepare everything, print JSON, exit
- * node live.mjs --help
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { loadContext } from './load-context.mjs';
-import { resolveFiles } from './live-inject.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-async function liveCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live.mjs
-
-Prepare everything for live variant mode in a single command:
- - Checks .impeccable/live/config.json (required, created once per project)
- - Starts (or reuses) the live server in the background
- - Injects the browser script tag
- - Reads PRODUCT.md / DESIGN.md for project context
-
-On success, prints a JSON blob with:
- { ok, serverPort, serverToken, pageFile, hasContext, context }
-
-On config_missing, prints:
- { ok: false, error: "config_missing", configPath, hint }
-
-The agent should then:
- 1. If config_missing, create the config and re-run this script
- 2. Optionally open the project's dev/preview URL in the browser (see reference/live.md—not serverPort)
- 3. Enter the poll loop: node live-poll.mjs`);
- process.exit(0);
- }
-
- // 1. Check config (fail fast if missing — no point starting anything else)
- const checkOut = runScript('live-inject.mjs', ['--check']);
- const checkResult = safeParse(checkOut);
- if (!checkResult || !checkResult.ok) {
- console.log(JSON.stringify(checkResult || { ok: false, error: 'check_failed', raw: checkOut }));
- process.exit(0);
- }
-
- // 2. Start server (or reuse existing)
- const serverInfo = ensureServerRunning();
- if (!serverInfo) {
- console.log(JSON.stringify({ ok: false, error: 'server_start_failed' }));
- process.exit(1);
- }
-
- // 3. Inject the script tag at the current port
- const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)]);
- const injectResult = safeParse(injectOut);
- if (!injectResult || !injectResult.ok) {
- console.log(JSON.stringify({
- ok: false,
- error: 'inject_failed',
- detail: injectResult || injectOut,
- serverPort: serverInfo.port,
- }));
- process.exit(1);
- }
-
- // 4. Load PRODUCT.md + DESIGN.md context (auto-migrates legacy .impeccable.md)
- const ctx = loadContext(process.cwd());
-
- // 5. Compute drift-heal: compare resolved inject targets against the
- // project's HTML files. Orphans are HTML files not covered by config.
- // Warning only — the agent decides whether to act.
- const resolvedFiles = resolveFiles(process.cwd(), checkResult.config);
- const drift = scanForDrift(process.cwd(), resolvedFiles, checkResult.config);
-
- // 6. Emit everything the agent needs
- console.log(JSON.stringify({
- ok: true,
- serverPort: serverInfo.port,
- serverToken: serverInfo.token,
- pageFiles: resolvedFiles,
- configDrift: drift,
- hasProduct: ctx.hasProduct,
- product: ctx.product,
- productPath: ctx.productPath,
- hasDesign: ctx.hasDesign,
- design: ctx.design,
- designPath: ctx.designPath,
- migrated: ctx.migrated,
- }, null, 2));
-}
-
-/**
- * Drift-heal scan. Walks the project for HTML files under common
- * page-source directories (public/, src/, app/, pages/) and reports any
- * that aren't covered by the resolved inject targets. This is purely
- * advisory — the agent can ignore it, or suggest the user add the
- * orphans to config.files.
- *
- * Skipped if config.files already contains at least one glob pattern
- * covering everything in practice (signaled by the orphan count being 0).
- */
-function scanForDrift(rootDir, resolvedFiles, config) {
- const SCAN_ROOTS = ['public', 'src', 'app', 'pages'];
- const IGNORE_DIRS = new Set([
- 'node_modules', '.git', '.next', '.nuxt', '.svelte-kit', '.astro',
- '.turbo', '.vercel', '.cache', 'coverage', 'dist', 'build',
- ]);
-
- const resolvedSet = new Set(resolvedFiles.map((f) => f.split(path.sep).join('/')));
-
- // Files matching the user's `exclude` globs are intentional omissions,
- // not drift. Compile them to regexes so the orphan list stays signal.
- const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
- .map((p) => globToRegex(p));
- const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
-
- const orphans = [];
-
- const walk = (dir, relBase) => {
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
- for (const e of entries) {
- const rel = relBase ? `${relBase}/${e.name}` : e.name;
- if (e.isDirectory()) {
- if (IGNORE_DIRS.has(e.name) || e.name.startsWith('.')) continue;
- walk(path.join(dir, e.name), rel);
- } else if (e.isFile() && e.name.endsWith('.html')) {
- if (resolvedSet.has(rel)) continue;
- if (isUserExcluded(rel)) continue;
- orphans.push(rel);
- }
- }
- };
-
- for (const root of SCAN_ROOTS) {
- const abs = path.join(rootDir, root);
- if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
- walk(abs, root);
- }
- }
-
- if (orphans.length === 0) return null;
- const capped = orphans.slice(0, 20);
- return {
- orphans: capped,
- orphanCount: orphans.length,
- hint: `${orphans.length} HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like "public/**/*.html".`,
- };
-}
-
-/**
- * Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
- * to avoid a circular import (live-inject.mjs already imports nothing
- * from live.mjs). The two must stay in sync.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
- else { re += '.*'; i += 2; }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function runScript(name, args) {
- const scriptPath = path.join(__dirname, name);
- const cmd = `node "${scriptPath}" ${args.map(a => `"${a}"`).join(' ')}`;
- try {
- return execSync(cmd, { encoding: 'utf-8', cwd: process.cwd(), timeout: 15_000 });
- } catch (err) {
- // execSync throws on non-zero exit; return stdout if any
- return err.stdout || err.message || '';
- }
-}
-
-function safeParse(out) {
- try { return JSON.parse(String(out).trim()); } catch { return null; }
-}
-
-/**
- * Return { pid, port, token } for the running live server, starting one if needed.
- */
-function ensureServerRunning() {
- // Try to reuse an existing server
- try {
- const existing = readLiveServerInfo(process.cwd())?.info;
- if (existing && existing.pid) {
- try {
- process.kill(existing.pid, 0); // throws if dead
- return existing;
- } catch { /* stale PID file — the server script will clean it up */ }
- }
- } catch { /* no PID file */ }
-
- // Start a new server
- const out = runScript('live-server.mjs', ['--background']);
- return safeParse(out);
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live.mjs') || _running?.endsWith('live.mjs/')) {
- liveCli();
-}
@@ -1,141 +0,0 @@
-/**
- * Shared context loader for every impeccable command that needs to know
- * "who is this for" and "what does this look like".
- *
- * Input: project root (process.cwd()).
- *
- * Output (JSON to stdout):
- * {
- * hasProduct: boolean, // PRODUCT.md found (or auto-migrated)
- * product: string | null, // PRODUCT.md contents
- * productPath: string | null, // relative path
- * hasDesign: boolean, // DESIGN.md found
- * design: string | null, // DESIGN.md contents
- * designPath: string | null,
- * migrated: boolean, // true if we auto-renamed .impeccable.md -> PRODUCT.md
- * contextDir: string, // absolute path of the directory the files were found in
- * }
- *
- * Filename matching is case-insensitive for PRODUCT.md and DESIGN.md. The
- * Google DESIGN.md convention is uppercase at repo root; Kiro-style and
- * lowercase variants are also matched so users don't get punished for case.
- *
- * Lookup directory resolution (first match wins):
- * 1. process.env.IMPECCABLE_CONTEXT_DIR (absolute or relative to cwd)
- * 2. cwd, if PRODUCT.md / DESIGN.md / .impeccable.md is there (back-compat)
- * 3. Auto-fallback subdirectories of cwd: .agents/context/, then docs/
- * 4. cwd as a default "no context found" location
- *
- * Legacy `.impeccable.md` -> PRODUCT.md migration only fires at cwd root;
- * fallback directories are read-only as far as auto-rename is concerned.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
-const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
-const LEGACY_NAMES = ['.impeccable.md'];
-const FALLBACK_DIRS = ['.agents/context', 'docs'];
-
-/**
- * Resolve the directory that holds PRODUCT.md / DESIGN.md for
- * this project. Exported so other scripts (e.g. live-server.mjs) can read the
- * design files from the same location the loader uses.
- */
-export function resolveContextDir(cwd = process.cwd()) {
- // 1. Explicit override
- const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
- if (envDir && envDir.trim()) {
- const trimmed = envDir.trim();
- return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- }
-
- // 2. cwd wins if any canonical or legacy file is there. We check legacy too
- // so the auto-migration path in loadContext stays predictable.
- if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES, ...LEGACY_NAMES])) {
- return cwd;
- }
-
- // 3. Auto-fallback subdirs. Match if PRODUCT.md or DESIGN.md is present;
- // legacy `.impeccable.md` does not pull the lookup into a fallback dir.
- for (const rel of FALLBACK_DIRS) {
- const candidate = path.resolve(cwd, rel);
- if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
- return candidate;
- }
- }
-
- // 4. Nothing found — keep the historical "default to cwd" behaviour so the
- // caller's `hasProduct === false` branch still fires the same way.
- return cwd;
-}
-
-export function loadContext(cwd = process.cwd()) {
- let migrated = false;
- const contextDir = resolveContextDir(cwd);
-
- // 1. Look for PRODUCT.md (case-insensitive) in the resolved dir
- let productPath = firstExisting(contextDir, PRODUCT_NAMES);
-
- // 2. Legacy: if no PRODUCT.md but .impeccable.md exists at cwd root, rename
- // it in place. We only migrate at the root — fallback dirs are read-only
- // so we don't surprise users by mutating files under docs/ or .agents/.
- if (!productPath && contextDir === cwd) {
- const legacyPath = firstExisting(cwd, LEGACY_NAMES);
- if (legacyPath) {
- const newPath = path.join(cwd, 'PRODUCT.md');
- try {
- fs.renameSync(legacyPath, newPath);
- productPath = newPath;
- migrated = true;
- } catch {
- // Rename failed (permissions, etc.) — fall back to reading legacy in place
- productPath = legacyPath;
- }
- }
- }
-
- // 3. DESIGN.md (case-insensitive)
- const designPath = firstExisting(contextDir, DESIGN_NAMES);
-
- const product = productPath ? safeRead(productPath) : null;
- const design = designPath ? safeRead(designPath) : null;
-
- return {
- hasProduct: !!product,
- product,
- productPath: productPath ? path.relative(cwd, productPath) : null,
- hasDesign: !!design,
- design,
- designPath: designPath ? path.relative(cwd, designPath) : null,
- migrated,
- contextDir,
- };
-}
-
-function firstExisting(dir, names) {
- for (const name of names) {
- const abs = path.join(dir, name);
- if (fs.existsSync(abs)) return abs;
- }
- return null;
-}
-
-function safeRead(p) {
- try { return fs.readFileSync(p, 'utf-8'); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// CLI mode — print the context as JSON
-// ---------------------------------------------------------------------------
-
-function cli() {
- const result = loadContext(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('load-context.mjs') || _running?.endsWith('load-context.mjs/')) {
- cli();
-}
@@ -1,14 +0,0 @@
@@ -1,214 +0,0 @@
-#!/usr/bin/env node
-/**
- * Pin/unpin sub-commands as standalone skill shortcuts.
- *
- * Usage:
- * node <scripts_path>/pin.mjs pin <command>
- * node <scripts_path>/pin.mjs unpin <command>
- *
- * `pin audit` creates a lightweight /audit skill that redirects to /impeccable audit.
- * `unpin audit` removes that shortcut.
- *
- * The script discovers harness directories (.claude/skills, .cursor/skills, etc.)
- * in the project root and creates/removes the pin in all of them.
- */
-
-import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
-import { join, resolve, dirname } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-// All known harness directories
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Valid sub-command names
-const VALID_COMMANDS = [
- 'craft', 'teach', 'extract', 'document', 'shape',
- 'critique', 'audit',
- 'polish', 'bolder', 'quieter', 'distill', 'harden', 'onboard', 'live',
- 'animate', 'colorize', 'typeset', 'layout', 'delight', 'overdrive',
- 'clarify', 'adapt', 'optimize',
-];
-
-// Marker to identify pinned skills (so unpin doesn't delete user skills)
-const PIN_MARKER = '<!-- impeccable-pinned-skill -->';
-
-/**
- * Walk up from startDir to find a project root.
- */
-function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- while (dir !== '/') {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Find harness skill directories that have an impeccable skill installed.
- */
-function findHarnessDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const skillsDir = join(projectRoot, harness, 'skills');
- // Only pin in harness dirs that already have impeccable installed
- const impeccableDir = join(skillsDir, 'impeccable');
- if (existsSync(impeccableDir) || existsSync(join(skillsDir, 'i-impeccable'))) {
- dirs.push(skillsDir);
- }
- }
- return dirs;
-}
-
-/**
- * Load command metadata (descriptions for pinned skills).
- */
-function loadCommandMetadata() {
- const metadataPath = join(__dirname, 'command-metadata.json');
- if (existsSync(metadataPath)) {
- return JSON.parse(readFileSync(metadataPath, 'utf-8'));
- }
- return {};
-}
-
-/**
- * Generate a pinned skill's SKILL.md content.
- */
-function generatePinnedSkill(command, metadata) {
- const desc = metadata[command]?.description || `Shortcut for /impeccable ${command}.`;
- const hint = metadata[command]?.argumentHint || '[target]';
-
- return `---
-name: ${command}
-description: "${desc}"
-argument-hint: "${hint}"
-user-invocable: true
----
-
-${PIN_MARKER}
-
-This is a pinned shortcut for \`{{command_prefix}}impeccable ${command}\`.
-
-Invoke {{command_prefix}}impeccable ${command}, passing along any arguments provided here, and follow its instructions.
-`;
-}
-
-/**
- * Pin a command: create shortcut skill in all harness dirs.
- */
-function pin(command, projectRoot) {
- const metadata = loadCommandMetadata();
- const harnessDirs = findHarnessDirs(projectRoot);
-
- if (harnessDirs.length === 0) {
- console.log('No harness directories with impeccable installed found.');
- return false;
- }
-
- const content = generatePinnedSkill(command, metadata);
- let created = 0;
-
- for (const skillsDir of harnessDirs) {
- // Check if skill already exists (and isn't a pin)
- const skillDir = join(skillsDir, command);
- if (existsSync(skillDir)) {
- const existingMd = join(skillDir, 'SKILL.md');
- if (existsSync(existingMd)) {
- const existing = readFileSync(existingMd, 'utf-8');
- if (!existing.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (non-pinned skill already exists)`);
- continue;
- }
- }
- }
-
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(join(skillDir, 'SKILL.md'), content, 'utf-8');
- console.log(` + ${skillDir}`);
- created++;
- }
-
- if (created > 0) {
- console.log(`\nPinned '${command}' as a standalone shortcut in ${created} location(s).`);
- console.log(`You can now use /${command} directly.`);
- }
-
- return created > 0;
-}
-
-/**
- * Unpin a command: remove shortcut skill from all harness dirs.
- */
-function unpin(command, projectRoot) {
- const harnessDirs = findHarnessDirs(projectRoot);
- let removed = 0;
-
- for (const skillsDir of harnessDirs) {
- const skillDir = join(skillsDir, command);
- if (!existsSync(skillDir)) continue;
-
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) continue;
-
- // Safety: only remove if it's a pinned skill
- const content = readFileSync(skillMd, 'utf-8');
- if (!content.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (not a pinned skill)`);
- continue;
- }
-
- rmSync(skillDir, { recursive: true, force: true });
- console.log(` - ${skillDir}`);
- removed++;
- }
-
- if (removed > 0) {
- console.log(`\nUnpinned '${command}' from ${removed} location(s).`);
- console.log(`Use /impeccable ${command} to access it.`);
- } else {
- console.log(`No pinned '${command}' shortcut found.`);
- }
-
- return removed > 0;
-}
-
-// --- CLI ---
-const [,, action, command] = process.argv;
-
-if (!action || !command) {
- console.log('Usage: node pin.mjs <pin|unpin> <command>');
- console.log(`\nAvailable commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-if (action !== 'pin' && action !== 'unpin') {
- console.error(`Unknown action: ${action}. Use 'pin' or 'unpin'.`);
- process.exit(1);
-}
-
-if (!VALID_COMMANDS.includes(command)) {
- console.error(`Unknown command: ${command}`);
- console.error(`Available commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-const root = findProjectRoot();
-
-if (action === 'pin') {
- pin(command, root);
-} else {
- unpin(command, root);
-}
@@ -1,167 +0,0 @@
----
-name: impeccable
-description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
-version: 3.1.1
-user-invocable: true
-argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · teach|document|extract|live] [target]"
-license: Apache 2.0. Based on Anthropic's frontend-design skill. See NOTICE.md for attribution.
----
-
-Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
-
-## Setup
-
-Before any design work or file edits:
-
-1. Load context (PRODUCT.md / DESIGN.md) via the loader script.
-2. Identify the register and load the matching register reference (brand.md or product.md).
-3. **If the user invoked a sub-command (e.g. `craft`, `shape`, `audit`), load its reference file too.** This is non-negotiable: `craft` without `craft.md` loaded means you'll skip the shape-and-confirm step the user expects.
-
-Skipping these produces generic output that ignores the project.
-
-### 1. Context gathering
-
-Two files, case-insensitive. The loader looks at the project root by default and falls back to `.agents/context/` and `docs/` if the root is clean. Override with `IMPECCABLE_CONTEXT_DIR=path/to/dir` (absolute or relative to cwd).
-
-- **PRODUCT.md**: required. Users, brand, tone, anti-references, strategic principles.
-- **DESIGN.md**: optional, strongly recommended. Colors, typography, elevation, components.
-
-Load both in one call:
-
-```bash
-node .trae/skills/impeccable/scripts/load-context.mjs
-```
-
-Consume the full JSON output. Never pipe through `head`, `tail`, `grep`, or `jq`. The output's `contextDir` field tells you where the files were resolved from.
-
-If the output is already in this session's conversation history, don't re-run. Exceptions requiring a fresh load: you just ran `/impeccable teach` or `/impeccable document` (they rewrite the files), or the user manually edited one.
-
-`/impeccable live` already warms context via `live.mjs`. If you've run `live.mjs`, don't also run `load-context.mjs` this session.
-
-If PRODUCT.md is missing, empty, or placeholder (`[TODO]` markers, <200 chars): run `/impeccable teach`, then resume the user's original task with the fresh context. If the original task was `/impeccable craft`, resume into `/impeccable shape` before any implementation work.
-
-If DESIGN.md is missing: nudge once per session (*"Run `/impeccable document` for more on-brand output"*), then proceed.
-
-### 2. Register
-
-Every design task is **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboard, tool: design SERVES the product).
-
-Identify before designing. Priority: (1) cue in the task itself ("landing page" vs "dashboard"); (2) the surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. First match wins.
-
-If PRODUCT.md lacks the `register` field (legacy), infer it once from its "Users" and "Product Purpose" sections, then cache the inferred value for the session. Suggest the user run `/impeccable teach` to add the field explicitly.
-
-Load the matching reference: [reference/brand.md](reference/brand.md) or [reference/product.md](reference/product.md). The shared design laws below apply to both.
-
-## Shared design laws
-
-Apply to every design, both registers. Match implementation complexity to the aesthetic vision: maximalism needs elaborate code, minimalism needs precision. Interpret creatively. Vary across projects; never converge on the same choices. the model is capable of extraordinary work. Don't hold back.
-
-### Color
-
-- Use OKLCH. Reduce chroma as lightness approaches 0 or 100; high chroma at extremes looks garish.
-- Never use `#000` or `#fff`. Tint every neutral toward the brand hue (chroma 0.005–0.01 is enough).
-- Pick a **color strategy** before picking colors. Four steps on the commitment axis:
- - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism.
- - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages.
- - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz.
- - **Drenched**: the surface IS the color. Brand heroes, campaign pages.
-- The "one accent ≤10%" rule is Restrained only. Committed / Full palette / Drenched exceed it on purpose. Don't collapse every design to Restrained by reflex.
-
-### Theme
-
-Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe."
-
-Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does.
-
-"Observability dashboard" does not force an answer. "SRE glancing at incident severity on a 27-inch monitor at 2am in a dim room" does. Run the sentence, not the category.
-
-### Typography
-
-- Cap body line length at 65–75ch.
-- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales.
-
-### Layout
-
-- Vary spacing for rhythm. Same padding everywhere is monotony.
-- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
-- Don't wrap everything in a container. Most things don't need one.
-
-### Motion
-
-- Don't animate CSS layout properties.
-- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
-
-### Absolute bans
-
-Match-and-refuse. If you're about to write any of these, rewrite the element with different structure.
-
-- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing.
-- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size.
-- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing.
-- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché.
-- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly.
-- **Modal as first thought.** Modals are usually laziness. Exhaust inline / progressive alternatives first.
-
-### Copy
-
-- Every word earns its place. No restated headings, no intros that repeat the title.
-- **No em dashes.** Use commas, colons, semicolons, periods, or parentheses. Also not `--`.
-
-### The AI slop test
-
-If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference.
-
-**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses.
-
-- **First-order:** if someone could guess the theme + palette from the category alone ("observability → dark blue", "healthcare → white + teal", "finance → navy + gold", "crypto → neon on black"), it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
-- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families.
-
-## Commands
-
-| Command | Category | Description | Reference |
-|---|---|---|---|
-| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) |
-| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) |
-| `teach` | Build | Set up PRODUCT.md and DESIGN.md context | [reference/teach.md](reference/teach.md) |
-| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) |
-| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) |
-| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) |
-| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) |
-| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) |
-| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) |
-| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) |
-| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) |
-| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) |
-| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) |
-| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) |
-| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) |
-| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) |
-| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) |
-| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) |
-| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) |
-| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) |
-| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) |
-| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
-| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
-
-### Routing rules
-
-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
-3. **First word doesn't match**: general design invocation. Apply the setup steps, shared design laws, and the loaded register reference, using the full argument as context.
-
-Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `/impeccable`.
-
-If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `teach` as a blocker, finish teach, refresh context, then resume the original command and target.
-
-## Pin / Unpin
-
-**Pin** creates a standalone shortcut so `/<command>` invokes `/impeccable <command>` directly. **Unpin** removes it. The script writes to every harness directory present in the project.
-
-```bash
-node .trae/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
-```
-
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
@@ -1,190 +0,0 @@
-> **Additional context needed**: target platforms/devices and usage contexts.
-
-Adapt an existing design to a different context: another screen size, device, platform, or use case. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context.
-
-
----
-
-## Assess Adaptation Challenge
-
-Understand what needs adaptation and why:
-
-1. **Identify the source context**:
- - What was it designed for originally? (Desktop web? Mobile app?)
- - What assumptions were made? (Large screen? Mouse input? Fast connection?)
- - What works well in current context?
-
-2. **Understand target context**:
- - **Device**: Mobile, tablet, desktop, TV, watch, print?
- - **Input method**: Touch, mouse, keyboard, voice, gamepad?
- - **Screen constraints**: Size, resolution, orientation?
- - **Connection**: Fast wifi, slow 3G, offline?
- - **Usage context**: On-the-go vs desk, quick glance vs focused reading?
- - **User expectations**: What do users expect on this platform?
-
-3. **Identify adaptation challenges**:
- - What won't fit? (Content, navigation, features)
- - What won't work? (Hover states on touch, tiny touch targets)
- - What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop)
-
-**CRITICAL**: Adaptation is rethinking the experience for the new context, not scaling pixels.
-
-## Plan Adaptation Strategy
-
-Create context-appropriate strategy:
-
-### Mobile Adaptation (Desktop → Mobile)
-
-**Layout Strategy**:
-- Single column instead of multi-column
-- Vertical stacking instead of side-by-side
-- Full-width components instead of fixed widths
-- Bottom navigation instead of top/side navigation
-
-**Interaction Strategy**:
-- Touch targets 44x44px minimum (not hover-dependent)
-- Swipe gestures where appropriate (lists, carousels)
-- Bottom sheets instead of dropdowns
-- Thumbs-first design (controls within thumb reach)
-- Larger tap areas with more spacing
-
-**Content Strategy**:
-- Progressive disclosure (don't show everything at once)
-- Prioritize primary content (secondary content in tabs/accordions)
-- Shorter text (more concise)
-- Larger text (16px minimum)
-
-**Navigation Strategy**:
-- Hamburger menu or bottom navigation
-- Reduce navigation complexity
-- Sticky headers for context
-- Back button in navigation flow
-
-### Tablet Adaptation (Hybrid Approach)
-
-**Layout Strategy**:
-- Two-column layouts (not single or three-column)
-- Side panels for secondary content
-- Master-detail views (list + detail)
-- Adaptive based on orientation (portrait vs landscape)
-
-**Interaction Strategy**:
-- Support both touch and pointer
-- Touch targets 44x44px but allow denser layouts than phone
-- Side navigation drawers
-- Multi-column forms where appropriate
-
-### Desktop Adaptation (Mobile → Desktop)
-
-**Layout Strategy**:
-- Multi-column layouts (use horizontal space)
-- Side navigation always visible
-- Multiple information panels simultaneously
-- Fixed widths with max-width constraints (don't stretch to 4K)
-
-**Interaction Strategy**:
-- Hover states for additional information
-- Keyboard shortcuts
-- Right-click context menus
-- Drag and drop where helpful
-- Multi-select with Shift/Cmd
-
-**Content Strategy**:
-- Show more information upfront (less progressive disclosure)
-- Data tables with many columns
-- Richer visualizations
-- More detailed descriptions
-
-### Print Adaptation (Screen → Print)
-
-**Layout Strategy**:
-- Page breaks at logical points
-- Remove navigation, footer, interactive elements
-- Black and white (or limited color)
-- Proper margins for binding
-
-**Content Strategy**:
-- Expand shortened content (show full URLs, hidden sections)
-- Add page numbers, headers, footers
-- Include metadata (print date, page title)
-- Convert charts to print-friendly versions
-
-### Email Adaptation (Web → Email)
-
-**Layout Strategy**:
-- Narrow width (600px max)
-- Single column only
-- Inline CSS (no external stylesheets)
-- Table-based layouts (for email client compatibility)
-
-**Interaction Strategy**:
-- Large, obvious CTAs (buttons not text links)
-- No hover states (not reliable)
-- Deep links to web app for complex interactions
-
-## Implement Adaptations
-
-Apply changes systematically:
-
-### Responsive Breakpoints
-
-Choose appropriate breakpoints:
-- Mobile: 320px-767px
-- Tablet: 768px-1023px
-- Desktop: 1024px+
-- Or content-driven breakpoints (where design breaks)
-
-### Layout Adaptation Techniques
-
-- **CSS Grid/Flexbox**: Reflow layouts automatically
-- **Container Queries**: Adapt based on container, not viewport
-- **`clamp()`**: Fluid sizing between min and max
-- **Media queries**: Different styles for different contexts
-- **Display properties**: Show/hide elements per context
-
-### Touch Adaptation
-
-- Increase touch target sizes (44x44px minimum)
-- Add more spacing between interactive elements
-- Remove hover-dependent interactions
-- Add touch feedback (ripples, highlights)
-- Consider thumb zones (easier to reach bottom than top)
-
-### Content Adaptation
-
-- Use `display: none` sparingly (still downloads)
-- Progressive enhancement (core content first, enhancements on larger screens)
-- Lazy loading for off-screen content
-- Responsive images (`srcset`, `picture` element)
-
-### Navigation Adaptation
-
-- Transform complex nav to hamburger/drawer on mobile
-- Bottom nav bar for mobile apps
-- Persistent side navigation on desktop
-- Breadcrumbs on smaller screens for context
-
-**IMPORTANT**: Test on real devices. Device emulation in DevTools is helpful but not perfect.
-
-**NEVER**:
-- Hide core functionality on mobile (if it matters, make it work)
-- Assume desktop = powerful device (consider accessibility, older machines)
-- Use different information architecture across contexts (confusing)
-- Break user expectations for platform (mobile users expect mobile patterns)
-- Forget landscape orientation on mobile/tablet
-- Use generic breakpoints blindly (use content-driven breakpoints)
-- Ignore touch on desktop (many desktop devices have touch)
-
-## Verify Adaptations
-
-Test thoroughly across contexts:
-
-- **Real devices**: Test on actual phones, tablets, desktops
-- **Different orientations**: Portrait and landscape
-- **Different browsers**: Safari, Chrome, Firefox, Edge
-- **Different OS**: iOS, Android, Windows, macOS
-- **Different input methods**: Touch, mouse, keyboard
-- **Edge cases**: Very small screens (320px), very large screens (4K)
-- **Slow connections**: Test on throttled network
-
-When the adaptation feels native to each context, hand off to `/impeccable polish` for the final pass.
@@ -1,175 +0,0 @@
-> **Additional context needed**: performance constraints.
-
-Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it.
-
----
-
-## Register
-
-Brand: orchestrated page-load sequences, staggered reveals, scroll-driven animation. Motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions.
-
-Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it.
-
----
-
-## Assess Animation Opportunities
-
-Analyze where motion would improve the experience:
-
-1. **Identify static areas**:
- - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.)
- - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes)
- - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious
- - **Lack of delight**: Functional but joyless interactions
- - **Missed guidance**: Opportunities to direct attention or explain behavior
-
-2. **Understand the context**:
- - What's the personality? (Playful vs serious, energetic vs calm)
- - What's the performance budget? (Mobile-first? Complex page?)
- - Who's the audience? (Motion-sensitive users? Power users who want speed?)
- - What matters most? (One hero animation vs many micro-interactions?)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them.
-
-## Plan Animation Strategy
-
-Create a purposeful animation plan:
-
-- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?)
-- **Feedback layer**: Which interactions need acknowledgment?
-- **Transition layer**: Which state changes need smoothing?
-- **Delight layer**: Where can we surprise and delight?
-
-**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments.
-
-## Implement Animations
-
-Add motion systematically across these categories:
-
-### Entrance Animations
-- **Page load choreography**: Stagger element reveals (100-150ms delays), fade + slide combinations
-- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects)
-- **Content reveals**: Scroll-triggered animations using intersection observer
-- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management
-
-### Micro-interactions
-- **Button feedback**:
- - Hover: Subtle scale (1.02-1.05), color shift, shadow increase
- - Click: Quick scale down then up (0.95 → 1), ripple effect
- - Loading: Spinner or pulse state
-- **Form interactions**:
- - Input focus: Border color transition, slight scale or glow
- - Validation: Shake on error, check mark on success, smooth color transitions
-- **Toggle switches**: Smooth slide + color transition (200-300ms)
-- **Checkboxes/radio**: Check mark animation, ripple effect
-- **Like/favorite**: Scale + rotation, particle effects, color transition
-
-### State Transitions
-- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms)
-- **Expand/collapse**: Height transition with overflow handling, icon rotation
-- **Loading states**: Skeleton screen fades, spinner animations, progress bars
-- **Success/error**: Color transitions, icon animations, gentle scale pulse
-- **Enable/disable**: Opacity transitions, cursor changes
-
-### Navigation & Flow
-- **Page transitions**: Crossfade between routes, shared element transitions
-- **Tab switching**: Slide indicator, content fade/slide
-- **Carousel/slider**: Smooth transforms, snap points, momentum
-- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators
-
-### Feedback & Guidance
-- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights
-- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning
-- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation
-- **Focus flow**: Highlight path through form or workflow
-
-### Delight Moments
-- **Empty states**: Subtle floating animations on illustrations
-- **Completed actions**: Confetti, check mark flourish, success celebrations
-- **Easter eggs**: Hidden interactions for discovery
-- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches
-
-## Technical Implementation
-
-Use appropriate techniques for each animation:
-
-### Timing & Easing
-
-**Durations by purpose:**
-- **100-150ms**: Instant feedback (button press, toggle)
-- **200-300ms**: State changes (hover, menu open)
-- **300-500ms**: Layout changes (accordion, modal)
-- **500-800ms**: Entrance animations (page load)
-
-**Easing curves (use these, not CSS defaults):**
-```css
-/* Recommended: natural deceleration */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */
-
-/* AVOID: feel dated and tacky */
-/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */
-/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */
-```
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-### CSS Animations
-```css
-/* Prefer for simple, declarative animations */
-- transitions for state changes
-- @keyframes for complex sequences
-- transform and opacity for reliable movement
-- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth
-```
-
-### JavaScript Animation
-```javascript
-/* Use for complex, interactive animations */
-- Web Animations API for programmatic control
-- Framer Motion for React
-- GSAP for complex sequences
-```
-
-### Performance
-- **Motion materials**: Use transform/opacity for reliable movement, but use blur, filters, masks, shadows, and color shifts when they materially improve the effect
-- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- **will-change**: Add sparingly for known expensive animations
-- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate
-- **Monitor FPS**: Ensure 60fps on target devices
-
-### Accessibility
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**NEVER**:
-- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself
-- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work
-- Use durations over 500ms for feedback (it feels laggy)
-- Animate without purpose (every animation needs a reason)
-- Ignore `prefers-reduced-motion` (this is an accessibility violation)
-- Animate everything (animation fatigue makes interfaces feel exhausting)
-- Block interaction during animations unless intentional
-
-## Verify Quality
-
-Test animations thoroughly:
-
-- **Smooth at 60fps**: No jank on target devices
-- **Feels natural**: Easing curves feel organic, not robotic
-- **Appropriate timing**: Not too fast (jarring) or too slow (laggy)
-- **Reduced motion works**: Animations disabled or simplified appropriately
-- **Doesn't block**: Users can interact during/after animations
-- **Adds value**: Makes interface clearer or more delightful
-
-When the motion clarifies state instead of decorating it, hand off to `/impeccable polish` for the final pass.
@@ -1,133 +0,0 @@
-Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues; document them for other commands to address.
-
-This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation.
-
-## Diagnostic Scan
-
-Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below.
-
-### 1. Accessibility (A11y)
-
-**Check for**:
-- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA)
-- **Missing ARIA**: Interactive elements without proper roles, labels, or states
-- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps
-- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons
-- **Alt text**: Missing or poor image descriptions
-- **Form issues**: Inputs without labels, poor error messaging, missing required indicators
-
-**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA)
-
-### 2. Performance
-
-**Check for**:
-- **Layout thrashing**: Reading/writing layout properties in loops
-- **Expensive animations**: Casual layout-property animation, unbounded blur/filter/shadow effects, or effects that visibly drop frames
-- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change
-- **Bundle size**: Unnecessary imports, unused dependencies
-- **Render performance**: Unnecessary re-renders, missing memoization
-
-**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized)
-
-### 3. Theming
-
-**Check for**:
-- **Hard-coded colors**: Colors not using design tokens
-- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme
-- **Inconsistent tokens**: Using wrong tokens, mixing token types
-- **Theme switching issues**: Values that don't update on theme change
-
-**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly)
-
-### 4. Responsive Design
-
-**Check for**:
-- **Fixed widths**: Hard-coded widths that break on mobile
-- **Touch targets**: Interactive elements < 44x44px
-- **Horizontal scroll**: Content overflow on narrow viewports
-- **Text scaling**: Layouts that break when text size increases
-- **Missing breakpoints**: No mobile/tablet variants
-
-**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets)
-
-### 5. Anti-Patterns (CRITICAL)
-
-Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy).
-
-**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design)
-
-## Generate Report
-
-### Audit Health Score
-
-| # | Dimension | Score | Key Finding |
-|---|-----------|-------|-------------|
-| 1 | Accessibility | ? | [most critical a11y issue or "--"] |
-| 2 | Performance | ? | |
-| 3 | Responsive Design | ? | |
-| 4 | Theming | ? | |
-| 5 | Anti-Patterns | ? | |
-| **Total** | | **??/20** | **[Rating band]** |
-
-**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues)
-
-### Anti-Patterns Verdict
-**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest.
-
-### Executive Summary
-- Audit Health Score: **??/20** ([rating band])
-- Total issues found (count by severity: P0/P1/P2/P3)
-- Top 3-5 critical issues
-- Recommended next steps
-
-### Detailed Findings by Severity
-
-Tag every issue with **P0-P3 severity**:
-- **P0 Blocking**: Prevents task completion. Fix immediately
-- **P1 Major**: Significant difficulty or WCAG AA violation. Fix before release
-- **P2 Minor**: Annoyance, workaround exists. Fix in next pass
-- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits
-
-For each issue, document:
-- **[P?] Issue name**
-- **Location**: Component, file, line
-- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern
-- **Impact**: How it affects users
-- **WCAG/Standard**: Which standard it violates (if applicable)
-- **Recommendation**: How to fix it
-- **Suggested command**: Which command to use (prefer: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-### Patterns & Systemic Issues
-
-Identify recurring problems that indicate systemic gaps rather than one-off mistakes:
-- "Hard-coded colors appear in 15+ components, should use design tokens"
-- "Touch targets consistently too small (<44px) throughout mobile experience"
-
-### Positive Findings
-
-Note what's working well: good practices to maintain and replicate.
-
-## Recommended Actions
-
-List recommended commands in priority order (P0 first, then P1, then P2):
-
-1. **[P?] `/command-name`**: Brief description (specific context from audit findings)
-2. **[P?] `/command-name`**: Brief description (specific context)
-
-**Rules**: Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset. Map findings to the most appropriate command. End with `/impeccable polish` as the final step if any fixes were recommended.
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable audit` after fixes to see your score improve.
-
-**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters.
-
-**NEVER**:
-- Report issues without explaining impact (why does this matter?)
-- Provide generic recommendations (be specific and actionable)
-- Skip positive findings (celebrate what works)
-- Forget to prioritize (everything can't be P0)
-- Report false positives without verification
-
@@ -1,113 +0,0 @@
-When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact and personality through stronger hierarchy, committed scale, and decisive type.
-
----
-
-## Register
-
-Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
-
-Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too safe or boring:
-
-1. **Identify weakness sources**:
- - **Generic choices**: System fonts, basic colors, standard layouts
- - **Timid scale**: Everything is medium-sized with no drama
- - **Low contrast**: Everything has similar visual weight
- - **Static**: No motion, no energy, no life
- - **Predictable**: Standard patterns with no surprises
- - **Flat hierarchy**: Nothing stands out or commands attention
-
-2. **Understand the context**:
- - What's the brand personality? (How far can we push?)
- - What's the purpose? (Marketing can be bolder than financial dashboards)
- - Who's the audience? (What will resonate?)
- - What are the constraints? (Brand guidelines, accessibility, performance)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
-
-**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
-
-## Plan Amplification
-
-Create a strategy to increase impact while maintaining coherence:
-
-- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
-- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
-- **Risk budget**: How experimental can we be? Push boundaries within constraints.
-- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
-
-**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration.
-
-## Amplify the Design
-
-Systematically increase impact across these dimensions:
-
-### Typography Amplification
-- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and [typography.md](typography.md) for inspiration)
-- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
-- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
-- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
-
-### Color Intensification
-- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
-- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop
-- **Dominant color strategy**: Let one bold color own 60% of the design
-- **Sharp accents**: High-contrast accent colors that pop
-- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
-- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
-
-### Spatial Drama
-- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
-- **Break the grid**: Let hero elements escape containers and cross boundaries
-- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
-- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
-- **Overlap**: Layer elements intentionally for depth
-
-### Visual Effects
-- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
-- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
-- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop)
-- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
-- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
-
-### Motion & Animation
-- **Entrance choreography**: Staggered, dramatic page load animations with 50-100ms delays
-- **Scroll effects**: Parallax, reveal animations, scroll-triggered sequences
-- **Micro-interactions**: Satisfying hover effects, click feedback, state changes
-- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect)
-
-### Composition Boldness
-- **Hero moments**: Create clear focal points with dramatic treatment
-- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
-- **Full-bleed elements**: Use full viewport width/height for impact
-- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
-
-**NEVER**:
-- Add effects randomly without purpose (chaos ≠ bold)
-- Sacrifice readability for aesthetics (body text must be readable)
-- Make everything bold (then nothing is bold; you need contrast)
-- Ignore accessibility (bold design must still meet WCAG standards)
-- Overwhelm with motion (animation fatigue is real)
-- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
-
-## Verify Quality
-
-Ensure amplification maintains usability and coherence:
-
-- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over.
-- **Still functional**: Can users accomplish tasks without distraction?
-- **Coherent**: Does everything feel intentional and unified?
-- **Memorable**: Will users remember this experience?
-- **Performant**: Do all these effects run smoothly?
-- **Accessible**: Does it still meet accessibility standards?
-
-**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects."
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,118 +0,0 @@
-# Brand register
-
-When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made.
-
-The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look.
-
-## The brand slop test
-
-If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?"
-
-Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home.
-
-**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register.
-
-Then the inverse test: in one sentence, describe what you're about to build the way a competitor would describe theirs. If that sentence fits the modal landing page in the category, restart.
-
-## Typography
-
-### Font selection procedure
-
-Every project. Never skip.
-
-1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words.
-2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture.
-3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy."
-4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over.
-
-### Reflex-reject list
-
-Training-data defaults. Ban list. Look further:
-
-Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif
-
-### Reflex-reject aesthetic lanes
-
-Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further.
-
-- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery.
-
-(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.)
-
-The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md).
-
-### Pairing and voice
-
-Distinctive + refined is the goal. The specific shape depends on the brand:
-
-- **Editorial / long-form / luxury**: display serif + sans body (a magazine shape).
-- **Tech / dev tools / fintech**: one committed sans, usually; custom-tight tracking, strong weight contrast inside a single family.
-- **Consumer / food / travel**: warmer pairings, often a humanist sans plus a script or display serif.
-- **Creative studios / agencies**: rule-breaking welcome. Mono-only, or display-only, or custom-drawn type as voice.
-
-Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair.
-
-Vary across projects. If the last brief was a serif-display landing page, this one isn't.
-
-### Scale
-
-Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted.
-
-Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room.
-
-## Color
-
-Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register.
-
-- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige.
-- Palette IS voice. A calm brand and a restless brand should not share palette mechanics.
-- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit.
-- Don't converge across projects. If the last brand surface was restrained-on-cream, this one is not.
-- When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette.
-
-## Layout
-
-- Asymmetric compositions are one option. Break the grid intentionally for emphasis.
-- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings.
-- Alternative: a strict, visible grid as the voice (brutalist / Swiss / tech-spec aesthetics). Either asymmetric or rigorously-gridded can be "designed"; the failure mode is splitting the difference into a generic centered stack.
-- Don't default to centering everything. Left-aligned with asymmetric layouts feels more designed; a strict grid reads as confident structure. A centered-stack hero with icon-title-subtitle cards reads as template.
-- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness.
-
-## Imagery
-
-Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo.
-
-**When the brief implies imagery (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product), you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy.
-
-- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `<div>` placeholders.
-- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel".
-- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one.
-- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish".
-
-"Imagery" here is broader than stock photography: product screenshots, custom data visualizations, generated SVG, and canvas/WebGL scenes are all imagery. Text-only pages where typography alone carries the entire visual weight are the failure mode.
-
-## Motion
-
-- One well-orchestrated page-load with staggered reveals beats scattered micro-interactions, when the brand invites it. Tech-minimal brands often skip entrance motion entirely; the restraint is the voice.
-- For collapsing/expanding sections, transition `grid-template-rows` rather than `height`.
-
-## Brand bans (on top of the shared absolute bans)
-
-- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume.
-- Large rounded-corner icons above every heading. Screams template.
-- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.)
-- All-caps body copy. Reserve caps for short labels and headings.
-- Timid palettes and average layouts. Safe = invisible.
-- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs.
-- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic.
-- Repeated tiny uppercase tracked labels above every section heading. A single strong kicker can be voice; repeating it as section grammar is AI scaffolding unless it's a deliberate, named brand system.
-
-## Brand permissions
-
-Brand can afford things product can't. Take them.
-
-- Ambitious first-load motion. Reveals, scroll-triggered transitions, typographic choreography.
-- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing.
-- Typographic risk. Enormous display type, unexpected italic cuts, mixed cases, hand-drawn headlines, a single oversize word as a hero.
-- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics.
-- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment.
@@ -1,174 +0,0 @@
-> **Additional context needed**: audience technical level and users' mental state in context.
-
-Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task.
-
-
----
-
-## Assess Current Copy
-
-Identify what makes the text unclear or ineffective:
-
-1. **Find clarity problems**:
- - **Jargon**: Technical terms users won't understand
- - **Ambiguity**: Multiple interpretations possible
- - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file"
- - **Length**: Too wordy or too terse
- - **Assumptions**: Assuming user knowledge they don't have
- - **Missing context**: Users don't know what to do or why
- - **Tone mismatch**: Too formal, too casual, or inappropriate for situation
-
-2. **Understand the context**:
- - Who's the audience? (Technical? General? First-time users?)
- - What's the user's mental state? (Stressed during error? Confident during success?)
- - What's the action? (What do we want users to do?)
- - What's the constraint? (Character limits? Space limitations?)
-
-**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets.
-
-## Plan Copy Improvements
-
-Create a strategy for clearer communication:
-
-- **Primary message**: What's the ONE thing users need to know?
-- **Action needed**: What should users do next (if anything)?
-- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?)
-- **Constraints**: Length limits, brand voice, localization considerations
-
-**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words.
-
-## Improve Copy Systematically
-
-Refine text across these common areas:
-
-### Error Messages
-**Bad**: "Error 403: Forbidden"
-**Good**: "You don't have permission to view this page. Contact your admin for access."
-
-**Bad**: "Invalid input"
-**Good**: "Email addresses need an @ symbol. Try: name@example.com"
-
-**Principles**:
-- Explain what went wrong in plain language
-- Suggest how to fix it
-- Don't blame the user
-- Include examples when helpful
-- Link to help/support if applicable
-
-### Form Labels & Instructions
-**Bad**: "DOB (MM/DD/YYYY)"
-**Good**: "Date of birth" (with placeholder showing format)
-
-**Bad**: "Enter value here"
-**Good**: "Your email address" or "Company name"
-
-**Principles**:
-- Use clear, specific labels (not generic placeholders)
-- Show format expectations with examples
-- Explain why you're asking (when not obvious)
-- Put instructions before the field, not after
-- Keep required field indicators clear
-
-### Button & CTA Text
-**Bad**: "Click here" | "Submit" | "OK"
-**Good**: "Create account" | "Save changes" | "Got it, thanks"
-
-**Principles**:
-- Describe the action specifically
-- Use active voice (verb + noun)
-- Match user's mental model
-- Be specific ("Save" is better than "OK")
-
-### Help Text & Tooltips
-**Bad**: "This is the username field"
-**Good**: "Choose a username. You can change this later in Settings."
-
-**Principles**:
-- Add value (don't just repeat the label)
-- Answer the implicit question ("What is this?" or "Why do you need this?")
-- Keep it brief but complete
-- Link to detailed docs if needed
-
-### Empty States
-**Bad**: "No items"
-**Good**: "No projects yet. Create your first project to get started."
-
-**Principles**:
-- Explain why it's empty (if not obvious)
-- Show next action clearly
-- Make it welcoming, not dead-end
-
-### Success Messages
-**Bad**: "Success"
-**Good**: "Settings saved! Your changes will take effect immediately."
-
-**Principles**:
-- Confirm what happened
-- Explain what happens next (if relevant)
-- Be brief but complete
-- Match the user's emotional moment (celebrate big wins)
-
-### Loading States
-**Bad**: "Loading..." (for 30+ seconds)
-**Good**: "Analyzing your data... this usually takes 30-60 seconds"
-
-**Principles**:
-- Set expectations (how long?)
-- Explain what's happening (when it's not obvious)
-- Show progress when possible
-- Offer escape hatch if appropriate ("Cancel")
-
-### Confirmation Dialogs
-**Bad**: "Are you sure?"
-**Good**: "Delete 'Project Alpha'? This can't be undone."
-
-**Principles**:
-- State the specific action
-- Explain consequences (especially for destructive actions)
-- Use clear button labels ("Delete project" not "Yes")
-- Don't overuse confirmations (only for risky actions)
-
-### Navigation & Wayfinding
-**Bad**: Generic labels like "Items" | "Things" | "Stuff"
-**Good**: Specific labels like "Your projects" | "Team members" | "Settings"
-
-**Principles**:
-- Be specific and descriptive
-- Use language users understand (not internal jargon)
-- Make hierarchy clear
-- Consider information scent (breadcrumbs, current location)
-
-## Apply Clarity Principles
-
-Every piece of copy should follow these rules:
-
-1. **Be specific**: "Enter email" not "Enter value"
-2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity)
-3. **Be active**: "Save changes" not "Changes will be saved"
-4. **Be human**: "Oops, something went wrong" not "System error encountered"
-5. **Tell users what to do**, not just what happened
-6. **Be consistent**: Use same terms throughout (don't vary for variety)
-
-**NEVER**:
-- Use jargon without explanation
-- Blame users ("You made an error" → "This field is required")
-- Be vague ("Something went wrong" without explanation)
-- Use passive voice unnecessarily
-- Write overly long explanations (be concise)
-- Use humor for errors (be empathetic instead)
-- Assume technical knowledge
-- Vary terminology (pick one term and stick with it)
-- Repeat information (headers restating intros, redundant explanations)
-- Use placeholders as the only labels (they disappear when users type)
-
-## Verify Improvements
-
-Test that copy improvements work:
-
-- **Comprehension**: Can users understand without context?
-- **Actionability**: Do users know what to do next?
-- **Brevity**: Is it as short as possible while remaining clear?
-- **Consistency**: Does it match terminology elsewhere?
-- **Tone**: Is it appropriate for the situation?
-
-When the copy reads cleanly, hand off to `/impeccable polish` for the final pass.
@@ -1,105 +0,0 @@
-# Codex: Visual Direction & Asset Production
-
-This file is loaded by `/impeccable craft` when the harness has native image generation (currently Codex via `image_gen`). Other harnesses skip it. It covers the two craft steps that depend on real image generation: landing the visual direction, and producing the raster assets the implementation will compose.
-
-Read this *before* generating any images. The order matters, and the per-step user pauses are what keep generated imagery from drifting away from the brief.
-
-### Four stop points before code
-
-Steps A through D each end with the user. Do not advance past any of them on your own read of the situation.
-
-1. **STOP after Step A questions.** Wait for answers.
-2. **STOP after Step B palette generation.** Wait for "confirm palette."
-3. **STOP after Step C mocks.** Wait for direction approval or delegation.
-4. **Only after Step D approves a direction** do you return to craft.md Step 4 and write code.
-
-Prior shape approval does **not** satisfy any of these. Shape's "confirm or override" advances you into Step A; it is not a substitute for it.
-
-## Step A: Explore Directions with the User
-
-Before generating anything, run a brief direction conversation grounded in the shape brief.
-
-**Step A is required even when shape just produced a confirmed brief.** The shape questions and Step A questions cover different ground: shape pins purpose, content, scope; Step A pins palette, atmosphere, and named visual references for the comps you're about to generate. The only time you can skip Step A is when the user has already answered these exact palette/atmosphere/reference questions in the same session.
-
-Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions:
-
-- "Brief says 'editorial restraint, Klim-adjacent.' Are we closer to a quiet specimen page or a magazine-spread feel with hero imagery?"
-- "Palette strategy from shape was 'Committed.' Want it warm-grounded (deep oxblood + cream) or cool-grounded (slate + paper white)?"
-
-**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded.
-
-## Step B: Generate the Brand Palette First
-
-Generate **one** palette artifact before any mocks. This is a small, focused image: typography pairing on the chosen background, primary + accent color swatches, one signature ornament or motif. Single image, single pass.
-
-Why palette first: mocks generated against a vague color sense produce noise that drowns out the structural decisions. A confirmed palette is the first concrete contract for everything downstream.
-
-Show the palette to the user. Ask one question: "This is the palette I'm locking in for the mocks. Confirm, or call out what to shift?"
-
-**STOP and wait for confirmation.** Do not generate mocks against an unconfirmed palette. "Probably good enough" is the wrong call here; the palette is the contract for everything downstream.
-
-## Step C: Generate 1-3 Visual Mocks Against the Palette
-
-Once the palette is confirmed, generate **1 to 3** high-fidelity north-star comps. Each mock must use the confirmed palette and typography. Mocks differ in *structural* direction (hierarchy, topology, density, composition), not in color or motif.
-
-- Brand work: push visual identity, composition, mood, and signature motifs.
-- Product work: push hierarchy, topology, density, tone, grounded in realistic product structure.
-- Landing pages and long-form brand surfaces: show enough of the second fold to establish the system beyond the hero.
-
-Use the `image_gen` tool directly (or via the imagegen skill when available). Don't ask the user to install anything.
-
-## Step D: Approval Loop
-
-Show the comps. Ask what carries forward. Iterate until **one direction is approved** or the user explicitly delegates.
-
-**STOP and wait for the approval or the delegation.** Do not begin Step E or return to craft.md Step 4 until a single direction is named. If the user delegates, pick the strongest direction and explain it from the brief, not personal taste.
-
-Before moving to assets, summarize what to carry into code and what *not* to literalize from the mock. This is the handoff between visual exploration and semantic implementation.
-
-## Step E: Mock Fidelity Inventory
-
-Inventory the approved mock's major visible ingredients. For each, decide implementation: semantic HTML/CSS/SVG, generated raster, sourced raster, icon library, canvas/WebGL, or accepted omission.
-
-Common ingredients to inventory:
-
-- Hero silhouette and dominant composition
-- Signature motifs (planets, devices, portraits, charts, route lines, insets, badges, etc.)
-- Nav and primary CTA treatment
-- Section sequence, especially the second fold
-- Image-native content the concept depends on
-- Typography, density, color/material treatment, motion cues
-
-Treat the mock as a north star, not a screenshot to trace. Don't rasterize core UI text. But if the live result lacks the mock's major ingredients, the implementation is wrong.
-
-If a photographic, architectural, product, or place-led mock becomes generic CSS scenery, decorative diagrams, bullets, or copy, stop and fix it. That's a broken implementation, not a harmless interpretation.
-
-Don't substitute a different hero composition or visual driver post-approval without user sign-off.
-
-## Step F: Asset Slicing via the Asset Producer
-
-Raster ingredients identified in Step E need clean production assets. Use the bundled `impeccable_asset_producer` subagent rather than producing inline.
-
-Spawn it as a scoped subagent. If you do not have explicit permission to use agents, stop and ask:
-
-```text
-Asset production will work better as a scoped subagent job. Should I spawn the Impeccable asset producer subagent for this step?
-```
-
-Pass to the agent:
-
-- Approved mock path or screenshot reference
-- Crop paths or a contact sheet with crop ids
-- Output directory
-- Required dimensions, format, transparency needs
-- Avoid list
-- Notes on what should remain semantic HTML/CSS/SVG instead of raster
-
-Attach image generation capability to the spawned agent when the harness supports it. Do **not** load image-generation reference material into the parent thread.
-
-Inline asset production is allowed only if the user declines subagents, the harness cannot spawn the authorized agent, or the user explicitly asks for single-thread mode.
-
-Prefer HTML/CSS/SVG/canvas when they can credibly reproduce an ingredient; reach for real, generated, or stock imagery when the mock or subject matter calls for actual visual content.
-
-## After This File
-
-Once Steps A through F are complete, return to `craft.md` Step 5 (Build to Production Quality). The implementation builds against the confirmed palette, approved mock, and the assets the producer wrote.
@@ -1,106 +0,0 @@
-# Cognitive Load Assessment
-
-Cognitive load is the total mental effort required to use an interface. Overloaded users make mistakes, get frustrated, and leave. This reference helps identify and fix cognitive overload.
-
----
-
-## Three Types of Cognitive Load
-
-### Intrinsic Load: The Task Itself
-Complexity inherent to what the user is trying to do. You can't eliminate this, but you can structure it.
-
-**Manage it by**:
-- Breaking complex tasks into discrete steps
-- Providing scaffolding (templates, defaults, examples)
-- Progressive disclosure: show what's needed now, hide the rest
-- Grouping related decisions together
-
-### Extraneous Load: Bad Design
-Mental effort caused by poor design choices. **Eliminate this ruthlessly.** It's pure waste.
-
-**Common sources**:
-- Confusing navigation that requires mental mapping
-- Unclear labels that force users to guess meaning
-- Visual clutter competing for attention
-- Inconsistent patterns that prevent learning
-- Unnecessary steps between user intent and result
-
-### Germane Load: Learning Effort
-Mental effort spent building understanding. This is *good* cognitive load; it leads to mastery.
-
-**Support it by**:
-- Progressive disclosure that reveals complexity gradually
-- Consistent patterns that reward learning
-- Feedback that confirms correct understanding
-- Onboarding that teaches through action, not walls of text
-
----
-
-## Cognitive Load Checklist
-
-Evaluate the interface against these 8 items:
-
-- [ ] **Single focus**: Can the user complete their primary task without distraction from competing elements?
-- [ ] **Chunking**: Is information presented in digestible groups (≤4 items per group)?
-- [ ] **Grouping**: Are related items visually grouped together (proximity, borders, shared background)?
-- [ ] **Visual hierarchy**: Is it immediately clear what's most important on the screen?
-- [ ] **One thing at a time**: Can the user focus on a single decision before moving to the next?
-- [ ] **Minimal choices**: Are decisions simplified (≤4 visible options at any decision point)?
-- [ ] **Working memory**: Does the user need to remember information from a previous screen to act on the current one?
-- [ ] **Progressive disclosure**: Is complexity revealed only when the user needs it?
-
-**Scoring**: Count the failed items. 0–1 failures = low cognitive load (good). 2–3 = moderate (address soon). 4+ = high cognitive load (critical fix needed).
-
----
-
-## The Working Memory Rule
-
-**Humans can hold ≤4 items in working memory at once** (Miller's Law revised by Cowan, 2001).
-
-At any decision point, count the number of distinct options, actions, or pieces of information a user must simultaneously consider:
-- **≤4 items**: Within working memory limits, manageable
-- **5–7 items**: Pushing the boundary; consider grouping or progressive disclosure
-- **8+ items**: Overloaded; users will skip, misclick, or abandon
-
-**Practical applications**:
-- Navigation menus: ≤5 top-level items (group the rest under clear categories)
-- Form sections: ≤4 fields visible per group before a visual break
-- Action buttons: 1 primary, 1–2 secondary, group the rest in a menu
-- Dashboard widgets: ≤4 key metrics visible without scrolling
-- Pricing tiers: ≤3 options (more causes analysis paralysis)
-
----
-
-## Common Cognitive Load Violations
-
-### 1. The Wall of Options
-**Problem**: Presenting 10+ choices at once with no hierarchy.
-**Fix**: Group into categories, highlight recommended, use progressive disclosure.
-
-### 2. The Memory Bridge
-**Problem**: User must remember info from step 1 to complete step 3.
-**Fix**: Keep relevant context visible, or repeat it where it's needed.
-
-### 3. The Hidden Navigation
-**Problem**: User must build a mental map of where things are.
-**Fix**: Always show current location (breadcrumbs, active states, progress indicators).
-
-### 4. The Jargon Barrier
-**Problem**: Technical or domain language forces translation effort.
-**Fix**: Use plain language. If domain terms are unavoidable, define them inline.
-
-### 5. The Visual Noise Floor
-**Problem**: Every element has the same visual weight; nothing stands out.
-**Fix**: Establish clear hierarchy: one primary element, 2–3 secondary, everything else muted.
-
-### 6. The Inconsistent Pattern
-**Problem**: Similar actions work differently in different places.
-**Fix**: Standardize interaction patterns. Same type of action = same type of UI.
-
-### 7. The Multi-Task Demand
-**Problem**: Interface requires processing multiple simultaneous inputs (reading + deciding + navigating).
-**Fix**: Sequence the steps. Let the user do one thing at a time.
-
-### 8. The Context Switch
-**Problem**: User must jump between screens/tabs/modals to gather info for a single decision.
-**Fix**: Co-locate the information needed for each decision. Reduce back-and-forth.
@@ -1,105 +0,0 @@
-# Color & Contrast
-
-## Color Spaces: Use OKLCH
-
-**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark.
-
-The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish.
-
-The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand.
-
-## Building Functional Palettes
-
-### Tinted Neutrals
-
-**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces.
-
-The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette.
-
-**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects.
-
-### Palette Structure
-
-A complete system needs:
-
-| Role | Purpose | Example |
-|------|---------|---------|
-| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades |
-| **Neutral** | Text, backgrounds, borders | 9-11 shade scale |
-| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each |
-| **Surface** | Cards, modals, overlays | 2-3 elevation levels |
-
-**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise.
-
-### The 60-30-10 Rule (Applied Correctly)
-
-This rule is about **visual weight**, not pixel count:
-
-- **60%**: Neutral backgrounds, white space, base surfaces
-- **30%**: Secondary colors: text, borders, inactive states
-- **10%**: Accent: CTAs, highlights, focus states
-
-The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power.
-
-## Contrast & Accessibility
-
-### WCAG Requirements
-
-| Content Type | AA Minimum | AAA Target |
-|--------------|------------|------------|
-| Body text | 4.5:1 | 7:1 |
-| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 |
-| UI components, icons | 3:1 | 4.5:1 |
-| Non-essential decorations | None | None |
-
-**The gotcha**: Placeholder text still needs 4.5:1. That light gray placeholder you see everywhere? Usually fails WCAG.
-
-### Dangerous Color Combinations
-
-These commonly fail contrast or cause readability issues:
-
-- Light gray text on white (the #1 accessibility fail)
-- **Gray text on any colored background**: gray looks washed out and dead on color. Use a darker shade of the background color, or transparency
-- Red text on green background (or vice versa): 8% of men can't distinguish these
-- Blue text on red background (vibrates visually)
-- Yellow text on white (almost always fails)
-- Thin light text on images (unpredictable contrast)
-
-### Never Use Pure Gray or Pure Black
-
-Pure gray (`oklch(50% 0 0)`) and pure black (`#000`) don't exist in nature; real shadows and surfaces always have a color cast. Even a chroma of 0.005-0.01 is enough to feel natural without being obviously tinted. (See tinted neutrals example above.)
-
-### Testing
-
-Don't trust your eyes. Use tools:
-
-- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/)
-- Browser DevTools → Rendering → Emulate vision deficiencies
-- [Polypane](https://polypane.app/) for real-time testing
-
-## Theming: Light & Dark Mode
-
-### Dark Mode Is Not Inverted Light Mode
-
-You can't just swap colors. Dark mode requires different design decisions:
-
-| Light Mode | Dark Mode |
-|------------|-----------|
-| Shadows for depth | Lighter surfaces for depth (no shadows) |
-| Dark text on light | Light text on dark (reduce font weight) |
-| Vibrant accents | Desaturate accents slightly |
-| White backgrounds | Never pure black; use dark gray (oklch 12-18%) |
-
-In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light.
-
-### Token Hierarchy
-
-Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same.
-
-## Alpha Is A Design Smell
-
-Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed.
-
----
-
-**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Using pure black (#000) for large areas. Skipping color blindness testing (8% of men affected).
@@ -1,154 +0,0 @@
-> **Additional context needed**: existing brand colors.
-
-Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit.
-
----
-
-## Register
-
-Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it.
-
-Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen.
-
----
-
-## Assess Color Opportunity
-
-Analyze the current state and identify opportunities:
-
-1. **Understand current state**:
- - **Color absence**: Pure grayscale? Limited neutrals? One timid accent?
- - **Missed opportunities**: Where could color add meaning, hierarchy, or delight?
- - **Context**: What's appropriate for this domain and audience?
- - **Brand**: Are there existing brand colors we should use?
-
-2. **Identify where color adds value**:
- - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue)
- - **Hierarchy**: Drawing attention to important elements
- - **Categorization**: Different sections, types, or states
- - **Emotional tone**: Warmth, energy, trust, creativity
- - **Wayfinding**: Helping users navigate and understand structure
- - **Delight**: Moments of visual interest and personality
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose.
-
-## Plan Color Strategy
-
-Create a purposeful color introduction plan:
-
-- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals)
-- **Dominant color**: Which color owns 60% of colored elements?
-- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%)
-- **Application strategy**: Where does each color appear and why?
-
-**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more.
-
-## Introduce Color Strategically
-
-Add color systematically across these dimensions:
-
-### Semantic Color
-- **State indicators**:
- - Success: Green tones (emerald, forest, mint)
- - Error: Red/pink tones (rose, crimson, coral)
- - Warning: Orange/amber tones
- - Info: Blue tones (sky, ocean, indigo)
- - Neutral: Gray/slate for inactive states
-
-- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.)
-- **Progress indicators**: Colored bars, rings, or charts showing completion or health
-
-### Accent Color Application
-- **Primary actions**: Color the most important buttons/CTAs
-- **Links**: Add color to clickable text (maintain accessibility)
-- **Icons**: Colorize key icons for recognition and personality
-- **Headers/titles**: Add color to section headers or key labels
-- **Hover states**: Introduce color on interaction
-
-### Background & Surfaces
-- **Tinted backgrounds**: Replace pure gray (`#f5f5f5`) with warm neutrals (`oklch(97% 0.01 60)`) or cool tints (`oklch(97% 0.01 250)`)
-- **Colored sections**: Use subtle background colors to separate areas
-- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue)
-- **Cards & surfaces**: Tint cards or surfaces slightly for warmth
-
-**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
-
-### Data Visualization
-- **Charts & graphs**: Use color to encode categories or values
-- **Heatmaps**: Color intensity shows density or importance
-- **Comparison**: Color coding for different datasets or timeframes
-
-### Borders & Accents
-- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`)
-- **Underlines**: Color underlines for emphasis or active states
-- **Dividers**: Subtle colored dividers instead of gray lines
-- **Focus rings**: Colored focus indicators matching brand
-- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe
-
-**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe.
-
-### Typography Color
-- **Colored headings**: Use brand colors for section headings (maintain contrast)
-- **Highlight text**: Color for emphasis or categories
-- **Labels & tags**: Small colored labels for metadata or categories
-
-### Decorative Elements
-- **Illustrations**: Add colored illustrations or icons
-- **Shapes**: Geometric shapes in brand colors as background elements
-- **Gradients**: Colorful gradient overlays or mesh backgrounds
-- **Blobs/organic shapes**: Soft colored shapes for visual interest
-
-## Balance & Refinement
-
-Ensure color addition improves rather than overwhelms:
-
-### Maintain Hierarchy
-- **Dominant color** (60%): Primary brand color or most used accent
-- **Secondary color** (30%): Supporting color for variety
-- **Accent color** (10%): High contrast for key moments
-- **Neutrals** (remaining): Gray/black/white for structure
-
-### Accessibility
-- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components)
-- **Don't rely on color alone**: Use icons, labels, or patterns alongside color
-- **Test for color blindness**: Verify red/green combinations work for all users
-
-### Cohesion
-- **Consistent palette**: Use colors from defined palette, not arbitrary choices
-- **Systematic application**: Same color meanings throughout (green always = success)
-- **Temperature consistency**: Warm palette stays warm, cool stays cool
-
-**NEVER**:
-- Use every color in the rainbow (choose 2-4 colors beyond neutrals)
-- Apply color randomly without semantic meaning
-- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead
-- Use pure gray for neutrals. Add subtle color tint (warm or cool) for depth
-- Use pure black (`#000`) or pure white (`#fff`) for large areas
-- Violate WCAG contrast requirements
-- Use color as the only indicator (accessibility issue)
-- Make everything colorful (defeats the purpose)
-- Default to purple-blue gradients (AI slop aesthetic)
-
-## Verify Color Addition
-
-Test that colorization improves the experience:
-
-- **Better hierarchy**: Does color guide attention appropriately?
-- **Clearer meaning**: Does color help users understand states/categories?
-- **More engaging**: Does the interface feel warmer and more inviting?
-- **Still accessible**: Do all color combinations meet WCAG standards?
-- **Not overwhelming**: Is color balanced and purposeful?
-
-When the palette earns its place, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage.
-
-```json
-{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"}
-```
-
-Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract.
@@ -1,123 +0,0 @@
-# Craft Flow
-
-Build a feature with impeccable UX and UI quality: shape the design, land the visual direction, build real production code, inspect and improve in-browser until it meets a high-end studio bar.
-
-Before writing code, you need: PRODUCT.md loaded, register identified and the matching reference loaded, and a confirmed design direction for this task (either from `shape` or supplied by the user). PRODUCT.md is project context, not a task-specific brief.
-
-Treat any approved visual direction (generated mock or stated reference) as a concrete contract for composition, hierarchy, density, atmosphere, signature motifs, and distinctive visual moves. Don't let mocks replace structure, copy, accessibility, or state design. But if the live result lacks the approved direction's major ingredients, the implementation is wrong.
-
-### Gates: do not compress
-
-Craft has **multiple user gates**, not one. When the harness has native image generation (Codex via `image_gen`), the gate sequence before code is:
-
-1. **Shape brief confirmed** (Step 1)
-2. **Direction questions answered** (codex.md Step A)
-3. **Palette confirmed** (codex.md Step B)
-4. **One mock direction approved or delegated** (codex.md Step D)
-
-You must stop at every gate. **Shape confirmation alone is NOT a green light to start coding.** It is the green light to begin codex.md Step A. Compressing gates 2 through 4 because the shape brief felt complete is the dominant failure mode of this flow.
-
-When the harness lacks native image generation, gates 2-4 collapse into the brief itself, and shape confirmation does advance straight to code.
-
-## Step 0: Project Foundation
-
-Before shape, before code: figure out what kind of project you're working in.
-
-Look at the working directory. Run `ls`. Check for:
-
-- An existing framework: `astro.config.mjs/ts`, `next.config.js/ts`, `nuxt.config.ts`, `svelte.config.js`, `vite.config.js/ts`, `package.json` with framework deps, `Cargo.toml` + Leptos/Yew, `Gemfile` + Rails. **If found, use it.** Do not start a parallel build, do not introduce a second framework, do not write to `dist/` or `build/` directly. Whatever pipeline the project has, respect it.
-- An existing component library or design system: `src/components/`, `app/components/`, a `tokens.css` / `theme.ts`, an `astro.config` `integrations`. Read what's there before adding to it.
-- An existing icon set: `lucide-react`, `@phosphor-icons/react`, `@iconify/*`, hand-rolled SVG sprites in `assets/icons/`. **Use what's already in the project**; don't introduce a second set.
-
-If the directory is empty (greenfield), don't pick a framework silently. Ask the user via the AskUserQuestion tool, with sensible defaults framed by the brief:
-
-```text
-What should this be built on?
- - Astro (default for content-led brand sites, landing pages, marketing surfaces)
- - SvelteKit / Next.js / Nuxt (when the brief implies an app surface or significant interactivity)
- - Single index.html (one-shot demo, prototype, or a deliberately framework-free experiment)
-```
-
-Default: Astro for brand briefs, the project's existing framework for product briefs. Ask once; don't re-ask mid-task.
-
-## Step 1: Shape the Design
-
-Run /impeccable shape, passing along whatever feature description the user provided. Shape is **required** for craft; it is what produces a confirmed direction.
-
-Present the shape output and stop. Wait for the user to confirm, override, or course-correct before writing code.
-
-If the user already supplied a confirmed brief or ran shape separately, use it and skip this step.
-
-When the original prompt + PRODUCT.md already answer scope, content, and visual direction with no real ambiguity, the shape output can be **compact** (3-5 bullets stating what you're building and the visual lane, ending with one or two specific questions or "confirm or override"). The full 10-section structured brief is reserved for genuinely ambiguous, multi-screen, or stakeholder-heavy tasks. Don't pad a clear brief into a long one to look thorough; equally, don't skip the pause to look efficient.
-
-If the harness has native image generation (Codex), a compact shape's "confirm or override" advances to **Step 3 and the codex.md flow**, not to Step 4. Phrase the closing line accordingly: "Confirm or override; once we lock direction, I'll run a couple of palette and reference questions before generating any mocks." This stops the model from reading shape confirmation as code-green.
-
-## Step 2: Load References
-
-Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult:
-
-- [spatial-design.md](spatial-design.md) for layout and spacing
-- [typography.md](typography.md) for type hierarchy
-
-Then add references based on the brief's needs:
-- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md)
-- Animation or transitions? Consult [motion-design.md](motion-design.md)
-- Color-heavy or themed? Consult [color-and-contrast.md](color-and-contrast.md)
-- Responsive requirements? Consult [responsive-design.md](responsive-design.md)
-- Heavy on copy, labels, or errors? Consult [ux-writing.md](ux-writing.md)
-
-## Step 3: Visual Direction & Assets (Harness-Gated)
-
-If the harness has **native image generation** (currently Codex via `image_gen`), this step is mandatory. **Stop and load [codex.md](codex.md)**. It covers palette generation, mock exploration, the approval loop, mock-fidelity inventory, and asset slicing via the `impeccable_asset_producer` subagent. Follow Steps A-F in that file, then return here for Step 4.
-
-If the harness lacks native image generation, **state in one line that the visual-direction-by-generation step is being skipped because the harness lacks native image generation, then proceed**. The one-line announcement is required; it forces a conscious decision instead of letting the step quietly evaporate. The brief is your only visual reference. Implement directly from it, treating any named anchor references and the brief's "Design Direction" as the contract.
-
-Whether you generated mocks or not: don't replace required imagery with generic cards, bullets, emoji, fake metrics, decorative CSS panels, or filler copy. Image-led briefs (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product) need real or sourced imagery in the build, not CSS scenery.
-
-## Step 4: Build to Production Quality
-
-**Precondition.** If Step 3 routed you to codex.md (native image generation available), Steps A through D in that file must be complete before any code: questions answered, palette confirmed, mocks generated, one direction approved or delegated. **Do not mention implementation, file paths, or patch plans until that's done.** A confirmed shape brief is not enough; the model that compressed those gates is the model that already failed this flow.
-
-Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration.
-
-### Production bar
-
-- **Real content.** No placeholder copy, placeholder images, dead links, fake controls, or unused scaffold at presentation time.
-- **Preserve the approved mock's major ingredients.** Missing hero objects, world/product imagery, section structure, CTA/nav treatment, or distinctive motifs are blocking defects unless the user accepted the change.
-- **Semantic first.** Real headings, landmarks, labels, form associations, button/link semantics, accessible names, state announcements where needed.
-- **Deliberate spacing and alignment.** No default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment.
-- **Intentional typography.** Chosen loading strategy, clear hierarchy, readable measure, stable line breaks, no overflow at any width.
-- **Realistic state coverage.** Default, hover, focus-visible, active, disabled, loading, error, success, empty, overflow, long/short text, first-run.
-- **Finished interaction quality.** Keyboard paths, touch targets, feedback timing, scroll behavior, state transitions, no hover-only functionality.
-- **Coherent icon set.** Use the project's established set; otherwise pick one library or use accessible text. Don't mix.
-- **Respect the build pipeline.** Edit source files and run the project's build (`npm run build` or equivalent). Don't write to `build/` / `dist/` / `.next/` with `cat`, heredoc, or Bash redirects; that skips asset hashing, image optimization, code splitting, and CSS extraction, and produces output the dev server won't serve.
-- **Verify image URLs before referencing them.** Use image-search MCP or web-fetch when available; guessed photo IDs ship as broken-image placeholders. Without verification, prefer fewer images you're confident about.
-- **Optimized imagery and media.** Correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset`/`picture` for raster, no project-referenced asset left outside the workspace.
-- **Premium motion.** Use atmospheric blur, filter, mask, shadow, reveal when they improve the experience. Avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion.
-- **Maintainable.** Reusable local patterns, clear component boundaries, project conventions. No rasterized UI text or one-off hacks when a local pattern exists.
-- **Technically clean.** Production build passes, no console errors, no avoidable layout shift, no needless dependencies, no broken asset paths.
-- **Ask when uncertain.** If a discovery materially changes the brief or approved direction, stop and ask. Don't guess.
-
-## Step 5: Iterate Visually
-
-Look at what you built like a designer would. Your eyes are whatever the harness gives you: a connected browser, a screenshotting tool, Playwright, or asking the user. Use them for responsive testing (mobile, tablet, desktop minimum) and general visual validation.
-
-If your tool returns a file path, read the PNG back into the conversation. A screenshot you didn't read doesn't count.
-
-For long-form brand surfaces, inspect major sections individually. Thumbnails hide spacing, clipping, and cascade defects.
-
-After the first pass, write an honest critique against the brief, the approved mock's major ingredients (hero silhouette, motifs, imagery, nav/CTA, density), and impeccable's DON'Ts. Patch material defects and re-inspect. **Don't invent defects to demonstrate iteration.** A confident "first pass clean, shipping" beats a fake fix.
-
-Actively check: responsive behavior (composes, not shrinks), every state (empty / error / loading / edge), craft details (spacing, alignment, hierarchy, contrast, motion timing, focus), performance basics. The exit bar: defensible in a high-end studio review.
-
-Detector or QA output is defect evidence only; never proof the work is finished.
-
-## Step 6: Present
-
-Present the result to the user:
-- Show the feature in its primary state
-- Summarize the browser/viewports checked and the most important fixes made after inspection
-- Walk through the key states (empty, error, responsive)
-- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients.
-- Note any remaining limitations or follow-up risks honestly
-- Ask: "What's working? What isn't?"
@@ -1,236 +0,0 @@
-### Purpose
-
-Resolve one stable target, run two independent assessments, synthesize a design critique, persist a snapshot, and ask the user what to improve next. The chat response is the primary deliverable; the snapshot is an archive/backlog for future commands.
-
-### Hard Invariants
-
-- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
-- Assessment A must finish before detector findings enter the parent synthesis context. Detector output is deterministic, but it still anchors judgment.
-- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize.
-- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
-- Viewable targets require browser inspection when available.
-- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
-- Do not claim a user-visible overlay exists unless script injection succeeded and the detector ran in the page.
-
-### Setup
-
-1. **Resolve the target** to a concrete file path or URL. Prefer a source path over a dev-server URL when both identify the same surface; ports drift, paths do not.
- - "the homepage" -> `site/pages/index.astro` or `index.html`
- - "the settings modal" -> the primary component file
- - "this page" -> the current URL or source file
-2. **Compute the slug**:
- ```bash
- node .trae/skills/impeccable/scripts/critique-storage.mjs slug "<resolved-path-or-url>"
- ```
- Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique.
-3. **Read `.impeccable/critique/ignore.md`** if it exists. Drop matching findings silently; it is the only prior-run input critique consumes.
-
-### Assessment Orchestration
-
-Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis.
-
-If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
-
-### Assessment A: Design Review
-
-Read relevant source files and visually inspect the live page when browser automation is available. Think like a design director.
-
-Evaluate:
-- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill.
-- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases.
-- **Cognitive load**: consult [cognitive-load](cognitive-load.md); report checklist failures and decision points with >4 visible options.
-- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments.
-- **Nielsen heuristics**: consult [heuristics-scoring](heuristics-scoring.md); score all 10 heuristics 0-4.
-
-Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions.
-
-### Assessment B: Detector + Browser Evidence
-
-Run the bundled detector and browser visualization evidence. Assessment B is mandatory and must remain isolated from Assessment A until both are complete.
-
-CLI scan:
-```bash
-node .trae/skills/impeccable/scripts/detect.mjs --json [--fast] [target]
-```
-
-- Pass markup files/directories as `[target]`; do not pass CSS-only files.
-- For URLs, skip CLI scan and use browser visualization.
-- For 200+ scannable files, use `--fast`; for 500+, narrow scope or ask.
-- Exit code 0 = clean; 2 = findings.
-- If the detector entrypoint is missing or fails to load, report deterministic scan unavailable and continue with browser/manual review.
-
-Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
-
-1. Create a fresh tab and navigate.
-2. Preflight mutable injection by setting `document.title` and appending a `<script>` tag. Read-only evaluate APIs do not count.
-3. If mutation is unavailable, skip live server, browser presentation, and injection; report fallback signal.
-4. If mutation is available, start `node .trae/skills/impeccable/scripts/live-server.mjs --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then stop the live server.
-5. For multi-view targets, inject on 3-5 representative pages.
-
-Return: CLI findings JSON/counts, browser console findings if applicable, false positives, and skipped/failed browser steps with concrete reasons.
-
-After Assessment B returns usable CLI findings, reuse them. Do not rerun `detect.mjs` in the parent unless Assessment B failed, was truncated, or omitted count, rule names, or file locations.
-
-### Generate Combined Critique Report
-
-Synthesize both assessments into a single report. Do NOT simply concatenate. Weave the findings together, noting where the LLM review and detector agree, where the detector caught issues the LLM missed, and where detector findings are false positives.
-
-The chat response is the primary user-facing deliverable. Present the full structured critique below in chat; do not replace it with a summary and a link. The persisted snapshot is only an archive/backlog for later commands.
-
-Structure your feedback as a design director would:
-
-#### Design Health Score
-> *Consult [heuristics-scoring](heuristics-scoring.md)*
-
-Present the Nielsen's 10 heuristics scores as a table:
-
-| # | Heuristic | Score | Key Issue |
-|---|-----------|-------|-----------|
-| 1 | Visibility of System Status | ? | [specific finding or "n/a" if solid] |
-| 2 | Match System / Real World | ? | |
-| 3 | User Control and Freedom | ? | |
-| 4 | Consistency and Standards | ? | |
-| 5 | Error Prevention | ? | |
-| 6 | Recognition Rather Than Recall | ? | |
-| 7 | Flexibility and Efficiency | ? | |
-| 8 | Aesthetic and Minimalist Design | ? | |
-| 9 | Error Recovery | ? | |
-| 10 | Help and Documentation | ? | |
-| **Total** | | **??/40** | **[Rating band]** |
-
-Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32.
-
-#### Anti-Patterns Verdict
-
-**Start here.** Does this look AI-generated?
-
-**LLM assessment**: Your own evaluation of AI slop tells. Cover overall aesthetic feel, layout sameness, generic composition, missed opportunities for personality.
-
-**Deterministic scan**: Summarize what the automated detector found, with counts and file locations. Note any additional issues the detector caught that you missed, and flag any false positives.
-
-**Visual overlays** (if injection succeeded): Tell the user that overlays are now visible in the **[Human]** tab in their browser, highlighting the detected issues. Summarize what the console output reported. If browser visualization was attempted but injection failed, say that no reliable user-visible overlay is available and report the fallback signal instead.
-
-#### Overall Impression
-A brief gut reaction: what works, what doesn't, and the single biggest opportunity.
-
-#### What's Working
-Highlight 2-3 things done well. Be specific about why they work.
-
-#### Priority Issues
-The 3-5 most impactful design problems, ordered by importance.
-
-For each issue, tag with **P0-P3 severity** (consult [heuristics-scoring](heuristics-scoring.md) for severity definitions):
-- **[P?] What**: Name the problem clearly
-- **Why it matters**: How this hurts users or undermines goals
-- **Fix**: What to do about it (be concrete)
-- **Suggested command**: Which command could address this (from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
-
-#### Persona Red Flags
-> *Consult [personas](personas.md)*
-
-Auto-select 2-3 personas most relevant to this interface type (use the selection table in the reference). If `RULES.md` contains a `## Design Context` section from `impeccable teach`, also generate 1-2 project-specific personas from the audience/brand info.
-
-For each selected persona, walk through the primary user action and list specific red flags found:
-
-**Alex (Power User)**: No keyboard shortcuts detected. Form requires 8 clicks for primary action. Forced modal onboarding. High abandonment risk.
-
-**Jordan (First-Timer)**: Icon-only nav in sidebar. Technical jargon in error messages ("404 Not Found"). No visible help. Will abandon at step 2.
-
-Be specific. Name the exact elements and interactions that fail each persona. Don't write generic persona descriptions; write what broke for them.
-
-#### Minor Observations
-Quick notes on smaller issues worth addressing.
-
-#### Questions to Consider
-Provocative questions that might unlock better solutions:
-- "What if the primary action were more prominent?"
-- "Does this need to feel this complex?"
-- "What would a confident version of this look like?"
-
-**Remember**:
-- Be direct. Vague feedback wastes everyone's time.
-- Be specific. "The submit button," not "some elements."
-- Say what's wrong AND why it matters to users.
-- Give concrete suggestions. Cut "consider exploring..." entirely.
-- Prioritize ruthlessly. If everything is important, nothing is.
-- Don't soften criticism. Developers need honest feedback to ship great design.
-
-### Persist the Snapshot
-
-Once the report above is finalized, write it to `.impeccable/critique/` so the user can refer back, and so `/impeccable polish` can pick up the priority issues without a copy-paste.
-
-Skip this step if the Setup slug was null (vague or root-level target).
-
-1. **Write the body to a temp file** so you can pipe it to the helper. Use the full critique report (heuristic table, anti-patterns verdict, priority issues, persona red flags, minor observations, and questions), but stop before the "Ask the User" / "Recommended Actions" sections that come later.
-
-2. **Pass the structured metadata** through `IMPECCABLE_CRITIQUE_META` (JSON), then run the write command:
- ```bash
- IMPECCABLE_CRITIQUE_META='{"target":"<user phrasing>","total_score":<n>,"p0_count":<n>,"p1_count":<n>}' \
- node .trae/skills/impeccable/scripts/critique-storage.mjs write <slug> <body-file>
- ```
- The helper prints the absolute path it wrote.
-
-3. **Delete the temp body file** after the write attempt completes, whether the write succeeded or failed. If deletion fails, mention `temp-file cleanup failed: <reason>` briefly in the final output, but do not block the critique.
-
-4. **Read the trend** for context:
- ```bash
- node .trae/skills/impeccable/scripts/critique-storage.mjs trend <slug> 5
- ```
- This returns a JSON array of the last 5 frontmatter entries (including the one you just wrote).
-
-5. **Append a single line to the user-visible output**, after the report and before the questions:
-
- > **Trend for `<slug>` (last 5 runs): 24 → 28 → 32 → 29 → 32**
- > Wrote `.impeccable/critique/<filename>`.
-
- If this is the first run for the slug, the trend is just one score; say so: "First run for this target, no trend yet."
-
-This is fire-and-forget. Do not show the user the helper's JSON output; only the human-readable trend line and the written path. Failures here should not block the rest of the flow; print the error and move on.
-
-### Ask the User
-
-**After presenting findings**, use targeted questions based on what was actually found. ask the user directly to clarify what you cannot infer. These answers will shape the action plan.
-
-Ask questions along these lines (adapt to the specific findings; do NOT ask generic questions):
-
-1. **Priority direction**: Based on the issues found, ask which category matters most to the user right now. For example: "I found problems with visual hierarchy, color usage, and information overload. Which area should we tackle first?" Offer the top 2-3 issue categories as options.
-
-2. **Design intent**: If the critique found a tonal mismatch, ask whether it was intentional. For example: "The interface feels clinical and corporate. Is that the intended tone, or should it feel warmer/bolder/more playful?" Offer 2-3 tonal directions as options based on what would fix the issues found.
-
-3. **Scope**: Ask how much the user wants to take on. For example: "I found N issues. Want to address everything, or focus on the top 3?" Offer scope options like "Top 3 only", "All issues", "Critical issues only".
-
-4. **Constraints** (optional; only ask if relevant): If the findings touch many areas, ask if anything is off-limits. For example: "Should any sections stay as-is?" This prevents the plan from touching things the user considers done.
-
-**Rules for questions**:
-- Every question must reference specific findings from the report. Never ask generic "who is your audience?" questions.
-- Keep it to 2-4 questions maximum. Respect the user's time.
-- Offer concrete options, not open-ended prompts.
-- If findings are straightforward (e.g., only 1-2 clear issues), skip questions and go directly to Recommended Actions.
-
-### Recommended Actions
-
-**After receiving the user's answers**, present a prioritized action summary reflecting the user's priorities and scope from Ask the User.
-
-#### Action Summary
-
-List recommended commands in priority order, based on the user's answers:
-
-1. **`/command-name`**: Brief description of what to fix (specific context from critique findings)
-2. **`/command-name`**: Brief description (specific context)
-...
-
-**Rules for recommendations**:
-- Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset
-- Order by the user's stated priorities first, then by impact
-- Each item's description should carry enough context that the command knows what to focus on
-- Map each Priority Issue to the appropriate command
-- Skip commands that would address zero issues
-- If the user chose a limited scope, only include items within that scope
-- If the user marked areas as off-limits, exclude commands that would touch those areas
-- End with `/impeccable polish` as the final step if any fixes were recommended
-
-After presenting the summary, tell the user:
-
-> You can ask me to run these one at a time, all at once, or in any order you prefer.
->
-> Re-run `/impeccable critique` after fixes to see your score improve.
@@ -1,302 +0,0 @@
-> **Additional context needed**: what's appropriate for the domain (playful vs professional vs quirky vs elegant).
-
-Find the moments where personality and unexpected polish would turn a functional interface into one users remember and tell other people about. Add only where the moment earns it; delight everywhere reads as noise.
-
----
-
-## Register
-
-Brand: delight can be distributed across copy voice, section transitions, discovery rewards, seasonal touches, personality across the whole surface.
-
-Product: delight at specific moments, not pages. Completion, first-time actions, error recovery, milestone crossings. Reliability and consistency carry the rest of the experience; delight pushed everywhere reads as noise.
-
----
-
-## Assess Delight Opportunities
-
-Identify where delight would enhance (not distract from) the experience:
-
-1. **Find natural delight moments**:
- - **Success states**: Completed actions (save, send, publish)
- - **Empty states**: First-time experiences, onboarding
- - **Loading states**: Waiting periods that could be entertaining
- - **Achievements**: Milestones, streaks, completions
- - **Interactions**: Hover states, clicks, drags
- - **Errors**: Softening frustrating moments
- - **Easter eggs**: Hidden discoveries for curious users
-
-2. **Understand the context**:
- - What's the brand personality? (Playful? Professional? Quirky? Elegant?)
- - Who's the audience? (Tech-savvy? Creative? Corporate?)
- - What's the emotional context? (Accomplishment? Exploration? Frustration?)
- - What's appropriate? (Banking app ≠ gaming app)
-
-3. **Define delight strategy**:
- - **Subtle sophistication**: Refined micro-interactions (luxury brands)
- - **Playful personality**: Whimsical illustrations and copy (consumer apps)
- - **Helpful surprises**: Anticipating needs before users ask (productivity tools)
- - **Sensory richness**: Satisfying sounds, smooth animations (creative tools)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Delight should enhance usability, never obscure it. If users notice the delight more than accomplishing their goal, you've gone too far.
-
-## Delight Principles
-
-Follow these guidelines:
-
-### Delight Amplifies, Never Blocks
-- Delight moments should be quick (< 1 second)
-- Never delay core functionality for delight
-- Make delight skippable or subtle
-- Respect user's time and task focus
-
-### Surprise and Discovery
-- Hide delightful details for users to discover
-- Reward exploration and curiosity
-- Don't announce every delight moment
-- Let users share discoveries with others
-
-### Appropriate to Context
-- Match delight to emotional moment (celebrate success, empathize with errors)
-- Respect the user's state (don't be playful during critical errors)
-- Match brand personality and audience expectations
-- Cultural sensitivity (what's delightful varies by culture)
-
-### Compound Over Time
-- Delight should remain fresh with repeated use
-- Vary responses (not same animation every time)
-- Reveal deeper layers with continued use
-- Build anticipation through patterns
-
-## Delight Techniques
-
-Add personality and joy through these methods:
-
-### Micro-interactions & Animation
-
-**Button delight**:
-```css
-/* Satisfying button press */
-.button {
- transition: transform 0.1s, box-shadow 0.1s;
-}
-.button:active {
- transform: translateY(2px);
- box-shadow: 0 2px 4px rgba(0,0,0,0.2);
-}
-
-/* Ripple effect on click */
-/* Smooth lift on hover */
-.button:hover {
- transform: translateY(-2px);
- transition: transform 0.2s cubic-bezier(0.25, 1, 0.5, 1); /* ease-out-quart */
-}
-```
-
-**Loading delight**:
-- Playful loading animations (not just spinners)
-- Personality in loading messages (write product-specific ones, not generic AI filler)
-- Progress indication with encouraging messages
-- Skeleton screens with subtle animations
-
-**Success animations**:
-- Checkmark draw animation
-- Confetti burst for major achievements
-- Gentle scale + fade for confirmation
-- Satisfying sound effects (subtle)
-
-**Hover surprises**:
-- Icons that animate on hover
-- Color shifts or glow effects
-- Tooltip reveals with personality
-- Cursor changes (custom cursors for branded experiences)
-
-### Personality in Copy
-
-**Playful error messages**:
-```
-"Error 404"
-"This page is playing hide and seek. (And winning)"
-
-"Connection failed"
-"Looks like the internet took a coffee break. Want to retry?"
-```
-
-**Encouraging empty states**:
-```
-"No projects"
-"Your canvas awaits. Create something amazing."
-
-"No messages"
-"Inbox zero! You're crushing it today."
-```
-
-**Playful labels & tooltips**:
-```
-"Delete"
-"Send to void" (for playful brand)
-
-"Help"
-"Rescue me" (tooltip)
-```
-
-**IMPORTANT**: Match copy personality to brand. Banks shouldn't be wacky, but they can be warm.
-
-### Illustrations & Visual Personality
-
-**Custom illustrations**:
-- Empty state illustrations (not stock icons)
-- Error state illustrations (friendly monsters, quirky characters)
-- Loading state illustrations (animated characters)
-- Success state illustrations (celebrations)
-
-**Icon personality**:
-- Custom icon set matching brand personality
-- Animated icons (subtle motion on hover/click)
-- Illustrative icons (more detailed than generic)
-- Consistent style across all icons
-
-**Background effects**:
-- Subtle particle effects
-- Gradient mesh backgrounds
-- Geometric patterns
-- Parallax depth
-- Time-of-day themes (morning vs night)
-
-### Satisfying Interactions
-
-**Drag and drop delight**:
-- Lift effect on drag (shadow, scale)
-- Snap animation when dropped
-- Satisfying placement sound
-- Undo toast ("Dropped in wrong place? [Undo]")
-
-**Toggle switches**:
-- Smooth slide with spring physics
-- Color transition
-- Haptic feedback on mobile
-- Optional sound effect
-
-**Progress & achievements**:
-- Streak counters with celebratory milestones
-- Progress bars that "celebrate" at 100%
-- Badge unlocks with animation
-- Playful stats ("You're on fire! 5 days in a row")
-
-**Form interactions**:
-- Input fields that animate on focus
-- Checkboxes with a satisfying scale pulse when checked
-- Success state that celebrates valid input
-- Auto-grow textareas
-
-### Sound Design
-
-**Subtle audio cues** (when appropriate):
-- Notification sounds (distinctive but not annoying)
-- Success sounds (satisfying "ding")
-- Error sounds (empathetic, not harsh)
-- Typing sounds for chat/messaging
-- Ambient background audio (very subtle)
-
-**IMPORTANT**:
-- Respect system sound settings
-- Provide mute option
-- Keep volumes quiet (subtle cues, not alarms)
-- Don't play on every interaction (sound fatigue is real)
-
-### Easter Eggs & Hidden Delights
-
-**Discovery rewards**:
-- Konami code unlocks special theme
-- Hidden keyboard shortcuts (Cmd+K for special features)
-- Hover reveals on logos or illustrations
-- Alt text jokes on images (for screen reader users too!)
-- Console messages for developers ("Like what you see? We're hiring!")
-
-**Seasonal touches**:
-- Holiday themes (subtle, tasteful)
-- Seasonal color shifts
-- Weather-based variations
-- Time-based changes (dark at night, light during day)
-
-**Contextual personality**:
-- Different messages based on time of day
-- Responses to specific user actions
-- Randomized variations (not same every time)
-- Progressive reveals with continued use
-
-### Loading & Waiting States
-
-**Make waiting engaging**:
-- Interesting loading messages that rotate
-- Progress bars with personality
-- Mini-games during long loads
-- Fun facts or tips while waiting
-- Countdown with encouraging messages
-
-```
-Loading messages: write ones specific to your product, not generic AI filler:
-- "Crunching your latest numbers..."
-- "Syncing with your team's changes..."
-- "Preparing your dashboard..."
-- "Checking for updates since yesterday..."
-```
-
-**WARNING**: Avoid cliched loading messages like "Herding pixels", "Teaching robots to dance", "Consulting the magic 8-ball", "Counting backwards from infinity". These are AI-slop copy, instantly recognizable as machine-generated. Write messages that are specific to what your product actually does.
-
-### Celebration Moments
-
-**Success celebrations**:
-- Confetti for major milestones
-- Animated checkmarks for completions
-- Progress bar celebrations at 100%
-- "Achievement unlocked" style notifications
-- Personalized messages ("You published your 10th article!")
-
-**Milestone recognition**:
-- First-time actions get special treatment
-- Streak tracking and celebration
-- Progress toward goals
-- Anniversary celebrations
-
-## Implementation Patterns
-
-**Animation libraries**:
-- Framer Motion (React)
-- GSAP (universal)
-- Lottie (After Effects animations)
-- Canvas confetti (party effects)
-
-**Sound libraries**:
-- Howler.js (audio management)
-- Use-sound (React hook)
-
-**Physics libraries**:
-- React Spring (spring physics)
-- Popmotion (animation primitives)
-
-**IMPORTANT**: File size matters. Compress images, optimize animations, lazy load delight features.
-
-**NEVER**:
-- Delay core functionality for delight
-- Force users through delightful moments (make skippable)
-- Use delight to hide poor UX
-- Overdo it (less is more)
-- Ignore accessibility (animate responsibly, provide alternatives)
-- Make every interaction delightful (special moments should be special)
-- Sacrifice performance for delight
-- Be inappropriate for context (read the room)
-
-## Verify Delight Quality
-
-Test that delight actually delights:
-
-- **User reactions**: Do users smile? Share screenshots?
-- **Doesn't annoy**: Still pleasant after 100th time?
-- **Doesn't block**: Can users opt out or skip?
-- **Performant**: No jank, no slowdown
-- **Appropriate**: Matches brand and context
-- **Accessible**: Works with reduced motion, screen readers
-
-When the moments feel earned, hand off to `/impeccable polish` for the final pass.
@@ -1,111 +0,0 @@
-Strip a design to its essence. Remove anything that doesn't earn its place: redundant elements, repeated information, decorative noise, cosmetic complexity.
-
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel complex or cluttered:
-
-1. **Identify complexity sources**:
- - **Too many elements**: Competing buttons, redundant information, visual clutter
- - **Excessive variation**: Too many colors, fonts, sizes, styles without purpose
- - **Information overload**: Everything visible at once, no progressive disclosure
- - **Visual noise**: Unnecessary borders, shadows, backgrounds, decorations
- - **Confusing hierarchy**: Unclear what matters most
- - **Feature creep**: Too many options, actions, or paths forward
-
-2. **Find the essence**:
- - What's the primary user goal? (There should be ONE)
- - What's actually necessary vs nice-to-have?
- - What can be removed, hidden, or combined?
- - What's the 20% that delivers 80% of value?
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: Simplicity is not about removing features. It's about removing obstacles between users and their goals. Every element should justify its existence.
-
-## Plan Simplification
-
-Create a ruthless editing strategy:
-
-- **Core purpose**: What's the ONE thing this should accomplish?
-- **Essential elements**: What's truly necessary to achieve that purpose?
-- **Progressive disclosure**: What can be hidden until needed?
-- **Consolidation opportunities**: What can be combined or integrated?
-
-**IMPORTANT**: Simplification is hard. It requires saying no to good ideas to make room for great execution. Be ruthless.
-
-## Simplify the Design
-
-Systematically remove complexity across these dimensions:
-
-### Information Architecture
-- **Reduce scope**: Remove secondary actions, optional features, redundant information
-- **Progressive disclosure**: Hide complexity behind clear entry points (accordions, modals, step-through flows)
-- **Combine related actions**: Merge similar buttons, consolidate forms, group related content
-- **Clear hierarchy**: ONE primary action, few secondary actions, everything else tertiary or hidden
-- **Remove redundancy**: If it's said elsewhere, don't repeat it here
-
-### Visual Simplification
-- **Reduce color palette**: Use 1-2 colors plus neutrals, not 5-7 colors
-- **Limit typography**: One font family, 3-4 sizes maximum, 2-3 weights
-- **Remove decorations**: Eliminate borders, shadows, backgrounds that don't serve hierarchy or function
-- **Flatten structure**: Reduce nesting, remove unnecessary containers; never nest cards inside cards
-- **Remove unnecessary cards**: Cards aren't needed for basic layout; use spacing and alignment instead
-- **Consistent spacing**: Use one spacing scale, remove arbitrary gaps
-
-### Layout Simplification
-- **Linear flow**: Replace complex grids with simple vertical flow where possible
-- **Remove sidebars**: Move secondary content inline or hide it
-- **Full-width**: Use available space generously instead of complex multi-column layouts
-- **Consistent alignment**: Pick left or center, stick with it
-- **Generous white space**: Let content breathe, don't pack everything tight
-
-### Interaction Simplification
-- **Reduce choices**: Fewer buttons, fewer options, clearer path forward (paradox of choice is real)
-- **Smart defaults**: Make common choices automatic, only ask when necessary
-- **Inline actions**: Replace modal flows with inline editing where possible
-- **Remove steps**: Can signup be one step instead of three? Can checkout be simplified?
-- **Clear CTAs**: ONE obvious next step, not five competing actions
-
-### Content Simplification
-- **Shorter copy**: Cut every sentence in half, then do it again
-- **Active voice**: "Save changes" not "Changes will be saved"
-- **Remove jargon**: Plain language always wins
-- **Scannable structure**: Short paragraphs, bullet points, clear headings
-- **Essential information only**: Remove marketing fluff, legalese, hedging
-- **Remove redundant copy**: No headers restating intros, no repeated explanations, say it once
-
-### Code Simplification
-- **Remove unused code**: Dead CSS, unused components, orphaned files
-- **Flatten component trees**: Reduce nesting depth
-- **Consolidate styles**: Merge similar styles, use utilities consistently
-- **Reduce variants**: Does that component need 12 variations, or can 3 cover 90% of cases?
-
-**NEVER**:
-- Remove necessary functionality (simplicity ≠ feature-less)
-- Sacrifice accessibility for simplicity (clear labels and ARIA still required)
-- Make things so simple they're unclear (mystery ≠ minimalism)
-- Remove information users need to make decisions
-- Eliminate hierarchy completely (some things should stand out)
-- Oversimplify complex domains (match complexity to actual task complexity)
-
-## Verify Simplification
-
-Ensure simplification improves usability:
-
-- **Faster task completion**: Can users accomplish goals more quickly?
-- **Reduced cognitive load**: Is it easier to understand what to do?
-- **Still complete**: Are all necessary features still accessible?
-- **Clearer hierarchy**: Is it obvious what matters most?
-- **Better performance**: Does simpler design load faster?
-
-## Document Removed Complexity
-
-If you removed features or options:
-- Document why they were removed
-- Consider if they need alternative access points
-- Note any user feedback to monitor
-
-When the cuts feel right, hand off to `/impeccable polish` for the final pass. As Antoine de Saint-Exupéry put it: "Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away."
@@ -1,427 +0,0 @@
-Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
-
-DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
-
-## The frontmatter: token schema
-
-The YAML frontmatter is the machine-readable layer. It's what Stitch's linter validates and what the live panel renders tiles from. Keep it tight; every entry should correspond to a token the project actually uses.
-
-```yaml
----
-name: <project title>
-description: <one-line tagline>
-colors:
- primary: "#b8422e"
- neutral-bg: "#faf7f2"
- # ...one entry per extracted color; key = descriptive slug
-typography:
- display:
- fontFamily: "Cormorant Garamond, Georgia, serif"
- fontSize: "clamp(2.5rem, 7vw, 4.5rem)"
- fontWeight: 300
- lineHeight: 1
- letterSpacing: "normal"
- body:
- # ...
-rounded:
- sm: "4px"
- md: "8px"
-spacing:
- sm: "8px"
- md: "16px"
-components:
- button-primary:
- backgroundColor: "{colors.primary}"
- textColor: "{colors.neutral-bg}"
- rounded: "{rounded.sm}"
- padding: "16px 48px"
- button-primary-hover:
- backgroundColor: "{colors.primary-deep}"
----
-```
-
-Rules that matter:
-
-- **Token refs** use `{path.to.token}` (e.g. `{colors.primary}`, `{rounded.md}`). Components may reference primitives; primitives may not reference each other.
-- **Stitch validates colors as hex sRGB only** (`#RGB` / `#RGBA` / `#RRGGBB` / `#RRGGBBAA`); OKLCH/HSL/P3 trigger a linter warning, not a hard error. YAML accepts the string either way and our own parser is format-agnostic. Choose based on project posture: (a) if the project has an "OKLCH-only" doctrine or uses Display-P3 values that don't round-trip through sRGB, put OKLCH directly in the frontmatter and accept the Stitch linter warning; (b) if the project wants strict Stitch compliance or plans to use their Tailwind/DTCG export pipeline, put hex in the frontmatter and keep OKLCH in prose as the canonical reference. Never split the source of truth without explicit reason.
-- **Component sub-tokens** are limited to 8 props: `backgroundColor`, `textColor`, `typography`, `rounded`, `padding`, `size`, `height`, `width`. Shadows, motion, focus rings, backdrop-filter: none of those fit. Carry them in the sidecar (Step 4b).
-- **Scale keys are open-ended.** Use whatever names the project already uses (`warm-ash-cream`, `surface-container-low`). Don't rename to Material defaults.
-- **Variants are naming convention, not schema.** `button-primary` / `button-primary-hover` / `button-primary-active` as sibling keys.
-
-## The markdown body: six sections (exact order)
-
-1. `## Overview`
-2. `## Colors`
-3. `## Typography`
-4. `## Elevation`
-5. `## Components`
-6. `## Do's and Don'ts`
-
-Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] Palette` (Stitch's own outputs do this), but the literal word in each header (Overview, Colors, Typography, Elevation, Components, Do's and Don'ts) must be present. Do NOT add extra top-level sections (Layout Principles, Responsive Behavior, Motion, Agent Prompt Guide). Fold that content into the six spec sections where it naturally belongs.
-
-## When to run
-
-- The user just ran `/impeccable teach` and needs the visual side documented.
-- The skill noticed no `DESIGN.md` exists and nudged the user to create one.
-- An existing `DESIGN.md` is stale (the design has drifted).
-- Before a large redesign, to capture the current state as a reference.
-
-If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user the existing file and ask the user directly to clarify what you cannot infer. whether to refresh, overwrite, or merge.
-
-## Two paths
-
-- **Scan mode** (default): the project has design tokens, components, or rendered output. Extract, then confirm descriptive language. Use when there's code to analyze.
-- **Seed mode**: the project is pre-implementation (fresh teach, nothing built yet). Interview for five high-level answers, write a minimal DESIGN.md marked `<!-- SEED -->`. Re-run in scan mode once there's code.
-
-Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode; don't silently switch. `/impeccable document --seed` forces seed mode regardless of code presence.
-
-## Scan mode (approach C: auto-extract, then confirm descriptive language)
-
-### Step 1: Find the design assets
-
-Search the codebase in priority order:
-
-1. **CSS custom properties**: grep for `--color-`, `--font-`, `--spacing-`, `--radius-`, `--shadow-`, `--ease-`, `--duration-` declarations in CSS files (usually `src/styles/`, `public/css/`, `app/globals.css`, etc.). Record name, value, and the file it's defined in.
-2. **Tailwind config**: if `tailwind.config.{js,ts,mjs}` exists, read the `theme.extend` block for colors, fontFamily, spacing, borderRadius, boxShadow.
-3. **CSS-in-JS theme files**: styled-components, emotion, vanilla-extract, stitches; look for `theme.ts`, `tokens.ts`, or equivalent.
-4. **Design token files**: `tokens.json`, `design-tokens.json`, Style Dictionary output, W3C token community group format.
-5. **Component library**: scan the main button, card, input, navigation, dialog components. Note their variant APIs and default styles.
-6. **Global stylesheet**: the root CSS file usually has the base typography and color assignments.
-7. **Visible rendered output**: if browser automation tools are available, load the live site and sample computed styles from key elements (body, h1, a, button, .card). This catches values that tokens miss.
-
-### Step 2: Auto-extract what can be auto-extracted
-
-Build a structured draft from the discovered tokens. For each token class:
-
-- **Colors**: Group into Primary / Secondary / Tertiary / Neutral (the Material-derived roles Stitch uses). If the project only has one accent, express it as Primary + Neutral; omit Secondary and Tertiary rather than inventing them.
-- **Typography**: Map observed sizes and weights to the Material hierarchy (display / headline / title / body / label). Note font-family stacks and the scale ratio.
-- **Elevation**: Catalogue the shadow vocabulary. If the project is flat and uses tonal layering instead, that's a valid answer; state it explicitly.
-- **Components**: For each common component (button, card, input, chip, list item, tooltip, nav), extract shape (radius), color assignment, hover/focus treatment, internal padding.
-- **Spacing + layout**: Fold into Overview or relevant Components. The spec does NOT have a Layout section.
-
-### Step 2b: Stage the frontmatter
-
-From the auto-extracted tokens, draft the YAML frontmatter now (you'll write it at the top of DESIGN.md in Step 4). This is the machine-readable layer: what the live panel and Stitch's linter consume.
-
-- **Colors**: one entry per extracted color. Key = descriptive slug (`warm-ash-cream`, `editorial-magenta`, not `blue-800`). Value = whichever format the project treats as canonical (OKLCH or hex; see the frontmatter rules above). Don't split the source of truth: one format in the frontmatter, don't redefine the same token in prose with a different value.
-- **Typography**: one entry per role (`display`, `headline`, `title`, `body`, `label`). Typography is an object; include only the props that are real for the project (`fontFamily`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `fontFeature`, `fontVariation`).
-- **Rounded / Spacing**: whatever scale steps the project actually uses, keyed by whatever scale name the project uses (`sm` / `md` / `lg`, or `surface-sm`, or numeric steps).
-- **Components**: one entry per variant (`button-primary`, `button-primary-hover`, `button-ghost`). Reference primitives via `{colors.X}`, `{rounded.Y}`. If a variant needs a property Stitch's 8-prop set doesn't cover (shadow, focus ring, backdrop-filter), carry the full snippet in the sidecar instead.
-
-Skip anything the project doesn't have. Empty scale keys or fabricated tokens pollute the spec.
-
-### Step 3: Ask the user for qualitative language
-
-The following require creative input that cannot be auto-extracted. Group them into one `AskUserQuestion` interaction:
-
-- **Creative North Star**: a single named metaphor for the whole system ("The Editorial Sanctuary", "The Golden State Curator", "The Lab Notebook"). Offer 2-3 options that honor PRODUCT.md's brand personality.
-- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, anti-references (what the system should not feel like).
-- **Color character** (for auto-extracted colors): descriptive names ("Deep Muted Teal-Navy", not "blue-800"). Suggest 2-3 options per key color based on hue/saturation.
-- **Elevation philosophy**: flat/layered/lifted. If shadows exist, is their role ambient or structural?
-- **Component philosophy**: the feel of buttons, cards, inputs in one phrase ("tactile and confident" vs. "refined and restrained").
-
-Quote a line from PRODUCT.md when possible so the user sees their own strategic language carry forward.
-
-### Step 4: Write DESIGN.md
-
-The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the structure below. Headers must match character-for-character. Optional evocative subtitles (e.g. `## 2. Colors: The Coastal Palette`) are allowed.
-
-```markdown
----
-name: [Project Title]
-description: [one-line tagline]
-colors:
- # ... staged frontmatter from Step 2b
----
-
-# Design System: [Project Title]
-
-## 1. Overview
-
-**Creative North Star: "[Named metaphor in quotes]"**
-
-[2-3 paragraph holistic description: personality, density, aesthetic philosophy. Start from the North Star and work outward. State what this system explicitly rejects (pulled from PRODUCT.md's anti-references). End with a short **Key Characteristics:** bullet list.]
-
-## 2. Colors
-
-[Describe the palette character in one sentence.]
-
-### Primary
-- **[Descriptive Name]** (#HEX / oklch(...)): [Where and why this color is used. Be specific about context, not just role.]
-
-### Secondary (optional; omit if the project has only one accent)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Tertiary (optional)
-- **[Descriptive Name]** (#HEX): [Role.]
-
-### Neutral
-- **[Descriptive Name]** (#HEX): [Text / background / border / divider role.]
-- [...]
-
-### Named Rules (optional, powerful)
-**The [Rule Name] Rule.** [Short, forceful prohibition or doctrine, e.g. "The One Voice Rule. The primary accent is used on ≤10% of any given screen. Its rarity is the point."]
-
-## 3. Typography
-
-**Display Font:** [Family] (with [fallback])
-**Body Font:** [Family] (with [fallback])
-**Label/Mono Font:** [Family, if distinct]
-
-**Character:** [1-2 sentence personality description of the pairing.]
-
-### Hierarchy
-- **Display** ([weight], [size/clamp], [line-height]): [Purpose; where it appears.]
-- **Headline** ([weight], [size], [line-height]): [Purpose.]
-- **Title** ([weight], [size], [line-height]): [Purpose.]
-- **Body** ([weight], [size], [line-height]): [Purpose. Include max line length like 65–75ch if relevant.]
-- **Label** ([weight], [size], [letter-spacing], [case if uppercase]): [Purpose.]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [Short doctrine about type use.]
-
-## 4. Elevation
-
-[One paragraph: does this system use shadows, tonal layering, or a hybrid? If "no shadows", say so explicitly and describe how depth is conveyed instead.]
-
-### Shadow Vocabulary (if applicable)
-- **[Role name]** (`box-shadow: [exact value]`): [When to use it.]
-- [...]
-
-### Named Rules (optional)
-**The [Rule Name] Rule.** [e.g. "The Flat-By-Default Rule. Surfaces are flat at rest. Shadows appear only as a response to state (hover, elevation, focus)."]
-
-## 5. Components
-
-For each component, lead with a short character line, then specify shape, color assignment, states, and any distinctive behavior.
-
-### Buttons
-- **Shape:** [radius described, exact value in parens]
-- **Primary:** [color assignment + padding, in semantic + exact terms]
-- **Hover / Focus:** [transitions, treatments]
-- **Secondary / Ghost / Tertiary (if applicable):** [brief description]
-
-### Chips (if used)
-- **Style:** [background, text color, border treatment]
-- **State:** [selected / unselected, filter / action variants]
-
-### Cards / Containers
-- **Corner Style:** [radius]
-- **Background:** [colors used]
-- **Shadow Strategy:** [reference Elevation section]
-- **Border:** [if any]
-- **Internal Padding:** [scale]
-
-### Inputs / Fields
-- **Style:** [stroke, background, radius]
-- **Focus:** [treatment, e.g. glow, border shift, etc.]
-- **Error / Disabled:** [if applicable]
-
-### Navigation
-- **Style, typography, default/hover/active states, mobile treatment.**
-
-### [Signature Component] (optional; if the project has a distinctive custom component worth documenting)
-[Description.]
-
-## 6. Do's and Don'ts
-
-Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: include exact colors, pixel values, and named anti-patterns the user mentioned in PRODUCT.md. **Every anti-reference in PRODUCT.md should show up here as a "Don't" with the same language**, so the visual spec carries the strategic line through. Quote PRODUCT.md directly where possible: if PRODUCT.md says *"avoid dark mode with purple gradients, neon accents, glassmorphism"*, the Don'ts here should repeat that by name.
-
-### Do:
-- **Do** [specific prescription with exact values / named rule].
-- **Do** [...]
-
-### Don't:
-- **Don't** [specific prohibition, e.g. "use border-left greater than 1px as a colored stripe"].
-- **Don't** [...]
-- **Don't** [...]
-```
-
-### Step 4b: Write .impeccable/design.json sidecar (extensions only)
-
-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.
-
-Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.
-
-#### Schema
-
-```json
-{
- "schemaVersion": 2,
- "generatedAt": "ISO-8601 string",
- "title": "Design System: [Project Title]",
- "extensions": {
- "colorMeta": {
- "primary": { "role": "primary", "displayName": "Editorial Magenta", "canonical": "oklch(60% 0.25 350)", "tonalRamp": ["...", "...", "..."] },
- "warm-ash-cream": { "role": "neutral", "displayName": "Warm Ash Cream", "canonical": "oklch(96% 0.005 350)", "tonalRamp": ["...", "...", "..."] }
- },
- "typographyMeta": {
- "display": { "displayName": "Display", "purpose": "Hero headlines only." }
- },
- "shadows": [
- { "name": "ambient-low", "value": "0 4px 24px rgba(0,0,0,0.12)", "purpose": "Diffuse hover glow under accent elements." }
- ],
- "motion": [
- { "name": "ease-standard", "value": "cubic-bezier(0.4, 0, 0.2, 1)", "purpose": "Default easing for state transitions." }
- ],
- "breakpoints": [
- { "name": "sm", "value": "640px" }
- ]
- },
- "components": [
- {
- "name": "Primary Button",
- "kind": "button | input | nav | chip | card | custom",
- "refersTo": "button-primary",
- "description": "One-line what and when.",
- "html": "<button class=\"ds-btn-primary\">GET STARTED</button>",
- "css": ".ds-btn-primary { background: #191c1d; color: #fff; padding: 16px 48px; letter-spacing: 0.05em; text-transform: uppercase; font-weight: 500; border: none; border-radius: 0; transition: background 0.2s, transform 0.2s; } .ds-btn-primary:hover { background: oklch(60% 0.25 350); transform: translateY(-2px); }"
- }
- ],
- "narrative": {
- "northStar": "The Editorial Sanctuary",
- "overview": "2-3 paragraphs of the philosophy, pulled from DESIGN.md Overview section.",
- "keyCharacteristics": ["...", "..."],
- "rules": [{ "name": "The One Voice Rule", "body": "...", "section": "colors|typography|elevation" }],
- "dos": ["Do use ..."],
- "donts": ["Don't use ..."]
- }
-}
-```
-
-**What changed from schemaVersion 1.** The old sidecar carried token primitive arrays (`tokens.colors[]`, `tokens.typography[]`, etc.). Those values now live in the frontmatter. The sidecar only carries metadata that can't live in the frontmatter (tonal ramps, canonical OKLCH when the hex is an approximation, display names, role hints), keyed by the frontmatter token name (`colorMeta.<token-name>`, `typographyMeta.<token-name>`). Components still carry full HTML/CSS because Stitch's 8-prop set can't hold them.
-
-#### Component translation rules
-
-The `html` and `css` fields must be **self-contained, drop-in snippets** that render correctly when injected into a shadow DOM. The panel applies them directly: no post-processing, no framework runtime.
-
-1. **Tailwind expansion.** If the source uses Tailwind (className="bg-primary text-white rounded-lg px-6 py-3"), expand every utility to literal CSS properties in the `css` string. Do **not** reference Tailwind classes; do **not** assume a Tailwind CSS bundle is loaded. Each component is self-contained.
-2. **Token resolution.** If the project exposes tokens as CSS custom properties on `:root` (e.g. `--color-primary`, `--radius-md`), reference them via `var(--color-primary)`; they inherit through the shadow DOM and stay live-bound. If tokens live only in JS theme objects (styled-components, CSS-in-JS), resolve to literal values at generation time.
-3. **Icons.** Inline as SVG. Do not reference Lucide/Heroicons packages, icon fonts, or `<img src="...">`. A typical icon is 16-24px; copy the SVG path data directly.
-4. **States.** Include `:hover`, `:focus-visible`, and (if meaningful) `:active` rules inline. A static default-only snapshot makes the panel feel dead. Hover + focus rules in the CSS make it feel alive.
-5. **Reset bloat.** Extract only the component's *distinctive* CSS (background, color, padding, border-radius, typography, transition). Skip universal resets (`box-sizing: border-box`, `line-height: inherit`, `-webkit-font-smoothing`). The panel already has a neutral canvas; don't re-ship resets.
-6. **Scoped class names.** Prefix every class with `ds-` (e.g. `ds-btn-primary`, `ds-input-search`) so component CSS doesn't collide with other components' CSS in the same shadow DOM.
-
-#### What to include
-
-Aim for a tight set of **5-10 components** that best represent the visual system:
-
-- **Canonical primitives (always include if the project has them):** button (each variant as a separate component entry), input/text field, navigation, chip/tag, card.
-- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.
-- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.
-
-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.
-
-#### Tonal ramps
-
-For each color token, generate an 8-step `tonalRamp` array: dark to light, same hue and chroma, stepped lightness from ~15% to ~95%. The panel renders this as a strip under the swatch. If the project already defines a tonal scale (Material `surface-container-low` family, Tailwind-style `blue-50..blue-900`), use those values. Otherwise synthesize in OKLCH.
-
-#### Narrative mapping
-
-Pull directly from the DESIGN.md you just wrote:
-
-- `narrative.northStar` → the `**Creative North Star: "..."**` line from Overview
-- `narrative.overview` → the philosophy paragraphs from Overview
-- `narrative.keyCharacteristics` → the bulleted `**Key Characteristics:**` list
-- `narrative.rules` → every `**The [Name] Rule.** [body]` across all sections, tagged with `section`
-- `narrative.dos` / `narrative.donts` → the bullet lists from Do's and Don'ts verbatim
-
-Do not reword. The panel shows these as secondary collapsible context; the same voice that's in the Markdown carries through.
-
-### Step 5: Confirm, refine, and refresh session cache
-
-1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).
-2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.
-3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"
-4. **Refresh the session cache.** Run `node .trae/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.
-
-## Seed mode
-
-For projects with no visual system to extract yet. Produces a minimal scaffold, not a full spec.
-
-### Step 1: Confirm seed mode
-
-Before interviewing: "There's no existing visual system to scan. I'll ask five quick questions to seed a starter DESIGN.md. You can re-run `/impeccable document` once there's code, to capture the real tokens and components. OK?"
-
-If the user prefers to skip, stop. No file.
-
-### Step 2: Five questions
-
-Group into one `AskUserQuestion` interaction. Options must be concrete.
-
-1. **Color strategy.** Pick one:
- - Restrained: tinted neutrals + one accent ≤10%
- - Committed: one saturated color carries 30–60% of the surface
- - Full palette: 3–4 named color roles, each deliberate
- - Drenched: the surface IS the color
-
- Then: one hue family or anchor reference ("deep teal", "mustard", "Klim #ff4500 orange").
-
-2. **Typography direction.** Pick one (specific fonts come later):
- - Serif display + sans body
- - Single sans (warm / technical / geometric / humanist; pick a feel)
- - Display + mono
- - Mono-forward
- - Editorial script + sans
-
-3. **Motion energy.** Pick one:
- - Restrained: state changes only
- - Responsive: feedback + transitions, no choreography
- - Choreographed: orchestrated entrances, scroll-driven sequences
-
-4. **Three named references.** Brands, products, printed objects. Not adjectives.
-
-5. **One anti-reference.** What it should NOT feel like. Also named.
-
-### Step 3: Write seed DESIGN.md
-
-Use the six-section spec from Scan mode. Populate what the interview answers; leave the rest as honest placeholders. The seed is a scaffold, not a fabricated spec.
-
-Lead the file with:
-
-```markdown
-<!-- SEED: re-run /impeccable document once there's code to capture the actual tokens and components. -->
-```
-
-Per-section guidance in seed mode:
-
-- **Overview**: Creative North Star and philosophy phrased from the answers (color strategy + motion energy + references). Reference the user's anti-reference directly.
-- **Colors**: Color strategy as a Named Rule (e.g. *"The Drenched Rule. The surface IS the color."*). Hue family or anchor reference. No hex values; mark as `[to be resolved during implementation]`.
-- **Typography**: the direction the user picked (e.g. "Serif display + sans body"). No font names yet: `[font pairing to be chosen at implementation]`.
-- **Elevation**: inferred from motion energy. Restrained/Responsive → flat by default; Choreographed → layered. One sentence.
-- **Components**: omit entirely; no components exist yet.
-- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.
-
-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.
-
-### Step 4: Confirm and refresh session cache
-
-1. Show the seed DESIGN.md. Call out that it is a seed (the marker is the literal commitment).
-2. Tell the user: "Re-run `/impeccable document` once you have some code. That pass will extract real tokens and generate the sidecar."
-3. Run `node .trae/skills/impeccable/scripts/load-context.mjs` once so the seed lands in conversation for the rest of the session.
-
-## Style guidelines
-
-- **Frontmatter first, prose second.** Tokens go in the YAML frontmatter; prose contextualizes them. Don't redefine a token value in two places; the frontmatter is normative.
-- **Cite PRODUCT.md anti-references by name** in the Do's and Don'ts section. If PRODUCT.md lists "SaaS landing-page clichés" or "generic AI tool marketing" as anti-references, the DESIGN.md Don'ts should repeat those phrases verbatim so the visual spec enforces the strategic line.
-- **Match the spec, don't invent new sections.** The six section names are fixed. If you have Layout/Motion/Responsive content to document, fold it into Overview (philosophy-level rules) or Components (per-component behavior).
-- **Descriptive > technical**: "Gently curved edges (8px radius)" > "rounded-lg". Include the technical value in parens, lead with the description.
-- **Functional > decorative**: for each token, explain WHERE and WHY it's used, not just WHAT it is.
-- **Exact values in parens**: hex codes, px/rem values, font weights; always the number in parens alongside the description.
-- **Use Named Rules**: `**The [Name] Rule.** [short doctrine]`. These are memorable, citable, and much stickier for AI consumers than bullet lists. Stitch's own outputs use them heavily ("The No-Line Rule", "The Ghost Border Fallback"). Aim for 1-3 per section.
-- **Be forceful**. The voice of a design director. "Prohibited", "forbidden", "never", "always", not "consider", "might", "prefer". Match PRODUCT.md's tone.
-- **Concrete anti-pattern tests**. Stitch writes things like *"If it looks like a 2014 app, the shadow is too dark and the blur is too small."* A one-sentence audit test beats a paragraph of principle.
-- **Reference PRODUCT.md**. The anti-references section of PRODUCT.md should directly inform the Do's and Don'ts section here. Quote or paraphrase.
-- **Group colors by role**, not by hex-order or hue-order. Primary / Secondary / Tertiary / Neutral is the spec ordering.
-
-## Pitfalls
-
-- Don't paste raw CSS class names. Translate to descriptive language.
-- Don't extract every token. Stop at what's actually reused; one-offs pollute the system.
-- Don't invent components that don't exist. If the project only has buttons and cards, only document those.
-- Don't overwrite an existing DESIGN.md without asking.
-- Don't duplicate content from PRODUCT.md. DESIGN.md is strictly visual.
-- Don't add a "Layout Principles" or "Motion" or "Responsive Behavior" top-level section. The spec has six, not nine. Fold that content where it belongs.
-- Don't rename sections even slightly. "Colors" not "Color Palette & Roles". "Typography" not "Typography Rules". Tooling parsing depends on exact headers.
-- Don't duplicate token values between frontmatter and prose. If a color is in `colors.primary` as hex, the prose can name it and describe its role but should not reassert a different hex. The frontmatter is normative.
-- Don't invent frontmatter token groups outside Stitch's schema (no `motion:`, `breakpoints:`, `shadows:` at the top level). Stitch's Zod schema only accepts `colors`, `typography`, `rounded`, `spacing`, `components`. Anything else belongs in the sidecar's `extensions`.
@@ -1,69 +0,0 @@
-# Extract Flow
-
-Identify reusable patterns, components, and design tokens, then extract and consolidate them into the design system for systematic reuse.
-
-## Step 1: Discover the Design System
-
-Find the design system, component library, or shared UI directory. Understand its structure: component organization, naming conventions, design token structure, import/export conventions.
-
-**CRITICAL**: If no design system exists, ask the user directly to clarify what you cannot infer. before creating one. Understand the preferred location and structure first.
-
-## Step 2: Identify Patterns
-
-Look for extraction opportunities in the target area:
-
-- **Repeated components**: Similar UI patterns used 3+ times (buttons, cards, inputs)
-- **Hard-coded values**: Colors, spacing, typography, shadows that should be tokens
-- **Inconsistent variations**: Multiple implementations of the same concept
-- **Composition patterns**: Layout or interaction patterns that repeat (form rows, toolbar groups, empty states)
-- **Type styles**: Repeated font-size + weight + line-height combinations
-- **Animation patterns**: Repeated easing, duration, or keyframe combinations
-
-Assess value: only extract things used 3+ times with the same intent. Premature abstraction is worse than duplication.
-
-## Step 3: Plan Extraction
-
-Create a systematic plan:
-
-- **Components to extract**: Which UI elements become reusable components?
-- **Tokens to create**: Which hard-coded values become design tokens?
-- **Variants to support**: What variations does each component need?
-- **Naming conventions**: Component names, token names, prop names that match existing patterns
-- **Migration path**: How to refactor existing uses to consume the new shared versions
-
-**IMPORTANT**: Design systems grow incrementally. Extract what is clearly reusable now, not everything that might someday be reusable.
-
-## Step 4: Extract & Enrich
-
-Build improved, reusable versions:
-
-- **Components**: Clear props API with sensible defaults, proper variants for different use cases, accessibility built in (ARIA, keyboard navigation, focus management), documentation and usage examples
-- **Design tokens**: Clear naming (primitive vs semantic), proper hierarchy and organization, documentation of when to use each token
-- **Patterns**: When to use this pattern, code examples, variations and combinations
-
-## Step 5: Migrate
-
-Replace existing uses with the new shared versions:
-
-- **Find all instances**: Search for the patterns you extracted
-- **Replace systematically**: Update each use to consume the shared version
-- **Test thoroughly**: Ensure visual and functional parity
-- **Delete dead code**: Remove the old implementations
-
-## Step 6: Document
-
-Update design system documentation:
-
-- Add new components to the component library
-- Document token usage and values
-- Add examples and guidelines
-- Update any Storybook or component catalog
-
-**NEVER**:
-- Extract one-off, context-specific implementations without generalization
-- Create components so generic they are useless
-- Extract without considering existing design system conventions
-- Skip proper TypeScript types or prop documentation
-- Create tokens for every single value (tokens should have semantic meaning)
-- Extract things that differ in intent (two buttons that look similar but serve different purposes should stay separate)
-
@@ -1,347 +0,0 @@
-Designs that only work with perfect data aren't production-ready. Harden the interface against the inputs, errors, languages, and network conditions that real users will throw at it.
-
-## Assess Hardening Needs
-
-Identify weaknesses and edge cases:
-
-1. **Test with extreme inputs**:
- - Very long text (names, descriptions, titles)
- - Very short text (empty, single character)
- - Special characters (emoji, RTL text, accents)
- - Large numbers (millions, billions)
- - Many items (1000+ list items, 50+ options)
- - No data (empty states)
-
-2. **Test error scenarios**:
- - Network failures (offline, slow, timeout)
- - API errors (400, 401, 403, 404, 500)
- - Validation errors
- - Permission errors
- - Rate limiting
- - Concurrent operations
-
-3. **Test internationalization**:
- - Long translations (German is often 30% longer than English)
- - RTL languages (Arabic, Hebrew)
- - Character sets (Chinese, Japanese, Korean, emoji)
- - Date/time formats
- - Number formats (1,000 vs 1.000)
- - Currency symbols
-
-**CRITICAL**: Designs that only work with perfect data aren't production-ready. Harden against reality.
-
-## Hardening Dimensions
-
-Systematically improve resilience:
-
-### Text Overflow & Wrapping
-
-**Long text handling**:
-```css
-/* Single line with ellipsis */
-.truncate {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-/* Multi-line with clamp */
-.line-clamp {
- display: -webkit-box;
- -webkit-line-clamp: 3;
- -webkit-box-orient: vertical;
- overflow: hidden;
-}
-
-/* Allow wrapping */
-.wrap {
- word-wrap: break-word;
- overflow-wrap: break-word;
- hyphens: auto;
-}
-```
-
-**Flex/Grid overflow**:
-```css
-/* Prevent flex items from overflowing */
-.flex-item {
- min-width: 0; /* Allow shrinking below content size */
- overflow: hidden;
-}
-
-/* Prevent grid items from overflowing */
-.grid-item {
- min-width: 0;
- min-height: 0;
-}
-```
-
-**Responsive text sizing**:
-- Use `clamp()` for fluid typography
-- Set minimum readable sizes (14px on mobile)
-- Test text scaling (zoom to 200%)
-- Ensure containers expand with text
-
-### Internationalization (i18n)
-
-**Text expansion**:
-- Add 30-40% space budget for translations
-- Use flexbox/grid that adapts to content
-- Test with longest language (usually German)
-- Avoid fixed widths on text containers
-
-```jsx
-// ❌ Bad: Assumes short English text
-<button className="w-24">Submit</button>
-
-// ✅ Good: Adapts to content
-<button className="px-4 py-2">Submit</button>
-```
-
-**RTL (Right-to-Left) support**:
-```css
-/* Use logical properties */
-margin-inline-start: 1rem; /* Not margin-left */
-padding-inline: 1rem; /* Not padding-left/right */
-border-inline-end: 1px solid; /* Not border-right */
-
-/* Or use dir attribute */
-[dir="rtl"] .arrow { transform: scaleX(-1); }
-```
-
-**Character set support**:
-- Use UTF-8 encoding everywhere
-- Test with Chinese/Japanese/Korean (CJK) characters
-- Test with emoji (they can be 2-4 bytes)
-- Handle different scripts (Latin, Cyrillic, Arabic, etc.)
-
-**Date/Time formatting**:
-```javascript
-// ✅ Use Intl API for proper formatting
-new Intl.DateTimeFormat('en-US').format(date); // 1/15/2024
-new Intl.DateTimeFormat('de-DE').format(date); // 15.1.2024
-
-new Intl.NumberFormat('en-US', {
- style: 'currency',
- currency: 'USD'
-}).format(1234.56); // $1,234.56
-```
-
-**Pluralization**:
-```javascript
-// ❌ Bad: Assumes English pluralization
-`${count} item${count !== 1 ? 's' : ''}`
-
-// ✅ Good: Use proper i18n library
-t('items', { count }) // Handles complex plural rules
-```
-
-### Error Handling
-
-**Network errors**:
-- Show clear error messages
-- Provide retry button
-- Explain what happened
-- Offer offline mode (if applicable)
-- Handle timeout scenarios
-
-```jsx
-// Error states with recovery
-{error && (
- <ErrorMessage>
- <p>Failed to load data. {error.message}</p>
- <button onClick={retry}>Try again</button>
- </ErrorMessage>
-)}
-```
-
-**Form validation errors**:
-- Inline errors near fields
-- Clear, specific messages
-- Suggest corrections
-- Don't block submission unnecessarily
-- Preserve user input on error
-
-**API errors**:
-- Handle each status code appropriately
- - 400: Show validation errors
- - 401: Redirect to login
- - 403: Show permission error
- - 404: Show not found state
- - 429: Show rate limit message
- - 500: Show generic error, offer support
-
-**Graceful degradation**:
-- Core functionality works without JavaScript
-- Images have alt text
-- Progressive enhancement
-- Fallbacks for unsupported features
-
-### Edge Cases & Boundary Conditions
-
-**Empty states**:
-- No items in list
-- No search results
-- No notifications
-- No data to display
-- Provide clear next action
-
-**Loading states**:
-- Initial load
-- Pagination load
-- Refresh
-- Show what's loading ("Loading your projects...")
-- Time estimates for long operations
-
-**Large datasets**:
-- Pagination or virtual scrolling
-- Search/filter capabilities
-- Performance optimization
-- Don't load all 10,000 items at once
-
-**Concurrent operations**:
-- Prevent double-submission (disable button while loading)
-- Handle race conditions
-- Optimistic updates with rollback
-- Conflict resolution
-
-**Permission states**:
-- No permission to view
-- No permission to edit
-- Read-only mode
-- Clear explanation of why
-
-**Browser compatibility**:
-- Polyfills for modern features
-- Fallbacks for unsupported CSS
-- Feature detection (not browser detection)
-- Test in target browsers
-
-### Input Validation & Sanitization
-
-**Client-side validation**:
-- Required fields
-- Format validation (email, phone, URL)
-- Length limits
-- Pattern matching
-- Custom validation rules
-
-**Server-side validation** (always):
-- Never trust client-side only
-- Validate and sanitize all inputs
-- Protect against injection attacks
-- Rate limiting
-
-**Constraint handling**:
-```html
-<!-- Set clear constraints -->
-<input
- type="text"
- maxlength="100"
- pattern="[A-Za-z0-9]+"
- required
- aria-describedby="username-hint"
-/>
-<small id="username-hint">
- Letters and numbers only, up to 100 characters
-</small>
-```
-
-### Accessibility Resilience
-
-**Keyboard navigation**:
-- All functionality accessible via keyboard
-- Logical tab order
-- Focus management in modals
-- Skip links for long content
-
-**Screen reader support**:
-- Proper ARIA labels
-- Announce dynamic changes (live regions)
-- Descriptive alt text
-- Semantic HTML
-
-**Motion sensitivity**:
-```css
-@media (prefers-reduced-motion: reduce) {
- * {
- animation-duration: 0.01ms !important;
- animation-iteration-count: 1 !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**High contrast mode**:
-- Test in Windows high contrast mode
-- Don't rely only on color
-- Provide alternative visual cues
-
-### Performance Resilience
-
-**Slow connections**:
-- Progressive image loading
-- Skeleton screens
-- Optimistic UI updates
-- Offline support (service workers)
-
-**Memory leaks**:
-- Clean up event listeners
-- Cancel subscriptions
-- Clear timers/intervals
-- Abort pending requests on unmount
-
-**Throttling & Debouncing**:
-```javascript
-// Debounce search input
-const debouncedSearch = debounce(handleSearch, 300);
-
-// Throttle scroll handler
-const throttledScroll = throttle(handleScroll, 100);
-```
-
-## Testing Strategies
-
-**Manual testing**:
-- Test with extreme data (very long, very short, empty)
-- Test in different languages
-- Test offline
-- Test slow connection (throttle to 3G)
-- Test with screen reader
-- Test keyboard-only navigation
-- Test on old browsers
-
-**Automated testing**:
-- Unit tests for edge cases
-- Integration tests for error scenarios
-- E2E tests for critical paths
-- Visual regression tests
-- Accessibility tests (axe, WAVE)
-
-**IMPORTANT**: Hardening is about expecting the unexpected. Real users will do things you never imagined.
-
-**NEVER**:
-- Assume perfect input (validate everything)
-- Ignore internationalization (design for global)
-- Leave error messages generic ("Error occurred")
-- Forget offline scenarios
-- Trust client-side validation alone
-- Use fixed widths for text
-- Assume English-length text
-- Block entire interface when one component errors
-
-## Verify Hardening
-
-Test thoroughly with edge cases:
-
-- **Long text**: Try names with 100+ characters
-- **Emoji**: Use emoji in all text fields
-- **RTL**: Test with Arabic or Hebrew
-- **CJK**: Test with Chinese/Japanese/Korean
-- **Network issues**: Disable internet, throttle connection
-- **Large datasets**: Test with 1000+ items
-- **Concurrent actions**: Click submit 10 times rapidly
-- **Errors**: Force API errors, test all error states
-- **Empty**: Remove all data, test empty states
-
-When edge cases are covered, hand off to `/impeccable polish` for the final pass.
@@ -1,234 +0,0 @@
-# Heuristics Scoring Guide
-
-Score each of Nielsen's 10 Usability Heuristics on a 0–4 scale. Be honest: a 4 means genuinely excellent, not "good enough."
-
-## Nielsen's 10 Heuristics
-
-### 1. Visibility of System Status
-
-Keep users informed about what's happening through timely, appropriate feedback.
-
-**Check for**:
-- Loading indicators during async operations
-- Confirmation of user actions (save, submit, delete)
-- Progress indicators for multi-step processes
-- Current location in navigation (breadcrumbs, active states)
-- Form validation feedback (inline, not just on submit)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No feedback; user is guessing what happened |
-| 1 | Rare feedback; most actions produce no visible response |
-| 2 | Partial; some states communicated, major gaps remain |
-| 3 | Good; most operations give clear feedback, minor gaps |
-| 4 | Excellent; every action confirms, progress is always visible |
-
-### 2. Match Between System and Real World
-
-Speak the user's language. Follow real-world conventions. Information appears in natural, logical order.
-
-**Check for**:
-- Familiar terminology (no unexplained jargon)
-- Logical information order matching user expectations
-- Recognizable icons and metaphors
-- Domain-appropriate language for the target audience
-- Natural reading flow (left-to-right, top-to-bottom priority)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Pure tech jargon, alien to users |
-| 1 | Mostly confusing; requires domain expertise to navigate |
-| 2 | Mixed; some plain language, some jargon leaks through |
-| 3 | Mostly natural; occasional term needs context |
-| 4 | Speaks the user's language fluently throughout |
-
-### 3. User Control and Freedom
-
-Users need a clear "emergency exit" from unwanted states without extended dialogue.
-
-**Check for**:
-- Undo/redo functionality
-- Cancel buttons on forms and modals
-- Clear navigation back to safety (home, previous)
-- Easy way to clear filters, search, selections
-- Escape from long or multi-step processes
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Users get trapped; no way out without refreshing |
-| 1 | Difficult exits; must find obscure paths to escape |
-| 2 | Some exits; main flows have escape, edge cases don't |
-| 3 | Good control; users can exit and undo most actions |
-| 4 | Full control; undo, cancel, back, and escape everywhere |
-
-### 4. Consistency and Standards
-
-Users shouldn't wonder whether different words, situations, or actions mean the same thing.
-
-**Check for**:
-- Consistent terminology throughout the interface
-- Same actions produce same results everywhere
-- Platform conventions followed (standard UI patterns)
-- Visual consistency (colors, typography, spacing, components)
-- Consistent interaction patterns (same gesture = same behavior)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Inconsistent everywhere; feels like different products stitched together |
-| 1 | Many inconsistencies; similar things look/behave differently |
-| 2 | Partially consistent; main flows match, details diverge |
-| 3 | Mostly consistent; occasional deviation, nothing confusing |
-| 4 | Fully consistent; cohesive system, predictable behavior |
-
-### 5. Error Prevention
-
-Better than good error messages is a design that prevents problems in the first place.
-
-**Check for**:
-- Confirmation before destructive actions (delete, overwrite)
-- Constraints preventing invalid input (date pickers, dropdowns)
-- Smart defaults that reduce errors
-- Clear labels that prevent misunderstanding
-- Autosave and draft recovery
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Errors easy to make; no guardrails anywhere |
-| 1 | Few safeguards; some inputs validated, most aren't |
-| 2 | Partial prevention; common errors caught, edge cases slip |
-| 3 | Good prevention; most error paths blocked proactively |
-| 4 | Excellent; errors nearly impossible through smart constraints |
-
-### 6. Recognition Rather Than Recall
-
-Minimize memory load. Make objects, actions, and options visible or easily retrievable.
-
-**Check for**:
-- Visible options (not buried in hidden menus)
-- Contextual help when needed (tooltips, inline hints)
-- Recent items and history
-- Autocomplete and suggestions
-- Labels on icons (not icon-only navigation)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Heavy memorization; users must remember paths and commands |
-| 1 | Mostly recall; many hidden features, few visible cues |
-| 2 | Some aids; main actions visible, secondary features hidden |
-| 3 | Good recognition; most things discoverable, few memory demands |
-| 4 | Everything discoverable; users never need to memorize |
-
-### 7. Flexibility and Efficiency of Use
-
-Accelerators, invisible to novices, speed up expert interaction.
-
-**Check for**:
-- Keyboard shortcuts for common actions
-- Customizable interface elements
-- Recent items and favorites
-- Bulk/batch actions
-- Power user features that don't complicate the basics
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | One rigid path; no shortcuts or alternatives |
-| 1 | Limited flexibility; few alternatives to the main path |
-| 2 | Some shortcuts; basic keyboard support, limited bulk actions |
-| 3 | Good accelerators; keyboard nav, some customization |
-| 4 | Highly flexible; multiple paths, power features, customizable |
-
-### 8. Aesthetic and Minimalist Design
-
-Interfaces should not contain irrelevant or rarely needed information. Every element should serve a purpose.
-
-**Check for**:
-- Only necessary information visible at each step
-- Clear visual hierarchy directing attention
-- Purposeful use of color and emphasis
-- No decorative clutter competing for attention
-- Focused, uncluttered layouts
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Overwhelming; everything competes for attention equally |
-| 1 | Cluttered; too much noise, hard to find what matters |
-| 2 | Some clutter; main content clear, periphery noisy |
-| 3 | Mostly clean; focused design, minor visual noise |
-| 4 | Perfectly minimal; every element earns its pixel |
-
-### 9. Help Users Recognize, Diagnose, and Recover from Errors
-
-Error messages should use plain language, precisely indicate the problem, and constructively suggest a solution.
-
-**Check for**:
-- Plain language error messages (no error codes for users)
-- Specific problem identification ("Email is missing @" not "Invalid input")
-- Actionable recovery suggestions
-- Errors displayed near the source of the problem
-- Non-blocking error handling (don't wipe the form)
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | Cryptic errors; codes, jargon, or no message at all |
-| 1 | Vague errors; "Something went wrong" with no guidance |
-| 2 | Clear but unhelpful; names the problem but not the fix |
-| 3 | Clear with suggestions; identifies problem and offers next steps |
-| 4 | Perfect recovery; pinpoints issue, suggests fix, preserves user work |
-
-### 10. Help and Documentation
-
-Even if the system is usable without docs, help should be easy to find, task-focused, and concise.
-
-**Check for**:
-- Searchable help or documentation
-- Contextual help (tooltips, inline hints, guided tours)
-- Task-focused organization (not feature-organized)
-- Concise, scannable content
-- Easy access without leaving current context
-
-**Scoring**:
-| Score | Criteria |
-|-------|----------|
-| 0 | No help available anywhere |
-| 1 | Help exists but hard to find or irrelevant |
-| 2 | Basic help; FAQ or docs exist, not contextual |
-| 3 | Good documentation; searchable, mostly task-focused |
-| 4 | Excellent contextual help; right info at the right moment |
-
----
-
-## Score Summary
-
-**Total possible**: 40 points (10 heuristics × 4 max)
-
-| Score Range | Rating | What It Means |
-|-------------|--------|---------------|
-| 36–40 | Excellent | Minor polish only; ship it |
-| 28–35 | Good | Address weak areas, solid foundation |
-| 20–27 | Acceptable | Significant improvements needed before users are happy |
-| 12–19 | Poor | Major UX overhaul required; core experience broken |
-| 0–11 | Critical | Redesign needed; unusable in current state |
-
----
-
-## Issue Severity (P0–P3)
-
-Tag each individual issue found during scoring with a priority level:
-
-| Priority | Name | Description | Action |
-|----------|------|-------------|--------|
-| **P0** | Blocking | Prevents task completion entirely | Fix immediately; this is a showstopper |
-| **P1** | Major | Causes significant difficulty or confusion | Fix before release |
-| **P2** | Minor | Annoyance, but workaround exists | Fix in next pass |
-| **P3** | Polish | Nice-to-fix, no real user impact | Fix if time permits |
-
-**Tip**: If you're unsure between two levels, ask: "Would a user contact support about this?" If yes, it's at least P1.
@@ -1,195 +0,0 @@
-# Interaction Design
-
-## The Eight Interactive States
-
-Every interactive element needs these states designed:
-
-| State | When | Visual Treatment |
-|-------|------|------------------|
-| **Default** | At rest | Base styling |
-| **Hover** | Pointer over (not touch) | Subtle lift, color shift |
-| **Focus** | Keyboard/programmatic focus | Visible ring (see below) |
-| **Active** | Being pressed | Pressed in, darker |
-| **Disabled** | Not interactive | Reduced opacity, no pointer |
-| **Loading** | Processing | Spinner, skeleton |
-| **Error** | Invalid state | Red border, icon, message |
-| **Success** | Completed | Green check, confirmation |
-
-**The common miss**: Designing hover without focus, or vice versa. They're different. Keyboard users never see hover states.
-
-## Focus Rings: Do Them Right
-
-**Never `outline: none` without replacement.** It's an accessibility violation. Instead, use `:focus-visible` to show focus only for keyboard users:
-
-```css
-/* Hide focus ring for mouse/touch */
-button:focus {
- outline: none;
-}
-
-/* Show focus ring for keyboard */
-button:focus-visible {
- outline: 2px solid var(--color-accent);
- outline-offset: 2px;
-}
-```
-
-**Focus ring design**:
-- High contrast (3:1 minimum against adjacent colors)
-- 2-3px thick
-- Offset from element (not inside it)
-- Consistent across all interactive elements
-
-## Form Design: The Non-Obvious
-
-**Placeholders aren't labels.** They disappear on input. Always use visible `<label>` elements. **Validate on blur**, not on every keystroke (exception: password strength). Place errors **below** fields with `aria-describedby` connecting them.
-
-## Loading States
-
-**Optimistic updates**: Show success immediately, rollback on failure. Use for low-stakes actions (likes, follows), not payments or destructive actions. **Skeleton screens > spinners**: they preview content shape and feel faster than generic spinners.
-
-## Modals: The Inert Approach
-
-Focus trapping in modals used to require complex JavaScript. Now use the `inert` attribute:
-
-```html
-<!-- When modal is open -->
-<main inert>
- <!-- Content behind modal can't be focused or clicked -->
-</main>
-<dialog open>
- <h2>Modal Title</h2>
- <!-- Focus stays inside modal -->
-</dialog>
-```
-
-Or use the native `<dialog>` element:
-
-```javascript
-const dialog = document.querySelector('dialog');
-dialog.showModal(); // Opens with focus trap, closes on Escape
-```
-
-## The Popover API
-
-For tooltips, dropdowns, and non-modal overlays, use native popovers:
-
-```html
-<button popovertarget="menu">Open menu</button>
-<div id="menu" popover>
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-**Benefits**: Light-dismiss (click outside closes), proper stacking, no z-index wars, accessible by default.
-
-## Dropdown & Overlay Positioning
-
-Dropdowns rendered with `position: absolute` inside a container that has `overflow: hidden` or `overflow: auto` will be clipped. This is the single most common dropdown bug in generated code.
-
-### CSS Anchor Positioning
-
-The modern solution uses the CSS Anchor Positioning API to tether an overlay to its trigger without JavaScript:
-
-```css
-.trigger {
- anchor-name: --menu-trigger;
-}
-
-.dropdown {
- position: fixed;
- position-anchor: --menu-trigger;
- position-area: block-end span-inline-end;
- margin-top: 4px;
-}
-
-/* Flip above if no room below */
-@position-try --flip-above {
- position-area: block-start span-inline-end;
- margin-bottom: 4px;
-}
-```
-
-Because the dropdown uses `position: fixed`, it escapes any `overflow` clipping on ancestor elements. The `@position-try` block handles viewport edges automatically. **Browser support**: Chrome 125+, Edge 125+. Not yet in Firefox or Safari - use a fallback for those browsers.
-
-### Popover + Anchor Combo
-
-Combining the Popover API with anchor positioning gives you stacking, light-dismiss, accessibility, and correct positioning in one pattern:
-
-```html
-<button popovertarget="menu" class="trigger">Open</button>
-<div id="menu" popover class="dropdown">
- <button>Option 1</button>
- <button>Option 2</button>
-</div>
-```
-
-The `popover` attribute places the element in the **top layer**, which sits above all other content regardless of z-index or overflow. No portal needed.
-
-### Portal / Teleport Pattern
-
-In component frameworks, render the dropdown at the document root and position it with JavaScript:
-
-- **React**: `createPortal(dropdown, document.body)`
-- **Vue**: `<Teleport to="body">`
-- **Svelte**: Use a portal library or mount to `document.body`
-
-Calculate position from the trigger's `getBoundingClientRect()`, then apply `position: fixed` with `top` and `left` values. Recalculate on scroll and resize.
-
-### Fixed Positioning Fallback
-
-For browsers without anchor positioning support, `position: fixed` with manual coordinates avoids overflow clipping:
-
-```css
-.dropdown {
- position: fixed;
- /* top/left set via JS from trigger's getBoundingClientRect() */
-}
-```
-
-Check viewport boundaries before rendering. If the dropdown would overflow the bottom edge, flip it above the trigger. If it would overflow the right edge, align it to the trigger's right side instead.
-
-### Anti-Patterns
-
-- **`position: absolute` inside `overflow: hidden`** - The dropdown will be clipped. Use `position: fixed` or the top layer instead.
-- **Arbitrary z-index values** like `z-index: 9999` - Use a semantic z-index scale: `dropdown (100) -> sticky (200) -> modal-backdrop (300) -> modal (400) -> toast (500) -> tooltip (600)`.
-- **Rendering dropdown markup inline** without an escape hatch from the parent's stacking context. Either use `popover` (top layer), a portal, or `position: fixed`.
-
-## Destructive Actions: Undo > Confirm
-
-**Undo is better than confirmation dialogs.** Users click through confirmations mindlessly. Remove from UI immediately, show undo toast, actually delete after toast expires. Use confirmation only for truly irreversible actions (account deletion), high-cost actions, or batch operations.
-
-## Keyboard Navigation Patterns
-
-### Roving Tabindex
-
-For component groups (tabs, menu items, radio groups), one item is tabbable; arrow keys move within:
-
-```html
-<div role="tablist">
- <button role="tab" tabindex="0">Tab 1</button>
- <button role="tab" tabindex="-1">Tab 2</button>
- <button role="tab" tabindex="-1">Tab 3</button>
-</div>
-```
-
-Arrow keys move `tabindex="0"` between items. Tab moves to the next component entirely.
-
-### Skip Links
-
-Provide skip links (`<a href="#main-content">Skip to main content</a>`) for keyboard users to jump past navigation. Hide off-screen, show on focus.
-
-## Gesture Discoverability
-
-Swipe-to-delete and similar gestures are invisible. Hint at their existence:
-
-- **Partially reveal**: Show delete button peeking from edge
-- **Onboarding**: Coach marks on first use
-- **Alternative**: Always provide a visible fallback (menu with "Delete")
-
-Don't rely on gestures as the only way to perform actions.
-
----
-
-**Avoid**: Removing focus indicators without alternatives. Using placeholder text as labels. Touch targets <44x44px. Generic error messages. Custom controls without ARIA/keyboard support.
@@ -1,141 +0,0 @@
-Space is the most underused design tool. Find the layout's actual problem (monotone spacing, weak hierarchy, identical card grids, the centered-stack default) and fix the structure, not the surface.
-
----
-
-## Register
-
-Brand: asymmetric compositions, fluid spacing with `clamp()`, intentional grid-breaking for emphasis. Rhythm through contrast: tight groupings paired with generous separations.
-
-Product: predictable grids, consistent densities, familiar navigation patterns. Responsive behavior is structural (collapse sidebar, responsive table), not fluid typography. Consistency IS an affordance.
-
----
-
-## Assess Current Layout
-
-Analyze what's weak about the current spatial design:
-
-1. **Spacing**:
- - Is spacing consistent or arbitrary? (Random padding/margin values)
- - Is all spacing the same? (Equal padding everywhere = no rhythm)
- - Are related elements grouped tightly, with generous space between groups?
-
-2. **Visual hierarchy**:
- - Apply the squint test: blur your (metaphorical) eyes. Can you still identify the most important element, second most important, and clear groupings?
- - Is hierarchy achieved effectively? (Space and weight alone can be enough; is the current approach working?)
- - Does whitespace guide the eye to what matters?
-
-3. **Grid & structure**:
- - Is there a clear underlying structure, or does the layout feel random?
- - Are identical card grids used everywhere? (Icon + heading + text, repeated endlessly)
- - Is everything centered? (Left-aligned with asymmetric layouts feels more designed, but not a hard and fast rule)
-
-4. **Rhythm & variety**:
- - Does the layout have visual rhythm? (Alternating tight/generous spacing)
- - Is every section structured the same way? (Monotonous repetition)
- - Are there intentional moments of surprise or emphasis?
-
-5. **Density**:
- - Is the layout too cramped? (Not enough breathing room)
- - Is the layout too sparse? (Excessive whitespace without purpose)
- - Does density match the content type? (Data-dense UIs need tighter spacing; marketing pages need more air)
-
-**CRITICAL**: Layout problems are often the root cause of interfaces feeling "off" even when colors and fonts are fine. Space is a design material; use it with intention.
-
-## Plan Layout Improvements
-
-Consult the [spatial design reference](spatial-design.md) for detailed guidance on grids, rhythm, and container queries.
-
-Create a systematic plan:
-
-- **Spacing system**: Use a consistent scale (a framework's built-in scale like Tailwind's, rem-based tokens, or a custom system). The specific values matter less than consistency.
-- **Hierarchy strategy**: How will space communicate importance?
-- **Layout approach**: What structure fits the content? Flex for 1D, Grid for 2D, named areas for complex page layouts.
-- **Rhythm**: Where should spacing be tight vs generous?
-
-## Improve Layout Systematically
-
-### Establish a Spacing System
-
-- Use a consistent spacing scale (framework scales like Tailwind, rem-based tokens, or a custom scale all work). What matters is that values come from a defined set, not arbitrary numbers.
-- Name tokens semantically if using custom properties: `--space-xs` through `--space-xl`, not `--spacing-8`
-- Use `gap` for sibling spacing instead of margins; eliminates margin collapse hacks
-- Apply `clamp()` for fluid spacing that breathes on larger screens
-
-### Create Visual Rhythm
-
-- **Tight grouping** for related elements (8-12px between siblings)
-- **Generous separation** between distinct sections (48-96px)
-- **Varied spacing** within sections (not every row needs the same gap)
-- **Asymmetric compositions**: break the predictable centered-content pattern when it makes sense
-
-### Choose the Right Layout Tool
-
-- **Use Flexbox for 1D layouts**: Rows of items, nav bars, button groups, card contents, most component internals. Flex is simpler and more appropriate for the majority of layout tasks.
-- **Use Grid for 2D layouts**: Page-level structure, dashboards, data-dense interfaces, anything where rows AND columns need coordinated control.
-- **Don't default to Grid** when Flexbox with `flex-wrap` would be simpler and more flexible.
-- Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints.
-- Use named grid areas (`grid-template-areas`) for complex page layouts; redefine at breakpoints.
-
-### Break Card Grid Monotony
-
-- Don't default to card grids for everything; spacing and alignment create visual grouping naturally
-- Use cards only when content is truly distinct and actionable. Never nest cards inside cards
-- Vary card sizes, span columns, or mix cards with non-card content to break repetition
-
-### Strengthen Visual Hierarchy
-
-- Use the fewest dimensions needed for clear hierarchy. Space alone can be enough; generous whitespace around an element draws the eye. Some of the most polished designs achieve rhythm with just space and weight. Add color or size contrast only when simpler means aren't sufficient.
-- Be aware of reading flow: in LTR languages, the eye naturally scans top-left to bottom-right, but primary action placement depends on context (e.g., bottom-right in dialogs, top in navigation).
-- Create clear content groupings through proximity and separation.
-
-### Manage Depth & Elevation
-
-- Create a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip)
-- Build a consistent shadow scale (sm → md → lg → xl); shadows should be subtle
-- Use elevation to reinforce hierarchy, not as decoration
-
-### Optical Adjustments
-
-- If an icon looks visually off-center despite being geometrically centered, nudge it. But only if you're confident it actually looks wrong. Don't adjust speculatively.
-
-**NEVER**:
-- Use arbitrary spacing values outside your scale
-- Make all spacing equal (variety creates hierarchy)
-- Wrap everything in cards (not everything needs a container)
-- Nest cards inside cards (use spacing and dividers for hierarchy within)
-- Use identical card grids everywhere (icon + heading + text, repeated)
-- Center everything (left-aligned with asymmetry feels more designed)
-- Default to the hero metric layout (big number, small label, stats, gradient) as a template. If showing real user data, a prominent metric can work, but it should display actual data, not decorative numbers.
-- Default to CSS Grid when Flexbox would be simpler; use the simplest tool for the job
-- Use arbitrary z-index values (999, 9999); build a semantic scale
-
-## Verify Layout Improvements
-
-- **Squint test**: Can you identify primary, secondary, and groupings with blurred vision?
-- **Rhythm**: Does the page have a satisfying beat of tight and generous spacing?
-- **Hierarchy**: Is the most important content obvious within 2 seconds?
-- **Breathing room**: Does the layout feel comfortable, not cramped or wasteful?
-- **Consistency**: Is the spacing system applied uniformly?
-- **Responsiveness**: Does the layout adapt gracefully across screen sizes?
-
-When the rhythm and hierarchy land, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `density` param. Drive all spacing tokens in the variant's scoped CSS through `calc(var(--p-density, 1) * <base>)`: paddings, gaps, column widths. Users slide from airy to packed and see layout re-breathe with no regeneration.
-
-```json
-{"id":"density","kind":"range","min":0.6,"max":1.4,"step":0.05,"default":1,"label":"Density"}
-```
-
-For variants whose topology genuinely changes (stacked vs. side-by-side, grid vs. bento), use a `steps` param whose scoped CSS branches via `:scope[data-p-structure="X"]`. One structure param + one density param is a powerful combo; resist adding a third.
-
-```json
-{"id":"structure","kind":"steps","default":"grid","label":"Structure","options":[
- {"value":"stacked","label":"Stacked"},
- {"value":"grid","label":"Grid"},
- {"value":"bento","label":"Bento"}
-]}
-```
-
-See `reference/live.md` for the full params contract.
@@ -1,622 +0,0 @@
-Interactive live variant mode: select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via the dev server's HMR.
-
-## Prerequisites
-
-A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR a static HTML file open in the browser.
-
-## The contract (read once)
-
-Execute in order. No step skipped, no step reordered.
-
-1. `live.mjs`: boot.
-2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.
-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.
-5. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.
-6. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.
-7. On `exit`: run the cleanup at the bottom.
-
-Harness policy:
-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.
-- **Cursor**: run the poll in the **foreground** (blocking shell; not a background terminal, not a subagent). Cursor background terminals and subagents do not reliably resume the chat with poll stdout.
-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.
-- **Other harnesses**: foreground unless you know stdout reliably returns to this session.
-
-Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.
-
-## Start
-
-```bash
-node .trae/skills/impeccable/scripts/live.mjs
-```
-
-Output JSON: `{ ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath, migrated }`. `pageFiles` is the list of HTML entries the live script was injected into. Keep PRODUCT.md and DESIGN.md in mind for variant generation; **DESIGN.md wins on visual decisions; PRODUCT.md wins on strategic/voice decisions.** When DESIGN.md is missing, identity is **not** absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt. If `migrated: true`, the loader auto-renamed legacy `.impeccable.md` to `PRODUCT.md`; mention this once and suggest `/impeccable document` for the matching DESIGN.md.
-
-`serverPort` and `serverToken` belong to the small **Impeccable live helper** HTTP server (serves `/live.js`, SSE, and `/poll`). That port is **not** your dev server and is usually not the URL you open to view the app. The browser page is whatever origin serves one of the `pageFiles` entries (Vite / Next / Bun / tunnel / LAN hostname).
-
-If output is `{ ok: false, error: "config_missing" | "config_invalid", path }`, this project hasn't been configured for live mode (or its config is stale). See **First-time setup** at the bottom.
-
-## Poll loop
-
-```
-LOOP:
- node .trae/skills/impeccable/scripts/live-poll.mjs # default long timeout; no --timeout=
- Read JSON; dispatch on "type"
-
- "generate" → Handle Generate; reply done; LOOP
- "accept" → Handle Accept; complete carbonize cleanup if required; LOOP
- "discard" → Handle Discard; LOOP
- "prefetch" → Handle Prefetch; LOOP
- "timeout" → LOOP
- "exit" → break → Cleanup
-```
-
-## Recovery commands
-
-The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.
-
-Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:
-
-```bash
-node .trae/skills/impeccable/scripts/live-status.mjs
-node .trae/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID
-node .trae/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID
-```
-
-- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.
-- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.
-- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.
-
-Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.
-
-## Handle `generate`
-
-Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.
-
-Speed matters; the user is watching a spinner. Minimize tool calls by using the `wrap` helper and writing all variants in a single edit.
-
-### 1. Read the screenshot (if present)
-
-`event.screenshotPath` is **only sent when the user placed at least one comment or stroke before Go.** When present, it's an absolute path to a PNG of the element as rendered with the annotations baked in. **Read it before planning**: annotations encode user intent not recoverable from `element.outerHTML` alone.
-
-When `screenshotPath` is absent, don't ask for one and don't go looking for the current rendering. The omission is deliberate: without annotations, a screenshot would anchor the model on the existing design and fight the three-distinct-directions brief. Work from `element.outerHTML`, the computed styles in `event.element`, and the freeform prompt if present.
-
-`event.comments` and `event.strokes` carry structured metadata alongside the visual. Treat the screenshot as primary; use the structured data for specifics worth quoting (e.g. the exact text of a comment).
-
-Reading annotations precisely:
-
-- **Comment position carries meaning.** Its `{x, y}` is element-local CSS px (same coord space as `element.boundingRect`). Find the child under that point and apply the comment text LOCALLY to that sub-element. A comment near the title is about the title, not a global description.
-- **Comments and strokes are independent annotations** unless clearly paired by overlap or tight proximity. Don't let the visual weight of a prominent stroke override the precise location of a textually-specific comment elsewhere.
-- **Strokes are gestures; read them by shape.** Closed loop = "this thing" (emphasis / focus); arrow = direction (move / point to); cross or slash = delete; free scribble = emphasis or delete depending on context. A loop around region X means "pay attention to X," not "only change pixels inside X."
-- **When a stroke's intent is ambiguous** (circle or arrow? emphasis or move?), state your reading in one sentence of rationale rather than silently guessing. If the uncertainty materially changes the brief, ask one short clarifying question before generating.
-
-### 2. Wrap the element
-
-```bash
-node .trae/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"
-```
-
-Flag mapping. Keep them separate, don't collapse into `--query`:
-
-- `--element-id` ← `event.element.id`
-- `--classes` ← `event.element.classes` joined with commas
-- `--tag` ← `event.element.tagName`
-- `--text` ← first ~80 chars of `event.element.textContent` (trim, single-line). **Pass this every call.** When the picked element shares classes + tag with sibling components (a list of `<Card>`s, repeating sections), this is what disambiguates which branch in source to wrap. Without it, wrap silently lands on the first match and may rewrite the wrong element.
-
-The helper searches ID first, then classes, then tag + class combo. If `event.pageUrl` implies the file (e.g. `/` is usually `index.html`), pass `--file PATH` to skip the search. `--query` is a fallback for raw text search only; do not use it for normal element lookups.
-
-If `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.
-
-Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.
-
-`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:
-
-- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.
-- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.
-
-Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.
-
-**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:
-
-- `{ error: "file_is_generated", file, hint }`: user-supplied `--file` points at a generated file.
-- `{ error: "element_not_in_source", generatedMatch, hint }`: element exists only in a generated file (the next build would wipe any edits).
-- `{ error: "element_not_found", hint }`: element isn't in any project file; likely runtime-injected (JS component, dynamic render from data).
-
-All three carry `fallback: "agent-driven"`. Follow **Handle fallback** below.
-
-### 3. Load the action's reference
-
-If `event.action` is `impeccable` (the default freeform action), use SKILL.md's shared laws plus the loaded register reference (`brand.md` or `product.md`). Do not load a sub-command reference. **Freeform is not a pass to skip parameters:** you still follow the composition budget and the freeform bias in **§7 Parameters** below. Sub-command files list MUST-have signature knobs; freeform has no such file, so sizing knobs from surface weight and primary axes is entirely on you.
-
-Any other `event.action` (`bolder`, `quieter`, `distill`, `polish`, `typeset`, `colorize`, `layout`, `adapt`, `animate`, `delight`, `overdrive`): Read `reference/<action>.md` before planning. Each sub-command encodes a specific discipline; skipping its reference produces generic output. Those files may require specific params; layer them on top of the §7 budget, not instead of it.
-
-### 4. Plan three variants: identity first, then mode, then axes
-
-The wrong frame for live mode is "show three different design directions." Live runs on an existing surface; the brand has already been chosen. The job is variation **within identity**, not selection between identities. Failure mode: three editorial-typographic variants on a brief that wasn't editorial. Bigger failure mode: three off-brand variants the user can't accept because they don't look like their product.
-
-Four phases. Do them in order.
-
-#### Phase A: Extract the identity (non-skippable)
-
-The existing surface has an identity already. Read it before planning anything. Sources, in priority order:
-
-1. **DESIGN.md** if loaded: read the visual system fields (palette, type pairing, motion, components). This is the authoritative answer.
-2. **CSS custom properties** in the page's stylesheets (`:root { --color-...; --font-...; ... }`): these are de-facto tokens.
-3. **Computed styles** on the picked element and its parent: colors, fonts, spacing scales, corner radii.
-4. **Sibling components on the page**: what visual rhetoric do existing components use? (Asymmetric or centered? Dense or airy? Bold or quiet?)
-
-Write down what you see in **one sentence**. The sentence describes the surface that's actually on screen; it is not aspirational, not opinionated, not edited toward what the brand "should" be. Capture, in roughly this order:
-
-- The dominant surface color and accent color, by hex or token name (use the actual values, not categories like "warm" or "neutral").
-- The type pairing: the actual font names loaded, primary first.
-- The layout topology: how the dominant elements are arranged (stacked / side-by-side / grid / asymmetric / overlay).
-- The surface treatment: corners, borders, shadows, density of decoration.
-- The voice tone you read off the copy itself, not off the aesthetic feel.
-
-Be specific. "Modern" is not a color, "elegant" is not a type pairing, "clean" is not a layout. If you can't extract a real value for an axis, skip it rather than fabricate. The point is to record what is, not to describe what you wish it were.
-
-Do not include adjectives that name an aesthetic family ("editorial-leaning", "terminal-flavored", "brutalist"); those are conclusions, not data. They belong to Phase C lane selection in departure mode, not to identity description. Letting them sneak into Phase A is how the identity-lock collapses into a self-fulfilling prophecy.
-
-This sentence is the **identity lock**. Every variant must be readable as the same brand if rendered side by side. Skipping this phase is the primary cause of off-brand variants. Absence of DESIGN.md is never an excuse; extract from CSS and computed styles instead.
-
-#### Phase B: Pick mode (default vs departure)
-
-**Default mode**: the existing identity is preserved. Variants vary expression axes within it. *This is the right mode for ~90% of live sessions.* The user picked an element on a real product they're shipping; they expect variants of *their* hero, not three different brands' heroes.
-
-**Departure mode**: the existing identity is rejected. Variants propose alternatives consistent with PRODUCT.md voice. Trigger only when at least one is true:
-
-- PRODUCT.md anti-references explicitly call out the current surface ("the current `index.html` is itself an example"; "diffuse away from this"; "the page on screen is the failure"). Generic anti-references that describe what to avoid in general do **not** trigger departure mode; only ones that point at *this* surface specifically.
-- The user's freeform prompt explicitly asks for departure ("rebuild this from scratch", "what if it weren't editorial at all", "show me something completely different").
-
-If you're unsure, you're in default mode. The cost of being wrong about default is "three on-brand variants with similar feel": recoverable, the user picks none. The cost of being wrong about departure is "three off-brand variants": unrecoverable, the user is annoyed.
-
-#### Phase C: Plan three variants
-
-**Default mode.** Each variant commits to a different **primary axis** of difference, while preserving the identity sentence. The six axes:
-
-1. **Hierarchy**: which element commands the eye?
-2. **Layout topology**: stacked / side-by-side / grid / asymmetric / overlay
-3. **Typographic system**: pairing logic, scale ratio, case/weight strategy *within the available faces*
-4. **Color strategy**: which existing palette role carries the surface (Restrained / Committed / Full palette / Drenched). Use the brand's existing palette tokens, not new colors.
-5. **Density**: minimal / comfortable / dense
-6. **Structural decomposition**: merge, split, progressive disclosure
-
-Three variants → three DIFFERENT axes. The trio reads as *the same brand at three angles*. Do not introduce new fonts, new palette hues, or new aesthetic-family signals; those belong to departure mode.
-
-**While planning each variant, also name its 2–3 parameter knobs** (per the §7 budget table). Parameters are part of the design, not a decoration added afterward. If the variant explores density, expose a density knob. If it explores color commitment, expose a color-amount range. Deciding "what's tunable" during planning produces better knobs than retrofitting them onto finished HTML.
-
-**Departure mode.** Each variant anchors to a different **aesthetic direction**, derived from the brand's stated voice and register in PRODUCT.md. Do NOT pick from a fixed catalog of lane categories. The right three directions for this brand are not the same as the right three for another brand, and picking from a list is itself the training-data reflex (the model selects "Swiss-grid, Terminal, Industrial-signage" every time because those are the furthest-from-editorial items in any enumerated list).
-
-Instead, work from the brand:
-
-1. Read PRODUCT.md's Brand Personality words. What physical, spatial, or material experiences would embody those words if design were not involved? (A personality described as "specific, earned, unmistakable" evokes a hand-stamped letter, a numbered print, a watchmaker's loupe. A personality described as "restless, loud, unfiltered" evokes a concert poster, a spray-painted wall, a megaphone.)
-2. From those physical experiences, derive three visual directions that are genuinely different from each other AND from the current surface you're departing.
-3. Avoid the **reflex-reject lanes** in [brand.md](brand.md). Don't trade one monoculture for another. If you find yourself reaching for "Swiss-grid" or "Terminal" or "Industrial-signage" by reflex, you are pattern-matching a catalog in your training data, not reading the brand. Start over from the personality words.
-4. Each direction must be expressible in one concrete sentence that names a real-world referent ("a museum exhibition label system for a contemporary art gallery" not "clean and minimal"). If your sentence contains only adjectives, it's not concrete enough.
-5. **While planning each direction, also name its 2–3 parameter knobs** (per the §7 budget table). The same principle as default mode: decide "what's tunable" during planning, not after writing the HTML. A departure-mode hero with 0 parameters is not "bold creative vision," it's a missed opportunity for the user to fine-tune the direction they pick.
-
-#### Phase D: Squint test
-
-**Default mode squint.** Read each variant's identity sentence and compare to the locked identity from Phase A. If any variant has drifted to a different palette, type voice, or visual rhetoric, it has crossed into departure mode by accident; rework. Then check that each variant commits to a different primary axis. Three "tighter density" variants is failure.
-
-**Departure mode squint.** Two passes, family before sentence:
-
-1. **Family pass.** Label each variant with one design-family word of your own choosing (any concrete noun: *exhibition, storefront, cockpit, recipe-card, playbill, field-manual*). If any two variants share a label, or if the label could apply to the other variants equally well, rework. Do not use a fixed vocabulary list for the labels. *This pass is non-negotiable in departure mode and catches the monoculture failure that the sentence pass misses.*
-2. **Sentence pass.** Write three one-sentence descriptions side by side. If two of them rhyme ("both feature big type" / "both are stacks of sections" / "both center the CTA"), rework the offender.
-
-**When the primary axis is color or theme, forbid the trio from sharing theme + dominant hue.** Two dark-plus-one-dark is not distinct. Aim for three color worlds, not three shades of the same.
-
-**For action-specific invocations**, each variant must vary along the dimension the action names:
-
-- `bolder`: amplify a different dimension per variant (scale / saturation / structural change). Not three "slightly bigger" variants.
-- `quieter`: pull back a different dimension (color / ornament / spacing).
-- `distill`: remove a different class of excess (visual noise / redundant content / nested structure).
-- `polish`: target a different refinement axis (rhythm / hierarchy / micro-details like corner radii, focus states, optical kerning).
-- `typeset`: different type pairing AND different scale ratio each. Not three riffs on one pairing.
-- `colorize`: different hue family each (not shades of one hue). Vary chroma and contrast strategy.
-- `layout`: different structural arrangement (stacked / side-by-side / grid / asymmetric). Not spacing tweaks.
-- `adapt`: different target context per variant (mobile-first / tablet / desktop / print or low-data). Don't make three mobile layouts.
-- `animate`: different motion vocabulary (cascade stagger / clip wipe / scale-and-focus / morph / parallax). Not three staggered fades.
-- `delight`: different flavor of personality (unexpected micro-interaction / typographic surprise / illustrated accent / sonic-or-haptic moment / easter-egg interaction).
-- `overdrive`: different convention broken (scale / structure / motion / input model / state transitions). Skip `overdrive.md`'s "propose and ask" step; live mode is non-interactive.
-
-### 5. Apply the freeform prompt (if present)
-
-`event.freeformPrompt` is the user's ceiling on direction (all variants must honor it), but still explore meaningfully different *interpretations*. The interpretations stay within whichever mode you picked in Phase B.
-
-In **default mode**, the prompt narrows the axes you choose, not the identity. *"Make it feel more confident"* → variant 1 amplifies hierarchy (one element commands the eye), variant 2 commits the existing accent color (Committed strategy on the brand's hue), variant 3 tightens density and removes decorative slack. Three different axes, same brand.
-
-In **departure mode**, the prompt narrows the lanes you draw from, not the families. *"Make it feel like a newspaper front page"* would itself be a departure-mode prompt; honor it but pick three meaningfully different newspaper-adjacent lanes (broadsheet vs. tabloid vs. trade journal), and run the family pass to confirm they don't collapse into one.
-
-When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.
-
-### 6. Write all variants in a single edit
-
-Complete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).
-
-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).
-
-Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:
-
-```html
-<!-- Variants: insert below this line -->
-<style data-impeccable-css="SESSION_ID">
- /* rules matching cssAuthoring.rulePattern */
-</style>
-<div data-impeccable-variant="1">
- <!-- variant 1: full element replacement (single top-level element) -->
-</div>
-<div data-impeccable-variant="2" style="display: none">
- <!-- variant 2: full element replacement -->
-</div>
-<div data-impeccable-variant="3" style="display: none">
- <!-- variant 3: full element replacement -->
-</div>
-```
-
-**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.
-
-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.
-
-One edit, all variants; the browser's MutationObserver picks everything up in one pass.
-
-For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.
-
-**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:
-
-```tsx
-<style data-impeccable-css="SESSION_ID">{`
- @scope ([data-impeccable-variant="1"]) { ... }
- @scope ([data-impeccable-variant="2"]) { ... }
-`}</style>
-<div data-impeccable-variant="1">
- {/* variant 1 */}
-</div>
-<div data-impeccable-variant="2" style={{ display: 'none' }}>
- {/* variant 2 */}
-</div>
-```
-
-The wrap script already gives you a single-rooted JSX wrapper: a `<div data-impeccable-variants="…">` outer element with the marker comments tucked inside. Drop the variants block above into the "Variants: insert below this line" comment and the source stays valid TSX.
-
-### 7. Parameters (composition-sized, 0–4 per variant)
-
-Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement. The browser docks a small panel to the right of the outline with one control per parameter. The user drags/clicks and sees instant feedback: there is zero regeneration cost because the knob toggles a CSS variable or data attribute that the variant's scoped CSS is already authored against.
-
-**What “optional” does not mean.** Parameters are not nice-to-have decoration on large work. The word meant “omit controls that are redundant or cosmetic,” not “default to zero because three variants were enough work.”
-
-**When to add.** As soon as the variant’s scoped CSS has a meaningful continuous or stepped axis: density, color amount, type scale, motion intensity, column weight, and so on. If you can imagine the user muttering “a bit tighter” or “a touch more accent” **without** wanting a full regeneration, wire that axis. **Not** micro-margins or one-off nudges; those are not parameters.
-
-**Freeform (`action` is `impeccable`) bias.** You did not load a sub-command reference, so you must **choose** signature axes yourself. Match the budget table: for a hero or large composition, that means **2–3 axes per variant**, not 1. Prefer knobs that sit on the dimensions where your three variants actually differ (if density varies, expose it as a `steps` knob; if color commitment varies, expose it as a `range`). A hero that ships with **0** params is almost always a mistake, not a judgment call. A hero with exactly **1** param is underweight unless the design is genuinely a fixed-point comparison. Start from the budget table, not from zero.
-
-**Budget scales with the element's visual weight, not token budget.** Knobs need real estate to read as tunable; three sliders on a single control are noise.
-
-- **Leaf / tiny**: a single button, icon, input, bare heading, solitary paragraph: **0 params.**
-- **Small composition**: labeled input, simple card, short callout (≤ ~5 visual children): **0–1** params when one dominant axis is obvious; otherwise **0.**
-- **Medium composition**: section component, nav cluster, dense card, short feature block (6–15 visual children): **target 2**; **1** is acceptable if the block is simple; **0** only when variants are truly fixed points.
-- **Large composition**: hero section, full page region, spread layout, strong internal structure (16+ visual children or multiple sub-sections): **target 2–3**; **up to 4** when several independent axes (e.g. structure `steps` + `density` + one accent) are all authored in scoped CSS.
-
-**When in doubt, ask whether a dial exists before defaulting to zero.** The user can always request more variants, but the point of live mode is instant tuning without another Go. Crowding the panel is bad; **under-shipping** knobs on a dense composition is the more common failure for freeform. Count by **visual** children, not DOM depth; a shallow-but-wide hero is still large.
-
-**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.
-
-**How to declare.** Put a JSON manifest on the variant wrapper:
-
-```html
-<div data-impeccable-variant="1" data-impeccable-params='[
- {"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"},
- {"id":"density","kind":"steps","default":"snug","label":"Density","options":[
- {"value":"airy","label":"Airy"},
- {"value":"snug","label":"Snug"},
- {"value":"packed","label":"Packed"}
- ]},
- {"id":"serif","kind":"toggle","default":false,"label":"Serif display"}
-]'>
- ...variant content...
-</div>
-```
-
-**Three kinds:**
-
-- `range`: smooth slider. Drives a CSS custom property `--p-<id>` on the variant wrapper. Author CSS with `var(--p-color-amount, 0.5)`. Fields: `min`, `max`, `step`, `default` (number), `label`.
-- `steps`: segmented radio. Drives a data attribute `data-p-<id>` on the variant wrapper. Author CSS with `:scope[data-p-density="airy"] .grid { ... }`. Fields: `options` (array of `{value, label}`), `default` (string), `label`.
-- `toggle`: on/off switch. Drives BOTH a CSS var (`--p-<id>: 0|1`) and a data attribute (present when on, absent when off). Use whichever is more convenient. Fields: `default` (boolean), `label`.
-
-**Signature params per action.** For named sub-commands, read that action’s `reference/<action>.md` for one or two **MUST** params (e.g. `layout` → `density`). Those are non-negotiable when the design can express them. **Freeform has no file-level MUST**; the **Freeform (`impeccable`) bias** in this section is the stand-in. If the user’s action is both stylized and sub-command (e.g. `colorize`), the sub-command’s MUST list takes precedence for its axes; still respect the **Hard cap** and add no redundant duplicate knobs.
-
-**Reset on variant switch.** User dials density on v1, flips to v2, v2 starts at v2's declared defaults. Known limitation; preservation across variants may land later.
-
-**On accept**, the browser sends the user's current values in the accept event. `live-accept.mjs` writes them as a sibling comment:
-
-```html
-<!-- impeccable-param-values SESSION_ID: {"color-amount":0.7,"density":"packed"} -->
-```
-
-The carbonize cleanup step (see below) reads that comment and bakes the chosen values into the final CSS. For `steps`/`toggle` attribute selectors: keep only the branch matching the chosen value, drop the others, collapse `:scope[data-p-density="packed"] .grid` to a semantic class rule. For `range` vars: either substitute the literal or keep the var with the chosen value as its new default.
-
-### 8. Signal done
-
-```bash
-node .trae/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
-```
-
-`RELATIVE_PATH` is relative to project root (`public/index.html`, `src/App.tsx`, etc.); the browser fetches source directly if the dev server lacks HMR.
-
-Then run `live-poll.mjs` again immediately.
-
-### Aborting an in-flight session
-
-If wrap or generation fails after the browser has flipped to GENERATING (e.g. wrap landed on the wrong source branch and you've already reverted it, or generation hit an unrecoverable error), tell the **browser** so its bar resets to PICKING:
-
-```bash
-node .trae/skills/impeccable/scripts/live-poll.mjs --reply EVENT_ID error "Short reason"
-```
-
-Don't run `live-accept --discard` for this; that's a pure file mutator, the browser doesn't see it, and the bar gets stuck on the GENERATING dots forever (the user has to refresh). `--discard` is only correct when the **browser** initiated the discard (user clicked ✕ during CYCLING) and the agent is just running source-side cleanup the browser already triggered.
-
-## Handle fallback
-
-When wrap returns `fallback: "agent-driven"`, the deterministic flow doesn't apply. Pick up here.
-
-The goal is the same: give the user three variants to choose from AND persist the accepted one in a place the next build won't wipe. The difference is that you have to pick the right source file yourself.
-
-### Step 1: Identify where the element actually lives
-
-Use the error payload:
-
-- `element_not_in_source` with `generatedMatch: "public/docs/foo.html"`: the served HTML is generated. Find the generator (grep for writers of that path, e.g. `scripts/build-sub-pages.js`, an Astro/Next template) and locate the template or partial that emits this element.
-- `element_not_found`: the element is runtime-injected. Look for the component that renders it (React/Vue/Svelte), the JS that assembles it, or the data source that feeds it.
-- `file_is_generated` with `file: "..."`: user pointed at a generated file explicitly. Same resolution as `element_not_in_source`.
-
-Read the candidate source until you're confident where a change to the element would belong. If the change is purely visual, that source might be a shared stylesheet, not the template.
-
-### Step 2: Show three variants in the DOM for preview
-
-The browser bar is waiting for variants. Even without a wrapper in source, you still need to show something:
-
-1. Manually write the wrapper scaffold into the **served** file (the one the browser actually loaded). Use the same structure `live-wrap.mjs` produces; `<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents">…</div><!-- end -->`.
-2. Insert your three variant divs inside it, same shape as the deterministic path.
-3. Signal done with `--reply EVENT_ID done --file <served file>`. The browser's no-HMR fallback will fetch and inject.
-
-This served-file edit is **temporary**: next regen wipes it, and that's fine. The real work happens on accept.
-
-### Step 3: On accept, write to true source
-
-When the accept event arrives (`_acceptResult.handled` will usually be `false` here because accept also refuses to persist into generated files; see Handle accept for the carbonize branch), extract the accepted variant's content and write it into the source you identified in Step 1:
-
-- Structural change → edit the template / component source.
-- Visual-only change → add or update rules in the appropriate stylesheet; remove the inline `<style>` scope.
-- Dynamic from data → update the data source or the render logic.
-
-Then remove the temporary wrapper from the served file if it's still there.
-
-### Step 4: On discard, clean up the served file
-
-Remove the wrapper you inserted in Step 2. Nothing else to do.
-
-## Handle `accept`
-
-Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.
-
-- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.
-- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.
-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.
-- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.
-- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.
-
-### Required after accept (carbonize)
-
-When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.
-
-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.
-
-1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.
-2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).
-3. **Bake in parameter values while rewriting selectors.** For `@scope ([data-impeccable-variant="N"])` wrappers: retarget to real, semantic classes on the accepted HTML (`.why-visual--v2 .v2-label { … }`). For `:scope[data-p-<id>="VALUE"]` selectors: keep only the branch matching the chosen value from the param-values comment; drop the others (they're dead after accept). For `var(--p-<id>, DEFAULT)` in the CSS: either substitute the literal value, or if the param is still useful as a knob going forward, leave the var and update its initial declaration to the chosen value.
-4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; those are live-mode plumbing, not source.
-5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.
-
-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.
-
-A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.
-
-## Handle `discard`
-
-Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.
-
-## Handle `prefetch`
-
-Event: `{pageUrl}`. The browser fires this the first time the user selects an element on a given route, as a latency shortcut; it signals the user is likely about to Go on a page you haven't read yet.
-
-Resolve `pageUrl` to the underlying file:
-
-- Root `/` → the `pageFile` returned by `live.mjs` (usually `public/index.html` or equivalent).
-- Sub-routes (e.g. `/docs`, `/docs/live`) → the generated or source file for that route. Use your knowledge of the project layout (multi-page static sites often resolve `/foo` → `public/foo/index.html`; SPAs may map all routes to a single entry).
-
-Read the file into context, then poll again. No `--reply`: this is speculative pre-work; Go will come later. If you can't confidently resolve the route to a file, skip and poll again.
-
-Dedupe is the browser's job (one prefetch per unique pathname per session); trust it. If the same file shows up twice from different routes mapping to the same file, the second Read is cached anyway.
-
-## Exit
-
-The user can stop live mode by:
-- Saying "stop live mode" / "exit live" in chat
-- Closing the browser tab (SSE drops, poll returns `exit` after 8s)
-- The browser's exit button
-
-When the poll returns `exit`, proceed to cleanup. If the poll is still running as a background task, kill it first.
-
-## Cleanup
-
-```bash
-node .trae/skills/impeccable/scripts/live-server.mjs stop
-```
-
-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.
-
-Then:
-- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).
-- Remove any leftover carbonize blocks (search for `impeccable-carbonize-start` markers).
-
-## First-time setup (config missing or invalid)
-
-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.
-
-Schema:
-
-```json
-{
- "files": ["<path-or-glob>", "<path-or-glob>", ...],
- "exclude": ["<optional-glob>", ...],
- "insertBefore": "</body>",
- "commentSyntax": "html",
- "cspChecked": true
-}
-```
-
-`files` is the inject target; **the HTML files the browser actually loads**, not necessarily source. Each entry is either a literal path (`"public/index.html"`) or a glob pattern (`"public/**/*.html"`). Tracked or generated doesn't matter here; wrap has its own generated-file guard and routes accepts through the fallback flow.
-
-`exclude` (optional) is a list of glob patterns matching files to skip, even if a `files` glob would have included them. Use for email templates, demo fixtures, or any HTML that isn't a live page.
-
-`cspChecked` tracks whether the CSP detection step below has already run. Absent on first setup; set to `true` after CSP is checked (whether patched, declined, or not needed).
-
-**Hard-excluded paths (cannot be overridden).** `**/node_modules/**` and `**/.git/**` are never matched regardless of what the user writes. These are vendor/metadata directories and injecting into them would silently instrument third-party code.
-
-**Glob syntax.** `**` matches any number of path segments (including zero), `*` matches any characters except `/`, `?` matches a single character except `/`. Paths are always relative to the project root with forward slashes.
-
-| Framework | `files` | `insertBefore` | `commentSyntax` |
-|-----------|---------|----------------|-----------------|
-| SPA with single shell (Vite / React / Plain HTML) | `["index.html"]` | `</body>` | `html` |
-| Next.js (App Router) | `["app/layout.tsx"]` | `</body>` | `jsx` |
-| Next.js (Pages) | `["pages/_document.tsx"]` | `</body>` | `jsx` |
-| Nuxt | `["app.vue"]` | `</body>` | `html` |
-| Svelte / SvelteKit | `["src/app.html"]` | `</body>` | `html` |
-| Astro | `[" <root layout .astro>"]` | `</body>` | `html` |
-| Multi-page (separate HTML per route) | `["public/**/*.html"]`: a glob covering the served directory | `</body>` | `html` |
-
-Pick an anchor that exists in every file (`</body>` almost always works). Use `insertAfter` if the anchor should match **after** a specific line.
-
-For multi-page sites, **prefer a glob over a literal file list**. New pages added later are picked up automatically on the next `live-inject.mjs` run; no config maintenance needed.
-
-For multi-page sites whose pages are *rebuilt* by a generator (Astro, static-site generators, custom scripts like `build-sub-pages.js`), the inject survives only until the next regeneration. Re-run `live.mjs` after each build. Accept is unaffected; it writes to true source via the fallback flow.
-
-### Drift-heal warning
-
-On every `live.mjs` boot, after inject, the project is scanned for HTML files under common page-source roots (`public/`, `src/`, `app/`, `pages/`). If any exist that aren't covered by the resolved `files` list, the output includes a `configDrift` field:
-
-```json
-{
- "ok": true,
- "serverPort": 8400,
- "pageFiles": [ "..." ],
- "configDrift": {
- "orphans": ["public/new-section/index.html", "public/docs/new-command.html"],
- "orphanCount": 2,
- "hint": "2 HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like \"public/**/*.html\"."
- }
-}
-```
-
-When `configDrift` is present, surface it to the user once per session before entering the poll loop:
-
-> Noticed N HTML file(s) in the project that aren't in `config.files`:
->
-> - `public/new-section/index.html`
-> - `public/docs/new-command.html`
->
-> Add them, or switch `files` to a glob like `["public/**/*.html"]` and let it track new pages automatically?
-
-Don't auto-update the config; let the user decide. `configDrift` is `null` when there's no drift.
-
-### CSP detection (first-time only)
-
-If `config.cspChecked === true`, skip this entire section. You already asked this user once; the answer sticks.
-
-Otherwise, run the detection helper:
-
-```bash
-node .trae/skills/impeccable/scripts/detect-csp.mjs
-```
-
-Output: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.
-
-- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.
-- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:
- - Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)
- - SvelteKit `kit.csp.directives`
- - Nuxt `nuxt-security` module's `contentSecurityPolicy`
-- **`append-string`**: CSP written as a literal value string. Auto-patchable. See *append-string* below. Covers:
- - Inline `next.config.*` `headers()` with a CSP literal
- - Nuxt `routeRules` / `nitro.routeRules` headers
-- **`middleware`** or **`meta-tag`**: rarer. Detected but not auto-patched in v1. Show the user the detected files and ask them to add `http://localhost:8400` to `script-src` and `connect-src` manually, then mark `cspChecked: true` and proceed.
-
-#### Consent prompt template
-
-Use this phrasing so the experience is consistent across agents:
-
-> **CSP patch needed.** I detected a Content Security Policy in your project that blocks `http://localhost:8400`: the live picker won't load without an allowance. Here's the change I'd make:
->
-> ```diff
-> [file: <patchTarget>]
-> [exact diff, 2–5 lines]
-> ```
->
-> It's guarded by `NODE_ENV === "development"` so the extra entry only appears in dev and never reaches production. You can remove it any time by reverting this file. Apply? [y/n]
-
-On "no": skip the patch, mention live won't work until the user adds the allowance manually, still write `cspChecked: true` (the question's been asked).
-
-On "yes": apply the Shape-specific patch below, then write `cspChecked: true`.
-
-#### append-arrays
-
-CSP expressed as structured directive arrays. Patch mechanism: declare a dev-only array, spread it into the script-src and connect-src arrays.
-
-**Declare near the top of the file that holds the CSP arrays:**
-
-```ts
-// Dev-only allowance so impeccable live mode can load. Guarded by NODE_ENV.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? ["http://localhost:8400"] : [];
-```
-
-**Append `...__impeccableLiveDev` to the script-src and connect-src directive arrays.** Per-framework specifics:
-
-- **Next.js + monorepo helper**: edit the *app's* `next.config.*` (not the shared helper), appending to `additionalScriptSrc` and `additionalConnectSrc` passed into `createBaseNextConfig` (or equivalent). Keeps the shared package clean.
-- **SvelteKit**: edit `svelte.config.js`, appending to `kit.csp.directives['script-src']` and `kit.csp.directives['connect-src']`.
-- **Nuxt + nuxt-security**: edit `nuxt.config.*`, appending to `security.headers.contentSecurityPolicy['script-src']` and `['connect-src']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-turborepo/expected-after-patch.ts` (Next.js)
-- `tests/framework-fixtures/sveltekit-csp/expected-after-patch.js` (SvelteKit)
-
-Idempotency: if `__impeccableLiveDev` already exists in the file, the patch is already applied; skip asking and just mark `cspChecked: true`.
-
-#### append-string
-
-CSP built as a literal value string. Two-point patch: declare a dev-only string near the top, interpolate it into the CSP at the `script-src` and `connect-src` directives.
-
-```ts
-// Dev-only allowance so impeccable live mode can load.
-const __impeccableLiveDev =
- process.env.NODE_ENV === "development" ? " http://localhost:8400" : "";
-```
-
-Then in the CSP value string:
-- `script-src 'self' 'unsafe-inline'` → `` `script-src 'self' 'unsafe-inline'${__impeccableLiveDev}` ``
-- `connect-src 'self'` → `` `connect-src 'self'${__impeccableLiveDev}` ``
-
-(Leading space on the dev string so it concatenates cleanly into the existing value. Convert the literal CSP directives into template strings as part of the edit if they aren't already.)
-
-Per-framework specifics:
-- **Next.js inline `headers()`**: edit `next.config.*`, splicing the variable into the CSP value.
-- **Nuxt `routeRules`**: edit `nuxt.config.*`, splicing into the CSP in `routeRules['/**'].headers['Content-Security-Policy']`.
-
-Reference outputs:
-- `tests/framework-fixtures/nextjs-inline-csp/expected-after-patch.js` (Next.js)
-- `tests/framework-fixtures/nuxt-csp/expected-after-patch.ts` (Nuxt)
-
-### Troubleshooting
-
-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.
-
-Then re-run `live.mjs`.
@@ -1,109 +0,0 @@
-# Motion Design
-
-## Duration: The 100/300/500 Rule
-
-Timing matters more than easing. These durations feel right for most UI:
-
-| Duration | Use Case | Examples |
-|----------|----------|----------|
-| **100-150ms** | Instant feedback | Button press, toggle, color change |
-| **200-300ms** | State changes | Menu open, tooltip, hover states |
-| **300-500ms** | Layout changes | Accordion, modal, drawer |
-| **500-800ms** | Entrance animations | Page load, hero reveals |
-
-**Exit animations are faster than entrances.** Use ~75% of enter duration.
-
-## Easing: Pick the Right Curve
-
-**Don't use `ease`.** It's a compromise that's rarely optimal. Instead:
-
-| Curve | Use For | CSS |
-|-------|---------|-----|
-| **ease-out** | Elements entering | `cubic-bezier(0.16, 1, 0.3, 1)` |
-| **ease-in** | Elements leaving | `cubic-bezier(0.7, 0, 0.84, 0)` |
-| **ease-in-out** | State toggles (there → back) | `cubic-bezier(0.65, 0, 0.35, 1)` |
-
-**For micro-interactions, use exponential curves.** They feel natural because they mimic real physics (friction, deceleration):
-
-```css
-/* Quart out - smooth, refined (recommended default) */
---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1);
-
-/* Quint out - slightly more dramatic */
---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1);
-
-/* Expo out - snappy, confident */
---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1);
-```
-
-**Avoid bounce and elastic curves.** They were trendy in 2015 but now feel tacky and amateurish. Real objects don't bounce when they stop; they decelerate smoothly. Overshoot effects draw attention to the animation itself rather than the content.
-
-## Premium Motion Materials
-
-Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties: blur reveals, backdrop-filter panels, saturation or brightness shifts, shadow bloom, SVG filters, masks, clip paths, gradient-position movement, and variable font or shader-driven effects.
-
-Use the right material for the effect:
-
-- **Transform / opacity**: movement, press feedback, simple reveals, list choreography.
-- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances, atmospheric transitions.
-- **Clip path / masks**: wipes, reveals, editorial cropping, product-like transitions.
-- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state.
-- **Grid-template rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly.
-
-The hard rule is not "transform and opacity only." The hard rule is: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify in-browser that the result is smooth on the target viewports. If blur/filter makes the interaction feel significantly more premium and remains smooth, use it.
-
-## Staggered Animations
-
-Use CSS custom properties for cleaner stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"` on each item. **Cap total stagger time**: 10 items at 50ms = 500ms total. For many items, reduce per-item delay or cap staggered count.
-
-## Reduced Motion
-
-This is not optional. Vestibular disorders affect ~35% of adults over 40.
-
-```css
-/* Define animations normally */
-.card {
- animation: slide-up 500ms ease-out;
-}
-
-/* Provide alternative for reduced motion */
-@media (prefers-reduced-motion: reduce) {
- .card {
- animation: fade-in 200ms ease-out; /* Crossfade instead of motion */
- }
-}
-
-/* Or disable entirely */
-@media (prefers-reduced-motion: reduce) {
- *, *::before, *::after {
- animation-duration: 0.01ms !important;
- transition-duration: 0.01ms !important;
- }
-}
-```
-
-**What to preserve**: Functional animations like progress bars, loading spinners (slowed down), and focus indicators should still work, just without spatial movement.
-
-## Perceived Performance
-
-**Nobody cares how fast your site is, just how fast it feels.** Perception can be as effective as actual performance.
-
-**The 80ms threshold**: Our brains buffer sensory input for ~80ms to synchronize perception. Anything under 80ms feels instant and simultaneous. This is your target for micro-interactions.
-
-**Active vs passive time**: Passive waiting (staring at a spinner) feels longer than active engagement. Strategies to shift the balance:
-
-- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening.
-- **Early completion**: Show content progressively, don't wait for everything. Video buffering, progressive images, streaming HTML.
-- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Instagram likes work offline; the UI updates instantly, syncs later. Use for low-stakes actions; avoid for payments or destructive operations.
-
-**Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances, but ease-in toward a task's end compresses perceived time.
-
-**Caution**: Too-fast responses can decrease perceived value. Users may distrust instant results for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
-
-## Performance
-
-Don't use `will-change` preemptively, only when animation is imminent (`:hover`, `.animating`). For scroll-triggered animations, use Intersection Observer instead of scroll events; unobserve after animating once. Create motion tokens for consistency (durations, easings, common transitions).
-
----
-
-**Avoid**: Animating everything (animation fatigue is real). Using >500ms for UI feedback. Ignoring `prefers-reduced-motion`. Using animation to hide slow loading.
@@ -1,234 +0,0 @@
-> **Additional context needed**: the "aha moment" you want users to reach, and users' experience level.
-
-Get users to first value as fast as possible. Onboarding's job is not to teach the product. Its job is to get people to the moment that proves the product is worth their time.
-
-## Assess Onboarding Needs
-
-Understand what users need to learn and why:
-
-1. **Identify the challenge**:
- - What are users trying to accomplish?
- - What's confusing or unclear about current experience?
- - Where do users get stuck or drop off?
- - What's the "aha moment" we want users to reach?
-
-2. **Understand the users**:
- - What's their experience level? (Beginners, power users, mixed?)
- - What's their motivation? (Excited and exploring? Required by work?)
- - What's their time commitment? (5 minutes? 30 minutes?)
- - What alternatives do they know? (Coming from competitor? New to category?)
-
-3. **Define success**:
- - What's the minimum users need to learn to be successful?
- - What's the key action we want them to take? (First project? First invite?)
- - How do we know onboarding worked? (Completion rate? Time to value?)
-
-**CRITICAL**: Onboarding should get users to value as quickly as possible, not teach everything possible.
-
-## Onboarding Principles
-
-Follow these core principles:
-
-### Show, Don't Tell
-- Demonstrate with working examples, not just descriptions
-- Provide real functionality in onboarding, not separate tutorial mode
-- Use progressive disclosure, teach one thing at a time
-
-### Make It Optional (When Possible)
-- Let experienced users skip onboarding
-- Don't block access to product
-- Provide "Skip" or "I'll explore on my own" options
-
-### Time to Value
-- Get users to their "aha moment" ASAP
-- Front-load most important concepts
-- Teach 20% that delivers 80% of value
-- Save advanced features for contextual discovery
-
-### Context Over Ceremony
-- Teach features when users need them, not upfront
-- Empty states are onboarding opportunities
-- Tooltips and hints at point of use
-
-### Respect User Intelligence
-- Don't patronize or over-explain
-- Be concise and clear
-- Assume users can figure out standard patterns
-
-## Design Onboarding Experiences
-
-Create appropriate onboarding for the context:
-
-### Initial Product Onboarding
-
-**Welcome Screen**:
-- Clear value proposition (what is this product?)
-- What users will learn/accomplish
-- Time estimate (honest about commitment)
-- Option to skip (for experienced users)
-
-**Account Setup**:
-- Minimal required information (collect more later)
-- Explain why you're asking for each piece of information
-- Smart defaults where possible
-- Social login when appropriate
-
-**Core Concept Introduction**:
-- Introduce 1-3 core concepts (not everything)
-- Use simple language and examples
-- Interactive when possible (do, don't just read)
-- Progress indication (step 1 of 3)
-
-**First Success**:
-- Guide users to accomplish something real
-- Pre-populated examples or templates
-- Celebrate completion (but don't overdo it)
-- Clear next steps
-
-### Feature Discovery & Adoption
-
-**Empty States**:
-Instead of blank space, show:
-- What will appear here (description + screenshot/illustration)
-- Why it's valuable
-- Clear CTA to create first item
-- Example or template option
-
-Example:
-```
-No projects yet
-Projects help you organize your work and collaborate with your team.
-[Create your first project] or [Start from template]
-```
-
-**Contextual Tooltips**:
-- Appear at relevant moment (first time user sees feature)
-- Point directly at relevant UI element
-- Brief explanation + benefit
-- Dismissable (with "Don't show again" option)
-- Optional "Learn more" link
-
-**Feature Announcements**:
-- Highlight new features when they're released
-- Show what's new and why it matters
-- Let users try immediately
-- Dismissable
-
-**Progressive Onboarding**:
-- Teach features when users encounter them
-- Badges or indicators on new/unused features
-- Unlock complexity gradually (don't show all options immediately)
-
-### Guided Tours & Walkthroughs
-
-**When to use**:
-- Complex interfaces with many features
-- Significant changes to existing product
-- Industry-specific tools needing domain knowledge
-
-**How to design**:
-- Spotlight specific UI elements (dim rest of page)
-- Keep steps short (3-7 steps max per tour)
-- Allow users to click through tour freely
-- Include "Skip tour" option
-- Make replayable (help menu)
-
-**Best practices**:
-- Interactive over passive (let users click real buttons)
-- Focus on workflow, not features ("Create a project" not "This is the project button")
-- Provide sample data so actions work
-
-### Interactive Tutorials
-
-**When to use**:
-- Users need hands-on practice
-- Concepts are complex or unfamiliar
-- High stakes (better to practice in safe environment)
-
-**How to design**:
-- Sandbox environment with sample data
-- Clear objectives ("Create a chart showing sales by region")
-- Step-by-step guidance
-- Validation (confirm they did it right)
-- Graduation moment (you're ready!)
-
-### Documentation & Help
-
-**In-product help**:
-- Contextual help links throughout interface
-- Keyboard shortcut reference
-- Search-able help center
-- Video tutorials for complex workflows
-
-**Help patterns**:
-- `?` icon near complex features
-- "Learn more" links in tooltips
-- Keyboard shortcut hints (`⌘K` shown on search box)
-
-## Empty State Design
-
-Every empty state needs:
-
-### What Will Be Here
-"Your recent projects will appear here"
-
-### Why It Matters
-"Projects help you organize your work and collaborate with your team"
-
-### How to Get Started
-[Create project] or [Import from template]
-
-### Visual Interest
-Illustration or icon (not just text on blank page)
-
-### Contextual Help
-"Need help getting started? [Watch 2-min tutorial]"
-
-**Empty state types**:
-- **First use**: Never used this feature (emphasize value, provide template)
-- **User cleared**: Intentionally deleted everything (light touch, easy to recreate)
-- **No results**: Search or filter returned nothing (suggest different query, clear filters)
-- **No permissions**: Can't access (explain why, how to get access)
-- **Error state**: Failed to load (explain what happened, retry option)
-
-## Implementation Patterns
-
-### Technical approaches:
-
-**Tooltip libraries**: Tippy.js, Popper.js
-**Tour libraries**: Intro.js, Shepherd.js, React Joyride
-**Modal patterns**: Focus trap, backdrop, ESC to close
-**Progress tracking**: LocalStorage for "seen" states
-**Analytics**: Track completion, drop-off points
-
-**Storage patterns**:
-```javascript
-// Track which onboarding steps user has seen
-localStorage.setItem('onboarding-completed', 'true');
-localStorage.setItem('feature-tooltip-seen-reports', 'true');
-```
-
-**IMPORTANT**: Don't show same onboarding twice (annoying). Track completion and respect dismissals.
-
-**NEVER**:
-- Force users through long onboarding before they can use product
-- Patronize users with obvious explanations
-- Show same tooltip repeatedly (respect dismissals)
-- Block all UI during tour (let users explore)
-- Create separate tutorial mode disconnected from real product
-- Overwhelm with information upfront (progressive disclosure!)
-- Hide "Skip" or make it hard to find
-- Forget about returning users (don't show initial onboarding again)
-
-## Verify Onboarding Quality
-
-Test with real users:
-
-- **Time to completion**: Can users complete onboarding quickly?
-- **Comprehension**: Do users understand after completing?
-- **Action**: Do users take desired next step?
-- **Skip rate**: Are too many users skipping? (Maybe it's too long or not valuable)
-- **Completion rate**: Are users completing? (If low, simplify)
-- **Time to value**: How long until users get first value?
-
-When users hit the aha moment fast and don't drop off, hand off to `/impeccable polish` for the final pass.
@@ -1,258 +0,0 @@
-Performance is a feature. Identify the actual bottleneck for THIS interface, fix it, then measure. Don't optimize what isn't slow.
-
-## Assess Performance Issues
-
-Understand current performance and identify problems:
-
-1. **Measure current state**:
- - **Core Web Vitals**: LCP, FID/INP, CLS scores
- - **Load time**: Time to interactive, first contentful paint
- - **Bundle size**: JavaScript, CSS, image sizes
- - **Runtime performance**: Frame rate, memory usage, CPU usage
- - **Network**: Request count, payload sizes, waterfall
-
-2. **Identify bottlenecks**:
- - What's slow? (Initial load? Interactions? Animations?)
- - What's causing it? (Large images? Expensive JavaScript? Layout thrashing?)
- - How bad is it? (Perceivable? Annoying? Blocking?)
- - Who's affected? (All users? Mobile only? Slow connections?)
-
-**CRITICAL**: Measure before and after. Premature optimization wastes time. Optimize what actually matters.
-
-## Optimization Strategy
-
-Create systematic improvement plan:
-
-### Loading Performance
-
-**Optimize Images**:
-- Use modern formats (WebP, AVIF)
-- Proper sizing (don't load 3000px image for 300px display)
-- Lazy loading for below-fold images
-- Responsive images (`srcset`, `picture` element)
-- Compress images (80-85% quality is usually imperceptible)
-- Use CDN for faster delivery
-
-```html
-<img
- src="hero.webp"
- srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
- sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
- loading="lazy"
- alt="Hero image"
-/>
-```
-
-**Reduce JavaScript Bundle**:
-- Code splitting (route-based, component-based)
-- Tree shaking (remove unused code)
-- Remove unused dependencies
-- Lazy load non-critical code
-- Use dynamic imports for large components
-
-```javascript
-// Lazy load heavy component
-const HeavyChart = lazy(() => import('./HeavyChart'));
-```
-
-**Optimize CSS**:
-- Remove unused CSS
-- Critical CSS inline, rest async
-- Minimize CSS files
-- Use CSS containment for independent regions
-
-**Optimize Fonts**:
-- Use `font-display: swap` or `optional`
-- Subset fonts (only characters you need)
-- Preload critical fonts
-- Use system fonts when appropriate
-- Limit font weights loaded
-
-```css
-@font-face {
- font-family: 'CustomFont';
- src: url('/fonts/custom.woff2') format('woff2');
- font-display: swap; /* Show fallback immediately */
- unicode-range: U+0020-007F; /* Basic Latin only */
-}
-```
-
-**Optimize Loading Strategy**:
-- Critical resources first (async/defer non-critical)
-- Preload critical assets
-- Prefetch likely next pages
-- Service worker for offline/caching
-- HTTP/2 or HTTP/3 for multiplexing
-
-### Rendering Performance
-
-**Avoid Layout Thrashing**:
-```javascript
-// ❌ Bad: Alternating reads and writes (causes reflows)
-elements.forEach(el => {
- const height = el.offsetHeight; // Read (forces layout)
- el.style.height = height * 2; // Write
-});
-
-// ✅ Good: Batch reads, then batch writes
-const heights = elements.map(el => el.offsetHeight); // All reads
-elements.forEach((el, i) => {
- el.style.height = heights[i] * 2; // All writes
-});
-```
-
-**Optimize Rendering**:
-- Use CSS `contain` property for independent regions
-- Minimize DOM depth (flatter is faster)
-- Reduce DOM size (fewer elements)
-- Use `content-visibility: auto` for long lists
-- Virtual scrolling for very long lists (react-window, react-virtualized)
-
-**Reduce Paint & Composite**:
-- Use `transform` and `opacity` for reliable movement, but allow blur, filters, masks, clip paths, shadows, and color shifts when they create meaningful polish
-- Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
-- Use `will-change` sparingly for known expensive operations
-- Bound expensive paint areas for blur/filter/shadow effects (smaller and isolated is faster)
-
-### Animation Performance
-
-**GPU Acceleration**:
-```css
-/* ✅ GPU-accelerated (fast) */
-.animated {
- transform: translateX(100px);
- opacity: 0.5;
-}
-
-/* ❌ CPU-bound (slow) */
-.animated {
- left: 100px;
- width: 300px;
-}
-```
-
-**Smooth 60fps**:
-- Target 16ms per frame (60fps)
-- Use `requestAnimationFrame` for JS animations
-- Debounce/throttle scroll handlers
-- Use CSS animations when possible
-- Avoid long-running JavaScript during animations
-
-**Intersection Observer**:
-```javascript
-// Efficiently detect when elements enter viewport
-const observer = new IntersectionObserver((entries) => {
- entries.forEach(entry => {
- if (entry.isIntersecting) {
- // Element is visible, lazy load or animate
- }
- });
-});
-```
-
-### React/Framework Optimization
-
-**React-specific**:
-- Use `memo()` for expensive components
-- `useMemo()` and `useCallback()` for expensive computations
-- Virtualize long lists
-- Code split routes
-- Avoid inline function creation in render
-- Use React DevTools Profiler
-
-**Framework-agnostic**:
-- Minimize re-renders
-- Debounce expensive operations
-- Memoize computed values
-- Lazy load routes and components
-
-### Network Optimization
-
-**Reduce Requests**:
-- Combine small files
-- Use SVG sprites for icons
-- Inline small critical assets
-- Remove unused third-party scripts
-
-**Optimize APIs**:
-- Use pagination (don't load everything)
-- GraphQL to request only needed fields
-- Response compression (gzip, brotli)
-- HTTP caching headers
-- CDN for static assets
-
-**Optimize for Slow Connections**:
-- Adaptive loading based on connection (navigator.connection)
-- Optimistic UI updates
-- Request prioritization
-- Progressive enhancement
-
-## Core Web Vitals Optimization
-
-### Largest Contentful Paint (LCP < 2.5s)
-- Optimize hero images
-- Inline critical CSS
-- Preload key resources
-- Use CDN
-- Server-side rendering
-
-### First Input Delay (FID < 100ms) / INP (< 200ms)
-- Break up long tasks
-- Defer non-critical JavaScript
-- Use web workers for heavy computation
-- Reduce JavaScript execution time
-
-### Cumulative Layout Shift (CLS < 0.1)
-- Set dimensions on images and videos
-- Don't inject content above existing content
-- Use `aspect-ratio` CSS property
-- Reserve space for ads/embeds
-- Avoid animations that cause layout shifts
-
-```css
-/* Reserve space for image */
-.image-container {
- aspect-ratio: 16 / 9;
-}
-```
-
-## Performance Monitoring
-
-**Tools to use**:
-- Chrome DevTools (Lighthouse, Performance panel)
-- WebPageTest
-- Core Web Vitals (Chrome UX Report)
-- Bundle analyzers (webpack-bundle-analyzer)
-- Performance monitoring (Sentry, DataDog, New Relic)
-
-**Key metrics**:
-- LCP, FID/INP, CLS (Core Web Vitals)
-- Time to Interactive (TTI)
-- First Contentful Paint (FCP)
-- Total Blocking Time (TBT)
-- Bundle size
-- Request count
-
-**IMPORTANT**: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.
-
-**NEVER**:
-- Optimize without measuring (premature optimization)
-- Sacrifice accessibility for performance
-- Break functionality while optimizing
-- Use `will-change` everywhere (creates new layers, uses memory)
-- Lazy load above-fold content
-- Optimize micro-optimizations while ignoring major issues (optimize the biggest bottleneck first)
-- Forget about mobile performance (often slower devices, slower connections)
-
-## Verify Improvements
-
-Test that optimizations worked:
-
-- **Before/after metrics**: Compare Lighthouse scores
-- **Real user monitoring**: Track improvements for real users
-- **Different devices**: Test on low-end Android, not just flagship iPhone
-- **Slow connections**: Throttle to 3G, test experience
-- **No regressions**: Ensure functionality still works
-- **User perception**: Does it *feel* faster?
-
-When the user-facing numbers move, hand off to `/impeccable polish` for the final pass.
@@ -1,130 +0,0 @@
-Start your response with:
-
-```
-──────────── ⚡ OVERDRIVE ─────────────
-》》》 Entering overdrive mode...
-```
-
-Push an interface past conventional limits. This isn't just about visual effects. It's about using the full power of the browser to make any part of an interface feel extraordinary: a table that handles a million rows, a dialog that morphs from its trigger, a form that validates in real-time with streaming feedback, a page transition that feels cinematic.
-
-**EXTRA IMPORTANT FOR THIS COMMAND**: Context determines what "extraordinary" means. A particle system on a creative portfolio is impressive. The same particle system on a settings page is embarrassing. But a settings page with instant optimistic saves and animated state transitions? That's extraordinary too. Understand the project's personality and goals before deciding what's appropriate.
-
-### Propose Before Building
-
-This command has the highest potential to misfire. Do NOT jump straight into implementation. You MUST:
-
-1. **Think through 2-3 different directions**: consider different techniques, levels of ambition, and aesthetic approaches. For each direction, briefly describe what the result would look and feel like.
-2. **ask the user directly to clarify what you cannot infer.** to present these directions and get the user's pick before writing any code. Explain trade-offs (browser support, performance cost, complexity).
-3. Only proceed with the direction the user confirms.
-
-Skipping this step risks building something embarrassing that needs to be thrown away.
-
-### Iterate with Browser Automation
-
-Technically ambitious effects almost never work on the first try. You MUST actively use browser automation tools to preview your work, visually verify the result, and iterate. Do not assume the effect looks right, check it. Expect multiple rounds of refinement. The gap between "technically works" and "looks extraordinary" is closed through visual iteration, not code alone.
-
----
-
-## Assess What "Extraordinary" Means Here
-
-The right kind of technical ambition depends entirely on what you're working with. Before choosing a technique, ask: **what would make a user of THIS specific interface say "wow, that's nice"?**
-
-### For visual/marketing surfaces
-Pages, hero sections, landing pages, portfolios: the "wow" is often sensory: a scroll-driven reveal, a shader background, a cinematic page transition, generative art that responds to the cursor.
-
-### For functional UI
-Tables, forms, dialogs, navigation: the "wow" is in how it FEELS: a dialog that morphs from the button that triggered it via View Transitions, a data table that renders 100k rows at 60fps via virtual scrolling, a form with streaming validation that feels instant, drag-and-drop with spring physics.
-
-### For performance-critical UI
-The "wow" is invisible but felt: a search that filters 50k items without a flicker, a complex form that never blocks the main thread, an image editor that processes in near-real-time. The interface just never hesitates.
-
-### For data-heavy interfaces
-Charts and dashboards: the "wow" is in fluidity: GPU-accelerated rendering via Canvas/WebGL for massive datasets, animated transitions between data states, force-directed graph layouts that settle naturally.
-
-**The common thread**: something about the implementation goes beyond what users expect from a web interface. The technique serves the experience, not the other way around.
-
-## The Toolkit
-
-Organized by what you're trying to achieve, not by technology name.
-
-### Make transitions feel cinematic
-- **View Transitions API** (same-document: all browsers; cross-document: no Firefox): shared element morphing between states. A list item expanding into a detail page. A button morphing into a dialog. This is the closest thing to native FLIP animations.
-- **`@starting-style`** (all browsers): animate elements from `display: none` to visible with CSS only, including entry keyframes
-- **Spring physics**: natural motion with mass, tension, and damping instead of cubic-bezier. Libraries: motion (formerly Framer Motion), GSAP, or roll your own spring solver.
-
-### Tie animation to scroll position
-- **Scroll-driven animations** (`animation-timeline: scroll()`): CSS-only, no JS. Parallax, progress bars, reveal sequences all driven by scroll position. (Chrome/Edge/Safari; Firefox: flag only; always provide a static fallback)
-
-### Render beyond CSS
-- **WebGL** (all browsers): shader effects, post-processing, particle systems. Libraries: Three.js, OGL (lightweight), regl. Use for effects CSS can't express.
-- **WebGPU** (Chrome/Edge; Safari partial; Firefox: flag only): next-gen GPU compute. More powerful than WebGL but limited browser support. Always fall back to WebGL2.
-- **Canvas 2D / OffscreenCanvas**: custom rendering, pixel manipulation, or moving heavy rendering off the main thread entirely via Web Workers + OffscreenCanvas.
-- **SVG filter chains**: displacement maps, turbulence, morphology for organic distortion effects. CSS-animatable.
-
-### Make data feel alive
-- **Virtual scrolling**: render only visible rows for tables/lists with tens of thousands of items. No library required for simple cases; TanStack Virtual for complex ones.
-- **GPU-accelerated charts**: Canvas or WebGL-rendered data visualization for datasets too large for SVG/DOM. Libraries: deck.gl, regl-based custom renderers.
-- **Animated data transitions**: morph between chart states rather than replacing. D3's `transition()` or View Transitions for DOM-based charts.
-
-### Animate complex properties
-- **`@property`** (all browsers): register custom CSS properties with types, enabling animation of gradients, colors, and complex values that CSS can't normally interpolate.
-- **Web Animations API** (all browsers): JavaScript-driven animations with the performance of CSS. Composable, cancellable, reversible. The foundation for complex choreography.
-
-### Push performance boundaries
-- **Web Workers**: move computation off the main thread. Heavy data processing, image manipulation, search indexing: anything that would cause jank.
-- **OffscreenCanvas**: render in a Worker thread. The main thread stays free while complex visuals render in the background.
-- **WASM**: near-native performance for computation-heavy features. Image processing, physics simulations, codecs.
-
-### Interact with the device
-- **Web Audio API**: spatial audio, audio-reactive visualizations, sonic feedback. Requires user gesture to start.
-- **Device APIs**: orientation, ambient light, geolocation. Use sparingly and always with user permission.
-
-**NOTE**: This command is about enhancing how an interface FEELS, not changing what a product DOES. Adding real-time collaboration, offline support, or new backend capabilities are product decisions, not UI enhancements. Focus on making existing features feel extraordinary.
-
-## Implement with Discipline
-
-### Progressive enhancement is non-negotiable
-
-Every technique must degrade gracefully. The experience without the enhancement must still be good.
-
-```css
-@supports (animation-timeline: scroll()) {
- .hero { animation-timeline: scroll(); }
-}
-```
-
-```javascript
-if ('gpu' in navigator) { /* WebGPU */ }
-else if (canvas.getContext('webgl2')) { /* WebGL2 fallback */ }
-/* CSS-only fallback must still look good */
-```
-
-### Performance rules
-
-- Target 60fps. If dropping below 50, simplify.
-- Respect `prefers-reduced-motion`, always. Provide a beautiful static alternative.
-- Lazy-initialize heavy resources (WebGL contexts, WASM modules) only when near viewport.
-- Pause off-screen rendering. Kill what you can't see.
-- Test on real mid-range devices, not just your development machine.
-
-### Polish is the difference
-
-The gap between "cool" and "extraordinary" is in the last 20% of refinement: the easing curve on a spring animation, the timing offset in a staggered reveal, the subtle secondary motion that makes a transition feel physical. Don't ship the first version that works; ship the version that feels inevitable.
-
-**NEVER**:
-- Ignore `prefers-reduced-motion`. This is an accessibility requirement, not a suggestion
-- Ship effects that cause jank on mid-range devices
-- Use bleeding-edge APIs without a functional fallback
-- Add sound without explicit user opt-in
-- Use technical ambition to mask weak design fundamentals; fix those first with other commands
-- Layer multiple competing extraordinary moments. Focus creates impact, excess creates noise
-
-## Verify the Result
-
-- **The wow test**: Show it to someone who hasn't seen it. Do they react?
-- **The removal test**: Take it away. Does the experience feel diminished, or does nobody notice?
-- **The device test**: Run it on a phone, a tablet, a Chromebook. Still smooth?
-- **The accessibility test**: Enable reduced motion. Still beautiful?
-- **The context test**: Does this make sense for THIS brand and audience?
-
-"Technically extraordinary" isn't about using the newest API. It's about making an interface do something users didn't think a website could do.
@@ -1,179 +0,0 @@
-# Persona-Based Design Testing
-
-Test the interface through the eyes of 5 distinct user archetypes. Each persona exposes different failure modes that a single "design director" perspective would miss.
-
-**How to use**: Select 2–3 personas most relevant to the interface being critiqued. Walk through the primary user action as each persona. Report specific red flags, not generic concerns.
-
----
-
-## 1. Impatient Power User: "Alex"
-
-
-**Profile**: Expert with similar products. Expects efficiency, hates hand-holding. Will find shortcuts or leave.
-
-**Behaviors**:
-- Skips all onboarding and instructions
-- Looks for keyboard shortcuts immediately
-- Tries to bulk-select, batch-edit, and automate
-- Gets frustrated by required steps that feel unnecessary
-- Abandons if anything feels slow or patronizing
-
-**Test Questions**:
-- Can Alex complete the core task in under 60 seconds?
-- Are there keyboard shortcuts for common actions?
-- Can onboarding be skipped entirely?
-- Do modals have keyboard dismiss (Esc)?
-- Is there a "power user" path (shortcuts, bulk actions)?
-
-**Red Flags** (report these specifically):
-- Forced tutorials or unskippable onboarding
-- No keyboard navigation for primary actions
-- Slow animations that can't be skipped
-- One-item-at-a-time workflows where batch would be natural
-- Redundant confirmation steps for low-risk actions
-
----
-
-## 2. Confused First-Timer: "Jordan"
-
-**Profile**: Never used this type of product. Needs guidance at every step. Will abandon rather than figure it out.
-
-**Behaviors**:
-- Reads all instructions carefully
-- Hesitates before clicking anything unfamiliar
-- Looks for help or support constantly
-- Misunderstands jargon and abbreviations
-- Takes the most literal interpretation of any label
-
-**Test Questions**:
-- Is the first action obviously clear within 5 seconds?
-- Are all icons labeled with text?
-- Is there contextual help at decision points?
-- Does terminology assume prior knowledge?
-- Is there a clear "back" or "undo" at every step?
-
-**Red Flags** (report these specifically):
-- Icon-only navigation with no labels
-- Technical jargon without explanation
-- No visible help option or guidance
-- Ambiguous next steps after completing an action
-- No confirmation that an action succeeded
-
----
-
-## 3. Accessibility-Dependent User: "Sam"
-
-**Profile**: Uses screen reader (VoiceOver/NVDA), keyboard-only navigation. May have low vision, motor impairment, or cognitive differences.
-
-**Behaviors**:
-- Tabs through the interface linearly
-- Relies on ARIA labels and heading structure
-- Cannot see hover states or visual-only indicators
-- Needs adequate color contrast (4.5:1 minimum)
-- May use browser zoom up to 200%
-
-**Test Questions**:
-- Can the entire primary flow be completed keyboard-only?
-- Are all interactive elements focusable with visible focus indicators?
-- Do images have meaningful alt text?
-- Is color contrast WCAG AA compliant (4.5:1 for text)?
-- Does the screen reader announce state changes (loading, success, errors)?
-
-**Red Flags** (report these specifically):
-- Click-only interactions with no keyboard alternative
-- Missing or invisible focus indicators
-- Meaning conveyed by color alone (red = error, green = success)
-- Unlabeled form fields or buttons
-- Time-limited actions without extension option
-- Custom components that break screen reader flow
-
----
-
-## 4. Deliberate Stress Tester: "Riley"
-
-**Profile**: Methodical user who pushes interfaces beyond the happy path. Tests edge cases, tries unexpected inputs, and probes for gaps in the experience.
-
-**Behaviors**:
-- Tests edge cases intentionally (empty states, long strings, special characters)
-- Submits forms with unexpected data (emoji, RTL text, very long values)
-- Tries to break workflows by navigating backwards, refreshing mid-flow, or opening in multiple tabs
-- Looks for inconsistencies between what the UI promises and what actually happens
-- Documents problems methodically
-
-**Test Questions**:
-- What happens at the edges (0 items, 1000 items, very long text)?
-- Do error states recover gracefully or leave the UI in a broken state?
-- What happens on refresh mid-workflow? Is state preserved?
-- Are there features that appear to work but produce broken results?
-- How does the UI handle unexpected input (emoji, special chars, paste from Excel)?
-
-**Red Flags** (report these specifically):
-- Features that appear to work but silently fail or produce wrong results
-- Error handling that exposes technical details or leaves UI in a broken state
-- Empty states that show nothing useful ("No results" with no guidance)
-- Workflows that lose user data on refresh or navigation
-- Inconsistent behavior between similar interactions in different parts of the UI
-
----
-
-## 5. Distracted Mobile User: "Casey"
-
-**Profile**: Using phone one-handed on the go. Frequently interrupted. Possibly on a slow connection.
-
-**Behaviors**:
-- Uses thumb only; prefers bottom-of-screen actions
-- Gets interrupted mid-flow and returns later
-- Switches between apps frequently
-- Has limited attention span and low patience
-- Types as little as possible, prefers taps and selections
-
-**Test Questions**:
-- Are primary actions in the thumb zone (bottom half of screen)?
-- Is state preserved if the user leaves and returns?
-- Does it work on slow connections (3G)?
-- Can forms use autocomplete and smart defaults?
-- Are touch targets at least 44×44pt?
-
-**Red Flags** (report these specifically):
-- Important actions positioned at the top of the screen (unreachable by thumb)
-- No state persistence; progress lost on tab switch or interruption
-- Large text inputs required where selection would work
-- Heavy assets loading on every page (no lazy loading)
-- Tiny tap targets or targets too close together
-
----
-
-## Selecting Personas
-
-Choose personas based on the interface type:
-
-| Interface Type | Primary Personas | Why |
-|---------------|-----------------|-----|
-| Landing page / marketing | Jordan, Riley, Casey | First impressions, trust, mobile |
-| Dashboard / admin | Alex, Sam | Power users, accessibility |
-| E-commerce / checkout | Casey, Riley, Jordan | Mobile, edge cases, clarity |
-| Onboarding flow | Jordan, Casey | Confusion, interruption |
-| Data-heavy / analytics | Alex, Sam | Efficiency, keyboard nav |
-| Form-heavy / wizard | Jordan, Sam, Casey | Clarity, accessibility, mobile |
-
----
-
-## Project-Specific Personas
-
-If `RULES.md` contains a `## Design Context` section (generated by `impeccable teach`), derive 1–2 additional personas from the audience and brand information:
-
-1. Read the target audience description
-2. Identify the primary user archetype not covered by the 5 predefined personas
-3. Create a persona following this template:
-
-```
-### [Role]: "[Name]"
-
-**Profile**: [2-3 key characteristics derived from Design Context]
-
-**Behaviors**: [3-4 specific behaviors based on the described audience]
-
-**Red Flags**: [3-4 things that would alienate this specific user type]
-```
-
-Only generate project-specific personas when real Design Context data is available. Don't invent audience details; use the 5 predefined personas when no context exists.
@@ -1,242 +0,0 @@
-> **Additional context needed**: quality bar (MVP vs flagship).
-
-Perform a meticulous final pass to catch all the small details that separate good work from great work. The difference between shipped and polished.
-
-Detector and automated QA output are defect evidence only. A clean script result is never proof that the design is strong; gather browser evidence and inspect the real interaction path.
-
-## Design System Discovery
-
-Aligning the feature to the design system is **not optional**. Polish without alignment is decoration on top of drift, and it makes the next person's job harder. Discovery comes before any other polish work.
-
-1. **Find the design system**: Search for design system documentation, component libraries, style guides, or token definitions. Study the core patterns: design principles, target audience, color tokens, spacing scale, typography styles, component API, motion conventions.
-2. **Note the conventions**: How are shared components imported? What spacing scale is used? Which colors come from tokens vs hard-coded values? What motion and interaction patterns are established? What flow shapes are used for comparable actions (modal vs full-page, inline vs route, save-on-blur vs explicit submit)?
-3. **Identify drift, then name the root cause**: For every deviation, classify it as a **missing token** (the value should exist in the system but doesn't), a **one-off implementation** (a shared component already exists but wasn't used), or a **conceptual misalignment** (the feature's flow, IA, or hierarchy doesn't match neighboring features). The fix differs by category: patch the value, swap to the shared component, or rework the flow. Fixing the symptom without naming the cause is how drift compounds.
-
-If a design system exists, polish **must** align the feature with it. If none exists, polish against the conventions visible in the codebase. **If anything about the system is ambiguous, ask. Never guess at design system principles.**
-
-## Pre-Polish Assessment
-
-Understand the current state and goals before touching anything:
-
-1. **Review completeness**:
- - Is it functionally complete?
- - Are there known issues to preserve (mark with TODOs)?
- - What's the quality bar? (MVP vs flagship feature?)
- - When does it ship? (How much time for polish?)
-
-2. **Think experience-first**: Who actually uses this, and what's the best possible experience for them? Effective design beats decorative polish; a feature that looks beautiful but fights the user's flow is not polished. Walk the path from their perspective before opening DevTools.
-
-3. **Identify polish areas**:
- - Visual inconsistencies
- - Spacing and alignment issues
- - Interaction state gaps
- - Copy inconsistencies
- - Edge cases and error states
- - Loading and transition smoothness
- - Information architecture and flow drift (does this feature reveal complexity the way neighboring features do?)
-
-4. **Pull in any prior critique** (optional signal): If `/impeccable critique` has been run on the same target, its priority issues are a useful prior for what to address first. Resolve the target to a file path or URL, then:
- ```bash
- slug=$(node .trae/skills/impeccable/scripts/critique-storage.mjs slug "<resolved>")
- node .trae/skills/impeccable/scripts/critique-storage.mjs latest "$slug"
- ```
- Exit 0 with body = found; fold the P0/P1 items into your polish list and mention the snapshot path so the user sees what you read. Exit 2 = no snapshot, continue without it. The critique is one input among many. Do your own pass either way.
-
-5. **Triage cosmetic vs functional**: Classify each issue as **cosmetic** (looks off, doesn't impede the user) or **functional** (breaks, blocks, or confuses the experience). When polish time is tight, functional issues ship first; cosmetic ones can land in a follow-up. Quality should be consistent; never perfect one corner while leaving another rough.
-
-**CRITICAL**: Polish is the last step, not the first. Don't polish work that's not functionally complete.
-
-## Polish Systematically
-
-Work through these dimensions methodically:
-
-### Visual Alignment & Spacing
-
-- **Pixel-perfect alignment**: Everything lines up to grid
-- **Consistent spacing**: All gaps use spacing scale (no random 13px gaps)
-- **Optical alignment**: Adjust for visual weight (icons may need offset for optical centering)
-- **Responsive consistency**: Spacing and alignment work at all breakpoints
-- **Grid adherence**: Elements snap to baseline grid
-
-**Check**:
-- Enable grid overlay and verify alignment
-- Check spacing with browser inspector
-- Test at multiple viewport sizes
-- Look for elements that "feel" off
-
-### Information Architecture & Flow
-
-Visual polish on a misshapen flow is wasted work. Match the *shape* of the experience to the system, not just the surface.
-
-- **Progressive disclosure**: Match how much is revealed when, compared to neighboring features. A settings page exposing 40 fields when the rest of the app reveals 5 at a time is drift, even if every field is perfectly styled.
-- **Established user flows**: Multi-step actions follow the same shape as comparable flows elsewhere: modal vs full-page, inline edit vs separate route, save-on-blur vs explicit submit, optimistic vs pessimistic updates.
-- **Hierarchy & complexity**: The same conceptual weight gets the same visual weight throughout. Primary actions don't become tertiary in one corner of the product, and tertiary actions don't shout.
-- **Empty, loading, and arrival transitions**: How content arrives, updates, and leaves matches how it does in adjacent features.
-- **Naming and mental model**: The feature uses the same nouns and verbs as the rest of the system. A "Workspace" here shouldn't be a "Project" three screens away.
-
-### Typography Refinement
-
-- **Hierarchy consistency**: Same elements use same sizes/weights throughout
-- **Line length**: 45-75 characters for body text
-- **Line height**: Appropriate for font size and context
-- **Widows & orphans**: No single words on last line
-- **Hyphenation**: Appropriate for language and column width
-- **Kerning**: Adjust letter spacing where needed (especially headlines)
-- **Font loading**: No FOUT/FOIT flashes
-
-### Color & Contrast
-
-- **Contrast ratios**: All text meets WCAG standards
-- **Consistent token usage**: No hard-coded colors, all use design tokens
-- **Theme consistency**: Works in all theme variants
-- **Color meaning**: Same colors mean same things throughout
-- **Accessible focus**: Focus indicators visible with sufficient contrast
-- **Tinted neutrals**: No pure gray or pure black; add subtle color tint (0.01 chroma)
-- **Gray on color**: Never put gray text on colored backgrounds; use a shade of that color or transparency
-
-### Interaction States
-
-Every interactive element needs all states:
-
-- **Default**: Resting state
-- **Hover**: Subtle feedback (color, scale, shadow)
-- **Focus**: Keyboard focus indicator (never remove without replacement)
-- **Active**: Click/tap feedback
-- **Disabled**: Clearly non-interactive
-- **Loading**: Async action feedback
-- **Error**: Validation or error state
-- **Success**: Successful completion
-
-**Missing states create confusion and broken experiences**.
-
-### Micro-interactions & Transitions
-
-- **Smooth transitions**: All state changes animated appropriately (150-300ms)
-- **Consistent easing**: Use ease-out-quart/quint/expo for natural deceleration. Never bounce or elastic; they feel dated.
-- **No jank**: Smooth animations; use atmospheric blur/filter/mask/shadow effects when they add polish, but bound expensive paint areas and avoid casual layout-property animation
-- **Appropriate motion**: Motion serves purpose, not decoration
-- **Reduced motion**: Respects `prefers-reduced-motion`
-
-### Content & Copy
-
-- **Consistent terminology**: Same things called same names throughout
-- **Consistent capitalization**: Title Case vs Sentence case applied consistently
-- **Grammar & spelling**: No typos
-- **Appropriate length**: Not too wordy, not too terse
-- **Punctuation consistency**: Periods on sentences, not on labels (unless all labels have them)
-
-### Icons & Images
-
-- **Consistent style**: All icons from same family or matching style
-- **Appropriate sizing**: Icons sized consistently for context
-- **Proper alignment**: Icons align with adjacent text optically
-- **Alt text**: All images have descriptive alt text
-- **Loading states**: Images don't cause layout shift, proper aspect ratios
-- **Retina support**: 2x assets for high-DPI screens
-
-### Forms & Inputs
-
-- **Label consistency**: All inputs properly labeled
-- **Required indicators**: Clear and consistent
-- **Error messages**: Helpful and consistent
-- **Tab order**: Logical keyboard navigation
-- **Auto-focus**: Appropriate (don't overuse)
-- **Validation timing**: Consistent (on blur vs on submit)
-
-### Edge Cases & Error States
-
-- **Loading states**: All async actions have loading feedback
-- **Empty states**: Helpful empty states, not just blank space
-- **Error states**: Clear error messages with recovery paths
-- **Success states**: Confirmation of successful actions
-- **Long content**: Handles very long names, descriptions, etc.
-- **No content**: Handles missing data gracefully
-- **Offline**: Appropriate offline handling (if applicable)
-
-### Responsiveness
-
-- **All breakpoints**: Test mobile, tablet, desktop
-- **Touch targets**: 44x44px minimum on touch devices
-- **Readable text**: No text smaller than 14px on mobile
-- **No horizontal scroll**: Content fits viewport
-- **Appropriate reflow**: Content adapts logically
-
-### Performance
-
-- **Fast initial load**: Optimize critical path
-- **No layout shift**: Elements don't jump after load (CLS)
-- **Smooth interactions**: No lag or jank
-- **Optimized images**: Appropriate formats and sizes
-- **Lazy loading**: Off-screen content loads lazily
-
-### Code Quality
-
-- **Remove console logs**: No debug logging in production
-- **Remove commented code**: Clean up dead code
-- **Remove unused imports**: Clean up unused dependencies
-- **Consistent naming**: Variables and functions follow conventions
-- **Type safety**: No TypeScript `any` or ignored errors
-- **Accessibility**: Proper ARIA labels and semantic HTML
-
-## Polish Checklist
-
-Go through systematically:
-
-- [ ] Aligned to the design system (drift named and resolved by root cause)
-- [ ] Information architecture and flow shape match neighboring features
-- [ ] Visual alignment perfect at all breakpoints
-- [ ] Spacing uses design tokens consistently
-- [ ] Typography hierarchy consistent
-- [ ] All interactive states implemented
-- [ ] All transitions smooth (60fps)
-- [ ] Copy is consistent and polished
-- [ ] Icons are consistent and properly sized
-- [ ] All forms properly labeled and validated
-- [ ] Error states are helpful
-- [ ] Loading states are clear
-- [ ] Empty states are welcoming
-- [ ] Touch targets are 44x44px minimum
-- [ ] Contrast ratios meet WCAG AA
-- [ ] Keyboard navigation works
-- [ ] Focus indicators visible
-- [ ] No console errors or warnings
-- [ ] No layout shift on load
-- [ ] Works in all supported browsers
-- [ ] Respects reduced motion preference
-- [ ] Code is clean (no TODOs, console.logs, commented code)
-
-**IMPORTANT**: Polish is about details. Zoom in. Squint at it. Use it yourself. The little things add up.
-
-Sweat the details. Zoom in until the alignment is right and the spacing reads as deliberate. Then ship.
-
-**NEVER**:
-- Polish before it's functionally complete
-- Polish without aligning to the design system; that's decoration on drift
-- Guess at design system principles instead of asking when something is ambiguous
-- Spend hours on polish if it ships in 30 minutes (triage)
-- Introduce bugs while polishing (test thoroughly)
-- Ignore systematic issues (if spacing is off everywhere, fix the system, not just one screen)
-- Perfect one thing while leaving others rough (consistent quality level)
-- Create new one-off components when design system equivalents exist
-- Hard-code values that should use design tokens
-- Introduce new patterns or flows that diverge from established ones
-
-## Final Verification
-
-Before marking as done:
-
-- **Use it yourself**: Actually interact with the feature.
-- **Test on real devices**: Not just browser DevTools.
-- **Ask someone else to review**: Fresh eyes catch things.
-- **Compare to design**: Match intended design.
-- **Check all states**: Don't just test happy path.
-- **Treat automation carefully**: Run detector or QA commands when they are available and relevant, fix their defects, but never cite a clean result as proof that the work is polished.
-
-## Clean Up
-
-After polishing, ensure code quality:
-
-- **Replace custom implementations**: If the design system provides a component you reimplemented, switch to the shared version.
-- **Remove orphaned code**: Delete unused styles, components, or files made obsolete by polish.
-- **Consolidate tokens**: If you introduced new values, check whether they should be tokens.
-- **Verify DRYness**: Look for duplication introduced during polishing and consolidate.
@@ -1,62 +0,0 @@
-# Product register
-
-When design SERVES the product: app UIs, admin dashboards, settings panels, data tables, tools, authenticated surfaces, anything where the user is in a task.
-
-## The product slop test
-
-Not "would someone say AI made this." Familiarity is often a feature here. The test is: would a user fluent in the category's best tools (Linear, Figma, Notion, Raycast, Stripe come to mind) sit down and trust this interface, or pause at every subtly-off component?
-
-Product UI's failure mode isn't flatness, it's strangeness without purpose: over-decorated buttons, mismatched form controls, gratuitous motion, display fonts where labels should be, invented affordances for standard tasks. The bar is earned familiarity. The tool should disappear into the task.
-
-## Typography
-
-- **System fonts are legitimate.** `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` gives you native feel on every platform. Inter is the common cross-platform default for a reason.
-- **One family is often right.** Product UIs don't need display/body pairing. A well-tuned sans carries headings, buttons, labels, body, data.
-- **Fixed rem scale, not fluid.** Clamp-sized headings don't serve product UI. Users view at consistent DPI, and a fluid h1 that shrinks in a sidebar looks worse, not better.
-- **Tighter scale ratio.** 1.125–1.2 between steps is typical. More type elements here than on brand surfaces; exaggerated contrast creates noise.
-- **Line length still applies for prose** (65–75ch). Data and compact UI can run denser; tables at 120ch+ are fine.
-
-## Color
-
-Product defaults to Restrained. A single surface can earn Committed (a dashboard where one category color carries a report, an onboarding flow with a drenched welcome screen), but Restrained is the floor.
-
-- State-rich semantic vocabulary: hover, focus, active, disabled, selected, loading, error, warning, success, info. Standardize these.
-- Accent color used for primary actions, current selection, and state indicators only, not decoration.
-- A second neutral layer for sidebars, toolbars, and panels (slightly cooler or warmer than the content surface).
-
-## Layout
-
-- Predictable grids. Consistency IS an affordance; users navigate faster when the structure is expected.
-- Familiar patterns are features. Standard navigation (top bar, side nav), breadcrumbs, tabs, and form layouts have established user expectations. Don't reinvent for flavor.
-- Responsive behavior is structural (collapse sidebar, responsive table, breakpoint-driven columns), not fluid typography.
-
-## Components
-
-Every interactive component has: default, hover, focus, active, disabled, loading, error. Don't ship with half of these.
-
-- Skeleton states for loading, not spinners in the middle of content.
-- Empty states that teach the interface, not "nothing here."
-- Consistent affordances across the surface. Same button shape. Same form-control vocabulary. Same icon style.
-
-## Motion
-
-- 150–250 ms on most transitions. Users are in flow; don't make them wait for choreography.
-- Motion conveys state, not decoration. State change, feedback, loading, reveal: nothing else.
-- No orchestrated page-load sequences. Product loads into a task; users don't want to watch it load.
-
-## Product bans (on top of the shared absolute bans)
-
-- Decorative motion that doesn't convey state.
-- Inconsistent component vocabulary across screens. If the "save" button looks different in two places, one is wrong.
-- Display fonts in UI labels, buttons, data.
-- Reinventing standard affordances for flavor (custom scrollbars, weird form controls, non-standard modals).
-- Heavy color or full-saturation accents on inactive states.
-
-## Product permissions
-
-Product can afford things brand surfaces can't.
-
-- System fonts and familiar sans defaults (Inter, SF Pro, system-ui stacks).
-- Standard navigation patterns: top bar + side nav, breadcrumbs, tabs, command palettes.
-- Density. Tables with many rows, panels with many labels, dense information when users need it.
-- Consistency over surprise. The same visual vocabulary screen to screen is a virtue; delight is saved for moments, not pages.
@@ -1,99 +0,0 @@
-Quiet design is harder than bold design. Subtlety needs precision. Reduce visual intensity in designs that are too loud, aggressive, or overstimulating without losing personality or making the result generic.
-
----
-
-## Register
-
-Brand: "quieter" means more restrained palette, more whitespace, more typographic air. Drama is reduced, not eliminated; the POV stays intact.
-
-Product: "quieter" means reducing visual noise. Fewer background accents, flatter cards, less color, less motion. The tool should disappear more completely into the task.
-
----
-
-## Assess Current State
-
-Analyze what makes the design feel too intense:
-
-1. **Identify intensity sources**:
- - **Color saturation**: Overly bright or saturated colors
- - **Contrast extremes**: Too much high-contrast juxtaposition
- - **Visual weight**: Too many bold, heavy elements competing
- - **Animation excess**: Too much motion or overly dramatic effects
- - **Complexity**: Too many visual elements, patterns, or decorations
- - **Scale**: Everything is large and loud with no hierarchy
-
-2. **Understand the context**:
- - What's the purpose? (Marketing vs tool vs reading experience)
- - Who's the audience? (Some contexts need energy)
- - What's working? (Don't throw away good ideas)
- - What's the core message? (Preserve what matters)
-
-If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
-
-**CRITICAL**: "Quieter" doesn't mean boring or generic. It means refined and easier on the eyes. Think luxury, not laziness.
-
-## Plan Refinement
-
-Create a strategy to reduce intensity while maintaining impact:
-
-- **Color approach**: Desaturate or shift to more restrained tones?
-- **Hierarchy approach**: Which elements should stay bold (very few), which should recede?
-- **Simplification approach**: What can be removed entirely?
-- **Sophistication approach**: How can we signal quality through restraint?
-
-**IMPORTANT**: Subtlety requires precision. Quiet without intent collapses to generic.
-
-## Refine the Design
-
-Systematically reduce intensity across these dimensions:
-
-### Color Refinement
-- **Reduce saturation**: Shift from fully saturated to 70-85% saturation
-- **Soften palette**: Replace bright colors with muted tones
-- **Reduce color variety**: Use fewer colors more thoughtfully
-- **Neutral dominance**: Let neutrals do more work, use color as accent (10% rule)
-- **Gentler contrasts**: High contrast only where it matters most
-- **Tinted grays**: Use warm or cool tinted grays instead of pure gray. Adds depth without loudness
-- **Never gray on color**: If you have gray text on a colored background, use a darker shade of that color or transparency instead
-
-### Visual Weight Reduction
-- **Typography**: Reduce font weights (900 → 600, 700 → 500), decrease sizes where appropriate
-- **Hierarchy through subtlety**: Use weight, size, and space instead of color and boldness
-- **White space**: Increase breathing room, reduce density
-- **Borders & lines**: Reduce thickness, decrease opacity, or remove entirely
-
-### Simplification
-- **Remove decorative elements**: Gradients, shadows, patterns, textures that don't serve purpose
-- **Simplify shapes**: Reduce border radius extremes, simplify custom shapes
-- **Reduce layering**: Flatten visual hierarchy where possible
-- **Clean up effects**: Reduce or remove blur effects, glows, multiple shadows
-
-### Motion Reduction
-- **Reduce animation intensity**: Shorter distances (10-20px instead of 40px), gentler easing
-- **Remove decorative animations**: Keep functional motion, remove flourishes
-- **Subtle micro-interactions**: Replace dramatic effects with gentle feedback
-- **Refined easing**: Use ease-out-quart for smooth, understated motion. Never bounce or elastic
-- **Remove animations entirely** if they're not serving a clear purpose
-
-### Composition Refinement
-- **Reduce scale jumps**: Smaller contrast between sizes creates calmer feeling
-- **Align to grid**: Bring rogue elements back into systematic alignment
-- **Even out spacing**: Replace extreme spacing variations with consistent rhythm
-
-**NEVER**:
-- Make everything the same size/weight (hierarchy still matters)
-- Remove all color (quiet ≠ grayscale)
-- Eliminate all personality (maintain character through refinement)
-- Sacrifice usability for aesthetics (functional elements still need clear affordances)
-- Make everything small and light (some anchors needed)
-
-## Verify Quality
-
-Ensure refinement maintains quality:
-
-- **Still functional**: Can users still accomplish tasks easily?
-- **Still distinctive**: Does it have character, or is it generic now?
-- **Better reading**: Is text easier to read for extended periods?
-- **Restrained, not absent**: Does the POV survive the cuts?
-
-When the result feels right, hand off to `/impeccable polish` for the final pass.
@@ -1,114 +0,0 @@
-# Responsive Design
-
-## Mobile-First: Write It Right
-
-Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
-
-## Breakpoints: Content-Driven
-
-Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
-
-## Detect Input Method, Not Just Screen Size
-
-**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
-
-```css
-/* Fine pointer (mouse, trackpad) */
-@media (pointer: fine) {
- .button { padding: 8px 16px; }
-}
-
-/* Coarse pointer (touch, stylus) */
-@media (pointer: coarse) {
- .button { padding: 12px 20px; } /* Larger touch target */
-}
-
-/* Device supports hover */
-@media (hover: hover) {
- .card:hover { transform: translateY(-2px); }
-}
-
-/* Device doesn't support hover (touch) */
-@media (hover: none) {
- .card { /* No hover state - use active instead */ }
-}
-```
-
-**Critical**: Don't rely on hover for functionality. Touch users can't hover.
-
-## Safe Areas: Handle the Notch
-
-Modern phones have notches, rounded corners, and home indicators. Use `env()`:
-
-```css
-body {
- padding-top: env(safe-area-inset-top);
- padding-bottom: env(safe-area-inset-bottom);
- padding-left: env(safe-area-inset-left);
- padding-right: env(safe-area-inset-right);
-}
-
-/* With fallback */
-.footer {
- padding-bottom: max(1rem, env(safe-area-inset-bottom));
-}
-```
-
-**Enable viewport-fit** in your meta tag:
-```html
-<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
-```
-
-## Responsive Images: Get It Right
-
-### srcset with Width Descriptors
-
-```html
-<img
- src="hero-800.jpg"
- srcset="
- hero-400.jpg 400w,
- hero-800.jpg 800w,
- hero-1200.jpg 1200w
- "
- sizes="(max-width: 768px) 100vw, 50vw"
- alt="Hero image"
->
-```
-
-**How it works**:
-- `srcset` lists available images with their actual widths (`w` descriptors)
-- `sizes` tells the browser how wide the image will display
-- Browser picks the best file based on viewport width AND device pixel ratio
-
-### Picture Element for Art Direction
-
-When you need different crops/compositions (not just resolutions):
-
-```html
-<picture>
- <source media="(min-width: 768px)" srcset="wide.jpg">
- <source media="(max-width: 767px)" srcset="tall.jpg">
- <img src="fallback.jpg" alt="...">
-</picture>
-```
-
-## Layout Adaptation Patterns
-
-**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `<details>/<summary>` for content that can collapse on mobile.
-
-## Testing: Don't Trust DevTools Alone
-
-DevTools device emulation is useful for layout but misses:
-
-- Actual touch interactions
-- Real CPU/memory constraints
-- Network latency patterns
-- Font rendering differences
-- Browser chrome/keyboard appearances
-
-**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
-
----
-
-**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
@@ -1,165 +0,0 @@
-Shape the UX and UI for a feature before any code is written. This command produces a **design brief**: a structured artifact that guides implementation through discovery, not guesswork.
-
-**Scope**: Design planning only. This command does NOT write code. It produces the thinking that makes code good.
-
-**Output**: A design brief that can be handed off to /impeccable craft, or directly to /impeccable for freeform implementation. When visual direction probes are used, the images are supporting artifacts, not the primary output.
-
-## Philosophy
-
-Most AI-generated UIs fail not because of bad code, but because of skipped thinking. They jump to "here's a card grid" without asking "what is the user trying to accomplish?" This command inverts that: understand deeply first, so implementation is precise.
-
-## Phase 1: Discovery Interview
-
-**Do NOT write any code or make any design decisions during this phase.** Your only job is to understand the feature deeply enough to make excellent design decisions later.
-
-This is a required interaction, not optional guidance. Ask these questions in conversation, adapting based on answers. Don't dump them all at once; have a natural dialogue. ask the user directly to clarify what you cannot infer.
-
-### Interview cadence
-
-Discovery includes at least one user-answer round unless PRODUCT.md, DESIGN.md, or an already-confirmed brief directly answers the needed inputs. With a sparse prompt, do **not** synthesize a complete brief for confirmation on the first response.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Treat PRODUCT.md and DESIGN.md as anchors; they reduce repeated questions but do **not** replace shape for craft. Shape is task-specific.
-- One round is the default. Add a second only if the first answers leave material gaps. Don't run a second round just to feel thorough.
-- Round 1 should clarify purpose, audience/context, content/scope, and (for brand) visual direction.
-- Round 2, when needed, fills in whatever's still genuinely missing.
-
-**Assert-then-confirm, not menu-with-escape.** When PRODUCT.md and the user's prompt make one option obvious, name it and ask the user to confirm or override. Don't enumerate "Restrained / Committed / Or something else?" as a real choice; "This reads as Restrained, confirm?" beats a four-option menu when the answer is already clear.
-
-### Purpose & Context
-- What is this feature for? What problem does it solve?
-- Who specifically will use it? (Not "users"; be specific: role, context, frequency)
-- What does success look like? How will you know this feature is working?
-- What's the user's state of mind when they reach this feature? (Rushed? Exploring? Anxious? Focused?)
-
-### Content & Data
-- What content or data does this feature display or collect?
-- What are the realistic ranges? (Minimum, typical, maximum, e.g., 0 items, 5 items, 500 items)
-- What are the edge cases? (Empty state, error state, first-time use, power user)
-- Is any content dynamic? What changes and how often?
-- What visual assets are real content here? Note required images, product shots, illustrations, maps, textures, diagrams, generated objects, or existing project assets.
-
-### Design Direction
-
-Force a visual decision on three fronts. Skip anything PRODUCT.md or DESIGN.md already answers; ask only what's missing.
-
-- **Color strategy for this surface.** Pick one: Restrained / Committed / Full palette / Drenched. Can override the project default if the surface earns it (e.g. a drenched hero inside an otherwise Restrained product).
-- **Theme via scene sentence.** Write one sentence of physical context for this surface: who uses it, where, under what ambient light, in what mood. The sentence forces dark vs light. If it doesn't, add detail until it does.
-- **Two or three named anchor references.** Specific products, brands, objects. Not adjectives like "modern" or "clean."
-
-### Scope
-
-Always ask. Sketch quality and shipped quality are different outputs; don't guess between them.
-
-- **Fidelity.** Sketch / mid-fi / high-fi / production-ready?
-- **Breadth.** One screen / a flow / a whole surface?
-- **Interactivity.** Static visual / interactive prototype / shipped-quality component?
-- **Time intent.** Quick exploration, or polish until it ships?
-
-Scope answers are task-scoped. Don't write them to PRODUCT.md or DESIGN.md; carry them through the design brief only.
-
-### Constraints
-- Are there technical constraints? (Framework, performance budget, browser support)
-- Are there content constraints? (Localization, dynamic text length, user-generated content)
-- Mobile/responsive requirements?
-- Accessibility requirements beyond WCAG AA?
-
-### Anti-Goals
-- What should this NOT be? What would be a wrong direction?
-- What's the biggest risk of getting this wrong?
-
-## Phase 1.5: Visual Direction Probe (Capability-Gated)
-
-After the discovery interview, generate a small set of visual direction probes **before** writing the final brief when all of these are true:
-
-- The work is **net-new** or directionally ambiguous enough that visual exploration will clarify the brief.
-- The requested fidelity is **mid-fi, high-fi, or production-ready**. Skip for sketch-only planning.
-- The current harness gives you native image generation (Codex's `image_gen`, an equivalent MCP tool, or similar). Don't ask the user to install APIs or tooling.
-
-When those conditions are met, this step is mandatory. If image generation isn't natively available, do not ask the user to install APIs or tooling. State in one line that the image step is skipped because the harness lacks native image generation, then proceed. The one-line announcement is required, not optional; it forces a conscious decision instead of letting the step quietly evaporate.
-
-Use probes to explore visual lanes, not to replace the brief.
-
-Do not skip probes because the final UI will be semantic, editable, code-native, responsive, or accessible. Those are implementation requirements, not reasons to avoid visual exploration.
-
-### What to generate
-
-Generate **2 to 4** distinct direction probes based on the discovery answers, especially:
-
-- Color strategy
-- Theme scene sentence
-- Named anchor references
-- Scope and fidelity
-
-The probes should differ in primary visual direction (hierarchy, topology, density, typographic voice, or color strategy), not just palette tweaks.
-
-### How to use the probes
-
-- Treat them as **direction tests**, not final designs.
-- Use them to pressure-test whether the brief is pointing at the right lane.
-- Ask the user which direction feels closest, what feels off, and what should carry forward.
-- If the probes reveal a mismatch, revise the brief inputs before finalizing the brief.
-
-### Important limits
-
-- Do **not** skip discovery because image generation is available.
-- Do **not** treat generated imagery as final UX specification, final copy, or final accessibility behavior.
-- Do **not** use this step for minor refinements of existing work. It's for shaping a new surface or clarifying a big directional choice.
-
-If image generation isn't natively available, announce the skip in one line and proceed to the design brief.
-
-## Phase 2: Design Brief
-
-After the interview and any required probes, present a brief and **end your response**. The user must confirm before any implementation runs. Do not present a brief and then continue to code in the same response, even if the brief feels obvious to you. The user's confirmation is the gate.
-
-**Choose the brief shape based on how clear the answers are:**
-
-- **Compact form (3-5 bullets)** when discovery was crisp and the original prompt + PRODUCT.md already pinned scope, content, and direction. State what you're building, the visual lane, and end with one or two specific questions or a clear "confirm or override?" prompt. This is the default for typical craft requests with a clear prompt.
-- **Full structured form (sections below)** when the task is genuinely ambiguous, multi-screen, or when the user asked for shape as a standalone step. Use this when the discipline of structure earns its weight.
-
-Don't pad a clear brief into a long one to look thorough. A 70-line brief restating answers the user just gave is noise, not rigor. Equally, don't skip the confirmation pause to look efficient: the pause is the point.
-
-Present the brief, then **stop and wait for explicit confirmation**. You are not the judge of whether the user already approved. Even when the brief feels obviously right, ask once and wait. The pause is what separates shape from premature implementation.
-
-### Brief Structure
-
-**1. Feature Summary** (2-3 sentences)
-What this is, who it's for, what it needs to accomplish.
-
-**2. Primary User Action**
-The single most important thing a user should do or understand here.
-
-**3. Design Direction**
-Color strategy (Restrained / Committed / Full palette / Drenched) + the theme scene sentence + 2–3 named anchor references. Reference PRODUCT.md and DESIGN.md where they already answer, and note any per-surface overrides.
-
-If you ran the Visual Direction Probe step, name which probe direction won and what changed in the brief because of it.
-
-**4. Scope**
-Fidelity, breadth, interactivity, and time intent from the Scope section of the interview. Task-scoped; these don't persist beyond the brief.
-
-**5. Layout Strategy**
-High-level spatial approach: what gets emphasis, what's secondary, how information flows. Describe the visual hierarchy and rhythm, not specific CSS.
-
-**6. Key States**
-List every state the feature needs: default, empty, loading, error, success, edge cases. For each, note what the user needs to see and feel.
-
-**7. Interaction Model**
-How users interact with this feature. What happens on click, hover, scroll? What feedback do they get? What's the flow from entry to completion?
-
-**8. Content Requirements**
-What copy, labels, empty state messages, error messages, and microcopy are needed. Note any dynamic content and its realistic ranges. For image-led surfaces, also list the required image/media roles and their likely source (project asset, generated raster, semantic SVG/CSS, canvas/WebGL, icon library, or accepted omission).
-
-**9. Recommended References**
-Based on the brief, list which impeccable reference files would be most valuable during implementation (e.g., spatial-design.md for complex layouts, motion-design.md for animated features, interaction-design.md for form-heavy features).
-
-**10. Open Questions**
-Anything genuinely unresolved. Don't list "open questions" you've already recommended a default for; assert the default and move on. If you'd write `Recommend: X` next to a question, just decide X.
-
----
-
-ask the user directly to clarify what you cannot infer. Ask for explicit confirmation of the brief before finishing.
-
-If the user disagrees with any part, revisit the relevant discovery questions. A shape run is incomplete until the user confirms direction.
-
-Once confirmed, the brief is complete. The user can now hand it to /impeccable, or use it to guide any other implementation approach. (If the user wants the full discovery-then-build flow in one step, they should use /impeccable craft instead, which runs this command internally.)
@@ -1,100 +0,0 @@
-# Spatial Design
-
-## Spacing Systems
-
-### Use 4pt Base, Not 8pt
-
-8pt systems are too coarse; you'll frequently need 12px (between 8 and 16). Use 4pt for granularity: 4, 8, 12, 16, 24, 32, 48, 64, 96px.
-
-### Name Tokens Semantically
-
-Name by relationship (`--space-sm`, `--space-lg`), not value (`--spacing-8`). Use `gap` instead of margins for sibling spacing; it eliminates margin collapse and cleanup hacks.
-
-## Grid Systems
-
-### The Self-Adjusting Grid
-
-Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Columns are at least 280px, as many as fit per row, leftovers stretch. For complex layouts, use named grid areas (`grid-template-areas`) and redefine them at breakpoints.
-
-## Visual Hierarchy
-
-### The Squint Test
-
-Blur your eyes (or screenshot and blur). Can you still identify:
-- The most important element?
-- The second most important?
-- Clear groupings?
-
-If everything looks the same weight blurred, you have a hierarchy problem.
-
-### Hierarchy Through Multiple Dimensions
-
-Don't rely on size alone. Combine:
-
-| Tool | Strong Hierarchy | Weak Hierarchy |
-|------|------------------|----------------|
-| **Size** | 3:1 ratio or more | <2:1 ratio |
-| **Weight** | Bold vs Regular | Medium vs Regular |
-| **Color** | High contrast | Similar tones |
-| **Position** | Top/left (primary) | Bottom/right |
-| **Space** | Surrounded by white space | Crowded |
-
-**The best hierarchy uses 2-3 dimensions at once**: A heading that's larger, bolder, AND has more space above it.
-
-### Cards Are Not Required
-
-Cards are overused. Spacing and alignment create visual grouping naturally. Use cards only when content is truly distinct and actionable, items need visual comparison in a grid, or content needs clear interaction boundaries. **Never nest cards inside cards.** Use spacing, typography, and subtle dividers for hierarchy within a card.
-
-## Container Queries
-
-Viewport queries are for page layouts. **Container queries are for components**:
-
-```css
-.card-container {
- container-type: inline-size;
-}
-
-.card {
- display: grid;
- gap: var(--space-md);
-}
-
-/* Card layout changes based on its container, not viewport */
-@container (min-width: 400px) {
- .card {
- grid-template-columns: 120px 1fr;
- }
-}
-```
-
-**Why this matters**: A card in a narrow sidebar stays compact, while the same card in a main content area expands automatically, without viewport hacks.
-
-## Optical Adjustments
-
-Text at `margin-left: 0` looks indented due to letterform whitespace; use negative margin (`-0.05em`) to optically align. Geometrically centered icons often look off-center; play icons need to shift right, arrows shift toward their direction.
-
-### Touch Targets vs Visual Size
-
-Buttons can look small but need large touch targets (44px minimum). Use padding or pseudo-elements:
-
-```css
-.icon-button {
- width: 24px; /* Visual size */
- height: 24px;
- position: relative;
-}
-
-.icon-button::before {
- content: '';
- position: absolute;
- inset: -10px; /* Expand tap target to 44px */
-}
-```
-
-## Depth & Elevation
-
-Create semantic z-index scales (dropdown → sticky → modal-backdrop → modal → toast → tooltip) instead of arbitrary numbers. For shadows, create a consistent elevation scale (sm → md → lg → xl). **Key insight**: Shadows should be subtle. If you can clearly see it, it's probably too strong.
-
----
-
-**Avoid**: Arbitrary spacing values outside your scale. Making all spacing equal (variety creates hierarchy). Creating hierarchy through size alone - combine size, weight, color, and space.
@@ -1,156 +0,0 @@
-# Teach Flow
-
-Gathers design context for a project and writes two complementary files at the project root:
-
-- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
-- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
-
-Every other impeccable command reads these files before doing any work.
-
-## Step 1: Load current state
-
-Run the shared loader first so you know what already exists:
-
-```bash
-node .trae/skills/impeccable/scripts/load-context.mjs
-```
-
-The output tells you whether PRODUCT.md and/or DESIGN.md already exist. If `migrated: true`, legacy `.impeccable.md` was auto-renamed to `PRODUCT.md`. Mention this once to the user.
-
-Decision tree:
-- **Neither file exists (empty project or no context yet)**: do Steps 2-4 (write PRODUCT.md), then decide on DESIGN.md based on whether there's code to analyze.
-- **PRODUCT.md exists, DESIGN.md missing**: skip to Step 5 and offer to run `/impeccable document` for DESIGN.md.
-- **PRODUCT.md exists but has no `## Register` section (legacy)**: add it. Infer a hypothesis from the codebase (see Step 2), confirm with the user, write the field.
-- **Both exist**: ask the user directly to clarify what you cannot infer. Ask which file to refresh. Skip the one the user doesn't want changed.
-- **Just DESIGN.md exists (unusual)**: do Steps 2-4 to produce PRODUCT.md.
-
-Never silently overwrite an existing file. Always confirm first.
-
-If teach was invoked as a setup blocker by another command, such as `/impeccable craft landing page`, pause that command here. Complete teach, re-run the loader, then resume the original command with the freshly loaded context. For craft, resume into shape next; teach creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief.
-
-## Step 2: Explore the codebase
-
-Before asking questions, thoroughly scan the project to discover what you can:
-
-- **README and docs**: Project purpose, target audience, any stated goals
-- **Package.json / config files**: Tech stack, dependencies, existing design libraries
-- **Existing components**: Current design patterns, spacing, typography in use
-- **Brand assets**: Logos, favicons, color values already defined
-- **Design tokens / CSS variables**: Existing color palettes, font stacks, spacing scales
-- **Any style guides or brand documentation**
-
-Also form a **register hypothesis** from what you find:
-
-- Brand signals: `/`, `/about`, `/pricing`, `/blog/*`, `/docs/*`, hero sections, big typography, scroll-driven sections, landing-page-shaped content.
-- Product signals: `/app/*`, `/dashboard`, `/settings`, `/(auth)`, forms, data tables, side/top nav, app-shell components.
-
-Register is a hypothesis at this point, not a decision; Step 3 confirms it.
-
-Note what you've learned and what remains unclear. This exploration feeds both PRODUCT.md and DESIGN.md.
-
-## Step 3: Ask strategic questions (for PRODUCT.md)
-
-ask the user directly to clarify what you cannot infer. Ask only about what you couldn't infer from the codebase.
-
-### Interview mode, not confirmation mode
-
-If the repo is empty or the user's brief is sparse, run a short interview before proposing PRODUCT.md. Do **not** turn a one-sentence request into a complete inferred PRODUCT.md and ask for blanket confirmation.
-
-- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop.
-- Ask **2-3 questions per round**, then wait for answers.
-- Use inferred answers as hypotheses or options, not as finished facts.
-- Complete at least one real user-answer round before drafting PRODUCT.md, unless every required answer is directly discoverable from repo docs.
-- Round 1 should establish register, users/purpose, and desired outcome.
-- Round 2 should establish brand personality or references, anti-references, and accessibility needs.
-
-### Minimum viable interview
-
-Ask enough to complete PRODUCT.md. At minimum, cover register confirmation, users and purpose, brand personality, anti-references, and accessibility needs unless each answer is directly discoverable from repo context. After at least one interview round, you may propose inferred answers, but the user must confirm them before you write PRODUCT.md. Never synthesize PRODUCT.md from the original task prompt alone.
-
-### Register (ask first; it shapes everything below)
-
-Every design task is either **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboards, tools: design SERVES the product).
-
-If Step 2 produced a clear hypothesis, lead with it: *"From the codebase, this looks like a [brand / product] surface. Does that match your intent, or should we treat it differently?"*
-
-If the signal is genuinely split (e.g. a product with a big marketing landing), ask the user directly to clarify what you cannot infer. Ask which register describes the **primary** surface. The register can be overridden per task later, but PRODUCT.md carries one default.
-
-### Users & Purpose
-- Who uses this? What's their context when using it?
-- What job are they trying to get done?
-- For brand: what emotions should the interface evoke? (confidence, delight, calm, urgency)
-- For product: what workflow are they in? What's the primary task on any given screen?
-
-### Brand & Personality
-- How would you describe the brand personality in 3 words?
-- Reference sites or apps that capture the right feel? What specifically about them?
- - For brand, push for real-world references in the right lane (tech-minimal, editorial-magazine, consumer-warm, brutalist-grid, etc.), not generic "modern" adjectives.
- - For product, push for category best-tool references (Linear, Figma, Notion, Raycast, Stripe).
-- What should this explicitly NOT look like? Any anti-references?
-
-### Accessibility & Inclusion
-- Specific accessibility requirements? (WCAG level, known user needs)
-- Considerations for reduced motion, color blindness, or other accommodations?
-
-Skip questions where the answer is already clear. **Do NOT ask about colors, fonts, radii, or visual styling here.** Those belong in DESIGN.md, not PRODUCT.md.
-
-## Step 4: Write PRODUCT.md
-
-Write PRODUCT.md only after the user has confirmed the strategic answers from Step 3. If an inferred answer is uncertain or unconfirmed, ask before writing.
-
-Synthesize into a strategic document:
-
-```markdown
-# Product
-
-## Register
-
-product
-
-## Users
-[Who they are, their context, the job to be done]
-
-## Product Purpose
-[What this product does, why it exists, what success looks like]
-
-## Brand Personality
-[Voice, tone, 3-word personality, emotional goals]
-
-## Anti-references
-[What this should NOT look like. Specific bad-example sites or patterns to avoid.]
-
-## Design Principles
-[3-5 strategic principles derived from the conversation. Principles like "practice what you preach", "show, don't tell", "expert confidence". NOT visual rules like "use OKLCH" or "magenta accent".]
-
-## Accessibility & Inclusion
-[WCAG level, known user needs, considerations]
-```
-
-Register is either `brand` or `product` as a bare value. No prose, no commentary.
-
-Write to `PROJECT_ROOT/PRODUCT.md`. If `.impeccable.md` existed, the loader already renamed it; merge into that content rather than starting from scratch.
-
-## Step 5: Decide on DESIGN.md
-
-Offer `/impeccable document` either way. Two paths:
-
-- **Code exists** (CSS tokens, components, a running site): "I can generate a DESIGN.md that captures your visual system (colors, typography, components) so variants stay on-brand. Want to do that now?"
-- **Pre-implementation** (empty project): "I can seed a starter DESIGN.md from five quick questions about color strategy, type direction, motion energy, and references. You can re-run once there's code, to capture the real tokens. Want to do that now?"
-
-If the user agrees, delegate to `/impeccable document` (it auto-detects scan vs seed). Load its reference and follow that flow.
-
-If the user prefers to skip, mention they can run `/impeccable document` any time later.
-
-## Step 6: Confirm and wrap up
-
-Summarize:
-- Register captured (brand / product)
-- What was written (PRODUCT.md, DESIGN.md, or both)
-- The 3-5 strategic principles from PRODUCT.md that will guide future work
-- If DESIGN.md is pending, remind the user how to generate it later
-
-**Critical: re-run the loader to refresh session context.** After writing PRODUCT.md, run `node .trae/skills/impeccable/scripts/load-context.mjs` one final time and let its full JSON output land in conversation. This ensures subsequent commands in this session use the freshly-written PRODUCT.md, not a stale earlier version.
-
-If teach was invoked as a blocker by another impeccable command (e.g. the user ran `/impeccable polish` with no PRODUCT.md), resume that original task now with the fresh context.
-
-Optionally ask the user directly to clarify what you cannot infer. Ask whether they'd like a brief summary of PRODUCT.md appended to RULES.md for easier agent reference. If yes, append a short **Design Context** pointer section there.
@@ -1,124 +0,0 @@
-Typography carries most of the information on the page. Replace generic defaults (Inter, Roboto, system fallback at flat scale) with type that reflects the brand and scales with intentional contrast.
-
----
-
-## Register
-
-Brand: run the font selection procedure in [brand.md](brand.md). Pairing follows the brand's lane (display serif + sans body for editorial/luxury, one committed sans for tech, etc.). Fluid `clamp()` scale, ≥1.25 ratio between steps.
-
-Product: system fonts and familiar sans stacks are legitimate here. One well-tuned family typically carries the whole UI. Fixed `rem` scale, 1.125–1.2 ratio between more closely-spaced steps.
-
----
-
-## Assess Current Typography
-
-Analyze what's weak or generic about the current type:
-
-1. **Font choices**:
- - Are we using invisible defaults? (Inter, Roboto, Arial, Open Sans, system defaults)
- - Does the font match the brand personality? (A playful brand shouldn't use a corporate typeface)
- - Are there too many font families? (More than 2-3 is almost always a mess)
-
-2. **Hierarchy**:
- - Can you tell headings from body from captions at a glance?
- - Are font sizes too close together? (14px, 15px, 16px = muddy hierarchy)
- - Are weight contrasts strong enough? (Medium vs Regular is barely visible)
-
-3. **Sizing & scale**:
- - Is there a consistent type scale, or are sizes arbitrary?
- - Does body text meet minimum readability? (16px+)
- - Is the sizing strategy appropriate for the context? (Fixed `rem` scales for app UIs; fluid `clamp()` for marketing/content page headings)
-
-4. **Readability**:
- - Are line lengths comfortable? (45-75 characters ideal)
- - Is line-height appropriate for the font and context?
- - Is there enough contrast between text and background?
-
-5. **Consistency**:
- - Are the same elements styled the same way throughout?
- - Are font weights used consistently? (Not bold in one section, semibold in another for the same role)
- - Is letter-spacing intentional or default everywhere?
-
-**CRITICAL**: The goal isn't to make text "fancier." It's to make it clearer, more readable, and more intentional. Good typography is invisible; bad typography is distracting.
-
-## Plan Typography Improvements
-
-Consult the [typography reference](typography.md) for detailed guidance on scales, pairing, and loading strategies.
-
-Create a systematic plan:
-
-- **Font selection**: Do fonts need replacing? What fits the brand/context?
-- **Type scale**: Establish a modular scale (e.g., 1.25 ratio) with clear hierarchy
-- **Weight strategy**: Which weights serve which roles? (Regular for body, Semibold for labels, Bold for headings, or whatever fits)
-- **Spacing**: Line-heights, letter-spacing, and margins between typographic elements
-
-## Improve Typography Systematically
-
-### Font Selection
-
-If fonts need replacing:
-- Choose fonts that reflect the brand personality
-- Pair with genuine contrast (serif + sans, geometric + humanist), or use a single family in multiple weights
-- Ensure web font loading doesn't cause layout shift (`font-display: swap`, metric-matched fallbacks)
-
-### Establish Hierarchy
-
-Build a clear type scale:
-- **5 sizes cover most needs**: caption, secondary, body, subheading, heading
-- **Use a consistent ratio** between levels (1.25, 1.333, or 1.5)
-- **Combine dimensions**: Size + weight + color + space for strong hierarchy. Don't rely on size alone
-- **App UIs**: Use a fixed `rem`-based type scale, optionally adjusted at 1-2 breakpoints. Fluid sizing undermines the spatial predictability that dense, container-based layouts need
-- **Marketing / content pages**: Use fluid sizing via `clamp(min, preferred, max)` for headings and display text. Keep body text fixed
-
-### Fix Readability
-
-- Set `max-width` on text containers using `ch` units (`max-width: 65ch`)
-- Adjust line-height per context: tighter for headings (1.1-1.2), looser for body (1.5-1.7)
-- Increase line-height slightly for light-on-dark text
-- Ensure body text is at least 16px / 1rem
-
-### Refine Details
-
-- Use `tabular-nums` for data tables and numbers that should align
-- Apply proper `letter-spacing`: slightly open for small caps and uppercase, default or tight for large display text
-- Use semantic token names (`--text-body`, `--text-heading`), not value names (`--font-16`)
-- Set `font-kerning: normal` and consider OpenType features where appropriate
-
-### Weight Consistency
-
-- Define clear roles for each weight and stick to them
-- Don't use more than 3-4 weights (Regular, Medium, Semibold, Bold is plenty)
-- Load only the weights you actually use (each weight adds to page load)
-
-**NEVER**:
-- Use more than 2-3 font families
-- Pick sizes arbitrarily; commit to a scale
-- Set body text below 16px
-- Use decorative/display fonts for body text
-- Disable browser zoom (`user-scalable=no`)
-- Use `px` for font sizes; use `rem` to respect user settings
-- Default to Inter/Roboto/Open Sans when personality matters
-- Pair fonts that are similar but not identical (two geometric sans-serifs)
-
-## Verify Typography Improvements
-
-- **Hierarchy**: Can you identify heading vs body vs caption instantly?
-- **Readability**: Is body text comfortable to read in long passages?
-- **Consistency**: Are same-role elements styled identically throughout?
-- **Personality**: Does the typography reflect the brand?
-- **Performance**: Are web fonts loading efficiently without layout shift?
-- **Accessibility**: Does text meet WCAG contrast ratios? Is it zoomable to 200%?
-
-When the type carries the hierarchy on its own, hand off to `/impeccable polish` for the final pass.
-
-## Live-mode signature params
-
-Each variant MUST declare a `scale` param controlling the hierarchy ratio. Express all font sizes in the variant's scoped CSS through `calc(var(--p-scale, 1) * <base>)` or, better, scale the type ramp via `clamp(min, calc(var(--p-scale, 1) * Npx), max)`. Users slide from subdued to commanding.
-
-```json
-{"id":"scale","kind":"range","min":0.85,"max":1.3,"step":0.05,"default":1,"label":"Scale"}
-```
-
-Where the variant riffs on a specific pairing, expose the pairing choice as a `steps` param (e.g. "serif display + sans body" vs. "mono display + sans body" vs. "all-sans"). Each branch routes through `:scope[data-p-pairing="X"]` selectors in scoped CSS.
-
-See `reference/live.md` for the full params contract.
@@ -1,159 +0,0 @@
-# Typography
-
-## Classic Typography Principles
-
-### Vertical Rhythm
-
-Your line-height should be the base unit for ALL vertical spacing. If body text has `line-height: 1.5` on `16px` type (= 24px), spacing values should be multiples of 24px. This creates subconscious harmony; text and space share a mathematical foundation.
-
-### Modular Scale & Hierarchy
-
-The common mistake: too many font sizes that are too close together (14px, 15px, 16px, 18px...). This creates muddy hierarchy.
-
-**Use fewer sizes with more contrast.** A 5-size system covers most needs:
-
-| Role | Typical Ratio | Use Case |
-|------|---------------|----------|
-| xs | 0.75rem | Captions, legal |
-| sm | 0.875rem | Secondary UI, metadata |
-| base | 1rem | Body text |
-| lg | 1.25-1.5rem | Subheadings, lead text |
-| xl+ | 2-4rem | Headlines, hero text |
-
-Popular ratios: 1.25 (major third), 1.333 (perfect fourth), 1.5 (perfect fifth). Pick one and commit.
-
-### Readability & Measure
-
-Use `ch` units for character-based measure (`max-width: 65ch`). Line-height scales inversely with line length: narrow columns need tighter leading, wide columns need more.
-
-**Non-obvious**: Light text on dark backgrounds needs compensation on three axes, not just one. Bump line-height by 0.05–0.1, add a touch of letter-spacing (0.01–0.02em), and optionally step the body weight up one notch (regular → medium). The perceived weight drops across all three; fix all three.
-
-**Paragraph rhythm**: Pick either space between paragraphs OR first-line indentation. Never both. Digital usually wants space; editorial/long-form can justify indent-only.
-
-## Font Selection & Pairing
-
-The tactical selection procedure and the reflex-reject list live in [reference/brand.md](brand.md) under **Font selection procedure** and **Reflex-reject list** (loaded for brand-register tasks). The rest of this section covers the adjacent knowledge: anti-reflex corrections, system font use, and pairing rules.
-
-### Anti-reflexes worth defending against
-
-- A technical/utilitarian brief does NOT need a serif "for warmth." Most tech tools should look like tech tools.
-- An editorial/premium brief does NOT need the same expressive serif everyone is using right now. Premium can be Swiss-modern, can be neo-grotesque, can be a literal monospace, can be a quiet humanist sans.
-- A children's product does NOT need a rounded display font. Kids' books use real type.
-- A "modern" brief does NOT need a geometric sans. The most modern thing you can do is not use the font everyone else is using.
-
-**System fonts are underrated**: `-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui` looks native, loads instantly, and is highly readable. Consider this for apps where performance > personality.
-
-### Pairing Principles
-
-**The non-obvious truth**: You often don't need a second font. One well-chosen font family in multiple weights creates cleaner hierarchy than two competing typefaces. Only add a second font when you need genuine contrast (e.g., display headlines + body serif).
-
-When pairing, contrast on multiple axes:
-- Serif + Sans (structure contrast)
-- Geometric + Humanist (personality contrast)
-- Condensed display + Wide body (proportion contrast)
-
-**Never pair fonts that are similar but not identical** (e.g., two geometric sans-serifs). They create visual tension without clear hierarchy.
-
-### Web Font Loading
-
-The layout shift problem: fonts load late, text reflows, and users see content jump. Here's the fix:
-
-```css
-/* 1. Use font-display: swap for visibility */
-@font-face {
- font-family: 'CustomFont';
- src: url('font.woff2') format('woff2');
- font-display: swap;
-}
-
-/* 2. Match fallback metrics to minimize shift */
-@font-face {
- font-family: 'CustomFont-Fallback';
- src: local('Arial');
- size-adjust: 105%; /* Scale to match x-height */
- ascent-override: 90%; /* Match ascender height */
- descent-override: 20%; /* Match descender depth */
- line-gap-override: 10%; /* Match line spacing */
-}
-
-body {
- font-family: 'CustomFont', 'CustomFont-Fallback', sans-serif;
-}
-```
-
-Tools like [Fontaine](https://github.com/unjs/fontaine) calculate these overrides automatically.
-
-**`swap` vs `optional`**: `swap` shows fallback text immediately and FOUT-swaps when the web font arrives. `optional` uses the fallback if the web font misses a small load budget (~100ms) and avoids the shift entirely. Pick `optional` when zero layout shift matters more than seeing the branded font on slow networks.
-
-**Preload the critical weight only**: typically the regular-weight body font used above the fold. Preloading every weight costs more bandwidth than it saves.
-
-**Variable fonts for 3+ weights or styles**: a single variable font file is usually smaller than three static weight files, gives fractional weight control, and pairs well with `font-optical-sizing: auto`. For 1–2 weights, static is fine.
-
-## Modern Web Typography
-
-### Fluid Type
-
-Fluid typography via `clamp(min, preferred, max)` scales text smoothly with the viewport. The middle value (e.g., `5vw + 1rem`) controls scaling rate (higher vw = faster scaling). Add a rem offset so it doesn't collapse to 0 on small screens.
-
-**Use fluid type for**: Headings and display text on marketing/content pages where text dominates the layout and needs to breathe across viewport sizes.
-
-**Use fixed `rem` scales for**: App UIs, dashboards, and data-dense interfaces. No major app design system (Material, Polaris, Primer, Carbon) uses fluid type in product UI; fixed scales with optional breakpoint adjustments give the spatial predictability that container-based layouts need. Body text should also be fixed even on marketing pages, since the size difference across viewports is too small to warrant it.
-
-**Bound your clamp()**: keep `max-size ≤ ~2.5 × min-size`. Wider ratios break the browser's zoom and reflow behaviour and make large viewports feel like the page is shouting.
-
-**Scale container width and font-size together** so effective character measure stays in the 45–75ch band at every viewport. A heading that widens faster than its container drifts out of the comfortable measure at the top end.
-
-### OpenType Features
-
-Most developers don't know these exist. Use them for polish:
-
-```css
-/* Tabular numbers for data alignment */
-.data-table { font-variant-numeric: tabular-nums; }
-
-/* Proper fractions */
-.recipe-amount { font-variant-numeric: diagonal-fractions; }
-
-/* Small caps for abbreviations */
-abbr { font-variant-caps: all-small-caps; }
-
-/* Disable ligatures in code */
-code { font-variant-ligatures: none; }
-
-/* Enable kerning (usually on by default, but be explicit) */
-body { font-kerning: normal; }
-```
-
-Check what features your font supports at [Wakamai Fondue](https://wakamaifondue.com/).
-
-### Rendering polish
-
-```css
-/* Even out heading line lengths (browser picks better break points) */
-h1, h2, h3 { text-wrap: balance; }
-
-/* Reduce orphans and ragged endings in long prose */
-article p { text-wrap: pretty; }
-
-/* Variable fonts: pick the right optical-size master automatically */
-body { font-optical-sizing: auto; }
-```
-
-**ALL-CAPS tracking**: capitals sit too close at default spacing. Add 5–12% letter-spacing (`letter-spacing: 0.05em` to `0.12em`) to short all-caps labels, eyebrows, and small headings. Real small caps (via `font-variant-caps`) need the same treatment, slightly gentler.
-
-## Typography System Architecture
-
-Name tokens semantically (`--text-body`, `--text-heading`), not by value (`--font-size-16`). Include font stacks, size scale, weights, line-heights, and letter-spacing in your token system.
-
-## Accessibility Considerations
-
-Beyond contrast ratios (which are well-documented), consider:
-
-- **Never disable zoom**: `user-scalable=no` breaks accessibility. If your layout breaks at 200% zoom, fix the layout.
-- **Use rem/em for font sizes**: This respects user browser settings. Never `px` for body text.
-- **Minimum 16px body text**: Smaller than this strains eyes and fails WCAG on mobile.
-- **Adequate touch targets**: Text links need padding or line-height that creates 44px+ tap targets.
-
----
-
-**Avoid**: More than 2-3 font families per project. Skipping fallback font definitions. Ignoring font loading performance (FOUT/FOIT). Using decorative fonts for body text.
@@ -1,107 +0,0 @@
-# UX Writing
-
-## The Button Label Problem
-
-**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
-
-| Bad | Good | Why |
-|-----|------|-----|
-| OK | Save changes | Says what will happen |
-| Submit | Create account | Outcome-focused |
-| Yes | Delete message | Confirms the action |
-| Cancel | Keep editing | Clarifies what "cancel" means |
-| Click here | Download PDF | Describes the destination |
-
-**For destructive actions**, name the destruction:
-- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
-- "Delete 5 items" not "Delete selected" (show the count)
-
-## Error Messages: The Formula
-
-Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
-
-### Error Message Templates
-
-| Situation | Template |
-|-----------|----------|
-| **Format error** | "[Field] needs to be [format]. Example: [example]" |
-| **Missing required** | "Please enter [what's missing]" |
-| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
-| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
-| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
-
-### Don't Blame the User
-
-Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
-
-## Empty States Are Opportunities
-
-Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
-
-## Voice vs Tone
-
-**Voice** is your brand's personality, consistent everywhere.
-**Tone** adapts to the moment.
-
-| Moment | Tone Shift |
-|--------|------------|
-| Success | Celebratory, brief: "Done! Your changes are live." |
-| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
-| Loading | Reassuring: "Saving your work..." |
-| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
-
-**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
-
-## Writing for Accessibility
-
-**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
-
-## Writing for Translation
-
-### Plan for Expansion
-
-German text is ~30% longer than English. Allocate space:
-
-| Language | Expansion |
-|----------|-----------|
-| German | +30% |
-| French | +20% |
-| Finnish | +30-40% |
-| Chinese | -30% (fewer chars, but same width) |
-
-### Translation-Friendly Patterns
-
-Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
-
-## Consistency: The Terminology Problem
-
-Pick one term and stick with it:
-
-| Inconsistent | Consistent |
-|--------------|------------|
-| Delete / Remove / Trash | Delete |
-| Settings / Preferences / Options | Settings |
-| Sign in / Log in / Enter | Sign in |
-| Create / Add / New | Create |
-
-Build a terminology glossary and enforce it. Variety creates confusion.
-
-## Avoid Redundant Copy
-
-If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
-
-## Loading States
-
-Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
-
-## Confirmation Dialogs: Use Sparingly
-
-Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
-
-## Form Instructions
-
-Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
-
----
-
-**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
@@ -1,284 +0,0 @@
-#!/usr/bin/env node
-/**
- * Cleans up deprecated Impeccable skill files, symlinks, and
- * skills-lock.json entries left over from previous versions.
- *
- * Safe to run repeatedly -- it is a no-op when nothing needs cleaning.
- *
- * Usage (from the project root):
- * node {{scripts_path}}/cleanup-deprecated.mjs
- *
- * What it does:
- * 1. Finds every harness-specific skills directory (.claude/skills,
- * .cursor/skills, .agents/skills, etc.).
- * 2. For each deprecated skill name (with and without i- prefix),
- * checks if the directory exists and its SKILL.md mentions
- * "impeccable" (to avoid deleting unrelated user skills).
- * 3. Deletes confirmed matches (files, directories, or symlinks).
- * 4. Removes the corresponding entries from skills-lock.json.
- */
-
-import { existsSync, readFileSync, writeFileSync, rmSync, readdirSync, statSync, lstatSync, unlinkSync } from 'node:fs';
-import { join, resolve } from 'node:path';
-
-// Skills that were renamed, merged, or folded in v2.0, v2.1, and v3.0.
-const DEPRECATED_NAMES = [
- // v2.0 renames
- 'frontend-design', // renamed to impeccable
- 'teach-impeccable', // folded into /impeccable teach
- // v2.1 merges
- 'arrange', // renamed to layout
- 'normalize', // merged into polish
- 'onboard', // merged into harden
- 'extract', // merged into /impeccable extract
- // v3.0 consolidation: all standalone skills -> /impeccable sub-commands
- 'adapt',
- 'animate',
- 'audit',
- 'bolder',
- 'clarify',
- 'colorize',
- 'critique',
- 'delight',
- 'distill',
- 'harden',
- 'layout',
- 'optimize',
- 'overdrive',
- 'polish',
- 'quieter',
- 'shape',
- 'typeset',
-];
-
-// All known harness directories that may contain a skills/ subfolder.
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Per-skill fingerprints for SKILL.md bodies that never mentioned
-// "impeccable" in their v2.x source. Used as a last-resort match
-// when no skills-lock.json exists and the word heuristic fails.
-// The strings are lifted verbatim from the v2.x frontmatter
-// descriptions, so collisions with hand-written user skills are
-// vanishingly unlikely.
-const SKILL_FINGERPRINTS = {
- harden: 'Make interfaces production-ready: error handling, empty states',
- optimize: 'Diagnoses and fixes UI performance across loading speed',
-};
-
-/**
- * Walk up from startDir until we find a directory that looks like a
- * project root (has package.json, .git, or skills-lock.json).
- */
-export function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- const { root } = { root: '/' };
- while (dir !== root) {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Load skills-lock.json from the project root, or null if missing/unreadable.
- */
-export function loadLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return null;
- try {
- return JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return null;
- }
-}
-
-/**
- * Check whether a skill directory belongs to Impeccable. Three layered
- * signals, in order of reliability:
- * 1. Lock source equals "pbakaus/impeccable" (authoritative).
- * 2. SKILL.md body contains the word "impeccable".
- * 3. SKILL.md body contains a per-skill fingerprint (for harden and
- * optimize, whose v2.x SKILL.md never mentioned the pack name).
- */
-export function isImpeccableSkill(skillDir, { skillName, lock } = {}) {
- // 1. Authoritative: the lock file claims this skill is ours.
- if (skillName && lock?.skills?.[skillName]?.source === 'pbakaus/impeccable') {
- return true;
- }
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) return false;
- let content;
- try {
- content = readFileSync(skillMd, 'utf-8');
- } catch {
- return false;
- }
- // 2. Word-level content heuristic.
- if (/impeccable/i.test(content)) return true;
- // 3. Per-skill fingerprint for old skills that never mentioned the pack.
- // Strip the i- prefix so both `harden` and `i-harden` resolve to the
- // same fingerprint entry.
- const unprefixed = skillName?.startsWith('i-') ? skillName.slice(2) : skillName;
- const fingerprint = unprefixed && SKILL_FINGERPRINTS[unprefixed];
- if (fingerprint && content.includes(fingerprint)) return true;
- return false;
-}
-
-/**
- * Build the full list of names to check: each deprecated name, plus
- * its i-prefixed variant.
- */
-export function buildTargetNames() {
- const names = [];
- for (const name of DEPRECATED_NAMES) {
- names.push(name);
- names.push(`i-${name}`);
- }
- return names;
-}
-
-/**
- * Find every skills directory across all harness dirs in the project.
- * Returns absolute paths that exist on disk.
- */
-export function findSkillsDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const candidate = join(projectRoot, harness, 'skills');
- if (existsSync(candidate)) {
- dirs.push(candidate);
- }
- }
- return dirs;
-}
-
-/**
- * Remove deprecated skill directories/symlinks from all harness dirs.
- * Reads skills-lock.json so the authoritative "source" field can
- * drive deletion even when SKILL.md never mentions impeccable.
- * Returns an array of paths that were deleted.
- */
-export function removeDeprecatedSkills(projectRoot, lock) {
- if (lock === undefined) lock = loadLock(projectRoot);
- const targets = buildTargetNames();
- const skillsDirs = findSkillsDirs(projectRoot);
- const deleted = [];
-
- for (const skillsDir of skillsDirs) {
- for (const name of targets) {
- const skillPath = join(skillsDir, name);
-
- // Use lstat to detect symlinks (existsSync follows symlinks and
- // returns false for dangling ones).
- let stat;
- try {
- stat = lstatSync(skillPath);
- } catch {
- continue; // does not exist at all
- }
-
- if (stat.isSymbolicLink()) {
- // Symlink: check the target if it's alive, otherwise treat
- // dangling symlinks to deprecated names as safe to remove.
- const targetAlive = existsSync(skillPath);
- const isMatch = targetAlive
- ? isImpeccableSkill(skillPath, { skillName: name, lock })
- : true;
- if (isMatch) {
- unlinkSync(skillPath);
- deleted.push(skillPath);
- }
- continue;
- }
-
- // Regular directory -- verify it belongs to impeccable
- if (isImpeccableSkill(skillPath, { skillName: name, lock })) {
- rmSync(skillPath, { recursive: true, force: true });
- deleted.push(skillPath);
- }
- }
- }
-
- return deleted;
-}
-
-/**
- * Remove deprecated entries from skills-lock.json.
- * Only removes entries whose source is "pbakaus/impeccable".
- * Returns the list of removed skill names.
- */
-export function cleanSkillsLock(projectRoot) {
- const lockPath = join(projectRoot, 'skills-lock.json');
- if (!existsSync(lockPath)) return [];
-
- let lock;
- try {
- lock = JSON.parse(readFileSync(lockPath, 'utf-8'));
- } catch {
- return [];
- }
-
- if (!lock.skills || typeof lock.skills !== 'object') return [];
-
- const targets = buildTargetNames();
- const removed = [];
-
- for (const name of targets) {
- const entry = lock.skills[name];
- if (!entry) continue;
- // Only remove if it belongs to impeccable
- if (entry.source === 'pbakaus/impeccable') {
- delete lock.skills[name];
- removed.push(name);
- }
- }
-
- if (removed.length > 0) {
- writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\n', 'utf-8');
- }
-
- return removed;
-}
-
-/**
- * Run the full cleanup. Returns a summary object.
- *
- * Order matters: read the lock and delete directories first, then
- * strip lock entries. Otherwise the authoritative signal is gone by
- * the time directory deletion runs.
- */
-export function cleanup(projectRoot) {
- const root = projectRoot || findProjectRoot();
- const lock = loadLock(root);
- const deletedPaths = removeDeprecatedSkills(root, lock);
- const removedLockEntries = cleanSkillsLock(root);
- return { deletedPaths, removedLockEntries, projectRoot: root };
-}
-
-// CLI entry point
-if (process.argv[1] && resolve(process.argv[1]) === resolve(new URL(import.meta.url).pathname)) {
- const result = cleanup();
- if (result.deletedPaths.length === 0 && result.removedLockEntries.length === 0) {
- console.log('No deprecated Impeccable skills found. Nothing to clean up.');
- } else {
- if (result.deletedPaths.length > 0) {
- console.log(`Removed ${result.deletedPaths.length} deprecated skill(s):`);
- for (const p of result.deletedPaths) console.log(` - ${p}`);
- }
- if (result.removedLockEntries.length > 0) {
- console.log(`Cleaned ${result.removedLockEntries.length} entry/entries from skills-lock.json:`);
- for (const name of result.removedLockEntries) console.log(` - ${name}`);
- }
- }
-}
@@ -1,94 +0,0 @@
-{
- "craft": {
- "description": "Full confirmed-brief-then-build flow. Runs multi-round shape discovery first, resolves visual probe and north-star mock gates when available, then builds and visually iterates. Use when building a new feature end-to-end.",
- "argumentHint": "[feature description]"
- },
- "teach": {
- "description": "Gathers design context for a project. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles) and, when code exists to analyze, DESIGN.md (visual: colors, typography, components). Every other command reads these files before doing work. Use once per project.",
- "argumentHint": ""
- },
- "document": {
- "description": "Generate a DESIGN.md file that captures the current visual design system. Auto-extracts colors, typography, spacing, radii, and component patterns from the codebase, then asks the user to confirm descriptive language for atmosphere and color character. Follows the Google Stitch DESIGN.md format so the file is tool-compatible. Use when you need a visual design spec an AI agent can follow to stay on-brand.",
- "argumentHint": ""
- },
- "extract": {
- "description": "Pull reusable patterns, components, and design tokens into the design system. Identifies repeated patterns and consolidates them. Use when you have drift across the codebase and want to bring things back to a consistent system.",
- "argumentHint": "[target]"
- },
- "live": {
- "description": "Interactive live variant mode. Select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via HMR. Requires a running dev server. Use when you want to visually experiment with design alternatives in real time.",
- "argumentHint": ""
- },
- "adapt": {
- "description": "Adapt designs to work across different screen sizes, devices, contexts, or platforms. Implements breakpoints, fluid layouts, and touch targets. Use when the user mentions responsive design, mobile layouts, breakpoints, viewport adaptation, or cross-device compatibility.",
- "argumentHint": "[target] [context (mobile, tablet, print...)]"
- },
- "animate": {
- "description": "Review a feature and enhance it with purposeful animations, micro-interactions, and motion effects that improve usability and delight. Use when the user mentions adding animation, transitions, micro-interactions, motion design, hover effects, or making the UI feel more alive.",
- "argumentHint": "[target]"
- },
- "audit": {
- "description": "Run technical quality checks across accessibility, performance, theming, responsive design, and anti-patterns. Generates a scored report with P0-P3 severity ratings and actionable plan. Use when the user wants an accessibility check, performance audit, or technical quality review.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "bolder": {
- "description": "Amplify safe or boring designs to make them more visually interesting and stimulating. Increases impact while maintaining usability. Use when the user says the design looks bland, generic, too safe, lacks personality, or wants more visual impact and character.",
- "argumentHint": "[target]"
- },
- "clarify": {
- "description": "Improve unclear UX copy, error messages, microcopy, labels, and instructions to make interfaces easier to understand. Use when the user mentions confusing text, unclear labels, bad error messages, hard-to-follow instructions, or wanting better UX writing.",
- "argumentHint": "[target]"
- },
- "colorize": {
- "description": "Add strategic color to features that are too monochromatic or lack visual interest, making interfaces more engaging and expressive. Use when the user mentions the design looking gray, dull, lacking warmth, needing more color, or wanting a more vibrant or expressive palette.",
- "argumentHint": "[target]"
- },
- "critique": {
- "description": "Evaluate design from a UX perspective, assessing visual hierarchy, information architecture, emotional resonance, cognitive load, and overall quality with quantitative scoring, persona-based testing, automated anti-pattern detection, and actionable feedback. Use when the user asks to review, critique, evaluate, or give feedback on a design or component.",
- "argumentHint": "[area (feature, page, component...)]"
- },
- "delight": {
- "description": "Add moments of joy, personality, and unexpected touches that make interfaces memorable and enjoyable to use. Elevates functional to delightful. Use when the user asks to add polish, personality, animations, micro-interactions, delight, or make an interface feel fun or memorable.",
- "argumentHint": "[target]"
- },
- "distill": {
- "description": "Strip designs to their essence by removing unnecessary complexity. Great design is simple, powerful, and clean. Use when the user asks to simplify, declutter, reduce noise, remove elements, or make a UI cleaner and more focused.",
- "argumentHint": "[target]"
- },
- "harden": {
- "description": "Make interfaces production-ready: error handling, i18n, text overflow, edge case management, and resilience under real-world data. Use when the user asks to harden, make production-ready, handle edge cases, add error states, or fix overflow and i18n issues.",
- "argumentHint": "[target]"
- },
- "onboard": {
- "description": "Design onboarding flows, first-run experiences, and empty states that guide new users to value. Covers welcome screens, account setup, progressive disclosure, contextual tooltips, feature announcements, and activation moments. Use when the user mentions onboarding, first-time users, empty states, activation, getting started, new user flows, or the aha moment.",
- "argumentHint": "[target]"
- },
- "layout": {
- "description": "Improve layout, spacing, and visual rhythm. Fixes monotonous grids, inconsistent spacing, and weak visual hierarchy. Use when the user mentions layout feeling off, spacing issues, visual hierarchy, crowded UI, alignment problems, or wanting better composition.",
- "argumentHint": "[target]"
- },
- "optimize": {
- "description": "Diagnoses and fixes UI performance across loading speed, rendering, animations, images, and bundle size. Use when the user mentions slow, laggy, janky, performance, bundle size, load time, or wants a faster, smoother experience.",
- "argumentHint": "[target]"
- },
- "overdrive": {
- "description": "Pushes interfaces past conventional limits with technically ambitious implementations — shaders, spring physics, scroll-driven reveals, 60fps animations. Use when the user wants to wow, impress, go all-out, or make something that feels extraordinary.",
- "argumentHint": "[target]"
- },
- "polish": {
- "description": "Performs a final quality pass fixing alignment, spacing, consistency, and micro-detail issues before shipping. Use when the user mentions polish, finishing touches, pre-launch review, something looks off, or wants to go from good to great.",
- "argumentHint": "[target]"
- },
- "quieter": {
- "description": "Tones down visually aggressive or overstimulating designs, reducing intensity while preserving quality. Use when the user mentions too bold, too loud, overwhelming, aggressive, garish, or wants a calmer, more refined aesthetic.",
- "argumentHint": "[target]"
- },
- "shape": {
- "description": "Plan UX and UI before code. Runs a required multi-round discovery interview, uses visual probes when available, and produces a user-confirmed design brief for implementation.",
- "argumentHint": "[feature to shape]"
- },
- "typeset": {
- "description": "Improves typography by fixing font choices, hierarchy, sizing, weight, and readability so text feels intentional. Use when the user mentions fonts, type, readability, text hierarchy, sizing looks off, or wants more polished, intentional typography.",
- "argumentHint": "[target]"
- }
-}
@@ -1,242 +0,0 @@
-#!/usr/bin/env node
-/**
- * Critique persistence helper.
- *
- * Each run of /impeccable critique writes a per-target snapshot to
- * .impeccable/critique/<timestamp>__<slug>.md
- * with a small YAML frontmatter carrying the score + P0/P1 counts.
- *
- * /impeccable polish reads the latest matching snapshot at start as its
- * fix backlog. No other skill auto-reads critique output.
- *
- * The slug is derived mechanically from the *resolved* primary artifact
- * (file path or URL), never from the user's natural-language phrasing.
- * Slug stability across runs is what lets the trend display work.
- *
- * CLI entry points (called from skill instructions):
- * node critique-storage.mjs slug <resolved-target>
- * node critique-storage.mjs write <slug> <snapshot-body-file>
- * node critique-storage.mjs latest <slug>
- * node critique-storage.mjs trend <slug> [limit]
- *
- * Note: there is intentionally no `ignore` subcommand. ignore.md is a plain
- * markdown file; the model reads it directly with its file-read tool. This
- * helper only exists for operations the model can't trivially do inline
- * (normalizing paths, generating filenames, globbing + parsing frontmatter).
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath, pathToFileURL } from 'node:url';
-import { getCritiqueDir } from './impeccable-paths.mjs';
-
-const SLUG_MAX = 50;
-
-/**
- * Mechanically derive a slug from a resolved target. Returns null if the
- * input doesn't look like a stable identifier (empty, project root, etc).
- *
- * Accepts file paths and URLs. The model resolves "the homepage" to a
- * concrete artifact before calling this — we never slug a natural-language
- * phrase.
- */
-export function slugFromTarget(resolved, { cwd = process.cwd() } = {}) {
- if (!resolved || typeof resolved !== 'string') return null;
- const trimmed = resolved.trim();
- if (!trimmed) return null;
-
- // URL
- if (/^https?:\/\//i.test(trimmed)) {
- let url;
- try { url = new URL(trimmed); } catch { return null; }
- const hostPath = `${url.hostname}${url.pathname}`;
- return kebab(hostPath);
- }
-
- // File path. Make it project-relative so two devs critiquing the same
- // checkout get the same slug regardless of where their repo is cloned.
- const abs = path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- let rel = path.relative(cwd, abs);
- // If the target is outside cwd, fall back to the basename so we still
- // produce a stable slug (vs the absolute path, which would include
- // home dirs / usernames).
- if (rel.startsWith('..') || path.isAbsolute(rel)) {
- rel = path.basename(abs);
- }
- if (!rel || rel === '.' || rel === '') return null;
- return kebab(rel);
-}
-
-function kebab(s) {
- const slug = s
- .toLowerCase()
- .replace(/[/\\.]+/g, '-')
- .replace(/[^a-z0-9-]+/g, '-')
- .replace(/-+/g, '-')
- .replace(/^-|-$/g, '');
- if (!slug) return null;
- // Cap from the tail — the tail (filename) is more identifying than the
- // top-level directory.
- return slug.length <= SLUG_MAX ? slug : slug.slice(slug.length - SLUG_MAX).replace(/^-/, '');
-}
-
-/**
- * Filename-safe UTC ISO timestamp: hyphens for separators, trailing Z.
- * Plain colons aren't allowed on Windows filesystems.
- */
-export function nowFilenameStamp(date = new Date()) {
- const iso = date.toISOString(); // 2026-05-12T18:30:00.123Z
- return iso.replace(/[:.]/g, '-').replace(/-\d+Z$/, 'Z');
-}
-
-/**
- * Write a snapshot for `slug`. `meta` carries the small structured frontmatter
- * keys read back by readTrend(). `body` is the human-readable critique
- * report (everything below the frontmatter).
- *
- * Returns the absolute path written.
- */
-export function writeSnapshot({ slug, meta, body, cwd = process.cwd(), now = new Date() }) {
- if (!slug) throw new Error('writeSnapshot requires a slug');
- const dir = getCritiqueDir(cwd);
- fs.mkdirSync(dir, { recursive: true });
- const timestamp = nowFilenameStamp(now);
- const filePath = path.join(dir, `${timestamp}__${slug}.md`);
- // Spread `meta` first so internally computed `timestamp` and `slug`
- // always win. Otherwise a caller-supplied meta blob (parsed from the
- // IMPECCABLE_CRITIQUE_META env var) could clobber them, leaving the
- // filename in disagreement with its frontmatter and corrupting trends.
- const front = serializeFrontmatter({ ...meta, timestamp, slug });
- fs.writeFileSync(filePath, `${front}\n${body.trim()}\n`, 'utf-8');
- return filePath;
-}
-
-function serializeFrontmatter(obj) {
- const lines = ['---'];
- for (const [key, value] of Object.entries(obj)) {
- if (value === undefined || value === null) continue;
- const str = typeof value === 'string' ? value : String(value);
- // Quote strings that contain : or # to keep parsing simple.
- const needsQuotes = typeof value === 'string' && /[:#]/.test(str);
- lines.push(`${key}: ${needsQuotes ? JSON.stringify(str) : str}`);
- }
- lines.push('---');
- return lines.join('\n');
-}
-
-function parseFrontmatter(text) {
- const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
- if (!match) return {};
- const out = {};
- for (const line of match[1].split(/\r?\n/)) {
- const colon = line.indexOf(':');
- if (colon < 0) continue;
- const key = line.slice(0, colon).trim();
- let value = line.slice(colon + 1).trim();
- if (/^".*"$/.test(value)) {
- try { value = JSON.parse(value); } catch { /* leave as-is */ }
- } else if (/^-?\d+$/.test(value)) {
- value = Number(value);
- }
- out[key] = value;
- }
- return out;
-}
-
-/**
- * Return all snapshot files for `slug`, sorted oldest → newest.
- */
-function listSnapshotsForSlug(slug, cwd) {
- const dir = getCritiqueDir(cwd);
- if (!fs.existsSync(dir)) return [];
- const suffix = `__${slug}.md`;
- return fs.readdirSync(dir)
- .filter((f) => f.endsWith(suffix))
- .sort()
- .map((f) => path.join(dir, f));
-}
-
-/**
- * Return the most recent snapshot for `slug`, or null. Polish reads this
- * to find its fix backlog when the slug matches.
- */
-export function readLatestSnapshot(slug, { cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- if (!all.length) return null;
- const latest = all[all.length - 1];
- const body = fs.readFileSync(latest, 'utf-8');
- return { path: latest, body, meta: parseFrontmatter(body) };
-}
-
-/**
- * Return the last `limit` snapshots' frontmatter, oldest → newest.
- * Critique appends a one-line trend to its output using this.
- */
-export function readTrend(slug, { limit = 5, cwd = process.cwd() } = {}) {
- const all = listSnapshotsForSlug(slug, cwd);
- const slice = all.slice(-limit);
- return slice.map((file) => parseFrontmatter(fs.readFileSync(file, 'utf-8')));
-}
-
-// ---- CLI ---------------------------------------------------------------
-
-function main(argv) {
- const [cmd, ...args] = argv;
- switch (cmd) {
- case 'slug': {
- const slug = slugFromTarget(args[0]);
- if (!slug) { process.stderr.write('no stable slug for input\n'); process.exit(1); }
- process.stdout.write(`${slug}\n`);
- return;
- }
- case 'write': {
- const [slug, bodyFile] = args;
- if (!slug || !bodyFile) { process.stderr.write('usage: write <slug> <body-file>\n'); process.exit(1); }
- const raw = fs.readFileSync(bodyFile, 'utf-8');
- // The body file may be a full report. The caller passes the meta as
- // a JSON object on stdin if it wants structured frontmatter; otherwise
- // we write with minimal metadata.
- let meta = {};
- const metaArg = process.env.IMPECCABLE_CRITIQUE_META;
- if (metaArg) {
- try { meta = JSON.parse(metaArg); } catch { /* ignore */ }
- }
- const out = writeSnapshot({ slug, meta, body: raw });
- process.stdout.write(`${out}\n`);
- return;
- }
- case 'latest': {
- const latest = readLatestSnapshot(args[0]);
- if (!latest) { process.exit(2); }
- process.stdout.write(latest.body);
- return;
- }
- case 'trend': {
- const rows = readTrend(args[0], { limit: args[1] ? Number(args[1]) : 5 });
- process.stdout.write(JSON.stringify(rows, null, 2) + '\n');
- return;
- }
- default:
- process.stderr.write('usage: critique-storage.mjs <slug|write|latest|trend> [args]\n');
- process.exit(1);
- }
-}
-
-function isMainModule() {
- if (!process.argv[1]) return false;
- try {
- return fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1]);
- } catch {
- // pathToFileURL normalizes Windows paths; keep it as a fallback for any
- // environment where realpath is unavailable.
- return import.meta.url === pathToFileURL(process.argv[1]).href;
- }
-}
-
-// Why the realpath check: generated skills are often reached through symlinked
-// harness directories (for example a demo repo's `.agents` -> source `.agents`).
-// Node resolves import.meta.url to the real file, while process.argv[1] keeps
-// the symlink path. Comparing canonical paths prevents a silent exit-0 no-op.
-if (isMainModule()) {
- main(process.argv.slice(2));
-}
@@ -1,820 +0,0 @@
-// Parse a DESIGN.md (Stitch-spec format) into a structured JSON model that
-// the live-mode design-system panel can render. Deterministic, dependency-free.
-//
-// Two-layer: YAML frontmatter (machine-readable tokens) + markdown body
-// (prose with six canonical H2 sections). When frontmatter is present, it's
-// exposed on `model.frontmatter` alongside the prose-scraped sections;
-// consumers can prefer frontmatter values and fall back to prose.
-
-const CANONICAL_SECTIONS = [
- 'Overview',
- 'Colors',
- 'Typography',
- 'Elevation',
- 'Components',
- "Do's and Don'ts",
-];
-
-// ---------- Frontmatter (Stitch YAML subset) ----------
-
-function parseFrontmatter(md) {
- const lines = md.split(/\r?\n/);
- if (lines[0]?.trim() !== '---') return { frontmatter: null, body: md };
-
- let end = -1;
- for (let i = 1; i < lines.length; i++) {
- if (lines[i].trim() === '---') { end = i; break; }
- }
- if (end === -1) return { frontmatter: null, body: md };
-
- const yaml = lines.slice(1, end).join('\n');
- const body = lines.slice(end + 1).join('\n');
- try {
- return { frontmatter: parseYamlSubset(yaml), body };
- } catch {
- return { frontmatter: null, body: md };
- }
-}
-
-// Minimal YAML reader for the Stitch frontmatter subset: scalar maps with
-// one level of nested objects (typography roles, components). Indent-based,
-// 2-space convention. No arrays, no anchors, no multi-line scalars — Stitch's
-// schema doesn't need them and accepting them would require a real YAML
-// dependency we don't want to vendor.
-function parseYamlSubset(yaml) {
- const lines = yaml.split(/\r?\n/);
- const root = {};
- const stack = [{ indent: -1, obj: root }];
-
- for (const raw of lines) {
- // Skip blanks and line-only comments. Don't strip inline comments:
- // unquoted hex values start with `#` and can't be safely distinguished
- // from a comment after whitespace.
- if (!raw.trim() || /^\s*#/.test(raw)) continue;
-
- const indent = raw.match(/^\s*/)[0].length;
- const content = raw.slice(indent);
-
- const colonIdx = findTopLevelColon(content);
- if (colonIdx === -1) continue;
-
- while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
- stack.pop();
- }
-
- const key = content.slice(0, colonIdx).trim();
- const rest = content.slice(colonIdx + 1).trim();
- const parent = stack[stack.length - 1].obj;
-
- if (rest === '') {
- const obj = {};
- parent[key] = obj;
- stack.push({ indent, obj });
- } else {
- parent[key] = parseScalar(rest);
- }
- }
-
- return root;
-}
-
-function findTopLevelColon(s) {
- let inQuote = null;
- for (let i = 0; i < s.length; i++) {
- const ch = s[i];
- if (inQuote) {
- if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
- } else if (ch === '"' || ch === "'") {
- inQuote = ch;
- } else if (ch === ':') {
- return i;
- }
- }
- return -1;
-}
-
-function parseScalar(raw) {
- const s = raw.trim();
- if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
- return s.slice(1, -1);
- }
- if (s === 'true') return true;
- if (s === 'false') return false;
- if (s === 'null' || s === '~') return null;
- if (/^-?\d+$/.test(s)) return Number(s);
- if (/^-?\d*\.\d+$/.test(s)) return Number(s);
- return s;
-}
-
-const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
-const OKLCH_RE = /oklch\([^)]+\)/gi;
-const RGBA_RE = /rgba?\([^)]+\)/gi;
-const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
-const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
-
-// ---------- Section splitting ----------
-
-function splitSections(md) {
- const lines = md.split(/\r?\n/);
- let title = null;
- const sections = {};
- let current = null;
-
- for (const raw of lines) {
- const line = raw.trimEnd();
-
- if (!title && line.startsWith('# ') && !line.startsWith('## ')) {
- title = line.replace(/^#\s+/, '').trim();
- continue;
- }
-
- const h2 = line.match(/^##\s+(?:\d+\.\s*)?([^:\n]+?)(?::\s*(.+))?$/);
- if (h2) {
- const rawName = normalizeApostrophes(h2[1].trim());
- const subtitle = h2[2] ? h2[2].trim() : null;
- const canonical = matchCanonicalSection(rawName);
- if (canonical) {
- current = { name: canonical, subtitle, lines: [] };
- sections[canonical] = current;
- continue;
- }
- // non-canonical H2 — ignore but stop feeding into current
- current = null;
- continue;
- }
-
- if (current) current.lines.push(raw);
- }
-
- return { title, sections };
-}
-
-function normalizeApostrophes(s) {
- return s.replace(/[\u2018\u2019]/g, "'");
-}
-
-function matchCanonicalSection(name) {
- const normalized = normalizeApostrophes(name).toLowerCase();
- // Exact match first
- for (const c of CANONICAL_SECTIONS) {
- if (normalizeApostrophes(c).toLowerCase() === normalized) return c;
- }
- // Keyword-contained match: "Overview & Creative North Star" -> "Overview",
- // "Elevation & Depth" -> "Elevation", etc.
- for (const c of CANONICAL_SECTIONS) {
- const key = normalizeApostrophes(c).toLowerCase();
- const pattern = new RegExp(`\\b${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
- if (pattern.test(normalized)) return c;
- }
- return null;
-}
-
-// ---------- Subsection splitting (inside a canonical section) ----------
-
-function splitSubsections(lines) {
- const subs = [];
- let current = { name: null, lines: [] };
- subs.push(current);
-
- for (const raw of lines) {
- const h3 = raw.match(/^###\s+(.+?)\s*$/);
- if (h3) {
- current = { name: h3[1].trim(), lines: [] };
- subs.push(current);
- continue;
- }
- current.lines.push(raw);
- }
-
- return subs;
-}
-
-// ---------- Generic helpers ----------
-
-function collectParagraphs(lines) {
- const paragraphs = [];
- let buf = [];
- const flush = () => {
- if (buf.length) {
- paragraphs.push(buf.join(' ').trim());
- buf = [];
- }
- };
- for (const raw of lines) {
- const trimmed = raw.trim();
- if (trimmed === '') { flush(); continue; }
- // Horizontal rules (---, ***) and headings/bullets end a paragraph.
- if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { flush(); continue; }
- if (raw.startsWith('#') || raw.match(/^[-*]\s/)) { flush(); continue; }
- buf.push(trimmed);
- }
- flush();
- return paragraphs.filter(Boolean);
-}
-
-function collectBullets(lines) {
- const bullets = [];
- let current = null;
- for (const raw of lines) {
- const m = raw.match(/^\s*[-*]\s+(.+)$/);
- if (m) {
- if (current) bullets.push(current);
- current = m[1];
- continue;
- }
- // continuation of a bullet (indented line)
- if (current && raw.match(/^\s{2,}\S/)) {
- current += ' ' + raw.trim();
- continue;
- }
- // blank line ends a bullet
- if (raw.trim() === '' && current) {
- bullets.push(current);
- current = null;
- }
- }
- if (current) bullets.push(current);
- return bullets;
-}
-
-function stripBold(s) {
- return s.replace(/\*\*(.+?)\*\*/g, '$1');
-}
-
-function extractNamedRules(lines) {
- const rules = [];
- const seen = new Set();
-
- // Style A (Impeccable): "**The X Rule.** body body body" — can span lines.
- const joined = lines.join('\n');
- const inlineStart = /\*\*(The [^*]+?Rule)\.\*\*/g;
- const inlineMatches = [];
- let m;
- while ((m = inlineStart.exec(joined)) !== null) {
- inlineMatches.push({ name: m[1], start: m.index, end: inlineStart.lastIndex });
- }
- for (let i = 0; i < inlineMatches.length; i++) {
- const mm = inlineMatches[i];
- const bodyEnd = i + 1 < inlineMatches.length ? inlineMatches[i + 1].start : joined.length;
- const body = joined
- .slice(mm.end, bodyEnd)
- .replace(/\n##[^\n]*$/s, '')
- .replace(/\n###[^\n]*$/s, '')
- .trim();
- const name = stripBold(mm.name).trim();
- seen.add(name.toLowerCase());
- rules.push({ name, body: stripBold(body) });
- }
-
- // Style B (Stitch): `### The "X" Rule` or `### The X Fallback`, body is the
- // bullets/paragraphs until the next heading. Accept Rule / Fallback / Principle.
- for (let i = 0; i < lines.length; i++) {
- const h3 = lines[i].match(/^###\s+(.+?)\s*$/);
- if (!h3) continue;
- const headerName = stripBold(h3[1]).replace(/["“”]/g, '').trim();
- if (!/^The\b.*\b(Rule|Fallback|Principle)\b/i.test(headerName)) continue;
- if (seen.has(headerName.toLowerCase())) continue;
-
- const bodyLines = [];
- for (let j = i + 1; j < lines.length; j++) {
- if (/^##\s|^###\s/.test(lines[j])) break;
- bodyLines.push(lines[j]);
- }
- const body = stripBold(bodyLines.join('\n').replace(/\n+/g, ' ')).trim();
- if (body) {
- seen.add(headerName.toLowerCase());
- rules.push({ name: headerName, body });
- }
- }
-
- // Style C (Stitch bullet form): "* **The Layering Principle:** body"
- // Colon/period lives inside the bold, so match "**...**" then inspect.
- for (const b of collectBullets(lines)) {
- const mm = b.match(/^\*\*([^*]+?)\*\*\s*(.+)$/);
- if (!mm) continue;
- const nameRaw = mm[1].replace(/[.:]\s*$/, '').replace(/["“”]/g, '').trim();
- if (!/^The\b.+\b(Rule|Fallback|Principle)$/i.test(nameRaw)) continue;
- if (seen.has(nameRaw.toLowerCase())) continue;
- seen.add(nameRaw.toLowerCase());
- rules.push({ name: nameRaw, body: stripBold(mm[2]).trim() });
- }
-
- return rules;
-}
-
-// ---------- Per-section extractors ----------
-
-function extractOverview(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
- const northStar = text.match(/\*\*Creative North Star:\s*"([^"]+)"\*\*/);
- const keyChars = [];
- const keyCharMatch = text.match(/\*\*Key Characteristics:\*\*\s*\n([\s\S]+?)(?:\n##|\n###|$)/);
- if (keyCharMatch) {
- for (const line of keyCharMatch[1].split('\n')) {
- const m = line.match(/^\s*[-*]\s+(.+)$/);
- if (m) keyChars.push(stripBold(m[1].trim()));
- }
- }
-
- // Philosophy paragraphs: everything that isn't a rule header or key-char block
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) =>
- !p.startsWith('**Creative North Star') &&
- !p.startsWith('**Key Characteristics')
- );
-
- return {
- subtitle: section.subtitle,
- creativeNorthStar: northStar ? northStar[1] : null,
- philosophy: paragraphs,
- keyCharacteristics: keyChars,
- };
-}
-
-function extractColors(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ');
- const groups = [];
- const ROLE_KEYWORDS = /^(primary|secondary|tertiary|neutral|accent)\b/i;
-
- for (const sub of subs.slice(1)) {
- if (!sub.name || /Named Rules?/i.test(sub.name) || /^The\s/i.test(sub.name)) continue;
-
- const bullets = collectBullets(sub.lines);
- const parsed = bullets.map((b) => parseColorBullet(b)).filter(Boolean);
- if (parsed.length === 0) continue;
-
- // If every bullet starts with a role keyword (Primary/Secondary/...), promote
- // each bullet to its own group. Otherwise keep the subsection as the group.
- const allRoleBullets =
- parsed.length > 0 && parsed.every((p) => p.name && ROLE_KEYWORDS.test(p.name));
-
- if (allRoleBullets) {
- for (const p of parsed) {
- groups.push({ role: p.name, colors: [p] });
- }
- } else {
- groups.push({ role: sub.name, colors: parsed });
- }
- }
-
- // If the Colors section has no subsections at all (unlikely), fall back to
- // scanning the whole section as a flat bullet list.
- if (groups.length === 0) {
- const flat = collectBullets(section.lines)
- .map((b) => parseColorBullet(b))
- .filter(Boolean);
- if (flat.length) {
- for (const p of flat) {
- if (p.name && ROLE_KEYWORDS.test(p.name)) {
- groups.push({ role: p.name, colors: [p] });
- } else {
- const fallback = groups.find((g) => g.role === 'Palette');
- if (fallback) fallback.colors.push(p);
- else groups.push({ role: 'Palette', colors: [p] });
- }
- }
- }
- }
-
- return {
- subtitle: section.subtitle,
- description: description || null,
- groups,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function parseColorBullet(bullet) {
- const text = bullet.trim();
-
- // Case 1 (Impeccable): **Name** (value-with-maybe-nested-parens): description
- const bold = text.match(/^\*\*(.+?)\*\*\s*(.*)$/);
- if (bold && bold[2].startsWith('(')) {
- const value = extractParenGroup(bold[2]);
- if (value !== null) {
- const after = bold[2].slice(value.length + 2).trimStart();
- if (after.startsWith(':')) {
- return buildColor(bold[1], value, after.slice(1).trim());
- }
- }
- }
-
- // Case 2 (Stitch): **Name (values):** description — value embedded in bold.
- const stitch = text.match(/^\*\*([^*]+?)\s*\(([^)]+)\):\*\*\s*(.*)$/);
- if (stitch) {
- return buildColor(stitch[1].trim(), stitch[2], stitch[3]);
- }
-
- // Case 3: bullet without bold, just hex/oklch inside.
- const values = collectColorValues(text);
- if (values.length) {
- return buildColor(null, values.join(' to '), text);
- }
- return null;
-}
-
-function extractParenGroup(s) {
- if (s[0] !== '(') return null;
- let depth = 0;
- for (let i = 0; i < s.length; i++) {
- if (s[i] === '(') depth++;
- else if (s[i] === ')') {
- depth--;
- if (depth === 0) return s.slice(1, i);
- }
- }
- return null;
-}
-
-function buildColor(name, rawValue, description) {
- const values = collectColorValues(rawValue);
- const primary = values[0] ?? rawValue.trim();
- return {
- name: name ? stripBold(name).trim() : null,
- value: primary,
- valueRange: values.length > 1 ? values : null,
- format: detectFormat(primary),
- description: stripBold(description || '').trim() || null,
- };
-}
-
-function collectColorValues(s) {
- const out = [];
- s.replace(HEX_RE, (v) => {
- out.push(v);
- return v;
- });
- s.replace(OKLCH_RE, (v) => {
- out.push(v);
- return v;
- });
- return out;
-}
-
-function detectFormat(v) {
- if (!v) return 'unknown';
- if (v.startsWith('#')) return 'hex';
- if (/^oklch/i.test(v)) return 'oklch';
- if (/^rgb/i.test(v)) return 'rgb';
- return 'unknown';
-}
-
-function scanInlineColors(lines) {
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '');
- const color = parseColorBullet(trimmed);
- if (color) out.push(color);
- }
- return out;
-}
-
-function parseStitchInlineGroups(lines) {
- // Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
- // Each bullet IS its own role. Group them under the spoken role name.
- const out = [];
- for (const line of lines) {
- if (!/^\s*[-*]\s/.test(line)) continue;
- const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
- const m = trimmed.match(
- /^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
- );
- if (m) {
- const role = m[1];
- const color = buildColor(role, m[2], m[3]);
- out.push({ role, colors: [color] });
- }
- }
- return out;
-}
-
-function extractTypography(section) {
- if (!section) return null;
- const text = section.lines.join('\n');
-
- const fonts = {};
- // Pattern A: **Display Font:** Family (with fallback)
- const fontLineRe = /\*\*([\w\s/]+?)Font:\*\*\s*([^\n(]+?)(?:\s*\(with\s+([^)]+)\))?\s*$/gm;
- let fm;
- while ((fm = fontLineRe.exec(text)) !== null) {
- const rawRole = fm[1].trim().toLowerCase().replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || 'display';
- fonts[role] = {
- family: fm[2].trim(),
- fallback: fm[3] ? fm[3].trim() : null,
- };
- }
-
- // Pattern B (Stitch): * **Display & Headlines (Noto Serif):** description
- if (Object.keys(fonts).length === 0) {
- const stitchRe = /\*\*([\w\s&/]+?)\s*\(([^)]+)\):\*\*\s*(.+)/g;
- let sm;
- while ((sm = stitchRe.exec(text)) !== null) {
- const rawRole = sm[1]
- .trim()
- .toLowerCase()
- .replace(/\s*&\s*/g, '-')
- .replace(/\s+/g, '-');
- const role = normalizeFontRole(rawRole) || rawRole;
- fonts[role] = { family: sm[2].trim(), fallback: null, purpose: sm[3].trim() };
- }
- }
-
- // Character paragraph — either a **Character:** label, or fall back to the
- // first free paragraph under the section header (Stitch style).
- const characterMatch = text.match(/\*\*Character:\*\*\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\n|\n###|\n##|$)/);
- let character = characterMatch ? characterMatch[1].replace(/\n/g, ' ').trim() : null;
- if (!character) {
- const paragraphs = collectParagraphs(section.lines).filter(
- (p) => !/^\*\*[\w\s/&]+Font/i.test(p) && !/^\*\*[\w\s/&]+\([^)]+\)/.test(p)
- );
- if (paragraphs.length) character = paragraphs[0];
- }
-
- // Hierarchy bullets under ### Hierarchy
- const subs = splitSubsections(section.lines);
- let hierarchy = [];
- const hierSub = subs.find((s) => s.name && /hierarch/i.test(s.name));
- if (hierSub) {
- const bullets = collectBullets(hierSub.lines);
- hierarchy = bullets.map(parseTypeBullet).filter(Boolean);
- }
-
- return {
- subtitle: section.subtitle,
- fonts,
- character,
- hierarchy,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function normalizeFontRole(raw) {
- // Canonical roles the panel cares about: display, body, label, mono.
- // Stitch often writes compound roles like "display-&-headlines" or "ui-&-body"
- // — collapse them to the first canonical role present.
- const tokens = raw.split(/[-/&\s]+/).filter(Boolean);
- const priority = ['display', 'headline', 'body', 'ui', 'label', 'mono'];
- const canonical = { headline: 'display', ui: 'body' };
- for (const p of priority) {
- if (tokens.includes(p)) return canonical[p] || p;
- }
- return null;
-}
-
-function parseTypeBullet(bullet) {
- // - **Display** (family, weight 300, italic, clamp(...), line-height 1): purpose
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(([^)]+)\):\s*(.*)$/);
- if (!m) return null;
- const name = m[1].trim();
- const specs = m[2].split(',').map((s) => s.trim());
- return {
- name,
- specs,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractElevation(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
-
- const description = collectParagraphs(subs[0].lines).join(' ') || null;
-
- const shadows = [];
- const seen = new Set();
- const dedupe = (entry) => {
- const key = (entry.name || '') + '::' + entry.value;
- if (seen.has(key)) return;
- seen.add(key);
- shadows.push(entry);
- };
-
- for (const b of collectBullets(section.lines)) {
- const parsed = parseShadowBullet(b);
- if (parsed) dedupe(parsed);
- }
-
- // Fallback: extract shadows written inline in prose. Stitch style is
- // "...use an extra-diffused shadow: `box-shadow: 0 12px 40px rgba(...)`."
- for (const p of collectParagraphs(section.lines)) {
- for (const inline of extractInlineShadows(p)) dedupe(inline);
- }
- for (const b of collectBullets(section.lines)) {
- for (const inline of extractInlineShadows(b)) dedupe(inline);
- }
-
- return {
- subtitle: section.subtitle,
- description,
- shadows,
- rules: extractNamedRules(section.lines),
- };
-}
-
-function extractInlineShadows(text) {
- // Find `box-shadow: ...` anywhere in prose and capture the value. Work on the
- // raw string so it handles both backtick-fenced and unfenced variants.
- const out = [];
- const re = /box-shadow\s*:\s*([^`;\n]+)/gi;
- let m;
- while ((m = re.exec(text)) !== null) {
- const value = m[1].replace(/[`.)]+$/, '').trim();
- if (!value) continue;
- // Name heuristic: the noun immediately before the shadow phrase.
- // e.g. "an extra-diffused shadow: ..." -> "extra-diffused shadow"
- const before = text.slice(0, m.index);
- const nameMatch = before.match(/\b([A-Za-z][A-Za-z\- ]{2,40})\s+shadow\b[^A-Za-z0-9]*$/i);
- let name = null;
- if (nameMatch) {
- const stripped = nameMatch[1]
- .replace(/^(?:use|using|apply|applying|is|are|looks? like)\s+/i, '')
- .replace(/^(?:a|an|the)\s+/i, '')
- .trim();
- if (stripped) {
- name =
- stripped.charAt(0).toUpperCase() + stripped.slice(1) + ' shadow';
- }
- }
- out.push({
- name,
- value,
- purpose: null,
- });
- }
- return out;
-}
-
-function parseShadowBullet(bullet) {
- // - **Name** (`box-shadow: value`): purpose
- // - **Name** (`value`): purpose
- // Only accept if the paren content looks like a shadow value (contains px,
- // rem, rgba, or box-shadow). This filters out `**Rule Name:**` bullets.
- const m = bullet.match(/^\*\*(.+?)\*\*\s*\(`?([^`]+?)`?\):\s*(.*)$/);
- if (!m) return null;
- const rawValue = m[2].replace(/^box-shadow:\s*/i, '').trim();
- const looksLikeShadow =
- /box-shadow|rgba?\(|\bpx\b|\brem\b|^-?\d+\s/i.test(rawValue) &&
- /\d/.test(rawValue);
- if (!looksLikeShadow) return null;
- const name = stripBold(m[1]).trim();
- return {
- name,
- value: rawValue,
- purpose: stripBold(m[3] || '').trim() || null,
- };
-}
-
-function extractComponents(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const components = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
-
- const bullets = collectBullets(sub.lines);
- const paragraphs = collectParagraphs(sub.lines);
-
- const variants = [];
- const properties = {};
-
- for (const b of bullets) {
- // - **Key:** value
- const m = b.match(/^\*\*(.+?):?\*\*:?\s*(.+)$/);
- if (m) {
- const key = stripBold(m[1]).trim();
- const value = stripBold(m[2]).trim();
- // Heuristic: "Primary", "Secondary", "Hover", "Focus" etc are variants;
- // "Shape", "Background", "Padding" are properties.
- if (/^(primary|secondary|tertiary|ghost|hover|focus|active|disabled|default|error|selected|unselected|state)$/i.test(key.split(/[\s/]/)[0])) {
- variants.push({ name: key, description: value });
- } else {
- properties[key.toLowerCase()] = value;
- }
- }
- }
-
- components.push({
- name: sub.name,
- description: paragraphs.join(' ') || null,
- properties,
- variants,
- });
- }
-
- return {
- subtitle: section.subtitle,
- components,
- };
-}
-
-function extractDosDonts(section) {
- if (!section) return null;
- const subs = splitSubsections(section.lines);
- const dos = [];
- const donts = [];
-
- for (const sub of subs.slice(1)) {
- if (!sub.name) continue;
- const subName = normalizeApostrophes(sub.name);
- const bullets = collectBullets(sub.lines).map((b) => stripBold(b).trim());
- if (/^do'?t?:?$/i.test(subName) || /^do:?$/i.test(subName)) {
- dos.push(...bullets);
- } else if (/^don'?t:?$/i.test(subName)) {
- donts.push(...bullets);
- }
- }
-
- // Classify by bullet prefix as a backup (catches loose bullets outside H3 wrappers)
- for (const b of collectBullets(section.lines)) {
- const stripped = normalizeApostrophes(stripBold(b).trim());
- if (/^don'?t\b/i.test(stripped)) {
- if (!donts.some((d) => normalizeApostrophes(d) === stripped)) donts.push(stripped);
- } else if (/^do\b/i.test(stripped)) {
- if (!dos.some((d) => normalizeApostrophes(d) === stripped)) dos.push(stripped);
- }
- }
-
- return { dos, donts };
-}
-
-// ---------- Coverage assessment ----------
-
-function assessCoverage(model) {
- const report = {};
-
- report.overview = model.overview
- ? {
- northStar: Boolean(model.overview.creativeNorthStar),
- philosophy: model.overview.philosophy.length > 0,
- keyCharacteristics: model.overview.keyCharacteristics.length,
- }
- : 'missing';
-
- report.colors = model.colors
- ? {
- groups: model.colors.groups.length,
- totalColors: model.colors.groups.reduce((n, g) => n + g.colors.length, 0),
- rules: model.colors.rules.length,
- }
- : 'missing';
-
- report.typography = model.typography
- ? {
- fonts: Object.keys(model.typography.fonts).length,
- hierarchyEntries: model.typography.hierarchy.length,
- character: Boolean(model.typography.character),
- rules: model.typography.rules.length,
- }
- : 'missing';
-
- report.elevation = model.elevation
- ? {
- shadows: model.elevation.shadows.length,
- rules: model.elevation.rules.length,
- description: Boolean(model.elevation.description),
- }
- : 'missing';
-
- report.components = model.components
- ? {
- count: model.components.components.length,
- variantTotal: model.components.components.reduce((n, c) => n + c.variants.length, 0),
- }
- : 'missing';
-
- report.dosDonts = model.dosDonts
- ? {
- dos: model.dosDonts.dos.length,
- donts: model.dosDonts.donts.length,
- }
- : 'missing';
-
- return report;
-}
-
-// ---------- Main ----------
-
-export function parseDesignMd(md) {
- const { frontmatter, body } = parseFrontmatter(md);
- const { title, sections } = splitSections(body);
- return {
- schemaVersion: 2,
- title,
- frontmatter,
- overview: extractOverview(sections['Overview']),
- colors: extractColors(sections['Colors']),
- typography: extractTypography(sections['Typography']),
- elevation: extractElevation(sections['Elevation']),
- components: extractComponents(sections['Components']),
- dosDonts: extractDosDonts(sections["Do's and Don'ts"]),
- };
-}
-
-export { assessCoverage };
@@ -1,198 +0,0 @@
-/**
- * Scan a project tree for Content-Security-Policy signals and classify the
- * shape so the agent knows which patch template to propose.
- *
- * Used at first-time `live.mjs` setup. Mechanical (grep-based) — no network,
- * no dev server, no JS evaluation. The classification drives a user-facing
- * consent prompt; the agent does the actual patch writing.
- *
- * Shapes are named by patch mechanism, not framework origin:
- * - "append-arrays": CSP defined as structured directive arrays. Patch
- * appends a dev-only localhost entry. Covers:
- * - Monorepo helpers with additional*Src options
- * (e.g. createBaseNextConfig for Next)
- * - SvelteKit kit.csp.directives
- * - nuxt-security module's contentSecurityPolicy
- * - "append-string": CSP built as a literal value string. Patch splices
- * a dev-only token into script-src and connect-src.
- * Covers:
- * - Inline Next.js headers() with CSP string
- * - Nuxt routeRules / nitro.routeRules CSP headers
- * - "middleware": CSP set dynamically in middleware.{ts,js}.
- * Detected but not auto-patched in v1.
- * - "meta-tag": <meta http-equiv="Content-Security-Policy"> in
- * layout files. Detected but not auto-patched in v1.
- * - null: no CSP signals found; no patch needed.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const SKIP_DIRS = new Set([
- 'node_modules',
- '.git',
- '.next',
- '.turbo',
- '.svelte-kit',
- '.nuxt',
- '.astro',
- 'dist',
- 'build',
- 'out',
- '.vercel',
-]);
-
-const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.tsx', '.jsx']);
-const LAYOUT_EXTS = new Set(['.tsx', '.jsx', '.astro', '.vue', '.svelte', '.html']);
-const MAX_DEPTH = 6;
-const MAX_READ_BYTES = 64 * 1024;
-
-// append-arrays signals: CSP expressed as structured directive arrays
-const MONOREPO_HELPER_SIGNALS = [
- /\bbuildCSPConfig\b/,
- /\bbuildSecurityHeaders\b/,
- /\badditionalScriptSrc\b/,
- /\badditionalConnectSrc\b/,
- /\bcreateBaseNextConfig\b/,
-];
-const SVELTEKIT_CSP_SIGNALS = [
- /\bkit\s*:/,
- /\bcsp\s*:/,
- /\bdirectives\s*:/,
-];
-const NUXT_SECURITY_SIGNALS = [
- /['"]nuxt-security['"]/,
- /\bcontentSecurityPolicy\b/,
-];
-
-// append-string signals: CSP written as a literal value string
-const INLINE_HEADER_SIGNALS = [
- /["']Content-Security-Policy["']/i,
- /\bscript-src\b/,
- /\bconnect-src\b/,
-];
-const NUXT_ROUTE_RULES_SIGNALS = [
- /\brouteRules\b/,
- /Content-Security-Policy/i,
- /\bscript-src\b/,
-];
-
-const MIDDLEWARE_HINT = /headers\.set\(\s*["']Content-Security-Policy["']/i;
-const META_TAG_HINT = /http-equiv\s*=\s*["']Content-Security-Policy["']/i;
-
-/**
- * @param {string} cwd Project root.
- * @returns {{ shape: string|null, signals: string[] }}
- */
-export function detectCsp(cwd = process.cwd()) {
- const hits = { appendArrays: [], appendString: [], middleware: [], metaTag: [] };
-
- walk(cwd, cwd, 0, (absPath, relPath, body) => {
- const ext = path.extname(absPath);
- const base = path.basename(absPath).toLowerCase();
- const isConfig = (name) =>
- new RegExp('(^|/)' + name + '\\.config\\.').test(relPath);
-
- // === append-arrays candidates ===
-
- // Monorepo CSP helper: packages/*/src/.../(config|security)/*
- if (SCAN_EXTS.has(ext) &&
- /packages\/[^/]+\/src\/.*(config|next-config|security)/.test(relPath) &&
- MONOREPO_HELPER_SIGNALS.some((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // SvelteKit kit.csp.directives
- if (SCAN_EXTS.has(ext) && isConfig('svelte') &&
- SVELTEKIT_CSP_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // Nuxt nuxt-security module
- if (SCAN_EXTS.has(ext) && isConfig('nuxt') &&
- NUXT_SECURITY_SIGNALS.every((re) => re.test(body))) {
- hits.appendArrays.push(relPath);
- return;
- }
-
- // === append-string candidates ===
-
- // Inline headers in Next/Nuxt/SvelteKit/Astro/Vite config
- if (SCAN_EXTS.has(ext) &&
- /(^|\/)(next|nuxt|vite|astro|svelte)\.config\./.test(relPath) &&
- INLINE_HEADER_SIGNALS.every((re) => re.test(body))) {
- // Nuxt routeRules is a sub-shape of append-string; we already covered
- // nuxt-security above via return, so any remaining Nuxt CSP match here
- // is a route-rules / inline-headers case. Either way, same patch
- // mechanism.
- hits.appendString.push(relPath);
- return;
- }
-
- // === detect-only shapes ===
-
- if ((base === 'middleware.ts' || base === 'middleware.js' || base === 'middleware.mjs') &&
- MIDDLEWARE_HINT.test(body)) {
- hits.middleware.push(relPath);
- }
-
- if (LAYOUT_EXTS.has(ext) && META_TAG_HINT.test(body)) {
- hits.metaTag.push(relPath);
- }
- });
-
- // Priority: append-arrays > append-string > middleware > meta-tag.
- // Structured patches are safer than string splices; runtime and HTML
- // injection patches are less reliable and v1 doesn't auto-apply them.
- if (hits.appendArrays.length > 0) {
- return { shape: 'append-arrays', signals: hits.appendArrays };
- }
- if (hits.appendString.length > 0) {
- return { shape: 'append-string', signals: hits.appendString };
- }
- if (hits.middleware.length > 0) {
- return { shape: 'middleware', signals: hits.middleware };
- }
- if (hits.metaTag.length > 0) {
- return { shape: 'meta-tag', signals: hits.metaTag };
- }
- return { shape: null, signals: [] };
-}
-
-function walk(root, dir, depth, visit) {
- if (depth > MAX_DEPTH) return;
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
-
- for (const entry of entries) {
- const abs = path.join(dir, entry.name);
- if (entry.isDirectory()) {
- if (SKIP_DIRS.has(entry.name)) continue;
- walk(root, abs, depth + 1, visit);
- continue;
- }
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name);
- if (!SCAN_EXTS.has(ext) && !LAYOUT_EXTS.has(ext)) continue;
- let body;
- try {
- const fd = fs.openSync(abs, 'r');
- try {
- const buf = Buffer.alloc(MAX_READ_BYTES);
- const n = fs.readSync(fd, buf, 0, MAX_READ_BYTES, 0);
- body = buf.slice(0, n).toString('utf-8');
- } finally { fs.closeSync(fd); }
- } catch { continue; }
- visit(abs, path.relative(root, abs), body);
- }
-}
-
-// CLI mode
-const _running = process.argv[1];
-if (_running?.endsWith('detect-csp.mjs') || _running?.endsWith('detect-csp.mjs/')) {
- const result = detectCsp(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
@@ -1,21 +0,0 @@
-#!/usr/bin/env node
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { pathToFileURL, fileURLToPath } from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const candidates = [
- path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
-];
-const detectorPath = candidates.find(p => fs.existsSync(p));
-
-if (!detectorPath) {
- process.stderr.write('Error: bundled detector not found.\n');
- process.exit(1);
-}
-
-const { detectCli } = await import(pathToFileURL(detectorPath));
-
-await detectCli();
@@ -1,1688 +0,0 @@
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
@@ -1,232 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
-import { detectHtml } from '../engines/static-html/detect-html.mjs';
-import { detectText } from '../engines/regex/detect-text.mjs';
-import {
- HTML_EXTENSIONS,
- buildImportGraph,
- detectFrameworkConfig,
- isPortListening,
- walkDir,
-} from '../node/file-system.mjs';
-
-// ---------------------------------------------------------------------------
-// Output formatting
-// ---------------------------------------------------------------------------
-
-function formatFindings(findings, jsonMode) {
- if (jsonMode) return JSON.stringify(findings, null, 2);
-
- const grouped = {};
- for (const f of findings) {
- if (!grouped[f.file]) grouped[f.file] = [];
- grouped[f.file].push(f);
- }
- const out = [];
- for (const [file, items] of Object.entries(grouped)) {
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
- out.push(`\n${file}${importNote}`);
- for (const item of items) {
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
- out.push(` → ${item.description}`);
- }
- }
- out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
- return out.join('\n');
-}
-
-// ---------------------------------------------------------------------------
-// Stdin handling
-// ---------------------------------------------------------------------------
-
-async function handleStdin() {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- const input = Buffer.concat(chunks).toString('utf-8');
- try {
- const parsed = JSON.parse(input);
- const fp = parsed?.tool_input?.file_path;
- if (fp && fs.existsSync(fp)) {
- return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
- ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
- }
- } catch { /* not JSON */ }
- return detectText(input, '<stdin>');
-}
-
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-async function confirm(question) {
- const rl = (await import('node:readline')).default.createInterface({
- input: process.stdin, output: process.stderr,
- });
- return new Promise((resolve) => {
- rl.question(`${question} [Y/n] `, (answer) => {
- rl.close();
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
- });
- });
-}
-
-function printUsage() {
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
-
-Scan files or URLs for UI anti-patterns and design quality issues.
-
-Options:
- --fast Regex-only mode (skip static HTML/CSS analysis, faster but misses linked stylesheets)
- --json Output results as JSON
- --help Show this help message
-
-Detection modes:
- HTML files Static HTML/CSS analysis (default, catches linked CSS)
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
- URLs Puppeteer full browser rendering (auto-detected)
- --fast Forces regex for all files
-
-Examples:
- impeccable detect src/
- impeccable detect index.html
- impeccable detect https://example.com
- impeccable detect --fast --json .`);
-}
-
-async function detectCli() {
- let args = process.argv.slice(2).map(arg => {
- if (arg === '-json') return '--json';
- if (arg === '-fast') return '--fast';
- return arg;
- });
- if (args[0] === 'detect') args = args.slice(1);
- const jsonMode = args.includes('--json');
- const helpMode = args.includes('--help');
- const fastMode = args.includes('--fast');
- const targets = args.filter(a => !a.startsWith('--'));
-
- if (helpMode) { printUsage(); process.exit(0); }
-
- let allFindings = [];
-
- if (!process.stdin.isTTY && targets.length === 0) {
- allFindings = await handleStdin();
- } else {
- const paths = targets.length > 0 ? targets : [process.cwd()];
- const urlTargetCount = paths.filter(target => /^https?:\/\//i.test(target)).length;
- const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
-
- try {
- for (const target of paths) {
- if (/^https?:\/\//i.test(target)) {
- try {
- const scanner = browserDetector
- ? (url) => browserDetector.detectUrl(url)
- : (url) => detectUrl(url);
- allFindings.push(...await scanner(target));
- } catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
- continue;
- }
-
- const resolved = path.resolve(target);
- let stat;
- try { stat = fs.statSync(resolved); }
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
-
- if (stat.isDirectory()) {
- // Check for framework dev server config (skip in JSON mode to avoid polluting output)
- if (!jsonMode) {
- const fwConfig = detectFrameworkConfig(resolved);
- if (fwConfig) {
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
- if (probe.listening && probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
- `For more accurate results, scan the running site:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- } else if (probe.listening && !probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
- );
- } else {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Start the dev server and scan via URL for best results:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- }
- }
- }
-
- const files = walkDir(resolved);
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
-
- // Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
- if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
- process.stderr.write(
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
- `Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
- `Use --fast to skip static HTML/CSS analysis, or target a specific subdirectory.\n`
- );
- const ok = await confirm('Continue?');
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
- }
-
- // Build import graph for multi-file awareness
- const graph = buildImportGraph(files);
- // Build reverse map: file -> set of files that import it
- const importedByMap = new Map();
- for (const [importer, imports] of graph) {
- for (const imported of imports) {
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
- importedByMap.get(imported).add(importer);
- }
- }
-
- for (const file of files) {
- const ext = path.extname(file).toLowerCase();
- let fileFindings;
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- fileFindings = await detectHtml(file);
- } else {
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
- }
- // Annotate findings with import context
- const importers = importedByMap.get(file);
- if (importers && importers.size > 0) {
- const importerNames = [...importers].map(f => path.basename(f));
- for (const f of fileFindings) {
- f.importedBy = importerNames;
- }
- }
- allFindings.push(...fileFindings);
- }
- } else if (stat.isFile()) {
- const ext = path.extname(resolved).toLowerCase();
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- allFindings.push(...await detectHtml(resolved));
- } else {
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
- }
- }
- }
- } finally {
- if (browserDetector) await browserDetector.close();
- }
- }
-
- if (allFindings.length > 0) {
- if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
- else process.stderr.write(formatFindings(allFindings, false) + '\n');
- process.exit(2);
- }
- if (jsonMode) process.stdout.write('[]\n');
- process.exit(0);
-}
-
-export { formatFindings, handleStdin, confirm, printUsage, detectCli };
@@ -1,4030 +0,0 @@
-/**
- * Anti-Pattern Browser Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * GENERATED -- do not edit. Source: cli/engine/browser/injected/index.mjs
- * Rebuild: node scripts/build-browser-detector.js
- *
- * Usage: <script src="detect-antipatterns-browser.js"></script>
- * Re-scan: window.impeccableScan()
- */
-(function () {
-if (typeof window === 'undefined') return;
-// --- cli/engine/shared/constants.mjs ---
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-// --- cli/engine/registry/antipatterns.mjs ---
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-// --- cli/engine/shared/color.mjs ---
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-// --- cli/engine/rules/checks.mjs ---
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-// --- cli/engine/browser/injected/index.mjs ---
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
-
-})();
@@ -1,43 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Anti-Pattern Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * Public API facade. Runtime engines live under cli/engine/engines/.
- */
-
-import { detectCli } from './cli/main.mjs';
-
-export { ANTIPATTERNS, RULE_ENGINE_SUPPORT, getAntipattern, getRulesForCategory, getRuleEngineSupport } from './registry/antipatterns.mjs';
-export { SAFE_TAGS, BORDER_SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS, KNOWN_SERIF_FONTS } from './shared/constants.mjs';
-export { isNeutralColor, parseRgb, relativeLuminance, contrastRatio, parseGradientColors, hasChroma, getHue, colorToHex } from './shared/color.mjs';
-export { isFullPage } from './shared/page.mjs';
-export {
- checkElementBorders,
- checkElementMotion,
- checkElementGlow,
- checkPageTypography,
- checkPageLayout,
- checkHtmlPatterns,
-} from './rules/checks.mjs';
-export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
-export { detectHtml } from './engines/static-html/detect-html.mjs';
-export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
-export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
-export {
- walkDir,
- SCANNABLE_EXTENSIONS,
- SKIP_DIRS,
- buildImportGraph,
- resolveImport,
- detectFrameworkConfig,
- isPortListening,
- FRAMEWORK_CONFIGS,
-} from './node/file-system.mjs';
-export { formatFindings, detectCli } from './cli/main.mjs';
-
-const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
-if (isMainModule) detectCli();
@@ -1,251 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { finding } from '../../findings.mjs';
-import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
-
-async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
- if (options?.visualContrast === false) return [];
- const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : 12;
- const scrollOffscreen = options?.visualContrastScrollOffscreen !== false;
- const existingLowContrastSelectors = new Set(
- serializedGroups
- .filter(group => group.findings?.some(f => f.type === 'low-contrast'))
- .map(group => group.selector)
- .filter(Boolean)
- );
-
- let browserAnalyses = [];
- const findings = [];
- if (options?.visualContrastBrowser !== false) {
- const browserFindings = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'browser-fallback',
- target,
- }, async () => {
- browserAnalyses = await page.evaluate(async ({ maxCandidates, scrollOffscreen }) => {
- if (typeof window.impeccableAnalyzeVisualContrast !== 'function') return [];
- return window.impeccableAnalyzeVisualContrast({ maxCandidates, scrollOffscreen });
- }, { maxCandidates, scrollOffscreen });
- return browserAnalyses
- .filter(result => result.finding && !existingLowContrastSelectors.has(result.selector))
- .map(result => result.finding);
- });
- findings.push(...browserFindings);
- }
-
- let candidates = browserAnalyses.length > 0 ? browserAnalyses : [];
- if (candidates.length === 0) {
- candidates = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'collect-candidates',
- target,
- }, () => page.evaluate(({ maxCandidates }) => {
- if (typeof window.impeccableCollectVisualContrastCandidates !== 'function') return [];
- return window.impeccableCollectVisualContrastCandidates({ maxCandidates });
- }, { maxCandidates }));
- }
-
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const browserResolvedSelectors = new Set(
- browserAnalyses
- .filter(result => result.status === 'fail' || result.status === 'pass')
- .map(result => result.selector)
- .filter(Boolean)
- );
- const filtered = candidates.filter(candidate =>
- !existingLowContrastSelectors.has(candidate.selector) &&
- !browserResolvedSelectors.has(candidate.selector)
- );
- if (options?.visualContrastPixel === false) return findings;
- for (const candidate of filtered) {
- const result = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'pixel-diff',
- target,
- }, async () => {
- const finding = await captureVisualContrastCandidate(page, candidate, viewport);
- return finding ? [finding] : [];
- });
- findings.push(...result);
- }
- return findings;
-}
-
-// ---------------------------------------------------------------------------
-// Puppeteer detection (for URLs)
-// ---------------------------------------------------------------------------
-
-async function detectUrl(url, options = {}) {
- const profile = options?.profile;
- const waitUntil = options?.waitUntil || 'networkidle0';
- const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const externalBrowser = options?.browser || null;
- let puppeteer;
- if (!externalBrowser) {
- try {
- puppeteer = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'import-puppeteer',
- target: url,
- }, () => import('puppeteer'));
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- }
-
- // Read the browser detection script — reuse it instead of reimplementing
- const browserScriptPath = path.resolve(
- path.dirname(fileURLToPath(import.meta.url)),
- '..',
- '..',
- 'detect-antipatterns-browser.js'
- );
- let browserScript;
- try {
- browserScript = profileStep(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'read-browser-script',
- target: url,
- }, () => fs.readFileSync(browserScriptPath, 'utf-8'));
- } catch {
- throw new Error(`Browser script not found at ${browserScriptPath}`);
- }
-
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
- // running in CI; local users keep the default hardened launch.
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
- const browser = externalBrowser || await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'launch-browser',
- target: url,
- }, () => puppeteer.default.launch({ headless: true, args: launchArgs }));
- const page = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'new-page',
- target: url,
- }, () => browser.newPage());
- let results = [];
- try {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'set-viewport',
- target: url,
- }, () => page.setViewport(viewport));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: `goto:${waitUntil}`,
- target: url,
- }, () => page.goto(url, { waitUntil, timeout: 30000 }));
- if (settleMs > 0) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'settle',
- target: url,
- }, () => new Promise(resolve => setTimeout(resolve, settleMs)));
- }
-
- // Inject the browser detection script and collect results
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'configure-pure-detect',
- target: url,
- }, () => page.evaluate(() => {
- window.__IMPECCABLE_CONFIG__ = {
- ...(window.__IMPECCABLE_CONFIG__ || {}),
- autoScan: false,
- };
- }));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'inject-browser-script',
- target: url,
- }, () => page.evaluate(browserScript));
- let serializedGroups = [];
- results = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'browser-scan',
- target: url,
- }, async () => {
- serializedGroups = await page.evaluate(() => {
- if (!window.impeccableDetect) return [];
- return window.impeccableDetect({ decorate: false, serialize: true });
- });
- return serializedGroups.flatMap(({ findings }) =>
- findings.map(f => ({ id: f.type, snippet: f.detail }))
- );
- });
- const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
- results.push(...visualFindings);
- } finally {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-page',
- target: url,
- }, () => page.close().catch(() => {}));
- if (!externalBrowser) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-browser',
- target: url,
- }, () => browser.close());
- }
- }
- return results.map(f => finding(f.id, url, f.snippet));
-}
-
-async function createBrowserDetector(options = {}) {
- let puppeteer;
- try {
- puppeteer = await import('puppeteer');
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- const launchArgs = options.launchArgs || (process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : []);
- const browser = options.browser || await puppeteer.default.launch({
- headless: options.headless ?? true,
- args: launchArgs,
- });
- const ownsBrowser = !options.browser;
- const defaults = {
- waitUntil: options.waitUntil || 'load',
- settleMs: Number.isFinite(options.settleMs) ? options.settleMs : 100,
- viewport: options.viewport || { width: 1280, height: 800 },
- };
- return {
- browser,
- async detectUrl(url, scanOptions = {}) {
- return detectUrl(url, {
- ...defaults,
- ...scanOptions,
- browser,
- });
- },
- async close() {
- if (ownsBrowser) await browser.close().catch(() => {});
- },
- };
-}
-
-export { runVisualContrastFallback, detectUrl, createBrowserDetector };
@@ -1,420 +0,0 @@
-import { GENERIC_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep } from '../../profile/profiler.mjs';
-
-// ---------------------------------------------------------------------------
-// Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
-// ---------------------------------------------------------------------------
-
-const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
-const hasBorderRadius = (line) => /border-radius/i.test(line);
-const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
-
-function isNeutralBorderColor(str) {
- const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
- if (!m) return false;
- const c = m[1].toLowerCase();
- if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
- const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
- if (hex) {
- const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
- if (shex) {
- const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- return false;
-}
-
-const REGEX_MATCHERS = [
- // --- Side-tab ---
- { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
- test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
- test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
- fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
- { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
- test: (m) => +m[1] >= 3,
- fmt: (m) => m[0] },
- // --- Border accent on rounded ---
- { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
- test: (m, line) => hasRounded(line) && +m[1] >= 1,
- fmt: (m) => m[0] },
- { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
- fmt: (m) => m[0] },
- // --- Overused font ---
- { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
- test: () => true,
- fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
- // --- Pure black background ---
- { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Gradient text ---
- { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
- test: (m, line) => /gradient/i.test(line),
- fmt: () => 'background-clip: text + gradient' },
- // --- Gradient text (Tailwind) ---
- { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
- test: (m, line) => /\bbg-gradient-to-/i.test(line),
- fmt: () => 'bg-clip-text + bg-gradient' },
- // --- Tailwind pure black background ---
- { id: 'pure-black-white', regex: /\bbg-black\b/g,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Tailwind gray on colored bg ---
- { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
- test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
- fmt: (m, line) => { const bg = line.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/); return `${m[0]} on ${bg?.[0] || '?'}`; } },
- // --- Tailwind AI palette ---
- { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
- fmt: (m) => `${m[0]} on heading` },
- { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
- fmt: (m) => `${m[0]} gradient` },
- // --- Bounce/elastic easing ---
- { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
- test: () => true,
- fmt: () => 'animate-bounce (Tailwind)' },
- { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
- test: (m) => {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
- },
- fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
- // --- Layout property transition ---
- { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition: ${found ? found.join(', ') : m[1].trim()}`;
- } },
- { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
- } },
-];
-
-const REGEX_ANALYZERS = [
- // Single font
- (content, filePath) => {
- const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
- const fonts = new Set();
- let m;
- while ((m = fontFamilyRe.exec(content)) !== null) {
- for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
- }
- }
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- while ((m = gfRe.exec(content)) !== null) {
- for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
- }
- if (fonts.size !== 1 || content.split('\n').length < 20) return [];
- const name = [...fonts][0];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
- return [finding('single-font', filePath, `only font used is ${name}`, line)];
- },
- // Flat type hierarchy
- (content, filePath) => {
- const sizes = new Set();
- const REM = 16;
- let m;
- const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
- while ((m = sizeRe.exec(content)) !== null) {
- const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
- if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
- }
- const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
- while ((m = clampRe.exec(content)) !== null) {
- sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
- sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
- }
- const TW = { 'text-xs': 12, 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24, 'text-3xl': 30, 'text-4xl': 36, 'text-5xl': 48, 'text-6xl': 60, 'text-7xl': 72, 'text-8xl': 96, 'text-9xl': 128 };
- for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
- if (sizes.size < 3) return [];
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio >= 2.0) return [];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (/font-size/i.test(lines[i]) || /\btext-(?:xs|sm|base|lg|xl|\d)/i.test(lines[i])) { line = i + 1; break; } }
- return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
- },
- // Monotonous spacing (regex)
- (content, filePath) => {
- const vals = [];
- let m;
- const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
- const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
- const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
- const rounded = vals.map(v => Math.round(v / 4) * 4);
- if (rounded.length < 10) return [];
- const counts = {};
- for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const pct = maxCount / rounded.length;
- const unique = [...new Set(rounded)].filter(v => v > 0);
- if (pct <= 0.6 || unique.length > 3) return [];
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
- },
- // Everything centered (regex)
- (content, filePath) => {
- const lines = content.split('\n');
- let centered = 0, total = 0;
- for (const line of lines) {
- if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
- total++;
- if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
- }
- }
- if (total < 5 || centered / total <= 0.7) return [];
- return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
- },
- // Dark glow (page-level: dark bg + colored box-shadow with blur)
- (content, filePath) => {
- // Check if page has a dark background
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
- if (!hasDarkBg) return [];
-
- // Check for colored box-shadow with blur > 4px
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let m;
- while ((m = shadowRe.exec(content)) !== null) {
- const val = m[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
- // Check blur: look for pattern like "0 0 20px" (third number > 4)
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- const lines = content.substring(0, m.index).split('\n');
- return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
- }
- }
- return [];
- },
-];
-
-// ---------------------------------------------------------------------------
-// Style block extraction (Vue/Svelte <style> blocks)
-// ---------------------------------------------------------------------------
-
-function extractStyleBlocks(content, ext) {
- ext = ext.toLowerCase();
- if (ext !== '.vue' && ext !== '.svelte') return [];
- const blocks = [];
- const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length + 1;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-// ---------------------------------------------------------------------------
-// CSS-in-JS extraction (styled-components, emotion)
-// ---------------------------------------------------------------------------
-
-const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
-
-function extractCSSinJS(content, ext) {
- ext = ext.toLowerCase();
- if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
- const blocks = [];
- const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null, options = {}) {
- const { profile, phase = 'regex-matchers' } = options || {};
- const findings = [];
- if (!profile) {
- for (const matcher of REGEX_MATCHERS) {
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- }
- return findings;
- }
-
- for (const matcher of REGEX_MATCHERS) {
- const matcherFindings = profileFindings(profile, {
- engine: 'regex',
- phase,
- ruleId: matcher.id,
- target: filePath,
- }, () => {
- const matches = [];
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- matches.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- return matches;
- });
- findings.push(...matcherFindings);
- }
- return findings;
-}
-
-function detectText(content, filePath, options = {}) {
- const profile = options?.profile;
- const findings = [];
- const lines = content.split('\n');
- const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
-
- // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
- // Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
- findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
- profile,
- phase: 'source',
- }));
-
- // Extract and scan <style> blocks from Vue/Svelte SFCs
- const styleBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'style-blocks',
- target: filePath,
- }, () => extractStyleBlocks(content, ext))
- : extractStyleBlocks(content, ext);
- for (const block of styleBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'style-block',
- }));
- }
-
- // Extract and scan CSS-in-JS template literals
- const cssJsBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'css-in-js',
- target: filePath,
- }, () => extractCSSinJS(content, ext))
- : extractCSSinJS(content, ext);
- for (const block of cssJsBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'css-in-js',
- }));
- }
-
- // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
- const deduped = [];
- for (const f of findings) {
- const isDupe = deduped.some(d =>
- d.antipattern === f.antipattern &&
- d.snippet === f.snippet &&
- Math.abs(d.line - f.line) <= 2
- );
- if (!isDupe) deduped.push(f);
- }
-
- // Page-level analyzers only run on full pages
- if (isFullPage(content)) {
- const analyzerIds = [
- 'single-font',
- 'flat-type-hierarchy',
- 'monotonous-spacing',
- 'everything-centered',
- 'dark-glow',
- ];
- for (let i = 0; i < REGEX_ANALYZERS.length; i++) {
- const analyzer = REGEX_ANALYZERS[i];
- deduped.push(...profileFindings(profile, {
- engine: 'regex',
- phase: 'page-analyzer',
- ruleId: analyzerIds[i] || `analyzer-${i + 1}`,
- target: filePath,
- }, () => analyzer(content, filePath)));
- }
- }
-
- return deduped;
-}
-
-export {
- REGEX_MATCHERS,
- REGEX_ANALYZERS,
- extractStyleBlocks,
- extractCSSinJS,
- runRegexMatchers,
- detectText,
-};
@@ -1,954 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { profileStep, recordProfileEvent } from '../../profile/profiler.mjs';
-import { parseAnyColor, resolveLengthPx, resolveVarRefs } from '../../rules/checks.mjs';
-
-// ---------------------------------------------------------------------------
-// jsdom CSS-variable border override map
-// ---------------------------------------------------------------------------
-//
-// jsdom's CSSOM silently drops any border shorthand that contains a var()
-// reference — the computed style for the element then shows empty width,
-// empty style, and a default black color. That's enough to hide the most
-// common real-world side-tab pattern in AI-generated pages:
-//
-// :root { --brand: #87a8ff; }
-// .card { border-left: 5px solid var(--brand); border-radius: 4px; }
-//
-// Real browsers (and therefore the browser detector path) resolve var()
-// natively, so this only affects the Node jsdom path.
-//
-// This pre-pass walks the stylesheets, finds any rule whose per-side or
-// all-sides border property contains var(), resolves the var() against
-// :root-level custom properties (read from the documentElement's computed
-// style, which jsdom DOES handle correctly), and attaches the resolved
-// width+color to every element that matches the rule's selector. The
-// Node-side `checkElementBorders` adapter consumes that map as a fallback
-// whenever jsdom's computed style came back empty.
-//
-// Limitations (intentional, to keep the pass simple):
-// * Only :root-level custom properties are resolved. Scoped overrides on
-// descendants are not tracked — uncommon in practice and would require
-// a per-element cascade walk.
-// * @media / @supports wrapped rules are ignored (jsdom often mishandles
-// these anyway).
-// * The fallback only fills sides that jsdom left empty, so any rule
-// whose border parses normally still wins via the computed style.
-
-const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
-
-// isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
-// CSS variables typically hold hex or named colors, so normalize those to
-// rgb() before handing the value off to the shared check. Anything we don't
-// recognise is passed through unchanged — isNeutralColor then treats it as
-// non-neutral, which is the safer default (matches the oklch-era bugfix).
-const NAMED_COLORS = {
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
-};
-
-function normalizeColorForCheck(value) {
- if (!value) return value;
- const v = value.trim();
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
- if (hex6) {
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
- if (hex3) {
- const [r, g, b] = [
- parseInt(hex3[1] + hex3[1], 16),
- parseInt(hex3[2] + hex3[2], 16),
- parseInt(hex3[3] + hex3[3], 16),
- ];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const named = NAMED_COLORS[v.toLowerCase()];
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
- return v;
-}
-
-function buildBorderOverrideMap(document, window) {
- const map = new Map();
- const rootStyle = window.getComputedStyle(document.documentElement);
-
- function resolveVar(value, depth = 0) {
- if (!value || depth > 10 || !value.includes('var(')) return value;
- return value.replace(
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
- (_, name, fallback) => {
- const v = rootStyle.getPropertyValue(name).trim();
- if (v) return resolveVar(v, depth + 1);
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
- return '';
- }
- );
- }
-
- function parseShorthand(text) {
- const m = text.trim().match(BORDER_SHORTHAND_RE);
- if (!m) return null;
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
- }
-
- // Read from the per-property accessors on rule.style. jsdom preserves
- // each border-* shorthand it parsed, even when the overall cssText has
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
- // `border-left: ...` loses the first declaration but keeps the second).
- const SIDE_PROPS = [
- ['borderLeft', 'Left'],
- ['borderRight', 'Right'],
- ['borderTop', 'Top'],
- ['borderBottom', 'Bottom'],
- ['borderInlineStart', 'Left'],
- ['borderInlineEnd', 'Right'],
- ];
-
- for (const sheet of document.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || []; } catch { continue; }
- for (const rule of rules) {
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
-
- const perSide = {};
-
- for (const [prop, side] of SIDE_PROPS) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const parsed = parseShorthand(resolveVar(val));
- if (parsed && parsed.color) perSide[side] = parsed;
- }
-
- // Uniform `border: <w> <style> var(...)` applies to every side the
- // per-side map didn't already claim.
- const borderAll = rule.style.border;
- if (borderAll && borderAll.includes('var(')) {
- const parsed = parseShorthand(resolveVar(borderAll));
- if (parsed && parsed.color) {
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
- if (!perSide[s]) perSide[s] = parsed;
- }
- }
- }
-
- // Longhand `border-*-color: var(...)` with width/style in separate
- // declarations. Rare in AI-generated pages, but cheap to cover.
- for (const [prop, side] of [
- ['borderLeftColor', 'Left'],
- ['borderRightColor', 'Right'],
- ['borderTopColor', 'Top'],
- ['borderBottomColor', 'Bottom'],
- ]) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const resolved = resolveVar(val).trim();
- if (!resolved) continue;
- // Width may or may not come from this rule — that's fine; the
- // adapter only substitutes the color when jsdom left it as a
- // literal var() string.
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
- }
-
- if (Object.keys(perSide).length === 0) continue;
-
- let matched;
- try { matched = document.querySelectorAll(rule.selectorText); }
- catch { continue; }
-
- for (const el of matched) {
- const existing = map.get(el);
- if (existing) {
- // Later rules overwrite earlier ones — approximates source-order
- // cascade for equal-specificity rules and is good enough for the
- // uncontested var()-dropped sides we're trying to recover.
- Object.assign(existing, perSide);
- } else {
- map.set(el, { ...perSide });
- }
- }
- }
- }
-
- return map;
-}
-
-// Strip `@layer NAME { … }` wrappers from a CSS / HTML source, leaving
-// the inner rules as flat CSS. jsdom doesn't implement CSS @layer, so
-// any rule inside a layer block becomes invisible to getComputedStyle.
-// Tailwind v4 makes this ubiquitous: every utility class lives in
-// `@layer utilities`, and Preflight lives in `@layer base`. Without
-// unwrapping, every Tailwind-styled element returns empty computed
-// styles. We walk the source character-by-character, balancing braces
-// so we correctly handle nested style rules inside the layer block.
-function unwrapCssAtLayer(source) {
- if (!source || !source.includes('@layer')) return source;
- // Find `@layer <name>? {` openers. The match starts at the @, and
- // we then balance braces from the opening { onward.
- const re = /@layer\b[^{;]*\{/g;
- let out = '';
- let lastIdx = 0;
- let m;
- while ((m = re.exec(source)) !== null) {
- const openStart = m.index;
- const openEnd = m.index + m[0].length; // position right after `{`
- let depth = 1;
- let i = openEnd;
- while (i < source.length && depth > 0) {
- const c = source.charCodeAt(i);
- if (c === 0x7b /* { */) depth++;
- else if (c === 0x7d /* } */) depth--;
- i++;
- }
- if (depth !== 0) {
- // Unbalanced — bail and return source unchanged.
- return source;
- }
- // Emit everything before the @layer, then the inner contents
- // (between the opening { and the matched closing }), then advance.
- out += source.slice(lastIdx, openStart);
- out += source.slice(openEnd, i - 1); // i-1 = position of the closing }
- lastIdx = i;
- re.lastIndex = i;
- }
- out += source.slice(lastIdx);
- return out;
-}
-
-// ---------------------------------------------------------------------------
-// Static HTML/CSS detection (default for local HTML files)
-// ---------------------------------------------------------------------------
-
-const STATIC_INHERITED_PROPS = new Set([
- 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight',
- 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'hyphens',
- 'webkitHyphens',
-]);
-
-const STATIC_DEFAULT_STYLE = {
- color: 'rgb(0, 0, 0)',
- backgroundColor: 'rgba(0, 0, 0, 0)',
- backgroundImage: 'none',
- borderTopWidth: '0px',
- borderRightWidth: '0px',
- borderBottomWidth: '0px',
- borderLeftWidth: '0px',
- borderTopColor: 'rgb(0, 0, 0)',
- borderRightColor: 'rgb(0, 0, 0)',
- borderBottomColor: 'rgb(0, 0, 0)',
- borderLeftColor: 'rgb(0, 0, 0)',
- borderRadius: '0px',
- boxShadow: 'none',
- fontFamily: '',
- fontSize: '16px',
- fontStyle: 'normal',
- fontWeight: '400',
- lineHeight: 'normal',
- letterSpacing: 'normal',
- textTransform: 'none',
- textAlign: 'start',
- hyphens: 'manual',
- webkitHyphens: 'manual',
- transitionProperty: '',
- transitionTimingFunction: '',
- animationName: '',
- animationTimingFunction: '',
- webkitBackgroundClip: '',
- backgroundClip: '',
- width: '',
- height: '',
- paddingTop: '0px',
- paddingRight: '0px',
- paddingBottom: '0px',
- paddingLeft: '0px',
- position: 'static',
- display: '',
-};
-
-const STATIC_PROP_MAP = {
- 'background-color': 'backgroundColor',
- 'background-image': 'backgroundImage',
- 'background-clip': 'backgroundClip',
- '-webkit-background-clip': 'webkitBackgroundClip',
- 'border-radius': 'borderRadius',
- 'border-top-width': 'borderTopWidth',
- 'border-right-width': 'borderRightWidth',
- 'border-bottom-width': 'borderBottomWidth',
- 'border-left-width': 'borderLeftWidth',
- 'border-top-color': 'borderTopColor',
- 'border-right-color': 'borderRightColor',
- 'border-bottom-color': 'borderBottomColor',
- 'border-left-color': 'borderLeftColor',
- 'box-shadow': 'boxShadow',
- 'font-family': 'fontFamily',
- 'font-size': 'fontSize',
- 'font-style': 'fontStyle',
- 'font-weight': 'fontWeight',
- 'line-height': 'lineHeight',
- 'letter-spacing': 'letterSpacing',
- 'text-transform': 'textTransform',
- 'text-align': 'textAlign',
- 'hyphens': 'hyphens',
- '-webkit-hyphens': 'webkitHyphens',
- 'transition-property': 'transitionProperty',
- 'transition-timing-function': 'transitionTimingFunction',
- 'animation-name': 'animationName',
- 'animation-timing-function': 'animationTimingFunction',
- 'width': 'width',
- 'height': 'height',
- 'padding-top': 'paddingTop',
- 'padding-right': 'paddingRight',
- 'padding-bottom': 'paddingBottom',
- 'padding-left': 'paddingLeft',
- 'position': 'position',
- 'display': 'display',
-};
-
-const STATIC_NAMED_COLORS = {
- black: { r: 0, g: 0, b: 0, a: 1 },
- white: { r: 255, g: 255, b: 255, a: 1 },
- transparent: { r: 0, g: 0, b: 0, a: 0 },
- gray: { r: 128, g: 128, b: 128, a: 1 },
- grey: { r: 128, g: 128, b: 128, a: 1 },
- silver: { r: 192, g: 192, b: 192, a: 1 },
- red: { r: 255, g: 0, b: 0, a: 1 },
- green: { r: 0, g: 128, b: 0, a: 1 },
- blue: { r: 0, g: 0, b: 255, a: 1 },
-};
-
-function splitCssList(value) {
- const parts = [];
- let depth = 0, quote = '', start = 0;
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; continue; }
- if (ch === '(' || ch === '[') depth++;
- else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);
- else if (ch === ',' && depth === 0) {
- parts.push(value.slice(start, i).trim());
- start = i + 1;
- }
- }
- const tail = value.slice(start).trim();
- if (tail) parts.push(tail);
- return parts;
-}
-
-function splitCssTokens(value) {
- const tokens = [];
- let depth = 0, quote = '', current = '';
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- current += ch;
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
- if (ch === '(') { depth++; current += ch; continue; }
- if (ch === ')') { depth = Math.max(0, depth - 1); current += ch; continue; }
- if (/\s/.test(ch) && depth === 0) {
- if (current) { tokens.push(current); current = ''; }
- continue;
- }
- current += ch;
- }
- if (current) tokens.push(current);
- return tokens;
-}
-
-function cssPropToCamel(prop) {
- if (!prop) return prop;
- const mapped = STATIC_PROP_MAP[prop];
- if (mapped) return mapped;
- return prop.replace(/-([a-z])/g, (_m, ch) => ch.toUpperCase());
-}
-
-function staticColorToCss(c) {
- if (!c) return '';
- if (c.a != null && c.a < 1) return `rgba(${c.r}, ${c.g}, ${c.b}, ${Number(c.a.toFixed(3))})`;
- return `rgb(${c.r}, ${c.g}, ${c.b})`;
-}
-
-function parseStaticColor(value) {
- const parsed = parseAnyColor(value);
- if (parsed) return parsed;
- const named = STATIC_NAMED_COLORS[String(value || '').trim().toLowerCase()];
- return named ? { ...named } : null;
-}
-
-function extractStaticColor(value) {
- if (!value) return '';
- const raw = String(value).trim();
- if (/^var\(/i.test(raw)) return raw;
- const colorLike = raw.match(/(?:rgba?\([^)]+\)|oklch\([^)]+\)|oklab\([^)]+\)|lch\([^)]+\)|lab\([^)]+\)|hsla?\([^)]+\)|hwb\([^)]+\)|#[0-9a-f]{3,8}\b|\b(?:black|white|gray|grey|silver|red|green|blue|transparent)\b)/i);
- if (!colorLike) return '';
- return colorLike[0];
-}
-
-function normalizeStaticCssValue(prop, value, customProps, parentStyle, currentStyle = null) {
- let resolved = resolveVarRefs(String(value || '').trim(), customProps);
- if (resolved === 'inherit') return parentStyle?.[prop] || STATIC_DEFAULT_STYLE[prop] || '';
- const isModernBorderColor = /^border[A-Z][a-z]+Color$/.test(prop) && /^(?:oklch|oklab|lch|lab|hsl|hwb)\(/i.test(resolved);
- if (!isModernBorderColor && (/color$/i.test(prop) || prop === 'color' || prop === 'backgroundColor')) {
- const parsed = parseStaticColor(resolved);
- if (parsed) resolved = staticColorToCss(parsed);
- }
- if (prop === 'fontSize') {
- const base = parseFloat(parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'letterSpacing') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'lineHeight' && resolved !== 'normal') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- return resolved;
-}
-
-function expandStaticBoxValues(tokens) {
- if (tokens.length === 0) return ['0px', '0px', '0px', '0px'];
- if (tokens.length === 1) return [tokens[0], tokens[0], tokens[0], tokens[0]];
- if (tokens.length === 2) return [tokens[0], tokens[1], tokens[0], tokens[1]];
- if (tokens.length === 3) return [tokens[0], tokens[1], tokens[2], tokens[1]];
- return [tokens[0], tokens[1], tokens[2], tokens[3]];
-}
-
-function parseStaticBorder(value) {
- const tokens = splitCssTokens(value);
- let width = '', color = '';
- for (const token of tokens) {
- if (!width && /^-?[\d.]+(?:px|rem|em|%)$/.test(token)) width = token;
- if (!color) color = extractStaticColor(token);
- }
- return { width, color };
-}
-
-function parseStaticFont(value) {
- const out = [];
- const slashParts = value.match(/(?:^|\s)([\d.]+(?:px|rem|em|%))(?:\/([^\s]+))?/);
- if (/\bitalic\b/i.test(value)) out.push(['fontStyle', 'italic']);
- const weight = value.match(/\b([1-9]00|bold|normal|lighter|bolder)\b/i);
- if (weight) out.push(['fontWeight', weight[1]]);
- if (slashParts) {
- out.push(['fontSize', slashParts[1]]);
- if (slashParts[2]) out.push(['lineHeight', slashParts[2]]);
- const familyStart = value.indexOf(slashParts[0]) + slashParts[0].length;
- const family = value.slice(familyStart).trim();
- if (family) out.push(['fontFamily', family]);
- }
- return out;
-}
-
-function parseStaticTransition(value) {
- const props = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const prop = tokens.find(token => /^[a-z-]+$/i.test(token) && !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none)$/.test(token) && !/s$/.test(token));
- if (prop) props.push(prop);
- }
- return {
- property: props.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function parseStaticAnimation(value) {
- const names = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const name = tokens.find(token =>
- /^[a-z_-][\w-]*$/i.test(token) &&
- !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none|running|paused)$/.test(token)
- );
- if (name) names.push(name);
- }
- return {
- name: names.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function expandStaticDeclaration(prop, value) {
- const p = prop.toLowerCase();
- const v = String(value || '').trim();
- if (!v) return [];
- if (p.startsWith('--')) return [[p, v]];
- if (p === 'background') {
- const out = [];
- const hasImage = /gradient|url\(/i.test(v);
- if (hasImage) out.push(['backgroundImage', v]);
- const beforeImage = hasImage ? v.split(/(?:repeating-)?(?:linear|radial|conic)-gradient\(|url\(/i)[0] : v;
- const color = extractStaticColor(hasImage ? beforeImage : v);
- if (color) out.push(['backgroundColor', color]);
- return out;
- }
- if (p === 'border') {
- const parsed = parseStaticBorder(v);
- const out = [];
- for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
- if (parsed.width) out.push([`border${side}Width`, parsed.width]);
- if (parsed.color) out.push([`border${side}Color`, parsed.color]);
- }
- return out;
- }
- const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
- if (sideMatch) {
- const parsed = parseStaticBorder(v);
- const side = sideMatch[1][0].toUpperCase() + sideMatch[1].slice(1);
- return [
- ...(parsed.width ? [[`border${side}Width`, parsed.width]] : []),
- ...(parsed.color ? [[`border${side}Color`, parsed.color]] : []),
- ];
- }
- if (p === 'border-width') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopWidth', vals[0]],
- ['borderRightWidth', vals[1]],
- ['borderBottomWidth', vals[2]],
- ['borderLeftWidth', vals[3]],
- ];
- }
- if (p === 'border-color') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopColor', vals[0]],
- ['borderRightColor', vals[1]],
- ['borderBottomColor', vals[2]],
- ['borderLeftColor', vals[3]],
- ];
- }
- if (p === 'padding') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['paddingTop', vals[0]],
- ['paddingRight', vals[1]],
- ['paddingBottom', vals[2]],
- ['paddingLeft', vals[3]],
- ];
- }
- if (p === 'font') return parseStaticFont(v);
- if (p === 'transition') {
- const parsed = parseStaticTransition(v);
- return [
- ...(parsed.property ? [['transitionProperty', parsed.property]] : []),
- ...(parsed.timing ? [['transitionTimingFunction', parsed.timing]] : []),
- ];
- }
- if (p === 'animation') {
- const parsed = parseStaticAnimation(v);
- return [
- ...(parsed.name ? [['animationName', parsed.name]] : []),
- ...(parsed.timing ? [['animationTimingFunction', parsed.timing]] : []),
- ];
- }
- const mapped = cssPropToCamel(p);
- if (STATIC_DEFAULT_STYLE[mapped] != null || STATIC_INHERITED_PROPS.has(mapped)) {
- return [[mapped, v]];
- }
- return [];
-}
-
-function compareStaticPriority(a, b) {
- if (!a) return true;
- if (!!b.important !== !!a.important) return !!b.important;
- if (!!b.inline !== !!a.inline) return !!b.inline;
- for (let i = 0; i < 3; i++) {
- if ((b.specificity[i] || 0) !== (a.specificity[i] || 0)) {
- return (b.specificity[i] || 0) > (a.specificity[i] || 0);
- }
- }
- return b.order >= a.order;
-}
-
-function staticSpecificity(selector) {
- const noWhere = selector.replace(/:where\([^)]*\)/g, '');
- const ids = (noWhere.match(/#[\w-]+/g) || []).length;
- const classes = (noWhere.match(/\.[\w-]+|\[[^\]]+\]|:(?!:)[\w-]+(?:\([^)]*\))?/g) || []).length;
- const stripped = noWhere
- .replace(/#[\w-]+/g, ' ')
- .replace(/\.[\w-]+|\[[^\]]+\]|:{1,2}[\w-]+(?:\([^)]*\))?/g, ' ')
- .replace(/[*>+~(),]/g, ' ');
- const types = (stripped.match(/\b[a-zA-Z][\w-]*\b/g) || []).length;
- return [ids, classes, types];
-}
-
-function applyStaticDeclaration(specified, node, prop, value, meta) {
- let map = specified.get(node);
- if (!map) { map = new Map(); specified.set(node, map); }
- for (const [expandedProp, expandedValue] of expandStaticDeclaration(prop, value)) {
- const existing = map.get(expandedProp);
- const next = { ...meta, prop: expandedProp, value: expandedValue };
- if (compareStaticPriority(existing, next)) map.set(expandedProp, next);
- }
-}
-
-function parseStaticStyleAttribute(styleText, orderBase = 0) {
- const decls = [];
- for (const part of String(styleText || '').split(';')) {
- const idx = part.indexOf(':');
- if (idx <= 0) continue;
- const prop = part.slice(0, idx).trim();
- let value = part.slice(idx + 1).trim();
- const important = /!important\s*$/i.test(value);
- value = value.replace(/\s*!important\s*$/i, '').trim();
- decls.push({ prop, value, important, order: orderBase + decls.length });
- }
- return decls;
-}
-
-function collectStaticCssRules(cssText, csstree) {
- const rules = [];
- let ast;
- try {
- ast = csstree.parse(cssText, { positions: false, parseValue: true, parseCustomProperty: false });
- } catch {
- return rules;
- }
- let order = 0;
- const walkList = (list, atRuleStack = []) => {
- list?.forEach?.(node => {
- if (node.type === 'Rule' && node.block) {
- if (atRuleStack.some(name => /keyframes$/i.test(name))) return;
- const selectorText = csstree.generate(node.prelude).trim();
- const declarations = [];
- node.block.children?.forEach?.(child => {
- if (child.type !== 'Declaration') return;
- declarations.push({
- prop: child.property,
- value: csstree.generate(child.value).trim(),
- important: !!child.important,
- });
- });
- for (const selector of splitCssList(selectorText)) {
- if (selector) rules.push({ selector, declarations, specificity: staticSpecificity(selector), order: order++ });
- }
- return;
- }
- if (node.type === 'Atrule' && node.block) {
- const name = String(node.name || '').toLowerCase();
- if (name === 'media' || name === 'supports' || name === 'layer') {
- walkList(node.block.children, [...atRuleStack, name]);
- }
- }
- });
- };
- walkList(ast.children);
- return rules;
-}
-
-class StaticElement {
- constructor(node, doc) {
- this.node = node;
- this._doc = doc;
- this.nodeType = 1;
- this.tagName = String(node.name || '').toUpperCase();
- this.nodeName = this.tagName;
- }
- get parentElement() {
- let cur = this.node.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- return cur ? this._doc.wrap(cur) : null;
- }
- get previousElementSibling() {
- let cur = this.node.prev;
- while (cur && cur.type !== 'tag') cur = cur.prev;
- return cur ? this._doc.wrap(cur) : null;
- }
- get children() {
- return (this.node.children || []).filter(child => child.type === 'tag').map(child => this._doc.wrap(child));
- }
- get childNodes() {
- return (this.node.children || []).map(child => {
- if (child.type === 'text') return { nodeType: 3, textContent: child.data || '' };
- if (child.type === 'tag') return this._doc.wrap(child);
- return { nodeType: 8, textContent: child.data || '' };
- });
- }
- get textContent() {
- return this._doc.domutils.textContent(this.node);
- }
- get className() {
- return this.getAttribute('class') || '';
- }
- get id() {
- return this.getAttribute('id') || '';
- }
- getAttribute(name) {
- return this.node.attribs?.[name] ?? null;
- }
- querySelector(selector) {
- try {
- const found = this._doc.selectOne(selector, this.node.children || []);
- return found ? this._doc.wrap(found) : null;
- } catch {
- return null;
- }
- }
- querySelectorAll(selector) {
- try {
- return this._doc.selectAll(selector, this.node.children || []).map(node => this._doc.wrap(node));
- } catch {
- return [];
- }
- }
- closest(selector) {
- let cur = this.node;
- while (cur && cur.type === 'tag') {
- try {
- if (this._doc.is(cur, selector)) return this._doc.wrap(cur);
- } catch {
- return null;
- }
- cur = cur.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- }
- return null;
- }
- contains(other) {
- let cur = other?.node || null;
- while (cur) {
- if (cur === this.node) return true;
- cur = cur.parent;
- }
- return false;
- }
-}
-
-class StaticDocument {
- constructor(root, modules) {
- this.root = root;
- this.selectAll = modules.selectAll;
- this.selectOne = modules.selectOne;
- this.is = modules.is;
- this.domutils = modules.domutils;
- this._wrappers = new WeakMap();
- this._styleMap = new WeakMap();
- }
- wrap(node) {
- let wrapped = this._wrappers.get(node);
- if (!wrapped) {
- wrapped = new StaticElement(node, this);
- this._wrappers.set(node, wrapped);
- }
- return wrapped;
- }
- querySelectorAll(selector) {
- try {
- return this.selectAll(selector, this.root.children || []).map(node => this.wrap(node));
- } catch {
- return [];
- }
- }
- querySelector(selector) {
- try {
- const found = this.selectOne(selector, this.root.children || []);
- return found ? this.wrap(found) : null;
- } catch {
- return null;
- }
- }
- get documentElement() {
- return this.querySelector('html');
- }
- get body() {
- return this.querySelector('body');
- }
- setStyle(node, style) {
- this._styleMap.set(node, style);
- }
- getStyle(el) {
- return this._styleMap.get(el.node) || makeStaticStyle();
- }
-}
-
-function makeStaticStyle(values = {}) {
- const style = { ...STATIC_DEFAULT_STYLE, ...values };
- style.getPropertyValue = (prop) => {
- const key = cssPropToCamel(prop);
- return style[key] || style[prop] || '';
- };
- return style;
-}
-
-function buildStaticWindow(staticDoc) {
- return {
- document: staticDoc,
- getComputedStyle: (el) => staticDoc.getStyle(el),
- };
-}
-
-function collectStaticCssText(root, fileDir, profile, filePath, modules) {
- const styleTexts = [];
- for (const styleEl of modules.selectAll('style', root.children || [])) {
- styleTexts.push(modules.domutils.textContent(styleEl));
- }
- const links = modules.selectAll('link', root.children || []);
- for (const link of links) {
- const rel = link.attribs?.rel || '';
- const href = link.attribs?.href || '';
- if (!/\bstylesheet\b/i.test(rel) || !href || /^(https?:)?\/\//i.test(href)) continue;
- const cssPath = path.resolve(fileDir, href);
- try {
- const css = profileStep(profile, {
- engine: 'static-html',
- phase: 'preprocess',
- ruleId: 'inline-linked-stylesheet',
- target: filePath,
- detail: href,
- }, () => fs.readFileSync(cssPath, 'utf-8'));
- styleTexts.push(css);
- } catch { /* skip unreadable */ }
- }
- return styleTexts.join('\n');
-}
-
-function buildStaticStyleMap(root, staticDoc, cssText, modules, profile, filePath) {
- const specified = new Map();
- const allNodes = modules.selectAll('*', root.children || []);
- const rules = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-css',
- ruleId: 'css-rules',
- target: filePath,
- }, () => collectStaticCssRules(cssText, modules.csstree));
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'css-selectors',
- target: filePath,
- }, () => {
- for (const rule of rules) {
- let matched;
- try {
- matched = modules.selectAll(rule.selector, root.children || []);
- } catch {
- recordProfileEvent(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'unsupported-selector',
- target: filePath,
- ms: 0,
- findings: 0,
- detail: rule.selector,
- });
- continue;
- }
- for (const node of matched) {
- for (const decl of rule.declarations) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: rule.specificity,
- order: rule.order,
- inline: false,
- });
- }
- }
- }
-
- let inlineOrder = rules.length + 1;
- for (const node of allNodes) {
- const styleText = node.attribs?.style;
- if (!styleText) continue;
- for (const decl of parseStaticStyleAttribute(styleText, inlineOrder)) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: [1, 0, 0],
- order: decl.order,
- inline: true,
- });
- }
- inlineOrder += 1000;
- }
- });
-
- const computeNode = (node, parentStyle = null, parentCustom = new Map()) => {
- const specifiedMap = specified.get(node) || new Map();
- const customProps = new Map(parentCustom);
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) customProps.set(prop, resolveVarRefs(decl.value, customProps));
- }
- const values = {};
- for (const prop of Object.keys(STATIC_DEFAULT_STYLE)) {
- if (STATIC_INHERITED_PROPS.has(prop) && parentStyle?.[prop] != null) values[prop] = parentStyle[prop];
- else values[prop] = STATIC_DEFAULT_STYLE[prop];
- }
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) continue;
- values[prop] = normalizeStaticCssValue(prop, decl.value, customProps, parentStyle, values);
- }
- const style = makeStaticStyle(values);
- staticDoc.setStyle(node, style);
- for (const child of node.children || []) {
- if (child.type === 'tag') computeNode(child, style, customProps);
- }
- };
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'cascade',
- ruleId: 'compute-styles',
- target: filePath,
- }, () => {
- for (const child of root.children || []) {
- if (child.type === 'tag') computeNode(child);
- }
- });
-}
-
-export {
- BORDER_SHORTHAND_RE,
- NAMED_COLORS,
- normalizeColorForCheck,
- buildBorderOverrideMap,
- unwrapCssAtLayer,
- STATIC_INHERITED_PROPS,
- STATIC_DEFAULT_STYLE,
- STATIC_PROP_MAP,
- STATIC_NAMED_COLORS,
- splitCssList,
- splitCssTokens,
- cssPropToCamel,
- staticColorToCss,
- parseStaticColor,
- extractStaticColor,
- normalizeStaticCssValue,
- expandStaticBoxValues,
- parseStaticBorder,
- parseStaticFont,
- parseStaticTransition,
- parseStaticAnimation,
- expandStaticDeclaration,
- compareStaticPriority,
- staticSpecificity,
- applyStaticDeclaration,
- parseStaticStyleAttribute,
- collectStaticCssRules,
- StaticElement,
- StaticDocument,
- makeStaticStyle,
- buildStaticWindow,
- collectStaticCssText,
- buildStaticStyleMap,
-};
@@ -1,174 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import {
- checkElementBorders,
- checkElementColors,
- checkElementGlow,
- checkElementHeroEyebrow,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementMotion,
- checkElementQuality,
- checkHtmlPatterns,
- checkPageLayout,
- checkPageQualityFromDoc,
- checkRepeatedSectionKickersFromDoc,
- resolveBackground,
- resolveBorderRadiusPx,
-} from '../../rules/checks.mjs';
-import { detectText } from '../regex/detect-text.mjs';
-import {
- StaticDocument,
- buildStaticStyleMap,
- buildStaticWindow,
- collectStaticCssText,
-} from './css-cascade.mjs';
-
-function checkStaticPageTypography(document, window) {
- const findings = [];
- const fonts = new Set();
- const overusedFound = new Set();
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span, div')) {
- const hasText = el.childNodes.some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const ff = window.getComputedStyle(el).fontFamily || '';
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
- if (fonts.size === 1 && document.querySelectorAll('*').length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div')) {
- const fontSize = parseFloat(window.getComputedStyle(el).fontSize);
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
- return findings;
-}
-
-const STATIC_ELEMENT_RULES = [
- { id: 'border-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementBorders(tag, style, null, resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window)) },
- { id: 'color-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementColors(el, style, tag, window, customPropMap, false) },
- { id: 'dark-glow', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window, customPropMap)) },
- { id: 'motion-rules', selector: '*', run: (el, tag, style) => checkElementMotion(tag, style) },
- { id: 'icon-tile-stack', selector: 'h1,h2,h3,h4,h5,h6', run: (el, tag, _style, window) => checkElementIconTile(el, tag, window) },
- { id: 'italic-serif-display', selector: 'h1,h2', run: (el, tag, style) => checkElementItalicSerif(el, style, tag) },
- { id: 'hero-eyebrow-chip', selector: 'h1', run: (el, tag, style, window, customPropMap) => checkElementHeroEyebrow(el, style, tag, window, customPropMap) },
- { id: 'quality-rules', selector: '*', run: (el, tag, style, window) => checkElementQuality(el, style, tag, window) },
-];
-
-async function detectHtml(filePath, options = {}) {
- const profile = options?.profile;
- const html = profileStep(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'read-html',
- target: filePath,
- }, () => fs.readFileSync(filePath, 'utf-8'));
-
- let modules;
- try {
- modules = await profileStepAsync(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'import-static-parser',
- target: filePath,
- }, async () => {
- const [htmlparser2, cssSelect, csstree, domutils] = await Promise.all([
- import('htmlparser2'),
- import('css-select'),
- import('css-tree'),
- import('domutils'),
- ]);
- return {
- parseDocument: htmlparser2.parseDocument,
- selectAll: cssSelect.selectAll,
- selectOne: cssSelect.selectOne,
- is: cssSelect.is,
- csstree,
- domutils,
- };
- });
- } catch {
- return detectText(html, filePath, options);
- }
-
- const resolvedPath = path.resolve(filePath);
- const fileDir = path.dirname(resolvedPath);
- const root = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-html',
- ruleId: 'parse-document',
- target: filePath,
- }, () => modules.parseDocument(html, { lowerCaseAttributeNames: false, lowerCaseTags: true }));
-
- const cssText = collectStaticCssText(root, fileDir, profile, filePath, modules);
- const document = new StaticDocument(root, modules);
- buildStaticStyleMap(root, document, cssText, modules, profile, filePath);
- const window = buildStaticWindow(document);
-
- const customPropMap = null;
-
- const findings = [];
- const runElementCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'element', ruleId, target: filePath }, callback)
- : callback();
-
- const visitedByRule = new Map();
- for (const rule of STATIC_ELEMENT_RULES) {
- const elements = document.querySelectorAll(rule.selector);
- visitedByRule.set(rule.id, elements.length);
- for (const el of elements) {
- const tag = el.tagName.toLowerCase();
- const style = window.getComputedStyle(el);
- for (const f of runElementCheck(rule.id, () => rule.run(el, tag, style, window, customPropMap))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
- }
-
- if (isFullPage(html)) {
- const runPageCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
- : callback();
- for (const f of runPageCheck('typography-rules', () => checkStaticPageTypography(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('repeated-section-kickers', () => checkRepeatedSectionKickersFromDoc(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('layout-rules', () => checkPageLayout(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('skipped-heading', () => checkPageQualityFromDoc(document))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('html-patterns', () => checkHtmlPatterns(html).filter(item =>
- item.id !== 'bounce-easing' && item.id !== 'layout-transition'
- ))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
-
- return findings;
-}
-
-export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -1,189 +0,0 @@
-function sanitizeScreenshotClip(clip, viewport) {
- if (!clip) return null;
- const x = Math.max(0, Math.floor(clip.x || 0));
- const y = Math.max(0, Math.floor(clip.y || 0));
- const width = Math.min(
- Math.max(1, Math.ceil(clip.width || 0)),
- Math.max(1, viewport?.width || 1600),
- );
- const height = Math.min(
- Math.max(1, Math.ceil(clip.height || 0)),
- 320,
- );
- if (width < 1 || height < 1) return null;
- return { x, y, width, height };
-}
-
-async function compareScreenshotContrast(page, beforeBase64, afterBase64, candidate) {
- return page.evaluate(async ({ beforeBase64, afterBase64, candidate }) => {
- const loadImage = (base64) => new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = () => reject(new Error('Could not decode contrast screenshot'));
- img.src = `data:image/png;base64,${base64}`;
- });
- const [before, after] = await Promise.all([loadImage(beforeBase64), loadImage(afterBase64)]);
- const width = Math.min(before.width, after.width);
- const height = Math.min(before.height, after.height);
- if (width < 1 || height < 1) return null;
-
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return null;
-
- ctx.drawImage(before, 0, 0, width, height);
- const beforePixels = ctx.getImageData(0, 0, width, height).data;
- ctx.clearRect(0, 0, width, height);
- ctx.drawImage(after, 0, 0, width, height);
- const afterPixels = ctx.getImageData(0, 0, width, height).data;
-
- const luminance = ({ r, g, b }) => {
- const convert = c => {
- const v = c / 255;
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
- };
- return 0.2126 * convert(r) + 0.7152 * convert(g) + 0.0722 * convert(b);
- };
- const ratio = (a, b) => {
- const l1 = luminance(a);
- const l2 = luminance(b);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
- };
-
- const cssTextColor = candidate.textColor && !candidate.preferRenderedForeground
- ? {
- r: candidate.textColor.r,
- g: candidate.textColor.g,
- b: candidate.textColor.b,
- }
- : null;
- const ratios = [];
- let glyphPixels = 0;
- let strongestDelta = 0;
- for (let i = 0; i < beforePixels.length; i += 4) {
- const delta = Math.abs(beforePixels[i] - afterPixels[i])
- + Math.abs(beforePixels[i + 1] - afterPixels[i + 1])
- + Math.abs(beforePixels[i + 2] - afterPixels[i + 2])
- + Math.abs(beforePixels[i + 3] - afterPixels[i + 3]);
- strongestDelta = Math.max(strongestDelta, delta);
- if (delta < 10) continue;
- glyphPixels++;
- const fg = cssTextColor || {
- r: beforePixels[i],
- g: beforePixels[i + 1],
- b: beforePixels[i + 2],
- };
- const bg = {
- r: afterPixels[i],
- g: afterPixels[i + 1],
- b: afterPixels[i + 2],
- };
- ratios.push(ratio(fg, bg));
- }
-
- if (ratios.length < 8) {
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: null,
- p10Ratio: null,
- medianRatio: null,
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: ratios[0],
- p10Ratio: pick(10),
- medianRatio: pick(50),
- };
- }, { beforeBase64, afterBase64, candidate });
-}
-
-async function captureVisualContrastCandidate(page, candidate, viewport) {
- const clip = sanitizeScreenshotClip(candidate.clip, viewport);
- if (!clip) return null;
-
- const beforeBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- const token = `impeccable-contrast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- const applied = await page.evaluate(({ selector, token, backgroundClipText }) => {
- let el;
- try {
- el = document.querySelector(selector);
- } catch {
- return false;
- }
- if (!el) return false;
- let style = document.getElementById('impeccable-visual-contrast-hide-style');
- if (!style) {
- style = document.createElement('style');
- style.id = 'impeccable-visual-contrast-hide-style';
- style.textContent = [
- '[data-impeccable-visual-contrast-target] {',
- ' color: transparent !important;',
- ' -webkit-text-fill-color: transparent !important;',
- ' text-shadow: none !important;',
- '}',
- '[data-impeccable-visual-contrast-target][data-impeccable-bgclip-text="true"] {',
- ' background-image: none !important;',
- '}',
- ].join('\n');
- document.head.appendChild(style);
- }
- el.setAttribute('data-impeccable-visual-contrast-target', token);
- if (backgroundClipText) el.setAttribute('data-impeccable-bgclip-text', 'true');
- return true;
- }, {
- selector: candidate.selector,
- token,
- backgroundClipText: candidate.backgroundClipText,
- });
- if (!applied) return null;
-
- let afterBase64;
- try {
- afterBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- } finally {
- await page.evaluate(({ selector }) => {
- try {
- const el = document.querySelector(selector);
- if (el) {
- el.removeAttribute('data-impeccable-visual-contrast-target');
- el.removeAttribute('data-impeccable-bgclip-text');
- }
- } catch {
- // Ignore invalid or stale selectors during cleanup.
- }
- }, { selector: candidate.selector }).catch(() => {});
- }
-
- const metrics = await compareScreenshotContrast(page, beforeBase64, afterBase64, candidate);
- if (!metrics || !Number.isFinite(metrics.p10Ratio) || metrics.glyphPixels < 8) return null;
- const measuredRatio = metrics.p10Ratio;
- if (measuredRatio >= candidate.threshold) return null;
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const reasonLabel = (candidate.reasons || []).slice(0, 3).join(', ') || 'visual background';
- return {
- id: 'low-contrast',
- snippet: `pixel contrast ${measuredRatio.toFixed(1)}:1 median ${metrics.medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) on ${reasonLabel}${textLabel}`,
- };
-}
-
-export {
- sanitizeScreenshotClip,
- compareScreenshotContrast,
- captureVisualContrastCandidate,
-};
@@ -1,12 +0,0 @@
-import { getAntipattern } from './registry/antipatterns.mjs';
-
-function getAP(id) {
- return getAntipattern(id);
-}
-
-function finding(id, filePath, snippet, line = 0) {
- const ap = getAP(id);
- return { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', file: filePath, line, snippet };
-}
-
-export { getAP, finding };
@@ -1,198 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-// ---------------------------------------------------------------------------
-// File walker
-// ---------------------------------------------------------------------------
-
-const SKIP_DIRS = new Set([
- 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
- '.svelte-kit', '__pycache__', '.turbo', '.vercel',
-]);
-
-const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
- '.jsx', '.tsx', '.js', '.ts',
- '.vue', '.svelte', '.astro',
-]);
-
-const HTML_EXTENSIONS = new Set(['.html', '.htm']);
-
-function walkDir(dir) {
- const files = [];
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
- for (const entry of entries) {
- if (SKIP_DIRS.has(entry.name)) continue;
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) files.push(...walkDir(full));
- else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
- }
- return files;
-}
-
-
-// ---------------------------------------------------------------------------
-// Import graph (multi-file awareness)
-// ---------------------------------------------------------------------------
-
-function resolveImport(specifier, fromDir, fileSet) {
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
- const base = path.resolve(fromDir, specifier);
- if (fileSet.has(base)) return base;
- for (const ext of SCANNABLE_EXTENSIONS) {
- const withExt = base + ext;
- if (fileSet.has(withExt)) return withExt;
- }
- // index file convention
- for (const ext of SCANNABLE_EXTENSIONS) {
- const indexFile = path.join(base, 'index' + ext);
- if (fileSet.has(indexFile)) return indexFile;
- }
- return null;
-}
-
-function buildImportGraph(files) {
- const fileSet = new Set(files);
- const graph = new Map();
-
- for (const file of files) {
- const content = fs.readFileSync(file, 'utf-8');
- const dir = path.dirname(file);
- const imports = new Set();
-
- // ES imports: import ... from '...' and import '...'
- const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
- let m;
- while ((m = esRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // CSS @import
- const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
- while ((m = cssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // SCSS @use / @forward
- const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
- while ((m = scssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- graph.set(file, imports);
- }
- return graph;
-}
-
-// ---------------------------------------------------------------------------
-// Framework dev server detection
-// ---------------------------------------------------------------------------
-
-const FRAMEWORK_CONFIGS = [
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /next/i } },
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-sveltekit-page', value: null } },
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /@vite\/client/ } },
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /astro/i } },
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
- portRe: /"port"\s*:\s*(\d+)/,
- fingerprint: { body: /ng-version/i } },
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
-];
-
-function detectFrameworkConfig(dir) {
- let entries;
- try { entries = fs.readdirSync(dir); } catch { return null; }
- const entrySet = new Set(entries);
-
- for (const cfg of FRAMEWORK_CONFIGS) {
- const match = cfg.files.find(f => entrySet.has(f));
- if (!match) continue;
-
- const configPath = path.join(dir, match);
- let port = cfg.defaultPort;
- try {
- const content = fs.readFileSync(configPath, 'utf-8');
- const portMatch = content.match(cfg.portRe);
- if (portMatch) port = parseInt(portMatch[1], 10);
- } catch { /* use default */ }
-
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
- }
- return null;
-}
-
-/**
- * Check if a port is listening and optionally verify it matches the expected framework.
- * Returns { listening: true, matched: true/false } or { listening: false }.
- */
-async function isPortListening(port, fingerprint = null) {
- if (!fingerprint) {
- // Simple TCP probe fallback
- const net = await import('node:net');
- return new Promise((resolve) => {
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
- sock.setTimeout(500);
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
- sock.on('error', () => resolve({ listening: false }));
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
- });
- }
-
- // HTTP probe with fingerprint matching
- try {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 2000);
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
- clearTimeout(timeout);
-
- // Check header fingerprint
- if (fingerprint.header) {
- const val = res.headers.get(fingerprint.header);
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
- return { listening: true, matched: true };
- }
- }
-
- // Check body fingerprint
- if (fingerprint.body) {
- const body = await res.text();
- if (fingerprint.body.test(body)) {
- return { listening: true, matched: true };
- }
- }
-
- // Port is listening but doesn't match the expected framework
- return { listening: true, matched: false };
- } catch {
- return { listening: false };
- }
-}
-
-export {
- SKIP_DIRS,
- SCANNABLE_EXTENSIONS,
- HTML_EXTENSIONS,
- walkDir,
- resolveImport,
- buildImportGraph,
- FRAMEWORK_CONFIGS,
- detectFrameworkConfig,
- isPortListening,
-};
@@ -1,166 +0,0 @@
-function profileNow() {
- return typeof performance !== 'undefined' && performance.now
- ? performance.now()
- : Date.now();
-}
-
-function createDetectorProfile() {
- return { events: [] };
-}
-
-function recordProfileEvent(profile, event) {
- if (!profile) return;
- const normalized = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- ms: Number.isFinite(event.ms) ? event.ms : 0,
- findings: Number.isFinite(event.findings) ? event.findings : 0,
- };
- if (event.detail) normalized.detail = event.detail;
- if (Array.isArray(event.findingIds) && event.findingIds.length) {
- normalized.findingIds = event.findingIds;
- }
- if (typeof profile === 'function') {
- profile(normalized);
- } else if (typeof profile.record === 'function') {
- profile.record(normalized);
- } else if (Array.isArray(profile.events)) {
- profile.events.push(normalized);
- } else if (Array.isArray(profile)) {
- profile.push(normalized);
- }
-}
-
-function extractFindingIds(findings) {
- if (!Array.isArray(findings) || findings.length === 0) return [];
- return [...new Set(findings.map(f => f?.id || f?.type || f?.antipattern).filter(Boolean))];
-}
-
-function profileFindings(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-function profileStep(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-async function profileFindingsAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = await callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-async function profileStepAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return await callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-function percentile(sortedValues, pct) {
- if (!sortedValues.length) return 0;
- const idx = Math.min(
- sortedValues.length - 1,
- Math.max(0, Math.ceil((pct / 100) * sortedValues.length) - 1),
- );
- return sortedValues[idx];
-}
-
-function summarizeDetectorProfile(profile) {
- const events = Array.isArray(profile)
- ? profile
- : (Array.isArray(profile?.events) ? profile.events : []);
- const groups = new Map();
- for (const event of events) {
- const key = [
- event.engine || 'unknown',
- event.phase || 'unknown',
- event.ruleId || 'unknown',
- event.target || '',
- ].join('\u0000');
- let group = groups.get(key);
- if (!group) {
- group = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- calls: 0,
- totalMs: 0,
- findings: 0,
- samples: [],
- };
- groups.set(key, group);
- }
- const ms = Number.isFinite(event.ms) ? event.ms : 0;
- group.calls += 1;
- group.totalMs += ms;
- group.findings += Number.isFinite(event.findings) ? event.findings : 0;
- group.samples.push(ms);
- }
- return [...groups.values()]
- .map(group => {
- const samples = group.samples.sort((a, b) => a - b);
- return {
- engine: group.engine,
- phase: group.phase,
- ruleId: group.ruleId,
- target: group.target,
- calls: group.calls,
- totalMs: Number(group.totalMs.toFixed(3)),
- avgMs: Number((group.totalMs / group.calls).toFixed(3)),
- p50: Number(percentile(samples, 50).toFixed(3)),
- p95: Number(percentile(samples, 95).toFixed(3)),
- findings: group.findings,
- };
- })
- .sort((a, b) => b.totalMs - a.totalMs);
-}
-
-export {
- profileNow,
- createDetectorProfile,
- recordProfileEvent,
- extractFindingIds,
- profileFindings,
- profileStep,
- profileFindingsAsync,
- profileStepAsync,
- percentile,
- summarizeDetectorProfile,
-};
@@ -1,278 +0,0 @@
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-const RULE_ENGINE_SUPPORT = {
- regex: new Set(['source', 'page-analyzer']),
- 'static-html': new Set(['element', 'page']),
- browser: new Set(['element', 'page', 'layout']),
- visual: new Set(['visual-contrast']),
-};
-
-function getAntipattern(id) {
- return ANTIPATTERNS.find(rule => rule.id === id);
-}
-
-function getRulesForCategory(category) {
- return ANTIPATTERNS.filter(rule => rule.category === category);
-}
-
-function getRuleEngineSupport(engine) {
- return RULE_ENGINE_SUPPORT[engine] || new Set();
-}
-
-export {
- ANTIPATTERNS,
- RULE_ENGINE_SUPPORT,
- getAntipattern,
- getRulesForCategory,
- getRuleEngineSupport,
-};
@@ -1,1948 +0,0 @@
-import {
- BORDER_SAFE_TAGS,
- GENERIC_FONTS,
- KNOWN_SERIF_FONTS,
- OVERUSED_FONTS,
- SAFE_TAGS,
- WCAG_LARGE_BOLD_TEXT_PX,
- WCAG_LARGE_TEXT_PX,
- isBrandFontOnOwnDomain,
-} from '../shared/constants.mjs';
-import {
- colorToHex,
- contrastRatio,
- getHue,
- hasChroma,
- isNeutralColor,
- parseGradientColors,
- parseRgb,
- relativeLuminance,
-} from '../shared/color.mjs';
-
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-export {
- checkBorders,
- isEmojiOnlyText,
- checkColors,
- isCardLikeFromProps,
- checkIconTile,
- resolveSerif,
- checkItalicSerif,
- isAccentColor,
- checkHeroEyebrow,
- checkRepeatedSectionKickers,
- checkMotion,
- checkGlow,
- checkHtmlPatterns,
- readOwnBackgroundColor,
- resolveBackground,
- resolveGradientStops,
- parseRadiusToPx,
- resolveBorderRadiusPx,
- checkElementBordersDOM,
- checkElementColorsDOM,
- checkElementIconTileDOM,
- checkElementItalicSerifDOM,
- checkElementHeroEyebrowDOM,
- buildCustomPropMap,
- resolveVarRefs,
- oklchToRgb,
- parseAnyColor,
- parseColorResolved,
- cleanInlineText,
- isRepeatedKickerCandidate,
- collectRepeatedSectionKickerCandidates,
- checkRepeatedSectionKickersDOM,
- checkElementMotionDOM,
- checkElementGlowDOM,
- checkElementAIPaletteDOM,
- resolveFontSizePx,
- resolveLengthPx,
- checkQuality,
- checkElementQualityDOM,
- checkPageQualityFromDoc,
- checkPageQualityDOM,
- checkElementQuality,
- checkElementBorders,
- checkElementColors,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementHeroEyebrow,
- checkRepeatedSectionKickersFromDoc,
- checkElementMotion,
- checkElementGlow,
- checkTypography,
- isCardLikeDOM,
- checkLayout,
- checkPageTypography,
- isCardLike,
- checkPageLayout,
-};
@@ -1,124 +0,0 @@
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-export {
- isNeutralColor,
- parseRgb,
- relativeLuminance,
- contrastRatio,
- parseGradientColors,
- hasChroma,
- getHue,
- colorToHex,
-};
@@ -1,101 +0,0 @@
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-export {
- SAFE_TAGS,
- BORDER_SAFE_TAGS,
- OVERUSED_FONTS,
- GOOGLE_DOMAINS,
- VERCEL_DOMAINS,
- GITHUB_DOMAINS,
- BRAND_FONT_DOMAINS,
- isBrandFontOnOwnDomain,
- GENERIC_FONTS,
- WCAG_LARGE_TEXT_PX,
- WCAG_LARGE_BOLD_TEXT_PX,
- KNOWN_SERIF_FONTS,
-};
@@ -1,7 +0,0 @@
-/** Check if content looks like a full page (not a component/partial) */
-function isFullPage(content) {
- const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
- return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
-}
-
-export { isFullPage };
@@ -1,110 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-export const IMPECCABLE_DIR = '.impeccable';
-export const LIVE_DIR = 'live';
-export const CRITIQUE_DIR = 'critique';
-
-export function getImpeccableDir(cwd = process.cwd()) {
- return path.join(cwd, IMPECCABLE_DIR);
-}
-
-export function getDesignSidecarPath(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), 'design.json');
-}
-
-export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {
- const candidates = [
- getDesignSidecarPath(cwd),
- path.join(cwd, 'DESIGN.json'),
- ];
- const contextLegacy = path.join(contextDir, 'DESIGN.json');
- if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
- return candidates;
-}
-
-export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
- return firstExisting(getDesignSidecarCandidates(cwd, contextDir));
-}
-
-export function getLiveDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), LIVE_DIR);
-}
-
-export function getLiveConfigPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'config.json');
-}
-
-export function getLegacyLiveConfigPath(scriptsDir) {
- return path.join(scriptsDir, 'config.json');
-}
-
-export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {
- if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
- const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
- return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
- }
- const primary = getLiveConfigPath(cwd);
- if (fs.existsSync(primary)) return primary;
- if (scriptsDir) {
- const legacy = getLegacyLiveConfigPath(scriptsDir);
- if (fs.existsSync(legacy)) return legacy;
- }
- return primary;
-}
-
-export function getLiveServerPath(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'server.json');
-}
-
-export function getLegacyLiveServerPath(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live.json');
-}
-
-export function readLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try {
- return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };
- } catch {
- /* try next */
- }
- }
- return null;
-}
-
-export function writeLiveServerInfo(cwd = process.cwd(), info) {
- const filePath = getLiveServerPath(cwd);
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- fs.writeFileSync(filePath, JSON.stringify(info));
- return filePath;
-}
-
-export function removeLiveServerInfo(cwd = process.cwd()) {
- for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
- try { fs.unlinkSync(filePath); } catch {}
- }
-}
-
-export function getLiveSessionsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'sessions');
-}
-
-export function getLegacyLiveSessionsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'sessions');
-}
-
-export function getLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(getLiveDir(cwd), 'annotations');
-}
-
-export function getCritiqueDir(cwd = process.cwd()) {
- return path.join(getImpeccableDir(cwd), CRITIQUE_DIR);
-}
-
-export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {
- return path.join(cwd, '.impeccable-live', 'annotations');
-}
-
-function firstExisting(paths) {
- return paths.find((filePath) => fs.existsSync(filePath)) || null;
-}
@@ -1,69 +0,0 @@
-/**
- * Decide whether a given file is "generated" (regenerated by a build step,
- * unsafe to write variants into) or "source" (safe to edit, changes persist).
- *
- * Why this matters: when the user picks an element on a page whose underlying
- * file is regenerated by a build step (e.g. `scripts/build-sub-pages.js`
- * rewriting `public/docs/*.html`), writing variants or accepted changes into
- * that file is silent data loss — the next build wipes them.
- *
- * Signals, in order of reliability:
- * 1. Git check-ignore: gitignored files are assumed generated.
- * 2. File-header markers ("GENERATED", "DO NOT EDIT", "AUTO-GENERATED")
- * within the first ~300 characters — catches non-git projects.
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-
-const HEADER_SCAN_BYTES = 300;
-const HEADER_MARKERS = [
- /@generated\b/i,
- /\bGENERATED\s+FILE\b/,
- /\bAUTO-?GENERATED\b/i,
- /\bDO\s+NOT\s+EDIT\b/i,
-];
-
-/**
- * @param {string} filePath - absolute or cwd-relative path
- * @param {object} [options]
- * @param {string} [options.cwd] - project root (defaults to process.cwd())
- */
-export function isGeneratedFile(filePath, options = {}) {
- const cwd = options.cwd || process.cwd();
- const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
-
- if (isGitIgnored(absPath, cwd)) return true;
- if (hasGeneratedHeader(absPath)) return true;
- return false;
-}
-
-function isGitIgnored(absPath, cwd) {
- try {
- execSync(`git check-ignore --quiet ${JSON.stringify(absPath)}`, {
- cwd,
- stdio: 'ignore',
- });
- return true; // exit 0 = ignored
- } catch (err) {
- // Exit code 1 = not ignored. Exit code 128 = not a git repo or other error.
- // In both cases, treat as "not known to be ignored."
- return false;
- }
-}
-
-function hasGeneratedHeader(absPath) {
- let fd;
- try {
- fd = fs.openSync(absPath, 'r');
- const buf = Buffer.alloc(HEADER_SCAN_BYTES);
- const bytesRead = fs.readSync(fd, buf, 0, HEADER_SCAN_BYTES, 0);
- const head = buf.slice(0, bytesRead).toString('utf-8');
- return HEADER_MARKERS.some((re) => re.test(head));
- } catch {
- return false;
- } finally {
- if (fd !== undefined) { try { fs.closeSync(fd); } catch {} }
- }
-}
@@ -1,595 +0,0 @@
-/**
- * CLI helper: deterministic accept/discard of variant sessions.
- *
- * Usage:
- * node live-accept.mjs --id SESSION_ID --discard
- * node live-accept.mjs --id SESSION_ID --variant N
- *
- * For discard: removes the entire variant wrapper and restores the original.
- * For accept: replaces the wrapper with the chosen variant's content. If the
- * session had a colocated <style> block, it's preserved with carbonize markers
- * for a background agent to integrate into the project's CSS.
- *
- * Output: JSON to stdout.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-export async function acceptCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-accept.mjs [options]
-
-Deterministic accept/discard for live variant sessions.
-
-Modes:
- --discard Remove variants, restore original
- --variant N Accept variant N, discard the rest
-
-Required:
- --id SESSION_ID Session ID of the variant wrapper
-
-Output (JSON):
- { handled, file, carbonize }`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const variantNum = argVal(args, '--variant');
- const paramValuesRaw = argVal(args, '--param-values');
- const isDiscard = args.includes('--discard');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }
-
- let paramValues = null;
- if (paramValuesRaw) {
- try { paramValues = JSON.parse(paramValuesRaw); }
- catch { paramValues = null; } // malformed blob: skip the comment rather than failing the accept
- }
-
- // Find the file containing this session's markers
- const found = findSessionFile(id, process.cwd());
- if (!found) {
- console.log(JSON.stringify({ handled: false, error: 'Session markers not found for id: ' + id }));
- process.exit(0);
- }
-
- const { file: targetFile, content, lines } = found;
- const relFile = path.relative(process.cwd(), targetFile);
-
- // Bail if the session lives in a generated file. The agent manually wrote
- // the wrapper there for preview, and is responsible for writing the
- // accepted variant to true source (or cleaning up on discard). See
- // "Handle fallback" in live.md.
- if (isGeneratedFile(targetFile, { cwd: process.cwd() })) {
- console.log(JSON.stringify({
- handled: false,
- mode: 'fallback',
- file: relFile,
- hint: 'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.',
- }));
- process.exit(0);
- }
-
- if (isDiscard) {
- const result = handleDiscard(id, lines, targetFile);
- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));
- } else {
- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);
- // Single-line attention-grabber when cleanup is required. The full
- // five-step checklist lives in reference/live.md (loaded once per
- // session); repeating it per-event would waste tokens.
- if (result.carbonize) {
- result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + relFile + '. See reference/live.md "Required after accept".';
- }
- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));
- }
-}
-
-// ---------------------------------------------------------------------------
-// Discard
-// ---------------------------------------------------------------------------
-
-function handleDiscard(id, lines, targetFile) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const original = extractOriginal(lines, block);
- const isJsx = detectCommentSyntax(targetFile).open === '{/*';
- const replaceRange = expandReplaceRange(block, lines, isJsx);
-
- // Restore at the line we're actually replacing FROM, not the marker line.
- // For JSX wrappers the marker comments live INSIDE the outer `<div>`, so
- // `block.start` sits 2 spaces deeper than the original element. Using that
- // as the deindent base would push the restored content 2 spaces too far
- // right on every JSX/TSX session. `replaceRange.start` is the outer wrapper
- // line, which is at the original element's indent for both HTML and JSX.
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
- const restored = deindentContent(original, indent);
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...restored,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
- return {};
-}
-
-// ---------------------------------------------------------------------------
-// Accept
-// ---------------------------------------------------------------------------
-
-function handleAccept(id, variantNum, lines, targetFile, paramValues) {
- const block = findMarkerBlock(id, lines);
- if (!block) return { handled: false, error: 'Markers not found' };
-
- const commentSyntax = detectCommentSyntax(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- // Anchor indent on the line we're replacing FROM (the outer wrapper),
- // not on `block.start` — for JSX that's the marker comment 2 spaces
- // deeper than the original element. See handleDiscard for the full
- // rationale.
- const replaceRange = expandReplaceRange(block, lines, isJsx);
- const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
-
- // Extract the chosen variant's inner content
- const variantContent = extractVariant(lines, block, variantNum);
- if (!variantContent) return { handled: false, error: 'Variant ' + variantNum + ' not found' };
-
- // Extract CSS block if present
- const cssContent = extractCss(lines, block, id);
-
- // Check if carbonizing is needed:
- // - CSS block exists, OR
- // - variant HTML contains helper classes/attributes that need cleanup
- const variantText = variantContent.join('\n');
- const hasHelperAttrs = variantText.includes('data-impeccable-variant');
- const needsCarbonize = !!(cssContent || hasHelperAttrs);
-
- // Build the replacement
- const restored = deindentContent(variantContent, indent);
- const replacement = [];
-
- if (cssContent) {
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
- // JSX targets need the CSS body wrapped in a template literal so that the
- // `{` and `}` in CSS rules don't get parsed as JSX expressions.
- replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
- // Re-indent CSS content to match
- for (const cssLine of cssContent) {
- replacement.push(indent + cssLine.trimStart());
- }
- replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
- if (paramValues && Object.keys(paramValues).length > 0) {
- // Preserve the user's knob positions for the carbonize-cleanup agent
- // to bake into the final CSS when it collapses scoped rules.
- replacement.push(indent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close);
- }
- replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close);
- }
-
- // Keep the `@scope ([data-impeccable-variant="N"])` selectors in the
- // carbonize CSS block working visually by re-wrapping the accepted content
- // in a data-impeccable-variant="N" div with `display: contents` (so layout
- // isn't affected). The carbonize agent strips this attribute + wrapper when
- // it moves the CSS to a proper stylesheet.
- //
- // Style attribute syntax has to follow the host file's flavor — JSX files
- // need the object form, otherwise React 19 throws "Failed to set indexed
- // property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
- if (cssContent) {
- const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
- replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
- replacement.push(...restored);
- replacement.push(indent + '</div>');
- } else {
- replacement.push(...restored);
- }
-
- const newLines = [
- ...lines.slice(0, replaceRange.start),
- ...replacement,
- ...lines.slice(replaceRange.end + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- return { carbonize: needsCarbonize };
-}
-
-// ---------------------------------------------------------------------------
-// Parsing helpers
-// ---------------------------------------------------------------------------
-
-/**
- * Find the start/end marker lines for a session.
- * Returns { start, end } (0-indexed line numbers) or null.
- */
-function findMarkerBlock(id, lines) {
- let start = -1;
- let end = -1;
- const startPattern = 'impeccable-variants-start ' + id;
- const endPattern = 'impeccable-variants-end ' + id;
-
- for (let i = 0; i < lines.length; i++) {
- if (start === -1 && lines[i].includes(startPattern)) start = i;
- if (lines[i].includes(endPattern)) { end = i; break; }
- }
-
- return (start !== -1 && end !== -1) ? { start, end } : null;
-}
-
-/**
- * Compute the line range to REPLACE (vs. just the marker range to extract
- * from). For JSX/TSX wrappers, live-wrap places the marker comments INSIDE
- * the `<div data-impeccable-variants="ID">` outer wrapper so the picked
- * element's JSX slot keeps a single child — a Fragment `<></>` would have
- * solved the multi-sibling case but failed inside `asChild` / cloneElement
- * parents with "Invalid prop supplied to React.Fragment".
- *
- * That means the marker block is enclosed by the wrapper `<div>` opener
- * (with `data-impeccable-variants="ID"`) and its matching `</div>`. We
- * walk back to the opener and forward to the closer so accept/discard
- * remove the entire scaffold, not just the inner markers.
- *
- * Marker lines themselves stay where they were so extractOriginal /
- * extractVariant / extractCss continue to walk the same range.
- */
-function expandReplaceRange(block, lines, isJsx) {
- if (!isJsx) return { start: block.start, end: block.end };
-
- let { start, end } = block;
-
- // Walk back for the wrapper `<div data-impeccable-variants="..."` opener.
- // The attr may sit on a continuation line of a multi-line opening tag, so
- // also walk to the line that actually contains `<div`.
- for (let i = start - 1; i >= Math.max(0, start - 12); i--) {
- if (/data-impeccable-variants=/.test(lines[i])) {
- let opener = i;
- while (opener > 0 && !/<div\b/.test(lines[opener])) opener--;
- start = opener;
- break;
- }
- }
-
- // Walk forward to the matching `</div>` by div-depth tracking from the
- // wrapper opener. Operate on JOINED text instead of per-line: a
- // multi-line self-closing JSX `<div\n className="spacer"\n/>` would
- // fool per-line regex tracking (the `<div` line matches openRe but the
- // `/>` line never matches selfCloseRe since it needs `<div` on the same
- // line). That left depth permanently over-counted and the wrapper's
- // outer `</div>` orphaned after accept/discard. Single regex with
- // `[^>]*?` (which spans newlines in JS) handles either form correctly.
- const joined = lines.slice(start).join('\n');
- // Match either `<div … />` (self-close, group 1 is `/`), `<div … >`
- // (open, group 1 is empty), or `</div>`.
- const tagRe = /<div\b[^>]*?(\/?)>|<\/div\s*>/g;
- let depth = 0;
- let m;
- while ((m = tagRe.exec(joined)) !== null) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && m[1] === '/';
- if (isClose) depth--;
- else if (!isSelfClose) depth++;
- if (depth <= 0) {
- // m.index is offset within `joined`; convert back to a file line.
- const linesBefore = joined.slice(0, m.index + m[0].length).split('\n').length - 1;
- const candidateEnd = start + linesBefore;
- if (candidateEnd >= end) {
- end = candidateEnd;
- break;
- }
- }
- }
-
- return { start, end };
-}
-
-/**
- * Join wrapper lines into a single string with `<style>` elements removed so
- * marker matching and div-depth tracking aren't confused by:
- * - CSS `@scope ([data-impeccable-variant="N"])` strings that look like the
- * HTML marker we're searching for
- * - JSX self-closing `<style ... />` (no separate `</style>` to close on)
- * - Same-line `<style>…</style>` blocks
- * - Multi-line `<style>\n…\n</style>` blocks
- */
-function stripStyleAndJoin(lines, block) {
- const out = [];
- let inStyle = false;
- for (let i = block.start; i <= block.end; i++) {
- let line = lines[i];
-
- if (!inStyle) {
- // Strip any complete <style> elements on this line (self-closed or
- // same-line-closed), including their body content.
- line = line
- .replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/g, '')
- .replace(/<style\b[^>]*\/\s*>/g, '');
-
- // If a <style> opener remains (multi-line body starts here), strip from
- // the opener to end-of-line and flip into skip mode.
- const openerIdx = line.search(/<style\b/);
- if (openerIdx !== -1) {
- line = line.slice(0, openerIdx);
- inStyle = true;
- }
- out.push(line);
- } else {
- // In multi-line style body; drop everything until we see </style>.
- const closeIdx = line.search(/<\/style\s*>/);
- if (closeIdx !== -1) {
- inStyle = false;
- out.push(line.slice(closeIdx).replace(/<\/style\s*>/, ''));
- }
- // else: skip line entirely
- }
- }
- return out.join('\n');
-}
-
-/**
- * Find the inner content of `<TAG ...attrMatch...>…</TAG>` inside `text`,
- * handling nested same-tag elements via depth counting. `attrMatch` is a
- * regex source fragment that must appear inside the opener tag.
- * Returns the inner string (may be empty), or null if not found.
- */
-function extractInnerByAttr(text, attrMatch) {
- const openerRe = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*' + attrMatch + '[^>]*>');
- const openMatch = text.match(openerRe);
- if (!openMatch) return null;
-
- const tagName = openMatch[1];
- const innerStart = openMatch.index + openMatch[0].length;
-
- // Match any opener or closer of this tag name after innerStart.
- // (Does not match self-closing <TAG … />, which doesn't contribute to depth.)
- const tagRe = new RegExp('<(?:/)?' + tagName + '\\b[^>]*>', 'g');
- tagRe.lastIndex = innerStart;
-
- let depth = 1;
- let m;
- while ((m = tagRe.exec(text))) {
- const isClose = m[0].startsWith('</');
- const isSelfClose = !isClose && /\/\s*>$/.test(m[0]);
- if (isClose) {
- depth--;
- if (depth === 0) return text.slice(innerStart, m.index);
- } else if (!isSelfClose) {
- depth++;
- }
- }
- return null;
-}
-
-/**
- * Extract the original element content from within the variant wrapper.
- * Returns an array of lines.
- */
-function extractOriginal(lines, block) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="original"');
- if (inner === null) return [];
- return inner.split('\n');
-}
-
-/**
- * Extract a specific variant's inner content (stripping the wrapper div).
- * Returns an array of lines, or null if not found.
- */
-function extractVariant(lines, block, variantNum) {
- const text = stripStyleAndJoin(lines, block);
- const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + variantNum + '"');
- if (inner === null) return null;
- const result = inner.split('\n');
- // Collapse a lone empty leading/trailing line (common after string splice).
- while (result.length > 1 && result[0].trim() === '') result.shift();
- while (result.length > 1 && result[result.length - 1].trim() === '') result.pop();
- return result.length > 0 ? result : null;
-}
-
-/**
- * Extract the colocated <style> block content (between the style tags).
- * Returns an array of CSS lines, or null if no style block found.
- *
- * Handles three shapes of `<style data-impeccable-css="ID" ...>`:
- * 1. Self-closing: `<style ... />` — no body; return null (nothing to carbonize).
- * 2. Same-line open+close: `<style>...</style>` — return the inner content.
- * 3. Multi-line: `<style>` on one line, `</style>` on a later line — return
- * the lines between them.
- */
-function extractCss(lines, block, id) {
- const styleAttr = 'data-impeccable-css="' + id + '"';
- let inStyle = false;
- const content = [];
-
- for (let i = block.start; i <= block.end; i++) {
- const line = lines[i];
-
- if (!inStyle && line.includes(styleAttr)) {
- // Self-closing: nothing to carbonize.
- if (/<style\b[^>]*\/\s*>/.test(line)) return null;
- // Same-line open + close: extract inner text.
- const sameLine = line.match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/);
- if (sameLine) {
- const inner = stripJsxTemplateWrap(sameLine[1]);
- return inner.length > 0 ? inner.split('\n') : null;
- }
- inStyle = true;
- continue; // skip the <style> opening tag
- }
-
- if (inStyle) {
- // Detect </style> anywhere on the line — JSX template-literal closes
- // (`}</style>`) put the close mid-line, and we don't want to absorb the
- // template-literal punctuation as CSS content.
- const closeIdx = line.indexOf('</style>');
- if (closeIdx !== -1) break;
- content.push(line);
- }
- }
-
- if (content.length === 0) return null;
- return stripJsxTemplateLines(content);
-}
-
-/**
- * Strip a JSX template-literal wrap (`{` … `}`) from CSS extracted out of a
- * `<style>` element in a JSX/TSX file. The agent may write the wrap with
- * `{` and `}` directly attached to the `<style>` tags, on their own lines,
- * or attached to the first/last CSS lines — all three are JSX-legal.
- *
- * Stripping is required because handleAccept re-wraps the CSS itself when
- * carbonizing. Without this, two consecutive accepts (or a previously-
- * accepted variants block being carbonized) would produce nested
- * `{` `{` … `}` `}`, which oxc rejects with "Expected `}` but found `@`".
- */
-function stripJsxTemplateLines(content) {
- const out = content.slice();
-
- // Drop any leading blank lines so we don't miss a `{` line buried below
- // them; same for trailing.
- while (out.length > 0 && out[0].trim() === '') out.shift();
- while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
- if (out.length === 0) return null;
-
- // Leading `{`: own line, or attached to the first CSS line.
- const firstTrim = out[0].trimStart();
- if (firstTrim === '{`') {
- out.shift();
- } else if (firstTrim.startsWith('{`')) {
- const idx = out[0].indexOf('{`');
- out[0] = out[0].slice(0, idx) + out[0].slice(idx + 2);
- if (out[0].trim() === '') out.shift();
- }
- if (out.length === 0) return null;
-
- // Trailing `` ` `` `}`: own line, or attached to the last CSS line.
- const lastIdx = out.length - 1;
- const lastTrim = out[lastIdx].trimEnd();
- if (lastTrim === '`}') {
- out.pop();
- } else if (lastTrim.endsWith('`}')) {
- const text = out[lastIdx];
- const idx = text.lastIndexOf('`}');
- out[lastIdx] = text.slice(0, idx) + text.slice(idx + 2);
- if (out[lastIdx].trim() === '') out.pop();
- }
-
- return out.length > 0 ? out : null;
-}
-
-function stripJsxTemplateWrap(text) {
- const lines = text.split('\n');
- const stripped = stripJsxTemplateLines(lines);
- return stripped ? stripped.join('\n') : '';
-}
-
-/**
- * De-indent content that was indented by live-wrap.mjs.
- * The wrap script adds `indent + ' '` (4 extra spaces) to each line.
- * We restore to just `indent` level.
- */
-function deindentContent(contentLines, baseIndent) {
- // Find the minimum indentation in the content to determine how much was added
- let minIndent = Infinity;
- for (const line of contentLines) {
- if (line.trim() === '') continue;
- const leadingSpaces = line.match(/^(\s*)/)[1].length;
- minIndent = Math.min(minIndent, leadingSpaces);
- }
- if (minIndent === Infinity) minIndent = 0;
-
- // Strip the extra indentation and re-add base indent
- return contentLines.map(line => {
- if (line.trim() === '') return '';
- return baseIndent + line.slice(minIndent);
- });
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- return { open: '<!--', close: '-->' };
-}
-
-// ---------------------------------------------------------------------------
-// File search (find the file containing session markers)
-// ---------------------------------------------------------------------------
-
-function findSessionFile(id, cwd) {
- const marker = 'impeccable-variants-start ' + id;
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, marker, seen, 0);
- if (result) {
- const content = fs.readFileSync(result, 'utf-8');
- return { file: result, content, lines: content.split('\n') };
- }
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth) {
- if (depth > 5) return null;
- let realDir;
- try { realDir = fs.realpathSync(dir); } catch { return null; }
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- if (!EXTENSIONS.includes(path.extname(entry.name).toLowerCase())) continue;
- const filePath = path.join(dir, entry.name);
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip */ }
- }
-
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
- if (result) return result;
- }
-
- return null;
-}
-
-// ---------------------------------------------------------------------------
-// Utilities
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-accept.mjs') || _running?.endsWith('live-accept.mjs/')) {
- acceptCli();
-}
-
-export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax };
@@ -1,123 +0,0 @@
-/**
- * Browser-side durable session helpers for Impeccable live mode.
- *
- * Kept separate from live-browser.js so recovery state can be tested without
- * booting the full overlay UI. Served before live-browser.js and attached to
- * window.__IMPECCABLE_LIVE_SESSION__.
- */
-(function (root) {
- 'use strict';
-
- function createLiveBrowserSessionState({ prefix, storage, idFactory }) {
- if (!prefix) throw new Error('prefix required');
- const store = storage || root.localStorage;
- const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };
- const sessionKey = prefix + '-session';
- const handledKey = sessionKey + '-handled';
- const scrollKey = sessionKey + '-scroll';
- let checkpointRevision = 0;
- const owner = makeId();
-
- function safeRead(key) {
- try { return store.getItem(key); } catch { return null; }
- }
-
- function safeWrite(key, value) {
- try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }
- }
-
- function safeRemove(key) {
- try { store.removeItem(key); } catch { /* unavailable storage */ }
- }
-
- function loadSession() {
- try {
- const raw = safeRead(sessionKey);
- if (!raw) return null;
- const parsed = JSON.parse(raw);
- if (Number.isInteger(parsed.checkpointRevision)) {
- checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);
- }
- return parsed;
- } catch { return null; }
- }
-
- function saveSession(session) {
- if (!session || !session.id) return;
- const payload = {
- ...session,
- checkpointRevision,
- };
- safeWrite(sessionKey, JSON.stringify(payload));
- }
-
- function clearSession() {
- safeRemove(sessionKey);
- }
-
- function nextCheckpointRevision() {
- checkpointRevision += 1;
- const existing = loadSession();
- if (existing?.id) saveSession(existing);
- return checkpointRevision;
- }
-
- function seedCheckpointRevision(value) {
- if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);
- return checkpointRevision;
- }
-
- function currentCheckpointRevision() {
- return checkpointRevision;
- }
-
- function markHandled(id) {
- if (!id) return;
- safeWrite(handledKey, id);
- }
-
- function isHandled(id) {
- return !!id && safeRead(handledKey) === id;
- }
-
- function clearHandled() {
- safeRemove(handledKey);
- }
-
- function writeScrollY(y) {
- safeWrite(scrollKey, String(y));
- }
-
- function readScrollY() {
- const raw = safeRead(scrollKey);
- if (raw == null) return null;
- const n = parseFloat(raw);
- return isFinite(n) ? n : null;
- }
-
- function clearScrollY() {
- safeRemove(scrollKey);
- }
-
- return {
- owner,
- sessionKey,
- handledKey,
- scrollKey,
- saveSession,
- loadSession,
- clearSession,
- nextCheckpointRevision,
- seedCheckpointRevision,
- currentCheckpointRevision,
- markHandled,
- isHandled,
- clearHandled,
- writeScrollY,
- readScrollY,
- clearScrollY,
- };
- }
-
- root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };
-})(typeof window !== 'undefined' ? window : globalThis);
@@ -1,4860 +0,0 @@
-/**
- * Impeccable Live Variant Mode — Browser Script
- *
- * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
- * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
- * before this code.
- *
- * UI: a single floating bar that morphs between three states —
- * configure (pick action + go), generating (progressive dots), and cycling
- * (prev/next + accept/discard). Feels like Spotlight, not a modal.
- */
-(function () {
- 'use strict';
- if (typeof window === 'undefined') return;
-
- // Guard against double-init. Bun's HTML loader may process the <script> tag
- // and create a bundled copy alongside the external load, or HMR may re-execute.
- // Check BEFORE reading token/port to catch all cases.
- if (window.__IMPECCABLE_LIVE_INIT__) return;
- window.__IMPECCABLE_LIVE_INIT__ = true;
-
- const TOKEN = window.__IMPECCABLE_TOKEN__;
- const PORT = window.__IMPECCABLE_PORT__;
- if (!TOKEN || !PORT) {
- window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
- return;
- }
-
- // ---------------------------------------------------------------------------
- // Design tokens
- // ---------------------------------------------------------------------------
-
- // Brand magenta is pinned to the site token (--color-accent in main.css)
- // so Accept / knobs / cycle-dots match the site's accent, not a washed
- // theme-adjusted one.
- const C = {
- brand: 'oklch(60% 0.25 350)',
- brandHov: 'oklch(52% 0.25 350)',
- brandSoft: 'oklch(60% 0.25 350 / 0.15)',
- ink: 'oklch(15% 0.01 350)',
- ash: 'oklch(55% 0 0)',
- paper: 'oklch(98% 0.005 350 / 0.92)',
- paperSolid:'oklch(98% 0.005 350)',
- mist: 'oklch(90% 0.01 350 / 0.6)',
- white: 'oklch(99% 0 0)',
- };
- const FONT = 'system-ui, -apple-system, sans-serif';
- const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
- // z-index: detect overlays use 99999, so our UI must be above them
- const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };
- const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
- const PREFIX = 'impeccable-live';
- const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
- prefix: PREFIX,
- storage: localStorage,
- idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),
- });
- if (!sessionState) {
- console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');
- window.__IMPECCABLE_LIVE_INIT__ = false;
- return;
- }
- const HIGHLIGHT_TRANSITION =
- 'top 140ms ' + EASE +
- ', left 140ms ' + EASE +
- ', width 140ms ' + EASE +
- ', height 140ms ' + EASE +
- ', opacity 150ms ease';
- const TOOLTIP_TRANSITION =
- 'top 140ms ' + EASE + ', left 140ms ' + EASE + ', opacity 150ms ease';
-
- const SKIP_TAGS = new Set([
- 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
- ]);
-
- // SVG icons stack above each chip label. All strokes use currentColor so the
- // icon recolors to C.brand when its chip is selected. 20x20 render, 24-viewBox,
- // 1.5 stroke — visually consistent with the Foundation grid on the homepage.
- const ICON_ATTRS = 'width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block"';
- const ICONS = {
- impeccable: `<svg ${ICON_ATTRS}><path d="M4 20l4-1L18 9l-3-3L5 16z"/><path d="M14 7l3 3"/></svg>`,
- bolder: `<svg ${ICON_ATTRS}><rect x="6" y="12" width="4" height="7" rx="0.5"/><rect x="14" y="5" width="4" height="14" rx="0.5"/></svg>`,
- quieter: `<svg ${ICON_ATTRS}><rect x="6" y="5" width="4" height="14" rx="0.5"/><rect x="14" y="12" width="4" height="7" rx="0.5"/></svg>`,
- distill: `<svg ${ICON_ATTRS}><path d="M4 5h16l-6 8v7l-4-2v-5z"/></svg>`,
- polish: `<svg ${ICON_ATTRS}><path d="M15 3l1 3 3 1-3 1-1 3-1-3-3-1 3-1z"/><path d="M7 13l0.6 1.8 1.8 0.6-1.8 0.6-0.6 1.8-0.6-1.8-1.8-0.6 1.8-0.6z"/></svg>`,
- typeset: `<svg ${ICON_ATTRS}><path d="M5 6h14" stroke-width="2.6"/><path d="M5 12h9" stroke-width="1.9"/><path d="M5 18h5" stroke-width="1.3"/></svg>`,
- colorize: `<svg ${ICON_ATTRS}><circle cx="9" cy="10" r="5"/><circle cx="15" cy="10" r="5"/><circle cx="12" cy="15" r="5"/></svg>`,
- layout: `<svg ${ICON_ATTRS}><rect x="3" y="4" width="8" height="16" rx="0.5"/><rect x="13" y="4" width="8" height="7" rx="0.5"/><rect x="13" y="13" width="8" height="7" rx="0.5"/></svg>`,
- adapt: `<svg ${ICON_ATTRS}><rect x="2.5" y="5" width="12" height="11" rx="1"/><line x1="2.5" y1="19" x2="14.5" y2="19"/><rect x="16.5" y="8" width="5" height="11" rx="1"/></svg>`,
- animate: `<svg ${ICON_ATTRS}><path d="M3 18c4-4 6-10 10-10"/><path d="M13 8c3 0 5 5 8 10"/><circle cx="13" cy="8" r="1.6" fill="currentColor" stroke="none"/></svg>`,
- delight: `<svg ${ICON_ATTRS}><path d="M12 3l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>`,
- overdrive: `<svg ${ICON_ATTRS}><path d="M13 3L5 13h5l-1 8 9-12h-6z"/></svg>`,
- };
-
- const ACTIONS = [
- { value: 'impeccable', label: 'Freeform' },
- { value: 'bolder', label: 'Bolder' },
- { value: 'quieter', label: 'Quieter' },
- { value: 'distill', label: 'Distill' },
- { value: 'polish', label: 'Polish' },
- { value: 'typeset', label: 'Typeset' },
- { value: 'colorize', label: 'Colorize' },
- { value: 'layout', label: 'Layout' },
- { value: 'adapt', label: 'Adapt' },
- { value: 'animate', label: 'Animate' },
- { value: 'delight', label: 'Delight' },
- { value: 'overdrive', label: 'Overdrive' },
- ];
-
- // ---------------------------------------------------------------------------
- // State
- // ---------------------------------------------------------------------------
-
- let state = 'IDLE';
- let hoveredElement = null;
- let selectedElement = null;
- let currentSessionId = null;
- let expectedVariants = 0;
- let arrivedVariants = 0;
- let visibleVariant = 0;
- let variantObserver = null;
- let hasProjectContext = false;
- let selectedAction = 'impeccable';
- let selectedCount = 3;
- const browserOwner = sessionState.owner;
- let checkpointTimer = null;
-
- // Scroll lock — holds window.scrollY at a fixed value while the session is
- // active, so HMR DOM patches and variant swaps can't drift the page. See
- // startScrollLock / stopScrollLock below.
- let scrollLockObserver = null;
- let scrollLockTargetY = null;
- let scrollLockRaf = null;
- let scrollLockAbort = null;
-
- // Dedicated key for scroll position — SEPARATE from LS_KEY so that
- // saveSession's state updates don't clobber a carefully-captured scrollY.
- // (Previously: saveSession wrote scrollY alongside state, so every call
- // during resume overwrote the pre-reload value with whatever the browser
- // had landed on, typically 0.)
- function writeScrollY(y) { sessionState.writeScrollY(y); }
- function readScrollY() { return sessionState.readScrollY(); }
- function clearScrollY() { sessionState.clearScrollY(); }
-
- // Pre-empt the browser: apply manual scroll restoration and jump to the
- // saved scrollY at script-parse time. Retries on fonts.ready and load
- // are essential: scrollTo(y) clamps to the current document.scrollHeight,
- // which is often hundreds of pixels short of the final value until
- // async-loaded fonts swap in and reflow.
- try {
- history.scrollRestoration = 'manual';
- const savedY = readScrollY();
- if (savedY != null) {
- const apply = () => {
- if (Math.abs(window.scrollY - savedY) > 0.5) {
- console.log('[impeccable.scroll] early restore', { from: window.scrollY, to: savedY });
- window.scrollTo(0, savedY);
- }
- };
- apply();
- if (document.fonts?.ready) document.fonts.ready.then(apply).catch(() => {});
- window.addEventListener('load', apply, { once: true });
- }
- } catch {}
-
- // UI refs
- let highlightEl = null;
- let tooltipEl = null;
- let barEl = null;
- let pickerEl = null;
- let toastEl = null;
- let scrollRaf = null;
-
- // ---------------------------------------------------------------------------
- // Helpers
- // ---------------------------------------------------------------------------
-
- function own(el) {
- return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
- }
-
- function pickable(el) {
- if (!el || el.nodeType !== 1) return false;
- if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
- if (own(el)) return false;
- const r = el.getBoundingClientRect();
- return r.width >= 20 && r.height >= 20;
- }
-
- function desc(el) {
- if (!el) return '';
- let s = el.tagName.toLowerCase();
- if (el.id) s += '#' + el.id;
- else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
- return s;
- }
-
- function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
-
- // Modal-aware chrome: keep our floating UI clickable inside Radix /
- // Headless UI / vaul portals.
- //
- // Two host-page behaviors break us when the picked element lives inside a
- // modal dialog:
- //
- // 1. Modal scroll-lock disables outside pointer events. Radix's
- // `DismissableLayer` sets `document.body.style.pointerEvents = 'none'`
- // while a modal is open and only restores `auto` on the layer. Our
- // chrome inherits `none` from <body> and becomes unclickable.
- // 2. The dialog's outside-interaction handler (Radix's
- // `usePointerDownOutside`) listens at document level and dismisses
- // the dialog whenever a `pointerdown` lands outside the layer node.
- // Our chrome is a sibling of <body>, so Radix classifies our clicks
- // as outside and tears the dialog down mid-task.
- //
- // We can't reliably re-parent our chrome into the dialog subtree (z-index
- // stacking, scroll containers, theming all become host-page concerns), so
- // we defang both behaviors at our root:
- //
- // - `pointer-events: auto !important` overrides the inherited `none`.
- // - Stop `pointerdown` / `mousedown` propagation so the document-level
- // dismiss listener never fires for our clicks.
- // - Stop `focusin` propagation so any focus shifts inside our chrome
- // don't read as "focus moved outside the dialog" to focus traps.
- //
- // Click events still bubble normally — only the early pointer/focus
- // signals that drive outside-interaction detection are silenced.
- function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
- if (!rootEl) return;
- if (setPointerEvents) {
- rootEl.style.setProperty('pointer-events', 'auto', 'important');
- }
- const stop = (e) => e.stopPropagation();
- rootEl.addEventListener('pointerdown', stop);
- rootEl.addEventListener('mousedown', stop);
- rootEl.addEventListener('focusin', stop);
- }
-
- // ---------------------------------------------------------------------------
- // Highlight overlay
- // ---------------------------------------------------------------------------
-
- function initHighlight() {
- highlightEl = document.createElement('div');
- highlightEl.id = PREFIX + '-highlight';
- Object.assign(highlightEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- border: '2px solid ' + C.brand, borderRadius: '3px',
- pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
- transition: HIGHLIGHT_TRANSITION,
- display: 'none', opacity: '0',
- });
- document.body.appendChild(highlightEl);
-
- tooltipEl = document.createElement('div');
- tooltipEl.id = PREFIX + '-tooltip';
- Object.assign(tooltipEl.style, {
- position: 'fixed',
- background: C.ink, color: C.white,
- fontFamily: MONO, fontSize: '10px', fontWeight: '500',
- padding: '2px 6px', borderRadius: '3px',
- zIndex: Z.highlight + 1, pointerEvents: 'none',
- whiteSpace: 'nowrap', display: 'none',
- letterSpacing: '0.02em',
- transition: TOOLTIP_TRANSITION,
- });
- document.body.appendChild(tooltipEl);
- }
-
- function showHighlight(el) {
- if (!el || !highlightEl) return;
- const r = el.getBoundingClientRect();
- const top = (r.top - 2) + 'px', left = (r.left - 2) + 'px';
- const width = (r.width + 4) + 'px', height = (r.height + 4) + 'px';
- const tipTop = r.top - 20;
- const tipY = (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px';
- const tipX = Math.max(4, r.left) + 'px';
- tooltipEl.textContent = desc(el);
-
- const hiWasHidden = highlightEl.style.display === 'none' || highlightEl.style.opacity === '0';
- if (hiWasHidden) {
- // Snap to first target without animating from (0,0), then fade in.
- highlightEl.style.transition = 'none';
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block' });
- tooltipEl.style.transition = 'none';
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block' });
- void highlightEl.offsetWidth;
- highlightEl.style.transition = HIGHLIGHT_TRANSITION;
- highlightEl.style.opacity = '1';
- tooltipEl.style.transition = TOOLTIP_TRANSITION;
- tooltipEl.style.opacity = '1';
- } else {
- Object.assign(highlightEl.style, { top, left, width, height, display: 'block', opacity: '1' });
- Object.assign(tooltipEl.style, { top: tipY, left: tipX, display: 'block', opacity: '1' });
- }
- }
-
- function hideHighlight() {
- if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
- if (tooltipEl) { tooltipEl.style.opacity = '0'; tooltipEl.style.display = 'none'; }
- }
-
- // ---------------------------------------------------------------------------
- // Annotation overlay (comment pins + magenta strokes)
- //
- // Active while state === 'CONFIGURING'. The overlay is a fixed-positioned
- // sibling of <body> mirroring selectedElement's bounding rect. Click (no
- // drag) drops a comment pin; drag paints a magenta SVG stroke. All coords
- // are stored in element-local CSS px so they survive scroll / resize and
- // correlate directly with the captured PNG.
- // ---------------------------------------------------------------------------
-
- const DRAG_THRESHOLD = 5; // px — below this, treat pointerup as a click
- const PIN_DBL_CLICK_MS = 300; // two clicks on the same pin within this delete it
- let annotOverlayEl = null;
- let annotSvgEl = null;
- let annotPinsEl = null;
- let annotClearChipEl = null;
- let annotState = { comments: [], strokes: [] };
- let annotActive = false;
- // `annotPointer` is either:
- // { kind: 'new', x0, y0, moved, strokeEl, strokePoints } creating a stroke/pin
- // { kind: 'pin', idx, startPointer, startPin, moved } dragging an existing pin
- let annotPointer = null;
- let annotEditing = null; // { idx, input, wrapEl }
- let annotLastPinClick = { idx: -1, time: 0 }; // for click-click-to-delete
-
- function initAnnotOverlay() {
- annotOverlayEl = document.createElement('div');
- annotOverlayEl.id = PREFIX + '-annot';
- Object.assign(annotOverlayEl.style, {
- position: 'fixed', top: '0', left: '0', width: '0', height: '0',
- pointerEvents: 'auto', zIndex: Z.highlight + 2,
- display: 'none', overflow: 'visible',
- cursor: 'crosshair', touchAction: 'none',
- });
-
- annotSvgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- annotSvgEl.id = PREFIX + '-annot-svg';
- Object.assign(annotSvgEl.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%',
- // The SVG itself doesn't absorb clicks; individual hit-paths opt-in via
- // pointer-events=stroke so gaps still fall through to the overlay.
- pointerEvents: 'none', overflow: 'visible',
- });
- annotOverlayEl.appendChild(annotSvgEl);
-
- annotPinsEl = document.createElement('div');
- annotPinsEl.id = PREFIX + '-annot-pins';
- Object.assign(annotPinsEl.style, {
- position: 'absolute', inset: '0',
- pointerEvents: 'none',
- });
- annotOverlayEl.appendChild(annotPinsEl);
-
- annotClearChipEl = document.createElement('div');
- annotClearChipEl.id = PREFIX + '-annot-clear';
- annotClearChipEl.dataset.annotClear = 'true';
- annotClearChipEl.textContent = 'Clear';
- Object.assign(annotClearChipEl.style, {
- position: 'absolute', top: '8px', right: '8px',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '10px', fontWeight: '500',
- letterSpacing: '0.08em', textTransform: 'uppercase',
- padding: '5px 12px', borderRadius: '999px',
- cursor: 'pointer', pointerEvents: 'auto',
- display: 'none', userSelect: 'none',
- boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
- });
- annotOverlayEl.appendChild(annotClearChipEl);
-
- annotOverlayEl.addEventListener('pointerdown', onAnnotDown);
- annotOverlayEl.addEventListener('pointermove', onAnnotMove);
- annotOverlayEl.addEventListener('pointerup', onAnnotUp);
- annotOverlayEl.addEventListener('pointercancel', onAnnotUp);
- document.body.appendChild(annotOverlayEl);
- // Modal-host friendliness: pointer-events is already 'auto' on this
- // overlay; we only need to silence the host's outside-interaction
- // listeners. Don't override pointer-events here (the overlay toggles
- // visibility via display:none, which is fine).
- defangOutsideHandlers(annotOverlayEl, { setPointerEvents: false });
- }
-
- function updateClearChip() {
- if (!annotClearChipEl) return;
- const hasAny = annotState.comments.length > 0 || annotState.strokes.length > 0;
- annotClearChipEl.style.display = hasAny ? 'block' : 'none';
- }
-
- function showAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- annotActive = true;
- positionAnnotOverlay(el);
- annotOverlayEl.style.display = 'block';
- }
-
- function hideAnnotOverlay() {
- annotActive = false;
- if (annotOverlayEl) annotOverlayEl.style.display = 'none';
- // Drop any in-progress edit without touching annotState — clearAnnotations
- // (if the caller is exiting configure mode) handles state reset.
- annotEditing = null;
- }
-
- function positionAnnotOverlay(el) {
- if (!annotOverlayEl || !el) return;
- const r = el.getBoundingClientRect();
- Object.assign(annotOverlayEl.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- annotSvgEl.setAttribute('viewBox', '0 0 ' + r.width + ' ' + r.height);
- }
-
- function clearAnnotations() {
- annotState.comments = [];
- annotState.strokes = [];
- if (annotSvgEl) while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- if (annotPinsEl) annotPinsEl.innerHTML = '';
- annotPointer = null;
- annotEditing = null;
- annotLastPinClick = { idx: -1, time: 0 };
- updateClearChip();
- }
-
- // Rebuild the SVG layer. Each stroke gets a wider invisible hit path
- // beneath the visible magenta path so clicks register on thin lines.
- function redrawStrokes() {
- while (annotSvgEl.firstChild) annotSvgEl.removeChild(annotSvgEl.firstChild);
- annotState.strokes.forEach((s, idx) => {
- const d = pointsToPath(s.points);
- const hit = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- hit.setAttribute('d', d);
- hit.setAttribute('stroke', 'transparent');
- hit.setAttribute('stroke-width', '16');
- hit.setAttribute('stroke-linecap', 'round');
- hit.setAttribute('stroke-linejoin', 'round');
- hit.setAttribute('fill', 'none');
- hit.setAttribute('pointer-events', 'stroke');
- hit.style.cursor = 'pointer';
- hit.dataset.annotStroke = String(idx);
- annotSvgEl.appendChild(hit);
- const visible = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- visible.setAttribute('d', d);
- visible.setAttribute('stroke', C.brand);
- visible.setAttribute('stroke-width', '3');
- visible.setAttribute('stroke-linecap', 'round');
- visible.setAttribute('stroke-linejoin', 'round');
- visible.setAttribute('fill', 'none');
- visible.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(visible);
- });
- updateClearChip();
- }
-
- function localCoords(e) {
- const rect = annotOverlayEl.getBoundingClientRect();
- return { x: e.clientX - rect.left, y: e.clientY - rect.top };
- }
-
- function onAnnotDown(e) {
- if (!annotActive) return;
-
- // 1) Clear chip → wipe all annotations
- if (e.target.closest?.('[data-annot-clear]')) {
- if (annotEditing) annotEditing = null;
- clearAnnotations();
- renderAllPins();
- redrawStrokes();
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 2) Stroke hit path → delete that stroke
- const strokeHit = e.target.closest?.('[data-annot-stroke]');
- if (strokeHit) {
- const idx = parseInt(strokeHit.dataset.annotStroke, 10);
- if (Number.isInteger(idx)) {
- annotState.strokes.splice(idx, 1);
- redrawStrokes();
- }
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 3) Pin → drag, edit, or delete-on-double-click
- const pinWrap = e.target.closest?.('[data-annot-pin]');
- if (pinWrap) {
- const idx = parseInt(pinWrap.dataset.annotPin, 10);
- if (!Number.isInteger(idx)) return;
- // Double-click (two pointerdowns on the same pin within window) → delete.
- const now = Date.now();
- if (annotLastPinClick.idx === idx && now - annotLastPinClick.time < PIN_DBL_CLICK_MS) {
- if (annotEditing && annotEditing.idx === idx) annotEditing = null;
- annotState.comments.splice(idx, 1);
- annotLastPinClick = { idx: -1, time: 0 };
- renderAllPins();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- annotLastPinClick = { idx, time: now };
- // If editing a different pin, commit that edit before starting here.
- if (annotEditing && annotEditing.idx !== idx) finalizeEditingPin();
- // If already editing THIS pin and the user clicked the dot, let the
- // input keep focus (don't start a drag — the click wasn't meant as one).
- if (annotEditing && annotEditing.idx === idx) return;
- const p = localCoords(e);
- const pin = annotState.comments[idx];
- annotPointer = {
- kind: 'pin', idx,
- startPointer: p,
- startPin: { x: pin.x, y: pin.y },
- moved: false,
- };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- return;
- }
-
- // 4) Empty area → commit any open edit, then start new annotation
- if (annotEditing) {
- finalizeEditingPin();
- e.stopPropagation(); e.preventDefault();
- return;
- }
- const p = localCoords(e);
- annotPointer = { kind: 'new', x0: p.x, y0: p.y, moved: false, strokeEl: null, strokePoints: null };
- try { annotOverlayEl.setPointerCapture(e.pointerId); } catch {}
- e.stopPropagation(); e.preventDefault();
- }
-
- function onAnnotMove(e) {
- if (!annotActive || !annotPointer) return;
- const p = localCoords(e);
-
- if (annotPointer.kind === 'pin') {
- const dx = p.x - annotPointer.startPointer.x;
- const dy = p.y - annotPointer.startPointer.y;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- }
- const pin = annotState.comments[annotPointer.idx];
- if (!pin) { annotPointer = null; return; }
- pin.x = annotPointer.startPin.x + dx;
- pin.y = annotPointer.startPin.y + dy;
- renderAllPins();
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const dx = p.x - annotPointer.x0, dy = p.y - annotPointer.y0;
- if (!annotPointer.moved) {
- if (Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
- annotPointer.moved = true;
- const strokeEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- strokeEl.setAttribute('stroke', C.brand);
- strokeEl.setAttribute('stroke-width', '3');
- strokeEl.setAttribute('stroke-linecap', 'round');
- strokeEl.setAttribute('stroke-linejoin', 'round');
- strokeEl.setAttribute('fill', 'none');
- strokeEl.setAttribute('pointer-events', 'none');
- annotSvgEl.appendChild(strokeEl);
- annotPointer.strokeEl = strokeEl;
- annotPointer.strokePoints = [[annotPointer.x0, annotPointer.y0]];
- }
- annotPointer.strokePoints.push([p.x, p.y]);
- annotPointer.strokeEl.setAttribute('d', pointsToPath(annotPointer.strokePoints));
- e.stopPropagation();
- }
-
- function onAnnotUp(e) {
- if (!annotActive || !annotPointer) return;
-
- if (annotPointer.kind === 'pin') {
- const wasDrag = annotPointer.moved;
- const idx = annotPointer.idx;
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- if (wasDrag) {
- // A drag is an intentional reposition; a follow-up click shouldn't be
- // interpreted as a double-click-to-delete.
- annotLastPinClick = { idx: -1, time: 0 };
- } else {
- beginEditPin(idx);
- }
- e.stopPropagation();
- return;
- }
-
- // kind === 'new'
- const wasDrag = annotPointer.moved;
- if (wasDrag) {
- annotState.strokes.push({ points: annotPointer.strokePoints });
- // Swap the temporary preview SVG path for the full render with hit paths.
- redrawStrokes();
- } else {
- const idx = annotState.comments.length;
- annotState.comments.push({ x: annotPointer.x0, y: annotPointer.y0, text: '' });
- renderAllPins();
- beginEditPin(idx);
- }
- try { annotOverlayEl.releasePointerCapture(e.pointerId); } catch {}
- annotPointer = null;
- e.stopPropagation();
- }
-
- function pointsToPath(points) {
- if (!points || points.length === 0) return '';
- let d = 'M' + points[0][0].toFixed(1) + ' ' + points[0][1].toFixed(1);
- for (let i = 1; i < points.length; i++) {
- d += ' L' + points[i][0].toFixed(1) + ' ' + points[i][1].toFixed(1);
- }
- return d;
- }
-
- function renderAllPins() {
- annotPinsEl.innerHTML = '';
- annotState.comments.forEach((c, idx) => {
- annotPinsEl.appendChild(buildPinElement(c, idx));
- });
- updateClearChip();
- }
-
- function buildPinElement(comment, idx) {
- const interactive = idx >= 0;
- const wrap = document.createElement('div');
- if (interactive) wrap.dataset.annotPin = String(idx);
- Object.assign(wrap.style, {
- position: 'absolute',
- left: (comment.x - 7) + 'px', top: (comment.y - 7) + 'px',
- pointerEvents: interactive ? 'auto' : 'none',
- display: 'flex', alignItems: 'flex-start', gap: '6px',
- cursor: interactive ? 'grab' : 'default',
- touchAction: 'none',
- });
- const dot = document.createElement('div');
- Object.assign(dot.style, {
- width: '14px', height: '14px', borderRadius: '50%',
- background: C.brand, border: '2px solid ' + C.white,
- boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
- flexShrink: '0',
- });
- wrap.appendChild(dot);
-
- if (comment.text) {
- const bubble = document.createElement('div');
- bubble.textContent = comment.text;
- Object.assign(bubble.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- marginTop: '-2px', maxWidth: '220px',
- pointerEvents: 'none', whiteSpace: 'pre-wrap',
- wordBreak: 'break-word',
- });
- wrap.appendChild(bubble);
- }
- return wrap;
- }
-
- function beginEditPin(idx) {
- const wrapEl = annotPinsEl.querySelector('[data-annot-pin="' + idx + '"]');
- if (!wrapEl) return;
- // Strip any existing bubble (but keep the dot)
- wrapEl.querySelectorAll('div:not(:first-child)').forEach(n => n.remove());
- const input = document.createElement('input');
- input.type = 'text';
- input.placeholder = 'Note…';
- Object.assign(input.style, {
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px', lineHeight: '1.4',
- padding: '4px 8px', borderRadius: '3px',
- border: '1px solid ' + C.brand,
- outline: 'none', marginTop: '-2px',
- width: '220px', pointerEvents: 'auto',
- });
- const originalText = annotState.comments[idx].text || '';
- input.value = originalText;
- wrapEl.appendChild(input);
- annotEditing = { idx, input, wrapEl, originalText };
- input.addEventListener('keydown', onAnnotInputKey, true);
- input.addEventListener('blur', () => {
- // Fires on both focus-loss and programmatic blur; commit unless we
- // already handled it.
- if (annotEditing && annotEditing.input === input) finalizeEditingPin();
- });
- // Stop clicks/pointerdowns inside the input from bubbling to the overlay
- ['pointerdown', 'click'].forEach(ev => {
- input.addEventListener(ev, e => e.stopPropagation());
- });
- setTimeout(() => input.focus(), 0);
- }
-
- function onAnnotInputKey(e) {
- if (e.key === 'Enter') {
- e.preventDefault(); e.stopPropagation();
- finalizeEditingPin();
- } else if (e.key === 'Escape') {
- e.preventDefault(); e.stopPropagation();
- cancelEditingPin();
- } else {
- // Keep arrows / backspace from hitting global handlers
- e.stopPropagation();
- }
- }
-
- function finalizeEditingPin() {
- if (!annotEditing) return;
- const { idx, input } = annotEditing;
- const text = input.value.trim();
- annotEditing = null;
- if (text) annotState.comments[idx].text = text;
- else annotState.comments.splice(idx, 1);
- renderAllPins();
- }
-
- function cancelEditingPin() {
- if (!annotEditing) return;
- const { idx, originalText } = annotEditing;
- annotEditing = null;
- // If the pin had text before this edit, revert to it. If it was a
- // just-created empty pin, Escape removes it.
- if (originalText) {
- annotState.comments[idx].text = originalText;
- } else {
- annotState.comments.splice(idx, 1);
- }
- renderAllPins();
- }
-
- // Build a detached annotation subtree suitable for injection into the clone
- // modern-screenshot creates. Coordinates are element-local so this slots
- // straight into an element that's been made position:relative. Takes an
- // explicit snapshot so it works after annotState has been cleared.
- function buildAnnotationsForCapture(rect, snapshot) {
- const comments = snapshot ? snapshot.comments : annotState.comments;
- const strokes = snapshot ? snapshot.strokes : annotState.strokes;
- if (comments.length === 0 && strokes.length === 0) return null;
- const wrap = document.createElement('div');
- Object.assign(wrap.style, {
- position: 'absolute', top: '0', left: '0',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none', overflow: 'visible',
- });
- if (strokes.length > 0) {
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- svg.setAttribute('viewBox', '0 0 ' + rect.width + ' ' + rect.height);
- Object.assign(svg.style, {
- position: 'absolute', top: '0', left: '0',
- width: '100%', height: '100%', overflow: 'visible',
- });
- for (const s of strokes) {
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- path.setAttribute('stroke', C.brand);
- path.setAttribute('stroke-width', '3');
- path.setAttribute('stroke-linecap', 'round');
- path.setAttribute('stroke-linejoin', 'round');
- path.setAttribute('fill', 'none');
- path.setAttribute('d', pointsToPath(s.points));
- svg.appendChild(path);
- }
- wrap.appendChild(svg);
- }
- for (const c of comments) {
- // idx=-1 means non-interactive; pointerEvents stay off in the clone
- wrap.appendChild(buildPinElement(c, -1));
- }
- return wrap;
- }
-
- // ---------------------------------------------------------------------------
- // Element context extraction
- // ---------------------------------------------------------------------------
-
- function extractContext(el) {
- const cs = getComputedStyle(el);
- const r = el.getBoundingClientRect();
- const props = {};
- for (const sheet of document.styleSheets) {
- try {
- for (const rule of sheet.cssRules) {
- if (rule.style) for (let i = 0; i < rule.style.length; i++) {
- const p = rule.style[i];
- if (p.startsWith('--') && !props[p]) {
- const v = cs.getPropertyValue(p).trim();
- if (v) props[p] = v;
- }
- }
- }
- } catch { /* cross-origin */ }
- }
- return {
- tagName: el.tagName.toLowerCase(), id: el.id || null,
- classes: [...el.classList],
- textContent: (el.textContent || '').slice(0, 500),
- outerHTML: el.outerHTML.slice(0, 10000),
- computedStyles: {
- 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
- 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
- 'color': cs.color, 'background': cs.background,
- 'background-color': cs.backgroundColor,
- 'padding': cs.padding, 'margin': cs.margin,
- 'display': cs.display, 'position': cs.position,
- 'gap': cs.gap, 'border-radius': cs.borderRadius,
- 'box-shadow': cs.boxShadow,
- },
- cssCustomProperties: props,
- parentContext: el.parentElement
- ? '<' + el.parentElement.tagName.toLowerCase()
- + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
- + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
- + '>'
- : null,
- boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
- };
- }
-
- // ---------------------------------------------------------------------------
- // The Bar — one floating element, three modes
- // ---------------------------------------------------------------------------
-
- // Contextual-bar palette. Cached at init so every build*Row reads a
- // consistent set of colors; detectPageTheme runs once rather than on every
- // phase transition.
- let BP = null;
-
- // Bar shadow variants. The default projects down + subtle around. When
- // the Tune popover opens below the bar, a downward shadow lands on the
- // dark popover and reads as a bright ghost line. We swap to UP-only while
- // tune is open below so the popover's top edge is clean.
- const BAR_SHADOW_DEFAULT = '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_UP = '0 -4px 20px oklch(0% 0 0 / 0.08), 0 -1px 3px oklch(0% 0 0 / 0.06)';
- const BAR_SHADOW_DOWN = BAR_SHADOW_DEFAULT;
-
- function initBar() {
- BP = barPaletteForTheme(detectPageTheme());
- barEl = document.createElement('div');
- barEl.id = PREFIX + '-bar';
- Object.assign(barEl.style, {
- position: 'fixed', zIndex: Z.bar,
- display: 'none', opacity: '0',
- transform: 'translateY(6px)',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- background: BP.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + BP.hairline,
- borderRadius: '10px',
- boxShadow: BAR_SHADOW_DEFAULT,
- transition: 'box-shadow 0.2s ease, opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
- fontFamily: FONT, fontSize: '13px', color: BP.text,
- padding: '6px',
- maxWidth: '520px', minWidth: '320px',
- });
- document.body.appendChild(barEl);
- defangOutsideHandlers(barEl);
- }
-
- function positionBar() {
- if (!barEl || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- const barH = barEl.offsetHeight || 44;
- const barW = barEl.offsetWidth || 380;
- const GLOBAL_BAR_RESERVE = 64; // global bar height + bottom margin + breathing room
- const GAP = 8;
-
- // Prefer below the element; fall back to above; if neither fits (element
- // taller than viewport), pin to a stable viewport anchor so the bar
- // doesn't teleport between top and bottom as the user scrolls.
- let top;
- const belowTop = r.bottom + GAP;
- const aboveTop = r.top - barH - GAP;
- if (belowTop + barH + GAP <= window.innerHeight - GLOBAL_BAR_RESERVE) {
- top = belowTop;
- } else if (aboveTop >= GAP) {
- top = aboveTop;
- } else {
- top = window.innerHeight - barH - GLOBAL_BAR_RESERVE;
- }
-
- let left = r.left + (r.width - barW) / 2;
- if (left < GAP) left = GAP;
- if (left + barW > window.innerWidth - GAP) left = window.innerWidth - barW - GAP;
- Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
- }
-
- function showBar(mode) {
- barEl.innerHTML = '';
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- barEl.style.display = 'block';
- positionBar();
- requestAnimationFrame(() => {
- barEl.style.opacity = '1';
- barEl.style.transform = 'translateY(0)';
- });
- }
-
- function hideBar() {
- if (!barEl) return;
- barEl.style.opacity = '0';
- barEl.style.transform = 'translateY(6px)';
- setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
- hideActionPicker();
- closeTunePopover();
- }
-
- function updateBarContent(mode) {
- if (!barEl || barEl.style.display === 'none') return;
- barEl.innerHTML = '';
- // Reset bar styling to the theme-aware palette
- barEl.style.background = BP.surface;
- barEl.style.border = '1px solid ' + BP.hairline;
- if (mode === 'configure') barEl.appendChild(buildConfigureRow());
- else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
- else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
- else if (mode === 'saving') barEl.appendChild(buildSavingRow());
- else if (mode === 'confirmed') {
- barEl.appendChild(buildConfirmedRow());
- barEl.style.background = 'oklch(95% 0.05 145)';
- barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
- }
- }
-
- // --- Configure row ---
-
- function buildConfigureRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
-
- // Action pill
- const pill = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '4px',
- padding: '5px 10px', borderRadius: '6px',
- background: BP.mark, color: BP.markText,
- fontFamily: FONT, fontSize: '12px', fontWeight: '500',
- border: 'none', cursor: 'pointer',
- transition: 'background 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap', flexShrink: '0',
- });
- pill.textContent = actionLabel() + ' \u25BE';
- pill.addEventListener('mouseenter', () => pill.style.background = BP.accent);
- pill.addEventListener('mouseleave', () => pill.style.background = BP.mark);
- pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
- pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
- pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
- row.appendChild(pill);
-
- // Freeform input. Focus state shows an accent-colored border only —
- // an earlier version tinted the background with `BP.accentSoft`, which
- // composited against the dark bar surface to a murky purple where the
- // browser's default placeholder gray was unreadable. Placeholder color
- // is set explicitly via a one-shot stylesheet keyed off this input's id
- // so it picks up the bar's `textDim` token in both themes.
- const input = document.createElement('input');
- input.id = PREFIX + '-input';
- input.type = 'text';
- input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
- Object.assign(input.style, {
- flex: '1', minWidth: '0',
- padding: '5px 8px', borderRadius: '6px',
- border: '1px solid transparent', background: 'transparent',
- fontFamily: FONT, fontSize: '12px', color: BP.text,
- outline: 'none',
- transition: 'border-color 0.15s ease',
- });
- if (!document.getElementById(PREFIX + '-input-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-input-style';
- s.textContent =
- '#' + PREFIX + '-input::placeholder { color: ' + BP.textDim + '; opacity: 1; }';
- document.head.appendChild(s);
- }
- input.addEventListener('focus', () => {
- input.style.borderColor = BP.accent;
- });
- input.addEventListener('blur', () => {
- input.style.borderColor = 'transparent';
- });
- input.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') { e.stopPropagation(); e.preventDefault(); handleGo(); return; }
- if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; return; }
- // Let arrow keys pass through to the element picker when the input is empty
- if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && !input.value) return;
- e.stopPropagation();
- });
- row.appendChild(input);
-
- // Variant count toggle
- const count = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: MONO, fontSize: '11px', fontWeight: '600',
- color: BP.textDim, cursor: 'pointer',
- transition: 'color 0.12s ease, border-color 0.12s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- count.textContent = '\u00D7' + selectedCount;
- count.title = 'Variants: click to change';
- count.addEventListener('mouseenter', () => { count.style.color = BP.text; count.style.borderColor = BP.text; });
- count.addEventListener('mouseleave', () => { count.style.color = BP.textDim; count.style.borderColor = BP.hairline; });
- count.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
- count.textContent = '\u00D7' + selectedCount;
- });
- row.appendChild(count);
-
- // Go button
- const go = el('button', {
- padding: '5px 12px', borderRadius: '6px',
- border: 'none', background: BP.accent, color: BP.mark,
- fontFamily: FONT, fontSize: '12px', fontWeight: '600',
- cursor: 'pointer',
- transition: 'filter 0.12s ease, transform 0.1s ease',
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- go.textContent = 'Go \u2192';
- go.addEventListener('mouseenter', () => go.style.filter = 'brightness(1.1)');
- go.addEventListener('mouseleave', () => go.style.filter = 'none');
- go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
- go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
- go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
- row.appendChild(go);
-
- // Auto-focus input after a beat
- setTimeout(() => input.focus(), 60);
- return row;
- }
-
- // --- Generating row ---
-
- function buildGeneratingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 4px',
- });
-
- // Action label
- const label = el('span', {
- fontWeight: '600', fontSize: '12px', color: BP.text,
- flexShrink: '0', whiteSpace: 'nowrap',
- });
- label.textContent = actionLabel();
- row.appendChild(label);
-
- // Dots
- row.appendChild(buildDots(false));
-
- // Status
- const status = el('span', {
- fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',
- marginLeft: 'auto',
- });
- // Variants currently arrive atomically in a single file edit, so a
- // per-variant counter would lie. Say what's true.
- status.textContent = arrivedVariants < expectedVariants
- ? 'Generating ' + expectedVariants + ' variants...'
- : 'Done';
- row.appendChild(status);
-
- return row;
- }
-
- // --- Cycling row ---
-
- const TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';
-
- function buildCyclingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '6px',
- padding: '1px 2px',
- });
-
- // Prev
- const prev = navBtn('\u2190');
- prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
- if (visibleVariant <= 1) prev.style.opacity = '0.3';
- row.appendChild(prev);
-
- // Dots (clickable)
- row.appendChild(buildDots(true));
-
- // Counter
- const counter = el('span', {
- fontFamily: MONO, fontSize: '11px', fontWeight: '500',
- color: BP.textDim, minWidth: '24px', textAlign: 'center',
- });
- counter.textContent = visibleVariant + '/' + arrivedVariants;
- row.appendChild(counter);
-
- // Next
- const next = navBtn('\u2192');
- next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
- if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
- row.appendChild(next);
-
- // Tune chip — only when the visible variant exposes params
- const visParams = parseVariantParams(getVisibleVariantEl());
- const hasParams = visParams.length > 0;
- if (hasParams) {
- const tune = el('button', {
- display: 'inline-flex', alignItems: 'center', gap: '6px',
- padding: '4px 10px', borderRadius: '5px',
- border: '1px solid transparent',
- background: tuneOpen ? BP.accentSoft : 'transparent',
- color: tuneOpen ? BP.accent : BP.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'color 0.12s ease, background 0.12s ease',
- whiteSpace: 'nowrap',
- });
- tune.innerHTML = TUNE_ICON_SVG;
- const tuneLabel = document.createElement('span');
- tuneLabel.textContent = 'Tune';
- tune.appendChild(tuneLabel);
- const tuneBadge = document.createElement('span');
- Object.assign(tuneBadge.style, {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- minWidth: '16px', height: '16px', padding: '0 4px',
- borderRadius: '999px',
- background: tuneOpen ? C.brand : BP.hairline,
- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',
- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',
- lineHeight: '1',
- boxSizing: 'border-box',
- });
- tuneBadge.textContent = String(visParams.length);
- tune.appendChild(tuneBadge);
- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';
- tune.addEventListener('mouseenter', () => {
- if (!tuneOpen) tune.style.background = BP.accentSoft;
- });
- tune.addEventListener('mouseleave', () => {
- if (!tuneOpen) tune.style.background = 'transparent';
- });
- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });
- tune.dataset.iceqTune = '1';
- row.appendChild(tune);
- }
-
- // Spacer
- row.appendChild(el('div', { flex: '1' }));
-
- // Accept — primary action, uses the site's saturated brand magenta
- // with paper-white text, not the theme-muted BP.accent.
- const accept = el('button', {
- padding: '5px 14px', borderRadius: '5px',
- border: 'none', background: C.brand, color: 'oklch(98% 0 0)',
- fontFamily: FONT, fontSize: '11px', fontWeight: '600',
- cursor: 'pointer', transition: 'filter 0.12s ease, transform 0.1s ease',
- whiteSpace: 'nowrap',
- });
- accept.textContent = '\u2713 Accept';
- accept.addEventListener('mouseenter', () => accept.style.filter = 'brightness(1.08)');
- accept.addEventListener('mouseleave', () => accept.style.filter = 'none');
- accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');
- accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');
- accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
- row.appendChild(accept);
-
- // Discard
- const discard = el('button', {
- padding: '4px 6px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- fontFamily: FONT, fontSize: '11px', color: BP.textDim,
- cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
- });
- discard.textContent = '\u2715';
- discard.title = 'Discard all variants';
- discard.addEventListener('mouseenter', () => { discard.style.color = BP.text; discard.style.borderColor = BP.text; });
- discard.addEventListener('mouseleave', () => { discard.style.color = BP.textDim; discard.style.borderColor = BP.hairline; });
- discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
- row.appendChild(discard);
-
- return row;
- }
-
- // --- Shared UI builders ---
-
- // --- Saving row (waiting for agent to process accept/discard) ---
-
- function buildSavingRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const spinner = el('div', {
- width: '14px', height: '14px', borderRadius: '50%',
- border: '2px solid ' + BP.hairline,
- borderTopColor: BP.accent,
- animation: 'impeccable-spin 0.6s linear infinite',
- flexShrink: '0',
- });
- row.appendChild(spinner);
- const label = el('span', {
- fontSize: '12px', color: BP.textDim, fontWeight: '500',
- });
- label.textContent = 'Applying variant...';
- row.appendChild(label);
-
- // Inject the keyframes if not already present
- if (!document.getElementById(PREFIX + '-keyframes')) {
- const style = document.createElement('style');
- style.id = PREFIX + '-keyframes';
- style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
- document.head.appendChild(style);
- }
- return row;
- }
-
- // --- Confirmed row (green success, auto-dismisses) ---
-
- function buildConfirmedRow() {
- const row = el('div', {
- display: 'flex', alignItems: 'center', gap: '8px',
- padding: '2px 8px',
- });
- const check = el('span', {
- fontSize: '15px', lineHeight: '1', flexShrink: '0',
- color: 'oklch(45% 0.15 145)',
- });
- check.textContent = '\u2713';
- row.appendChild(check);
- const label = el('span', {
- fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
- });
- label.textContent = 'Variant applied';
- row.appendChild(label);
- return row;
- }
-
- // --- Shared UI builders ---
-
- function buildDots(clickable) {
- const container = el('div', {
- display: 'flex', alignItems: 'center', gap: '4px',
- });
- for (let i = 1; i <= expectedVariants; i++) {
- const arrived = i <= arrivedVariants;
- const active = i === visibleVariant;
- // active: solid site-brand magenta dot. arrived+inactive: muted neutral.
- // pending (not yet arrived): faint outline ring. No borders on arrived
- // dots — the previous "accent ring + ash fill" combo read as noisy
- // magenta chips, especially when all variants had arrived and every
- // dot wore an accent ring.
- const dotBg = active ? C.brand
- : arrived ? BP.textDim
- : 'transparent';
- const dotBorder = arrived ? 'none' : '1.5px solid ' + BP.hairline;
- const dot = el('div', {
- width: active ? '8px' : '6px',
- height: active ? '8px' : '6px',
- borderRadius: '50%',
- background: dotBg,
- border: dotBorder,
- boxSizing: 'border-box',
- transition: 'all 0.2s ' + EASE,
- cursor: (clickable && arrived) ? 'pointer' : 'default',
- transform: arrived ? 'scale(1)' : 'scale(0.85)',
- opacity: arrived ? (active ? '1' : '0.6') : '0.4',
- });
- if (clickable && arrived) {
- const idx = i;
- dot.addEventListener('click', (e) => {
- e.stopPropagation();
- visibleVariant = idx;
- showVariantInDOM(currentSessionId, idx);
- updateSelectedElement();
- updateBarContent('cycling');
- });
- }
- container.appendChild(dot);
- }
- return container;
- }
-
- function navBtn(text) {
- const b = el('button', {
- width: '26px', height: '26px', borderRadius: '5px',
- border: '1px solid ' + BP.hairline, background: 'transparent',
- color: BP.text, fontFamily: FONT, fontSize: '13px',
- cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
- transition: 'border-color 0.12s ease, background 0.12s ease',
- padding: '0', lineHeight: '1',
- });
- b.textContent = text;
- b.addEventListener('mouseenter', () => { b.style.borderColor = BP.text; });
- b.addEventListener('mouseleave', () => { b.style.borderColor = BP.hairline; });
- return b;
- }
-
- function actionLabel() {
- const a = ACTIONS.find(a => a.value === selectedAction);
- return a ? a.label : 'Freeform';
- }
-
- function el(tag, styles) {
- const e = document.createElement(tag);
- if (styles) Object.assign(e.style, styles);
- return e;
- }
-
- // ---------------------------------------------------------------------------
- // Action picker popover
- // ---------------------------------------------------------------------------
-
- function initActionPicker() {
- const P = barPaletteForTheme(detectPageTheme());
- pickerEl = document.createElement('div');
- pickerEl.id = PREFIX + '-picker';
- Object.assign(pickerEl.style, {
- position: 'fixed', zIndex: Z.picker,
- display: 'none', opacity: '0',
- transform: 'scale(0.96) translateY(4px)',
- transformOrigin: 'bottom left',
- transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
- background: P.surface,
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
- padding: '6px',
- fontFamily: FONT,
- backdropFilter: 'blur(10px)',
- WebkitBackdropFilter: 'blur(10px)',
- });
-
- // Build the chip grid
- const grid = el('div', {
- display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
- });
-
- ACTIONS.forEach(action => {
- const chip = el('button', {
- display: 'flex', flexDirection: 'column', alignItems: 'center',
- gap: '4px',
- padding: '8px 6px', borderRadius: '6px',
- border: 'none',
- background: action.value === selectedAction ? P.accentSoft : 'transparent',
- color: action.value === selectedAction ? P.accent : P.text,
- fontFamily: FONT, fontSize: '11px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.1s ease, color 0.1s ease',
- textAlign: 'center', whiteSpace: 'nowrap',
- });
- const iconWrap = el('span', {
- display: 'flex', alignItems: 'center', justifyContent: 'center',
- height: '20px', opacity: '0.9',
- });
- iconWrap.innerHTML = ICONS[action.value] || '';
- const labelEl = el('span', { lineHeight: '1' });
- labelEl.textContent = action.label;
- chip.appendChild(iconWrap);
- chip.appendChild(labelEl);
- chip.dataset.action = action.value;
- chip.addEventListener('mouseenter', () => {
- if (action.value !== selectedAction) chip.style.background = P.accentSoft;
- });
- chip.addEventListener('mouseleave', () => {
- chip.style.background = action.value === selectedAction ? P.accentSoft : 'transparent';
- });
- chip.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedAction = action.value;
- hideActionPicker();
- updateBarContent('configure');
- });
- grid.appendChild(chip);
- });
-
- pickerEl.appendChild(grid);
- document.body.appendChild(pickerEl);
- defangOutsideHandlers(pickerEl);
-
- // Cache the palette on the picker so toggleActionPicker's state refresh
- // uses the same theme-aware colors when it repaints chips.
- pickerEl.__iceq_palette = P;
- }
-
- function toggleActionPicker() {
- if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
- // Rebuild chips to reflect current selection
- const P = pickerEl.__iceq_palette || barPaletteForTheme(detectPageTheme());
- pickerEl.querySelectorAll('button').forEach(chip => {
- const isActive = chip.dataset.action === selectedAction;
- chip.style.background = isActive ? P.accentSoft : 'transparent';
- chip.style.color = isActive ? P.accent : P.text;
- });
- // Position above the bar
- const barRect = barEl.getBoundingClientRect();
- const pickerH = 170; // approximate; grows with icon + label rows
- let top = barRect.top - pickerH - 6;
- if (top < 8) top = barRect.bottom + 6;
- Object.assign(pickerEl.style, {
- top: top + 'px', left: barRect.left + 'px',
- display: 'block',
- });
- requestAnimationFrame(() => {
- pickerEl.style.opacity = '1';
- pickerEl.style.transform = 'scale(1) translateY(0)';
- });
- }
-
- function hideActionPicker() {
- if (!pickerEl) return;
- pickerEl.style.opacity = '0';
- pickerEl.style.transform = 'scale(0.96) translateY(4px)';
- setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
- }
-
- // ---------------------------------------------------------------------------
- // Params panel (per-variant coarse controls)
- //
- // Variants may declare a parameter manifest via a JSON attribute on the
- // variant wrapper:
- //
- // <div data-impeccable-variant="1"
- // data-impeccable-params='[{"id":"density","kind":"steps",...}]'>
- //
- // The panel docks to the right edge of the outline during CYCLING and
- // exposes 2-5 coarse knobs. Values apply to the variant wrapper so scoped
- // CSS can respond instantly without regeneration:
- //
- // range / numeric toggle → CSS var (`--p-<id>`) used via var(--p-foo, N)
- // steps / boolean toggle → data-p-<id> attribute used via :scope[data-p-foo="..."]
- //
- // On variant switch, values reset to that variant's declared defaults.
- // On accept, current values are sent in the event payload so the agent
- // can bake them into the source-file write.
- // ---------------------------------------------------------------------------
-
- let paramsPanelEl = null; // outer wrapper (overflow:hidden, clips the slide)
- let paramsPanelInner = null; // translating content (carries bg, padding, knobs)
- let paramsPanelBody = null; // grid holding the knob cells
- let paramsCurrentValues = {}; // {paramId: value} — mirror of the visible variant's live values
- let tuneOpen = false; // whether the Tune popover is open right now
-
- // Theme-aware Tune popover. Appears as a drawer that slides out from the
- // contextual bar's bar-facing edge (below if the bar sits below the
- // element, above otherwise). Same width as the bar. Auto-wraps to extra
- // rows when the knobs exceed one row. The bar's border-radius on the
- // popover side goes flat while open so the two shapes read as one.
- let paramsPanelPalette = null;
-
- function initParamsPanel() {
- paramsPanelPalette = barPaletteForTheme(detectPageTheme());
- const P = paramsPanelPalette;
-
- // Single element, always in the DOM. The slide animation is a CSS mask
- // with mask-size growing from 0% to 100% along the bar-facing axis — no
- // display toggle, no opacity toggle, no transform trickery. The mask
- // hides everything initially; as it grows, content is revealed from
- // the bar edge outward.
- paramsPanelEl = document.createElement('div');
- paramsPanelEl.id = PREFIX + '-params-panel';
- Object.assign(paramsPanelEl.style, {
- position: 'fixed', zIndex: String(Z.bar - 1),
- background: P.surfaceDeep,
- color: P.text,
- fontFamily: FONT,
- padding: '14px 18px',
- boxSizing: 'border-box',
- borderRadius: '0 0 10px 10px',
- pointerEvents: 'none',
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
-
- // clip-path is the same conceptual reveal as mask but with rock-solid
- // transition support across engines. Closed state clips from the far
- // edge; open = inset(0) shows everything.
- clipPath: 'inset(0 0 100% 0)',
- transition: 'clip-path 0.44s ' + EASE,
-
- // Park off-screen until positionParamsPanel places it. These are NOT
- // in the transition list, so they snap instantly — no fly-in from the
- // top-left when first shown.
- top: '-9999px', left: '-9999px', width: '0',
- });
-
- paramsPanelBody = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
- gap: '12px 16px',
- });
-
- paramsPanelEl.appendChild(paramsPanelBody);
- document.body.appendChild(paramsPanelEl);
- // Don't override pointer-events: the panel toggles between 'none' (closed,
- // click-through) and 'auto' (open) on its own. Just silence the host's
- // outside-interaction listeners while the panel is open.
- defangOutsideHandlers(paramsPanelEl, { setPointerEvents: false });
- paramsPanelInner = paramsPanelEl; // compatibility alias for the rest of the code
- }
-
- function getVisibleVariantEl() {
- if (!currentSessionId) return null;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return null;
- return wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"]');
- }
-
- function parseVariantParams(variantEl) {
- if (!variantEl) return [];
- const raw = variantEl.getAttribute('data-impeccable-params');
- if (!raw) return [];
- try {
- const parsed = JSON.parse(raw);
- return Array.isArray(parsed) ? parsed : [];
- } catch (err) {
- console.warn('[impeccable] Invalid data-impeccable-params JSON:', err.message);
- return [];
- }
- }
-
- function applyParamValue(variantEl, param, value) {
- if (!variantEl) return;
- const attr = 'data-p-' + param.id;
- if (param.kind === 'range') {
- variantEl.style.setProperty('--p-' + param.id, String(value));
- } else if (param.kind === 'toggle') {
- const on = !!value;
- variantEl.style.setProperty('--p-' + param.id, on ? '1' : '0');
- if (on) variantEl.setAttribute(attr, 'on');
- else variantEl.removeAttribute(attr);
- } else if (param.kind === 'steps') {
- variantEl.setAttribute(attr, String(value));
- }
- }
-
- function applyParamDefaults(variantEl, params) {
- paramsCurrentValues = {};
- for (const p of params) {
- paramsCurrentValues[p.id] = p.default;
- applyParamValue(variantEl, p, p.default);
- }
- }
-
- function formatRangeValue(input) {
- const max = parseFloat(input.max), min = parseFloat(input.min);
- const v = parseFloat(input.value);
- if (!isFinite(v)) return input.value;
- return (max - min) <= 2 ? v.toFixed(2) : String(Math.round(v));
- }
-
- function buildParamsPanel(variantEl, params) {
- const P = paramsPanelPalette || barPaletteForTheme(detectPageTheme());
- paramsPanelBody.innerHTML = '';
- for (const p of params) {
- const row = el('div', { display: 'flex', flexDirection: 'column', gap: '6px' });
- const labelRow = el('div', {
- display: 'flex', justifyContent: 'space-between',
- alignItems: 'baseline', gap: '8px',
- });
- const lbl = el('span', {
- fontSize: '10.5px', fontWeight: '600', color: P.text,
- letterSpacing: '0.03em',
- });
- lbl.textContent = p.label || p.id;
- labelRow.appendChild(lbl);
- const readout = el('span', {
- fontSize: '10.5px', color: P.textDim,
- fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
- });
- labelRow.appendChild(readout);
- row.appendChild(labelRow);
-
- if (p.kind === 'range') {
- const input = document.createElement('input');
- input.type = 'range';
- input.min = String(p.min != null ? p.min : 0);
- input.max = String(p.max != null ? p.max : 1);
- input.step = String(p.step != null ? p.step : 0.05);
- input.value = String(p.default);
- Object.assign(input.style, {
- width: '100%', accentColor: C.brand, cursor: 'pointer',
- });
- readout.textContent = formatRangeValue(input);
- input.addEventListener('input', (e) => {
- e.stopPropagation();
- const v = parseFloat(input.value);
- paramsCurrentValues[p.id] = v;
- readout.textContent = formatRangeValue(input);
- applyParamValue(variantEl, p, v);
- queueCheckpoint('param_changed');
- });
- row.appendChild(input);
- } else if (p.kind === 'toggle') {
- const initial = !!p.default;
- readout.textContent = initial ? 'On' : 'Off';
- const track = el('button', {
- position: 'relative', width: '36px', height: '20px',
- borderRadius: '10px', border: 'none', padding: '0',
- cursor: 'pointer',
- background: initial ? C.brand : P.hairline,
- transition: 'background 0.15s ease',
- alignSelf: 'flex-start',
- });
- const knob = el('span', {
- position: 'absolute', top: '2px',
- left: initial ? '18px' : '2px',
- width: '16px', height: '16px', borderRadius: '50%',
- background: 'oklch(98% 0 0)',
- transition: 'left 0.18s ' + EASE,
- boxShadow: '0 1px 2px oklch(0% 0 0 / 0.2)',
- });
- track.appendChild(knob);
- track.addEventListener('click', (e) => {
- e.stopPropagation();
- const next = !paramsCurrentValues[p.id];
- paramsCurrentValues[p.id] = next;
- track.style.background = next ? C.brand : P.hairline;
- knob.style.left = next ? '18px' : '2px';
- readout.textContent = next ? 'On' : 'Off';
- applyParamValue(variantEl, p, next);
- queueCheckpoint('param_changed');
- });
- row.appendChild(track);
- } else if (p.kind === 'steps') {
- const opts = (p.options || []).map(o =>
- typeof o === 'string' ? { value: o, label: o } : o
- );
- const activeOpt = opts.find(o => o.value === p.default) || opts[0];
- readout.textContent = activeOpt ? activeOpt.label : String(p.default);
- const segRow = el('div', {
- display: 'grid',
- gridTemplateColumns: 'repeat(' + opts.length + ', 1fr)',
- gap: '1px', padding: '2px',
- background: P.hairline, borderRadius: '5px',
- });
- const segBtns = [];
- opts.forEach(o => {
- const active = o.value === p.default;
- const b = el('button', {
- padding: '5px 4px', border: 'none', borderRadius: '3px',
- background: active ? C.brand : 'transparent',
- color: active ? 'oklch(98% 0 0)' : P.text,
- fontFamily: FONT, fontSize: '10.5px', fontWeight: '500',
- cursor: 'pointer', whiteSpace: 'nowrap',
- transition: 'background 0.1s ease, color 0.1s ease',
- });
- b.textContent = o.label;
- b.addEventListener('click', (e) => {
- e.stopPropagation();
- paramsCurrentValues[p.id] = o.value;
- readout.textContent = o.label;
- segBtns.forEach(({ btn, val }) => {
- const on = val === o.value;
- btn.style.background = on ? C.brand : 'transparent';
- btn.style.color = on ? 'oklch(98% 0 0)' : P.text;
- });
- applyParamValue(variantEl, p, o.value);
- queueCheckpoint('param_changed');
- });
- segRow.appendChild(b);
- segBtns.push({ btn: b, val: o.value });
- });
- row.appendChild(segRow);
- }
-
- paramsPanelBody.appendChild(row);
- }
- }
-
- // Decide which way the popover opens: away from the picked element. If the
- // bar landed below the element, popover slides DOWN from the bar's bottom.
- // If the bar landed above, popover slides UP from the bar's top.
- function popoverDirection() {
- if (!barEl || !selectedElement) return 'below';
- const br = barEl.getBoundingClientRect();
- const er = selectedElement.getBoundingClientRect();
- return br.top >= er.bottom - 4 ? 'below' : 'above';
- }
-
- // The popover overlaps the bar by OVERLAP px on the bar-facing side. With
- // popover z-index below bar, that overlap sits behind bar (invisible) and
- // reinforces the "tucked behind" feel. Padding compensates so the real
- // content starts flush with bar's outer edge.
- const TUNE_OVERLAP = 6;
-
- // Closed clip-path depends on direction: for 'below' clip from the far
- // (bottom) edge so the reveal grows downward from the bar; for 'above'
- // clip from the top edge so the reveal grows upward from the bar.
- function closedClipPath(direction) {
- return direction === 'below' ? 'inset(0 0 100% 0)' : 'inset(100% 0 0 0)';
- }
-
- function setClipPath(value, withTransition) {
- const saved = paramsPanelEl.style.transition;
- if (!withTransition) paramsPanelEl.style.transition = 'none';
- paramsPanelEl.style.clipPath = value;
- if (!withTransition) {
- void paramsPanelEl.offsetHeight;
- paramsPanelEl.style.transition = saved;
- }
- }
-
- function positionParamsPanel() {
- if (!paramsPanelEl || !barEl || barEl.style.display === 'none') return;
- const br = barEl.getBoundingClientRect();
- const direction = popoverDirection();
- const prevDirection = paramsPanelEl.dataset.tuneDirection;
-
- // top/left/width are NOT in the transition list, so they snap instantly.
- paramsPanelEl.style.left = br.left + 'px';
- paramsPanelEl.style.width = br.width + 'px';
-
- if (direction === 'below') {
- paramsPanelEl.style.top = (br.bottom - TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '0 0 10px 10px';
- paramsPanelEl.style.paddingTop = (14 + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.paddingBottom = '14px';
- } else {
- const ih = paramsPanelEl.offsetHeight || 80;
- paramsPanelEl.style.top = (br.top - ih + TUNE_OVERLAP) + 'px';
- paramsPanelEl.style.borderRadius = '10px 10px 0 0';
- paramsPanelEl.style.paddingTop = '14px';
- paramsPanelEl.style.paddingBottom = (14 + TUNE_OVERLAP) + 'px';
- }
- paramsPanelEl.dataset.tuneDirection = direction;
-
- // If currently closed and direction flipped (or first-time setup),
- // snap the clip-path to the new direction's closed pose without
- // transitioning (so the clip doesn't slide across the element).
- if (!tuneOpen && (!prevDirection || prevDirection !== direction)) {
- setClipPath(closedClipPath(direction), false);
- }
- }
-
- function showParamsPanel() {
- if (!paramsPanelEl) return;
- positionParamsPanel();
- paramsPanelEl.style.pointerEvents = 'auto';
- // rAF so the positioning paint commits before the transition fires.
- requestAnimationFrame(() => {
- setClipPath('inset(0 0 0 0)', true);
- });
- }
-
- function hideParamsPanel() {
- if (!paramsPanelEl) return;
- paramsPanelEl.style.pointerEvents = 'none';
- const direction = paramsPanelEl.dataset.tuneDirection || 'below';
- setClipPath(closedClipPath(direction), true);
- }
-
- // Build/rebuild the panel's contents for the current variant AND apply
- // its defaults to the variant wrapper (so scoped CSS responds even before
- // the user opens the popover). Visibility is governed by tuneOpen.
- function refreshParamsPanel() {
- if (state !== 'CYCLING') {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) {
- paramsCurrentValues = {};
- tuneOpen = false;
- hideParamsPanel();
- return;
- }
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- if (tuneOpen) {
- // If already visible (variant cycled while open), refresh in place
- // instead of re-running the clip-path animation.
- const alreadyVisible = paramsPanelEl.style.display === 'block'
- && paramsPanelEl.style.opacity === '1';
- if (alreadyVisible) positionParamsPanel();
- else showParamsPanel();
- } else {
- hideParamsPanel();
- }
- }
-
- function toggleTunePopover() {
- if (tuneOpen) { closeTunePopover(); return; }
- openTunePopover();
- }
-
- function openTunePopover() {
- if (state !== 'CYCLING') return;
- const variantEl = getVisibleVariantEl();
- const params = parseVariantParams(variantEl);
- if (!variantEl || params.length === 0) return;
- // Build fresh to ensure the current variant's controls are shown.
- applyParamDefaults(variantEl, params);
- buildParamsPanel(variantEl, params);
- tuneOpen = true;
- showParamsPanel();
- // Kill the bar's shadow on the popover-facing side so the dark popover
- // doesn't pick up a bright glow line.
- if (barEl) {
- const direction = paramsPanelEl?.dataset.tuneDirection || 'below';
- barEl.style.boxShadow = direction === 'below' ? BAR_SHADOW_UP : BAR_SHADOW_DOWN;
- }
- // Re-render the bar so the Tune chip picks up the active styling.
- updateBarContent('cycling');
- }
-
- function closeTunePopover() {
- tuneOpen = false;
- hideParamsPanel();
- if (barEl) barEl.style.boxShadow = BAR_SHADOW_DEFAULT;
- if (barEl && barEl.style.display !== 'none' && state === 'CYCLING') {
- updateBarContent('cycling');
- }
- }
-
- // ---------------------------------------------------------------------------
- // Variant cycling in DOM
- // ---------------------------------------------------------------------------
-
- function showVariantInDOM(sessionId, num) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
- for (const child of wrapper.children) {
- const v = child.dataset ? child.dataset.impeccableVariant : null;
- if (!v) continue;
- child.style.display = (v === String(num)) ? '' : 'none';
- }
- // Unconditional refresh — covers first-reveal (no-op if state isn't
- // CYCLING yet, the subsequent CYCLING transition triggers its own
- // refresh) and every cycle step.
- refreshParamsPanel();
- }
-
- /**
- * No-HMR fallback: fetch the raw source file from the live server,
- * parse it, extract the variant wrapper, and inject it into the live DOM.
- * This works even when the dev server caches HTML (Bun, static servers).
- */
- function injectVariantsFromSource(filePath, sessionId) {
- const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
- fetch(url)
- .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
- .then(html => {
- // Parse the raw source HTML
- const parser = new DOMParser();
- const doc = parser.parseFromString(html, 'text/html');
- const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!srcWrapper) {
- console.error('[impeccable] Variant wrapper not found in source file.');
- return;
- }
-
- // Find the original element in the live DOM.
- // The original is inside the wrapper in the source. We find the
- // corresponding element in the live DOM by matching the first child's
- // tag + classes from the original snapshot.
- const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
- if (!origContent) return;
-
- const tag = origContent.tagName.toLowerCase();
- const cls = origContent.className;
- let liveEl = null;
- if (origContent.id) {
- liveEl = document.getElementById(origContent.id);
- } else if (cls) {
- // Find by tag + exact class match
- const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
- for (const c of candidates) {
- if (c.className === cls && !own(c)) { liveEl = c; break; }
- }
- }
-
- if (!liveEl) {
- console.error('[impeccable] Could not find original element in live DOM.');
- return;
- }
-
- const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;
-
- // Replace the live element with the full wrapper from source
- const wrapper = srcWrapper.cloneNode(true);
- liveEl.parentElement.replaceChild(wrapper, liveEl);
-
- // Update state: count variants, preserving the user's current variant
- // when a late HMR/source reinjection lands after they have cycled.
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants
- ? previousVisibleVariant
- : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);
- showVariantInDOM(sessionId, visibleVariant);
-
- // Update selectedElement to the visible variant's content
- selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;
-
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- saveSession();
- console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
- })
- .catch(err => {
- console.error('[impeccable] Failed to fetch source:', err);
- showToast('Could not load variants. Try refreshing the page.', 5000);
- });
- }
-
- function cycleVariant(dir) {
- const next = visibleVariant + dir;
- if (next < 1 || next > arrivedVariants) return;
- visibleVariant = next;
- showVariantInDOM(currentSessionId, next); // calls refreshParamsPanel itself
- updateSelectedElement();
- updateBarContent('cycling');
- saveSession();
- queueCheckpoint('variant_changed');
- }
-
- function updateSelectedElement() {
- if (!currentSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
- if (!wrapper) return;
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- function readVisibleVariantFromDOM(sessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return 0;
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- for (const variant of variants) {
- if (variant.style.display === 'none') continue;
- const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);
- if (idx > 0) return idx;
- }
- return 0;
- }
-
- // Resolve the element that represents the variant's visible content.
- // Contract: each variant div should contain exactly one top-level element
- // (the full replacement). In practice a model may ship loose siblings or
- // lead with <style>/<script>. Be defensive: skip non-visual elements, and
- // if the variant has multiple element children, use the variant div itself
- // (it wraps all of them and gets correct bounds).
- function pickVariantContent(wrapper, index) {
- if (!wrapper) return null;
- const variantDiv = wrapper.querySelector('[data-impeccable-variant="' + index + '"]');
- if (!variantDiv) return null;
- const NON_VISUAL = new Set(['STYLE', 'SCRIPT', 'LINK', 'META', 'TEMPLATE']);
- const visual = [];
- for (const child of variantDiv.children) {
- if (!NON_VISUAL.has(child.tagName)) visual.push(child);
- }
- if (visual.length === 1) return visual[0];
- return variantDiv;
- }
-
- // Hold window.scrollY at a fixed value across DOM mutations inside the
- // session's wrapper (HMR patches, variant inserts, cycle swaps).
- function startScrollLock(sessionId, initialTargetY) {
- stopScrollLock();
- scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)
- ? initialTargetY
- : window.scrollY;
- console.log('[impeccable.scroll] startScrollLock', { sessionId, scrollY: window.scrollY, targetY: scrollLockTargetY, initialOverride: initialTargetY });
-
- try { history.scrollRestoration = 'manual'; } catch {}
-
- const prevHtmlAnchor = document.documentElement.style.overflowAnchor;
- const prevBodyAnchor = document.body.style.overflowAnchor;
- document.documentElement.style.overflowAnchor = 'none';
- document.body.style.overflowAnchor = 'none';
-
- const correct = (why) => {
- scrollLockRaf = null;
- if (scrollLockTargetY == null) return;
- const before = window.scrollY;
- const delta = before - scrollLockTargetY;
- if (Math.abs(delta) < 0.5) {
- console.log('[impeccable.scroll] correct noop', { why, scrollY: before, targetY: scrollLockTargetY });
- return;
- }
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] corrected', { why, from: before, to: scrollLockTargetY, delta, nowAt: window.scrollY });
- };
- const schedule = (why) => {
- if (scrollLockRaf != null) return;
- scrollLockRaf = requestAnimationFrame(() => correct(why));
- };
-
- scrollLockObserver = new MutationObserver((mutations) => {
- for (const m of mutations) {
- if (m.target?.closest?.('[data-impeccable-variants="' + sessionId + '"]')) {
- const childAdds = Array.from(m.addedNodes).map(n => n.nodeType === 1 ? (n.tagName + (n.dataset?.impeccableVariant ? ('[variant=' + n.dataset.impeccableVariant + ']') : '')) : n.nodeType).join(',');
- console.log('[impeccable.scroll] mutation inside wrapper', { type: m.type, target: m.target?.tagName, adds: childAdds, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('mutation-in-wrapper');
- return;
- }
- for (const n of m.addedNodes) {
- if (n.nodeType === 1 && (n.matches?.('[data-impeccable-variants="' + sessionId + '"]') || n.querySelector?.('[data-impeccable-variants="' + sessionId + '"]'))) {
- console.log('[impeccable.scroll] wrapper node added', { tag: n.tagName, scrollYBefore: window.scrollY, targetY: scrollLockTargetY });
- schedule('wrapper-added');
- return;
- }
- }
- }
- });
- scrollLockObserver.observe(document.body, { childList: true, subtree: true });
-
- scrollLockAbort = new AbortController();
- scrollLockAbort.signal.addEventListener('abort', () => {
- document.documentElement.style.overflowAnchor = prevHtmlAnchor;
- document.body.style.overflowAnchor = prevBodyAnchor;
- }, { once: true });
- const sig = { signal: scrollLockAbort.signal };
- // Track whether the most recent scroll came from a user gesture. We
- // gate user-scroll re-anchoring on this flag so programmatic smooth
- // scrolls (browser reload-restore, scrollIntoView from other scripts)
- // don't accidentally update our target.
- let userGestureAt = 0;
- const USER_GESTURE_WINDOW_MS = 250;
-
- const reanchor = (why) => {
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- const prevTarget = scrollLockTargetY;
- scrollLockTargetY = window.scrollY;
- writeScrollY(scrollLockTargetY);
- console.log('[impeccable.scroll] reanchor', { why, prevTarget, newTarget: scrollLockTargetY });
- };
- const markGesture = (why) => {
- userGestureAt = performance.now();
- reanchor(why);
- };
- window.addEventListener('wheel', () => markGesture('wheel'), { passive: true, ...sig });
- window.addEventListener('touchstart', () => markGesture('touchstart'), { passive: true, ...sig });
- window.addEventListener('touchmove', () => markGesture('touchmove'), { passive: true, ...sig });
- window.addEventListener('keydown', (e) => {
- if (['PageDown', 'PageUp', ' ', 'End', 'Home', 'ArrowDown', 'ArrowUp'].includes(e.key)) markGesture('key:' + e.key);
- }, sig);
-
- // Correct on EVERY scroll event: whether it's the browser's
- // post-reload animated restore or some other script calling
- // scrollIntoView, we want to snap back immediately. Only skip if a
- // user gesture fired in the last 250ms.
- let lastLoggedScrollY = window.scrollY;
- window.addEventListener('scroll', () => {
- const now = window.scrollY;
- if (Math.abs(now - lastLoggedScrollY) > 5) {
- console.log('[impeccable.scroll] scroll event', { from: lastLoggedScrollY, to: now, targetY: scrollLockTargetY });
- lastLoggedScrollY = now;
- }
- if (scrollLockTargetY == null) return;
- if (performance.now() - userGestureAt < USER_GESTURE_WINDOW_MS) return;
- if (Math.abs(now - scrollLockTargetY) < 0.5) return;
- console.log('[impeccable.scroll] scroll-event snap', { from: now, to: scrollLockTargetY });
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- }, { passive: true, ...sig });
-
- // Apply target synchronously, not via rAF — racing the browser's
- // restore or a smooth-scroll animation means we want to win now.
- if (Math.abs(window.scrollY - scrollLockTargetY) > 0.5) {
- window.scrollTo({ top: scrollLockTargetY, left: window.scrollX, behavior: 'instant' });
- console.log('[impeccable.scroll] startScrollLock initial apply', { to: scrollLockTargetY });
- }
- }
-
- function stopScrollLock() {
- if (scrollLockObserver) { scrollLockObserver.disconnect(); scrollLockObserver = null; }
- if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }
- if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }
- scrollLockTargetY = null;
- // NOTE: do NOT clear the persistent scroll key here. startScrollLock
- // calls us as a reset, and clearing the key would nuke the Go-time
- // scrollY that the next resume needs to read.
- }
-
- // ---------------------------------------------------------------------------
- // MutationObserver for progressive variant reveal
- // ---------------------------------------------------------------------------
-
- function startVariantObserver(sessionId) {
- let updating = false; // re-entrancy guard
-
- const obs = new MutationObserver((mutations) => {
- if (updating) return;
-
- // Only react to mutations that add nodes with data-impeccable-variant,
- // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
- let dominated = false;
- for (const m of mutations) {
- if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
- for (const n of m.addedNodes) {
- if (n.nodeType !== 1) continue;
- // Direct hit: the added node itself is the wrapper or a variant.
- if (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant) {
- dominated = true; break;
- }
- // Subtree hit: framework HMR (notably SvelteKit) sometimes replaces
- // a whole subtree where the wrapper is a descendant of the added
- // node. Without this check, the observer ignores those mutations
- // and the session stays in GENERATING forever.
- if (n.querySelector?.('[data-impeccable-variants],[data-impeccable-variant]')) {
- dominated = true; break;
- }
- }
- if (dominated) break;
- }
- if (!dominated) return;
-
- const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
- if (!wrapper) return;
-
- // Re-anchor selectedElement if it was detached by live-wrap's HMR swap.
- // Without this, the shader / highlight / bar track a zero-rect phantom
- // and the overlay appears frozen.
- if (selectedElement && !document.body.contains(selectedElement)) {
- selectedElement = pickVariantContent(wrapper, 'original') || wrapper;
- }
-
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- const count = variants.length;
-
- // Nothing new
- if (count <= arrivedVariants) return;
-
- updating = true;
- arrivedVariants = count;
- if (visibleVariant === 0 && arrivedVariants > 0) {
- const saved = loadSession();
- const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;
- visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;
- showVariantInDOM(sessionId, visibleVariant);
- // showVariantInDOM hid the original (display:none); if we were still
- // anchored to the original's content, its boundingRect is now zero
- // and the bar snaps to (0,0). Re-point at the visible variant instead.
- const visEl = pickVariantContent(wrapper, visibleVariant);
- if (visEl) selectedElement = visEl;
- }
-
- const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- if (expected > 0) expectedVariants = expected;
-
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- state = 'CYCLING';
- hideShaderOverlay();
- updateBarContent('cycling');
- refreshParamsPanel();
- } else if (state === 'GENERATING') {
- updateBarContent('generating');
- }
- saveSession();
- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');
- updating = false;
- });
-
- obs.observe(document.body, { childList: true, subtree: true });
- return obs;
- }
-
- // ---------------------------------------------------------------------------
- // Bar scroll tracking
- // ---------------------------------------------------------------------------
-
- function startScrollTracking() {
- function tick() {
- if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
- positionBar();
- showHighlight(selectedElement);
- if (tuneOpen) positionParamsPanel();
- }
- if (annotActive) positionAnnotOverlay(selectedElement);
- // Shader overlay (via debug P toggle or generation) is repositioned
- // by its own branch below; debug no longer has a separate overlay.
- if (shaderState) positionShaderOverlay();
- scrollRaf = requestAnimationFrame(tick);
- }
- scrollRaf = requestAnimationFrame(tick);
- }
-
- function stopScrollTracking() {
- if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
- }
-
- // ---------------------------------------------------------------------------
- // SSE (server→browser) + fetch POST (browser→server)
- // Zero-dependency replacement for WebSocket.
- // ---------------------------------------------------------------------------
-
- let evtSource = null;
- let sseRetries = 0;
- const SSE_MAX_RETRIES = 20; // generous: heartbeats keep the connection alive, so retries mean real trouble
-
- function connectSSE() {
- evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
-
- evtSource.onopen = () => {
- sseRetries = 0; // reset on successful (re)connect
- };
-
- evtSource.onmessage = (e) => {
- sseRetries = 0; // reset on any successful message
- let msg; try { msg = JSON.parse(e.data); } catch { return; }
- switch (msg.type) {
- case 'connected':
- hasProjectContext = !!msg.hasProjectContext;
- if (!hasProjectContext) showToast('No PRODUCT.md found. Variants will be brand-agnostic. Run /impeccable teach to generate one.', 7000);
- console.log('[impeccable] Live mode connected.');
- if (state === 'IDLE') state = 'PICKING';
- break;
- case 'done':
- // Variants already arrived via HMR → normal transition.
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
- if (state === 'GENERATING') {
- state = 'CYCLING';
- updateBarContent('cycling');
- refreshParamsPanel();
- }
- break;
- }
- // Variants are in source but not in the DOM yet. Common when the
- // picked element lived inside conditional render (closed modal,
- // hidden tab, a route the user navigated away from). The variant
- // MutationObserver stays armed and auto-transitions to CYCLING
- // the moment the wrapper actually mounts. Nudge the user toward
- // that path with a toast — better than the prior force-reload
- // which reset framework state and left the session stuck.
- setTimeout(() => {
- if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;
- if (state !== 'GENERATING') return;
- showToast(
- "Variants ready. If the picked element isn't visible, retrace the path that revealed it — they'll appear automatically.",
- 15000,
- );
- }, 2000);
- break;
- case 'error':
- console.error('[impeccable] Error:', msg.message);
- showToast('Error: ' + msg.message, 5000);
- hideBar();
- state = 'PICKING';
- break;
- }
- };
-
- evtSource.onerror = () => {
- sseRetries++;
- if (sseRetries <= SSE_MAX_RETRIES) {
- console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
- return; // EventSource auto-reconnects
- }
- // Server is gone. Clean up gracefully.
- console.log('[impeccable] Live server unreachable. Cleaning up UI.');
- evtSource.close();
- evtSource = null;
- handleServerLost();
- };
- }
-
- /** Server died or became unreachable. Reset UI to a clean state. */
- function handleServerLost() {
- const recoveryState = currentSessionId ? state : 'IDLE';
- if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
- showToast('Live server disconnected. Session ended.', 5000);
- }
- hideBar();
- hideHighlight();
- hideShaderOverlay();
- hideAnnotOverlay();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- // Preserve local session state on server loss. The durable journal is the
- // source of truth, but localStorage plus the variant wrapper lets the UI
- // resume after a helper restart or page reload instead of treating a
- // transient disconnect as an explicit discard.
- selectedElement = null;
- selectedAction = 'impeccable';
- state = recoveryState;
- if (currentSessionId) saveSession();
- }
-
- function sendEvent(msg, opts) {
- msg.token = TOKEN;
- function handleFailure(err) {
- console.error('[impeccable] Failed to send event:', err);
- if (opts && opts.throwOnError) throw err;
- return null;
- }
- return fetch('http://localhost:' + PORT + '/events', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(msg),
- }).then(res => {
- if (res.ok) return res;
- return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));
- }).catch(handleFailure);
- }
-
- function checkpointPayload(reason) {
- return {
- type: 'checkpoint',
- id: currentSessionId,
- revision: sessionState.nextCheckpointRevision(),
- owner: browserOwner,
- phase: String(state || '').toLowerCase(),
- reason,
- pageUrl: location.pathname,
- expectedVariants,
- arrivedVariants,
- visibleVariant,
- paramValues: { ...paramsCurrentValues },
- };
- }
-
- function sendCheckpoint(reason) {
- if (!currentSessionId) return Promise.resolve(null);
- return sendEvent(checkpointPayload(reason)).catch(() => null);
- }
-
- function queueCheckpoint(reason) {
- if (!currentSessionId) return;
- if (checkpointTimer) clearTimeout(checkpointTimer);
- checkpointTimer = setTimeout(() => {
- checkpointTimer = null;
- sendCheckpoint(reason);
- }, 120);
- }
-
- // ---------------------------------------------------------------------------
- // Event handlers
- // ---------------------------------------------------------------------------
-
- function handleMouseMove(e) {
- if (state !== 'PICKING' || !pickActive) return;
- const target = document.elementFromPoint(e.clientX, e.clientY);
- if (!target || !pickable(target) || target === hoveredElement) return;
- hoveredElement = target;
- showHighlight(target);
- }
-
- function handleClick(e) {
- // Close action picker on any outside click
- if (pickerEl?.style.display !== 'none' && !own(e.target)) {
- hideActionPicker();
- }
- // Close Tune popover on outside click (anything outside panel + bar)
- if (tuneOpen && paramsPanelEl && !paramsPanelEl.contains(e.target) && barEl && !barEl.contains(e.target)) {
- closeTunePopover();
- }
- // In CONFIGURING: click outside the bar and selected element returns to PICKING
- if (state === 'CONFIGURING' && !own(e.target) && selectedElement && !selectedElement.contains(e.target)) {
- hideBar();
- stopScrollTracking();
- hideAnnotOverlay();
- clearAnnotations();
- state = 'PICKING';
- hoveredElement = null;
- hideHighlight();
- return;
- }
- if (state !== 'PICKING' || !pickActive) return;
- if (own(e.target)) return;
- if (!hoveredElement || !pickable(hoveredElement)) return;
- e.preventDefault();
- e.stopPropagation();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- maybePrefetchPage();
- maybeWarnConditionalAncestor(selectedElement);
- }
-
- /**
- * Surface a brief, non-blocking heads-up when the picked element lives
- * inside a container whose visibility is gated by ephemeral state — modals,
- * collapsible panels, popovers, off-screen tab panels. If HMR remounts the
- * parent during generation (Vite Fast Refresh, SvelteKit page reload), the
- * variants land in source but stay invisible until the user re-opens the
- * container. Telling the user upfront is much friendlier than the silent
- * timeout-then-toast that they'd otherwise hit.
- *
- * Heuristic, intentionally narrow — only fires for unambiguous cases so
- * we don't cry wolf on every nested element.
- */
- function maybeWarnConditionalAncestor(el) {
- let node = el?.parentElement;
- let depth = 0;
- while (node && depth < 12) {
- // 1. Active dialog / modal
- if (node.getAttribute && node.getAttribute('role') === 'dialog'
- && node.getAttribute('aria-modal') === 'true') {
- showToast('Heads up: this element lives inside a dialog. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 2. Common Radix / shadcn / headless-ui open-state attribute
- if (node.dataset && node.dataset.state === 'open') {
- showToast('Heads up: this element lives inside an open panel. If state resets during generation, you may need to re-open it.', 6000);
- return;
- }
- // 3. Tab panel — only meaningful when the page also shows ANOTHER
- // tab as selected. A single tabpanel with no tablist is just a static
- // section in disguise and isn't conditional.
- if (node.getAttribute && node.getAttribute('role') === 'tabpanel') {
- const list = document.querySelector('[role="tablist"]');
- if (list) {
- const tabs = list.querySelectorAll('[role="tab"]');
- if (tabs.length > 1) {
- showToast('Heads up: this element lives in a tab panel. If state resets during generation, switch back to this tab.', 6000);
- return;
- }
- }
- }
- // 4. Collapsible: aria-expanded sibling. Look for the trigger button.
- if (node.id) {
- const trigger = document.querySelector(`[aria-controls="${CSS.escape(node.id)}"][aria-expanded="true"]`);
- if (trigger) {
- showToast('Heads up: this element lives inside an expandable section. If state resets during generation, re-expand it.', 6000);
- return;
- }
- }
- node = node.parentElement;
- depth++;
- }
- }
-
- // Fire a lightweight prefetch event the first time the user selects an
- // element on a given route. The agent uses this to Read the underlying file
- // into context before Go is hit, shaving the read off the critical path.
- // Dedupe per session by pathname — clicking around on the same page doesn't
- // re-fire.
- //
- // DISABLED: quick-Go workflows pay an extra harness round trip because
- // prefetch + generate arrive as two events instead of one. Re-enable with
- // a browser-side debounce (~800–1000ms, cancelled on Go) if we want to
- // resurrect this. Server validator and skill dispatch remain in place so
- // flipping this flag is the only change needed.
- const PREFETCH_ENABLED = false;
- const prefetchedPaths = new Set();
- function maybePrefetchPage() {
- if (!PREFETCH_ENABLED) return;
- const path = location.pathname;
- if (prefetchedPaths.has(path)) return;
- prefetchedPaths.add(path);
- sendEvent({ type: 'prefetch', pageUrl: path });
- }
-
- function handleKeyDown(e) {
- // When the annotation input is focused, let it handle its own keys.
- if (annotEditing && annotEditing.input && e.target === annotEditing.input) return;
- if (e.key === 'Escape') {
- e.preventDefault();
- if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
- if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); hideAnnotOverlay(); clearAnnotations(); state = 'PICKING'; return; }
- if (state === 'CYCLING') { handleDiscard(); return; }
- if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
- if (state === 'PICKING') {
- // Use togglePick so the "Pick" button in the global bar also flips
- // off, otherwise the bar stays lit while nothing else is active.
- if (pickActive) togglePick();
- else { hideHighlight(); state = 'IDLE'; }
- return;
- }
- }
-
- // Arrow/Enter nav works in PICKING (hover) and CONFIGURING (selected, input empty)
- var navEl = (state === 'PICKING') ? hoveredElement : (state === 'CONFIGURING') ? selectedElement : null;
- if (navEl && (e.key === 'ArrowUp' || e.key === 'ArrowDown' || (e.key === 'Enter' && state === 'PICKING'))) {
- let next = null;
- if (e.key === 'ArrowDown' && !e.shiftKey) {
- next = navEl.nextElementSibling;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'ArrowUp' && !e.shiftKey) {
- next = navEl.previousElementSibling;
- while (next && !pickable(next)) next = next.previousElementSibling;
- } else if (e.key === 'ArrowUp' && e.shiftKey) {
- next = navEl.parentElement;
- if (next && !pickable(next)) next = null;
- } else if (e.key === 'ArrowDown' && e.shiftKey) {
- next = navEl.firstElementChild;
- while (next && !pickable(next)) next = next.nextElementSibling;
- } else if (e.key === 'Enter') {
- e.preventDefault();
- selectedElement = hoveredElement;
- state = 'CONFIGURING';
- showHighlight(selectedElement);
- clearAnnotations();
- showAnnotOverlay(selectedElement);
- showBar('configure');
- startScrollTracking();
- return;
- }
- if (next) {
- e.preventDefault();
- if (state === 'PICKING') {
- hoveredElement = next;
- } else {
- // CONFIGURING: re-select the new element and refresh the bar
- selectedElement = next;
- clearAnnotations();
- showAnnotOverlay(next);
- showBar('configure');
- startScrollTracking();
- }
- showHighlight(next);
- next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
- }
- return;
- }
-
- if (state === 'CYCLING') {
- if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
- if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
- if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
- }
- }
-
- function handleGo() {
- if (!selectedElement || state !== 'CONFIGURING') return;
- const input = document.getElementById(PREFIX + '-input');
- const prompt = input ? input.value.trim() : '';
-
- // Commit any pending pin edit BEFORE we snapshot annotations.
- if (annotEditing) finalizeEditingPin();
-
- currentSessionId = id8();
- expectedVariants = selectedCount;
- arrivedVariants = 0;
- visibleVariant = 0;
-
- // Flip to GENERATING immediately so the bar morphs without waiting on
- // capture + upload. The event is emitted from captureAndEmit() once the
- // screenshot is uploaded (or capture fails — we still emit, just without
- // screenshotPath).
- const elForCapture = selectedElement;
- const captureRect = elForCapture.getBoundingClientRect();
- const snapshot = {
- comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),
- strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),
- };
- const basePayload = {
- type: 'generate', id: currentSessionId,
- action: selectedAction,
- freeformPrompt: prompt || undefined,
- count: selectedCount,
- pageUrl: location.pathname,
- element: extractContext(elForCapture),
- };
- if (snapshot.comments.length > 0) basePayload.comments = snapshot.comments;
- if (snapshot.strokes.length > 0) basePayload.strokes = snapshot.strokes;
-
- // Hide the interactive overlay so it doesn't linger during generation.
- hideAnnotOverlay();
- clearAnnotations();
-
- state = 'GENERATING';
- showBar('generating');
- saveSession();
- sendCheckpoint('generate_started');
- writeScrollY(window.scrollY);
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
- console.log('[impeccable.scroll] Go pressed', { scrollY: window.scrollY, sessionId: currentSessionId });
- startScrollLock(currentSessionId);
-
- captureAndEmit(elForCapture, basePayload, snapshot, captureRect);
- }
-
- // ---------------------------------------------------------------------------
- // Screenshot capture + upload
- // ---------------------------------------------------------------------------
-
- let msLoadPromise = null;
- function loadModernScreenshot() {
- if (window.modernScreenshot) return Promise.resolve(window.modernScreenshot);
- if (msLoadPromise) return msLoadPromise;
- msLoadPromise = new Promise((resolve, reject) => {
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/modern-screenshot.js';
- s.onload = () => resolve(window.modernScreenshot);
- s.onerror = () => { msLoadPromise = null; reject(new Error('modern-screenshot failed to load')); };
- document.head.appendChild(s);
- });
- return msLoadPromise;
- }
-
- // Collect @font-face rules from every stylesheet on the page. Cross-origin
- // sheets (Google Fonts, Typekit, etc.) throw SecurityError on .cssRules
- // access, so modern-screenshot can't embed them on its own — the resulting
- // SVG falls back to system fonts and text re-wraps + renders with different
- // weight. We fetch the raw CSS text (CORS-permitted for these providers),
- // extract @font-face blocks, inline the referenced font files as base64
- // data URIs (SVGs rasterized via canvas can't fetch external resources,
- // so URLs inside the SVG silently fail without this), and pass the result
- // to modern-screenshot as font.cssText.
- const FONT_EXT_RE = /\.(woff2?|ttf|otf|eot)(\?.*)?$/i;
- const FONT_MIME = {
- woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', eot: 'application/vnd.ms-fontobject',
- };
- function bufferToBase64(buf) {
- const bytes = new Uint8Array(buf);
- let binary = '';
- const CHUNK = 0x8000;
- for (let i = 0; i < bytes.length; i += CHUNK) {
- binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
- }
- return btoa(binary);
- }
- async function inlineFontUrls(cssText) {
- const urlRe = /url\((['"]?)(https?:\/\/[^'")\s]+)\1\)/g;
- const urls = new Set();
- let m;
- while ((m = urlRe.exec(cssText))) {
- if (FONT_EXT_RE.test(m[2])) urls.add(m[2]);
- }
- const map = new Map();
- await Promise.all([...urls].map(async (url) => {
- try {
- const res = await fetch(url);
- if (!res.ok) return;
- const buf = await res.arrayBuffer();
- const ext = url.toLowerCase().match(FONT_EXT_RE)?.[1] || 'woff2';
- const mime = FONT_MIME[ext] || 'application/octet-stream';
- map.set(url, 'data:' + mime + ';base64,' + bufferToBase64(buf));
- } catch { /* skip; fall through to URL */ }
- }));
- return cssText.replace(urlRe, (orig, q, url) => {
- const data = map.get(url);
- return data ? 'url(' + q + data + q + ')' : orig;
- });
- }
- async function collectFontCssText() {
- const chunks = [];
- const fontFaceRe = /@font-face\s*\{[^}]*\}/g;
- for (const sheet of document.styleSheets) {
- try {
- const rules = sheet.cssRules;
- for (const rule of rules) {
- if (rule.constructor.name === 'CSSFontFaceRule' || rule.cssText?.startsWith('@font-face')) {
- chunks.push(rule.cssText);
- }
- }
- } catch {
- if (!sheet.href) continue;
- try {
- const res = await fetch(sheet.href);
- if (!res.ok) continue;
- const text = await res.text();
- let m2;
- while ((m2 = fontFaceRe.exec(text))) chunks.push(m2[0]);
- } catch { /* ignore; capture is best-effort */ }
- }
- }
- if (chunks.length === 0) return '';
- return inlineFontUrls(chunks.join('\n'));
- }
-
- // True if `s` is a computed color string that renders as nothing
- // (explicit `transparent`, or `rgba(...)` with alpha 0).
- function isTransparentColor(s) {
- if (!s) return true;
- if (s === 'transparent') return true;
- const m = /rgba?\(([^)]+)\)/.exec(s);
- if (!m) return false;
- const parts = m[1].split(',').map((p) => p.trim());
- if (parts.length === 4) return parseFloat(parts[3]) === 0;
- return false;
- }
-
- // modern-screenshot force-sets `background-color: X !important` on the
- // cloned root whenever `backgroundColor` is passed, clobbering the
- // element's own background. So we only pass it when the element is
- // genuinely transparent (no own color, no own image) — in that case
- // we resolve up the DOM to the nearest opaque ancestor so the capture
- // sits on the page's real background instead of rendering black.
- function resolveCanvasBackground(el) {
- const own = getComputedStyle(el);
- if (!isTransparentColor(own.backgroundColor)) return null;
- if (own.backgroundImage && own.backgroundImage !== 'none') return null;
- let node = el.parentElement;
- while (node) {
- const cs = getComputedStyle(node);
- if (!isTransparentColor(cs.backgroundColor)) return cs.backgroundColor;
- node = node.parentElement;
- }
- // The walk already passed through <body> and <html>; if they had been
- // opaque we would have returned. Falling through with the previous
- // `getComputedStyle(body).backgroundColor || …` chain is a trap: that
- // call returns the literal string `"rgba(0, 0, 0, 0)"` for a page that
- // never set its own bg, which is truthy and short-circuits the chain to
- // transparent-black — modern-screenshot then renders the capture on a
- // black canvas and the shader overlay flashes solid black during load.
- // The browser canvas defaults to white, so we do too.
- return '#ffffff';
- }
-
- // Capture the element (with current annotations baked in) and return a PNG
- // Blob. Shared between the Go flow (uploads it to the server) and the
- // debug toggle (displays it as an overlay for side-by-side comparison).
- async function captureElementToBlob(el, snapshot, rect) {
- try { if (document.fonts?.ready) await document.fonts.ready; } catch {}
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- let annotNode = null;
- let savedPosition = null;
- if (hasAnnotations) {
- const pos = getComputedStyle(el).position;
- if (pos === 'static') {
- savedPosition = el.style.position;
- el.style.position = 'relative';
- }
- annotNode = buildAnnotationsForCapture(rect, snapshot);
- el.appendChild(annotNode);
- }
- try {
- const ms = await loadModernScreenshot();
- const fontCssText = await collectFontCssText();
- const backgroundColor = resolveCanvasBackground(el);
- return await ms.domToBlob(el, {
- scale: Math.min(window.devicePixelRatio || 1, 2),
- font: fontCssText ? { cssText: fontCssText } : undefined,
- ...(backgroundColor ? { backgroundColor } : {}),
- });
- } finally {
- if (annotNode) annotNode.remove();
- if (savedPosition !== null) el.style.position = savedPosition;
- }
- }
-
- async function captureAndEmit(el, basePayload, snapshot, rect) {
- let screenshotPath;
- let blob;
- try {
- blob = await captureElementToBlob(el, snapshot, rect);
- } catch (err) {
- console.warn('[impeccable] capture failed, proceeding without screenshot:', err);
- }
- // Light up the shader overlay the moment capture is ready — no reason to
- // wait for the upload to complete before the user sees something alive.
- if (blob && state === 'GENERATING') {
- showShaderOverlay(el, blob, rect);
- }
- // Only upload + forward the screenshot when annotations (comments/strokes)
- // are present. Without annotations the image is pure visual anchoring —
- // it biases the model toward the current rendering and works against the
- // three-distinct-directions brief.
- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);
- if (blob && hasAnnotations) {
- try {
- const uploadRes = await fetch(
- 'http://localhost:' + PORT + '/annotation?token=' + encodeURIComponent(TOKEN) +
- '&eventId=' + encodeURIComponent(basePayload.id),
- { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: blob },
- );
- if (uploadRes.ok) {
- const { path: p } = await uploadRes.json();
- screenshotPath = p;
- } else {
- console.warn('[impeccable] annotation upload failed:', uploadRes.status);
- }
- } catch (err) {
- console.warn('[impeccable] annotation upload failed:', err);
- }
- }
- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);
- }
-
- // ---------------------------------------------------------------------------
- // Shader overlay — renders the captured screenshot as a WebGL texture and
- // runs an editorial "ink-wash" fragment shader over it during generation.
- // A single rolling band sweeps top-to-bottom, desaturating + tinting magenta
- // and leaving a soft trail. Makes the wait feel like a letterpress scan
- // instead of a dead spinner.
- // ---------------------------------------------------------------------------
-
- const SHADER_VS = `attribute vec2 a_position;
-attribute vec2 a_uv;
-varying vec2 v_uv;
-void main() {
- v_uv = a_uv;
- gl_Position = vec4(a_position, 0.0, 1.0);
-}`;
-
- const SHADER_FS = `precision highp float;
-uniform sampler2D u_texture;
-uniform float u_time;
-uniform vec2 u_resolution;
-uniform vec3 u_accent;
-varying vec2 v_uv;
-
-// Asymmetric roller band. Product of two one-sided smoothsteps — peaks at
-// d=0 with a short sharp leading ramp and a longer soft trailing tail. Clean
-// outside the [-leadW, trailW] range (no rogue "trail=1 everywhere below"
-// failure that reversed-edge smoothstep would give).
-float bandAt(float d, float leadW, float trailW) {
- float above = smoothstep(-leadW, 0.0, d);
- float below = 1.0 - smoothstep(0.0, trailW, d);
- return above * below;
-}
-
-void main() {
- vec2 uv = v_uv;
- // Roller sweeps top-to-bottom with small overshoot so each cycle enters
- // and exits the element cleanly.
- float phase = fract(u_time / 3.4);
- float y = phase * 1.25 - 0.12;
- float band = bandAt(uv.y - y, 0.05, 0.32);
-
- // Halftone cell grid (fixed ~10 px pitch).
- float cellPx = 10.0;
- vec2 gridUv = uv * u_resolution / cellPx;
- vec2 cellId = floor(gridUv);
- vec2 cellUv = fract(gridUv) - 0.5;
- vec2 sampleCenter = (cellId + 0.5) * cellPx / u_resolution;
- vec3 cellImg = texture2D(u_texture, sampleCenter).rgb;
- float luma = dot(cellImg, vec3(0.299, 0.587, 0.114));
- // Darker cells → bigger magenta dots (classic risograph halftone curve).
- float radius = sqrt(clamp(1.0 - luma, 0.0, 1.0)) * 0.56;
- float dotMask = smoothstep(radius + 0.06, radius, length(cellUv));
- vec3 paper = vec3(0.975, 0.965, 0.955);
- vec3 dotLayer = mix(paper, u_accent, dotMask);
-
- // Blend the halftone layer in where the roller is passing; leave the
- // element pristine elsewhere.
- vec3 base = texture2D(u_texture, uv).rgb;
- gl_FragColor = vec4(mix(base, dotLayer, band), 1.0);
-}`;
-
- // Editorial Magenta converted to approximate sRGB 0-1 (matches oklch(60% 0.25 350))
- const SHADER_ACCENT = [0.82, 0.16, 0.47];
- let shaderState = null; // { canvas, gl, program, texture, rafId, startTime }
-
- function compileShader(gl, type, source) {
- const sh = gl.createShader(type);
- gl.shaderSource(sh, source);
- gl.compileShader(sh);
- if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
- const info = gl.getShaderInfoLog(sh);
- gl.deleteShader(sh);
- throw new Error('shader compile failed: ' + info);
- }
- return sh;
- }
-
- function positionShaderOverlay() {
- if (!shaderState || !selectedElement) return;
- const r = selectedElement.getBoundingClientRect();
- Object.assign(shaderState.canvas.style, {
- top: r.top + 'px', left: r.left + 'px',
- width: r.width + 'px', height: r.height + 'px',
- });
- }
-
- function hideShaderOverlay() {
- if (!shaderState) return;
- if (shaderState.rafId) cancelAnimationFrame(shaderState.rafId);
- if (shaderState.canvas) shaderState.canvas.remove();
- const lose = shaderState.gl?.getExtension?.('WEBGL_lose_context');
- try { lose?.loseContext(); } catch {}
- shaderState = null;
- }
-
- async function showShaderOverlay(el, blob, rect) {
- hideShaderOverlay();
- if (!blob || !el) return;
- const canvas = document.createElement('canvas');
- canvas.id = PREFIX + '-shader';
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
- canvas.width = Math.max(1, Math.floor(rect.width * dpr));
- canvas.height = Math.max(1, Math.floor(rect.height * dpr));
- Object.assign(canvas.style, {
- position: 'fixed',
- top: rect.top + 'px', left: rect.left + 'px',
- width: rect.width + 'px', height: rect.height + 'px',
- pointerEvents: 'none',
- zIndex: Z.bar - 1,
- });
- document.body.appendChild(canvas);
-
- const gl = canvas.getContext('webgl', { premultipliedAlpha: false, preserveDrawingBuffer: false })
- || canvas.getContext('experimental-webgl');
- if (!gl) {
- // WebGL unavailable — fall back to a plain <img> overlay so the user
- // still sees something meaningful during generation.
- canvas.remove();
- const img = document.createElement('img');
- img.src = URL.createObjectURL(blob);
- img.id = PREFIX + '-shader';
- // Copy positioning via cssText. Object.assign across CSSStyleDeclaration
- // throws in modern Chromium because the source's indexed properties
- // (style[0], [1], ...) are read-only and the engine forbids writing
- // them on the destination.
- img.style.cssText = canvas.style.cssText;
- img.style.outline = '2px dashed ' + C.brand;
- img.style.outlineOffset = '-2px';
- document.body.appendChild(img);
- shaderState = { canvas: img, gl: null, program: null, texture: null, rafId: 0, startTime: 0 };
- return;
- }
-
- let program, texture;
- try {
- const vs = compileShader(gl, gl.VERTEX_SHADER, SHADER_VS);
- const fs = compileShader(gl, gl.FRAGMENT_SHADER, SHADER_FS);
- program = gl.createProgram();
- gl.attachShader(program, vs);
- gl.attachShader(program, fs);
- gl.linkProgram(program);
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- throw new Error('program link failed: ' + gl.getProgramInfoLog(program));
- }
- // Full-screen quad
- const buf = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
- -1, -1, 0, 1,
- 1, -1, 1, 1,
- -1, 1, 0, 0,
- -1, 1, 0, 0,
- 1, -1, 1, 1,
- 1, 1, 1, 0,
- ]), gl.STATIC_DRAW);
- const posLoc = gl.getAttribLocation(program, 'a_position');
- const uvLoc = gl.getAttribLocation(program, 'a_uv');
- gl.enableVertexAttribArray(posLoc);
- gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 16, 0);
- gl.enableVertexAttribArray(uvLoc);
- gl.vertexAttribPointer(uvLoc, 2, gl.FLOAT, false, 16, 8);
- } catch (err) {
- console.warn('[impeccable] shader setup failed:', err);
- canvas.remove();
- return;
- }
-
- // Upload the screenshot as a texture
- let bitmap;
- try {
- bitmap = await createImageBitmap(blob);
- } catch {
- // Safari fallback: go via a regular Image
- const imgUrl = URL.createObjectURL(blob);
- const img = new Image();
- img.src = imgUrl;
- await new Promise((r, rej) => { img.onload = r; img.onerror = rej; });
- bitmap = img;
- URL.revokeObjectURL(imgUrl);
- }
- texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
- if (bitmap.close) bitmap.close();
-
- const uTime = gl.getUniformLocation(program, 'u_time');
- const uRes = gl.getUniformLocation(program, 'u_resolution');
- const uAccent = gl.getUniformLocation(program, 'u_accent');
- const uTex = gl.getUniformLocation(program, 'u_texture');
- const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
-
- shaderState = { canvas, gl, program, texture, rafId: 0, startTime: performance.now(), reduced };
- function frame() {
- if (!shaderState) return;
- const elapsed = (performance.now() - shaderState.startTime) / 1000;
- const t = shaderState.reduced ? 0.0 : elapsed;
- gl.viewport(0, 0, canvas.width, canvas.height);
- gl.useProgram(program);
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.uniform1i(uTex, 0);
- gl.uniform1f(uTime, t);
- gl.uniform2f(uRes, canvas.width, canvas.height);
- gl.uniform3f(uAccent, SHADER_ACCENT[0], SHADER_ACCENT[1], SHADER_ACCENT[2]);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- shaderState.rafId = requestAnimationFrame(frame);
- }
- frame();
- }
-
- function handleAccept() {
- if (!currentSessionId || arrivedVariants === 0) return;
- const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);
- if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;
- const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };
- if (Object.keys(paramsCurrentValues).length > 0) {
- acceptPayload.paramValues = { ...paramsCurrentValues };
- }
- // The accepted variant is already the only visible child of the wrapper
- // (all other variants are display:none). HMR from the source rewrite will
- // replace the wrapper imminently. Don't eagerly replaceChild here — React
- // reconciliation races with our mutation and throws NotFoundError in Next
- // 16 / Turbopack. Schedule a fallback that runs the manual swap only if
- // HMR hasn't cleaned up by then (keeps static-server flows working).
- const acceptedSessionId = currentSessionId;
- const acceptedVariant = visibleVariant;
-
- state = 'SAVING';
- updateBarContent('saving');
-
- sendEvent(acceptPayload, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- confirmAcceptAfterReceipt();
- })
- .catch(() => {
- state = 'CYCLING';
- updateBarContent('cycling');
- showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);
- });
-
- function confirmAcceptAfterReceipt() {
- state = 'CONFIRMED';
- updateBarContent('confirmed');
- scheduleAcceptCleanup();
- }
-
- function scheduleAcceptCleanup() {
- setTimeout(function() {
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }, 1800);
-
- // Static-server / no-HMR fallback: if the wrapper is still around 2s after
- // the cleanup above, swap it out manually. By now React has either moved
- // on or the app isn't React at all. Preserve the `data-impeccable-variant="N"`
- // div (with display:contents) so @scope rules anchored to the variant
- // attribute keep matching until reload replaces it with the carbonize block.
- setTimeout(function() {
- const wrapper = document.querySelector('[data-impeccable-variants="' + acceptedSessionId + '"]');
- if (!wrapper) return;
- const accepted = wrapper.querySelector('[data-impeccable-variant="' + acceptedVariant + '"]');
- if (accepted && accepted.firstElementChild) {
- const parent = wrapper.parentElement;
- if (!parent) return;
- accepted.style.display = 'contents';
- parent.replaceChild(accepted, wrapper);
- }
- }, 2000);
- }
- }
-
- function handleDiscard() {
- if (!currentSessionId) return;
- sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })
- .then(() => {
- markSessionHandled();
- cleanup();
- })
- .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));
- }
-
- // ---------------------------------------------------------------------------
- // Session persistence via live-browser-session.js
- // ---------------------------------------------------------------------------
- // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
-
- function saveSession() {
- if (!currentSessionId) return;
- // NOTE: scrollY is stored under a separate key (writeScrollY). Storing
- // it here would overwrite the Go-time value every time state changes.
- sessionState.saveSession({
- id: currentSessionId,
- state,
- action: selectedAction,
- count: selectedCount,
- expected: expectedVariants,
- arrived: arrivedVariants,
- visible: visibleVariant,
- });
- }
-
- function loadSession() {
- return sessionState.loadSession();
- }
-
- function clearSession() {
- sessionState.clearSession();
- }
-
- /** Mark session as handled (accepted/discarded). The agent will clean up
- * the source, but until it does the wrapper is still in the HTML. This
- * prevents resumeSession from picking it up again after reload. */
- function markSessionHandled() {
- if (!currentSessionId) return;
- sessionState.markHandled(currentSessionId);
- }
-
- function isSessionHandled(id) {
- return sessionState.isHandled(id);
- }
-
- function clearHandled() {
- sessionState.clearHandled();
- }
-
- function cleanup() {
- // Hide the wrapper immediately so variants disappear. DON'T structurally
- // mutate the DOM yet — HMR from the agent's source rewrite is on its way,
- // and a manual replaceChild under React causes NotFoundError when the
- // reconciler later tries to remove a wrapper we already removed.
- // Schedule a 2s fallback that does the manual swap only if HMR hasn't
- // replaced the wrapper by then (keeps static-server / no-HMR flows alive).
- const cleanupSessionId = currentSessionId;
- if (cleanupSessionId) {
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (wrapper) wrapper.style.display = 'none';
- }
- setTimeout(function() {
- if (!cleanupSessionId) return;
- const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');
- if (!wrapper) return;
- const orig = wrapper.querySelector('[data-impeccable-variant="original"]');
- if (orig) {
- const content = orig.firstElementChild;
- if (content) {
- wrapper.parentElement.replaceChild(content, wrapper);
- return;
- }
- }
- wrapper.remove();
- }, 2000);
- hideBar();
- hideHighlight();
- stopScrollTracking();
- if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
- stopScrollLock();
- clearScrollY();
- clearSession();
- selectedElement = null;
- currentSessionId = null;
- selectedAction = 'impeccable';
- state = 'PICKING';
- }
-
- // ---------------------------------------------------------------------------
- // Toast
- // ---------------------------------------------------------------------------
-
- function showToast(message, duration) {
- if (toastEl) toastEl.remove();
- // Stack the toast above the global bar (which sits at bottom:14px) so
- // the two never overlap. Read the bar's actual rect — its height varies
- // with hover-expanded labels — and fall back to a sensible default
- // when the bar isn't mounted yet.
- const barRect = globalBarEl?.getBoundingClientRect();
- const barTopFromBottom = barRect && barRect.height > 0
- ? Math.max(16, window.innerHeight - barRect.top + 12)
- : 16;
- toastEl = el('div', {
- position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
- transform: 'translateX(-50%) translateY(8px)',
- background: C.ink, color: C.white,
- fontFamily: FONT, fontSize: '12px',
- padding: '8px 16px', borderRadius: '8px',
- zIndex: Z.toast, opacity: '0',
- transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
- pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
- });
- toastEl.id = PREFIX + '-toast';
- toastEl.textContent = message;
- document.body.appendChild(toastEl);
- requestAnimationFrame(() => {
- toastEl.style.opacity = '1';
- toastEl.style.transform = 'translateX(-50%) translateY(0)';
- });
- setTimeout(() => {
- if (toastEl) {
- toastEl.style.opacity = '0';
- toastEl.style.transform = 'translateX(-50%) translateY(8px)';
- setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
- }
- }, duration);
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- // Resume an active variant session after HMR/page reload.
- // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
- // variants before HMR fired. Pick up where we left off.
- function resumeSession() {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) { clearSession(); clearHandled(); return false; }
-
- const sessionId = wrapper.dataset.impeccableVariants;
-
- // Don't resume if this session was already accepted/discarded
- if (isSessionHandled(sessionId)) return false;
-
- currentSessionId = sessionId;
- expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
- const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
- arrivedVariants = variants.length;
-
- // Restore state from localStorage if available
- const saved = loadSession();
- if (saved && saved.id === sessionId) {
- visibleVariant = (saved.visible > 0 && saved.visible <= arrivedVariants) ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
- if (saved.action) selectedAction = saved.action;
- if (saved.count) selectedCount = saved.count;
- } else {
- visibleVariant = arrivedVariants > 0 ? 1 : 0;
- }
-
- // Find the visible variant's content element for highlight positioning.
- // Try the visible variant first, fall back to the original's content.
- const visEl = visibleVariant > 0 ? pickVariantContent(wrapper, visibleVariant) : null;
- const origEl = pickVariantContent(wrapper, 'original');
- selectedElement = visEl || origEl || wrapper.parentElement;
-
- // Set display state BEFORE starting observer (avoid triggering it)
- if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
-
- state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
- showBar(state === 'CYCLING' ? 'cycling' : 'generating');
- startScrollTracking();
- // Build the params panel for the restored visible variant. Previously
- // this was missed on page-reload resume: showVariantInDOM above fires
- // refreshParamsPanel, but state was still IDLE at that moment so it
- // hid. Now that state is CYCLING, re-fire.
- if (state === 'CYCLING') refreshParamsPanel();
- saveSession();
- queueCheckpoint('browser_resumed');
-
- // Start observing for more variants AFTER initial setup
- if (variantObserver) variantObserver.disconnect();
- variantObserver = startVariantObserver(currentSessionId);
-
- // Hold the target at its saved viewport top through any subsequent
- // HMR patches, variant inserts, or cycle swaps.
- startScrollLock(currentSessionId, readScrollY());
-
- // If we reloaded mid-generation (Bun's HTML HMR destroys the shader
- // canvas), re-capture the original's content and restart the shader so
- // the wait doesn't go dead.
- if (state === 'GENERATING' && origEl) {
- (async () => {
- try {
- const rect = origEl.getBoundingClientRect();
- if (rect.width === 0 || rect.height === 0) return;
- const blob = await captureElementToBlob(origEl, null, rect);
- if (blob && state === 'GENERATING') {
- showShaderOverlay(origEl, blob, rect);
- }
- } catch (err) {
- console.warn('[impeccable] shader resume failed:', err);
- }
- })();
- }
- return true;
- }
-
- // ---------------------------------------------------------------------------
- // Global bar (always visible at bottom)
- // ---------------------------------------------------------------------------
-
- let globalBarEl = null;
- let detectActive = false;
- let pickActive = true;
- let detectCount = 0;
- let detectScriptLoaded = false;
-
- // Theme-aware color palette for the global bar. We detect the page's
- // ambient background and invert — dark bar on light pages, light bar on
- // dark pages. This keeps the bar from fighting with the host design.
- function detectPageTheme() {
- try {
- // Dev override: set localStorage 'impeccable-dev-theme' to 'light' or
- // 'dark' to preview the opposite palette without actually changing the
- // page bg. Used for screenshots and theme QA.
- const override = localStorage.getItem('impeccable-dev-theme');
- if (override === 'light' || override === 'dark') return override;
-
- // Walk body → html, taking the first opaque background. The browser's
- // default body / html background is `rgba(0, 0, 0, 0)`, which a naive
- // regex would read as black and mislabel a perfectly white page as
- // dark. Honoring alpha avoids that — and falling through to <html>
- // catches the common pattern of a bg only on <html> (or only on body).
- function readOpaque(el) {
- if (!el) return null;
- const bg = getComputedStyle(el).backgroundColor;
- const m = bg.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);
- if (!m) return null;
- const alpha = m[4] == null ? 1 : parseFloat(m[4]);
- if (alpha < 0.5) return null; // transparent / nearly transparent → skip
- return [+m[1], +m[2], +m[3]];
- }
-
- const rgb = readOpaque(document.body) || readOpaque(document.documentElement);
- // Both transparent → fall back to the browser's effective canvas color.
- // White is the universal default; only one in a thousand sites swaps it
- // via `color-scheme: dark` on <html>, and `prefers-color-scheme` lets
- // us catch that case.
- if (!rgb) {
- return matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
- }
- const [r, g, b] = rgb;
- // Perceptual luminance (Rec. 709)
- const L = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
- return L > 0.55 ? 'light' : 'dark';
- } catch { return 'light'; }
- }
-
- function barPaletteForTheme(theme) {
- if (theme === 'dark') {
- // Light bar on dark page
- return {
- surface: 'oklch(98% 0 0 / 0.92)',
- surfaceDeep: 'oklch(92% 0.005 60 / 0.96)', // slightly deeper, faint warm
- hairline: 'oklch(70% 0 0 / 0.35)',
- text: 'oklch(15% 0 0)',
- textDim: 'oklch(45% 0 0)',
- accent: 'oklch(60% 0.25 350)',
- accentSoft: 'oklch(60% 0.25 350 / 0.18)',
- mark: 'oklch(98% 0 0)', // logo mark fill
- markText: 'oklch(15% 0 0)', // logo "/" color
- exitHover: 'oklch(85% 0 0 / 0.5)',
- };
- }
- // Dark bar on light page. Bar is a warm charcoal, logo slab is much
- // deeper so the rounded-right shape reads as a clear sculpted mark.
- return {
- surface: 'oklch(26% 0 0 / 0.94)',
- surfaceDeep: 'oklch(18% 0 0 / 0.96)', // darker sand for Tune popover
- hairline: 'oklch(42% 0 0 / 0.5)',
- text: 'oklch(96% 0 0)',
- textDim: 'oklch(72% 0 0)',
- accent: 'oklch(72% 0.22 350)',
- accentSoft: 'oklch(72% 0.22 350 / 0.22)',
- mark: 'oklch(8% 0 0)',
- markText: 'oklch(96% 0 0)',
- exitHover: 'oklch(36% 0 0 / 0.6)',
- };
- }
-
- // Impeccable logo mark — matches the site-header SVG (rounded square + "/").
- function brandMarkSvg(fill, ink, size = 18) {
- return `<svg width="${size}" height="${size}" viewBox="0 0 32 32" aria-hidden="true">
- <rect width="32" height="32" rx="7" fill="${fill}"/>
- <text x="16" y="24" font-family="system-ui, -apple-system, sans-serif" font-size="22" font-weight="500" fill="${ink}" text-anchor="middle">/</text>
- </svg>`;
- }
-
- function initGlobalBar() {
- const theme = detectPageTheme();
- const P = barPaletteForTheme(theme);
-
- // Custom focus-visible for bar buttons. Browser default is a heavy
- // blue ring that looks jarring on the dark capsule. Replace with a
- // soft accent-tinted inner ring that respects the bar's palette.
- if (!document.getElementById(PREFIX + '-bar-focus-style')) {
- const s = document.createElement('style');
- s.id = PREFIX + '-bar-focus-style';
- s.textContent =
- '#' + PREFIX + '-global-bar button:focus { outline: none; }' +
- '#' + PREFIX + '-global-bar button:focus-visible {' +
- ' outline: none;' +
- ' box-shadow: 0 0 0 2px ' + P.accentSoft + ', 0 0 0 3px ' + P.accent + ';' +
- '}';
- document.head.appendChild(s);
- }
-
- globalBarEl = el('div', {
- position: 'fixed', bottom: '14px', left: '50%',
- transform: 'translateX(-50%) translateY(20px)',
- zIndex: Z.bar + 5,
- display: 'flex', alignItems: 'stretch',
- gap: '2px',
- background: P.surface,
- backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
- border: '1px solid ' + P.hairline,
- borderRadius: '10px',
- boxShadow: '0 4px 20px oklch(0% 0 0 / 0.12), 0 1px 3px oklch(0% 0 0 / 0.08)',
- fontFamily: FONT, fontSize: '12px', lineHeight: '1',
- opacity: '0',
- overflow: 'hidden', // clip the full-bleed brand mark to the bar radius
- transition: 'opacity 0.3s ' + EASE + ', transform 0.3s ' + EASE,
- });
- globalBarEl.id = PREFIX + '-global-bar';
- globalBarEl.dataset.theme = theme;
-
- // Brand mark — fills bar height on the left. Left side inherits the bar's
- // rounded corner via overflow:hidden; right side is a clean hard edge since
- // the near-black/charcoal contrast does the shape-defining work.
- const brand = el('span', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- alignSelf: 'stretch',
- padding: '0 12px 0 14px',
- background: P.mark,
- color: P.markText,
- fontFamily: 'system-ui, -apple-system, sans-serif',
- fontWeight: '500',
- fontSize: '18px', lineHeight: '1',
- });
- brand.textContent = '/';
- brand.title = 'Impeccable';
- globalBarEl.appendChild(brand);
-
- // Inner wrapper: holds the toggles with normal bar padding.
- const inner = el('div', {
- display: 'flex', alignItems: 'center',
- padding: '4px 5px', gap: '2px',
- });
- inner.id = PREFIX + '-global-bar-inner';
- globalBarEl.appendChild(inner);
-
- // --- button factory: icon-only at rest, label slides in on hover/active ---
- function makeIconBtn({ id, svg, label, ariaLabel, labelFont, onClick }) {
- const b = el('button', {
- position: 'relative',
- display: 'inline-flex', alignItems: 'center',
- padding: '6px 8px', borderRadius: '7px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '11.5px', fontWeight: '500',
- cursor: 'pointer',
- transition: 'background 0.15s ease, color 0.15s ease',
- whiteSpace: 'nowrap', overflow: 'hidden',
- });
- b.id = id;
- b.title = ariaLabel || label || '';
- b.setAttribute('aria-label', ariaLabel || label || '');
- b.innerHTML = svg + (label
- ? `<span class="icon-btn-label" style="display:inline-block;max-width:0;opacity:0;margin-left:0;overflow:hidden;font-family:${labelFont || FONT};transition:max-width 0.25s ${EASE}, opacity 0.2s ease, margin-left 0.25s ${EASE};">${label}</span>`
- : '');
- const labelEl = b.querySelector('.icon-btn-label');
- const expand = () => {
- if (!labelEl) return;
- labelEl.style.maxWidth = '120px'; labelEl.style.opacity = '1'; labelEl.style.marginLeft = '6px';
- };
- const collapse = () => {
- if (!labelEl || b.dataset.active === 'true') return;
- labelEl.style.maxWidth = '0'; labelEl.style.opacity = '0'; labelEl.style.marginLeft = '0';
- };
- // Per-button hover only changes color (no layout). The label expand/
- // collapse is driven by the bar-level mouseenter/mouseleave so moving
- // the mouse between adjacent buttons doesn't trigger per-button width
- // thrashing — the whole bar grows once and shrinks once.
- b.addEventListener('mouseenter', () => { if (b.dataset.active !== 'true') b.style.color = P.text; });
- b.addEventListener('mouseleave', () => { if (b.dataset.active !== 'true') b.style.color = P.textDim; });
- b.addEventListener('click', onClick);
- b._expandLabel = expand;
- b._collapseLabel = collapse;
- return b;
- }
-
- // Pick toggle — starts active (primary intent when entering live mode).
- const pickBtn = makeIconBtn({
- id: PREFIX + '-pick-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',
- label: 'Pick',
- ariaLabel: 'Pick element',
- onClick: () => togglePick(),
- });
- pickBtn.style.background = P.accentSoft;
- pickBtn.style.color = P.accent;
- pickBtn.dataset.active = 'true';
- pickBtn._expandLabel();
- inner.appendChild(pickBtn);
-
- // Detect toggle
- const detectBtn = makeIconBtn({
- id: PREFIX + '-detect-toggle',
- svg: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',
- label: 'Detect',
- ariaLabel: 'Detect anti-patterns',
- onClick: () => toggleDetect(),
- });
- const detectBadge = el('span', {
- fontSize: '10px', fontWeight: '600',
- padding: '0px 5px', borderRadius: '7px', lineHeight: '16px',
- background: P.accent, color: P.surface.includes('18%') ? 'oklch(18% 0 0)' : 'oklch(98% 0 0)',
- display: 'none', fontFamily: MONO, marginLeft: '4px',
- });
- detectBadge.id = PREFIX + '-detect-badge';
- detectBtn.appendChild(detectBadge);
- inner.appendChild(detectBtn);
-
- // DESIGN.md panel toggle — quartet of color squares as the mark.
- const designBtn = makeIconBtn({
- id: PREFIX + '-design-toggle',
- svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px ${P.hairline};flex-shrink:0">
- <span style="background:oklch(60% 0.25 350)"></span>
- <span style="background:oklch(60% 0.15 45)"></span>
- <span style="background:oklch(55% 0.12 250)"></span>
- <span style="background:oklch(30% 0 0)"></span>
- </span>`,
- label: 'DESIGN.md',
- ariaLabel: 'Toggle DESIGN.md panel',
- labelFont: MONO,
- onClick: () => toggleDesignPanel(),
- });
- inner.appendChild(designBtn);
-
- // Thin divider before the exit button
- const divider = el('span', {
- width: '1px', height: '18px',
- background: P.hairline,
- margin: '0 4px 0 2px',
- });
- inner.appendChild(divider);
-
- // Exit × on the right — intentionally subtle (textDim at rest, text on
- // hover) so it sits behind the active toggles in visual hierarchy.
- //
- // Explicit padding + box-sizing here is load-bearing: a host page like
- // `button { padding: 0.5rem 1rem; }` (very common in resets) would
- // otherwise inflate this 24x24 button into 56x40 and push the SVG out
- // of the visible bar — the X stays invisible even though the styles in
- // DevTools look fine. Every other chrome button sets padding inline;
- // this one needed it too.
- const exitBtn = el('button', {
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- padding: '0', boxSizing: 'border-box',
- width: '24px', height: '24px', borderRadius: '6px',
- border: 'none', background: 'transparent',
- color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
- cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
- });
- exitBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></svg>';
- exitBtn.title = 'Exit live mode';
- exitBtn.addEventListener('mouseenter', () => { exitBtn.style.color = P.text; exitBtn.style.background = P.exitHover; });
- exitBtn.addEventListener('mouseleave', () => { exitBtn.style.color = P.textDim; exitBtn.style.background = 'transparent'; });
- exitBtn.addEventListener('click', () => { sendEvent({ type: 'exit' }); teardown(); });
- inner.appendChild(exitBtn);
-
- // Bar-level hover: expand every toggle's label at once; collapse on leave.
- // Buttons with dataset.active="true" ignore collapse (their label stays).
- const toggles = [pickBtn, detectBtn, designBtn];
- globalBarEl.addEventListener('mouseenter', () => {
- toggles.forEach((t) => t._expandLabel && t._expandLabel());
- });
- globalBarEl.addEventListener('mouseleave', () => {
- toggles.forEach((t) => t._collapseLabel && t._collapseLabel());
- });
-
- document.body.appendChild(globalBarEl);
- defangOutsideHandlers(globalBarEl);
-
- requestAnimationFrame(() => {
- globalBarEl.style.opacity = '1';
- globalBarEl.style.transform = 'translateX(-50%) translateY(0)';
- });
-
- // Listen for detection results AND ready signal
- window.addEventListener('message', onDetectMessage);
- }
-
- function updateGlobalBarState() {
- const detectToggle = document.getElementById(PREFIX + '-detect-toggle');
- const detectBadge = document.getElementById(PREFIX + '-detect-badge');
- const pickToggle = document.getElementById(PREFIX + '-pick-toggle');
- const designToggle = document.getElementById(PREFIX + '-design-toggle');
- const theme = globalBarEl?.dataset.theme || 'light';
- const P = barPaletteForTheme(theme);
-
- // Sync one toggle's active state, colors, and slide-label visibility.
- function sync(btn, active) {
- if (!btn) return;
- btn.style.background = active ? P.accentSoft : 'transparent';
- btn.style.color = active ? P.accent : P.textDim;
- btn.dataset.active = active ? 'true' : 'false';
- if (active && btn._expandLabel) btn._expandLabel();
- else if (!active && btn._collapseLabel) btn._collapseLabel();
- }
- sync(pickToggle, pickActive);
- sync(detectToggle, detectActive);
- sync(designToggle, designState.open);
-
- // If the bar is currently under the cursor, keep all labels expanded —
- // otherwise clicking a toggle that deactivates (e.g. closing DESIGN.md)
- // would collapse its label while the user's mouse is still on the bar.
- if (globalBarEl && globalBarEl.matches(':hover')) {
- [pickToggle, detectToggle, designToggle].forEach((t) => t?._expandLabel?.());
- }
-
- if (detectBadge) {
- detectBadge.style.display = (detectActive && detectCount > 0) ? 'inline' : 'none';
- detectBadge.textContent = detectCount;
- }
-
- // When pick is active, make detect overlays click-through so the picker works
- document.querySelectorAll('.impeccable-overlay').forEach(o => {
- o.style.pointerEvents = pickActive ? 'none' : '';
- });
- }
-
- let detectReady = false; // true once detect script posts 'impeccable-ready'
- let detectPendingScan = false; // scan requested before script was ready
-
- function toggleDetect() {
- detectActive = !detectActive;
- updateGlobalBarState();
-
- if (detectActive) {
- if (!detectScriptLoaded) {
- detectPendingScan = true;
- loadDetectScript();
- } else if (detectReady) {
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- } else {
- detectPendingScan = true;
- }
- } else {
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- detectCount = 0;
- updateGlobalBarState();
- }
- }
-
- function togglePick() {
- pickActive = !pickActive;
- updateGlobalBarState();
-
- if (!pickActive) {
- // Disabling pick clears any in-flight selection and UI: highlight,
- // contextual bar, selectedElement. Otherwise a stale selection sits
- // on screen with no obvious way to dismiss.
- hideHighlight();
- hideBar();
- hideActionPicker();
- selectedElement = null;
- if (state === 'PICKING' || state === 'CONFIGURING') state = 'IDLE';
- } else {
- if (state === 'IDLE') state = 'PICKING';
- }
- }
-
- function loadDetectScript() {
- if (detectScriptLoaded) return;
- detectScriptLoaded = true;
- const s = document.createElement('script');
- s.src = 'http://localhost:' + PORT + '/detect.js';
- s.dataset.impeccableExtension = 'true';
- document.head.appendChild(s);
- }
-
- function onDetectMessage(e) {
- if (!e.data || typeof e.data.source !== 'string') return;
- // Detection script is loaded and ready
- if (e.data.source === 'impeccable-ready') {
- detectReady = true;
- if (detectPendingScan && detectActive) {
- detectPendingScan = false;
- window.postMessage({ source: 'impeccable-command', action: 'scan' }, '*');
- }
- }
- // Scan results arrived
- if (e.data.source === 'impeccable-results') {
- detectCount = e.data.count || 0;
- updateGlobalBarState();
- }
- }
-
- /** Full teardown: remove all UI, disconnect SSE, clean up. */
- function teardown() {
- cleanup();
- hideBar();
- if (globalBarEl) {
- globalBarEl.style.transform = 'translateY(100%)';
- setTimeout(() => { if (globalBarEl) globalBarEl.remove(); globalBarEl = null; }, 300);
- }
- if (highlightEl) { highlightEl.remove(); highlightEl = null; }
- if (tooltipEl) { tooltipEl.remove(); tooltipEl = null; }
- if (barEl) { barEl.remove(); barEl = null; }
- if (pickerEl) { pickerEl.remove(); pickerEl = null; }
- if (paramsPanelEl) { paramsPanelEl.remove(); paramsPanelEl = null; paramsPanelInner = null; paramsPanelBody = null; }
- if (evtSource) { evtSource.close(); evtSource = null; }
- document.removeEventListener('mousemove', handleMouseMove, true);
- document.removeEventListener('click', handleClick, true);
- document.removeEventListener('keydown', handleKeyDown, true);
- window.removeEventListener('message', onDetectMessage);
- // Remove detection overlays
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- state = 'IDLE';
- window.__IMPECCABLE_LIVE_INIT__ = false;
- console.log('[impeccable] Live mode exited.');
- }
-
- // ---------------------------------------------------------------------------
- // Design System Panel — visualizes the project's .impeccable/design.json sidecar
- // ---------------------------------------------------------------------------
-
- const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';
- const DESIGN_PANEL_WIDTH = 440;
-
- let designHost = null;
- let designShadow = null;
- let designState = {
- open: false,
- tab: 'visual', // 'visual' | 'raw'
- parsed: null, // parseDesignMd output (frontmatter + body sections)
- sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)
- hasMd: false,
- hasSidecar: false,
- present: null, // true/false once fetch resolves
- raw: null, // raw DESIGN.md for the raw tab
- mdNewerThanJson: false, // stale-hint flag
- loading: false,
- error: null,
- collapsed: { // narrative-section accordion state
- rules: true, dosdonts: true, overview: true,
- },
- };
-
- function loadDesignPrefs() {
- // `open` is intentionally NOT persisted — the panel always starts closed
- // so live mode doesn't auto-slide a big panel over the page on startup.
- try {
- const raw = localStorage.getItem(DESIGN_PREFS_KEY);
- if (!raw) return;
- const prefs = JSON.parse(raw);
- if (prefs.tab === 'visual' || prefs.tab === 'raw') designState.tab = prefs.tab;
- if (prefs.collapsed && typeof prefs.collapsed === 'object') {
- Object.assign(designState.collapsed, prefs.collapsed);
- }
- } catch { /* ignore */ }
- }
-
- function saveDesignPrefs() {
- try {
- localStorage.setItem(DESIGN_PREFS_KEY, JSON.stringify({
- tab: designState.tab,
- collapsed: designState.collapsed,
- }));
- } catch { /* ignore */ }
- }
-
- function initDesignPanel() {
- designHost = document.createElement('div');
- designHost.id = PREFIX + '-design-host';
- Object.assign(designHost.style, {
- position: 'fixed', top: '0', left: '0',
- width: '0', height: '0',
- zIndex: String(Z.bar + 10),
- pointerEvents: 'none',
- });
- designShadow = designHost.attachShadow({ mode: 'open' });
-
- const style = document.createElement('style');
- // Theme-match the bar: dark chrome on light pages, light chrome on dark pages.
- const theme = detectPageTheme();
- style.textContent = designPanelCss(barPaletteForTheme(theme));
- designShadow.appendChild(style);
-
- const root = document.createElement('div');
- root.className = 'root';
- designShadow.appendChild(root);
-
- document.body.appendChild(designHost);
- // The host is pointer-events: none; the panel inside the shadow DOM
- // manages its own auto/none. Events bubble through the shadow boundary,
- // so attaching here silences host-page outside-interaction handlers
- // without touching the host's click-through behavior.
- defangOutsideHandlers(designHost, { setPointerEvents: false });
-
- loadDesignPrefs();
- renderDesignChrome();
- if (designState.open) {
- fetchDesignSystem();
- }
- }
-
- // Neutral panel palette — deliberately NOT Impeccable-branded. The panel is
- // a viewer of the project's design system, not an Impeccable surface.
- const DP = {
- canvas: 'oklch(94% 0 0)', // panel background
- tile: 'oklch(98.5% 0 0)', // card-on-canvas
- tileAlt: 'oklch(96% 0 0)', // subtler tile for inner surfaces
- ink: 'oklch(15% 0 0)',
- ink2: 'oklch(35% 0 0)',
- meta: 'oklch(55% 0 0)',
- hairline: 'oklch(88% 0 0)',
- hairlineSoft: 'oklch(92% 0 0)',
- amber: 'oklch(70% 0.13 65)', // stale-hint accent
- amberBg: 'oklch(95% 0.05 80)',
- };
-
- function designPanelCss(BP) {
- // BP = bar palette (theme-aware, matches the global bar).
- // DP = internal content palette (neutral, so tiles render colors true).
- return `
- :host, .root { all: initial; }
- .root {
- font-family: ${FONT};
- color: ${DP.ink};
- pointer-events: none;
- }
- .root * { box-sizing: border-box; }
- button { font: inherit; color: inherit; }
-
- /* --- Panel shell: chrome matches the bar; body canvas stays neutral --- */
- .panel {
- position: fixed; top: 12px; bottom: 72px; right: 12px;
- width: ${DESIGN_PANEL_WIDTH}px; max-width: calc(100vw - 24px);
- background: ${BP.surface};
- border: 1px solid ${BP.hairline};
- border-radius: 14px;
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- box-shadow: 0 20px 60px oklch(0% 0 0 / 0.18), 0 4px 12px oklch(0% 0 0 / 0.08);
- display: flex; flex-direction: column;
- transform: translateX(calc(100% + 24px));
- opacity: 0;
- transition: transform 0.35s ${EASE}, opacity 0.25s ${EASE};
- pointer-events: none;
- overflow: hidden;
- }
- .panel[data-open="true"] { transform: translateX(0); opacity: 1; pointer-events: auto; }
-
- .panel-header {
- display: flex; align-items: center; gap: 10px;
- padding: 10px 10px 10px 14px;
- background: transparent;
- border-bottom: 1px solid ${BP.hairline};
- }
- .panel-title {
- flex: 1; min-width: 0;
- font-family: ${MONO};
- font-size: 11.5px; font-weight: 600;
- letter-spacing: 0.02em;
- color: ${BP.text};
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
- }
- .panel-close {
- border: none; background: transparent; color: ${BP.textDim};
- width: 26px; height: 26px; border-radius: 7px;
- display: inline-flex; align-items: center; justify-content: center;
- cursor: pointer; transition: background 0.15s ease, color 0.15s ease;
- }
- .panel-close:hover { background: ${BP.hairline}; color: ${BP.text}; }
-
- .tabs {
- display: inline-flex; padding: 2px;
- background: ${BP.hairline};
- border-radius: 7px;
- gap: 2px;
- }
- .tab {
- border: none; background: transparent;
- padding: 4px 10px; border-radius: 5px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 600; letter-spacing: 0.08em;
- text-transform: uppercase;
- color: ${BP.textDim}; cursor: pointer;
- transition: background 0.15s ease, color 0.15s ease;
- }
- .tab[data-active="true"] { background: ${BP.surface}; color: ${BP.text}; }
-
- .panel-body {
- flex: 1; overflow-y: auto;
- padding: 12px 12px 20px;
- background: ${DP.canvas};
- scrollbar-width: thin;
- scrollbar-color: ${DP.hairline} transparent;
- }
- .panel-body::-webkit-scrollbar { width: 8px; }
- .panel-body::-webkit-scrollbar-thumb { background: ${DP.hairline}; border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
-
- /* --- States --- */
- .empty, .loading, .error {
- margin: 16px 4px;
- padding: 28px 20px; text-align: center;
- background: ${DP.tile}; border-radius: 14px;
- color: ${DP.ink2}; font-size: 13px; line-height: 1.55;
- }
- .empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
- .empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
- .error { color: oklch(45% 0.15 25); }
-
- /* --- Stale hint --- */
- .stale {
- display: flex; align-items: center; gap: 8px;
- margin: 8px 4px 12px;
- padding: 8px 12px;
- background: ${DP.amberBg};
- border-radius: 10px;
- font-size: 11.5px; color: ${DP.ink2};
- }
- .stale-dot { width: 8px; height: 8px; border-radius: 50%; background: ${DP.amber}; flex-shrink: 0; }
- .stale-text { flex: 1; min-width: 0; }
- .stale-text strong { color: ${DP.ink}; font-weight: 600; }
-
- /* --- Parsed-md fallback banner --- */
- .parsed-md-cta {
- margin: 8px 4px 14px;
- padding: 14px 16px;
- background: ${DP.tile};
- border: 1px dashed ${DP.hairline};
- border-radius: 12px;
- font-size: 12px; color: ${DP.ink2}; line-height: 1.55;
- }
- .parsed-md-cta strong { color: ${DP.ink}; display: block; margin-bottom: 4px; font-size: 13px; font-weight: 600; }
- .parsed-md-cta code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; font-size: 11.5px; color: ${DP.ink}; }
-
- /* --- Tile primitives --- */
- .tile {
- position: relative;
- background: ${DP.tile};
- border-radius: 16px;
- padding: 16px;
- margin: 0 4px 10px;
- }
- .tile-row { margin: 0 4px 10px; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
- .tile-row .tile { margin: 0; }
- .tile-meta {
- display: flex; align-items: baseline; justify-content: space-between;
- gap: 10px;
- font-family: ${MONO};
- font-size: 10px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase;
- color: ${DP.meta};
- }
- .tile-meta .name { color: ${DP.ink}; font-weight: 600; letter-spacing: 0.05em; text-transform: none; font-family: ${FONT}; font-size: 12.5px; }
-
- /* --- Color tile --- */
- .c-tile { cursor: pointer; transition: transform 0.2s ${EASE}; }
- .c-tile:hover { transform: translateY(-1px); }
- .c-hero {
- height: 72px; border-radius: 10px; margin-top: 10px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.05);
- }
- .c-ramp {
- display: flex; gap: 0; height: 14px; border-radius: 4px; overflow: hidden;
- margin-top: 8px;
- box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.04);
- }
- .c-ramp > span { flex: 1; }
- .c-desc { margin-top: 8px; font-size: 11.5px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Type tile --- */
- .t-tile { }
- .t-specimen {
- margin: 4px 0 6px;
- color: ${DP.ink};
- line-height: 0.9;
- }
- .t-family { margin-top: 4px; font-size: 12px; font-weight: 600; color: ${DP.ink}; }
- .t-purpose { margin-top: 4px; font-size: 11px; line-height: 1.45; color: ${DP.ink2}; }
-
- /* --- Shadow tile --- */
- .s-tile { }
- .s-surface {
- height: 60px; margin: 8px 2px 10px;
- background: ${DP.tile};
- border-radius: 10px;
- }
- .s-value { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; word-break: break-all; line-height: 1.4; }
- .s-purpose { margin-top: 4px; font-size: 11px; color: ${DP.ink2}; line-height: 1.45; }
-
- /* --- Radii strip --- */
- .r-strip { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
- .r-item { display: flex; flex-direction: column; align-items: center; gap: 4px; flex: 1; min-width: 60px; }
- .r-sample { width: 44px; height: 44px; background: ${DP.canvas}; box-shadow: inset 0 0 0 1px oklch(0% 0 0 / 0.08); }
- .r-label { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; text-transform: uppercase; }
- .r-val { font-family: ${MONO}; font-size: 10px; color: ${DP.ink}; }
-
- /* --- Component tile (hosts live primitives) --- */
- .cmp-tile { }
- .cmp-stage {
- margin: 12px -4px 0;
- padding: 18px 16px 10px;
- border-top: 1px solid ${DP.hairlineSoft};
- display: flex; flex-direction: column; align-items: center; justify-content: center;
- gap: 14px;
- min-height: 68px;
- }
- .cmp-stage + .cmp-stage { border-top: 1px dashed ${DP.hairlineSoft}; }
- .cmp-sublabel { font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.06em; }
- .cmp-kind { font-family: ${MONO}; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; }
-
- /* --- Collapsible --- */
- .coll {
- margin: 0 4px 8px;
- background: ${DP.tile};
- border-radius: 12px;
- overflow: hidden;
- }
- .coll-head {
- display: flex; align-items: center; gap: 10px;
- width: 100%;
- padding: 12px 14px;
- background: transparent; border: none;
- cursor: pointer; text-align: left;
- font-family: ${FONT}; font-size: 12.5px; font-weight: 600; color: ${DP.ink};
- transition: background 0.12s ease;
- }
- .coll-head:hover { background: ${DP.tileAlt}; }
- .coll-chev {
- width: 12px; height: 12px; flex-shrink: 0;
- color: ${DP.meta};
- transition: transform 0.2s ${EASE};
- }
- .coll[data-open="true"] .coll-chev { transform: rotate(90deg); }
- .coll-count { margin-left: auto; font-family: ${MONO}; font-size: 10px; color: ${DP.meta}; letter-spacing: 0.05em; }
- .coll-body { padding: 0 14px 14px; display: none; }
- .coll[data-open="true"] .coll-body { display: block; }
-
- .rule-card {
- padding: 10px 0;
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .rule-card:first-child { border-top: none; padding-top: 2px; }
- .rule-card .name { font-size: 11.5px; font-weight: 700; color: ${DP.ink}; margin-bottom: 3px; }
- .rule-card .name .section { font-family: ${MONO}; font-size: 9px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: ${DP.meta}; margin-left: 8px; }
- .rule-card .body { font-size: 11.5px; color: ${DP.ink2}; line-height: 1.5; }
-
- .coll .dos { display: grid; gap: 0; margin-top: 2px; }
- .coll .do, .coll .dont {
- position: relative;
- padding: 8px 0 8px 22px;
- font-size: 11.5px; line-height: 1.5; color: ${DP.ink2};
- border-top: 1px solid ${DP.hairlineSoft};
- }
- .coll .do:first-child, .coll .dont:first-child,
- .coll .do:first-of-type { border-top: none; }
- .coll .do + .dont { border-top: 1px solid ${DP.hairlineSoft}; }
- .coll .do::before, .coll .dont::before {
- content: ''; position: absolute; left: 4px; top: 13px;
- width: 8px; height: 8px; border-radius: 50%;
- }
- .coll .do::before { background: oklch(62% 0.16 145); }
- .coll .dont::before { background: oklch(58% 0.22 25); }
-
- .coll .overview-body {
- font-size: 12px; line-height: 1.55; color: ${DP.ink2};
- }
- .coll .overview-body .north-star {
- display: block; font-family: ${FONT}; font-style: italic;
- font-size: 15px; line-height: 1.3; color: ${DP.ink};
- margin-bottom: 8px;
- }
- .coll .overview-body p { margin: 0 0 8px; }
- .coll .overview-body ul { margin: 6px 0 0; padding-left: 16px; font-size: 11.5px; }
- .coll .overview-body li { margin-bottom: 3px; }
-
- /* --- raw tab markdown (unchanged layout, neutralized palette) --- */
- .md { padding: 4px 10px 20px; font-size: 13px; line-height: 1.6; color: ${DP.ink}; }
- .md h1, .md h2, .md h3, .md h4 { margin: 20px 0 8px; color: ${DP.ink}; font-weight: 600; }
- .md h1 { font-size: 18px; }
- .md h2 { font-size: 15px; padding-bottom: 4px; border-bottom: 1px solid ${DP.hairlineSoft}; }
- .md h3 { font-size: 13px; }
- .md h4 { font-size: 12px; color: ${DP.meta}; }
- .md p { margin: 0 0 10px; }
- .md ul, .md ol { margin: 0 0 10px; padding-left: 20px; }
- .md li { margin-bottom: 4px; }
- .md code { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 1px 5px; border-radius: 4px; }
- .md pre { font-family: ${MONO}; font-size: 12px; background: ${DP.canvas}; padding: 10px 12px; border-radius: 8px; overflow-x: auto; margin: 0 0 10px; }
- .md pre code { background: none; padding: 0; }
- .md strong { font-weight: 700; }
- .md em { font-style: italic; }
- .md a { color: ${DP.ink}; text-decoration: underline; }
- .md hr { border: none; border-top: 1px solid ${DP.hairlineSoft}; margin: 16px 0; }
- `;
- }
-
- function renderDesignChrome() {
- const root = designShadow.querySelector('.root');
- root.innerHTML = '';
-
- // (Panel toggle lives in the global bar — no floating FAB.)
- // Panel
- const panel = document.createElement('aside');
- panel.className = 'panel';
- panel.setAttribute('data-open', designState.open ? 'true' : 'false');
- panel.appendChild(buildDesignHeader());
- const body = document.createElement('div');
- body.className = 'panel-body';
- body.id = 'panel-body';
- panel.appendChild(body);
- root.appendChild(panel);
-
- renderDesignBody();
- }
-
- function buildDesignHeader() {
- const header = document.createElement('div');
- header.className = 'panel-header';
-
- const title = document.createElement('div');
- title.className = 'panel-title';
- title.textContent = 'DESIGN.md';
- header.appendChild(title);
-
- const tabs = document.createElement('div');
- tabs.className = 'tabs';
- for (const t of [['visual', 'Visual'], ['raw', 'Raw']]) {
- const btn = document.createElement('button');
- btn.className = 'tab';
- btn.textContent = t[1];
- btn.setAttribute('data-active', designState.tab === t[0] ? 'true' : 'false');
- btn.addEventListener('click', () => {
- if (designState.tab === t[0]) return;
- designState.tab = t[0];
- saveDesignPrefs();
- renderDesignChrome();
- if (t[0] === 'raw' && designState.raw === null && !designState.loading) {
- fetchDesignSystem(); // raw is part of the same fetch pair
- }
- });
- tabs.appendChild(btn);
- }
- header.appendChild(tabs);
-
- const close = document.createElement('button');
- close.className = 'panel-close';
- close.innerHTML = '✕';
- close.setAttribute('aria-label', 'Close panel');
- close.addEventListener('click', toggleDesignPanel);
- header.appendChild(close);
-
- return header;
- }
-
- function toggleDesignPanel() {
- designState.open = !designState.open;
- renderDesignChrome();
- updateGlobalBarState();
- if (designState.open && designState.present === null && !designState.loading) {
- fetchDesignSystem();
- }
- }
-
- async function fetchDesignSystem() {
- designState.loading = true;
- designState.error = null;
- renderDesignBody();
- try {
- const [jsonRes, rawRes] = await Promise.all([
- fetch(`http://localhost:${PORT}/design-system.json?token=${TOKEN}`, { cache: 'no-store' }),
- fetch(`http://localhost:${PORT}/design-system/raw?token=${TOKEN}`, { cache: 'no-store' }),
- ]);
- const jsonData = await jsonRes.json();
- designState.present = jsonData.present === true;
- designState.parsed = jsonData.parsed || null;
- designState.sidecar = jsonData.sidecar || null;
- designState.hasMd = !!jsonData.hasMd;
- designState.hasSidecar = !!jsonData.hasSidecar;
- designState.mdNewerThanJson = !!jsonData.mdNewerThanJson;
- designState.raw = designState.present && rawRes.ok ? await rawRes.text() : null;
- designState.error = jsonData.parseError || jsonData.sidecarError || null;
- } catch (err) {
- designState.error = err?.message || 'Failed to load design system.';
- } finally {
- designState.loading = false;
- renderDesignChrome(); // refresh title from data
- }
- }
-
- function renderDesignBody() {
- const body = designShadow.querySelector('#panel-body');
- if (!body) return;
- body.innerHTML = '';
-
- if (designState.loading) {
- body.appendChild(msgDiv('loading', 'Loading design system…'));
- return;
- }
- if (designState.error) {
- body.appendChild(msgDiv('error', designState.error));
- return;
- }
- if (designState.present === false) {
- const empty = document.createElement('div');
- empty.className = 'empty';
- empty.innerHTML = `<strong>No DESIGN.md yet</strong>Create one by running <code>/impeccable document</code> in your terminal, then re-open this panel.`;
- body.appendChild(empty);
- return;
- }
-
- if (designState.tab === 'raw') {
- renderRawTab(body, designState.raw || '');
- return;
- }
-
- // Visual tab — single unified render path.
- if (designState.mdNewerThanJson) body.appendChild(renderStaleHint());
- if (designState.hasMd && !designState.hasSidecar) {
- body.appendChild(renderParsedMdCta());
- }
- renderDesignVisual(body, designState.parsed, designState.sidecar);
- }
-
- function msgDiv(cls, text) {
- const d = document.createElement('div');
- d.className = cls;
- d.textContent = text;
- return d;
- }
-
- function renderStaleHint() {
- const box = document.createElement('div');
- box.className = 'stale';
- box.innerHTML = `
- <span class="stale-dot"></span>
- <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>
- `;
- return box;
- }
-
- function renderParsedMdCta() {
- const box = document.createElement('div');
- box.className = 'parsed-md-cta';
- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;
- return box;
- }
-
- // --- Unified render: merge parsed DESIGN.md frontmatter with sidecar v2 ---
-
- function renderDesignVisual(body, parsed, sidecar) {
- const frontmatter = parsed?.frontmatter || {};
- const extensions = sidecar?.extensions || {};
- const proseColors = parsed?.colors || null;
-
- const colors = buildColorModels(frontmatter.colors, extensions.colorMeta, proseColors);
- if (colors.length) renderColorTiles(body, colors);
-
- const types = buildTypographyModels(frontmatter.typography, extensions.typographyMeta);
- if (types.length) renderTypeTiles(body, types);
-
- const radii = buildRadiiModels(frontmatter.rounded);
- if (radii.length) renderRadiiTile(body, radii);
-
- if (extensions.shadows?.length) renderShadowTiles(body, extensions.shadows);
-
- const components = sidecar?.components || [];
- if (components.length) renderComponentTiles(body, components);
-
- // Narrative: sidecar wins if present (richer, agent-curated). Otherwise
- // synthesize from prose sections.
- const narrative = sidecar?.narrative || synthesizeNarrative(parsed);
- if (narrative.rules?.length) body.appendChild(renderRulesCollapsible(narrative.rules));
- if ((narrative.dos?.length || narrative.donts?.length)) body.appendChild(renderDosDontsCollapsible(narrative));
- if (narrative.overview || narrative.northStar || narrative.keyCharacteristics?.length) {
- body.appendChild(renderOverviewCollapsible(narrative));
- }
-
- if (body.childElementCount === 0) {
- body.appendChild(msgDiv('empty', 'No design system data available.'));
- }
- }
-
- // Frontmatter primitives + sidecar colorMeta → tile-ready color models.
- // A matching prose bullet (when the slug sits in the bullet text) supplies
- // description as a last-resort fallback.
- function buildColorModels(fmColors, colorMeta, proseColors) {
- if (!fmColors) return [];
- const meta = colorMeta || {};
- return Object.entries(fmColors).map(([key, value]) => {
- const m = meta[key] || {};
- return {
- role: m.role || humanizeKey(key),
- name: m.displayName || humanizeKey(key),
- value: value,
- canonical: m.canonical || null,
- description: m.description || findProseDescription(proseColors, key, m.displayName),
- tonalRamp: m.tonalRamp || null,
- };
- });
- }
-
- function buildTypographyModels(fmTypography, typographyMeta) {
- if (!fmTypography) return [];
- const meta = typographyMeta || {};
- return Object.entries(fmTypography).map(([key, spec]) => {
- const m = meta[key] || {};
- const { family, fallback } = splitFontFamily(spec?.fontFamily);
- return {
- role: key,
- name: m.displayName || humanizeKey(key),
- family,
- fallback,
- weight: spec?.fontWeight ?? 400,
- // fontStyle isn't in Stitch's frontmatter schema; the sidecar carries
- // it when a role is rendered in italic (e.g. display italic).
- style: m.style || 'normal',
- sampleSize: spec?.fontSize || '1rem',
- lineHeight: spec?.lineHeight != null ? String(spec.lineHeight) : '',
- letterSpacing: spec?.letterSpacing,
- purpose: m.purpose,
- };
- });
- }
-
- function buildRadiiModels(fmRounded) {
- if (!fmRounded) return [];
- return Object.entries(fmRounded).map(([name, value]) => ({ name, value }));
- }
-
- function splitFontFamily(stack) {
- if (!stack || typeof stack !== 'string') return { family: '', fallback: '' };
- const parts = stack.split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, ''));
- return { family: parts[0] || '', fallback: parts.slice(1).join(', ') };
- }
-
- function humanizeKey(k) {
- return String(k || '').replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
- }
-
- function findProseDescription(proseColors, key, displayName) {
- if (!proseColors || !proseColors.groups) return null;
- const needles = [key, displayName].filter(Boolean).map((s) => s.toLowerCase());
- for (const g of proseColors.groups) {
- for (const c of g.colors || []) {
- const hay = String(c.name || '').toLowerCase();
- if (hay && needles.some((n) => hay.includes(n) || n.includes(hay))) {
- return c.description || null;
- }
- }
- }
- return null;
- }
-
- function synthesizeNarrative(parsed) {
- if (!parsed) return {};
- const md = parsed;
- return {
- northStar: md.overview?.creativeNorthStar,
- overview: (md.overview?.philosophy || []).join(' '),
- keyCharacteristics: md.overview?.keyCharacteristics || [],
- rules: [
- ...(md.colors?.rules || []).map((r) => ({ ...r, section: 'colors' })),
- ...(md.typography?.rules || []).map((r) => ({ ...r, section: 'typography' })),
- ...(md.elevation?.rules || []).map((r) => ({ ...r, section: 'elevation' })),
- ],
- dos: md.dosDonts?.dos || [],
- donts: md.dosDonts?.donts || [],
- };
- }
-
- function renderColorTiles(body, colors) {
- for (const c of colors) {
- const tile = document.createElement('div');
- tile.className = 'tile c-tile';
- tile.title = 'Click to copy';
- tile.addEventListener('click', () => copyToClipboard(c.value));
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(c.name || c.role || 'Color')}</span><span>${escapeHtml(c.value || '')}</span>`;
- tile.appendChild(meta);
-
- const hero = document.createElement('div');
- hero.className = 'c-hero';
- hero.style.background = c.value;
- tile.appendChild(hero);
-
- const ramp = synthesizeRamp(c);
- if (ramp.length) {
- const r = document.createElement('div');
- r.className = 'c-ramp';
- r.innerHTML = ramp.map((v) => `<span style="background:${cssSafe(v)}"></span>`).join('');
- tile.appendChild(r);
- }
-
- if (c.description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = c.description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function synthesizeRamp(c) {
- if (c.tonalRamp?.length) return c.tonalRamp;
- // If base value is OKLCH, synthesize an 8-step ramp across lightness.
- const m = typeof c.value === 'string' && c.value.match(/^oklch\(\s*([\d.]+)%\s+([\d.]+)\s+([\d.]+)\s*(?:\/\s*([\d.]+))?\s*\)$/i);
- if (!m) return [];
- const [, , chroma, hue] = m;
- const steps = [20, 32, 44, 56, 68, 80, 90, 96];
- return steps.map((l) => `oklch(${l}% ${chroma} ${hue})`);
- }
-
- function renderTypeTiles(body, types) {
- for (const t of types) {
- const tile = document.createElement('div');
- tile.className = 'tile t-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span>${escapeHtml(t.role || '')}</span><span>${escapeHtml(t.weight || '')} ${escapeHtml(t.style === 'italic' ? 'italic' : '')}</span>`;
- tile.appendChild(meta);
-
- const specimen = document.createElement('div');
- specimen.className = 't-specimen';
- specimen.textContent = 'Aa';
- specimen.style.fontFamily = fontStack(t);
- specimen.style.fontWeight = String(t.weight || 400);
- specimen.style.fontStyle = t.style || 'normal';
- specimen.style.fontSize = '56px'; // Fixed specimen size — compare faces, not scales.
- specimen.style.letterSpacing = 'normal';
- specimen.style.textTransform = 'none';
- tile.appendChild(specimen);
-
- // The system's actual sample size for this role, shown as small mono meta below.
- if (t.sampleSize) {
- const scale = document.createElement('div');
- scale.style.cssText = 'font-family:' + MONO + '; font-size: 10px; color:' + DP.meta + '; margin-top: 2px;';
- scale.textContent = t.sampleSize;
- tile.appendChild(scale);
- }
-
- const family = document.createElement('div');
- family.className = 't-family';
- family.textContent = t.family || t.name || '';
- tile.appendChild(family);
-
- if (t.purpose) {
- const p = document.createElement('div');
- p.className = 't-purpose';
- p.textContent = t.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function fontStack(t) {
- const fam = t.family || '';
- const fb = t.fallback || '';
- if (fam && /[,\s]/.test(fam) && !fam.includes("'") && !fam.includes('"')) {
- return `"${fam}", ${fb}`;
- }
- return fam && fb ? `"${fam}", ${fb}` : (fam || fb);
- }
-
- function renderRadiiTile(body, radii) {
- const tile = document.createElement('div');
- tile.className = 'tile';
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">Corner Radii</span><span>${radii.length}</span>`;
- tile.appendChild(meta);
-
- const strip = document.createElement('div');
- strip.className = 'r-strip';
- for (const r of radii) {
- const item = document.createElement('div');
- item.className = 'r-item';
- const s = document.createElement('div');
- s.className = 'r-sample';
- s.style.borderRadius = r.value || '0';
- item.appendChild(s);
- const lbl = document.createElement('div');
- lbl.className = 'r-label';
- lbl.textContent = r.name || '';
- item.appendChild(lbl);
- const val = document.createElement('div');
- val.className = 'r-val';
- val.textContent = r.value || '';
- item.appendChild(val);
- strip.appendChild(item);
- }
- tile.appendChild(strip);
- body.appendChild(tile);
- }
-
- function renderShadowTiles(body, shadows) {
- for (const sh of shadows) {
- const tile = document.createElement('div');
- tile.className = 'tile s-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- meta.innerHTML = `<span class="name">${escapeHtml(sh.name || 'Shadow')}</span><span>Elevation</span>`;
- tile.appendChild(meta);
-
- const surface = document.createElement('div');
- surface.className = 's-surface';
- surface.style.boxShadow = sh.value || 'none';
- tile.appendChild(surface);
-
- const val = document.createElement('div');
- val.className = 's-value';
- val.textContent = sh.value || '';
- tile.appendChild(val);
-
- if (sh.purpose) {
- const p = document.createElement('div');
- p.className = 's-purpose';
- p.textContent = sh.purpose;
- tile.appendChild(p);
- }
- body.appendChild(tile);
- }
- }
-
- function renderComponentTiles(body, components) {
- // Group consecutive components that share a kind into one tile. This avoids
- // a pile of one-component tiles (e.g., three button variants = three tiles)
- // and reads more like a proper category.
- const groups = groupByKind(components);
-
- for (const group of groups) {
- const tile = document.createElement('div');
- tile.className = 'tile cmp-tile';
-
- const meta = document.createElement('div');
- meta.className = 'tile-meta';
- const groupTitle = group.length === 1
- ? (group[0].name || group[0].kind || 'Component')
- : titleForKind(group[0].kind, group.length);
- meta.innerHTML = `<span class="name">${escapeHtml(groupTitle)}</span><span class="cmp-kind">${escapeHtml(group[0].kind || '')}</span>`;
- tile.appendChild(meta);
-
- for (const c of group) {
- const stage = document.createElement('div');
- stage.className = 'cmp-stage';
-
- // Render the component in its own shadow root so its CSS can't bleed.
- const host = document.createElement('div');
- const sub = host.attachShadow({ mode: 'open' });
- const style = document.createElement('style');
- style.textContent = c.css || '';
- sub.appendChild(style);
- const container = document.createElement('div');
- container.innerHTML = c.html || '';
- sub.appendChild(container);
- stage.appendChild(host);
-
- // Show component name as a sublabel only when the tile groups >1 item,
- // or when the component's display name differs from its kind.
- const showSublabel = group.length > 1;
- if (showSublabel) {
- const lbl = document.createElement('div');
- lbl.className = 'cmp-sublabel';
- lbl.textContent = c.name || '';
- stage.appendChild(lbl);
- }
- tile.appendChild(stage);
- }
-
- // Single shared description if all items carry the same one; otherwise
- // skip — per-item descriptions clutter a grouped tile.
- if (group.length === 1 && group[0].description) {
- const d = document.createElement('div');
- d.className = 'c-desc';
- d.textContent = group[0].description;
- tile.appendChild(d);
- }
- body.appendChild(tile);
- }
- }
-
- function groupByKind(components) {
- const groups = [];
- for (const c of components) {
- const last = groups[groups.length - 1];
- if (last && last[0].kind && c.kind === last[0].kind) {
- last.push(c);
- } else {
- groups.push([c]);
- }
- }
- return groups;
- }
-
- function titleForKind(kind, count) {
- const labels = {
- button: 'Buttons',
- input: 'Inputs',
- nav: 'Navigation',
- chip: 'Chips',
- card: 'Cards',
- custom: 'Components',
- };
- return labels[kind] || (kind ? kind.charAt(0).toUpperCase() + kind.slice(1) + 's' : 'Components');
- }
-
- // --- Collapsibles ---------------------------------------------------------
-
- function buildCollapsible(key, label, count) {
- const wrap = document.createElement('div');
- wrap.className = 'coll';
- wrap.setAttribute('data-open', designState.collapsed[key] ? 'false' : 'true');
-
- const head = document.createElement('button');
- head.className = 'coll-head';
- head.innerHTML = `
- <svg class="coll-chev" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 2.5L8 6 4 9.5"/></svg>
- <span>${escapeHtml(label)}</span>
- ${count != null ? `<span class="coll-count">${escapeHtml(String(count))}</span>` : ''}
- `;
- head.addEventListener('click', () => {
- designState.collapsed[key] = !designState.collapsed[key];
- saveDesignPrefs();
- renderDesignBody();
- });
- wrap.appendChild(head);
-
- const body = document.createElement('div');
- body.className = 'coll-body';
- wrap.appendChild(body);
- return { wrap, body };
- }
-
- function renderRulesCollapsible(rules) {
- const { wrap, body } = buildCollapsible('rules', 'Named Rules', rules.length);
- for (const r of rules) {
- const card = document.createElement('div');
- card.className = 'rule-card';
- const name = document.createElement('div');
- name.className = 'name';
- name.innerHTML = `${escapeHtml(r.name)}${r.section ? `<span class="section">${escapeHtml(r.section)}</span>` : ''}`;
- card.appendChild(name);
- const b = document.createElement('div');
- b.className = 'body';
- b.textContent = r.body || '';
- card.appendChild(b);
- body.appendChild(card);
- }
- return wrap;
- }
-
- function renderDosDontsCollapsible(n) {
- const total = (n.dos?.length || 0) + (n.donts?.length || 0);
- const { wrap, body } = buildCollapsible('dosdonts', "Do's and Don'ts", total);
- const grid = document.createElement('div');
- grid.className = 'dos';
- for (const d of n.dos || []) {
- const el = document.createElement('div');
- el.className = 'do';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- for (const d of n.donts || []) {
- const el = document.createElement('div');
- el.className = 'dont';
- el.innerHTML = inlineMd(d);
- grid.appendChild(el);
- }
- body.appendChild(grid);
- return wrap;
- }
-
- function renderOverviewCollapsible(n) {
- const { wrap, body } = buildCollapsible('overview', 'Overview', null);
- const ov = document.createElement('div');
- ov.className = 'overview-body';
- if (n.northStar) {
- const star = document.createElement('span');
- star.className = 'north-star';
- star.textContent = '“' + n.northStar + '”';
- ov.appendChild(star);
- }
- if (n.overview) {
- const p = document.createElement('p');
- p.innerHTML = inlineMd(n.overview);
- ov.appendChild(p);
- }
- if (n.keyCharacteristics?.length) {
- const ul = document.createElement('ul');
- ul.innerHTML = n.keyCharacteristics.map((k) => `<li>${inlineMd(k)}</li>`).join('');
- ov.appendChild(ul);
- }
- body.appendChild(ov);
- return wrap;
- }
-
- function cssSafe(v) {
- // Strip anything outside valid CSS value chars to prevent injection via
- // .impeccable/design.json values rendered into inline style strings.
- return String(v).replace(/[<>"'`\n]/g, '');
- }
-
- // --- Raw tab: minimal markdown renderer (subset) --------------------------
-
- function renderRawTab(body, md) {
- const wrap = document.createElement('div');
- wrap.className = 'md';
- wrap.innerHTML = renderMarkdown(md);
- body.appendChild(wrap);
- }
-
- function renderMarkdown(md) {
- const lines = md.split(/\r?\n/);
- const out = [];
- let i = 0;
- let inCode = false;
- let codeBuf = [];
- let paraBuf = [];
- let listBuf = []; // array of { indent, html }
- let listType = null; // 'ul' | 'ol'
-
- const flushPara = () => {
- if (paraBuf.length) {
- out.push(`<p>${inlineMd(paraBuf.join(' '))}</p>`);
- paraBuf = [];
- }
- };
- const flushList = () => {
- if (listBuf.length) {
- out.push(buildListHtml(listBuf, listType));
- listBuf = [];
- listType = null;
- }
- };
- const flushAll = () => { flushPara(); flushList(); };
-
- for (; i < lines.length; i++) {
- const line = lines[i];
-
- // Code fence
- const fence = line.match(/^```(\w*)\s*$/);
- if (fence) {
- if (!inCode) { flushAll(); inCode = true; codeBuf = []; }
- else {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- inCode = false;
- }
- continue;
- }
- if (inCode) { codeBuf.push(line); continue; }
-
- if (line.trim() === '') { flushAll(); continue; }
-
- const hr = line.match(/^\s*(?:---+|\*\*\*+)\s*$/);
- if (hr) { flushAll(); out.push('<hr />'); continue; }
-
- const heading = line.match(/^(#{1,4})\s+(.+)$/);
- if (heading) {
- flushAll();
- const lvl = heading[1].length;
- out.push(`<h${lvl}>${inlineMd(heading[2])}</h${lvl}>`);
- continue;
- }
-
- const bullet = line.match(/^(\s*)([-*])\s+(.+)$/);
- const ordered = line.match(/^(\s*)(\d+)\.\s+(.+)$/);
- if (bullet || ordered) {
- flushPara();
- const m = bullet || ordered;
- const indent = Math.floor(m[1].length / 2);
- const t = bullet ? 'ul' : 'ol';
- if (listType && listType !== t) flushList();
- listType = t;
- listBuf.push({ indent, html: inlineMd(m[3]) });
- continue;
- }
-
- paraBuf.push(line);
- }
- flushAll();
- if (inCode && codeBuf.length) {
- out.push(`<pre><code>${escapeHtml(codeBuf.join('\n'))}</code></pre>`);
- }
- return out.join('\n');
- }
-
- function buildListHtml(items, type) {
- // Nest by indent (one level deep is plenty for DESIGN.md).
- let html = `<${type}>`;
- let lastIndent = 0;
- for (const it of items) {
- if (it.indent > lastIndent) html += `<${type}>`;
- else if (it.indent < lastIndent) html += `</${type}>`.repeat(lastIndent - it.indent);
- html += `<li>${it.html}</li>`;
- lastIndent = it.indent;
- }
- html += `</${type}>`.repeat(lastIndent + 1);
- return html;
- }
-
- function inlineMd(text) {
- // Order matters: escape first, then re-inject tags.
- let s = escapeHtml(text);
- // Code spans
- s = s.replace(/`([^`]+)`/g, (_, code) => `<code>${code}</code>`);
- // Links [text](url)
- s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, t, u) => `<a href="${u}" target="_blank" rel="noopener noreferrer">${t}</a>`);
- // Bold
- s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
- // Italic (only single *…*, skip if inside bold already handled)
- s = s.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em>$2</em>');
- return s;
- }
-
- function highlightBold(text) {
- return inlineMd(text);
- }
-
- function escapeHtml(s) {
- return String(s)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
-
- function copyToClipboard(text) {
- if (!text) return;
- try {
- navigator.clipboard.writeText(text);
- showToast('Copied: ' + text);
- } catch { /* ignore */ }
- }
-
- // ---------------------------------------------------------------------------
- // Init
- // ---------------------------------------------------------------------------
-
- function init() {
- try { history.scrollRestoration = 'manual'; } catch {}
- initHighlight();
- initAnnotOverlay();
- initBar();
- initActionPicker();
- initParamsPanel();
- initGlobalBar();
- initDesignPanel();
- document.addEventListener('mousemove', handleMouseMove, true);
- document.addEventListener('click', handleClick, true);
- document.addEventListener('keydown', handleKeyDown, true);
- connectSSE();
-
- // Check for an active session to resume (variant wrapper already in DOM after HMR)
- if (!resumeSession()) {
- console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
- // SvelteKit (and any framework that hydrates after HTML parse) may add
- // the variant wrapper AFTER init runs. Watch for it and retry resume
- // once it appears. Disconnect on first hit.
- const scout = new MutationObserver(() => {
- const wrapper = document.querySelector('[data-impeccable-variants]');
- if (!wrapper) return;
- scout.disconnect();
- if (resumeSession()) {
- console.log('[impeccable] Resumed deferred session ' + currentSessionId + ' (post-hydration).');
- }
- });
- scout.observe(document.body, { childList: true, subtree: true });
- } else {
- console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
- }
- }
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
- } else {
- init();
- }
-})();
@@ -1,75 +0,0 @@
-#!/usr/bin/env node
-/**
- * Canonical durable completion acknowledgement for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function parseArgs(argv) {
- const out = { status: 'complete' };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';
- else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }
- else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function completeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help || !args.id) {
- console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);
- process.exit(args.help ? 0 : 1);
- }
-
- const serverInfo = readServerInfo();
- const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;
- if (serverResult?.ok) {
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const snapshot = store.getSnapshot(args.id, { includeCompleted: true });
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });
- const event = args.status === 'discarded'
- ? { type: 'discarded', id: args.id }
- : args.status === 'agent_error'
- ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }
- : { type: 'complete', id: args.id };
- const snapshot = store.appendEvent(event);
- console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));
-}
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function completeThroughServer(info, args) {
- const type = args.status === 'discarded'
- ? 'discarded'
- : args.status === 'agent_error'
- ? 'error'
- : 'complete';
- try {
- const res = await fetch(`http://localhost:${info.port}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),
- });
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {
- completeCli();
-}
@@ -1,18 +0,0 @@
-export function completionTypeForAcceptResult(eventType, acceptResult) {
- if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';
- if (acceptResult?.handled === true) return 'complete';
- if (acceptResult?.mode === 'error') return 'error';
- return 'agent_done';
-}
-
-export function completionAckForAcceptResult(eventId, completionType, acceptResult) {
- const ack = { ok: true, type: completionType };
- if (acceptResult?.handled === true && acceptResult?.carbonize === true) {
- ack.final = false;
- ack.requiresComplete = true;
- ack.nextCommand = `live-complete.mjs --id ${eventId}`;
- ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';
- }
- return ack;
-}
@@ -1,446 +0,0 @@
-/**
- * CLI helper: insert/remove the live variant mode script tag in the project's
- * main HTML entry point.
- *
- * On first live run, the agent generates `.impeccable/live/config.json`
- * with the project's insertion target (framework-specific). On
- * every subsequent run, this script handles insert/remove deterministically
- * with zero LLM involvement.
- *
- * Usage:
- * node live-inject.mjs --port PORT # Insert the live script tag
- * node live-inject.mjs --remove # Remove the live script tag
- * node live-inject.mjs --check # Check whether live config exists
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { resolveLiveConfigPath } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });
-const MARKER_OPEN_TEXT = 'impeccable-live-start';
-const MARKER_CLOSE_TEXT = 'impeccable-live-end';
-
-/**
- * Hard-excluded directory patterns. These are NEVER user-facing pages and
- * matching them would silently inject tracking scripts into third-party
- * code. The user cannot turn these off via config — they are the floor.
- */
-const HARD_EXCLUDES = [
- '**/node_modules/**',
- '**/.git/**',
-];
-
-export async function injectCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-inject.mjs [options]
-
-Insert or remove the live mode script tag in the project's HTML entry point.
-Reads configuration from .impeccable/live/config.json.
-
-Modes:
- --port PORT Insert script tag pointing at http://localhost:PORT/live.js
- --remove Remove the script tag (if present)
- --check Print whether .impeccable/live/config.json exists and its content
-
-Output (JSON):
- { ok, file, inserted|removed, config? }`);
- process.exit(0);
- }
-
- if (args.includes('--check')) {
- if (!fs.existsSync(CONFIG_PATH)) {
- console.log(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(0);
- }
- let cfg;
- try {
- cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- try {
- validateConfig(cfg);
- } catch (err) {
- console.log(JSON.stringify({ ok: false, error: 'config_invalid', message: err.message, path: CONFIG_PATH }));
- return;
- }
- console.log(JSON.stringify({ ok: true, config: cfg, path: CONFIG_PATH }));
- return;
- }
-
- // Load config
- if (!fs.existsSync(CONFIG_PATH)) {
- console.error(JSON.stringify({ ok: false, error: 'config_missing', path: CONFIG_PATH }));
- process.exit(1);
- }
- const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
- validateConfig(config);
-
- const resolvedFiles = resolveFiles(process.cwd(), config);
-
- if (args.includes('--remove')) {
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const detagged = removeTag(content, config.commentSyntax);
- const updated = revertCspMeta(detagged);
- if (updated === content) return { file: relFile, removed: false, note: 'no tag present' };
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- removed: detagged !== content,
- cspReverted: updated !== detagged,
- };
- });
- console.log(JSON.stringify({ ok: true, results }));
- return;
- }
-
- // Insert mode — need --port
- const portIdx = args.indexOf('--port');
- const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : NaN;
- if (!Number.isFinite(port)) {
- console.error(JSON.stringify({ ok: false, error: 'missing_port' }));
- process.exit(1);
- }
-
- const results = resolvedFiles.map((relFile) => {
- const absFile = path.resolve(process.cwd(), relFile);
- if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };
- const content = fs.readFileSync(absFile, 'utf-8');
- const withoutOld = revertCspMeta(removeTag(content, config.commentSyntax));
- const withTag = insertTag(withoutOld, config, port);
- if (withTag === withoutOld) {
- return { file: relFile, error: 'insertion_point_not_found', anchor: config.insertBefore || config.insertAfter };
- }
- const updated = patchCspMeta(withTag, port);
- fs.writeFileSync(absFile, updated, 'utf-8');
- return {
- file: relFile,
- inserted: true,
- cspPatched: updated !== withTag,
- };
- });
- const anyInserted = results.some((r) => r.inserted);
- console.log(JSON.stringify({ ok: anyInserted, port, results }));
- if (!anyInserted) process.exit(1);
-}
-
-/**
- * Expand config.files (which may contain glob patterns) into a literal list
- * of existing file paths relative to rootDir. Literal entries pass through;
- * glob patterns are expanded via fs.globSync. HARD_EXCLUDES and config.exclude
- * are applied as filters. Duplicates are removed. Order is preserved by
- * first appearance.
- */
-export function resolveFiles(rootDir, config) {
- const patterns = config.files;
- const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
- const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
- const excludeRegexes = allExcludes.map(globToRegex);
-
- const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
- const isGlob = (s) => /[*?[]/.test(s);
-
- const seen = new Set();
- const out = [];
- for (const pat of patterns) {
- if (!isGlob(pat)) {
- // Literal path — include even if it doesn't exist yet; the caller
- // reports file_not_found per-entry. Exclude list doesn't apply to
- // explicit literal entries (user named it on purpose).
- if (!seen.has(pat)) {
- seen.add(pat);
- out.push(pat);
- }
- continue;
- }
- let matches;
- try {
- matches = fs.globSync(pat, { cwd: rootDir, withFileTypes: true });
- } catch {
- continue;
- }
- for (const ent of matches) {
- if (!ent.isFile || !ent.isFile()) continue;
- const abs = path.join(ent.parentPath || ent.path || rootDir, ent.name);
- const rel = path.relative(rootDir, abs).split(path.sep).join('/');
- if (isExcluded(rel)) continue;
- if (seen.has(rel)) continue;
- seen.add(rel);
- out.push(rel);
- }
- }
- return out;
-}
-
-/**
- * Convert a glob pattern to a RegExp. Supports:
- * ** → any number of path segments (including zero)
- * * → any chars except `/`
- * ? → any single char except `/`
- * Paths are normalized to forward slashes before matching.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- // ** — any number of segments, including zero. Handle the common
- // **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
- if (pattern[i + 2] === '/') {
- re += '(?:.*/)?';
- i += 3;
- } else {
- re += '.*';
- i += 2;
- }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Core operations
-// ---------------------------------------------------------------------------
-
-function validateConfig(cfg) {
- if (!cfg || typeof cfg !== 'object') throw new Error('config.json must be an object');
- if (!Array.isArray(cfg.files) || cfg.files.length === 0) {
- throw new Error('config.files (non-empty string array) required');
- }
- if (!cfg.files.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.files must contain only non-empty strings');
- }
- if (cfg.exclude !== undefined) {
- if (!Array.isArray(cfg.exclude)) {
- throw new Error('config.exclude, if present, must be a string array');
- }
- if (!cfg.exclude.every((f) => typeof f === 'string' && f.length > 0)) {
- throw new Error('config.exclude must contain only non-empty strings');
- }
- }
- if (typeof cfg.insertBefore !== 'string' && typeof cfg.insertAfter !== 'string') {
- throw new Error('config.insertBefore or config.insertAfter (string) required');
- }
- if (cfg.commentSyntax !== 'html' && cfg.commentSyntax !== 'jsx') {
- throw new Error("config.commentSyntax must be 'html' or 'jsx'");
- }
- if (cfg.cspChecked !== undefined && typeof cfg.cspChecked !== 'boolean') {
- throw new Error("config.cspChecked, if present, must be a boolean");
- }
-}
-
-function commentOpen(syntax) { return syntax === 'jsx' ? '{/*' : '<!--'; }
-function commentClose(syntax) { return syntax === 'jsx' ? '*/}' : '-->'; }
-
-function buildTagBlock(syntax, port) {
- const open = commentOpen(syntax);
- const close = commentClose(syntax);
- return (
- open + ' ' + MARKER_OPEN_TEXT + ' ' + close + '\n' +
- '<script src="http://localhost:' + port + '/live.js"></script>\n' +
- open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n'
- );
-}
-
-function insertTag(content, config, port) {
- const block = buildTagBlock(config.commentSyntax, port);
- // insertBefore: match the LAST occurrence. Anchors like `</body>` naturally
- // belong at the end, and the same literal can appear earlier in code blocks
- // within rendered documentation pages.
- if (config.insertBefore) {
- const idx = content.lastIndexOf(config.insertBefore);
- if (idx === -1) return content;
- return content.slice(0, idx) + block + content.slice(idx);
- }
- // insertAfter: match the FIRST occurrence — typical anchors like `<head>` or
- // `<body>` open near the top of the document.
- const idx = content.indexOf(config.insertAfter);
- if (idx === -1) return content;
- const after = idx + config.insertAfter.length;
- // Preserve a single trailing newline if the anchor didn't end with one
- const prefix = content[after] === '\n' ? content.slice(0, after + 1) : content.slice(0, after) + '\n';
- return prefix + block + content.slice(prefix.length);
-}
-
-/**
- * Remove the live script block. Matches either HTML or JSX comment markers
- * regardless of config (so stale tags from a wrong config can still be cleaned).
- *
- * Indent-preserving: captures any whitespace immediately preceding the opener
- * marker and re-emits it in place of the removed block. `insertTag` inserted
- * the block *after* the original line's indent and *before* the anchor (e.g.
- * `</body>`), which moved the indent onto the opener line and left the anchor
- * unindented. Replacing the whole block (plus its trailing newline) with just
- * the captured indent hands the indent back to the anchor that follows.
- */
-function removeTag(content, _syntax) {
- const patterns = [
- /([ \t]*)<!--\s*impeccable-live-start\s*-->[\s\S]*?<!--\s*impeccable-live-end\s*-->[ \t]*\n/,
- /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}[ \t]*\n/,
- ];
- for (const pat of patterns) {
- const next = content.replace(pat, '$1');
- if (next !== content) return next;
- }
- return content;
-}
-
-// ---------------------------------------------------------------------------
-// Content-Security-Policy meta-tag patcher
-//
-// When the user's HTML carries `<meta http-equiv="Content-Security-Policy">`,
-// the cross-origin load of /live.js (and the SSE/POST connection back to
-// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
-//
-// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
-// and stash the original `content` value in a `data-impeccable-csp-original`
-// attribute (base64) so revert is exact.
-//
-// On remove: detect the marker attribute, decode it, restore the original
-// content value verbatim, drop the marker.
-//
-// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
-// shared helpers) is NOT patched here — those need framework-specific config
-// edits and are handled via the existing detect-csp.mjs reference output.
-// Only the in-source meta-tag form gets the auto-patch.
-// ---------------------------------------------------------------------------
-
-const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
-
-function findCspMetaTags(content) {
- const out = [];
- const tagRe = /<meta\s+([^>]*?)\/?>/gis;
- let m;
- while ((m = tagRe.exec(content)) !== null) {
- const attrs = m[1];
- if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
- out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
- }
- return out;
-}
-
-function getAttr(attrs, name) {
- const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
- const m = attrs.match(re);
- return m ? { quote: m[1], value: m[2], full: m[0] } : null;
-}
-
-function appendOriginToDirective(csp, directive, origin) {
- const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
- const m = csp.match(re);
- if (m) {
- const tokens = m[4].trim().split(/\s+/);
- if (tokens.includes(origin)) return csp;
- return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
- }
- // Directive missing — add it. Use 'self' + origin so we don't inadvertently
- // narrow the policy compared to the default-src fallback (most users with
- // an explicit CSP have 'self' there).
- return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
-}
-
-export function patchCspMeta(content, port) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
- const origin = `http://localhost:${port}`;
-
- // Walk last-to-first so prior splices don't invalidate later indices.
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const attrs = tag.attrs;
- if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
- const contentAttr = getAttr(attrs, 'content');
- if (!contentAttr) continue;
-
- const original = contentAttr.value;
- let patched = original;
- patched = appendOriginToDirective(patched, 'script-src', origin);
- patched = appendOriginToDirective(patched, 'connect-src', origin);
- // The shader overlay during 'generating' creates a screenshot via
- // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
- // those. Add `blob:` so the overlay doesn't throw a CSP violation.
- patched = appendOriginToDirective(patched, 'img-src', 'blob:');
- if (patched === original) continue;
-
- const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
- const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
- // The tagRe captures any whitespace between the last attribute and the
- // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
- // a replace would land it BEFORE that trailing space, leaving a double
- // space inside attrs and clobbering the space before `/>`. Split off
- // the trailing whitespace, splice the marker into the attribute body,
- // and re-append the original trailing whitespace so a self-closing
- // `<meta … />` round-trips byte-for-byte.
- const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
- const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
- const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
- const newTag = tag.full.replace(attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-export function revertCspMeta(content) {
- const tags = findCspMetaTags(content);
- if (tags.length === 0) return content;
-
- let result = content;
- for (let i = tags.length - 1; i >= 0; i--) {
- const tag = tags[i];
- const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
- if (!origAttr) continue;
- const contentAttr = getAttr(tag.attrs, 'content');
- if (!contentAttr) continue;
-
- let originalValue;
- try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
- catch { continue; }
-
- const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
- let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
- // Drop the marker attribute and any single space immediately preceding it.
- newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
- const newTag = tag.full.replace(tag.attrs, newAttrs);
-
- result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
- }
- return result;
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
- injectCli();
-}
-
-export { insertTag, removeTag, validateConfig, buildTagBlock };
-// patchCspMeta + revertCspMeta are exported above where they're defined.
@@ -1,200 +0,0 @@
-/**
- * CLI client for the live variant mode poll/reply protocol.
- *
- * Usage:
- * npx impeccable poll # Block until browser event, print JSON
- * npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
- * npx impeccable poll --reply <id> done # Reply "done" to event <id>
- * npx impeccable poll --reply <id> error "msg" # Reply with error
- */
-
-import { execFileSync } from 'node:child_process';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-// Node's built-in fetch (undici under the hood) enforces a 300s headers
-// timeout that can't be lowered per-request. We cap each request below
-// that ceiling and loop in `pollOnce` to synthesize a long poll without
-// depending on the standalone undici package.
-const PER_REQUEST_TIMEOUT_MS = 270_000;
-
-function readServerInfo() {
- const record = readLiveServerInfo(process.cwd());
- if (!record) {
- console.error('No running live server found. Start one with: npx impeccable live');
- process.exit(1);
- }
- return record.info;
-}
-
-export function buildPollReplyPayload(token, { id, type, message, file, data }) {
- return { token, id, type, message, file, data };
-}
-
-async function postReply(base, token, reply) {
- const res = await fetch(`${base}/poll`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(buildPollReplyPayload(token, reply)),
- });
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error || res.statusText);
- }
-}
-
-export async function pollCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable poll [options]
-
-Wait for a browser event from the live variant server, or reply to one.
-
-Modes:
- poll Block until a browser event arrives, print JSON
- poll --reply <id> done Reply "done" to event <id>
- poll --reply <id> error "msg" Reply with an error message
-
-Options:
- --timeout=MS Long-poll timeout in ms (default: 600000). Use the default unless the user asked to pause live; never use a short timeout to end the chat turn
- --help Show this help message`);
- process.exit(0);
- }
-
- const info = readServerInfo();
- const base = `http://localhost:${info.port}`;
-
- // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
- const replyIdx = args.indexOf('--reply');
- if (replyIdx !== -1) {
- const id = args[replyIdx + 1];
- const status = args[replyIdx + 2] || 'done';
- const fileIdx = args.indexOf('--file');
- const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
- // Message is any remaining positional arg that isn't a flag
- const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
-
- if (!id) {
- console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
- process.exit(1);
- }
-
- try {
- await postReply(base, info.token, { id, type: status, message, file: filePath });
-
- // Success — silent exit (agent doesn't need output for replies)
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Reply failed:', err.message);
- }
- process.exit(1);
- }
- return;
- }
-
- // Poll mode: block until browser event. Default 10 min. Node's built-in
- // fetch enforces a 300s headers timeout, so we loop in slices under that
- // ceiling and keep re-polling until we get a real event or the user's
- // total timeout runs out.
- const timeoutArg = args.find(a => a.startsWith('--timeout='));
- const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600000;
-
- const deadline = Date.now() + totalTimeout;
- let event;
- try {
- while (true) {
- const remaining = deadline - Date.now();
- if (remaining <= 0) {
- event = { type: 'timeout' };
- break;
- }
- const slice = Math.min(remaining, PER_REQUEST_TIMEOUT_MS);
- const res = await fetch(`${base}/poll?token=${info.token}&timeout=${slice}`);
-
- if (res.status === 401) {
- console.error('Authentication failed. The server token may have changed.');
- console.error('Try restarting: npx impeccable live stop && npx impeccable live');
- process.exit(1);
- }
-
- if (!res.ok) {
- console.error(`Poll failed: ${res.status} ${res.statusText}`);
- process.exit(1);
- }
-
- const next = await res.json();
- // Server-side timeout means no browser event arrived in this slice.
- // Loop and re-poll until we get a real event or we hit the user's
- // total deadline.
- if (next?.type === 'timeout' && Date.now() < deadline) continue;
- event = next;
- break;
- }
-
- // Auto-handle accept/discard via deterministic script
- if (event.type === 'accept' || event.type === 'discard') {
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const acceptScript = path.join(__dirname, 'live-accept.mjs');
- const scriptArgs = event.type === 'discard'
- ? ['--id', event.id, '--discard']
- : ['--id', event.id, '--variant', event.variantId];
- if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
- scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
- }
- try {
- const out = execFileSync(
- 'node',
- [acceptScript, ...scriptArgs],
- { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 }
- );
- event._acceptResult = JSON.parse(out.trim());
- } catch (err) {
- event._acceptResult = { handled: false, mode: 'error', error: err.message };
- }
-
- const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
- try {
- await postReply(base, info.token, {
- id: event.id,
- type: completionType,
- message: event._acceptResult?.error,
- file: event._acceptResult?.file,
- data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
- });
- } catch (err) {
- event._completionAck = { ok: false, error: err.message };
- }
- if (!event._completionAck) {
- event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
- }
- }
-
- // Second signal path: stderr banner in case the agent parses stdout
- // JSON but skips nested fields. One line is enough — the full checklist
- // is in reference/live.md.
- if (event._acceptResult?.carbonize === true) {
- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
- }
-
- // Print the event as JSON — the agent reads this from stdout
- console.log(JSON.stringify(event));
- } catch (err) {
- if (err.cause?.code === 'ECONNREFUSED') {
- console.error('Live server not running. Start one with: npx impeccable live');
- } else {
- console.error('Poll failed:', err.message);
- }
- process.exit(1);
- }
-}
-
-// Auto-execute when run directly
-const _running = process.argv[1];
-if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
- pollCli();
-}
@@ -1,48 +0,0 @@
-#!/usr/bin/env node
-/**
- * Recover the next agent action from the durable live-session journal.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-
-function parseArgs(argv) {
- const out = { id: null };
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg === '--id') out.id = argv[++i];
- else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
- else if (arg === '--help' || arg === '-h') out.help = true;
- }
- return out;
-}
-
-export async function resumeCli() {
- const args = parseArgs(process.argv.slice(2));
- if (args.help) {
- console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);
- return;
- }
-
- const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });
- const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;
- if (!snapshot) {
- console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));
- return;
- }
-
- const pending = snapshot.pendingEvent || null;
- const nextAction = pending
- ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`
- : snapshot.phase === 'carbonize_required'
- ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`
- : snapshot.phase === 'accept_requested'
- ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`
- : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;
-
- console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {
- resumeCli();
-}
@@ -1,838 +0,0 @@
-#!/usr/bin/env node
-/**
- * Live variant mode server (self-contained, zero dependencies).
- *
- * Serves the browser script (/live.js), the detection overlay (/detect.js),
- * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
- * browser→server events. Agent communicates via HTTP long-poll (/poll).
- *
- * Usage:
- * node <scripts_path>/live-server.mjs # start
- * node <scripts_path>/live-server.mjs stop # stop + remove injected live.js tag
- * node <scripts_path>/live-server.mjs stop --keep-inject # stop only
- * node <scripts_path>/live-server.mjs --help
- */
-
-import http from 'node:http';
-import { randomUUID } from 'node:crypto';
-import { spawn, execFileSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import net from 'node:net';
-import { fileURLToPath } from 'node:url';
-import { parseDesignMd } from './design-parser.mjs';
-import { resolveContextDir } from './load-context.mjs';
-import { createLiveSessionStore } from './live-session-store.mjs';
-import {
- getDesignSidecarPath,
- getLiveAnnotationsDir,
- readLiveServerInfo,
- removeLiveServerInfo,
- resolveDesignSidecarPath,
- writeLiveServerInfo,
-} from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated
-// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
-// DESIGN.json fallback for existing projects.
-const CONTEXT_DIR = resolveContextDir(process.cwd());
-const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anyway
-const SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s
-
-// ---------------------------------------------------------------------------
-// Port detection
-// ---------------------------------------------------------------------------
-
-async function findOpenPort(start = 8400) {
- return new Promise((resolve) => {
- const srv = net.createServer();
- srv.listen(start, '127.0.0.1', () => {
- const port = srv.address().port;
- srv.close(() => resolve(port));
- });
- srv.on('error', () => resolve(findOpenPort(start + 1)));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Session state
-// ---------------------------------------------------------------------------
-
-const state = {
- token: null,
- port: null,
- sseClients: new Set(), // SSE response objects (server→browser push)
- pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
- pendingPolls: [], // agent poll callbacks waiting for browser events
- exitTimer: null,
- sessionDir: null, // per-session tmp dir for annotation screenshots
- sessionStore: null,
- leaseTimer: null,
-};
-
-// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;
-// cap at 10 MB to guard against runaway writes from a misbehaving client.
-const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
-
-function enqueueEvent(event) {
- if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;
- state.pendingEvents.push({ event, leaseUntil: 0 });
- flushPendingPolls();
-}
-
-function restorePendingEventsFromStore() {
- if (!state.sessionStore) return;
- for (const snapshot of state.sessionStore.listActiveSessions()) {
- if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);
- }
-}
-
-function findAvailablePendingEvent(now = Date.now()) {
- return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);
-}
-
-function leaseEvent(entry, leaseMs) {
- if (!entry.event?.id) {
- const idx = state.pendingEvents.indexOf(entry);
- if (idx !== -1) state.pendingEvents.splice(idx, 1);
- return entry.event;
- }
- entry.leaseUntil = Date.now() + leaseMs;
- return entry.event;
-}
-
-function acknowledgePendingEvent(id) {
- if (!id) return false;
- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);
- if (idx === -1) return false;
- state.pendingEvents.splice(idx, 1);
- scheduleLeaseFlush();
- return true;
-}
-
-function scheduleLeaseFlush() {
- if (state.leaseTimer) {
- clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- }
- if (state.pendingPolls.length === 0) return;
- const now = Date.now();
- const nextLeaseUntil = state.pendingEvents
- .map((entry) => entry.leaseUntil || 0)
- .filter((leaseUntil) => leaseUntil > now)
- .sort((a, b) => a - b)[0];
- if (!nextLeaseUntil) return;
- state.leaseTimer = setTimeout(() => {
- state.leaseTimer = null;
- flushPendingPolls();
- }, Math.max(0, nextLeaseUntil - now));
-}
-
-function flushPendingPolls() {
- while (state.pendingPolls.length > 0) {
- const entry = findAvailablePendingEvent();
- if (!entry) {
- scheduleLeaseFlush();
- return;
- }
- const poll = state.pendingPolls.shift();
- poll.resolve(leaseEvent(entry, poll.leaseMs));
- }
- scheduleLeaseFlush();
-}
-
-/** Push a message to all connected SSE clients. */
-function broadcast(msg) {
- const data = 'data: ' + JSON.stringify(msg) + '\n\n';
- for (const res of state.sseClients) {
- try { res.write(data); } catch { /* client gone */ }
- }
-}
-
-// ---------------------------------------------------------------------------
-// Load scripts
-// ---------------------------------------------------------------------------
-
-function loadBrowserScripts() {
- // Detection script: prefer the skill-bundled detector, then fall back to
- // source/npm package locations for local development and older installs.
- // This one IS cached — detect.js rarely changes during a session.
- const detectPaths = [
- path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- path.join(process.cwd(), 'node_modules', 'impeccable', 'cli', 'engine', 'detect-antipatterns-browser.js'),
- ];
- let detectScript = '';
- for (const p of detectPaths) {
- try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
- }
-
- // live-browser.js: DO NOT cache. Return the path so the /live.js handler
- // can re-read on every request. Editing the browser script during iteration
- // should land on the next tab reload, not require a server restart.
- const sessionPath = path.join(__dirname, 'live-browser-session.js');
- const livePath = path.join(__dirname, 'live-browser.js');
- for (const p of [sessionPath, livePath]) {
- if (!fs.existsSync(p)) {
- process.stderr.write('Error: live browser script not found at ' + p + '\n');
- process.exit(1);
- }
- }
-
- return { detectScript, sessionPath, livePath };
-}
-
-function hasProjectContext() {
- // PRODUCT.md carries brand voice / anti-references — that's what determines
- // whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
- // concern, surfaced by the design panel's own empty state. Legacy
- // .impeccable.md is auto-migrated to PRODUCT.md by load-context.mjs.
- try {
- fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
- return true;
- } catch { return false; }
-}
-
-function statOrNull(filePath) {
- try { return fs.statSync(filePath); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// Validation (inline — no external import needed for self-contained script)
-// ---------------------------------------------------------------------------
-
-const VISUAL_ACTIONS = [
- 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
- 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
-];
-
-// Browser generates ids via crypto.randomUUID().slice(0, 8) (8 hex chars)
-// and variantIds via String(small integer). Restrict to those shapes so
-// any value that reaches a downstream child_process or DOM selector is
-// inert by construction.
-const ID_PATTERN = /^[0-9a-f]{8}$/;
-const VARIANT_ID_PATTERN = /^[0-9]{1,3}$/;
-
-function isValidId(v) { return typeof v === 'string' && ID_PATTERN.test(v); }
-function isValidVariantId(v) { return typeof v === 'string' && VARIANT_ID_PATTERN.test(v); }
-
-function validateEvent(msg) {
- if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
- switch (msg.type) {
- case 'generate':
- if (!isValidId(msg.id)) return 'generate: missing or malformed id';
- if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
- if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
- if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
- // Optional annotation fields (all-or-nothing: if any present, all must be well-formed).
- if (msg.screenshotPath !== undefined && typeof msg.screenshotPath !== 'string') return 'generate: screenshotPath must be string';
- if (msg.comments !== undefined && !Array.isArray(msg.comments)) return 'generate: comments must be array';
- if (msg.strokes !== undefined && !Array.isArray(msg.strokes)) return 'generate: strokes must be array';
- return null;
- case 'accept':
- if (!isValidId(msg.id)) return 'accept: missing or malformed id';
- if (!isValidVariantId(msg.variantId)) return 'accept: missing or malformed variantId';
- if (msg.paramValues !== undefined) {
- if (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues)) {
- return 'accept: paramValues must be an object';
- }
- }
- return null;
- case 'discard':
- return isValidId(msg.id) ? null : 'discard: missing or malformed id';
- case 'checkpoint':
- if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';
- if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';
- if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {
- return 'checkpoint: paramValues must be an object';
- }
- return null;
- case 'exit':
- return null;
- case 'prefetch':
- if (!msg.pageUrl || typeof msg.pageUrl !== 'string') return 'prefetch: missing pageUrl';
- return null;
- default:
- return 'Unknown event type: ' + msg.type;
- }
-}
-
-// ---------------------------------------------------------------------------
-// HTTP request handler
-// ---------------------------------------------------------------------------
-
-function createRequestHandler({ detectScript, sessionPath, livePath }) {
- return (req, res) => {
- const url = new URL(req.url, `http://localhost:${state.port}`);
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
- if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
-
- const p = url.pathname;
-
- // --- Scripts ---
- if (p === '/live.js') {
- // Re-read from disk each request so edits to live-browser.js land on
- // the next tab reload. No-store headers prevent browser caching across
- // sessions — during iteration, a cached old script silently breaks
- // every subsequent session.
- let sessionScript;
- let liveScript;
- try {
- sessionScript = fs.readFileSync(sessionPath, 'utf-8');
- liveScript = fs.readFileSync(livePath, 'utf-8');
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'text/plain' });
- res.end('Error reading live browser scripts: ' + err.message);
- return;
- }
- const body =
- `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
- `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
- sessionScript + '\n' +
- liveScript;
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
- 'Pragma': 'no-cache',
- });
- res.end(body);
- return;
- }
- if (p === '/detect.js' || p === '/') {
- if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
- res.writeHead(200, { 'Content-Type': 'application/javascript' });
- res.end(detectScript);
- return;
- }
-
- // --- Vendored modern-screenshot (UMD build) ---
- // Lazy-loaded by live.js when the user clicks Go; exposes
- // window.modernScreenshot.domToBlob(...) for capture.
- if (p === '/modern-screenshot.js') {
- const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
- try {
- res.writeHead(200, {
- 'Content-Type': 'application/javascript',
- 'Cache-Control': 'public, max-age=31536000, immutable',
- });
- res.end(fs.readFileSync(vendorPath));
- } catch {
- res.writeHead(404); res.end('Vendor script not found');
- }
- return;
- }
-
- // --- Annotation upload (browser → server, raw PNG body) ---
- // Client generates the eventId, POSTs the PNG, then POSTs the generate
- // event with screenshotPath already set. Keeps bytes out of the SSE/poll
- // bridge and preserves the "one shot from the user's POV" UX.
- if (p === '/annotation' && req.method === 'POST') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const eventId = url.searchParams.get('eventId');
- if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid eventId' }));
- return;
- }
- if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
- res.writeHead(415, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
- return;
- }
- if (!state.sessionDir) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Session dir unavailable' }));
- return;
- }
- const chunks = [];
- let total = 0;
- let aborted = false;
- req.on('data', (c) => {
- if (aborted) return;
- total += c.length;
- if (total > MAX_ANNOTATION_BYTES) {
- aborted = true;
- res.writeHead(413, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Payload too large' }));
- req.destroy();
- return;
- }
- chunks.push(c);
- });
- req.on('end', () => {
- if (aborted) return;
- const absPath = path.join(state.sessionDir, eventId + '.png');
- try {
- fs.writeFileSync(absPath, Buffer.concat(chunks));
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Write failed: ' + err.message }));
- return;
- }
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true, path: absPath }));
- });
- req.on('error', () => {
- if (!aborted) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Upload failed' }));
- }
- });
- return;
- }
-
- // --- Health ---
- if (p === '/status') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
- const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok',
- port: state.port,
- connectedClients: state.sseClients.size,
- pendingEvents: state.pendingEvents.map((entry) => ({
- id: entry.event?.id,
- type: entry.event?.type,
- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),
- leaseUntil: entry.leaseUntil || null,
- })),
- activeSessions: sessions,
- }));
- return;
- }
-
- if (p === '/health') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok', port: state.port, mode: 'variant',
- hasProjectContext: hasProjectContext(),
- connectedClients: state.sseClients.size,
- }));
- return;
- }
-
- // --- Design system (unified v2 response) + raw ---
- // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json
- // sidecar when present. Panel merges them:
- // { present, parsed, sidecar, hasMd, hasSidecar,
- // mdNewerThanJson, parseError?, sidecarError? }
- // - parsed: output of parseDesignMd (frontmatter
- // + six canonical sections) when DESIGN.md exists.
- // - sidecar: .impeccable/design.json contents when present.
- // Expected shape: schemaVersion 2, carrying
- // extensions + components + narrative.
- // /design-system/raw returns DESIGN.md markdown verbatim
- if (p === '/design-system.json' || p === '/design-system/raw') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
-
- const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
- const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
- const mdStat = statOrNull(mdPath);
- const jsonStat = statOrNull(jsonPath);
-
- if (p === '/design-system/raw') {
- if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
- res.end(fs.readFileSync(mdPath, 'utf-8'));
- return;
- }
-
- if (!mdStat && !jsonStat) {
- res.writeHead(404, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ present: false }));
- return;
- }
-
- const response = {
- present: true,
- hasMd: !!mdStat,
- hasSidecar: !!jsonStat,
- mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
- };
-
- if (mdStat) {
- try {
- response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
- } catch (err) {
- response.parseError = err.message;
- }
- }
-
- if (jsonStat) {
- try {
- response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
- } catch (err) {
- response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;
- }
- }
-
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(response));
- return;
- }
-
- // --- Source file (no-HMR fallback) ---
- if (p === '/source') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- const filePath = url.searchParams.get('path');
- if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
- const absPath = path.resolve(process.cwd(), filePath);
- if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
- let content;
- try { content = fs.readFileSync(absPath, 'utf-8'); }
- catch { res.writeHead(404); res.end('File not found'); return; }
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
- res.end(content);
- return;
- }
-
- // --- SSE: server→browser push (replaces WebSocket) ---
- if (p === '/events' && req.method === 'GET') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- 'Connection': 'keep-alive',
- });
- res.write('data: ' + JSON.stringify({
- type: 'connected',
- hasProjectContext: hasProjectContext(),
- }) + '\n\n');
-
- state.sseClients.add(res);
- clearTimeout(state.exitTimer);
-
- // Keepalive: SSE comment every 30s prevents silent connection drops.
- const heartbeat = setInterval(() => {
- try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
- }, SSE_HEARTBEAT_INTERVAL);
-
- req.on('close', () => {
- clearInterval(heartbeat);
- state.sseClients.delete(res);
- if (state.sseClients.size === 0) {
- clearTimeout(state.exitTimer);
- state.exitTimer = setTimeout(() => {
- if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
- }, 8000);
- }
- });
- return;
- }
-
- // --- Browser→server events (replaces WebSocket messages) ---
- if (p === '/events' && req.method === 'POST') {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const error = validateEvent(msg);
- if (error) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error }));
- return;
- }
- if (state.sessionStore && msg.id) {
- try {
- state.sessionStore.appendEvent(msg);
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
- return;
- }
- }
- if (msg.type !== 'checkpoint') enqueueEvent(msg);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
- return;
- }
-
- // --- Stop ---
- if (p === '/stop') {
- const token = url.searchParams.get('token');
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.end('stopping');
- shutdown();
- return;
- }
-
- // --- Agent poll ---
- if (p === '/poll' && req.method === 'GET') {
- handlePollGet(req, res, url);
- return;
- }
- if (p === '/poll' && req.method === 'POST') {
- handlePollPost(req, res);
- return;
- }
-
- res.writeHead(404); res.end('Not found');
- };
-}
-
-// ---------------------------------------------------------------------------
-// Agent poll endpoints (unchanged from WS version)
-// ---------------------------------------------------------------------------
-
-function handlePollGet(req, res, url) {
- const token = url.searchParams.get('token');
- if (token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
- const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
- const available = findAvailablePendingEvent();
- if (available) {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(leaseEvent(available, leaseMs)));
- return;
- }
- const poll = { resolve, leaseMs };
- const timer = setTimeout(() => {
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ type: 'timeout' }));
- }, timeout);
- function resolve(event) {
- clearTimeout(timer);
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(event));
- }
- state.pendingPolls.push(poll);
- scheduleLeaseFlush();
- req.on('close', () => {
- clearTimeout(timer);
- const idx = state.pendingPolls.indexOf(poll);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- });
-}
-
-function handlePollPost(req, res) {
- let body = '';
- req.on('data', (c) => { body += c; });
- req.on('end', () => {
- let msg;
- try { msg = JSON.parse(body); } catch {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Invalid JSON' }));
- return;
- }
- if (msg.token !== state.token) {
- res.writeHead(401, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Unauthorized' }));
- return;
- }
- acknowledgePendingEvent(msg.id);
- if (state.sessionStore && msg.id) {
- try {
- const eventType = msg.type === 'discard' || msg.type === 'discarded'
- ? 'discarded'
- : msg.type === 'complete'
- ? 'complete'
- : msg.type === 'error'
- ? 'agent_error'
- : 'agent_done';
- state.sessionStore.appendEvent({
- type: eventType,
- id: msg.id,
- file: msg.file,
- message: msg.message,
- carbonize: msg.data?.carbonize === true,
- });
- } catch { /* keep reply path best-effort; browser still needs SSE */ }
- }
- flushPendingPolls();
- // Forward the reply to the browser via SSE
- broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
-}
-
-// ---------------------------------------------------------------------------
-// Lifecycle
-// ---------------------------------------------------------------------------
-
-let httpServer = null;
-
-function shutdown() {
- removeLiveServerInfo(process.cwd());
- if (state.leaseTimer) clearTimeout(state.leaseTimer);
- state.leaseTimer = null;
- if (state.sessionDir) {
- try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}
- }
- for (const res of state.sseClients) { try { res.end(); } catch {} }
- state.sseClients.clear();
- for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });
- state.pendingPolls.length = 0;
- if (httpServer) httpServer.close();
- process.exit(0);
-}
-
-// ---------------------------------------------------------------------------
-// Main
-// ---------------------------------------------------------------------------
-
-const args = process.argv.slice(2);
-
-if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live-server.mjs [options]
-
-Start the live variant mode server (zero dependencies).
-
-Commands:
- (default) Start the server (foreground)
- stop Stop the server and remove the injected live.js script tag
- stop --keep-inject Stop the server only (leave the script tag in the HTML entry)
-
-Options:
- --background Start detached, print connection JSON to stdout, then exit
- --port=PORT Use a specific port (default: auto-detect starting at 8400)
- --keep-inject Only with stop: skip live-inject.mjs --remove
- --help Show this help
-
-Endpoints:
- /live.js Browser script (element picker + variant cycling)
- /detect.js Detection overlay (backwards compatible)
- /modern-screenshot.js Vendored modern-screenshot UMD build (lazy-loaded by live.js)
- /annotation POST raw image/png to stage a variant screenshot
- /events SSE stream (server→browser) + POST (browser→server)
- /poll Long-poll for agent CLI
- /source Raw source file reader (no-HMR fallback)
- /status Durable recovery status (token-protected)
- /health Health check`);
- process.exit(0);
-}
-
-if (args.includes('stop')) {
- const keepInject = args.includes('--keep-inject');
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);
- if (res.ok) console.log(`Stopped live server on port ${info.port}.`);
- } catch {
- console.log('No running live server found.');
- }
- if (!keepInject) {
- const injectPath = path.join(__dirname, 'live-inject.mjs');
- try {
- const out = execFileSync(process.execPath, [injectPath, '--remove'], {
- encoding: 'utf-8',
- cwd: process.cwd(),
- });
- const line = out.trim().split('\n').filter(Boolean).pop();
- if (line) {
- try {
- const j = JSON.parse(line);
- if (j.removed === true) {
- console.log(`Removed live script tag from ${j.file}.`);
- }
- } catch {
- /* ignore non-JSON lines */
- }
- }
- } catch (err) {
- const detail = err.stderr?.toString?.().trim?.()
- || err.stdout?.toString?.().trim?.()
- || err.message
- || String(err);
- console.warn(`Note: could not remove live script tag (${detail.split('\n')[0]})`);
- }
- }
- process.exit(0);
-}
-
-// --background: spawn a detached child server, wait for it to be ready,
-// print the connection JSON, then exit. This keeps the startup command
-// simple (no shell backgrounding or chained commands).
-if (args.includes('--background')) {
- const childArgs = args.filter(a => a !== '--background');
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), ...childArgs], {
- detached: true,
- stdio: 'ignore',
- cwd: process.cwd(),
- });
- child.unref();
-
- // Poll for the PID file (the child writes it once the HTTP server is listening).
- const deadline = Date.now() + 10_000;
- while (Date.now() < deadline) {
- try {
- const { info } = readLiveServerInfo(process.cwd()) || {};
- if (info.pid !== process.pid) {
- // Output JSON so the agent can read port + token from stdout.
- console.log(JSON.stringify(info));
- process.exit(0);
- }
- } catch { /* not ready yet */ }
- await new Promise(r => setTimeout(r, 200));
- }
- console.error('Timed out waiting for live server to start.');
- process.exit(1);
-}
-
-// Check for existing session
-const existingRecord = readLiveServerInfo(process.cwd());
-if (existingRecord?.info) {
- const existing = existingRecord.info;
- try {
- process.kill(existing.pid, 0);
- console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
- console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');
- process.exit(1);
- } catch {
- try { fs.unlinkSync(existingRecord.path); } catch {}
- }
-}
-
-state.token = randomUUID();
-state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });
-restorePendingEventsFromStore();
-const portArg = args.find(a => a.startsWith('--port='));
-state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
-// Annotation screenshots live in the project root so the agent's Read tool
-// doesn't trip a per-file permission prompt. Sessioned by token so concurrent
-// projects (or quick restarts) don't collide.
-const annotRoot = getLiveAnnotationsDir(process.cwd());
-fs.mkdirSync(annotRoot, { recursive: true });
-state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));
-
-const { detectScript, sessionPath, livePath } = loadBrowserScripts();
-httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));
-
-httpServer.listen(state.port, '127.0.0.1', () => {
- writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });
- const url = `http://localhost:${state.port}`;
- console.log(`\nImpeccable live server running on ${url}`);
- console.log(`Token: ${state.token}\n`);
- console.log(`Inject: <script src="${url}/live.js"><\/script>`);
- console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
-});
-
-process.on('SIGINT', shutdown);
-process.on('SIGTERM', shutdown);
@@ -1,254 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';
-
-const COMPLETED_PHASES = new Set(['completed', 'discarded']);
-
-export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {
- const rootDir = getLiveSessionsDir(cwd);
- const legacyRootDir = getLegacyLiveSessionsDir(cwd);
- fs.mkdirSync(rootDir, { recursive: true });
- const snapshotCache = new Map();
-
- function loadCachedOrRebuild(id) {
- const cached = snapshotCache.get(id);
- if (cached) return cached;
- const journalPath = getReadableJournalPath(id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- return rebuilt;
- }
-
- function getReadableJournalPath(id) {
- const primary = getJournalPath(rootDir, id);
- if (fs.existsSync(primary)) return primary;
- const legacy = getJournalPath(legacyRootDir, id);
- if (fs.existsSync(legacy)) return legacy;
- return primary;
- }
-
- return {
- rootDir,
- legacyRootDir,
- appendEvent(event) {
- const normalized = normalizeEvent(event, sessionId);
- const journalPath = getJournalPath(rootDir, normalized.id);
- const snapshotPath = getSnapshotPath(rootDir, normalized.id);
- const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);
- if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {
- fs.copyFileSync(legacyJournalPath, journalPath);
- }
- const prior = loadCachedOrRebuild(normalized.id);
- const seq = prior.nextSeq;
- const entry = {
- seq,
- id: normalized.id,
- type: normalized.type,
- ts: new Date().toISOString(),
- event: normalized,
- };
- fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');
- const next = applyEvent(prior.snapshot, entry, prior.diagnostics);
- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });
- writeSnapshot(snapshotPath, next);
- return next;
- },
- getSnapshot(id = sessionId, opts = {}) {
- if (!id) throw new Error('session id required');
- const journalPath = getReadableJournalPath(id);
- const snapshotPath = getSnapshotPath(rootDir, id);
- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);
- snapshotCache.set(id, rebuilt);
- writeSnapshot(snapshotPath, rebuilt.snapshot);
- if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;
- return rebuilt.snapshot;
- },
- listActiveSessions() {
- const ids = new Set();
- for (const dir of [legacyRootDir, rootDir]) {
- if (!fs.existsSync(dir)) continue;
- for (const name of fs.readdirSync(dir)) {
- if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));
- }
- }
- return [...ids]
- .sort()
- .map((id) => this.getSnapshot(id))
- .filter(Boolean);
- },
- };
-}
-
-function normalizeEvent(event, fallbackId) {
- if (!event || typeof event !== 'object') throw new Error('event object required');
- const id = event.id || fallbackId;
- if (!id || typeof id !== 'string') throw new Error('event id required');
- if (!event.type || typeof event.type !== 'string') throw new Error('event type required');
- return { ...event, id };
-}
-
-function getJournalPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.jsonl');
-}
-
-function getSnapshotPath(rootDir, id) {
- return path.join(rootDir, safeSessionId(id) + '.snapshot.json');
-}
-
-function safeSessionId(id) {
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);
- return id;
-}
-
-function baseSnapshot(id) {
- return {
- id,
- phase: 'new',
- pageUrl: null,
- sourceFile: null,
- expectedVariants: 0,
- arrivedVariants: 0,
- visibleVariant: null,
- paramValues: {},
- pendingEventSeq: null,
- pendingEvent: null,
- deliveryLease: null,
- checkpointRevision: 0,
- activeOwner: null,
- sourceMarkers: {},
- fallbackMode: null,
- annotationArtifacts: [],
- diagnostics: [],
- updatedAt: null,
- };
-}
-
-function rebuildSnapshotFromJournal(journalPath, id) {
- let snapshot = baseSnapshot(id);
- const diagnostics = [];
- let nextSeq = 1;
- if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };
-
- const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- if (!line.trim()) continue;
- try {
- const entry = JSON.parse(line);
- if (!entry || typeof entry !== 'object') throw new Error('entry is not object');
- if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);
- snapshot = applyEvent(snapshot, entry);
- } catch (err) {
- diagnostics.push({
- error: 'journal_parse_failed',
- line: i + 1,
- message: err.message,
- });
- }
- }
- snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];
- return { snapshot, diagnostics, nextSeq };
-}
-
-function applyEvent(snapshot, entry, inheritedDiagnostics = []) {
- const event = entry.event || entry;
- const next = {
- ...snapshot,
- paramValues: { ...(snapshot.paramValues || {}) },
- sourceMarkers: { ...(snapshot.sourceMarkers || {}) },
- annotationArtifacts: [...(snapshot.annotationArtifacts || [])],
- diagnostics: [...(snapshot.diagnostics || [])],
- updatedAt: entry.ts || new Date().toISOString(),
- };
-
- if (inheritedDiagnostics.length && next.diagnostics.length === 0) {
- next.diagnostics = [...inheritedDiagnostics];
- }
-
- switch (event.type) {
- case 'generate':
- next.phase = 'generate_requested';
- next.pageUrl = event.pageUrl ?? next.pageUrl;
- next.expectedVariants = event.count ?? next.expectedVariants;
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });
- break;
- case 'variants_ready':
- case 'agent_done':
- next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';
- next.sourceFile = event.file ?? next.sourceFile;
- next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- if (event.carbonize === true) {
- next.diagnostics.push({
- error: 'carbonize_cleanup_required',
- file: event.file || null,
- message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',
- });
- }
- break;
- case 'checkpoint':
- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {
- next.phase = event.phase ?? next.phase;
- next.checkpointRevision = event.revision ?? next.checkpointRevision;
- next.activeOwner = event.owner ?? next.activeOwner;
- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;
- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- } else {
- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });
- }
- break;
- case 'accept':
- case 'accept_intent':
- next.phase = 'accept_requested';
- next.visibleVariant = Number(event.variantId ?? next.visibleVariant);
- if (event.paramValues) next.paramValues = { ...event.paramValues };
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discard':
- next.phase = 'discard_requested';
- next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;
- next.pendingEvent = toPendingEvent(event);
- break;
- case 'discarded':
- next.phase = 'discarded';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'complete':
- next.phase = 'completed';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- break;
- case 'agent_error':
- next.phase = 'agent_error';
- next.pendingEventSeq = null;
- next.pendingEvent = null;
- next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });
- break;
- default:
- next.diagnostics.push({ error: 'unknown_event_type', type: event.type });
- break;
- }
- return next;
-}
-
-function toPendingEvent(event) {
- const pending = { ...event };
- delete pending.token;
- return pending;
-}
-
-function upsertArtifact(artifacts, artifact) {
- if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {
- artifacts.push(artifact);
- }
-}
-
-function writeSnapshot(snapshotPath, snapshot) {
- fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');
-}
@@ -1,47 +0,0 @@
-#!/usr/bin/env node
-/**
- * Print durable recovery status for Impeccable live sessions.
- */
-
-import { createLiveSessionStore } from './live-session-store.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-function readServerInfo() {
- return readLiveServerInfo(process.cwd())?.info || null;
-}
-
-async function fetchServerStatus(info) {
- if (!info) return null;
- try {
- const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-export async function statusCli() {
- const info = readServerInfo();
- const server = await fetchServerStatus(info);
- const store = createLiveSessionStore({ cwd: process.cwd() });
- const activeSessions = store.listActiveSessions();
- const payload = {
- liveServer: server ? {
- status: server.status,
- port: server.port,
- connectedClients: server.connectedClients,
- pendingEvents: server.pendingEvents,
- } : null,
- activeSessions: server?.activeSessions || activeSessions,
- recoveryHint: server
- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'
- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',
- };
- console.log(JSON.stringify(payload, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {
- statusCli();
-}
@@ -1,632 +0,0 @@
-/**
- * CLI helper: find an element in source and wrap it in a variant container.
- *
- * Usage:
- * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
- *
- * Searches project files for the element matching the query (class name, ID, or
- * text snippet), wraps it with the variant scaffolding, and prints the file path
- * + line range where the agent should insert variant HTML.
- *
- * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { isGeneratedFile } from './is-generated.mjs';
-
-const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
-
-export async function wrapCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: impeccable wrap [options]
-
-Find an element in source and wrap it in a variant container.
-
-Required:
- --id ID Session ID for the variant wrapper
- --count N Number of expected variants (1-8)
-
-Element identification (at least one required):
- --element-id ID HTML id attribute of the element
- --classes A,B,C Comma-separated CSS class names
- --tag TAG Tag name (div, section, etc.)
- --query TEXT Fallback: raw text to search for
-
-Optional:
- --file PATH Source file to search in (skips auto-detection)
- --text TEXT Picked element's textContent. Used to disambiguate when
- classes/tag match multiple sibling elements (e.g. a list
- of <Card>s with the same className). Pass the first ~80
- chars of event.element.textContent.
- --help Show this help message
-
-Output (JSON):
- { file, startLine, endLine, insertLine, commentSyntax }
-
-The agent should insert variant HTML at insertLine.`);
- process.exit(0);
- }
-
- const id = argVal(args, '--id');
- const count = parseInt(argVal(args, '--count') || '3');
- const elementId = argVal(args, '--element-id');
- const classes = argVal(args, '--classes');
- const tag = argVal(args, '--tag');
- const query = argVal(args, '--query');
- const filePath = argVal(args, '--file');
- const text = argVal(args, '--text');
-
- if (!id) { console.error('Missing --id'); process.exit(1); }
- if (!elementId && !classes && !query) {
- console.error('Need at least one of: --element-id, --classes, --query');
- process.exit(1);
- }
-
- // Build search queries in priority order (most specific first)
- const queries = buildSearchQueries(elementId, classes, tag, query);
-
- const genOpts = { cwd: process.cwd() };
-
- // Find the source file. Generated files are excluded from auto-search so we
- // don't silently write variants into a file the next build will wipe.
- let targetFile = filePath;
- let matchedQuery = null;
- if (!targetFile) {
- for (const q of queries) {
- targetFile = findFileWithQuery(q, process.cwd(), genOpts);
- if (targetFile) { matchedQuery = q; break; }
- }
- if (!targetFile) {
- // Nothing in source. Did the element show up in a generated file? That
- // tells the agent "fall back to the agent-driven flow" vs "element just
- // doesn't exist in this project."
- let generatedHit = null;
- for (const q of queries) {
- generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
- if (generatedHit) break;
- }
- if (generatedHit) {
- console.error(JSON.stringify({
- error: 'element_not_in_source',
- fallback: 'agent-driven',
- generatedMatch: path.relative(process.cwd(), generatedHit),
- hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
- }));
- } else {
- console.error(JSON.stringify({
- error: 'element_not_found',
- fallback: 'agent-driven',
- hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
- }));
- }
- process.exit(1);
- }
- } else {
- if (isGeneratedFile(targetFile, genOpts)) {
- console.error(JSON.stringify({
- error: 'file_is_generated',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
- hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- matchedQuery = queries[0];
- }
-
- const content = fs.readFileSync(targetFile, 'utf-8');
- const lines = content.split('\n');
-
- // Find the element, trying each query in priority order. When `--text` is
- // supplied, collect every candidate the queries surface and disambiguate
- // by the picked element's textContent. Without `--text`, fall back to the
- // legacy first-match behavior so unmodified callers keep working.
- let match = null;
- if (text) {
- const candidates = [];
- for (const q of queries) {
- const all = findAllElements(lines, q, tag);
- for (const c of all) {
- if (!candidates.some((x) => x.startLine === c.startLine)) {
- candidates.push(c);
- }
- }
- // Once a more-specific query (ID, full className combo) yielded a unique
- // result, stop — falling through to the loose tag+single-class query
- // would readmit the siblings we just disambiguated past.
- if (candidates.length === 1) break;
- }
- if (candidates.length === 0) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- if (candidates.length === 1) {
- match = candidates[0];
- } else {
- const filtered = filterByText(candidates, lines, text);
- if (filtered.length === 1) {
- match = filtered[0];
- } else if (filtered.length === 0) {
- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the
- // browser-side textContent doesn't appear literally in source. Fall
- // back to first-match rather than refusing — this is the same
- // behavior unmodified callers see, just preserved.
- match = candidates[0];
- } else {
- // Multiple candidates ALSO match the text. Truly ambiguous — refuse
- // rather than pick wrong, and hand the agent the candidate locations
- // so it can disambiguate by reading the file.
- console.error(JSON.stringify({
- error: 'element_ambiguous',
- fallback: 'agent-driven',
- file: path.relative(process.cwd(), targetFile),
- candidates: filtered.map((c) => ({
- startLine: c.startLine + 1,
- endLine: c.endLine + 1,
- })),
- hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
- }));
- process.exit(1);
- }
- }
- } else {
- for (const q of queries) {
- match = findElement(lines, q, tag);
- if (match) break;
- }
- if (!match) {
- console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
- process.exit(1);
- }
- }
-
- const { startLine, endLine } = match;
- const commentSyntax = detectCommentSyntax(targetFile);
- const styleMode = detectStyleMode(targetFile);
- const isJsx = commentSyntax.open === '{/*';
- const indent = lines[startLine].match(/^(\s*)/)[1];
-
- // Extract the original element. Reindent under the wrapper while preserving
- // the relative depth between lines — `l.trimStart()` would strip ALL leading
- // whitespace and collapse e.g. `<aside>`/` <h1>`/`</aside>` (6/8/6 spaces)
- // to a single uniform indent, so on accept/discard the round-trip restores
- // the inner element at its parent's depth instead of nested inside it.
- // Strip only the COMMON minimum leading whitespace across the picked lines;
- // `deindentContent` on the accept side already mirrors this convention.
- const originalLines = lines.slice(startLine, endLine + 1);
- const originalBaseIndent = minLeadingSpaces(originalLines);
- const reindentOriginal = (extra) => originalLines
- .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
- .join('\n');
- const originalIndented = reindentOriginal(' ');
-
- // Wrapper attributes differ by syntax. HTML allows plain string attrs;
- // JSX requires object-literal style and parses string attrs as HTML (which
- // either type-errors or renders a literal CSS string).
- const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
-
- // JSX/TSX guard: the picked element occupies a single JSX child slot
- // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
- // any other expression position). Replacing it with `comment + <div> +
- // comment` yields three adjacent siblings — invalid JSX. We can't use a
- // Fragment `<></>` either: parents that clone children (Radix `asChild`,
- // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
- // they try to pass an `id` through.
- //
- // Solution: keep the wrapper `<div>` as the single JSX-slot child and
- // tuck both marker comments INSIDE it. accept/discard then expands its
- // replacement range to include the wrapper's `<div>` open / close lines
- // so the entire scaffold gets removed cleanly.
- const wrapperLines = isJsx ? [
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- reindentOriginal(' '),
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- indent + '</div>',
- ] : [
- indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',
- indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
- indent + ' <div data-impeccable-variant="original">',
- originalIndented,
- indent + ' </div>',
- indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
- indent + '</div>',
- indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
- ];
-
- // Replace the original element with the wrapper
- const newLines = [
- ...lines.slice(0, startLine),
- ...wrapperLines,
- ...lines.slice(endLine + 1),
- ];
- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
-
- // Calculate insert line (the "insert below this line" comment).
- // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
- // the insert marker (HTML: start-comment + outer-div + Original-comment +
- // original-div + content + close-original-div; JSX: outer-div +
- // start-comment + Original-comment + original-div + content +
- // close-original-div). Multi-line originals push the marker by their
- // extra line count.
- const insertLine = startLine + 6 + (originalLines.length - 1);
-
- console.log(JSON.stringify({
- file: path.relative(process.cwd(), targetFile),
- startLine: startLine + 1, // 1-indexed for the agent
- // wrapperLines is an array but one element (the original-content slot)
- // is a `\n`-joined multi-line string, so the actual file-row count is
- // wrapperLines.length + (originalLines.length - 1). Without the offset,
- // endLine pointed inside the wrapper for any picked element that
- // spanned more than one source line.
- endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexed
- insertLine: insertLine + 1, // 1-indexed: where variants go
- commentSyntax: commentSyntax,
- styleMode: styleMode.mode,
- styleTag: styleMode.styleTag,
- cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
- cssAuthoring: buildCssAuthoring(styleMode, count),
- originalLineCount: originalLines.length,
- }));
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function argVal(args, flag) {
- const idx = args.indexOf(flag);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
-
-/**
- * Build search query strings in priority order (most specific first).
- * ID is most reliable, then specific class combos, then single classes, then raw query.
- */
-function buildSearchQueries(elementId, classes, tag, query) {
- const queries = [];
-
- // 1. ID is the most specific
- if (elementId) {
- queries.push('id="' + elementId + '"');
- }
-
- // 2. Full class attribute match (for elements with distinctive multi-class combos).
- // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
- // convention the file uses will match.
- if (classes) {
- const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
- if (classList.length > 1) {
- const joined = classList.join(' ');
- const sorted = [...classList].sort((a, b) => b.length - a.length);
- queries.push('class="' + joined + '"');
- queries.push('className="' + joined + '"');
- queries.push(sorted[0]); // most distinctive single class, fallback
- } else if (classList.length === 1) {
- queries.push(classList[0]);
- }
- }
-
- // 3. Tag + class combo (e.g., <section class="hero">).
- // Same dual-emit for JSX compatibility.
- if (tag && classes) {
- const firstClass = classes.split(',')[0].trim();
- queries.push('<' + tag + ' class="' + firstClass);
- queries.push('<' + tag + ' className="' + firstClass);
- }
-
- // 4. Raw fallback query
- if (query) {
- queries.push(query);
- }
-
- return queries;
-}
-
-function detectCommentSyntax(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.jsx' || ext === '.tsx') {
- return { open: '{/*', close: '*/}' };
- }
- // HTML, Vue, Svelte, Astro all use HTML comments
- return { open: '<!--', close: '-->' };
-}
-
-function detectStyleMode(filePath) {
- const ext = path.extname(filePath).toLowerCase();
- if (ext === '.astro') {
- return {
- mode: 'astro-global-prefixed',
- styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',
- };
- }
- return {
- mode: 'scoped',
- styleTag: '<style data-impeccable-css="SESSION_ID">',
- };
-}
-
-function buildCssSelectorPrefixExamples(styleMode, count) {
- if (styleMode !== 'astro-global-prefixed') return [];
- return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);
-}
-
-function buildCssAuthoring(styleMode, count) {
- const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
- if (styleMode.mode === 'astro-global-prefixed') {
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'global-prefixed',
- rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',
- selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),
- requirements: [
- 'Use the styleTag exactly; the is:inline attribute is required for this file.',
- 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',
- 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
- ],
- forbidden: [
- 'Do not use @scope for this styleMode.',
- ],
- };
- }
- return {
- mode: styleMode.mode,
- styleTag: styleMode.styleTag,
- strategy: 'scope-rule',
- rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',
- selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),
- requirements: [
- 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',
- 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
- 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
- ],
- forbidden: [
- 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',
- 'Do not add is:inline to the style tag for this styleMode.',
- ],
- };
-}
-
-/**
- * Search project files for the query string (class name, ID, etc.)
- * Returns the first matching file path, or null.
- */
-function findFileWithQuery(query, cwd, genOpts = {}) {
- const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
- const seen = new Set();
-
- for (const dir of searchDirs) {
- const absDir = path.join(cwd, dir);
- if (!fs.existsSync(absDir)) continue;
- const result = searchDir(absDir, query, seen, 0, genOpts);
- if (result) return result;
- }
- return null;
-}
-
-function searchDir(dir, query, seen, depth, genOpts) {
- if (depth > 5) return null; // don't go too deep
- const realDir = fs.realpathSync(dir);
- if (seen.has(realDir)) return null;
- seen.add(realDir);
-
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return null; }
-
- // Check files first
- for (const entry of entries) {
- if (!entry.isFile()) continue;
- const ext = path.extname(entry.name).toLowerCase();
- if (!EXTENSIONS.includes(ext)) continue;
-
- const filePath = path.join(dir, entry.name);
- if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
- try {
- const content = fs.readFileSync(filePath, 'utf-8');
- if (content.includes(query)) return filePath;
- } catch { /* skip unreadable files */ }
- }
-
- // Then recurse into directories. Always skip node_modules and .git (never
- // project content). dist/build/out are left to the isGeneratedFile guard so
- // the includeGenerated second-pass can still find the element there and
- // report `generatedMatch`.
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
- const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
- if (result) return result;
- }
-
- return null;
-}
-
-/**
- * Regex that matches a tag opener on a line. Allows the tag name to be
- * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
- * openers (e.g. `<section\n className="..."\n>`) are recognised.
- */
-const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
-
-/**
- * Find the element's start and end line in the file.
- *
- * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
- * `id="..."`), or a raw text snippet. Because a query can appear on a
- * continuation line of a multi-line tag (e.g. the `className="..."` row of a
- * `<section\n className="..."\n>` JSX tag), we walk backward from the match
- * line to find the actual tag opener. When `tag` is provided, opener candidates
- * must match that tag name.
- */
-/**
- * Return the smallest leading-whitespace count across a set of lines,
- * ignoring blank lines (whose indent isn't load-bearing). Used to compute
- * the common base indent of a multi-line picked element so reindenting
- * under the wrapper preserves the relative depth between lines.
- */
-function minLeadingSpaces(lines) {
- let min = Infinity;
- for (const l of lines) {
- if (l.trim() === '') continue;
- const m = l.match(/^(\s*)/);
- if (m && m[1].length < min) min = m[1].length;
- }
- return min === Infinity ? 0 : min;
-}
-
-function findElement(lines, query, tag = null) {
- // Iterate all matches — the first substring hit isn't always the right one.
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
-
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- // Skip lines already inside a variant wrapper
- if (lines[i].includes('data-impeccable-variant')) continue;
-
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
-
- const endLine = findClosingLine(lines, openerLine);
- return { startLine: openerLine, endLine };
- }
-
- return null;
-}
-
-/**
- * Like findElement, but returns every match. Used for ambiguity detection
- * when the agent passes --text: when the same className appears on multiple
- * sibling elements (a list of cards, repeated section variants, etc.),
- * first-match silently lands on the wrong branch. Returning all matches lets
- * the caller narrow by textContent or fail with a structured ambiguity error.
- */
-function findAllElements(lines, query, tag = null) {
- const out = [];
- const seen = new Set();
- for (let i = 0; i < lines.length; i++) {
- if (!lines[i].includes(query)) continue;
- const stripped = lines[i].trim();
- if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
- if (lines[i].includes('data-impeccable-variant')) continue;
- const openerLine = findOpenerLine(lines, i, tag);
- if (openerLine === -1) continue;
- if (seen.has(openerLine)) continue; // multiple matches inside the same element
- seen.add(openerLine);
- const endLine = findClosingLine(lines, openerLine);
- out.push({ startLine: openerLine, endLine });
- }
- return out;
-}
-
-/**
- * Narrow a candidate set to those whose source body matches a meaningful
- * prefix of the picked element's textContent. The compare strips tags and
- * JSX expressions, then checks two whitespace normalizations side-by-side:
- *
- * - single-space ("hero two second card body")
- * - no-whitespace ("herotwosecondcardbody")
- *
- * Both are needed because `el.textContent` concatenates sibling text without
- * inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
- * `"Hero TwoSecond…"`), while the source has whitespace between tags. If
- * EITHER normalization matches, the candidate keeps. A snippet shorter than
- * 8 chars after stripping is too weak to disambiguate — the caller falls
- * back to first-match.
- */
-function filterByText(candidates, lines, text) {
- const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
- // Too short to disambiguate. Return [] so the caller's `filtered.length
- // === 0` branch fires (fall back to first-match) — the previous
- // `candidates.slice()` return forced `filtered.length > 1` and surfaced
- // a spurious `element_ambiguous` error on every short-text picker event
- // with multiple candidates.
- if (trimmed.length < 8) return [];
- const targetSpaced = trimmed;
- const targetCompact = trimmed.replace(/\s+/g, '');
-
- return candidates.filter((c) => {
- const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
- const inner = body
- .replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
- .replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
- .toLowerCase();
- const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
- const sourceCompact = inner.replace(/\s+/g, '');
- return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
- });
-}
-
-/**
- * Resolve a match line to the real tag opener. If the match line itself opens
- * a tag, return it. Otherwise walk up to 10 lines backward looking for the
- * first tag opener. If `tag` is specified, the opener must match that tag
- * name; an opener with a different tag name aborts the backward walk for this
- * match (we don't jump across element boundaries).
- *
- * Returns the line index of the opener, or -1 if none can be resolved.
- */
-function findOpenerLine(lines, matchLine, tag) {
- const self = lines[matchLine].match(OPENER_RE);
- if (self) {
- if (!tag || self[1] === tag) return matchLine;
- return -1;
- }
- const MAX_BACKWALK = 10;
- for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
- const opener = lines[i].match(OPENER_RE);
- if (!opener) continue;
- if (!tag || opener[1] === tag) return i;
- // Different tag name than requested — abort; we're inside a non-target opener.
- return -1;
- }
- return -1;
-}
-
-/**
- * Starting from a line with an opening tag, find the line with the matching
- * closing tag by counting tag nesting depth.
- */
-function findClosingLine(lines, start) {
- const openMatch = lines[start].match(OPENER_RE);
- if (!openMatch) return start; // caller passed a non-opener; nothing to span
-
- const tagName = openMatch[1];
- let depth = 0;
- const openRe = new RegExp('<' + tagName + '(?=[\\s/>]|$)', 'g');
- const selfCloseRe = new RegExp('<' + tagName + '[^>]*/>', 'g');
- const closeRe = new RegExp('</' + tagName + '\\s*>', 'g');
-
- for (let i = start; i < lines.length; i++) {
- const line = lines[i];
- const opens = (line.match(openRe) || []).length;
- const selfCloses = (line.match(selfCloseRe) || []).length;
- const closes = (line.match(closeRe) || []).length;
-
- depth += opens - selfCloses - closes;
-
- if (depth <= 0) return i;
- }
-
- // If we can't find the close, return a reasonable guess
- return Math.min(start + 50, lines.length - 1);
-}
-
-// Auto-execute when run directly (node live-wrap.mjs ...)
-const _running = process.argv[1];
-if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {
- wrapCli();
-}
-
-// Test exports (used by tests/live-wrap.test.mjs)
-export { buildSearchQueries, findElement, findClosingLine, detectCommentSyntax };
@@ -1,247 +0,0 @@
-/**
- * CLI entry point: prepare everything needed to enter the live variant poll loop.
- *
- * Does (all in one command):
- * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)
- * 2. Start the live server in the background (or reuse a running one)
- * 3. Inject the browser script tag into the project's entry file
- * 4. Read PRODUCT.md / DESIGN.md for project context
- * 5. Print a single JSON blob with everything the agent needs
- *
- * After this, the agent's only remaining steps are:
- * - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll
- * - Enter the poll loop: `node live-poll.mjs`
- *
- * Usage:
- * node live.mjs # Prepare everything, print JSON, exit
- * node live.mjs --help
- */
-
-import { execSync } from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { loadContext } from './load-context.mjs';
-import { resolveFiles } from './live-inject.mjs';
-import { readLiveServerInfo } from './impeccable-paths.mjs';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-async function liveCli() {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: node live.mjs
-
-Prepare everything for live variant mode in a single command:
- - Checks .impeccable/live/config.json (required, created once per project)
- - Starts (or reuses) the live server in the background
- - Injects the browser script tag
- - Reads PRODUCT.md / DESIGN.md for project context
-
-On success, prints a JSON blob with:
- { ok, serverPort, serverToken, pageFile, hasContext, context }
-
-On config_missing, prints:
- { ok: false, error: "config_missing", configPath, hint }
-
-The agent should then:
- 1. If config_missing, create the config and re-run this script
- 2. Optionally open the project's dev/preview URL in the browser (see reference/live.md—not serverPort)
- 3. Enter the poll loop: node live-poll.mjs`);
- process.exit(0);
- }
-
- // 1. Check config (fail fast if missing — no point starting anything else)
- const checkOut = runScript('live-inject.mjs', ['--check']);
- const checkResult = safeParse(checkOut);
- if (!checkResult || !checkResult.ok) {
- console.log(JSON.stringify(checkResult || { ok: false, error: 'check_failed', raw: checkOut }));
- process.exit(0);
- }
-
- // 2. Start server (or reuse existing)
- const serverInfo = ensureServerRunning();
- if (!serverInfo) {
- console.log(JSON.stringify({ ok: false, error: 'server_start_failed' }));
- process.exit(1);
- }
-
- // 3. Inject the script tag at the current port
- const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)]);
- const injectResult = safeParse(injectOut);
- if (!injectResult || !injectResult.ok) {
- console.log(JSON.stringify({
- ok: false,
- error: 'inject_failed',
- detail: injectResult || injectOut,
- serverPort: serverInfo.port,
- }));
- process.exit(1);
- }
-
- // 4. Load PRODUCT.md + DESIGN.md context (auto-migrates legacy .impeccable.md)
- const ctx = loadContext(process.cwd());
-
- // 5. Compute drift-heal: compare resolved inject targets against the
- // project's HTML files. Orphans are HTML files not covered by config.
- // Warning only — the agent decides whether to act.
- const resolvedFiles = resolveFiles(process.cwd(), checkResult.config);
- const drift = scanForDrift(process.cwd(), resolvedFiles, checkResult.config);
-
- // 6. Emit everything the agent needs
- console.log(JSON.stringify({
- ok: true,
- serverPort: serverInfo.port,
- serverToken: serverInfo.token,
- pageFiles: resolvedFiles,
- configDrift: drift,
- hasProduct: ctx.hasProduct,
- product: ctx.product,
- productPath: ctx.productPath,
- hasDesign: ctx.hasDesign,
- design: ctx.design,
- designPath: ctx.designPath,
- migrated: ctx.migrated,
- }, null, 2));
-}
-
-/**
- * Drift-heal scan. Walks the project for HTML files under common
- * page-source directories (public/, src/, app/, pages/) and reports any
- * that aren't covered by the resolved inject targets. This is purely
- * advisory — the agent can ignore it, or suggest the user add the
- * orphans to config.files.
- *
- * Skipped if config.files already contains at least one glob pattern
- * covering everything in practice (signaled by the orphan count being 0).
- */
-function scanForDrift(rootDir, resolvedFiles, config) {
- const SCAN_ROOTS = ['public', 'src', 'app', 'pages'];
- const IGNORE_DIRS = new Set([
- 'node_modules', '.git', '.next', '.nuxt', '.svelte-kit', '.astro',
- '.turbo', '.vercel', '.cache', 'coverage', 'dist', 'build',
- ]);
-
- const resolvedSet = new Set(resolvedFiles.map((f) => f.split(path.sep).join('/')));
-
- // Files matching the user's `exclude` globs are intentional omissions,
- // not drift. Compile them to regexes so the orphan list stays signal.
- const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
- .map((p) => globToRegex(p));
- const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
-
- const orphans = [];
-
- const walk = (dir, relBase) => {
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
- catch { return; }
- for (const e of entries) {
- const rel = relBase ? `${relBase}/${e.name}` : e.name;
- if (e.isDirectory()) {
- if (IGNORE_DIRS.has(e.name) || e.name.startsWith('.')) continue;
- walk(path.join(dir, e.name), rel);
- } else if (e.isFile() && e.name.endsWith('.html')) {
- if (resolvedSet.has(rel)) continue;
- if (isUserExcluded(rel)) continue;
- orphans.push(rel);
- }
- }
- };
-
- for (const root of SCAN_ROOTS) {
- const abs = path.join(rootDir, root);
- if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
- walk(abs, root);
- }
- }
-
- if (orphans.length === 0) return null;
- const capped = orphans.slice(0, 20);
- return {
- orphans: capped,
- orphanCount: orphans.length,
- hint: `${orphans.length} HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like "public/**/*.html".`,
- };
-}
-
-/**
- * Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
- * to avoid a circular import (live-inject.mjs already imports nothing
- * from live.mjs). The two must stay in sync.
- */
-function globToRegex(pattern) {
- let re = '';
- let i = 0;
- while (i < pattern.length) {
- const c = pattern[i];
- if (c === '*') {
- if (pattern[i + 1] === '*') {
- if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
- else { re += '.*'; i += 2; }
- } else {
- re += '[^/]*';
- i += 1;
- }
- } else if (c === '?') {
- re += '[^/]';
- i += 1;
- } else if (/[.+^${}()|[\]\\]/.test(c)) {
- re += '\\' + c;
- i += 1;
- } else {
- re += c;
- i += 1;
- }
- }
- return new RegExp('^' + re + '$');
-}
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function runScript(name, args) {
- const scriptPath = path.join(__dirname, name);
- const cmd = `node "${scriptPath}" ${args.map(a => `"${a}"`).join(' ')}`;
- try {
- return execSync(cmd, { encoding: 'utf-8', cwd: process.cwd(), timeout: 15_000 });
- } catch (err) {
- // execSync throws on non-zero exit; return stdout if any
- return err.stdout || err.message || '';
- }
-}
-
-function safeParse(out) {
- try { return JSON.parse(String(out).trim()); } catch { return null; }
-}
-
-/**
- * Return { pid, port, token } for the running live server, starting one if needed.
- */
-function ensureServerRunning() {
- // Try to reuse an existing server
- try {
- const existing = readLiveServerInfo(process.cwd())?.info;
- if (existing && existing.pid) {
- try {
- process.kill(existing.pid, 0); // throws if dead
- return existing;
- } catch { /* stale PID file — the server script will clean it up */ }
- }
- } catch { /* no PID file */ }
-
- // Start a new server
- const out = runScript('live-server.mjs', ['--background']);
- return safeParse(out);
-}
-
-// ---------------------------------------------------------------------------
-// Auto-execute
-// ---------------------------------------------------------------------------
-
-const _running = process.argv[1];
-if (_running?.endsWith('live.mjs') || _running?.endsWith('live.mjs/')) {
- liveCli();
-}
@@ -1,141 +0,0 @@
-/**
- * Shared context loader for every impeccable command that needs to know
- * "who is this for" and "what does this look like".
- *
- * Input: project root (process.cwd()).
- *
- * Output (JSON to stdout):
- * {
- * hasProduct: boolean, // PRODUCT.md found (or auto-migrated)
- * product: string | null, // PRODUCT.md contents
- * productPath: string | null, // relative path
- * hasDesign: boolean, // DESIGN.md found
- * design: string | null, // DESIGN.md contents
- * designPath: string | null,
- * migrated: boolean, // true if we auto-renamed .impeccable.md -> PRODUCT.md
- * contextDir: string, // absolute path of the directory the files were found in
- * }
- *
- * Filename matching is case-insensitive for PRODUCT.md and DESIGN.md. The
- * Google DESIGN.md convention is uppercase at repo root; Kiro-style and
- * lowercase variants are also matched so users don't get punished for case.
- *
- * Lookup directory resolution (first match wins):
- * 1. process.env.IMPECCABLE_CONTEXT_DIR (absolute or relative to cwd)
- * 2. cwd, if PRODUCT.md / DESIGN.md / .impeccable.md is there (back-compat)
- * 3. Auto-fallback subdirectories of cwd: .agents/context/, then docs/
- * 4. cwd as a default "no context found" location
- *
- * Legacy `.impeccable.md` -> PRODUCT.md migration only fires at cwd root;
- * fallback directories are read-only as far as auto-rename is concerned.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-
-const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
-const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
-const LEGACY_NAMES = ['.impeccable.md'];
-const FALLBACK_DIRS = ['.agents/context', 'docs'];
-
-/**
- * Resolve the directory that holds PRODUCT.md / DESIGN.md for
- * this project. Exported so other scripts (e.g. live-server.mjs) can read the
- * design files from the same location the loader uses.
- */
-export function resolveContextDir(cwd = process.cwd()) {
- // 1. Explicit override
- const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
- if (envDir && envDir.trim()) {
- const trimmed = envDir.trim();
- return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
- }
-
- // 2. cwd wins if any canonical or legacy file is there. We check legacy too
- // so the auto-migration path in loadContext stays predictable.
- if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES, ...LEGACY_NAMES])) {
- return cwd;
- }
-
- // 3. Auto-fallback subdirs. Match if PRODUCT.md or DESIGN.md is present;
- // legacy `.impeccable.md` does not pull the lookup into a fallback dir.
- for (const rel of FALLBACK_DIRS) {
- const candidate = path.resolve(cwd, rel);
- if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
- return candidate;
- }
- }
-
- // 4. Nothing found — keep the historical "default to cwd" behaviour so the
- // caller's `hasProduct === false` branch still fires the same way.
- return cwd;
-}
-
-export function loadContext(cwd = process.cwd()) {
- let migrated = false;
- const contextDir = resolveContextDir(cwd);
-
- // 1. Look for PRODUCT.md (case-insensitive) in the resolved dir
- let productPath = firstExisting(contextDir, PRODUCT_NAMES);
-
- // 2. Legacy: if no PRODUCT.md but .impeccable.md exists at cwd root, rename
- // it in place. We only migrate at the root — fallback dirs are read-only
- // so we don't surprise users by mutating files under docs/ or .agents/.
- if (!productPath && contextDir === cwd) {
- const legacyPath = firstExisting(cwd, LEGACY_NAMES);
- if (legacyPath) {
- const newPath = path.join(cwd, 'PRODUCT.md');
- try {
- fs.renameSync(legacyPath, newPath);
- productPath = newPath;
- migrated = true;
- } catch {
- // Rename failed (permissions, etc.) — fall back to reading legacy in place
- productPath = legacyPath;
- }
- }
- }
-
- // 3. DESIGN.md (case-insensitive)
- const designPath = firstExisting(contextDir, DESIGN_NAMES);
-
- const product = productPath ? safeRead(productPath) : null;
- const design = designPath ? safeRead(designPath) : null;
-
- return {
- hasProduct: !!product,
- product,
- productPath: productPath ? path.relative(cwd, productPath) : null,
- hasDesign: !!design,
- design,
- designPath: designPath ? path.relative(cwd, designPath) : null,
- migrated,
- contextDir,
- };
-}
-
-function firstExisting(dir, names) {
- for (const name of names) {
- const abs = path.join(dir, name);
- if (fs.existsSync(abs)) return abs;
- }
- return null;
-}
-
-function safeRead(p) {
- try { return fs.readFileSync(p, 'utf-8'); } catch { return null; }
-}
-
-// ---------------------------------------------------------------------------
-// CLI mode — print the context as JSON
-// ---------------------------------------------------------------------------
-
-function cli() {
- const result = loadContext(process.cwd());
- console.log(JSON.stringify(result, null, 2));
-}
-
-const _running = process.argv[1];
-if (_running?.endsWith('load-context.mjs') || _running?.endsWith('load-context.mjs/')) {
- cli();
-}
@@ -1,14 +0,0 @@
@@ -1,214 +0,0 @@
-#!/usr/bin/env node
-/**
- * Pin/unpin sub-commands as standalone skill shortcuts.
- *
- * Usage:
- * node <scripts_path>/pin.mjs pin <command>
- * node <scripts_path>/pin.mjs unpin <command>
- *
- * `pin audit` creates a lightweight /audit skill that redirects to /impeccable audit.
- * `unpin audit` removes that shortcut.
- *
- * The script discovers harness directories (.claude/skills, .cursor/skills, etc.)
- * in the project root and creates/removes the pin in all of them.
- */
-
-import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
-import { join, resolve, dirname } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-// All known harness directories
-const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
- '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
-];
-
-// Valid sub-command names
-const VALID_COMMANDS = [
- 'craft', 'teach', 'extract', 'document', 'shape',
- 'critique', 'audit',
- 'polish', 'bolder', 'quieter', 'distill', 'harden', 'onboard', 'live',
- 'animate', 'colorize', 'typeset', 'layout', 'delight', 'overdrive',
- 'clarify', 'adapt', 'optimize',
-];
-
-// Marker to identify pinned skills (so unpin doesn't delete user skills)
-const PIN_MARKER = '<!-- impeccable-pinned-skill -->';
-
-/**
- * Walk up from startDir to find a project root.
- */
-function findProjectRoot(startDir = process.cwd()) {
- let dir = resolve(startDir);
- while (dir !== '/') {
- if (
- existsSync(join(dir, 'package.json')) ||
- existsSync(join(dir, '.git')) ||
- existsSync(join(dir, 'skills-lock.json'))
- ) {
- return dir;
- }
- const parent = resolve(dir, '..');
- if (parent === dir) break;
- dir = parent;
- }
- return resolve(startDir);
-}
-
-/**
- * Find harness skill directories that have an impeccable skill installed.
- */
-function findHarnessDirs(projectRoot) {
- const dirs = [];
- for (const harness of HARNESS_DIRS) {
- const skillsDir = join(projectRoot, harness, 'skills');
- // Only pin in harness dirs that already have impeccable installed
- const impeccableDir = join(skillsDir, 'impeccable');
- if (existsSync(impeccableDir) || existsSync(join(skillsDir, 'i-impeccable'))) {
- dirs.push(skillsDir);
- }
- }
- return dirs;
-}
-
-/**
- * Load command metadata (descriptions for pinned skills).
- */
-function loadCommandMetadata() {
- const metadataPath = join(__dirname, 'command-metadata.json');
- if (existsSync(metadataPath)) {
- return JSON.parse(readFileSync(metadataPath, 'utf-8'));
- }
- return {};
-}
-
-/**
- * Generate a pinned skill's SKILL.md content.
- */
-function generatePinnedSkill(command, metadata) {
- const desc = metadata[command]?.description || `Shortcut for /impeccable ${command}.`;
- const hint = metadata[command]?.argumentHint || '[target]';
-
- return `---
-name: ${command}
-description: "${desc}"
-argument-hint: "${hint}"
-user-invocable: true
----
-
-${PIN_MARKER}
-
-This is a pinned shortcut for \`{{command_prefix}}impeccable ${command}\`.
-
-Invoke {{command_prefix}}impeccable ${command}, passing along any arguments provided here, and follow its instructions.
-`;
-}
-
-/**
- * Pin a command: create shortcut skill in all harness dirs.
- */
-function pin(command, projectRoot) {
- const metadata = loadCommandMetadata();
- const harnessDirs = findHarnessDirs(projectRoot);
-
- if (harnessDirs.length === 0) {
- console.log('No harness directories with impeccable installed found.');
- return false;
- }
-
- const content = generatePinnedSkill(command, metadata);
- let created = 0;
-
- for (const skillsDir of harnessDirs) {
- // Check if skill already exists (and isn't a pin)
- const skillDir = join(skillsDir, command);
- if (existsSync(skillDir)) {
- const existingMd = join(skillDir, 'SKILL.md');
- if (existsSync(existingMd)) {
- const existing = readFileSync(existingMd, 'utf-8');
- if (!existing.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (non-pinned skill already exists)`);
- continue;
- }
- }
- }
-
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(join(skillDir, 'SKILL.md'), content, 'utf-8');
- console.log(` + ${skillDir}`);
- created++;
- }
-
- if (created > 0) {
- console.log(`\nPinned '${command}' as a standalone shortcut in ${created} location(s).`);
- console.log(`You can now use /${command} directly.`);
- }
-
- return created > 0;
-}
-
-/**
- * Unpin a command: remove shortcut skill from all harness dirs.
- */
-function unpin(command, projectRoot) {
- const harnessDirs = findHarnessDirs(projectRoot);
- let removed = 0;
-
- for (const skillsDir of harnessDirs) {
- const skillDir = join(skillsDir, command);
- if (!existsSync(skillDir)) continue;
-
- const skillMd = join(skillDir, 'SKILL.md');
- if (!existsSync(skillMd)) continue;
-
- // Safety: only remove if it's a pinned skill
- const content = readFileSync(skillMd, 'utf-8');
- if (!content.includes(PIN_MARKER)) {
- console.log(` SKIP: ${skillDir} (not a pinned skill)`);
- continue;
- }
-
- rmSync(skillDir, { recursive: true, force: true });
- console.log(` - ${skillDir}`);
- removed++;
- }
-
- if (removed > 0) {
- console.log(`\nUnpinned '${command}' from ${removed} location(s).`);
- console.log(`Use /impeccable ${command} to access it.`);
- } else {
- console.log(`No pinned '${command}' shortcut found.`);
- }
-
- return removed > 0;
-}
-
-// --- CLI ---
-const [,, action, command] = process.argv;
-
-if (!action || !command) {
- console.log('Usage: node pin.mjs <pin|unpin> <command>');
- console.log(`\nAvailable commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-if (action !== 'pin' && action !== 'unpin') {
- console.error(`Unknown action: ${action}. Use 'pin' or 'unpin'.`);
- process.exit(1);
-}
-
-if (!VALID_COMMANDS.includes(command)) {
- console.error(`Unknown command: ${command}`);
- console.error(`Available commands: ${VALID_COMMANDS.join(', ')}`);
- process.exit(1);
-}
-
-const root = findProjectRoot();
-
-if (action === 'pin') {
- pin(command, root);
-} else {
- unpin(command, root);
-}
@@ -1,69 +0,0 @@
-# Repository Guidelines
-
-## Skill bootstrap: skip the post-update-cleanup step
-
-If you load the Impeccable skill from `.agents/skills/impeccable/SKILL.md` (or any sibling harness directory under this repo), it begins with a `<post-update-cleanup>` block that runs `scripts/cleanup-deprecated.mjs` and then self-deletes. **Do not run it here, and do not delete the block.** This repo is the source of truth for the skill; cleanup-deprecated assumes a consumer project and would touch legitimate source files. The block is regenerated from `skill/SKILL.md` on every `bun run build`, so any deletion churns back. Skip it silently and proceed with the task.
-
-## Project Structure & Module Organization
-
-`source/` is the source of truth. Author skills in `skill/` and keep provider output in `dist/` generated, not hand-edited. Build logic lives in `scripts/`, with provider configs in `scripts/lib/transformers/`. Runtime detection code ships from `src/`. The website lives in `public/`, local API/dev serving lives in `server/`, and regression coverage lives in `tests/` with fixtures under `tests/fixtures/`.
-
-## Build, Test, and Development Commands
-
-- `bun run dev` - start the local Bun server.
-- `bun run build` - regenerate `dist/`, derived site assets, and validation output.
-- `bun run rebuild` - clean and rebuild everything from scratch.
-- `bun test tests/build.test.js` - run a focused Bun test.
-- `bun run test` - run the full Bun + Node test suite.
-- `bun run test:live-e2e` - opt-in live-mode E2E against framework fixtures (~2 min; needs `npx playwright install chromium` once).
-- `bun run build:browser` / `bun run build:extension` - rebuild browser-specific bundles.
-
-Run `bun run build` after changing anything in `source/`, transformer code, or user-facing counts.
-
-## Sandbox gotchas for Codex agents
-
-Some repo workflows need to run outside the sandbox in the desktop app:
-
-- GitHub SSH operations that depend on the 1Password SSH agent, such as `gh pr checkout`, may fail in the sandbox with `sign_and_send_pubkey` or no 1Password approval prompt. Rerun them outside the sandbox instead of falling back to unrelated workarounds.
-- `bun run build` rewrites committed harness directories such as `.agents/skills/`. In the sandbox, Bun can hit filesystem errors while removing/recreating those trees (for example `EFAULT` on `.agents/skills`). Rerun the build outside the sandbox before treating it as a real build failure.
-- Puppeteer/headless-Chrome tests, especially `node --test tests/detect-antipatterns-browser.test.mjs` and the browser portion of `bun run test`, can hang in the sandbox while launching Chrome. Run them outside the sandbox for authoritative results.
-- The jsdom fixture suite is intentionally run with Node, not Bun: use `node --test tests/detect-antipatterns-fixtures.test.mjs` or the `bun run test` script. A direct `bun test tests/detect-antipatterns-fixtures.test.mjs` can time out and is not the supported signal.
-
-## Coding Style & Naming Conventions
-
-Use ESM, semicolons, and the existing two-space indentation style in JS, HTML, and CSS. Prefer small, single-purpose modules over large abstractions. Keep filenames descriptive and lowercase with hyphens where needed; skill entrypoints stay as `SKILL.md`, helper scripts use `.js` or `.mjs`. In source frontmatter, use clear kebab-case names and concise descriptions. There is no dedicated formatter or linter configured here, so match surrounding code closely.
-
-## Testing Guidelines
-
-Tests use Bun’s test runner plus Node’s built-in `--test`. Name tests `*.test.js` or `*.test.mjs` and place new fixtures near the behavior they cover, usually under `tests/fixtures/`. Prefer targeted test runs while iterating, then finish with `bun run test`. If you change generated outputs or provider transforms, verify both source parsing and at least one affected provider path in `dist/`.
-
-For changes to `skill/scripts/live-*.{mjs,js}`, also run `bun run test:live-e2e` (kept out of the default suite because it does real `npm install` per fixture and boots framework dev servers). Scope to one fixture with `IMPECCABLE_E2E_ONLY=<fixture-name>` while iterating; pass `IMPECCABLE_E2E_DEBUG=1` for page-DOM and dev-server-log dumps on failure. Schema and authoring guide for new fixtures live in `tests/framework-fixtures/README.md`.
-
-Set `IMPECCABLE_E2E_AGENT=llm` to swap the deterministic fake agent for a Claude-backed one (`tests/live-e2e/agents/llm-agent.mjs`, default Haiku 4.5, override via `IMPECCABLE_E2E_LLM_MODEL`). Requires `ANTHROPIC_API_KEY`; tests skip cleanly when it's unset. This path hits the API — use it for verification, not CI.
-
-## Anti-pattern detection rules
-
-`cli/engine/detect-antipatterns.mjs` is the source of truth for the rule engine. It feeds the CLI, the site overlay (`cli/engine/detect-antipatterns-browser.js`, regenerated by `bun run build:browser`), the Chrome extension (`extension/detector/`, regenerated by `bun run build:extension`), and the homepage `DETECTION_COUNT` in `site/public/js/generated/counts.js` (regenerated by `bun run build`). After any rule change run all three builds plus `bun run test` so nothing drifts.
-
-TDD order is non-negotiable:
-
-1. Add a fixture at `tests/fixtures/antipatterns/{rule-id}.html` with two columns (should-flag / should-pass), each case identified by a unique heading. ≥4 flag cases and ≥5 false-positive shapes. **Use explicit pixel dimensions in CSS** — jsdom does no layout.
-2. Add a failing test in `tests/detect-antipatterns-fixtures.test.mjs` using the snippet-substring pattern (regex `/"([^"]+)"/` against `SHOULD_FLAG` / `SHOULD_PASS` lists).
-3. Add the rule entry to the `ANTIPATTERNS` array (`id`, `category` = `slop` or `quality`, `name`, `description`, optional `skillSection` / `skillGuideline`).
-4. Implement a pure `checkXxx(opts)` returning `[{ id, snippet }]` — no DOM access inside.
-5. Add two adapters that wrap the pure check: `checkElementXxxDOM(el)` for the browser (`getComputedStyle` + `getBoundingClientRect`) and `checkElementXxx(el, tag, window)` for jsdom (`parseFloat(style.width)` instead of layout). Wire **both** adapters into **both** element loops in `cli/engine/detect-antipatterns.mjs` (browser loop ~line 1837, jsdom loop in `detectHtml` ~line 2058). Forgetting one is the most common mistake.
-6. Verify on a live page at `http://localhost:3000/fixtures/antipatterns/{rule-id}.html` and on the homepage. The two adapter paths can disagree.
-
-Conventions: wrap the identifying heading text in straight double quotes inside snippets so the fixture test can extract it. jsdom-specific helpers `resolveBackground()`, `resolveGradientStops()`, and `parseGradientColors()` exist because `background:` shorthand isn't decomposed and computed colors aren't normalized in jsdom — use them. Reference rules to copy from: `side-tab` (border), `low-contrast` (color+gradient), `icon-tile-stack` (sibling relationship), `flat-type-hierarchy` (page-level).
-
-## Commit & Pull Request Guidelines
-
-Recent history favors short, imperative subjects such as `Fix: ...`, `Add ...`, `Improve ...`, or `Bump ...`. Keep commits focused and explain the user-facing impact when it is not obvious. PRs should summarize what changed, list validation performed, and call out regenerated artifacts like `dist/` or `build/`. Include screenshots for visible `site/` changes and mention affected providers when transform behavior changes.
-
-## Releases
-
@@ -1,302 +0,0 @@
-# Project Instructions for Claude
-
-## Skill bootstrap: skip the post-update-cleanup step
-
-The `<post-update-cleanup>` block at the top of `.claude/skills/impeccable/SKILL.md` runs `scripts/cleanup-deprecated.mjs` and then self-deletes. **Do not run it in this repo, and do not delete the block.** This repo is the source of truth for the Impeccable skill; the cleanup script scans for "leftover" skill files to remove and its judgment doesn't fit a repo where the skill lives in `skill/`. The block is also regenerated from `skill/SKILL.md` on every `bun run build`, so any deletion churns back on the next build. Skip the step silently and proceed.
-
-Same rule for AGENTS.md and every other harness-specific instruction file: treat post-update-cleanup as a no-op in this repo.
-
-## Architecture (v3.0+)
-
-There is **one** user-invocable skill, `impeccable`, with **23 commands** underneath it. Users type `/impeccable polish`, `/impeccable audit`, etc. The skill is defined in `skill/`:
-
-- `SKILL.md` — frontmatter (with the auto-trigger-optimized description and the `allowed-tools` list), shared design laws, and the **Commands** router table.
-- `reference/` — one `<command>.md` per command (`audit.md`, `polish.md`, `critique.md`, etc.) plus the domain reference files (`typography.md`, `color-and-contrast.md`, etc.). When a sub-command is matched, the router loads its reference file.
-- `reference/brand.md` and `reference/product.md` — the two register references. SKILL.md's Setup section selects one based on the task cue, the surface in focus, or the `register` field in PRODUCT.md (first match wins).
-- `scripts/command-metadata.json` — single source of truth for each command's description, argument hint, and (eventually) category. Both the build and `pin.mjs` read from this.
-- `scripts/pin.mjs` — creates/removes lightweight redirect shims so users can have `/audit` as a standalone shortcut that delegates to `/impeccable audit`.
-- `scripts/cleanup-deprecated.mjs` — runs once after an update to remove leftover files from renamed/merged commands.
-
-**Do not add standalone skills** unless there's a strong reason. The consolidation was deliberate: the `/` menu pollution problem is real and gets worse as users install more plugins.
-
-### Register (brand vs product)
-
-Every design task belongs to one of two registers:
-
-- **Brand** — design IS the product: marketing, landing pages, brand sites, campaign surfaces, portfolios, long-form content. Distinctiveness is the bar. Spans every visual lane (tech-minimal, luxury, editorial-magazine, consumer-warm, brutalist, etc.) — do not default to only one.
-- **Product** — design SERVES the product: app UI, admin, dashboards, tools. Earned familiarity is the bar — fluent users of Linear / Figma / Notion / Raycast / Stripe should trust it.
-
-PRODUCT.md at the project root carries a `## Register` section with a bare value (`brand` or `product`). `/impeccable teach` asks about register first because it shapes every downstream answer.
-
-Sub-command reference files add a short `## Register` section near the top *only where the answer diverges between the two*. Don't restate the register files' content in sub-commands — link instead. Sub-commands where register meaningfully diverges today: `typeset`, `animate`, `bolder`, `delight`, `colorize`, `layout`, `quieter`.
-
-**a11y lives in `audit.md`**, not in SKILL.md, `brand.md`, or `product.md`. Models over-cautious themselves into safe, underdesigned output when reminded about accessibility at design time. The audit command is the dedicated place for that check.
-
-## CSS
-
-Plain hand-written CSS, no Tailwind. Imported into Astro pages/layouts via frontmatter `import` statements; Vite resolves `@import` chains automatically.
-
-The CSS architecture (under `site/styles/`):
-- `main.css` — Main entry point, imports the partials and defines tokens/reset
-- `workflow.css` — Commands section, glass terminal, magazine spread styles
-- `sub-pages.css` — `/docs`, `/anti-patterns`, `/tutorials`, detail pages
-- `tokens.css` — OKLCH color tokens (ink, charcoal, ash, mist, cream, accent)
-- `footer.css` — shared across all pages, imported in `Base.astro`
-
-Edit any of these directly and the dev server hot-reloads. No rebuild needed for CSS changes.
-
-## Color token rule
-
-- **`--color-ink`** (10% lightness) is for body copy. Use it even for small text.
-- **`--color-charcoal`** (25% lightness) reads as washed-out gray in small text. Only use for headings or larger body copy at ≥16px.
-- **`--color-ash`** (55%) is for secondary labels, captions, relationship meta lines.
-- **Never use pure black or pure white.** Use the tinted tokens.
-
-## Prose: read STYLE.md before writing user-facing copy
-
-Editorial brief is at `STYLE.md` (root). Read it before editing the homepage, sub-pages, command editorials, tutorials, or READMEs. The site has been called out for AI prose; the rules there exist to keep that from creeping back.
-
-The build's `validateProse` step (in `scripts/build.js`) enforces a denylist: em dashes (`—` and HTML entities), the `--` em-dash substitute, `load-bearing`, `highest-leverage`, `biggest unlock`, `seamless`, `robust`, `delve`, `elevate`, `empower`, `underscore`, `pivotal`, `tapestry`, `data-driven`, `reflex defaults`, `collapses into monoculture`, `in today's`, `gone are the days`, `whether you're`, `let's dive in`, `in summary`, `in conclusion`, `moreover`, `furthermore`. Each rule prints a rationale and a suggested replacement when it fires. **Do not silently work around the regex.** If a banned word has earned a real meaning here, raise it as a STYLE.md amendment.
-
-The validator scans `site/pages/`, `site/content/`, `site/components/`, `site/layouts/`, `README.md`, `README.npm.md`. It deliberately skips `skill/` because LLM-facing reference instructions sometimes need technical phrasings the marketing copy can't.
-
-The deeper structural issues (negation pivot, triadic auto-pilot, uniform paragraph rhythm, hollow confidence) require human judgment. STYLE.md lists them. Use them on every editorial pass.
-
-## Editorial content lives under `site/content/`
-
-Skill editorials and tutorials are read by `scripts/build.js` (for taglines and downstream tooling) and by Astro's content collection (for what actually renders on the site). One tree, one place to edit:
-- `site/content/skills/<id>.md` — optional editorial wrapper with frontmatter `tagline` plus body sections
-- `site/content/tutorials/<slug>.md` — full tutorial content
-- `site/data/anti-patterns-catalog.js` — detection-rule catalog (visual examples, gallery items, layer definitions)
-
-## Development Server
-
-```bash
-bun run dev # Bun dev server at http://localhost:3000
-bun run preview # Build + Cloudflare Pages local preview
-```
-
-The dev server runs Astro (`astro dev`). Editing files in `site/content/skills/`, `skill/`, or `scripts/lib/sub-pages-data.js` requires a **server restart** (not just a browser reload) to see the change. CSS, components, and pages hot-reload fine without a restart.
-
-**Legacy URL redirects** are emitted to `_redirects` by `scripts/build.js` (via `generateCFConfig`); the dynamic `/skills/:id → /docs/:id` redirect lives in `site/public/_redirects` (Cloudflare Pages reads both at deploy). Current redirects: `/skills` → `/docs`, `/skills/:id` → `/docs/:id`, `/cheatsheet` → `/docs`, `/gallery` → `/visual-mode#try-it-live`.
-
-## Deployment
-
-Hosted on Cloudflare Pages. Static assets served from `build/`, API routes handled via `_redirects` rewrites (JSON) and Pages Functions (downloads).
-
-```bash
-bun run deploy # Build + deploy to Cloudflare Pages
-```
-
-## Build System
-
-The build system compiles the impeccable skill from `skill/` to provider-specific formats in `dist/`:
-
-```bash
-bun run build # Build all providers
-bun run rebuild # Clean and rebuild
-```
-
-Source files use placeholders that get replaced per-provider:
-- `{{model}}` — Model name (Claude, Gemini, GPT, etc.)
-- `{{config_file}}` — Config file name (CLAUDE.md, .cursorrules, etc.)
-- `{{ask_instruction}}` — How to ask user questions
-- `{{command_prefix}}` — `/` or `$` depending on provider
-- `{{available_commands}}` — auto-populated list of commands (from `IMPECCABLE_SUB_COMMANDS` in `scripts/lib/utils.js`)
-- `{{scripts_path}}` — provider-aware path to the skill's scripts directory
-
-### Harness output directories are tracked
-
-`.claude/skills/`, `.cursor/skills/`, `.agents/skills/`, and the other 8 harness directories are **intentionally committed to the repo**. `npx skills` reads them directly from this repo at install time, and they enable clean submodule use. Do not gitignore them. Run `bun run build` to refresh them after editing `skill/`.
-
-Local state files inside harness directories (e.g. `.claude/scheduled_tasks.lock`, `.claude/settings.local.json`) ARE gitignored.
-
-### Generated sub-pages are gitignored
-
-`site/public/docs/`, `site/public/anti-patterns/`, `site/public/tutorials/`, `site/public/visual-mode/`, `site/public/slop/` are gitignored as legacy generator output paths. Astro's content collections drive the live site under `site/pages/docs/`, `site/pages/tutorials/`, etc.; nothing reads from those gitignored dirs anymore.
-
-## Testing
-
-```bash
-bun run test # Default suite: unit + static framework fixtures
-bun run test:live-e2e # Opt-in: full-cycle live-mode E2E across framework fixtures
-```
-
-Unit tests (build orchestration, detector logic) run via `bun test`. Fixture tests (jsdom-based HTML detection) run via `node --test` because bun is too slow with jsdom. The `test` script handles this split automatically.
-
-**Important:** `tests/build.test.js` uses `spyOn(transformers, 'transformCursor')` with the named exports from `scripts/lib/transformers/index.js`. Those named exports (`transformCursor`, `transformClaudeCode`, etc.) are kept specifically for test spying, even though `build.js` itself uses `createTransformer + PROVIDERS` directly. **Do not delete them as "dead code"** — I made that mistake once and broke 8 tests.
-
-### Live-mode E2E
-
-`tests/live-e2e.test.mjs` drives the entire user flow (handshake → pick → Go → cycle → accept → carbonize cleanup) against every fixture in `tests/framework-fixtures/` that declares a `runtime` block. Each fixture installs real deps, boots its framework dev server (Vite, Next, SvelteKit, Astro, Nuxt static), and runs Playwright Chromium against a deterministic fake agent that produces realistic variants in the exact format `reference/live.md` describes.
-
-```bash
-bun run test:live-e2e # full suite, ~2 min, 19 fixtures
-IMPECCABLE_E2E_ONLY=vite8-react-modal bun run test:live-e2e # scope to one fixture
-IMPECCABLE_E2E_DEBUG=1 bun run test:live-e2e # dump page DOM + dev-server tail on failure
-```
-
-**One-time setup**: `npx playwright install chromium` (the suite uses a specific Chromium build keyed to the bundled Playwright version).
-
-**Kept out of the default `bun run test`** because (a) it does real `npm install` per fixture, (b) it boots framework dev servers, (c) wall time is ~2 minutes, and (d) it requires Playwright's browser cache. Run it locally before shipping changes to anything in `skill/scripts/live-*.{mjs,js}`.
-
-The agent is pluggable via a one-method interface in `tests/live-e2e/agent.mjs`: `generateVariants(event, context) → { scopedCss, variants[] }`. The default fake agent emits canned variants that exercise all three param kinds (`range`, `steps`, `toggle`). The orchestrator (wrap, write, accept, carbonize) is agent-agnostic.
-
-**LLM agent (opt-in)**: set `IMPECCABLE_E2E_AGENT=llm` to swap the fake agent for `tests/live-e2e/agents/llm-agent.mjs`, which calls Claude (default Haiku 4.5) via `@anthropic-ai/sdk`. Requires `ANTHROPIC_API_KEY` in env; the test runner skips with a clear message when it's unset. Override the model with `IMPECCABLE_E2E_LLM_MODEL=claude-sonnet-4-6` if Haiku produces unreliable JSON. Caching is on — live.md is the cacheable prefix, and after the first call subsequent fixtures pay only the cache-read rate. Pass rate on a typical sweep is 18/19; the modal fixture's intrinsic state-loss flake is amplified by LLM latency and may need a re-run. **This path hits the API and costs money** — keep it out of CI unless you really want it there.
-
-Adding a new fixture is a matter of cloning a directory under `tests/framework-fixtures/`, swapping the source files, and writing a `fixture.json`. See `tests/framework-fixtures/README.md` for the full schema.
-
-## CLI
-
-The CLI lives in this repo under `cli/`: `cli/bin/` (entry + sub-commands), `cli/engine/` (the detect-antipatterns rule engine + browser variant), `cli/lib/` (helpers shared by CLI and Cloudflare Pages Functions). Published to npm as `impeccable`.
-
-```bash
-npx impeccable detect [file-or-dir-or-url...] # detect anti-patterns
-npx impeccable detect --fast --json src/ # regex-only, JSON output
-npx impeccable live # start browser overlay server
-npx impeccable skills install # install skills
-npx impeccable --help # show help
-```
-
-The browser detector (`cli/engine/detect-antipatterns-browser.js`) is generated from the main engine. After changing `cli/engine/detect-antipatterns.mjs`, rebuild it:
-
-```bash
-bun run build:browser
-```
-
-**IMPORTANT**: Always use `node` (not `bun`) to run the detect CLI. Bun's jsdom implementation is extremely slow and will cause scans with HTML files to hang for minutes.
-
-## Versioning
-
-There are three independently versioned components. Only bump the one(s) that actually changed:
-
-**CLI** (npm package):
-- `package.json` → `version`
-- Bump when: CLI code changes (`cli/bin/`, `cli/engine/detect-antipatterns.mjs`, etc.)
-
-**Skills** (Claude Code plugin / skill definitions):
-- `.claude-plugin/plugin.json` → `version`
-- `.claude-plugin/marketplace.json` → `plugins[0].version`
-- Bump when: skill content changes (`skill/`, reference files, command metadata, etc.)
-
-**Chrome extension**:
-- `extension/manifest.json` → `version`
-- Bump when: extension code changes (`extension/`)
-
-**Website changelog** (`site/pages/index.astro`):
-- Hero version link text + new changelog entry in the changelog section
-- Update for user-facing changes only, not internal build/tooling details
-- Use the most prominent version that changed (skills version is usually the right one)
-
-After bumping, see **Releases** below for how to tag and publish.
-
-## Releases
-
-GitHub releases are tagged per-component, not per-version, since the three components ship independently. Tag prefixes: `skill-v`, `cli-v`, `ext-v`.
-
-Workflow for any component:
-
-1. Bump the manifest version (see Versioning above).
-2. Add a changelog entry to `site/pages/index.astro`. Skill entries use a bare `vX.Y.Z` label; CLI and extension entries use the prefixed forms `CLI vX.Y.Z` and `Extension vX.Y.Z`. The release script extracts notes by matching this label, so the prefix matters.
-3. Commit and push to `main`.
-4. Run `bun run release:<skill|cli|ext>`. Preview first with `node scripts/release.mjs <component> --dry-run`.
-
-The script refuses to run if: the working tree is dirty, HEAD is ahead of origin, the tag already exists, the matching changelog entry is missing, or (for skill/extension) `bun run build` / `bun run build:extension` produces uncommitted changes — meaning the harness output dirs or `extension/detector/` files weren't refreshed before the bump was committed.
-
-Skill releases attach `dist/universal.zip`. Extension releases run `bun run build:extension` first and attach `dist/extension.zip`. CLI releases print a reminder to run `npm publish` separately; extension releases print a reminder to upload the zip to the Chrome Web Store dashboard.
-
-If you need to fix release notes after the fact (typo, missing thank-you, formatting bug): `gh release edit <tag> --notes-file <md>`. The release script's `htmlToMarkdown` function is the cleanest source for regenerating notes from the changelog.
-
-## Adding New Commands
-
-All commands live under `/impeccable`. To add a new one:
-
-1. Create `skill/reference/<command>.md` with the command's instructions (this is what the LLM loads when the command is invoked)
-2. Add a row to the **Sub-command reference table** in `skill/SKILL.md`
-3. Add an entry to the **Command menu** section in the same file
-4. Add the command name to `IMPECCABLE_SUB_COMMANDS` in `scripts/lib/utils.js`
-5. Add it to `VALID_COMMANDS` in `skill/scripts/pin.mjs`
-6. Add its metadata (description + argumentHint) to `skill/scripts/command-metadata.json`
-7. Add its category to `SKILL_CATEGORIES` in `scripts/lib/sub-pages-data.js`
-8. Add its relationships (leadsTo / pairs / combinesWith) to `COMMAND_RELATIONSHIPS` in the same file
-9. Add the same category entry to `site/scripts/data.js` `commandCategories` and `commandProcessSteps` (for the homepage carousel)
-10. Add symbol + number to `commandSymbols` and `commandNumbers` in `site/scripts/components/framework-viz.js` (periodic table)
-11. Optional: write an editorial wrapper at `site/content/skills/<command>.md` with a short `tagline` and expanded body (When to use it / How it works / Try it / Pitfalls)
-
-The build system counts commands from the router table automatically. Update the command count in **all** of these locations when the total changes:
-
-- `site/pages/index.astro` — meta descriptions, hero box, section lead
-- `/cheatsheet` redirects to `/docs` (no standalone page)
-- `README.md` — intro, command count, commands table
-- `NOTICE.md` — command count
-- `AGENTS.md` — intro command count
-- `.claude-plugin/plugin.json` — description
-- `.claude-plugin/marketplace.json` — metadata description + plugin description
-
-The build validator (`generateCounts` in `scripts/build.js`) checks these files for stale numeric counts and fails the build if any disagree with the router table.
-
-## Adding editorial content for existing commands
-
-Editorial files live at `site/content/skills/<command>.md` and have a `tagline` frontmatter plus a body with the standard four sections:
-
-- **When to use it** — the specific scenarios this command owns
-- **How it works** — the internal process, phases, or approach
-- **Try it** — one or two concrete examples with expected output
-- **Pitfalls** — real failure modes, with alternatives to reach for instead
-
-The tagline is used by UI surfaces (magazine spread, docs cards) that need a short human-friendly label. The long description in `command-metadata.json` stays optimized for auto-trigger keyword matching in the AI harness.
-
-Every command should have an editorial file eventually, but the build does not require one: commands without editorials fall back to the frontmatter description.
-
-## Adding or modifying anti-pattern detection rules
-
-`cli/engine/detect-antipatterns.mjs` is the source of truth for the rule engine. It powers the CLI, the public-site overlay, the Chrome extension, and the homepage rule count. Five places stay in sync:
-
-| Where | How it stays in sync |
-|---|---|
-| `cli/engine/detect-antipatterns.mjs` (`ANTIPATTERNS` array + `checkXxx` logic) | Hand-edited |
-| `cli/engine/detect-antipatterns-browser.js` | `bun run build:browser` |
-| `extension/detector/detect.js` + `extension/detector/antipatterns.json` | `bun run build:extension` |
-| `site/public/js/generated/counts.js` (`DETECTION_COUNT`) | `bun run build` |
-| `skill/SKILL.md` and `reference/*.md` | Hand-edited if the rule introduces new design guidance |
-
-Always run all three builds and the test suite after a rule change:
-
-```bash
-bun run build && bun run build:browser && bun run build:extension && bun run test
-```
-
-### TDD order (non-negotiable)
-
-1. **Fixture** at `tests/fixtures/antipatterns/{rule-id}.html` with two columns (should-flag / should-pass), each case identified by a unique heading. Cover ≥4 flag cases and ≥5 false-positive shapes. Use **explicit pixel dimensions in CSS** because jsdom does no layout.
-2. **Failing test** in `tests/detect-antipatterns-fixtures.test.mjs` using the snippet-substring pattern (regex `/"([^"]+)"/` against `SHOULD_FLAG` / `SHOULD_PASS` lists). Run it and watch it fail before implementing.
-3. **Rule entry** in the `ANTIPATTERNS` array: `id`, `category` (`slop` for AI tells, `quality` for real design or a11y issues), `name`, `description`, optional `skillSection` and `skillGuideline`.
-4. **Pure check function** `checkXxx(opts)` returning `[{ id, snippet }]`. No DOM access in the pure function.
-5. **Two adapters**: `checkElementXxxDOM(el)` for the browser (`getComputedStyle` + `getBoundingClientRect`) and `checkElementXxx(el, tag, window)` for jsdom (`parseFloat(style.width)` instead of layout). Wire **both** into **both** element loops in `cli/engine/detect-antipatterns.mjs` — the browser loop (~line 1837) and the jsdom loop in `detectHtml` (~line 2058). Forgetting one is the most common mistake; symptom is "test passes, live page silent" or vice versa.
-6. **Verify on a live page**: `http://localhost:3000/fixtures/antipatterns/{rule-id}.html` and the homepage (no false positives). The two adapter paths can disagree, so manual browser checks catch what the fixture test can't.
-
-### Conventions and jsdom gotchas
-
-- **Snippet format**: wrap the identifying heading text in straight double quotes (e.g. `'icon tile above h3 "Lightning Fast"'`) so the fixture test can extract it. For rules not anchored to a heading, pick another stable identifier.
-- **jsdom doesn't lay out**: `getBoundingClientRect()` returns 0×0. Read `parseFloat(style.width)` and `parseFloat(style.height)` from explicit CSS instead.
-- **`background:` shorthand isn't decomposed in jsdom**: use the existing `resolveBackground()` and `resolveGradientStops()` helpers (~line 631 / 670).
-- **Computed colors aren't normalized in jsdom**: `parseGradientColors()` handles both hex and rgb forms.
-
-Reference rules to copy from: `side-tab` (border, ~line 312), `low-contrast` (color + gradient, ~line 339), `icon-tile-stack` (sibling relationship, ~line 425), `flat-type-hierarchy` (page-level, ~line 1080).
-
-## Evals Framework (separate private repo)
-
-The eval framework lives in a separate private repo at `~/code/impeccable-evals/`. It measures whether the `/impeccable` skill improves or harms AI-generated frontend design by running the same brief through a model with and without the skill loaded.
-
-**If you're picking up eval work, switch to that repo and read its `AGENT.md` first.** It captures model choices, sample size policy, lessons learned, common workflows, and gotchas.
-
-```bash
-cd ~/code/impeccable-evals
-bun run serve # dashboard on http://localhost:8723
-```
-
-The eval runners read this repo's skill from `../impeccable/skill/` and staged provider skills from `../impeccable/build/_data/dist/*`. Run `bun run build` in this repo before an eval sweep if you want the Claude/Gemini staged skills to reflect your latest edits.
-
-### After structural skill changes, update `inline-skill.ts` in the evals repo
-
-The harness inlines `SKILL.md` into the system prompt for "skill-on", stripping sections irrelevant to an API-driven craft run. The stripped list in `runner/inline-skill.ts` needs to stay in sync with `SKILL.md`'s top-level `##` headings. As of v3.0, it should strip `## Setup (non-optional)` (was `## Context Gathering Protocol`), `## Commands` (was `## Command Router`), and `## Pin / Unpin`. Keep `## Shared design laws`. If you add or rename a top-level section, update the strip list there.
@@ -1,297 +0,0 @@
----
-name: Impeccable
-description: Warm-paper editorial sanctuary — committed serif display, one decisive magenta, flat surfaces at rest.
-
-# Colors use OKLCH per `The OKLCH-Only Rule` in §2. Stitch's linter validates
-# hex sRGB only, so it will warn on these entries — deliberate trade for one
-# source of truth and full wide-gamut fidelity. Our own parser accepts strings.
-colors:
- editorial-magenta: "oklch(60% 0.25 350)"
- editorial-magenta-deep: "oklch(52% 0.25 350)"
- warm-ash-cream: "oklch(96% 0.005 350)"
- crisp-paper-white: "oklch(98% 0 0)"
- deep-graphite: "oklch(10% 0 0)"
- soft-charcoal: "oklch(25% 0 0)"
- mid-ash: "oklch(55% 0 0)"
- paper-mist: "oklch(92% 0 0)"
- magenta-whisper: "oklch(60% 0.25 350 / 0.15)"
- magenta-veil: "oklch(60% 0.25 350 / 0.25)"
-
-typography:
- display:
- fontFamily: "Cormorant Garamond, Georgia, serif"
- fontSize: "clamp(2.5rem, 7vw, 4.5rem)"
- fontWeight: 300
- lineHeight: 1
- headline:
- fontFamily: "Cormorant Garamond, Georgia, serif"
- fontSize: "clamp(1.75rem, 4vw, 2.5rem)"
- fontWeight: 400
- lineHeight: 1.2
- title:
- fontFamily: "Cormorant Garamond, Georgia, serif"
- fontSize: "clamp(1.125rem, 2.5vw, 1.75rem)"
- fontWeight: 400
- lineHeight: 1.3
- body:
- fontFamily: "Instrument Sans, system-ui, sans-serif"
- fontSize: "1rem"
- fontWeight: 400
- lineHeight: 1.6
- body-lead:
- fontFamily: "Instrument Sans, system-ui, sans-serif"
- fontSize: "1.0625rem"
- fontWeight: 400
- lineHeight: 1.65
- supporting:
- fontFamily: "Instrument Sans, system-ui, sans-serif"
- fontSize: "0.875rem"
- fontWeight: 400
- lineHeight: 1.6
- label:
- fontFamily: "Instrument Sans, system-ui, sans-serif"
- fontSize: "0.9rem"
- fontWeight: 500
- letterSpacing: "0.05em"
- micro-label:
- fontFamily: "Instrument Sans, system-ui, sans-serif"
- fontSize: "0.6875rem"
- fontWeight: 500
- letterSpacing: "0.1em"
- mono:
- fontFamily: "Space Grotesk, monospace"
- fontSize: "0.75rem"
- fontWeight: 400
-
-rounded:
- none: "0"
- sm: "4px"
- md: "8px"
- lg: "12px"
- xl: "16px"
-
-spacing:
- xs: "8px"
- sm: "16px"
- md: "24px"
- lg: "32px"
- xl: "48px"
- "2xl": "80px"
- "3xl": "120px"
-
-components:
- button-primary:
- backgroundColor: "{colors.deep-graphite}"
- textColor: "{colors.crisp-paper-white}"
- typography: "{typography.label}"
- rounded: "{rounded.none}"
- padding: "16px 48px"
- button-primary-hover:
- backgroundColor: "{colors.editorial-magenta}"
- textColor: "{colors.crisp-paper-white}"
- input-text:
- backgroundColor: "transparent"
- textColor: "{colors.deep-graphite}"
- rounded: "{rounded.sm}"
- padding: "8px 12px"
- card:
- backgroundColor: "{colors.warm-ash-cream}"
- textColor: "{colors.deep-graphite}"
- rounded: "{rounded.md}"
- padding: "24px"
- card-feature:
- backgroundColor: "{colors.crisp-paper-white}"
- textColor: "{colors.deep-graphite}"
- rounded: "{rounded.lg}"
- padding: "48px"
- nav-link:
- textColor: "{colors.deep-graphite}"
- typography: "{typography.body}"
- nav-link-hover:
- textColor: "{colors.editorial-magenta}"
----
-
-# Design System: Impeccable
-
-## 1. Overview: The Editorial Sanctuary
-
-**Creative North Star: "The Editorial Sanctuary"**
-
-The Impeccable site reads more like a printed design publication than a SaaS landing page. Committed typography, generous breathing room, and a single decisive accent that cuts through warm paper. The interface feels **considered, unhurried, and expert** — the work of someone who has made the calls a thousand times and has zero interest in chasing the current AI-tool aesthetic.
-
-The aesthetic philosophy is **restraint in service of craft**. Every element earns its place. Nothing is decorative without function. The palette is dominated by warm paper tones with one vibrant voice. The typography pairs a stately italic serif with a clean neutral sans. Motion is reserved for moments that actually communicate state. The site is the demo — it must pass the same anti-pattern audit it asks its users to run on their own work.
-
-This system explicitly rejects the AI-tool visual vocabulary that surrounds the product: dark mode with purple gradients, neon accents, glassmorphism, glowing cyan-on-black, SaaS hero-metric layouts, and identical-card feature grids. When in doubt, do less than a marketing site would, more than a portfolio would.
-
-**Key Characteristics:**
-- Warm off-white paper tones with an almost-imperceptible magenta tint for subliminal palette cohesion.
-- A single decisive magenta accent used on no more than 10% of any screen. Its rarity is the point.
-- Italic serif for display type; clean neutral sans for body at 1.6+ line-height.
-- Sharp, uppercase, letter-tracked primary CTAs — no rounded-rectangle-with-drop-shadow defaults.
-- Flat surfaces at rest. Shadows appear only as a response to state (hover, elevation, focus).
-- Asymmetric magazine-scale spacing; intentionally skips the 4px step.
-
-## 2. Colors: The Warm-Paper Palette
-
-A two-chord palette: warm paper neutrals carrying a near-invisible magenta tint, plus one decisive accent in the same hue family. No secondary or tertiary accents in the core system — the restraint is doctrinal.
-
-### Primary
-- **Editorial Magenta** (oklch(60% 0.25 350)): The one vibrant voice. Primary CTAs, active navigation states, live-state indicators, rare editorial emphasis. Never used as a gradient, never as a background wash, never as text fill. Rarity is the design choice.
-
-### Neutral
-- **Warm Ash Cream** (oklch(96% 0.005 350)): Primary page background. Near-white with a near-imperceptible magenta tint that creates subconscious cohesion with Editorial Magenta. Used on `body` and standard surfaces.
-- **Crisp Paper White** (oklch(98% 0 0)): Pure background. Used for inverted text moments (white-on-dark CTAs) and surfaces needing maximum contrast. Almost never the page background — too cold alone.
-- **Deep Graphite** (oklch(10% 0 0)): Primary text for body copy and headlines. Softer than pure black, reads as confident-but-not-aggressive on warm paper. Background of the primary CTA.
-- **Soft Charcoal** (oklch(25% 0 0)): Secondary text — taglines, hook paragraphs, supporting copy. Clearly subordinate to Deep Graphite without being washed out.
-- **Mid Ash** (oklch(55% 0 0)): Tertiary text — micro-labels, captions, meta lines, "works with" labels. At small sizes reads as intentionally recessed metadata.
-- **Paper Mist** (oklch(92% 0 0)): Hairline borders, section dividers, the barely-visible structural seams.
-
-### Accent Alpha Variants
-- **Editorial Magenta Deep** (oklch(52% 0.25 350)): Hover/active state for Editorial Magenta. Small darkening, confirms interaction without shouting.
-- **Magenta Whisper** (oklch(60% 0.25 350 / 0.15)): Glow backdrop under accent elements on hover (diffuse shadows only), subtle selection highlights.
-- **Magenta Veil** (oklch(60% 0.25 350 / 0.25)): Slightly stronger translucent tint for focus rings and emphasis shells.
-
-### Command Category Tints (fenced — do not extend)
-A separate six-tint vocabulary used exclusively to color-code the periodic-table visualization of impeccable's 23 commands. These tints predate the OKLCH system and live in one component. **Do not extend this vocabulary elsewhere.**
-
-- **Create** (bg `#fdf2f8` / border `#ec4899` / text `#be185d`)
-- **Evaluate** (bg `#fdf4ff` / border `#d946ef` / text `#a21caf`)
-- **Refine** (bg `#eff6ff` / border `#3b82f6` / text `#1d4ed8`)
-- **Simplify** (bg `#fffbeb` / border `#f59e0b` / text `#b45309`)
-- **Harden** (bg `#f0fdf4` / border `#22c55e` / text `#15803d`)
-- **System** (bg `#f5f5f4` / border `#78716c` / text `#44403c`)
-
-### Named Rules
-
-**The One Voice Rule.** Editorial Magenta is the only vibrant color in the system. No supporting accent is added, ever, no matter how much a layout "wants" a second color. If a second emphasis point is needed, use scale or weight, never a second hue.
-
-**The Paper-Not-White Rule.** The page background is Warm Ash Cream, never Crisp Paper White. Pure white is reserved for specific inverted surfaces. Warmth is load-bearing — without it, the site reads as generic and the decisive magenta reads as abrasive rather than decisive.
-
-**The OKLCH-Only Rule.** All new colors must be declared in OKLCH. Legacy hex values exist only in the fenced Command Category Tints. Do not introduce new hex-declared colors into the system.
-
-## 3. Typography: The Italic-and-Ink Voice
-
-**Display Font:** Cormorant Garamond (with Georgia fallback)
-**Body Font:** Instrument Sans (with system-ui fallback)
-**Label/Mono Font:** Space Grotesk (used as a geometric mono, not for code blocks)
-
-**Character:** The display face is a refined transitional serif used in its **italic** cut — stately without being stuffy, drawing on long-form editorial headline traditions. The body face is a clean neutral sans with subtle geometric warmth, chosen to set long paragraphs without visual overhead. The "mono" is a contemporary grotesque reserved for small labels and metadata where a machine-adjacent feel reinforces the command-line product story.
-
-### Hierarchy
-
-- **Display** (display family, weight 300, italic, clamp(2.5rem, 7vw, 4.5rem), line-height 1): Hero title only. The light weight + italic cursive reads as an author signature rather than a marketing headline.
-- **Headline** (display family, weight 400, clamp(1.75rem, 4vw, 2.5rem), line-height 1.2): Section headings. Larger editorial moments.
-- **Title** (display family, weight 400, italic, clamp(1.125rem, 2.5vw, 1.75rem), line-height 1.3): Hero tagline / section leads. A quieter second display voice.
-- **Body** (body family, weight 400, 1rem, line-height 1.6): Paragraph copy. Capped at 65–75ch for readability.
-- **Body Lead** (body family, weight 400, 1rem–1.0625rem, line-height 1.6–1.65): The one or two "lead" paragraphs on each page. Slightly relaxed leading.
-- **Supporting** (body family, weight 400, 0.875rem, line-height 1.6): Captions, footnotes, supporting context.
-- **Label** (body family, weight 500, 0.9rem, `text-transform: uppercase`, `letter-spacing: 0.05em`): CTA labels. Short, declarative.
-- **Micro-Label** (body family, weight 500, 0.625–0.6875rem, `text-transform: uppercase`, `letter-spacing: 0.1em`): "Works with", "What's Included", "v3.0 Changelog".
-- **Monospace Meta** (mono family, weight 400–500, 0.6875–0.8125rem): Command names in inline prose, periodic-table tile labels.
-
-### Named Rules
-
-**The Italic-Is-Voice Rule.** Italic is used as a voice choice for display type, not as emphasis within body copy. Body emphasis is carried by weight or by swapping to the mono family (see `<em>` in command menus). Treating italic as emphasis inside paragraphs dilutes the display voice.
-
-**The 1.6 Leading Rule.** Body line-height is 1.6 everywhere. Not 1.5, not 1.7, not "relaxed". This is the load-bearing readability decision — when the site reads as calm and editorial, it's 1.6 doing the work.
-
-**The Fluid-Headlines-Only Rule.** Headings use `clamp()` fluid sizing. Body copy uses fixed `rem` values. Fluid body sizes look clever and feel wrong — they make line-lengths wander off spec.
-
-## 4. Elevation
-
-Flat by default. Depth is conveyed through **state response**, not structural shadow. Surfaces rest on a single tonal layer (Warm Ash Cream); shadows appear only when an element is hovered, deliberately lifted, or requires ambient separation from a busy area.
-
-### Shadow Vocabulary
-
-- **Soft Hover Lift** (`0 4px 24px -4px rgba(0,0,0,0.12), 0 1px 3px rgba(0,0,0,0.06)`): The default hover response on cards and interactive surfaces. Diffuse, offset downward.
-- **Lifted Card** (`0 20px 40px rgba(0,0,0,0.08)`): Deliberately elevated content (featured cards, install blocks). Low alpha — never reads as dark.
-- **Accent Glow** (`0 20px 60px var(--color-accent-dim)`): Magenta-tinted ambient shadow under the one or two moments that should feel magnetic. Used sparingly — this is the "rare ingredient" of the shadow vocabulary.
-- **Tooltip / Popover** (`0 0 20px rgba(0,0,0,0.15)` or `0 2px 8px rgba(0,0,0,0.1)`): Tight shadow for small floating UI.
-
-### Named Rules
-
-**The Flat-By-Default Rule.** Surfaces are flat at rest. If you find yourself adding a shadow to a non-interactive, non-elevated element, stop — you're reaching for Material Design muscle memory. Use a hairline Paper Mist border instead, or no articulation at all.
-
-**The Low-Alpha Rule.** Every shadow in the system uses ≤0.15 alpha on its strongest blur. Higher alphas read as 2014 Material Design drop shadows — an immediate tell that the design wasn't considered.
-
-**The Tinted-Shadow-Only-For-Accent Rule.** Neutral shadows (black alpha) for structure. Colored (magenta-dim) shadows only for the deliberate accent-glow moments. Never tint shadows for decorative effect.
-
-## 5. Components
-
-### Buttons
-
-- **Shape:** Flat and squared by default (`border-radius: 0`). Sharp corners are an explicit editorial choice — the site rejects the rounded-rectangle-with-drop-shadow default that marks most AI-adjacent marketing pages.
-- **Primary (hero-cta-combined):** Deep Graphite background, Crisp Paper White text. Padding 16px / 48px (`--spacing-sm` / `--spacing-xl`). Uppercase, `letter-spacing: 0.05em`, weight 500. No border, no shadow at rest.
-- **Hover:** `transform: translateY(-2px)` and background shifts to Editorial Magenta. Transition 200ms linear ease. A small confident step up, never a bounce.
-- **Focus:** Browser-default focus ring combined with the hover treatment. Visible keyboard focus is required.
-- **Secondary:** Inline text link in body copy, weight 500, hover shifts to Editorial Magenta. **No boxed secondary button exists in the system** — the site avoids the "stack of equal-weight CTAs" pattern entirely.
-- **Chip (picker overlay):** Radius 3–5px, small padding, mono-family label. Used in the live-mode action selector.
-
-### Cards & Containers
-
-- **Corner Style:** Controlled vocabulary — 4px (chips / inline callouts), 8px (standard cards and card-CTAs), 12px (feature cards, install blocks), 16px (large content frames). No single "rounded-lg" default. Radius is picked per component weight.
-- **Background:** Warm Ash Cream or Crisp Paper White depending on layering. Deeper nested surfaces may lift to Paper Mist as a near-imperceptible tone shift.
-- **Shadow:** Flat at rest — see Elevation for the shadow vocabulary that applies on hover/lift.
-- **Border:** Hairline 1px in Paper Mist when a surface needs articulation without shadow.
-- **Internal Padding:** 16–32px for typical cards; large editorial frames 48px+. Padding matches visual weight, not applied uniformly.
-
-### Inputs / Fields
-
-The site is primarily editorial, so inputs are minimal:
-
-- **Email / text field:** Radius 4–6px, hairline Paper Mist border, transparent background. Focus state shifts border to Editorial Magenta with a Magenta Whisper backdrop glow.
-- **Combobox / select (filter controls):** Same stroke vocabulary, smaller padding, chevron glyph in Mid Ash.
-- **No custom checkbox/radio styling** beyond what the live-mode command picker needs.
-
-### Navigation
-
-- **Site Header:** 62px compact bar, left-aligned brand lockup (monochrome mark + wordmark), right-aligned link cluster.
-- **Typography:** Body family, weight 500, 0.9–1rem. Normal case — the header is readable prose, not a set of signals.
-- **Default State:** Deep Graphite on Warm Ash Cream.
-- **Hover / Active:** Smooth color transition to Editorial Magenta, 200ms. No underline bar at rest; if an active indicator is needed, a thin accent-colored underline appears.
-- **Mobile:** Collapses to an icon-triggered drawer when horizontal space is insufficient.
-
-### Periodic Table of Commands (signature component)
-
-A distinctive custom element worth documenting: the 23 commands are laid out as a periodic-table grid of 56×64px tiles, each with a category tint background, category-colored border, atomic number in the top-left (mono family, 7px), a symbol in the center (display family, weight 500, 20px), and a command label in mono below. Hover lifts the tile 2px with a category-colored shadow. Tiles are the one place where the Category Tint vocabulary (see Colors) is used on a colored surface rather than as a text accent.
-
-### Layout & Spacing (fold from spec-absent Layout section)
-
-- **Max width:** Content blocks cap at 900px (`--width-content`); page-level containers at 1400px (`--width-max`). Prose further constrained to 65–75ch.
-- **Spacing scale:** 8 / 16 / 24 / 32 / 48 / 80 / 120px (`--spacing-xs` through `--spacing-3xl`). The 4px step is deliberately omitted — this is an editorial scale, not an app-UI scale.
-- **Rhythm:** 80–120px between top-level sections, 24–48px between content groups within a section, 6–16px inside tight clusters.
-- **Grid:** No traditional column grid. Hero layouts are asymmetric two-column splits. Feature sections use `repeat(auto-fit, minmax(280px, 1fr))` rather than breakpoint-driven columns.
-- **Motion:** 150ms for color/opacity, 300–400ms for transforms, 600–1200ms for orchestrated entrances. All use `--ease-out` (`cubic-bezier(0.16, 1, 0.3, 1)`) or `--ease-out-quint`. `prefers-reduced-motion` collapses every non-essential transition.
-
-## 6. Do's and Don'ts
-
-### Do:
-
-- **Do** treat Warm Ash Cream (not Crisp Paper White) as the default page background. Warmth is load-bearing — see The Paper-Not-White Rule.
-- **Do** use Editorial Magenta on ≤10% of any given screen. Scarcity is what makes it read as decisive rather than noisy — see The One Voice Rule.
-- **Do** set all new colors in OKLCH. Hex is for the fenced Command Category Tints only.
-- **Do** use italic display type as a voice, not as emphasis inside paragraphs. Body emphasis is carried by weight.
-- **Do** use `clamp()` fluid sizing for headings; use fixed `rem` for body — see The Fluid-Headlines-Only Rule.
-- **Do** keep the primary CTA sharp and squared. `border-radius: 0`, uppercase, letter-tracked. This is the editorial signature.
-- **Do** use `--ease-out` (`cubic-bezier(0.16, 1, 0.3, 1)`) or `--ease-out-quint` on transitions. Expo-out only.
-- **Do** leave surfaces flat at rest. Reach for shadows only on hover or for deliberate elevation — see The Flat-By-Default Rule.
-- **Do** respect `prefers-reduced-motion` on every animation.
-- **Do** cap body line length at 65–75ch via `max-width`.
-
-### Don't:
-
-- **Don't** use pure black (#000) or pure white (#fff). Always the tinted neutrals (Deep Graphite / Warm Ash Cream / Crisp Paper White).
-- **Don't** use `border-left` or `border-right` greater than 1px as a colored stripe on cards, list items, callouts, or alerts. Ever. This is the single most recognizable AI-dashboard tell.
-- **Don't** use `background-clip: text` with a gradient. Gradient text is banned across the site. If you want emphasis, use weight or size, never gradient fill.
-- **Don't** default to dark mode. The site is light mode because editorial reading is a light-mode activity. Dark mode with glowing accents is the AI-tool aesthetic Impeccable exists to replace.
-- **Don't** use glassmorphism (blurred translucent cards, glass borders, glow backgrounds as decoration). It is on PRODUCT.md's explicit anti-reference list.
-- **Don't** add a second accent color. If a layout "needs" a second emphasis point, use scale or weight, not hue.
-- **Don't** use rounded rectangles with generic drop shadows. That's the "could be any AI output" fingerprint.
-- **Don't** use bounce or elastic easing. Real objects decelerate smoothly — expo-out is the signature.
-- **Don't** animate layout properties (`width`, `height`, `padding`, `margin`). Use `transform` and `opacity` only.
-- **Don't** nest cards inside cards. Flatten the hierarchy.
-- **Don't** use identical card grids (same-sized cards with icon + heading + text, repeated endlessly).
-- **Don't** use the hero-metric layout template (big number + small label + supporting stats + gradient accent). SaaS cliché.
-- **Don't** extend the Command Category Tints vocabulary. Those hex tints are scoped to the periodic-table viz.
-- **Don't** hedge in UI copy. "Maybe consider" and "could be helpful" are banned in-product — match PRODUCT.md's expert-decisive voice.
-- **Don't** introduce a new spacing token outside the 8/16/24/32/48/80/120 scale. If you need a specific pixel gap, use a literal value rather than polluting the token scale.
@@ -1,206 +0,0 @@
-# Developer Guide
-
-Documentation for contributors to Impeccable.
-
-## Architecture
-
-The skill at `skill/` is transformed into provider-specific formats by a config-driven factory. Each provider is defined as a config object in `scripts/lib/transformers/providers.js` -- adding a new provider requires only a new config entry.
-
-For detailed harness capabilities (which frontmatter fields each supports, placeholder systems, directory structures), see [HARNESSES.md](HARNESSES.md).
-
-## Source Format
-
-### Skill (`skill/SKILL.md`)
-
-```yaml
----
-name: skill-name
-description: What this skill provides
-argument-hint: "[target]"
-user-invocable: true
-license: License info (optional)
-compatibility: Environment requirements (optional)
----
-
-Your skill instructions here...
-```
-
-**Frontmatter fields** (based on [Agent Skills spec](https://agentskills.io/specification)):
-- `name` (required): Skill identifier (1-64 chars, lowercase/numbers/hyphens)
-- `description` (required): What the skill provides (1-1024 chars)
-- `user-invocable` (optional): Boolean -- if `true`, the skill can be invoked as a slash command
-- `argument-hint` (optional): Hint shown during autocomplete (e.g., `[target]`, `[area (feature, page...)]`)
-- `license` (optional): License/attribution info
-- `compatibility` (optional): Environment requirements (1-500 chars)
-- `metadata` (optional): Arbitrary key-value pairs
-- `allowed-tools` (optional, experimental): Pre-approved tools list
-
-**Body placeholders** (replaced per-provider during build):
-- `{{model}}` -- Provider-specific model name (e.g., "Claude", "Gemini", "GPT")
-- `{{config_file}}` -- Provider-specific config file (e.g., "CLAUDE.md", ".cursorrules")
-- `{{ask_instruction}}` -- How to ask the user for clarification
-- `{{command_prefix}}` -- Slash command prefix (`/` for most, `$` for Codex)
-- `{{available_commands}}` -- Comma-separated list of user-invocable commands
-
-## Building
-
-### Prerequisites
-- Bun (fast JavaScript runtime and package manager)
-- No external dependencies required
-
-### Commands
-
-```bash
-# Build all provider formats
-bun run build
-
-# Clean dist folder
-bun run clean
-
-# Rebuild from scratch
-bun run rebuild
-```
-
-### What Gets Generated
-
-```
-source/ -> dist/
- skills/{name}/SKILL.md {provider}/{configDir}/skills/{name}/SKILL.md
-```
-
-Each provider gets its own output directory.
-
-## Build System Details
-
-The build system uses a factory pattern under `scripts/`:
-
-```
-scripts/
- build.js # Main orchestrator
- lib/
- utils.js # Frontmatter parsing, placeholder replacement, YAML generation
- zip.js # ZIP bundle generation
- transformers/
- factory.js # createTransformer() -- generates transformer functions from config
- providers.js # PROVIDERS config map -- one entry per provider
- index.js # Re-exports factory-generated transformer functions
-```
-
-### Adding a New Provider
-
-1. Add a placeholder config to `PROVIDER_PLACEHOLDERS` in `scripts/lib/utils.js`:
- ```javascript
- 'my-provider': {
- model: 'MyModel',
- config_file: 'CONFIG.md',
- ask_instruction: 'ask the user directly to clarify.',
- command_prefix: '/'
- }
- ```
-
-2. Add a provider config to `PROVIDERS` in `scripts/lib/transformers/providers.js`:
- ```javascript
- 'my-provider': {
- provider: 'my-provider',
- configDir: '.my-provider',
- displayName: 'My Provider',
- frontmatterFields: ['user-invocable', 'argument-hint', 'license'],
- }
- ```
-
-3. Run `bun run build` -- the provider is automatically picked up by the build loop.
-
-4. Update `HARNESSES.md` with the provider's capabilities.
-
-### Provider Config Options
-
-| Field | Description |
-|-------|-------------|
-| `provider` | Key for output directory and placeholder lookup |
-| `configDir` | Dot-directory name (e.g., `.claude`) |
-| `displayName` | Human-readable name for build logs |
-| `frontmatterFields` | Which optional fields to emit (see `factory.js` FIELD_SPECS) |
-| `bodyTransform` | Optional `(body, skill) => body` function for post-processing |
-| `placeholderProvider` | Override which PROVIDER_PLACEHOLDERS key to use (for variants sharing config) |
-
-### Key Functions
-
-- `createTransformer(config)`: Factory that returns a transformer function from a provider config
-- `parseFrontmatter()`: Extracts YAML frontmatter and body from SKILL.md files
-- `readSourceFiles()`: Reads `skill/SKILL.md` plus its `reference/` and `scripts/` siblings
-- `replacePlaceholders()`: Substitutes `{{model}}`, `{{config_file}}`, etc. per provider
-- `generateYamlFrontmatter()`: Serializes objects to YAML frontmatter (auto-quotes values starting with `[` or `{`)
-
-## Best Practices
-
-### Skill Writing
-
-1. **Focused scope**: One clear domain per skill
-2. **Clear descriptions**: Make purpose obvious
-3. **Clear instructions**: LLM should understand exactly what to do
-4. **Include examples**: Where they clarify intent
-5. **State constraints**: What NOT to do as clearly as what to do
-6. **Test across providers**: Verify it works in multiple contexts
-
-## Reference Documentation
-
-- [Agent Skills Specification](https://agentskills.io/specification) - Open standard
-- [HARNESSES.md](HARNESSES.md) - Provider capabilities matrix
-- [Cursor Skills](https://cursor.com/docs/context/skills)
-- [Claude Code Skills](https://code.claude.com/docs/en/skills)
-- [Gemini CLI Skills](https://geminicli.com/docs/cli/skills/)
-- [Codex CLI Skills](https://developers.openai.com/codex/skills/)
-- [VS Code Copilot Skills](https://code.visualstudio.com/docs/copilot/customization/agent-skills)
-- [Kiro Skills](https://kiro.dev/docs/skills/)
-- [OpenCode Skills](https://opencode.ai/docs/skills/)
-- [Pi Skills](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/skills.md)
-- [Qoder Skills](https://docs.qoder.com/extensions/skills)
-
-## Repository Structure
-
-```
-impeccable/
- source/ # Edit these! Source of truth
- skills/ # Skill definitions
- frontend-design/
- SKILL.md
- reference/*.md # Domain-specific references
- audit/SKILL.md
- polish/SKILL.md
- ...
- dist/ # Generated output (gitignored)
- scripts/
- build.js # Main orchestrator
- lib/
- utils.js # Shared utilities
- zip.js # ZIP generation
- transformers/
- factory.js # Config-driven transformer factory
- providers.js # Provider config map
- index.js # Re-exports
- tests/ # Bun test suite
- HARNESSES.md # Provider capabilities reference
- DEVELOP.md # This file
- README.md # User documentation
-```
-
-## Troubleshooting
-
-### Build fails with YAML parsing errors
-- Check frontmatter indentation (YAML is indent-sensitive)
-- Ensure `---` delimiters are on their own lines
-- Values starting with `[` or `{` are auto-quoted; other special YAML chars may need manual quoting
-
-### Output doesn't match expectations
-- Check the provider config in `scripts/lib/transformers/providers.js`
-- Verify source file has correct frontmatter structure
-- Run `bun run rebuild` to ensure clean build
-
-### Provider doesn't recognize the files
-- Check installation path for your provider
-- Verify file naming matches provider requirements
-- Consult [HARNESSES.md](HARNESSES.md) for provider-specific details
-
-## Questions?
-
-Open an issue or submit a PR!
@@ -1,97 +0,0 @@
-# Harness Skills Capabilities Reference
-
-Source of truth for what each AI coding harness supports in terms of agent skills.
-Used to inform provider configs in `scripts/lib/transformers/providers.js`.
-
-Last verified: 2026-04-28
-
-## Official Documentation
-
-| Harness | Docs URL |
-|---------|----------|
-| Claude Code | https://code.claude.com/docs/en/skills |
-| Cursor | https://cursor.com/docs/context/skills |
-| Gemini CLI | https://geminicli.com/docs/cli/skills/ |
-| Codex CLI | https://developers.openai.com/codex/skills |
-| GitHub Copilot (Agents) | https://code.visualstudio.com/docs/copilot/customization/agent-skills |
-| Kiro | https://kiro.dev/docs/skills/ |
-| OpenCode | https://opencode.ai/docs/skills/ |
-| Pi | https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/skills.md |
-| Qoder | https://docs.qoder.com/extensions/skills |
-| Trae | TBD (no official skills docs found yet) |
-| Rovo Dev | https://support.atlassian.com/rovo/docs/extend-rovo-dev-cli-with-agent-skills |
-
-## Spec Compliance
-
-All harnesses follow the [Agent Skills specification](https://agentskills.io/specification) to varying degrees. The spec defines these frontmatter fields: `name`, `description`, `license`, `compatibility`, `metadata`, `allowed-tools`.
-
-Provider-specific extensions beyond the spec: `user-invocable`, `argument-hint`, `disable-model-invocation`, `allowed-tools` (extended syntax), `model`, `effort`, `context`, `agent`, `hooks`, `subtask`, `mcp`.
-
-## Frontmatter Support
-
-Fields marked with * are spec-standard. Others are provider extensions.
-
-| Field | Claude Code | Cursor | Gemini | Codex | Copilot | Kiro | OpenCode | Pi | Qoder | Rovo Dev |
-|-------|:-----------:|:------:|:------:|:-----:|:-------:|:----:|:--------:|:--:|:-----:|:--------:|
-| `name`* | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
-| `description`* | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
-| `license`* | Yes | Yes | Ignored | No | Yes | Yes | Yes | Yes | Yes | Yes |
-| `compatibility`* | Yes | Yes | Ignored | No | Yes | Yes | Yes | Yes | Yes | Yes |
-| `metadata`* | Yes | Yes | Ignored | No | Yes | Yes | Yes | Yes | Yes | Yes |
-| `allowed-tools`* | Yes | No | Ignored | No | No | No | Yes | Yes | Yes | Yes |
-| `user-invocable` | Yes | No | No | No | Yes | No | Yes | No | Yes | Yes |
-| `argument-hint` | Yes | No | No | No | Yes | No | Yes | No | Yes | Yes |
-| `disable-model-invocation` | Yes | Yes | No | No | Yes | No | Yes | Yes | TBD | TBD |
-| `model` | Yes | No | No | No | No | No | Yes | No | No | No |
-| `effort` | Yes | No | No | No | No | No | No | No | No | No |
-| `context` | Yes | No | No | No | No | No | No | No | No | No |
-| `agent` | Yes | No | No | No | No | No | Yes | No | No | No |
-| `hooks` | Yes | No | No | No | No | No | No | No | No | No |
-
-Notes:
-- Gemini CLI validates only `name` and `description`; other spec fields are parsed but ignored.
-- Codex CLI uses a separate `agents/openai.yaml` sidecar for skill metadata (icons, branding, MCP tools, invocation control). Native Codex custom agents are separate TOML files under `.codex/agents/` or `~/.codex/agents/`.
-- Kiro recognizes `user-invocable` and `disable-model-invocation` per community reports but does not formally document them.
-- Unknown fields are silently ignored by all harnesses.
-
-## Skill Directory Structure
-
-| Harness | Native directory | Also reads |
-|---------|-----------------|------------|
-| Claude Code | `.claude/skills/` | - |
-| Cursor | `.cursor/skills/` | `.agents/skills/`, `.claude/skills/` |
-| Gemini CLI | `.gemini/skills/` | `.agents/skills/` |
-| Codex CLI | `.agents/skills/` (primary) | - |
-| GitHub Copilot | `.github/skills/` | `.agents/skills/`, `.claude/skills/` |
-| Kiro | `.kiro/skills/` | - |
-| OpenCode | `.opencode/skills/` | `.agents/skills/`, `.claude/skills/` |
-| Pi | `.pi/skills/` | `.agents/skills/` |
-| Qoder | `.qoder/skills/` | `~/.qoder/skills/` (user-level) |
-| Trae China | `.trae-cn/skills/` | TBD |
-| Trae International | `.trae/skills/` | TBD |
-| Rovo Dev | `.rovodev/skills/` | `~/.rovodev/skills/` (user-level) |
-
-All harnesses support the `{skill-name}/SKILL.md` directory structure with optional `reference/`, `scripts/`, and `assets/` subdirectories.
-
-## Native Subagent Directory Structure
-
-| Harness | Native directory | File format |
-|---------|------------------|-------------|
-| Claude Code | `.claude/agents/` | Markdown with YAML frontmatter |
-| Codex CLI | `.codex/agents/` | TOML |
-
-Impeccable keeps canonical agent prompts under `skill/agents/` and emits provider-native files only for harnesses with documented subagent formats.
-
-## Placeholder / Variable Substitution
-
-Claude Code supports runtime variable substitution directly in SKILL.md bodies: `$ARGUMENTS`, `$0`-`$N`, `${CLAUDE_SKILL_DIR}`, `${CLAUDE_SESSION_ID}`. No other harness supports substitution in skills.
-
-Some harnesses have separate "custom commands" systems (distinct from skills) with their own substitution:
-
-| Harness | Command system | Substitution syntax |
-|---------|---------------|-------------------|
-| Gemini CLI | `.gemini/commands/` (TOML) | `{{args}}`, `!{shell}`, `@{file}` |
-| Codex CLI | `.codex/prompts/` | `$ARGNAME` |
-| OpenCode | `.opencode/commands/` | `$ARGUMENTS`, `$1`-`$N`, `` !`shell` `` |
-
-Our build system handles cross-provider placeholders at compile time via `replacePlaceholders()` for `{{model}}`, `{{config_file}}`, `{{ask_instruction}}`, and `{{available_commands}}`.
@@ -1,191 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to the Licensor for inclusion in the Work by the copyright
- owner or by an individual or Legal Entity authorized to submit on
- behalf of the copyright owner. For the purposes of this definition,
- "submitted" means any form of electronic, verbal, or written
- communication sent to the Licensor or its representatives, including
- but not limited to communication on electronic mailing lists, source
- code control systems, and issue tracking systems that are managed by,
- or on behalf of, the Licensor for the purpose of discussing and
- improving the Work, but excluding communication that is conspicuously
- marked or otherwise designated in writing by the copyright owner as
- "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- Copyright 2025 Paul Bakaus
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
@@ -1,25 +0,0 @@
-# Notice
-
-Impeccable
-Copyright 2025-2026 Paul Bakaus
-
-## Anthropic frontend-design Skill
-
-The `impeccable` skill in this project builds on Anthropic's original frontend-design skill.
-
-**Original work:** https://github.com/anthropics/skills/tree/main/skills/frontend-design
-**Original license:** Apache License 2.0
-**Copyright:** 2025 Anthropic, PBC
-
-This project extends the original with:
-- 7 domain-specific reference files (typography, color-and-contrast, spatial-design, motion-design, interaction-design, responsive-design, ux-writing)
-- 23 commands
-- Expanded patterns and anti-patterns
-
-## Typecraft Guide Skill
-
-The `typography.md` reference in this project incorporates a set of tactical additions merged in from ehmo's `typecraft-guide-skill` at the author's request: dark-mode weight/tracking compensation, `font-display: optional` vs `swap`, preload-critical-weight-only guidance, variable fonts for 3+ weights, `clamp()` max-to-min ratio bound, responsive measure/container coupling, `text-wrap: balance` / `pretty`, `font-optical-sizing: auto`, ALL-CAPS tracking quantification, and the paragraph-rhythm rule (space OR indent, never both).
-
-**Original work:** https://github.com/ehmo/typecraft-guide-skill
-**Original license:** see upstream repo
-**Author:** ehmo
@@ -1,46 +0,0 @@
-# Product
-
-## Register
-
-brand
-
-## Users
-
-Designers, product managers, and engineers who use AI coding tools (Cursor, Claude Code, Gemini CLI, Codex CLI, and others) and want better design output from their AI. They land on the site from GitHub, social media, or word of mouth, already aware that AI-generated UIs have quality problems. They're looking for a practical solution, not education about the problem.
-
-## Product Purpose
-
-Impeccable gives builders a shared design vocabulary with their AI, delivered as a plug-and-play skill that works in every major AI coding harness. Success is measured in two ways: (1) the user can steer AI output with design precision instead of vague prose, and (2) the AI produces interfaces that pass professional design review, not "looks like an AI made it" output.
-
-## Brand Personality
-
-Expert, opinionated, refined. Impeccable speaks with an authoritative design voice: confident taste, editorial quality, zero hedging. It's the design director in the room who knows exactly what's wrong and how to fix it. The tone is **direct** (no "maybe consider"), **specific** (no "improve the vibe"), and **rooted in craft** (no hype, no hedging).
-
-Three-word personality: **expert, decisive, editorial**.
-
-## Anti-references
-
-The site and brand must be the antithesis of everything Impeccable critiques. Specifically, avoid:
-
-- **Generic AI tool marketing**: dark mode with purple gradients, neon accents, glassmorphism, glowing particles, cyan-on-black.
-- **SaaS landing-page clichés**: hero-metric layouts, identical-card feature grids, sparkline decorations, "boost your productivity" copy.
-- **Hedging language**: "might", "could", "consider", "perhaps". Impeccable is opinionated — it picks a direction and commits.
-- **Educational framing**: this product is for people who already know they have a problem; we solve it, we don't teach it.
-- **Over-decoration**: every visual element must earn its place. No ornament for ornament's sake.
-
-## Design Principles
-
-1. **Practice what you preach.** The site must pass its own anti-pattern tests with flying colors. If we ship anything we'd flag in an audit, we've lost.
-2. **Show, don't tell.** Demonstrate design quality through execution, not through words about design quality. The site IS the demo.
-3. **Expert confidence.** Direct, opinionated, decisive. No hedging. Every assertion should sound like it comes from someone who has seen a thousand interfaces and knows what works.
-4. **Editorial over marketing.** Feels like a design publication (Eye Magazine, It's Nice That, A List Apart) rather than a SaaS landing page. Long-form reading, considered typography, breathing room.
-5. **Purposeful restraint.** Every element earns its place. Nothing decorative without function. Nothing included because "landing pages usually have that".
-
-## Accessibility & Inclusion
-
-Baseline: WCAG 2.1 AA on all pages. Key commitments:
-- Color contrast ratios verified with actual contrast checks, not eyeballing.
-- All interactive elements keyboard-navigable with visible focus states.
-- `prefers-reduced-motion` respected for every animation.
-- Semantic HTML first, ARIA as a supplement, never as a workaround.
-- Copy readable at an 8th-grade level; jargon only when precisely needed (design terms like "OKLCH", "chroma" are acceptable because they're the actual vocabulary users are here to learn).
@@ -1,263 +0,0 @@
-# Impeccable
-
-The vocabulary you didn't know you needed. 1 skill, 23 commands, and curated anti-patterns for impeccable frontend design.
-
-> **Quick start:** Visit [impeccable.style](https://impeccable.style) to download ready-to-use bundles.
-
-## Why Impeccable?
-
-Anthropic's [frontend-design](https://github.com/anthropics/skills/tree/main/skills/frontend-design) was the first widely-used design skill for Claude. Impeccable started from there.
-
-Every model trained on the same SaaS templates. Skip the guidance and you get the same handful of tells on every project: Inter for everything, purple-to-blue gradients, cards nested in cards, gray text on colored backgrounds, the rounded-square icon tile above every heading.
-
-Impeccable adds:
-- **7 domain reference files** ([view source](skill/)). Typography, color, motion, spatial, interaction, responsive, UX writing. Load on every command, alongside a brand-vs-product register that adjusts the defaults.
-- **23 commands.** A shared design vocabulary with your AI: `polish`, `audit`, `critique`, `distill`, `animate`, `bolder`, `quieter`, and more.
-- **27 deterministic anti-pattern rules** plus a 12-rule LLM critique pass. CLI and browser extension run the deterministic ones with no LLM and no API key. Each is tied to specific design guidance the skill teaches against.
-
-## What's Included
-
-### The Skill: impeccable
-
-A comprehensive design skill with 7 domain-specific references ([view skill](skill/SKILL.md)):
-
-| Reference | Covers |
-|-----------|--------|
-| [typography](skill/reference/typography.md) | Type systems, font pairing, modular scales, OpenType |
-| [color-and-contrast](skill/reference/color-and-contrast.md) | OKLCH, tinted neutrals, dark mode, accessibility |
-| [spatial-design](skill/reference/spatial-design.md) | Spacing systems, grids, visual hierarchy |
-| [motion-design](skill/reference/motion-design.md) | Easing curves, staggering, reduced motion |
-| [interaction-design](skill/reference/interaction-design.md) | Forms, focus states, loading patterns |
-| [responsive-design](skill/reference/responsive-design.md) | Mobile-first, fluid design, container queries |
-| [ux-writing](skill/reference/ux-writing.md) | Button labels, error messages, empty states |
-
-### 23 Commands
-
-All commands are accessed through `/impeccable`:
-
-| Command | What it does |
-|---------|--------------|
-| `/impeccable craft` | Full shape-then-build flow with visual iteration |
-| `/impeccable teach` | One-time setup: gather design context, write root PRODUCT.md and DESIGN.md |
-| `/impeccable document` | Generate root DESIGN.md from existing project code |
-| `/impeccable extract` | Pull reusable components and tokens into the design system |
-| `/impeccable shape` | Plan UX/UI before writing code |
-| `/impeccable critique` | UX design review: hierarchy, clarity, emotional resonance |
-| `/impeccable audit` | Run technical quality checks (a11y, performance, responsive) |
-| `/impeccable polish` | Final pass, design system alignment, and shipping readiness |
-| `/impeccable bolder` | Amplify boring designs |
-| `/impeccable quieter` | Tone down overly bold designs |
-| `/impeccable distill` | Strip to essence |
-| `/impeccable harden` | Error handling, i18n, text overflow, edge cases |
-| `/impeccable onboard` | First-run flows, empty states, activation paths |
-| `/impeccable animate` | Add purposeful motion |
-| `/impeccable colorize` | Introduce strategic color |
-| `/impeccable typeset` | Fix font choices, hierarchy, sizing |
-| `/impeccable layout` | Fix layout, spacing, visual rhythm |
-| `/impeccable delight` | Add moments of joy |
-| `/impeccable overdrive` | Add technically extraordinary effects |
-| `/impeccable clarify` | Improve unclear UX copy |
-| `/impeccable adapt` | Adapt for different devices |
-| `/impeccable optimize` | Performance improvements |
-| `/impeccable live` | Visual variant mode: iterate on elements in the browser |
-
-Use `/impeccable pin <command>` to create standalone shortcuts (e.g., `pin audit` creates `/audit`).
-
-#### Usage Examples
-
-```
-/impeccable audit blog # Audit blog hub + post pages
-/impeccable critique landing # UX design review
-/impeccable polish settings # Final pass before shipping
-/impeccable harden checkout # Add error handling + edge cases
-```
-
-Or use `/impeccable` directly with a description:
-```
-/impeccable redo this hero section
-```
-
-### Anti-Patterns
-
-The skill includes explicit guidance on what to avoid:
-
-- Don't use overused fonts (Arial, Inter, system defaults)
-- Don't use gray text on colored backgrounds
-- Don't use pure black/gray (always tint)
-- Don't wrap everything in cards or nest cards inside cards
-- Don't use bounce/elastic easing (feels dated)
-
-## See It In Action
-
-Visit [impeccable.style](https://impeccable.style#casestudies) to see before/after case studies of real projects transformed with Impeccable commands.
-
-## Installation
-
-### Option 1: Download from Website (Recommended)
-
-Visit [impeccable.style](https://impeccable.style), download the ZIP for your tool, and extract to your project.
-
-### Option 2: Copy from Repository
-
-**Cursor:**
-```bash
-cp -r dist/cursor/.cursor your-project/
-```
-
-> **Note:** Cursor skills require setup:
-> 1. Switch to Nightly channel in Cursor Settings → Beta
-> 2. Enable Agent Skills in Cursor Settings → Rules
->
-> [Learn more about Cursor skills](https://cursor.com/docs/context/skills)
-
-**Claude Code:**
-```bash
-# Project-specific
-cp -r dist/claude-code/.claude your-project/
-
-# Or global (applies to all projects)
-cp -r dist/claude-code/.claude/* ~/.claude/
-```
-
-**OpenCode:**
-```bash
-cp -r dist/opencode/.opencode your-project/
-```
-
-**Pi:**
-```bash
-cp -r dist/pi/.pi your-project/
-```
-
-**Gemini CLI:**
-```bash
-cp -r dist/gemini/.gemini your-project/
-```
-
-> **Note:** Gemini CLI skills require setup:
-> 1. Install preview version: `npm i -g @google/gemini-cli@preview`
-> 2. Run `/settings` and enable "Skills"
-> 3. Run `/skills list` to verify installation
->
-> [Learn more about Gemini CLI skills](https://geminicli.com/docs/cli/skills/)
-
-**Codex CLI:**
-```bash
-# Project-local
-cp -r dist/agents/.agents your-project/
-mkdir -p your-project/.codex
-cp -r dist/codex/.codex/agents your-project/.codex/
-
-# Or user-wide
-mkdir -p ~/.agents/skills
-cp -r dist/agents/.agents/skills/* ~/.agents/skills/
-mkdir -p ~/.codex
-cp -r dist/codex/.codex/agents ~/.codex/
-```
-
-**GitHub Copilot:**
-```bash
-cp -r dist/github/.github your-project/
-```
-
-**Trae:**
-```bash
-# Trae China (domestic version)
-cp -r dist/trae/.trae-cn/skills/* ~/.trae-cn/skills/
-
-# Trae International
-cp -r dist/trae/.trae/skills/* ~/.trae/skills/
-```
-
-> **Note:** Trae has two versions with different config directories:
-> - **Trae China**: `~/.trae-cn/skills/`
-> - **Trae International**: `~/.trae/skills/`
->
-> After copying, restart Trae IDE to activate the skills.
-
-**Rovo Dev:**
-```bash
-# Project-specific
-cp -r dist/rovo-dev/.rovodev your-project/
-
-# Or global (applies to all projects)
-cp -r dist/rovo-dev/.rovodev/skills/* ~/.rovodev/skills/
-```
-
-**Qoder:**
-```bash
-# Project-specific
-cp -r dist/qoder/.qoder your-project/
-
-# Or global (applies to all projects)
-cp -r dist/qoder/.qoder/skills/* ~/.qoder/skills/
-```
-
-## Usage
-
-Once installed, use commands in your AI harness:
-
-```
-/audit # Find issues
-/normalize # Fix inconsistencies
-/polish # Final cleanup
-/distill # Remove complexity
-```
-
-Most commands accept an optional argument to focus on a specific area:
-
-```
-/audit header
-/polish checkout-form
-```
-
-**Note:** Codex uses skills here, not `/prompts:` commands. Open `/skills` or type `$impeccable`. Repo-local installs live in `.agents/skills/`; user-wide installs live in `~/.agents/skills/`. GitHub Copilot uses `.github/skills/`. Restart the tool if a newly installed skill does not appear.
-
-## CLI
-
-Impeccable includes a standalone CLI for detecting anti-patterns without an AI harness:
-
-```bash
-npx impeccable detect src/ # scan a directory
-npx impeccable detect index.html # scan an HTML file
-npx impeccable detect https://example.com # scan a URL (Puppeteer)
-npx impeccable detect --fast --json . # regex-only, JSON output
-```
-
-The detector catches 24 issues across AI slop (side-tab borders, purple gradients, bounce easing, dark glows) and general design quality (line length, cramped padding, small touch targets, skipped headings, and more).
-
-## Supported Tools
-
-- [Cursor](https://cursor.com)
-- [Claude Code](https://claude.ai/code)
-- [OpenCode](https://opencode.ai)
-- [Pi](https://pi.dev)
-- [Gemini CLI](https://github.com/google-gemini/gemini-cli)
-- [Codex CLI](https://github.com/openai/codex)
-- [VS Code Copilot](https://code.visualstudio.com)
-- [Kiro](https://kiro.dev)
-- [Trae](https://trae.ai)
-- [Rovo Dev](https://www.atlassian.com/software/rovo)
-- [Qoder](https://qoder.com)
-
-## Community & Ecosystem
-
-Join the community and ecosystem conversations:
-
-- GitHub Discussions: file bugs, request features, and help newcomers.
-- [Impeccable on npm](https://www.npmjs.com/package/impeccable): grab the CLI, follow releases, and star the package.
-- Follow @pbakaus on Twitter for release notes, sample lint reports, and video highlights of new rules.
-
-## Contributing
-
-See [DEVELOP.md](DEVELOP.md) for contributor guidelines and build instructions.
-
-## License
-
-Apache 2.0. See [LICENSE](LICENSE).
-
-The impeccable skill builds on [Anthropic's original frontend-design skill](https://github.com/anthropics/skills/tree/main/skills/frontend-design). See [NOTICE.md](NOTICE.md) for attribution.
-
----
-
-Created by [Paul Bakaus](https://www.paulbakaus.com)
@@ -1,76 +0,0 @@
-# Impeccable CLI
-
-Detect UI anti-patterns and design quality issues from the command line. Scans HTML, CSS, JSX, TSX, Vue, and Svelte files for 27 specific patterns including AI-generated UI tells, accessibility violations, and general design quality problems.
-
-## Quick Start
-
-```bash
-# Install skills into your AI harness (Claude, Cursor, Gemini, etc.)
-npx impeccable skills install
-
-# Update skills to the latest version
-npx impeccable skills update
-
-# List all available commands
-npx impeccable skills help
-
-# Scan files or directories for anti-patterns
-npx impeccable detect src/
-
-# Scan a live URL (requires Puppeteer)
-npx impeccable detect https://example.com
-
-# JSON output for CI/tooling
-npx impeccable detect --json src/
-
-# Regex-only mode (faster, no jsdom)
-npx impeccable detect --fast src/
-```
-
-## What It Detects
-
-**AI Slop Tells**: patterns that scream "AI generated this":
-- Side-tab accent borders, gradient text on headings
-- Purple/violet gradients and cyan-on-dark palettes
-- Dark mode with glowing accents, border + border-radius clashes
-
-**Typography Issues**: overused fonts (Inter, Roboto), flat type hierarchy, single font families
-
-**Color & Contrast**: WCAG AA violations, gray text on colored backgrounds, pure black/white
-
-**Layout & Composition**: nested cards, monotonous spacing, everything-centered layouts
-
-**Motion**: bounce/elastic easing, layout property transitions
-
-**Quality**: tiny body text, cramped padding, long line lengths, small touch targets
-
-25 detections in total. See the full list at [impeccable.style](https://impeccable.style).
-
-## Exit Codes
-
-- `0`: no issues found
-- `2`: anti-patterns detected
-
-## Options
-
-```
-impeccable detect [options] [file-or-dir-or-url...]
-
- --fast Regex-only mode (skip jsdom, faster but less accurate)
- --json Output findings as JSON
- --help Show help
-```
-
-## Requirements
-
-- Node.js 18+
-- `jsdom` (included as dependency, used for HTML scanning)
-- `puppeteer` (optional, only needed for URL scanning)
-
-## Part of Impeccable
-
-This CLI is part of [Impeccable](https://impeccable.style), a cross-provider design skill pack for AI-powered development tools. The full suite includes 22 steering commands for Claude, Cursor, Gemini, Codex, and more.
-
-## License
-
-[Apache 2.0](https://github.com/pbakaus/impeccable/blob/main/LICENSE)
@@ -1,103 +0,0 @@
-# STYLE.md
-
-Editorial brief for impeccable.design. Read this before writing or editing user-facing copy: the homepage, sub-pages, command editorials, tutorials, and READMEs.
-
-The bar: **for every paragraph, point to the sentence that makes it specifically yours.** If you can't, the paragraph is AI by default, even if a human typed it.
-
-## Principles
-
-1. **Open with the reader's wrong belief, your strongest claim, or the example.** No "in this guide", no "let's dive in".
-2. **Take a position someone could disagree with.** If the paragraph could be inverted without changing meaning, it has no position. Sign your stance.
-3. **Name names. Use numbers.** Real competitors, real customer names, real version numbers, real file paths, real benchmarks. Cut "lightweight"; write "54 KB".
-4. **Verbs lead. Nouns follow.** Imperative is fine. Active voice. Cut nominalizations ("the implementation of" → "implementing").
-5. **Vary sentence length on purpose.** Long, long, short. Smooth uniform rhythm is the deepest AI tell.
-6. **Prose carries the load; structure supports it.** Bullets are for parallel options. Paragraphs are for argument. Don't bullet what would be tighter as a sentence.
-7. **Plain words. Technical terms only when something specifically rests on them.** Mixing levels lets the technical terms hit harder.
-8. **Allow ungrammatical fragments for rhythm.** Five words. Confidence signal.
-9. **Respect the reader's competence.** No "developers should consider"; just "you might not need an effect".
-10. **Read it aloud. Fix anything you stumble over.**
-11. **Concrete over comprehensive.** Coverage is an AI obsession. Trade coverage for momentum. Leave things out.
-12. **Close by handing off the next move.** Don't summarize. End on the strongest sentence, give a directive ("Now do this"), or just stop.
-
-## Denylist
-
-The build's `validateProse` step (in `scripts/build.js`) fails the build on these. The list is the editorial brief, enforced. Add a rule here when you ban a new pattern; remove a rule when the term has earned a real meaning here. **Do not silently allowlist** by working around the regex.
-
-### Stolen-engineer diction
-Engineering words that became AI flavor once they leaked into training data around late 2024.
-
-| Banned | Why | Use instead |
-|---|---|---|
-| `load-bearing` | Almost always vague. The literal sense is rare. | Name the specific thing it does. "The decision that shapes the rest", "carries the brand", "matters specifically". |
-| `highest-leverage` | Vague claim of impact. | Say what specifically pays off. "The change that moves the design most". |
-| `biggest unlock` | Marketing-speak. | Describe the actual change. |
-
-### Internal jargon leaking out
-Words that work in a research notebook and fail in user copy.
-
-| Banned | Why | Use instead |
-|---|---|---|
-| `reflex defaults` | Eval-team jargon. | "Instincts", "first guesses", "default reaches". |
-| `collapses into monoculture` | Eval-paper voice. | Describe what specifically went wrong (e.g. "every model picked the same three fonts"). |
-| `data-driven` | Empty marketing adjective. | Cite the data. "Validated against 15 briefs across two models". |
-
-### Marketing voice
-Adjectives and verbs that gesture at quality without doing the work.
-
-| Banned | Why | Use instead |
-|---|---|---|
-| `seamless`, `seamlessly` | Hollow positive. | Say what specifically works without friction. |
-| `robust`, `robustness` | Hollow positive. | Cite the failure mode handled. |
-| `elevate`, `elevates` | Marketing verb. | Use the specific verb (improve, raise, sharpen). |
-| `empower`, `empowers` | Marketing verb. | "Let you", "make possible". |
-| `underscore`, `underscores` | AI tell. | "Show", "make clear". |
-| `pivotal` | Hollow positive. | "Central", "key", or describe the role. |
-| `tapestry` | AI scenery noun. | Cut. |
-
-### Verbs
-| Banned | Why | Use instead |
-|---|---|---|
-| `delve`, `delves`, `delved`, `delving` | The most-flagged AI tell of all. | "Look at", "explore", or just delete the throat-clearing verb. |
-
-### Throat-clearing
-Sentences that delay the point. Cut them; almost nothing of value is lost.
-
-| Banned | Why | Use instead |
-|---|---|---|
-| `in today's …` | Generic opener. | Start at the actual point. |
-| `gone are the days` | Cliché opener. | Make the point directly. |
-| `whether you're …` | Audience-pandering; addresses no one. | Pick one reader. Write to them. |
-| `let's dive in` | Throat-clearing. | Just start. |
-
-### Closers
-| Banned | Why | Use instead |
-|---|---|---|
-| `in summary`, `in conclusion` | Restates what was just said. | End on the strongest sentence. Trust the reader. |
-
-### Transitions
-| Banned | Why | Use instead |
-|---|---|---|
-| `moreover`, `furthermore` | Metronome transition crutch. | Drop, or use "also", or restructure. |
-
-### Punctuation
-| Banned | Why | Use instead |
-|---|---|---|
-| Em dash `—` (and HTML entities `—`, `—`, `—`) | Decision-avoidance: writer didn't pick a relationship between the clauses. | Comma, colon, semicolon, period, parentheses. Pick the relationship. |
-| ` -- ` (double hyphen as em-dash substitute) | Worse than the em dash. Signals failed cleanup. | Real punctuation. |
-
-## Patterns the validator can't catch
-
-The above are the easy wins. The deeper issues require human judgment on every paragraph.
-
-- **Negation pivot.** "It's not just X, it's Y." "Less about X, more about Y." This is now a stronger AI tell than any vocabulary item. Use sparingly. Most instances should be replaced with a direct positive claim.
-- **Triadic everything.** Every list exactly three items. Every adjective in groups of three ("fast, simple, and powerful"). Vary count: use 2 or 4. Use 1.
-- **The five-paragraph essay shape.** Intro → 3 sections → conclusion, on every page. Mix it up. Lead with the example. Skip the conclusion. Let some sections be one sentence.
-- **Uniform paragraph length.** Insert a 4-word sentence. Insert a one-line paragraph.
-- **Synthetic balance.** Pros and cons of equal length when one is clearly right. Write the recommendation; note real exceptions briefly.
-- **Hollow confidence.** "Powerful" without numbers. Replace with a concrete fact.
-- **Hedging stacks.** "It might potentially be useful to consider..." Each hedge is fine; stacked, they sound trained.
-- **Interchangeable copy.** Swap "Impeccable" for a competitor name. If nothing becomes false, the copy is generic.
-
-## When in doubt
-
-Read the paragraph aloud. If you stumble, rewrite. If a sentence describes nothing specific to this product, cut it.
@@ -1,16 +0,0 @@
-import { defineConfig } from 'astro/config';
-
-export default defineConfig({
- srcDir: './site',
- publicDir: './site/public',
- output: 'static',
- build: {
- format: 'directory',
- },
- outDir: './build',
- vite: {
- build: {
- assetsInlineLimit: 0,
- },
- },
-});
@@ -1,12 +0,0 @@
-{
- "$schema": "https://biomejs.dev/schemas/1.9.4/schema.json",
- "css": {
- "parser": {
- "tailwindDirectives": true
- }
- }
-}
-
-
-
-
@@ -1,1344 +0,0 @@
-{
- "lockfileVersion": 1,
- "configVersion": 1,
- "workspaces": {
- "": {
- "name": "vibe-design-plugins",
- "dependencies": {
- "css-select": "^5.2.2",
- "css-tree": "^3.2.1",
- "domutils": "^3.2.2",
- "htmlparser2": "^10.0.0",
- "marked": "^16.4.2",
- },
- "devDependencies": {
- "@ai-sdk/anthropic": "^3.0.71",
- "@ai-sdk/openai": "^3.0.53",
- "@anthropic-ai/claude-agent-sdk": "^0.2.119",
- "@anthropic-ai/sdk": "^0.91.1",
- "@google/genai": "^1.50.1",
- "@paper-design/shaders": "^0.0.76",
- "ai": "^6.0.168",
- "archiver": "^7.0.1",
- "astro": "^6.2.1",
- "modern-screenshot": "^4.7.0",
- "motion": "^12.38.0",
- "playwright": "^1.59.1",
- "wrangler": "^4.85.0",
- "zod": "^4.3.6",
- },
- "optionalDependencies": {
- "puppeteer": "^24.42.0",
- },
- },
- },
- "packages": {
- "@ai-sdk/anthropic": ["@ai-sdk/anthropic@3.0.71", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-bUWOzrzR0gJKJO/PLGMR4uH2dqEgqGhrsCV+sSpk4KtOEnUQlfjZI/F7BFlqSvVpFbjdgYRRLysAeEZpJ6S1lg=="],
-
- "@ai-sdk/gateway": ["@ai-sdk/gateway@3.0.104", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ZKX5n74io8VIRlhIMSLWVlvT3sXC8Z7cZ9GHuWBWZDVi96+62AIsWuLGvMfcBA1STYuSoDrp6rIziZmvrTq0TA=="],
-
- "@ai-sdk/openai": ["@ai-sdk/openai@3.0.53", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-Wld+Rbc05KaUn08uBt06eEuwcgalcIFtIl32Yp+GxuZXUQwOb6YeAuq+C6da4ch6BurFoqEaLemJVwjBb7x+PQ=="],
-
- "@ai-sdk/provider": ["@ai-sdk/provider@3.0.8", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-oGMAgGoQdBXbZqNG0Ze56CHjDZ1IDYOwGYxYjO5KLSlz5HiNQ9udIXsPZ61VWaHGZ5XW/jyjmr6t2xz2jGVwbQ=="],
-
- "@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.23", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.6" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-z8GlDaCmRSDlqkMF2f4/RFgWxdarvIbyuk+m6WXT1LYgsnGiXRJGTD2Z1+SDl3LqtFuRtGX1aghYvQLoHL/9pg=="],
-
- "@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.2.119", "", { "dependencies": { "@anthropic-ai/sdk": "^0.81.0", "@modelcontextprotocol/sdk": "^1.29.0" }, "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.2.119", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.2.119", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.2.119", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.2.119", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.2.119", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.2.119", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.2.119", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.2.119" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-6AvthpsaOTlkn514brSGOcCSLHDXODnU+ExN1O3CJCjxr5RBcmzR057C9EIM0G7IchnXsRfMZgRO1QKsjTXdbA=="],
-
- "@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.2.119", "", { "os": "darwin", "cpu": "arm64" }, "sha512-kxnG37SZqUata2Jcp/YQ0n9Y7o/sinE/8LdG4ltM1gePh+z+0Mfa4vBUUTEBMBFth9PTovKoesIuVuyFpvO/Cw=="],
-
- "@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.2.119", "", { "os": "darwin", "cpu": "x64" }, "sha512-9Aj8g3ELsmZuOFg17TCkikeg/Wt2ucVT8hOOPQUatzLd7BKhydrHLA0RP42nBpWECO1B/n/mPdQ4iS/LS3s2Fg=="],
-
- "@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.2.119", "", { "os": "linux", "cpu": "arm64" }, "sha512-v3o464XkiYehp/OKidQQirxdVb+aGSvdJvHF2zH9p33W8M/NC21zwwh4dhwDnKsyrtBIgkt2CcMwzIl30r0OtA=="],
-
- "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.2.119", "", { "os": "linux", "cpu": "arm64" }, "sha512-IPGWgtz+gGnD7fxKAvSf913EUT/lYBTBE8EZ7lh3+x5ZP2859LWLmrCm053Lf3nMWo/CWikZsVPwkDVwpz6tIQ=="],
-
- "@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.2.119", "", { "os": "linux", "cpu": "x64" }, "sha512-9ePt4ZN+hsqDw4AgS4KtcWIGKfL9Oq28kwkrTER/QAcSrVKxiLonp81cCLzg7Ok/IUJu4Cfd71GZbFv/WE54zw=="],
-
- "@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.2.119", "", { "os": "linux", "cpu": "x64" }, "sha512-QYxFNAe4FFridPkKhGlNcNBJ0TaIygWYyvfI9g4kX0i+RVbresUWuZVkWY06ioJ0fXoixFJ+HNQBMB7dLrIp8Q=="],
-
- "@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.2.119", "", { "os": "win32", "cpu": "arm64" }, "sha512-p/TjcKQvkCYtXGPlR+mdyNwqCmvRcQL34Wtq0yUZ+iqmI/eyCe59IJ3AZrE0EZoqmiAevEYzatPIt9sncC9uxw=="],
-
- "@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.2.119", "", { "os": "win32", "cpu": "x64" }, "sha512-k98Ju0wtktm6FhqTE/cXlVr6K4kGqBolVjEGzeKkW6ZILc7124euwNapAvkQCwMAavAxS/ZnO3jdKMtHtwTVTA=="],
-
- "@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.91.1", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-LAmu761tSN9r66ixvmciswUj/ZC+1Q4iAfpedTfSVLeswRwnY3n2Nb6Tsk+cLPP28aLOPWeMgIuTuCcMC6W/iw=="],
-
- "@astrojs/compiler": ["@astrojs/compiler@4.0.0", "", {}, "sha512-eouss7G8ygdZqHuke033VMcVw5HTZUu+PXd/h06DGDUg/jt5btPYPqh66ENWw/mU78rBrf/oeC4oqoBwMtDMNA=="],
-
- "@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.9.0", "", { "dependencies": { "picomatch": "^4.0.4" } }, "sha512-GdYkzR26re8izmyYlBqf4z2s7zNngmWLFuxw0UKiPNqHraZGS6GKWIwSHgS22RDlu2ePFJ8bzmpBcUszut/SDg=="],
-
- "@astrojs/markdown-remark": ["@astrojs/markdown-remark@7.1.1", "", { "dependencies": { "@astrojs/internal-helpers": "0.9.0", "@astrojs/prism": "4.0.1", "github-slugger": "^2.0.0", "hast-util-from-html": "^2.0.3", "hast-util-to-text": "^4.0.2", "js-yaml": "^4.1.1", "mdast-util-definitions": "^6.0.0", "rehype-raw": "^7.0.0", "rehype-stringify": "^10.0.1", "remark-gfm": "^4.0.1", "remark-parse": "^11.0.0", "remark-rehype": "^11.1.2", "remark-smartypants": "^3.0.2", "retext-smartypants": "^6.2.0", "shiki": "^4.0.0", "smol-toml": "^1.6.0", "unified": "^11.0.5", "unist-util-remove-position": "^5.0.0", "unist-util-visit": "^5.1.0", "unist-util-visit-parents": "^6.0.2", "vfile": "^6.0.3" } }, "sha512-C6e9BnLGlbdv6bV8MYGeHpHxsUHrCrB4OuRLqi5LI7oiBVcBcqfUN06zpwFQdHgV48QCCrMmLpyqBr7VqC+swA=="],
-
- "@astrojs/prism": ["@astrojs/prism@4.0.1", "", { "dependencies": { "prismjs": "^1.30.0" } }, "sha512-nksZQVjlferuWzhPsBpQ1JE5XuKAf1id1/9Hj4a9KG4+ofrlzxUUwX4YGQF/SuDiuiGKEnzopGOt38F3AnVWsQ=="],
-
- "@astrojs/telemetry": ["@astrojs/telemetry@3.3.1", "", { "dependencies": { "ci-info": "^4.4.0", "dlv": "^1.1.3", "dset": "^3.1.4", "is-docker": "^4.0.0", "is-wsl": "^3.1.1", "which-pm-runs": "^1.1.0" } }, "sha512-7fcIxXS9J4ls5tr8b3ww9rbAIz2+HrhNJYZdkAhhB4za/I5IZ/60g+Bs8q7zwG0tOIZfNB4JWhVJ1Qkl/OrNCw=="],
-
- "@babel/code-frame": ["@babel/code-frame@7.29.0", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw=="],
-
- "@babel/helper-string-parser": ["@babel/helper-string-parser@7.27.1", "", {}, "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA=="],
-
- "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.28.5", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="],
-
- "@babel/parser": ["@babel/parser@7.29.3", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-b3ctpQwp+PROvU/cttc4OYl4MzfJUWy6FZg+PMXfzmt/+39iHVF0sDfqay8TQM3JA2EUOyKcFZt75jWriQijsA=="],
-
- "@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="],
-
- "@babel/types": ["@babel/types@7.29.0", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.28.5" } }, "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A=="],
-
- "@capsizecss/unpack": ["@capsizecss/unpack@4.0.0", "", { "dependencies": { "fontkitten": "^1.0.0" } }, "sha512-VERIM64vtTP1C4mxQ5thVT9fK0apjPFobqybMtA1UdUujWka24ERHbRHFGmpbbhp73MhV+KSsHQH9C6uOTdEQA=="],
-
- "@clack/core": ["@clack/core@1.3.0", "", { "dependencies": { "fast-wrap-ansi": "^0.2.0", "sisteransi": "^1.0.5" } }, "sha512-xJPHpAmEQUBrXSLx0gF+q5K/IyihXpsHZcha+jB+tyahsKRK3Dxo4D0coZDewHo12NhiuzC3dTtMPbm53GEAAA=="],
-
- "@clack/prompts": ["@clack/prompts@1.3.0", "", { "dependencies": { "@clack/core": "1.3.0", "fast-string-width": "^3.0.2", "fast-wrap-ansi": "^0.2.0", "sisteransi": "^1.0.5" } }, "sha512-GgcWwRCs/xPtaqlMy8qRhPnZf9vlWcWZNHAitnVQ3yk7JmSralSiq5q07yaffYE8SogtDm7zFeKccx1QNVARpw=="],
-
- "@cloudflare/kv-asset-handler": ["@cloudflare/kv-asset-handler@0.4.2", "", {}, "sha512-SIOD2DxrRRwQ+jgzlXCqoEFiKOFqaPjhnNTGKXSRLvp1HiOvapLaFG2kEr9dYQTYe8rKrd9uvDUzmAITeNyaHQ=="],
-
- "@cloudflare/unenv-preset": ["@cloudflare/unenv-preset@2.16.1", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": ">1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw=="],
-
- "@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20260424.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-yFR1XaJbSDLg/qbwtrYaU2xwFXatIPKR5nrMQCN1q/m6+Qe/j6r+kCnFEvOJjMZOm9iCKsE6Qly5clgl4u32qw=="],
-
- "@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20260424.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-LqWKcE7x/9KyC2iQvKPeb20hKST3dYXDZlYTvFymgR1DfLS0OFOCzVGTloVNd7WqvK4SkdzBYfxo7QMIAeBK0w=="],
-
- "@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20260424.1", "", { "os": "linux", "cpu": "x64" }, "sha512-YlEBFbAYZHe/ylzl8WEYQEU/jr+0XMqXaST2oBk5oVjksdb1NGuJaggluCdZAzuJJ8UqdTmyhY5u/qrasbiFWA=="],
-
- "@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20260424.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-qJ0X0m6cL8fWDUPDg8K4IxYZXNJI6XbeOihqjnqKbAClrjdPDn8VUSd+z2XiCQ5NylMtMrpa/skC9UfaR6mh8g=="],
-
- "@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20260424.1", "", { "os": "win32", "cpu": "x64" }, "sha512-tZ7Z9qmYNAP6z1/+8r/zKbk8F8DZmpmwNzMeN+zkde2Wnhfr3FBqOkJXT/5zmli8HPoWrIXxSiyqcNDMy8V2Zg=="],
-
- "@cspotcode/source-map-support": ["@cspotcode/source-map-support@0.8.1", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="],
-
- "@emnapi/runtime": ["@emnapi/runtime@1.8.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg=="],
-
- "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.3", "", { "os": "aix", "cpu": "ppc64" }, "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg=="],
-
- "@esbuild/android-arm": ["@esbuild/android-arm@0.27.3", "", { "os": "android", "cpu": "arm" }, "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA=="],
-
- "@esbuild/android-arm64": ["@esbuild/android-arm64@0.27.3", "", { "os": "android", "cpu": "arm64" }, "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg=="],
-
- "@esbuild/android-x64": ["@esbuild/android-x64@0.27.3", "", { "os": "android", "cpu": "x64" }, "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ=="],
-
- "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.27.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg=="],
-
- "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.27.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg=="],
-
- "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.27.3", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w=="],
-
- "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.27.3", "", { "os": "freebsd", "cpu": "x64" }, "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA=="],
-
- "@esbuild/linux-arm": ["@esbuild/linux-arm@0.27.3", "", { "os": "linux", "cpu": "arm" }, "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw=="],
-
- "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.27.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg=="],
-
- "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.27.3", "", { "os": "linux", "cpu": "ia32" }, "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg=="],
-
- "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.27.3", "", { "os": "linux", "cpu": "none" }, "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA=="],
-
- "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.27.3", "", { "os": "linux", "cpu": "none" }, "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw=="],
-
- "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.27.3", "", { "os": "linux", "cpu": "ppc64" }, "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA=="],
-
- "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.27.3", "", { "os": "linux", "cpu": "none" }, "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ=="],
-
- "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.27.3", "", { "os": "linux", "cpu": "s390x" }, "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw=="],
-
- "@esbuild/linux-x64": ["@esbuild/linux-x64@0.27.3", "", { "os": "linux", "cpu": "x64" }, "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA=="],
-
- "@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.27.3", "", { "os": "none", "cpu": "arm64" }, "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA=="],
-
- "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.27.3", "", { "os": "none", "cpu": "x64" }, "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA=="],
-
- "@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.27.3", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw=="],
-
- "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.27.3", "", { "os": "openbsd", "cpu": "x64" }, "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ=="],
-
- "@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.27.3", "", { "os": "none", "cpu": "arm64" }, "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g=="],
-
- "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.27.3", "", { "os": "sunos", "cpu": "x64" }, "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA=="],
-
- "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.27.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA=="],
-
- "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.27.3", "", { "os": "win32", "cpu": "ia32" }, "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q=="],
-
- "@esbuild/win32-x64": ["@esbuild/win32-x64@0.27.3", "", { "os": "win32", "cpu": "x64" }, "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA=="],
-
- "@google/genai": ["@google/genai@1.50.1", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"] }, "sha512-YbkX7H9+1Pt8wOt7DDREy8XSoiL6fRDzZQRyaVBarFf8MR3zHGqVdvM4cLbDXqPhxqvegZShgfxb8kw9C7YhAQ=="],
-
- "@hono/node-server": ["@hono/node-server@1.19.14", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="],
-
- "@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],
-
- "@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.2.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w=="],
-
- "@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.2.4" }, "os": "darwin", "cpu": "x64" }, "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw=="],
-
- "@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.2.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g=="],
-
- "@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.2.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg=="],
-
- "@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.2.4", "", { "os": "linux", "cpu": "arm" }, "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A=="],
-
- "@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.2.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw=="],
-
- "@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.2.4", "", { "os": "linux", "cpu": "ppc64" }, "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA=="],
-
- "@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.2.4", "", { "os": "linux", "cpu": "none" }, "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA=="],
-
- "@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.2.4", "", { "os": "linux", "cpu": "s390x" }, "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ=="],
-
- "@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.2.4", "", { "os": "linux", "cpu": "x64" }, "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw=="],
-
- "@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.2.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw=="],
-
- "@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.2.4", "", { "os": "linux", "cpu": "x64" }, "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg=="],
-
- "@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.2.4" }, "os": "linux", "cpu": "arm" }, "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw=="],
-
- "@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.2.4" }, "os": "linux", "cpu": "arm64" }, "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg=="],
-
- "@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.2.4" }, "os": "linux", "cpu": "ppc64" }, "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA=="],
-
- "@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.2.4" }, "os": "linux", "cpu": "none" }, "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw=="],
-
- "@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.2.4" }, "os": "linux", "cpu": "s390x" }, "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg=="],
-
- "@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.2.4" }, "os": "linux", "cpu": "x64" }, "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ=="],
-
- "@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" }, "os": "linux", "cpu": "arm64" }, "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg=="],
-
- "@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.2.4" }, "os": "linux", "cpu": "x64" }, "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q=="],
-
- "@img/sharp-wasm32": ["@img/sharp-wasm32@0.34.5", "", { "dependencies": { "@emnapi/runtime": "^1.7.0" }, "cpu": "none" }, "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw=="],
-
- "@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.34.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g=="],
-
- "@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.34.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg=="],
-
- "@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.34.5", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],
-
- "@isaacs/cliui": ["@isaacs/cliui@8.0.2", "", { "dependencies": { "string-width": "^5.1.2", "string-width-cjs": "npm:string-width@^4.2.0", "strip-ansi": "^7.0.1", "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", "wrap-ansi": "^8.1.0", "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" } }, "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA=="],
-
- "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="],
-
- "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],
-
- "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.9", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ=="],
-
- "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.29.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],
-
- "@opentelemetry/api": ["@opentelemetry/api@1.9.0", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="],
-
- "@oslojs/encoding": ["@oslojs/encoding@1.1.0", "", {}, "sha512-70wQhgYmndg4GCPxPPxPGevRKqTIJ2Nh4OkiMWmDAVYsTQ+Ta7Sq+rPevXyXGdzr30/qZBnyOalCszoMxlyldQ=="],
-
- "@paper-design/shaders": ["@paper-design/shaders@0.0.76", "", {}, "sha512-AcNDY4J66YQHUfQYFInkCP7M9VOje0od7wLpOR7LtCmc532opJy6ll+h1W9zBovz8tt9U7OADUmJ/qKEXyOX/A=="],
-
- "@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],
-
- "@poppinss/colors": ["@poppinss/colors@4.1.6", "", { "dependencies": { "kleur": "^4.1.5" } }, "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg=="],
-
- "@poppinss/dumper": ["@poppinss/dumper@0.6.5", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@sindresorhus/is": "^7.0.2", "supports-color": "^10.0.0" } }, "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw=="],
-
- "@poppinss/exception": ["@poppinss/exception@1.2.3", "", {}, "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw=="],
-
- "@protobufjs/aspromise": ["@protobufjs/aspromise@1.1.2", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="],
-
- "@protobufjs/base64": ["@protobufjs/base64@1.1.2", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="],
-
- "@protobufjs/codegen": ["@protobufjs/codegen@2.0.4", "", {}, "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg=="],
-
- "@protobufjs/eventemitter": ["@protobufjs/eventemitter@1.1.0", "", {}, "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q=="],
-
- "@protobufjs/fetch": ["@protobufjs/fetch@1.1.0", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1", "@protobufjs/inquire": "^1.1.0" } }, "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ=="],
-
- "@protobufjs/float": ["@protobufjs/float@1.0.2", "", {}, "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ=="],
-
- "@protobufjs/inquire": ["@protobufjs/inquire@1.1.0", "", {}, "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q=="],
-
- "@protobufjs/path": ["@protobufjs/path@1.1.2", "", {}, "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA=="],
-
- "@protobufjs/pool": ["@protobufjs/pool@1.1.0", "", {}, "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw=="],
-
- "@protobufjs/utf8": ["@protobufjs/utf8@1.1.0", "", {}, "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw=="],
-
- "@puppeteer/browsers": ["@puppeteer/browsers@2.13.0", "", { "dependencies": { "debug": "^4.4.3", "extract-zip": "^2.0.1", "progress": "^2.0.3", "proxy-agent": "^6.5.0", "semver": "^7.7.4", "tar-fs": "^3.1.1", "yargs": "^17.7.2" }, "bin": { "browsers": "lib/cjs/main-cli.js" } }, "sha512-46BZJYJjc/WwmKjsvDFykHtXrtomsCIrwYQPOP7VfMJoZY2bsDF9oROBABR3paDjDcmkUye1Pb1BqdcdiipaWA=="],
-
- "@rollup/pluginutils": ["@rollup/pluginutils@5.3.0", "", { "dependencies": { "@types/estree": "^1.0.0", "estree-walker": "^2.0.2", "picomatch": "^4.0.2" }, "peerDependencies": { "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" }, "optionalPeers": ["rollup"] }, "sha512-5EdhGZtnu3V88ces7s53hhfK5KSASnJZv8Lulpc04cWO3REESroJXg73DFsOmgbU2BhwV0E20bu2IDZb3VKW4Q=="],
-
- "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.60.2", "", { "os": "android", "cpu": "arm" }, "sha512-dnlp69efPPg6Uaw2dVqzWRfAWRnYVb1XJ8CyyhIbZeaq4CA5/mLeZ1IEt9QqQxmbdvagjLIm2ZL8BxXv5lH4Yw=="],
-
- "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.60.2", "", { "os": "android", "cpu": "arm64" }, "sha512-OqZTwDRDchGRHHm/hwLOL7uVPB9aUvI0am/eQuWMNyFHf5PSEQmyEeYYheA0EPPKUO/l0uigCp+iaTjoLjVoHg=="],
-
- "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.60.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-UwRE7CGpvSVEQS8gUMBe1uADWjNnVgP3Iusyda1nSRwNDCsRjnGc7w6El6WLQsXmZTbLZx9cecegumcitNfpmA=="],
-
- "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.60.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-gjEtURKLCC5VXm1I+2i1u9OhxFsKAQJKTVB8WvDAHF+oZlq0GTVFOlTlO1q3AlCTE/DF32c16ESvfgqR7343/g=="],
-
- "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.60.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-Bcl6CYDeAgE70cqZaMojOi/eK63h5Me97ZqAQoh77VPjMysA/4ORQBRGo3rRy45x4MzVlU9uZxs8Uwy7ZaKnBw=="],
-
- "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.60.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-LU+TPda3mAE2QB0/Hp5VyeKJivpC6+tlOXd1VMoXV/YFMvk/MNk5iXeBfB4MQGRWyOYVJ01625vjkr0Az98OJQ=="],
-
- "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.60.2", "", { "os": "linux", "cpu": "arm" }, "sha512-2QxQrM+KQ7DAW4o22j+XZ6RKdxjLD7BOWTP0Bv0tmjdyhXSsr2Ul1oJDQqh9Zf5qOwTuTc7Ek83mOFaKnodPjg=="],
-
- "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.60.2", "", { "os": "linux", "cpu": "arm" }, "sha512-TbziEu2DVsTEOPif2mKWkMeDMLoYjx95oESa9fkQQK7r/Orta0gnkcDpzwufEcAO2BLBsD7mZkXGFqEdMRRwfw=="],
-
- "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.60.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-bO/rVDiDUuM2YfuCUwZ1t1cP+/yqjqz+Xf2VtkdppefuOFS2OSeAfgafaHNkFn0t02hEyXngZkxtGqXcXwO8Rg=="],
-
- "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.60.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-hr26p7e93Rl0Za+JwW7EAnwAvKkehh12BU1Llm9Ykiibg4uIr2rbpxG9WCf56GuvidlTG9KiiQT/TXT1yAWxTA=="],
-
- "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.60.2", "", { "os": "linux", "cpu": "none" }, "sha512-pOjB/uSIyDt+ow3k/RcLvUAOGpysT2phDn7TTUB3n75SlIgZzM6NKAqlErPhoFU+npgY3/n+2HYIQVbF70P9/A=="],
-
- "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.60.2", "", { "os": "linux", "cpu": "none" }, "sha512-2/w+q8jszv9Ww1c+6uJT3OwqhdmGP2/4T17cu8WuwyUuuaCDDJ2ojdyYwZzCxx0GcsZBhzi3HmH+J5pZNXnd+Q=="],
-
- "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.60.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-11+aL5vKheYgczxtPVVRhdptAM2H7fcDR5Gw4/bTcteuZBlH4oP9f5s9zYO9aGZvoGeBpqXI/9TZZihZ609wKw=="],
-
- "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.60.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-i16fokAGK46IVZuV8LIIwMdtqhin9hfYkCh8pf8iC3QU3LpwL+1FSFGej+O7l3E/AoknL6Dclh2oTdnRMpTzFQ=="],
-
- "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.60.2", "", { "os": "linux", "cpu": "none" }, "sha512-49FkKS6RGQoriDSK/6E2GkAsAuU5kETFCh7pG4yD/ylj9rKhTmO3elsnmBvRD4PgJPds5W2PkhC82aVwmUcJ7A=="],
-
- "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.60.2", "", { "os": "linux", "cpu": "none" }, "sha512-mjYNkHPfGpUR00DuM1ZZIgs64Hpf4bWcz9Z41+4Q+pgDx73UwWdAYyf6EG/lRFldmdHHzgrYyge5akFUW0D3mQ=="],
-
- "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.60.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-ALyvJz965BQk8E9Al/JDKKDLH2kfKFLTGMlgkAbbYtZuJt9LU8DW3ZoDMCtQpXAltZxwBHevXz5u+gf0yA0YoA=="],
-
- "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.60.2", "", { "os": "linux", "cpu": "x64" }, "sha512-UQjrkIdWrKI626Du8lCQ6MJp/6V1LAo2bOK9OTu4mSn8GGXIkPXk/Vsp4bLHCd9Z9Iz2OTEaokUE90VweJgIYQ=="],
-
- "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.60.2", "", { "os": "linux", "cpu": "x64" }, "sha512-bTsRGj6VlSdn/XD4CGyzMnzaBs9bsRxy79eTqTCBsA8TMIEky7qg48aPkvJvFe1HyzQ5oMZdg7AnVlWQSKLTnw=="],
-
- "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.60.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-6d4Z3534xitaA1FcMWP7mQPq5zGwBmGbhphh2DwaA1aNIXUu3KTOfwrWpbwI4/Gr0uANo7NTtaykFyO2hPuFLg=="],
-
- "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.60.2", "", { "os": "none", "cpu": "arm64" }, "sha512-NetAg5iO2uN7eB8zE5qrZ3CSil+7IJt4WDFLcC75Ymywq1VZVD6qJ6EvNLjZ3rEm6gB7XW5JdT60c6MN35Z85Q=="],
-
- "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.60.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-NCYhOotpgWZ5kdxCZsv6Iudx0wX8980Q/oW4pNFNihpBKsDbEA1zpkfxJGC0yugsUuyDZ7gL37dbzwhR0VI7pQ=="],
-
- "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.60.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-RXsaOqXxfoUBQoOgvmmijVxJnW2IGB0eoMO7F8FAjaj0UTywUO/luSqimWBJn04WNgUkeNhh7fs7pESXajWmkg=="],
-
- "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.60.2", "", { "os": "win32", "cpu": "x64" }, "sha512-qdAzEULD+/hzObedtmV6iBpdL5TIbKVztGiK7O3/KYSf+HIzU257+MX1EXJcyIiDbMAqmbwaufcYPvyRryeZtA=="],
-
- "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.60.2", "", { "os": "win32", "cpu": "x64" }, "sha512-Nd/SgG27WoA9e+/TdK74KnHz852TLa94ovOYySo/yMPuTmpckK/jIF2jSwS3g7ELSKXK13/cVdmg1Z/DaCWKxA=="],
-
- "@shikijs/core": ["@shikijs/core@4.0.2", "", { "dependencies": { "@shikijs/primitive": "4.0.2", "@shikijs/types": "4.0.2", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-hxT0YF4ExEqB8G/qFdtJvpmHXBYJ2lWW7qTHDarVkIudPFE6iCIrqdgWxGn5s+ppkGXI0aEGlibI0PAyzP3zlw=="],
-
- "@shikijs/engine-javascript": ["@shikijs/engine-javascript@4.0.2", "", { "dependencies": { "@shikijs/types": "4.0.2", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.4" } }, "sha512-7PW0Nm49DcoUIQEXlJhNNBHyoGMjalRETTCcjMqEaMoJRLljy1Bi/EGV3/qLBgLKQejdspiiYuHGQW6dX94Nag=="],
-
- "@shikijs/engine-oniguruma": ["@shikijs/engine-oniguruma@4.0.2", "", { "dependencies": { "@shikijs/types": "4.0.2", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-UpCB9Y2sUKlS9z8juFSKz7ZtysmeXCgnRF0dlhXBkmQnek7lAToPte8DkxmEYGNTMii72zU/lyXiCB6StuZeJg=="],
-
- "@shikijs/langs": ["@shikijs/langs@4.0.2", "", { "dependencies": { "@shikijs/types": "4.0.2" } }, "sha512-KaXby5dvoeuZzN0rYQiPMjFoUrz4hgwIE+D6Du9owcHcl6/g16/yT5BQxSW5cGt2MZBz6Hl0YuRqf12omRfUUg=="],
-
- "@shikijs/primitive": ["@shikijs/primitive@4.0.2", "", { "dependencies": { "@shikijs/types": "4.0.2", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-M6UMPrSa3fN5ayeJwFVl9qWofl273wtK1VG8ySDZ1mQBfhCpdd8nEx7nPZ/tk7k+TYcpqBZzj/AnwxT9lO+HJw=="],
-
- "@shikijs/themes": ["@shikijs/themes@4.0.2", "", { "dependencies": { "@shikijs/types": "4.0.2" } }, "sha512-mjCafwt8lJJaVSsQvNVrJumbnnj1RI8jbUKrPKgE6E3OvQKxnuRoBaYC51H4IGHePsGN/QtALglWBU7DoKDFnA=="],
-
- "@shikijs/types": ["@shikijs/types@4.0.2", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-qzbeRooUTPnLE+sHD/Z8DStmaDgnbbc/pMrU203950aRqjX/6AFHeDYT+j00y2lPdz0ywJKx7o/7qnqTivtlXg=="],
-
- "@shikijs/vscode-textmate": ["@shikijs/vscode-textmate@10.0.2", "", {}, "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg=="],
-
- "@sindresorhus/is": ["@sindresorhus/is@7.2.0", "", {}, "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw=="],
-
- "@speed-highlight/core": ["@speed-highlight/core@1.2.14", "", {}, "sha512-G4ewlBNhUtlLvrJTb88d2mdy2KRijzs4UhnlrOSRT4bmjh/IqNElZa3zkrZ+TC47TwtlDWzVLFADljF1Ijp5hA=="],
-
- "@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
-
- "@tootallnate/quickjs-emscripten": ["@tootallnate/quickjs-emscripten@0.23.0", "", {}, "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA=="],
-
- "@types/debug": ["@types/debug@4.1.13", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="],
-
- "@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],
-
- "@types/hast": ["@types/hast@3.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ=="],
-
- "@types/mdast": ["@types/mdast@4.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA=="],
-
- "@types/ms": ["@types/ms@2.1.0", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="],
-
- "@types/nlcst": ["@types/nlcst@2.0.3", "", { "dependencies": { "@types/unist": "*" } }, "sha512-vSYNSDe6Ix3q+6Z7ri9lyWqgGhJTmzRjZRqyq15N0Z/1/UnVsno9G/N40NBijoYx2seFDIl0+B2mgAb9mezUCA=="],
-
- "@types/node": ["@types/node@25.5.0", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw=="],
-
- "@types/retry": ["@types/retry@0.12.0", "", {}, "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA=="],
-
- "@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="],
-
- "@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="],
-
- "@ungap/structured-clone": ["@ungap/structured-clone@1.3.0", "", {}, "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g=="],
-
- "@vercel/oidc": ["@vercel/oidc@3.2.0", "", {}, "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug=="],
-
- "abort-controller": ["abort-controller@3.0.0", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="],
-
- "accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
-
- "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],
-
- "ai": ["ai@6.0.168", "", { "dependencies": { "@ai-sdk/gateway": "3.0.104", "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23", "@opentelemetry/api": "1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-2HqCJuO+1V2aV7vfYs5LFEUfxbkGX+5oa54q/gCCTL7KLTdbxcCu5D7TdLA5kwsrs3Szgjah9q6D9tpjHM3hUQ=="],
-
- "ajv": ["ajv@8.18.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="],
-
- "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
-
- "ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
-
- "ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
-
- "anymatch": ["anymatch@3.1.3", "", { "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" } }, "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw=="],
-
- "archiver": ["archiver@7.0.1", "", { "dependencies": { "archiver-utils": "^5.0.2", "async": "^3.2.4", "buffer-crc32": "^1.0.0", "readable-stream": "^4.0.0", "readdir-glob": "^1.1.2", "tar-stream": "^3.0.0", "zip-stream": "^6.0.1" } }, "sha512-ZcbTaIqJOfCc03QwD468Unz/5Ir8ATtvAHsK+FdXbDIbGfihqh9mrvdcYunQzqn4HrvWWaFyaxJhGZagaJJpPQ=="],
-
- "archiver-utils": ["archiver-utils@5.0.2", "", { "dependencies": { "glob": "^10.0.0", "graceful-fs": "^4.2.0", "is-stream": "^2.0.1", "lazystream": "^1.0.0", "lodash": "^4.17.15", "normalize-path": "^3.0.0", "readable-stream": "^4.0.0" } }, "sha512-wuLJMmIBQYCsGZgYLTy5FIB2pF6Lfb6cXMSF8Qywwk3t20zWnAi7zLcQFdKQmIB8wyZpY5ER38x08GbwtR2cLA=="],
-
- "argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
-
- "aria-query": ["aria-query@5.3.2", "", {}, "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw=="],
-
- "array-iterate": ["array-iterate@2.0.1", "", {}, "sha512-I1jXZMjAgCMmxT4qxXfPXa6SthSoE8h6gkSI9BGGNv8mP8G/v0blc+qFnZu6K42vTOiuME596QaLO0TP3Lk0xg=="],
-
- "ast-types": ["ast-types@0.13.4", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w=="],
-
@@ -1,56 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Impeccable CLI
- *
- * Usage:
- * npx impeccable detect [file-or-dir-or-url...]
- * npx impeccable skills help|install|update
- * npx impeccable --help
- */
-
-import { readFileSync } from 'node:fs';
-import { join, dirname } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-const args = process.argv.slice(2);
-const command = args[0];
-
-if (!command || command === '--help' || command === '-h') {
- console.log(`Usage: impeccable <command> [options]
-
-Commands:
- detect [file-or-dir-or-url...] Scan for UI anti-patterns and design quality issues
- skills help List all available skills and commands
- skills install Install impeccable skills into your project
- skills update Update skills to the latest version
- skills check Check if skill updates are available
-
-Options:
- --help Show this help message
- --version Show version number
-
-Run 'impeccable <command> --help' for command-specific options.`);
- process.exit(0);
-}
-
-if (command === '--version' || command === '-v') {
- const pkg = JSON.parse(readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf8'));
- console.log(pkg.version);
- process.exit(0);
-}
-
-if (command === 'detect') {
- process.argv = [process.argv[0], process.argv[1], ...args.slice(1)];
- const { detectCli } = await import('../engine/detect-antipatterns.mjs');
- await detectCli();
-} else if (command === 'skills') {
- const { run } = await import('./commands/skills.mjs');
- await run(args.slice(1));
-} else {
- // Default: treat as detect arguments (allow `npx impeccable src/` shorthand)
- process.argv = [process.argv[0], process.argv[1], ...args];
- const { detectCli } = await import('../engine/detect-antipatterns.mjs');
- await detectCli();
-}
@@ -1,653 +0,0 @@
-/**
- * `impeccable skills` subcommand
- *
- * Usage:
- * impeccable skills help Show all available skills and commands
- * impeccable skills install Install skills via npx skills add
- * impeccable skills update Update skills to latest version
- */
-
-import { execSync } from 'node:child_process';
-import { existsSync, readFileSync, readdirSync, statSync, lstatSync, symlinkSync, readlinkSync, unlinkSync, mkdirSync, writeFileSync, rmSync, renameSync, createWriteStream, realpathSync } from 'node:fs';
-import { join, resolve, dirname } from 'node:path';
-import { createInterface } from 'node:readline';
-import { fileURLToPath } from 'node:url';
-import { get } from 'node:https';
-import { createHash } from 'node:crypto';
-import { tmpdir } from 'node:os';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-const API_BASE = 'https://impeccable.style';
-
-// Provider folder names in project roots
-const PROVIDER_DIRS = ['.claude', '.cursor', '.gemini', '.agents', '.github', '.kiro', '.opencode', '.pi', '.qoder', '.trae', '.trae-cn'];
-
-function ask(question) {
- const rl = createInterface({ input: process.stdin, output: process.stdout });
- return new Promise(r => rl.question(question, ans => { rl.close(); r(ans.trim().toLowerCase()); }));
-}
-
-// ─── skills help ──────────────────────────────────────────────────────────────
-
-async function showHelp() {
- let commands;
- try {
- const res = await fetch(`${API_BASE}/api/commands`);
- commands = await res.json();
- } catch {
- console.error('Could not fetch command list from impeccable.style. Check your network connection.');
- process.exit(1);
- }
-
- const pad = (s, n) => s + ' '.repeat(Math.max(0, n - s.length));
-
- console.log('\n Impeccable Skills & Commands\n');
- console.log(' Install: npx impeccable skills install');
- console.log(' Update: npx impeccable skills update');
- console.log(' Docs: https://impeccable.style/cheatsheet\n');
- console.log(` ${pad('Command', 22)} Description`);
- console.log(` ${'-'.repeat(22)} ${'-'.repeat(52)}`);
-
- for (const cmd of commands.sort((a, b) => a.id.localeCompare(b.id))) {
- // Trim description to fit terminal
- const desc = cmd.description.length > 72
- ? cmd.description.substring(0, 69) + '...'
- : cmd.description;
- console.log(` ${pad('/' + cmd.id, 22)} ${desc}`);
- }
- console.log(`\n ${commands.length} commands available. Run /<command> in your AI harness.\n`);
-}
-
-// ─── version helpers ─────────────────────────────────────────────────────────
-
-/**
- * Read the skills version from the impeccable SKILL.md frontmatter.
- */
-function getSkillsVersion(root) {
- for (const d of PROVIDER_DIRS) {
- const skillMd = join(root, d, 'skills', 'impeccable', 'SKILL.md');
- if (!existsSync(skillMd)) continue;
- const content = readFileSync(skillMd, 'utf-8');
- const match = content.match(/^version:\s*(.+)$/m);
- if (match) return match[1].trim().replace(/^["']|["']$/g, '');
- }
- return null;
-}
-
-/**
- * Hash all SKILL.md files in a directory tree for comparison.
- * Returns a sorted string of "name:hash" pairs.
- */
-function hashSkillsDir(skillsDir) {
- if (!existsSync(skillsDir)) return '';
- const entries = [];
- for (const name of readdirSync(skillsDir).sort()) {
- const skillMd = join(skillsDir, name, 'SKILL.md');
- if (!existsSync(skillMd)) continue;
- const hash = createHash('sha256').update(readFileSync(skillMd)).digest('hex').slice(0, 12);
- entries.push(`${name}:${hash}`);
- }
- return entries.join(',');
-}
-
-/**
- * Download the universal bundle to a temp dir and return its path.
- * Caller is responsible for cleanup.
- */
-async function downloadAndExtractBundle() {
- const tmpZip = join(tmpdir(), `impeccable-update-${Date.now()}.zip`);
- const tmpDir = join(tmpdir(), `impeccable-update-${Date.now()}`);
- await downloadFile(`${API_BASE}/api/download/bundle/universal`, tmpZip);
- mkdirSync(tmpDir, { recursive: true });
- execSync(`unzip -qo "${tmpZip}" -d "${tmpDir}"`, { encoding: 'utf8' });
- rmSync(tmpZip, { force: true });
- return tmpDir;
-}
-
-/**
- * Normalize a SKILL.md's content for comparison by stripping
- * provider-specific paths. Different install methods (npx skills add
- * vs our bundle) resolve {{scripts_path}} to different provider dirs
- * (e.g. .agents vs .claude), so we strip those differences.
- */
-function normalizeForHash(content) {
- return content
- .replace(/\.(claude|cursor|agents|github|gemini|codex|kiro|opencode|pi|qoder|trae|trae-cn|rovodev)\/skills\//g, '.PROVIDER/skills/')
- .replace(/^version:\s*.+$/m, 'version: NORMALIZED');
-}
-
-/**
- * Deduplicate providers by resolved path. When .claude/skills is a
- * symlink to ../.agents/skills, both resolve to the same directory.
- * Returns an array of { provider, localSkillsDir } with one entry
- * per unique real path. The first provider that maps to a real path
- * wins (so the bundle uses that provider's build).
- */
-function deduplicateProviders(root, providers) {
- const seen = new Map(); // realPath -> { provider, localSkillsDir }
- for (const provider of providers) {
- const skillsDir = join(root, provider, 'skills');
- if (!existsSync(skillsDir)) continue;
- const real = realpathSync(skillsDir);
- if (!seen.has(real)) {
- seen.set(real, { provider, localSkillsDir: skillsDir });
- }
- }
- return [...seen.values()];
-}
-
-/**
- * Compare local skills against a downloaded bundle.
- * Only checks skills that exist in the bundle (ignores user's custom
- * skills that aren't part of impeccable). Deduplicates providers that
- * share the same real path (symlinks). Normalizes provider-specific
- * paths and version fields before comparing.
- * Returns true if every bundle skill matches the local copy.
- */
-function isUpToDate(root, providers, bundleDir) {
- const unique = deduplicateProviders(root, providers);
- if (unique.length === 0) return false;
-
- for (const { provider, localSkillsDir } of unique) {
- const bundleSkillsDir = join(bundleDir, provider, 'skills');
- if (!existsSync(bundleSkillsDir)) continue;
-
- for (const name of readdirSync(bundleSkillsDir)) {
- const bundleMd = join(bundleSkillsDir, name, 'SKILL.md');
- const localMd = join(localSkillsDir, name, 'SKILL.md');
- if (!existsSync(bundleMd)) continue;
- if (!existsSync(localMd)) return false;
-
- const bundleHash = createHash('sha256').update(normalizeForHash(readFileSync(bundleMd, 'utf-8'))).digest('hex');
- const localHash = createHash('sha256').update(normalizeForHash(readFileSync(localMd, 'utf-8'))).digest('hex');
- if (bundleHash !== localHash) return false;
- }
- }
- return true;
-}
-
-// ─── skills check ────────────────────────────────────────────────────────────
-
-async function check() {
- const root = findProjectRoot();
- const installed = isAlreadyInstalled(root);
-
- if (!installed) {
- console.log('Impeccable is not installed in this project.');
- console.log('Run `npx impeccable skills install` to install.');
- process.exit(0);
- }
-
- const providers = findInstalledProviders(root);
-
- console.log('Checking for updates...\n');
- try {
- const bundleDir = await downloadAndExtractBundle();
- const upToDate = isUpToDate(root, providers, bundleDir);
- rmSync(bundleDir, { recursive: true, force: true });
-
- if (upToDate) {
- const v = getSkillsVersion(root);
- console.log(`Skills are up to date${v ? ` (v${v})` : ''}.`);
- } else {
- console.log('Updates available.');
- console.log('Run `npx impeccable skills update` to update.');
- }
- } catch (e) {
- console.error(`Could not check for updates: ${e.message}`);
- process.exit(1);
- }
-}
-
-// ─── skills install ───────────────────────────────────────────────────────────
-
-// Check if impeccable skills are already present in any provider folder
-function isAlreadyInstalled(root) {
- for (const d of PROVIDER_DIRS) {
- const skillsDir = join(root, d, 'skills');
- if (!existsSync(skillsDir)) continue;
- try {
- const entries = readdirSync(skillsDir);
- // Look for 'impeccable' skill (or prefixed variant, or legacy 'teach-impeccable')
- if (entries.some(e =>
- e === 'impeccable' || e.endsWith('-impeccable') ||
- e === 'teach-impeccable' || e.endsWith('-teach-impeccable')
- )) {
- return d;
- }
- } catch {}
- }
- return null;
-}
-
-function escapeRegex(str) {
- return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
-}
-
-function prefixSkillContent(content, prefix, allSkillNames) {
- // Prefix the name in frontmatter
- let result = content.replace(/^name:\s*(.+)$/m, (_, name) => `name: ${prefix}${name.trim()}`);
-
- // Prefix cross-references: /skillname -> /prefix-skillname
- const sorted = [...allSkillNames].sort((a, b) => b.length - a.length);
- for (const name of sorted) {
- // Command invocations: /skillname
- result = result.replace(
- new RegExp(`/(?=${escapeRegex(name)}(?:[^a-zA-Z0-9_-]|$))`, 'g'),
- `/${prefix}`
- );
- // Prose references: "the skillname skill"
- result = result.replace(
- new RegExp(`(the) ${escapeRegex(name)} skill`, 'gi'),
- (_, article) => `${article} ${prefix}${name} skill`
- );
- }
- return result;
-}
-
-function isSkillDir(skillsDir, name) {
- // Skill entries can be real directories or symlinks to directories (npx skills uses symlinks)
- const full = join(skillsDir, name);
- try {
- return statSync(full).isDirectory() && existsSync(join(full, 'SKILL.md'));
- } catch { return false; }
-}
-
-function isRealSkillDir(skillsDir, name) {
- // Only real directories, not symlinks -- renaming the real dir renames the symlink targets too
- const full = join(skillsDir, name);
- try {
- const lstat = lstatSync(full);
- return lstat.isDirectory() && !lstat.isSymbolicLink() && existsSync(join(full, 'SKILL.md'));
- } catch { return false; }
-}
-
-function renameSkillsWithPrefix(root, prefix) {
- // First pass: collect all skill names across all providers (use first provider found)
- let allSkillNames = [];
- for (const d of PROVIDER_DIRS) {
- const skillsDir = join(root, d, 'skills');
- if (!existsSync(skillsDir)) continue;
- const entries = readdirSync(skillsDir);
- allSkillNames = entries.filter(name => isSkillDir(skillsDir, name));
- if (allSkillNames.length > 0) break;
- }
-
- // Second pass: rename real dirs and update their content
- let count = 0;
- for (const d of PROVIDER_DIRS) {
- const skillsDir = join(root, d, 'skills');
- if (!existsSync(skillsDir)) continue;
- try {
- const entries = readdirSync(skillsDir);
- for (const name of entries) {
- if (name.startsWith(prefix)) continue;
- if (!isRealSkillDir(skillsDir, name)) continue;
-
- const src = join(skillsDir, name);
- const dest = join(skillsDir, prefix + name);
-
- renameSync(src, dest);
-
- // Prefix frontmatter name + all cross-references in SKILL.md
- let content = readFileSync(join(dest, 'SKILL.md'), 'utf8');
- content = prefixSkillContent(content, prefix, allSkillNames);
- writeFileSync(join(dest, 'SKILL.md'), content);
- count++;
- }
- } catch {}
- }
-
- // Third pass: fix symlinks that now point to renamed targets (npx skills uses these)
- for (const d of PROVIDER_DIRS) {
- const skillsDir = join(root, d, 'skills');
- if (!existsSync(skillsDir)) continue;
- try {
- const entries = readdirSync(skillsDir);
- for (const name of entries) {
- if (name.startsWith(prefix)) continue;
- const full = join(skillsDir, name);
- try {
- if (!lstatSync(full).isSymbolicLink()) continue;
- const target = readlinkSync(full);
- const newTarget = target.replace(new RegExp(`/${escapeRegex(name)}$`), `/${prefix}${name}`);
- unlinkSync(full);
- symlinkSync(newTarget, join(skillsDir, prefix + name));
- } catch {}
- }
- } catch {}
- }
-
- return count;
-}
-
-async function install(flags) {
- const force = flags.includes('--force');
- const yes = flags.includes('-y') || flags.includes('--yes');
- const prefixFlag = flags.find(f => f.startsWith('--prefix='));
- const root = findProjectRoot();
- const existing = isAlreadyInstalled(root);
-
- if (existing && !force) {
- console.log(`Impeccable skills are already installed (found in ${existing}/).`);
- console.log('Run with --force to reinstall.\n');
- process.exit(0);
- }
-
- console.log('Installing impeccable skills via npx skills...\n');
- try {
- // --copy forces npx skills to install each provider's variant separately
- // instead of symlinking .claude/skills/ to .agents/skills/. The two
- // directories have meaningfully different per-provider content (frontmatter,
- // command prefix, paths), and the default symlink also fails silently when
- // .claude/ doesn't exist yet or on Windows without elevated privileges (#140).
- execSync(`npx skills add pbakaus/impeccable --copy${yes ? ' -y' : ''}`, { stdio: 'inherit' });
- } catch (e) {
- process.exit(e.status ?? 1);
- }
-
- // Ask about prefixing (skip in CI mode unless --prefix= is set)
- let prefix = '';
- if (prefixFlag) {
- prefix = prefixFlag.split('=')[1] || 'i-';
- } else if (!yes) {
- console.log();
- const wantPrefix = await ask('Prefix commands to avoid conflicts? e.g. /i-audit instead of /audit (y/N) ');
- if (wantPrefix === 'y' || wantPrefix === 'yes') {
- const custom = await ask('Prefix (default: i-): ');
- prefix = custom || 'i-';
- }
- }
-
- if (prefix) {
- const count = renameSkillsWithPrefix(root, prefix);
- if (count > 0) {
- console.log(`\nRenamed ${count} skills with "${prefix}" prefix.`);
- console.log(`Commands are now available as /${prefix}<command> (e.g. /${prefix}audit).`);
- }
- }
-
- // Clean up deprecated skills from previous versions
- try {
- const { cleanup } = await import('../../../skill/scripts/cleanup-deprecated.mjs');
- const result = cleanup(root);
- const total = result.deletedPaths.length + result.removedLockEntries.length;
- if (total > 0) {
- console.log(`Cleaned up ${total} deprecated skill(s) from previous versions.`);
- }
- } catch {
- // Cleanup script not available -- skip
- }
-
- console.log(`\nDone! Run /${prefix}impeccable teach in your AI harness to set up design context.\n`);
-}
-
-/** Detect prefix by looking for the 'impeccable' skill (or legacy 'teach-impeccable') */
-function detectPrefix(root) {
- for (const d of PROVIDER_DIRS) {
- const skillsDir = join(root, d, 'skills');
- if (!existsSync(skillsDir)) continue;
- for (const name of readdirSync(skillsDir)) {
- if (name === 'impeccable') return '';
- if (name.endsWith('-impeccable') && name !== 'teach-impeccable') return name.slice(0, -'impeccable'.length);
- // Legacy fallback
- if (name === 'teach-impeccable') return '';
- if (name.endsWith('-teach-impeccable')) return name.slice(0, -'teach-impeccable'.length);
- }
- }
- return '';
-}
-
-/** Undo prefixing: rename folders back and strip prefix from SKILL.md content */
-function undoPrefix(root, prefix) {
- if (!prefix) return;
- // Collect the unprefixed names (strip our prefix)
- let allPrefixedNames = [];
- for (const d of PROVIDER_DIRS) {
- const skillsDir = join(root, d, 'skills');
- if (!existsSync(skillsDir)) continue;
- allPrefixedNames = readdirSync(skillsDir).filter(n => n.startsWith(prefix) && isRealSkillDir(skillsDir, n));
- if (allPrefixedNames.length > 0) break;
- }
- const unprefixedNames = allPrefixedNames.map(n => n.slice(prefix.length));
-
- for (const d of PROVIDER_DIRS) {
- const skillsDir = join(root, d, 'skills');
- if (!existsSync(skillsDir)) continue;
- for (const name of readdirSync(skillsDir)) {
- if (!name.startsWith(prefix)) continue;
- const unprefixed = name.slice(prefix.length);
- const src = join(skillsDir, name);
- const dest = join(skillsDir, unprefixed);
-
- if (lstatSync(src).isSymbolicLink()) {
- const target = readlinkSync(src);
- const newTarget = target.replace(`/${name}`, `/${unprefixed}`);
- unlinkSync(src);
- symlinkSync(newTarget, dest);
- } else {
- renameSync(src, dest);
- // Strip prefix from SKILL.md content
- const skillMd = join(dest, 'SKILL.md');
- if (existsSync(skillMd)) {
- let content = readFileSync(skillMd, 'utf8');
- // Reverse the prefixing: replace prefixed names with unprefixed
- content = content.replace(new RegExp(`^name:\\s*${escapeRegex(prefix)}`, 'm'), 'name: ');
- const sorted = [...allPrefixedNames].sort((a, b) => b.length - a.length);
- for (const pName of sorted) {
- const uName = pName.slice(prefix.length);
- content = content.replace(new RegExp(`/${escapeRegex(pName)}(?=[^a-zA-Z0-9_-]|$)`, 'g'), `/${uName}`);
- content = content.replace(new RegExp(`(the) ${escapeRegex(pName)} skill`, 'gi'), `$1 ${uName} skill`);
- }
- writeFileSync(skillMd, content);
- }
- }
- }
- }
-}
-
-// ─── skills update ────────────────────────────────────────────────────────────
-
-function findProjectRoot() {
- let dir = process.cwd();
- while (dir !== dirname(dir)) {
- if (existsSync(join(dir, '.git'))) return dir;
- dir = dirname(dir);
- }
- return process.cwd();
-}
-
-function findInstalledProviders(root) {
- const found = [];
- for (const d of PROVIDER_DIRS) {
- const skillsDir = join(root, d, 'skills');
- if (!existsSync(skillsDir)) continue;
- try {
- const entries = readdirSync(skillsDir);
- if (entries.some(name => isSkillDir(skillsDir, name))) found.push(d);
- } catch {}
- }
- return found;
-}
-
-function getModifiedSkillFiles(root, providerDirs) {
- // Use git to check if any skill files have local modifications
- const modified = [];
- try {
- const status = execSync('git status --porcelain', { cwd: root, encoding: 'utf8' });
- for (const line of status.split('\n')) {
- if (!line.trim()) continue;
- const file = line.substring(3);
- for (const d of providerDirs) {
- if (file.startsWith(`${d}/skills/`)) {
- const flag = line.substring(0, 2).trim();
- modified.push({ file, flag });
- }
- }
- }
- } catch {
- // Not a git repo or git not available
- }
- return modified;
-}
-
-function downloadFile(url, dest) {
- return new Promise((resolve, reject) => {
- const file = createWriteStream(dest);
- get(url, (res) => {
- if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
- // Follow redirect
- get(res.headers.location, (res2) => {
- res2.pipe(file);
- file.on('finish', () => { file.close(); resolve(); });
- }).on('error', reject);
- return;
- }
- if (res.statusCode !== 200) {
- reject(new Error(`HTTP ${res.statusCode}`));
- return;
- }
- res.pipe(file);
- file.on('finish', () => { file.close(); resolve(); });
- }).on('error', reject);
- });
-}
-
-async function update(flags = []) {
- const yes = flags.includes('-y') || flags.includes('--yes');
-
- // Clean up deprecated skills from previous versions.
- try {
- const { cleanup } = await import('../../../skill/scripts/cleanup-deprecated.mjs');
- const root = findProjectRoot();
- const result = cleanup(root);
- const total = result.deletedPaths.length + result.removedLockEntries.length;
- if (total > 0) {
- console.log(`Cleaned up ${total} deprecated skill(s) from previous versions.\n`);
- }
- } catch {
- // Cleanup script not available (e.g. running from npm package) -- skip
- }
-
- // Download the latest skills directly from impeccable.style.
- // We skip `npx skills update` because it has a known upstream bug
- // (vercel-labs/skills#775) where it can't find the lock file.
- const root = findProjectRoot();
- const providers = findInstalledProviders(root);
-
- if (providers.length === 0) {
- console.log('No impeccable skill folders found in this project.');
- console.log('Run `npx impeccable skills install` to install first.');
- process.exit(1);
- }
-
- console.log('Checking for updates...');
-
- let tmpDir;
- try {
- tmpDir = await downloadAndExtractBundle();
- } catch (e) {
- console.error(`Download failed: ${e.message}`);
- process.exit(1);
- }
-
- // Compare local vs remote -- skip if already up to date
- if (isUpToDate(root, providers, tmpDir)) {
- rmSync(tmpDir, { recursive: true, force: true });
- const v = getSkillsVersion(root);
- console.log(`Skills are up to date${v ? ` (v${v})` : ''}. Nothing to do.`);
- process.exit(0);
- }
-
- console.log(`Found skills in: ${providers.join(', ')}`);
-
- if (!yes) {
- const ans = await ask(`Update skills in ${providers.length} provider folder(s)? (Y/n) `);
- if (ans === 'n' || ans === 'no') {
- rmSync(tmpDir, { recursive: true, force: true });
- console.log('Aborted.');
- process.exit(0);
- }
- }
-
- try {
-
- // Copy from the bundle to each unique provider folder.
- // Deduplicate so symlinked dirs (e.g. .claude/skills -> .agents/skills)
- // are only written once with the correct provider's content.
- const unique = deduplicateProviders(root, providers);
- let updated = 0;
- for (const { provider, localSkillsDir } of unique) {
- const srcDir = join(tmpDir, provider, 'skills');
- if (!existsSync(srcDir)) continue;
-
- const skills = readdirSync(srcDir, { withFileTypes: true });
- for (const skill of skills) {
- if (!skill.isDirectory()) continue;
- const src = join(srcDir, skill.name);
- const dest = join(localSkillsDir, skill.name);
- if (existsSync(dest)) rmSync(dest, { recursive: true });
- copyDirSync(src, dest);
- updated++;
- }
- }
-
- rmSync(tmpDir, { recursive: true, force: true });
-
- // Re-apply prefix if detected
- const prefix = detectPrefix(root);
- if (prefix) {
- const count = renameSkillsWithPrefix(root, prefix);
- if (count > 0) console.log(`Re-applied "${prefix}" prefix to ${count} skills.`);
- }
-
- // Run cleanup to remove deprecated stubs from the fresh download
- try {
- const { cleanup: postCleanup } = await import('../../../skill/scripts/cleanup-deprecated.mjs');
- postCleanup(root);
- } catch {
- // Not available -- skip
- }
-
- const v = getSkillsVersion(root);
- console.log(`Updated ${updated} skill(s)${v ? ` to v${v}` : ''}.`);
- console.log('Done!\n');
- } catch (e) {
- console.error(`Update failed: ${e.message}`);
- if (tmpDir) rmSync(tmpDir, { recursive: true, force: true });
- process.exit(1);
- }
-}
-
-function copyDirSync(src, dest) {
- mkdirSync(dest, { recursive: true });
- for (const entry of readdirSync(src, { withFileTypes: true })) {
- const s = join(src, entry.name);
- const d = join(dest, entry.name);
- if (entry.isDirectory()) {
- copyDirSync(s, d);
- } else {
- writeFileSync(d, readFileSync(s));
- }
- }
-}
-
-// ─── Router ───────────────────────────────────────────────────────────────────
-
-export async function run(args) {
- const sub = args[0];
-
- if (!sub || sub === 'help' || sub === '--help' || sub === '-h') {
- await showHelp();
- } else if (sub === 'install') {
- await install(args.slice(1));
- } else if (sub === 'update') {
- await update(args.slice(1));
- } else if (sub === 'check') {
- await check();
- } else {
- console.error(`Unknown skills command: ${sub}`);
- console.error(`Run 'impeccable skills --help' for available commands.`);
- process.exit(1);
- }
-}
@@ -1,1688 +0,0 @@
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
@@ -1,232 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
-import { detectHtml } from '../engines/static-html/detect-html.mjs';
-import { detectText } from '../engines/regex/detect-text.mjs';
-import {
- HTML_EXTENSIONS,
- buildImportGraph,
- detectFrameworkConfig,
- isPortListening,
- walkDir,
-} from '../node/file-system.mjs';
-
-// ---------------------------------------------------------------------------
-// Output formatting
-// ---------------------------------------------------------------------------
-
-function formatFindings(findings, jsonMode) {
- if (jsonMode) return JSON.stringify(findings, null, 2);
-
- const grouped = {};
- for (const f of findings) {
- if (!grouped[f.file]) grouped[f.file] = [];
- grouped[f.file].push(f);
- }
- const out = [];
- for (const [file, items] of Object.entries(grouped)) {
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
- out.push(`\n${file}${importNote}`);
- for (const item of items) {
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
- out.push(` → ${item.description}`);
- }
- }
- out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
- return out.join('\n');
-}
-
-// ---------------------------------------------------------------------------
-// Stdin handling
-// ---------------------------------------------------------------------------
-
-async function handleStdin() {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- const input = Buffer.concat(chunks).toString('utf-8');
- try {
- const parsed = JSON.parse(input);
- const fp = parsed?.tool_input?.file_path;
- if (fp && fs.existsSync(fp)) {
- return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
- ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
- }
- } catch { /* not JSON */ }
- return detectText(input, '<stdin>');
-}
-
-
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
-async function confirm(question) {
- const rl = (await import('node:readline')).default.createInterface({
- input: process.stdin, output: process.stderr,
- });
- return new Promise((resolve) => {
- rl.question(`${question} [Y/n] `, (answer) => {
- rl.close();
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
- });
- });
-}
-
-function printUsage() {
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
-
-Scan files or URLs for UI anti-patterns and design quality issues.
-
-Options:
- --fast Regex-only mode (skip static HTML/CSS analysis, faster but misses linked stylesheets)
- --json Output results as JSON
- --help Show this help message
-
-Detection modes:
- HTML files Static HTML/CSS analysis (default, catches linked CSS)
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
- URLs Puppeteer full browser rendering (auto-detected)
- --fast Forces regex for all files
-
-Examples:
- impeccable detect src/
- impeccable detect index.html
- impeccable detect https://example.com
- impeccable detect --fast --json .`);
-}
-
-async function detectCli() {
- let args = process.argv.slice(2).map(arg => {
- if (arg === '-json') return '--json';
- if (arg === '-fast') return '--fast';
- return arg;
- });
- if (args[0] === 'detect') args = args.slice(1);
- const jsonMode = args.includes('--json');
- const helpMode = args.includes('--help');
- const fastMode = args.includes('--fast');
- const targets = args.filter(a => !a.startsWith('--'));
-
- if (helpMode) { printUsage(); process.exit(0); }
-
- let allFindings = [];
-
- if (!process.stdin.isTTY && targets.length === 0) {
- allFindings = await handleStdin();
- } else {
- const paths = targets.length > 0 ? targets : [process.cwd()];
- const urlTargetCount = paths.filter(target => /^https?:\/\//i.test(target)).length;
- const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
-
- try {
- for (const target of paths) {
- if (/^https?:\/\//i.test(target)) {
- try {
- const scanner = browserDetector
- ? (url) => browserDetector.detectUrl(url)
- : (url) => detectUrl(url);
- allFindings.push(...await scanner(target));
- } catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
- continue;
- }
-
- const resolved = path.resolve(target);
- let stat;
- try { stat = fs.statSync(resolved); }
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
-
- if (stat.isDirectory()) {
- // Check for framework dev server config (skip in JSON mode to avoid polluting output)
- if (!jsonMode) {
- const fwConfig = detectFrameworkConfig(resolved);
- if (fwConfig) {
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
- if (probe.listening && probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
- `For more accurate results, scan the running site:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- } else if (probe.listening && !probe.matched) {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
- );
- } else {
- process.stderr.write(
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
- `Start the dev server and scan via URL for best results:\n` +
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
- );
- }
- }
- }
-
- const files = walkDir(resolved);
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
-
- // Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
- if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
- process.stderr.write(
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
- `Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
- `Use --fast to skip static HTML/CSS analysis, or target a specific subdirectory.\n`
- );
- const ok = await confirm('Continue?');
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
- }
-
- // Build import graph for multi-file awareness
- const graph = buildImportGraph(files);
- // Build reverse map: file -> set of files that import it
- const importedByMap = new Map();
- for (const [importer, imports] of graph) {
- for (const imported of imports) {
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
- importedByMap.get(imported).add(importer);
- }
- }
-
- for (const file of files) {
- const ext = path.extname(file).toLowerCase();
- let fileFindings;
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- fileFindings = await detectHtml(file);
- } else {
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
- }
- // Annotate findings with import context
- const importers = importedByMap.get(file);
- if (importers && importers.size > 0) {
- const importerNames = [...importers].map(f => path.basename(f));
- for (const f of fileFindings) {
- f.importedBy = importerNames;
- }
- }
- allFindings.push(...fileFindings);
- }
- } else if (stat.isFile()) {
- const ext = path.extname(resolved).toLowerCase();
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
- allFindings.push(...await detectHtml(resolved));
- } else {
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
- }
- }
- }
- } finally {
- if (browserDetector) await browserDetector.close();
- }
- }
-
- if (allFindings.length > 0) {
- if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
- else process.stderr.write(formatFindings(allFindings, false) + '\n');
- process.exit(2);
- }
- if (jsonMode) process.stdout.write('[]\n');
- process.exit(0);
-}
-
-export { formatFindings, handleStdin, confirm, printUsage, detectCli };
@@ -1,4030 +0,0 @@
-/**
- * Anti-Pattern Browser Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * GENERATED -- do not edit. Source: cli/engine/browser/injected/index.mjs
- * Rebuild: node scripts/build-browser-detector.js
- *
- * Usage: <script src="detect-antipatterns-browser.js"></script>
- * Re-scan: window.impeccableScan()
- */
-(function () {
-if (typeof window === 'undefined') return;
-// --- cli/engine/shared/constants.mjs ---
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-// --- cli/engine/registry/antipatterns.mjs ---
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-// --- cli/engine/shared/color.mjs ---
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-// --- cli/engine/rules/checks.mjs ---
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-// --- cli/engine/browser/injected/index.mjs ---
-const IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
-
-if (IS_BROWSER) {
- // Detect extension mode via the script tag's data attribute or the document element fallback.
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
- const _myScript = document.currentScript;
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
- || document.documentElement.dataset.impeccableExtension === 'true';
-
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
- const LABEL_BG = BRAND_COLOR;
- const OUTLINE_COLOR = BRAND_COLOR;
-
- // Inject hover styles via CSS (more reliable than JS event listeners)
- const styleEl = document.createElement('style');
- styleEl.textContent = `
- @keyframes impeccable-reveal {
- from { opacity: 0; }
- to { opacity: 1; }
- }
- .impeccable-overlay:not(.impeccable-banner) {
- pointer-events: none;
- outline: 2px solid ${OUTLINE_COLOR};
- border-radius: 4px;
- transition: outline-color 0.15s ease;
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
- animation-play-state: paused;
- border-top-left-radius: 0;
- }
- .impeccable-overlay.impeccable-visible {
- animation-play-state: running;
- }
- .impeccable-overlay.impeccable-hover {
- outline-color: ${BRAND_COLOR_HOVER};
- z-index: 100001 !important;
- }
- .impeccable-overlay.impeccable-hover .impeccable-label {
- background: ${BRAND_COLOR_HOVER};
- }
- .impeccable-overlay.impeccable-spotlight {
- z-index: 100002 !important;
- }
- .impeccable-overlay.impeccable-spotlight-dimmed {
- opacity: 0.15 !important;
- animation: none !important;
- filter: blur(3px);
- }
- .impeccable-spotlight-backdrop {
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- backdrop-filter: blur(3px) brightness(0.6);
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
- pointer-events: none;
- z-index: 99998;
- opacity: 0;
- outline: none !important;
- animation: none !important;
- }
- .impeccable-spotlight-backdrop.impeccable-visible {
- opacity: 1;
- }
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
- display: none !important;
- }
- `;
- (document.head || document.documentElement).appendChild(styleEl);
-
- // Spotlight backdrop element (created lazily on first use)
- let spotlightBackdrop = null;
- let spotlightTarget = null;
-
- function getSpotlightBackdrop() {
- if (!spotlightBackdrop) {
- spotlightBackdrop = document.createElement('div');
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
- document.body.appendChild(spotlightBackdrop);
- }
- return spotlightBackdrop;
- }
-
- function updateSpotlightClipPath() {
- if (!spotlightBackdrop || !spotlightTarget) return;
- const r = spotlightTarget.getBoundingClientRect();
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
- const inset = 4;
- const radius = 6; // outline border-radius (4) + outline width (2)
- const x1 = r.left - inset;
- const y1 = r.top - inset;
- const x2 = r.right + inset;
- const y2 = r.bottom + inset;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- // Outer rect + rounded inner rect (evenodd creates a hole)
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
- }
-
- function showSpotlight(target) {
- if (!target || !target.getBoundingClientRect) return;
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
- spotlightTarget = target;
- return;
- }
- spotlightTarget = target;
- const bd = getSpotlightBackdrop();
- updateSpotlightClipPath();
- bd.classList.add('impeccable-visible');
- }
-
- function hideSpotlight() {
- spotlightTarget = null;
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
- }
-
- function isInViewport(el) {
- const r = el.getBoundingClientRect();
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
- }
-
- // Reposition spotlight on scroll/resize
- window.addEventListener('scroll', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- }, { passive: true });
- window.addEventListener('resize', () => {
- if (spotlightTarget) updateSpotlightClipPath();
- });
-
- const overlays = [];
- const TYPE_LABELS = {};
- const RULE_CATEGORY = {};
- for (const ap of ANTIPATTERNS) {
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
- }
-
- function isInFixedContext(el) {
- let p = el;
- while (p && p !== document.body) {
- if (getComputedStyle(p).position === 'fixed') return true;
- p = p.parentElement;
- }
- return false;
- }
-
- function positionOverlay(overlay) {
- const el = overlay._targetEl;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (overlay._isFixed) {
- // Viewport-relative coords for fixed targets
- overlay.style.top = `${rect.top - 2}px`;
- overlay.style.left = `${rect.left - 2}px`;
- } else {
- // Document-relative coords for normal targets
- overlay.style.top = `${rect.top + scrollY - 2}px`;
- overlay.style.left = `${rect.left + scrollX - 2}px`;
- }
- overlay.style.width = `${rect.width + 4}px`;
- overlay.style.height = `${rect.height + 4}px`;
- }
-
- function repositionOverlays() {
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
- // Skip overlays whose target is currently hidden (display: none on the overlay)
- if (o.style.display === 'none') continue;
- positionOverlay(o);
- }
- }
-
- let resizeRAF;
- const onResize = () => {
- cancelAnimationFrame(resizeRAF);
- resizeRAF = requestAnimationFrame(repositionOverlays);
- };
- window.addEventListener('resize', onResize);
- // Reposition on scroll too -- catches sticky/parallax shifts
- window.addEventListener('scroll', onResize, { passive: true });
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
- if (typeof ResizeObserver !== 'undefined') {
- const bodyResizeObserver = new ResizeObserver(onResize);
- bodyResizeObserver.observe(document.body);
- }
-
- // Track target element visibility via IntersectionObserver.
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
- // while display:none / closed <details> / hidden modals etc. do not.
- // This is event-driven -- no polling needed.
- let overlayIndex = 0;
- const visibilityObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- const overlay = entry.target._impeccableOverlay;
- if (!overlay) continue;
- if (entry.isIntersecting) {
- overlay.style.display = '';
- positionOverlay(overlay);
- if (!overlay._revealed) {
- overlay._revealed = true;
- if (firstScanDone) {
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
- overlay.style.animation = 'none';
- } else {
- // Initial scan: staggered cascade reveal
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
- }
- requestAnimationFrame(() => {
- overlay.classList.add('impeccable-visible');
- if (overlay._checkLabel) overlay._checkLabel();
- });
- }
- } else {
- overlay.style.display = 'none';
- }
- }
- }, { rootMargin: '99999px' });
-
- function detachOverlay(overlay) {
- if (!overlay) return;
- if (typeof overlay._cleanup === 'function') {
- try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
- }
- if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
- visibilityObserver.unobserve(overlay._targetEl);
- delete overlay._targetEl._impeccableOverlay;
- }
- const idx = overlays.indexOf(overlay);
- if (idx >= 0) overlays.splice(idx, 1);
- overlay.remove();
- }
-
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
- // Listens at document level so it catches transitions on ancestor elements
- // (the transform may be on a parent, not the flagged element itself).
- document.addEventListener('transitionend', (e) => {
- if (e.propertyName !== 'transform') return;
- for (const o of overlays) {
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
- positionOverlay(o);
- }
- }
- });
-
- const highlight = function(el, findings) {
- if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
-
- const fixed = isInFixedContext(el);
- const rect = el.getBoundingClientRect();
- const outline = document.createElement('div');
- outline.className = 'impeccable-overlay';
- outline._targetEl = el;
- outline._isFixed = fixed;
- Object.assign(outline.style, {
- position: fixed ? 'fixed' : 'absolute',
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
- zIndex: '99999', boxSizing: 'border-box',
- });
-
- // Build per-finding label entries: ✦ prefix for slop
- const entries = findings.map(f => {
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
- return { name: prefix + name, detail: f.detail || f.snippet };
- });
- const allText = entries.map(e => e.name).join(', ');
-
- const label = document.createElement('div');
- label.className = 'impeccable-label';
- Object.assign(label.style, {
- position: 'absolute', bottom: '100%', left: '-2px',
- display: 'flex', alignItems: 'center',
- whiteSpace: 'nowrap',
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
- color: 'white', lineHeight: '14px',
- background: LABEL_BG,
- fontFamily: 'system-ui, sans-serif',
- borderRadius: '4px 4px 0 0',
- });
-
- const textSpan = document.createElement('span');
- textSpan.style.padding = '3px 8px';
- textSpan.textContent = allText;
- label.appendChild(textSpan);
-
- // State for cycling mode
- let cycleMode = false;
- let cycleIndex = 0;
- let isHovered = false;
- let prevBtn, nextBtn;
-
- function updateCycleText() {
- const e = entries[cycleIndex];
- textSpan.textContent = isHovered ? e.detail : e.name;
- }
-
- function enableCycleMode() {
- if (cycleMode || entries.length < 2) return;
- cycleMode = true;
-
- const btnStyle = {
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
- pointerEvents: 'auto',
- };
-
- const navGroup = document.createElement('span');
- Object.assign(navGroup.style, {
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
- });
-
- prevBtn = document.createElement('button');
- prevBtn.textContent = '\u2039';
- Object.assign(prevBtn.style, btnStyle);
- prevBtn.style.paddingLeft = '6px';
- prevBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
- updateCycleText();
- });
-
- nextBtn = document.createElement('button');
- nextBtn.textContent = '\u203A';
- Object.assign(nextBtn.style, btnStyle);
- nextBtn.style.paddingRight = '2px';
- nextBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- cycleIndex = (cycleIndex + 1) % entries.length;
- updateCycleText();
- });
-
- navGroup.appendChild(prevBtn);
- navGroup.appendChild(nextBtn);
- label.insertBefore(navGroup, textSpan);
- textSpan.style.padding = '3px 8px 3px 4px';
- updateCycleText();
- }
-
- outline.appendChild(label);
-
- // Start hidden; the IntersectionObserver will show it once the target is rendered
- outline.style.display = 'none';
- outline._staggerIndex = overlayIndex++;
- el._impeccableOverlay = outline;
- visibilityObserver.observe(el);
-
- // After first paint, check label width vs outline
- outline._checkLabel = () => {
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
- enableCycleMode();
- }
- };
-
- // Hover: show detail text, darken
- const onMouseEnter = () => {
- isHovered = true;
- outline.classList.add('impeccable-hover');
- outline.style.outlineColor = BRAND_COLOR_HOVER;
- label.style.background = BRAND_COLOR_HOVER;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
- }
- };
- const onMouseLeave = () => {
- isHovered = false;
- outline.classList.remove('impeccable-hover');
- outline.style.outlineColor = '';
- label.style.background = LABEL_BG;
- if (cycleMode) {
- updateCycleText();
- } else {
- textSpan.textContent = allText;
- }
- };
- el.addEventListener('mouseenter', onMouseEnter);
- el.addEventListener('mouseleave', onMouseLeave);
- outline._cleanup = () => {
- el.removeEventListener('mouseenter', onMouseEnter);
- el.removeEventListener('mouseleave', onMouseLeave);
- };
-
- document.body.appendChild(outline);
- overlays.push(outline);
- };
-
- const showPageBanner = function(findings) {
- if (!findings.length) return;
- const banner = document.createElement('div');
- banner.className = 'impeccable-overlay impeccable-banner';
- Object.assign(banner.style, {
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
- background: LABEL_BG, color: 'white',
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
- transform: 'translateY(-100%)',
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- });
- requestAnimationFrame(() => requestAnimationFrame(() => {
- banner.style.transform = 'translateY(0)';
- }));
-
- // Scrollable findings area
- const scrollArea = document.createElement('div');
- Object.assign(scrollArea.style, {
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
- display: 'flex', gap: '8px', alignItems: 'center',
- padding: '0 12px', scrollSnapType: 'x mandatory',
- scrollbarWidth: 'none',
- });
- for (const f of findings) {
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
- const tag = document.createElement('span');
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
- Object.assign(tag.style, {
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
- });
- scrollArea.appendChild(tag);
- }
- banner.appendChild(scrollArea);
-
- // Controls area (only in standalone mode, not extension)
- if (!EXTENSION_MODE) {
- const controls = document.createElement('div');
- Object.assign(controls.style, {
- display: 'flex', alignItems: 'center', gap: '2px',
- padding: '0 8px', flexShrink: '0',
- });
-
- // Toggle visibility button
- const toggle = document.createElement('button');
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
- toggle.title = 'Toggle overlay visibility';
- Object.assign(toggle.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
- opacity: '0.85', transition: 'opacity 0.15s',
- });
- let overlaysVisible = true;
- toggle.addEventListener('click', () => {
- overlaysVisible = !overlaysVisible;
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
- });
- controls.appendChild(toggle);
-
- // Close button
- const close = document.createElement('button');
- close.textContent = '\u00d7';
- close.title = 'Dismiss banner';
- Object.assign(close.style, {
- background: 'none', border: 'none',
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
- });
- close.addEventListener('click', () => banner.remove());
- controls.appendChild(close);
-
- banner.appendChild(controls);
- }
- document.body.appendChild(banner);
- overlays.push(banner);
- };
-
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
- // These change between builds and produce brittle, ugly selectors.
- function isLikelyHashedClass(c) {
- if (!c) return true;
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
- if (/^_[\w-]{5,}$/.test(c)) return true;
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
- return false;
- }
-
- function buildSelectorSegment(el) {
- const tag = el.tagName.toLowerCase();
- let sel = tag;
-
- if (el.classList && el.classList.length > 0) {
- const classes = [...el.classList]
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
- .slice(0, 2);
- if (classes.length > 0) {
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
- }
- }
-
- // Disambiguate among siblings only if the parent has multiple matches
- const parent = el.parentElement;
- if (parent) {
- try {
- const matching = parent.querySelectorAll(':scope > ' + sel);
- if (matching.length > 1) {
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
- const idx = sameType.indexOf(el) + 1;
- sel += `:nth-of-type(${idx})`;
- }
- } catch {
- const idx = [...parent.children].indexOf(el) + 1;
- sel = `${tag}:nth-child(${idx})`;
- }
- }
- return sel;
- }
-
- function generateSelector(el) {
- if (el === document.body) return 'body';
- if (el === document.documentElement) return 'html';
- if (el.id) return '#' + CSS.escape(el.id);
-
- const parts = [];
- let current = el;
- let depth = 0;
- const MAX_DEPTH = 10;
-
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
- parts.unshift(buildSelectorSegment(current));
-
- // Anchor on an ancestor's ID and stop walking up
- if (current.id) {
- parts[0] = '#' + CSS.escape(current.id);
- break;
- }
-
- // Stop as soon as the partial selector uniquely identifies the target
- const trySelector = parts.join(' > ');
- try {
- const matches = document.querySelectorAll(trySelector);
- if (matches.length === 1 && matches[0] === el) {
- return trySelector;
- }
- } catch { /* invalid selector — keep walking */ }
-
- current = current.parentElement;
- depth++;
- }
-
- return parts.join(' > ');
- }
-
- function getDirectText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent || '')
- .join('');
- }
-
- function getDirectTextRect(el) {
- const rects = [];
- for (const node of el.childNodes) {
- if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
- const range = document.createRange();
- range.selectNodeContents(node);
- for (const rect of range.getClientRects()) {
- if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
- }
- range.detach?.();
- }
- if (rects.length === 0) return null;
- const left = Math.min(...rects.map(r => r.left));
- const top = Math.min(...rects.map(r => r.top));
- const right = Math.max(...rects.map(r => r.right));
- const bottom = Math.max(...rects.map(r => r.bottom));
- return {
- left,
- top,
- right,
- bottom,
- width: right - left,
- height: bottom - top,
- x: left,
- y: top,
- };
- }
-
- function collectVisualContrastReasons(el, style) {
- const reasons = new Set();
- const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
- const ownBgImage = style.backgroundImage || '';
- if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
- reasons.add('background-clip text');
- }
- if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
-
- let current = el;
- while (current && current.nodeType === 1) {
- const tag = current.tagName?.toLowerCase();
- const currentStyle = getComputedStyle(current);
- const bgImage = currentStyle.backgroundImage || '';
- const isDocumentSurface = tag === 'body' || tag === 'html';
-
- if (!isDocumentSurface && bgImage && bgImage !== 'none') {
- if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
- if (/gradient/i.test(bgImage)) reasons.add('gradient background');
- }
- if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
- if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
- if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
- if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
-
- const solidBg = parseRgb(currentStyle.backgroundColor);
- if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
- current = current.parentElement;
- }
-
- const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (sampleRect && document.elementsFromPoint) {
- const points = [
- [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
- [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
- ];
- for (const [x, y] of points) {
- if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
- const stack = document.elementsFromPoint(x, y);
- const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
- if (selfIndex < 0) continue;
- for (const node of stack.slice(selfIndex + 1)) {
- const nodeTag = node.tagName?.toLowerCase();
- if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
- reasons.add(`${nodeTag} underlay`);
- break;
- }
- }
- }
- }
-
- return [...reasons];
- }
-
- function collectVisualContrastCandidates(options = {}) {
- const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
- const candidates = [];
- for (const el of document.querySelectorAll('*')) {
- if (candidates.length >= maxCandidates) break;
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- if (el.closest('[id^="impeccable-live-"]')) continue;
- if (el === document.body || el === document.documentElement) continue;
-
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (style.display === 'none' || style.visibility === 'hidden') continue;
- const directText = getDirectText(el);
- const hasDirectText = directText.trim().length > 0;
- if (!hasDirectText || isEmojiOnlyText(directText)) continue;
-
- const bgColor = readOwnBackgroundColor(el, style);
- const isStyledButton = (tag === 'a' || tag === 'button')
- && bgColor && bgColor.a > 0.5;
- if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) continue;
-
- const reasons = collectVisualContrastReasons(el, style);
- if (reasons.length === 0) continue;
-
- const textColor = parseRgb(style.color);
- const fontSize = parseFloat(style.fontSize) || 16;
- const fontWeight = parseInt(style.fontWeight) || 400;
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- const clip = {
- x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
- y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
- width: Math.max(1, Math.ceil(rect.width + 4)),
- height: Math.max(1, Math.ceil(rect.height + 4)),
- };
-
- candidates.push({
- selector: generateSelector(el),
- tagName: tag,
- text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
- threshold,
- reasons,
- clip,
- textColor,
- preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
- reason === 'opacity stack' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'background-clip text'
- ),
- backgroundClipText: reasons.includes('background-clip text'),
- });
- }
- return candidates;
- }
-
- const visualContrastImageCache = new Map();
- const visualContrastRasterCache = new WeakMap();
-
- function clampByte(value) {
- return Math.max(0, Math.min(255, Math.round(value)));
- }
-
- function blendRgba(fg, bg) {
- if (!fg) return bg || null;
- if (!bg || fg.a == null || fg.a >= 0.999) {
- return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
- }
- const alpha = Math.max(0, Math.min(1, fg.a));
- return {
- r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
- g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
- b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
- a: 1,
- };
- }
-
- function pickWorstContrastColor(textColor, colors) {
- const usable = (colors || []).filter(Boolean);
- if (!usable.length) return null;
- let worst = usable[0];
- let worstRatio = contrastRatio(textColor, worst);
- for (const color of usable.slice(1)) {
- const ratio = contrastRatio(textColor, color);
- if (ratio < worstRatio) {
- worst = color;
- worstRatio = ratio;
- }
- }
- return worst;
- }
-
- function firstCssUrl(value) {
- const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
- if (!match) return '';
- return (match[1] || match[2] || match[3] || '').trim();
- }
-
- function getLayerValue(value, index = 0) {
- return String(value || '').split(',')[index]?.trim() || '';
- }
-
- function parsePositionToken(token, container, painted) {
- if (!token || token === 'center') return (container - painted) / 2;
- if (token === 'left' || token === 'top') return 0;
- if (token === 'right' || token === 'bottom') return container - painted;
- if (/%$/.test(token)) {
- const pct = parseFloat(token) / 100;
- return (container - painted) * pct;
- }
- if (/px$/.test(token)) return parseFloat(token) || 0;
- return (container - painted) / 2;
- }
-
- function parsePositionPair(positionValue) {
- const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
- const first = tokens[0] || '50%';
- if (tokens.length < 2) {
- if (first === 'top' || first === 'bottom') return ['50%', first];
- return [first, '50%'];
- }
- return [first, tokens[1] || '50%'];
- }
-
- function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- let paintedWidth = intrinsicWidth;
- let paintedHeight = intrinsicHeight;
- const size = String(sizeValue || 'auto').trim();
-
- if (size === 'cover' || size === 'contain') {
- const scale = size === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (size && size !== 'auto') {
- const parts = size.split(/\s+/);
- const widthToken = parts[0];
- const heightToken = parts[1] || 'auto';
- if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
- else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
- if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
- else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
- else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
- }
-
- const [xToken, yToken] = parsePositionPair(positionValue);
- const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
- const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
- return {
- left: containerRect.left + positionX,
- top: containerRect.top + positionY,
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function parseObjectPosition(positionValue) {
- return parsePositionPair(positionValue);
- }
-
- function resolveObjectImageRect(containerRect, image, style) {
- const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
- const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
- const fit = style.objectFit || 'fill';
- let paintedWidth = containerRect.width;
- let paintedHeight = containerRect.height;
- if (fit === 'contain' || fit === 'cover') {
- const scale = fit === 'cover'
- ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
- : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
- paintedWidth = intrinsicWidth * scale;
- paintedHeight = intrinsicHeight * scale;
- } else if (fit === 'none') {
- paintedWidth = intrinsicWidth;
- paintedHeight = intrinsicHeight;
- } else if (fit === 'scale-down') {
- const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
- paintedWidth = intrinsicWidth * containScale;
- paintedHeight = intrinsicHeight * containScale;
- }
- const [xToken, yToken] = parseObjectPosition(style.objectPosition);
- return {
- left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
- top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
- width: paintedWidth,
- height: paintedHeight,
- intrinsicWidth,
- intrinsicHeight,
- };
- }
-
- function pointToImageSource(point, paintedRect) {
- if (
- point.x < paintedRect.left ||
- point.y < paintedRect.top ||
- point.x > paintedRect.left + paintedRect.width ||
- point.y > paintedRect.top + paintedRect.height
- ) {
- return null;
- }
- return {
- x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
- y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
- };
- }
-
- async function loadVisualContrastImage(src) {
- if (!src) return null;
- if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
- const promise = new Promise(resolve => {
- const img = new Image();
- let settled = false;
- const finish = value => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve(value);
- };
- const timer = setTimeout(() => finish(null), 800);
- try {
- const absolute = new URL(src, location.href);
- if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
- img.crossOrigin = 'anonymous';
- }
- } catch {
- // Let the browser resolve unusual URLs itself.
- }
- img.onload = () => finish(img);
- img.onerror = () => finish(null);
- img.src = src;
- });
- visualContrastImageCache.set(src, promise);
- return promise;
- }
-
- function sampleDrawablePixel(drawable, sourcePoint) {
- if (visualContrastRasterCache.has(drawable)) {
- const cached = visualContrastRasterCache.get(drawable);
- if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
- try {
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = cached.ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- return {
- status: 'unresolved',
- reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
- };
- }
- }
-
- const canvas = document.createElement('canvas');
- const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
- const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
- const maxRasterSide = 640;
- const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
- canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
- canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
- try {
- ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
- const cached = {
- ctx,
- width: canvas.width,
- height: canvas.height,
- scaleX: canvas.width / intrinsicWidth,
- scaleY: canvas.height / intrinsicHeight,
- };
- visualContrastRasterCache.set(drawable, cached);
- const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
- const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
- const data = ctx.getImageData(x, y, 1, 1).data;
- return {
- status: 'sampled',
- color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
- };
- } catch (err) {
- const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
- visualContrastRasterCache.set(drawable, { ctx: null, reason });
- return {
- status: 'unresolved',
- reason,
- };
- }
- }
-
- async function sampleCssBackground(el, style, point, textColor) {
- const rect = el.getBoundingClientRect();
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none') {
- if (/gradient/i.test(bgImage)) {
- const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
- if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
- }
- if (/url\s*\(/i.test(bgImage)) {
- const img = await loadVisualContrastImage(firstCssUrl(bgImage));
- if (!img) return { status: 'unresolved', reason: 'image unavailable' };
- const paintedRect = resolvePaintedImageRect(
- rect,
- img,
- getLayerValue(style.backgroundSize) || 'auto',
- getLayerValue(style.backgroundPosition) || '50% 50%',
- );
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
- return sample;
- }
- }
- const bg = parseRgb(style.backgroundColor);
- if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
- return { status: 'unresolved', reason: 'no readable background' };
- }
-
- async function sampleImageElement(img, point) {
- const rect = img.getBoundingClientRect();
- const style = getComputedStyle(img);
- const paintedRect = resolveObjectImageRect(rect, img, style);
- const sourcePoint = pointToImageSource(point, paintedRect);
- if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
- const sample = sampleDrawablePixel(img, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
-
- if (img.currentSrc || img.src) {
- const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
- if (loaded) {
- const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
- const loadedPoint = pointToImageSource(point, loadedRect);
- if (loadedPoint) {
- const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
- if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
- }
- }
- }
- return sample;
- }
-
- function textSamplePoints(rect) {
- const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
- const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
- const xs = rect.width < 28
- ? [rect.left + rect.width / 2]
- : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
- const ys = rect.height < 22
- ? [rect.top + rect.height / 2]
- : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
- const points = [];
- for (const y of ys) {
- for (const x of xs) {
- if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
- }
- }
- return points;
- }
-
- async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
- if (depth > 8) {
- return { status: 'unresolved', reason: 'background stack too deep' };
- }
- const stack = typeof document.elementsFromPoint === 'function'
- ? document.elementsFromPoint(point.x, point.y)
- : [];
- const selfIndex = stack.findIndex(node => node === el || el.contains(node));
- const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
- const unresolved = [];
-
- for (const node of nodes) {
- if (!node || node.nodeType !== 1) continue;
- if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- const tag = node.tagName?.toLowerCase();
- if (tag === 'img') {
- const sample = await sampleImageElement(node, point);
- if (sample.status === 'sampled') return sample;
- unresolved.push(sample.reason);
- continue;
- }
- if (tag === 'canvas' || tag === 'video') {
- const rect = node.getBoundingClientRect();
- const sourcePoint = pointToImageSource(point, {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- intrinsicWidth: node.width || node.videoWidth || rect.width,
- intrinsicHeight: node.height || node.videoHeight || rect.height,
- });
- if (sourcePoint) {
- const sample = sampleDrawablePixel(node, sourcePoint);
- if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
- unresolved.push(sample.reason);
- }
- continue;
- }
- const style = getComputedStyle(node);
- const sample = await sampleCssBackground(node, style, point, textColor);
- if (sample.status === 'sampled') {
- if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
- const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
- if (under.status === 'sampled') {
- return {
- status: 'sampled',
- color: blendRgba(sample.color, under.color),
- method: `${sample.method}+alpha`,
- };
- }
- return sample;
- }
- unresolved.push(sample.reason);
- }
-
- return {
- status: 'unresolved',
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
- };
- }
-
- async function analyzeVisualContrastCandidate(candidate) {
- let el;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
- }
- if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
-
- const blockingReason = (candidate.reasons || []).find(reason =>
- reason === 'background-clip text' ||
- reason === 'blend mode' ||
- reason === 'filter' ||
- reason === 'backdrop filter' ||
- reason === 'opacity stack' ||
- reason === 'text shadow'
- );
- if (blockingReason) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
- }
-
- const style = getComputedStyle(el);
- const textColor = parseRgb(style.color) || candidate.textColor;
- if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
-
- const rect = getDirectTextRect(el) || el.getBoundingClientRect();
- if (!rect || rect.width < 4 || rect.height < 4) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
- }
-
- const points = textSamplePoints(rect);
- if (points.length === 0) {
- return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
- }
-
- const ratios = [];
- const methods = new Set();
- const unresolved = [];
- for (const point of points) {
- const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
- if (sample.status !== 'sampled' || !sample.color) {
- unresolved.push(sample.reason);
- continue;
- }
- const fg = blendRgba(textColor, sample.color);
- ratios.push(contrastRatio(fg, sample.color));
- if (sample.method) methods.add(sample.method);
- }
-
- if (ratios.length < Math.min(3, points.length)) {
- return {
- ...candidate,
- status: 'unresolved',
- confidence: 'none',
- samples: ratios.length,
- reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- const measuredRatio = pick(10);
- const medianRatio = pick(50);
- const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
- const method = [...methods].sort().join(', ') || 'browser-visual';
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
- return {
- ...candidate,
- status,
- confidence: method.includes('canvas-') ? 'high' : 'medium',
- method,
- ratio: measuredRatio,
- medianRatio,
- samples: ratios.length,
- finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
- };
- }
-
- function waitForVisualPaint() {
- return new Promise(resolve => {
- requestAnimationFrame(() => requestAnimationFrame(resolve));
- });
- }
-
- async function analyzeVisualContrast(options = {}) {
- const candidates = collectVisualContrastCandidates(options);
- const results = [];
- const shouldScrollOffscreen = options.scrollOffscreen === true;
- const restoreScroll = { x: window.scrollX, y: window.scrollY };
- for (const candidate of candidates) {
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- await waitForVisualPaint();
- }
- let result = await analyzeVisualContrastCandidate(candidate);
- if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (el && typeof el.scrollIntoView === 'function') {
- el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
- await waitForVisualPaint();
- result = await analyzeVisualContrastCandidate(candidate);
- }
- }
- results.push(result);
- }
- if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
- window.scrollTo(restoreScroll.x, restoreScroll.y);
- }
- return results;
- }
-
- function isElementHidden(el) {
- if (!el || el === document.body || el === document.documentElement) return false;
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
- return el.offsetWidth === 0 && el.offsetHeight === 0;
- }
-
- function serializeFindings(allFindings) {
- return allFindings.map(({ el, findings }) => ({
- selector: generateSelector(el),
- tagName: el.tagName?.toLowerCase() || 'unknown',
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
- ? el.getBoundingClientRect().toJSON() : null,
- isPageLevel: el === document.body || el === document.documentElement,
- isHidden: isElementHidden(el),
- findings: findings.map(f => {
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
- return {
- type: f.type || f.id,
- category: ap ? ap.category : 'quality',
- severity: ap?.severity || 'warning',
- detail: f.detail || f.snippet,
- name: ap ? ap.name : (f.type || f.id),
- description: ap ? ap.description : '',
- };
- }),
- }));
- }
-
- const printSummary = function(allFindings) {
- if (allFindings.length === 0) {
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
- return;
- }
- console.group(
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
- 'color: oklch(60% 0.25 350); font-weight: bold'
- );
- for (const { el, findings } of allFindings) {
- for (const f of findings) {
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
- }
- }
- console.groupEnd();
- };
-
- function addBrowserFindings(groupMap, el, findings) {
- if (!findings || findings.length === 0) return;
- const existing = groupMap.get(el);
- if (existing) existing.push(...findings);
- else groupMap.set(el, [...findings]);
- }
-
- function browserFindingsFromMap(groupMap) {
- return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
- }
-
- function collectBrowserFindings() {
- const groupMap = new Map();
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
-
- for (const el of document.querySelectorAll('*')) {
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Skip browser extension elements (Claude, etc.)
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
- // These are inspector chrome, not part of the user's design.
- if (el.closest('[id^="impeccable-live-"]')) continue;
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
- if (el === document.body || el === document.documentElement) continue;
-
- const findings = [
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementHeroEyebrowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
- ].filter(f => _ruleOk(f.type));
-
- addBrowserFindings(groupMap, el, findings);
- }
-
- const pageLevelFindings = [];
-
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
- if (typoFindings.length > 0) {
- pageLevelFindings.push(...typoFindings);
- addBrowserFindings(groupMap, document.body, typoFindings);
- }
-
- const sectionKickerFindings = checkRepeatedSectionKickersDOM()
- .map(f => ({ type: f.id, detail: f.snippet }))
- .filter(f => _ruleOk(f.type));
- if (sectionKickerFindings.length > 0) {
- pageLevelFindings.push(...sectionKickerFindings);
- addBrowserFindings(groupMap, document.body, sectionKickerFindings);
- }
-
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
- for (const f of layoutFindings) {
- const el = f.el || document.body;
- addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
- }
-
- // Page-level quality checks (headings, etc.)
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
- if (qualityFindings.length > 0) {
- pageLevelFindings.push(...qualityFindings);
- addBrowserFindings(groupMap, document.body, qualityFindings);
- }
-
- // Regex-on-HTML checks (shared with Node)
- // Clone the document and strip impeccable-live overlay nodes before the
- // regex scan, so the inspector's own inline styles (transitions on top/
- // left/width/height, etc.) don't register as page anti-patterns.
- const docClone = document.documentElement.cloneNode(true);
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
- node.remove();
- }
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
- if (htmlPatternFindings.length > 0) {
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
- pageLevelFindings.push(...mapped);
- addBrowserFindings(groupMap, document.body, mapped);
- }
-
- return {
- groupMap,
- allFindings: browserFindingsFromMap(groupMap),
- pageLevelFindings,
- };
- }
-
- function shouldRunVisualContrast(options = {}) {
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
- }
-
- function visualContrastOptions(options = {}) {
- const config = window.__IMPECCABLE_CONFIG__ || {};
- const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
- ? options.scrollOffscreen
- : typeof options.visualContrastScrollOffscreen === 'boolean'
- ? options.visualContrastScrollOffscreen
- : typeof config.visualContrastScrollOffscreen === 'boolean'
- ? config.visualContrastScrollOffscreen
- : false;
- return {
- ...options,
- maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : Number.isFinite(options.maxCandidates)
- ? options.maxCandidates
- : Number.isFinite(config.visualContrastMaxCandidates)
- ? config.visualContrastMaxCandidates
- : undefined,
- scrollOffscreen,
- };
- }
-
- let lastVisualContrastAnalyses = [];
- let lazyVisualContrastObserver = null;
- let lazyVisualContrastPending = new WeakMap();
- const lazyVisualContrastResolving = new WeakSet();
- let scanGeneration = 0;
-
- function rememberVisualContrastAnalysis(result) {
- if (!result?.selector) {
- lastVisualContrastAnalyses.push(result);
- return;
- }
- const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
- if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
- else lastVisualContrastAnalyses.push(result);
- }
-
- function disconnectLazyVisualContrastObserver() {
- if (lazyVisualContrastObserver) {
- lazyVisualContrastObserver.disconnect();
- lazyVisualContrastObserver = null;
- }
- lazyVisualContrastPending = new WeakMap();
- }
-
- function addVisualContrastResult(groupMap, result, options = {}) {
- if (result.status !== 'fail' || !result.finding || !result.selector) return false;
- let el = null;
- try {
- el = document.querySelector(result.selector);
- } catch {
- el = null;
- }
- if (!el) return false;
- const findingType = result.finding.type || result.finding.id || 'low-contrast';
- const existing = groupMap.get(el) || [];
- if (existing.some(f => (f.type || f.id) === findingType)) return false;
- addBrowserFindings(groupMap, el, [{
- type: findingType,
- detail: result.finding.detail || result.finding.snippet,
- }]);
- if (options.decorate && el !== document.body && el !== document.documentElement) {
- highlight(el, groupMap.get(el) || []);
- }
- return true;
- }
-
- function postSerializedFindings(groupMap) {
- if (!EXTENSION_MODE) return;
- const allFindings = browserFindingsFromMap(groupMap);
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- function postExtensionError(err) {
- if (!EXTENSION_MODE) return;
- window.postMessage({
- source: 'impeccable-error',
- message: err?.message || String(err),
- }, '*');
- }
-
- function reportVisualContrastError(err, detail = {}) {
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
- detail: {
- ...detail,
- message: err?.message || String(err),
- },
- }));
- if (EXTENSION_MODE) {
- postExtensionError(err);
- } else {
- console.warn('[impeccable] visual contrast scan failed', err);
- }
- }
-
- function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
- disconnectLazyVisualContrastObserver();
- if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
- if (typeof IntersectionObserver === 'undefined') return;
- const unresolved = (analyses || []).filter(result =>
- result?.status === 'unresolved' &&
- result.reason === 'text outside viewport' &&
- result.selector
- );
- if (unresolved.length === 0) return;
- const generation = runtime.generation || scanGeneration;
-
- lazyVisualContrastObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- if (!entry.isIntersecting) continue;
- const el = entry.target;
- const candidate = lazyVisualContrastPending.get(el);
- if (!candidate || lazyVisualContrastResolving.has(el)) continue;
- lazyVisualContrastObserver?.unobserve(el);
- lazyVisualContrastPending.delete(el);
- lazyVisualContrastResolving.add(el);
- waitForVisualPaint()
- .then(() => analyzeVisualContrastCandidate(candidate))
- .then(result => {
- if (generation !== scanGeneration) return;
- rememberVisualContrastAnalysis(result);
- const added = addVisualContrastResult(groupMap, result, { decorate: true });
- if (added) {
- postSerializedFindings(groupMap);
- window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
- detail: {
- selector: result.selector,
- status: result.status,
- finding: result.finding || null,
- },
- }));
- }
- })
- .catch(err => {
- reportVisualContrastError(err, { selector: candidate.selector });
- })
- .finally(() => {
- lazyVisualContrastResolving.delete(el);
- });
- }
- }, { threshold: 0.5 });
-
- for (const candidate of unresolved) {
- let el = null;
- try {
- el = document.querySelector(candidate.selector);
- } catch {
- el = null;
- }
- if (!el) continue;
- lazyVisualContrastPending.set(el, candidate);
- lazyVisualContrastObserver.observe(el);
- }
- }
-
- async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
- if (!shouldRunVisualContrast(options)) {
- lastVisualContrastAnalyses = [];
- disconnectLazyVisualContrastObserver();
- return [];
- }
- const resolvedOptions = visualContrastOptions(options);
- const analyses = await analyzeVisualContrast(resolvedOptions);
- if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
- lastVisualContrastAnalyses = analyses;
- for (const result of analyses) {
- addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
- }
- if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
- return analyses;
- }
-
- async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
- const collected = collectBrowserFindings();
- await addVisualContrastFindings(collected.groupMap, options, runtime);
- return {
- ...collected,
- allFindings: browserFindingsFromMap(collected.groupMap),
- visualContrastAnalyses: lastVisualContrastAnalyses,
- };
- }
-
- function clearOverlays() {
- scanGeneration += 1;
- disconnectLazyVisualContrastObserver();
- for (const o of [...overlays]) detachOverlay(o);
- overlays.length = 0;
- visibilityObserver.disconnect();
- overlayIndex = 0;
- }
-
- function renderBrowserFindings(collected) {
- const { allFindings, pageLevelFindings } = collected;
-
- for (const { el, findings } of allFindings) {
- if (el === document.body || el === document.documentElement) continue;
- highlight(el, findings);
- }
-
- if (pageLevelFindings.length > 0) {
- showPageBanner(pageLevelFindings);
- }
-
- if (!EXTENSION_MODE) printSummary(allFindings);
-
- // In extension mode, post serialized results for the DevTools panel
- if (EXTENSION_MODE) {
- window.postMessage({
- source: 'impeccable-results',
- findings: serializeFindings(allFindings),
- count: allFindings.length,
- }, '*');
- }
-
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
- setTimeout(() => { firstScanDone = true; }, 1000);
-
- return allFindings;
- }
-
- let firstScanDone = false;
- const scan = function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- const collected = collectBrowserFindings();
- const allFindings = renderBrowserFindings(collected);
- if (shouldRunVisualContrast(options)) {
- addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
- .then(() => {
- if (generation === scanGeneration) postSerializedFindings(collected.groupMap);
- })
- .catch(err => {
- reportVisualContrastError(err);
- });
- }
- return allFindings;
- };
-
- const scanAsync = async function(options = {}) {
- clearOverlays();
- const generation = scanGeneration;
- if (shouldRunVisualContrast(options)) {
- const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
- if (generation !== scanGeneration) return [];
- return renderBrowserFindings(collected);
- }
- lastVisualContrastAnalyses = [];
- return renderBrowserFindings(collectBrowserFindings());
- };
-
- const detect = function(options = {}) {
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- const detectAsync = async function(options = {}) {
- if (shouldRunVisualContrast(options)) {
- const { allFindings } = await collectBrowserFindingsAsync(options);
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- }
- lastVisualContrastAnalyses = [];
- const { allFindings } = collectBrowserFindings();
- return options.serialize === false ? allFindings : serializeFindings(allFindings);
- };
-
- if (EXTENSION_MODE) {
- // Extension mode: listen for commands, don't auto-scan
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
- if (e.data.action === 'scan') {
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
- try {
- scan(e.data.config || {});
- } catch (err) {
- postExtensionError(err);
- }
- }
- if (e.data.action === 'toggle-overlays') {
- const visible = !document.body.classList.contains('impeccable-hidden');
- document.body.classList.toggle('impeccable-hidden', visible);
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
- }
- if (e.data.action === 'remove') {
- clearOverlays();
- styleEl.remove();
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
- document.body.classList.remove('impeccable-hidden');
- }
- if (e.data.action === 'highlight') {
- try {
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
- if (target) {
- // Scroll first so positionOverlay reads the post-scroll rect
- if (!isInViewport(target) && target.scrollIntoView) {
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
- }
- for (const o of overlays) {
- if (o.classList.contains('impeccable-banner')) continue;
- const isMatch = o._targetEl === target;
- o.classList.toggle('impeccable-spotlight', isMatch);
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
- if (isMatch) {
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
- o.style.display = '';
- o.style.animation = 'none';
- o.classList.add('impeccable-visible');
- o._revealed = true;
- positionOverlay(o);
- }
- }
- showSpotlight(target);
- }
- } catch { /* invalid selector */ }
- }
- if (e.data.action === 'unhighlight') {
- hideSpotlight();
- for (const o of overlays) {
- o.classList.remove('impeccable-spotlight');
- o.classList.remove('impeccable-spotlight-dimmed');
- }
- }
- });
- window.postMessage({ source: 'impeccable-ready' }, '*');
- } else {
- if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
- const runAutoScan = () => {
- try {
- scan();
- } catch (err) {
- console.warn('[impeccable] scan failed', err);
- }
- };
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
- } else {
- setTimeout(runAutoScan, 100);
- }
- }
- }
-
- window.impeccableDetect = detect;
- window.impeccableDetectAsync = detectAsync;
- window.impeccableScan = scan;
- window.impeccableScanAsync = scanAsync;
- window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
- window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
- window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
-}
-
-})();
@@ -1,43 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Anti-Pattern Detector for Impeccable
- * Copyright (c) 2026 Paul Bakaus
- * SPDX-License-Identifier: Apache-2.0
- *
- * Public API facade. Runtime engines live under cli/engine/engines/.
- */
-
-import { detectCli } from './cli/main.mjs';
-
-export { ANTIPATTERNS, RULE_ENGINE_SUPPORT, getAntipattern, getRulesForCategory, getRuleEngineSupport } from './registry/antipatterns.mjs';
-export { SAFE_TAGS, BORDER_SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS, KNOWN_SERIF_FONTS } from './shared/constants.mjs';
-export { isNeutralColor, parseRgb, relativeLuminance, contrastRatio, parseGradientColors, hasChroma, getHue, colorToHex } from './shared/color.mjs';
-export { isFullPage } from './shared/page.mjs';
-export {
- checkElementBorders,
- checkElementMotion,
- checkElementGlow,
- checkPageTypography,
- checkPageLayout,
- checkHtmlPatterns,
-} from './rules/checks.mjs';
-export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
-export { detectHtml } from './engines/static-html/detect-html.mjs';
-export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
-export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
-export {
- walkDir,
- SCANNABLE_EXTENSIONS,
- SKIP_DIRS,
- buildImportGraph,
- resolveImport,
- detectFrameworkConfig,
- isPortListening,
- FRAMEWORK_CONFIGS,
-} from './node/file-system.mjs';
-export { formatFindings, detectCli } from './cli/main.mjs';
-
-const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
-if (isMainModule) detectCli();
@@ -1,251 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { finding } from '../../findings.mjs';
-import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
-
-async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
- if (options?.visualContrast === false) return [];
- const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
- ? options.visualContrastMaxCandidates
- : 12;
- const scrollOffscreen = options?.visualContrastScrollOffscreen !== false;
- const existingLowContrastSelectors = new Set(
- serializedGroups
- .filter(group => group.findings?.some(f => f.type === 'low-contrast'))
- .map(group => group.selector)
- .filter(Boolean)
- );
-
- let browserAnalyses = [];
- const findings = [];
- if (options?.visualContrastBrowser !== false) {
- const browserFindings = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'browser-fallback',
- target,
- }, async () => {
- browserAnalyses = await page.evaluate(async ({ maxCandidates, scrollOffscreen }) => {
- if (typeof window.impeccableAnalyzeVisualContrast !== 'function') return [];
- return window.impeccableAnalyzeVisualContrast({ maxCandidates, scrollOffscreen });
- }, { maxCandidates, scrollOffscreen });
- return browserAnalyses
- .filter(result => result.finding && !existingLowContrastSelectors.has(result.selector))
- .map(result => result.finding);
- });
- findings.push(...browserFindings);
- }
-
- let candidates = browserAnalyses.length > 0 ? browserAnalyses : [];
- if (candidates.length === 0) {
- candidates = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'collect-candidates',
- target,
- }, () => page.evaluate(({ maxCandidates }) => {
- if (typeof window.impeccableCollectVisualContrastCandidates !== 'function') return [];
- return window.impeccableCollectVisualContrastCandidates({ maxCandidates });
- }, { maxCandidates }));
- }
-
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const browserResolvedSelectors = new Set(
- browserAnalyses
- .filter(result => result.status === 'fail' || result.status === 'pass')
- .map(result => result.selector)
- .filter(Boolean)
- );
- const filtered = candidates.filter(candidate =>
- !existingLowContrastSelectors.has(candidate.selector) &&
- !browserResolvedSelectors.has(candidate.selector)
- );
- if (options?.visualContrastPixel === false) return findings;
- for (const candidate of filtered) {
- const result = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'visual-contrast',
- ruleId: 'pixel-diff',
- target,
- }, async () => {
- const finding = await captureVisualContrastCandidate(page, candidate, viewport);
- return finding ? [finding] : [];
- });
- findings.push(...result);
- }
- return findings;
-}
-
-// ---------------------------------------------------------------------------
-// Puppeteer detection (for URLs)
-// ---------------------------------------------------------------------------
-
-async function detectUrl(url, options = {}) {
- const profile = options?.profile;
- const waitUntil = options?.waitUntil || 'networkidle0';
- const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
- const viewport = options?.viewport || { width: 1280, height: 800 };
- const externalBrowser = options?.browser || null;
- let puppeteer;
- if (!externalBrowser) {
- try {
- puppeteer = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'import-puppeteer',
- target: url,
- }, () => import('puppeteer'));
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- }
-
- // Read the browser detection script — reuse it instead of reimplementing
- const browserScriptPath = path.resolve(
- path.dirname(fileURLToPath(import.meta.url)),
- '..',
- '..',
- 'detect-antipatterns-browser.js'
- );
- let browserScript;
- try {
- browserScript = profileStep(profile, {
- engine: 'browser',
- phase: 'setup',
- ruleId: 'read-browser-script',
- target: url,
- }, () => fs.readFileSync(browserScriptPath, 'utf-8'));
- } catch {
- throw new Error(`Browser script not found at ${browserScriptPath}`);
- }
-
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
- // running in CI; local users keep the default hardened launch.
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
- const browser = externalBrowser || await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'launch-browser',
- target: url,
- }, () => puppeteer.default.launch({ headless: true, args: launchArgs }));
- const page = await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'new-page',
- target: url,
- }, () => browser.newPage());
- let results = [];
- try {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'set-viewport',
- target: url,
- }, () => page.setViewport(viewport));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: `goto:${waitUntil}`,
- target: url,
- }, () => page.goto(url, { waitUntil, timeout: 30000 }));
- if (settleMs > 0) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'settle',
- target: url,
- }, () => new Promise(resolve => setTimeout(resolve, settleMs)));
- }
-
- // Inject the browser detection script and collect results
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'configure-pure-detect',
- target: url,
- }, () => page.evaluate(() => {
- window.__IMPECCABLE_CONFIG__ = {
- ...(window.__IMPECCABLE_CONFIG__ || {}),
- autoScan: false,
- };
- }));
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'inject-browser-script',
- target: url,
- }, () => page.evaluate(browserScript));
- let serializedGroups = [];
- results = await profileFindingsAsync(profile, {
- engine: 'browser',
- phase: 'scan',
- ruleId: 'browser-scan',
- target: url,
- }, async () => {
- serializedGroups = await page.evaluate(() => {
- if (!window.impeccableDetect) return [];
- return window.impeccableDetect({ decorate: false, serialize: true });
- });
- return serializedGroups.flatMap(({ findings }) =>
- findings.map(f => ({ id: f.type, snippet: f.detail }))
- );
- });
- const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
- results.push(...visualFindings);
- } finally {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-page',
- target: url,
- }, () => page.close().catch(() => {}));
- if (!externalBrowser) {
- await profileStepAsync(profile, {
- engine: 'browser',
- phase: 'load',
- ruleId: 'close-browser',
- target: url,
- }, () => browser.close());
- }
- }
- return results.map(f => finding(f.id, url, f.snippet));
-}
-
-async function createBrowserDetector(options = {}) {
- let puppeteer;
- try {
- puppeteer = await import('puppeteer');
- } catch {
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
- }
- const launchArgs = options.launchArgs || (process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : []);
- const browser = options.browser || await puppeteer.default.launch({
- headless: options.headless ?? true,
- args: launchArgs,
- });
- const ownsBrowser = !options.browser;
- const defaults = {
- waitUntil: options.waitUntil || 'load',
- settleMs: Number.isFinite(options.settleMs) ? options.settleMs : 100,
- viewport: options.viewport || { width: 1280, height: 800 },
- };
- return {
- browser,
- async detectUrl(url, scanOptions = {}) {
- return detectUrl(url, {
- ...defaults,
- ...scanOptions,
- browser,
- });
- },
- async close() {
- if (ownsBrowser) await browser.close().catch(() => {});
- },
- };
-}
-
-export { runVisualContrastFallback, detectUrl, createBrowserDetector };
@@ -1,420 +0,0 @@
-import { GENERIC_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep } from '../../profile/profiler.mjs';
-
-// ---------------------------------------------------------------------------
-// Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
-// ---------------------------------------------------------------------------
-
-const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
-const hasBorderRadius = (line) => /border-radius/i.test(line);
-const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
-
-function isNeutralBorderColor(str) {
- const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
- if (!m) return false;
- const c = m[1].toLowerCase();
- if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
- const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
- if (hex) {
- const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
- if (shex) {
- const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
- }
- return false;
-}
-
-const REGEX_MATCHERS = [
- // --- Side-tab ---
- { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
- test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
- test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
- fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
- { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
- fmt: (m) => m[0] },
- { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
- test: (m) => +m[1] >= 3,
- fmt: (m) => m[0] },
- // --- Border accent on rounded ---
- { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
- test: (m, line) => hasRounded(line) && +m[1] >= 1,
- fmt: (m) => m[0] },
- { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
- test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
- fmt: (m) => m[0] },
- // --- Overused font ---
- { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica|Fraunces|Geist Sans|Geist Mono|Geist|Mona Sans|Plus Jakarta Sans|Space Grotesk|Recoleta|Instrument Sans)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat|Fraunces|Plus\+Jakarta\+Sans|Space\+Grotesk|Instrument\+Sans|Mona\+Sans|Geist)\b/gi,
- test: () => true,
- fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
- // --- Pure black background ---
- { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Gradient text ---
- { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
- test: (m, line) => /gradient/i.test(line),
- fmt: () => 'background-clip: text + gradient' },
- // --- Gradient text (Tailwind) ---
- { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
- test: (m, line) => /\bbg-gradient-to-/i.test(line),
- fmt: () => 'bg-clip-text + bg-gradient' },
- // --- Tailwind pure black background ---
- { id: 'pure-black-white', regex: /\bbg-black\b/g,
- test: () => true,
- fmt: (m) => m[0] },
- // --- Tailwind gray on colored bg ---
- { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
- test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
- fmt: (m, line) => { const bg = line.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/); return `${m[0]} on ${bg?.[0] || '?'}`; } },
- // --- Tailwind AI palette ---
- { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
- fmt: (m) => `${m[0]} on heading` },
- { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
- test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
- fmt: (m) => `${m[0]} gradient` },
- // --- Bounce/elastic easing ---
- { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
- test: () => true,
- fmt: () => 'animate-bounce (Tailwind)' },
- { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
- test: () => true,
- fmt: (m) => m[0] },
- { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
- test: (m) => {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
- },
- fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
- // --- Layout property transition ---
- { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition: ${found ? found.join(', ') : m[1].trim()}`;
- } },
- { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
- test: (m) => {
- const val = m[1].toLowerCase();
- if (/\ball\b/.test(val)) return false;
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
- },
- fmt: (m) => {
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
- } },
-];
-
-const REGEX_ANALYZERS = [
- // Single font
- (content, filePath) => {
- const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
- const fonts = new Set();
- let m;
- while ((m = fontFamilyRe.exec(content)) !== null) {
- for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
- }
- }
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- while ((m = gfRe.exec(content)) !== null) {
- for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
- }
- if (fonts.size !== 1 || content.split('\n').length < 20) return [];
- const name = [...fonts][0];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
- return [finding('single-font', filePath, `only font used is ${name}`, line)];
- },
- // Flat type hierarchy
- (content, filePath) => {
- const sizes = new Set();
- const REM = 16;
- let m;
- const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
- while ((m = sizeRe.exec(content)) !== null) {
- const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
- if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
- }
- const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
- while ((m = clampRe.exec(content)) !== null) {
- sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
- sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
- }
- const TW = { 'text-xs': 12, 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24, 'text-3xl': 30, 'text-4xl': 36, 'text-5xl': 48, 'text-6xl': 60, 'text-7xl': 72, 'text-8xl': 96, 'text-9xl': 128 };
- for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
- if (sizes.size < 3) return [];
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio >= 2.0) return [];
- const lines = content.split('\n');
- let line = 1;
- for (let i = 0; i < lines.length; i++) { if (/font-size/i.test(lines[i]) || /\btext-(?:xs|sm|base|lg|xl|\d)/i.test(lines[i])) { line = i + 1; break; } }
- return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
- },
- // Monotonous spacing (regex)
- (content, filePath) => {
- const vals = [];
- let m;
- const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
- const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
- const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
- const rounded = vals.map(v => Math.round(v / 4) * 4);
- if (rounded.length < 10) return [];
- const counts = {};
- for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const pct = maxCount / rounded.length;
- const unique = [...new Set(rounded)].filter(v => v > 0);
- if (pct <= 0.6 || unique.length > 3) return [];
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
- },
- // Everything centered (regex)
- (content, filePath) => {
- const lines = content.split('\n');
- let centered = 0, total = 0;
- for (const line of lines) {
- if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
- total++;
- if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
- }
- }
- if (total < 5 || centered / total <= 0.7) return [];
- return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
- },
- // Dark glow (page-level: dark bg + colored box-shadow with blur)
- (content, filePath) => {
- // Check if page has a dark background
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
- if (!hasDarkBg) return [];
-
- // Check for colored box-shadow with blur > 4px
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let m;
- while ((m = shadowRe.exec(content)) !== null) {
- const val = m[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
- // Check blur: look for pattern like "0 0 20px" (third number > 4)
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- const lines = content.substring(0, m.index).split('\n');
- return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
- }
- }
- return [];
- },
-];
-
-// ---------------------------------------------------------------------------
-// Style block extraction (Vue/Svelte <style> blocks)
-// ---------------------------------------------------------------------------
-
-function extractStyleBlocks(content, ext) {
- ext = ext.toLowerCase();
- if (ext !== '.vue' && ext !== '.svelte') return [];
- const blocks = [];
- const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length + 1;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-// ---------------------------------------------------------------------------
-// CSS-in-JS extraction (styled-components, emotion)
-// ---------------------------------------------------------------------------
-
-const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
-
-function extractCSSinJS(content, ext) {
- ext = ext.toLowerCase();
- if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
- const blocks = [];
- const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
- let m;
- while ((m = re.exec(content)) !== null) {
- const before = content.substring(0, m.index);
- const startLine = before.split('\n').length;
- blocks.push({ content: m[1], startLine });
- }
- return blocks;
-}
-
-function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null, options = {}) {
- const { profile, phase = 'regex-matchers' } = options || {};
- const findings = [];
- if (!profile) {
- for (const matcher of REGEX_MATCHERS) {
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- }
- return findings;
- }
-
- for (const matcher of REGEX_MATCHERS) {
- const matcherFindings = profileFindings(profile, {
- engine: 'regex',
- phase,
- ruleId: matcher.id,
- target: filePath,
- }, () => {
- const matches = [];
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- matcher.regex.lastIndex = 0;
- let m;
- while ((m = matcher.regex.exec(line)) !== null) {
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
- const context = blockContext
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
- : line;
- if (matcher.test(m, context)) {
- matches.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
- }
- }
- }
- return matches;
- });
- findings.push(...matcherFindings);
- }
- return findings;
-}
-
-function detectText(content, filePath, options = {}) {
- const profile = options?.profile;
- const findings = [];
- const lines = content.split('\n');
- const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
-
- // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
- // Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
- findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
- profile,
- phase: 'source',
- }));
-
- // Extract and scan <style> blocks from Vue/Svelte SFCs
- const styleBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'style-blocks',
- target: filePath,
- }, () => extractStyleBlocks(content, ext))
- : extractStyleBlocks(content, ext);
- for (const block of styleBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'style-block',
- }));
- }
-
- // Extract and scan CSS-in-JS template literals
- const cssJsBlocks = profile
- ? profileStep(profile, {
- engine: 'regex',
- phase: 'extract',
- ruleId: 'css-in-js',
- target: filePath,
- }, () => extractCSSinJS(content, ext))
- : extractCSSinJS(content, ext);
- for (const block of cssJsBlocks) {
- const blockLines = block.content.split('\n');
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true, {
- profile,
- phase: 'css-in-js',
- }));
- }
-
- // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
- const deduped = [];
- for (const f of findings) {
- const isDupe = deduped.some(d =>
- d.antipattern === f.antipattern &&
- d.snippet === f.snippet &&
- Math.abs(d.line - f.line) <= 2
- );
- if (!isDupe) deduped.push(f);
- }
-
- // Page-level analyzers only run on full pages
- if (isFullPage(content)) {
- const analyzerIds = [
- 'single-font',
- 'flat-type-hierarchy',
- 'monotonous-spacing',
- 'everything-centered',
- 'dark-glow',
- ];
- for (let i = 0; i < REGEX_ANALYZERS.length; i++) {
- const analyzer = REGEX_ANALYZERS[i];
- deduped.push(...profileFindings(profile, {
- engine: 'regex',
- phase: 'page-analyzer',
- ruleId: analyzerIds[i] || `analyzer-${i + 1}`,
- target: filePath,
- }, () => analyzer(content, filePath)));
- }
- }
-
- return deduped;
-}
-
-export {
- REGEX_MATCHERS,
- REGEX_ANALYZERS,
- extractStyleBlocks,
- extractCSSinJS,
- runRegexMatchers,
- detectText,
-};
@@ -1,954 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { profileStep, recordProfileEvent } from '../../profile/profiler.mjs';
-import { parseAnyColor, resolveLengthPx, resolveVarRefs } from '../../rules/checks.mjs';
-
-// ---------------------------------------------------------------------------
-// jsdom CSS-variable border override map
-// ---------------------------------------------------------------------------
-//
-// jsdom's CSSOM silently drops any border shorthand that contains a var()
-// reference — the computed style for the element then shows empty width,
-// empty style, and a default black color. That's enough to hide the most
-// common real-world side-tab pattern in AI-generated pages:
-//
-// :root { --brand: #87a8ff; }
-// .card { border-left: 5px solid var(--brand); border-radius: 4px; }
-//
-// Real browsers (and therefore the browser detector path) resolve var()
-// natively, so this only affects the Node jsdom path.
-//
-// This pre-pass walks the stylesheets, finds any rule whose per-side or
-// all-sides border property contains var(), resolves the var() against
-// :root-level custom properties (read from the documentElement's computed
-// style, which jsdom DOES handle correctly), and attaches the resolved
-// width+color to every element that matches the rule's selector. The
-// Node-side `checkElementBorders` adapter consumes that map as a fallback
-// whenever jsdom's computed style came back empty.
-//
-// Limitations (intentional, to keep the pass simple):
-// * Only :root-level custom properties are resolved. Scoped overrides on
-// descendants are not tracked — uncommon in practice and would require
-// a per-element cascade walk.
-// * @media / @supports wrapped rules are ignored (jsdom often mishandles
-// these anyway).
-// * The fallback only fills sides that jsdom left empty, so any rule
-// whose border parses normally still wins via the computed style.
-
-const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
-
-// isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
-// CSS variables typically hold hex or named colors, so normalize those to
-// rgb() before handing the value off to the shared check. Anything we don't
-// recognise is passed through unchanged — isNeutralColor then treats it as
-// non-neutral, which is the safer default (matches the oklch-era bugfix).
-const NAMED_COLORS = {
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
-};
-
-function normalizeColorForCheck(value) {
- if (!value) return value;
- const v = value.trim();
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
- if (hex6) {
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
- if (hex3) {
- const [r, g, b] = [
- parseInt(hex3[1] + hex3[1], 16),
- parseInt(hex3[2] + hex3[2], 16),
- parseInt(hex3[3] + hex3[3], 16),
- ];
- return `rgb(${r}, ${g}, ${b})`;
- }
- const named = NAMED_COLORS[v.toLowerCase()];
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
- return v;
-}
-
-function buildBorderOverrideMap(document, window) {
- const map = new Map();
- const rootStyle = window.getComputedStyle(document.documentElement);
-
- function resolveVar(value, depth = 0) {
- if (!value || depth > 10 || !value.includes('var(')) return value;
- return value.replace(
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
- (_, name, fallback) => {
- const v = rootStyle.getPropertyValue(name).trim();
- if (v) return resolveVar(v, depth + 1);
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
- return '';
- }
- );
- }
-
- function parseShorthand(text) {
- const m = text.trim().match(BORDER_SHORTHAND_RE);
- if (!m) return null;
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
- }
-
- // Read from the per-property accessors on rule.style. jsdom preserves
- // each border-* shorthand it parsed, even when the overall cssText has
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
- // `border-left: ...` loses the first declaration but keeps the second).
- const SIDE_PROPS = [
- ['borderLeft', 'Left'],
- ['borderRight', 'Right'],
- ['borderTop', 'Top'],
- ['borderBottom', 'Bottom'],
- ['borderInlineStart', 'Left'],
- ['borderInlineEnd', 'Right'],
- ];
-
- for (const sheet of document.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || []; } catch { continue; }
- for (const rule of rules) {
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
-
- const perSide = {};
-
- for (const [prop, side] of SIDE_PROPS) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const parsed = parseShorthand(resolveVar(val));
- if (parsed && parsed.color) perSide[side] = parsed;
- }
-
- // Uniform `border: <w> <style> var(...)` applies to every side the
- // per-side map didn't already claim.
- const borderAll = rule.style.border;
- if (borderAll && borderAll.includes('var(')) {
- const parsed = parseShorthand(resolveVar(borderAll));
- if (parsed && parsed.color) {
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
- if (!perSide[s]) perSide[s] = parsed;
- }
- }
- }
-
- // Longhand `border-*-color: var(...)` with width/style in separate
- // declarations. Rare in AI-generated pages, but cheap to cover.
- for (const [prop, side] of [
- ['borderLeftColor', 'Left'],
- ['borderRightColor', 'Right'],
- ['borderTopColor', 'Top'],
- ['borderBottomColor', 'Bottom'],
- ]) {
- const val = rule.style[prop];
- if (!val || !val.includes('var(')) continue;
- const resolved = resolveVar(val).trim();
- if (!resolved) continue;
- // Width may or may not come from this rule — that's fine; the
- // adapter only substitutes the color when jsdom left it as a
- // literal var() string.
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
- }
-
- if (Object.keys(perSide).length === 0) continue;
-
- let matched;
- try { matched = document.querySelectorAll(rule.selectorText); }
- catch { continue; }
-
- for (const el of matched) {
- const existing = map.get(el);
- if (existing) {
- // Later rules overwrite earlier ones — approximates source-order
- // cascade for equal-specificity rules and is good enough for the
- // uncontested var()-dropped sides we're trying to recover.
- Object.assign(existing, perSide);
- } else {
- map.set(el, { ...perSide });
- }
- }
- }
- }
-
- return map;
-}
-
-// Strip `@layer NAME { … }` wrappers from a CSS / HTML source, leaving
-// the inner rules as flat CSS. jsdom doesn't implement CSS @layer, so
-// any rule inside a layer block becomes invisible to getComputedStyle.
-// Tailwind v4 makes this ubiquitous: every utility class lives in
-// `@layer utilities`, and Preflight lives in `@layer base`. Without
-// unwrapping, every Tailwind-styled element returns empty computed
-// styles. We walk the source character-by-character, balancing braces
-// so we correctly handle nested style rules inside the layer block.
-function unwrapCssAtLayer(source) {
- if (!source || !source.includes('@layer')) return source;
- // Find `@layer <name>? {` openers. The match starts at the @, and
- // we then balance braces from the opening { onward.
- const re = /@layer\b[^{;]*\{/g;
- let out = '';
- let lastIdx = 0;
- let m;
- while ((m = re.exec(source)) !== null) {
- const openStart = m.index;
- const openEnd = m.index + m[0].length; // position right after `{`
- let depth = 1;
- let i = openEnd;
- while (i < source.length && depth > 0) {
- const c = source.charCodeAt(i);
- if (c === 0x7b /* { */) depth++;
- else if (c === 0x7d /* } */) depth--;
- i++;
- }
- if (depth !== 0) {
- // Unbalanced — bail and return source unchanged.
- return source;
- }
- // Emit everything before the @layer, then the inner contents
- // (between the opening { and the matched closing }), then advance.
- out += source.slice(lastIdx, openStart);
- out += source.slice(openEnd, i - 1); // i-1 = position of the closing }
- lastIdx = i;
- re.lastIndex = i;
- }
- out += source.slice(lastIdx);
- return out;
-}
-
-// ---------------------------------------------------------------------------
-// Static HTML/CSS detection (default for local HTML files)
-// ---------------------------------------------------------------------------
-
-const STATIC_INHERITED_PROPS = new Set([
- 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight',
- 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'hyphens',
- 'webkitHyphens',
-]);
-
-const STATIC_DEFAULT_STYLE = {
- color: 'rgb(0, 0, 0)',
- backgroundColor: 'rgba(0, 0, 0, 0)',
- backgroundImage: 'none',
- borderTopWidth: '0px',
- borderRightWidth: '0px',
- borderBottomWidth: '0px',
- borderLeftWidth: '0px',
- borderTopColor: 'rgb(0, 0, 0)',
- borderRightColor: 'rgb(0, 0, 0)',
- borderBottomColor: 'rgb(0, 0, 0)',
- borderLeftColor: 'rgb(0, 0, 0)',
- borderRadius: '0px',
- boxShadow: 'none',
- fontFamily: '',
- fontSize: '16px',
- fontStyle: 'normal',
- fontWeight: '400',
- lineHeight: 'normal',
- letterSpacing: 'normal',
- textTransform: 'none',
- textAlign: 'start',
- hyphens: 'manual',
- webkitHyphens: 'manual',
- transitionProperty: '',
- transitionTimingFunction: '',
- animationName: '',
- animationTimingFunction: '',
- webkitBackgroundClip: '',
- backgroundClip: '',
- width: '',
- height: '',
- paddingTop: '0px',
- paddingRight: '0px',
- paddingBottom: '0px',
- paddingLeft: '0px',
- position: 'static',
- display: '',
-};
-
-const STATIC_PROP_MAP = {
- 'background-color': 'backgroundColor',
- 'background-image': 'backgroundImage',
- 'background-clip': 'backgroundClip',
- '-webkit-background-clip': 'webkitBackgroundClip',
- 'border-radius': 'borderRadius',
- 'border-top-width': 'borderTopWidth',
- 'border-right-width': 'borderRightWidth',
- 'border-bottom-width': 'borderBottomWidth',
- 'border-left-width': 'borderLeftWidth',
- 'border-top-color': 'borderTopColor',
- 'border-right-color': 'borderRightColor',
- 'border-bottom-color': 'borderBottomColor',
- 'border-left-color': 'borderLeftColor',
- 'box-shadow': 'boxShadow',
- 'font-family': 'fontFamily',
- 'font-size': 'fontSize',
- 'font-style': 'fontStyle',
- 'font-weight': 'fontWeight',
- 'line-height': 'lineHeight',
- 'letter-spacing': 'letterSpacing',
- 'text-transform': 'textTransform',
- 'text-align': 'textAlign',
- 'hyphens': 'hyphens',
- '-webkit-hyphens': 'webkitHyphens',
- 'transition-property': 'transitionProperty',
- 'transition-timing-function': 'transitionTimingFunction',
- 'animation-name': 'animationName',
- 'animation-timing-function': 'animationTimingFunction',
- 'width': 'width',
- 'height': 'height',
- 'padding-top': 'paddingTop',
- 'padding-right': 'paddingRight',
- 'padding-bottom': 'paddingBottom',
- 'padding-left': 'paddingLeft',
- 'position': 'position',
- 'display': 'display',
-};
-
-const STATIC_NAMED_COLORS = {
- black: { r: 0, g: 0, b: 0, a: 1 },
- white: { r: 255, g: 255, b: 255, a: 1 },
- transparent: { r: 0, g: 0, b: 0, a: 0 },
- gray: { r: 128, g: 128, b: 128, a: 1 },
- grey: { r: 128, g: 128, b: 128, a: 1 },
- silver: { r: 192, g: 192, b: 192, a: 1 },
- red: { r: 255, g: 0, b: 0, a: 1 },
- green: { r: 0, g: 128, b: 0, a: 1 },
- blue: { r: 0, g: 0, b: 255, a: 1 },
-};
-
-function splitCssList(value) {
- const parts = [];
- let depth = 0, quote = '', start = 0;
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; continue; }
- if (ch === '(' || ch === '[') depth++;
- else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);
- else if (ch === ',' && depth === 0) {
- parts.push(value.slice(start, i).trim());
- start = i + 1;
- }
- }
- const tail = value.slice(start).trim();
- if (tail) parts.push(tail);
- return parts;
-}
-
-function splitCssTokens(value) {
- const tokens = [];
- let depth = 0, quote = '', current = '';
- for (let i = 0; i < value.length; i++) {
- const ch = value[i];
- if (quote) {
- current += ch;
- if (ch === quote && value[i - 1] !== '\\') quote = '';
- continue;
- }
- if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
- if (ch === '(') { depth++; current += ch; continue; }
- if (ch === ')') { depth = Math.max(0, depth - 1); current += ch; continue; }
- if (/\s/.test(ch) && depth === 0) {
- if (current) { tokens.push(current); current = ''; }
- continue;
- }
- current += ch;
- }
- if (current) tokens.push(current);
- return tokens;
-}
-
-function cssPropToCamel(prop) {
- if (!prop) return prop;
- const mapped = STATIC_PROP_MAP[prop];
- if (mapped) return mapped;
- return prop.replace(/-([a-z])/g, (_m, ch) => ch.toUpperCase());
-}
-
-function staticColorToCss(c) {
- if (!c) return '';
- if (c.a != null && c.a < 1) return `rgba(${c.r}, ${c.g}, ${c.b}, ${Number(c.a.toFixed(3))})`;
- return `rgb(${c.r}, ${c.g}, ${c.b})`;
-}
-
-function parseStaticColor(value) {
- const parsed = parseAnyColor(value);
- if (parsed) return parsed;
- const named = STATIC_NAMED_COLORS[String(value || '').trim().toLowerCase()];
- return named ? { ...named } : null;
-}
-
-function extractStaticColor(value) {
- if (!value) return '';
- const raw = String(value).trim();
- if (/^var\(/i.test(raw)) return raw;
- const colorLike = raw.match(/(?:rgba?\([^)]+\)|oklch\([^)]+\)|oklab\([^)]+\)|lch\([^)]+\)|lab\([^)]+\)|hsla?\([^)]+\)|hwb\([^)]+\)|#[0-9a-f]{3,8}\b|\b(?:black|white|gray|grey|silver|red|green|blue|transparent)\b)/i);
- if (!colorLike) return '';
- return colorLike[0];
-}
-
-function normalizeStaticCssValue(prop, value, customProps, parentStyle, currentStyle = null) {
- let resolved = resolveVarRefs(String(value || '').trim(), customProps);
- if (resolved === 'inherit') return parentStyle?.[prop] || STATIC_DEFAULT_STYLE[prop] || '';
- const isModernBorderColor = /^border[A-Z][a-z]+Color$/.test(prop) && /^(?:oklch|oklab|lch|lab|hsl|hwb)\(/i.test(resolved);
- if (!isModernBorderColor && (/color$/i.test(prop) || prop === 'color' || prop === 'backgroundColor')) {
- const parsed = parseStaticColor(resolved);
- if (parsed) resolved = staticColorToCss(parsed);
- }
- if (prop === 'fontSize') {
- const base = parseFloat(parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'letterSpacing') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- if (prop === 'lineHeight' && resolved !== 'normal') {
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
- const px = resolveLengthPx(resolved, base);
- if (px != null) resolved = `${px}px`;
- }
- return resolved;
-}
-
-function expandStaticBoxValues(tokens) {
- if (tokens.length === 0) return ['0px', '0px', '0px', '0px'];
- if (tokens.length === 1) return [tokens[0], tokens[0], tokens[0], tokens[0]];
- if (tokens.length === 2) return [tokens[0], tokens[1], tokens[0], tokens[1]];
- if (tokens.length === 3) return [tokens[0], tokens[1], tokens[2], tokens[1]];
- return [tokens[0], tokens[1], tokens[2], tokens[3]];
-}
-
-function parseStaticBorder(value) {
- const tokens = splitCssTokens(value);
- let width = '', color = '';
- for (const token of tokens) {
- if (!width && /^-?[\d.]+(?:px|rem|em|%)$/.test(token)) width = token;
- if (!color) color = extractStaticColor(token);
- }
- return { width, color };
-}
-
-function parseStaticFont(value) {
- const out = [];
- const slashParts = value.match(/(?:^|\s)([\d.]+(?:px|rem|em|%))(?:\/([^\s]+))?/);
- if (/\bitalic\b/i.test(value)) out.push(['fontStyle', 'italic']);
- const weight = value.match(/\b([1-9]00|bold|normal|lighter|bolder)\b/i);
- if (weight) out.push(['fontWeight', weight[1]]);
- if (slashParts) {
- out.push(['fontSize', slashParts[1]]);
- if (slashParts[2]) out.push(['lineHeight', slashParts[2]]);
- const familyStart = value.indexOf(slashParts[0]) + slashParts[0].length;
- const family = value.slice(familyStart).trim();
- if (family) out.push(['fontFamily', family]);
- }
- return out;
-}
-
-function parseStaticTransition(value) {
- const props = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const prop = tokens.find(token => /^[a-z-]+$/i.test(token) && !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none)$/.test(token) && !/s$/.test(token));
- if (prop) props.push(prop);
- }
- return {
- property: props.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function parseStaticAnimation(value) {
- const names = [];
- const timings = [];
- for (const item of splitCssList(value)) {
- const tokens = splitCssTokens(item);
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
- if (timing) timings.push(timing);
- const name = tokens.find(token =>
- /^[a-z_-][\w-]*$/i.test(token) &&
- !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none|running|paused)$/.test(token)
- );
- if (name) names.push(name);
- }
- return {
- name: names.join(', '),
- timing: timings.join(', '),
- };
-}
-
-function expandStaticDeclaration(prop, value) {
- const p = prop.toLowerCase();
- const v = String(value || '').trim();
- if (!v) return [];
- if (p.startsWith('--')) return [[p, v]];
- if (p === 'background') {
- const out = [];
- const hasImage = /gradient|url\(/i.test(v);
- if (hasImage) out.push(['backgroundImage', v]);
- const beforeImage = hasImage ? v.split(/(?:repeating-)?(?:linear|radial|conic)-gradient\(|url\(/i)[0] : v;
- const color = extractStaticColor(hasImage ? beforeImage : v);
- if (color) out.push(['backgroundColor', color]);
- return out;
- }
- if (p === 'border') {
- const parsed = parseStaticBorder(v);
- const out = [];
- for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
- if (parsed.width) out.push([`border${side}Width`, parsed.width]);
- if (parsed.color) out.push([`border${side}Color`, parsed.color]);
- }
- return out;
- }
- const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
- if (sideMatch) {
- const parsed = parseStaticBorder(v);
- const side = sideMatch[1][0].toUpperCase() + sideMatch[1].slice(1);
- return [
- ...(parsed.width ? [[`border${side}Width`, parsed.width]] : []),
- ...(parsed.color ? [[`border${side}Color`, parsed.color]] : []),
- ];
- }
- if (p === 'border-width') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopWidth', vals[0]],
- ['borderRightWidth', vals[1]],
- ['borderBottomWidth', vals[2]],
- ['borderLeftWidth', vals[3]],
- ];
- }
- if (p === 'border-color') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['borderTopColor', vals[0]],
- ['borderRightColor', vals[1]],
- ['borderBottomColor', vals[2]],
- ['borderLeftColor', vals[3]],
- ];
- }
- if (p === 'padding') {
- const vals = expandStaticBoxValues(splitCssTokens(v));
- return [
- ['paddingTop', vals[0]],
- ['paddingRight', vals[1]],
- ['paddingBottom', vals[2]],
- ['paddingLeft', vals[3]],
- ];
- }
- if (p === 'font') return parseStaticFont(v);
- if (p === 'transition') {
- const parsed = parseStaticTransition(v);
- return [
- ...(parsed.property ? [['transitionProperty', parsed.property]] : []),
- ...(parsed.timing ? [['transitionTimingFunction', parsed.timing]] : []),
- ];
- }
- if (p === 'animation') {
- const parsed = parseStaticAnimation(v);
- return [
- ...(parsed.name ? [['animationName', parsed.name]] : []),
- ...(parsed.timing ? [['animationTimingFunction', parsed.timing]] : []),
- ];
- }
- const mapped = cssPropToCamel(p);
- if (STATIC_DEFAULT_STYLE[mapped] != null || STATIC_INHERITED_PROPS.has(mapped)) {
- return [[mapped, v]];
- }
- return [];
-}
-
-function compareStaticPriority(a, b) {
- if (!a) return true;
- if (!!b.important !== !!a.important) return !!b.important;
- if (!!b.inline !== !!a.inline) return !!b.inline;
- for (let i = 0; i < 3; i++) {
- if ((b.specificity[i] || 0) !== (a.specificity[i] || 0)) {
- return (b.specificity[i] || 0) > (a.specificity[i] || 0);
- }
- }
- return b.order >= a.order;
-}
-
-function staticSpecificity(selector) {
- const noWhere = selector.replace(/:where\([^)]*\)/g, '');
- const ids = (noWhere.match(/#[\w-]+/g) || []).length;
- const classes = (noWhere.match(/\.[\w-]+|\[[^\]]+\]|:(?!:)[\w-]+(?:\([^)]*\))?/g) || []).length;
- const stripped = noWhere
- .replace(/#[\w-]+/g, ' ')
- .replace(/\.[\w-]+|\[[^\]]+\]|:{1,2}[\w-]+(?:\([^)]*\))?/g, ' ')
- .replace(/[*>+~(),]/g, ' ');
- const types = (stripped.match(/\b[a-zA-Z][\w-]*\b/g) || []).length;
- return [ids, classes, types];
-}
-
-function applyStaticDeclaration(specified, node, prop, value, meta) {
- let map = specified.get(node);
- if (!map) { map = new Map(); specified.set(node, map); }
- for (const [expandedProp, expandedValue] of expandStaticDeclaration(prop, value)) {
- const existing = map.get(expandedProp);
- const next = { ...meta, prop: expandedProp, value: expandedValue };
- if (compareStaticPriority(existing, next)) map.set(expandedProp, next);
- }
-}
-
-function parseStaticStyleAttribute(styleText, orderBase = 0) {
- const decls = [];
- for (const part of String(styleText || '').split(';')) {
- const idx = part.indexOf(':');
- if (idx <= 0) continue;
- const prop = part.slice(0, idx).trim();
- let value = part.slice(idx + 1).trim();
- const important = /!important\s*$/i.test(value);
- value = value.replace(/\s*!important\s*$/i, '').trim();
- decls.push({ prop, value, important, order: orderBase + decls.length });
- }
- return decls;
-}
-
-function collectStaticCssRules(cssText, csstree) {
- const rules = [];
- let ast;
- try {
- ast = csstree.parse(cssText, { positions: false, parseValue: true, parseCustomProperty: false });
- } catch {
- return rules;
- }
- let order = 0;
- const walkList = (list, atRuleStack = []) => {
- list?.forEach?.(node => {
- if (node.type === 'Rule' && node.block) {
- if (atRuleStack.some(name => /keyframes$/i.test(name))) return;
- const selectorText = csstree.generate(node.prelude).trim();
- const declarations = [];
- node.block.children?.forEach?.(child => {
- if (child.type !== 'Declaration') return;
- declarations.push({
- prop: child.property,
- value: csstree.generate(child.value).trim(),
- important: !!child.important,
- });
- });
- for (const selector of splitCssList(selectorText)) {
- if (selector) rules.push({ selector, declarations, specificity: staticSpecificity(selector), order: order++ });
- }
- return;
- }
- if (node.type === 'Atrule' && node.block) {
- const name = String(node.name || '').toLowerCase();
- if (name === 'media' || name === 'supports' || name === 'layer') {
- walkList(node.block.children, [...atRuleStack, name]);
- }
- }
- });
- };
- walkList(ast.children);
- return rules;
-}
-
-class StaticElement {
- constructor(node, doc) {
- this.node = node;
- this._doc = doc;
- this.nodeType = 1;
- this.tagName = String(node.name || '').toUpperCase();
- this.nodeName = this.tagName;
- }
- get parentElement() {
- let cur = this.node.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- return cur ? this._doc.wrap(cur) : null;
- }
- get previousElementSibling() {
- let cur = this.node.prev;
- while (cur && cur.type !== 'tag') cur = cur.prev;
- return cur ? this._doc.wrap(cur) : null;
- }
- get children() {
- return (this.node.children || []).filter(child => child.type === 'tag').map(child => this._doc.wrap(child));
- }
- get childNodes() {
- return (this.node.children || []).map(child => {
- if (child.type === 'text') return { nodeType: 3, textContent: child.data || '' };
- if (child.type === 'tag') return this._doc.wrap(child);
- return { nodeType: 8, textContent: child.data || '' };
- });
- }
- get textContent() {
- return this._doc.domutils.textContent(this.node);
- }
- get className() {
- return this.getAttribute('class') || '';
- }
- get id() {
- return this.getAttribute('id') || '';
- }
- getAttribute(name) {
- return this.node.attribs?.[name] ?? null;
- }
- querySelector(selector) {
- try {
- const found = this._doc.selectOne(selector, this.node.children || []);
- return found ? this._doc.wrap(found) : null;
- } catch {
- return null;
- }
- }
- querySelectorAll(selector) {
- try {
- return this._doc.selectAll(selector, this.node.children || []).map(node => this._doc.wrap(node));
- } catch {
- return [];
- }
- }
- closest(selector) {
- let cur = this.node;
- while (cur && cur.type === 'tag') {
- try {
- if (this._doc.is(cur, selector)) return this._doc.wrap(cur);
- } catch {
- return null;
- }
- cur = cur.parent;
- while (cur && cur.type !== 'tag') cur = cur.parent;
- }
- return null;
- }
- contains(other) {
- let cur = other?.node || null;
- while (cur) {
- if (cur === this.node) return true;
- cur = cur.parent;
- }
- return false;
- }
-}
-
-class StaticDocument {
- constructor(root, modules) {
- this.root = root;
- this.selectAll = modules.selectAll;
- this.selectOne = modules.selectOne;
- this.is = modules.is;
- this.domutils = modules.domutils;
- this._wrappers = new WeakMap();
- this._styleMap = new WeakMap();
- }
- wrap(node) {
- let wrapped = this._wrappers.get(node);
- if (!wrapped) {
- wrapped = new StaticElement(node, this);
- this._wrappers.set(node, wrapped);
- }
- return wrapped;
- }
- querySelectorAll(selector) {
- try {
- return this.selectAll(selector, this.root.children || []).map(node => this.wrap(node));
- } catch {
- return [];
- }
- }
- querySelector(selector) {
- try {
- const found = this.selectOne(selector, this.root.children || []);
- return found ? this.wrap(found) : null;
- } catch {
- return null;
- }
- }
- get documentElement() {
- return this.querySelector('html');
- }
- get body() {
- return this.querySelector('body');
- }
- setStyle(node, style) {
- this._styleMap.set(node, style);
- }
- getStyle(el) {
- return this._styleMap.get(el.node) || makeStaticStyle();
- }
-}
-
-function makeStaticStyle(values = {}) {
- const style = { ...STATIC_DEFAULT_STYLE, ...values };
- style.getPropertyValue = (prop) => {
- const key = cssPropToCamel(prop);
- return style[key] || style[prop] || '';
- };
- return style;
-}
-
-function buildStaticWindow(staticDoc) {
- return {
- document: staticDoc,
- getComputedStyle: (el) => staticDoc.getStyle(el),
- };
-}
-
-function collectStaticCssText(root, fileDir, profile, filePath, modules) {
- const styleTexts = [];
- for (const styleEl of modules.selectAll('style', root.children || [])) {
- styleTexts.push(modules.domutils.textContent(styleEl));
- }
- const links = modules.selectAll('link', root.children || []);
- for (const link of links) {
- const rel = link.attribs?.rel || '';
- const href = link.attribs?.href || '';
- if (!/\bstylesheet\b/i.test(rel) || !href || /^(https?:)?\/\//i.test(href)) continue;
- const cssPath = path.resolve(fileDir, href);
- try {
- const css = profileStep(profile, {
- engine: 'static-html',
- phase: 'preprocess',
- ruleId: 'inline-linked-stylesheet',
- target: filePath,
- detail: href,
- }, () => fs.readFileSync(cssPath, 'utf-8'));
- styleTexts.push(css);
- } catch { /* skip unreadable */ }
- }
- return styleTexts.join('\n');
-}
-
-function buildStaticStyleMap(root, staticDoc, cssText, modules, profile, filePath) {
- const specified = new Map();
- const allNodes = modules.selectAll('*', root.children || []);
- const rules = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-css',
- ruleId: 'css-rules',
- target: filePath,
- }, () => collectStaticCssRules(cssText, modules.csstree));
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'css-selectors',
- target: filePath,
- }, () => {
- for (const rule of rules) {
- let matched;
- try {
- matched = modules.selectAll(rule.selector, root.children || []);
- } catch {
- recordProfileEvent(profile, {
- engine: 'static-html',
- phase: 'selector-match',
- ruleId: 'unsupported-selector',
- target: filePath,
- ms: 0,
- findings: 0,
- detail: rule.selector,
- });
- continue;
- }
- for (const node of matched) {
- for (const decl of rule.declarations) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: rule.specificity,
- order: rule.order,
- inline: false,
- });
- }
- }
- }
-
- let inlineOrder = rules.length + 1;
- for (const node of allNodes) {
- const styleText = node.attribs?.style;
- if (!styleText) continue;
- for (const decl of parseStaticStyleAttribute(styleText, inlineOrder)) {
- applyStaticDeclaration(specified, node, decl.prop, decl.value, {
- important: decl.important,
- specificity: [1, 0, 0],
- order: decl.order,
- inline: true,
- });
- }
- inlineOrder += 1000;
- }
- });
-
- const computeNode = (node, parentStyle = null, parentCustom = new Map()) => {
- const specifiedMap = specified.get(node) || new Map();
- const customProps = new Map(parentCustom);
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) customProps.set(prop, resolveVarRefs(decl.value, customProps));
- }
- const values = {};
- for (const prop of Object.keys(STATIC_DEFAULT_STYLE)) {
- if (STATIC_INHERITED_PROPS.has(prop) && parentStyle?.[prop] != null) values[prop] = parentStyle[prop];
- else values[prop] = STATIC_DEFAULT_STYLE[prop];
- }
- for (const [prop, decl] of specifiedMap) {
- if (prop.startsWith('--')) continue;
- values[prop] = normalizeStaticCssValue(prop, decl.value, customProps, parentStyle, values);
- }
- const style = makeStaticStyle(values);
- staticDoc.setStyle(node, style);
- for (const child of node.children || []) {
- if (child.type === 'tag') computeNode(child, style, customProps);
- }
- };
-
- profileStep(profile, {
- engine: 'static-html',
- phase: 'cascade',
- ruleId: 'compute-styles',
- target: filePath,
- }, () => {
- for (const child of root.children || []) {
- if (child.type === 'tag') computeNode(child);
- }
- });
-}
-
-export {
- BORDER_SHORTHAND_RE,
- NAMED_COLORS,
- normalizeColorForCheck,
- buildBorderOverrideMap,
- unwrapCssAtLayer,
- STATIC_INHERITED_PROPS,
- STATIC_DEFAULT_STYLE,
- STATIC_PROP_MAP,
- STATIC_NAMED_COLORS,
- splitCssList,
- splitCssTokens,
- cssPropToCamel,
- staticColorToCss,
- parseStaticColor,
- extractStaticColor,
- normalizeStaticCssValue,
- expandStaticBoxValues,
- parseStaticBorder,
- parseStaticFont,
- parseStaticTransition,
- parseStaticAnimation,
- expandStaticDeclaration,
- compareStaticPriority,
- staticSpecificity,
- applyStaticDeclaration,
- parseStaticStyleAttribute,
- collectStaticCssRules,
- StaticElement,
- StaticDocument,
- makeStaticStyle,
- buildStaticWindow,
- collectStaticCssText,
- buildStaticStyleMap,
-};
@@ -1,174 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
-import { isFullPage } from '../../shared/page.mjs';
-import { finding } from '../../findings.mjs';
-import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
-import {
- checkElementBorders,
- checkElementColors,
- checkElementGlow,
- checkElementHeroEyebrow,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementMotion,
- checkElementQuality,
- checkHtmlPatterns,
- checkPageLayout,
- checkPageQualityFromDoc,
- checkRepeatedSectionKickersFromDoc,
- resolveBackground,
- resolveBorderRadiusPx,
-} from '../../rules/checks.mjs';
-import { detectText } from '../regex/detect-text.mjs';
-import {
- StaticDocument,
- buildStaticStyleMap,
- buildStaticWindow,
- collectStaticCssText,
-} from './css-cascade.mjs';
-
-function checkStaticPageTypography(document, window) {
- const findings = [];
- const fonts = new Set();
- const overusedFound = new Set();
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span, div')) {
- const hasText = el.childNodes.some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const ff = window.getComputedStyle(el).fontFamily || '';
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
- if (fonts.size === 1 && document.querySelectorAll('*').length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div')) {
- const fontSize = parseFloat(window.getComputedStyle(el).fontSize);
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
- return findings;
-}
-
-const STATIC_ELEMENT_RULES = [
- { id: 'border-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementBorders(tag, style, null, resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window)) },
- { id: 'color-rules', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementColors(el, style, tag, window, customPropMap, false) },
- { id: 'dark-glow', selector: '*', run: (el, tag, style, window, customPropMap) => checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window, customPropMap)) },
- { id: 'motion-rules', selector: '*', run: (el, tag, style) => checkElementMotion(tag, style) },
- { id: 'icon-tile-stack', selector: 'h1,h2,h3,h4,h5,h6', run: (el, tag, _style, window) => checkElementIconTile(el, tag, window) },
- { id: 'italic-serif-display', selector: 'h1,h2', run: (el, tag, style) => checkElementItalicSerif(el, style, tag) },
- { id: 'hero-eyebrow-chip', selector: 'h1', run: (el, tag, style, window, customPropMap) => checkElementHeroEyebrow(el, style, tag, window, customPropMap) },
- { id: 'quality-rules', selector: '*', run: (el, tag, style, window) => checkElementQuality(el, style, tag, window) },
-];
-
-async function detectHtml(filePath, options = {}) {
- const profile = options?.profile;
- const html = profileStep(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'read-html',
- target: filePath,
- }, () => fs.readFileSync(filePath, 'utf-8'));
-
- let modules;
- try {
- modules = await profileStepAsync(profile, {
- engine: 'static-html',
- phase: 'setup',
- ruleId: 'import-static-parser',
- target: filePath,
- }, async () => {
- const [htmlparser2, cssSelect, csstree, domutils] = await Promise.all([
- import('htmlparser2'),
- import('css-select'),
- import('css-tree'),
- import('domutils'),
- ]);
- return {
- parseDocument: htmlparser2.parseDocument,
- selectAll: cssSelect.selectAll,
- selectOne: cssSelect.selectOne,
- is: cssSelect.is,
- csstree,
- domutils,
- };
- });
- } catch {
- return detectText(html, filePath, options);
- }
-
- const resolvedPath = path.resolve(filePath);
- const fileDir = path.dirname(resolvedPath);
- const root = profileStep(profile, {
- engine: 'static-html',
- phase: 'parse-html',
- ruleId: 'parse-document',
- target: filePath,
- }, () => modules.parseDocument(html, { lowerCaseAttributeNames: false, lowerCaseTags: true }));
-
- const cssText = collectStaticCssText(root, fileDir, profile, filePath, modules);
- const document = new StaticDocument(root, modules);
- buildStaticStyleMap(root, document, cssText, modules, profile, filePath);
- const window = buildStaticWindow(document);
-
- const customPropMap = null;
-
- const findings = [];
- const runElementCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'element', ruleId, target: filePath }, callback)
- : callback();
-
- const visitedByRule = new Map();
- for (const rule of STATIC_ELEMENT_RULES) {
- const elements = document.querySelectorAll(rule.selector);
- visitedByRule.set(rule.id, elements.length);
- for (const el of elements) {
- const tag = el.tagName.toLowerCase();
- const style = window.getComputedStyle(el);
- for (const f of runElementCheck(rule.id, () => rule.run(el, tag, style, window, customPropMap))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
- }
-
- if (isFullPage(html)) {
- const runPageCheck = (ruleId, callback) => profile
- ? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
- : callback();
- for (const f of runPageCheck('typography-rules', () => checkStaticPageTypography(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('repeated-section-kickers', () => checkRepeatedSectionKickersFromDoc(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('layout-rules', () => checkPageLayout(document, window))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('skipped-heading', () => checkPageQualityFromDoc(document))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- for (const f of runPageCheck('html-patterns', () => checkHtmlPatterns(html).filter(item =>
- item.id !== 'bounce-easing' && item.id !== 'layout-transition'
- ))) {
- findings.push(finding(f.id, filePath, f.snippet));
- }
- }
-
- return findings;
-}
-
-export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -1,189 +0,0 @@
-function sanitizeScreenshotClip(clip, viewport) {
- if (!clip) return null;
- const x = Math.max(0, Math.floor(clip.x || 0));
- const y = Math.max(0, Math.floor(clip.y || 0));
- const width = Math.min(
- Math.max(1, Math.ceil(clip.width || 0)),
- Math.max(1, viewport?.width || 1600),
- );
- const height = Math.min(
- Math.max(1, Math.ceil(clip.height || 0)),
- 320,
- );
- if (width < 1 || height < 1) return null;
- return { x, y, width, height };
-}
-
-async function compareScreenshotContrast(page, beforeBase64, afterBase64, candidate) {
- return page.evaluate(async ({ beforeBase64, afterBase64, candidate }) => {
- const loadImage = (base64) => new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = () => reject(new Error('Could not decode contrast screenshot'));
- img.src = `data:image/png;base64,${base64}`;
- });
- const [before, after] = await Promise.all([loadImage(beforeBase64), loadImage(afterBase64)]);
- const width = Math.min(before.width, after.width);
- const height = Math.min(before.height, after.height);
- if (width < 1 || height < 1) return null;
-
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx) return null;
-
- ctx.drawImage(before, 0, 0, width, height);
- const beforePixels = ctx.getImageData(0, 0, width, height).data;
- ctx.clearRect(0, 0, width, height);
- ctx.drawImage(after, 0, 0, width, height);
- const afterPixels = ctx.getImageData(0, 0, width, height).data;
-
- const luminance = ({ r, g, b }) => {
- const convert = c => {
- const v = c / 255;
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
- };
- return 0.2126 * convert(r) + 0.7152 * convert(g) + 0.0722 * convert(b);
- };
- const ratio = (a, b) => {
- const l1 = luminance(a);
- const l2 = luminance(b);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
- };
-
- const cssTextColor = candidate.textColor && !candidate.preferRenderedForeground
- ? {
- r: candidate.textColor.r,
- g: candidate.textColor.g,
- b: candidate.textColor.b,
- }
- : null;
- const ratios = [];
- let glyphPixels = 0;
- let strongestDelta = 0;
- for (let i = 0; i < beforePixels.length; i += 4) {
- const delta = Math.abs(beforePixels[i] - afterPixels[i])
- + Math.abs(beforePixels[i + 1] - afterPixels[i + 1])
- + Math.abs(beforePixels[i + 2] - afterPixels[i + 2])
- + Math.abs(beforePixels[i + 3] - afterPixels[i + 3]);
- strongestDelta = Math.max(strongestDelta, delta);
- if (delta < 10) continue;
- glyphPixels++;
- const fg = cssTextColor || {
- r: beforePixels[i],
- g: beforePixels[i + 1],
- b: beforePixels[i + 2],
- };
- const bg = {
- r: afterPixels[i],
- g: afterPixels[i + 1],
- b: afterPixels[i + 2],
- };
- ratios.push(ratio(fg, bg));
- }
-
- if (ratios.length < 8) {
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: null,
- p10Ratio: null,
- medianRatio: null,
- };
- }
-
- ratios.sort((a, b) => a - b);
- const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
- return {
- glyphPixels,
- strongestDelta,
- worstRatio: ratios[0],
- p10Ratio: pick(10),
- medianRatio: pick(50),
- };
- }, { beforeBase64, afterBase64, candidate });
-}
-
-async function captureVisualContrastCandidate(page, candidate, viewport) {
- const clip = sanitizeScreenshotClip(candidate.clip, viewport);
- if (!clip) return null;
-
- const beforeBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- const token = `impeccable-contrast-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- const applied = await page.evaluate(({ selector, token, backgroundClipText }) => {
- let el;
- try {
- el = document.querySelector(selector);
- } catch {
- return false;
- }
- if (!el) return false;
- let style = document.getElementById('impeccable-visual-contrast-hide-style');
- if (!style) {
- style = document.createElement('style');
- style.id = 'impeccable-visual-contrast-hide-style';
- style.textContent = [
- '[data-impeccable-visual-contrast-target] {',
- ' color: transparent !important;',
- ' -webkit-text-fill-color: transparent !important;',
- ' text-shadow: none !important;',
- '}',
- '[data-impeccable-visual-contrast-target][data-impeccable-bgclip-text="true"] {',
- ' background-image: none !important;',
- '}',
- ].join('\n');
- document.head.appendChild(style);
- }
- el.setAttribute('data-impeccable-visual-contrast-target', token);
- if (backgroundClipText) el.setAttribute('data-impeccable-bgclip-text', 'true');
- return true;
- }, {
- selector: candidate.selector,
- token,
- backgroundClipText: candidate.backgroundClipText,
- });
- if (!applied) return null;
-
- let afterBase64;
- try {
- afterBase64 = await page.screenshot({
- encoding: 'base64',
- clip,
- captureBeyondViewport: true,
- });
- } finally {
- await page.evaluate(({ selector }) => {
- try {
- const el = document.querySelector(selector);
- if (el) {
- el.removeAttribute('data-impeccable-visual-contrast-target');
- el.removeAttribute('data-impeccable-bgclip-text');
- }
- } catch {
- // Ignore invalid or stale selectors during cleanup.
- }
- }, { selector: candidate.selector }).catch(() => {});
- }
-
- const metrics = await compareScreenshotContrast(page, beforeBase64, afterBase64, candidate);
- if (!metrics || !Number.isFinite(metrics.p10Ratio) || metrics.glyphPixels < 8) return null;
- const measuredRatio = metrics.p10Ratio;
- if (measuredRatio >= candidate.threshold) return null;
- const textLabel = candidate.text ? ` "${candidate.text}"` : '';
- const reasonLabel = (candidate.reasons || []).slice(0, 3).join(', ') || 'visual background';
- return {
- id: 'low-contrast',
- snippet: `pixel contrast ${measuredRatio.toFixed(1)}:1 median ${metrics.medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) on ${reasonLabel}${textLabel}`,
- };
-}
-
-export {
- sanitizeScreenshotClip,
- compareScreenshotContrast,
- captureVisualContrastCandidate,
-};
@@ -1,12 +0,0 @@
-import { getAntipattern } from './registry/antipatterns.mjs';
-
-function getAP(id) {
- return getAntipattern(id);
-}
-
-function finding(id, filePath, snippet, line = 0) {
- const ap = getAP(id);
- return { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', file: filePath, line, snippet };
-}
-
-export { getAP, finding };
@@ -1,198 +0,0 @@
-import fs from 'node:fs';
-import path from 'node:path';
-
-// ---------------------------------------------------------------------------
-// File walker
-// ---------------------------------------------------------------------------
-
-const SKIP_DIRS = new Set([
- 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
- '.svelte-kit', '__pycache__', '.turbo', '.vercel',
-]);
-
-const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
- '.jsx', '.tsx', '.js', '.ts',
- '.vue', '.svelte', '.astro',
-]);
-
-const HTML_EXTENSIONS = new Set(['.html', '.htm']);
-
-function walkDir(dir) {
- const files = [];
- let entries;
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
- for (const entry of entries) {
- if (SKIP_DIRS.has(entry.name)) continue;
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) files.push(...walkDir(full));
- else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
- }
- return files;
-}
-
-
-// ---------------------------------------------------------------------------
-// Import graph (multi-file awareness)
-// ---------------------------------------------------------------------------
-
-function resolveImport(specifier, fromDir, fileSet) {
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
- const base = path.resolve(fromDir, specifier);
- if (fileSet.has(base)) return base;
- for (const ext of SCANNABLE_EXTENSIONS) {
- const withExt = base + ext;
- if (fileSet.has(withExt)) return withExt;
- }
- // index file convention
- for (const ext of SCANNABLE_EXTENSIONS) {
- const indexFile = path.join(base, 'index' + ext);
- if (fileSet.has(indexFile)) return indexFile;
- }
- return null;
-}
-
-function buildImportGraph(files) {
- const fileSet = new Set(files);
- const graph = new Map();
-
- for (const file of files) {
- const content = fs.readFileSync(file, 'utf-8');
- const dir = path.dirname(file);
- const imports = new Set();
-
- // ES imports: import ... from '...' and import '...'
- const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
- let m;
- while ((m = esRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // CSS @import
- const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
- while ((m = cssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- // SCSS @use / @forward
- const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
- while ((m = scssRe.exec(content)) !== null) {
- const resolved = resolveImport(m[1], dir, fileSet);
- if (resolved) imports.add(resolved);
- }
-
- graph.set(file, imports);
- }
- return graph;
-}
-
-// ---------------------------------------------------------------------------
-// Framework dev server detection
-// ---------------------------------------------------------------------------
-
-const FRAMEWORK_CONFIGS = [
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /next/i } },
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-sveltekit-page', value: null } },
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /@vite\/client/ } },
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { body: /astro/i } },
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
- portRe: /"port"\s*:\s*(\d+)/,
- fingerprint: { body: /ng-version/i } },
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
- portRe: /port\s*[:=]\s*(\d+)/,
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
-];
-
-function detectFrameworkConfig(dir) {
- let entries;
- try { entries = fs.readdirSync(dir); } catch { return null; }
- const entrySet = new Set(entries);
-
- for (const cfg of FRAMEWORK_CONFIGS) {
- const match = cfg.files.find(f => entrySet.has(f));
- if (!match) continue;
-
- const configPath = path.join(dir, match);
- let port = cfg.defaultPort;
- try {
- const content = fs.readFileSync(configPath, 'utf-8');
- const portMatch = content.match(cfg.portRe);
- if (portMatch) port = parseInt(portMatch[1], 10);
- } catch { /* use default */ }
-
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
- }
- return null;
-}
-
-/**
- * Check if a port is listening and optionally verify it matches the expected framework.
- * Returns { listening: true, matched: true/false } or { listening: false }.
- */
-async function isPortListening(port, fingerprint = null) {
- if (!fingerprint) {
- // Simple TCP probe fallback
- const net = await import('node:net');
- return new Promise((resolve) => {
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
- sock.setTimeout(500);
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
- sock.on('error', () => resolve({ listening: false }));
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
- });
- }
-
- // HTTP probe with fingerprint matching
- try {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 2000);
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
- clearTimeout(timeout);
-
- // Check header fingerprint
- if (fingerprint.header) {
- const val = res.headers.get(fingerprint.header);
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
- return { listening: true, matched: true };
- }
- }
-
- // Check body fingerprint
- if (fingerprint.body) {
- const body = await res.text();
- if (fingerprint.body.test(body)) {
- return { listening: true, matched: true };
- }
- }
-
- // Port is listening but doesn't match the expected framework
- return { listening: true, matched: false };
- } catch {
- return { listening: false };
- }
-}
-
-export {
- SKIP_DIRS,
- SCANNABLE_EXTENSIONS,
- HTML_EXTENSIONS,
- walkDir,
- resolveImport,
- buildImportGraph,
- FRAMEWORK_CONFIGS,
- detectFrameworkConfig,
- isPortListening,
-};
@@ -1,166 +0,0 @@
-function profileNow() {
- return typeof performance !== 'undefined' && performance.now
- ? performance.now()
- : Date.now();
-}
-
-function createDetectorProfile() {
- return { events: [] };
-}
-
-function recordProfileEvent(profile, event) {
- if (!profile) return;
- const normalized = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- ms: Number.isFinite(event.ms) ? event.ms : 0,
- findings: Number.isFinite(event.findings) ? event.findings : 0,
- };
- if (event.detail) normalized.detail = event.detail;
- if (Array.isArray(event.findingIds) && event.findingIds.length) {
- normalized.findingIds = event.findingIds;
- }
- if (typeof profile === 'function') {
- profile(normalized);
- } else if (typeof profile.record === 'function') {
- profile.record(normalized);
- } else if (Array.isArray(profile.events)) {
- profile.events.push(normalized);
- } else if (Array.isArray(profile)) {
- profile.push(normalized);
- }
-}
-
-function extractFindingIds(findings) {
- if (!Array.isArray(findings) || findings.length === 0) return [];
- return [...new Set(findings.map(f => f?.id || f?.type || f?.antipattern).filter(Boolean))];
-}
-
-function profileFindings(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-function profileStep(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-async function profileFindingsAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- const findings = await callback();
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: Array.isArray(findings) ? findings.length : 0,
- findingIds: extractFindingIds(findings),
- });
- return findings;
-}
-
-async function profileStepAsync(profile, meta, callback) {
- if (!profile) return callback();
- const started = profileNow();
- try {
- return await callback();
- } finally {
- recordProfileEvent(profile, {
- ...meta,
- ms: profileNow() - started,
- findings: 0,
- });
- }
-}
-
-function percentile(sortedValues, pct) {
- if (!sortedValues.length) return 0;
- const idx = Math.min(
- sortedValues.length - 1,
- Math.max(0, Math.ceil((pct / 100) * sortedValues.length) - 1),
- );
- return sortedValues[idx];
-}
-
-function summarizeDetectorProfile(profile) {
- const events = Array.isArray(profile)
- ? profile
- : (Array.isArray(profile?.events) ? profile.events : []);
- const groups = new Map();
- for (const event of events) {
- const key = [
- event.engine || 'unknown',
- event.phase || 'unknown',
- event.ruleId || 'unknown',
- event.target || '',
- ].join('\u0000');
- let group = groups.get(key);
- if (!group) {
- group = {
- engine: event.engine || 'unknown',
- phase: event.phase || 'unknown',
- ruleId: event.ruleId || 'unknown',
- target: event.target || '',
- calls: 0,
- totalMs: 0,
- findings: 0,
- samples: [],
- };
- groups.set(key, group);
- }
- const ms = Number.isFinite(event.ms) ? event.ms : 0;
- group.calls += 1;
- group.totalMs += ms;
- group.findings += Number.isFinite(event.findings) ? event.findings : 0;
- group.samples.push(ms);
- }
- return [...groups.values()]
- .map(group => {
- const samples = group.samples.sort((a, b) => a - b);
- return {
- engine: group.engine,
- phase: group.phase,
- ruleId: group.ruleId,
- target: group.target,
- calls: group.calls,
- totalMs: Number(group.totalMs.toFixed(3)),
- avgMs: Number((group.totalMs / group.calls).toFixed(3)),
- p50: Number(percentile(samples, 50).toFixed(3)),
- p95: Number(percentile(samples, 95).toFixed(3)),
- findings: group.findings,
- };
- })
- .sort((a, b) => b.totalMs - a.totalMs);
-}
-
-export {
- profileNow,
- createDetectorProfile,
- recordProfileEvent,
- extractFindingIds,
- profileFindings,
- profileStep,
- profileFindingsAsync,
- profileStepAsync,
- percentile,
- summarizeDetectorProfile,
-};
@@ -1,278 +0,0 @@
-const ANTIPATTERNS = [
- // ── AI slop: tells that something was AI-generated ──
- {
- id: 'side-tab',
- category: 'slop',
- name: 'Side-tab accent border',
- description:
- 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'border-accent-on-rounded',
- category: 'slop',
- name: 'Border accent on rounded element',
- description:
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
- skillSection: 'Visual Details',
- skillGuideline: 'colored accent stripe',
- },
- {
- id: 'overused-font',
- category: 'slop',
- name: 'Overused font',
- description:
- 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
- skillSection: 'Typography',
- skillGuideline: 'overused fonts like Inter',
- },
- {
- id: 'single-font',
- category: 'slop',
- name: 'Single font for everything',
- description:
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
- skillSection: 'Typography',
- skillGuideline: 'only one font family for the entire page',
- },
- {
- id: 'flat-type-hierarchy',
- category: 'slop',
- name: 'Flat type hierarchy',
- description:
- 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
- skillSection: 'Typography',
- skillGuideline: 'flat type hierarchy',
- },
- {
- id: 'gradient-text',
- category: 'slop',
- name: 'Gradient text',
- description:
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gradient text for',
- },
- {
- id: 'ai-color-palette',
- category: 'slop',
- name: 'AI color palette',
- description:
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'AI color palette',
- },
- {
- id: 'nested-cards',
- category: 'slop',
- name: 'Nested cards',
- description:
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Nest cards inside cards',
- },
- {
- id: 'monotonous-spacing',
- category: 'slop',
- name: 'Monotonous spacing',
- description:
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
- skillSection: 'Layout & Space',
- skillGuideline: 'same spacing everywhere',
- },
- {
- id: 'everything-centered',
- category: 'slop',
- name: 'Everything centered',
- description:
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
- skillSection: 'Layout & Space',
- skillGuideline: 'Center everything',
- },
- {
- id: 'bounce-easing',
- category: 'slop',
- name: 'Bounce or elastic easing',
- description:
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
- skillSection: 'Motion',
- skillGuideline: 'bounce or elastic easing',
- },
- {
- id: 'dark-glow',
- category: 'slop',
- name: 'Dark mode with glowing accents',
- description:
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'dark mode with glowing accents',
- },
- {
- id: 'icon-tile-stack',
- category: 'slop',
- name: 'Icon tile stacked above heading',
- description:
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
- skillSection: 'Typography',
- skillGuideline: 'large icons with rounded corners above every heading',
- },
- {
- id: 'italic-serif-display',
- category: 'slop',
- name: 'Italic serif display headline',
- description:
- 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
- skillSection: 'Typography',
- skillGuideline: 'oversized italic serif as the hero headline',
- },
- {
- id: 'hero-eyebrow-chip',
- category: 'slop',
- name: 'Hero eyebrow / pill chip',
- description:
- 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
- skillSection: 'Typography',
- skillGuideline: 'tiny uppercase tracked label above the hero headline',
- },
- {
- id: 'repeated-section-kickers',
- category: 'slop',
- severity: 'advisory',
- name: 'Repeated section kicker labels',
- description:
- 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
- skillSection: 'Typography',
- skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
- },
-
- // ── Quality: general design and accessibility issues ──
- {
- id: 'pure-black-white',
- category: 'quality',
- name: 'Pure black background',
- description:
- 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'pure black (#000)',
- },
- {
- id: 'gray-on-color',
- category: 'quality',
- name: 'Gray text on colored background',
- description:
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
- skillSection: 'Color & Contrast',
- skillGuideline: 'gray text on colored backgrounds',
- },
- {
- id: 'low-contrast',
- category: 'quality',
- name: 'Low contrast text',
- description:
- 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
- },
- {
- id: 'layout-transition',
- category: 'quality',
- name: 'Layout property animation',
- description:
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
- skillSection: 'Motion',
- skillGuideline: 'Animate layout properties',
- },
- {
- id: 'line-length',
- category: 'quality',
- name: 'Line length too long',
- description:
- 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
- skillSection: 'Layout & Space',
- skillGuideline: 'wrap beyond ~80 characters',
- },
- {
- id: 'cramped-padding',
- category: 'quality',
- name: 'Cramped padding',
- description:
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
- },
- {
- id: 'body-text-viewport-edge',
- category: 'quality',
- name: 'Body text touching viewport edge',
- description:
- 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
- },
- {
- id: 'tight-leading',
- category: 'quality',
- name: 'Tight line height',
- description:
- 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
- },
- {
- id: 'skipped-heading',
- category: 'quality',
- name: 'Skipped heading level',
- description:
- 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
- },
- {
- id: 'justified-text',
- category: 'quality',
- name: 'Justified text',
- description:
- 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
- },
- {
- id: 'tiny-text',
- category: 'quality',
- name: 'Tiny body text',
- description:
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
- },
- {
- id: 'all-caps-body',
- category: 'quality',
- name: 'All-caps body text',
- description:
- 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
- skillSection: 'Typography',
- skillGuideline: 'long body passages in uppercase',
- },
- {
- id: 'wide-tracking',
- category: 'quality',
- name: 'Wide letter spacing on body text',
- description:
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
- },
-];
-
-const RULE_ENGINE_SUPPORT = {
- regex: new Set(['source', 'page-analyzer']),
- 'static-html': new Set(['element', 'page']),
- browser: new Set(['element', 'page', 'layout']),
- visual: new Set(['visual-contrast']),
-};
-
-function getAntipattern(id) {
- return ANTIPATTERNS.find(rule => rule.id === id);
-}
-
-function getRulesForCategory(category) {
- return ANTIPATTERNS.filter(rule => rule.category === category);
-}
-
-function getRuleEngineSupport(engine) {
- return RULE_ENGINE_SUPPORT[engine] || new Set();
-}
-
-export {
- ANTIPATTERNS,
- RULE_ENGINE_SUPPORT,
- getAntipattern,
- getRulesForCategory,
- getRuleEngineSupport,
-};
@@ -1,1948 +0,0 @@
-import {
- BORDER_SAFE_TAGS,
- GENERIC_FONTS,
- KNOWN_SERIF_FONTS,
- OVERUSED_FONTS,
- SAFE_TAGS,
- WCAG_LARGE_BOLD_TEXT_PX,
- WCAG_LARGE_TEXT_PX,
- isBrandFontOnOwnDomain,
-} from '../shared/constants.mjs';
-import {
- colorToHex,
- contrastRatio,
- getHue,
- hasChroma,
- isNeutralColor,
- parseGradientColors,
- parseRgb,
- relativeLuminance,
-} from '../shared/color.mjs';
-
-const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
-
-// ─── Section 3: Pure Detection ──────────────────────────────────────────────
-
-function checkBorders(tag, widths, colors, radius) {
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const findings = [];
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
-
- for (const side of sides) {
- const w = widths[side];
- if (w < 1 || isNeutralColor(colors[side])) continue;
-
- const otherSides = sides.filter(s => s !== side);
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
-
- const sn = side.toLowerCase();
- const isSide = side === 'Left' || side === 'Right';
-
- if (isSide) {
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
- } else {
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
- }
- }
-
- return findings;
-}
-
-// Returns true if the given text is composed entirely of emoji characters
-// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
-// regardless of CSS `color`, so contrast checks against the element's text
-// color are meaningless for these nodes.
-const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
-const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
-function isEmojiOnlyText(text) {
- if (!text) return false;
- if (!EMOJI_CHAR_RE.test(text)) return false;
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
-}
-
-function checkColors(opts) {
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
- if (SAFE_TAGS.has(tag)) {
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
- // exists to suppress contrast noise on inline links and unstyled controls,
- // where the element has no own background and the contrast against the
- // ancestor surface is already the intended visual. When the element has
- // its own opaque background and direct text, it is a styled button — and
- // contrast on its own surface is a real, frequent bug worth flagging.
- const isStyledButton = (tag === 'a' || tag === 'button')
- && hasDirectText
- && bgColor && bgColor.a > 0.5;
- if (!isStyledButton) return [];
- }
- const findings = [];
-
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
- }
-
- if (hasDirectText && textColor && !isEmojiOnly) {
- // Run background-dependent checks against either a solid bg or, if the
- // ancestor is a gradient, against every gradient stop (use the worst case).
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
- if (bgs) {
- // Gray on colored background — flag if every stop is chromatic
- const textLum = relativeLuminance(textColor);
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
- }
-
- // Low contrast (WCAG AA) — worst case across all bg stops
- const ratios = bgs.map(b => contrastRatio(textColor, b));
- let worstIdx = 0;
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
- const ratio = ratios[worstIdx];
- const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
- const threshold = isLargeText ? 3.0 : 4.5;
- if (ratio < threshold) {
- // Skip the false-positive class where text has alpha < 1 AND we
- // couldn't find an opaque ancestor (effectiveBg is null, we're
- // comparing against gradient-stop fallback). In jsdom mode the
- // detector can't resolve `var(--X)` color tokens, so a dark
- // section sitting between the text and the body's decorative
- // gradient is invisible to us — we end up measuring contrast
- // against the body's paper-grain noise instead of the real
- // local bg. Real low-contrast bugs use alpha=1 and have a
- // resolvable opaque ancestor; semi-transparent Tailwind tokens
- // like `text-paper/60` on `bg-ink` sections are the FP pattern.
- const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
- if (!isAlphaFallbackFP) {
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
- }
- }
- }
-
- // AI palette: purple/violet on headings
- if (hasChroma(textColor, 50)) {
- const hue = getHue(textColor);
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
- }
- }
- }
-
- // Gradient text
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- }
-
- // Tailwind class checks
- if (classList) {
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
- }
-
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
- if (grayMatch && colorBgMatch) {
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
- }
-
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
- }
-
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
- }
- }
-
- return findings;
-}
-
-function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
- if (!hasShadow && !hasBorder) return false;
- return hasRadius || hasBg;
-}
-
-const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
-
-// Pure check: given a heading and metrics about its previousElementSibling,
-// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
-//
-// Triggers when ALL of the following hold for the sibling:
-// • size 32–128px on both axes (not too small, not a hero image)
-// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
-// • has a non-transparent background-color, background-image, OR a visible border
-// (covers solid colors, white-with-border, gradients — anything that visually
-// defines a tile)
-// • border-radius < width/2 (excludes round avatars; rounded squares pass)
-// • contains an <svg> or icon-class <i> element that's smaller than the tile
-// • the tile sits above the heading (its bottom is above the heading's top)
-function checkIconTile(opts) {
- const { headingTag, headingText, headingTop,
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
- hasIconChild, iconChildWidth } = opts;
- if (!HEADING_TAGS.has(headingTag)) return [];
- if (!siblingTag) return [];
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- // Size window: 32–128px on each axis
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
-
- // Squarish aspect ratio
- const ratio = siblingWidth / siblingHeight;
- if (ratio < 0.7 || ratio > 1.4) return [];
-
- // Must have something that visually defines the tile
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
- const borderVisible = siblingBorderWidth > 0;
- if (!bgVisible && !borderVisible) return [];
-
- // Exclude circles (avatars). Rounded squares pass.
- if (siblingBorderRadius >= siblingWidth / 2) return [];
-
- // Must contain an icon element smaller than the tile
- if (!hasIconChild) return [];
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
-
- // Vertical stacking: tile must end above where the heading starts.
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'icon-tile-stack',
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
- }];
-}
-
-// Resolve the primary (non-generic) face from a font-family string and return
-// whether the resolved primary is serif. Two paths:
-// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
-// 2. Primary face is unknown but the stack ends in the generic `serif`
-// token → treat as serif. Authors who declare `font-family: 'X', serif`
-// almost always have a serif primary; a sans declared with a serif
-// fallback is a code smell, not the common case.
-// Returns { primary, isSerif } so the snippet can name the face.
-function resolveSerif(fontFamily) {
- if (!fontFamily) return { primary: null, isSerif: false };
- const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
- if (!primary) return { primary: null, isSerif: false };
- if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
- if (tokens.includes('serif')) return { primary, isSerif: true };
- return { primary, isSerif: false };
-}
-
-function checkItalicSerif(opts) {
- const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
- if (fontStyle !== 'italic') return [];
- // Anchor the rule on hero-scale text. h1 is the canonical hero element;
- // h2 ≥ 48px catches the cases where the design demotes the visual hero
- // to an h2 but keeps the size.
- if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
- if (fontSize < 48) return [];
- const { primary, isSerif } = resolveSerif(fontFamily);
- if (!isSerif) return [];
-
- const text = (headingText || '').trim().slice(0, 60);
- return [{
- id: 'italic-serif-display',
- snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
- }];
-}
-
-// Color saturation check. Returns true when the color has visible
-// chroma — i.e., it's an "accent color" rather than near-neutral.
-// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
-// expected to be pre-resolved by the caller.
-function isAccentColor(cssColor) {
- if (!cssColor) return false;
- const s = String(cssColor).trim();
- // rgb / rgba — direct channel-distance check.
- const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
- const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
- if (rgbStrict) {
- const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- // #hex — 3, 4, 6, or 8 digit.
- const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
- if (hexM) {
- let h = hexM[1];
- if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
- else h = h.slice(0, 6);
- if (h.length === 6) {
- const r = parseInt(h.slice(0, 2), 16);
- const g = parseInt(h.slice(2, 4), 16);
- const b = parseInt(h.slice(4, 6), 16);
- return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
- }
- }
- // oklch(L C H) — chroma C is what matters. Typical neutral grays
- // have C < 0.02; visible accents are 0.05+. CSS minification can
- // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
- // extract all numbers and take the second rather than matching a
- // strict L-then-whitespace-then-C pattern.
- if (/^oklch\(/i.test(s)) {
- const nums = s.match(/\d*\.\d+|\d+/g);
- if (nums && nums.length >= 2) {
- const c = parseFloat(nums[1]);
- return !Number.isNaN(c) && c >= 0.05;
- }
- }
- // hsl(H, S%, L%) — saturation > 20% reads as accent.
- const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
- if (hslM) {
- const sat = parseFloat(hslM[1]);
- return !Number.isNaN(sat) && sat >= 20;
- }
- return false;
-}
-
-// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
-// previousElementSibling, and gate on EITHER the classic tracked-
-// uppercase eyebrow OR the modern accent-colored bold eyebrow.
-function checkHeroEyebrow(opts) {
- const {
- headingTag, headingText, headingFontSize,
- siblingTag, siblingText, siblingTextTransform,
- siblingFontSize, siblingLetterSpacing,
- siblingFontWeight, siblingColor,
- } = opts;
- if (headingTag !== 'h1') return [];
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
- // jsdom can resolve — the computed value comes back as "2em" or
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
- // on virtually every Tailwind v4 / framework build. The other gates
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
- // tracked-caps) are tight enough to avoid false positives on non-
- // hero h1s — a tiny tan label directly above any h1 is the
- // antipattern regardless of how big the h1 ends up.
- if (!siblingTag) return [];
- // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
- // headings) — never an eyebrow.
- if (HEADING_TAGS.has(siblingTag)) return [];
-
- const text = (siblingText || '').trim();
- if (text.length < 2 || text.length > 60) return [];
- if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
-
- // Branch A: classic tracked-uppercase eyebrow.
- const isUppercased = siblingTextTransform === 'uppercase'
- || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
- const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
-
- // Branch B: modern accent-bold eyebrow — sentence case, low
- // tracking, but bold + accent-colored. The style choices changed;
- // the pattern is the same kicker-above-headline anti-pattern.
- const weight = Number(siblingFontWeight) || 400;
- const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
-
- if (!isClassicTracked && !isAccentBold) return [];
-
- const headingTextSnippet = (headingText || '').trim().slice(0, 60);
- const eyebrowSnippet = text.slice(0, 40);
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
- return [{
- id: 'hero-eyebrow-chip',
- snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
- }];
-}
-
-function checkRepeatedSectionKickers(opts) {
- const { candidates, minCount = 3 } = opts;
- if (!Array.isArray(candidates) || candidates.length < minCount) return [];
- return candidates.map(candidate => ({
- id: 'repeated-section-kickers',
- snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
- }));
-}
-
-const LAYOUT_TRANSITION_PROPS = new Set([
- 'width', 'height', 'padding', 'margin',
- 'max-height', 'max-width', 'min-height', 'min-width',
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
-]);
-
-function checkMotion(opts) {
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
- if (SAFE_TAGS.has(tag)) return [];
- const findings = [];
-
- // --- Bounce/elastic easing ---
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
- }
- if (classList && /\banimate-bounce\b/.test(classList)) {
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
- }
-
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
- if (timingFunctions) {
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let m;
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
- break;
- }
- }
- }
-
- // --- Layout property transition ---
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
- if (layoutFound.length > 0) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
- }
- }
-
- return findings;
-}
-
-function checkGlow(opts) {
- const { boxShadow, effectiveBg } = opts;
- if (!boxShadow || boxShadow === 'none') return [];
- if (!effectiveBg) return [];
-
- // Only flag on dark backgrounds (luminance < 0.1)
- const bgLum = relativeLuminance(effectiveBg);
- if (bgLum >= 0.1) return [];
-
- // Split multiple shadows (commas not inside parentheses)
- const parts = boxShadow.split(/,(?![^(]*\))/);
- for (const shadow of parts) {
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
- if (!colorMatch) continue;
- const color = parseRgb(colorMatch[0]);
- if (!color || !hasChroma(color, 30)) continue;
-
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
- .map(m => parseFloat(m[1]));
-
- // Third value is blur (offset-x, offset-y, blur, [spread])
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
- }
- }
-
- return [];
-}
-
-/**
- * Regex-on-HTML checks shared between browser and Node page-level detection.
- * These don't need DOM access, just the raw HTML string.
- */
-function checkHtmlPatterns(html) {
- const findings = [];
-
- // --- Color ---
-
- // Pure black background
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
- if (pureBlackBgRe.test(html)) {
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
- }
-
- // AI color palette: purple/violet
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
- if (purpleHexRe.test(html)) {
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
- if (purpleTextRe.test(html)) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
- }
- }
-
- // Gradient text (background-clip: text + gradient)
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
- let gm;
- while ((gm = gradientRe.exec(html)) !== null) {
- const start = Math.max(0, gm.index - 200);
- const context = html.substring(start, gm.index + gm[0].length + 200);
- if (/gradient/i.test(context)) {
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
- break;
- }
- }
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
- }
-
- // --- Layout ---
-
- // Monotonous spacing
- const spacingValues = [];
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
- let sm;
- while ((sm = spacingRe.exec(html)) !== null) {
- const v = parseInt(sm[1], 10);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const gapRe = /gap\s*:\s*(\d+)px/gi;
- while ((sm = gapRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10));
- }
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
- while ((sm = twSpaceRe.exec(html)) !== null) {
- spacingValues.push(parseInt(sm[1], 10) * 4);
- }
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
- while ((sm = remSpacingRe.exec(html)) !== null) {
- const v = Math.round(parseFloat(sm[1]) * 16);
- if (v > 0 && v < 200) spacingValues.push(v);
- }
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
- if (roundedSpacing.length >= 10) {
- const counts = {};
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
- const maxCount = Math.max(...Object.values(counts));
- const dominantPct = maxCount / roundedSpacing.length;
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
- if (dominantPct > 0.6 && unique.length <= 3) {
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
- findings.push({
- id: 'monotonous-spacing',
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
- });
- }
- }
-
- // --- Motion ---
-
- // Bounce/elastic animation names
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
- if (bounceRe.test(html)) {
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
- }
-
- // Overshoot cubic-bezier
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
- let bm;
- while ((bm = bezierRe.exec(html)) !== null) {
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
- break;
- }
- }
-
- // Layout property transitions
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
- let tm;
- while ((tm = transRe.exec(html)) !== null) {
- const val = tm[1].toLowerCase();
- if (/\ball\b/.test(val)) continue;
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
- if (found) {
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
- break;
- }
- }
-
- // --- Dark glow ---
-
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
- let shm;
- while ((shm = shadowRe.exec(html)) !== null) {
- const val = shm[1];
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (!colorMatch) continue;
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
- if (pxVals.length >= 3 && pxVals[2] > 4) {
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
- break;
- }
- }
- }
-
- return findings;
-}
-
-// ─── Section 4: resolveBackground (unified) ─────────────────────────────────
-
-// Read the element's own background color, computed-style first, with a
-// jsdom-friendly fallback that parses the inline `background:` shorthand
-// from the raw style attribute. jsdom (~v29) does not decompose the
-// shorthand into `backgroundColor`, so without this fallback the CLI silently
-// returns null for any element styled via `background: rgb(...)` or
-// `background: #abc`. Real browsers always decompose, so the fallback is
-// a no-op there.
-function readOwnBackgroundColor(el, computedStyle) {
- const bg = parseRgb(computedStyle.backgroundColor);
- if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
- const rawStyle = el.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (!inlineBg) return bg;
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return bg;
- const fromRgb = parseRgb(inlineBg);
- if (fromRgb) return fromRgb;
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
- if (hexMatch) {
- const h = hexMatch[1];
- if (h.length === 6) {
- return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: 1 };
- }
- return { r: parseInt(h[0] + h[0], 16), g: parseInt(h[1] + h[1], 16), b: parseInt(h[2] + h[2], 16), a: 1 };
- }
- return bg;
-}
-
-function resolveBackground(el, win, customPropMap) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- const hasGradientOrUrl = bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage));
-
- // Try the solid bg-color FIRST. If the element has both a solid color
- // and a gradient/url overlay (a common pattern: `background: var(--paper)
- // radial-gradient(...)` for paper-grain texture), the solid color is the
- // dominant visible surface for contrast purposes; the overlay is
- // decorative. The old behavior bailed on any gradient ancestor, which
- // caused massive false-positive contrast findings on grain-textured
- // body backgrounds.
- let bg = parseRgb(style.backgroundColor);
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
- // through customPropMap so Tailwind v4 color tokens become RGB.
- if (customPropMap) {
- bg = parseColorResolved(style.backgroundColor, customPropMap);
- }
- if (!bg || bg.a < 0.1) {
- // Inline-style fallback. jsdom doesn't decompose background
- // shorthand, so colors set via inline style are otherwise invisible.
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
- }
- }
- }
-
- if (bg && bg.a > 0.1) {
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
- }
- // No solid bg-color at this level. If THIS level has a gradient/url
- // with no underlying solid color we can read:
- // • on body/html: assume white. Body-level gradients are almost
- // always decorative texture (paper grain, noise) on top of a
- // solid bg-color the page set via `background: var(--paper)`
- // shorthand — which jsdom can't decompose into bg-color. The
- // downstream gradient-stops fallback path produces catastrophic
- // false positives in this case (gradient noise stops have
- // accidental browns/blacks that look like card backgrounds).
- // • on other elements: bail to null and let the caller fall back
- // to gradient stops (gradient buttons / hero sections are real
- // bgs worth checking against).
- if (hasGradientOrUrl) {
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
- return { r: 255, g: 255, b: 255, a: 1 };
- }
- return null;
- }
- current = current.parentElement;
- }
- return { r: 255, g: 255, b: 255 };
-}
-
-// Walk parents looking for a gradient background and return its color stops.
-// Used as a fallback when resolveBackground() returns null because the
-// effective background is a gradient (no single solid color to compare against).
-function resolveGradientStops(el, win) {
- let current = el;
- while (current && current.nodeType === 1) {
- const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
- const bgImage = style.backgroundImage || '';
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
- const stops = parseGradientColors(bgImage);
- if (stops.length > 0) return stops;
- }
- if (!DETECTOR_IS_BROWSER) {
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
- const rawStyle = current.getAttribute?.('style') || '';
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
- const stops = parseGradientColors(bgMatch[1]);
- if (stops.length > 0) return stops;
- }
- }
- current = current.parentElement;
- }
- return null;
-}
-
-// Parse a single CSS length token to pixels. Accepts "12px", "50%", a
-// shorthand like "12px 4px" (uses the first value), or empty / null.
-// Returns the pixel value, or null when the input is unparseable.
-// Percentages convert against `widthPx` when one is supplied. Without a
-// usable width (jsdom returns "auto" for many real-world elements,
-// which parseFloat collapses to 0), fall back to the raw percentage
-// number so callers gating on `> 0` (border-accent-on-rounded,
-// isCardLike's hasRadius) still see a positive value, matching the
-// original parseFloat("50%") === 50 behavior.
-function parseRadiusToPx(value, widthPx) {
- if (!value || typeof value !== 'string') return null;
- const trimmed = value.trim();
- if (!trimmed) return null;
- const first = trimmed.split(/\s+/)[0];
- const num = parseFloat(first);
- if (Number.isNaN(num)) return null;
- if (/%$/.test(first)) {
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
- return num;
- }
- return num;
-}
-
-function resolveBorderRadiusPx(el, style, widthPx, win) {
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
- if (fromComputed !== null) return fromComputed;
- return 0;
-}
-
-// ─── Section 5: Element Adapters ────────────────────────────────────────────
-
-// Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
-
-function checkElementBordersDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (BORDER_SAFE_TAGS.has(tag)) return [];
- const rect = el.getBoundingClientRect();
- if (rect.width < 20 || rect.height < 20) return [];
- const style = getComputedStyle(el);
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- }
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
-}
-
-function checkElementColorsDOM(el) {
- const tag = el.tagName.toLowerCase();
- // No early SAFE_TAGS bail here — checkColors() does its own gating that
- // includes the styled-button exception for <a> / <button> with their own
- // opaque background. Bailing here would prevent that exception from firing.
- const rect = el.getBoundingClientRect();
- if (rect.width < 10 || rect.height < 10) return [];
- const style = getComputedStyle(el);
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
- const effectiveBg = resolveBackground(el);
- return checkColors({
- tag,
- textColor: parseRgb(style.color),
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementIconTileDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibRect = sibling.getBoundingClientRect();
- const headRect = el.getBoundingClientRect();
- const sibStyle = getComputedStyle(sibling);
-
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
- // may contain an emoji/symbol character directly as its only text content
- // (the "card-icon" pattern from many AI-generated demos).
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- const iconRect = iconChild?.getBoundingClientRect();
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: headRect.top,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibRect.width,
- siblingHeight: sibRect.height,
- siblingBottom: sibRect.bottom,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconRect?.width || 0,
- });
-}
-
-function checkElementItalicSerifDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1' && tag !== 'h2') return [];
- const style = getComputedStyle(el);
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrowDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const headStyle = getComputedStyle(el);
- const sibStyle = getComputedStyle(sibling);
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
- siblingFontWeight: sibStyle.fontWeight || '',
- siblingColor: sibStyle.color || '',
- });
-}
-
-// Build a map of CSS custom properties declared on :root / :host / html.
-// Used to resolve var(--X) refs that jsdom returns verbatim in
-// getComputedStyle. Tailwind v4 routes every utility class through
-// CSS vars (font-weight: var(--font-weight-bold), font-size:
-// var(--text-xs), letter-spacing: var(--tracking-widest)), so without
-// resolution every style-based check silently fails on Tailwind v4
-// builds — the values come back as literal "var(--font-weight-bold)"
-// strings and parseFloat returns NaN.
-function buildCustomPropMap(document) {
- const map = new Map();
- let sheets;
- try { sheets = Array.from(document.styleSheets || []); }
- catch { return map; }
- for (const sheet of sheets) {
- let rules;
- try { rules = Array.from(sheet.cssRules || []); }
- catch { continue; }
- for (const rule of rules) {
- // Style rules only (type 1). Walk @media / @supports if present.
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
- continue;
- }
- if (rule.type !== 1 /* STYLE_RULE */) continue;
- const sel = rule.selectorText || '';
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
- const style = rule.style;
- if (!style) continue;
- for (let i = 0; i < style.length; i++) {
- const prop = style[i];
- if (!prop || !prop.startsWith('--')) continue;
- const val = style.getPropertyValue(prop).trim();
- if (val) map.set(prop, val);
- }
- }
- }
- return map;
-}
-
-// Resolve var(--X[, fallback]) refs in a computed-style value string.
-// Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
-// the original string when no refs are present or the chain doesn't
-// resolve. Safe to call on already-resolved values.
-function resolveVarRefs(raw, customPropMap, depth = 0) {
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
- if (depth > 8) return raw;
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
- const v = customPropMap.get(name);
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
- });
-}
-
-// OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
-// C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
-// Needed because jsdom doesn't compute oklch() values — getComputedStyle
-// returns the literal "oklch(...)" string. Without this, the entire
-// Tailwind v4 color palette (which is OKLCH-based) is invisible to the
-// detector's contrast / color checks.
-function oklchToRgb(L, C, H) {
- const hRad = (H * Math.PI) / 180;
- const a = C * Math.cos(hRad);
- const b = C * Math.sin(hRad);
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
- const enc = (x) => {
- const c = Math.max(0, Math.min(1, x));
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
- };
- return {
- r: Math.round(enc(rLin) * 255),
- g: Math.round(enc(gLin) * 255),
- b: Math.round(enc(bLin) * 255),
- a: 1,
- };
-}
-
-// Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
-// Use this when the input might be any CSS color form; use plain parseRgb
-// when you only expect computed rgb() values from real browsers.
-function parseAnyColor(s) {
- if (!s || typeof s !== 'string') return null;
- const str = s.trim();
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
- let m;
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
- m = str.match(/^#([0-9a-f]{3,8})$/i);
- if (m) {
- const h = m[1];
- if (h.length === 3 || h.length === 4) {
- return {
- r: parseInt(h[0] + h[0], 16),
- g: parseInt(h[1] + h[1], 16),
- b: parseInt(h[2] + h[2], 16),
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
- };
- }
- if (h.length === 6 || h.length === 8) {
- return {
- r: parseInt(h.slice(0, 2), 16),
- g: parseInt(h.slice(2, 4), 16),
- b: parseInt(h.slice(4, 6), 16),
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
- };
- }
- }
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
- // Match L (with optional %), then C and H separated permissively.
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?\s*\)/i);
- if (m) {
- const Lnum = parseFloat(m[1]);
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
- return oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
- }
- return null;
-}
-
-// Resolve var() refs in a color string (via customPropMap), then parse.
-// Returns null on any failure. Used in jsdom-mode paths where
-// getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
-function parseColorResolved(str, customPropMap) {
- if (!str) return null;
- const resolved = customPropMap ? resolveVarRefs(str, customPropMap) : str;
- return parseAnyColor(resolved);
-}
-
-const REPEATED_KICKER_SKIP_SELECTOR = [
- 'nav',
- 'form',
- 'table',
- 'thead',
- 'tbody',
- 'tfoot',
- 'figure',
- 'figcaption',
- 'ol',
- 'ul',
- 'li',
- '[role="navigation"]',
- '[aria-label*="breadcrumb" i]',
- '[class*="breadcrumb" i]',
- '[data-impeccable-allow-kickers]',
-].join(',');
-
-function cleanInlineText(el) {
- return [...el.childNodes]
- .filter(n => n.nodeType === 3)
- .map(n => n.textContent)
- .join(' ')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isRepeatedKickerCandidate(opts) {
- const {
- headingTag,
- headingText,
- headingFontSize,
- kickerTag,
- kickerText,
- kickerTextTransform,
- kickerFontSize,
- kickerLetterSpacing,
- } = opts;
- if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
- if (!headingText || headingText.length < 3) return false;
- if (!(headingFontSize >= 20)) return false;
- if (!kickerTag || HEADING_TAGS.has(kickerTag)) return false;
- if (!['p', 'span', 'div', 'small'].includes(kickerTag)) return false;
- if (!kickerText || kickerText.length < 2 || kickerText.length > 34) return false;
- if (/^step\s*\d+/i.test(kickerText) || /^\d{1,2}$/.test(kickerText)) return false;
-
- const isUppercased = kickerTextTransform === 'uppercase'
- || (/[A-Z]/.test(kickerText) && !/[a-z]/.test(kickerText));
- if (!isUppercased) return false;
- if (!(kickerFontSize > 0 && kickerFontSize <= 14)) return false;
- const minTrackedSpacing = Math.max(1, kickerFontSize * 0.08);
- if (!(kickerLetterSpacing >= minTrackedSpacing)) return false;
- return true;
-}
-
-function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
- const candidates = [];
- for (const heading of doc.querySelectorAll('h2, h3, h4')) {
- if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
- const kicker = heading.previousElementSibling;
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
-
- const headingStyle = getStyle(heading);
- const kickerStyle = getStyle(kicker);
- const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
- const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
-
- if (!isRepeatedKickerCandidate({
- headingTag: heading.tagName.toLowerCase(),
- headingText,
- headingFontSize,
- kickerTag: kicker.tagName.toLowerCase(),
- kickerText,
- kickerTextTransform: kickerStyle.textTransform || '',
- kickerFontSize,
- kickerLetterSpacing,
- })) {
- continue;
- }
-
- candidates.push({
- headingTag: heading.tagName.toLowerCase(),
- headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
- kickerText: kickerText.slice(0, 40),
- });
- }
- return candidates;
-}
-
-function checkRepeatedSectionKickersDOM() {
- const candidates = collectRepeatedSectionKickerCandidates(
- document,
- (el) => getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotionDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag)) return [];
- const style = getComputedStyle(el);
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: el.getAttribute('class') || '',
- });
-}
-
-function checkElementGlowDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- // Use parent's background — glow radiates outward, so the surrounding context matters
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
- if (!parentBg) {
- // Gradient background — sample its colors to determine if it's dark
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const bgImage = getComputedStyle(cur).backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- if (gradColors.length > 0) {
- // Average the gradient colors
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gradColors.length);
- avg.g = Math.round(avg.g / gradColors.length);
- avg.b = Math.round(avg.b / gradColors.length);
- parentBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
-}
-
-function checkElementAIPaletteDOM(el) {
- const style = getComputedStyle(el);
- const findings = [];
-
- // Check gradient backgrounds for purple/violet or cyan
- const bgImage = style.backgroundImage || '';
- const gradColors = parseGradientColors(bgImage);
- for (const c of gradColors) {
- if (hasChroma(c, 50)) {
- const hue = getHue(c);
- if (hue >= 260 && hue <= 310) {
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
- break;
- }
- if (hue >= 160 && hue <= 200) {
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
- break;
- }
- }
- }
-
- // Check for neon text (vivid cyan/purple color on dark background)
- const textColor = parseRgb(style.color);
- if (textColor && hasChroma(textColor, 80)) {
- const hue = getHue(textColor);
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
- if (isAIPalette) {
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
- // Also check gradient parents
- let effectiveBg = parentBg;
- if (!effectiveBg) {
- let cur = el.parentElement;
- while (cur && cur.nodeType === 1) {
- const gi = getComputedStyle(cur).backgroundImage || '';
- const gc = parseGradientColors(gi);
- if (gc.length > 0) {
- const avg = { r: 0, g: 0, b: 0 };
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
- avg.r = Math.round(avg.r / gc.length);
- avg.g = Math.round(avg.g / gc.length);
- avg.b = Math.round(avg.b / gc.length);
- effectiveBg = avg;
- break;
- }
- cur = cur.parentElement;
- }
- }
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
- }
- }
- }
-
- return findings;
-}
-
-const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
-
-// Resolve a CSS font-size value to pixels by walking up the parent chain.
-// Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
-// specified value verbatim — so for the Node path we walk parents ourselves.
-function resolveFontSizePx(el, win) {
- const chain = []; // raw font-size strings, leaf → root
- let cur = el;
- while (cur && cur.nodeType === 1) {
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
- chain.push(fs || '');
- cur = cur.parentElement;
- }
- // Walk root → leaf, resolving each value relative to its parent context.
- let px = 16; // root default
- for (let i = chain.length - 1; i >= 0; i--) {
- const v = chain[i];
- if (!v || v === 'inherit') continue;
- const num = parseFloat(v);
- if (isNaN(num)) continue;
- if (v.endsWith('px')) px = num;
- else if (v.endsWith('rem')) px = num * 16;
- else if (v.endsWith('em')) px = num * px;
- else if (v.endsWith('%')) px = (num / 100) * px;
- else px = num; // unitless — already resolved
- }
- return px;
-}
-
-// Resolve a CSS length value (line-height, letter-spacing, etc.) given a
-// known font-size context. Returns null for "normal" / unparseable values.
-function resolveLengthPx(value, fontSizePx) {
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
- const num = parseFloat(value);
- if (isNaN(num)) return null;
- if (value.endsWith('px')) return num;
- if (value.endsWith('rem')) return num * 16;
- if (value.endsWith('em')) return num * fontSizePx;
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
- // Unitless line-height = multiplier, return px equivalent
- return num * fontSizePx;
-}
-
-// Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
-// jsdom and the browser). Two checks (line-length, cramped-padding) gate on
-// element rect dimensions, which jsdom can't compute — pass `rect: null` from
-// the Node adapter to skip those.
-//
-// Both adapters resolve font-size, line-height and letter-spacing to pixels
-// before calling this so the pure function only deals with numbers.
-function checkQuality(opts) {
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80, viewportWidth = 0 } = opts;
- const findings = [];
- // Skip browser extension injected elements
- const elId = el.id || '';
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
-
- // --- Line length too long --- (browser-only: needs rect.width)
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
- const charsPerLine = rect.width / (fontSize * 0.5);
- if (charsPerLine > lineMax + 5) {
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
- }
- }
-
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
- // Vertical and horizontal thresholds are independent because line-height
- // already provides built-in vertical breathing room (the line box is taller
- // than the cap height), but horizontal has no equivalent. Both scale with
- // font-size — bigger text demands proportionally more padding.
- // vertical: max(4px, fontSize × 0.3)
- // horizontal: max(8px, fontSize × 0.5)
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
- const borders = {
- top: parseFloat(style.borderTopWidth) || 0,
- right: parseFloat(style.borderRightWidth) || 0,
- bottom: parseFloat(style.borderBottomWidth) || 0,
- left: parseFloat(style.borderLeftWidth) || 0,
- };
- const borderCount = Object.values(borders).filter(w => w > 0).length;
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
- if (borderCount >= 2 || hasBg) {
- const vPads = [], hPads = [];
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
-
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
- const vThresh = Math.max(4, fontSize * 0.3);
- const hThresh = Math.max(8, fontSize * 0.5);
-
- // Emit at most one finding per element — pick whichever axis is worse.
- if (vMin < vThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
- } else if (hMin < hThresh) {
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
- }
- }
- }
-
- // --- Body text touching viewport edge --- (browser-only: needs rect)
- // Catches the failure mode where the agent ships body paragraphs
- // with NO container providing horizontal padding — text bleeds
- // directly to the viewport edge. Different from cramped-padding,
- // which requires a colored/bordered container. Here the failure
- // is the absence of the container entirely.
- //
- // Gate aggressively to avoid false positives:
- // - <p> or <li> only (body content; not headings, not nav, not
- // wrappers)
- // - text > 40 chars (paragraph-like, not a label)
- // - rect.width > 50% of viewport (real body, not a pull-quote)
- // - rect.left < 16 OR rect.right > viewport - 16 (actually
- // touching the edge)
- // - not inside <nav> or <header> (those legitimately bleed)
- // - element itself has no background-color (intentional full-bleed
- // sections set a bg-color and provide their own internal padding)
- if (rect && hasDirectText && textLen > 40 && ['P', 'LI'].includes(tag.toUpperCase()) && viewportWidth > 0) {
- const inNavHeader = el.closest && (el.closest('nav') || el.closest('header'));
- const hasOwnBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent';
- const isPositioned = ['fixed', 'absolute'].includes(style.position || '');
- const widthRatio = rect.width / viewportWidth;
- const leftClose = rect.left < 16;
- const rightClose = rect.right > viewportWidth - 16;
- if (!inNavHeader && !hasOwnBg && !isPositioned && widthRatio > 0.5 && (leftClose || rightClose)) {
- const which = leftClose && rightClose
- ? `left ${Math.round(rect.left)}px / right ${Math.round(viewportWidth - rect.right)}px`
- : leftClose
- ? `left ${Math.round(rect.left)}px`
- : `right ${Math.round(viewportWidth - rect.right)}px`;
- findings.push({ id: 'body-text-viewport-edge', snippet: `<${tag.toLowerCase()}> with ${textLen}-char body bleeds to viewport edge (${which})` });
- }
- }
-
- // --- Tight line height ---
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- if (lineHeightPx != null && fontSize > 0) {
- const ratio = lineHeightPx / fontSize;
- if (ratio > 0 && ratio < 1.3) {
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
- }
- }
- }
-
- // --- Justified text (without hyphens) ---
- if (hasDirectText && style.textAlign === 'justify') {
- const hyphens = style.hyphens || style.webkitHyphens || '';
- if (hyphens !== 'auto') {
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
- }
- }
-
- // --- Tiny body text ---
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
- if (hasDirectText && textLen > 20 && fontSize < 12) {
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
- const isUppercase = style.textTransform === 'uppercase';
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
- }
- }
-
- // --- All-caps body text ---
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
- }
- }
-
- // --- Wide letter spacing on body text ---
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
- const trackingEm = letterSpacingPx / fontSize;
- if (trackingEm > 0.05) {
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
- }
- }
- }
-
- return findings;
-}
-
-function checkElementQualityDOM(el) {
- const tag = el.tagName.toLowerCase();
- const style = getComputedStyle(el);
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- // Browser getComputedStyle resolves everything to px — direct parseFloat
- // works.
- const fontSize = parseFloat(style.fontSize) || 16;
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- const rect = el.getBoundingClientRect();
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
- const viewportWidth = (typeof window !== 'undefined' ? window.innerWidth : 0) || 0;
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax, viewportWidth });
-}
-
-// Pure page-level skipped-heading walk. Takes a Document so it works in both
-// the browser and jsdom.
-function checkPageQualityFromDoc(doc) {
- const findings = [];
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
- let prevLevel = 0;
- let prevText = '';
- for (const h of headings) {
- const level = parseInt(h.tagName[1]);
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
- if (prevLevel > 0 && level > prevLevel + 1) {
- findings.push({
- id: 'skipped-heading',
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
- });
- }
- prevLevel = level;
- prevText = text;
- }
- return findings;
-}
-
-// Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
-function checkPageQualityDOM() {
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
-}
-
-// Node adapters — take pre-extracted jsdom computed style
-
-// jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
-// CSS length the rule needs ourselves (walking the parent chain for
-// font-size inheritance), and pass `rect: null` to skip the two rules that
-// genuinely need element rects (line-length, cramped-padding).
-function checkElementQuality(el, style, tag, window) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
- const textLen = el.textContent?.trim().length || 0;
- const fontSize = resolveFontSizePx(el, window);
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
-}
-
-function checkElementBorders(tag, style, overrides, resolvedRadius) {
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
- const widths = {}, colors = {};
- for (const s of sides) {
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
- colors[s] = style[`border${s}Color`] || '';
- // jsdom silently drops any border shorthand containing var(), leaving
- // both width and color empty on the computed style. When the detectHtml
- // pre-pass pulled a resolved value off the rule, use it to fill in the
- // missing side so the side-tab check can run. Real browsers resolve
- // var() natively, so this fallback is a no-op in the browser path.
- if (widths[s] === 0 && overrides && overrides[s]) {
- widths[s] = overrides[s].width;
- colors[s] = overrides[s].color;
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
- // Longhand case: jsdom kept the width but left the color as the
- // literal `var(...)` string. Substitute the resolved color.
- colors[s] = overrides[s].color;
- }
- }
- // resolvedRadius lets the caller pre-resolve the radius via
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
- // shorthand serialization. Falls back to the computed value for tests
- // and browser callers that don't pre-resolve.
- const radius = resolvedRadius != null
- ? resolvedRadius
- : (parseFloat(style.borderRadius) || 0);
- return checkBorders(tag, widths, colors, radius);
-}
-
-function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasDirectText = directText.trim().length > 0;
-
- const effectiveBg = resolveBackground(el, window, customPropMap);
- // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
- // parseRgb misses Tailwind-tokenized text colors. Resolve through the
- // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
- let textColor = customPropMap ? parseColorResolved(style.color, customPropMap) : null;
- if (!textColor) textColor = parseRgb(style.color);
-
- // Anchor-inherit FP workaround: jsdom's UA stylesheet has `:link { color:
- // blue }` at high specificity. The page's `a { color: inherit }` rule
- // (Tailwind v4 preflight) loses to jsdom even though it WINS in real
- // browsers (Chrome's UA wraps :link in :where() — zero specificity).
- // When the page declares the inherit rule AND we see jsdom's default
- // link blue on an anchor, walk to the nearest non-anchor ancestor and
- // use its color instead.
- if (
- hasAnchorInheritRule &&
- textColor &&
- textColor.r === 0 && textColor.g === 0 && textColor.b === 238 &&
- (tag === 'a' || el.closest?.('a'))
- ) {
- let cur = el.parentElement;
- while (cur && cur.tagName !== 'HTML') {
- if (cur.tagName !== 'A') {
- const ps = window.getComputedStyle(cur);
- const inh = (customPropMap ? parseColorResolved(ps.color, customPropMap) : null) || parseRgb(ps.color);
- if (inh && !(inh.r === 0 && inh.g === 0 && inh.b === 238)) {
- textColor = inh;
- break;
- }
- }
- cur = cur.parentElement;
- }
- }
-
- return checkColors({
- tag,
- textColor,
- bgColor: readOwnBackgroundColor(el, style),
- effectiveBg,
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
- fontSize: parseFloat(style.fontSize) || 16,
- fontWeight: parseInt(style.fontWeight) || 400,
- hasDirectText,
- isEmojiOnly: isEmojiOnlyText(directText),
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
- bgImage: style.backgroundImage || '',
- classList: el.getAttribute?.('class') || el.className || '',
- });
-}
-
-function checkElementIconTile(el, tag, window) {
- if (!HEADING_TAGS.has(tag)) return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
-
- const sibStyle = window.getComputedStyle(sibling);
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
- const sibWidth = parseFloat(sibStyle.width) || 0;
- const sibHeight = parseFloat(sibStyle.height) || 0;
-
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
- let iconWidth = 0;
- if (iconChild) {
- const iconStyle = window.getComputedStyle(iconChild);
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
- }
- // Or: tile contains an emoji/symbol character directly as its only content
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
-
- return checkIconTile({
- headingTag: tag,
- headingText: el.textContent || '',
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
- siblingTag: sibling.tagName.toLowerCase(),
- siblingWidth: sibWidth,
- siblingHeight: sibHeight,
- siblingBottom: 0,
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
- siblingBgImage: sibStyle.backgroundImage || '',
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
- iconChildWidth: iconWidth,
- });
-}
-
-function checkElementItalicSerif(el, style, tag) {
- if (tag !== 'h1' && tag !== 'h2') return [];
- return checkItalicSerif({
- tag,
- fontStyle: style.fontStyle || '',
- fontFamily: style.fontFamily || '',
- fontSize: parseFloat(style.fontSize) || 0,
- headingText: el.textContent || '',
- });
-}
-
-function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
- if (tag !== 'h1') return [];
- const sibling = el.previousElementSibling;
- if (!sibling) return [];
- const sibStyle = window.getComputedStyle(sibling);
- // Resolve Tailwind v4 CSS-variable wrappers (font-weight:var(--font-weight-bold)
- // etc.) before parsing. jsdom returns these verbatim from getComputedStyle;
- // without resolution every style-based gate fails silently on Tailwind v4 builds.
- const fontSizeRaw = customPropMap ? resolveVarRefs(sibStyle.fontSize, customPropMap) : sibStyle.fontSize;
- const fontWeightRaw = customPropMap ? resolveVarRefs(sibStyle.fontWeight, customPropMap) : sibStyle.fontWeight;
- const letterSpacingRaw = customPropMap ? resolveVarRefs(sibStyle.letterSpacing, customPropMap) : sibStyle.letterSpacing;
- const colorRaw = customPropMap ? resolveVarRefs(sibStyle.color, customPropMap) : sibStyle.color;
- const headingFontSizeRaw = customPropMap ? resolveVarRefs(style.fontSize, customPropMap) : style.fontSize;
- const siblingFontSize = parseFloat(fontSizeRaw) || 0;
- // resolveLengthPx returns null for 'normal' / 'auto'; coerce to 0 so the
- // gate falls through cleanly. jsdom returns letter-spacing verbatim
- // (e.g. '0.15em'), unlike real browsers, so this conversion is required.
- return checkHeroEyebrow({
- headingTag: tag,
- headingText: el.textContent || '',
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
- siblingTag: sibling.tagName.toLowerCase(),
- siblingText: sibling.textContent || '',
- siblingTextTransform: sibStyle.textTransform || '',
- siblingFontSize,
- siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
- siblingFontWeight: fontWeightRaw || '',
- siblingColor: colorRaw || '',
- });
-}
-
-function checkRepeatedSectionKickersFromDoc(doc, win) {
- const candidates = collectRepeatedSectionKickerCandidates(
- doc,
- (el) => win.getComputedStyle(el),
- (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
- );
- return checkRepeatedSectionKickers({ candidates });
-}
-
-function checkElementMotion(tag, style) {
- return checkMotion({
- tag,
- transitionProperty: style.transitionProperty || '',
- animationName: style.animationName || '',
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
- classList: '',
- });
-}
-
-function checkElementGlow(tag, style, effectiveBg) {
- if (!style.boxShadow || style.boxShadow === 'none') return [];
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
-}
-
-// ─── Section 6: Page-Level Checks ───────────────────────────────────────────
-
-// Browser page-level checks — use document/getComputedStyle globals
-
-function checkTypography() {
- const findings = [];
-
- // Walk actual text-bearing elements and tally font usage by *computed style*.
- // This is much more accurate than scanning CSS rules — it ignores rules that
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
- // anti-patterns), and counts what the user actually sees.
- const fontUsage = new Map(); // primary font name → count of elements
- let totalTextElements = 0;
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
- // Skip impeccable's own elements
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
- // Only count elements that actually have visible direct text
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
- if (!hasText) continue;
- const style = getComputedStyle(el);
- const ff = style.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (!primary) continue;
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
- totalTextElements++;
- }
-
- if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
- const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
- }
-
- // Single-font check: only one distinct primary font across all text
- if (fontUsage.size === 1) {
- const only = [...fontUsage.keys()][0];
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
- }
- }
-
- const sizes = new Set();
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
- const fs = parseFloat(getComputedStyle(el).fontSize);
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLikeDOM(el) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
- const style = getComputedStyle(el);
- const cls = el.getAttribute('class') || '';
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
- const hasBorder = /\bborder\b/.test(cls);
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkLayout() {
- const findings = [];
- const flaggedEls = new Set();
-
- for (const el of document.querySelectorAll('*')) {
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
- const cls = el.getAttribute('class') || '';
- const style = getComputedStyle(el);
- if (style.position === 'absolute' || style.position === 'fixed') continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- const rect = el.getBoundingClientRect();
- if (rect.width < 50 || rect.height < 30) continue;
-
- let parent = el.parentElement;
- while (parent) {
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
- parent = parent.parentElement;
- }
- }
-
- for (const el of flaggedEls) {
- let isAncestor = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
- }
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
- }
-
- return findings;
-}
-
-// Node page-level checks — take document/window as parameters
-
-function checkPageTypography(doc, win) {
- const findings = [];
-
- const fonts = new Set();
- const overusedFound = new Set();
-
- for (const sheet of doc.styleSheets) {
- let rules;
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
- if (!rules) continue;
- for (const rule of rules) {
- if (rule.type !== 1) continue;
- const ff = rule.style?.fontFamily;
- if (!ff) continue;
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
- if (primary) {
- fonts.add(primary);
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
- }
- }
- }
-
- // Check Google Fonts links in HTML
- const html = doc.documentElement?.outerHTML || '';
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
- let m;
- while ((m = gfRe.exec(html)) !== null) {
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
- for (const f of families) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
-
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
- let fm;
- while ((fm = ffRe.exec(html)) !== null) {
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
- if (f && !GENERIC_FONTS.has(f)) {
- fonts.add(f);
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
- }
- }
- }
-
- for (const font of overusedFound) {
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
- }
-
- // Single font
- if (fonts.size === 1) {
- const els = doc.querySelectorAll('*');
- if (els.length >= 20) {
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
- }
- }
-
- // Flat type hierarchy
- const sizes = new Set();
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
- for (const el of textEls) {
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
- }
- if (sizes.size >= 3) {
- const sorted = [...sizes].sort((a, b) => a - b);
- const ratio = sorted[sorted.length - 1] / sorted[0];
- if (ratio < 2.0) {
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
- }
- }
-
- return findings;
-}
-
-function isCardLike(el, win) {
- const tag = el.tagName.toLowerCase();
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
-
- const style = win.getComputedStyle(el);
- const rawStyle = el.getAttribute?.('style') || '';
- const cls = el.getAttribute?.('class') || '';
-
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
- const hasBorder = /\bborder\b/.test(cls);
- const widthPx = parseFloat(style.width) || 0;
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
-
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
-}
-
-function checkPageLayout(doc, win) {
- const findings = [];
-
- // Nested cards
- const allEls = doc.querySelectorAll('*');
- const flaggedEls = new Set();
- for (const el of allEls) {
- if (!isCardLike(el, win)) continue;
- if (flaggedEls.has(el)) continue;
-
- const tag = el.tagName.toLowerCase();
- const cls = el.getAttribute?.('class') || '';
- const rawStyle = el.getAttribute?.('style') || '';
-
- if (['pre', 'code'].includes(tag)) continue;
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
- if ((el.textContent?.trim().length || 0) < 10) continue;
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
-
- // Walk up to find card-like ancestor
- let parent = el.parentElement;
- while (parent) {
- if (isCardLike(parent, win)) {
- flaggedEls.add(el);
- break;
- }
- parent = parent.parentElement;
- }
- }
-
- // Only report innermost nested cards
- for (const el of flaggedEls) {
- let isAncestorOfFlagged = false;
- for (const other of flaggedEls) {
- if (other !== el && el.contains(other)) {
- isAncestorOfFlagged = true;
- break;
- }
- }
- if (!isAncestorOfFlagged) {
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
- }
- }
-
- // Everything centered
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
- let centeredCount = 0;
- let totalText = 0;
- for (const el of textEls) {
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
- if (!hasDirectText) continue;
- totalText++;
-
- let cur = el;
- let isCentered = false;
- while (cur && cur.nodeType === 1) {
- const rawStyle = cur.getAttribute?.('style') || '';
- const cls = cur.getAttribute?.('class') || '';
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
- isCentered = true;
- break;
- }
- if (cur.tagName === 'BODY') break;
- cur = cur.parentElement;
- }
- if (isCentered) centeredCount++;
- }
-
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
- findings.push({
- id: 'everything-centered',
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
- });
- }
-
- return findings;
-}
-
-export {
- checkBorders,
- isEmojiOnlyText,
- checkColors,
- isCardLikeFromProps,
- checkIconTile,
- resolveSerif,
- checkItalicSerif,
- isAccentColor,
- checkHeroEyebrow,
- checkRepeatedSectionKickers,
- checkMotion,
- checkGlow,
- checkHtmlPatterns,
- readOwnBackgroundColor,
- resolveBackground,
- resolveGradientStops,
- parseRadiusToPx,
- resolveBorderRadiusPx,
- checkElementBordersDOM,
- checkElementColorsDOM,
- checkElementIconTileDOM,
- checkElementItalicSerifDOM,
- checkElementHeroEyebrowDOM,
- buildCustomPropMap,
- resolveVarRefs,
- oklchToRgb,
- parseAnyColor,
- parseColorResolved,
- cleanInlineText,
- isRepeatedKickerCandidate,
- collectRepeatedSectionKickerCandidates,
- checkRepeatedSectionKickersDOM,
- checkElementMotionDOM,
- checkElementGlowDOM,
- checkElementAIPaletteDOM,
- resolveFontSizePx,
- resolveLengthPx,
- checkQuality,
- checkElementQualityDOM,
- checkPageQualityFromDoc,
- checkPageQualityDOM,
- checkElementQuality,
- checkElementBorders,
- checkElementColors,
- checkElementIconTile,
- checkElementItalicSerif,
- checkElementHeroEyebrow,
- checkRepeatedSectionKickersFromDoc,
- checkElementMotion,
- checkElementGlow,
- checkTypography,
- isCardLikeDOM,
- checkLayout,
- checkPageTypography,
- isCardLike,
- checkPageLayout,
-};
@@ -1,124 +0,0 @@
-// ─── Section 2: Color Utilities ─────────────────────────────────────────────
-
-function isNeutralColor(color) {
- if (!color || color === 'transparent') return true;
-
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgb) {
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
- }
-
- // oklch()/lch() — chroma is the second numeric component.
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
- // literally (it does NOT convert them to rgb).
- const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (oklch) return parseFloat(oklch[1]) < 0.02;
- const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
- if (lch) return parseFloat(lch[1]) < 3;
-
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
- const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (oklab) {
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
- return Math.hypot(a, b) < 0.02;
- }
- const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
- if (lab) {
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
- return Math.hypot(a, b) < 3;
- }
-
- // hsl/hsla — saturation is the second numeric component (percent).
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
- // safety across versions and for any engine that preserves the format.
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
- if (hsl) return parseFloat(hsl[1]) < 10;
-
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
- if (hwb) {
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
- return (1 - Math.min(100, w + b) / 100) < 0.1;
- }
-
- // Unknown / unrecognized format — err on the side of DETECTING rather
- // than silently skipping. This is the opposite of the previous default,
- // which was the root cause of the oklch bug.
- return false;
-}
-
-function parseRgb(color) {
- if (!color || color === 'transparent') return null;
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (!m) return null;
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
-}
-
-function relativeLuminance({ r, g, b }) {
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
- );
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
-}
-
-function contrastRatio(c1, c2) {
- const l1 = relativeLuminance(c1);
- const l2 = relativeLuminance(c2);
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
-}
-
-function parseGradientColors(bgImage) {
- if (!bgImage || !bgImage.includes('gradient')) return [];
- const colors = [];
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
- const c = parseRgb(m[0]);
- if (c) colors.push(c);
- }
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
- const h = m[1];
- if (h.length === 6) {
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
- } else {
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
- }
- }
- return colors;
-}
-
-function hasChroma(c, threshold = 30) {
- if (!c) return false;
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
-}
-
-function getHue(c) {
- if (!c) return 0;
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
- if (max === min) return 0;
- const d = max - min;
- let h;
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
- else if (max === g) h = ((b - r) / d + 2) / 6;
- else h = ((r - g) / d + 4) / 6;
- return Math.round(h * 360);
-}
-
-function colorToHex(c) {
- if (!c) return '?';
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
-}
-
-export {
- isNeutralColor,
- parseRgb,
- relativeLuminance,
- contrastRatio,
- parseGradientColors,
- hasChroma,
- getHue,
- colorToHex,
-};
@@ -1,101 +0,0 @@
-// ─── Section 1: Constants ───────────────────────────────────────────────────
-
-const SAFE_TAGS = new Set([
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
-]);
-
-// Per-check safe-tags override for the border (side-tab / border-accent)
-// rule. We intentionally re-allow <label> here because card-shaped clickable
-// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
-// canonical side-tab anti-pattern shapes and must be detected. The rule's
-// other preconditions (non-neutral color, width >= 2px on a single side,
-// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
-// already filter out plain inline form labels so this does not introduce
-// false positives. See modern-color-borders.html for the test matrix.
-const BORDER_SAFE_TAGS = new Set(
- [...SAFE_TAGS].filter(t => t !== 'label')
-);
-
-const OVERUSED_FONTS = new Set([
- // Older monoculture (still ubiquitous):
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
- // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
- 'fraunces', 'instrument sans',
- 'geist', 'geist sans', 'geist mono',
- 'mona sans',
- 'plus jakarta sans', 'space grotesk', 'recoleta',
-]);
-
-// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
-// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
-const GOOGLE_DOMAINS = [
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
-];
-const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
-const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
-const BRAND_FONT_DOMAINS = {
- 'roboto': GOOGLE_DOMAINS,
- 'google sans': GOOGLE_DOMAINS,
- 'product sans': GOOGLE_DOMAINS,
- 'geist': VERCEL_DOMAINS,
- 'geist sans': VERCEL_DOMAINS,
- 'geist mono': VERCEL_DOMAINS,
- 'mona sans': GITHUB_DOMAINS,
-};
-
-function isBrandFontOnOwnDomain(font) {
- if (typeof location === 'undefined') return false;
- const allowed = BRAND_FONT_DOMAINS[font];
- if (!allowed) return false;
- const host = location.hostname.toLowerCase();
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
-}
-
-const GENERIC_FONTS = new Set([
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
- 'inherit', 'initial', 'unset', 'revert',
-]);
-
-// WCAG large text thresholds are defined in points: 18pt normal text and
-// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
-const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
-const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
-
-// Serif faces that show up in italic-display heroes. The rule also fires when
-// the primary face is unknown but the stack ends in the generic `serif` token,
-// which catches custom/private faces with a serif fallback.
-const KNOWN_SERIF_FONTS = new Set([
- 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
- 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
- 'tiempos', 'tiempos headline', 'tiempos text',
- 'lora', 'vollkorn', 'spectral',
- 'source serif pro', 'source serif 4', 'source serif',
- 'ibm plex serif', 'merriweather',
- 'libre caslon', 'libre baskerville', 'baskerville',
- 'georgia', 'times new roman', 'times',
- 'dm serif display', 'dm serif text',
- 'instrument serif', 'gt sectra', 'ogg', 'canela',
- 'freight display', 'freight text',
-]);
-
-export {
- SAFE_TAGS,
- BORDER_SAFE_TAGS,
- OVERUSED_FONTS,
- GOOGLE_DOMAINS,
- VERCEL_DOMAINS,
- GITHUB_DOMAINS,
- BRAND_FONT_DOMAINS,
- isBrandFontOnOwnDomain,
- GENERIC_FONTS,
- WCAG_LARGE_TEXT_PX,
- WCAG_LARGE_BOLD_TEXT_PX,
- KNOWN_SERIF_FONTS,
-};
@@ -1,7 +0,0 @@
-/** Check if content looks like a full page (not a component/partial) */
-function isFullPage(content) {
- const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
- return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
-}
-
-export { isFullPage };
@@ -1,25 +0,0 @@
-export const FILE_DOWNLOAD_PROVIDER_CONFIG_DIRS = Object.freeze({
- cursor: '.cursor',
- 'claude-code': '.claude',
- gemini: '.gemini',
- codex: '.codex',
- agents: '.agents',
- github: '.github',
- kiro: '.kiro',
- opencode: '.opencode',
- pi: '.pi',
- qoder: '.qoder',
-});
-
-export const FILE_DOWNLOAD_PROVIDERS = Object.freeze(
- Object.keys(FILE_DOWNLOAD_PROVIDER_CONFIG_DIRS)
-);
-
-export const BUNDLE_DOWNLOAD_PROVIDERS = Object.freeze([
- 'universal',
-]);
-
-export const DOWNLOAD_PROVIDERS = Object.freeze([
- ...FILE_DOWNLOAD_PROVIDERS,
- ...BUNDLE_DOWNLOAD_PROVIDERS,
-]);
@@ -1,281 +0,0 @@
-{
- "schemaVersion": 2,
- "generatedAt": "2026-04-29T00:00:00Z",
- "title": "Design System: Lumina",
- "extensions": {
- "colorMeta": {
- "cream": {
- "role": "neutral",
- "displayName": "Cream",
- "canonical": "oklch(96.5% 0.012 80)",
- "tonalRamp": [
- "oklch(15% 0.012 80)",
- "oklch(25% 0.012 80)",
- "oklch(35% 0.012 80)",
- "oklch(50% 0.012 80)",
- "oklch(65% 0.012 80)",
- "oklch(80% 0.012 80)",
- "oklch(90% 0.012 80)",
- "oklch(96.5% 0.012 80)"
- ]
- },
- "cream-warm": {
- "role": "neutral",
- "displayName": "Cream Warm",
- "canonical": "oklch(92% 0.020 75)",
- "tonalRamp": [
- "oklch(15% 0.020 75)",
- "oklch(25% 0.020 75)",
- "oklch(35% 0.020 75)",
- "oklch(50% 0.020 75)",
- "oklch(65% 0.020 75)",
- "oklch(78% 0.020 75)",
- "oklch(85% 0.020 75)",
- "oklch(92% 0.020 75)"
- ]
- },
- "peach": {
- "role": "neutral",
- "displayName": "Peach",
- "canonical": "oklch(91% 0.040 60)",
- "tonalRamp": [
- "oklch(20% 0.040 60)",
- "oklch(30% 0.060 60)",
- "oklch(45% 0.080 60)",
- "oklch(60% 0.080 60)",
- "oklch(72% 0.060 60)",
- "oklch(82% 0.050 60)",
- "oklch(88% 0.045 60)",
- "oklch(91% 0.040 60)"
- ]
- },
- "line": {
- "role": "neutral",
- "displayName": "Line (Hairline Border)",
- "canonical": "oklch(89% 0.018 75)",
- "tonalRamp": [
- "oklch(15% 0.018 75)",
- "oklch(25% 0.018 75)",
- "oklch(40% 0.018 75)",
- "oklch(55% 0.018 75)",
- "oklch(70% 0.018 75)",
- "oklch(80% 0.018 75)",
- "oklch(85% 0.018 75)",
- "oklch(89% 0.018 75)"
- ]
- },
- "ink": {
- "role": "neutral",
- "displayName": "Ink",
- "canonical": "oklch(15% 0.010 60)",
- "tonalRamp": [
- "oklch(15% 0.010 60)",
- "oklch(22% 0.010 60)",
- "oklch(30% 0.010 60)",
- "oklch(40% 0.010 60)",
- "oklch(55% 0.010 60)",
- "oklch(70% 0.010 60)",
- "oklch(85% 0.010 60)",
- "oklch(94% 0.010 60)"
- ]
- },
- "soft": {
- "role": "neutral",
- "displayName": "Soft",
- "canonical": "oklch(40% 0.012 60)",
- "tonalRamp": [
- "oklch(15% 0.012 60)",
- "oklch(25% 0.012 60)",
- "oklch(35% 0.012 60)",
- "oklch(40% 0.012 60)",
- "oklch(55% 0.012 60)",
- "oklch(70% 0.012 60)",
- "oklch(82% 0.012 60)",
- "oklch(92% 0.012 60)"
- ]
- },
- "accent": {
- "role": "primary",
- "displayName": "Burnt Orange Accent",
- "canonical": "oklch(60% 0.150 40)",
- "tonalRamp": [
- "oklch(15% 0.060 40)",
- "oklch(25% 0.090 40)",
- "oklch(35% 0.120 40)",
- "oklch(48% 0.150 40)",
- "oklch(60% 0.150 40)",
- "oklch(72% 0.130 40)",
- "oklch(85% 0.080 40)",
- "oklch(95% 0.040 40)"
- ]
- },
- "accent-deep": {
- "role": "primary",
- "displayName": "Accent Deep",
- "canonical": "oklch(50% 0.150 38)",
- "tonalRamp": [
- "oklch(15% 0.060 38)",
- "oklch(25% 0.090 38)",
- "oklch(35% 0.120 38)",
- "oklch(50% 0.150 38)",
- "oklch(62% 0.140 38)",
- "oklch(75% 0.110 38)",
- "oklch(86% 0.070 38)",
- "oklch(95% 0.035 38)"
- ]
- }
- },
- "typographyMeta": {
- "display": {
- "displayName": "Display",
- "purpose": "Hero headlines only. Fraunces, weight 400, optical-sized for large display."
- },
- "headline": {
- "displayName": "Headline",
- "purpose": "Section headlines (the features-head h2, cta-section h2)."
- },
- "title": {
- "displayName": "Title",
- "purpose": "Card headings inside the feature grid."
- },
- "lede": {
- "displayName": "Lede",
- "purpose": "The supporting paragraph that sits below a hero headline."
- },
- "body": {
- "displayName": "Body",
- "purpose": "Default paragraph copy. Cap line length at 65–75ch."
- },
- "label": {
- "displayName": "Label",
- "purpose": "The eyebrow chip and any small uppercase labels."
- }
- },
- "shadows": [],
- "motion": [
- {
- "name": "ease-button",
- "value": "ease",
- "duration": "150ms",
- "purpose": "Default easing for button hover transforms."
- },
- {
- "name": "ease-card",
- "value": "ease",
- "duration": "300ms",
- "purpose": "Card hover transition (currently unused but reserved)."
- }
- ],
- "breakpoints": [
- { "name": "container", "value": "1180px" },
- { "name": "logo-strip", "value": "1100px" }
- ]
- },
- "components": [
- {
- "name": "Primary Button",
- "kind": "button",
- "refersTo": "button-primary",
- "description": "The default CTA. Ink background, cream text, fully rounded.",
- "html": "<a href=\"#\" class=\"ds-btn-primary\">Start free trial</a>",
- "css": ".ds-btn-primary { display: inline-flex; align-items: center; gap: 8px; padding: 14px 28px; border-radius: 999px; background: #1f1a15; color: #faf6ef; font-family: 'Inter', system-ui, sans-serif; font-weight: 500; font-size: 15px; text-decoration: none; transition: transform 150ms ease; } .ds-btn-primary:hover { transform: translateY(-1px); }"
- },
- {
- "name": "Ghost Button",
- "kind": "button",
- "refersTo": "button-ghost",
- "description": "Secondary CTA, always paired with the primary.",
- "html": "<a href=\"#\" class=\"ds-btn-ghost\">Watch demo</a>",
- "css": ".ds-btn-ghost { display: inline-flex; align-items: center; gap: 8px; padding: 14px 28px; border-radius: 999px; background: transparent; color: #1f1a15; border: 1px solid #1f1a15; font-family: 'Inter', system-ui, sans-serif; font-weight: 500; font-size: 15px; text-decoration: none; transition: transform 150ms ease; } .ds-btn-ghost:hover { transform: translateY(-1px); }"
- },
- {
- "name": "Nav Pill",
- "kind": "button",
- "refersTo": "nav-pill",
- "description": "Compact primary CTA used in the nav. Smaller padding than the full button.",
- "html": "<a href=\"#\" class=\"ds-nav-pill\">Get started</a>",
- "css": ".ds-nav-pill { display: inline-flex; align-items: center; padding: 9px 18px; border-radius: 999px; background: #1f1a15; color: #faf6ef; font-family: 'Inter', system-ui, sans-serif; font-weight: 500; font-size: 14px; text-decoration: none; }"
- },
- {
- "name": "Eyebrow Chip",
- "kind": "chip",
- "description": "The small uppercase label sitting above the hero headline. Pure typography, no background.",
- "html": "<div class=\"ds-eyebrow\">AI-native workflows</div>",
- "css": ".ds-eyebrow { display: inline-block; font-family: 'Inter', system-ui, sans-serif; font-size: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.16em; color: #a8431f; }"
- },
- {
- "name": "Feature Card",
- "kind": "card",
- "refersTo": "card",
- "description": "Tonal-layered card on cream-warm with hairline border. Flat, no shadow.",
- "html": "<div class=\"ds-card\">\n <div class=\"ds-card-icon\">⚡</div>\n <h3 class=\"ds-card-title\">Lightning Fast</h3>\n <p class=\"ds-card-body\">Move from idea to production in minutes.</p>\n</div>",
- "css": ".ds-card { background: #f4ebdc; border: 1px solid #e6dccb; border-radius: 20px; padding: 40px 32px; text-align: center; max-width: 280px; } .ds-card-icon { width: 56px; height: 56px; border-radius: 14px; background: #faf6ef; border: 1px solid #e6dccb; display: inline-flex; align-items: center; justify-content: center; font-size: 28px; margin-bottom: 24px; } .ds-card-title { font-family: 'Fraunces', Georgia, serif; font-weight: 500; font-size: 22px; letter-spacing: -0.01em; margin: 0 0 12px; color: #1f1a15; } .ds-card-body { font-family: 'Inter', system-ui, sans-serif; font-size: 15px; color: #5b4f44; margin: 0; line-height: 1.55; }"
- },
- {
- "name": "Hero Headline",
- "kind": "custom",
- "description": "The display-scale headline with the One-Italic Rule applied: italic accent on a single word.",
- "html": "<h1 class=\"ds-hero-h1\">Build faster with <em>intelligent</em> workflows</h1>",
- "css": ".ds-hero-h1 { font-family: 'Fraunces', Georgia, serif; font-weight: 400; font-size: clamp(48px, 7vw, 88px); line-height: 1.05; letter-spacing: -0.02em; color: #1f1a15; max-width: 720px; margin: 0; } .ds-hero-h1 em { font-style: italic; color: #a8431f; }"
- },
- {
- "name": "Logo Strip Wordmark",
- "kind": "custom",
- "description": "The italic Fraunces wordmarks in the logo row — the exception to the One-Italic Rule.",
- "html": "<span class=\"ds-logo-mark\">Northwind</span>",
- "css": ".ds-logo-mark { font-family: 'Fraunces', Georgia, serif; font-style: italic; font-size: 22px; color: #5b4f44; }"
- }
- ],
- "narrative": {
- "northStar": "Editorial confidence in warm light.",
- "overview": "The system reads as a printed magazine spread, transposed to a screen. Cream paper as the page surface, ink-dark headlines in Fraunces, restrained pacing carried by whitespace. Density is mid. The accent (a burnt orange warming toward the lower stop of the cream-to-peach hero gradient) appears sparingly: on the eyebrow chip, the logo dot, and the italic emphasis inside the hero headline. Nowhere else.\n\nWhat the system explicitly rejects, per PRODUCT.md anti-references: glassmorphism, dark mode with neon glow, gradient text, side-stripe accents on cards, and the broader \"Fraunces-cream-peach SaaS template\" that this very page exemplifies. The DESIGN.md documents the current visual reality so the live-mode design panel can render it accurately. The brand intent is to diffuse away from it.",
- "keyCharacteristics": [
- "Warm-paper palette anchored on cream (#faf6ef)",
- "Display in Fraunces, body in Inter",
- "Editorial-leaning layout vocabulary",
- "Rounded throughout (14px, 20px, 999px)",
- "Flat: no shadows, depth via tonal layering"
- ],
- "rules": [
- {
- "name": "The Cream-Family Rule",
- "body": "Every neutral surface tints toward the brand hue. No pure white anywhere, no pure black, no untinted gray. The eye should never read this page as 'default browser.'",
- "section": "colors"
- },
- {
- "name": "The 10% Accent Rule",
- "body": "The burnt orange covers no more than 10% of any rendered surface. Its rarity is the point.",
- "section": "colors"
- },
- {
- "name": "The One-Italic Rule",
- "body": "Italic appears exactly once per page: on a single emphasized word inside the hero headline. Nowhere else. The logo strip's italic Fraunces wordmarks are the exception that proves it (wordmark, not running italic).",
- "section": "typography"
- },
- {
- "name": "The No-Gradient-Text Rule",
- "body": "Type is solid color, always. The hero's cream-to-peach gradient is a section background, never a typographic effect.",
- "section": "typography"
- },
- {
- "name": "The Flat-By-Default Rule",
- "body": "Surfaces are flat at rest. Hover lift uses transform: translateY(-1px), never a shadow. Glassmorphism, neon glow, and elevation halos are absent by design.",
- "section": "elevation"
- }
- ],
- "dos": [
- "Do keep the burnt-orange accent under 10% of any visible surface; it's a typographic accent and a logo dot, not a button.",
- "Do use Fraunces for display and Inter for body; respect the One-Italic Rule.",
- "Do carry depth via tonal layering and hairline borders, not shadows.",
- "Do tint every neutral toward the cream hue. Reject pure white and pure gray.",
- "Do keep buttons fully rounded (999px) and cards moderately rounded (20px); the contrast is intentional."
- ],
- "donts": [
- "Don't add box-shadows to surfaces. The system is flat by default; hover lift uses transform, not shadow.",
- "Don't introduce gradient text or background-clip: text. The hero gradient is a section background, never a typographic effect.",
- "Don't add glassmorphism, neon glow, dark mode by default, or side-stripe colored borders. All banned in PRODUCT.md anti-references.",
- "Don't introduce a fourth color outside the cream / ink / orange family without an explicit reason recorded in PRODUCT.md.",
- "Don't drift into the broader 'Fraunces-cream-peach SaaS template' the page already exemplifies. The PRODUCT.md anti-references this aesthetic; departure-mode variants should diffuse away from it."
- ]
- }
-}
@@ -1,207 +0,0 @@
----
-name: Lumina
-description: Editorial-warm landing page for an AI-native workflow tool.
-colors:
- cream: "#faf6ef"
- cream-warm: "#f4ebdc"
- peach: "#f6dfcb"
- line: "#e6dccb"
- ink: "#1f1a15"
- soft: "#5b4f44"
- accent: "#c8552b"
- accent-deep: "#a8431f"
-typography:
- display:
- fontFamily: "Fraunces, Georgia, serif"
- fontSize: "clamp(3rem, 7vw, 5.5rem)"
- fontWeight: 400
- lineHeight: 1.05
- letterSpacing: "-0.02em"
- headline:
- fontFamily: "Fraunces, Georgia, serif"
- fontSize: "clamp(2.25rem, 4.5vw, 3.25rem)"
- fontWeight: 400
- lineHeight: 1.1
- letterSpacing: "-0.02em"
- title:
- fontFamily: "Fraunces, Georgia, serif"
- fontSize: "1.375rem"
- fontWeight: 500
- lineHeight: 1.3
- letterSpacing: "-0.01em"
- body:
- fontFamily: "Inter, system-ui, sans-serif"
- fontSize: "1rem"
- fontWeight: 400
- lineHeight: 1.55
- letterSpacing: "normal"
- lede:
- fontFamily: "Inter, system-ui, sans-serif"
- fontSize: "1.25rem"
- fontWeight: 400
- lineHeight: 1.55
- letterSpacing: "normal"
- label:
- fontFamily: "Inter, system-ui, sans-serif"
- fontSize: "0.75rem"
- fontWeight: 600
- lineHeight: 1.4
- letterSpacing: "0.16em"
-rounded:
- card: "20px"
- icon: "14px"
- pill: "999px"
-spacing:
- xs: "8px"
- sm: "16px"
- md: "24px"
- lg: "32px"
- xl: "56px"
- 2xl: "80px"
- 3xl: "120px"
-components:
- button-primary:
- backgroundColor: "{colors.ink}"
- textColor: "{colors.cream}"
- rounded: "{rounded.pill}"
- padding: "14px 28px"
- button-ghost:
- backgroundColor: "transparent"
- textColor: "{colors.ink}"
- rounded: "{rounded.pill}"
- padding: "14px 28px"
- nav-pill:
- backgroundColor: "{colors.ink}"
- textColor: "{colors.cream}"
- rounded: "{rounded.pill}"
- padding: "9px 18px"
- card:
- backgroundColor: "{colors.cream-warm}"
- textColor: "{colors.soft}"
- rounded: "{rounded.card}"
- padding: "40px 32px"
- icon-tile:
- backgroundColor: "{colors.cream}"
- rounded: "{rounded.icon}"
- size: "56px"
----
-
-# Design System: Lumina
-
-## 1. Overview
-
-**Creative North Star: "Editorial confidence in warm light."**
-
-The system reads as a printed magazine spread, transposed to a screen. Cream paper as the page surface, ink-dark headlines in Fraunces, restrained pacing carried by whitespace. Density is mid. The accent (a burnt orange warming toward the lower stop of the cream-to-peach hero gradient) appears sparingly: on the eyebrow chip, the logo dot, and the italic emphasis inside the hero headline. Nowhere else.
-
-What the system explicitly rejects, per PRODUCT.md anti-references: glassmorphism, dark mode with neon glow, gradient text, side-stripe accents on cards, and the broader "Fraunces-cream-peach SaaS template" that this very page exemplifies. The DESIGN.md documents the current visual reality so the live-mode design panel can render it accurately. The brand intent is to diffuse away from it.
-
-**Key Characteristics:**
-- Warm-paper palette anchored on cream (#faf6ef)
-- Display in Fraunces, body in Inter
-- Editorial-leaning layout vocabulary
-- Rounded throughout (14px, 20px, 999px)
-- Flat: no shadows, depth via tonal layering
-
-## 2. Colors
-
-A single warm-cream family carrying both surface and neutral text, with one muted-orange accent that earns its rare appearances.
-
-### Primary
-- **Burnt Orange Accent** (#c8552b): the eyebrow chip's color, the logo dot, the italic emphasis inside the hero headline. Decorative; never a surface, never a button background.
-- **Accent Deep** (#a8431f): the darker variant for hover and emphasis states; same hue, a step deeper.
-
-### Neutral
-- **Cream** (#faf6ef): the page surface, the nav background (translucent), and the bottom of the hero gradient.
-- **Cream Warm** (#f4ebdc): the feature card surface; one shade darker than cream, anchors the card group as a contained set.
-- **Peach** (#f6dfcb): the warmer stop of the hero gradient. Atmospheric, not structural.
-- **Ink** (#1f1a15): primary body text; primary-button background; the dark CTA section's surface.
-- **Soft** (#5b4f44): secondary text; captions; footer copy; nav link rest state.
-- **Line** (#e6dccb): hairline borders on cards, the nav, the footer, and the icon tiles.
-
-### Named Rules
-**The Cream-Family Rule.** Every neutral surface tints toward the brand hue. No pure white anywhere, no pure black, no untinted gray. The eye should never read this page as "default browser."
-
-**The 10% Accent Rule.** The burnt orange covers no more than 10% of any rendered surface. Its rarity is the point.
-
-## 3. Typography
-
-**Display Font:** Fraunces (Georgia fallback, serif)
-**Body Font:** Inter (system-ui fallback, sans-serif)
-
-**Character:** A magazine-cover serif for the headlines and brand mark, paired with a refined sans for everything else. The italic Fraunces inside `<em>` is the system's only italic, used exactly once per page on a single word inside the hero headline.
-
-### Hierarchy
-- **Display** (Fraunces, clamp(48px, 7vw, 88px), weight 400, line-height 1.05, letter-spacing -0.02em): hero headlines only.
-- **Headline** (Fraunces, clamp(36px, 4.5vw, 52px), weight 400, line-height 1.1): section headlines.
-- **Title** (Fraunces, 22px, weight 500, letter-spacing -0.01em): card headings.
-- **Lede** (Inter, 20px, weight 400, line-height 1.55): the supporting paragraph below a hero headline.
-- **Body** (Inter, 15–18px, weight 400, line-height 1.55): default paragraph copy. Cap line length at 65–75ch.
-- **Label** (Inter, 12px, weight 600, letter-spacing 0.16em, uppercase): the eyebrow chip and any small uppercase labels.
-
-### Named Rules
-**The One-Italic Rule.** Italic appears exactly once per page: on a single emphasized word inside the hero headline. Nowhere else. The logo strip's italic Fraunces wordmarks are the exception that proves it (wordmark, not running italic).
-
-**The No-Gradient-Text Rule.** Type is solid color, always. The hero's cream-to-peach gradient is a section background, never a typographic effect.
-
-## 4. Elevation
-
-Flat. No shadows on cards, buttons, surfaces, or any rendered element. Depth is conveyed by three things and only those:
-
-- **Tonal layering**: cream (page) sits below cream-warm (cards), which sit below ink (the dark CTA section).
-- **Hairline borders**: 1px line color (`--line`) on every contained surface.
-- **Sticky-nav backdrop blur**: the only blur in the system, marking the nav as living above content.
-
-### Named Rules
-**The Flat-By-Default Rule.** Surfaces are flat at rest. Hover lift uses `transform: translateY(-1px)`, never a shadow. Glassmorphism, neon glow, and elevation halos are absent by design.
-
-## 5. Components
-
-### Buttons
-- **Shape:** fully rounded (border-radius: 999px). The full-size variant is 14px 28px padding; the smaller nav pill is 9px 18px.
-- **Primary** (`.btn-primary`, `.pill`): background ink, text cream. The primary CTA on every section.
-- **Ghost** (`.btn-ghost`): transparent background, ink 1px border, ink text. Secondary CTA, always paired with primary.
-- **Hover:** translateY(-1px), 150ms ease.
-- **Inverted Primary** (`.cta-section .btn-primary`): background cream, text ink. Used because the dark CTA section reverses the surface contrast.
-
-### Cards (Feature Tiles)
-- **Corner Style:** 20px rounded (less than pill, more than container).
-- **Background:** cream-warm (`--cream-warm`), one shade darker than the surrounding cream surface.
-- **Border:** 1px line color.
-- **Internal Padding:** 40px 32px (generous; cards breathe).
-- **Shadow:** none, see Elevation.
-
-### Icon Tile (inside Cards)
-- **Size:** 56×56px.
-- **Background:** cream (`--cream`).
-- **Border:** 1px line color.
-- **Corner Style:** 14px rounded.
-- **Position:** centered above the card heading, 24px bottom margin.
-
-### Eyebrow Chip
-- **Style:** uppercase Inter, 12px, weight 600, letter-spacing 0.16em, color accent-deep (#a8431f). No background or border — pure typographic label.
-- **Position:** standalone above the hero `<h1>`, with 32px bottom margin.
-
-### Navigation
-- **Background:** translucent cream (`rgba(250, 246, 239, 0.85)`) with `backdrop-filter: blur(10px)`. Sticky to the top.
-- **Border:** 1px line color at the bottom edge.
-- **Links:** 14px Inter, weight 400, color soft (rest), color ink (hover). The trailing pill CTA uses the nav-pill component.
-
-### Logo Strip
-- **Items:** Fraunces italic, 22px, color soft. Six wordmarks, justified across a single row, separated by hairline borders top and bottom.
-
-## 6. Do's and Don'ts
-
-### Do:
-- **Do** keep the burnt-orange accent under 10% of any visible surface; it's a typographic accent and a logo dot, not a button.
-- **Do** use Fraunces for display and Inter for body; respect the One-Italic Rule.
-- **Do** carry depth via tonal layering and hairline borders, not shadows.
-- **Do** tint every neutral toward the cream hue. Reject pure white and pure gray.
-- **Do** keep buttons fully rounded (999px) and cards moderately rounded (20px); the contrast is intentional.
-
-### Don't:
-- **Don't** add box-shadows to surfaces. The system is flat by default; hover lift uses transform, not shadow.
-- **Don't** introduce gradient text or `background-clip: text`. The hero gradient is a section background, never a typographic effect.
-- **Don't** add glassmorphism, neon glow, dark mode by default, or side-stripe colored borders — all banned in PRODUCT.md anti-references.
-- **Don't** introduce a fourth color outside the cream / ink / orange family without an explicit reason recorded in PRODUCT.md.
-- **Don't** drift into the broader "Fraunces-cream-peach SaaS template" the page already exemplifies. The PRODUCT.md anti-references this aesthetic; departure-mode variants should diffuse away from it.
@@ -1,39 +0,0 @@
-# Lumina
-
-## Register
-
-brand
-
-## Users
-
-Senior product builders at Series A through C software companies: founding engineers, design-leaning PMs, and tech-fluent founders. They evaluate tools fast, distrust marketing-speak, and have spent the last twelve months watching every SaaS landing page converge on the same warm-cream-and-Fraunces template. They will close the tab on anything that pattern-matches to "AI startup default" within two seconds.
-
-## Product Purpose
-
-Lumina is an AI-native workflow tool for product teams. The marketing site exists to make taste-aware buyers stop, read, and remember. Success is not "high conversion." Success is "shared in a group chat with the message: have you seen this yet."
-
-## Brand Personality
-
-Three-word personality: **specific, earned, unmistakable**. The voice is closer to a well-written engineering blog post than a pitch deck. Claims are concrete and verifiable. Adjectives are rationed. The brand has a point of view and trusts the reader's intelligence.
-
-## Anti-references
-
-Explicitly avoid the patterns that have become the new monoculture:
-
-- **The Fraunces-cream-peach SaaS template.** Warm cream backgrounds, large italic Fraunces headlines, soft burnt-orange accent, gentle peach gradients. This was novel in early 2025 and is now everywhere. The current `index.html` is itself an example. Diffuse away from it.
-- **Three-icon feature tile rows.** Icon-above-h3-above-paragraph, repeated three or four times across equal-width cards, generic single-word feature names ("Lightning Fast", "Enterprise Secure", "Built to Scale"). The flattest possible expression of "we have features."
-- **Hero superlatives.** "All-in-one platform", "in record time", "powered by AI, designed for humans", "trusted by 10,000+ teams worldwide". B2B SaaS mad-libs.
-- **Soft-everything aesthetic.** Rounded corners on every element, soft shadows on every surface, polite center-aligned spacing, no edges, no opinions.
-- **Decorative gradient text and glass-blur backdrops.** Both already banned by the shared design laws; restated here because they're still the first thing models reach for on brand surfaces.
-
-## Design Principles
-
-1. **Distinctiveness over polish.** Polish is table stakes; standing out from the SaaS-default sea is the job. If the page could plausibly be running on twenty other companies' domains, it has failed regardless of how clean it looks.
-2. **Specific over generic.** Real numbers, real product screenshots, real customer names, real claims with evidence. No abstract feature taxonomies.
-3. **Earned attention, not decorative attention.** Type weight, scale, and rhythm carry hierarchy. Animation, gradients, and effects are reserved for moments that genuinely warrant them.
-4. **Commitment over compromise.** Confidence shows up as restraint OR as full commitment, never as a hedged middle. A timid centered-stack with polite shadows is the failure mode this brand exists to avoid.
-5. **Confidence without volume.** The strongest brands speak quietly when quiet is the right register, and loudly when loud is. Insecurity is what splits the difference.
-
-## Accessibility & Inclusion
-
-WCAG 2.2 AA minimum across body text, headings, and interactive controls. Honor `prefers-reduced-motion` for any animation. Color is never the sole carrier of meaning. Tap targets ≥44px on mobile. Tested with screen readers; reading order matches visual order.
@@ -1,350 +0,0 @@
-<!doctype html>
-<html lang="en">
-<head>
-<meta charset="utf-8" />
-<meta name="viewport" content="width=device-width, initial-scale=1" />
-<title>Lumina — The future of intelligent workflows</title>
-<link rel="icon" href="data:," />
-<link rel="preconnect" href="https://fonts.googleapis.com" />
-<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
-<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet" />
-<style>
- :root {
- --bg: #0a0a14;
- --bg-elev: #14141f;
- --text: #ffffff;
- --text-muted: rgba(255, 255, 255, 0.6);
- --border: rgba(255, 255, 255, 0.08);
- --purple: #8b5cf6;
- --violet: #7c3aed;
- --pink: #ec4899;
- --cyan: #06b6d4;
- }
- * { box-sizing: border-box; }
- html, body { margin: 0; padding: 0; }
- body {
- font-family: 'Inter', system-ui, sans-serif;
- color: var(--text);
- background: var(--bg);
- -webkit-font-smoothing: antialiased;
- line-height: 1.6;
- overflow-x: hidden;
- }
-
- /* Nav */
- .nav {
- position: sticky; top: 0; z-index: 10;
- backdrop-filter: blur(24px);
- background: rgba(10, 10, 20, 0.6);
- border-bottom: 1px solid var(--border);
- }
- .nav-inner {
- max-width: 1180px; margin: 0 auto;
- padding: 18px 32px;
- display: flex; align-items: center; gap: 40px;
- }
- .logo {
- font-weight: 700; font-size: 22px;
- letter-spacing: -0.02em;
- background: linear-gradient(135deg, var(--purple), var(--pink));
- -webkit-background-clip: text;
- background-clip: text;
- color: transparent;
- }
- .nav-links { display: flex; gap: 28px; font-size: 14px; }
- .nav-links a { color: var(--text-muted); text-decoration: none; }
- .nav-cta { margin-left: auto; display: flex; gap: 16px; align-items: center; }
- .nav-cta a { font-size: 14px; color: var(--text-muted); text-decoration: none; }
- .pill {
- background: linear-gradient(135deg, var(--purple), var(--pink));
- color: #fff;
- padding: 9px 18px; border-radius: 999px;
- font-weight: 600; font-size: 14px;
- box-shadow: 0 0 32px rgba(139, 92, 246, 0.5);
- }
-
- /* Hero */
- .hero {
- padding: 140px 32px 160px;
- text-align: center;
- position: relative;
- overflow: hidden;
- }
- .hero::before {
- content: '';
- position: absolute;
- top: -200px; left: 50%;
- transform: translateX(-50%);
- width: 800px; height: 800px;
- background: radial-gradient(circle, rgba(139, 92, 246, 0.4) 0%, transparent 70%);
- filter: blur(80px);
- z-index: 0;
- }
- .hero::after {
- content: '';
- position: absolute;
- top: 100px; right: 5%;
- width: 400px; height: 400px;
- background: radial-gradient(circle, rgba(6, 182, 212, 0.3) 0%, transparent 70%);
- filter: blur(80px);
- z-index: 0;
- }
- .hero > * { position: relative; z-index: 1; }
- .eyebrow {
- display: inline-block;
- padding: 6px 14px;
- border-radius: 999px;
- background: rgba(139, 92, 246, 0.15);
- border: 1px solid rgba(139, 92, 246, 0.3);
- color: var(--purple);
- text-transform: uppercase;
- letter-spacing: 0.12em;
- font-size: 12px;
- font-weight: 600;
- margin-bottom: 32px;
- }
- .h1 {
- font-weight: 800;
- font-size: clamp(48px, 7vw, 88px);
- line-height: 1.05;
- letter-spacing: -0.03em;
- max-width: 920px;
- margin: 0 auto 28px;
- background: linear-gradient(135deg, #ffffff 0%, #c4b5fd 50%, var(--pink) 100%);
- -webkit-background-clip: text;
- background-clip: text;
- color: transparent;
- }
- .lede {
- font-size: 20px;
- color: var(--text-muted);
- max-width: 620px;
- margin: 0 auto 44px;
- }
- .ctas { display: flex; gap: 16px; justify-content: center; margin-bottom: 48px; }
- .btn {
- padding: 14px 32px;
- border-radius: 12px;
- font-weight: 600;
- font-size: 15px;
- text-decoration: none;
- display: inline-flex; align-items: center; gap: 8px;
- transition: all 0.2s ease;
- border: 0;
- }
- .btn-primary {
- background: linear-gradient(135deg, var(--purple), var(--pink));
- color: #fff;
- box-shadow: 0 0 40px rgba(139, 92, 246, 0.5), 0 4px 16px rgba(139, 92, 246, 0.3);
- }
- .btn-primary:hover {
- transform: translateY(-2px);
- box-shadow: 0 0 60px rgba(139, 92, 246, 0.7);
- }
- .btn-ghost {
- color: #fff;
- border: 1px solid var(--border);
- background: rgba(255, 255, 255, 0.04);
- backdrop-filter: blur(12px);
- }
- .trust { font-size: 13px; color: var(--text-muted); }
- .trust strong { color: #fff; font-weight: 600; }
-
- /* Logo strip */
- .logos {
- padding: 56px 32px;
- border-top: 1px solid var(--border);
- border-bottom: 1px solid var(--border);
- }
- .logos-inner {
- max-width: 1100px; margin: 0 auto;
- display: flex; justify-content: space-between; align-items: center;
- flex-wrap: wrap; gap: 32px;
- font-weight: 600; font-size: 18px; color: var(--text-muted);
- opacity: 0.6;
- }
-
- /* Features */
- .features {
- padding: 120px 32px;
- max-width: 1180px;
- margin: 0 auto;
- position: relative;
- }
- .features-head {
- text-align: center;
- max-width: 720px;
- margin: 0 auto 80px;
- }
- .features-head h2 {
- font-weight: 800;
- font-size: clamp(36px, 4.5vw, 52px);
- line-height: 1.1;
- letter-spacing: -0.03em;
- margin: 0 0 20px;
- background: linear-gradient(135deg, #fff, #c4b5fd);
- -webkit-background-clip: text;
- background-clip: text;
- color: transparent;
- }
- .features-head p { font-size: 18px; color: var(--text-muted); margin: 0; }
- .grid {
- display: grid;
- grid-template-columns: repeat(3, 1fr);
- gap: 24px;
- }
- .card {
- background: rgba(255, 255, 255, 0.03);
- backdrop-filter: blur(24px);
- border: 1px solid var(--border);
- border-radius: 24px;
- padding: 40px 32px;
- text-align: center;
- transition: all 0.3s ease;
- }
- .card:hover {
- border-color: rgba(139, 92, 246, 0.3);
- background: rgba(139, 92, 246, 0.04);
- transform: translateY(-4px);
- }
- .icon {
- width: 56px; height: 56px;
- border-radius: 16px;
- background: linear-gradient(135deg, var(--purple), var(--pink));
- display: inline-flex; align-items: center; justify-content: center;
- font-size: 28px;
- margin-bottom: 24px;
- box-shadow: 0 0 32px rgba(139, 92, 246, 0.4);
- }
- .card h3 {
- font-weight: 700;
- font-size: 22px;
- margin: 0 0 12px;
- letter-spacing: -0.02em;
- color: #fff;
- }
- .card p {
- font-size: 15px;
- color: var(--text-muted);
- margin: 0;
- }
-
- /* CTA */
- .cta-section {
- padding: 120px 32px;
- text-align: center;
- position: relative;
- overflow: hidden;
- }
- .cta-section::before {
- content: '';
- position: absolute;
- inset: 0;
- background: radial-gradient(ellipse at center, rgba(139, 92, 246, 0.2) 0%, transparent 70%);
- }
- .cta-section > * { position: relative; }
- .cta-section h2 {
- font-weight: 800;
- font-size: clamp(36px, 5vw, 60px);
- line-height: 1.1;
- letter-spacing: -0.03em;
- margin: 0 0 20px;
- max-width: 720px;
- margin-left: auto; margin-right: auto;
- background: linear-gradient(135deg, #fff, #c4b5fd, var(--pink));
- -webkit-background-clip: text;
- background-clip: text;
- color: transparent;
- }
- .cta-section p {
- font-size: 18px;
- color: var(--text-muted);
- margin: 0 auto 40px;
- max-width: 540px;
- }
-
- /* Footer */
- .footer {
- padding: 40px 32px;
- text-align: center;
- font-size: 13px;
- color: var(--text-muted);
- border-top: 1px solid var(--border);
- }
-</style>
-</head>
-<body>
- <nav class="nav">
- <div class="nav-inner">
- <div class="logo">Lumina ✨</div>
- <div class="nav-links">
- <a href="#">Product</a>
- <a href="#">Solutions</a>
- <a href="#">Pricing</a>
- <a href="#">Customers</a>
- <a href="#">Docs</a>
- </div>
- <div class="nav-cta">
- <a href="#">Sign in</a>
- <a href="#" class="pill">Get started →</a>
- </div>
- </div>
- </nav>
-
- <section class="hero">
- <div class="eyebrow">🚀 Powered by AI</div>
- <h1 class="h1">Build faster with intelligent workflows</h1>
- <p class="lede">The all-in-one platform that helps modern teams ship better products in record time. Powered by AI, designed for humans.</p>
- <div class="ctas">
- <a href="#" class="btn btn-primary">Join the waitlist →</a>
- <a href="#" class="btn btn-ghost">Watch demo</a>
- </div>
- <div class="trust">Backed by <strong>top-tier investors</strong></div>
- </section>
-
- <section class="logos">
- <div class="logos-inner">
- <span>Northwind</span>
- <span>Halcyon</span>
- <span>Meridian</span>
- <span>Fieldnote</span>
- <span>Atlas & Co.</span>
- <span>Verity</span>
- </div>
- </section>
-
- <section class="features">
- <div class="features-head">
- <h2>Everything you need to ship faster</h2>
- <p>One platform. Endless possibilities. Built for the future.</p>
- </div>
- <div class="grid">
- <div class="card">
- <div class="icon">⚡</div>
- <h3>Lightning Fast</h3>
- <p>Move from idea to production in minutes, not months. Our AI handles the heavy lifting so you can focus on what matters.</p>
- </div>
- <div class="card">
- <div class="icon">🔒</div>
- <h3>Enterprise Secure</h3>
- <p>SOC 2 compliant infrastructure with end-to-end encryption. Your data is safe, always.</p>
- </div>
- <div class="card">
- <div class="icon">📈</div>
- <h3>Built to Scale</h3>
- <p>From your first prototype to millions of users, Lumina grows with your team without breaking a sweat.</p>
- </div>
- </div>
- </section>
-
- <section class="cta-section">
- <h2>Ready to transform how your team builds?</h2>
- <p>Join thousands of teams already shipping faster with Lumina.</p>
- <a href="#" class="btn btn-primary">Get early access →</a>
- </section>
-
- <footer class="footer">
- © 2022 Lumina, Inc. Powered by AI in San Francisco.
- </footer>
-</body>
-</html>
@@ -1,309 +0,0 @@
-<!doctype html>
-<html lang="en">
-<head>
-<meta charset="utf-8" />
-<meta name="viewport" content="width=device-width, initial-scale=1" />
-<title>Lumina — Intelligent workflows for modern product teams</title>
-<link rel="icon" href="data:," />
-<link rel="preconnect" href="https://fonts.googleapis.com" />
-<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
-<link href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,300;9..144,400;9..144,500;9..144,600;9..144,700&family=Inter:wght@400;500;600&display=swap" rel="stylesheet" />
-<style>
- :root {
- --cream: #faf6ef;
- --cream-warm: #f4ebdc;
- --peach: #f6dfcb;
- --ink: #1f1a15;
- --soft: #5b4f44;
- --line: #e6dccb;
- --accent: #c8552b;
- --accent-deep: #a8431f;
- }
- * { box-sizing: border-box; }
- html, body { margin: 0; padding: 0; }
- body {
- font-family: 'Inter', system-ui, sans-serif;
- color: var(--ink);
- background: var(--cream);
- -webkit-font-smoothing: antialiased;
- line-height: 1.55;
- }
- .serif { font-family: 'Fraunces', Georgia, serif; font-optical-sizing: auto; }
-
- /* Nav */
- .nav {
- position: sticky; top: 0; z-index: 10;
- backdrop-filter: blur(10px);
- background: rgba(250, 246, 239, 0.85);
- border-bottom: 1px solid var(--line);
- }
- .nav-inner {
- max-width: 1180px; margin: 0 auto;
- padding: 18px 32px;
- display: flex; align-items: center; gap: 40px;
- }
- .logo {
- font-family: 'Fraunces', Georgia, serif;
- font-weight: 600; font-size: 22px;
- letter-spacing: -0.01em;
- }
- .logo-dot {
- display: inline-block; width: 8px; height: 8px;
- background: var(--accent); border-radius: 50%;
- margin-right: 8px; vertical-align: middle;
- }
- .nav-links { display: flex; gap: 28px; font-size: 14px; }
- .nav-links a { color: var(--soft); text-decoration: none; }
- .nav-cta { margin-left: auto; display: flex; gap: 16px; align-items: center; }
- .nav-cta a:not(.pill) { font-size: 14px; color: var(--soft); text-decoration: none; }
- .pill {
- background: var(--ink); color: var(--cream);
- padding: 9px 18px; border-radius: 999px;
- font-weight: 500; font-size: 14px;
- }
-
- /* Hero */
- .hero {
- background: linear-gradient(180deg, var(--cream) 0%, var(--peach) 100%);
- padding: 120px 32px 140px;
- text-align: center;
- position: relative;
- overflow: hidden;
- }
- .eyebrow {
- text-transform: uppercase;
- letter-spacing: 0.16em;
- font-size: 12px;
- font-weight: 600;
- color: var(--accent-deep);
- margin-bottom: 32px;
- }
- .h1 {
- font-family: 'Fraunces', Georgia, serif;
- font-weight: 400;
- font-size: clamp(48px, 7vw, 88px);
- line-height: 1.05;
- letter-spacing: -0.02em;
- max-width: 920px;
- margin: 0 auto 28px;
- }
- .h1 em { font-style: italic; color: var(--accent-deep); }
- .lede {
- font-size: 20px;
- color: var(--soft);
- max-width: 620px;
- margin: 0 auto 44px;
- }
- .ctas { display: flex; gap: 16px; justify-content: center; margin-bottom: 48px; }
- .btn {
- padding: 14px 28px;
- border-radius: 999px;
- font-weight: 500;
- font-size: 15px;
- text-decoration: none;
- display: inline-flex; align-items: center; gap: 8px;
- transition: transform 0.15s ease;
- }
- .btn-primary { background: var(--ink); color: var(--cream); }
- .btn-ghost { color: var(--ink); border: 1px solid var(--ink); }
- .btn:hover { transform: translateY(-1px); }
- .trust { font-size: 13px; color: var(--soft); }
- .trust strong { color: var(--ink); font-weight: 600; }
-
- /* Logo strip */
- .logos {
- padding: 56px 32px;
- border-top: 1px solid var(--line);
- border-bottom: 1px solid var(--line);
- background: var(--cream);
- }
- .logos-inner {
- max-width: 1100px; margin: 0 auto;
- display: flex; justify-content: space-between; align-items: center;
- flex-wrap: wrap; gap: 32px;
- font-family: 'Fraunces', Georgia, serif;
- font-style: italic; font-size: 22px; color: var(--soft);
- }
-
- /* Features */
- .features {
- padding: 120px 32px;
- max-width: 1180px;
- margin: 0 auto;
- }
- .features-head {
- text-align: center;
- max-width: 720px;
- margin: 0 auto 80px;
- }
- .features-head h2 {
- font-family: 'Fraunces', Georgia, serif;
- font-weight: 400;
- font-size: clamp(36px, 4.5vw, 52px);
- line-height: 1.1;
- letter-spacing: -0.02em;
- margin: 0 0 20px;
- }
- .features-head p { font-size: 18px; color: var(--soft); margin: 0; }
- .grid {
- display: grid;
- grid-template-columns: repeat(3, 1fr);
- gap: 32px;
- }
- .card {
- background: var(--cream-warm);
- border: 1px solid var(--line);
- border-radius: 20px;
- padding: 40px 32px;
- text-align: center;
- }
- .icon {
- width: 56px; height: 56px;
- border-radius: 14px;
- background: var(--cream);
- border: 1px solid var(--line);
- display: inline-flex; align-items: center; justify-content: center;
- font-size: 28px;
- margin-bottom: 24px;
- }
- .card h3 {
- font-family: 'Fraunces', Georgia, serif;
- font-weight: 500;
- font-size: 22px;
- margin: 0 0 12px;
- letter-spacing: -0.01em;
- }
- .card p {
- font-size: 15px;
- color: var(--soft);
- margin: 0;
- }
-
- /* CTA */
- .cta-section {
- background: var(--ink);
- color: var(--cream);
- padding: 120px 32px;
- text-align: center;
- }
- .cta-section h2 {
- font-family: 'Fraunces', Georgia, serif;
- font-weight: 400;
- font-size: clamp(36px, 5vw, 60px);
- line-height: 1.1;
- letter-spacing: -0.02em;
- margin: 0 0 20px;
- max-width: 720px;
- margin-left: auto; margin-right: auto;
- }
- .cta-section p {
- font-size: 18px;
- color: rgba(250, 246, 239, 0.7);
- margin: 0 auto 40px;
- max-width: 540px;
- }
- .cta-section .btn-primary {
- background: var(--cream);
- color: var(--ink);
- }
-
- /* Footer */
- .footer {
- padding: 40px 32px;
- text-align: center;
- font-size: 13px;
- color: var(--soft);
- border-top: 1px solid var(--line);
- background: var(--cream);
- }
-</style>
-</head>
-<body>
-
-<nav class="nav">
- <div class="nav-inner">
- <div class="logo"><span class="logo-dot"></span>Lumina</div>
- <div class="nav-links">
- <a href="#">Product</a>
- <a href="#">Solutions</a>
- <a href="#">Pricing</a>
- <a href="#">Customers</a>
- <a href="#">Docs</a>
- </div>
- <div class="nav-cta">
- <a href="#">Sign in</a>
- <a href="#" class="pill">Get started</a>
- </div>
- </div>
-</nav>
-
-
-
-
-
-<section class="hero">
- <div class="eyebrow">AI-native workflows</div>
- <h1 class="h1">Build faster with <em>intelligent</em> workflows for modern teams</h1>
- <p class="lede">The all-in-one platform that helps product teams ship better software in record time. Powered by AI, designed for humans.</p>
- <div class="ctas">
- <a href="#" class="btn btn-primary">Start free trial →</a>
- <a href="#" class="btn btn-ghost">Watch demo</a>
- </div>
- <div class="trust">Trusted by <strong>10,000+</strong> forward-thinking teams worldwide</div>
-</section>
-
-
-
-
-
-<section class="logos">
- <div class="logos-inner">
- <span>Northwind</span>
- <span>Halcyon</span>
- <span>Meridian</span>
- <span>Fieldnote</span>
- <span>Atlas & Co.</span>
- <span>Verity</span>
- </div>
-</section>
-
-<section class="features">
- <div class="features-head">
- <h2>Everything you need to ship great products</h2>
- <p>One platform. Endless possibilities. Built for teams who care about craft.</p>
- </div>
-
- <div class="grid">
- <div class="card">
- <div class="icon">⚡</div>
- <h3>Lightning Fast</h3>
- <p>Move from idea to production in minutes, not months. Our AI handles the heavy lifting so you can focus on what matters.</p>
- </div>
- <div class="card">
- <div class="icon">🔒</div>
- <h3>Enterprise Secure</h3>
- <p>SOC 2 compliant infrastructure with end-to-end encryption. Your data is safe, always.</p>
- </div>
- <div class="card">
- <div class="icon">📈</div>
- <h3>Built to Scale</h3>
- <p>From your first prototype to millions of users — Lumina grows with your team without breaking a sweat.</p>
- </div>
- </div>
-
-</section>
-
-
-<section class="cta-section">
- <h2>Ready to transform how your team builds?</h2>
- <p>Join thousands of teams already shipping faster with Lumina.</p>
- <a href="#" class="btn btn-primary">Start your free trial →</a>
-</section>
-
-
-<footer class="footer">
- © 2026 Lumina, Inc. — Crafted with care in San Francisco.
-</footer>
-
-</body>
-</html>
@@ -1,14 +0,0 @@
-{
- "name": "landing-demo",
- "private": true,
- "version": "0.0.0",
- "type": "module",
- "scripts": {
- "dev": "vite",
- "build": "vite build",
- "preview": "vite preview"
- },
- "devDependencies": {
- "vite": "^8.0.0"
- }
-}
@@ -1,63 +0,0 @@
-# Chrome Web Store Listing
-
-## Name
-Impeccable
-
-## Short description (132 chars max)
-Detect AI slop and design anti-patterns in any web page. Open DevTools and see what needs fixing.
-
-## Detailed description
-
-Impeccable detects 24 common UI anti-patterns directly in your browser. Open DevTools on any page and overlays instantly highlight issues, from AI-generated design tells to accessibility and quality problems.
-
-WHAT IT DETECTS
-
-AI slop (design tells that scream "AI made this"):
-- Side-tab accent borders
-- Gradient text on headings
-- Purple/violet AI color palettes
-- Nested cards, monotonous spacing
-- Bounce/elastic easing
-- Dark mode with glowing accents
-- Overused fonts, flat type hierarchy
-
-Quality issues (general design and accessibility):
-- Low contrast text (WCAG AA)
-- Cramped padding, tight line height
-- Skipped heading levels
-- Line length too long
-- Tiny body text, justified text
-- Layout property animations
-
-HOW IT WORKS
-
-1. Install the extension
-2. Open DevTools on any page (Cmd+Opt+I / F12)
-3. Overlays appear automatically, highlighting issues
-4. Click the "Impeccable" panel tab for a structured list of all findings
-5. Click any finding to jump to the element in the Elements panel
-
-FEATURES
-
-- Auto-scans when DevTools opens, no manual step needed
-- Grouped findings: AI tells vs. quality issues
-- Click-to-inspect: jump from a finding to the element
-- Toggle overlays on/off from the panel or toolbar popup
-- Per-rule settings: disable detections you don't care about
-- Re-scans on navigation, including SPA route changes
-- Works on any website
-- Runs 100% locally, no data sent anywhere
-
-Open source at https://github.com/pbakaus/impeccable
-
-## Category
-Developer Tools
-
-## Language
-English
-
-## Privacy policy URL
-https://impeccable.style/privacy
-
-## Single purpose description
-Detects and highlights UI anti-patterns (AI-generated design tells and general quality issues) on any web page.
@@ -1,272 +0,0 @@
-/**
- * Impeccable DevTools Extension - Service Worker
- *
- * Routes messages between popup, DevTools panel, and content scripts.
- * Maintains per-tab state and updates the badge.
- */
-
-// Per-tab state: { tabId: { findings, overlaysVisible, injected } }
-const tabState = new Map();
-
-// Active DevTools panel connections: { tabId: Set<port> }
-const panelPorts = new Map();
-
-function getState(tabId) {
- if (!tabState.has(tabId)) {
- tabState.set(tabId, { findings: [], overlaysVisible: true, injected: false, csInjected: false });
- }
- return tabState.get(tabId);
-}
-
-function updateBadge(tabId) {
- const state = tabState.get(tabId);
- const count = state?.findings?.length || 0;
- const text = count > 0 ? String(count) : '';
- chrome.action.setBadgeText({ text, tabId }).catch(() => {});
- chrome.action.setBadgeBackgroundColor({ color: '#d6336c', tabId }).catch(() => {});
-}
-
-function notifyPanels(tabId, message) {
- const ports = panelPorts.get(tabId);
- if (ports) {
- for (const port of ports) {
- try { port.postMessage(message); } catch { /* port disconnected */ }
- }
- }
-}
-
-async function getSettings() {
- return chrome.storage.sync.get({
- disabledRules: [],
- lineLengthMode: 'strict', // 'strict' = 80, 'lax' = 120
- spotlightBlur: true, // dim/blur the page on hover-highlight
- autoScan: 'panel', // 'panel' = scan when Impeccable UI opens, 'devtools' = scan when DevTools opens
- });
-}
-
-async function buildScanConfig() {
- const { disabledRules, lineLengthMode, spotlightBlur } = await getSettings();
- const config = {};
- if (disabledRules.length) config.disabledRules = disabledRules;
- config.lineLengthMax = lineLengthMode === 'lax' ? 120 : 80;
- config.spotlightBlur = spotlightBlur;
- return config;
-}
-
-// Inject the content script on-demand. We removed the static content_scripts entry to
-// minimize the always-on footprint; the script is only loaded when the user explicitly
-// engages with the extension (DevTools panel/sidebar opened, popup scan, etc).
-async function ensureContentScriptInjected(tabId) {
- const state = getState(tabId);
- if (state.csInjected) return true;
- try {
- await chrome.scripting.executeScript({
- target: { tabId },
- files: ['content/content-script.js'],
- injectImmediately: true,
- });
- state.csInjected = true;
- return true;
- } catch (err) {
- // Common cause: chrome:// pages, the web store, or other restricted URLs
- return false;
- }
-}
-
-async function sendScanToTab(tabId) {
- const ok = await ensureContentScriptInjected(tabId);
- if (!ok) return;
- const config = await buildScanConfig();
- chrome.tabs.sendMessage(tabId, { action: 'scan', config }).catch(() => {});
-}
-
-// Handle messages from content scripts and popup
-chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
- const tabId = msg.tabId || sender.tab?.id;
-
- if (msg.action === 'findings' && tabId) {
- const state = getState(tabId);
- state.findings = msg.findings || [];
- state.injected = true;
- updateBadge(tabId);
- notifyPanels(tabId, { action: 'findings', findings: state.findings });
- // Broadcast for popup
- chrome.runtime.sendMessage({ action: 'findings-updated', tabId, findings: state.findings }).catch(() => {});
- sendResponse({ ok: true });
- }
-
- else if (msg.action === 'scan' && tabId) {
- sendScanToTab(tabId);
- sendResponse({ ok: true });
- }
-
- else if (msg.action === 'toggle-overlays' && tabId) {
- chrome.tabs.sendMessage(tabId, { action: 'toggle-overlays' }).catch(() => {});
- sendResponse({ ok: true });
- }
-
- else if (msg.action === 'page-pointer-active' && tabId) {
- notifyPanels(tabId, { action: 'page-pointer-active' });
- sendResponse({ ok: true });
- }
-
- else if (msg.action === 'overlays-toggled' && tabId) {
- const state = getState(tabId);
- state.overlaysVisible = msg.visible;
- notifyPanels(tabId, { action: 'overlays-toggled', visible: msg.visible });
- chrome.runtime.sendMessage({ action: 'overlays-toggled-broadcast', tabId, visible: msg.visible }).catch(() => {});
- sendResponse({ ok: true });
- }
-
- else if (msg.action === 'get-state' && tabId) {
- sendResponse(getState(tabId));
- }
-
- else if (msg.action === 'inject-fallback' && tabId) {
- // CSP fallback: inject detector via chrome.scripting (bypasses page CSP)
- chrome.scripting.executeScript({
- target: { tabId },
- world: 'MAIN',
- files: ['detector/detect.js'],
- }).then(() => {
- // Detector will post impeccable-ready, content script handles the rest
- }).catch((err) => {
- console.warn('[impeccable] Fallback injection failed:', err);
- });
- sendResponse({ ok: true });
- }
-
- else if (msg.action === 'disabled-rules-changed') {
- // Re-scan all tabs that have been injected
- for (const [tid, state] of tabState) {
- if (state.injected) sendScanToTab(tid);
- }
- sendResponse({ ok: true });
- }
-
- return true;
-});
-
-// Track which tabs have DevTools open (via the devtools.js lifecycle port)
-const devtoolsTabs = new Set();
-
-async function tearDownTab(tabId) {
- devtoolsTabs.delete(tabId);
- // Send the remove command and await it — this keeps the SW alive long enough
- // to actually deliver the message (setTimeout doesn't survive SW termination in MV3).
- try {
- await chrome.tabs.sendMessage(tabId, { action: 'remove' });
- } catch { /* tab might be closed or content script gone */ }
- const state = tabState.get(tabId);
- if (state) {
- state.findings = [];
- state.injected = false;
- state.csInjected = false;
- }
- updateBadge(tabId);
- panelPorts.delete(tabId);
-}
-
-// Handle long-lived connections from DevTools pages and panels
-chrome.runtime.onConnect.addListener((port) => {
- // Lifecycle port from devtools.js -- tracks DevTools open/close
- if (port.name.startsWith('impeccable-devtools-')) {
- const tabId = parseInt(port.name.replace('impeccable-devtools-', ''), 10);
- devtoolsTabs.add(tabId);
-
- port.onMessage.addListener((msg) => {
- if (msg.action === 'scan') sendScanToTab(tabId);
- // 'ping' is just a keepalive; no action needed
- });
-
- port.onDisconnect.addListener(() => {
- // Tear down immediately — defer with setTimeout doesn't work reliably in MV3
- // because the SW can be terminated before the timer fires.
- tearDownTab(tabId);
- });
- }
-
- // Panel port from panel.js -- for forwarding findings/state
- if (port.name.startsWith('impeccable-panel-')) {
- const tabId = parseInt(port.name.replace('impeccable-panel-', ''), 10);
- if (!panelPorts.has(tabId)) panelPorts.set(tabId, new Set());
- panelPorts.get(tabId).add(port);
-
- // Send current state to newly connected panel
- const state = getState(tabId);
- port.postMessage({ action: 'state', ...state });
-
- // If no findings yet, the auto-scan from devtools.js may have been lost -- trigger one
- if (!state.findings.length) {
- sendScanToTab(tabId);
- }
-
- port.onMessage.addListener((msg) => {
- if (msg.action === 'scan') {
- sendScanToTab(tabId);
- } else if (msg.action === 'toggle-overlays') {
- chrome.tabs.sendMessage(tabId, { action: 'toggle-overlays' }).catch(() => {});
- } else if (msg.action === 'highlight') {
- chrome.tabs.sendMessage(tabId, { action: 'highlight', selector: msg.selector }).catch(() => {});
- } else if (msg.action === 'unhighlight') {
- chrome.tabs.sendMessage(tabId, { action: 'unhighlight' }).catch(() => {});
- }
- });
-
- port.onDisconnect.addListener(() => {
- panelPorts.get(tabId)?.delete(port);
- if (panelPorts.get(tabId)?.size === 0) panelPorts.delete(tabId);
- });
- }
-
- // Sidebar pane port (Elements panel sidebar) -- receives findings updates.
- // Connecting the sidebar is a strong signal of "user engaged with Impeccable"
- // so we trigger a scan if no findings exist yet (matches the panel port behavior).
- if (port.name.startsWith('impeccable-sidebar-')) {
- const tabId = parseInt(port.name.replace('impeccable-sidebar-', ''), 10);
- if (!panelPorts.has(tabId)) panelPorts.set(tabId, new Set());
- panelPorts.get(tabId).add(port);
-
- const state = getState(tabId);
- port.postMessage({ action: 'state', ...state });
- if (!state.findings.length) sendScanToTab(tabId);
-
- port.onDisconnect.addListener(() => {
- panelPorts.get(tabId)?.delete(port);
- if (panelPorts.get(tabId)?.size === 0) panelPorts.delete(tabId);
- });
- }
-});
-
-// On navigation, reset content-script state for any tracked tab (page reload destroys
-// the content script regardless of which UI surfaced it). Auto-rescan is gated separately
-// on DevTools being open AND the user having previously engaged.
-chrome.webNavigation?.onCompleted?.addListener((details) => {
- if (details.frameId !== 0) return;
- const state = tabState.get(details.tabId);
- if (!state) return;
-
- // Capture engagement state BEFORE clearing (used by the auto-rescan branch).
- const wasActive = state.injected || state.findings.length > 0;
-
- // Always clear: the content script is gone after reload, full stop. Skipping this when
- // DevTools wasn't open meant the popup-only flow saw a stale csInjected: true on the
- // second click and silently no-op'd against a tab that had no listener.
- state.findings = [];
- state.injected = false;
- state.csInjected = false;
- updateBadge(details.tabId);
- notifyPanels(details.tabId, { action: 'navigated' });
-
- // Auto-rescan only when DevTools is the driver — the popup is user-triggered and
- // shouldn't fire scans the user didn't ask for.
- if (devtoolsTabs.has(details.tabId) && wasActive) {
- setTimeout(() => sendScanToTab(details.tabId), 300);
- }
-});
-
-// Clean up state when tabs close
-chrome.tabs.onRemoved.addListener((tabId) => {
- tabState.delete(tabId);
- panelPorts.delete(tabId);
-});
@@ -1,125 +0,0 @@
-/**
- * Impeccable DevTools Extension - Content Script
- *
- * Bridges between the extension messaging system and the page-context detector.
- * The detector must run in page context (not isolated world) because it needs
- * access to getComputedStyle, document.styleSheets.cssRules, etc.
- *
- * Wrapped in an IIFE with an idempotency flag so re-injection (via
- * chrome.scripting.executeScript) is a no-op and doesn't cause:
- * - SyntaxError: Identifier 'foo' has already been declared
- * - Duplicate event listeners accumulating over time
- */
-(function () {
- if (window.__IMPECCABLE_CS_LOADED__) return;
- window.__IMPECCABLE_CS_LOADED__ = true;
-
- let injected = false;
- let pendingScan = false;
- let scanConfig = null;
-
- // Listen for commands from the service worker
- chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
- if (msg.action === 'scan') {
- scanConfig = msg.config || null;
- injectAndScan();
- sendResponse({ ok: true });
- } else if (msg.action === 'toggle-overlays') {
- window.postMessage({ source: 'impeccable-command', action: 'toggle-overlays' }, '*');
- sendResponse({ ok: true });
- } else if (msg.action === 'remove') {
- window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
- injected = false;
- sendResponse({ ok: true });
- } else if (msg.action === 'highlight') {
- window.postMessage({ source: 'impeccable-command', action: 'highlight', selector: msg.selector }, '*');
- sendResponse({ ok: true });
- } else if (msg.action === 'unhighlight') {
- window.postMessage({ source: 'impeccable-command', action: 'unhighlight' }, '*');
- sendResponse({ ok: true });
- }
- return true;
- });
-
- // Listen for results and state changes from the detector in page context
- window.addEventListener('message', (e) => {
- if (e.source !== window || !e.data) return;
-
- if (e.data.source === 'impeccable-results') {
- chrome.runtime.sendMessage({
- action: 'findings',
- findings: e.data.findings,
- count: e.data.count,
- }).catch(() => {});
- }
-
- if (e.data.source === 'impeccable-overlays-toggled') {
- chrome.runtime.sendMessage({
- action: 'overlays-toggled',
- visible: e.data.visible,
- }).catch(() => {});
- }
-
- if (e.data.source === 'impeccable-ready') {
- injected = true;
- if (pendingScan) {
- pendingScan = false;
- sendScanCommand();
- }
- }
- });
-
- // Forward "page is active" signal to the extension when the cursor moves over the page.
- // This is the reliable way to know the user has left the DevTools panel — the panel's
- // own pointerleave/mouseleave events are unreliable on fast cursor movement.
- let lastPageActive = 0;
- document.addEventListener('pointermove', () => {
- const now = Date.now();
- if (now - lastPageActive < 150) return; // throttle
- lastPageActive = now;
- chrome.runtime.sendMessage({ action: 'page-pointer-active' }).catch(() => {});
- }, { passive: true, capture: true });
-
- // SPA navigation detection (pushState/replaceState don't fire events, but
- // popstate and hashchange cover back/forward and hash navigation)
- let lastUrl = location.href;
- function onPossibleNavigation() {
- if (location.href === lastUrl) return;
- lastUrl = location.href;
- if (injected) {
- // Detector is still loaded in page context, just re-scan after DOM settles
- setTimeout(sendScanCommand, 500);
- }
- }
- window.addEventListener('popstate', onPossibleNavigation);
- window.addEventListener('hashchange', onPossibleNavigation);
-
- function sendScanCommand() {
- const msg = { source: 'impeccable-command', action: 'scan' };
- if (scanConfig) msg.config = scanConfig;
- window.postMessage(msg, '*');
- }
-
- function injectAndScan() {
- if (injected) {
- sendScanCommand();
- return;
- }
-
- // Set the extension flag via a data attribute (CSP-safe: content scripts share the DOM)
- document.documentElement.dataset.impeccableExtension = 'true';
-
- // Inject the detector script into page context
- const script = document.createElement('script');
- script.src = chrome.runtime.getURL('detector/detect.js');
- script.dataset.impeccableExtension = 'true';
- pendingScan = true;
- script.onload = () => script.remove();
- script.onerror = () => {
- script.remove();
- // Fallback: use chrome.scripting.executeScript for strict CSP pages
- chrome.runtime.sendMessage({ action: 'inject-fallback' });
- };
- (document.head || document.documentElement).appendChild(script);
- }
-})();
@@ -1,5 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head><meta charset="utf-8"></head>
-<body><script src="devtools.js"></script></body>
-</html>
@@ -1,50 +0,0 @@
-/**
- * Impeccable DevTools Extension - DevTools Page
- *
- * Creates the Impeccable panel and triggers an auto-scan when DevTools opens.
- * This page lives for the entire DevTools session -- its port disconnect
- * is the canonical signal that DevTools has closed.
- */
-
-chrome.devtools.panels.create(
- 'Impeccable',
- 'icons/icon-32.png',
- 'devtools/panel.html'
-);
-
-// Sidebar pane in the Elements panel: shows findings for the currently selected element
-chrome.devtools.panels.elements.createSidebarPane('Impeccable', (sidebar) => {
- sidebar.setPage('devtools/sidebar.html');
- sidebar.setHeight('200px');
-});
-
-// Lifecycle port to the service worker. Auto-reconnects if the SW gets terminated
-// (which can happen in MV3 after ~30s of inactivity, especially when the browser is unfocused).
-const portName = `impeccable-devtools-${chrome.devtools.inspectedWindow.tabId}`;
-let lifecyclePort = null;
-let firstConnect = true;
-function connectLifecycle() {
- lifecyclePort = chrome.runtime.connect({ name: portName });
- // On the very first connection, decide whether to auto-scan based on the user's setting.
- // Default ('panel'): wait until the user opens the Impeccable panel or sidebar.
- // Opt-in ('devtools'): scan immediately when DevTools opens.
- if (firstConnect) {
- firstConnect = false;
- chrome.storage.sync.get({ autoScan: 'panel' }, (settings) => {
- if (settings.autoScan === 'devtools') {
- try { lifecyclePort?.postMessage({ action: 'scan' }); } catch {}
- }
- });
- }
- lifecyclePort.onDisconnect.addListener(() => {
- lifecyclePort = null;
- // Reconnect on the next tick so the SW sees a fresh connection
- setTimeout(connectLifecycle, 100);
- });
-}
-connectLifecycle();
-
-// Heartbeat to keep the SW alive
-setInterval(() => {
- try { lifecyclePort?.postMessage({ action: 'ping' }); } catch {}
-}, 20000);
@@ -1,520 +0,0 @@
-* {
- margin: 0;
- padding: 0;
- box-sizing: border-box;
-}
-
-/* Light theme (default DevTools) */
-:root {
- --bg: #fff;
- --bg-subtle: #f5f5f5;
- --bg-hover: #eee;
- --text: #1a1a1a;
- --text-dim: #666;
- --accent: oklch(48% 0.25 350);
- --accent-dim: oklch(40% 0.18 350);
- --border: #ddd;
- --radius: 6px;
-}
-
-/* Dark theme (set via JS from chrome.devtools.panels.themeName) */
-.theme-dark {
- --bg: #1a1a1a;
- --bg-subtle: #242424;
- --bg-hover: #2a2a2a;
- --text: #f5f3ef;
- --text-dim: #999;
- --accent: oklch(55% 0.25 350);
- --accent-dim: oklch(45% 0.18 350);
- --border: #333;
-}
-
-body {
- background: var(--bg);
- color: var(--text);
- font-family: system-ui, -apple-system, sans-serif;
- font-size: 12px;
- line-height: 1.5;
- overflow-y: auto;
- height: 100vh;
-}
-
-/* Toolbar */
-.toolbar {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 8px 12px;
- border-bottom: 1px solid var(--border);
- background: var(--bg);
- position: sticky;
- top: 0;
- z-index: 10;
-}
-
-.toolbar-left {
- display: flex;
- align-items: center;
- gap: 8px;
-}
-
-.toolbar-right {
- display: flex;
- align-items: center;
- gap: 4px;
-}
-
-.logo {
- font-size: 18px;
- font-weight: 500;
- color: var(--text);
- opacity: 0.7;
-}
-
-h1 {
- font-size: 13px;
- font-weight: 600;
- letter-spacing: 0.01em;
-}
-
-.badge {
- background: var(--accent);
- color: white;
- font-size: 11px;
- font-weight: 600;
- padding: 1px 6px;
- border-radius: 10px;
- min-width: 20px;
- text-align: center;
- display: none;
-}
-
-.badge.visible {
- display: inline-block;
-}
-
-/* Tool buttons */
-.tool-btn {
- display: flex;
- align-items: center;
- justify-content: center;
- width: 28px;
- height: 28px;
- border: none;
- border-radius: var(--radius);
- background: transparent;
- color: var(--text-dim);
- cursor: pointer;
- transition: background 0.15s, color 0.15s;
-}
-
-.tool-btn:hover {
- background: var(--bg-hover);
- color: var(--text);
-}
-
-.tool-btn.inactive {
- opacity: 0.4;
-}
-
-/* Findings */
-#findings-container {
- padding: 8px;
-}
-
-.finding-group {
- margin-bottom: 2px;
-}
-
-.group-header {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 6px 8px;
- border-radius: var(--radius);
- cursor: pointer;
- user-select: none;
- transition: background 0.15s;
-}
-
-.group-header:hover {
- background: var(--bg-hover);
-}
-
-.group-chevron {
- font-size: 10px;
- color: var(--text-dim);
- transition: transform 0.15s;
- width: 12px;
- flex-shrink: 0;
-}
-
-.group-header.collapsed .group-chevron {
- transform: rotate(-90deg);
-}
-
-.group-name {
- font-weight: 600;
- font-size: 12px;
- flex: 1;
- min-width: 0;
-}
-
-.group-count {
- font-size: 11px;
- color: var(--text-dim);
- font-weight: 500;
-}
-
-.group-items {
- overflow: hidden;
-}
-
-.group-header.collapsed + .group-items {
- display: none;
-}
-
-.finding-item {
- display: flex;
- flex-direction: column;
- gap: 2px;
- padding: 5px 8px 5px 28px;
- border-radius: var(--radius);
- cursor: pointer;
- transition: background 0.15s;
-}
-
-.finding-item:hover {
- background: var(--bg-hover);
-}
-
-.finding-row {
- display: flex;
- align-items: center;
- gap: 6px;
- min-width: 0;
-}
-
-.finding-row .finding-selector {
- flex: 1;
- min-width: 0;
-}
-
-.finding-copy {
- display: none;
- align-items: center;
- justify-content: center;
- width: 18px;
- height: 18px;
- flex-shrink: 0;
- border: none;
- border-radius: 4px;
- background: transparent;
- color: var(--text-dim);
- cursor: pointer;
- transition: background 0.15s, color 0.15s;
-}
-
-.finding-item:hover .finding-copy {
- display: flex;
-}
-
-.finding-copy:hover {
- background: var(--bg);
- color: var(--accent);
-}
-
-.finding-copy.copied {
- color: var(--accent);
-}
-
-.tool-btn.copied {
- color: var(--accent);
-}
-
-.finding-selector {
- font-family: ui-monospace, 'SF Mono', 'Cascadia Code', monospace;
- font-size: 11px;
- color: var(--accent);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.finding-detail {
- font-size: 11px;
- color: var(--text-dim);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.finding-description {
- font-size: 11px;
- color: var(--text-dim);
- opacity: 0.7;
- line-height: 1.4;
- padding: 2px 0 4px;
- display: none;
-}
-
-.finding-item:hover .finding-description {
- display: block;
-}
-
-/* Finding tags (page-level, hidden, etc.) */
-.finding-tag {
- display: inline-block;
- font-size: 9px;
- font-weight: 600;
- text-transform: uppercase;
- letter-spacing: 0.05em;
- padding: 1px 5px;
- border-radius: 3px;
- margin-bottom: 2px;
-}
-
-.tag-page {
- color: var(--accent-dim);
- background: transparent;
-}
-
-.tag-hidden {
- color: var(--text-dim);
- background: var(--bg-hover);
-}
-
-.finding-item.is-hidden {
- opacity: 0.55;
- cursor: default;
-}
-
-.finding-item.is-hidden:hover {
- background: transparent;
-}
-
-/* Empty state */
-.empty-state {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: 48px 24px;
- text-align: center;
-}
-
-.empty-icon {
- font-size: 32px;
- font-weight: 500;
- opacity: 0.3;
- margin-bottom: 12px;
-}
-
-.empty-title {
- font-size: 13px;
- font-weight: 500;
- margin-bottom: 4px;
-}
-
-.empty-hint {
- font-size: 12px;
- color: var(--text-dim);
-}
-
-/* Category sections */
-.category-section {
- margin-bottom: 4px;
-}
-
-.category-header {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 8px 8px 4px;
-}
-
-.category-dot {
- width: 8px;
- height: 8px;
- border-radius: 50%;
- flex-shrink: 0;
-}
-
-.category-dot-slop {
- background: oklch(55% 0.25 350);
-}
-
-.category-dot-quality {
- background: var(--text-dim);
-}
-
-.category-name {
- font-size: 11px;
- font-weight: 600;
- text-transform: uppercase;
- letter-spacing: 0.05em;
- color: var(--text-dim);
-}
-
-.category-count {
- font-size: 11px;
- color: var(--text-dim);
- font-weight: 500;
-}
-
-/* Settings */
-#settings-container {
- border-bottom: 1px solid var(--border);
- padding: 0 8px 8px;
-}
-
-.settings-header {
- font-size: 11px;
- font-weight: 600;
- color: var(--text-dim);
- text-transform: uppercase;
- letter-spacing: 0.05em;
- padding: 8px 8px 6px;
-}
-
-.settings-grid {
- display: grid;
- grid-template-columns: 1fr 1fr;
- gap: 1px 12px;
- padding-bottom: 8px;
-}
-
-#settings-list .settings-header {
- padding: 8px 8px 4px;
-}
-
-.setting-row {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 4px 8px 8px;
- gap: 12px;
-}
-
-.setting-label {
- font-size: 11px;
- color: var(--text);
-}
-
-.setting-segmented {
- display: inline-flex;
- border: 1px solid var(--border);
- border-radius: var(--radius);
- overflow: hidden;
-}
-
-.setting-segmented button {
- background: transparent;
- border: none;
- color: var(--text-dim);
- font-size: 11px;
- padding: 3px 8px;
- cursor: pointer;
- font-family: inherit;
- border-right: 1px solid var(--border);
-}
-
-.setting-segmented button:last-child {
- border-right: none;
-}
-
-.setting-segmented button:hover {
- color: var(--text);
-}
-
-.setting-segmented button.active {
- background: var(--accent);
- color: white;
-}
-
-.setting-switch {
- position: relative;
- display: inline-block;
- width: 28px;
- height: 16px;
- cursor: pointer;
- flex-shrink: 0;
-}
-
-.setting-switch input {
- position: absolute;
- opacity: 0;
- width: 0;
- height: 0;
-}
-
-.setting-switch-track {
- position: absolute;
- top: 0; left: 0; right: 0; bottom: 0;
- background: var(--border);
- border-radius: 8px;
- transition: background 0.15s ease;
-}
-
-.setting-switch-track::before {
- content: '';
- position: absolute;
- top: 2px;
- left: 2px;
- width: 12px;
- height: 12px;
- background: var(--bg);
- border-radius: 50%;
- transition: transform 0.15s ease;
-}
-
-.setting-switch input:checked + .setting-switch-track {
- background: var(--accent);
-}
-
-.setting-switch input:checked + .setting-switch-track::before {
- transform: translateX(12px);
-}
-
-.setting-rule {
- display: flex;
- align-items: center;
- gap: 6px;
- padding: 3px 8px;
- border-radius: var(--radius);
- font-size: 11px;
- cursor: pointer;
- transition: background 0.15s;
-}
-
-.setting-rule:hover {
- background: var(--bg-hover);
-}
-
-.setting-rule input[type="checkbox"] {
- margin: 0;
- accent-color: var(--accent);
-}
-
-/* Scanning state */
-.scanning-indicator {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 12px;
- color: var(--text-dim);
- font-size: 12px;
-}
-
-.scanning-dot {
- width: 6px;
- height: 6px;
- border-radius: 50%;
- background: var(--accent);
- animation: pulse 1s ease-in-out infinite;
-}
-
-@keyframes pulse {
- 0%, 100% { opacity: 0.3; }
- 50% { opacity: 1; }
-}
@@ -1,66 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="utf-8">
- <link rel="stylesheet" href="panel.css">
-</head>
-<body>
- <header class="toolbar">
- <div class="toolbar-left">
- <span class="logo">/</span>
- <h1>Impeccable</h1>
- <span class="badge" id="badge">0</span>
- </div>
- <div class="toolbar-right">
- <button class="tool-btn" id="btn-copy-all" title="Copy all findings">
- <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M11 1H3a2 2 0 0 0-2 2v10h2V3h8V1zm3 3H7a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h7a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 11H7V6h7v9z" fill="currentColor"/></svg>
- </button>
- <button class="tool-btn" id="btn-rescan" title="Re-scan page">
- <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M13.65 2.35A8 8 0 1 0 16 8h-2a6 6 0 1 1-1.76-4.24L10 6h6V0l-2.35 2.35z" fill="currentColor"/></svg>
- </button>
- <button class="tool-btn" id="btn-toggle" title="Toggle overlays">
- <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M8 3C4.36 3 1.26 5.28 0 8.5c1.26 3.22 4.36 5.5 8 5.5s6.74-2.28 8-5.5C14.74 5.28 11.64 3 8 3zm0 9.17c-2.58 0-4.67-2.09-4.67-4.67S5.42 2.83 8 2.83s4.67 2.09 4.67 4.67S10.58 12.17 8 12.17zM8 5a3.5 3.5 0 1 0 0 7 3.5 3.5 0 0 0 0-7z" fill="currentColor"/></svg>
- </button>
- <button class="tool-btn" id="btn-settings" title="Settings">
- <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M13.6 8.8c.04-.26.06-.53.06-.8s-.02-.54-.06-.8l1.74-1.36a.42.42 0 0 0 .1-.52l-1.64-2.84a.41.41 0 0 0-.5-.18l-2.06.82a5.96 5.96 0 0 0-1.38-.8L9.5.2A.4.4 0 0 0 9.1 0H5.82a.4.4 0 0 0-.4.34l-.3 2.12c-.5.2-.96.48-1.38.8l-2.06-.82a.4.4 0 0 0-.5.18L-.46 5.46a.41.41 0 0 0 .1.52L1.38 7.34c-.04.26-.06.53-.06.8s.02.54.06.8L-.36 10.3a.42.42 0 0 0-.1.52l1.64 2.84c.1.18.32.24.5.18l2.06-.82c.42.32.88.6 1.38.8l.3 2.12a.4.4 0 0 0 .4.34h3.28a.4.4 0 0 0 .4-.34l.3-2.12c.5-.2.96-.48 1.38-.8l2.06.82c.18.08.4 0 .5-.18l1.64-2.84a.41.41 0 0 0-.1-.52L13.6 8.8zM7.46 10.8c-1.56 0-2.82-1.26-2.82-2.8s1.26-2.8 2.82-2.8 2.82 1.26 2.82 2.8-1.26 2.8-2.82 2.8z" fill="currentColor"/></svg>
- </button>
- </div>
- </header>
-
- <div id="settings-container" style="display: none">
- <div class="settings-header">Preferences</div>
- <div class="setting-row">
- <span class="setting-label">Auto-scan</span>
- <div class="setting-segmented" id="auto-scan-mode">
- <button data-value="panel">When panel opens</button>
- <button data-value="devtools">When DevTools opens</button>
- </div>
- </div>
- <div class="setting-row">
- <span class="setting-label">Line length</span>
- <div class="setting-segmented" id="line-length-mode">
- <button data-value="strict">Strict (80)</button>
- <button data-value="lax">Lax (120)</button>
- </div>
- </div>
- <div class="setting-row">
- <span class="setting-label">Highlight blur</span>
- <label class="setting-switch">
- <input type="checkbox" id="spotlight-blur-toggle">
- <span class="setting-switch-track"></span>
- </label>
- </div>
- <div id="settings-list"></div>
- </div>
-
- <main id="findings-container">
- <div class="empty-state" id="empty-state">
- <div class="empty-icon">/</div>
- <p class="empty-title">No anti-patterns detected</p>
- <p class="empty-hint">Overlays will appear on the page when issues are found</p>
- </div>
- </main>
-
- <script src="panel.js"></script>
-</body>
-</html>
@@ -1,519 +0,0 @@
-/**
- * Impeccable DevTools Extension - Panel
- *
- * Displays findings, provides controls for scanning and overlay toggling,
- * and allows clicking findings to inspect elements.
- */
-
-// Match the DevTools theme (light or dark)
-if (chrome.devtools.panels.themeName === 'dark') {
- document.documentElement.classList.add('theme-dark');
-}
-
-const tabId = chrome.devtools.inspectedWindow.tabId;
-
-// Auto-reconnecting port. Service workers in MV3 can be terminated after ~30s of
-// inactivity (especially when the browser window is unfocused). When they restart,
-// the existing port becomes invalid. We recreate it lazily on the next use.
-let port = null;
-function getPort() {
- if (port) return port;
- port = chrome.runtime.connect({ name: `impeccable-panel-${tabId}` });
- port.onMessage.addListener(handlePortMessage);
- port.onDisconnect.addListener(() => { port = null; });
- return port;
-}
-function postToPort(msg) {
- try {
- getPort().postMessage(msg);
- } catch {
- // Port died mid-call. Drop it and try once more with a fresh port.
- port = null;
- try { getPort().postMessage(msg); } catch { /* give up silently */ }
- }
-}
-
-const badge = document.getElementById('badge');
-const container = document.getElementById('findings-container');
-const emptyState = document.getElementById('empty-state');
-const btnRescan = document.getElementById('btn-rescan');
-const btnToggle = document.getElementById('btn-toggle');
-const btnCopyAll = document.getElementById('btn-copy-all');
-const settingsContainer = document.getElementById('settings-container');
-const settingsList = document.getElementById('settings-list');
-const btnSettings = document.getElementById('btn-settings');
-
-let overlaysVisible = true;
-let allAntipatterns = [];
-let disabledRules = [];
-let currentFindings = [];
-
-// Load antipatterns list and disabled rules
-async function initSettings() {
- try {
- const resp = await fetch(chrome.runtime.getURL('detector/antipatterns.json'));
- allAntipatterns = await resp.json();
- } catch { allAntipatterns = []; }
-
- const stored = await chrome.storage.sync.get({
- disabledRules: [],
- lineLengthMode: 'strict',
- spotlightBlur: true,
- autoScan: 'panel',
- });
- disabledRules = stored.disabledRules;
- renderSettings();
- initLineLengthControl(stored.lineLengthMode);
- initSpotlightBlurToggle(stored.spotlightBlur);
- initAutoScanControl(stored.autoScan);
-}
-
-function initAutoScanControl(currentMode) {
- const group = document.getElementById('auto-scan-mode');
- if (!group) return;
- for (const btn of group.querySelectorAll('button')) {
- btn.classList.toggle('active', btn.dataset.value === currentMode);
- btn.addEventListener('click', async () => {
- const mode = btn.dataset.value;
- for (const b of group.querySelectorAll('button')) {
- b.classList.toggle('active', b === btn);
- }
- await chrome.storage.sync.set({ autoScan: mode });
- });
- }
-}
-
-function initLineLengthControl(currentMode) {
- const group = document.getElementById('line-length-mode');
- if (!group) return;
- for (const btn of group.querySelectorAll('button')) {
- btn.classList.toggle('active', btn.dataset.value === currentMode);
- btn.addEventListener('click', async () => {
- const mode = btn.dataset.value;
- for (const b of group.querySelectorAll('button')) {
- b.classList.toggle('active', b === btn);
- }
- await chrome.storage.sync.set({ lineLengthMode: mode });
- chrome.runtime.sendMessage({ action: 'disabled-rules-changed' });
- });
- }
-}
-
-function initSpotlightBlurToggle(currentValue) {
- const cb = document.getElementById('spotlight-blur-toggle');
- if (!cb) return;
- cb.checked = currentValue;
- cb.addEventListener('change', async () => {
- await chrome.storage.sync.set({ spotlightBlur: cb.checked });
- chrome.runtime.sendMessage({ action: 'disabled-rules-changed' });
- });
-}
-
-function renderSettings() {
- settingsList.innerHTML = '';
-
- const categories = {
- slop: { label: 'AI tells', items: [] },
- quality: { label: 'Quality', items: [] },
- };
- for (const ap of allAntipatterns) {
- const cat = ap.category || 'quality';
- (categories[cat] || categories.quality).items.push(ap);
- }
-
- for (const [, group] of Object.entries(categories)) {
- if (!group.items.length) continue;
-
- const header = document.createElement('div');
- header.className = 'settings-header';
- header.textContent = group.label;
- settingsList.appendChild(header);
-
- const grid = document.createElement('div');
- grid.className = 'settings-grid';
-
- for (const ap of group.items) {
- const label = document.createElement('label');
- label.className = 'setting-rule';
-
- const checkbox = document.createElement('input');
- checkbox.type = 'checkbox';
- checkbox.checked = !disabledRules.includes(ap.id);
- checkbox.addEventListener('change', () => toggleRule(ap.id, checkbox.checked));
-
- const text = document.createElement('span');
- text.textContent = ap.name;
-
- label.appendChild(checkbox);
- label.appendChild(text);
- grid.appendChild(label);
- }
- settingsList.appendChild(grid);
- }
-}
-
-async function toggleRule(ruleId, enabled) {
- if (enabled) {
- disabledRules = disabledRules.filter(id => id !== ruleId);
- } else {
- if (!disabledRules.includes(ruleId)) disabledRules.push(ruleId);
- }
- await chrome.storage.sync.set({ disabledRules });
- chrome.runtime.sendMessage({ action: 'disabled-rules-changed' });
-}
-
-// Listen for messages from the service worker (called by getPort() on each new connection)
-function handlePortMessage(msg) {
- if (msg.action === 'page-pointer-active') {
- // Cursor is active on the page → user has left the panel
- setHoveredItem(null);
- return;
- }
- if (msg.action === 'findings' || msg.action === 'state') {
- renderFindings(msg.findings || []);
- if (msg.overlaysVisible !== undefined) {
- overlaysVisible = msg.overlaysVisible;
- updateToggleButton();
- }
- }
- if (msg.action === 'overlays-toggled') {
- overlaysVisible = msg.visible;
- updateToggleButton();
- }
- if (msg.action === 'navigated') {
- showScanning();
- }
-}
-
-// Initial connection
-getPort();
-
-// Heartbeat to keep the MV3 service worker alive while the panel is open.
-// SWs can be terminated after ~30s of inactivity, especially when the browser is unfocused.
-setInterval(() => postToPort({ action: 'ping' }), 20000);
-
-// Controls
-btnRescan.addEventListener('click', () => {
- showScanning();
- postToPort({ action: 'scan' });
-});
-
-btnToggle.addEventListener('click', () => {
- postToPort({ action: 'toggle-overlays' });
-});
-
-btnSettings.addEventListener('click', () => {
- const isVisible = settingsContainer.style.display !== 'none';
- settingsContainer.style.display = isVisible ? 'none' : '';
- btnSettings.classList.toggle('active', !isVisible);
-});
-
-function updateToggleButton() {
- btnToggle.title = overlaysVisible ? 'Hide overlays' : 'Show overlays';
- btnToggle.classList.toggle('inactive', !overlaysVisible);
-}
-
-function showScanning() {
- container.innerHTML = `
- <div class="scanning-indicator">
- <div class="scanning-dot"></div>
- Scanning page...
- </div>`;
-}
-
-// Maps each anti-pattern to the most relevant Impeccable skill(s) for fixing it.
-// These are suggestions; the user decides whether and how to apply them.
-const FIX_SKILLS = {
- // AI slop
- 'side-tab': 'distill, polish',
- 'border-accent-on-rounded':'distill, polish',
- 'overused-font': 'typeset',
- 'single-font': 'typeset',
- 'flat-type-hierarchy': 'typeset',
- 'gradient-text': 'typeset, distill',
- 'ai-color-palette': 'colorize, distill',
- 'nested-cards': 'distill, arrange',
- 'monotonous-spacing': 'arrange',
- 'everything-centered': 'arrange',
- 'bounce-easing': 'animate',
- 'dark-glow': 'quieter, distill',
- 'icon-tile-stacked-above-heading': 'distill, arrange',
- // Quality
- 'pure-black-white': 'colorize',
- 'gray-on-color': 'colorize',
- 'low-contrast': 'colorize, audit',
- 'layout-transition': 'animate, optimize',
- 'line-length': 'arrange, typeset',
- 'cramped-padding': 'arrange, polish',
- 'tight-leading': 'typeset',
- 'skipped-heading': 'audit, harden',
- 'justified-text': 'typeset',
- 'tiny-text': 'typeset',
- 'all-caps-body': 'typeset',
- 'wide-tracking': 'typeset',
-};
-
-function fixSkillFor(type) {
- const skills = FIX_SKILLS[type] || 'polish';
- // Prefix each comma-separated skill with a slash for clarity
- return skills.split(',').map(s => '/' + s.trim()).join(', ');
-}
-
-// Returns a sorted array of unique skills referenced by the given findings,
-// most-frequent first. Each entry already has the leading slash.
-function uniqueSkillsForFindings(findings) {
- const counts = new Map();
- for (const item of findings) {
- for (const f of item.findings) {
- const list = (FIX_SKILLS[f.type] || 'polish').split(',').map(s => '/' + s.trim());
- for (const s of list) {
- counts.set(s, (counts.get(s) || 0) + 1);
- }
- }
- }
- return [...counts.entries()].sort((a, b) => b[1] - a[1]).map(([s]) => s);
-}
-
-function getInspectedUrl() {
- return new Promise((resolve) => {
- // Strip the URL fragment — anchors are noise for "what page is this from"
- chrome.devtools.inspectedWindow.eval(
- '(function(){var u=new URL(location.href);u.hash="";return u.toString();})()',
- (result) => resolve(typeof result === 'string' ? result : '')
- );
- });
-}
-
-async function formatFindingsForCopy(findings) {
- if (!findings.length) return 'Impeccable found no anti-patterns on this page.';
- const url = await getInspectedUrl();
- const lines = ['# Impeccable findings'];
- if (url) lines.push(`URL: ${url}`);
- lines.push('');
-
- const groups = { slop: [], quality: [] };
- for (const item of findings) {
- for (const f of item.findings) {
- const cat = f.category || 'quality';
- groups[cat].push({ ...f, selector: item.selector, isPageLevel: item.isPageLevel });
- }
- }
-
- if (groups.slop.length) {
- lines.push(`## AI tells (${groups.slop.length})`);
- for (const f of groups.slop) {
- const where = f.isPageLevel ? '_(page-level)_' : `\`${f.selector}\``;
- lines.push(`- **${f.name}** at ${where}: ${f.detail}`);
- }
- lines.push('');
- }
-
- if (groups.quality.length) {
- lines.push(`## Quality issues (${groups.quality.length})`);
- for (const f of groups.quality) {
- const where = f.isPageLevel ? '_(page-level)_' : `\`${f.selector}\``;
- lines.push(`- **${f.name}** at ${where}: ${f.detail}`);
- }
- lines.push('');
- }
-
- // Roll up suggested skills across all findings (most-relevant first)
- const skills = uniqueSkillsForFindings(findings);
- if (skills.length) {
- lines.push(`Suggested Impeccable skills to fix: ${skills.join(', ')}`);
- lines.push('');
- }
-
- lines.push('---');
- lines.push('Detected by [Impeccable](https://impeccable.style). Skills are suggestions, not required.');
- return lines.join('\n');
-}
-
-async function formatSingleFindingForCopy(item, finding) {
- const url = await getInspectedUrl();
- const where = item.isPageLevel ? '_(page-level)_' : `\`${item.selector}\``;
- const lines = [`# Impeccable: ${finding.name}`];
- if (url) lines.push(`URL: ${url}`);
- lines.push(`Element: ${where}`);
- lines.push(`Detail: ${finding.detail}`);
- lines.push('');
- lines.push(finding.description);
- lines.push('');
- lines.push(`Suggested Impeccable skill(s) to fix: ${fixSkillFor(finding.type)}`);
- return lines.join('\n');
-}
-
-async function copyToClipboard(text, btn) {
- if (text instanceof Promise) text = await text;
- try {
- await navigator.clipboard.writeText(text);
- if (btn) {
- const orig = btn.title;
- btn.title = 'Copied!';
- btn.classList.add('copied');
- setTimeout(() => {
- btn.title = orig;
- btn.classList.remove('copied');
- }, 1200);
- }
- } catch (err) {
- console.warn('Copy failed', err);
- }
-}
-
-btnCopyAll.addEventListener('click', () => {
- copyToClipboard(formatFindingsForCopy(currentFindings), btnCopyAll);
-});
-
-// Delegated hover tracking on the findings container.
-// Reliably handles cursor moving between items, into children, or out of the panel.
-let currentHoverSelector = null;
-function setHoveredItem(selector) {
- if (selector === currentHoverSelector) return;
- currentHoverSelector = selector;
- if (selector) {
- postToPort({ action: 'highlight', selector });
- } else {
- postToPort({ action: 'unhighlight' });
- }
-}
-
-container.addEventListener('pointermove', (e) => {
- const item = e.target.closest('.finding-item');
- const selector = item && !item.classList.contains('is-hidden') ? item.dataset.selector || null : null;
- setHoveredItem(selector);
-});
-
-// Slow-cursor fallbacks (these fire reliably for slow movements)
-container.addEventListener('pointerleave', () => setHoveredItem(null));
-window.addEventListener('blur', () => setHoveredItem(null));
-
-
-function renderFindings(findings) {
- currentFindings = findings;
- if (!findings.length) {
- container.innerHTML = '';
- container.appendChild(emptyState);
- emptyState.style.display = '';
- badge.classList.remove('visible');
- badge.textContent = '0';
- return;
- }
-
- emptyState.style.display = 'none';
-
- // Count total element-level findings
- const totalCount = findings.reduce((sum, f) => sum + f.findings.length, 0);
- badge.textContent = String(totalCount);
- badge.classList.add('visible');
-
- // Group findings by category, then by anti-pattern type
- const categories = { slop: new Map(), quality: new Map() };
- for (const item of findings) {
- for (const f of item.findings) {
- const cat = f.category || 'quality';
- const groups = categories[cat] || categories.quality;
- if (!groups.has(f.type)) {
- groups.set(f.type, { name: f.name, description: f.description, items: [] });
- }
- groups.get(f.type).items.push({
- selector: item.selector,
- tagName: item.tagName,
- isPageLevel: item.isPageLevel,
- isHidden: item.isHidden,
- detail: f.detail,
- });
- }
- }
-
- container.innerHTML = '';
-
- const CATEGORY_LABELS = { slop: 'AI tells', quality: 'Quality issues' };
- for (const [catKey, groups] of Object.entries(categories)) {
- if (groups.size === 0) continue;
-
- const catCount = [...groups.values()].reduce((sum, g) => sum + g.items.length, 0);
- const section = document.createElement('div');
- section.className = 'category-section category-' + catKey;
-
- const catHeader = document.createElement('div');
- catHeader.className = 'category-header';
- catHeader.innerHTML = `
- <span class="category-dot category-dot-${catKey}"></span>
- <span class="category-name">${CATEGORY_LABELS[catKey]}</span>
- <span class="category-count">${catCount}</span>`;
- section.appendChild(catHeader);
-
- for (const [type, group] of groups) {
- const groupEl = document.createElement('div');
- groupEl.className = 'finding-group';
-
- const header = document.createElement('div');
- header.className = 'group-header';
- header.innerHTML = `
- <span class="group-chevron">▼</span>
- <span class="group-name">${escapeHtml(group.name)}</span>
- <span class="group-count">${group.items.length}</span>`;
- header.addEventListener('click', () => header.classList.toggle('collapsed'));
- groupEl.appendChild(header);
-
- const itemsEl = document.createElement('div');
- itemsEl.className = 'group-items';
-
- for (const item of group.items) {
- const itemEl = document.createElement('div');
- itemEl.className = 'finding-item' + (item.isHidden ? ' is-hidden' : '');
- const tag = item.isPageLevel
- ? '<span class="finding-tag tag-page">page</span>'
- : item.isHidden ? '<span class="finding-tag tag-hidden" title="Element is currently hidden on the page">hidden</span>' : '';
- itemEl.innerHTML = `
- ${tag}
- <div class="finding-row">
- <span class="finding-selector">${escapeHtml(item.selector)}</span>
- <button class="finding-copy" title="Copy this finding">
- <svg width="11" height="11" viewBox="0 0 16 16" fill="none"><path d="M11 1H3a2 2 0 0 0-2 2v10h2V3h8V1zm3 3H7a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h7a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 11H7V6h7v9z" fill="currentColor"/></svg>
- </button>
- </div>
- <span class="finding-detail">${escapeHtml(item.detail)}</span>
- <span class="finding-description">${escapeHtml(group.description)}</span>`;
-
- const copyBtn = itemEl.querySelector('.finding-copy');
- const finding = { type, name: group.name, description: group.description, detail: item.detail };
- copyBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- copyToClipboard(formatSingleFindingForCopy(item, finding), copyBtn);
- });
-
- if (!item.isPageLevel && !item.isHidden) {
- itemEl.dataset.selector = item.selector;
- itemEl.addEventListener('click', () => inspectElement(item.selector));
- }
-
- itemsEl.appendChild(itemEl);
- }
-
- groupEl.appendChild(itemsEl);
- section.appendChild(groupEl);
- }
-
- container.appendChild(section);
- }
-}
-
-function inspectElement(selector) {
- const json = JSON.stringify(selector);
- chrome.devtools.inspectedWindow.eval(
- `(function() {
- var el = document.querySelector(${json});
- if (el) { el.scrollIntoView({ behavior: 'smooth', block: 'center' }); inspect(el); }
- })()`
- );
-}
-
-function escapeHtml(str) {
- const div = document.createElement('div');
- div.textContent = str;
- return div.innerHTML;
-}
-
-initSettings();